]> CyberLeo.Net >> Repos - FreeBSD/releng/9.0.git/blob - release/picobsd/build/picobsd
Copy stable/9 to releng/9.0 as part of the FreeBSD 9.0-RELEASE release
[FreeBSD/releng/9.0.git] / release / picobsd / build / picobsd
1 #!/bin/sh -
2 #
3 # $FreeBSD$
4 # This file requires sysutils/makefs to run
5 #
6 # The PicoBSD build script. Invoked as
7 #
8 #       picobsd [options] image_type [site_name]
9 #
10 # Where image_type is a directory with the picobsd config info,
11 # and ${image_type}/floppy.tree.${site_name} contains
12 # optional site-specific configuration.
13 #
14 # For Options, see the bottom of the file where the processing is
15 # done. The picobsd(8) manpage might be of some help, but code and docs
16 # tend to lose sync over time.
17 #
18 # This script depends on the following files:
19 #
20 # in ${PICO_TREE} :
21 #   Makefile.conf       Makefile used to build the kernel
22 #   config              shell variables, sourced here.
23 #   mfs.mtree           mtree config file
24 #   floppy.tree/        files which go on the floppy
25 #   mfs_tree/           files which go onto the mfs
26 #
27 # in ${MY_TREE} :
28 #   PICOBSD             kernel config file
29 #   config              shell variables, sourced here.
30 #   crunch.conf         crunchgen configuration
31 #   mfs.mtree           overrides ${PICO_TREE}/mfs.mtree
32 #   floppy.tree.exclude files from floppy.tree/ which we do not need here.
33 #   floppy.tree/        local additions to ${PICO_TREE}/mfs_free
34 #   floppy.tree.${site}/ same as above, site specific.
35 #   mfs_tree/           local additions to the mfs_free
36 #   buildtree.mk        optional Makefile to build an extension for floppy tree
37 #                       (generated in buildtree/ )
38
39 #
40 #--- The main entry point is at the end.
41 #
42
43 # There are two initialization functions:
44 #
45 # + set_defaults
46 #   is run on entry to the script, and is used to set default values
47 #   for all variables that do not depend on image type and source tree.
48 #
49 # + set_build_parameters
50 #   is run after command line parsing
51 #
52 # VARIABLE NAMES:
53 # + variables that control operation (e.g. verbosity) and are generally
54 #   set from the command line have o_ ("option") as a name prefix
55 #
56 # + variables that contain pathnames and values that should not change
57 #   have c_ ("constant") as a name prefix
58 #
59 # + variables exported to Makefiles and subshells are CAPITAL
60 #
61 # + variables local to the script are lowercase, possibly with
62 #   an l_ ("local") prefix.
63 #
64 # There are unfortunately exceptions:
65 # name, l_usrtree, l_objtree
66
67 # SRC points to your FreeBSD source tree.
68 # l_usrtree points to the /usr subdir for the source tree.
69 #     Normally /usr or ${SRC}/../usr
70 # l_objtree points to the obj tree. Normally ${l_usrtree}/obj-pico
71 # c_label is either bsdlabel or disklabel
72 # PICO_TREE is where standard picobsd stuff resides.
73 #     Normally ${SRC}/release/picobsd
74 # You can set SRC with --src <directory>
75 # It is not recommended to override the other variables.
76
77 # MY_TREE (set later) is where this floppy type resides.
78 # BUILDDIR is the build directory
79
80 # log something on stdout if verbose.
81 o_verbose=0     # this needs to be here!
82 log() { #       message
83     local foo
84     [ ${o_verbose} -gt 0 ] && printf "\n*** %s\n" "$*"
85     [ ${o_verbose}  -gt 1 ] && read -p "=== Press enter to continue" foo
86     return 0
87 }
88
89 # unconditionally log and wait for input
90 logverbose() {  # message
91     local foo
92     printf "\n*** %s\n" "$*"
93     read -p "=== Press enter to continue" foo
94     return 0
95 }
96
97 # set some default values for variables.
98 # needs to be done as the first thing in the script.
99
100 set_defaults() {        # no arguments
101     # EDITOR is the editor you use
102     # fd_size  floppy size in KB (default to 1440). You can use 1480,
103     #   1720, 2880, etc. but beware that only 1440 and 1480 will boot
104     #   from 1.44M floppy drives (1480 will not work on vmware).
105     EDITOR=${EDITOR:-vi}
106     fd_size=${fd_size:-1440}
107
108     o_use_loader="yes"          # use /boot/loader
109         # You should not change it unless you are really short
110         # of space, and your kernel is small enough that the
111         # bootblocks manage to load it.
112
113     o_all_in_mfs="yes"          # put all files in mfs so you can boot
114                                 # and run the image via diskless boot.
115     o_clean=""                  # set if you want to clean prev.builds.
116     o_interactive=""            # default is interactive
117     o_verbose=0                 # verbose level, 0 is silent
118     o_tarv=""                   # tar verbose flag, "" or "v"
119     o_init_src=""               # set to build libs and includes.
120     o_makeopts=${MAKEOPTS:--s}  # make options, be silent by default
121     o_no_devfs=                 # default is use devfs.
122         # You should only set it when building 4.x images
123     o_do_modules=""             # do not build modules
124
125     SRC="/usr/src"              # default location for sources
126     c_startdir=`pwd`            # directory where we start
127                                 # used to lookup config and create BUILDDIR
128
129     # XXX 6.x/7.x have a single /boot/boot block, which is the concatenation
130     # of the old two. For the time being, we keep these, but this should
131     # be fixed at some point.
132
133     # blocks
134     c_boot1=/boot/boot1         # boot blocks (in case you want custom ones)
135     c_boot2=/boot/boot2
136
137     c_reply=${c_reply:-`mktemp "/tmp/reply.XXXXXXXXXX"`}
138                                 # file where User replies will be put
139     c_mnt=`mktemp -d "/tmp/picobsd.XXXXXXXXXX"`
140                                 # mountpoint used to build memory filesystems
141     c_fs=fs.PICOBSD             # filename used for the memory filesystem
142     c_img=picobsd.bin           # filename used for the picobsd image
143     c_iso=picobsd.iso           # filename used for the ISO image
144     generate_iso="NO"           # don't generate the iso image
145
146     # select the right disklabel program
147     case `uname -r` in
148         4.*)
149             c_label="disklabel"
150             ;;
151         *)
152             c_label="bsdlabel"
153             ;;
154     esac
155
156     set -e
157
158     trap fail 2
159     #trap fail 3
160     #trap fail 6
161     trap fail 15
162 }
163
164 # use the new build infrastructure to create libraries
165 # and also to build a specific target
166 create_includes_and_libraries2() { # opt_dir opt_target
167     local no
168     log "create_includes_and_libraries2() for ${SRC}"
169     if [ ${OSVERSION} -ge 600000 ] ; then
170         no="-DNO_CLEAN -DNO_PROFILE -DNO_GAMES -DNO_LIBC_R" # WITHOUT_CDDL=1"
171     else
172         no="-DNOCLEAN -DNOPROFILE -DNOGAMES -DNOLIBC_R"
173     fi
174     MAKEOBJDIRPREFIX=${l_objtree}
175     export MAKEOBJDIRPREFIX
176     ( cd ${SRC};
177     # make -DNOCLEAN -DNOPROFILE -DNOGAMES -DNOLIBC_R -DPICOBSD buildworld
178     if [ -d "$1" ] ; then
179         cd $1 ; ${BINMAKE} ${o_par} $2  # specific target, e.g. ld-elf.so
180     else
181         ${BINMAKE} ${o_par} _+_= $no toolchain _includes _libraries
182     fi
183     )
184 }
185
186 # entry for 4.x and earlier trees
187 create_includes_and_libraries() {
188     local e i
189
190     log "create_includes_and_libraries() for ${SRC}"
191     # Optionally creates include directory and libraries.
192     mkdir -p ${l_usrtree}/include       # the include directory...
193     mkdir -p ${l_usrtree}/share/misc    # a few things go here
194     mkdir -p ${l_usrtree}/lib           # libraries
195     mkdir -p ${l_usrtree}/sbin          # some binaries
196     # override variables for ownershiip and destinations
197     # BINOWN:BINGRP are also used for include files
198     (cd ${SRC}; \
199         BINOWN=`id -un` BINGRP=`id -gn` \
200         DESTDIR=${l_usrtree}/.. \
201         make -m ${SRC}/share/mk includes ) || fail $? includes
202     # Pick up the correct headers for libraries.
203     CFLAGS="-nostdinc -I${l_usrtree}/include" ; export CFLAGS
204
205     (cd ${SRC}
206         # $e is the invocation of make with correct environment
207         # XXX check the NO* options below, maybe system dependent.
208         e="MAKEOBJDIRPREFIX=${l_objtree}/picobsd/libraries \
209             BINOWN=`id -un` BINGRP=`id -gn` \
210             DESTDIR=${l_usrtree}/.. \
211             make -m ${SRC}/share/mk \
212                 -DNOHTML -DNOINFO -DNOMAN -DNOSHARE -DNOFSCHG "
213         log "do a 'make obj' in a few places."
214         # This is very version-specific... The following works for 5.0
215         for i in lib secure/lib gnu/lib \
216                 gnu/usr.bin/perl usr.bin/lex usr.sbin/config ; do
217             (cd ${i}; eval $e obj)
218         done
219         log "now make the static libraries"
220         eval $e -DNOPROFILE -DNOPIC libraries
221         (cd ${SRC}/usr.sbin/config
222         eval $e         # build binary
223         eval $e install # install it
224         )
225     ) || fail $? "libraries"
226     log "Libraries done"
227 }
228
229 # set_type <the_type> [the_site] looks in user or system directories
230 # for the directory named as the first argument, reads the configuration
231 # files and sets variables according to the config.
232 # Also sets MY_TREE and BUILDDIR and SITE
233
234 set_type() {    # the_type the_site
235     local a i
236
237     log "set_type() : Type '$1' site '$2'"
238     THETYPE=$1
239     SITE=$2
240     a=$1
241     name=""     # clear in case of errors
242     for i in ${c_startdir}/${a} ${PICO_TREE}/${a} ; do
243         log "set_type: checking $i"
244         [ -d $i -a -f $i/PICOBSD -a -f $i/crunch.conf ] || continue
245         set -- `cat $i/PICOBSD | \
246             awk '/^#PicoBSD/ {print $2, $3, $4, $5, $6}'`
247         [ x"$1" != "x" ] || continue
248         MFS_SIZE=$1 ; init_name=$2
249         mfs_inodes=$3 ; fd_inodes=$4
250         name=`(cd $i ; pwd) `
251         name=`basename $name`
252         MY_TREE=$i
253         BUILDDIR=${c_startdir}/build_dir-${name}
254         log "Matching file $name in $i"
255         return ;
256     done
257     logverbose "Type $a NOT FOUND"
258 }
259
260 clean_tree() {
261     log "clean_tree()"
262     if [ -z "${name}" ] ; then
263         echo "---> Wrong floppy type"
264         exit 3
265     fi
266     rm -rf ${BUILDDIR}
267 }
268
269 # prepare a message to be printed in the dialog menus.
270 set_msgs() {            # OK
271     log "set_msgs()"
272
273     MSG1="Type: ${THETYPE} name $name"
274
275     MSG="PicoBSD build -- Current parameters:\n\n\t1.  ${MSG1}\n\
276 \t2.  MFS size: ${MFS_SIZE} kB\n\
277 \t3.  Site-info: ${SITE}\n\t4.  Full-path: ${MY_TREE}\n"
278 }
279
280 # Main build procedure. Builds both the disk image and the ISO
281 build_image() {
282     log "build_image() <${name}>"
283     [ -n "${name}" ] || fail $? bad_type
284     clear
285     set_msgs
286     printf "${MSG}---> We'll use the sources living in ${SRC}\n\n"
287
288     # read config variables from a global and then a type-specific file
289     # basically STAND_LINKS and MY_DEVS, but can also override other
290     # variables.
291     # 
292     . ${PICO_TREE}/build/config
293     [ -f "${MY_TREE}/config" ]          && . ${MY_TREE}/config
294     [ -f "${o_additional_config}" ]     && . ${o_additional_config}
295
296     # location of the object directory
297     PICO_OBJ=${l_objtree}/picobsd/${THETYPE}
298     log "PICO_OBJ is ${PICO_OBJ}"
299
300     # create build directory and subtree
301     mkdir -p ${BUILDDIR}/crunch
302     # remove any old stuff
303     rm -f ${BUILDDIR}/kernel.gz ${BUILDDIR}/${c_fs}
304     # invoke commands to build a kernel
305     do_kernel
306     # fill a subdirectory with things that go into the floppy
307     # (mostly /etc and similar stuff)
308     populate_floppy_fs
309     # populate it and produce a file with the MFS image
310     populate_mfs_tree           # things which go into mfs
311     # create, mount and fill a filesystem with floppy image
312     fill_floppy_image # copies everything into the floppy
313 }
314
315 # Set build parameters interactively
316
317 main_dialog() {
318   local ans i l
319
320   log "main_dialog()"
321   while true ; do
322     set_msgs
323     rm ${c_reply}
324     dialog --menu "PicoBSD build menu -- (29 sep 2001)" 19 70 12 \
325         N "--> READY, build it <---" \
326         T "${MSG1}" \
327         K "edit Kernel config file" \
328         E "Edit crunch.conf file" \
329         S "MFS Size: ${MFS_SIZE}kB" \
330         I "Init type: ${init_name}" \
331         F "Floppy size: ${fd_size}kB" \
332         M "MFS bytes per inode: ${mfs_inodes}" \
333         U "UFS bytes per inode: ${fd_inodes}" \
334         $ "Site-info: ${SITE}" \
335         Q "Quit" \
336         2> ${c_reply}
337     ans=`cat ${c_reply}`
338     rm ${c_reply}
339     case ${ans} in
340     T)
341         l=""
342         for i in ${c_startdir} ${c_startdir}/* ${PICO_TREE}/* ; do
343             if [ -d $i -a -f $i/PICOBSD -a -f $i/crunch.conf ]; then
344                 l="$l `basename $i` `basename $i`"
345             fi
346         done
347         log $l
348         { dialog --menu "Setup the type of configuration" 12 70 5 $l \
349                 2> ${c_reply} && set_type "`cat ${c_reply}`" ${SITE} ; } || true
350         ;;
351     I)
352         { dialog --menu "Choose your init(8) program" \
353         10 70 2 init "Standard init (requires getty)" \
354         oinit "small init from TinyWare" 2> ${c_reply} \
355                 && init_name=`cat ${c_reply}` ; } || true
356         ;;
357
358     K) ${EDITOR} ${MY_TREE}/PICOBSD ;;
359
360     E) ${EDITOR} ${MY_TREE}/crunch.conf ;;
361
362     S)
363         { dialog --title "MFS Size setup" --inputbox \
364 "MFS size depends on what you need to put on the MFS image. Typically \
365 ranges between 820kB (for very small bridge/router images) to \
366 as much as 2500kB kB for a densely packed image. \
367 Keep in mind that this memory is \
368 totally lost to other programs. Usually you want to keep \
369 this as small as possible. " 10 70 2> ${c_reply} \
370         && MFS_SIZE=`cat ${c_reply}` ; } || true
371         ;;
372
373     \$)
374         { dialog --title "Site info setup" --inputbox \
375         "Please enter the full path to the directory \
376         containing site-specific setup. \
377         This directory tree must contain files that replace \
378         standard ones in floppy.tree/ and mfs.tree/ . " \
379         10 70 2> ${c_reply} && SITE=`cat ${c_reply}` ; } || true
380         ;;
381
382     F)
383         { dialog --menu "Set floppy size" 15 70 4 \
384             1440 "1.44MB" 1720 "1.72MB" 2880 "2.88MB" 4096 "4MB" \
385                  2> ${c_reply} && fd_size=`cat ${c_reply}` ; } || true
386         ;;
387
388     M)
389         { dialog --title "MFS bytes per inode:" --inputbox \
390         "Enter MFS bytes per inode (typically 4096..65536). \
391         A larger value means fewer inodes but more space on MFS" \
392         10 70 2> ${c_reply} && mfs_inodes=`cat ${c_reply}`  ; } || true
393         ;;
394
395     U)
396         { dialog --title "Floppy bytes per inode:" --inputbox \
397         "Enter floppy bytes per inode (typically 3072..65536). \
398         A larger value means fewer inodes but more space on the floppy." \
399         10 70 2> ${c_reply} && fd_inodes=`cat ${c_reply}` ; } || true
400         ;;
401
402     N) break 2
403         ;;
404
405     Q) exit 0 ;;
406
407     *) echo "\aUnknown option \"${ans}\". Try again."
408         sleep 2
409         clear
410         ;;
411     esac
412   done
413 }
414
415 # Call the build procedure
416 # Install image
417 do_install() {
418     log "do_install()"
419
420     if [ "${o_interactive}" = "NO" ] ; then
421         echo "+++ Build completed +++"
422         cat .build.reply || true
423         return
424     fi
425     dialog --title "Build ${THETYPE} completed" --inputbox \
426 "\nThe build process was completed successfuly.\n\
427 `cat .build.reply` \n\n\
428 Now we are going to install the image on the floppy.\n\
429 Please insert a blank floppy in /dev/fd0.\\n
430 WARNING: the contents of the floppy will be permanently erased!\n\
431 \n\
432 Your options:\n\
433         * ^C or [Cancel] to abort,\n\
434         * Enter to install ${c_img},\n\
435 " 20 80 2> ${c_reply}
436     if [ "$?" = "0" ]; then
437         echo "Writing ${c_img}..."
438         dd if=${BUILDDIR}/${c_img} of=/dev/fd0.${fd_size}
439     else
440         echo "Ok, the image is in ${c_img}"
441     fi
442     echo "Done."
443 }
444
445
446 #-------------------------------------------------------------------
447
448 # invoke the picobsd Makefile to compile the kernel.
449 # if MODULES is set (value is irrelevant) the makefile will build modules.
450 do_kernel() {           # OK
451     log "do_kernel() Preparing kernel \"$name\" in $MY_TREE"
452     (cd $MY_TREE; export name SRC BUILDDIR # used in this makefile ;
453         # export CONFIG
454         [ "${o_do_modules}" = "yes" ] && export MODULES=""
455         ${BINMAKE} ${o_par} -v -f ${PICO_TREE}/build/Makefile.conf ) || \
456         fail $? missing_kernel
457 }
458
459 # Populate the variable part of the floppy filesystem. Must be done before
460 # the MFS because its content might need to be copied there as well.
461 #
462 # This involves fetching files from three subtrees, in this order:
463 #
464 #  1. a standard one, from which type-specific files are excluded;
465 #  2. a type-specific one;
466 #  3. a site-specific one.
467 #
468 # Files are first copied to a local tree and then compressed.
469
470 populate_floppy_fs() {          # OK
471     local dst excl srcdir
472
473     log "populate_floppy_fs()"
474     dst=${BUILDDIR}/floppy.tree
475     log "pwd=`pwd` Populating floppy filesystem..."
476
477     rm -rf ${dst} || true       # clean relics from old compilations.
478     mkdir ${dst}                # create a clean tree
479
480     # compute exclude list for generic tree
481     excl=${MY_TREE}/floppy.tree.exclude
482     if [ -f ${excl} ] ; then
483         log "Files excluded from generic tree: `echo;cat ${excl}`"
484         excl="--exclude-from ${excl}"
485     else
486         excl=""
487     fi
488     # copy from the floppy trees into the destination
489     for FLOPPY_TREE in ${PICO_TREE}/floppy.tree ${MY_TREE}/floppy.tree \
490                 ${MY_TREE}/floppy.tree.${SITE} ; do
491         if [ -d ${FLOPPY_TREE} ] ; then
492             (cd ${FLOPPY_TREE} ; tar -cf - --exclude CVS \
493                     --exclude .svn ${excl} . ) | \
494                 (cd ${dst} ; tar x${o_tarv}f - )
495             log "Copied from ${FLOPPY_TREE}"
496         fi
497         excl="" # reset the exclude list.
498     done
499
500     # add local manipulation
501     if [ -f ${MY_TREE}/buildtree.mk ] ; then
502         log "building local floppy tree"
503         ${BINMAKE} -C ${dst} -f ${MY_TREE}/buildtree.mk floppy.tree
504     fi
505  
506     # compress the files in etc/, just in case
507     # XXX this should be done in the makefile.
508     # gzip returns an error if it fails to compress some file
509     (cd $dst ; gzip -9 etc/*
510             log "Compressed files in etc/ `echo; ls -l etc`"
511     ) || true
512 }
513
514 # Copy the specified files to the destination filesystem.
515 # Each file is specified as a pair "src dst", dst is assumed to be
516 # a directory (and created with mkdir -p) if it has a trailing /
517 # Be careful to escape metacharacters.
518 # You can use ${CROSS} to point to the root of the cross build
519 # (remember that it might be incomplete)
520
521 do_copyfiles() {        # rootdir varname
522         log Copy files to $1
523         local root=$1
524         local srcs dst
525         local CROSS=${_SHLIBDIRPREFIX}
526         eval set "\${${2}}"
527         srcs=""
528         for dst in $* ; do
529                 [ -z "$srcs" ] && srcs=$dst && continue
530                 eval srcs="$srcs"       # expand wildcard and vars
531                 case x"$dst" in
532                 */ )    mkdir -p ${root}/${dst} ;;
533                 # * )   mkdir -p `dirname ${root}/${dst}` ;;
534                 esac
535                 cp -p ${srcs} ${root}/${dst} || true
536                 srcs=""
537         done
538 }
539
540 # do_links is a helper function to create links between programs
541 # in stand/
542 # This is done reading the names and destination from variable
543 # links in a config file, in the format
544 #       : dst names
545
546 do_links() {    # rootdir varname
547         local root=$1
548         local l i dst
549         eval l="\${${2}}"
550         dst=""
551         log "Create links for ${l}"
552         (cd ${root}/stand
553         for i in $l ; do
554             if [ "$dst" = ":" -o "$i" = ":" ] ; then
555                 dst=$i
556             elif [ -n "${dst}" ] ; then
557                 ln -s ${dst} ${i}
558             fi
559         done
560         )
561 }
562
563 # find_progs is a helper function to locate the named programs
564 # or libraries in ${o_objdir} or ${_SHLIBDIRPREFIX},
565 # and return the full pathnames.
566 # Called as "find_progs [-L libpath] [-P binpath] prog1 prog2 ... "
567 # On return it sets ${u_progs} to the list of programs, and ${u_libs}
568 # to the list of shared libraries used.
569
570 # '-L path' can be used to specify a search path for libraries
571 #    (which searches in $path/lib:$path/usr/lib:$path/usr/local/lib
572 # '-P binpath' can be used to specify a search path for programs
573 #    (which searches in a lot of places in the subtree)
574 # -L must be the first, followed by -P
575 #
576 # You can use it e.g. in a local confign file by writing
577 #
578 #  do_copyfiles_user() {
579 #       local dst=$1
580 #       find_progs nvi sed less grep
581 #       cp -p ${u_progs} ${dst}/bin
582 #       cp -p ${u_libs} ${dst}/lib
583 #       mkdir -p ${dst}/libexec
584 #       find_progs ld-elf.so.1
585 #       cp -p ${u_progs} ${dst}/libexec # ignore errors
586 #  }
587
588 find_progs() {  # programs
589         local i
590         local oo=${o_objdir:-${_SHLIBDIRPREFIX}} # default objdir
591         local lp=$oo/lib                        # default lib.prefix
592         local o=""                              # additional objdir
593         if [ x"$1" = "x-L" -a -d "$2" ] ; then # set lib search path
594                 o=$2; shift; shift
595                 lp="$lp:$o/lib:$o/usr/lib:$o/usr/local/lib"
596                 o="-P $o"
597         fi
598         u_libs=""
599         u_progs="`find_progs_helper $*`"
600         log "looking for libs for <$u_progs> in $lp"
601         [ -z "${u_progs}" ] && return 1 # not found, error
602         i="`( LD_LIBRARY_PATH=$lp ldd ${u_progs} ) | \
603                 grep -v '^/' | awk '{print $1}' | sort | uniq`"
604         u_libs="`find_progs_helper $o $i`"
605         return 0
606 }
607
608 find_progs_helper() {   # programs
609         local dir=${o_objdir:-${_SHLIBDIRPREFIX}/..}
610         local ldir=""
611         if [ x"$1" = "x-P" -a -d "$2" ] ; then # set path
612                 ldir=$2; shift; shift
613         fi
614         local progs="$*"
615         local subdirs=". local/bin local/sbin local/lib local/libexec \
616                 bin sbin usr.bin usr.sbin libexec lib \
617                 gnu/usr.bin gnu/lib \
618                 secure/usr.bin secure/usr.sbin secure/libexec secure/lib"
619         local names=""  # files to search
620         local o=""
621         local i
622         for i in $progs ; do
623                 # full pathnames are just listed
624                 [ -f "$i" ] && echo $i && continue
625                 names="${names} ${o} -name $i"
626                 o="-o"
627         done
628         [ -z "${names}" ] && return 0
629         local places=""                         # places to search
630         for i in $subdirs ; do
631                 [ -d "${dir}/${i}" ] && places="${places} ${dir}/${i}"
632         done
633         if [ -n "${ldir}" ] ; then
634             for i in $subdirs ; do
635                 [ -d "${ldir}/${i}" ] && places="${places} ${ldir}/${i}"
636             done
637         fi
638         # use maxdepth 3 because some libs are way down
639         find ${places} -maxdepth 3 -type f \( ${names} \)
640 }
641
642 # Populate the memory filesystem with binaries and non-variable
643 # configuration files.
644 # First do an mtree pass, then create directory links and device entries,
645 # then run crunchgen etc. to build the binary and create links.
646 # Then copy the specific/generic mfs_tree.
647 # Finally, if required, make a copy of the floppy.tree onto /fd
648
649 populate_mfs_tree() {
650     local i j a dst MFS_TREE
651
652     log "populate_mfs_tree()"
653     dst=${BUILDDIR}/mfs.tree
654     rm -rf ${dst} || true       # clean relics from old compilations.
655     mkdir ${dst}                # create a fresh tree
656
657     log "pwd=`pwd`, Populating MFS tree..."
658
659     # use type-specific mfs.mtree, default to generic one.
660     a=${MY_TREE}/mfs.mtree
661     [ -f ${a} ] || a=${PICO_TREE}/build/mfs.mtree
662     log "Running mtree using $a..."
663     mtree -deU -f $a -p ${dst} > /dev/null || fail $? mtree
664
665     # Create symlinks using relative pathnames, so it is possible
666     # to follow them also when building the image.
667     # Note that names in STAND_LINKS should not have a leading /
668     for i in ${STAND_LINKS}; do
669         j=`echo $i | sed -E 's:^[^/]+::;s:/[^/]+:../:g'`
670         ln -s ${j}stand ${dst}/$i
671     done
672     ln -s ../../dev/null ${dst}/var/run/log
673     ln -s ../../../etc/termcap ${dst}/usr/share/misc/termcap
674
675     ### now build the crunched binaries ###
676     (
677     cd ${BUILDDIR}/crunch
678     log "Making and installing crunch1 from `pwd` src ${SRC}..."
679     a=${BUILDDIR}/crunch1.conf
680     ( export BUILDDIR SRC MY_TREE PICO_OBJ ;
681         ${BINMAKE} \
682                 -v -f ${PICO_TREE}/build/Makefile.conf ${BUILDDIR}/crunch.mk )
683     log "Libs are ${LIBS} "
684     export SRC # used by crunch.mk
685     # export LIBS CFLAGS
686     log "Now make -f crunch.mk"
687     ${BINMAKE} ${o_makeopts} -f ${BUILDDIR}/crunch.mk
688     strip --remove-section=.note --remove-section=.comment crunch1
689     mv crunch1 ${dst}/stand/crunch
690     chmod 555 ${dst}/stand/crunch
691     log "Making links for binaries..."
692     for i in `crunchgen -l $a` ; do
693         ln ${dst}/stand/crunch ${dst}/stand/${i};
694     done
695     # rm $a # do not remove!
696     ) || fail $? crunch
697
698     if [ -f ${dst}/stand/sshd ] ; then
699         log "Setting up host key for sshd:"
700         if [ -f ${BUILDDIR}/floppy.tree/etc/ssh_host_key.gz ] ; then
701             log "Using existing host key"
702         else
703             log "Generating new host key" 
704             ssh-keygen -t rsa1 -f ${BUILDDIR}/floppy.tree/etc/ssh_host_key \
705                  -N "" -C "root@picobsd"
706             gzip -9 ${BUILDDIR}/floppy.tree/etc/ssh_host_key* || true
707         fi
708     fi
709
710     log "Copy generic and site-specific MFS tree..."
711     for MFS_TREE in ${PICO_TREE}/mfs_tree ${MY_TREE}/mfs_tree ; do
712         if [ -d ${MFS_TREE} ] ; then
713             log "Copy ${MFS_TREE} ..."
714             (cd ${MFS_TREE} ; tar -cf - --exclude CVS --exclude .svn . ) | \
715                     (cd ${dst} ; tar x${o_tarv}f - )
716         fi
717     done
718
719     if [ -f ${MY_TREE}/buildtree.mk ] ; then
720         log "building local floppy tree"
721         ${BINMAKE} -C ${dst} -f ${MY_TREE}/buildtree.mk mfs.tree
722     fi
723
724     if [ "${o_all_in_mfs}" = "yes" ]; then
725         log "Copy generic floppy_tree into MFS..."
726         # ignore failure in case the floppy is empty
727         cp -Rp ${BUILDDIR}/floppy.tree/* ${dst}/fd || true
728     fi
729
730     # 4.x compatibility - create device nodes
731     if [ -n "${o_no_devfs}" ] ; then
732         # create device entries using MAKEDEV
733         (cd ${dst}/dev
734         ln -s ${SRC}/etc/MAKEDEV ; chmod 555 MAKEDEV
735         # log `pwd`
736         sh ./MAKEDEV ${MY_DEVS}
737         rm MAKEDEV
738         )
739     fi
740     if [ "`id -u`" = "0" ] ; then
741         log "Fixing permissions"
742         (cd ${dst}; chown -R root . )
743     fi
744
745     log "for a shared 'crunch' take libraries and dynamic loader as well"
746     find_progs ${dst}/stand/crunch
747     if [ -n "${u_libs}" ] ; then
748         mkdir -p ${dst}/lib && cp -p ${u_libs} ${dst}/lib
749         mkdir -p ${dst}/libexec
750         create_includes_and_libraries2 libexec/rtld-elf
751         find_progs ld-elf.so.1 && cp -p ${u_progs} ${dst}/libexec
752     fi
753
754     [ -n "${copy_files}" ] && do_copyfiles ${dst} copy_files
755     do_copyfiles_user ${dst} || true
756     [ -n "${links}" ] && do_links ${dst} links
757     strip ${dst}/libexec/* ${dst}/lib/* ${dst}/stand/* 2> /dev/null || true
758
759     # The 'import_files' mechanism is deprecated, as it requires
760     # root permissions to follow the symlinks, and also does
761     # not let you rename the entries.
762     if [ -n "${import_files}" ] ; then
763         log "importing ${import_files} into mfs"
764         # We do it in a chroot environment on the target so
765         # symlinks are followed correctly.
766         # Make sure we have a statically linked tar there.
767         mkdir -p ${dst}/rescue
768         cp /rescue/tar ${dst}/rescue
769         (cd ${l_usrtree}/.. ; tar cf - ${import_files} ) | \
770             (chroot ${dst} /rescue/tar xPf - )
771         rm -rf ${dst}/rescue
772     fi
773
774     # final step -- build the mfs image
775     (cd ${BUILDDIR}
776         # override the owner
777         echo "/set uid=0 gid=0" > mtree.out
778         mtree -ic -p ${dst} -k "" >> mtree.out
779         log "mtre.out at ${BUILDDIR}/mtree.out"
780         makefs -t ffs -o bsize=4096 -o fsize=512 \
781                 -s ${MFS_SIZE}k -f 1000 -F mtree.out ${c_fs} ${dst}
782         ls -l ${c_fs} )
783     log "done mfs image"
784 }
785
786 final_cleanup() {
787     log "final_cleanup()"
788     rm -rf ${c_mnt} ${c_reply} 2> /dev/null || true
789     rm -f ${c_reply}
790 }
791
792 # fail errno errcode
793 # This function is used to trap errors and print msgs
794 #
795 fail() {
796     local errno errocode where
797
798     errno=$1
799     errcode=$2
800     where=$3
801     echo "---> fail: Error <${errno}> error code <${errcode}> in <${where}>"
802     case ${errcode} in
803     mtree)
804         echo "Error while making hierarchy in ${c_mnt}"
805         ;;
806     crunch)
807         echo "Error while building ${name}."
808         ;;
809     missing_kernel)
810         echo "Error: you must build PICOBSD${suffix} kernel first"
811         ;;
812     includes)
813         echo "Error: failed while making includes"
814         ;;
815     libraries)
816         echo "Error: failed while making libraries"
817         ;;
818     bad_type)
819         echo "Error: unknown floppy type ${name}"
820         ;;
821     no_space)
822         echo "Error: no space left on device (${where})"
823         ;;
824     no_mfs)
825         echo "Error: while writing MFS into the kernel."
826         ;;
827     "")
828         echo "User break"
829         errcode="userbreak"
830         ;;
831     *)
832         echo "unknown error, maybe user break: $errno $errcode"
833         ;;
834     esac
835     echo "---> Aborting $0"
836     # try to cleanup the vnode.
837     final_cleanup
838     exit 2
839 }
840
841 fill_floppy_image() {
842     local blocks dst mfs_start mfs_end mfs_size img_size
843
844     log "fill_floppy_image()"
845     dst=${c_mnt}        # where to create the image
846
847     log "Preparing ${fd_size}kB floppy filesystem..."
848
849     # correct blocks according to size.
850     blocks=${fd_size};
851     if [ "${blocks}" = "1720" ]; then
852         blocks=1722
853     elif [ "${blocks}" = "1480" ]; then
854         blocks=1476
855     fi
856
857     log "Labeling floppy image"
858     b2=${BUILDDIR}/boot2 # modified boot2
859     cp -f ${c_boot2} ${b2}
860     chmod 0644 ${b2}
861
862     if [ ${o_use_loader} = "no" ] ; then
863         log "patch ${c_boot2} to boot /kernel right away"
864         set `strings -at d ${b2} | grep "/boot/loader"`
865         echo -e "/kernel\0\0\0\0\0" | \
866             dd of=${b2} obs=$1 oseek=1 conv=notrunc 2>/dev/null
867     fi
868     chmod 0444 ${b2}
869
870     dst=${BUILDDIR}/image.tree
871     rm -rf ${dst}
872     mkdir -p ${dst}
873     (
874     cd ${BUILDDIR}
875     set 0 0 # reset variables
876     # $1 takes the offset of the MFS filesystem
877     set `strings -at d kernel | grep "MFS Filesystem goes here"`
878     mfs_start=$1
879     set 0 0 # reset variables
880     set `strings -at d kernel | grep "MFS Filesystem had better"`
881     mfs_end=$1
882     mfs_size="$((${mfs_end} - ${mfs_start}))"
883     set -- `ls -l ${c_fs}`; imgsize="$5"
884     if [ ${mfs_start} -gt 0 -a ${mfs_size} -ge ${imgsize} ] ; then
885         mfs_ofs=$((${mfs_start} + 8192))
886         log "Preload kernel with file ${c_fs} at ${mfs_ofs}"
887         log "`ls -l ${c_fs}` to fit in ${mfs_size}"
888         dd if=${c_fs} ibs=8192 iseek=1 of=kernel obs=${mfs_ofs} \
889             oseek=1 conv=notrunc # 2> /dev/null
890     else
891         log "not loading mfs, size ${mfs_size} img ${imgsize}"
892     fi
893     log "Compress with kgzip and copy to floppy image"
894     if [ ${o_use_loader} = "no" ] ; then
895         kgzip -o kernel.gz kernel
896         cp -p kernel.gz ${dst}/kernel || fail $? no_space "copying kernel"
897     else
898         gzip kernel
899         mkdir -p  ${dst}/boot/kernel
900         echo "hint.acpi.0.disabled=\"1\"" > ${dst}/boot/loader.conf
901         echo "console=\"comconsole\"" >> ${dst}/boot/loader.conf
902         cp -p /boot/loader ${dst}/boot/loader || fail $? no_space "copying bootloader"
903         cp -p kernel.gz ${dst}/boot/kernel/kernel.gz || fail $? no_space "copying kernel"
904     fi
905
906     # now transfer the floppy tree. If it is already in mfs, dont bother.
907     if [ "${o_all_in_mfs}" != "yes" ] ; then
908         log "Now transfer floppy tree if not already in MFS image"
909         cp -Rp floppy.tree/* ${dst} || \
910                 fail $? no_space "copying floppy tree"
911     fi
912     )
913
914     # add local manipulation to the image
915     if [ -f ${MY_TREE}/buildtree.mk ] ; then
916         ${BINMAKE} -C ${dst} -f ${MY_TREE}/buildtree.mk image.tree
917     fi
918
919     log "image used `du -s ${dst}` of ${blocks}k"
920     if [ "${generate_iso}" = "YES" ]; then
921         logverbose "generate_iso ${generate_iso}"
922         # build_iso_image       # XXX not implemented yet
923         (cd ${BUILDDIR}
924         cp -p /boot/cdboot ${dst}/boot || fail $? no_space "copying cdboot"
925         mkisofs -b boot/cdboot -no-emul-boot -J -r -ldots -l -L \
926                 -o ${c_iso} ${dst}
927         )
928     fi
929
930     (cd ${BUILDDIR}
931     makefs -t ffs -o bsize=4096 -o fsize=512 \
932         -s ${blocks}k -f 50 ${c_img} ${dst}
933
934     ${c_label} -w -f `pwd`/${c_img} auto # write in a label
935     # copy partition c: into a: with some sed magic
936     ${c_label} -f `pwd`/${c_img} | sed -e '/  c:/{p;s/c:/a:/;}' | \
937         ${c_label} -R -f `pwd`/${c_img} /dev/stdin
938     ${c_label} -f `pwd`/${c_img}
939
940     ls -l ${c_img}
941     ${c_label} -f `pwd`/${c_img}
942     log "after disklabel"
943     )
944
945     echo "BUILDDIR ${BUILDDIR}"
946
947     # dump the primary and secondary boot
948     # XXX primary is 512 bytes
949     dd if=${c_boot1} of=${BUILDDIR}/${c_img} conv=notrunc 2>/dev/null
950     # XXX secondary starts after the 0x114 = dec 276 bytes of the label
951     # so we skip 276 from the source, and 276+512=788 from dst
952     # the old style blocks used 512 and 1024 respectively
953
954     dd if=${b2} iseek=1 ibs=276 2> /dev/null | \
955         dd of=${BUILDDIR}/${c_img} oseek=1 obs=788 conv=notrunc 2>/dev/null
956     log "done disk image"
957     # XXX (log "Fixing permissions"; cd ${dst}; chown -R root *)
958     rm -rf ${BUILDDIR}/floppy.tree || true # cleanup
959     # df -ik ${dst} | colrm 70 > .build.reply
960     rm -rf ${dst}
961     rm ${BUILDDIR}/${c_fs}
962     # rm ${BUILDDIR}/kernel.gz
963 }
964
965 # This function creates variables which depend on the source tree in use:
966 # SRC, l_usrtree, l_objtree
967 # Optionally creates libraries, includes and the like (for cross compiles,
968 # needs to be done once).
969
970 set_build_parameters() {
971     if [ "${SRC}" = "/usr/src" ] ; then
972         l_usrtree=${USR:-/usr}
973     else
974         l_usrtree=${USR:-${SRC}/../usr}
975     fi
976     l_objtree=${l_usrtree}/obj-pico
977
978     PICO_TREE=${PICO_TREE:-${SRC}/release/picobsd}
979     set `grep "#define[\t ]__FreeBSD_version" ${SRC}/sys/sys/param.h`
980     OSVERSION=$3
981     log "OSVERSION is ${OSVERSION}"
982     if [ ${OSVERSION} -ge 500035 ] ; then
983         export MAKEOBJDIRPREFIX=${l_objtree}
984         export TARGET_ARCH=i386 TARGET=i386
985         eval "export BINMAKE=\"`cd ${SRC}; make -f Makefile -V BINMAKE`\""
986         eval export `cd ${SRC}; ${BINMAKE} -f Makefile.inc1 -V WMAKEENV`
987     fi
988
989     if [ "${o_init_src}" != "" ] ; then
990         if [ ${OSVERSION} -lt 500035 ] ; then
991             create_includes_and_libraries
992         else
993             create_includes_and_libraries2
994         fi
995     fi
996     if [ ${OSVERSION} -lt 500035 ] ; then
997         # Create the right LIBS and CFLAGS for further builds.
998         # and build the config program
999         LIBS="-L${l_usrtree}/lib"
1000         CFLAGS="-nostdinc -I${l_usrtree}/include"
1001         export LIBS CFLAGS
1002         CONFIG=${l_usrtree}/sbin/config
1003         export CONFIG
1004     fi
1005
1006     # if we have o_objdir, find where bin/ is
1007     if [ ! -z "${o_objdir}" ] ; then
1008         if [ -d ${o_objdir}/bin ] ; then
1009             # fine
1010         elif [ -d "${o_objdir}${SRC}/bin" ] ; then
1011             o_objdir="${o_objdir}${SRC}"
1012             log "Changing objdir to ${o_objdir}"
1013         else
1014             log "Cannot find objdir in ${o_objdir}, sorry"
1015             o_objdir=""
1016         fi
1017     fi
1018 }
1019
1020 #-------------------------------------------------------------------
1021 # Main entry of the script. Initialize variables, parse command line
1022 # arguments.
1023
1024 # o_par="-j 8"  # parallel make and other make options
1025
1026 set_defaults
1027 while [ true ]; do
1028     log "Parsing $1"
1029     case $1 in
1030     --src)      # set the source path instead of /usr/src
1031         SRC=`realpath $2`
1032         shift
1033         ;;
1034     --init)
1035         o_init_src="YES"
1036         ;;
1037
1038     --floppy_size)
1039         fd_size=$2
1040         shift
1041         ;;
1042
1043     --no_loader)        # omit /boot/loader, just rely on boot2
1044                         # (it may have problems with kernels > 4MB)
1045         o_use_loader="no"
1046         ;;
1047
1048     --all_in_mfs)
1049         o_all_in_mfs="yes"
1050         ;;
1051
1052     --no_all_in_mfs)
1053         o_all_in_mfs="no"
1054         ;;
1055
1056     --modules)  # also build kernel modules
1057         o_do_modules="yes"
1058         ;;
1059     -n)
1060         o_interactive="NO"
1061         ;;
1062
1063     -clear|-clean|-c) # clean
1064         o_clean="YES"
1065         o_interactive="NO"
1066         ;;
1067
1068     -v) # need -v -v to wait for user input
1069         o_verbose=$((${o_verbose}+1))   # verbose level
1070         o_tarv="v"                      # tar verbose flag
1071         o_makeopts="-d l" # be verbose
1072         ;;
1073
1074     --iso) # generate iso image
1075         generate_iso="YES"
1076         ;;
1077
1078     --cfg) # read additional config from this file
1079         o_additional_config=`realpath $2`
1080         shift
1081         ;;
1082
1083     --objdir)   # Place with results of a previous buildworld
1084                 # useful if you want to copy shared binaries and libs
1085         o_objdir=`realpath $2`
1086         shift
1087         ;;
1088
1089     *)
1090         break
1091         ;;
1092
1093     esac
1094     shift
1095 done
1096
1097 set_build_parameters    # things that depend on ${SRC}
1098 set_type $1 $2          # type and site, respectively
1099
1100 [ "${o_interactive}" != "NO" ] && main_dialog
1101
1102 if [ "${o_clean}" = "YES" ] ; then
1103     clean_tree
1104 else
1105     build_image
1106     do_install
1107 fi
1108 final_cleanup
1109 exit 0