]> rtime.felk.cvut.cz Git - novaboot.git/blob - novaboot
server: Doc grammar fixes
[novaboot.git] / novaboot
1 #!/usr/bin/env perl
2
3 # This program is free software: you can redistribute it and/or modify
4 # it under the terms of the GNU General Public License as published by
5 # the Free Software Foundation, either version 2 of the License, or
6 # (at your option) any later version.
7
8 # This program is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11 # GNU General Public License for more details.
12
13 # You should have received a copy of the GNU General Public License
14 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
15
16 ## Initialization
17
18 use strict;
19 use warnings;
20 use warnings (exists $ENV{NOVABOOT_TEST} ?
21               (FATAL => 'all') :
22               (FATAL => qw(inplace))); # Open warnings in <<>> are fatal
23 use Getopt::Long qw(GetOptionsFromString GetOptionsFromArray);
24 use Pod::Usage;
25 use File::Basename;
26 use File::Spec;
27 use File::Path qw(make_path);
28 use IO::Handle;
29 use Time::HiRes("usleep");
30 use Socket;
31 use FileHandle;
32 use IPC::Open2;
33 use POSIX qw(:errno_h sysconf);
34 use Cwd qw(getcwd abs_path);
35 use Expect;
36
37 # always flush
38 $| = 1;
39
40 my $invocation_dir = $ENV{PWD} || getcwd();
41
42 # We prefer using PWD, to use nicer paths names with symbolic links.
43 # However, when executed from 'make -C dir', PWD may contain the make
44 # invocation path, not the real invocation path with dir at the end.
45 # We fix that here.
46 if (abs_path($ENV{PWD}) ne abs_path(getcwd())) {
47     $invocation_dir = getcwd();
48 }
49
50 ## Configuration file handling
51
52 # Default configuration
53 $CFG::hypervisor = "";
54 $CFG::hypervisor_params = "serial";
55 $CFG::genisoimage = "genisoimage";
56 $CFG::qemu = 'qemu-system-i386 -cpu coreduo -smp 2';
57 $CFG::default_target = '';
58 $CFG::netif = 'eth0';
59 %CFG::targets = (
60     'qemu' => '--qemu',
61     "tud" => '--copy=erwin.inf.tu-dresden.de:~sojka/boot/novaboot --rsync-flags="--chmod=Dg+s,ug+w,o-w,+rX --rsync-path=\"umask 002 && rsync\"" --grub --grub-prefix=(nd)/tftpboot/sojka/novaboot --grub-preamble="timeout 0" --concat --iprelay=141.76.48.80:2324 --scriptmod=s/\\\\bhostserial\\\\b/hostserialpci/g',
62     "novabox" => '--ssh=novabox@rtime.felk.cvut.cz',
63     "localhost" => '--scriptmod=s/console=tty[A-Z0-9,]+// --copy=/boot/novaboot/$NAME --grub2 --grub-prefix=/boot/novaboot/$NAME --grub2-prolog="  set root=\'(hd0,msdos1)\'"',
64     "ryu" =>  '--uboot --uboot-init="mw f0000b00 \${psc_cfg}; sleep 1" --uboot-addr kernel=800000 --uboot-addr ramdisk=b00000 --uboot-addr fdt=7f0000',
65     "ryuglab" => '--target ryu --ssh=ryu@pc-sojkam.felk.cvut.cz',
66     "ryulocal" => '--target ryu --dhcp-tftp --serial --reset-cmd="if which dtrrts; then dtrrts $NB_SERIAL 0 1; sleep 0.1; dtrrts $NB_SERIAL 1 1; fi"',
67     );
68
69 {
70     my %const;
71     $const{linux}->{_SC_NPROCESSORS_CONF} = 83;
72     my $nproc = sysconf($const{$^O}->{_SC_NPROCESSORS_CONF});
73
74     $CFG::scons = "scons -j$nproc";
75     $CFG::make = "make -j$nproc";
76 }
77
78 my $builddir;
79
80 sub read_config($) {
81     my ($cfg) = @_;
82     {
83         package CFG; # Put config data into a separate namespace
84
85         my $rc = do($cfg);
86
87         # Check for errors
88         if ($@) {
89             die("ERROR: Failure compiling '$cfg' - $@");
90         } elsif (! defined($rc)) {
91             die("ERROR: Failure reading '$cfg' - $!");
92         } elsif (! $rc) {
93             die("ERROR: Failure processing '$cfg'");
94         }
95     }
96     $builddir = File::Spec->rel2abs($CFG::builddir, dirname($cfg)) if defined $CFG::builddir;
97     print STDERR "novaboot: Read $cfg\n";
98 }
99
100 my @cfgs;
101 {
102     # We don't use $0 here, because it points to the novaboot itself and
103     # not to the novaboot script. The problem with this approach is that
104     # when a script is run as "novaboot <options> <script>" then $ARGV[0]
105     # contains the first option. Hence the -f check.
106     my $dir = File::Spec->rel2abs($ARGV[0] && -f $ARGV[0] ? dirname($ARGV[0]) : '', $invocation_dir);
107     while ((-d $dir || -l $dir ) && $dir ne "/") {
108         push @cfgs, "$dir/.novaboot" if -r "$dir/.novaboot";
109         my @dirs = File::Spec->splitdir($dir);
110         $dir = File::Spec->catdir(@dirs[0..$#dirs-1]);
111     }
112     @cfgs = reverse @cfgs;
113
114     my $xdg_config_home = $ENV{'XDG_CONFIG_HOME'} || $ENV{'HOME'}.'/.config';
115     unshift(@cfgs, "$xdg_config_home/novaboot") if -r "$xdg_config_home/novaboot";
116
117     $dir = $ENV{'NOVABOOT_CONFIG_DIR'} || '/etc/novaboot.d';
118     if (opendir(my $dh, $dir)) {
119         my @etccfg = map { "$dir/$_" } grep { /^[-_a-zA-Z0-9]+$/ && -f "$dir/$_" } readdir($dh);
120         closedir $dh;
121         @etccfg = sort(@etccfg);
122         @cfgs = ( @etccfg, @cfgs );
123     }
124 }
125 my $cfg = $ENV{'NOVABOOT_CONFIG'};
126 Getopt::Long::Configure(qw/no_ignore_case pass_through/);
127 GetOptions ("config|c=s" => \$cfg);
128 read_config($_) foreach $cfg or @cfgs;
129
130 ## Command line handling
131
132 my $explicit_target = $ENV{'NOVABOOT_TARGET'};
133 GetOptions ("target|t=s" => \$explicit_target);
134
135 # Variables for command line options
136 my ($amt, @append, $bender, @chainloaders, $concat, $config_name_opt, $dhcp_tftp, $dump_opt, $dump_config, @exiton, $exiton_timeout, @expect_raw, $final_eol, $gen_only, $grub_config, $grub_prefix, $grub_preamble, $grub2_prolog, $grub2_config, $help, $ider, $interaction, $iprelay, $iprelay_cmd, $iso_image, $interactive, $kernel_opt, $make, $man, $netif, $no_file_gen, $off_opt, $on_opt, $pulsar, $pulsar_root, $qemu, $qemu_append, $qemu_flags_cmd, @remote_cmd, $remote_expect, $remote_expect_silent, $remote_expect_timeout, $reset, @reset_cmd, $reset_send, $rom_prefix, $rsync_flags, @scriptmod, $scons, $serial, $server, $stty, $tftp, $tftp_port, $uboot, %uboot_addr, $uboot_cmd, @uboot_init, $uboot_stop_key);
137
138 my ($target_reset, $target_power_on, $target_power_off);
139
140 # Default values of certain command line options
141 %uboot_addr = (
142     'kernel'  => '${kernel_addr_r}',
143     'ramdisk' => '${ramdisk_addr_r}',
144     'fdt'     => '${fdt_addr_r}',
145     );
146 $rsync_flags = '';
147 $rom_prefix = 'rom://';
148 $stty = 'raw -crtscts -onlcr -echo 115200';
149 $reset = 1;                     # Reset target by default
150 $interaction = 1;               # Perform target interaction by default
151 $final_eol = 1;
152 $netif = $CFG::netif;
153 $remote_expect_timeout = -1;
154
155 my @expect_seen = ();
156 sub handle_expect
157 {
158     my ($n, $v) = @_;
159     push(@expect_seen, '-re') if $n eq "expect-re";
160     push(@expect_seen, $v);
161 }
162
163 sub handle_send
164 {
165     my ($n, $v) = @_;
166     unless (@expect_seen) { die("No --expect before --send"); }
167     my $ret = ($n eq "sendcont") ? exp_continue : 0;
168     unshift(@expect_raw, sub { shift->send(eval("\"$v\"")); $ret; });
169     unshift(@expect_raw, @expect_seen);
170     @expect_seen = ();
171 }
172
173 # Options which can be safely specified on the server (via --ssh),
174 # i.e. which cannot cause unwanted local code execution etc.
175 my %opt_spec_safe = (
176     "grub|g:s"       => \$grub_config,
177     "grub-preamble=s"=> \$grub_preamble,
178     "grub2-prolog=s" => \$grub2_prolog,
179     "grub2:s"        => \$grub2_config,
180     "prefix|grub-prefix=s" => \$grub_prefix,
181     "pulsar-root=s"  => \$pulsar_root,
182     "pulsar|p:s"     => \$pulsar,
183     "remote-expect=s"=> \$remote_expect,
184     "remote-expect-silent=s"=> sub { $remote_expect=$_[1]; $remote_expect_silent=1; },
185     "remote-expect-timeout=i"=> \$remote_expect_timeout,
186     "uboot-addr=s"   => \%uboot_addr,
187     "uboot-cmd=s"    => \$uboot_cmd,
188     "uboot-stop-key=s" => \$uboot_stop_key,
189     "uboot-init=s"   => sub { push @uboot_init, { command => $_[1] }; },
190     "uboot:s"        => \$uboot,
191     );
192
193 my %opt_spec = (
194     %opt_spec_safe,
195     "amt=s"          => \$amt,
196     "append|a=s"     => \@append,
197     "bender|b"       => \$bender,
198     "build-dir=s"    => sub { my ($n, $v) = @_; $builddir = File::Spec->rel2abs($v); },
199     "concat"         => \$concat,
200     "chainloader=s"  => \@chainloaders,
201     "dhcp-tftp|d"    => \$dhcp_tftp,
202     "dump"           => \$dump_opt,
203     "dump-config"    => \$dump_config,
204     "exiton=s"       => \@exiton,
205     "exiton-timeout=i"=> \$exiton_timeout,
206     "exiton-re=s"    => sub { my ($n, $v) = @_; push(@exiton, '-re', $v); },
207     "expect=s"       => \&handle_expect,
208     "expect-re=s"    => \&handle_expect,
209     "expect-raw=s"   => sub { my ($n, $v) = @_; unshift(@expect_raw, eval($v)); },
210     "final-eol!"     => \$final_eol,
211     "gen-only"       => \$gen_only,
212     "ider"           => \$ider,
213     "interaction!"   => \$interaction,
214     "iprelay=s"      => \$iprelay,
215     "iprelay-cmd=s"  => \$iprelay_cmd,
216     "iso:s"          => \$iso_image,
217     "kernel|k=s"     => \$kernel_opt,
218     "interactive|i"  => \$interactive,
219     "name=s"         => \$config_name_opt,
220     "make|m:s"       => \$make,
221     "netif=s"        => \$netif,
222     "no-file-gen"    => \$no_file_gen,
223     "off"            => \$off_opt,
224     "on"             => \$on_opt,
225     "qemu|Q:s"       => \$qemu,
226     "qemu-append=s"  => \$qemu_append,
227     "qemu-flags|q=s" => \$qemu_flags_cmd,
228     "remote-cmd=s"   => sub { @remote_cmd = ($_[1]); },
229     "reset!"         => \$reset,
230     "reset-cmd=s"    => sub { @reset_cmd = ($_[1]); },
231     "reset-send=s"   => \$reset_send,
232     "rsync-flags=s"  => \$rsync_flags,
233     "scons:s"        => \$scons,
234     "scriptmod=s"    => \@scriptmod,
235     "send=s"         => \&handle_send,
236     "sendcont=s"     => \&handle_send,
237     "serial|s:s"     => \$serial,
238     "server:s"       => \$server,
239     "copy:s"         => \$server,
240     "ssh:s"          => \&handle_novaboot_server,
241     "strip-rom"      => sub { $rom_prefix = ''; },
242     "stty=s"         => \$stty,
243     "tftp"           => \$tftp,
244     "tftp-port=i"    => \$tftp_port,
245     "no-uboot"       => sub { undef $uboot; },
246     "h"              => \$help,
247     "help"           => \$man,
248     );
249
250 sub handle_novaboot_server
251 {
252     my ($n, $val) = @_;
253     my $xdg_runtime_dir = $ENV{XDG_RUNTIME_DIR} || '/var/run';
254     my $ssh_ctl_path = "${xdg_runtime_dir}/novaboot$$";
255
256     @remote_cmd = ('ssh', '-tt', '-M', '-S', $ssh_ctl_path, $val, 'console');
257     $remote_expect = "novaboot-shell: Connected";
258     $server = "$val:";
259     $rsync_flags = "--rsh='ssh -S \'${ssh_ctl_path}\''";
260     ($grub_prefix = $val) =~ s|(.*)@.*|\/$1\/| if index($val, '@') != -1;
261     @reset_cmd = ('ssh', '-tt', '-S', $ssh_ctl_path, $val, 'reset');
262
263     $target_power_off = sub { system_verbose('ssh', '-tt', '-S', $ssh_ctl_path, $val, 'off'); };
264     $target_power_on  = sub { system_verbose('ssh', '-tt', '-S', $ssh_ctl_path, $val, 'on'); };
265
266     my $cmd = "ssh '${val}' get-config";
267     print STDERR "novaboot: Running: $cmd\n";
268     my @target_config = qx($cmd  < /dev/null);
269     if ($?) { die("Cannot get target configuration from the server"); }
270     printf "novaboot: Received configuration from the server:%s\n", (!@target_config) ? " empty" : "";
271     foreach (@target_config) { chomp; print "  $_\n"; }
272
273     my $p = Getopt::Long::Parser->new;
274     $p->configure(qw/no_ignore_case no_pass_through/);
275     $p->getoptionsfromarray(\@target_config, %opt_spec_safe) or die("Error processing configuration from the server");
276
277     if (scalar @target_config) { die "Unsuported configuration received from the server: ".join(", ", @target_config); }
278 }
279
280 # First process target options
281 {
282     my $t = defined($explicit_target) ? $explicit_target : $CFG::default_target;
283     my @target_expanded;
284     Getopt::Long::Configure(qw/no_ignore_case pass_through/);
285     while ($t) {
286         exists $CFG::targets{$t} or die("Unknown target '$t' (valid targets are: ".join(", ", sort keys(%CFG::targets)).")");
287
288         undef $explicit_target;
289         my ($ret, $remaining_args) = GetOptionsFromString ($CFG::targets{$t}, ("target|t=s" => \$explicit_target));
290         if (!$ret) { die "Error parsing target $t option"; }
291         push(@target_expanded, @$remaining_args);
292         $t = $explicit_target;
293     }
294
295     my @args = (@target_expanded, @ARGV);
296     print STDERR "novaboot: Effective options: @args\n";
297
298     Getopt::Long::Configure(qw/no_ignore_case no_pass_through/);
299     GetOptionsFromArray(\@target_expanded, %opt_spec) or die ("Error in target definition");
300 }
301
302 # Then process other command line options - some of them may override
303 # what was specified by the target
304 GetOptions %opt_spec or die("Error in command line arguments");
305 pod2usage(1) if $help;
306 pod2usage(-exitstatus => 0, -verbose => 2) if $man;
307
308 ### Dump sanitized configuration (if requested)
309
310 if ($dump_config) {
311     use Data::Dumper;
312     $Data::Dumper::Indent=1;
313     print "# This file is in perl syntax.\n";
314     foreach my $key(sort(keys(%CFG::))) { # See "Symbol Tables" in perlmod(1)
315         if (defined ${$CFG::{$key}}) { print Data::Dumper->Dump([${$CFG::{$key}}], ["*$key"]); }
316         if (        @{$CFG::{$key}}) { print Data::Dumper->Dump([\@{$CFG::{$key}}], ["*$key"]); }
317         if (        %{$CFG::{$key}}) { print Data::Dumper->Dump([\%{$CFG::{$key}}], ["*$key"]); }
318     }
319     print "1;\n";
320     exit;
321 }
322
323 ### Sanitize configuration
324
325 if ($interactive && !-t STDIN) {
326     die("novaboot: Interactive mode not supported when not on terminal");
327 }
328
329 if (defined $config_name_opt && scalar(@ARGV) > 1) { die "You cannot use --name with multiple scripts"; }
330
331 if ($ider) {
332     $iso_image //= ''; # IDE-R needs an ISO image
333     if (!defined $amt) { die "Error: --ider requires --amt"; }
334 }
335
336 {
337     my %input_opts = ('--iprelay'    => \$iprelay,
338                       '--iprelay-cmd'=> \$iprelay_cmd,
339                       '--serial'     => \$serial,
340                       '--remote-cmd' => (@remote_cmd ? \$remote_cmd[0] : undef),
341                       '--amt'        => \$amt);
342     my @opts = grep(defined(${$input_opts{$_}}) , keys %input_opts);
343
344     die("novaboot: More than one target connection option: ".join(', ', @opts)) if scalar @opts > 1;
345 }
346
347 # Default options
348 if (defined $serial) {
349     $serial ||= "/dev/ttyUSB0";
350     $ENV{NB_SERIAL} = $serial;
351 }
352 if (defined $grub_config) { $grub_config ||= "menu.lst"; }
353 if (defined $grub2_config) { $grub2_config ||= "./boot/grub/grub.cfg"; }
354
355 ## Parse the novaboot script(s)
356 my @scripts;
357 my $file;
358 my $EOF;
359 my $last_fn = '';
360 my ($modules, $variables, $generated, $copy, $chainload, $continuation) = ([], {}, [], []);
361 my $skip_reading = defined($on_opt) || defined($off_opt);
362 while (!$skip_reading && ($_ = <<>>)) {
363     if ($ARGV ne $last_fn) { # New script
364         die "Missing EOF in $last_fn" if $file;
365         die "Unfinished line in $last_fn" if $continuation;
366         $last_fn = $ARGV;
367         push @scripts, { 'filename' => $ARGV,
368                          'modules' => $modules = [],
369                          'variables' => $variables = {},
370                          'generated' => $generated = [],
371                          'copy' => $copy = [],
372                          'chainload' => $chainload = [],
373         };
374
375     }
376     chomp();
377     next if /^#/ || /^\s*$/;    # Skip comments and empty lines
378
379     $_ =~ s/^[[:space:]]*// if ($continuation);
380
381     if (/\\$/) {                # Line continuation
382         $continuation .= substr($_, 0, length($_)-1);
383         next;
384     }
385
386     if ($continuation) {        # Last continuation line
387         $_ = $continuation . $_;
388         $continuation = '';
389     }
390
391     foreach my $mod(@scriptmod) { eval $mod; }
392
393     if ($file && $_ eq $EOF) {  # Heredoc end
394         undef $file;
395         next;
396     }
397     if ($file) {                # Heredoc content
398         push @{$file}, "$_\n";
399         next;
400     }
401     if (/^([A-Z_]+)=(.*)$/) {   # Internal variable
402         $$variables{$1} = $2;
403         push(@exiton, $2) if ($1 eq "EXITON");
404         $interaction = $2 if ($1 eq "INTERACTION");
405         next;
406     }
407     sub process_load_copy($) {
408         die("novaboot: '$last_fn' line $.: Missing file name\n") unless /^[^ <]+/;
409         if (/^([^ ]*)(.*?)[[:space:]]*<<([^ ]*)$/) { # Heredoc start
410             $file = [];
411             push @$generated, {filename => $1, content => $file};
412             $EOF = $3;
413             return "$1$2";
414         }
415         if (/^([^ ]*)(.*?)[[:space:]]*< ?(.*)$/) { # Command substitution
416             push @$generated, {filename => $1, command => $3};
417             return "$1$2";
418         }
419         s/\s*$//;               # Strip trailing whitespace
420         return $_;
421     }
422     if (s/^load *//) {          # Load line
423         push @$modules, process_load_copy($_);
424         next;
425     }
426     if (s/^copy *//) {          # Copy line
427         push @$copy, process_load_copy($_);
428         next;
429     }
430     if (s/^chld *//) {          # Chainload line
431         push @$chainload, process_load_copy($_);
432         next;
433     }
434     if (/^run (.*)/) {          # run line
435         push @$generated, {command => $1};
436         next;
437     }
438     if (/^uboot(?::([0-9]+)s)? +(< *)?(.*)/) {  # uboot line
439         # TODO: If U-Boot supports some interactive menu, it might
440         # make sense to store uboot lines per novaboot script.
441         my ($timeout, $redir, $string, $dest) = ($1, $2, $3);
442         if ($string =~ /(.*) *> *(.*)/) {
443             $string = $1;
444             $dest = $2;
445         }
446         push @uboot_init, { command => $redir ? "" : $string,
447                             system =>  $redir ? $string : "",
448                             timeout => $timeout,
449                             dest => $dest,
450         };
451         next;
452     }
453
454     die("novaboot: Cannot parse script '$last_fn' line $.. Didn't you forget 'load' keyword?\n");
455 }
456 # use Data::Dumper;
457 # print Dumper(\@scripts);
458
459 foreach my $script (@scripts) {
460     $modules = $$script{modules};
461     @$modules[0] =~ s/^[^ ]*/$kernel_opt/ if $kernel_opt;
462     @$modules[0] .= ' ' . join(' ', @append) if @append;
463
464     my $kernel;
465     if (exists $variables->{KERNEL}) {
466         $kernel = $variables->{KERNEL};
467     } else {
468         if ($CFG::hypervisor) {
469             $kernel = $CFG::hypervisor . " ";
470             if (exists $variables->{HYPERVISOR_PARAMS}) {
471                 $kernel .= $variables->{HYPERVISOR_PARAMS};
472             } else {
473                 $kernel .= $CFG::hypervisor_params;
474             }
475         }
476     }
477     @$modules = ($kernel, @$modules) if $kernel;
478     @$modules = (@chainloaders, @$modules);
479     @$modules = ("bin/boot/bender", @$modules) if ($bender || defined $ENV{'NOVABOOT_BENDER'});
480 }
481
482 if ($dump_opt) {
483     foreach my $script (@scripts) {
484         print join("\n", @{$$script{modules}})."\n";
485     }
486     exit(0);
487 }
488
489 ## Helper functions
490
491 sub generate_configs($$$) {
492     my ($base, $generated, $filename) = @_;
493     if ($base) { $base = "$base/"; };
494     foreach my $g(@$generated) {
495       if (exists $$g{content}) {
496         my $config = $$g{content};
497         my $fn = $$g{filename};
498         open(my $f, '>', $fn) || die("$fn: $!");
499         map { s|\brom://([^ ]*)|$rom_prefix$base$1|g; print $f "$_"; } @{$config};
500         close($f);
501         print STDERR "novaboot: Created $fn\n";
502       } elsif (exists $$g{command} && ! $no_file_gen) {
503         $ENV{SRCDIR} = dirname(File::Spec->rel2abs( $filename, $invocation_dir ));
504         if (exists $$g{filename}) {
505             system_verbose("( $$g{command} ) > $$g{filename}");
506         } else {
507             system_verbose($$g{command});
508         }
509       }
510     }
511 }
512
513 sub generate_grub_config($$$$;$)
514 {
515     my ($filename, $title, $base, $modules_ref, $preamble) = @_;
516     if ($base) { $base = "$base/"; };
517     open(my $fg, '>', $filename) or die "$filename: $!";
518     print $fg "$preamble\n" if $preamble;
519     print $fg "title $title\n" if $title;
520     #print $fg "root $base\n"; # root doesn't really work for (nd)
521     my $first = 1;
522     foreach (@$modules_ref) {
523         if ($first) {
524             $first = 0;
525             my ($kbin, $kcmd) = split(' ', $_, 2);
526             $kcmd = '' if !defined $kcmd;
527             print $fg "kernel ${base}$kbin $kcmd\n";
528         } else {
529             s|\brom://([^ ]*)|$rom_prefix$base$1|g; # Translate rom:// files - needed for vdisk parameter of sigma0
530             print $fg "module $base$_\n";
531         }
532     }
533     close($fg);
534     print("novaboot: Created $builddir/$filename\n");
535     return $filename;
536 }
537
538 sub generate_syslinux_config($$$$)
539 {
540     my ($filename, $title, $base, $modules_ref) = @_;
541     if ($base && $base !~ /\/$/) { $base = "$base/"; };
542     open(my $fg, '>', $filename) or die "$filename: $!";
543     print $fg "LABEL $title\n";
544     #TODO print $fg "MENU LABEL $human_readable_title\n";
545
546     my ($kbin, $kcmd) = split(' ', @$modules_ref[0], 2);
547
548     if (system("file $kbin|grep 'Linux kernel'") == 0) {
549         my $initrd = @$modules_ref[1];
550         die('Too many "load" lines for Linux kernel') if (scalar @$modules_ref > 2);
551         print $fg "LINUX $base$kbin\n";
552         print $fg "APPEND $kcmd\n";
553         print $fg "INITRD $base$initrd\n";
554     } else {
555         print $fg "KERNEL mboot.c32\n";
556         my @append;
557         foreach (@$modules_ref) {
558             s|\brom://([^ ]*)|$rom_prefix$base$1|g; # Translate rom:// files - needed for vdisk parameter of sigma0
559             push @append, "$base$_";
560             print $fg "APPEND ".join(' --- ', @append)."\n";
561         }
562     }
563     #TODO print $fg "TEXT HELP\n";
564     #TODO print $fg "some help here\n";
565     #TODO print $fg "ENDTEXT\n";
566     close($fg);
567     print("novaboot: Created $builddir/$filename\n");
568     return $filename;
569 }
570
571 sub generate_grub2_config($$$$;$$)
572 {
573     my ($filename, $title, $base, $modules_ref, $preamble, $prolog) = @_;
574     if ($base && substr($base,-1,1) ne '/') { $base = "$base/"; };
575     my $dir = dirname($filename);
576     make_path($dir, {
577                 chmod => 0755,
578     });
579     open(my $fg, '>', $filename) or die "$filename: $!";
580     print $fg "$preamble\n" if $preamble;
581     $title ||= 'novaboot';
582     print $fg "menuentry $title {\n";
583     print $fg "$prolog\n" if $prolog;
584     my $first = 1;
585     my $boot_method = $variables->{BOOT_METHOD} // "multiboot";
586     my $module_load_method = "module";
587     if ($boot_method eq "linux") {
588         $module_load_method = "initrd";
589         die('Too many "load" lines for Linux kernel') if (scalar(@$modules_ref) > 2);
590     }
591     foreach (@$modules_ref) {
592         if ($first) {
593             $first = 0;
594             my ($kbin, $kcmd) = split(' ', $_, 2);
595             $kcmd = '' if !defined $kcmd;
596             print $fg "  $boot_method ${base}$kbin $kcmd\n";
597         } else {
598             my @args = split;
599             if ($boot_method eq "multiboot") {
600                 # GRUB2 doesn't pass filename in multiboot info so we have to duplicate it here
601                 $_ = join(' ', ($args[0], @args));
602                 s|\brom://|$rom_prefix|g; # We do not need to translate path for GRUB2
603             }
604             print $fg "  $module_load_method $base$_\n";
605         }
606     }
607     print $fg "}\n";
608     close($fg);
609     print("novaboot: Created $builddir/$filename\n");
610     return $filename;
611 }
612
613 sub generate_pulsar_config($$$)
614 {
615     my ($filename, $modules_ref, $chainload_ref) = @_;
616     open(my $fg, '>', $filename) or die "$filename: $!";
617     print $fg "root $pulsar_root\n" if defined $pulsar_root;
618     if (scalar(@$chainload_ref) > 0) {
619         print $fg "chld $$chainload_ref[0]\n";
620     } else {
621         my $first = 1;
622         my ($kbin, $kcmd);
623         foreach (@$modules_ref) {
624             if ($first) {
625                 $first = 0;
626                 ($kbin, $kcmd) = split(' ', $_, 2);
627                 $kcmd = '' if !defined $kcmd;
628             } else {
629                 my @args = split;
630                 s|\brom://|$rom_prefix|g;
631                 print $fg "load $_\n";
632             }
633         }
634         # Put kernel as last - this is needed for booting Linux and has no influence on non-Linux OSes
635         print $fg "exec $kbin $kcmd\n";
636     }
637     close($fg);
638     print("novaboot: Created $builddir/$filename\n");
639     return $filename;
640 }
641
642 sub shell_cmd_string(@)
643 {
644     if (scalar(@_) == 1) {
645         return $_[0];
646     } else {
647         return join(' ', map((/^[-_=a-zA-Z0-9\/\.\+]+$/ ? "$_" : "'$_'"), @_));
648     }
649 }
650
651 sub exec_verbose(@)
652 {
653     print STDERR "novaboot: Running: ".shell_cmd_string(@_)."\n";
654     exec(@_);
655     exit(1); # should not be reached
656 }
657
658 sub system_verbose
659 {
660     print STDERR "novaboot: Running: ".shell_cmd_string(@_)."\n";
661     my $ret = system(@_);
662     if ($ret & 0x007f) { die("Command terminated by a signal"); }
663     if ($ret & 0xff00) {die("Command exit with non-zero exit code"); }
664     if ($ret) { die("Command failure $ret"); }
665 }
666
667 sub trim($) {
668     my ($str) = @_;
669     $str =~ s/^\s+|\s+$//g;
670     return $str
671 }
672
673 ## WvTest headline
674
675 if (exists $variables->{WVDESC}) {
676     print STDERR "Testing \"$variables->{WVDESC}\" in $last_fn:\n";
677 } elsif ($last_fn =~ /\.wv$/) {
678     print STDERR "Testing \"all\" in $last_fn:\n";
679 }
680
681 ## Connect to the target and check whether it is not occupied
682
683 # We have to do this before file generation phase, because file
684 # generation is intermixed with file deployment phase and we want to
685 # check whether the target is not used by somebody else before
686 # deploying files. Otherwise, we may rewrite other user's files on a
687 # boot server.
688
689 my $exp; # Expect object to communicate with the target over serial line
690
691 sub kill_exp_on_signal() {
692     # Sometimes, under unclear circumstances (e.g. when running under
693     # both Jenkins and Robotframework), novaboot does not terminate
694     # console command when killed. The console is then blocked by the
695     # stale process forever. Theoretically, this should not happen,
696     # because when novaboot is killed, console command's controlling
697     # terminal sends SIGHUP to the console command and the command
698     # should terminate. It seems that at least SSH sometimes ignores
699     # HUP and does not terminate. The code below seems to work around
700     # that problem by killing the process immediately with SIGTERM,
701     # which is not ignored.
702
703     sub kill_console { kill TERM => $exp->pid if $exp->pid; die "Terminated by SIG$_[0]"; };
704
705     # For our Jenkins/Robotframework use case, it was sufficient to
706     # handle the TERM signal, but to be on the safe side, we also
707     # catch other signals.
708     $SIG{TERM} = \&kill_console;
709     $SIG{HUP} = \&kill_console;
710     $SIG{INT} = \&kill_console;
711     $SIG{QUIT} = \&kill_console;
712 }
713
714
715 my ($amt_user, $amt_password, $amt_host, $amt_port);
716
717 if (defined $iprelay || defined $iprelay_cmd) {
718     if (defined $iprelay) {
719         my $IPRELAY;
720         $iprelay =~ /([.0-9]+)(:([0-9]+))?/;
721         my $addr = $1;
722         my $port = $3 || 23;
723         my $paddr   = sockaddr_in($port, inet_aton($addr));
724         my $proto   = getprotobyname('tcp');
725         socket($IPRELAY, PF_INET, SOCK_STREAM, $proto)  || die "socket: $!";
726         print STDERR "novaboot: Connecting to IP relay... ";
727         connect($IPRELAY, $paddr)    || die "connect: $!";
728         print STDERR "done\n";
729         $exp = Expect->init(\*$IPRELAY);
730         $exp->log_stdout(1);
731     }
732     if (defined $iprelay_cmd) {
733         print STDERR "novaboot: Running: $iprelay_cmd\n";
734         $exp = new Expect;
735         $exp->raw_pty(1);
736         $exp->spawn($iprelay_cmd);
737         kill_exp_on_signal();
738     }
739
740     while (1) {
741         print $exp "\xFF\xF6";  # AYT
742         my $connected = $exp->expect(20, # Timeout in seconds
743                                      '<iprelayd: connected>',
744                                      '-re', '<WEB51 HW[^>]*>')
745             || die "iprelay connection: " . ($! || "timeout");
746         last if $connected;
747     }
748
749     sub relaycmd($$) {
750         my ($relay, $onoff) = @_;
751         die unless ($relay == 1 || $relay == 2);
752
753         my $cmd = ($relay == 1 ? 0x5 : 0x6) | ($onoff ? 0x20 : 0x10);
754         return "\xFF\xFA\x2C\x32".chr($cmd)."\xFF\xF0";
755     }
756
757     sub relayconf($$) {
758         my ($relay, $onoff) = @_;
759         die unless ($relay == 1 || $relay == 2);
760         my $cmd = ($relay == 1 ? 0xdf : 0xbf) | ($onoff ? 0x00 : 0xff);
761         return "\xFF\xFA\x2C\x97".chr($cmd)."\xFF\xF0";
762     }
763
764     sub relay($$;$) {
765         my ($relay, $onoff, $can_giveup) = @_;
766         my $confirmation = '';
767         $exp->log_stdout(0);
768         print $exp relaycmd($relay, $onoff);
769         my $confirmed = $exp->expect(20, # Timeout in seconds
770                                      relayconf($relay, $onoff))
771             || die "iprelay command: " . ($! || "timeout");
772         if (!$confirmed) {
773             if ($can_giveup) {
774                 print("Relay confirmation timeout - ignoring\n");
775             } else {
776                 die "Relay confirmation timeout";
777             }
778         }
779         $exp->log_stdout(1);
780     }
781
782     $target_reset = sub {
783         relay(2, 1, 1); # Reset the machine
784         usleep(100000);
785         relay(2, 0);
786     };
787
788     $target_power_off = sub {
789         relay(1, 1);            # Press power button
790         usleep(6000000);        # Long press to switch off
791         relay(1, 0);
792     };
793
794     $target_power_on = sub {
795         relay(1, 1);            # Press power button
796         usleep(100000);         # Short press
797         relay(1, 0);
798     };
799 }
800 elsif ($serial) {
801     my $CONN;
802     system_verbose("stty -F $serial $stty");
803     open($CONN, "+<", $serial) || die "open $serial: $!";
804     $exp = Expect->init(\*$CONN);
805 }
806 elsif (@remote_cmd) {
807     print STDERR "novaboot: Running: ".shell_cmd_string(@remote_cmd)."\n";
808     $exp = Expect->spawn(@remote_cmd);
809     kill_exp_on_signal();
810 }
811 elsif (defined $amt) {
812     require LWP::UserAgent;
813     require LWP::Authen::Digest;
814
815     sub genXML {
816         my ($host, $username, $password, $schema, $className, $pstate) = @_;
817         #AMT numbers for PowerStateChange (MNI => bluescreen on windows;-)
818         my %pstates = ("on"        => 2,
819                        "standby"   => 4,
820                        "hibernate" => 7,
821                        "off"       => 8,
822                        "reset"     => 10,
823                        "MNI"       => 11);
824         return <<END;
825                 <s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:a="http://schemas.xmlsoap.org/ws/2004/08/addressing" xmlns:w="http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd">
826                 <s:Header><a:To>http://$host:16992/wsman</a:To>
827                 <w:ResourceURI s:mustUnderstand="true">$schema</w:ResourceURI>
828                 <a:ReplyTo><a:Address s:mustUnderstand="true">http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</a:Address></a:ReplyTo>
829                 <a:Action s:mustUnderstand="true">$schema$className</a:Action>
830                 <w:MaxEnvelopeSize s:mustUnderstand="true">153600</w:MaxEnvelopeSize>
831                 <a:MessageID>uuid:709072C9-609C-4B43-B301-075004043C7C</a:MessageID>
832                 <w:Locale xml:lang="en-US" s:mustUnderstand="false" />
833                 <w:OperationTimeout>PT60.000S</w:OperationTimeout>
834                 <w:SelectorSet><w:Selector Name="Name">Intel(r) AMT Power Management Service</w:Selector></w:SelectorSet>
835                 </s:Header><s:Body>
836                 <p:RequestPowerStateChange_INPUT xmlns:p="http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_PowerManagementService">
837                 <p:PowerState>$pstates{$pstate}</p:PowerState>
838                 <p:ManagedElement><a:Address>http://$host:16992/wsman</a:Address>
839                 <a:ReferenceParameters><w:ResourceURI>http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ComputerSystem</w:ResourceURI>
840                 <w:SelectorSet><w:Selector Name="Name">ManagedSystem</w:Selector></w:SelectorSet>
841                 </a:ReferenceParameters></p:ManagedElement>
842                 </p:RequestPowerStateChange_INPUT>
843                 </s:Body></s:Envelope>
844 END
845     }
846
847     sub sendPOST {
848         my ($host, $username, $password, $content) = @_;
849
850         my $ua = LWP::UserAgent->new();
851         $ua->agent("novaboot");
852
853         my $req = HTTP::Request->new(POST => "http://$host:16992/wsman");
854         my $res = $ua->request($req);
855         die ("Unexpected AMT response: " . $res->status_line) unless $res->code == 401;
856
857         my ($realm) = $res->header("WWW-Authenticate") =~ /Digest realm="(.*?)"/;
858         $ua->credentials("$host:16992", $realm, $username => $password);
859
860         # Create a request
861         $req = HTTP::Request->new(POST => "http://$host:16992/wsman");
862         $req->content_type('application/x-www-form-urlencoded');
863         $req->content($content);
864         $res = $ua->request($req);
865         die ("AMT power change request failed: " . $res->status_line) unless $res->is_success;
866         $res->content() =~ /<g:ReturnValue>(\d+)<\/g:ReturnValue>/;
867         return $1;
868     }
869
870     sub powerChange  {
871         my ($host, $username, $password, $pstate)=@_;
872         my $schema="http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_PowerManagementService";
873         my $className="/RequestPowerStateChange";
874         my $content = genXML($host, $username, $password ,$schema, $className, $pstate);
875         return sendPOST($host, $username, $password, $content);
876     }
877
878     ($amt_user,$amt_password,$amt_host,$amt_port) = ($amt =~ /(?:(.*?)(?::(.*))?@)?([^:]*)(?::([0-9]*))?/);;
879     $amt_user ||= "admin";
880     $amt_password ||= $ENV{'AMT_PASSWORD'} || die "AMT password not specified";
881     $amt_host || die "AMT host not specified";
882     $amt_port ||= 16994;
883
884
885     $target_power_off = sub {
886         $exp->close();
887         my $result = powerChange($amt_host,$amt_user,$amt_password, "off");
888         die "AMT power off failed (ReturnValue $result)" if $result != 0;
889     };
890
891     $target_power_on = sub {
892         my $result = powerChange($amt_host,$amt_user,$amt_password, "on");
893         die "AMT power on failed (ReturnValue $result)" if $result != 0;
894     };
895
896     $target_reset = sub {
897         my $result = powerChange($amt_host,$amt_user,$amt_password, "reset");
898         if ($result != 0) {
899             print STDERR "Warning: Cannot reset $amt_host, trying power on. ";
900             $result = powerChange($amt_host,$amt_user,$amt_password, "on");
901         }
902         die "AMT reset failed (ReturnValue $result)" if $result != 0;
903     };
904
905     my $cmd = "amtterm -u $amt_user -p $amt_password $amt_host $amt_port";
906     print STDERR "novaboot: Running: $cmd\n" =~ s/\Q$amt_password\E/???/r;
907     $exp = Expect->spawn($cmd);
908     $exp->expect(10, "RUN_SOL") || die "Expect for 'RUN_SOL': " . ($! || "timeout");
909 }
910
911
912 if ($remote_expect) {
913     $exp || die("No serial line connection");
914     my $log = $exp->log_stdout;
915     if (defined $remote_expect_silent) {
916         $exp->log_stdout(0);
917     }
918     $exp->expect($remote_expect_timeout >= 0 ? $remote_expect_timeout : undef,
919                  $remote_expect) || die "Expect for '$remote_expect':" . ($! || "timeout");;
920     if (defined $remote_expect_silent) {
921         $exp->log_stdout($log);
922         print $exp->after() if $log;
923     }
924 }
925
926 if (@reset_cmd) {
927     $target_reset = sub {
928         system_verbose(@reset_cmd);
929     };
930 }
931
932 if (defined $reset_send) {
933     $target_reset = sub {
934         $reset_send =~ s/\\n/\n/g;
935         $exp->send($reset_send);
936     };
937 }
938
939 if (defined $on_opt && defined $target_power_on) {
940     &$target_power_on();
941     exit;
942 }
943 if (defined $off_opt && defined $target_power_off) {
944     print STDERR "novaboot: Switching the target off...\n";
945     &$target_power_off();
946     exit;
947 }
948
949 $builddir ||= dirname(File::Spec->rel2abs( ${$scripts[0]}{filename})) if scalar @scripts;
950 if (defined $builddir) {
951     chdir($builddir) or die "Can't change directory to $builddir: $!";
952     print STDERR "novaboot: Entering directory `$builddir'\n";
953 } else {
954     $builddir = $invocation_dir;
955 }
956
957 ## File generation phase
958 my (%files_iso, $menu_iso, $filename);
959 my $config_name = '';
960 my $prefix = '';
961
962 foreach my $script (@scripts) {
963     $filename = $$script{filename};
964     $modules = $$script{modules};
965     $generated = $$script{generated};
966     $variables = $$script{variables};
967
968     ($config_name = $filename) =~ s#.*/##;
969     $config_name = $config_name_opt if (defined $config_name_opt);
970
971     if (exists $variables->{BUILDDIR}) {
972         $builddir = File::Spec->rel2abs($variables->{BUILDDIR});
973         chdir($builddir) or die "Can't change directory to $builddir: $!";
974         print STDERR "novaboot: Entering directory `$builddir'\n";
975     }
976
977     if ($grub_prefix) {
978         $prefix = $grub_prefix;
979         $prefix =~ s/\$NAME/$config_name/;
980         $prefix =~ s/\$BUILDDIR/$builddir/;
981     }
982     # TODO: use $grub_prefix as first parameter if some switch is given
983     generate_configs('', $generated, $filename);
984
985 ### Generate bootloader configuration files
986     my @bootloader_configs;
987     push @bootloader_configs, generate_grub_config($grub_config, $config_name, $prefix, $modules, $grub_preamble) if (defined $grub_config);
988     push @bootloader_configs, generate_grub2_config($grub2_config, $config_name, $prefix, $modules, $grub_preamble, $grub2_prolog) if (defined $grub2_config);
989     push @bootloader_configs, generate_pulsar_config('config-'.($pulsar||'novaboot'), $modules, $chainload) if (defined $pulsar);
990
991 ### Run scons or make
992     {
993         my @all;
994         push @all, @$modules;
995         push @all, @$copy;
996         push @all, @$chainload;
997         my @files = map({ ($file) = m/([^ ]*)/; $file; } @all);
998
999         # Filter-out generated files
1000         my @to_build = grep({ my $file = $_; !scalar(grep($file eq ($$_{filename} || ''), @$generated)) } @files);
1001
1002         system_verbose($scons || $CFG::scons." ".join(" ", @to_build)) if (defined $scons);
1003         system_verbose($make  || $CFG::make ." ".join(" ", @to_build)) if (defined $make);
1004     }
1005
1006 ### Copy files (using rsync)
1007     if (defined $server && !defined($gen_only)) {
1008         (my $real_server = $server) =~ s/\$NAME/$config_name/;
1009
1010         my ($hostname, $path) = split(":", $real_server, 2);
1011         if (! defined $path) {
1012             $path = $hostname;
1013             $hostname = "";
1014         }
1015         my $files = join(" ", map({ ($file) = m/([^ ]*)/; $file; } ( @$modules, @bootloader_configs, @$copy)));
1016         map({ my $file = (split)[0]; die "Not a file: $file: $!" if ! -e $file || -d $file; } @$modules);
1017         my $istty = -t STDOUT && ($ENV{'TERM'} || 'dumb') ne 'dumb';
1018         my $progress = $istty ? "--progress" : "";
1019         if ($files) {
1020             system_verbose("rsync $progress -RL --chmod=ugo=rwX $rsync_flags $files $real_server");
1021             if ($server =~ m|/\$NAME$| && $concat) {
1022                 my $cmd = join("; ", map { "( cd $path/.. && cat */$_ > $_ )" } @bootloader_configs);
1023                 system_verbose($hostname ? "ssh $hostname '$cmd'" : $cmd);
1024             }
1025         }
1026     }
1027
1028 ### Prepare ISO image generation
1029     if (defined $iso_image) {
1030         generate_configs("(cd)", $generated, $filename);
1031         my $menu;
1032         generate_syslinux_config(\$menu, $config_name, "/", $modules);
1033         $menu_iso .= "$menu\n";
1034         map { ($file,undef) = split; $files_iso{$file} = 1; } @$modules;
1035     }
1036 }
1037
1038 ## Generate ISO image
1039 if (defined $iso_image) {
1040     system_verbose("mkdir -p isolinux");
1041
1042     my @files;
1043     if (-f '/usr/lib/ISOLINUX/isolinux.bin') {
1044         # Newer ISOLINUX version
1045         @files = qw(/usr/lib/ISOLINUX/isolinux.bin /usr/lib/syslinux/modules/bios/mboot.c32 /usr/lib/syslinux/modules/bios/libcom32.c32 /usr/lib/syslinux/modules/bios/menu.c32 /usr/lib/syslinux/modules/bios/ldlinux.c32);
1046     } elsif (-f '/usr/lib/syslinux/isolinux.bin') {
1047         # Older ISOLINUX version
1048         @files = qw(/usr/lib/syslinux/isolinux.bin /usr/lib/syslinux/mboot.c32 /usr/lib/syslinux/menu.c32);
1049     } else {
1050         # NixOS and maybe others
1051         my $syslinux = `which syslinux` || die "Cannot find syslinux";
1052         chomp $syslinux;
1053         $syslinux =~ s,/bin/syslinux$,,;
1054         @files = ("$syslinux/share/syslinux/isolinux.bin", "$syslinux/share/syslinux/mboot.c32", "$syslinux/share/syslinux/libcom32.c32", "$syslinux/share/syslinux/menu.c32", "$syslinux/share/syslinux/ldlinux.c32");
1055     }
1056     system_verbose("cp @files isolinux && chmod +w isolinux/*");
1057     open(my $fh, ">isolinux/isolinux.cfg");
1058     if ($#scripts) {
1059         print $fh "TIMEOUT 50\n";
1060         print $fh "DEFAULT menu\n";
1061     } else {
1062         print $fh "DEFAULT $config_name\n";
1063     }
1064     print $fh "$menu_iso";
1065     close($fh);
1066
1067     my $files = join(" ", map("$_=$_", (keys(%files_iso), 'isolinux/isolinux.cfg', map(s|.*/|isolinux/|r, @files))));
1068     $iso_image ||= "$config_name.iso";
1069
1070     # Note: We use -U flag below to "Allow 'untranslated' filenames,
1071     # completely violating the ISO9660 standards". Without this
1072     # option, isolinux is not able to read files names for example
1073     # bzImage-3.0.
1074     system_verbose("$CFG::genisoimage -R -b isolinux/isolinux.bin -c isolinux/boot.cat -no-emul-boot -boot-load-size 4 -boot-info-table -hide-rr-moved -U -o $iso_image -graft-points $files");
1075     print("ISO image created: $builddir/$iso_image\n");
1076 }
1077
1078 exit(0) if defined $gen_only;
1079
1080 ## Boot the system using various methods and send serial output to stdout
1081
1082 if (scalar(@scripts) > 1 && ( defined $dhcp_tftp || defined $serial || defined $iprelay)) {
1083     die "You cannot do this with multiple scripts simultaneously";
1084 }
1085
1086 if ($variables->{WVTEST_TIMEOUT}) {
1087     print STDERR "wvtest: timeout ", $variables->{WVTEST_TIMEOUT}, "\n";
1088 }
1089
1090 ### Start in Qemu
1091
1092 if (defined $qemu) {
1093     # Qemu
1094     $qemu ||= $variables->{QEMU} || $CFG::qemu;
1095     my @qemu_flags = split(" ", $qemu);
1096     $qemu = shift(@qemu_flags);
1097
1098     @qemu_flags = split(/ +/, trim($variables->{QEMU_FLAGS})) if exists $variables->{QEMU_FLAGS};
1099     @qemu_flags = split(/ +/, trim($qemu_flags_cmd)) if $qemu_flags_cmd;
1100     push(@qemu_flags, split(/ +/, trim($qemu_append || '')));
1101
1102     if (defined $iso_image) {
1103         # Boot NOVA with grub (and test the iso image)
1104         push(@qemu_flags, ('-cdrom', $iso_image));
1105     } else {
1106         # Boot NOVA without GRUB
1107
1108         # Non-patched qemu doesn't like commas, but NUL can live with pluses instead of commans
1109         foreach (@$modules) {s/,/+/g;}
1110         generate_configs("", $generated, $filename);
1111
1112         if (scalar @$modules) {
1113             my ($kbin, $kcmd) = split(' ', shift(@$modules), 2);
1114             $kcmd = '' if !defined $kcmd;
1115             my $dtb;
1116             @$modules = map { if (/\.dtb$/) { $dtb=$_; (); } else { $_ } } @$modules;
1117             my $initrd = join ",", @$modules;
1118
1119             push(@qemu_flags, ('-kernel', $kbin, '-append', $kcmd));
1120             push(@qemu_flags, ('-initrd', $initrd)) if $initrd;
1121             push(@qemu_flags, ('-dtb', $dtb)) if $dtb;
1122         }
1123     }
1124     if (!grep /^-serial$/, @qemu_flags) {
1125         push(@qemu_flags,  qw(-serial stdio)); # Redirect serial output (for collecting test restuls)
1126     }
1127     unshift(@qemu_flags, ('-name', $config_name));
1128     print STDERR "novaboot: Running: ".shell_cmd_string($qemu, @qemu_flags)."\n";
1129     $exp = Expect->spawn(($qemu, @qemu_flags)) || die("exec() failed: $!");
1130 }
1131
1132 ### Local DHCPD and TFTPD
1133
1134 my ($dhcpd_pid, $tftpd_pid);
1135
1136 $tftp=1 if $tftp_port;
1137
1138 if (defined $dhcp_tftp)
1139 {
1140     generate_configs("(nd)", $generated, $filename);
1141     system_verbose('mkdir -p tftpboot');
1142     generate_grub_config("tftpboot/os-menu.lst", $config_name, "(nd)", \@$modules, "timeout 0");
1143     open(my $fh, '>', 'dhcpd.conf');
1144     my $mac = `cat /sys/class/net/$netif/address`;
1145     chomp $mac;
1146     print $fh "
1147 subnet 10.23.23.0 netmask 255.255.255.0 {
1148         range 10.23.23.10 10.23.23.100;
1149         next-server 10.23.23.1;
1150 }
1151 class \"pxe-clients\" {
1152      match option vendor-class-identifier;
1153 }
1154 subclass \"pxe-clients\"  \"PXEClient:Arch:00000:UNDI:002001\" {
1155      option bootfile-name \"boot/grub/i386-pc/core.0\";
1156 }
1157 subclass \"pxe-clients\"  \"PXEClient:Arch:00007:UNDI:003016\" {
1158      option bootfile-name \"boot/grub/x86_64-efi/core.efi\";
1159 }
1160 host server {
1161         hardware ethernet $mac;
1162         fixed-address 10.23.23.1;
1163 }";
1164     close($fh);
1165     system_verbose("sudo ip a add 10.23.23.1/24 dev $netif;
1166             sudo ip l set dev $netif up;
1167             sudo touch dhcpd.leases");
1168
1169     # We run servers by forking ourselves, because the servers end up
1170     # in our process group and get killed by signals sent to the
1171     # process group (e.g. Ctrl-C on terminal).
1172     $dhcpd_pid = fork();
1173     exec_verbose("sudo dhcpd -d -cf dhcpd.conf -lf dhcpd.leases -pf dhcpd.pid") if ($dhcpd_pid == 0);
1174 }
1175
1176 if (defined $dhcp_tftp || defined $tftp) {
1177     $tftp_port ||= 69;
1178     my $tftp_root = "$builddir";
1179     $tftp_root = "$server" if(defined $server);
1180
1181     # Prepare a GRUB netboot directory
1182     system_verbose("grub-mknetdir --net-directory=$tftp_root") if (defined $grub2_config);
1183
1184     # Generate TFTP mapfile
1185     open(my $fh, '>', "$tftp_root/mapfile");
1186     print $fh "# Some PXE clients (mainly UEFI) have bug. They add zero byte to the end of the
1187 # path name. This rule removes it
1188 r     \\.efi.*   \\.efi";
1189     close($fh);
1190     # Unfortunately, tftpd requires root privileges even with
1191     # non-privileged (>1023) port due to initgroups().
1192     system_verbose("sudo in.tftpd --listen --secure -v -v -v --pidfile tftpd.pid -m mapfile --address :$tftp_port $tftp_root");
1193
1194     # Kill server when we die
1195     $SIG{__DIE__} = sub { system_verbose('sudo pkill --pidfile=dhcpd.pid') if (defined $dhcp_tftp);
1196                           system_verbose("sudo pkill --pidfile=$tftp_root/tftpd.pid"); };
1197
1198     # We have to kill tftpd explicitely, because it is not in our process group
1199     $SIG{INT} = sub { system_verbose("sudo pkill --pidfile=$tftp_root/tftpd.pid"); exit(0); };
1200 }
1201
1202 ### AMT IDE-R
1203 if (defined $ider) {
1204     my $ider_cmd= "amtider -c $iso_image -u $amt_user -p $amt_password $amt_host $amt_port"  ;
1205     print STDERR "novaboot: Running: $ider_cmd\n" =~ s/\Q$amt_password\E/???/r;
1206     my $ider_pid = fork();
1207     if ($ider_pid == 0) {
1208         exec($ider_cmd);
1209         die "IDE redirection failed";
1210     }
1211     # FIXME: This collides with --tftp option. Hopefully, nobody needs
1212     # to use both simultaneously.
1213     $SIG{__DIE__} = sub { system_verbose('kill $ider_pid'); };
1214 }
1215
1216 ### Reset target (IP relay, AMT, ...)
1217
1218 if (defined $target_reset && $reset) {
1219     print STDERR "novaboot: Resetting the test box... ";
1220     &$target_reset();
1221     print STDERR "done\n";
1222     if (defined $exp) {
1223         # We don't want to output anything printed by the target
1224         # before reset so we clear the buffers now. This is, however,
1225         # not ideal because we may loose some data that were sent
1226         # after the reset. If this is a problem, one should reset and
1227         # connect to serial line in atomic manner. For example, if
1228         # supported by hardware, use --remote-cmd 'sterm -d ...' and
1229         # do not use separate --reset-cmd.
1230         my $log = $exp->log_stdout;
1231         $exp->log_stdout(0);
1232         $exp->expect(0); # Read data from target
1233         $exp->clear_accum();    # Clear the read data
1234         $exp->log_stdout($log);
1235     }
1236 }
1237
1238 ### U-boot conversation
1239 if (defined $uboot) {
1240     my $uboot_prompt = $uboot || '=> ';
1241     print STDERR "novaboot: Waiting for U-Boot prompt...\n";
1242     $exp || die("No serial line connection");
1243     $exp->log_stdout(1);
1244     #$exp->exp_internal(1);
1245     $exp->expect(20,
1246                  [qr/Hit any key to stop autoboot:/, sub {
1247                      $exp->send($uboot_stop_key // "\n");
1248                      exp_continue; }],
1249                  $uboot_prompt) || die "No U-Boot prompt deteceted";
1250     foreach my $cmdspec (@uboot_init) {
1251         my ($cmd, $timeout);
1252         die "Internal error - please report a bug" unless ref($cmdspec) eq "HASH";
1253
1254         if ($cmdspec->{system}) {
1255             $cmd = `$cmdspec->{system}`;
1256         } else {
1257             $cmd = $cmdspec->{command};
1258         }
1259         $timeout = $cmdspec->{timeout} // 10;
1260
1261         if ($cmd =~ /\$NB_MYIP/) {
1262             my $ip = (grep /inet /, `ip addr show $netif`)[0] || die "Problem determining IP address of $netif";
1263             $ip =~ s/\s*inet ([0-9.]*).*/$1/;
1264             $cmd =~ s/\$NB_MYIP/$ip/g;
1265         }
1266         if ($cmd =~ /\$NB_PREFIX/) {
1267             my $p = $prefix;
1268             $p =~ s|/*$||;
1269             $cmd =~ s/\$NB_PREFIX/$p/g;
1270         }
1271         chomp($cmd);
1272         $exp->send("$cmd\n");
1273
1274         my ($matched_pattern_position, $error,
1275             $successfully_matching_string,
1276             $before_match, $after_match) =
1277                 $exp->expect($timeout, $uboot_prompt);
1278         die "No U-Boot prompt: $error" if $error;
1279
1280         if ($cmdspec->{dest}) {
1281             open(my $fh, ">", $cmdspec->{dest}) or die "Cannot open '$cmdspec->{dest}': $!";
1282             print $fh $before_match;
1283             close($fh);
1284         }
1285     }
1286
1287     # Load files if there are some load lines in the script
1288     if (scalar(@$modules) > 0  && !$variables->{NO_BOOT}) {
1289         my ($kbin, $kcmd) = split(' ', shift(@$modules), 2);
1290         my $dtb;
1291         @$modules = map { if (/\.dtb$/) { $dtb=$_; (); } else { $_ } } @$modules;
1292         my $initrd = shift @$modules;
1293
1294         if (defined $kbin && $kbin ne '/dev/null') {
1295             die "No '--uboot-addr kernel' given" unless $uboot_addr{kernel};
1296             $exp->send("tftpboot $uboot_addr{kernel} $prefix$kbin\n");
1297             $exp->expect(15,
1298                          [qr/##/, sub { exp_continue; }],
1299                          $uboot_prompt) || die "Kernel load: " . ($! || "timeout");
1300         }
1301         if (defined $dtb) {
1302             die "No '--uboot-addr fdt' given" unless $uboot_addr{fdt};
1303             $exp->send("tftpboot $uboot_addr{fdt} $prefix$dtb\n");
1304             $exp->expect(15,
1305                          [qr/##/, sub { exp_continue; }],
1306                          $uboot_prompt) || die "Device tree load: " . ($! || "timeout");
1307         } else  {
1308             $uboot_addr{fdt} = '';
1309         }
1310         if (defined $initrd) {
1311             die "No '--uboot-addr ramdisk' given" unless $uboot_addr{ramdisk};
1312             $exp->send("tftpboot $uboot_addr{ramdisk} $prefix$initrd\n");
1313             $exp->expect(15,
1314                          [qr/##/, sub { exp_continue; }],
1315                          $uboot_prompt) || die "Initrd load: " . ($! || "timeout");
1316         } else {
1317             $uboot_addr{ramdisk} = '-';
1318         }
1319
1320         $kcmd //= '';
1321         $exp->send("setenv bootargs $kcmd\n");
1322         $exp->expect(5, $uboot_prompt)  || die "U-Boot prompt: " . ($! || "timeout");
1323
1324     }
1325     $uboot_cmd //= $variables->{UBOOT_CMD} // 'bootm $kernel_addr $ramdisk_addr $fdt_addr';
1326     if (!$variables->{NO_BOOT} && $uboot_cmd ne '') {
1327         $uboot_cmd =~ s/\$kernel_addr/$uboot_addr{kernel}/g;
1328         $uboot_cmd =~ s/\$ramdisk_addr/$uboot_addr{ramdisk}/g;
1329         $uboot_cmd =~ s/\$fdt_addr/$uboot_addr{fdt}/g;
1330
1331         $exp->send($uboot_cmd . "\n");
1332         $exp->expect(5, "\n")  || die "U-Boot command: " . ($! || "timeout");
1333     }
1334 }
1335
1336 ### Serial line interaction
1337 if ($interaction && defined $exp) {
1338     # Serial line of the target is available
1339     my $interrupt = 'Ctrl-C';
1340     if ($interactive && !@exiton) {
1341         $interrupt = '"~~."';
1342     }
1343     print STDERR "novaboot: Serial line interaction (press $interrupt to interrupt)...\n";
1344     $exp->log_stdout(1);
1345     if (@exiton) {
1346         $exp->expect($exiton_timeout, @exiton, @expect_raw) || die("exiton: " . ($! || "timeout"));
1347     } else {
1348         my @inputs = ($exp);
1349         my $infile = new IO::File;
1350         $infile->IO::File::fdopen(*STDIN,'r');
1351         my $in_object = Expect->exp_init($infile);
1352         $in_object->set_group($exp);
1353
1354         if ($interactive) {
1355             $in_object->set_seq('~~\.', sub { print STDERR "novaboot: Escape sequence detected\r\n"; undef; });
1356             $in_object->manual_stty(0);   # Use raw terminal mode
1357         } else {
1358             $in_object->manual_stty(1);   # Do not modify terminal settings
1359         }
1360         push(@inputs, $in_object);
1361         #use Data::Dumper;
1362         #print Dumper(\@expect_raw);
1363         $exp->expect(undef, @expect_raw) if @expect_raw;
1364
1365         $^W = 0; # Suppress Expect warning: handle id(3) is not a tty. Not changing mode at /usr/share/perl5/Expect.pm line 393, <> line 8.
1366         Expect::interconnect(@inputs) unless defined($exp->exitstatus);
1367         $^W = 1;
1368     }
1369 }
1370
1371 # When exp-spawned command ignores SIGHUP, Expect waits 5 seconds
1372 # before killing it. We kill it by SIGTERM immediately.
1373 kill TERM => $exp->pid if defined $exp && $exp->pid;
1374
1375 ## Kill dhcpc or tftpd
1376 if (defined $dhcp_tftp || defined $tftp) {
1377     die("novaboot: This should kill servers on background\n");
1378 }
1379
1380 # Always finish novaboot output with newline
1381 print "\n" if $final_eol;
1382
1383 ## Documentation
1384
1385 =encoding utf8
1386
1387 =head1 NAME
1388
1389 novaboot - Boots a locally compiled operating system on a remote
1390 target or in qemu
1391
1392 =head1 SYNOPSIS
1393
1394 B<novaboot> --help
1395
1396 B<novaboot> [option]... [--] script...
1397
1398 B<./script> [option]...
1399
1400 =head1 DESCRIPTION
1401
1402 Novaboot makes booting of a locally compiled operating system (OS)
1403 (e.g. NOVA or Linux) on remote targets as simple as running a program
1404 locally. It automates things like copying OS images to a TFTP server,
1405 generation of bootloader configuration files, resetting of target
1406 hardware or redirection of target's serial line to stdin/out. Novaboot
1407 is highly configurable and makes it easy to boot a single image on
1408 different targets or different images on a single target.
1409
1410 Novaboot operation is controlled by configuration files, command line
1411 options and by a so-called novaboot script, which can be thought as a
1412 generalization of bootloader configuration files (see L</"NOVABOOT
1413 SCRIPT SYNTAX">). The typical way of using novaboot is to make the
1414 novaboot script executable and set its first line to I<#!/usr/bin/env
1415 novaboot>. Then, booting a particular OS configuration becomes the
1416 same as executing a local program â€“ the novaboot script.
1417
1418 Novaboot uses configuration files to, among other things, define
1419 command line options needed for different targets. Users typically use
1420 only the B<-t>/B<--target> command line option to select the target.
1421 Internally, this option expands to the pre-configured options.
1422 Novaboot searches configuration files at multiple places, which allows
1423 having per-system, per-user or per-project configurations.
1424 Configuration file syntax is described in section L</"CONFIGURATION
1425 FILES">.
1426
1427 Novaboot newcomers may be confused by a large number of configuration
1428 options. Understanding all these options is not always needed,
1429 depending on the used setup. The L<figure from the doc directory
1430 |https://github.com/wentasah/novaboot/blob/master/doc/typical-setups.svg>
1431 shows different setups that vary in how much effort is needed
1432 to configure novaboot for them. The setups are:
1433
1434 =over 3
1435
1436 =item A: Laptop and target device only
1437
1438 This requires to configure everything on the laptop side, including a
1439 serial line connection (L</--serial>, L</--remote-cmd>, ...), power
1440 on/off/reset commands (L</--reset-cmd>, ...), TFTP server
1441 (L</--copy>, L</--prefix>...), device IP addresses, etc.
1442
1443 =item B: Laptop, target device and external TFTP server
1444
1445 Like the previous setup, but the TFTP (and maybe DHCP) configuration
1446 is handled by a server. Novaboot users need to understand where to
1447 copy their files to the TFTP server (L</--copy>) and which IP
1448 addresses their target will get, but do not need to configure the
1449 servers themselves.
1450
1451 =item C: Novaboot server running novaboot-shell
1452
1453 With this setup, the configuration is done on the server. Users only
1454 need to know the SSH account (L</--ssh>) used to communicate between
1455 novaboot and novaboot server. The server is implemented as a
1456 restricted shell (L<novaboot-shell(1)>) on the server. No need to give
1457 full shell access to novaboot users on the server.
1458
1459 =back
1460
1461 =head2 Simple examples of using C<novaboot>:
1462
1463 To boot Linux (files F<bzImage> and F<rootfs.cpio> in current
1464 directory), create F<mylinux> file with this content:
1465
1466     #!/usr/bin/env novaboot
1467     load bzImage console=ttyS0,115200
1468     load rootfs.cpio
1469
1470 =over 3
1471
1472 =item 1.
1473
1474 Booting an OS in Qemu can be accomplished by giving the B<--qemu> option.
1475 Thus running
1476
1477  novaboot --qemu mylinux
1478
1479 (or C<./mylinux --qemu> as described above) will run Qemu and make it
1480 boot the configuration specified in the F<mylinux> script. How is qemu
1481 started can be configured in various ways (see below).
1482
1483 =item 2.
1484
1485 Create a bootloader configuration file (currently supported
1486 bootloaders are GRUB, GRUB2, ISOLINUX, Pulsar, and U-Boot) and copy it
1487 with all other files needed for booting to a remote TFTP server. Then
1488 use a TCP/IP-controlled relay/serial-to-TCP converter to reset the
1489 target and receive its serial output.
1490
1491  ./mylinux --grub2 --copy=192.168.1.1:/tftp --iprelay=192.168.1.2
1492
1493 Alternatively, you can put these switches to the configuration file
1494 and run:
1495
1496  ./mylinux --target mytarget
1497
1498 =item 3.
1499
1500 Specifying all the options needed by novaboot to successfully control
1501 the target, either on command line or in configuration files, can be
1502 difficult for users. Novaboot supports configuring the target
1503 centrally via L<novaboot-shell(1)> on a server. With such a
1504 configuration, users only need to use the B<--ssh> option to specify
1505 where to boot their OS:
1506
1507  ./mylinux --ssh myboard@example.com
1508
1509 Typically, the server is the computer connected to and controlling the
1510 target board and running the TFTP server.
1511
1512 =item 4.
1513
1514 Run DHCP and TFTP server on developer's machine to boot the target
1515 from it.
1516
1517  ./mylinux --dhcp-tftp
1518
1519 This usage is useful when no network infrastructure is in place, and
1520 the target is connected directly to developer's box.
1521
1522 =item 5.
1523
1524 Create bootable ISO image.
1525
1526  novaboot --iso -- script1 script2
1527
1528 The created ISO image will have ISOLINUX bootloader installed on it,
1529 and the boot menu will allow selecting between I<script1> and
1530 I<script2> configurations.
1531
1532 =back
1533
1534 =head1 OPTIONS AND PHASES
1535
1536 Novaboot performs its work in several phases. Command line options
1537 described bellow influence the execution of each phase or allow their
1538 skipping. The list of phases (in the execution order) is as follows.
1539
1540 =over
1541
1542 =item 1. L<Configuration reading|/Configuration reading phase>
1543
1544 =item 2. L<Command line processing|/Command line processing phase>
1545
1546 =item 3. L<Script preprocessing|/Script preprocessing phase>
1547
1548 =item 4. L<File generation|/File generation phase>
1549
1550 =item 5. L<Target connection|/Target connection check>
1551
1552 =item 6. L<File deployment|/File deployment phase>
1553
1554 =item 7. L<Target power-on and reset|/Target power-on and reset phase>
1555
1556 =item 8. L<Interaction with the bootloader|/Interaction with the bootloader on the target>
1557
1558 =item 9. L<Target interaction|/Target interaction phase>
1559
1560 =back
1561
1562 Each phase is described in the following sections together with the
1563 command line options that control it.
1564
1565 =head2 Configuration reading phase
1566
1567 After starting, novaboot reads zero or more configuration files. We
1568 describe their content in section L</"CONFIGURATION FILES">. By default, the
1569 configuration is read from multiple locations. First from the system
1570 configuration directory (F</etc/novaboot.d/>), second from the user
1571 configuration file (F<~/.config/novaboot>) and third from F<.novaboot>
1572 files along the path to the current directory. Alternatively, a single
1573 configuration file specified with the B<-c> switch or with the
1574 C<NOVABOOT_CONFIG> environment variable is read. The latter read files
1575 override settings from the former ones.
1576
1577 The system configuration directory is determined by the content of
1578 NOVABOOT_CONFIG_DIR environment variable and defaults to
1579 F</etc/novaboot.d>. Files in this directory with names consisting
1580 solely of English letters, numbers, dashes '-' and underscores '_'
1581 (note that dot '.' is not included) are read in alphabetical order.
1582
1583 Then, the user configuration file is read from
1584 F<$XDG_CONFIG_HOME/novaboot>. If C<$XDG_CONFIG_HOME> environment
1585 variable is not set F<~/.config/novaboot> is read instead.
1586
1587 Finally, novaboot searches for files named F<.novaboot> starting from the
1588 directory of the novaboot script (or working directory, see bellow)
1589 and continuing upwards up to the root directory. The found
1590 configuration files are then read in the opposite order (i.e. from the
1591 root directory downwards). This ordering allows having, for example, a project
1592 specific configuration in F<~/project/.novaboot>.
1593
1594 Note the difference between F<~/.config/novaboot> and F<~/.novaboot>.
1595 The former one is always read, whereas the latter only when novaboot
1596 script or working directory is under the C<$HOME> directory.
1597
1598 In certain cases, the location of the novaboot script cannot be
1599 determined in this early phase. This situation happens either when the script is
1600 read from the standard input or when novaboot is invoked explicitly as
1601 in the example L</"4."> above. In this case, the current working
1602 directory is used as a starting point for configuration file search
1603 instead of the novaboot script directory.
1604
1605 =over 8
1606
1607 =item -c, --config=I<filename>
1608
1609 Use the specified configuration file instead of the default one(s).
1610
1611 =back
1612
1613 =head2 Command line processing phase
1614
1615 =over 8
1616
1617 =item --dump-config
1618
1619 Dump the current configuration to stdout end exit. Useful as an
1620 initial template for a configuration file.
1621
1622 =item -h, --help
1623
1624 Print short (B<-h>) or long (B<--help>) help.
1625
1626 =item -t, --target=I<target>
1627
1628 This option serves as a user configurable shortcut for other novaboot
1629 options. The effect of this option is the same as specifying the
1630 options stored in the C<%targets> configuration variable under key
1631 I<target>. See also L</"CONFIGURATION FILES">.
1632
1633 When this option is not given, novaboot tries to determine the target
1634 to use from either B<NOVABOOT_TARGET> environment variable or
1635 B<$default_target> configuration file variable.
1636
1637 =item --ssh=I<user@hostname>
1638
1639 Configures novaboot to control the target via C<novaboot-shell>
1640 running remotely via SSH.
1641
1642 Using this option is the same as specifying B<--remote-cmd>,
1643 B<--remote-expect>, B<--copy> B<--rsync-flags>, B<--prefix> and
1644 B<--reset-cmd> manually in a way compatible with C<novaboot-shell>.
1645 The server can be configured to provide other, safe bootloader-related
1646 options, to the client. When this happens, novaboot prints them to
1647 stdout.
1648
1649 Currently, this in an initial experimental implementation. We plan to
1650 change/extend this feature soon!
1651
1652 =back
1653
1654 =head2 Script preprocessing phase
1655
1656 This phase allows modifying the parsed novaboot script before it is
1657 used in the later phases.
1658
1659 =over 8
1660
1661 =item -a, --append=I<parameters>
1662
1663 Append a string to the first C<load> line in the novaboot script. This option
1664 can be used to append parameters to the kernel's or root task's
1665 command line. This option can appear multiple times.
1666
1667 =item -b, --bender
1668
1669 Use L<Bender|https://github.com/TUD-OS/morbo/blob/master/standalone/bender.c>
1670 chainloader. Bender scans the PCI bus for PCI serial ports and stores
1671 the information about them in the BIOS data area for use by the
1672 kernel.
1673
1674 =item --chainloader=I<chainloader>
1675
1676 Specifies a chainloader that is loaded before the kernel and other
1677 files specified in the novaboot script. E.g. 'bin/boot/bender
1678 promisc'.
1679
1680 =item --dump
1681
1682 Print the modules to boot and their parameters, after this phase
1683 finishes. Then exit. This is useful for seeing the effect of other
1684 options in this section.
1685
1686 =item -k, --kernel=F<file>
1687
1688 Replace the first word on the first C<load> line in the novaboot
1689 script with F<file>.
1690
1691 =item --scriptmod=I<Perl expression>
1692
1693 When novaboot reads the script, I<Perl expression> is executed for every
1694 line (in $_ variable). For example, C<novaboot
1695 --scriptmod=s/sigma0/omega6/g> replaces every occurrence of I<sigma0>
1696 in the script with I<omega6>.
1697
1698 When this option is present, it overrides I<$script_modifier> variable
1699 from the configuration file, which has the same effect. If this option
1700 is given multiple times all expressions are evaluated in the command
1701 line order.
1702
1703 =back
1704
1705 =head2 File generation phase
1706
1707 In this phase, files needed for booting are generated in a so-called
1708 I<build directory> (see L</--build-dir>). In most cases configuration
1709 for a bootloader is generated automatically by novaboot. It is also
1710 possible to generate other files using I<heredoc> or I<"<"> syntax in
1711 novaboot scripts. Finally, novaboot can generate binaries in this phases by
1712 running C<scons> or C<make>.
1713
1714 =over 8
1715
1716 =item --build-dir=I<directory>
1717
1718 Overrides the default build directory location.
1719
1720 The default build directory location is determined as follows: If the
1721 configuration file defines the C<$builddir> variable, its value is
1722 used. Otherwise, it is the directory that contains the first processed
1723 novaboot script.
1724
1725 See also L</BUILDDIR> variable.
1726
1727 =item -g, --grub[=I<filename>]
1728
1729 Generates grub bootloader menu file. If the I<filename> is not
1730 specified, F<menu.lst> is used. The I<filename> is relative to the
1731 build directory (see B<--build-dir>).
1732
1733 =item --grub-preamble=I<prefix>
1734
1735 Specifies the I<preamble> that is at the beginning of the generated
1736 GRUB or GRUB2 config files. This is useful for specifying GRUB's
1737 timeout.
1738
1739 =item --prefix=I<prefix>
1740
1741 Specifies I<prefix> (e.g. F</srv/tftp>) that is put in front of every
1742 filename in generated bootloader configuration files (or in U-Boot
1743 commands).
1744
1745 If the I<prefix> contains string $NAME, it will be replaced with the
1746 name of the novaboot script (see also B<--name>).
1747
1748 If the I<prefix> contains string $BUILDDIR, it will be replaced with
1749 the build directory (see also B<--build-dir>).
1750
1751 =item --grub-prefix
1752
1753 Alias for B<--prefix>.
1754
1755 =item --grub2[=I<filename>]
1756
1757 Generate GRUB2 menu entry in I<filename>. If I<filename> is not
1758 specified F<./boot/grub/grub.cfg> is used. The content of the menu entry can be
1759 customized with B<--grub-preamble>, B<--grub2-prolog> or
1760 B<--grub_prefix> options.
1761
1762 GRUB2 can boot multiboot-compliant kernels and a few kernels with specific
1763 support. L</BOOT_METHOD> could be used to specify the command used by GRUB2 to
1764 load the kernel. See L<GNU GRUB Manual|https://www.gnu.org/software/grub/manual/grub/grub.html#Booting>.
1765
1766 To use the generated menu entry on your development
1767 machine that uses GRUB2, append the following snippet to
1768 F</etc/grub.d/40_custom> file and regenerate your grub configuration,
1769 i.e. run update-grub on Debian/Ubuntu.
1770
1771   if [ -f /path/to/nul/build/grub.cfg ]; then
1772     source /path/to/nul/build/grub.cfg
1773   fi
1774
1775 =item --grub2-prolog=I<prolog>
1776
1777 Specifies the text that novaboot puts at the beginning of the GRUB2 menu entry.
1778
1779 =item -m, --make[=make command]
1780
1781 Runs C<make> to build files that are not generated by novaboot itself.
1782
1783 =item --name=I<string>
1784
1785 Use the name I<string> instead of the name of the novaboot script.
1786 This name is used for things like a title of grub menu or for the
1787 server directory where the boot files are copied to.
1788
1789 =item --no-file-gen
1790
1791 Do not run external commands to generate files (i.e. "<" syntax and
1792 C<run> keyword). This switch does not influence the generation of files
1793 specified with "<<WORD" syntax.
1794
1795 =item -p, --pulsar[=mac]
1796
1797 Generates pulsar bootloader configuration file named F<config-I<mac>>
1798 The I<mac> string is typically a MAC address and defaults to
1799 I<novaboot>.
1800
1801 =item --scons[=scons command]
1802
1803 Runs C<scons> to build files that are not generated by novaboot
1804 itself.
1805
1806 =item --strip-rom
1807
1808 Strip I<rom://> prefix from command lines and generated config files.
1809 The I<rom://> prefix is used by NUL. For NRE, it has to be stripped.
1810
1811 =item --gen-only
1812
1813 Exit novaboot after file generation phase.
1814
1815 =back
1816
1817 =head2 Target connection check
1818
1819 In this phase novaboot connects to target's serial port (if it has
1820 one). If another novaboot user/instance occupies the target, novaboot
1821 exits here with an error message.
1822
1823 =over 8
1824
1825 =item --amt=I<"[user[:password]@]host[:port]>
1826
1827 Use Intel AMT technology to control the target machine. WS management
1828 is used to powercycle it and Serial-Over-Lan (SOL) for input/output.
1829 The hostname or (IP address) is given by the I<host> parameter. If the
1830 I<password> is not specified, environment variable AMT_PASSWORD is
1831 used. The I<port> specifies a TCP port for SOL. If not specified, the
1832 default is 16992. The default I<user> is admin.
1833
1834 =item --iprelay=I<addr[:port]>
1835
1836 Use TCP/IP relay and serial port to access the target's serial port
1837 and powercycle it. The I<addr> parameter specifies the IP address of
1838 the relay. If I<port> is not specified, it defaults to 23.
1839
1840 Note: This option is supposed to work with HWG-ER02a IP relays.
1841
1842 =item --iprelay-cmd=I<command>
1843
1844 Similar to B<--iprelay> but uses I<command> to talk to the iprelay
1845 rather than direct network connection.
1846
1847 =item -s, --serial[=device]
1848
1849 Target's serial line is connected to host's serial line (device). The
1850 default value for device is F</dev/ttyUSB0>.
1851
1852 The value of this option is exported in NB_NOVABOOT environment
1853 variable to all subprocesses run by C<novaboot>.
1854
1855 =item --stty=I<settings>
1856
1857 Specifies settings passed to C<stty> invoked on the serial line
1858 specified with B<--serial> option. If this option is not given,
1859 C<stty> is called with C<raw -crtscts -onlcr 115200> settings.
1860
1861 =item --remote-cmd=I<cmd>
1862
1863 Command that mediates connection to the target's serial line. For
1864 example C<ssh server 'cu -l /dev/ttyS0'>.
1865
1866 =item --remote-expect=I<string>
1867
1868 Wait for reception of I<string> after establishing the remote serial
1869 line connection. Novaboot assumes that after establishing the serial
1870 line connection, the user running novaboot has exclusive access to the
1871 target. If establishing of the serial line connection happens
1872 asynchronously (e.g. running a command remotely via SSH), we need this
1873 option to wait until the exclusive access is confirmed by the remote
1874 side.
1875
1876 Depending on target configuration, this option can solve two practical
1877 problems: 1) Overwriting of files deployed by another user currently
1878 using the target. 2) Resetting the target board before serial line
1879 connection is established and thus missing bootloader interaction.
1880
1881 Example of usage with the L<sterm
1882 tool|https://rtime.felk.cvut.cz/gitweb/sojka/sterm.git>:
1883
1884   --remote-cmd='ssh -tt example.com sterm -v /dev/ttyUSB0' --remote-expect='sterm: Connected'
1885
1886 =item --remote-expect-silent=I<string>
1887
1888 The same as B<--remote-expect> except that the remote output is not
1889 echoed to stdout while waiting for the I<string>. Everything after the
1890 matched string is printed to stdout, so you may want to include line
1891 end characters in the I<string> as well.
1892
1893 =item --remote-expect-timeout=I<seconds>
1894
1895 Timeout in seconds for B<--remote-expect> or
1896 B<--remote-expect-seconds>. When negative, waits forever. The default
1897 is -1 seconds.
1898
1899 =back
1900
1901 =head2 File deployment phase
1902
1903 In some setups, it is necessary to copy the files needed for booting
1904 to a particular location, e.g. to a TFTP boot server or to the
1905 F</boot> partition.
1906
1907 =over 8
1908
1909 =item -d, --dhcp-tftp
1910
1911 Turns your workstation into a DHCP and TFTP server so that the OS can
1912 be booted via PXE BIOS (or similar mechanism) on the test machine
1913 directly connected by a plain Ethernet cable to your workstation.
1914
1915 The DHCP and TFTP servers require root privileges and C<novaboot>
1916 uses C<sudo> command to obtain those. You can put the following to
1917 I</etc/sudoers> to allow running the necessary commands without asking
1918 for a password.
1919
1920  Cmnd_Alias NOVABOOT = /bin/ip a add 10.23.23.1/24 dev eth0, /bin/ip l set dev eth0 up, /usr/sbin/dhcpd -d -cf dhcpd.conf -lf dhcpd.leases -pf dhcpd.pid, /usr/sbin/in.tftpd --listen --secure -v -v -v --pidfile tftpd.pid *, /usr/bin/touch dhcpd.leases, /usr/bin/pkill --pidfile=dhcpd.pid, /usr/bin/pkill --pidfile=tftpd.pid
1921  your_login ALL=NOPASSWD: NOVABOOT
1922
1923 =item --tftp
1924
1925 Starts a TFTP server on your workstation. This is similar to
1926 B<--dhcp-tftp> except that DHCP server is not started.
1927
1928 The TFTP server requires root privileges and C<novaboot> uses C<sudo>
1929 command to obtain those. You can put the following to I</etc/sudoers>
1930 to allow running the necessary commands without asking for a password.
1931
1932  Cmnd_Alias NOVABOOT =  /usr/sbin/in.tftpd --listen --secure -v -v -v --pidfile tftpd.pid *, /usr/bin/pkill --pidfile=tftpd.pid
1933  your_login ALL=NOPASSWD: NOVABOOT
1934
1935 =item --tftp-port=I<port>
1936
1937 Port to run the TFTP server on. Implies B<--tftp>.
1938
1939 =item --netif=I<network interface>
1940
1941 Network interface used to deploy files to the target. This option
1942 influences the configuration of the DHCP server started by
1943 B<--dhcp-tftp> and the value that B<$NB_MYIP> get replaced with during
1944 U-Boot conversation. The default value is C<$netif> variable from
1945 configuration files, which defaults to I<eth0>.
1946
1947 =item --iso[=filename]
1948
1949 Generates the ISO image that boots NOVA system via GRUB. If no filename
1950 is given, the image is stored under I<NAME>.iso, where I<NAME> is the name
1951 of the novaboot script (see also B<--name>).
1952
1953 =item --server[=[[user@]server:]path]
1954
1955 Alias of B<--copy> (kept for backward compatibility).
1956
1957 =item --copy[=[[user@]server:]path]
1958
1959 Copy all files needed for booting to another location. The files will
1960 be copied (by B<rsync> tool) to the directory I<path>. If the I<path>
1961 contains string $NAME, it will be replaced with the name of the
1962 novaboot script (see also B<--name>).
1963
1964 =item --rsync-flags=I<flags>
1965
1966 Specifies I<flags> to append to F<rsync> command line when
1967 copying files as a result of I<--copy> option.
1968
1969 =item --concat
1970
1971 If B<--copy> is used and its value ends with $NAME, then after
1972 copying the files, a new bootloader configuration file (e.g. menu.lst)
1973 is created at I<path-wo-name>, i.e. the path specified by B<--copy>
1974 with $NAME part removed. The content of the file is created by
1975 concatenating all files of the same name from all subdirectories of
1976 I<path-wo-name> found on the "server".
1977
1978 =item --ider
1979
1980 Use Intel AMT technology for IDE redirection. This allows the target
1981 machine to boot from novaboot created ISO image. Implies B<--iso>.
1982
1983 The experimental C<amtider> utility needed by this option can be
1984 obtained from https://github.com/wentasah/amtterm.
1985
1986 =back
1987
1988 =head2 Target power-on and reset phase
1989
1990 At this point, the target is reset (or switched on/off). There are
1991 several ways how this can be accomplished. Resetting a physical target
1992 can currently be accomplished by the following options: B<--amt>,
1993 B<--iprelay>, B<--reset-cmd> and B<--reset-send>.
1994
1995 =over 8
1996
1997 =item --on, --off
1998
1999 Switch on/off the target machine and exit. The script (if any) is
2000 completely ignored. Currently, it works only with the following
2001 options: B<--iprelay>, B<--amt>, B<--ssh>.
2002
2003 =item -Q, --qemu[=I<qemu-binary>]
2004
2005 Boot the configuration in qemu. Optionally, the name of qemu binary
2006 can be specified as a parameter.
2007
2008 =item --qemu-append=I<flags>
2009
2010 Append I<flags> to the default qemu flags (QEMU_FLAGS variable or
2011 C<-cpu coreduo -smp 2>).
2012
2013 =item -q, --qemu-flags=I<flags>
2014
2015 Replace the default qemu flags (QEMU_FLAGS variable or C<-cpu coreduo
2016 -smp 2>) with I<flags> specified here.
2017
2018 =item --reset-cmd=I<cmd>
2019
2020 Runs command I<cmd> to reset the target.
2021
2022 =item --reset-send=I<string>
2023
2024 Reset the target by sending the given I<string> to the remote serial
2025 line. "\n" sequences are replaced with the newline character.
2026
2027 =item --no-reset, --reset
2028
2029 Disable/enable resetting of the target.
2030
2031 =back
2032
2033 =head2 Interaction with the bootloader on the target
2034
2035 =over 8
2036
2037 =item --uboot[=I<prompt>]
2038
2039 Interact with U-Boot bootloader to boot the thing described in the
2040 novaboot script. I<prompt> specifies the U-Boot's prompt (default is
2041 "=> ", other common prompts are "U-Boot> " or "U-Boot# ").
2042
2043 =item --no-uboot
2044
2045 Disable U-Boot interaction previously enabled with B<--uboot>.
2046
2047 =item --uboot-stop-key=I<key>
2048
2049 Character, which is sent as a response to U-Boot's "Hit any key to
2050 stop autoboot" message. The default value is newline, but some devices
2051 (e.g. TP-Link TD-W8970) require a specific key to be pressed.
2052
2053 =item --uboot-init
2054
2055 Command(s) to send the U-Boot bootloader before loading the images and
2056 booting them. This option can be given multiple times. After sending
2057 commands from each option novaboot waits for U-Boot I<prompt>.
2058
2059 If the command contains string I<$NB_MYIP> then this string is
2060 replaced by IPv4 address of eth0 interface (see also B<--netif>).
2061 Similarly, I<$NB_PREFIX> is replaced with prefix given by B<--prefix>.
2062
2063 See also C<uboot> keyword in L</"NOVABOOT SCRIPT SYNTAX">).
2064
2065 =item --uboot-addr I<name>=I<address>
2066
2067 Load address of U-Boot's C<tftpboot> command for loading I<name>,
2068 where name is one of I<kernel>, I<ramdisk> or I<fdt> (flattened device
2069 tree).
2070
2071 The default addresses are ${I<name>_addr_r}, i.e. U-Boot environment
2072 variables used by convention for this purpose.
2073
2074 =item --uboot-cmd=I<command>
2075
2076 Specifies U-Boot command used to execute the OS. If the command
2077 contains strings C<$kernel_addr>, C<$ramdisk_addr>, C<$fdt_addr>,
2078 these are replaced with the addresses configured with B<--uboot-addr>.
2079
2080 The default value is
2081
2082     bootm $kernel_addr $ramdisk_addr $fdt_addr
2083
2084 or the C<UBOOT_CMD> variable if defined in the novaboot script.
2085
2086 =back
2087
2088 =head2 Target interaction phase
2089
2090 In this phase, target's serial output is redirected to stdout and if
2091 stdin is a TTY, it is redirected to the target's serial input allowing
2092 interactive work with the target.
2093
2094 =over 8
2095
2096 =item --exiton=I<string>
2097
2098 When the I<string> is sent by the target, novaboot exits. This option can
2099 be specified multiple times, in which case novaboot exits whenever
2100 either of the specified strings is sent.
2101
2102 If the I<string> is C<-re>, then the next B<--exiton>'s I<string> is
2103 treated as a regular expression. For example:
2104
2105     --exiton -re --exiton 'error:.*failed'
2106
2107 =item --exiton-re=I<regex>
2108
2109 The same as --exiton -re --exiton I<regex>.
2110
2111 =item --exiton-timeout=I<seconds>
2112
2113 By default B<--exiton> waits for the string match forever. When this
2114 option is specified, "exiton" timeouts after the specified number of
2115 seconds and novaboot returns non-zero exit code.
2116
2117 =item -i, --interactive
2118
2119 Setup things for the interactive use of the target. Your terminal will
2120 be switched to raw mode. In raw mode, your local terminal does not
2121 process input in any way (no echoing of entered characters, no
2122 interpretation of special characters). This, among others, means that
2123 Ctrl-C is passed to the target and does not interrupt novaboot. To
2124 exit from novaboot interactive mode type "~~.".
2125
2126 =item --no-interaction, --interaction
2127
2128 Skip resp. force target interaction phase. When skipped, novaboot exits
2129 immediately after the boot is initiated.
2130
2131 =item --expect=I<string>
2132
2133 When the I<string> is received from the target, send the string specified
2134 with the subsequent B<--send*> option to the target.
2135
2136 =item --expect-re=I<regex>
2137
2138 When target's output matches regular expression I<regex>, send the
2139 string specified with the subsequent B<--send*> option to the target.
2140
2141 =item --expect-raw=I<perl-code>
2142
2143 Provides direct control over Perl's Expect module.
2144
2145 =item --send=I<string>
2146
2147 Send I<string> to the target after the previously specified
2148 B<--expect*> was matched in the target's output. The I<string> may
2149 contain escape sequences such as "\n".
2150
2151 Note that I<string> is actually interpreted by Perl, so it can contain
2152 much more that escape sequences. This behavior may change in the
2153 future.
2154
2155 Example: C<--expect='login: ' --send='root\n'>
2156
2157 =item --sendcont=I<string>
2158
2159 Similar to B<--send> but continue expecting more input.
2160
2161 Example: C<--expect='Continue?' --sendcont='yes\n'>
2162
2163 =item --final-eol, --no-final-eol
2164
2165 By default, B<novaboot> always prints an end-of-line character at the
2166 end of its execution in order to ensure that the output of programs
2167 started after novaboot appears at the beginning of the line. When this
2168 is not desired B<--no-final-eol> option can be used to override this
2169 behavior.
2170
2171 =back
2172
2173 =head1 NOVABOOT SCRIPT SYNTAX
2174
2175 The syntax tries to mimic POSIX shell syntax. The syntax is defined
2176 by the following rules.
2177
2178 Lines starting with "#" and empty lines are ignored.
2179
2180 Lines that end with "\" are concatenated with the following line after
2181 removal of the final "\" and leading whitespace of the following line.
2182
2183 Lines of the form I<VARIABLE=...> (i.e. matching '^[A-Z_]+=' regular
2184 expression) assign values to internal variables. See L</VARIABLES>
2185 section.
2186
2187 Otherwise, the first word on the line defines the meaning of the line.
2188 The following keywords are supported:
2189
2190 =over 4
2191
2192 =item C<load>
2193
2194 These lines represent modules to boot. The
2195 word after C<load> is a file name (relative to the build directory
2196 (see B<--build-dir>) of the module to load and the remaining words are
2197 passed to it as the command line parameters.
2198
2199 When booting Linux, the first C<load> line usually refers to the
2200 kernel image and its command line parameters (unless you use some
2201 special pre-loader). Other C<load> lines may refer to an initramfs
2202 image and/or a device tree blob. Their order is not important, as the
2203 device tree is recognized as the file name ending with C<.dtb>.
2204
2205 When the C<load> line ends with "<<WORD" then the subsequent lines
2206 until the line containing solely WORD are copied literally to the file
2207 named on that line. This is similar to the heredoc feature of UNIX
2208 shells.
2209
2210 When the C<load> line ends with "< CMD" then command CMD is executed
2211 with F</bin/sh> and its standard output is stored in the file named on
2212 that line. The SRCDIR variable in CMD's environment is set to the
2213 absolute path of the directory containing the interpreted novaboot
2214 script.
2215
2216 =item C<copy>
2217
2218 These lines are similar to C<load> lines. The
2219 file mentioned there is copied to the same place as in the case of C<load>
2220 (e.g. tftp server), but the file is not used in the bootloader
2221 configuration. Such a file can be used by the target for other
2222 purposes than booting, e.g. at OS runtime or for firmware update.
2223
2224 =item C<chld>
2225
2226 Chainload another bootloader. Instead of loading multiboot modules
2227 identified with C<load> keyword, run another bootloader. This is
2228 currently supported only by pulsar and can be used to load e.g. Grub
2229 as in the example below:
2230
2231  chld boot/grub/i386-pc/core.0
2232
2233
2234 =item C<run>
2235
2236 Lines starting with C<run> keyword contain shell commands that are run
2237 during file generation phase. This is the same as the "< CMD" syntax
2238 for C<load> keyboard except that the command's output is not
2239 redirected to a file. The ordering of commands is the same as they
2240 appear in the novaboot script.
2241
2242 =item C<uboot>
2243
2244 These lines represent U-Boot commands that are sent to the target if
2245 B<--uboot> option is given. Having a U-Boot line in the novaboot
2246 script is the same as giving B<--uboot-init> option to novaboot. The
2247 following syntax variants are supported:
2248
2249
2250   uboot[:<timeout>] <string> [> <file>]
2251   uboot[:<timeout>] < <shell> [> <file>]
2252
2253 C<string> is the literal U-Boot command.
2254
2255 The C<uboot> keyword can be suffixed with timeout specification. The
2256 syntax is C<uboot:Ns>, where C<N> is the whole number of seconds. If
2257 the U-Boot command prompt does not appear before the timeout, novaboot
2258 fails. The default timeout is 10 seconds.
2259
2260 In the second variant with the C<<> character the shell code is
2261 executed and its standard output is sent to U-Boot. Example:
2262
2263   uboot < printf "mmc write \$loadaddr 1 %x" $(($(/usr/bin/stat -c%s rootfs.ext4) / 512))
2264
2265 When C<E<gt> file> part is present, the output of the U-Boot command
2266 is written into the given file.
2267
2268 =back
2269
2270 Example (Linux):
2271
2272   #!/usr/bin/env novaboot
2273   load bzImage console=ttyS0,115200
2274   run  make -C buildroot
2275   load rootfs.cpio < gen_cpio buildroot/images/rootfs.cpio "myapp->/etc/init.d/S99myapp"
2276
2277 Example (NOVA User Land - NUL):
2278
2279   #!/usr/bin/env novaboot
2280   WVDESC=Example program
2281   load bin/apps/sigma0.nul S0_DEFAULT script_start:1,1 \
2282                            verbose hostkeyb:0,0x60,1,12,2
2283   load bin/apps/hello.nul
2284   load hello.nulconfig <<EOF
2285   sigma0::mem:16 name::/s0/log name::/s0/timer name::/s0/fs/rom ||
2286   rom://bin/apps/hello.nul
2287   EOF
2288
2289 This example will load three modules: F<sigma0.nul>, F<hello.nul> and
2290 F<hello.nulconfig>. sigma0 receives some command line parameters and
2291 F<hello.nulconfig> file is generated on the fly from the lines between
2292 C<<<EOF> and C<EOF>.
2293
2294 Example (Zynq system update via U-Boot):
2295
2296   #!/usr/bin/env novaboot
2297
2298   uboot dhcp
2299
2300   # Write kernel to FAT filesystem on the 1st SD card partition
2301   run mkimage -f uboot-image.its image.ub
2302   copy image.ub
2303   uboot:60s tftpboot ${loadaddr} $NB_PREFIX/image.ub
2304   uboot fatwrite mmc 0:1 ${loadaddr} image.ub $filesize
2305   uboot set bootargs console=ttyPS0,115200 root=/dev/mmcblk0p2
2306
2307   # Write root FS image to the 2nd SD card partition
2308   copy rootfs/images/rootfs.ext4
2309   uboot:60s tftpboot ${loadaddr} $NB_PREFIX/rootfs/images/rootfs.ext4
2310   uboot mmc part > mmc-part.txt
2311   uboot < printf "mmc write \$loadaddr %x %x" $(awk '{ if ($1 == "2") { print $2 }}' mmc-part.txt) $(($(/usr/bin/stat -L --printf=%s rootfs/images/rootfs.ext4) / 512))
2312
2313   UBOOT_CMD=boot
2314
2315
2316 =head2 VARIABLES
2317
2318 The following variables are interpreted in the novaboot script:
2319
2320 =over 8
2321
2322 =item BOOT_METHOD
2323
2324 Specifies the way GRUB2 boots the kernel. For kernels with multiboot
2325 support use C<multiboot> method (the default). For Linux kernel use C<linux> method.
2326
2327 =item BUILDDIR
2328
2329 Novaboot chdir()s to this directory before file generation phase. The
2330 directory name specified here is relative to the build directory
2331 specified by other means (see L</--build-dir>).
2332
2333 =item EXITON
2334
2335 Assigning this variable has the same effect as specifying L</--exiton>
2336 option.
2337
2338 =item INTERACTION
2339
2340 Setting this variable to zero is the same as giving
2341 L</--no-interaction>, specifying to one corresponds to
2342 L</--interaction>.
2343
2344 =item HYPERVISOR_PARAMS
2345
2346 Parameters passed to the hypervisor. The default value is "serial", unless
2347 overridden in the configuration file.
2348
2349 =item KERNEL
2350
2351 The kernel to use instead of the hypervisor specified in the
2352 configuration file with the C<$hypervisor> variable. The value should
2353 contain the name of the kernel image as well as its command line
2354 parameters. If this variable is defined and non-empty, the variable
2355 HYPERVISOR_PARAMS is not used.
2356
2357 =item NO_BOOT
2358
2359 If this variable is 1, the system is not booted. This is currently
2360 only implemented for U-Boot bootloader where it is useful for
2361 interacting with the bootloader without booting the system - e.g. for
2362 flashing.
2363
2364 =item QEMU
2365
2366 Use a specific qemu binary (can be overridden with B<-Q>) and flags
2367 when booting this script under qemu. If QEMU_FLAGS variable is also
2368 specified flags specified in QEMU variable are replaced by those in
2369 QEMU_FLAGS.
2370
2371 =item QEMU_FLAGS
2372
2373 Use specific qemu flags (can be overridden with B<-q>).
2374
2375 =item UBOOT_CMD
2376
2377 See L</--uboot-cmd>.
2378
2379 =item WVDESC
2380
2381 Description of the WvTest-compliant program.
2382
2383 =item WVTEST_TIMEOUT
2384
2385 The timeout in seconds for WvTest harness. If no complete line appears
2386 in the test output within the time specified here, the test fails. It
2387 is necessary to specify this for long running tests that produce no
2388 intermediate output.
2389
2390 =back
2391
2392 =head1 CONFIGURATION FILES
2393
2394 Novaboot can read its configuration from one or more files. By
2395 default, novaboot looks for files in F</etc/novaboot.d>, file
2396 F<~/.config/novaboot> and files named F<.novaboot> as described in
2397 L</Configuration reading phase>. Alternatively, configuration file
2398 location can be specified with the B<-c> switch or with the
2399 NOVABOOT_CONFIG environment variable. The configuration file has Perl
2400 syntax (i.e. it is better to put C<1;> as the last line) and should set
2401 values of certain Perl variables. The current configuration can be
2402 dumped with the B<--dump-config> switch. Some configuration variables
2403 can be overridden by environment variables (see below) or by command
2404 line switches.
2405
2406 Supported configuration variables include:
2407
2408 =over 8
2409
2410 =item $builddir
2411
2412 Build directory location relative to the location of the configuration
2413 file.
2414
2415 =item $default_target
2416
2417 Default target (see below) to use when no target is explicitly
2418 specified with the B<--target> command line option or
2419 B<NOVABOOT_TARGET> environment variable.
2420
2421 =item $netif
2422
2423 Default value for the B<--netif> option. If not specified, it defaults
2424 to I<eth0>.
2425
2426 =item %targets
2427
2428 Hash of target definitions to be used with the B<--target> option. The
2429 key is the identifier of the target, the value is the string with
2430 command line options. For instance, if the configuration file contains:
2431
2432  $targets{'mybox'} = '--copy=boot:/tftproot --serial=/dev/ttyUSB0 --grub',
2433
2434 then the following two commands are equivalent:
2435
2436  ./myos --copy=boot:/tftproot --serial=/dev/ttyUSB0 --grub
2437  ./myos -t mybox
2438
2439 =back
2440
2441 =head1 ENVIRONMENT VARIABLES
2442
2443 Some options can be specified not only via config file or command line
2444 but also through environment variables. Environment variables override
2445 the values from the configuration file and command line parameters
2446 override the environment variables.
2447
2448 =over 8
2449
2450 =item NOVABOOT_CONFIG
2451
2452 Name of the novaboot configuration file to use instead of the default
2453 one(s).
2454
2455 =item NOVABOOT_CONFIG_DIR
2456
2457 Name of the novaboot configuration directory. When not specified
2458 F</etc/novaboot.d> is used.
2459
2460 =item NOVABOOT_TARGET
2461
2462 Name of the novaboot target to use. This overrides the value of
2463 B<$default_target> from the configuration file and can be overridden
2464 with the B<--target> command line option.
2465
2466 =item NOVABOOT_BENDER
2467
2468 Defining this variable has the same effect as using B<--bender>
2469 option.
2470
2471 =back
2472
2473 =head1 AUTHORS
2474
2475 Michal Sojka <sojka@os.inf.tu-dresden.de>
2476
2477 Latest novaboot version can be found at
2478 L<https://github.com/wentasah/novaboot>.
2479
2480 =cut
2481
2482 # LocalWords:  novaboot Novaboot NOVABOOT TFTP PXE DHCP filename stty
2483 # LocalWords:  chainloader stdout Qemu qemu preprocessing ISOLINUX bootable
2484 # LocalWords:  config subprocesses sudo sudoers tftp dhcp IDE stdin
2485 # LocalWords:  subdirectories TTY whitespace heredoc POSIX WvTest