├── .gitignore ├── DCO-1.1.txt ├── DCO.txt ├── LICENSE ├── MANIFEST.in ├── README.md ├── bin └── virtme-prep-kdir-mods ├── make-release-tarball.sh ├── samples ├── README.md ├── xfstests └── xfstests_trampoline ├── setup.py ├── virtme-configkernel ├── virtme-mkinitramfs ├── virtme-run └── virtme ├── __init__.py ├── architectures.py ├── commands ├── __init__.py ├── configkernel.py ├── mkinitramfs.py └── run.py ├── cpiowriter.py ├── guest ├── __init__.py ├── virtme-init └── virtme-udhcpc-script ├── mkinitramfs.py ├── modfinder.py ├── qemu_helpers.py ├── resources.py ├── scripts ├── util.py └── virtmods.py /.gitignore: -------------------------------------------------------------------------------- 1 | *~ 2 | __pycache__ 3 | build 4 | dist 5 | .mypy_cache -------------------------------------------------------------------------------- /DCO-1.1.txt: -------------------------------------------------------------------------------- 1 | The text 'Signed-off-by:' in a commit message indicates that the signer 2 | agrees to the Developer's Certificate of Origin 1.1, reproduced below. 3 | 4 | I (Andrew Lutomirski) believe that the DCO is Copyright Linus Torvalds 5 | and released under the GPL v2. 6 | 7 | Developer's Certificate of Origin 1.1 8 | 9 | By making a contribution to this project, I certify that: 10 | 11 | (a) The contribution was created in whole or in part by me and I 12 | have the right to submit it under the open source license 13 | indicated in the file; or 14 | 15 | (b) The contribution is based upon previous work that, to the best 16 | of my knowledge, is covered under an appropriate open source 17 | license and I have the right under that license to submit that 18 | work with modifications, whether created in whole or in part 19 | by me, under the same open source license (unless I am 20 | permitted to submit under a different license), as indicated 21 | in the file; or 22 | 23 | (c) The contribution was provided directly to me by some other 24 | person who certified (a), (b) or (c) and I have not modified 25 | it. 26 | 27 | (d) I understand and agree that this project and the contribution 28 | are public and that a record of the contribution (including all 29 | personal information I submit with it, including my sign-off) is 30 | maintained indefinitely and may be redistributed consistent with 31 | this project or the open source license(s) involved. 32 | 33 | -------------------------------------------------------------------------------- /DCO.txt: -------------------------------------------------------------------------------- 1 | Developer's Certificate of Origin 1.1 2 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 3 | 4 | By making a contribution to this project, I certify that: 5 | 6 | (a) The contribution was created in whole or in part by me and I 7 | have the right to submit it under the open source license 8 | indicated in the file; or 9 | 10 | (b) The contribution is based upon previous work that, to the best 11 | of my knowledge, is covered under an appropriate open source 12 | license and I have the right under that license to submit that 13 | work with modifications, whether created in whole or in part 14 | by me, under the same open source license (unless I am 15 | permitted to submit under a different license), as indicated 16 | in the file; or 17 | 18 | (c) The contribution was provided directly to me by some other 19 | person who certified (a), (b) or (c) and I have not modified 20 | it. 21 | 22 | (d) I understand and agree that this project and the contribution 23 | are public and that a record of the contribution (including all 24 | personal information I submit with it, including my sign-off) is 25 | maintained indefinitely and may be redistributed consistent with 26 | this project or the open source license(s) involved. 27 | 28 | then you just add a line saying:: 29 | 30 | Signed-off-by: Random J Developer 31 | 32 | using your real name (sorry, no pseudonyms or anonymous contributions.) 33 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | , 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include README.md 2 | include LICENSE 3 | include virtme/guest/* 4 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | What is virtme? 2 | =============== 3 | 4 | Virtme is a set of simple tools to run a virtualized Linux kernel that 5 | uses the host Linux distribution or a simple rootfs instead of a whole 6 | disk image. 7 | 8 | Virtme is tiny, easy to use, and makes testing kernel changes quite simple. 9 | 10 | Some day this might be useful as a sort of sandbox. Right now it's not 11 | really configurable enough for that. 12 | 13 | Virtme is hosted at kernel.org in utils/kernel/virtme/virtme.git ([web][korg-web] | [git][korg-git]). It's mirrored [on github][github]. Please submit bugs 14 | and PRs via github. Release tarballs are at [kernel.org in /pub/linux/utils/kernel/virtme][korg-releases]. 15 | 16 | [korg-web]: https://git.kernel.org/cgit/utils/kernel/virtme/virtme.git "virtme on kernel.org" 17 | [korg-git]: git://git.kernel.org/pub/scm/utils/kernel/virtme/virtme.git "git address" 18 | [korg-releases]: https://mirrors.edge.kernel.org/pub/linux/utils/kernel/virtme/releases/ "virtme releases on kernel.org" 19 | [github]: https://github.com/amluto/virtme 20 | 21 | How to use virtme 22 | ================= 23 | 24 | You'll need a Linux kernel that has these options (built-in or as modules) 25 | 26 | CONFIG_VIRTIO 27 | CONFIG_VIRTIO_PCI 28 | CONFIG_NET_9P 29 | CONFIG_NET_9P_VIRTIO 30 | CONFIG_9P_FS 31 | 32 | For networking support, you also need CONFIG_VIRTIO_NET. 33 | 34 | For script support, you need CONFIG_VIRTIO_CONSOLE. 35 | 36 | For disk support, you need CONFIG_SCSI_VIRTIO. 37 | 38 | That kernel needs to be sane. Your kernel is probably sane, but allmodconfig and allyesconfig generate insane kernels. Sanity includes: 39 | 40 | CONFIG_CMDLINE_OVERRIDE=n 41 | CONFIG_BINFMT_SCRIPT=y 42 | CONFIG_TMPFS=y 43 | 44 | You may also have better luck if you set: 45 | 46 | CONFIG_EMBEDDED=n 47 | CONFIG_EXPERT=n 48 | CONFIG_MODULE_SIG_FORCE=n 49 | CONFIG_DEVTMPFS=y 50 | 51 | An easy, somewhat-reliable way to generate a working config is via 52 | the virtme-configkernel. It needs to be run on a kernel source directory, 53 | like: 54 | 55 | virtme-configkernel --arch=ARCH --defconfig 56 | 57 | Your host system will need to satisfy some prerequisites: 58 | 59 | * You need Python 3.3 or higher. 60 | * QEMU 1.6 or higher is recommended. QEMU 1.4 and 1.5 are partially supported using a rather ugly kludge. 61 | * You will have a much better experience if KVM is enabled. That means that you should be on bare metal with hardware virtualization (VT-x or SVM) enabled or in a VM that supports nested virtualization. On some Linux distributions, you may need to be a member of the "kvm" group. Using VirtualBox or most VPS providers will fall back to emulation. 62 | * Depending on the options you use, you may need a statically linked `busybox` binary somewhere in your path. 63 | 64 | Once you have such a kernel, run one of: 65 | 66 | * virtme-run --kdir PATH_TO_KERNEL_TREE 67 | * virtme-run --installed-kernel 68 | * virtme-run --installed-kernel VERSION 69 | * virtme-run --kimg PATH_TO_KERNEL_IMAGE 70 | 71 | With --installed-kernel or --kdir, modules associated with the kernel will be available in the VM. With --kdir in particular, you will either need to follow the directions that virtme-run prints or specify --mods=auto to make this work. With --kimg, modules are not supported. 72 | 73 | You can then do things like `cd /home/username` and you will have readonly 74 | access to all your files. 75 | 76 | Virtme gives you console input and output by default. Type ctrl-a x to exit. 77 | Type ctrl-a c to access the QEMU monitor. 78 | 79 | For now, the virtme console is a serial console -- virtconsole seems to be unusably buggy. I don't know of any way to keep the tty state in sync between the host and guest, so resizing the host window after starting the guest may confuse guest libraries like readline. 80 | 81 | Graphics 82 | ======== 83 | 84 | If you want graphical output instead of console output, pass --graphics. Note that this is the opposite of QEMU's default behavior. 85 | 86 | Architecture support 87 | ==================== 88 | 89 | By default, virtme will use whatever architecture would be shown by `uname -m`. You can override this with `--arch`. Note that you may need to do some poorly documented fiddling for now to get non-native architectures working, and you will almost certainly need to set `--root` to a root that matches the architecture. 90 | 91 | In general, the easiest way to configure a working kernel is to run: 92 | 93 | virtme-configkernel --arch=ARCH --defconfig 94 | 95 | x86 96 | --- 97 | 98 | x86 (both x86_64 and i386) is fully supported, although some odd KVM configurations may cause problems. 99 | 100 | ARM 101 | --- 102 | 103 | ARM is supported using qemu's `vexpress-a15` machine. There is no built-in KVM support for ARM right now, although it might work by accident -- I don't own a real KVM-capable ARM machine to test it on. 104 | 105 | If you use any mode other than --kdir, you'll need to manually set QEMU's -dtb option. I'm not sure why -- I assumed that QEMU would provide its own device tree, but this doesn't seem to be the case. 106 | 107 | Aarch64 108 | ------- 109 | 110 | Aarch64 works out of the box if you have a new enough version of QEMU. 111 | 112 | PPC64 113 | ----- 114 | 115 | PPC64 appears to be reasonably functional. 116 | 117 | RISC-V 118 | ------ 119 | 120 | riscv64 works out of the box, but you'll neet at least QEMU-4.1.0 to be 121 | able to run `vmlinux`-style kernels. riscv32 is not supported because 122 | there are no existing userspace images for it. Support is provided via 123 | QEMU's `virt` machine with OpenSBI for firmware. 124 | 125 | Others 126 | ------ 127 | 128 | Other architectures may or may not work. Adding support is trivial, so ping me if you need another architecture. Unrecognized architectures use a set of maybe-acceptable defaults. 129 | 130 | Upcoming features 131 | ================= 132 | 133 | In the near term, the high-priority features are: 134 | 135 | * Support for modular virtfs and 9p for non-installed kernels. 136 | 137 | Contributing 138 | ============ 139 | 140 | Please see DCO.txt 141 | -------------------------------------------------------------------------------- /bin/virtme-prep-kdir-mods: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # This is still a bit of an experiment. 4 | FAKEVER=0.0.0 5 | MODDIR=".virtme_mods/lib/modules/$FAKEVER" 6 | 7 | # Some distro don't have /sbin or /usr/sbin in user's default path. Make sure 8 | # to setup the right path to find all the commands needed to setup the modules 9 | # (depmod, etc.). 10 | PATH=$PATH:/sbin:/usr/sbin 11 | 12 | if ! [ -f "modules.order" ]; then 13 | echo 'virtme-prep-kdir-mods must be run from a kernel build directory' >&2 14 | echo "modules.order is missing. Your kernel may be too old or you didn't make modules." >&2 15 | exit 1 16 | fi 17 | 18 | # Set up .virtme_mods/lib/modules/0.0.0 as a module directory for this kernel, 19 | # but fill it with symlinks instead of actual modules. 20 | 21 | mkdir -p "$MODDIR/kernel" 22 | ln -srfT . "$MODDIR/build" 23 | 24 | # Remove all preexisting symlinks and add symlinks to all modules that belong 25 | # to the build kenrnel. 26 | find "$MODDIR/kernel" -type l -print0 |xargs -0 rm -f -- 27 | while read -r i; do 28 | [ ! -e "$i" ] && i=$(echo "$i" | sed s:^kernel/::) 29 | mkdir -p "$MODDIR/kernel/$(dirname "$i")" 30 | ln -sr "$i" "$MODDIR/kernel/$i" 31 | done < modules.order 32 | 33 | 34 | # Link in the files that make modules_install would copy 35 | ln -srf modules.builtin modules.builtin.modinfo modules.order "$MODDIR/" 36 | 37 | # Now run depmod to collect dependencies 38 | depmod -ae -F System.map -b .virtme_mods "$FAKEVER" 39 | -------------------------------------------------------------------------------- /make-release-tarball.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | if (( $# != 1 )); then 4 | echo "Usage: make-release-tarball VERSION" 5 | exit 1 6 | fi 7 | 8 | ver="$1" 9 | 10 | exec git archive --prefix=virtme-$ver/ --format=tar -o /dev/stdout HEAD 11 | -------------------------------------------------------------------------------- /samples/README.md: -------------------------------------------------------------------------------- 1 | Samples 2 | ======= 3 | 4 | These are a collection of sample scripts. I will answer questions about 5 | them, but I will not really support them, and I reserve the right to 6 | break them at any time. Don't rely on them in production. 7 | 8 | These scripts mostly expect to find virtme-run in PATH. -------------------------------------------------------------------------------- /samples/xfstests: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | if (( $# != 3 )); then 4 | echo 'Usage: xfstests TEST_DEV SCRATCH_DEV PATH_TO_XFSTESTS' 5 | echo 'This will reformat TEST_DEV and SCRATCH_DEV' 6 | exit 1 7 | fi 8 | 9 | here="`dirname $0`" 10 | samples_path="`realpath "$here"`" 11 | xfstests_path="`realpath "$3"`" 12 | 13 | # script-sh is awkward for this purpose. The escaping here is wrong. 14 | virtme-run --installed-kernel --disk "test=$1" --disk "scratch=$2" --script-sh "$samples_path/xfstests_trampoline $xfstests_path" --qemu-opts -m 2048 -smp 2 15 | -------------------------------------------------------------------------------- /samples/xfstests_trampoline: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Observations: 4 | # 5 | # - If TEST_DEV is a symlink, xfstests fails with strange errors. 6 | # - There appears to be some confusion about RESULT_BASE and RESULTS_BASE. 7 | # Neither one is documented. 8 | 9 | mkdir /tmp/testmnt 10 | export TEST_DEV="`realpath /dev/disk/by-id/scsi-0virtme_disk_test`" 11 | export TEST_DIR=/tmp/testmnt 12 | mkfs.xfs -f $TEST_DEV 13 | 14 | mkdir /tmp/scratchmnt 15 | export SCRATCH_DEV="`realpath /dev/disk/by-id/scsi-0virtme_disk_scratch`" 16 | export SCRATCH_MNT=/tmp/scratchmnt 17 | mkfs.xfs -f $SCRATCH_DEV 18 | mount -t xfs "$SCRATCH_DEV" "$SCRATCH_MNT" 19 | 20 | echo "Scratch dev is $SCRATCH_DEV" 21 | 22 | export RESULT_BASE=/tmp/results 23 | export RESULTS_BASE="$RESULT_BASE" 24 | mkdir $RESULT_BASE 25 | 26 | cd "$1" 27 | echo "Starting xfstests" 28 | ./check 29 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import os 4 | import sys 5 | from setuptools import setup 6 | 7 | if sys.version_info < (3,3): 8 | print('virtme requires Python 3.3 or higher') 9 | sys.exit(1) 10 | 11 | _VERSION = '0.1.1' 12 | 13 | setup( 14 | name='virtme', 15 | version=_VERSION, 16 | author='Andy Lutomirski', 17 | author_email='luto@amacapital.net', 18 | description='Virtualize the running distro or a simple rootfs', 19 | url='https://git.kernel.org/cgit/utils/kernel/virtme/virtme.git', 20 | download_url='https://www.kernel.org/pub/linux/utils/kernel/virtme/releases/virtme-%s.tar.xz' % _VERSION, 21 | license='GPLv2', 22 | long_description=open(os.path.join(os.path.dirname(__file__), 23 | 'README.md'), 'r').read(), 24 | packages=['virtme', 'virtme.commands', 'virtme.guest'], 25 | install_requires=[], 26 | entry_points = { 27 | 'console_scripts': [ 28 | 'virtme-run = virtme.commands.run:main', 29 | 'virtme-configkernel = virtme.commands.configkernel:main', 30 | 'virtme-mkinitramfs = virtme.commands.mkinitramfs:main', 31 | ] 32 | }, 33 | scripts = [ 34 | 'bin/virtme-prep-kdir-mods', 35 | ], 36 | package_data = { 37 | 'virtme.guest': [ 38 | 'virtme-init', 39 | 'virtme-udhcpc-script', 40 | ], 41 | }, 42 | classifiers=['Environment :: Console', 43 | 'Intended Audience :: Developers', 44 | 'Intended Audience :: System Administrators', 45 | 'License :: OSI Approved :: GNU General Public License v2 (GPLv2)', 46 | 'Operating System :: POSIX :: Linux', 47 | ], 48 | 49 | # virtme actually does work as a zip, but that forces the guest 50 | # tools to get extracted at run time. 51 | zip_safe = False, 52 | ) 53 | -------------------------------------------------------------------------------- /virtme-configkernel: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- mode: python -*- 3 | # virtme-configkernel: Configure a kernel for virtme 4 | # Copyright © 2014 Andy Lutomirski 5 | # Licensed under the GPLv2, which is available in the virtme distribution 6 | # as a file called LICENSE with SHA-256 hash: 7 | # 8177f97513213526df2cf6184d8ff986c675afb514d4e68a404010521b880643 8 | 9 | # This file is not installed; it's just used to run virtme from inside 10 | # a source distribution. 11 | 12 | import sys 13 | if sys.version_info < (3,3): 14 | print('virtme requires Python 3.3 or higher') 15 | sys.exit(1) 16 | 17 | from virtme.commands import configkernel 18 | exit(configkernel.main()) 19 | -------------------------------------------------------------------------------- /virtme-mkinitramfs: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- mode: python -*- 3 | # virtme-mkinitramfs: Generate an initramfs image for virtme 4 | # Copyright © 2019 Marcos Paulo de Souza 5 | # Licensed under the GPLv2, which is available in the virtme distribution 6 | # as a file called LICENSE with SHA-256 hash: 7 | # 8177f97513213526df2cf6184d8ff986c675afb514d4e68a404010521b880643 8 | 9 | import sys 10 | if sys.version_info < (3,3): 11 | print('virtme requires Python 3.3 or higher') 12 | sys.exit(1) 13 | 14 | from virtme.commands import mkinitramfs 15 | exit(mkinitramfs.main()) 16 | -------------------------------------------------------------------------------- /virtme-run: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- mode: python -*- 3 | # virtme-run: The main command-line virtme frontend 4 | # Copyright © 2014 Andy Lutomirski 5 | # Licensed under the GPLv2, which is available in the virtme distribution 6 | # as a file called LICENSE with SHA-256 hash: 7 | # 8177f97513213526df2cf6184d8ff986c675afb514d4e68a404010521b880643 8 | 9 | # This file is not installed; it's just use to run virtme from inside 10 | # a source distribution. 11 | 12 | import sys 13 | if sys.version_info < (3,3): 14 | print('virtme requires Python 3.3 or higher') 15 | sys.exit(1) 16 | 17 | from virtme.commands import run 18 | exit(run.main()) 19 | -------------------------------------------------------------------------------- /virtme/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amluto/virtme/3dfc002efdb2d8c06ff1306be276ec32f9bd00bb/virtme/__init__.py -------------------------------------------------------------------------------- /virtme/architectures.py: -------------------------------------------------------------------------------- 1 | # -*- mode: python -*- 2 | # qemu_helpers: Helpers to find QEMU and handle its quirks 3 | # Copyright © 2014 Andy Lutomirski 4 | # Licensed under the GPLv2, which is available in the virtme distribution 5 | # as a file called LICENSE with SHA-256 hash: 6 | # 8177f97513213526df2cf6184d8ff986c675afb514d4e68a404010521b880643 7 | 8 | import os 9 | from typing import List, Optional 10 | 11 | class Arch(object): 12 | def __init__(self, name) -> None: 13 | self.virtmename = name 14 | self.qemuname = name 15 | self.linuxname = name 16 | self.gccname = name 17 | 18 | defconfig_target = 'defconfig' 19 | 20 | @staticmethod 21 | def serial_dev_name(index) -> str: 22 | return 'ttyS%d' % index 23 | 24 | @staticmethod 25 | def qemuargs(is_native) -> List[str]: 26 | return [] 27 | 28 | @staticmethod 29 | def virtio_dev_type(virtiotype) -> str: 30 | # Return a full name for a virtio device. It would be 31 | # nice if QEMU abstracted this away, but it doesn't. 32 | return 'virtio-%s-pci' % virtiotype 33 | 34 | @staticmethod 35 | def earlyconsole_args() -> List[str]: 36 | return [] 37 | 38 | @staticmethod 39 | def serial_console_args() -> List[str]: 40 | return [] 41 | 42 | @staticmethod 43 | def qemu_nodisplay_args() -> List[str]: 44 | return ['-vga', 'none', '-display', 'none'] 45 | 46 | @staticmethod 47 | def config_base() -> List[str]: 48 | return [] 49 | 50 | def kimg_path(self) -> str: 51 | return 'arch/%s/boot/bzImage' % self.linuxname 52 | 53 | @staticmethod 54 | def dtb_path() -> Optional[str]: 55 | return None 56 | 57 | class Arch_unknown(Arch): 58 | @staticmethod 59 | def qemuargs(is_native): 60 | return Arch.qemuargs(is_native) 61 | 62 | class Arch_x86(Arch): 63 | def __init__(self, name): 64 | Arch.__init__(self, name) 65 | 66 | self.linuxname = 'x86' 67 | self.defconfig_target = '%s_defconfig' % name 68 | 69 | @staticmethod 70 | def qemuargs(is_native): 71 | ret = Arch.qemuargs(is_native) 72 | 73 | # Add a watchdog. This is useful for testing. 74 | ret.extend(['-watchdog', 'i6300esb']) 75 | 76 | if is_native and os.access('/dev/kvm', os.R_OK): 77 | # If we're likely to use KVM, request a full-featured CPU. 78 | # (NB: if KVM fails, this will cause problems. We should probe.) 79 | ret.extend(['-cpu', 'host']) # We can't migrate regardless. 80 | 81 | return ret 82 | 83 | @staticmethod 84 | def earlyconsole_args(): 85 | return ['earlyprintk=serial,ttyS0,115200'] 86 | 87 | @staticmethod 88 | def serial_console_args(): 89 | return ['console=ttyS0'] 90 | 91 | @staticmethod 92 | def config_base(): 93 | return ['CONFIG_SERIO=y', 94 | 'CONFIG_PCI=y', 95 | 'CONFIG_INPUT=y', 96 | 'CONFIG_INPUT_KEYBOARD=y', 97 | 'CONFIG_KEYBOARD_ATKBD=y', 98 | 'CONFIG_SERIAL_8250=y', 99 | 'CONFIG_SERIAL_8250_CONSOLE=y', 100 | 'CONFIG_X86_VERBOSE_BOOTUP=y', 101 | 'CONFIG_VGA_CONSOLE=y', 102 | 'CONFIG_FB=y', 103 | 'CONFIG_FB_VESA=y', 104 | 'CONFIG_FRAMEBUFFER_CONSOLE=y', 105 | 'CONFIG_RTC_CLASS=y', 106 | 'CONFIG_RTC_HCTOSYS=y', 107 | 'CONFIG_RTC_DRV_CMOS=y', 108 | 'CONFIG_HYPERVISOR_GUEST=y', 109 | 'CONFIG_PARAVIRT=y', 110 | 'CONFIG_KVM_GUEST=y', 111 | 112 | # Depending on the host kernel, virtme can nest! 113 | 'CONFIG_KVM=y', 114 | 'CONFIG_KVM_INTEL=y', 115 | 'CONFIG_KVM_AMD=y', 116 | ] 117 | 118 | class Arch_arm(Arch): 119 | def __init__(self): 120 | Arch.__init__(self, 'arm') 121 | 122 | self.defconfig_target = 'vexpress_defconfig' 123 | 124 | @staticmethod 125 | def qemuargs(is_native): 126 | ret = Arch.qemuargs(is_native) 127 | 128 | # Emulate a vexpress-a15. 129 | ret.extend(['-M', 'vexpress-a15']) 130 | 131 | # TODO: consider adding a PCI bus (and figuring out how) 132 | 133 | # TODO: This won't boot unless -dtb is set, but we need to figure 134 | # out how to find the dtb file. 135 | 136 | return ret 137 | 138 | @staticmethod 139 | def virtio_dev_type(virtiotype): 140 | return 'virtio-%s-device' % virtiotype 141 | 142 | @staticmethod 143 | def earlyconsole_args(): 144 | return ['earlyprintk=serial,ttyAMA0,115200'] 145 | 146 | @staticmethod 147 | def serial_console_args(): 148 | return ['console=ttyAMA0'] 149 | 150 | def kimg_path(self): 151 | return 'arch/arm/boot/zImage' 152 | 153 | def dtb_path(self): 154 | return 'arch/arm/boot/dts/vexpress-v2p-ca15-tc1.dtb' 155 | 156 | class Arch_aarch64(Arch): 157 | def __init__(self): 158 | Arch.__init__(self, 'aarch64') 159 | 160 | self.qemuname = 'aarch64' 161 | self.linuxname = 'arm64' 162 | self.gccname = 'aarch64' 163 | 164 | @staticmethod 165 | def qemuargs(is_native): 166 | ret = Arch.qemuargs(is_native) 167 | 168 | if is_native: 169 | ret.extend(['-M', 'virt,gic-version=host']) 170 | ret.extend(['-cpu', 'host']) 171 | else: 172 | # Emulate a fully virtual system. 173 | ret.extend(['-M', 'virt']) 174 | 175 | # Despite being called qemu-system-aarch64, QEMU defaults to 176 | # emulating a 32-bit CPU. Override it. 177 | ret.extend(['-cpu', 'cortex-a57']) 178 | 179 | 180 | return ret 181 | 182 | @staticmethod 183 | def virtio_dev_type(virtiotype): 184 | return 'virtio-%s-device' % virtiotype 185 | 186 | @staticmethod 187 | def earlyconsole_args(): 188 | return ['earlyprintk=serial,ttyAMA0,115200'] 189 | 190 | @staticmethod 191 | def serial_console_args(): 192 | return ['console=ttyAMA0'] 193 | 194 | def kimg_path(self): 195 | return 'arch/arm64/boot/Image' 196 | 197 | class Arch_ppc64(Arch): 198 | def __init__(self): 199 | Arch.__init__(self, 'ppc64') 200 | 201 | self.defconfig_target = 'ppc64_defconfig' 202 | self.qemuname = 'ppc64' 203 | self.linuxname = 'powerpc' 204 | self.gccname = 'ppc64' 205 | 206 | def qemuargs(self, is_native): 207 | ret = Arch.qemuargs(is_native) 208 | 209 | ret.extend(['-M', 'pseries']) 210 | 211 | return ret 212 | 213 | def kimg_path(self): 214 | # Apparently SLOF (QEMU's bundled firmware?) can't boot a zImage. 215 | return 'vmlinux' 216 | 217 | class Arch_riscv64(Arch): 218 | def __init__(self): 219 | Arch.__init__(self, 'riscv64') 220 | 221 | self.defconfig_target = 'defconfig' 222 | self.qemuname = 'riscv64' 223 | self.linuxname = 'riscv' 224 | self.gccname = 'riscv64' 225 | 226 | def qemuargs(self, is_native): 227 | ret = Arch.qemuargs(is_native) 228 | 229 | ret.extend(['-machine', 'virt']) 230 | ret.extend(['-bios', 'default']) 231 | 232 | return ret 233 | 234 | @staticmethod 235 | def serial_console_args(): 236 | return ['console=ttyS0'] 237 | 238 | def kimg_path(self): 239 | return 'arch/riscv/boot/Image' 240 | 241 | class Arch_sparc64(Arch): 242 | def __init__(self): 243 | Arch.__init__(self, 'sparc64') 244 | 245 | self.defconfig_target = 'sparc64_defconfig' 246 | self.qemuname = 'sparc64' 247 | self.linuxname = 'sparc' 248 | self.gccname = 'sparc64' 249 | 250 | def qemuargs(self, is_native): 251 | ret = Arch.qemuargs(is_native) 252 | 253 | return ret 254 | 255 | def kimg_path(self): 256 | return 'arch/sparc/boot/image' 257 | 258 | def qemu_nodisplay_args(self): 259 | # qemu-system-sparc fails to boot if -display none is set. 260 | return ['-nographic', '-vga', 'none'] 261 | 262 | class Arch_s390x(Arch): 263 | def __init__(self): 264 | Arch.__init__(self, 's390x') 265 | 266 | self.qemuname = 's390x' 267 | self.linuxname = 's390' 268 | self.gccname = 's390x' 269 | 270 | @staticmethod 271 | def virtio_dev_type(virtiotype): 272 | return 'virtio-%s-ccw' % virtiotype 273 | 274 | def qemuargs(self, is_native): 275 | ret = Arch.qemuargs(is_native) 276 | 277 | # Ask for the latest version of s390-ccw 278 | ret.extend(['-M', 's390-ccw-virtio']) 279 | 280 | # To be able to configure a console, we need to get rid of the 281 | # default console 282 | ret.extend(['-nodefaults']) 283 | 284 | ret.extend(['-device', 'sclpconsole,chardev=console']) 285 | 286 | return ret 287 | 288 | @staticmethod 289 | def config_base(): 290 | return ['CONFIG_MARCH_Z900=y'] 291 | 292 | ARCHES = {arch.virtmename: arch for arch in [ 293 | Arch_x86('x86_64'), 294 | Arch_x86('i386'), 295 | Arch_arm(), 296 | Arch_aarch64(), 297 | Arch_ppc64(), 298 | Arch_riscv64(), 299 | Arch_sparc64(), 300 | Arch_s390x(), 301 | ]} 302 | 303 | def get(arch: str) -> Arch: 304 | if arch in ARCHES: 305 | return ARCHES[arch] 306 | else: 307 | return Arch_unknown(arch) 308 | -------------------------------------------------------------------------------- /virtme/commands/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amluto/virtme/3dfc002efdb2d8c06ff1306be276ec32f9bd00bb/virtme/commands/__init__.py -------------------------------------------------------------------------------- /virtme/commands/configkernel.py: -------------------------------------------------------------------------------- 1 | # -*- mode: python -*- 2 | # virtme-configkernel: Configure a kernel for virtme 3 | # Copyright © 2014 Andy Lutomirski 4 | # Licensed under the GPLv2, which is available in the virtme distribution 5 | # as a file called LICENSE with SHA-256 hash: 6 | # 8177f97513213526df2cf6184d8ff986c675afb514d4e68a404010521b880643 7 | 8 | from typing import Optional 9 | 10 | import argparse 11 | import os 12 | import shlex 13 | import shutil 14 | import subprocess 15 | import multiprocessing 16 | from .. import architectures 17 | 18 | uname = os.uname() 19 | 20 | def make_parser(): 21 | parser = argparse.ArgumentParser( 22 | description='Configure a kernel for virtme', 23 | ) 24 | 25 | parser.add_argument('--arch', action='store', metavar='ARCHITECTURE', 26 | default=uname.machine, 27 | help='Target architecture') 28 | 29 | g = parser.add_argument_group(title='Mode').add_mutually_exclusive_group() 30 | 31 | g.add_argument('--allnoconfig', action='store_true', 32 | help='Overwrite configuration with a virtme-suitable allnoconfig (unlikely to work)') 33 | 34 | g.add_argument('--defconfig', action='store_true', 35 | help='Overwrite configuration with a virtme-suitable defconfig') 36 | 37 | g.add_argument('--update', action='store_true', 38 | help='Update existing config for virtme') 39 | 40 | return parser 41 | 42 | _ARGPARSER = make_parser() 43 | 44 | def arg_fail(message): 45 | print(message) 46 | _ARGPARSER.print_usage() 47 | exit(1) 48 | 49 | _GENERIC_CONFIG = [ 50 | '# Generic', 51 | 'CONFIG_UEVENT_HELPER=n', # Obsolete and slow 52 | 'CONFIG_VIRTIO=y', 53 | 'CONFIG_VIRTIO_PCI=y', 54 | 'CONFIG_VIRTIO_MMIO=y', 55 | 'CONFIG_NET=y', 56 | 'CONFIG_NET_CORE=y', 57 | 'CONFIG_NETDEVICES=y', 58 | 'CONFIG_NETWORK_FILESYSTEMS=y', 59 | 'CONFIG_INET=y', 60 | 'CONFIG_NET_9P=y', 61 | 'CONFIG_NET_9P_VIRTIO=y', 62 | 'CONFIG_9P_FS=y', 63 | 'CONFIG_VIRTIO_NET=y', 64 | 'CONFIG_CMDLINE_OVERRIDE=n', 65 | 'CONFIG_BINFMT_SCRIPT=y', 66 | 'CONFIG_SHMEM=y', 67 | 'CONFIG_TMPFS=y', 68 | 'CONFIG_UNIX=y', 69 | 'CONFIG_MODULE_SIG_FORCE=n', 70 | 'CONFIG_DEVTMPFS=y', 71 | 'CONFIG_TTY=y', 72 | 'CONFIG_VT=y', 73 | 'CONFIG_UNIX98_PTYS=y', 74 | 'CONFIG_EARLY_PRINTK=y', 75 | 'CONFIG_INOTIFY_USER=y', 76 | '', 77 | '# virtio-scsi support', 78 | 'CONFIG_BLOCK=y', 79 | 'CONFIG_SCSI_LOWLEVEL=y', 80 | 'CONFIG_SCSI=y', 81 | 'CONFIG_SCSI_VIRTIO=y', 82 | 'CONFIG_BLK_DEV_SD=y', 83 | '', 84 | '# virt-serial support', 85 | 'CONFIG_VIRTIO_CONSOLE=y', 86 | '', 87 | '# watchdog (useful for test scripts)', 88 | 'CONFIG_WATCHDOG=y', 89 | 'CONFIG_WATCHDOG_CORE=y', 90 | 'CONFIG_I6300ESB_WDT=y', 91 | ] 92 | 93 | def main(): 94 | args = _ARGPARSER.parse_args() 95 | 96 | if not os.path.isfile('scripts/kconfig/merge_config.sh') and \ 97 | not os.path.isfile('source/scripts/kconfig/merge_config.sh'): 98 | print('virtme-configkernel must be run in a kernel source/build directory') 99 | return 1 100 | 101 | arch = architectures.get(args.arch) 102 | 103 | conf = (_GENERIC_CONFIG + 104 | ['# Arch-specific options'] + 105 | arch.config_base()) 106 | 107 | archargs = ['ARCH=%s' % shlex.quote(arch.linuxname)] 108 | 109 | if shutil.which('%s-linux-gnu-gcc' % arch.gccname): 110 | archargs.append('CROSS_COMPILE=%s' % shlex.quote("%s-linux-gnu-" % arch.gccname)) 111 | 112 | maketarget: Optional[str] 113 | 114 | if args.allnoconfig: 115 | maketarget = 'allnoconfig' 116 | updatetarget = 'syncconfig' 117 | elif args.defconfig: 118 | maketarget = arch.defconfig_target 119 | updatetarget = 'olddefconfig' 120 | elif args.update: 121 | maketarget = None 122 | updatetarget = 'olddefconfig' 123 | else: 124 | arg_fail('No mode selected') 125 | 126 | # TODO: Get rid of most of the noise and check the result. 127 | 128 | # Set up an initial config 129 | if maketarget: 130 | subprocess.check_call(['make'] + archargs + [maketarget]) 131 | 132 | config = '.config' 133 | 134 | # Check if KBUILD_OUTPUT is defined and if it's a directory 135 | config_dir = os.environ.get('KBUILD_OUTPUT', '') 136 | if config_dir and os.path.isdir(config_dir): 137 | config = os.path.join(config_dir, config) 138 | 139 | with open(config, 'ab') as conffile: 140 | conffile.write('\n'.join(conf).encode('utf-8')) 141 | 142 | subprocess.check_call(['make'] + archargs + [updatetarget]) 143 | 144 | print("Configured. Build with 'make %s -j%d'" % 145 | (' '.join(archargs), multiprocessing.cpu_count())) 146 | 147 | return 0 148 | 149 | if __name__ == '__main__': 150 | exit(main()) 151 | -------------------------------------------------------------------------------- /virtme/commands/mkinitramfs.py: -------------------------------------------------------------------------------- 1 | # -*- mode: python -*- 2 | # virtme-mkinitramfs: Generate an initramfs image for virtme 3 | # Copyright © 2014 Andy Lutomirski 4 | # Licensed under the GPLv2, which is available in the virtme distribution 5 | # as a file called LICENSE with SHA-256 hash: 6 | # 8177f97513213526df2cf6184d8ff986c675afb514d4e68a404010521b880643 7 | 8 | import argparse 9 | from .. import modfinder 10 | from .. import virtmods 11 | from .. import mkinitramfs 12 | 13 | def make_parser(): 14 | parser = argparse.ArgumentParser( 15 | description='Generate an initramfs image for virtme', 16 | ) 17 | 18 | parser.add_argument('--mod-kversion', action='store', default=None, 19 | help='Find kernel modules related to kernel version set') 20 | 21 | parser.add_argument('--rw', action='store_true', default=False, 22 | help='Mount initramfs as rw. Default is ro') 23 | 24 | parser.add_argument('--outfile', action='store', default=None, 25 | help='Filename of the resulting initramfs file. Default: send initramfs to stdout') 26 | 27 | return parser 28 | 29 | def main(): 30 | import sys 31 | 32 | args = make_parser().parse_args() 33 | 34 | config = mkinitramfs.Config() 35 | 36 | if args.mod_kversion is not None: 37 | config.modfiles = modfinder.find_modules_from_install( 38 | virtmods.MODALIASES, kver=args.mod_kversion) 39 | 40 | # search for busybox in the root filesystem 41 | config.busybox = mkinitramfs.find_busybox(root = '/', is_native = True) 42 | 43 | if args.rw: 44 | config.access = 'rw' 45 | 46 | if args.outfile is None: 47 | buf = sys.stdout.buffer 48 | else: 49 | buf = open(args.outfile, 'w+b') 50 | 51 | mkinitramfs.mkinitramfs(buf, config) 52 | 53 | return 0 54 | 55 | if __name__ == '__main__': 56 | exit(main()) 57 | -------------------------------------------------------------------------------- /virtme/commands/run.py: -------------------------------------------------------------------------------- 1 | # -*- mode: python -*- 2 | # virtme-run: The main command-line virtme frontend 3 | # Copyright © 2014 Andy Lutomirski 4 | # Licensed under the GPLv2, which is available in the virtme distribution 5 | # as a file called LICENSE with SHA-256 hash: 6 | # 8177f97513213526df2cf6184d8ff986c675afb514d4e68a404010521b880643 7 | 8 | from typing import Any, Optional, List, NoReturn, Dict, Tuple 9 | 10 | import argparse 11 | import tempfile 12 | import os 13 | import errno 14 | import fcntl 15 | import sys 16 | import shlex 17 | import re 18 | import itertools 19 | import subprocess 20 | from .. import virtmods 21 | from .. import modfinder 22 | from .. import mkinitramfs 23 | from .. import qemu_helpers 24 | from .. import architectures 25 | from .. import resources 26 | 27 | uname = os.uname() 28 | 29 | class SilentError(Exception): 30 | pass 31 | 32 | def make_parser() -> argparse.ArgumentParser: 33 | parser = argparse.ArgumentParser( 34 | description='Virtualize your system (or another) under a kernel image', 35 | ) 36 | 37 | g: Any 38 | 39 | g = parser.add_argument_group(title='Selection of kernel and modules').add_mutually_exclusive_group() 40 | g.add_argument('--installed-kernel', action='store', nargs='?', 41 | const=uname.release, default=None, metavar='VERSION', 42 | help='Use an installed kernel and its associated modules. If no version is specified, the running kernel will be used.') 43 | 44 | g.add_argument('--kimg', action='store', 45 | help='Use specified kernel image with no modules.') 46 | 47 | g.add_argument('--kdir', action='store', metavar='KDIR', 48 | help='Use a compiled kernel source directory') 49 | 50 | g = parser.add_argument_group(title='Kernel options') 51 | g.add_argument('--mods', action='store', choices=['none', 'use', 'auto'], default='use', 52 | help='Setup loadable kernel modules inside a compiled kernel source directory (used in conjunction with --kdir); none: ignore kernel modules, use: asks user to refresh virtme\'s kernel modules directory, auto: automatically refreshes virtme\'s kernel modules directory') 53 | 54 | g.add_argument('-a', '--kopt', action='append', default=[], 55 | help='Add a kernel option. You can specify this more than once.') 56 | 57 | g.add_argument('--xen', action='store', 58 | help='Boot Xen using the specified uncompressed hypervisor.') 59 | 60 | g = parser.add_argument_group(title='Common guest options') 61 | g.add_argument('--root', action='store', default='/', 62 | help='Local path to use as guest root') 63 | g.add_argument('--rw', action='store_true', 64 | help='Give the guest read-write access to its root filesystem') 65 | g.add_argument('--graphics', action='store_true', 66 | help='Show graphical output instead of using a console.') 67 | g.add_argument('--net', action='store', const='user', nargs='?', 68 | choices=['user', 'bridge'], 69 | help='Enable basic network access.') 70 | g.add_argument('--balloon', action='store_true', 71 | help='Allow the host to ask the guest to release memory.') 72 | g.add_argument('--disk', action='append', default=[], metavar='NAME=PATH', 73 | help='Add a read/write virtio-scsi disk. The device node will be /dev/disk/by-id/scsi-0virtme_disk_NAME.') 74 | g.add_argument('--blk-disk', action='append', default=[], metavar='NAME=PATH', 75 | help='Add a read/write virtio-blk disk. The device nodes will be /dev/disk/by-id/virtio-virtme_disk_blk_NAME.') 76 | g.add_argument('--memory', action='store', default=None, 77 | help='Set guest memory and qemu -m flag.') 78 | g.add_argument('--cpus', action='store', default=None, 79 | help='Set guest cpu and qemu -smp flag.') 80 | g.add_argument('--name', action='store', default=None, 81 | help='Set guest hostname and qemu -name flag.') 82 | 83 | g = parser.add_argument_group( 84 | title='Scripting', 85 | description="Using any of the scripting options will run a script in the guest. The script's stdin will be attached to virtme-run's stdin and the script's stdout and stderr will both be attached to virtme-run's stdout. Kernel logs will go to stderr. This behaves oddly if stdin is a terminal; try using 'cat |virtme-run' if you have trouble with script mode.") 86 | g.add_argument('--script-sh', action='store', metavar='SHELL_COMMAND', 87 | help='Run a one-line shell script in the guest.') 88 | g.add_argument('--script-exec', action='store', metavar='BINARY', 89 | help='Run the specified binary in the guest.') 90 | 91 | g = parser.add_argument_group( 92 | title='Architecture', 93 | description="Options related to architecture selection") 94 | g.add_argument('--arch', action='store', metavar='ARCHITECTURE', 95 | default=uname.machine, 96 | help='Guest architecture') 97 | g.add_argument('--busybox', action='store', metavar='PATH_TO_BUSYBOX', 98 | help='Use the specified busybox binary.') 99 | 100 | g = parser.add_argument_group(title='Virtualizer settings') 101 | g.add_argument('-q', '--qemu-opt', action='append', default=[], 102 | help="Add a single QEMU argument. Use this when --qemu-opts's greedy behavior is problematic.'") 103 | g.add_argument('--qemu-opts', action='store', nargs=argparse.REMAINDER, 104 | metavar='OPTS...', help='Additional arguments for QEMU. This will consume all remaining arguments, so it must be specified last. Avoid using -append; use --kopt instead.') 105 | 106 | g = parser.add_argument_group(title='Debugging/testing') 107 | g.add_argument('--force-initramfs', action='store_true', 108 | help='Use an initramfs even if unnecessary') 109 | g.add_argument('--dry-run', action='store_true', 110 | help="Initialize everything but don't run the guest") 111 | g.add_argument('--show-command', action='store_true', 112 | help='Show the VM command line') 113 | g.add_argument('--save-initramfs', action='store', 114 | help='Save the generated initramfs to the specified path') 115 | g.add_argument('--show-boot-console', action='store_true', 116 | help='Show the boot console when running scripts') 117 | 118 | g = parser.add_argument_group(title='Guest userspace configuration') 119 | g.add_argument('--pwd', action='store_true', 120 | help='Propagate current working directory to the guest') 121 | g.add_argument('--cwd', action='store', 122 | help='Change guest working directory') 123 | 124 | g = parser.add_argument_group(title='Sharing resources with guest') 125 | g.add_argument('--rwdir', action='append', default=[], 126 | help="Supply a read/write directory to the guest. Use --rwdir=path or --rwdir=guestpath=hostpath.") 127 | g.add_argument('--rodir', action='append', default=[], 128 | help="Supply a read-only directory to the guest. Use --rodir=path or --rodir=guestpath=hostpath.") 129 | 130 | return parser 131 | 132 | _ARGPARSER = make_parser() 133 | 134 | def arg_fail(message, show_usage=True) -> NoReturn: 135 | print(message) 136 | if show_usage: 137 | _ARGPARSER.print_usage() 138 | sys.exit(1) 139 | 140 | def is_file_more_recent(a, b) -> bool: 141 | return os.stat(a).st_mtime > os.stat(b).st_mtime 142 | 143 | class Kernel: 144 | __slots__ = ['kimg', 'dtb', 'modfiles', 'moddir', 'use_root_mods', 'config'] 145 | 146 | kimg: str 147 | dtb: Optional[str] 148 | modfiles: List[str] 149 | moddir: Optional[str] 150 | use_root_mods: bool 151 | config: Optional[Dict[str, str]] 152 | 153 | def load_config(self, kdir: str) -> None: 154 | cfgfile = os.path.join(kdir, '.config') 155 | if os.path.isfile(cfgfile): 156 | self.config = {} 157 | regex = re.compile('^(CONFIG_[A-Z0-9_]+)=([ymn])$') 158 | for line in open(cfgfile, 'r'): 159 | m = regex.match(line.strip()) 160 | if m: 161 | self.config[m.group(1)] = m.group(2) 162 | 163 | def find_kernel_and_mods(arch, args) -> Kernel: 164 | kernel = Kernel() 165 | 166 | kernel.use_root_mods = False 167 | 168 | if args.installed_kernel is not None: 169 | kver = args.installed_kernel 170 | if args.mods != 'none': 171 | kernel.modfiles = modfinder.find_modules_from_install( 172 | virtmods.MODALIASES, kver=kver) 173 | kernel.moddir = os.path.join('/lib/modules', kver) 174 | else: 175 | kernel.modfiles = [] 176 | kernel.moddir = None 177 | kernel.kimg = '/usr/lib/modules/%s/vmlinuz' % kver 178 | if not os.path.exists(kernel.kimg): 179 | kernel.kimg = '/boot/vmlinuz-%s' % kver 180 | kernel.dtb = None # For now 181 | kernel.use_root_mods = True 182 | elif args.kdir is not None: 183 | kernel.kimg = os.path.join(args.kdir, arch.kimg_path()) 184 | virtme_mods = os.path.join(args.kdir, '.virtme_mods') 185 | mod_file = os.path.join(args.kdir, 'modules.order') 186 | virtme_mod_file = os.path.join(virtme_mods, 'lib/modules/0.0.0/modules.dep') 187 | kernel.load_config(args.kdir) 188 | 189 | # Kernel modules support 190 | kver = None 191 | kernel.moddir = None 192 | kernel.modfiles = [] 193 | 194 | modmode = args.mods 195 | if kernel.config is not None and kernel.config.get('CONFIG_MODULES', 'n') != 'y': 196 | modmode = 'none' 197 | 198 | if modmode == 'none': 199 | pass 200 | elif modmode == 'use' or modmode == 'auto': 201 | # Check if modules.order exists, otherwise it's not possible to use 202 | # this option 203 | if not os.path.exists(mod_file): 204 | arg_fail('%s not found: kernel modules not enabled or kernel not compiled properly' % mod_file, show_usage=False) 205 | # Check if virtme's kernel modules directory needs to be updated 206 | if not os.path.exists(virtme_mods) or \ 207 | is_file_more_recent(mod_file, virtme_mod_file): 208 | if modmode == 'use': 209 | # Inform user to manually refresh virtme's kernel modules 210 | # directory 211 | arg_fail("please run virtme-prep-kdir-mods to update virtme's kernel modules directory or use --mods=auto", show_usage=False) 212 | else: 213 | # Auto-refresh virtme's kernel modules directory 214 | try: 215 | resources.run_script('virtme-prep-kdir-mods', 216 | cwd=args.kdir) 217 | except subprocess.CalledProcessError: 218 | raise SilentError() 219 | kernel.moddir = os.path.join(virtme_mods, 'lib/modules', '0.0.0') 220 | kernel.modfiles = modfinder.find_modules_from_install( 221 | virtmods.MODALIASES, root=virtme_mods, kver='0.0.0') 222 | print(kernel.moddir) 223 | else: 224 | arg_fail("invalid argument '%s', please use --mods=none|use|auto" % args.mods) 225 | 226 | dtb_path = arch.dtb_path() 227 | if dtb_path is None: 228 | kernel.dtb = None 229 | else: 230 | kernel.dtb = os.path.join(args.kdir, dtb_path) 231 | elif args.kimg is not None: 232 | kernel.kimg = args.kimg 233 | kernel.modfiles = [] 234 | kernel.moddir = None 235 | kernel.dtb = None # TODO: fix this 236 | if args.mods != 'use': 237 | arg_fail("--mods is not currently supported properly with --kimg") 238 | else: 239 | arg_fail('You must specify a kernel to use.') 240 | 241 | return kernel 242 | 243 | def export_virtfs(qemu: qemu_helpers.Qemu, arch: architectures.Arch, 244 | qemuargs: List[str], path: str, 245 | mount_tag: str, security_model='none', readonly=True) -> None: 246 | # NB: We can't use -virtfs for this, because it can't handle a mount_tag 247 | # that isn't a valid QEMU identifier. 248 | fsid = 'virtfs%d' % len(qemuargs) 249 | qemuargs.extend(['-fsdev', 'local,id=%s,path=%s,security_model=%s%s%s' % 250 | (fsid, qemu.quote_optarg(path), 251 | security_model, ',readonly=on' if readonly else '', 252 | ',multidevs=remap' if qemu.has_multidevs else '')]) 253 | qemuargs.extend(['-device', '%s,fsdev=%s,mount_tag=%s' % (arch.virtio_dev_type('9p'), fsid, qemu.quote_optarg(mount_tag))]) 254 | 255 | def quote_karg(arg: str) -> str: 256 | if '"' in arg: 257 | raise ValueError("cannot quote '\"' in kernel args") 258 | 259 | if ' ' in arg: 260 | return '"%s"' % arg 261 | else: 262 | return arg 263 | 264 | # Validate name=path arguments from --disk and --blk-disk 265 | def sanitize_disk_args(func: str, arg: str) -> Tuple[str, str]: 266 | namefile = arg.split('=', 1) 267 | if len(namefile) != 2: 268 | arg_fail('invalid argument to %s' % func) 269 | name, fn = namefile 270 | if '=' in fn or ',' in fn: 271 | arg_fail("%s filenames cannot contain '=' or ','" % (func)) 272 | if '=' in name or ',' in name: 273 | arg_fail("%s device names cannot contain '=' or ','" % (func)) 274 | 275 | return name, fn 276 | 277 | # Allowed characters in mount paths. We can extend this over time if needed. 278 | _SAFE_PATH_PATTERN = '[a-zA-Z0-9_+ /.-]+' 279 | _RWDIR_RE = re.compile('^(%s)(?:=(%s))?$' % 280 | (_SAFE_PATH_PATTERN, _SAFE_PATH_PATTERN)) 281 | 282 | def do_it() -> int: 283 | args = _ARGPARSER.parse_args() 284 | 285 | arch = architectures.get(args.arch) 286 | is_native = (args.arch == uname.machine) 287 | 288 | qemu = qemu_helpers.Qemu(arch.qemuname) 289 | qemu.probe() 290 | 291 | need_initramfs = args.force_initramfs or qemu.cannot_overmount_virtfs 292 | 293 | config = mkinitramfs.Config() 294 | 295 | kernel = find_kernel_and_mods(arch, args) 296 | config.modfiles = kernel.modfiles 297 | if config.modfiles: 298 | need_initramfs = True 299 | 300 | qemuargs: List[str] = [qemu.qemubin] 301 | kernelargs = [] 302 | xenargs = [] 303 | 304 | # Put the '-name' flag first so it's easily visible in ps, top, etc. 305 | if args.name: 306 | qemuargs.extend(['-name', args.name]) 307 | kernelargs.append('virtme_hostname=%s' % args.name) 308 | 309 | # Set up virtfs 310 | export_virtfs(qemu, arch, qemuargs, args.root, '/dev/root', readonly=(not args.rw)) 311 | 312 | guest_tools_path = resources.find_guest_tools() 313 | if guest_tools_path is None: 314 | raise ValueError("couldn't find guest tools -- virtme is installed incorrectly") 315 | 316 | export_virtfs(qemu, arch, qemuargs, guest_tools_path, 317 | 'virtme.guesttools') 318 | 319 | initcmds = ['mkdir -p /run/virtme/guesttools', 320 | '/bin/mount -n -t 9p -o ro,version=9p2000.L,trans=virtio,access=any virtme.guesttools /run/virtme/guesttools', 321 | 'exec /run/virtme/guesttools/virtme-init'] 322 | 323 | # Arrange for modules to end up in the right place 324 | if kernel.moddir is not None: 325 | if kernel.use_root_mods: 326 | # Tell virtme-init to use the root /lib/modules 327 | kernelargs.append("virtme_root_mods=1") 328 | else: 329 | # We're grabbing modules from somewhere other than /lib/modules. 330 | # Rather than mounting it separately, symlink it in the guest. 331 | # This allows symlinks within the module directory to resolve 332 | # correctly in the guest. 333 | kernelargs.append("virtme_link_mods=/%s" % qemu.quote_optarg(os.path.relpath(kernel.moddir, args.root))) 334 | else: 335 | # No modules are available. virtme-init will hide /lib/modules/KVER 336 | pass 337 | 338 | # Set up mounts 339 | mount_index = 0 340 | for dirtype, dirarg in itertools.chain((('rwdir', i) for i in args.rwdir), 341 | (('rodir', i) for i in args.rodir)): 342 | m = _RWDIR_RE.match(dirarg) 343 | if not m: 344 | arg_fail('invalid --%s parameter %r' % (dirtype, dirarg)) 345 | if m.group(2) is not None: 346 | guestpath = m.group(1) 347 | hostpath = m.group(2) 348 | else: 349 | hostpath = m.group(1) 350 | guestpath = os.path.relpath(hostpath, args.root) 351 | if guestpath.startswith('..'): 352 | arg_fail('%r is not inside the root' % hostpath) 353 | 354 | idx = mount_index 355 | mount_index += 1 356 | tag = 'virtme.initmount%d' % idx 357 | export_virtfs(qemu, arch, qemuargs, hostpath, tag, readonly=(dirtype != 'rwdir')) 358 | kernelargs.append('virtme_initmount%d=%s' % (idx, guestpath)) 359 | 360 | # Turn on KVM if available 361 | if is_native: 362 | qemuargs.extend(['-machine', 'accel=kvm:tcg']) 363 | 364 | # Add architecture-specific options 365 | qemuargs.extend(arch.qemuargs(is_native)) 366 | 367 | # Set up / override baseline devices 368 | qemuargs.extend(['-parallel', 'none']) 369 | qemuargs.extend(['-net', 'none']) 370 | 371 | if not args.graphics and not args.script_sh and not args.script_exec: 372 | # It would be nice to use virtconsole, but it's terminally broken 373 | # in current kernels. Nonetheless, I'm configuring the console 374 | # manually to make it easier to tweak in the future. 375 | qemuargs.extend(['-echr', '1']) 376 | qemuargs.extend(['-serial', 'none']) 377 | qemuargs.extend(['-chardev', 'stdio,id=console,signal=off,mux=on']) 378 | 379 | # We should be using the new-style -device serialdev,chardev=xyz, 380 | # but many architecture-specific serial devices don't support that. 381 | qemuargs.extend(['-serial', 'chardev:console']) 382 | 383 | qemuargs.extend(['-mon', 'chardev=console']) 384 | 385 | kernelargs.extend(arch.earlyconsole_args()) 386 | qemuargs.extend(arch.qemu_nodisplay_args()) 387 | 388 | if not args.xen: 389 | kernelargs.extend(arch.serial_console_args()) 390 | else: 391 | # Horrible special case 392 | xenargs.extend(['console=com1']) 393 | kernelargs.extend(['xencons=hvc', 'console=hvc0']) 394 | 395 | # PS/2 probing is slow; give the kernel a hint to speed it up. 396 | kernelargs.extend(['psmouse.proto=exps']) 397 | 398 | # Fix the terminal defaults (and set iutf8 because that's a better 399 | # default nowadays). I don't know of any way to keep this up to date 400 | # after startup, though. 401 | try: 402 | terminal_size = os.get_terminal_size() 403 | kernelargs.extend(['virtme_stty_con=rows %d cols %d iutf8' % 404 | (terminal_size.lines, terminal_size.columns)]) 405 | except OSError as e: 406 | # don't die if running with a non-TTY stdout 407 | if e.errno != errno.ENOTTY: 408 | raise 409 | 410 | # Propagate the terminal type 411 | if 'TERM' in os.environ: 412 | kernelargs.extend(['TERM=%s' % os.environ['TERM']]) 413 | 414 | if args.balloon: 415 | qemuargs.extend(['-balloon', 'virtio']) 416 | 417 | if args.memory: 418 | qemuargs.extend(['-m', args.memory]) 419 | 420 | if args.cpus: 421 | qemuargs.extend(['-smp', args.cpus]) 422 | 423 | if args.blk_disk: 424 | for i,d in enumerate(args.blk_disk): 425 | driveid = 'blk-disk%d' % i 426 | name, fn = sanitize_disk_args('--blk-disk', d) 427 | qemuargs.extend(['-drive', 'if=none,id=%s,file=%s' % (driveid, fn), 428 | '-device', 'virtio-blk-pci,drive=%s,serial=%s' % (driveid, name)]) 429 | 430 | if args.disk: 431 | qemuargs.extend(['-device', '%s,id=scsi' % arch.virtio_dev_type('scsi')]) 432 | 433 | for i,d in enumerate(args.disk): 434 | driveid = 'disk%d' % i 435 | name, fn = sanitize_disk_args('--disk', d) 436 | qemuargs.extend(['-drive', 'if=none,id=%s,file=%s' % (driveid, fn), 437 | '-device', 'scsi-hd,drive=%s,vendor=virtme,product=disk,serial=%s' % (driveid, name)]) 438 | 439 | has_script = False 440 | 441 | def do_script(shellcmd: str, use_exec=False, show_boot_console=False) -> None: 442 | if args.graphics: 443 | arg_fail('scripts and --graphics are mutually exclusive') 444 | 445 | nonlocal has_script 446 | nonlocal need_initramfs 447 | if has_script: 448 | arg_fail('conflicting script options') 449 | has_script = True 450 | need_initramfs = True # TODO: Fix this 451 | 452 | # Turn off default I/O 453 | qemuargs.extend(arch.qemu_nodisplay_args()) 454 | 455 | # Send kernel logs to stderr 456 | qemuargs.extend(['-serial', 'none']) 457 | qemuargs.extend(['-chardev', 'file,id=console,path=/proc/self/fd/2']) 458 | 459 | # We should be using the new-style -device serialdev,chardev=xyz, 460 | # but many architecture-specific serial devices don't support that. 461 | qemuargs.extend(['-serial', 'chardev:console']) 462 | 463 | if show_boot_console: 464 | serdev = qemu.quote_optarg(arch.serial_dev_name(0)) 465 | kernelargs.extend(['console=%s' % serdev, 466 | 'earlyprintk=serial,%s,115200' % serdev]) 467 | 468 | # Set up a virtserialport for script I/O 469 | qemuargs.extend(['-chardev', 'stdio,id=stdio,signal=on,mux=off']) 470 | qemuargs.extend(['-device', arch.virtio_dev_type('serial')]) 471 | qemuargs.extend(['-device', 'virtserialport,name=virtme.scriptio,chardev=stdio']) 472 | 473 | # Scripts shouldn't reboot 474 | qemuargs.extend(['-no-reboot']) 475 | 476 | # Ask virtme-init to run the script 477 | config.virtme_data[b'script'] = """#!/bin/sh 478 | 479 | {prefix}{shellcmd} 480 | """.format(shellcmd=shellcmd, prefix="exec " if use_exec else "").encode('ascii') 481 | 482 | # Nasty issue: QEMU will set O_NONBLOCK on fds 0, 1, and 2. 483 | # This isn't inherently bad, but it can cause a problem if 484 | # another process is reading from 1 or writing to 0, which is 485 | # exactly what happens if you're using a terminal and you 486 | # redirect some, but not all, of the tty fds. Work around it 487 | # by giving QEMU private copies of the open object if either 488 | # of them is a terminal. 489 | for oldfd,mode in ((0,os.O_RDONLY), (1,os.O_WRONLY), (2,os.O_WRONLY)): 490 | if os.isatty(oldfd): 491 | try: 492 | newfd = os.open('/proc/self/fd/%d' % oldfd, mode) 493 | except OSError: 494 | pass 495 | else: 496 | os.dup2(newfd, oldfd) 497 | os.close(newfd) 498 | 499 | if args.script_sh is not None: 500 | do_script(args.script_sh, show_boot_console=args.show_boot_console) 501 | 502 | if args.script_exec is not None: 503 | do_script(shlex.quote(args.script_exec), use_exec=True, show_boot_console=args.show_boot_console) 504 | 505 | if args.net: 506 | qemuargs.extend(['-device', 'virtio-net-pci,netdev=n0']) 507 | if args.net == 'user': 508 | qemuargs.extend(['-netdev', 'user,id=n0']) 509 | elif args.net == 'bridge': 510 | # This is highly experimental. At least on Fedora 30 on 511 | # a wireless network, it appears to successfully start but 512 | # not have any network access. Patches or guidance welcome. 513 | # (I assume it's mostly a lost cause on a wireless network 514 | # due to a lack of widespread or automatic WDS support.) 515 | qemuargs.extend(['-netdev', 'bridge,id=n0,br=virbr0']) 516 | else: 517 | assert False 518 | kernelargs.extend(['virtme.dhcp']) 519 | 520 | if args.pwd: 521 | rel_pwd = os.path.relpath(os.getcwd(), args.root) 522 | if rel_pwd.startswith('..'): 523 | print('current working directory is not contained in the root') 524 | return 1 525 | kernelargs.append('virtme_chdir=%s' % rel_pwd) 526 | 527 | if args.cwd is not None: 528 | if args.pwd: 529 | arg_fail('--pwd and --cwd are mutually exclusive') 530 | rel_cwd = os.path.relpath(args.cwd, args.root) 531 | if rel_cwd.startswith('..'): 532 | print('specified working directory is not contained in the root') 533 | return 1 534 | kernelargs.append('virtme_chdir=%s' % rel_cwd) 535 | 536 | initrdpath: Optional[str] 537 | 538 | if need_initramfs: 539 | if args.busybox is not None: 540 | config.busybox = args.busybox 541 | else: 542 | busybox = mkinitramfs.find_busybox(args.root, is_native) 543 | if busybox is None: 544 | print('virtme-run: initramfs is needed, and no busybox was found', 545 | file=sys.stderr) 546 | return 1 547 | config.busybox = busybox 548 | 549 | if args.rw: 550 | config.access = 'rw' 551 | 552 | # Set up the initramfs (warning: hack ahead) 553 | if args.save_initramfs is not None: 554 | initramfsfile = open(args.save_initramfs, 'xb') 555 | initramfsfd = initramfsfile.fileno() 556 | else: 557 | initramfsfd,tmpname = tempfile.mkstemp('irfs') 558 | os.unlink(tmpname) 559 | initramfsfile = os.fdopen(initramfsfd, 'r+b') 560 | mkinitramfs.mkinitramfs(initramfsfile, config) 561 | initramfsfile.flush() 562 | if args.save_initramfs is not None: 563 | initrdpath = args.save_initramfs 564 | else: 565 | fcntl.fcntl(initramfsfd, fcntl.F_SETFD, 0) 566 | initrdpath = '/proc/self/fd/%d' % initramfsfd 567 | else: 568 | if args.save_initramfs is not None: 569 | print('--save_initramfs specified but initramfs is not used', 570 | file=sys.stderr) 571 | return 1 572 | 573 | # No initramfs! Warning: this is slower than using an initramfs 574 | # because the kernel will wait for device probing to finish. 575 | # Sigh. 576 | kernelargs.extend([ 577 | 'rootfstype=9p', 578 | 'rootflags=version=9p2000.L,trans=virtio,access=any', 579 | 'raid=noautodetect', 580 | 'rw' if args.rw else 'ro', 581 | ]) 582 | initrdpath = None 583 | initcmds.insert(0, 'mount -t tmpfs run /run') 584 | 585 | # Now that we're done setting up kernelargs, append user-specified args 586 | # and then initargs 587 | kernelargs.extend(args.kopt) 588 | 589 | # Unknown options get turned into arguments to init, which is annoying 590 | # because we're explicitly passing '--' to set the arguments directly. 591 | # Fortunately, 'init=' will clear any arguments parsed so far, so make 592 | # sure that 'init=' appears directly before '--'. 593 | kernelargs.append('init=/bin/sh') 594 | kernelargs.append('--') 595 | kernelargs.extend(['-c', ';'.join(initcmds)]) 596 | 597 | if args.xen is None: 598 | # Load a normal kernel 599 | qemuargs.extend(['-kernel', kernel.kimg]) 600 | if kernelargs: 601 | qemuargs.extend(['-append', 602 | ' '.join(quote_karg(a) for a in kernelargs)]) 603 | if initrdpath is not None: 604 | qemuargs.extend(['-initrd', initrdpath]) 605 | if kernel.dtb is not None: 606 | qemuargs.extend(['-dtb', kernel.dtb]) 607 | 608 | if xenargs: 609 | raise ValueError("Can't pass Xen any arguments if we're not using Xen") 610 | else: 611 | # Use multiboot syntax to load Xen 612 | qemuargs.extend(['-kernel', args.xen]) 613 | if xenargs: 614 | qemuargs.extend(['-append', 615 | ' '.join(quote_karg(a) for a in xenargs)]) 616 | qemuargs.extend(['-initrd', '%s %s%s' % ( 617 | kernel.kimg, 618 | ' '.join(quote_karg(a).replace(',', ',,') for a in kernelargs), 619 | (',%s' % initrdpath) if initrdpath is not None else '')]) 620 | 621 | # Handle --qemu-opt(s) 622 | qemuargs.extend(args.qemu_opt) 623 | if args.qemu_opts is not None: 624 | qemuargs.extend(args.qemu_opts) 625 | 626 | if args.show_command: 627 | print(' '.join(shlex.quote(a) for a in qemuargs)) 628 | 629 | # Go! 630 | if not args.dry_run: 631 | os.execv(qemu.qemubin, qemuargs) 632 | 633 | return 0 634 | 635 | def main() -> int: 636 | try: 637 | return do_it() 638 | except SilentError: 639 | return 1 640 | 641 | if __name__ == '__main__': 642 | try: 643 | exit(main()) 644 | except SilentError: 645 | exit(1) 646 | -------------------------------------------------------------------------------- /virtme/cpiowriter.py: -------------------------------------------------------------------------------- 1 | # -*- mode: python -*- 2 | # cpiowriter: A barebones initramfs writer 3 | # Copyright © 2014 Andy Lutomirski 4 | # Licensed under the GPLv2, which is available in the virtme distribution 5 | # as a file called LICENSE with SHA-256 hash: 6 | # 8177f97513213526df2cf6184d8ff986c675afb514d4e68a404010521b880643 7 | 8 | import sys 9 | 10 | class CpioWriter(object): 11 | TYPE_DIR = 0o0040000 12 | TYPE_REG = 0o0100000 13 | TYPE_SYMLINK = 0o0120000 14 | TYPE_CHRDEV = 0o0020000 15 | TYPE_MASK = 0o0170000 16 | 17 | def __init__(self, f): 18 | self.__f = f 19 | self.__totalsize = 0 20 | self.__next_ino = 0 21 | 22 | def __write(self, data): 23 | self.__f.write(data) 24 | self.__totalsize += len(data) 25 | 26 | def write_object(self, name, body, mode, ino=None, nlink=None, 27 | uid=0, gid=0, mtime=0, devmajor=0, devminor=0, 28 | rdevmajor=0, rdevminor=0): 29 | if nlink is None: 30 | nlink = (2 if (mode & CpioWriter.TYPE_MASK) == CpioWriter.TYPE_DIR 31 | else 1) 32 | 33 | if b'\0' in name: 34 | raise ValueError('Filename cannot contain a NUL') 35 | 36 | namesize = len(name) + 1 37 | 38 | if isinstance(body, bytes): 39 | filesize = len(body) 40 | else: 41 | filesize = body.seek(0, 2) 42 | body.seek(0) 43 | 44 | if ino is None: 45 | ino = self.__next_ino 46 | self.__next_ino += 1 47 | 48 | fields = [ino, mode, uid, gid, nlink, mtime, filesize, 49 | devmajor, devminor, rdevmajor, rdevminor, namesize, 0] 50 | hdr = ('070701' + ''.join('%08X' % f for f in fields)).encode('ascii') 51 | 52 | self.__write(hdr) 53 | self.__write(name) 54 | self.__write(b'\0') 55 | self.__write(((2-namesize) % 4) * b'\0') 56 | 57 | if isinstance(body, bytes): 58 | self.__write(body) 59 | else: 60 | while True: 61 | buf = body.read(65536) 62 | if buf == b'': 63 | break 64 | self.__write(buf) 65 | 66 | self.__write(((-filesize) % 4) * b'\0') 67 | 68 | def write_trailer(self): 69 | self.write_object(name=b'TRAILER!!!', body=b'', mode=0, ino=0, nlink=1) 70 | self.__write(((-self.__totalsize) % 512) * b'\0') 71 | 72 | def mkdir(self, name, mode): 73 | self.write_object(name=name, mode=CpioWriter.TYPE_DIR | mode, body=b'') 74 | 75 | def symlink(self, src, dst): 76 | self.write_object(name=dst, mode=CpioWriter.TYPE_SYMLINK | 0o777, 77 | body=src) 78 | 79 | def write_file(self, name, body, mode): 80 | self.write_object(name=name, body=body, mode=CpioWriter.TYPE_REG | mode) 81 | 82 | def mkchardev(self, name, dev, mode): 83 | major,minor = dev 84 | self.write_object(name=name, mode=CpioWriter.TYPE_CHRDEV | mode, 85 | rdevmajor=major, rdevminor=minor, 86 | body=b'') 87 | -------------------------------------------------------------------------------- /virtme/guest/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amluto/virtme/3dfc002efdb2d8c06ff1306be276ec32f9bd00bb/virtme/guest/__init__.py -------------------------------------------------------------------------------- /virtme/guest/virtme-init: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # virtme-init: virtme's basic init (PID 1) process 3 | # Copyright © 2014 Andy Lutomirski 4 | # Licensed under the GPLv2, which is available in the virtme distribution 5 | # as a file called LICENSE with SHA-256 hash: 6 | # 8177f97513213526df2cf6184d8ff986c675afb514d4e68a404010521b880643 7 | 8 | export PATH=/bin:/sbin:/usr/bin:/usr/sbin 9 | 10 | log() { 11 | if [[ -e /dev/kmsg ]]; then 12 | echo "<6>virtme-init: $*" >/dev/kmsg 13 | else 14 | echo "virtme-init: $*" 15 | fi 16 | } 17 | 18 | mount -t sysfs -o nosuid,noexec,nodev sys /sys/ 19 | 20 | declare -A mount_tags 21 | for i in /sys/bus/virtio/drivers/9pnet_virtio/virtio*/mount_tag; do 22 | # mount_tag is terminated with a NUL byte, which leads to a 23 | # "command substitution: ignored null byte in input" warning from 24 | # bash; use sed instead of a bare 'cat' here to strip it off. 25 | mount_tags["`sed '$s/\x00$//;' "$i"`"]=1 26 | done 27 | 28 | kver="`uname -r`" 29 | 30 | if [[ -n "$virtme_root_mods" ]]; then 31 | # /lib/modules is already set up 32 | true 33 | elif [[ -n "$virtme_link_mods" ]]; then 34 | mount -n -t tmpfs none /lib/modules 35 | ln -s "$virtme_link_mods" "/lib/modules/$kver" 36 | elif [[ -d "/lib/modules/$kver" ]]; then 37 | # We may have mismatched modules. Mask them off. 38 | mount -n -t tmpfs -o ro,mode=0000 disallow_modules "/lib/modules/$kver" 39 | fi 40 | 41 | mount -t tmpfs tmpfs /tmp/ 42 | [[ -w /var/log ]] || mount -t tmpfs tmpfs /var/log/ 43 | 44 | # Fix up /etc a little bit 45 | touch /tmp/fstab 46 | mount --bind /tmp/fstab /etc/fstab 47 | rm /tmp/fstab 48 | 49 | # Populate dummy entries in /etc/shadow to allow switching to any user defined 50 | # in the system 51 | (umask 0644 && touch /tmp/shadow) 52 | sed -e 's/^\([^:]\+\).*/\1:!:::::::/' < /etc/passwd > /tmp/shadow 53 | mount --bind /tmp/shadow /etc/shadow 54 | rm /tmp/shadow 55 | 56 | # Find udevd 57 | if [[ -x /usr/lib/systemd/systemd-udevd ]]; then 58 | udevd=/usr/lib/systemd/systemd-udevd 59 | elif [[ -x /lib/systemd/systemd-udevd ]]; then 60 | udevd=/lib/systemd/systemd-udevd 61 | else 62 | udevd=`which udevd` 63 | fi 64 | 65 | # Mount proc (needed for stat, sadly) 66 | mount -t proc -o nosuid,noexec,nodev proc /proc/ 67 | 68 | # devtmpfs might be automounted; if not, mount it. 69 | if ! findmnt --kernel --mountpoint /dev &>/dev/null; then 70 | # Ideally we'll use devtmpfs (but don't rely on /dev/null existing). 71 | if [[ -c /dev/null ]]; then 72 | mount -n -t devtmpfs -o mode=0755,nosuid,noexec devtmpfs /dev \ 73 | &>/dev/null 74 | else 75 | mount -n -t devtmpfs -o mode=0755,nosuid,noexec devtmpfs /dev 76 | fi 77 | 78 | if (( $? != 0 )); then 79 | # The running kernel doesn't have devtmpfs. Use regular tmpfs. 80 | mount -t tmpfs -o mode=0755,nosuid,noexec none /dev 81 | 82 | # Make some basic devices first, and let udev handle the rest 83 | mknod -m 0666 /dev/null c 1 3 84 | mknod -m 0660 /dev/kmsg c 1 11 85 | mknod -m 0600 /dev/console c 5 1 86 | fi 87 | fi 88 | 89 | for tag in "${!virtme_initmount@}"; do 90 | if [[ ! -d "${!tag}" ]]; then 91 | mkdir -p "${!tag}" 92 | fi 93 | mount -t 9p -o version=9p2000.L,trans=virtio,access=any "virtme.initmount${tag:16}" "${!tag}" || exit 1 94 | done 95 | 96 | if [[ -n "virtme_chdir" ]]; then 97 | cd -- "${virtme_chdir}" 98 | fi 99 | 100 | log "basic initialization done" 101 | 102 | ######## The remainder of this script is a very simple init (PID 1) ######## 103 | 104 | # Does the system use systemd-tmpfiles? 105 | tmpfiles=`which systemd-tmpfiles 2>/dev/null` && { 106 | log "running systemd-tmpfiles" 107 | systemd-tmpfiles --create --boot --exclude-prefix="/dev" 108 | } 109 | 110 | # Make dbus work (if tmpfiles wasn't there or didn't create the directory). 111 | install -d /run/dbus 112 | 113 | # Try to get udevd to coldplug everything. 114 | if [[ -n "$udevd" ]]; then 115 | if [[ -e '/sys/kernel/uevent_helper' ]]; then 116 | # This kills boot performance. 117 | log "you have CONFIG_UEVENT_HELPER on; turn it off" 118 | echo '' >/sys/kernel/uevent_helper 119 | fi 120 | log "starting udevd" 121 | "$udevd" --daemon --resolve-names=never 122 | log "triggering udev coldplug" 123 | udevadm trigger --type=subsystems --action=add >/dev/null 2>&1 124 | udevadm trigger --type=devices --action=add >/dev/null 2>&1 125 | log "waiting for udev to settle" 126 | udevadm settle 127 | log "udev is done" 128 | else 129 | log "udevd not found" 130 | fi 131 | 132 | # Set up useful things in /sys, assuming our kernel supports it. 133 | mount -t configfs configfs /sys/kernel/config &>/dev/null 134 | mount -t debugfs debugfs /sys/kernel/debug &>/dev/null 135 | mount -t tracefs tracefs /sys/kernel/tracing &>/dev/null 136 | 137 | # Set up cgroup mount points (mount cgroupv2 hierarchy by default) 138 | if mount -t tmpfs tmpfs /sys/fs/cgroup &>/dev/null; then 139 | mkdir /sys/fs/cgroup/unified 140 | mount -t cgroup2 cgroup2 /sys/fs/cgroup/unified 141 | fi 142 | 143 | # Set up filesystems that live in /dev 144 | mkdir -p -m 0755 /dev/shm /dev/pts 145 | mount -t devpts -o gid=tty,mode=620,noexec,nosuid devpts /dev/pts 146 | mount -t tmpfs -o mode=1777,nosuid,nodev tmpfs /dev/shm 147 | 148 | # Install /proc/self/fd symlinks into /dev if not already present 149 | declare -r -A fdlinks=(["/dev/fd"]="/proc/self/fd" 150 | ["/dev/stdin"]="/proc/self/fd/0" 151 | ["/dev/stdout"]="/proc/self/fd/1" 152 | ["/dev/stderr"]="/proc/self/fd/2") 153 | 154 | for p in "${!fdlinks[@]}"; do 155 | [[ -e "$p" ]] || ln -s "${fdlinks[$p]}" "$p" 156 | done 157 | 158 | if [[ -n "$virtme_hostname" ]]; then 159 | log "Setting hostname to $virtme_hostname..." 160 | hostname "$virtme_hostname" 161 | fi 162 | 163 | # Bring up networking 164 | ip link set dev lo up 165 | 166 | if cat /proc/cmdline |grep -q -E '(^| )virtme.dhcp($| )'; then 167 | real_resolv_conf=/etc/resolv.conf 168 | if [[ -L "$real_resolv_conf" ]]; then 169 | real_resolv_conf="`readlink /etc/resolv.conf`" 170 | if [[ ! -e $real_resolv_conf ]]; then 171 | mkdir -p "`dirname $real_resolv_conf`" 172 | touch $real_resolv_conf 173 | fi 174 | fi 175 | if [[ -f "$real_resolv_conf" ]]; then 176 | tmpfile="`mktemp --tmpdir=/tmp`" 177 | chmod 644 "$tmpfile" 178 | mount --bind "$tmpfile" "$real_resolv_conf" 179 | rm "$tmpfile" 180 | fi 181 | 182 | # udev is liable to rename the interface out from under us. 183 | virtme_net=`ls "$(ls -d /sys/bus/virtio/drivers/virtio_net/virtio* |sort -g |head -n1)"/net` 184 | busybox udhcpc -i "$virtme_net" -n -q -f -s "$(dirname $0)/virtme-udhcpc-script" 185 | fi 186 | 187 | if [[ -x /run/virtme/data/script ]]; then 188 | if [[ ! -e "/dev/virtio-ports/virtme.scriptio" ]]; then 189 | echo "virtme-init: cannot find script I/O port; make sure virtio-serial is available" 190 | poweroff -f 191 | exit 1 192 | fi 193 | 194 | log 'starting script' 195 | setsid /run/virtme/data/script <>/dev/virtio-ports/virtme.scriptio 1>&0 2>&0 196 | log "script returned $?" 197 | 198 | # Hmm. We should expose the return value somehow. 199 | sync 200 | poweroff -f 201 | exit 1 202 | fi 203 | 204 | # Figure out what the main console is 205 | consdev="`grep ' ... (.C' /proc/consoles |cut -d' ' -f1`" 206 | if [[ -z "$consdev" ]]; then 207 | log "can't deduce console device" 208 | exec bash --login # At least try to be helpful 209 | fi 210 | 211 | deallocvt 212 | 213 | if [[ "$consdev" == "tty0" ]]; then 214 | # Create some VTs 215 | openvt -c 2 -- /bin/bash 216 | openvt -c 3 -- /bin/bash 217 | openvt -c 4 -- /bin/bash 218 | 219 | consdev=tty1 # sigh 220 | fi 221 | 222 | if [[ ! -e "/dev/$consdev" ]]; then 223 | log "/dev/$consdev doesn't exist." 224 | exec bash --login 225 | fi 226 | 227 | # Parameters that start with virtme_ shouldn't pollute the environment 228 | for p in "${!virtme_@}"; do export -n "$p"; done 229 | 230 | echo "virtme-init: console is $consdev" 231 | 232 | # Set up a basic environment 233 | install -d -m 0755 /tmp/roothome 234 | export HOME=/tmp/roothome 235 | 236 | # Bring up a functioning shell on the console. This is a bit magical: 237 | # We have no controlling terminal because we're attached to a fake 238 | # console device (probably something like /dev/console), which can't 239 | # be a controlling terminal. We are also not a member of a session. 240 | # Init apparently can't setsid (whether that's a limitation of the 241 | # setsid binary or the system call, I don't know). 242 | while true; do 243 | # Program the console sensibly 244 | if [[ -n "${virtme_stty_con}" ]]; then 245 | stty ${virtme_stty_con} <"/dev/$consdev" 246 | fi 247 | 248 | setsid bash 0<>"/dev/$consdev" 1>&0 2>&0 249 | echo "Shell died. Will respawn." 250 | sleep 0.5 251 | done 252 | -------------------------------------------------------------------------------- /virtme/guest/virtme-udhcpc-script: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # virtme-udhcpc-script: A trivial udhcpc script 3 | # Copyright © 2014 Andy Lutomirski 4 | # Licensed under the GPLv2, which is available in the virtme distribution 5 | # as a file called LICENSE with SHA-256 hash: 6 | # 8177f97513213526df2cf6184d8ff986c675afb514d4e68a404010521b880643 7 | 8 | if [[ "$1" == "deconfig" ]]; then 9 | ip link set dev "$interface" up 10 | ip addr flush dev "$interface" 11 | elif [[ "$1" == "bound" ]]; then 12 | ip addr add "$ip/$mask" dev "$interface" 13 | ip route add default via "$router" dev "$interface" 14 | if [[ -n "$dns" ]]; then 15 | # A lot of systems will have /etc/resolv.conf symlinked to 16 | # /run/NetworkManager/something_or_other. Debian symlinks to /run/resolvconf. 17 | # Create both directories. 18 | install -d /run/NetworkManager 19 | install -d /run/resolvconf 20 | 21 | echo -e "# Generated by virtme-udhcpc-script\n\nnameserver $dns" \ 22 | >/etc/resolv.conf 23 | fi 24 | fi 25 | -------------------------------------------------------------------------------- /virtme/mkinitramfs.py: -------------------------------------------------------------------------------- 1 | # -*- mode: python -*- 2 | # virtme-mkinitramfs: Generate an initramfs image for virtme 3 | # Copyright © 2014 Andy Lutomirski 4 | # Licensed under the GPLv2, which is available in the virtme distribution 5 | # as a file called LICENSE with SHA-256 hash: 6 | # 8177f97513213526df2cf6184d8ff986c675afb514d4e68a404010521b880643 7 | 8 | from typing import List, Dict, Optional 9 | 10 | import shutil 11 | import io 12 | import os.path 13 | import shlex 14 | import itertools 15 | from . import cpiowriter 16 | from . import util 17 | 18 | def make_base_layout(cw): 19 | for dir in (b'lib', b'bin', b'var', b'etc', b'newroot', b'dev', b'proc', 20 | b'tmproot', b'run_virtme', b'run_virtme/data', b'run_virtme/guesttools'): 21 | cw.mkdir(dir, 0o755) 22 | 23 | cw.symlink(b'bin', b'sbin') 24 | cw.symlink(b'lib', b'lib64') 25 | 26 | def make_dev_nodes(cw): 27 | cw.mkchardev(b'dev/null', (1, 3), mode=0o666) 28 | cw.mkchardev(b'dev/kmsg', (1, 11), mode=0o666) 29 | cw.mkchardev(b'dev/console', (5, 1), mode=0o660) 30 | 31 | def install_busybox(cw, config): 32 | with open(config.busybox, 'rb') as busybox: 33 | cw.write_file(name=b'bin/busybox', body=busybox, mode=0o755) 34 | 35 | for tool in ('sh', 'mount', 'umount', 'switch_root', 'sleep', 'mkdir', 36 | 'mknod', 'insmod', 'cp', 'cat'): 37 | cw.symlink(b'busybox', ('bin/%s' % tool).encode('ascii')) 38 | 39 | cw.mkdir(b'bin/real_progs', mode=0o755) 40 | 41 | def install_modprobe(cw): 42 | cw.write_file(name=b'bin/modprobe', body=b'\n'.join([ 43 | b'#!/bin/sh', 44 | b'echo "virtme: initramfs does not have module $3" >/dev/console', 45 | b'exit 1', 46 | ]), mode=0o755) 47 | 48 | _LOGFUNC = """log() { 49 | if [[ -e /dev/kmsg ]]; then 50 | echo "<6>virtme initramfs: $*" >/dev/kmsg 51 | else 52 | echo "virtme initramfs: $*" 53 | fi 54 | } 55 | """ 56 | 57 | def install_modules(cw, modfiles): 58 | cw.mkdir(b'modules', 0o755) 59 | paths = [] 60 | for mod in modfiles: 61 | with open(mod, 'rb') as f: 62 | modpath = 'modules/' + os.path.basename(mod) 63 | paths.append(modpath) 64 | cw.write_file(name=modpath.encode('ascii'), 65 | body=f, mode=0o644) 66 | 67 | script = _LOGFUNC + '\n'.join('log \'loading %s...\'; insmod %s' % 68 | (os.path.basename(p), shlex.quote(p)) for p in paths) 69 | cw.write_file(name=b'modules/load_all.sh', 70 | body=script.encode('ascii'), mode=0o644) 71 | 72 | _INIT = """#!/bin/sh 73 | 74 | {logfunc} 75 | 76 | source /modules/load_all.sh 77 | 78 | log 'mounting hostfs...' 79 | 80 | if ! /bin/mount -n -t 9p -o {access},version=9p2000.L,trans=virtio,access=any /dev/root /newroot/; then 81 | echo "Failed to mount real root. We are stuck." 82 | sleep 5 83 | exit 1 84 | fi 85 | 86 | # Can we actually use /newroot/ as root? 87 | if ! mount -t proc -o nosuid,noexec,nodev proc /newroot/proc 2>/dev/null; then 88 | # QEMU 1.5 and below have a bug in virtfs that prevents mounting 89 | # anything on top of a virtfs mount. 90 | log "your host's virtfs is broken -- using a fallback tmpfs" 91 | need_fallback_tmpfs=1 92 | else 93 | umount /newroot/proc # Don't leave garbage behind 94 | fi 95 | 96 | if ! [[ -d /newroot/run ]]; then 97 | log "your guest's root does not have /run -- using a fallback tmpfs" 98 | need_fallback_tmpfs=1 99 | fi 100 | 101 | if [[ "$need_fallback_tmpfs" != "" ]]; then 102 | mount --move /newroot /tmproot 103 | mount -t tmpfs root_workaround /newroot/ 104 | cd tmproot 105 | mkdir /newroot/proc /newroot/sys /newroot/dev /newroot/run /newroot/tmp 106 | for i in *; do 107 | if [[ -d "$i" && \! -d "/newroot/$i" ]]; then 108 | mkdir /newroot/"$i" 109 | mount --bind "$i" /newroot/"$i" 110 | fi 111 | done 112 | mknod /newroot/dev/null c 1 3 113 | mount -o remount,ro -t tmpfs root_workaround /newroot 114 | umount -l /tmproot 115 | fi 116 | 117 | mount -t tmpfs run /newroot/run 118 | cp -a /run_virtme /newroot/run/virtme 119 | 120 | # Find init 121 | mount -t proc none /proc 122 | for arg in `cat /proc/cmdline`; do 123 | if [[ "${{arg%%=*}}" = "init" ]]; then 124 | init="${{arg#init=}}" 125 | break 126 | fi 127 | done 128 | umount /proc 129 | 130 | if [[ -z "$init" ]]; then 131 | log 'no init= option' 132 | exit 1 133 | fi 134 | 135 | log 'done; switching to real root' 136 | exec /bin/switch_root /newroot "$init" "$@" 137 | """ 138 | 139 | 140 | def generate_init(config) -> bytes: 141 | out = io.StringIO() 142 | out.write(_INIT.format( 143 | logfunc=_LOGFUNC, 144 | access=config.access)) 145 | return out.getvalue().encode('utf-8') 146 | 147 | class Config: 148 | __slots__ = ['modfiles', 'virtme_data', 'virtme_init_path', 'busybox', 'access'] 149 | def __init__(self): 150 | self.modfiles: List[str] = [] 151 | self.virtme_data: Dict[bytes, bytes] = {} 152 | self.virtme_init_path: Optional[str] = None 153 | self.busybox: Optional[str] = None 154 | self.access = 'ro' 155 | 156 | def mkinitramfs(out, config) -> None: 157 | cw = cpiowriter.CpioWriter(out) 158 | make_base_layout(cw) 159 | make_dev_nodes(cw) 160 | install_busybox(cw, config) 161 | install_modprobe(cw) 162 | if config.modfiles is not None: 163 | install_modules(cw, config.modfiles) 164 | for name,contents in config.virtme_data.items(): 165 | cw.write_file(b'run_virtme/data/' + name, body=contents, mode=0o755) 166 | cw.write_file(b'init', body=generate_init(config), 167 | mode=0o755) 168 | cw.write_trailer() 169 | 170 | def find_busybox(root, is_native) -> Optional[str]: 171 | return util.find_binary(['busybox-static', 'busybox.static', 'busybox'], 172 | root=root, use_path=is_native) 173 | -------------------------------------------------------------------------------- /virtme/modfinder.py: -------------------------------------------------------------------------------- 1 | # -*- mode: python -*- 2 | # modfinder: A simple tool to resolve required modules 3 | # Copyright © 2014 Andy Lutomirski 4 | # Licensed under the GPLv2, which is available in the virtme distribution 5 | # as a file called LICENSE with SHA-256 hash: 6 | # 8177f97513213526df2cf6184d8ff986c675afb514d4e68a404010521b880643 7 | 8 | """ 9 | This is a poor man's module resolver and loader. It does not support any 10 | sort of hotplug. Instead it generates a topological order and loads 11 | everything. The idea is to require very few modules. 12 | """ 13 | 14 | from typing import List 15 | 16 | import re 17 | import subprocess 18 | import os 19 | import itertools 20 | from . import util 21 | 22 | _INSMOD_RE = re.compile('insmod (.*[^ ]) *$') 23 | 24 | def resolve_dep(modalias, root=None, kver=None, moddir=None): 25 | # /usr/sbin might not be in the path, and modprobe is usually in /usr/sbin 26 | modprobe = util.find_binary_or_raise(['modprobe']) 27 | args = [modprobe, '--show-depends'] 28 | args += ['-C', '/var/empty'] 29 | if root is not None: 30 | args += ['-d', root] 31 | if kver is not None and kver != os.uname().release: 32 | # If booting the loaded kernel, skip -S. This helps certain 33 | # buggy modprobe versions that don't support -S. 34 | args += ['-S', kver] 35 | if moddir is not None: 36 | args += ['--moddir', moddir] 37 | args += ['--', modalias] 38 | 39 | deps = [] 40 | 41 | try: 42 | with open('/dev/null', 'r+b') as devnull: 43 | script = subprocess.check_output(args, stderr=devnull.fileno()).\ 44 | decode('utf-8', errors='replace') 45 | for line in script.split('\n'): 46 | m = _INSMOD_RE.match(line) 47 | if m: 48 | deps.append(m.group(1)) 49 | except subprocess.CalledProcessError: 50 | pass # This is most likely because the module is built in. 51 | 52 | return deps 53 | 54 | def merge_mods(lists) -> List[str]: 55 | found: set = set() 56 | mods = [] 57 | for mod in itertools.chain(*lists): 58 | if mod not in found: 59 | found.add(mod) 60 | mods.append(mod) 61 | return mods 62 | 63 | def find_modules_from_install(aliases, root=None, kver=None, moddir=None): 64 | return merge_mods(resolve_dep(a, root=root, kver=kver, moddir=moddir) 65 | for a in aliases) 66 | -------------------------------------------------------------------------------- /virtme/qemu_helpers.py: -------------------------------------------------------------------------------- 1 | # -*- mode: python -*- 2 | # qemu_helpers: Helpers to find QEMU and handle its quirks 3 | # Copyright © 2014 Andy Lutomirski 4 | # Licensed under the GPLv2, which is available in the virtme distribution 5 | # as a file called LICENSE with SHA-256 hash: 6 | # 8177f97513213526df2cf6184d8ff986c675afb514d4e68a404010521b880643 7 | 8 | import os 9 | import re 10 | import shutil 11 | import subprocess 12 | from typing import Optional 13 | 14 | class Qemu(object): 15 | qemubin: str 16 | version: Optional[str] 17 | 18 | def __init__(self, arch) -> None: 19 | self.arch = arch 20 | 21 | qemubin = shutil.which('qemu-system-%s' % arch) 22 | if qemubin is None and arch == os.uname().machine: 23 | qemubin = shutil.which('qemu-kvm') 24 | if qemubin is None: 25 | raise ValueError('cannot find qemu for %s' % arch) 26 | 27 | self.qemubin = qemubin 28 | self.version = None 29 | 30 | def probe(self) -> None: 31 | if self.version is None: 32 | self.version = subprocess.check_output([self.qemubin, '--version'])\ 33 | .decode('utf-8') 34 | self.cannot_overmount_virtfs = ( 35 | re.search(r'version 1\.[012345]', self.version) is not None) 36 | 37 | # QEMU 4.2+ supports -fsdev multidevs=remap 38 | self.has_multidevs = ( 39 | re.search(r'version (?:1\.|2\.|3\.|4\.[01][^\d])', self.version) is None) 40 | 41 | def quote_optarg(self, a: str) -> str: 42 | """Quote an argument to an option.""" 43 | return a.replace(',', ',,') 44 | 45 | -------------------------------------------------------------------------------- /virtme/resources.py: -------------------------------------------------------------------------------- 1 | # -*- mode: python -*- 2 | # resources.py: Find virtme's resources 3 | # Copyright © 2014-2019 Andy Lutomirski 4 | # Licensed under the GPLv2, which is available in the virtme distribution 5 | # as a file called LICENSE with SHA-256 hash: 6 | # 8177f97513213526df2cf6184d8ff986c675afb514d4e68a404010521b880643 7 | 8 | """Helpers to find virtme's guest tools and host scripts.""" 9 | 10 | import os 11 | import shutil 12 | import pkg_resources 13 | import subprocess 14 | 15 | def find_guest_tools(): 16 | """Return the path of the guest tools installed with the running virtme. 17 | """ 18 | 19 | if pkg_resources.resource_isdir(__name__, 'guest'): 20 | return pkg_resources.resource_filename(__name__, 'guest') 21 | 22 | # No luck. This is somewhat surprising. 23 | return None 24 | 25 | def find_script(name) -> str: 26 | # If we're running out of a source checkout, we can find scripts through 27 | # the 'virtme/scripts' symlink. 28 | fn = pkg_resources.resource_filename(__name__, 'scripts/%s' % name) 29 | if os.path.isfile(fn): 30 | return fn 31 | 32 | # Otherwise assume we're actually installed and in PATH. 33 | guess = shutil.which(name) 34 | if guess is not None: 35 | return guess 36 | 37 | # No luck. This is somewhat surprising. 38 | raise Exception('could not find script %s' % name) 39 | 40 | def run_script(name, **kwargs) -> None: 41 | fn = find_script(name) 42 | subprocess.check_call(executable=fn, args=[fn], **kwargs) 43 | -------------------------------------------------------------------------------- /virtme/scripts: -------------------------------------------------------------------------------- 1 | ../bin -------------------------------------------------------------------------------- /virtme/util.py: -------------------------------------------------------------------------------- 1 | # -*- mode: python -*- 2 | # util.py: Misc helpers 3 | # Copyright © 2014-2019 Andy Lutomirski 4 | # Licensed under the GPLv2, which is available in the virtme distribution 5 | # as a file called LICENSE with SHA-256 hash: 6 | # 8177f97513213526df2cf6184d8ff986c675afb514d4e68a404010521b880643 7 | 8 | from typing import Optional, Sequence 9 | 10 | import os 11 | import shutil 12 | import itertools 13 | 14 | def find_binary(names: Sequence[str], root: str = '/', 15 | use_path: bool = True) -> Optional[str]: 16 | dirs = [os.path.join(*i) for i in itertools.product( 17 | ['usr/local', 'usr', ''], 18 | ['bin', 'sbin'])] 19 | 20 | for n in names: 21 | if use_path: 22 | # Search PATH first 23 | path = shutil.which(n) 24 | if path is not None: 25 | return path 26 | 27 | for d in dirs: 28 | path = os.path.join(root, d, n) 29 | if os.path.isfile(path): 30 | return path 31 | 32 | # We give up. 33 | return None 34 | 35 | def find_binary_or_raise(names: Sequence[str], root: str = '/', 36 | use_path: bool = True) -> str: 37 | ret = find_binary(names, root=root, use_path=use_path) 38 | if ret is None: 39 | raise RuntimeError('Could not find %r' % names) 40 | return ret 41 | -------------------------------------------------------------------------------- /virtme/virtmods.py: -------------------------------------------------------------------------------- 1 | # -*- mode: python -*- 2 | # virtmods: Default module configuration 3 | # Copyright © 2014 Andy Lutomirski 4 | # Licensed under the GPLv2, which is available in the virtme distribution 5 | # as a file called LICENSE with SHA-256 hash: 6 | # 8177f97513213526df2cf6184d8ff986c675afb514d4e68a404010521b880643 7 | 8 | MODALIASES = [ 9 | # These are most likely portable across all architectures. 10 | 'fs-9p', 11 | 'virtio:d00000009v00001AF4', # 9pnet_virtio 12 | 'virtio:d00000003v00001AF4', # virtio_console 13 | 14 | # For virtio_pci architectures (which are, hopefully, all that we care 15 | # about), there's really only one required driver, virtio_pci. 16 | # For completeness, here are both of the instances we care about 17 | # for basic functionality. 18 | 'pci:v00001AF4d00001009sv00001AF4sd00000009bc00sc02i00', # 9pnet 19 | 'pci:v00001AF4d00001003sv00001AF4sd00000003bc07sc80i00', # virtconsole 20 | 21 | # Basic system functionality 22 | 'unix', # UNIX sockets, needed by udev 23 | 24 | # Basic emulated hardware 25 | 'i8042', 26 | 'atkbd', 27 | ] 28 | --------------------------------------------------------------------------------