Index: head/stand/libsa/environment.c =================================================================== --- head/stand/libsa/environment.c (revision 326608) +++ head/stand/libsa/environment.c (revision 326609) @@ -1,223 +1,223 @@ /* * Copyright (c) 1998 Michael Smith. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include __FBSDID("$FreeBSD$"); /* * Manage an environment-like space in which string variables may be stored. * Provide support for some method-like operations for setting/retrieving * variables in order to allow some type strength. */ #include "stand.h" #include static void env_discard(struct env_var *ev); struct env_var *environ = NULL; /* * Look up (name) and return it's env_var structure. */ struct env_var * env_getenv(const char *name) { struct env_var *ev; for (ev = environ; ev != NULL; ev = ev->ev_next) if (!strcmp(ev->ev_name, name)) break; return(ev); } /* * Some notes: * * If the EV_VOLATILE flag is set, a copy of the variable is made. * If EV_DYNAMIC is set, the variable has been allocated with * malloc and ownership transferred to the environment. * If (value) is NULL, the variable is set but has no value. */ int env_setenv(const char *name, int flags, const void *value, ev_sethook_t sethook, ev_unsethook_t unsethook) { struct env_var *ev, *curr, *last; if ((ev = env_getenv(name)) != NULL) { /* * If there's a set hook, let it do the work (unless we are working * for one already. */ if ((ev->ev_sethook != NULL) && !(flags & EV_NOHOOK)) return (ev->ev_sethook(ev, flags, value)); /* If there is data in the variable, discard it. */ if (ev->ev_value != NULL && (ev->ev_flags & EV_DYNAMIC) != 0) free(ev->ev_value); ev->ev_value = NULL; ev->ev_flags &= ~EV_DYNAMIC; } else { /* * New variable; create and sort into list */ ev = malloc(sizeof(struct env_var)); ev->ev_name = strdup(name); ev->ev_value = NULL; ev->ev_flags = 0; /* hooks can only be set when the variable is instantiated */ ev->ev_sethook = sethook; ev->ev_unsethook = unsethook; /* Sort into list */ ev->ev_prev = NULL; ev->ev_next = NULL; /* Search for the record to insert before */ for (last = NULL, curr = environ; curr != NULL; last = curr, curr = curr->ev_next) { if (strcmp(ev->ev_name, curr->ev_name) < 0) { if (curr->ev_prev) { curr->ev_prev->ev_next = ev; } else { environ = ev; } ev->ev_next = curr; ev->ev_prev = curr->ev_prev; curr->ev_prev = ev; break; } } if (curr == NULL) { if (last == NULL) { environ = ev; } else { last->ev_next = ev; ev->ev_prev = last; } } } /* If we have a new value, use it */ if (flags & EV_VOLATILE) { ev->ev_value = strdup(value); ev->ev_flags |= EV_DYNAMIC; } else { ev->ev_value = (char *)value; ev->ev_flags |= flags & EV_DYNAMIC; } return(0); } char * getenv(const char *name) { struct env_var *ev; /* Set but no value gives empty string */ if ((ev = env_getenv(name)) != NULL) { if (ev->ev_value != NULL) return(ev->ev_value); return(""); } return(NULL); } int setenv(const char *name, const char *value, int overwrite) { /* No guarantees about state, always assume volatile */ if (overwrite || (env_getenv(name) == NULL)) return(env_setenv(name, EV_VOLATILE, value, NULL, NULL)); return(0); } int -putenv(const char *string) +putenv(char *string) { char *value, *copy; int result; copy = strdup(string); if ((value = strchr(copy, '=')) != NULL) *(value++) = 0; result = setenv(copy, value, 1); free(copy); return(result); } int unsetenv(const char *name) { struct env_var *ev; int err; err = 0; if ((ev = env_getenv(name)) == NULL) { err = ENOENT; } else { if (ev->ev_unsethook != NULL) err = ev->ev_unsethook(ev); if (err == 0) { env_discard(ev); } } return(err); } static void env_discard(struct env_var *ev) { if (ev->ev_prev) ev->ev_prev->ev_next = ev->ev_next; if (ev->ev_next) ev->ev_next->ev_prev = ev->ev_prev; if (environ == ev) environ = ev->ev_next; free(ev->ev_name); if (ev->ev_value != NULL && (ev->ev_flags & EV_DYNAMIC) != 0) free(ev->ev_value); free(ev); } int env_noset(struct env_var *ev __unused, int flags __unused, const void *value __unused) { return(EPERM); } int env_nounset(struct env_var *ev __unused) { return(EPERM); } Index: head/stand/libsa/libstand.3 =================================================================== --- head/stand/libsa/libstand.3 (revision 326608) +++ head/stand/libsa/libstand.3 (revision 326609) @@ -1,676 +1,676 @@ .\" Copyright (c) Michael Smith .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" .\" THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF .\" SUCH DAMAGE. .\" .\" $FreeBSD$ .\" .Dd August 6, 2004 .Dt LIBSTAND 3 .Os .Sh NAME .Nm libstand .Nd support library for standalone executables .Sh SYNOPSIS .In stand.h .Sh DESCRIPTION The .Nm library provides a set of supporting functions for standalone applications, mimicking where possible the standard .Bx programming environment. The following sections group these functions by kind. Unless specifically described here, see the corresponding section 3 manpages for the given functions. .Sh STRING FUNCTIONS String functions are available as documented in .Xr string 3 and .Xr bstring 3 . .Sh MEMORY ALLOCATION .Bl -hang -width 10n .It Xo .Ft "void *" .Fn malloc "size_t size" .Xc .Pp Allocate .Fa size bytes of memory from the heap using a best-fit algorithm. .It Xo .Ft void .Fn free "void *ptr" .Xc .Pp Free the allocated object at .Fa ptr . .It Xo .Ft void .Fn setheap "void *start" "void *limit" .Xc .Pp Initialise the heap. This function must be called before calling .Fn alloc for the first time. The region between .Fa start and .Fa limit will be used for the heap; attempting to allocate beyond this will result in a panic. .It Xo .Ft "char *" .Fn sbrk "int junk" .Xc .Pp Provides the behaviour of .Fn sbrk 0 , i.e., returns the highest point that the heap has reached. This value can be used during testing to determine the actual heap usage. The .Fa junk argument is ignored. .El .Sh ENVIRONMENT A set of functions are provided for manipulating a flat variable space similar to the traditional shell-supported environment. Major enhancements are support for set/unset hook functions. .Bl -hang -width 10n .It Xo .Ft "char *" .Fn getenv "const char *name" .Xc .It Xo .Ft int .Fn setenv "const char *name" "const char *value" "int overwrite" .Xc .It Xo .Ft int -.Fn putenv "const char *string" +.Fn putenv "char *string" .Xc .It Xo .Ft int .Fn unsetenv "const char *name" .Xc .Pp These functions behave similarly to their standard library counterparts. .It Xo .Ft "struct env_var *" .Fn env_getenv "const char *name" .Xc .Pp Looks up a variable in the environment and returns its entire data structure. .It Xo .Ft int .Fn env_setenv "const char *name" "int flags" "const void *value" "ev_sethook_t sethook" "ev_unsethook_t unsethook" .Xc .Pp Creates a new or sets an existing environment variable called .Fa name . If creating a new variable, the .Fa sethook and .Fa unsethook arguments may be specified. .Pp The set hook is invoked whenever an attempt is made to set the variable, unless the EV_NOHOOK flag is set. Typically a set hook will validate the .Fa value argument, and then call .Fn env_setenv again with EV_NOHOOK set to actually save the value. The predefined function .Fn env_noset may be specified to refuse all attempts to set a variable. .Pp The unset hook is invoked when an attempt is made to unset a variable. If it returns zero, the variable will be unset. The predefined function .Fa env_nounset may be used to prevent a variable being unset. .El .Sh STANDARD LIBRARY SUPPORT .Bl -hang -width 10n .It Xo .Ft int .Fn getopt "int argc" "char * const *argv" "const char *optstring" .Xc .It Xo .Ft long .Fn strtol "const char *nptr" "char **endptr" "int base" .Xc .It Xo .Ft void .Fn srandom "unsigned int seed" .Xc .It Xo .Ft "long" .Fn random void .Xc .It Xo .Ft "char *" .Fn strerror "int error" .Xc .Pp Returns error messages for the subset of errno values supported by .Nm . .It Fn assert expression .Pp Requires .In assert.h . .It Xo .Ft int .Fn setjmp "jmp_buf env" .Xc .It Xo .Ft void .Fn longjmp "jmp_buf env" "int val" .Xc .Pp Defined as .Fn _setjmp and .Fn _longjmp respectively as there is no signal state to manipulate. Requires .In setjmp.h . .El .Sh CHARACTER I/O .Bl -hang -width 10n .It Xo .Ft void .Fn gets "char *buf" .Xc .Pp Read characters from the console into .Fa buf . All of the standard cautions apply to this function. .It Xo .Ft void .Fn ngets "char *buf" "int size" .Xc .Pp Read at most .Fa size - 1 characters from the console into .Fa buf . If .Fa size is less than 1, the function's behaviour is as for .Fn gets . .It Xo .Ft int .Fn fgetstr "char *buf" "int size" "int fd" .Xc .Pp Read a line of at most .Fa size characters into .Fa buf . Line terminating characters are stripped, and the buffer is always .Dv NUL terminated. Returns the number of characters in .Fa buf if successful, or -1 if a read error occurs. .It Xo .Ft int .Fn printf "const char *fmt" "..." .Xc .It Xo .Ft void .Fn vprintf "const char *fmt" "va_list ap" .Xc .It Xo .Ft int .Fn sprintf "char *buf" "const char *fmt" "..." .Xc .It Xo .Ft void .Fn vsprintf "char *buf" "const char *fmt" "va_list ap" .Xc .Pp The *printf functions implement a subset of the standard .Fn printf family functionality and some extensions. The following standard conversions are supported: c,d,n,o,p,s,u,x. The following modifiers are supported: +,-,#,*,0,field width,precision,l. .Pp The .Li b conversion is provided to decode error registers. Its usage is: .Bd -ragged -offset indent printf( .Qq reg=%b\en , regval, .Qq * ); .Ed .Pp where is the output expressed as a control character, e.g.\& \e10 gives octal, \e20 gives hex. Each is a sequence of characters, the first of which gives the bit number to be inspected (origin 1) and the next characters (up to a character less than 32) give the text to be displayed if the bit is set. Thus .Bd -ragged -offset indent printf( .Qq reg=%b\en , 3, .Qq \e10\e2BITTWO\e1BITONE ); .Ed .Pp would give the output .Bd -ragged -offset indent reg=3 .Ed .Pp The .Li D conversion provides a hexdump facility, e.g. .Bd -ragged -offset indent printf( .Qq %6D , ptr, .Qq \&: ); gives .Qq XX:XX:XX:XX:XX:XX .Ed .Bd -ragged -offset indent printf( .Qq %*D , len, ptr, .Qq "\ " ); gives .Qq XX XX XX ... .Ed .El .Sh CHARACTER TESTS AND CONVERSIONS .Bl -hang -width 10n .It Xo .Ft int .Fn isupper "int c" .Xc .It Xo .Ft int .Fn islower "int c" .Xc .It Xo .Ft int .Fn isspace "int c" .Xc .It Xo .Ft int .Fn isdigit "int c" .Xc .It Xo .Ft int .Fn isxdigit "int c" .Xc .It Xo .Ft int .Fn isascii "int c" .Xc .It Xo .Ft int .Fn isalpha "int c" .Xc .It Xo .Ft int .Fn toupper "int c" .Xc .It Xo .Ft int .Fn tolower "int c" .Xc .El .Sh FILE I/O .Bl -hang -width 10n .It Xo .Ft int .Fn open "const char *path" "int flags" .Xc .Pp Similar to the behaviour as specified in .Xr open 2 , except that file creation is not supported, so the mode parameter is not required. The .Fa flags argument may be one of O_RDONLY, O_WRONLY and O_RDWR (although no file systems currently support writing). .It Xo .Ft int .Fn close "int fd" .Xc .It Xo .Ft void .Fn closeall void .Xc .Pp Close all open files. .It Xo .Ft ssize_t .Fn read "int fd" "void *buf" "size_t len" .Xc .It Xo .Ft ssize_t .Fn write "int fd" "void *buf" "size_t len" .Xc .Pp (No file systems currently support writing.) .It Xo .Ft off_t .Fn lseek "int fd" "off_t offset" "int whence" .Xc .Pp Files being automatically uncompressed during reading cannot seek backwards from the current point. .It Xo .Ft int .Fn stat "const char *path" "struct stat *sb" .Xc .It Xo .Ft int .Fn fstat "int fd" "struct stat *sb" .Xc .Pp The .Fn stat and .Fn fstat functions only fill out the following fields in the .Fa sb structure: st_mode,st_nlink,st_uid,st_gid,st_size. The .Nm tftp file system cannot provide meaningful values for this call, and the .Nm cd9660 file system always reports files having uid/gid of zero. .El .Sh PAGER The .Nm library supplies a simple internal pager to ease reading the output of large commands. .Bl -hang -width 10n .It Xo .Ft void .Fn pager_open .Xc .Pp Initialises the pager and tells it that the next line output will be the top of the display. The environment variable LINES is consulted to determine the number of lines to be displayed before pausing. .It Xo .Ft void .Fn pager_close void .Xc .Pp Closes the pager. .It Xo .Ft int .Fn pager_output "const char *lines" .Xc .Pp Sends the lines in the .Dv NUL Ns -terminated buffer at .Fa lines to the pager. Newline characters are counted in order to determine the number of lines being output (wrapped lines are not accounted for). The .Fn pager_output function will return zero when all of the lines have been output, or nonzero if the display was paused and the user elected to quit. .It Xo .Ft int .Fn pager_file "const char *fname" .Xc .Pp Attempts to open and display the file .Fa fname . Returns -1 on error, 0 at EOF, or 1 if the user elects to quit while reading. .El .Sh MISC .Bl -hang -width 10n .It Xo .Ft void .Fn twiddle void .Xc .Pp Successive calls emit the characters in the sequence |,/,-,\\ followed by a backspace in order to provide reassurance to the user. .El .Sh REQUIRED LOW-LEVEL SUPPORT The following resources are consumed by .Nm - stack, heap, console and devices. .Pp The stack must be established before .Nm functions can be invoked. Stack requirements vary depending on the functions and file systems used by the consumer and the support layer functions detailed below. .Pp The heap must be established before calling .Fn alloc or .Fn open by calling .Fn setheap . Heap usage will vary depending on the number of simultaneously open files, as well as client behaviour. Automatic decompression will allocate more than 64K of data per open file. .Pp Console access is performed via the .Fn getchar , .Fn putchar and .Fn ischar functions detailed below. .Pp Device access is initiated via .Fn devopen and is performed through the .Fn dv_strategy , .Fn dv_ioctl and .Fn dv_close functions in the device switch structure that .Fn devopen returns. .Pp The consumer must provide the following support functions: .Bl -hang -width 10n .It Xo .Ft int .Fn getchar void .Xc .Pp Return a character from the console, used by .Fn gets , .Fn ngets and pager functions. .It Xo .Ft int .Fn ischar void .Xc .Pp Returns nonzero if a character is waiting from the console. .It Xo .Ft void .Fn putchar int .Xc .Pp Write a character to the console, used by .Fn gets , .Fn ngets , .Fn *printf , .Fn panic and .Fn twiddle and thus by many other functions for debugging and informational output. .It Xo .Ft int .Fn devopen "struct open_file *of" "const char *name" "const char **file" .Xc .Pp Open the appropriate device for the file named in .Fa name , returning in .Fa file a pointer to the remaining body of .Fa name which does not refer to the device. The .Va f_dev field in .Fa of will be set to point to the .Vt devsw structure for the opened device if successful. Device identifiers must always precede the path component, but may otherwise be arbitrarily formatted. Used by .Fn open and thus for all device-related I/O. .It Xo .Ft int .Fn devclose "struct open_file *of" .Xc .Pp Close the device allocated for .Fa of . The device driver itself will already have been called for the close; this call should clean up any allocation made by devopen only. .It Xo .Ft void .Fn panic "const char *msg" "..." .Xc .Pp Signal a fatal and unrecoverable error condition. The .Fa msg ... arguments are as for .Fn printf . .El .Sh INTERNAL FILE SYSTEMS Internal file systems are enabled by the consumer exporting the array .Vt struct fs_ops *file_system[] , which should be initialised with pointers to .Vt struct fs_ops structures. The following file system handlers are supplied by .Nm , the consumer may supply other file systems of their own: .Bl -hang -width ".Va cd9660_fsops" .It Va ufs_fsops The .Bx UFS. .It Va ext2fs_fsops Linux ext2fs file system. .It Va tftp_fsops File access via TFTP. .It Va nfs_fsops File access via NFS. .It Va cd9660_fsops ISO 9660 (CD-ROM) file system. .It Va gzipfs_fsops Stacked file system supporting gzipped files. When trying the gzipfs file system, .Nm appends .Li .gz to the end of the filename, and then tries to locate the file using the other file systems. Placement of this file system in the .Va file_system[] array determines whether gzipped files will be opened in preference to non-gzipped files. It is only possible to seek a gzipped file forwards, and .Fn stat and .Fn fstat on gzipped files will report an invalid length. .It Va bzipfs_fsops The same as .Va gzipfs_fsops , but for .Xr bzip2 1 Ns -compressed files. .El .Pp The array of .Vt struct fs_ops pointers should be terminated with a NULL. .Sh DEVICES Devices are exported by the supporting code via the array .Vt struct devsw *devsw[] which is a NULL terminated array of pointers to device switch structures. .Sh HISTORY The .Nm library contains contributions from many sources, including: .Bl -bullet -compact .It .Nm libsa from .Nx .It .Nm libc and .Nm libkern from .Fx 3.0 . .It .Nm zalloc from .An Matthew Dillon Aq Mt dillon@backplane.com .El .Pp The reorganisation and port to .Fx 3.0 , the environment functions and this manpage were written by .An Mike Smith Aq Mt msmith@FreeBSD.org . .Sh BUGS The lack of detailed memory usage data is unhelpful. Index: head/stand/libsa/stand.h =================================================================== --- head/stand/libsa/stand.h (revision 326608) +++ head/stand/libsa/stand.h (revision 326609) @@ -1,426 +1,426 @@ /* * Copyright (c) 1998 Michael Smith. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD$ * From $NetBSD: stand.h,v 1.22 1997/06/26 19:17:40 drochner Exp $ */ /*- * Copyright (c) 1993 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * @(#)stand.h 8.1 (Berkeley) 6/11/93 */ #ifndef STAND_H #define STAND_H #include #include #include #include /* this header intentionally exports NULL from */ #include #define CHK(fmt, args...) printf("%s(%d): " fmt "\n", __func__, __LINE__ , ##args) #define PCHK(fmt, args...) {printf("%s(%d): " fmt "\n", __func__, __LINE__ , ##args); getchar();} /* Avoid unwanted userlandish components */ #define _KERNEL #include #undef _KERNEL /* special stand error codes */ #define EADAPT (ELAST+1) /* bad adaptor */ #define ECTLR (ELAST+2) /* bad controller */ #define EUNIT (ELAST+3) /* bad unit */ #define ESLICE (ELAST+4) /* bad slice */ #define EPART (ELAST+5) /* bad partition */ #define ERDLAB (ELAST+6) /* can't read disk label */ #define EUNLAB (ELAST+7) /* unlabeled disk */ #define EOFFSET (ELAST+8) /* relative seek not supported */ #define ESALAST (ELAST+8) /* */ struct open_file; /* * This structure is used to define file system operations in a file system * independent way. * * XXX note that filesystem providers should export a pointer to their fs_ops * struct, so that consumers can reference this and thus include the * filesystems that they require. */ struct fs_ops { const char *fs_name; int (*fo_open)(const char *path, struct open_file *f); int (*fo_close)(struct open_file *f); int (*fo_read)(struct open_file *f, void *buf, size_t size, size_t *resid); int (*fo_write)(struct open_file *f, void *buf, size_t size, size_t *resid); off_t (*fo_seek)(struct open_file *f, off_t offset, int where); int (*fo_stat)(struct open_file *f, struct stat *sb); int (*fo_readdir)(struct open_file *f, struct dirent *d); }; /* * libstand-supplied filesystems */ extern struct fs_ops ufs_fsops; extern struct fs_ops tftp_fsops; extern struct fs_ops nfs_fsops; extern struct fs_ops cd9660_fsops; extern struct fs_ops nandfs_fsops; extern struct fs_ops gzipfs_fsops; extern struct fs_ops bzipfs_fsops; extern struct fs_ops dosfs_fsops; extern struct fs_ops ext2fs_fsops; extern struct fs_ops splitfs_fsops; extern struct fs_ops pkgfs_fsops; /* where values for lseek(2) */ #define SEEK_SET 0 /* set file offset to offset */ #define SEEK_CUR 1 /* set file offset to current plus offset */ #define SEEK_END 2 /* set file offset to EOF plus offset */ /* * Device switch */ struct devsw { const char dv_name[8]; int dv_type; /* opaque type constant, arch-dependant */ int (*dv_init)(void); /* early probe call */ int (*dv_strategy)(void *devdata, int rw, daddr_t blk, size_t size, char *buf, size_t *rsize); int (*dv_open)(struct open_file *f, ...); int (*dv_close)(struct open_file *f); int (*dv_ioctl)(struct open_file *f, u_long cmd, void *data); int (*dv_print)(int verbose); /* print device information */ void (*dv_cleanup)(void); }; /* * libstand-supplied device switch */ extern struct devsw netdev; extern int errno; /* * Generic device specifier; architecture-dependent * versions may be larger, but should be allowed to * overlap. */ struct devdesc { struct devsw *d_dev; int d_type; #define DEVT_NONE 0 #define DEVT_DISK 1 #define DEVT_NET 2 #define DEVT_CD 3 #define DEVT_ZFS 4 #define DEVT_FD 5 int d_unit; void *d_opendata; }; struct open_file { int f_flags; /* see F_* below */ struct devsw *f_dev; /* pointer to device operations */ void *f_devdata; /* device specific data */ struct fs_ops *f_ops; /* pointer to file system operations */ void *f_fsdata; /* file system specific data */ off_t f_offset; /* current file offset */ char *f_rabuf; /* readahead buffer pointer */ size_t f_ralen; /* valid data in readahead buffer */ off_t f_raoffset; /* consumer offset in readahead buffer */ #define SOPEN_RASIZE 512 }; #define SOPEN_MAX 64 extern struct open_file files[]; /* f_flags values */ #define F_READ 0x0001 /* file opened for reading */ #define F_WRITE 0x0002 /* file opened for writing */ #define F_RAW 0x0004 /* raw device open - no file system */ #define F_NODEV 0x0008 /* network open - no device */ #define F_MASK 0xFFFF /* Mode modifier for strategy() */ #define F_NORA (0x01 << 16) /* Disable Read-Ahead */ #define isascii(c) (((c) & ~0x7F) == 0) static __inline int isupper(int c) { return c >= 'A' && c <= 'Z'; } static __inline int islower(int c) { return c >= 'a' && c <= 'z'; } static __inline int isspace(int c) { return c == ' ' || (c >= 0x9 && c <= 0xd); } static __inline int isdigit(int c) { return c >= '0' && c <= '9'; } static __inline int isxdigit(int c) { return isdigit(c) || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'); } static __inline int isalpha(int c) { return isupper(c) || islower(c); } static __inline int isalnum(int c) { return isalpha(c) || isdigit(c); } static __inline int toupper(int c) { return islower(c) ? c - 'a' + 'A' : c; } static __inline int tolower(int c) { return isupper(c) ? c - 'A' + 'a' : c; } /* sbrk emulation */ extern void setheap(void *base, void *top); extern char *sbrk(int incr); /* Matt Dillon's zalloc/zmalloc */ extern void *malloc(size_t bytes); extern void free(void *ptr); /*#define free(p) {CHK("free %p", p); free(p);} */ /* use for catching guard violations */ extern void *calloc(size_t n1, size_t n2); extern void *realloc(void *ptr, size_t size); extern void *reallocf(void *ptr, size_t size); extern void mallocstats(void); extern int printf(const char *fmt, ...) __printflike(1, 2); extern void vprintf(const char *fmt, __va_list); extern int sprintf(char *buf, const char *cfmt, ...) __printflike(2, 3); extern int snprintf(char *buf, size_t size, const char *cfmt, ...) __printflike(3, 4); extern void vsprintf(char *buf, const char *cfmt, __va_list); extern void twiddle(u_int callerdiv); extern void twiddle_divisor(u_int globaldiv); extern void ngets(char *, int); #define gets(x) ngets((x), 0) extern int fgetstr(char *buf, int size, int fd); extern int open(const char *, int); #define O_RDONLY 0x0 #define O_WRONLY 0x1 #define O_RDWR 0x2 extern int close(int); extern void closeall(void); extern ssize_t read(int, void *, size_t); extern ssize_t write(int, void *, size_t); extern struct dirent *readdirfd(int); extern void srandom(unsigned int); extern u_long random(void); /* imports from stdlib, locally modified */ extern long strtol(const char *, char **, int); extern unsigned long strtoul(const char *, char **, int); extern char *optarg; /* getopt(3) external variables */ extern int optind, opterr, optopt, optreset; extern int getopt(int, char * const [], const char *); /* pager.c */ extern void pager_open(void); extern void pager_close(void); extern int pager_output(const char *lines); extern int pager_file(const char *fname); /* No signal state to preserve */ #define setjmp _setjmp #define longjmp _longjmp /* environment.c */ #define EV_DYNAMIC (1<<0) /* value was dynamically allocated, free if changed/unset */ #define EV_VOLATILE (1<<1) /* value is volatile, make a copy of it */ #define EV_NOHOOK (1<<2) /* don't call hook when setting */ struct env_var; typedef char *(ev_format_t)(struct env_var *ev); typedef int (ev_sethook_t)(struct env_var *ev, int flags, const void *value); typedef int (ev_unsethook_t)(struct env_var *ev); struct env_var { char *ev_name; int ev_flags; void *ev_value; ev_sethook_t *ev_sethook; ev_unsethook_t *ev_unsethook; struct env_var *ev_next, *ev_prev; }; extern struct env_var *environ; extern struct env_var *env_getenv(const char *name); extern int env_setenv(const char *name, int flags, const void *value, ev_sethook_t sethook, ev_unsethook_t unsethook); extern char *getenv(const char *name); extern int setenv(const char *name, const char *value, int overwrite); -extern int putenv(const char *string); +extern int putenv(char *string); extern int unsetenv(const char *name); extern ev_sethook_t env_noset; /* refuse set operation */ extern ev_unsethook_t env_nounset; /* refuse unset operation */ /* BCD conversions (undocumented) */ extern u_char const bcd2bin_data[]; extern u_char const bin2bcd_data[]; extern char const hex2ascii_data[]; #define bcd2bin(bcd) (bcd2bin_data[bcd]) #define bin2bcd(bin) (bin2bcd_data[bin]) #define hex2ascii(hex) (hex2ascii_data[hex]) /* min/max (undocumented) */ static __inline int imax(int a, int b) { return (a > b ? a : b); } static __inline int imin(int a, int b) { return (a < b ? a : b); } static __inline long lmax(long a, long b) { return (a > b ? a : b); } static __inline long lmin(long a, long b) { return (a < b ? a : b); } static __inline u_int max(u_int a, u_int b) { return (a > b ? a : b); } static __inline u_int min(u_int a, u_int b) { return (a < b ? a : b); } static __inline quad_t qmax(quad_t a, quad_t b) { return (a > b ? a : b); } static __inline quad_t qmin(quad_t a, quad_t b) { return (a < b ? a : b); } static __inline u_long ulmax(u_long a, u_long b) { return (a > b ? a : b); } static __inline u_long ulmin(u_long a, u_long b) { return (a < b ? a : b); } /* null functions for device/filesystem switches (undocumented) */ extern int nodev(void); extern int noioctl(struct open_file *, u_long, void *); extern void nullsys(void); extern int null_open(const char *path, struct open_file *f); extern int null_close(struct open_file *f); extern int null_read(struct open_file *f, void *buf, size_t size, size_t *resid); extern int null_write(struct open_file *f, void *buf, size_t size, size_t *resid); extern off_t null_seek(struct open_file *f, off_t offset, int where); extern int null_stat(struct open_file *f, struct stat *sb); extern int null_readdir(struct open_file *f, struct dirent *d); /* * Machine dependent functions and data, must be provided or stubbed by * the consumer */ extern void exit(int); extern int getchar(void); extern int ischar(void); extern void putchar(int); extern int devopen(struct open_file *, const char *, const char **); extern int devclose(struct open_file *f); extern void panic(const char *, ...) __dead2 __printflike(1, 2); extern struct fs_ops *file_system[]; extern struct fs_ops *exclusive_file_system; extern struct devsw *devsw[]; /* * Expose byteorder(3) functions. */ #ifndef _BYTEORDER_PROTOTYPED #define _BYTEORDER_PROTOTYPED extern uint32_t htonl(uint32_t); extern uint16_t htons(uint16_t); extern uint32_t ntohl(uint32_t); extern uint16_t ntohs(uint16_t); #endif #ifndef _BYTEORDER_FUNC_DEFINED #define _BYTEORDER_FUNC_DEFINED #define htonl(x) __htonl(x) #define htons(x) __htons(x) #define ntohl(x) __ntohl(x) #define ntohs(x) __ntohs(x) #endif void *Malloc(size_t, const char *, int); void *Calloc(size_t, size_t, const char *, int); void *Realloc(void *, size_t, const char *, int); void Free(void *, const char *, int); #if 1 #define malloc(x) Malloc(x, __FILE__, __LINE__) #define calloc(x, y) Calloc(x, y, __FILE__, __LINE__) #define free(x) Free(x, __FILE__, __LINE__) #define realloc(x, y) Realloc(x, y, __FILE__, __LINE__) #else #define malloc(x) Malloc(x, NULL, 0) #define calloc(x, y) Calloc(x, y, NULL, 0) #define free(x) Free(x, NULL, 0) #define realloc(x, y) Realloc(x, y, NULL, 0) #endif #endif /* STAND_H */ Index: head/stand/userboot/test/test.c =================================================================== --- head/stand/userboot/test/test.c (revision 326608) +++ head/stand/userboot/test/test.c (revision 326609) @@ -1,475 +1,475 @@ /*- * Copyright (c) 2011 Google, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD$ */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include char *host_base = NULL; struct termios term, oldterm; char *image; size_t image_size; int disk_fd = -1; uint64_t regs[16]; uint64_t pc; void test_exit(void *arg, int v); /* * Console i/o */ void test_putc(void *arg, int ch) { char c = ch; write(1, &c, 1); } int test_getc(void *arg) { char c; if (read(0, &c, 1) == 1) return c; return -1; } int test_poll(void *arg) { int n; if (ioctl(0, FIONREAD, &n) >= 0) return (n > 0); return (0); } /* * Host filesystem i/o */ struct test_file { int tf_isdir; size_t tf_size; struct stat tf_stat; union { int fd; DIR *dir; } tf_u; }; int test_open(void *arg, const char *filename, void **h_return) { struct stat st; struct test_file *tf; char path[PATH_MAX]; if (!host_base) return (ENOENT); strlcpy(path, host_base, PATH_MAX); if (path[strlen(path) - 1] == '/') path[strlen(path) - 1] = 0; strlcat(path, filename, PATH_MAX); tf = malloc(sizeof(struct test_file)); if (stat(path, &tf->tf_stat) < 0) { free(tf); return (errno); } tf->tf_size = st.st_size; if (S_ISDIR(tf->tf_stat.st_mode)) { tf->tf_isdir = 1; tf->tf_u.dir = opendir(path); if (!tf->tf_u.dir) goto out; *h_return = tf; return (0); } if (S_ISREG(tf->tf_stat.st_mode)) { tf->tf_isdir = 0; tf->tf_u.fd = open(path, O_RDONLY); if (tf->tf_u.fd < 0) goto out; *h_return = tf; return (0); } out: free(tf); return (EINVAL); } int test_close(void *arg, void *h) { struct test_file *tf = h; if (tf->tf_isdir) closedir(tf->tf_u.dir); else close(tf->tf_u.fd); free(tf); return (0); } int test_isdir(void *arg, void *h) { struct test_file *tf = h; return (tf->tf_isdir); } int test_read(void *arg, void *h, void *dst, size_t size, size_t *resid_return) { struct test_file *tf = h; ssize_t sz; if (tf->tf_isdir) return (EINVAL); sz = read(tf->tf_u.fd, dst, size); if (sz < 0) return (EINVAL); *resid_return = size - sz; return (0); } int test_readdir(void *arg, void *h, uint32_t *fileno_return, uint8_t *type_return, size_t *namelen_return, char *name) { struct test_file *tf = h; struct dirent *dp; if (!tf->tf_isdir) return (EINVAL); dp = readdir(tf->tf_u.dir); if (!dp) return (ENOENT); /* * Note: d_namlen is in the range 0..255 and therefore less * than PATH_MAX so we don't need to test before copying. */ *fileno_return = dp->d_fileno; *type_return = dp->d_type; *namelen_return = dp->d_namlen; memcpy(name, dp->d_name, dp->d_namlen); name[dp->d_namlen] = 0; return (0); } int test_seek(void *arg, void *h, uint64_t offset, int whence) { struct test_file *tf = h; if (tf->tf_isdir) return (EINVAL); if (lseek(tf->tf_u.fd, offset, whence) < 0) return (errno); return (0); } int test_stat(void *arg, void *h, int *mode_return, int *uid_return, int *gid_return, uint64_t *size_return) { struct test_file *tf = h; *mode_return = tf->tf_stat.st_mode; *uid_return = tf->tf_stat.st_uid; *gid_return = tf->tf_stat.st_gid; *size_return = tf->tf_stat.st_size; return (0); } /* * Disk image i/o */ int test_diskread(void *arg, int unit, uint64_t offset, void *dst, size_t size, size_t *resid_return) { ssize_t n; if (unit != 0 || disk_fd == -1) return (EIO); n = pread(disk_fd, dst, size, offset); if (n < 0) return (errno); *resid_return = size - n; return (0); } int test_diskioctl(void *arg, int unit, u_long cmd, void *data) { struct stat sb; if (unit != 0 || disk_fd == -1) return (EBADF); switch (cmd) { case DIOCGSECTORSIZE: *(u_int *)data = 512; break; case DIOCGMEDIASIZE: if (fstat(disk_fd, &sb) == 0) *(off_t *)data = sb.st_size; else return (ENOTTY); break; default: return (ENOTTY); } return (0); } /* * Guest virtual machine i/o * * Note: guest addresses are kernel virtual */ int test_copyin(void *arg, const void *from, uint64_t to, size_t size) { to &= 0x7fffffff; if (to > image_size) return (EFAULT); if (to + size > image_size) size = image_size - to; memcpy(&image[to], from, size); return(0); } int test_copyout(void *arg, uint64_t from, void *to, size_t size) { from &= 0x7fffffff; if (from > image_size) return (EFAULT); if (from + size > image_size) size = image_size - from; memcpy(to, &image[from], size); return(0); } void test_setreg(void *arg, int r, uint64_t v) { if (r < 0 || r >= 16) return; regs[r] = v; } void test_setmsr(void *arg, int r, uint64_t v) { } void test_setcr(void *arg, int r, uint64_t v) { } void test_setgdt(void *arg, uint64_t v, size_t sz) { } void test_exec(void *arg, uint64_t pc) { printf("Execute at 0x%"PRIu64"\n", pc); test_exit(arg, 0); } /* * Misc */ void test_delay(void *arg, int usec) { usleep(usec); } void test_exit(void *arg, int v) { tcsetattr(0, TCSAFLUSH, &oldterm); exit(v); } void test_getmem(void *arg, uint64_t *lowmem, uint64_t *highmem) { *lowmem = 128*1024*1024; *highmem = 0; } -const char * +char * test_getenv(void *arg, int idx) { - static const char *vars[] = { + static char *vars[] = { "foo=bar", "bar=barbar", NULL }; return (vars[idx]); } struct loader_callbacks cb = { .putc = test_putc, .getc = test_getc, .poll = test_poll, .open = test_open, .close = test_close, .isdir = test_isdir, .read = test_read, .readdir = test_readdir, .seek = test_seek, .stat = test_stat, .diskread = test_diskread, .diskioctl = test_diskioctl, .copyin = test_copyin, .copyout = test_copyout, .setreg = test_setreg, .setmsr = test_setmsr, .setcr = test_setcr, .setgdt = test_setgdt, .exec = test_exec, .delay = test_delay, .exit = test_exit, .getmem = test_getmem, .getenv = test_getenv, }; void usage() { printf("usage: [-b ] [-d ] [-h \n"); exit(1); } int main(int argc, char** argv) { void *h; void (*func)(struct loader_callbacks *, void *, int, int) __dead2; int opt; char *disk_image = NULL; const char *userboot_obj = "/boot/userboot.so"; while ((opt = getopt(argc, argv, "b:d:h:")) != -1) { switch (opt) { case 'b': userboot_obj = optarg; break; case 'd': disk_image = optarg; break; case 'h': host_base = optarg; break; case '?': usage(); } } h = dlopen(userboot_obj, RTLD_LOCAL); if (!h) { printf("%s\n", dlerror()); return (1); } func = dlsym(h, "loader_main"); if (!func) { printf("%s\n", dlerror()); return (1); } image_size = 128*1024*1024; image = malloc(image_size); if (disk_image) { disk_fd = open(disk_image, O_RDONLY); if (disk_fd < 0) err(1, "Can't open disk image '%s'", disk_image); } tcgetattr(0, &term); oldterm = term; term.c_iflag &= ~(ICRNL); term.c_lflag &= ~(ICANON|ECHO); tcsetattr(0, TCSAFLUSH, &term); func(&cb, NULL, USERBOOT_VERSION_3, disk_fd >= 0); } Index: head/stand/userboot/userboot/main.c =================================================================== --- head/stand/userboot/userboot/main.c (revision 326608) +++ head/stand/userboot/userboot/main.c (revision 326609) @@ -1,304 +1,304 @@ /*- * Copyright (c) 1998 Michael Smith * Copyright (c) 1998,2000 Doug Rabson * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include __FBSDID("$FreeBSD$"); #include #include #include #include #include "bootstrap.h" #include "disk.h" #include "libuserboot.h" #if defined(USERBOOT_ZFS_SUPPORT) #include "../zfs/libzfs.h" static void userboot_zfs_probe(void); static int userboot_zfs_found; #endif /* Minimum version required */ #define USERBOOT_VERSION USERBOOT_VERSION_3 #define MALLOCSZ (64*1024*1024) struct loader_callbacks *callbacks; void *callbacks_arg; extern char bootprog_info[]; static jmp_buf jb; struct arch_switch archsw; /* MI/MD interface boundary */ static void extract_currdev(void); void delay(int usec) { CALLBACK(delay, usec); } void exit(int v) { CALLBACK(exit, v); longjmp(jb, 1); } void loader_main(struct loader_callbacks *cb, void *arg, int version, int ndisks) { static char mallocbuf[MALLOCSZ]; - const char *var; + char *var; int i; if (version < USERBOOT_VERSION) abort(); callbacks = cb; callbacks_arg = arg; userboot_disk_maxunit = ndisks; /* * initialise the heap as early as possible. Once this is done, * alloc() is usable. */ setheap((void *)mallocbuf, (void *)(mallocbuf + sizeof(mallocbuf))); /* * Hook up the console */ cons_probe(); printf("\n%s", bootprog_info); #if 0 printf("Memory: %ld k\n", memsize() / 1024); #endif setenv("LINES", "24", 1); /* optional */ /* * Set custom environment variables */ i = 0; while (1) { var = CALLBACK(getenv, i++); if (var == NULL) break; putenv(var); } archsw.arch_autoload = userboot_autoload; archsw.arch_getdev = userboot_getdev; archsw.arch_copyin = userboot_copyin; archsw.arch_copyout = userboot_copyout; archsw.arch_readin = userboot_readin; #if defined(USERBOOT_ZFS_SUPPORT) archsw.arch_zfs_probe = userboot_zfs_probe; #endif /* * Initialise the block cache. Set the upper limit. */ bcache_init(32768, 512); /* * March through the device switch probing for things. */ for (i = 0; devsw[i] != NULL; i++) if (devsw[i]->dv_init != NULL) (devsw[i]->dv_init)(); extract_currdev(); if (setjmp(jb)) return; interact(NULL); /* doesn't return */ exit(0); } /* * Set the 'current device' by (if possible) recovering the boot device as * supplied by the initial bootstrap. */ static void extract_currdev(void) { struct disk_devdesc dev; //bzero(&dev, sizeof(dev)); #if defined(USERBOOT_ZFS_SUPPORT) if (userboot_zfs_found) { struct zfs_devdesc zdev; /* Leave the pool/root guid's unassigned */ bzero(&zdev, sizeof(zdev)); zdev.d_dev = &zfs_dev; zdev.d_type = zdev.d_dev->dv_type; dev = *(struct disk_devdesc *)&zdev; init_zfs_bootenv(zfs_fmtdev(&dev)); } else #endif if (userboot_disk_maxunit > 0) { dev.d_dev = &userboot_disk; dev.d_type = dev.d_dev->dv_type; dev.d_unit = 0; dev.d_slice = 0; dev.d_partition = 0; /* * If we cannot auto-detect the partition type then * access the disk as a raw device. */ if (dev.d_dev->dv_open(NULL, &dev)) { dev.d_slice = -1; dev.d_partition = -1; } } else { dev.d_dev = &host_dev; dev.d_type = dev.d_dev->dv_type; dev.d_unit = 0; } env_setenv("currdev", EV_VOLATILE, userboot_fmtdev(&dev), userboot_setcurrdev, env_nounset); env_setenv("loaddev", EV_VOLATILE, userboot_fmtdev(&dev), env_noset, env_nounset); } #if defined(USERBOOT_ZFS_SUPPORT) static void userboot_zfs_probe(void) { char devname[32]; uint64_t pool_guid; int unit; /* * Open all the disks we can find and see if we can reconstruct * ZFS pools from them. Record if any were found. */ for (unit = 0; unit < userboot_disk_maxunit; unit++) { sprintf(devname, "disk%d:", unit); pool_guid = 0; zfs_probe_dev(devname, &pool_guid); if (pool_guid != 0) userboot_zfs_found = 1; } } COMMAND_SET(lszfs, "lszfs", "list child datasets of a zfs dataset", command_lszfs); static int command_lszfs(int argc, char *argv[]) { int err; if (argc != 2) { command_errmsg = "a single dataset must be supplied"; return (CMD_ERROR); } err = zfs_list(argv[1]); if (err != 0) { command_errmsg = strerror(err); return (CMD_ERROR); } return (CMD_OK); } COMMAND_SET(reloadbe, "reloadbe", "refresh the list of ZFS Boot Environments", command_reloadbe); static int command_reloadbe(int argc, char *argv[]) { int err; char *root; if (argc > 2) { command_errmsg = "wrong number of arguments"; return (CMD_ERROR); } if (argc == 2) { err = zfs_bootenv(argv[1]); } else { root = getenv("zfs_be_root"); if (root == NULL) { return (CMD_OK); } err = zfs_bootenv(root); } if (err != 0) { command_errmsg = strerror(err); return (CMD_ERROR); } return (CMD_OK); } uint64_t ldi_get_size(void *priv) { int fd = (uintptr_t) priv; uint64_t size; ioctl(fd, DIOCGMEDIASIZE, &size); return (size); } #endif /* USERBOOT_ZFS_SUPPORT */ COMMAND_SET(quit, "quit", "exit the loader", command_quit); static int command_quit(int argc, char *argv[]) { exit(USERBOOT_EXIT_QUIT); return (CMD_OK); } COMMAND_SET(reboot, "reboot", "reboot the system", command_reboot); static int command_reboot(int argc, char *argv[]) { exit(USERBOOT_EXIT_REBOOT); return (CMD_OK); } Index: head/stand/userboot/userboot.h =================================================================== --- head/stand/userboot/userboot.h (revision 326608) +++ head/stand/userboot/userboot.h (revision 326609) @@ -1,213 +1,213 @@ /*- * Copyright (c) 2011 Doug Rabson * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD$ */ /* * USERBOOT interface versions */ #define USERBOOT_VERSION_1 1 #define USERBOOT_VERSION_2 2 #define USERBOOT_VERSION_3 3 /* * Version 4 added more generic callbacks for setting up * registers and descriptors. The callback structure is * backward compatible (new callbacks have been added at * the tail end). */ #define USERBOOT_VERSION_4 4 /* * Exit codes from the loader */ #define USERBOOT_EXIT_QUIT 1 #define USERBOOT_EXIT_REBOOT 2 struct loader_callbacks { /* * Console i/o */ /* * Wait until a key is pressed on the console and then return it */ int (*getc)(void *arg); /* * Write the character ch to the console */ void (*putc)(void *arg, int ch); /* * Return non-zero if a key can be read from the console */ int (*poll)(void *arg); /* * Host filesystem i/o */ /* * Open a file in the host filesystem */ int (*open)(void *arg, const char *filename, void **h_return); /* * Close a file */ int (*close)(void *arg, void *h); /* * Return non-zero if the file is a directory */ int (*isdir)(void *arg, void *h); /* * Read size bytes from a file. The number of bytes remaining * in dst after reading is returned in *resid_return */ int (*read)(void *arg, void *h, void *dst, size_t size, size_t *resid_return); /* * Read an entry from a directory. The entry's inode number is * returned in *fileno_return, its type in *type_return and * the name length in *namelen_return. The name itself is * copied to the buffer name which must be at least PATH_MAX * in size. */ int (*readdir)(void *arg, void *h, uint32_t *fileno_return, uint8_t *type_return, size_t *namelen_return, char *name); /* * Seek to a location within an open file */ int (*seek)(void *arg, void *h, uint64_t offset, int whence); /* * Return some stat(2) related information about the file */ int (*stat)(void *arg, void *h, int *mode_return, int *uid_return, int *gid_return, uint64_t *size_return); /* * Disk image i/o */ /* * Read from a disk image at the given offset */ int (*diskread)(void *arg, int unit, uint64_t offset, void *dst, size_t size, size_t *resid_return); /* * Guest virtual machine i/o */ /* * Copy to the guest address space */ int (*copyin)(void *arg, const void *from, uint64_t to, size_t size); /* * Copy from the guest address space */ int (*copyout)(void *arg, uint64_t from, void *to, size_t size); /* * Set a guest register value */ void (*setreg)(void *arg, int, uint64_t); /* * Set a guest MSR value */ void (*setmsr)(void *arg, int, uint64_t); /* * Set a guest CR value */ void (*setcr)(void *arg, int, uint64_t); /* * Set the guest GDT address */ void (*setgdt)(void *arg, uint64_t, size_t); /* * Transfer control to the guest at the given address */ void (*exec)(void *arg, uint64_t pc); /* * Misc */ /* * Sleep for usec microseconds */ void (*delay)(void *arg, int usec); /* * Exit with the given exit code */ void (*exit)(void *arg, int v); /* * Return guest physical memory map details */ void (*getmem)(void *arg, uint64_t *lowmem, uint64_t *highmem); /* * ioctl interface to the disk device */ int (*diskioctl)(void *arg, int unit, u_long cmd, void *data); /* * Returns an environment variable in the form "name=value". * * If there are no more variables that need to be set in the * loader environment then return NULL. * * 'num' is used as a handle for the callback to identify which * environment variable to return next. It will begin at 0 and * each invocation will add 1 to the previous value of 'num'. */ - const char * (*getenv)(void *arg, int num); + char * (*getenv)(void *arg, int num); /* * Version 4 additions. */ int (*vm_set_register)(void *arg, int vcpu, int reg, uint64_t val); int (*vm_set_desc)(void *arg, int vcpu, int reg, uint64_t base, u_int limit, u_int access); }; Index: head/usr.sbin/bhyveload/bhyveload.c =================================================================== --- head/usr.sbin/bhyveload/bhyveload.c (revision 326608) +++ head/usr.sbin/bhyveload/bhyveload.c (revision 326609) @@ -1,797 +1,797 @@ /*- * SPDX-License-Identifier: BSD-2-Clause-FreeBSD AND BSD-2-Clause * * Copyright (c) 2011 NetApp, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD$ */ /*- * Copyright (c) 2011 Google, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD$ */ #include __FBSDID("$FreeBSD$"); #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "userboot.h" #define MB (1024 * 1024UL) #define GB (1024 * 1024 * 1024UL) #define BSP 0 #define NDISKS 32 static char *host_base; static struct termios term, oldterm; static int disk_fd[NDISKS]; static int ndisks; static int consin_fd, consout_fd; static char *vmname, *progname; static struct vmctx *ctx; static uint64_t gdtbase, cr3, rsp; static void cb_exit(void *arg, int v); /* * Console i/o callbacks */ static void cb_putc(void *arg, int ch) { char c = ch; (void) write(consout_fd, &c, 1); } static int cb_getc(void *arg) { char c; if (read(consin_fd, &c, 1) == 1) return (c); return (-1); } static int cb_poll(void *arg) { int n; if (ioctl(consin_fd, FIONREAD, &n) >= 0) return (n > 0); return (0); } /* * Host filesystem i/o callbacks */ struct cb_file { int cf_isdir; size_t cf_size; struct stat cf_stat; union { int fd; DIR *dir; } cf_u; }; static int cb_open(void *arg, const char *filename, void **hp) { struct cb_file *cf; char path[PATH_MAX]; if (!host_base) return (ENOENT); strlcpy(path, host_base, PATH_MAX); if (path[strlen(path) - 1] == '/') path[strlen(path) - 1] = 0; strlcat(path, filename, PATH_MAX); cf = malloc(sizeof(struct cb_file)); if (stat(path, &cf->cf_stat) < 0) { free(cf); return (errno); } cf->cf_size = cf->cf_stat.st_size; if (S_ISDIR(cf->cf_stat.st_mode)) { cf->cf_isdir = 1; cf->cf_u.dir = opendir(path); if (!cf->cf_u.dir) goto out; *hp = cf; return (0); } if (S_ISREG(cf->cf_stat.st_mode)) { cf->cf_isdir = 0; cf->cf_u.fd = open(path, O_RDONLY); if (cf->cf_u.fd < 0) goto out; *hp = cf; return (0); } out: free(cf); return (EINVAL); } static int cb_close(void *arg, void *h) { struct cb_file *cf = h; if (cf->cf_isdir) closedir(cf->cf_u.dir); else close(cf->cf_u.fd); free(cf); return (0); } static int cb_isdir(void *arg, void *h) { struct cb_file *cf = h; return (cf->cf_isdir); } static int cb_read(void *arg, void *h, void *buf, size_t size, size_t *resid) { struct cb_file *cf = h; ssize_t sz; if (cf->cf_isdir) return (EINVAL); sz = read(cf->cf_u.fd, buf, size); if (sz < 0) return (EINVAL); *resid = size - sz; return (0); } static int cb_readdir(void *arg, void *h, uint32_t *fileno_return, uint8_t *type_return, size_t *namelen_return, char *name) { struct cb_file *cf = h; struct dirent *dp; if (!cf->cf_isdir) return (EINVAL); dp = readdir(cf->cf_u.dir); if (!dp) return (ENOENT); /* * Note: d_namlen is in the range 0..255 and therefore less * than PATH_MAX so we don't need to test before copying. */ *fileno_return = dp->d_fileno; *type_return = dp->d_type; *namelen_return = dp->d_namlen; memcpy(name, dp->d_name, dp->d_namlen); name[dp->d_namlen] = 0; return (0); } static int cb_seek(void *arg, void *h, uint64_t offset, int whence) { struct cb_file *cf = h; if (cf->cf_isdir) return (EINVAL); if (lseek(cf->cf_u.fd, offset, whence) < 0) return (errno); return (0); } static int cb_stat(void *arg, void *h, int *mode, int *uid, int *gid, uint64_t *size) { struct cb_file *cf = h; *mode = cf->cf_stat.st_mode; *uid = cf->cf_stat.st_uid; *gid = cf->cf_stat.st_gid; *size = cf->cf_stat.st_size; return (0); } /* * Disk image i/o callbacks */ static int cb_diskread(void *arg, int unit, uint64_t from, void *to, size_t size, size_t *resid) { ssize_t n; if (unit < 0 || unit >= ndisks ) return (EIO); n = pread(disk_fd[unit], to, size, from); if (n < 0) return (errno); *resid = size - n; return (0); } static int cb_diskioctl(void *arg, int unit, u_long cmd, void *data) { struct stat sb; if (unit < 0 || unit >= ndisks) return (EBADF); switch (cmd) { case DIOCGSECTORSIZE: *(u_int *)data = 512; break; case DIOCGMEDIASIZE: if (fstat(disk_fd[unit], &sb) != 0) return (ENOTTY); if (S_ISCHR(sb.st_mode) && ioctl(disk_fd[unit], DIOCGMEDIASIZE, &sb.st_size) != 0) return (ENOTTY); *(off_t *)data = sb.st_size; break; default: return (ENOTTY); } return (0); } /* * Guest virtual machine i/o callbacks */ static int cb_copyin(void *arg, const void *from, uint64_t to, size_t size) { char *ptr; to &= 0x7fffffff; ptr = vm_map_gpa(ctx, to, size); if (ptr == NULL) return (EFAULT); memcpy(ptr, from, size); return (0); } static int cb_copyout(void *arg, uint64_t from, void *to, size_t size) { char *ptr; from &= 0x7fffffff; ptr = vm_map_gpa(ctx, from, size); if (ptr == NULL) return (EFAULT); memcpy(to, ptr, size); return (0); } static void cb_setreg(void *arg, int r, uint64_t v) { int error; enum vm_reg_name vmreg; vmreg = VM_REG_LAST; switch (r) { case 4: vmreg = VM_REG_GUEST_RSP; rsp = v; break; default: break; } if (vmreg == VM_REG_LAST) { printf("test_setreg(%d): not implemented\n", r); cb_exit(NULL, USERBOOT_EXIT_QUIT); } error = vm_set_register(ctx, BSP, vmreg, v); if (error) { perror("vm_set_register"); cb_exit(NULL, USERBOOT_EXIT_QUIT); } } static void cb_setmsr(void *arg, int r, uint64_t v) { int error; enum vm_reg_name vmreg; vmreg = VM_REG_LAST; switch (r) { case MSR_EFER: vmreg = VM_REG_GUEST_EFER; break; default: break; } if (vmreg == VM_REG_LAST) { printf("test_setmsr(%d): not implemented\n", r); cb_exit(NULL, USERBOOT_EXIT_QUIT); } error = vm_set_register(ctx, BSP, vmreg, v); if (error) { perror("vm_set_msr"); cb_exit(NULL, USERBOOT_EXIT_QUIT); } } static void cb_setcr(void *arg, int r, uint64_t v) { int error; enum vm_reg_name vmreg; vmreg = VM_REG_LAST; switch (r) { case 0: vmreg = VM_REG_GUEST_CR0; break; case 3: vmreg = VM_REG_GUEST_CR3; cr3 = v; break; case 4: vmreg = VM_REG_GUEST_CR4; break; default: break; } if (vmreg == VM_REG_LAST) { printf("test_setcr(%d): not implemented\n", r); cb_exit(NULL, USERBOOT_EXIT_QUIT); } error = vm_set_register(ctx, BSP, vmreg, v); if (error) { perror("vm_set_cr"); cb_exit(NULL, USERBOOT_EXIT_QUIT); } } static void cb_setgdt(void *arg, uint64_t base, size_t size) { int error; error = vm_set_desc(ctx, BSP, VM_REG_GUEST_GDTR, base, size - 1, 0); if (error != 0) { perror("vm_set_desc(gdt)"); cb_exit(NULL, USERBOOT_EXIT_QUIT); } gdtbase = base; } static void cb_exec(void *arg, uint64_t rip) { int error; if (cr3 == 0) error = vm_setup_freebsd_registers_i386(ctx, BSP, rip, gdtbase, rsp); else error = vm_setup_freebsd_registers(ctx, BSP, rip, cr3, gdtbase, rsp); if (error) { perror("vm_setup_freebsd_registers"); cb_exit(NULL, USERBOOT_EXIT_QUIT); } cb_exit(NULL, 0); } /* * Misc */ static void cb_delay(void *arg, int usec) { usleep(usec); } static void cb_exit(void *arg, int v) { tcsetattr(consout_fd, TCSAFLUSH, &oldterm); exit(v); } static void cb_getmem(void *arg, uint64_t *ret_lowmem, uint64_t *ret_highmem) { *ret_lowmem = vm_get_lowmem_size(ctx); *ret_highmem = vm_get_highmem_size(ctx); } struct env { const char *str; /* name=value */ SLIST_ENTRY(env) next; }; static SLIST_HEAD(envhead, env) envhead; static void addenv(const char *str) { struct env *env; env = malloc(sizeof(struct env)); env->str = str; SLIST_INSERT_HEAD(&envhead, env, next); } -static const char * +static char * cb_getenv(void *arg, int num) { int i; struct env *env; i = 0; SLIST_FOREACH(env, &envhead, next) { if (i == num) return (env->str); i++; } return (NULL); } static int cb_vm_set_register(void *arg, int vcpu, int reg, uint64_t val) { return (vm_set_register(ctx, vcpu, reg, val)); } static int cb_vm_set_desc(void *arg, int vcpu, int reg, uint64_t base, u_int limit, u_int access) { return (vm_set_desc(ctx, vcpu, reg, base, limit, access)); } static struct loader_callbacks cb = { .getc = cb_getc, .putc = cb_putc, .poll = cb_poll, .open = cb_open, .close = cb_close, .isdir = cb_isdir, .read = cb_read, .readdir = cb_readdir, .seek = cb_seek, .stat = cb_stat, .diskread = cb_diskread, .diskioctl = cb_diskioctl, .copyin = cb_copyin, .copyout = cb_copyout, .setreg = cb_setreg, .setmsr = cb_setmsr, .setcr = cb_setcr, .setgdt = cb_setgdt, .exec = cb_exec, .delay = cb_delay, .exit = cb_exit, .getmem = cb_getmem, .getenv = cb_getenv, /* Version 4 additions */ .vm_set_register = cb_vm_set_register, .vm_set_desc = cb_vm_set_desc, }; static int altcons_open(char *path) { struct stat sb; int err; int fd; /* * Allow stdio to be passed in so that the same string * can be used for the bhyveload console and bhyve com-port * parameters */ if (!strcmp(path, "stdio")) return (0); err = stat(path, &sb); if (err == 0) { if (!S_ISCHR(sb.st_mode)) err = ENOTSUP; else { fd = open(path, O_RDWR | O_NONBLOCK); if (fd < 0) err = errno; else consin_fd = consout_fd = fd; } } return (err); } static int disk_open(char *path) { int err, fd; if (ndisks >= NDISKS) return (ERANGE); err = 0; fd = open(path, O_RDONLY); if (fd > 0) { disk_fd[ndisks] = fd; ndisks++; } else err = errno; return (err); } static void usage(void) { fprintf(stderr, "usage: %s [-S][-c ] [-d ] [-e ]\n" " %*s [-h ] [-m memsize[K|k|M|m|G|g|T|t]] \n", progname, (int)strlen(progname), ""); exit(1); } int main(int argc, char** argv) { char *loader; void *h; void (*func)(struct loader_callbacks *, void *, int, int); uint64_t mem_size; int opt, error, need_reinit, memflags; progname = basename(argv[0]); loader = NULL; memflags = 0; mem_size = 256 * MB; consin_fd = STDIN_FILENO; consout_fd = STDOUT_FILENO; while ((opt = getopt(argc, argv, "CSc:d:e:h:l:m:")) != -1) { switch (opt) { case 'c': error = altcons_open(optarg); if (error != 0) errx(EX_USAGE, "Could not open '%s'", optarg); break; case 'd': error = disk_open(optarg); if (error != 0) errx(EX_USAGE, "Could not open '%s'", optarg); break; case 'e': addenv(optarg); break; case 'h': host_base = optarg; break; case 'l': if (loader != NULL) errx(EX_USAGE, "-l can only be given once"); loader = strdup(optarg); if (loader == NULL) err(EX_OSERR, "malloc"); break; case 'm': error = vm_parse_memsize(optarg, &mem_size); if (error != 0) errx(EX_USAGE, "Invalid memsize '%s'", optarg); break; case 'C': memflags |= VM_MEM_F_INCORE; break; case 'S': memflags |= VM_MEM_F_WIRED; break; case '?': usage(); } } argc -= optind; argv += optind; if (argc != 1) usage(); vmname = argv[0]; need_reinit = 0; error = vm_create(vmname); if (error) { if (errno != EEXIST) { perror("vm_create"); exit(1); } need_reinit = 1; } ctx = vm_open(vmname); if (ctx == NULL) { perror("vm_open"); exit(1); } if (need_reinit) { error = vm_reinit(ctx); if (error) { perror("vm_reinit"); exit(1); } } vm_set_memflags(ctx, memflags); error = vm_setup_memory(ctx, mem_size, VM_MMAP_ALL); if (error) { perror("vm_setup_memory"); exit(1); } if (loader == NULL) { loader = strdup("/boot/userboot.so"); if (loader == NULL) err(EX_OSERR, "malloc"); } h = dlopen(loader, RTLD_LOCAL); if (!h) { printf("%s\n", dlerror()); free(loader); return (1); } func = dlsym(h, "loader_main"); if (!func) { printf("%s\n", dlerror()); free(loader); return (1); } tcgetattr(consout_fd, &term); oldterm = term; cfmakeraw(&term); term.c_cflag |= CLOCAL; tcsetattr(consout_fd, TCSAFLUSH, &term); addenv("smbios.bios.vendor=BHYVE"); addenv("boot_serial=1"); func(&cb, NULL, USERBOOT_VERSION_4, ndisks); free(loader); return (0); }