pax_global_header00006660000000000000000000000064124337634070014523gustar00rootroot0000000000000052 comment=6f11b1102fbb5b336e536dfb5bd99f70b48bfe07 virtme-0.0.2/000077500000000000000000000000001243376340700130305ustar00rootroot00000000000000virtme-0.0.2/.gitignore000066400000000000000000000000311243376340700150120ustar00rootroot00000000000000*~ __pycache__ build distvirtme-0.0.2/DCO-1.1.txt000066400000000000000000000025431243376340700144770ustar00rootroot00000000000000The text 'Signed-off-by:' in a commit message indicates that the signer agrees to the Developer's Certificate of Origin 1.1, reproduced below. I (Andrew Lutomirski) believe that the DCO is Copyright Linus Torvalds and released under the GPL v2. Developer's Certificate of Origin 1.1 By making a contribution to this project, I certify that: (a) The contribution was created in whole or in part by me and I have the right to submit it under the open source license indicated in the file; or (b) The contribution is based upon previous work that, to the best of my knowledge, is covered under an appropriate open source license and I have the right under that license to submit that work with modifications, whether created in whole or in part by me, under the same open source license (unless I am permitted to submit under a different license), as indicated in the file; or (c) The contribution was provided directly to me by some other person who certified (a), (b) or (c) and I have not modified it. (d) I understand and agree that this project and the contribution are public and that a record of the contribution (including all personal information I submit with it, including my sign-off) is maintained indefinitely and may be redistributed consistent with this project or the open source license(s) involved. virtme-0.0.2/LICENSE000066400000000000000000000432541243376340700140450ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. virtme-0.0.2/MANIFEST.in000066400000000000000000000000711243376340700145640ustar00rootroot00000000000000include README.md include LICENSE include virtme/guest/* virtme-0.0.2/README.md000066400000000000000000000111311243376340700143040ustar00rootroot00000000000000What is virtme? =============== Virtme is a set of simple tools to run a virtualized Linux kernel that uses the host Linux distribution or a simple rootfs instead of a whole disk image. Virtme is tiny, easy to use, and makes testing kernel changes quite simple. Some day this might be useful as a sort of sandbox. Right now it's not really configurable enough for that. Virtme is hosted at kernel.org in utils/kernel/virtme/virtme.git ([web][korg-web] | [git][korg-git]). It's mirrored [on github][github]. [korg-web]: https://git.kernel.org/cgit/utils/kernel/virtme/virtme.git "virtme on kernel.org" [korg-git]: git://git.kernel.org/pub/scm/utils/kernel/virtme/virtme.git "git address" [github]: https://github.com/amluto/virtme How to use virtme ================= You'll need a Linux kernel that has these options (built-in or as modules) CONFIG_VIRTIO CONFIG_VIRTIO_PCI CONFIG_NET_9P CONFIG_NET_9P_VIRTIO CONFIG_9P_FS For networking support, you also need CONFIG_VIRTIO_NET. For script support, you need CONFIG_VIRTIO_CONSOLE. For disk support, you need CONFIG_SCSI_VIRTIO. That kernel needs to be sane. Your kernel is probably sane, but allmodconfig and allyesconfig generate insane kernels. Sanity includes: CONFIG_CMDLINE_OVERRIDE=n CONFIG_BINFMT_SCRIPT=y CONFIG_TMPFS=y You may also have better luck if you set: CONFIG_EMBEDDED=n CONFIG_EXPERT=n CONFIG_MODULE_SIG_FORCE=n CONFIG_DEVTMPFS=y An easy, somewhat-reliable way to generate a working config is to append the `prereqs.config` file to your .config and then run `make defconfig`. Your host system will need to satisfy some prerequisites: * You need Python 3.3 or higher. * QEMU 1.6 or higher is recommended. QEMU 1.4 and 1.5 are partially supported using a rather ugly kludge. * 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. * Depending on the options you use, you may need a statically linked `busybox` binary somewhere in your path. Once you have such a kernel, run one of: * virtme-run --kimg PATH_TO_BZIMAGE * virtme-run --installed-kernel * virtme-run --installed-kernel VERSION On x86, you can usually find a bzImage in `arch/x86/boot/bzImage` once you've compiled your kernel. Note that the --kimg mode does not support modules. You can then do things like `cd /home/username` and you will have readonly access to all your files. Virtme gives you console input and output by default. Type ctrl-a x to exit. Type ctrl-a c to access the QEMU monitor. 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. Graphics ======== If you want graphical output instead of console output, pass --graphics. Note that this is the opposite of QEMU's default behavior. Architecture support ==================== 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. x86 --- x86 (both x86_64 and i386) is fully supported, although some odd KVM configurations may cause problems. ARM --- ARM is supported using qemu's `versatilepb` machine. This is an unfortunate choice: that's a rather outdated machine, and virtme should be using a different system (`vexpress-a15` or `virt`) that is more modern and does not depend on PCI. 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. Aarch64 ------- Aarch64 works out of the box if you have a new enough version of QEMU. PPC64 ----- PPC64 appears to be reasonably functional. Others ------ 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. Upcoming features ================= In the near term, the high-priority features are: * Support for modular virtfs and 9p for non-installed kernels. * Some way to configure writable mounts. * A clean way to run a script in the guest for testing. virtme-0.0.2/make-release-tarball.sh000077500000000000000000000002641243376340700173430ustar00rootroot00000000000000#!/bin/bash if (( $# != 1 )); then echo "Usage: make-release-tarball VERSION" exit 1 fi ver="$1" exec git archive --prefix=virtme-$ver/ --format=tar -o /dev/stdout HEAD virtme-0.0.2/samples/000077500000000000000000000000001243376340700144745ustar00rootroot00000000000000virtme-0.0.2/samples/README.md000066400000000000000000000004221243376340700157510ustar00rootroot00000000000000Samples ======= These are a collection of sample scripts. I will answer questions about them, but I will not really support them, and I reserve the right to break them at any time. Don't rely on them in production. These scripts mostly expect to find virtme-run in PATH.virtme-0.0.2/samples/xfstests000077500000000000000000000007451243376340700163130ustar00rootroot00000000000000#!/bin/bash if (( $# != 3 )); then echo 'Usage: xfstests TEST_DEV SCRATCH_DEV PATH_TO_XFSTESTS' echo 'This will reformat TEST_DEV and SCRATCH_DEV' exit 1 fi here="`dirname $0`" samples_path="`realpath "$here"`" xfstests_path="`realpath "$3"`" # script-sh is awkward for this purpose. The escaping here is wrong. virtme-run --installed-kernel --disk "test=$1" --disk "scratch=$2" --script-sh "$samples_path/xfstests_trampoline $xfstests_path" --qemu-opts -m 2048 -smp 2 virtme-0.0.2/samples/xfstests_trampoline000077500000000000000000000013031243376340700205340ustar00rootroot00000000000000#!/bin/bash # Observations: # # - If TEST_DEV is a symlink, xfstests fails with strange errors. # - There appears to be some confusion about RESULT_BASE and RESULTS_BASE. # Neither one is documented. mkdir /tmp/testmnt export TEST_DEV="`realpath /dev/disk/by-id/scsi-0virtme_disk_test`" export TEST_DIR=/tmp/testmnt mkfs.xfs -f $TEST_DEV mkdir /tmp/scratchmnt export SCRATCH_DEV="`realpath /dev/disk/by-id/scsi-0virtme_disk_scratch`" export SCRATCH_MNT=/tmp/scratchmnt mkfs.xfs -f $SCRATCH_DEV mount -t xfs "$SCRATCH_DEV" "$SCRATCH_MNT" echo "Scratch dev is $SCRATCH_DEV" export RESULT_BASE=/tmp/results export RESULTS_BASE="$RESULT_BASE" mkdir $RESULT_BASE cd "$1" echo "Starting xfstests" ./check virtme-0.0.2/setup.py000077500000000000000000000030171243376340700145460ustar00rootroot00000000000000#!/usr/bin/env python3 import os import sys try: from setuptools import setup except ImportError: from distutils.core import setup if sys.version_info < (3,3): print('virtme requires Python 3.3 or higher') sys.exit(1) _VERSION = '0.0.1' setup( name='virtme', version=_VERSION, author='Andy Lutomirski', author_email='luto@amacapital.net', description='Virtualize the running distro or a simple rootfs', url='https://git.kernel.org/cgit/utils/kernel/virtme/virtme.git', download_url='https://www.kernel.org/pub/linux/utils/kernel/virtme/releases/virtme-%s.tar.xz' % _VERSION, license='GPLv2', long_description=open(os.path.join(os.path.dirname(__file__), 'README.md'), 'r').read(), packages=['virtme', 'virtme.commands'], install_requires=[], entry_points = { 'console_scripts': [ 'virtme-run = virtme.commands.run:main', 'virtme-configkernel = virtme.commands.configkernel:main', ] }, data_files = [ ('share/virtme-guest-0', ['virtme/guest/virtme-init', 'virtme/guest/virtme-udhcpc-script', 'virtme/guest/virtme-loadmods', ]), ], classifiers=['Environment :: Console', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: GNU General Public License v2 (GPLv2)', 'Operating System :: POSIX :: Linux', ] ) virtme-0.0.2/virtme-configkernel000077500000000000000000000011161243376340700167270ustar00rootroot00000000000000#!/usr/bin/python3 # -*- mode: python -*- # virtme-configkernel: Configure a kernel for virtme # Copyright © 2014 Andy Lutomirski # Licensed under the GPLv2, which is available in the virtme distribution # as a file called LICENSE with SHA-256 hash: # 8177f97513213526df2cf6184d8ff986c675afb514d4e68a404010521b880643 # This file is not installed; it's just used to run virtme from inside # a source distribution. import sys if sys.version_info < (3,3): print('virtme requires Python 3.3 or higher') sys.exit(1) from virtme.commands import configkernel exit(configkernel.main()) virtme-0.0.2/virtme-mkinitramfs000077500000000000000000000016501243376340700166100ustar00rootroot00000000000000#!/usr/bin/python3 # -*- mode: python -*- # virtme-mkinitramfs: Generate an initramfs image for virtme # Copyright © 2014 Andy Lutomirski # Licensed under the GPLv2, which is available in the virtme distribution # as a file called LICENSE with SHA-256 hash: # 8177f97513213526df2cf6184d8ff986c675afb514d4e68a404010521b880643 import argparse import modfinder import virtmods import mkinitramfs _ARGPARSER = argparse.ArgumentParser( description='Generate initramfs image for virtme', ) _ARGPARSER.add_argument('--mod-kversion', action='store', default=None) def main(): import sys args = _ARGPARSER.parse_args() config = mkinitramfs.Config() if args.mod_kversion is not None: config.modfiles = modfinder.find_modules_from_install( virtmods.MODALIASES, kver=args.mod_kversion) mkinitramfs.mkinitramfs(sys.stdout.buffer, config) return 0 if __name__ == '__main__': exit(main()) virtme-0.0.2/virtme-run000077500000000000000000000010721243376340700150660ustar00rootroot00000000000000#!/usr/bin/python3 # -*- mode: python -*- # virtme-run: The main command-line virtme frontend # Copyright © 2014 Andy Lutomirski # Licensed under the GPLv2, which is available in the virtme distribution # as a file called LICENSE with SHA-256 hash: # 8177f97513213526df2cf6184d8ff986c675afb514d4e68a404010521b880643 # This file is not installed; it's just use to run virtme from inside # a source distribution. import sys if sys.version_info < (3,3): print('virtme requires Python 3.3 or higher') sys.exit(1) from virtme.commands import run exit(run.main()) virtme-0.0.2/virtme/000077500000000000000000000000001243376340700143365ustar00rootroot00000000000000virtme-0.0.2/virtme/__init__.py000066400000000000000000000000001243376340700164350ustar00rootroot00000000000000virtme-0.0.2/virtme/architectures.py000066400000000000000000000120111243376340700175500ustar00rootroot00000000000000# -*- mode: python -*- # qemu_helpers: Helpers to find QEMU and handle its quirks # Copyright © 2014 Andy Lutomirski # Licensed under the GPLv2, which is available in the virtme distribution # as a file called LICENSE with SHA-256 hash: # 8177f97513213526df2cf6184d8ff986c675afb514d4e68a404010521b880643 import os class Arch(object): def __init__(self, name): self.qemuname = name self.linuxname = name defconfig_target = 'defconfig' @staticmethod def serial_dev_name(index): return 'ttyS%d' % index @staticmethod def qemuargs(is_native): return [] @staticmethod def virtio_dev_type(virtiotype): # Return a full name for a virtio device. It would be # nice if QEMU abstracted this away, but it doesn't. return 'virtio-%s-pci' % virtiotype @staticmethod def earlyconsole_args(): return [] @staticmethod def serial_console_args(): return [] @staticmethod def config_base(): return [] class Arch_unknown(Arch): @staticmethod def qemuargs(is_native): return Arch.qemuargs(is_native) class Arch_x86(Arch): @staticmethod def qemuargs(is_native): ret = Arch.qemuargs(is_native) # Add a watchdog. This is useful for testing. ret.extend(['-watchdog', 'i6300esb']) if is_native and os.access('/dev/kvm', os.R_OK): # If we're likely to use KVM, request a full-featured CPU. # (NB: if KVM fails, this will cause problems. We should probe.) ret.extend(['-cpu', 'host']) # We can't migrate regardless. return ret @staticmethod def earlyconsole_args(): return ['earlyprintk=serial,ttyS0,115200'] @staticmethod def serial_console_args(): return ['console=ttyS0'] @staticmethod def config_base(): return ['CONFIG_SERIO=y', 'CONFIG_PCI=y', 'CONFIG_INPUT=y', 'CONFIG_INPUT_KEYBOARD=y', 'CONFIG_KEYBOARD_ATKBD=y', 'CONFIG_SERIAL_8250=y', 'CONFIG_SERIAL_8250_CONSOLE=y', 'CONFIG_X86_VERBOSE_BOOTUP=y', 'CONFIG_VGA_CONSOLE=y', 'CONFIG_FB=y', 'CONFIG_FB_VESA=y', 'CONFIG_FRAMEBUFFER_CONSOLE=y', 'CONFIG_RTC_CLASS=y', 'CONFIG_RTC_HCTOSYS=y', 'CONFIG_RTC_DRV_CMOS=y', 'CONFIG_HYPERVISOR_GUEST=y', 'CONFIG_PARAVIRT=y', 'CONFIG_KVM_GUEST=y', # Depending on the host kernel, virtme can nest! 'CONFIG_KVM=y', 'CONFIG_KVM_INTEL=y', 'CONFIG_KVM_AMD=y', ] class Arch_arm(Arch): def __init__(self, name): Arch.__init__(self, name) self.defconfig_target = 'versatile_defconfig' @staticmethod def qemuargs(is_native): ret = Arch.qemuargs(is_native) # Emulate a versatilepb. ret.extend(['-M', 'versatilepb']) # Add a watchdog. This is useful for testing. Oddly, this works # fine on ARM even though it's an Intel chipset device. ret.extend(['-watchdog', 'i6300esb']) return ret @staticmethod def virtio_dev_type(virtiotype): return 'virtio-%s-pci' % virtiotype @staticmethod def earlyconsole_args(): return ['earlyprintk=serial,ttyAMA0,115200'] @staticmethod def serial_console_args(): return ['console=ttyAMA0'] class Arch_aarch64(Arch): def __init__(self, name): Arch.__init__(self, name) self.qemuname = 'aarch64' self.linuxname = 'arm64' @staticmethod def qemuargs(is_native): ret = Arch.qemuargs(is_native) # Emulate a fully virtual system. ret.extend(['-M', 'virt']) # Despite being called qemu-system-aarch64, QEMU defaults to # emulating a 32-bit CPU. Override it. ret.extend(['-cpu', 'cortex-a57']) return ret @staticmethod def virtio_dev_type(virtiotype): return 'virtio-%s-device' % virtiotype @staticmethod def earlyconsole_args(): return ['earlyprintk=serial,ttyAMA0,115200'] @staticmethod def serial_console_args(): return ['console=ttyAMA0'] # Disabled because it doesn't work. class Arch_s390x(Arch): def __init__(self, name): Arch.__init__(self, name) self.qemuname = 's390x' self.linuxname = 's390' @staticmethod def virtio_dev_type(virtiotype): return 'virtio-%s-device' % virtiotype def qemuargs(self, is_native): return [ '-device', 'virtio-mmio', # This is very buggy. '-device', self.virtio_dev_type('serial'), # This is annoying but acceptable. '-device', 'virtconsole,chardev=console', ] ARCHES = { 'x86_64': Arch_x86, 'i386': Arch_x86, 'arm': Arch_arm, 'aarch64': Arch_aarch64, } def get(arch): return ARCHES.get(arch, Arch_unknown)(arch) virtme-0.0.2/virtme/commands/000077500000000000000000000000001243376340700161375ustar00rootroot00000000000000virtme-0.0.2/virtme/commands/__init__.py000066400000000000000000000000001243376340700202360ustar00rootroot00000000000000virtme-0.0.2/virtme/commands/configkernel.py000066400000000000000000000072361243376340700211670ustar00rootroot00000000000000# -*- mode: python -*- # virtme-configkernel: Configure a kernel for virtme # Copyright © 2014 Andy Lutomirski # Licensed under the GPLv2, which is available in the virtme distribution # as a file called LICENSE with SHA-256 hash: # 8177f97513213526df2cf6184d8ff986c675afb514d4e68a404010521b880643 import argparse import tempfile import os import shutil import subprocess import multiprocessing from .. import architectures uname = os.uname() def make_parser(): parser = argparse.ArgumentParser( description='Configure a kernel for virtme', ) parser.add_argument('--arch', action='store', metavar='ARCHITECTURE', default=uname.machine, help='Target architecture') parser.add_argument('--allnoconfig', action='store_true', help='Overwrite configuration with a virtme-suitable allnoconfig (unlikely to work)') parser.add_argument('--defconfig', action='store_true', help='Overwrite configuration with a virtme-suitable defconfig') return parser _ARGPARSER = make_parser() def arg_fail(message): print(message) _ARGPARSER.print_usage() exit(1) _GENERIC_CONFIG = [ '# Generic', 'CONFIG_VIRTIO=y', 'CONFIG_VIRTIO_PCI=y', 'CONFIG_VIRTIO_MMIO=y', 'CONFIG_NET=y', 'CONFIG_NET_CORE=y', 'CONFIG_NETDEVICES=y', 'CONFIG_NETWORK_FILESYSTEMS=y', 'CONFIG_INET=y', 'CONFIG_NET_9P=y', 'CONFIG_NET_9P_VIRTIO=y', 'CONFIG_9P_FS=y', 'CONFIG_VIRTIO_NET=y', 'CONFIG_CMDLINE_OVERRIDE=n', 'CONFIG_BINFMT_SCRIPT=y', 'CONFIG_SHMEM=y', 'CONFIG_TMPFS=y', 'CONFIG_UNIX=y', 'CONFIG_MODULE_SIG_FORCE=n', 'CONFIG_DEVTMPFS=y', 'CONFIG_TTY=y', 'CONFIG_VT=y', 'CONFIG_UNIX98_PTYS=y', 'CONFIG_EARLY_PRINTK=y', '', '# virtio-scsi support', 'CONFIG_BLOCK=y', 'CONFIG_SCSI_LOWLEVEL=y', 'CONFIG_SCSI=y', 'CONFIG_SCSI_VIRTIO=y', 'CONFIG_BLK_DEV_SD=y', '', '# virt-serial support', 'CONFIG_VIRTIO_CONSOLE=y', '', '# watchdog (useful for test scripts)', 'CONFIG_WATCHDOG=y', 'CONFIG_WATCHDOG_CORE=y', 'CONFIG_I6300ESB_WDT=y', ] def main(): args = _ARGPARSER.parse_args() if not os.path.isfile('scripts/kconfig/merge_config.sh'): print('virtme-configkernel must be run in a kernel source directory') return 1 arch = architectures.get(args.arch) conf = (_GENERIC_CONFIG + ['# Arch-specific options'] + arch.config_base()) if args.arch == 'x86_64': conf.append('CONFIG_64BIT=y') elif args.arch == 'i386': conf.append('CONFIG_64BIT=n') if shutil.which('%s-linux-gnu-gcc' % arch.qemuname): conf.append('CONFIG_CROSS_COMPILE="%s-linux-gnu-"' % arch.qemuname) if args.allnoconfig and args.defconfig: arg_fail('allnoconfig and defconfig are incompatible') if args.allnoconfig: maketarget = 'allnoconfig' updatetarget = 'silentoldconfig' elif args.defconfig: maketarget = arch.defconfig_target updatetarget = 'olddefconfig' else: arg_fail('One of --allnoconfig and --defconfig must be specified') # TODO: Get rid of most of the noise and check the result. # Set up an initial config subprocess.check_call(['make', 'ARCH=%s' % arch.linuxname, maketarget]) with open('.config', 'ab') as conffile: conffile.write('\n'.join(conf).encode('utf-8')) subprocess.check_call(['make', 'ARCH=%s' % arch.linuxname, updatetarget]) print("Configured. Build with 'make ARCH=%s -j%d'" % (arch.linuxname, multiprocessing.cpu_count())) return 0 if __name__ == '__main__': exit(main()) virtme-0.0.2/virtme/commands/run.py000066400000000000000000000403271243376340700173230ustar00rootroot00000000000000# -*- mode: python -*- # virtme-run: The main command-line virtme frontend # Copyright © 2014 Andy Lutomirski # Licensed under the GPLv2, which is available in the virtme distribution # as a file called LICENSE with SHA-256 hash: # 8177f97513213526df2cf6184d8ff986c675afb514d4e68a404010521b880643 import argparse import tempfile import shutil import os import fcntl import sys import shlex import re from .. import virtmods from .. import modfinder from .. import mkinitramfs from .. import qemu_helpers from .. import architectures from .. import guest_tools uname = os.uname() def make_parser(): parser = argparse.ArgumentParser( description='Virtualize your system (or another) under a kernel image', ) g = parser.add_argument_group(title='Selection of kernel and modules').add_mutually_exclusive_group() g.add_argument('--installed-kernel', action='store', nargs='?', const=uname.release, default=None, metavar='VERSION', help='Use an installed kernel and its associated modules. If no version is specified, the running kernel will be used.') g.add_argument('--kimg', action='store', help='Use specified kernel image with no modules.') # Disabled until kmod gets fixed. # g.add_argument('--kernel-build-dir', action='store', metavar='KDIR', # help='Use a compiled kernel source directory') g = parser.add_argument_group(title='Kernel options') g.add_argument('-a', '--kopt', action='append', default=[], help='Add a kernel option. You can specify this more than once.') g.add_argument('--xen', action='store', help='Boot Xen using the specified uncompressed hypervisor.') g = parser.add_argument_group(title='Common guest options') g.add_argument('--root', action='store', default='/', help='Local path to use as guest root') g.add_argument('--graphics', action='store_true', help='Show graphical output instead of using a console.') g.add_argument('--net', action='store_true', help='Enable basic network access.') g.add_argument('--balloon', action='store_true', help='Allow the host to ask the guest to release memory.') g.add_argument('--disk', action='append', default=[], metavar='NAME=PATH', help='Add a read/write virtio-scsi disk. The device node will be /dev/disk/by-id/scsi-0virtme_disk_NAME.') g = parser.add_argument_group( title='Scripting', 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.") g.add_argument('--script-sh', action='store', metavar='SHELL_COMMAND', help='Run a one-line shell script in the guest.') g.add_argument('--script-exec', action='store', metavar='BINARY', help='Run the specified binary in the guest.') g = parser.add_argument_group( title='Architecture', description="Options related to architecture selection") g.add_argument('--arch', action='store', metavar='ARCHITECTURE', default=uname.machine, help='Guest architecture') g.add_argument('--busybox', action='store', metavar='PATH_TO_BUSYBOX', help='Use the specified busybox binary.') g = parser.add_argument_group(title='Virtualizer settings') g.add_argument('-q', '--qemu-opt', action='append', default=[], help="Add a single QEMU argument. Use this when --qemu-opts's greedy behavior is problematic.'") g.add_argument('--qemu-opts', action='store', nargs=argparse.REMAINDER, 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.') g = parser.add_argument_group(title='Debugging/testing') g.add_argument('--force-initramfs', action='store_true', help='Use an initramfs even if unnecessary') g.add_argument('--dry-run', action='store_true', help="Initialize everything but don't run the guest") g.add_argument('--show-command', action='store_true', help='Show the VM command line') g = parser.add_argument_group(title='Guest userspace configuration') g.add_argument('--pwd', action='store_true', help='Propagate current working directory to the guest') g = parser.add_argument_group(title='Sharing resources with guest') g.add_argument('--rwdir', action='append', default=[], help="Supply a read/write directory to the guest. Use --rwdir=path or --rwdir=guestpath=hostpath.") return parser _ARGPARSER = make_parser() def arg_fail(message): print(message) _ARGPARSER.print_usage() sys.exit(1) def find_kernel_and_mods(args): if args.installed_kernel is not None: kver = args.installed_kernel modfiles = modfinder.find_modules_from_install( virtmods.MODALIASES, kver=kver) moddir = os.path.join('/lib/modules', kver) kimg = '/boot/vmlinuz-%s' % kver # Disabled until kmod gets fixed. # elif args.kernel_build_dir is not None: # kimg = os.path.join(args.kernel_build_dir, 'arch/x86/boot/bzImage') # modfiles = modfinder.find_modules_from_install( # virtmods.MODALIASES, # moddir=os.path.join(args.kernel_build_dir, '.tmp_moddir')) elif args.kimg is not None: kimg = args.kimg modfiles = [] moddir = None else: arg_fail('You must specify a kernel to use.') return kimg,modfiles,moddir def export_virtfs(qemu, arch, qemuargs, path, mount_tag, security_model='none', readonly=True): # NB: We can't use -virtfs for this, because it can't handle a mount_tag # that isn't a valid QEMU identifier. fsid = 'virtfs%d' % len(qemuargs) qemuargs.extend(['-fsdev', 'local,id=%s,path=%s,security_model=%s%s' % (fsid, qemu.quote_optarg(path), security_model, ',readonly' if readonly else '')]) qemuargs.extend(['-device', '%s,fsdev=%s,mount_tag=%s' % (arch.virtio_dev_type('9p'), fsid, qemu.quote_optarg(mount_tag))]) def quote_karg(arg): if '"' in arg: raise ValueError("cannot quote '\"' in kernel args") if ' ' in arg: return '"%s"' % arg else: return arg # Allowed characters in mount paths. We can extend this over time if needed. _SAFE_PATH_PATTERN = '[a-zA-Z0-9_+ /.-]+' _RWDIR_RE = re.compile('^(%s)(?:=(%s))?$' % (_SAFE_PATH_PATTERN, _SAFE_PATH_PATTERN)) def main(): args = _ARGPARSER.parse_args() qemu = qemu_helpers.Qemu(args.arch) qemu.probe() need_initramfs = args.force_initramfs or qemu.cannot_overmount_virtfs config = mkinitramfs.Config() kimg,modfiles,moddir = find_kernel_and_mods(args) config.modfiles = modfiles if config.modfiles: need_initramfs = True arch = architectures.get(args.arch) is_native = (args.arch == uname.machine) qemuargs = [qemu.qemubin] kernelargs = [] # Set up virtfs export_virtfs(qemu, arch, qemuargs, args.root, '/dev/root') guest_tools_in_guest, guest_tools_path = \ guest_tools.find_best_guest_tools(args.root) if guest_tools_path is None: raise ValueError("couldn't find usable virtme guest tools") if guest_tools_in_guest: virtme_init = os.path.join(guest_tools_path, 'virtme-init') else: virtme_init = '/run/virtme/guesttools/virtme-init' export_virtfs(qemu, arch, qemuargs, guest_tools_path, 'virtme.guesttools') need_initramfs = True # TODO: This has escaping issues for now kernelargs.append('init=%s' % os.path.join('/', virtme_init)) # Map modules if moddir is not None: export_virtfs(qemu, arch, qemuargs, moddir, 'virtme.moddir') # Set up mounts mount_index = 0 for rwdir in args.rwdir: m = _RWDIR_RE.match(rwdir) if not m: arg_fail('invalid --rwdir parameter') if m.group(2) is not None: guestpath = m.group(1) hostpath = m.group(2) else: hostpath = m.group(1) guestpath = os.path.relpath(hostpath, args.root) if guestpath.startswith('..'): arg_fail('%r is not inside the root' % hostpath) idx = mount_index mount_index += 1 tag = 'virtme.initmount%d' % idx export_virtfs(qemu, arch, qemuargs, hostpath, tag, readonly=False) kernelargs.append('virtme_initmount%d=%s' % (idx, guestpath)) # Turn on KVM if available if is_native: qemuargs.extend(['-machine', 'accel=kvm:tcg']) # Add architecture-specific options qemuargs.extend(arch.qemuargs(is_native)) # Set up / override baseline devices qemuargs.extend(['-parallel', 'none']) qemuargs.extend(['-net', 'none']) if not args.graphics and not args.script_sh and not args.script_exec: # It would be nice to use virtconsole, but it's terminally broken # in current kernels. Nonetheless, I'm configuring the console # manually to make it easier to tweak in the future. qemuargs.extend(['-echr', '1']) qemuargs.extend(['-serial', 'none']) qemuargs.extend(['-chardev', 'stdio,id=console,signal=off,mux=on']) # We should be using the new-style -device serialdev,chardev=xyz, # but many architecture-specific serial devices don't support that. qemuargs.extend(['-serial', 'chardev:console']) qemuargs.extend(['-mon', 'chardev=console']) kernelargs.extend(arch.earlyconsole_args()) kernelargs.extend(arch.serial_console_args()) qemuargs.extend(['-vga', 'none']) qemuargs.extend(['-display', 'none']) # PS/2 probing is slow; give the kernel a hint to speed it up. kernelargs.extend(['psmouse.proto=exps']) # Fix the terminal defaults (and set iutf8 because that's a better # default nowadays). I don't know of any way to keep this up to date # after startup, though. terminal_size = os.get_terminal_size() kernelargs.extend(['virtme_stty_con=rows %d cols %d iutf8' % (terminal_size.lines, terminal_size.columns)]) # Propagate the terminal type if 'TERM' in os.environ: kernelargs.extend(['TERM=%s' % os.environ['TERM']]) if args.balloon: qemuargs.extend(['-balloon', 'virtio']) if args.disk: qemuargs.extend(['-device', '%s,id=scsi' % arch.virtio_dev_type('scsi')]) for i,d in enumerate(args.disk): namefile = d.split('=', 1) if len(namefile) != 2: arg_fail('invalid argument to --disk') name,fn = namefile if '=' in fn or ',' in fn: arg_fail("--disk filenames cannot contain '=' or ','") if '=' in fn or ',' in name: arg_fail("--disk device names cannot contain '=' or ','") driveid = 'disk%d' % i qemuargs.extend(['-drive', 'if=none,id=%s,file=%s' % (driveid, fn), '-device', 'scsi-hd,drive=%s,vendor=virtme,product=disk,serial=%s' % (driveid, name)]) has_script = False def do_script(shellcmd): if args.graphics: arg_fail('scripts and --graphics are mutually exclusive') nonlocal has_script nonlocal need_initramfs if has_script: arg_fail('conflicting script options') has_script = True need_initramfs = True # TODO: Fix this # Turn off default I/O qemuargs.extend(['-vga', 'none']) qemuargs.extend(['-display', 'none']) # Send kernel logs to stderr qemuargs.extend(['-serial', 'none']) qemuargs.extend(['-chardev', 'file,id=console,path=/proc/self/fd/2']) # We should be using the new-style -device serialdev,chardev=xyz, # but many architecture-specific serial devices don't support that. qemuargs.extend(['-serial', 'chardev:console']) # Set up a virtserialport for script I/O qemuargs.extend(['-chardev', 'stdio,id=stdio,signal=on,mux=off']) qemuargs.extend(['-device', arch.virtio_dev_type('serial')]) qemuargs.extend(['-device', 'virtserialport,name=virtme.scriptio,chardev=stdio']) # Scripts shouldn't reboot qemuargs.extend(['-no-reboot']) # Ask virtme-init to run the script config.virtme_data[b'script'] = """#!/bin/sh exec {shellcmd} """.format(shellcmd=shellcmd).encode('ascii') # Nasty issue: QEMU will set O_NONBLOCK on fds 0, 1, and 2. # This isn't inherently bad, but it can cause a problem if # another process is reading from 1 or writing to 0, which is # exactly what happens if you're using a terminal and you # redirect some, but not all, of the tty fds. Work around it # by giving QEMU private copies of the open object if either # of them is a terminal. for oldfd,mode in ((0,os.O_RDONLY), (1,os.O_WRONLY), (2,os.O_WRONLY)): if os.isatty(oldfd): try: newfd = os.open('/proc/self/fd/%d' % oldfd, mode) except OSError: pass else: os.dup2(newfd, oldfd) os.close(newfd) if args.script_sh is not None: do_script(args.script_sh) if args.script_exec is not None: do_script(shlex.quote(args.script_exec)) if args.net: qemuargs.extend(['-net', 'nic,model=virtio']) qemuargs.extend(['-net', 'user']) kernelargs.extend(['virtme.dhcp']) if args.pwd: rel_pwd = os.path.relpath(os.getcwd(), args.root) if rel_pwd.startswith('..'): print('current working directory is not contained in the root') return 1 kernelargs.append('virtme_chdir=%s' % rel_pwd) if need_initramfs: if args.busybox is not None: config.busybox = args.busybox else: config.busybox = mkinitramfs.find_busybox(args.root, is_native) if config.busybox is None: print('virtme-run: initramfs is needed, and no busybox was found', file=sys.stderr) return 1 # Set up the initramfs (warning: hack ahead) tmpfd,tmpname = tempfile.mkstemp('irfs') os.unlink(tmpname) tmpfile = os.fdopen(tmpfd, 'r+b') mkinitramfs.mkinitramfs(tmpfile, config) tmpfile.flush() fcntl.fcntl(tmpfd, fcntl.F_SETFD, 0) initrdpath = '/proc/self/fd/%d' % tmpfile.fileno() else: # No initramfs! Warning: this is slower than using an initramfs # because the kernel will wait for device probing to finish. # Sigh. kernelargs.extend([ 'rootfstype=9p', 'rootflags=ro,version=9p2000.L,trans=virtio,access=any', 'raid=noautodetect', ]) initrdpath = None if args.xen is None: # Load a normal kernel qemuargs.extend(['-kernel', kimg]) if kernelargs: qemuargs.extend(['-append', ' '.join(quote_karg(a) for a in (kernelargs + args.kopt))]) if initrdpath is not None: qemuargs.extend(['-initrd', initrdpath]) else: # Use multiboot syntax to load Xen qemuargs.extend(['-kernel', args.xen]) qemuargs.extend(['-initrd', '%s %s%s' % ( kimg, ' '.join(quote_karg(a).replace(',', ',,') for a in kernelargs), (',%s' % initrdpath) if initrdpath is not None else '')]) # Handle --qemu-opt(s) qemuargs.extend(args.qemu_opt) if args.qemu_opts is not None: qemuargs.extend(args.qemu_opts) if args.show_command: print(' '.join(shlex.quote(a) for a in qemuargs)) # Go! if not args.dry_run: os.execv(qemu.qemubin, qemuargs) if __name__ == '__main__': exit(main()) virtme-0.0.2/virtme/cpiowriter.py000077500000000000000000000053331243376340700171060ustar00rootroot00000000000000# -*- mode: python -*- # cpiowriter: A barebones initramfs writer # Copyright © 2014 Andy Lutomirski # Licensed under the GPLv2, which is available in the virtme distribution # as a file called LICENSE with SHA-256 hash: # 8177f97513213526df2cf6184d8ff986c675afb514d4e68a404010521b880643 import sys class CpioWriter(object): TYPE_DIR = 0o0040000 TYPE_REG = 0o0100000 TYPE_SYMLINK = 0o0120000 TYPE_CHRDEV = 0o0020000 TYPE_MASK = 0o0170000 def __init__(self, f): self.__f = f self.__totalsize = 0 self.__next_ino = 0 def __write(self, data): self.__f.write(data) self.__totalsize += len(data) def write_object(self, name, body, mode, ino=None, nlink=None, uid=0, gid=0, mtime=0, devmajor=0, devminor=0, rdevmajor=0, rdevminor=0): if nlink is None: nlink = (2 if (mode & CpioWriter.TYPE_MASK) == CpioWriter.TYPE_DIR else 1) if b'\0' in name: raise ValueError('Filename cannot contain a NUL') namesize = len(name) + 1 if isinstance(body, bytes): filesize = len(body) else: filesize = body.seek(0, 2) body.seek(0) if ino is None: ino = self.__next_ino self.__next_ino += 1 fields = [ino, mode, uid, gid, nlink, mtime, filesize, devmajor, devminor, rdevmajor, rdevminor, namesize, 0] hdr = ('070701' + ''.join('%08X' % f for f in fields)).encode('ascii') self.__write(hdr) self.__write(name) self.__write(b'\0') self.__write(((2-namesize) % 4) * b'\0') if isinstance(body, bytes): self.__write(body) else: while True: buf = body.read(65536) if buf == b'': break self.__write(buf) self.__write(((-filesize) % 4) * b'\0') def write_trailer(self): self.write_object(name=b'TRAILER!!!', body=b'', mode=0, ino=0, nlink=1) self.__write(((-self.__totalsize) % 512) * b'\0') def mkdir(self, name, mode): self.write_object(name=name, mode=CpioWriter.TYPE_DIR | mode, body=b'') def symlink(self, src, dst): self.write_object(name=dst, mode=CpioWriter.TYPE_SYMLINK | 0o777, body=src) def write_file(self, name, body, mode): self.write_object(name=name, body=body, mode=CpioWriter.TYPE_REG | mode) def mkchardev(self, name, dev, mode): major,minor = dev self.write_object(name=name, mode=CpioWriter.TYPE_CHRDEV | mode, rdevmajor=major, rdevminor=minor, body=b'') virtme-0.0.2/virtme/guest/000077500000000000000000000000001243376340700154655ustar00rootroot00000000000000virtme-0.0.2/virtme/guest/virtme-init000077500000000000000000000115511243376340700176650ustar00rootroot00000000000000#!/bin/bash # virtme-init: virtme's basic init (PID 1) process # Copyright © 2014 Andy Lutomirski # Licensed under the GPLv2, which is available in the virtme distribution # as a file called LICENSE with SHA-256 hash: # 8177f97513213526df2cf6184d8ff986c675afb514d4e68a404010521b880643 export PATH=/bin:/sbin:/usr/bin:/usr/sbin log() { if [[ -e /dev/kmsg ]]; then echo "<6>virtme-init: $*" >/dev/kmsg else echo "virtme-init: $*" fi } mount -t sysfs -o nosuid,noexec,nodev sys /sys/ declare -A mount_tags for i in /sys/bus/virtio/drivers/9pnet_virtio/virtio*/mount_tag; do mount_tags["`cat "$i"`"]=1 done kver="`uname -r`" if [[ -n "${mount_tags[virtme.moddir]}" ]]; then mount -t tmpfs none /lib/modules mkdir /lib/modules/"$kver" mount -n -t 9p -o ro,version=9p2000.L,trans=virtio,access=any virtme.moddir /lib/modules/"$kver" elif [[ -d "/lib/modules/$kver" ]]; then # We may have mismatched modules. Mask them off. mount -n -t tmpfs -o ro,mode=0000 disallow_modules "/lib/modules/$kver" fi mount -t tmpfs tmpfs /tmp/ [[ -w /var/log ]] || mount -t tmpfs tmpfs /var/log/ [[ -n "${virtme_run_mounted}" ]] || mount -t tmpfs run /run # Fix up /etc a little bit touch /tmp/fstab mount --bind /tmp/fstab /etc/fstab rm /tmp/fstab # Find udevd if [[ -x /usr/lib/systemd/systemd-udevd ]]; then udevd=/usr/lib/systemd/systemd-udevd else udevd=`which udevd` fi # Mount proc (needed for stat, sadly) mount -t proc -o nosuid,noexec,nodev proc /proc/ # devtmpfs might be automounted; if not, mount it. if [[ "`stat --format=%m /dev`" != "/dev" ]]; then # Ideally we'll use devtmpfs (but don't rely on /dev/null existing). if [[ -c /dev/null ]]; then mount -n -t devtmpfs -o mode=0755,nosuid,noexec devtmpfs /dev \ &>/dev/null else mount -n -t devtmpfs -o mode=0755,nosuid,noexec devtmpfs /dev fi if (( $? != 0 )); then # The running kernel doesn't have devtmpfs. Use regular tmpfs. mount -t tmpfs -o mode=0755,nosuid,noexec none /dev # Make some basic devices first, and let udev handle the rest mknod -m 0666 /dev/null c 1 3 mknod -m 0660 /dev/kmsg c 1 11 mknod -m 0600 /dev/console c 5 1 fi fi for tag in "${!virtme_initmount@}"; do mount -t 9p -o version=9p2000.L,trans=virtio,access=any "virtme.initmount${tag:16}" "${!tag}" done if [[ -n "virtme_chdir" ]]; then cd -- "${virtme_chdir}" fi log "basic initialization done" ######## The remainder of this script is a very simple init (PID 1) ######## # Try to get udevd to coldplug everything. # We could use virtme-loadmods as a lightweight alternative. "$udevd" --daemon --resolve-names=never udevadm trigger --action=add >/dev/null 2>&1 udevadm settle # Set up filesystems that live in /dev mkdir -p -m 0755 /dev/shm /dev/pts mount -t devpts -o gid=tty,mode=620,noexec,nosuid devpts /dev/pts mount -t tmpfs -o mode=1777,nosuid,nodev tmpfs /dev/shm # Bring up networking ip link set dev lo up if cat /proc/cmdline |grep -q -E '(^| )virtme.dhcp($| )'; then if [[ -f /etc/resolv.conf ]]; then tmpfile="`mktemp --tmpdir=/tmp`" mount --bind "$tmpfile" /etc/resolv.conf rm "$tmpfile" fi busybox udhcpc -i eth0 -t 1 -n -q -f -s "$(dirname $0)/virtme-udhcpc-script" fi if [[ -x /run/virtme/data/script ]]; then if [[ ! -e "/dev/virtio-ports/virtme.scriptio" ]]; then echo "virtme-init: cannot find script I/O port; make sure virtio-serial is available" poweroff -f exit 1 fi log 'starting script' setsid /run/virtme/data/script <>/dev/virtio-ports/virtme.scriptio 2>&1 log "script returned $?" # Hmm. We should expose the return value somehow. sync poweroff -f exit 1 fi # Create some VTs deallocvt openvt -c 2 -- /bin/bash openvt -c 3 -- /bin/bash openvt -c 4 -- /bin/bash # Figure out what the main console is consdev="`grep ' ... (.C' /proc/consoles |cut -d' ' -f1`" if [[ -z "$consdev" ]]; then log "can't deduce console device" exec bash --login # At least try to be helpful fi if [[ "$consdev" == "tty0" ]]; then consdev=tty1 # sigh fi if [[ ! -e "/dev/$consdev" ]]; then log "/dev/$consdev doesn't exist." exec bash --login fi # Parameters that start with virtme_ shouldn't pollute the environment for p in "${!virtme_@}"; do export -n "$p"; done echo "virtme-init: console is $consdev" # Bring up a functioning shell on the console. This is a bit magical: # We have no controlling terminal because we're attached to a fake # console device (probably something like /dev/console), which can't # be a controlling terminal. We are also not a member of a session. # Init apparently can't setsid (whether that's a limitation of the # setsid binary or the system call, I don't know). while true; do # Program the console sensibly if [[ -n "${virtme_stty_con}" ]]; then stty ${virtme_stty_con} <"/dev/$consdev" fi setsid bash 0<>"/dev/$consdev" 1>&0 2>&0 echo "Shell died. Will respawn." sleep 0.5 done virtme-0.0.2/virtme/guest/virtme-loadmods000077500000000000000000000013101243376340700205140ustar00rootroot00000000000000#!/bin/sh # -*- mode: python -*- # virtme-loadmods: load modules for all available devices # Copyright © 2014 Andy Lutomirski # Licensed under the GPLv2, which is available in the virtme distribution # as a file called LICENSE with SHA-256 hash: # 8177f97513213526df2cf6184d8ff986c675afb514d4e68a404010521b880643 export PATH=/bin:/sbin:/usr/bin:/usr/sbin export TERM=linux log() { if [[ -e /dev/kmsg ]]; then echo "<6>virtme-loadmods: $*" >/dev/kmsg else echo "virtme-loadmods: $*" fi } log 'looking for modaliases' mods="$(find /sys/devices -type f -name modalias -print0 |xargs -0 cat |sort |uniq)" log "requesting $(echo "$mods" |wc -w) modules" modprobe -q -a -- $mods log 'done' exit 0 virtme-0.0.2/virtme/guest/virtme-udhcpc-script000077500000000000000000000012151243376340700214660ustar00rootroot00000000000000#!/bin/bash # virtme-udhcpc-script: A trivial udhcpc script # Copyright © 2014 Andy Lutomirski # Licensed under the GPLv2, which is available in the virtme distribution # as a file called LICENSE with SHA-256 hash: # 8177f97513213526df2cf6184d8ff986c675afb514d4e68a404010521b880643 if [[ "$1" == "deconfig" ]]; then ip link set dev "$interface" up ip addr flush dev "$interface" elif [[ "$1" == "bound" ]]; then ip addr add "$ip/$mask" dev "$interface" ip route add default via "$router" dev "$interface" if [[ -n "$dns" ]]; then echo -e "# Generated by virtme-udhcpc-script\n\nnameserver $dns" \ >/etc/resolv.conf fi fi virtme-0.0.2/virtme/guest_tools.py000066400000000000000000000050171243376340700172620ustar00rootroot00000000000000# -*- mode: python -*- # resources.py: Find virtme's resources # Copyright © 2014 Andy Lutomirski # Licensed under the GPLv2, which is available in the virtme distribution # as a file called LICENSE with SHA-256 hash: # 8177f97513213526df2cf6184d8ff986c675afb514d4e68a404010521b880643 """Helpers to find virtme's guest tools.""" import os import pkg_resources def find_dist_guest_tools(): """Return the path of the guest tools installed with the running virtme. This is much more complicated than it deserves to be. """ # First try: look for an ordinary resource. This will succeed when # running from the source tree, but it is unlikely to succeed # if we're running out of any sort of installation. if pkg_resources.resource_isdir(__name__, 'guest'): return pkg_resources.resource_filename(__name__, 'guest') # Second try: look for a distribution resource. provider = pkg_resources.get_provider(__name__) if provider.egg_info is not None: dist = pkg_resources.Distribution.from_filename(provider.egg_root) req = dist.as_requirement() if pkg_resources.resource_isdir(req, 'share/virtme-guest-0'): return pkg_resources.resource_filename(req, 'share/virtme-guest-0') # No luck. This is somewhat surprising. return None def find_installed_guest_tools(root): def has_dir(path): # Don't use os.path.join: we want to treat absolute paths # as relative. return os.path.isdir(root + '/' + path) if has_dir('usr/local/share/virtme-guest-0'): return '/usr/local/share/virtme-guest-0' elif has_dir('usr/share/virtme-guest-0'): return 'usr/share/virtme-guest-0' else: return None def find_best_guest_tools(root): """Returns the path to the best choice of guest tools. This returns a tuple (in_guest, relative_path). If in_guest is true, then relative_path is guaranteed to be relative. """ # Always prefer the installed guest tools. This way blocking access # to /home is more likely to work. path = find_installed_guest_tools(root) if path is not None: return (True, path) # Now try the host's copy. This is here to keep root != '/' as consistent # as possible if root != '/': path = find_installed_guest_tools('/') if path is not None: return (False, path) # Now try the dist copy. path = find_dist_guest_tools() if path is not None: return (root == '/', os.path.relpath(path, '/')) return (None, None) virtme-0.0.2/virtme/mkinitramfs.py000066400000000000000000000120541243376340700172360ustar00rootroot00000000000000# -*- mode: python -*- # virtme-mkinitramfs: Generate an initramfs image for virtme # Copyright © 2014 Andy Lutomirski # Licensed under the GPLv2, which is available in the virtme distribution # as a file called LICENSE with SHA-256 hash: # 8177f97513213526df2cf6184d8ff986c675afb514d4e68a404010521b880643 import shutil import io import os.path import shlex from . import cpiowriter from . import modfinder from . import virtmods def make_base_layout(cw): for dir in (b'lib', b'bin', b'var', b'etc', b'newroot', b'dev', b'proc', b'tmproot', b'run_virtme', b'run_virtme/data', b'run_virtme/guesttools'): cw.mkdir(dir, 0o755) cw.symlink(b'bin', b'sbin') cw.symlink(b'lib', b'lib64') def make_dev_nodes(cw): cw.mkchardev(b'dev/null', (1, 3), mode=0o666) cw.mkchardev(b'dev/kmsg', (1, 11), mode=0o666) cw.mkchardev(b'dev/console', (5, 1), mode=0o660) def install_busybox(cw, config): with open(config.busybox, 'rb') as busybox: cw.write_file(name=b'bin/busybox', body=busybox, mode=0o755) for tool in ('sh', 'mount', 'umount', 'switch_root', 'sleep', 'mkdir', 'mknod', 'insmod', 'cp', 'cat'): cw.symlink(b'busybox', ('bin/%s' % tool).encode('ascii')) cw.mkdir(b'bin/real_progs', mode=0o755) def install_modprobe(cw): cw.write_file(name=b'bin/modprobe', body=b'\n'.join([ b'#!/bin/sh', b'echo "virtme: initramfs does not have module $3" >/dev/console', ]), mode=0o755) _LOGFUNC = """log() { if [[ -e /dev/kmsg ]]; then echo "<6>virtme initramfs: $*" >/dev/kmsg else echo "virtme initramfs: $*" fi } """ def install_modules(cw, modfiles): cw.mkdir(b'modules', 0o755) paths = [] for mod in modfiles: with open(mod, 'rb') as f: modpath = 'modules/' + os.path.basename(mod) paths.append(modpath) cw.write_file(name=modpath.encode('ascii'), body=f, mode=0o644) script = _LOGFUNC + '\n'.join('log \'loading %s...\'; insmod %s' % (os.path.basename(p), shlex.quote(p)) for p in paths) cw.write_file(name=b'modules/load_all.sh', body=script.encode('ascii'), mode=0o644) _INIT = """#!/bin/sh {logfunc} source /modules/load_all.sh log 'mounting hostfs...' if ! /bin/mount -n -t 9p -o ro,version=9p2000.L,trans=virtio,access=any /dev/root /newroot/; then echo "Failed to switch to real root. We are stuck." sleep 5 exit 1 fi # Can we actually use /newroot/ as root? if ! mount -t proc -o nosuid,noexec,nodev proc /newroot/proc 2>/dev/null; then # QEMU 1.5 and below have a bug in virtfs that prevents mounting # anything on top of a virtfs mount. log "your host's virtfs is broken -- using a fallback tmpfs" mount --move /newroot /tmproot mount -t tmpfs root_workaround /newroot/ cd tmproot mkdir /newroot/proc /newroot/sys /newroot/dev /newroot/run /newroot/tmp for i in *; do if [[ -d "$i" && \! -d "/newroot/$i" ]]; then mkdir /newroot/"$i" mount --bind "$i" /newroot/"$i" fi done mknod /newroot/dev/null c 1 3 mount -o remount,ro -t tmpfs root_workaround /newroot umount -l /tmproot else umount /newroot/proc # Don't leave garbage behind fi mount -t tmpfs run /newroot/run cp -a /run_virtme /newroot/run/virtme export virtme_run_mounted=1 # Find init mount -t proc none /proc for arg in `cat /proc/cmdline`; do if [[ "${{arg%%=*}}" = "init" ]]; then init="${{arg#init=}}" break fi done umount /proc if [[ -z "$init" ]]; then log 'no init= option' exit 1 fi if /bin/mount -n -t 9p -o ro,version=9p2000.L,trans=virtio,access=any virtme.guesttools /newroot/run/virtme/guesttools 2>/dev/null; then log 'using separate guest tools' fi log 'done; switching to real root' exec /bin/switch_root /newroot "$init" "$@" """ def generate_init(): out = io.StringIO() out.write(_INIT.format( logfunc=_LOGFUNC)) return out.getvalue().encode('utf-8') class Config: __slots__ = ['modfiles', 'virtme_data', 'virtme_init_path', 'busybox'] def __init__(self): self.modfiles = [] self.virtme_data = {} self.virtme_init_path = None self.busybox = None def mkinitramfs(out, config): cw = cpiowriter.CpioWriter(out) make_base_layout(cw) make_dev_nodes(cw) install_busybox(cw, config) install_modprobe(cw) if config.modfiles is not None: install_modules(cw, config.modfiles) for name,contents in config.virtme_data.items(): cw.write_file(b'/run_virtme/data/' + name, body=contents, mode=0o755) cw.write_file(b'init', body=generate_init(), mode=0o755) cw.write_trailer() def find_busybox(root, is_native): for path in ('usr/local/bin/busybox', 'usr/local/sbin/busybox', 'usr/bin/busybox', 'usr/sbin/busybox', 'bin/busybox', 'sbin/busybox'): if os.path.isfile(os.path.join(root, path)): return os.path.join(root, path) if is_native: # Try the host's busybox, if any return shutil.which('busybox') # We give up. return None virtme-0.0.2/virtme/modfinder.py000066400000000000000000000034251243376340700166630ustar00rootroot00000000000000# -*- mode: python -*- # modfinder: A simple tool to resolve required modules # Copyright © 2014 Andy Lutomirski # Licensed under the GPLv2, which is available in the virtme distribution # as a file called LICENSE with SHA-256 hash: # 8177f97513213526df2cf6184d8ff986c675afb514d4e68a404010521b880643 """ This is a poor man's module resolver and loader. It does not support any sort of hotplug. Instead it generates a topological order and loads everything. The idea is to require very few modules. """ import re import subprocess import os.path import itertools _INSMOD_RE = re.compile('insmod (.*[^ ]) *$') def resolve_dep(modalias, root=None, kver=None, moddir=None): args = ['modprobe', '--show-depends'] args += ['-C', '/var/empty'] if root is not None: args += ['-d', root] if kver is not None: args += ['-S', kver] if moddir is not None: args += ['--moddir', moddir] args += ['--', modalias] deps = [] try: with open('/dev/null', 'r+b') as devnull: script = subprocess.check_output(args, stderr=devnull.fileno()).\ decode('utf-8', errors='replace') for line in script.split('\n'): m = _INSMOD_RE.match(line) if m: deps.append(m.group(1)) except subprocess.CalledProcessError: pass # This is most likely because the module is built in. return deps def merge_mods(lists): found = set() mods = [] for mod in itertools.chain(*lists): if mod not in found: found.add(mod) mods.append(mod) return mods def find_modules_from_install(aliases, root=None, kver=None, moddir=None): return merge_mods(resolve_dep(a, root=root, kver=kver, moddir=moddir) for a in aliases) virtme-0.0.2/virtme/qemu_helpers.py000066400000000000000000000022141243376340700174000ustar00rootroot00000000000000# -*- mode: python -*- # qemu_helpers: Helpers to find QEMU and handle its quirks # Copyright © 2014 Andy Lutomirski # Licensed under the GPLv2, which is available in the virtme distribution # as a file called LICENSE with SHA-256 hash: # 8177f97513213526df2cf6184d8ff986c675afb514d4e68a404010521b880643 import os import re import shutil import subprocess class Qemu(object): def __init__(self, arch): self.arch = arch self.qemubin = shutil.which('qemu-system-%s' % arch) if self.qemubin is None and arch == os.uname().machine: self.qemubin = shutil.which('qemu-kvm') if self.qemubin is None: raise ValueError('cannot find qemu for %s' % arch) self.version = None def probe(self): if self.version is None: self.version = subprocess.check_output([self.qemubin, '--version'])\ .decode('utf-8') self.cannot_overmount_virtfs = ( re.search(r'version 1\.[012345]', self.version) is not None) def quote_optarg(self, a): """Quote an argument to an option.""" return a.replace(',', ',,') virtme-0.0.2/virtme/virtmods.py000066400000000000000000000017551243376340700165670ustar00rootroot00000000000000# -*- mode: python -*- # virtmods: Default module configuration # Copyright © 2014 Andy Lutomirski # Licensed under the GPLv2, which is available in the virtme distribution # as a file called LICENSE with SHA-256 hash: # 8177f97513213526df2cf6184d8ff986c675afb514d4e68a404010521b880643 MODALIASES = [ # These are most likely portable across all architectures. 'fs-9p', 'virtio:d00000009v00001AF4', # 9pnet_virtio 'virtio:d00000003v00001AF4', # virtio_console # For virtio_pci architectures (which are, hopefully, all that we care # about), there's really only one required driver, virtio_pci. # For completeness, here are both of the instances we care about # for basic functionality. 'pci:v00001AF4d00001009sv00001AF4sd00000009bc00sc02i00', # 9pnet 'pci:v00001AF4d00001003sv00001AF4sd00000003bc07sc80i00', # virtconsole # Basic system functionality 'unix', # UNIX sockets, needed by udev # Basic emulated hardware 'i8042', 'atkbd', ]