]> rtime.felk.cvut.cz Git - novaboot.git/blob - novaboot
nix: Update flake inputs
[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                          $uboot_prompt,
1299                          [qr/#/, sub { exp_continue; }]
1300                 ) || die "Kernel load: " . ($! || "timeout");
1301         }
1302         if (defined $dtb) {
1303             die "No '--uboot-addr fdt' given" unless $uboot_addr{fdt};
1304             $exp->send("tftpboot $uboot_addr{fdt} $prefix$dtb\n");
1305             $exp->expect(15,
1306                          [qr/##/, sub { exp_continue; }],
1307                          $uboot_prompt) || die "Device tree load: " . ($! || "timeout");
1308         } else  {
1309             $uboot_addr{fdt} = '';
1310         }
1311         if (defined $initrd) {
1312             die "No '--uboot-addr ramdisk' given" unless $uboot_addr{ramdisk};
1313             $exp->send("tftpboot $uboot_addr{ramdisk} $prefix$initrd\n");
1314             $exp->expect(15,
1315                          [qr/##/, sub { exp_continue; }],
1316                          $uboot_prompt) || die "Initrd load: " . ($! || "timeout");
1317         } else {
1318             $uboot_addr{ramdisk} = '-';
1319         }
1320
1321         $kcmd //= '';
1322         $exp->send("setenv bootargs $kcmd\n");
1323         $exp->expect(5, $uboot_prompt)  || die "U-Boot prompt: " . ($! || "timeout");
1324
1325     }
1326     $uboot_cmd //= $variables->{UBOOT_CMD} // 'bootm $kernel_addr $ramdisk_addr $fdt_addr';
1327     if (!$variables->{NO_BOOT} && $uboot_cmd ne '') {
1328         $uboot_cmd =~ s/\$kernel_addr/$uboot_addr{kernel}/g;
1329         $uboot_cmd =~ s/\$ramdisk_addr/$uboot_addr{ramdisk}/g;
1330         $uboot_cmd =~ s/\$fdt_addr/$uboot_addr{fdt}/g;
1331
1332         $exp->send($uboot_cmd . "\n");
1333         $exp->expect(5, "\n")  || die "U-Boot command: " . ($! || "timeout");
1334     }
1335 }
1336
1337 ### Serial line interaction
1338 if ($interaction && defined $exp) {
1339     # Serial line of the target is available
1340     my $interrupt = 'Ctrl-C';
1341     if ($interactive && !@exiton) {
1342         $interrupt = '"~~."';
1343     }
1344     print STDERR "novaboot: Serial line interaction (press $interrupt to interrupt)...\n";
1345     $exp->log_stdout(1);
1346     if (@exiton) {
1347         $exp->expect($exiton_timeout, @exiton, @expect_raw) || die("exiton: " . ($! || "timeout"));
1348     } else {
1349         my @inputs = ($exp);
1350         my $infile = new IO::File;
1351         $infile->IO::File::fdopen(*STDIN,'r');
1352         my $in_object = Expect->exp_init($infile);
1353         $in_object->set_group($exp);
1354
1355         if ($interactive) {
1356             $in_object->set_seq('~~\.', sub { print STDERR "novaboot: Escape sequence detected\r\n"; undef; });
1357             $in_object->manual_stty(0);   # Use raw terminal mode
1358         } else {
1359             $in_object->manual_stty(1);   # Do not modify terminal settings
1360         }
1361         push(@inputs, $in_object);
1362         #use Data::Dumper;
1363         #print Dumper(\@expect_raw);
1364         $exp->expect(undef, @expect_raw) if @expect_raw;
1365
1366         $^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.
1367         Expect::interconnect(@inputs) unless defined($exp->exitstatus);
1368         $^W = 1;
1369     }
1370 }
1371
1372 # When exp-spawned command ignores SIGHUP, Expect waits 5 seconds
1373 # before killing it. We kill it by SIGTERM immediately.
1374 kill TERM => $exp->pid if defined $exp && $exp->pid;
1375
1376 ## Kill dhcpc or tftpd
1377 if (defined $dhcp_tftp || defined $tftp) {
1378     die("novaboot: This should kill servers on background\n");
1379 }
1380
1381 # Always finish novaboot output with newline
1382 print "\n" if $final_eol;
1383
1384 ## Documentation
1385
1386 =encoding utf8
1387
1388 =head1 NAME
1389
1390 novaboot - Boots a locally compiled operating system on a remote
1391 target or in qemu
1392
1393 =head1 SYNOPSIS
1394
1395 B<novaboot> --help
1396
1397 B<novaboot> [option]... [--] script...
1398
1399 B<./script> [option]...
1400
1401 =head1 DESCRIPTION
1402
1403 Novaboot makes booting of a locally compiled operating system (OS)
1404 (e.g. NOVA or Linux) on remote targets as simple as running a program
1405 locally. It automates things like copying OS images to a TFTP server,
1406 generation of bootloader configuration files, resetting of target
1407 hardware or redirection of target's serial line to stdin/out. Novaboot
1408 is highly configurable and makes it easy to boot a single image on
1409 different targets or different images on a single target.
1410
1411 Novaboot operation is controlled by configuration files, command line
1412 options and by a so-called novaboot script, which can be thought as a
1413 generalization of bootloader configuration files (see L</"NOVABOOT
1414 SCRIPT SYNTAX">). The typical way of using novaboot is to make the
1415 novaboot script executable and set its first line to I<#!/usr/bin/env
1416 novaboot>. Then, booting a particular OS configuration becomes the
1417 same as executing a local program â€“ the novaboot script.
1418
1419 Novaboot uses configuration files to, among other things, define
1420 command line options needed for different targets. Users typically use
1421 only the B<-t>/B<--target> command line option to select the target.
1422 Internally, this option expands to the pre-configured options.
1423 Novaboot searches configuration files at multiple places, which allows
1424 having per-system, per-user or per-project configurations.
1425 Configuration file syntax is described in section L</"CONFIGURATION
1426 FILES">.
1427
1428 Novaboot newcomers may be confused by a large number of configuration
1429 options. Understanding all these options is not always needed,
1430 depending on the used setup. The L<figure from the doc directory
1431 |https://github.com/wentasah/novaboot/blob/master/doc/typical-setups.svg>
1432 shows different setups that vary in how much effort is needed
1433 to configure novaboot for them. The setups are:
1434
1435 =over 3
1436
1437 =item A: Laptop and target device only
1438
1439 This requires to configure everything on the laptop side, including a
1440 serial line connection (L</--serial>, L</--remote-cmd>, ...), power
1441 on/off/reset commands (L</--reset-cmd>, ...), TFTP server
1442 (L</--copy>, L</--prefix>...), device IP addresses, etc.
1443
1444 =item B: Laptop, target device and external TFTP server
1445
1446 Like the previous setup, but the TFTP (and maybe DHCP) configuration
1447 is handled by a server. Novaboot users need to understand where to
1448 copy their files to the TFTP server (L</--copy>) and which IP
1449 addresses their target will get, but do not need to configure the
1450 servers themselves.
1451
1452 =item C: Novaboot server running novaboot-shell
1453
1454 With this setup, the configuration is done on the server. Users only
1455 need to know the SSH account (L</--ssh>) used to communicate between
1456 novaboot and novaboot server. The server is implemented as a
1457 restricted shell (L<novaboot-shell(1)>) on the server. No need to give
1458 full shell access to novaboot users on the server.
1459
1460 =back
1461
1462 =head2 Simple examples of using C<novaboot>:
1463
1464 To boot Linux (files F<bzImage> and F<rootfs.cpio> in current
1465 directory), create F<mylinux> file with this content:
1466
1467     #!/usr/bin/env novaboot
1468     load bzImage console=ttyS0,115200
1469     load rootfs.cpio
1470
1471 =over 3
1472
1473 =item 1.
1474
1475 Booting an OS in Qemu can be accomplished by giving the B<--qemu> option.
1476 Thus running
1477
1478  novaboot --qemu mylinux
1479
1480 (or C<./mylinux --qemu> as described above) will run Qemu and make it
1481 boot the configuration specified in the F<mylinux> script. How is qemu
1482 started can be configured in various ways (see below).
1483
1484 =item 2.
1485
1486 Create a bootloader configuration file (currently supported
1487 bootloaders are GRUB, GRUB2, ISOLINUX, Pulsar, and U-Boot) and copy it
1488 with all other files needed for booting to a remote TFTP server. Then
1489 use a TCP/IP-controlled relay/serial-to-TCP converter to reset the
1490 target and receive its serial output.
1491
1492  ./mylinux --grub2 --copy=192.168.1.1:/tftp --iprelay=192.168.1.2
1493
1494 Alternatively, you can put these switches to the configuration file
1495 and run:
1496
1497  ./mylinux --target mytarget
1498
1499 =item 3.
1500
1501 Specifying all the options needed by novaboot to successfully control
1502 the target, either on command line or in configuration files, can be
1503 difficult for users. Novaboot supports configuring the target
1504 centrally via L<novaboot-shell(1)> on a server. With such a
1505 configuration, users only need to use the B<--ssh> option to specify
1506 where to boot their OS:
1507
1508  ./mylinux --ssh myboard@example.com
1509
1510 Typically, the server is the computer connected to and controlling the
1511 target board and running the TFTP server.
1512
1513 =item 4.
1514
1515 Run DHCP and TFTP server on developer's machine to boot the target
1516 from it.
1517
1518  ./mylinux --dhcp-tftp
1519
1520 This usage is useful when no network infrastructure is in place, and
1521 the target is connected directly to developer's box.
1522
1523 =item 5.
1524
1525 Create bootable ISO image.
1526
1527  novaboot --iso -- script1 script2
1528
1529 The created ISO image will have ISOLINUX bootloader installed on it,
1530 and the boot menu will allow selecting between I<script1> and
1531 I<script2> configurations.
1532
1533 =back
1534
1535 =head1 OPTIONS AND PHASES
1536
1537 Novaboot performs its work in several phases. Command line options
1538 described bellow influence the execution of each phase or allow their
1539 skipping. The list of phases (in the execution order) is as follows.
1540
1541 =over
1542
1543 =item 1. L<Configuration reading|/Configuration reading phase>
1544
1545 =item 2. L<Command line processing|/Command line processing phase>
1546
1547 =item 3. L<Script preprocessing|/Script preprocessing phase>
1548
1549 =item 4. L<File generation|/File generation phase>
1550
1551 =item 5. L<Target connection|/Target connection check>
1552
1553 =item 6. L<File deployment|/File deployment phase>
1554
1555 =item 7. L<Target power-on and reset|/Target power-on and reset phase>
1556
1557 =item 8. L<Interaction with the bootloader|/Interaction with the bootloader on the target>
1558
1559 =item 9. L<Target interaction|/Target interaction phase>
1560
1561 =back
1562
1563 Each phase is described in the following sections together with the
1564 command line options that control it.
1565
1566 =head2 Configuration reading phase
1567
1568 After starting, novaboot reads zero or more configuration files. We
1569 describe their content in section L</"CONFIGURATION FILES">. By default, the
1570 configuration is read from multiple locations. First from the system
1571 configuration directory (F</etc/novaboot.d/>), second from the user
1572 configuration file (F<~/.config/novaboot>) and third from F<.novaboot>
1573 files along the path to the current directory. Alternatively, a single
1574 configuration file specified with the B<-c> switch or with the
1575 C<NOVABOOT_CONFIG> environment variable is read. The latter read files
1576 override settings from the former ones.
1577
1578 The system configuration directory is determined by the content of
1579 NOVABOOT_CONFIG_DIR environment variable and defaults to
1580 F</etc/novaboot.d>. Files in this directory with names consisting
1581 solely of English letters, numbers, dashes '-' and underscores '_'
1582 (note that dot '.' is not included) are read in alphabetical order.
1583
1584 Then, the user configuration file is read from
1585 F<$XDG_CONFIG_HOME/novaboot>. If C<$XDG_CONFIG_HOME> environment
1586 variable is not set F<~/.config/novaboot> is read instead.
1587
1588 Finally, novaboot searches for files named F<.novaboot> starting from the
1589 directory of the novaboot script (or working directory, see bellow)
1590 and continuing upwards up to the root directory. The found
1591 configuration files are then read in the opposite order (i.e. from the
1592 root directory downwards). This ordering allows having, for example, a project
1593 specific configuration in F<~/project/.novaboot>.
1594
1595 Note the difference between F<~/.config/novaboot> and F<~/.novaboot>.
1596 The former one is always read, whereas the latter only when novaboot
1597 script or working directory is under the C<$HOME> directory.
1598
1599 In certain cases, the location of the novaboot script cannot be
1600 determined in this early phase. This situation happens either when the script is
1601 read from the standard input or when novaboot is invoked explicitly as
1602 in the example L</"4."> above. In this case, the current working
1603 directory is used as a starting point for configuration file search
1604 instead of the novaboot script directory.
1605
1606 =over 8
1607
1608 =item -c, --config=I<filename>
1609
1610 Use the specified configuration file instead of the default one(s).
1611
1612 =back
1613
1614 =head2 Command line processing phase
1615
1616 =over 8
1617
1618 =item --dump-config
1619
1620 Dump the current configuration to stdout end exit. Useful as an
1621 initial template for a configuration file.
1622
1623 =item -h, --help
1624
1625 Print short (B<-h>) or long (B<--help>) help.
1626
1627 =item -t, --target=I<target>
1628
1629 This option serves as a user configurable shortcut for other novaboot
1630 options. The effect of this option is the same as specifying the
1631 options stored in the C<%targets> configuration variable under key
1632 I<target>. See also L</"CONFIGURATION FILES">.
1633
1634 When this option is not given, novaboot tries to determine the target
1635 to use from either B<NOVABOOT_TARGET> environment variable or
1636 B<$default_target> configuration file variable.
1637
1638 =item --ssh=I<user@hostname>
1639
1640 Configures novaboot to control the target via C<novaboot-shell>
1641 running remotely via SSH.
1642
1643 Using this option is the same as specifying B<--remote-cmd>,
1644 B<--remote-expect>, B<--copy> B<--rsync-flags>, B<--prefix> and
1645 B<--reset-cmd> manually in a way compatible with C<novaboot-shell>.
1646 The server can be configured to provide other, safe bootloader-related
1647 options, to the client. When this happens, novaboot prints them to
1648 stdout.
1649
1650 Currently, this in an initial experimental implementation. We plan to
1651 change/extend this feature soon!
1652
1653 =back
1654
1655 =head2 Script preprocessing phase
1656
1657 This phase allows modifying the parsed novaboot script before it is
1658 used in the later phases.
1659
1660 =over 8
1661
1662 =item -a, --append=I<parameters>
1663
1664 Append a string to the first C<load> line in the novaboot script. This option
1665 can be used to append parameters to the kernel's or root task's
1666 command line. This option can appear multiple times.
1667
1668 =item -b, --bender
1669
1670 Use L<Bender|https://github.com/TUD-OS/morbo/blob/master/standalone/bender.c>
1671 chainloader. Bender scans the PCI bus for PCI serial ports and stores
1672 the information about them in the BIOS data area for use by the
1673 kernel.
1674
1675 =item --chainloader=I<chainloader>
1676
1677 Specifies a chainloader that is loaded before the kernel and other
1678 files specified in the novaboot script. E.g. 'bin/boot/bender
1679 promisc'.
1680
1681 =item --dump
1682
1683 Print the modules to boot and their parameters, after this phase
1684 finishes. Then exit. This is useful for seeing the effect of other
1685 options in this section.
1686
1687 =item -k, --kernel=F<file>
1688
1689 Replace the first word on the first C<load> line in the novaboot
1690 script with F<file>.
1691
1692 =item --scriptmod=I<Perl expression>
1693
1694 When novaboot reads the script, I<Perl expression> is executed for every
1695 line (in $_ variable). For example, C<novaboot
1696 --scriptmod=s/sigma0/omega6/g> replaces every occurrence of I<sigma0>
1697 in the script with I<omega6>.
1698
1699 When this option is present, it overrides I<$script_modifier> variable
1700 from the configuration file, which has the same effect. If this option
1701 is given multiple times all expressions are evaluated in the command
1702 line order.
1703
1704 =back
1705
1706 =head2 File generation phase
1707
1708 In this phase, files needed for booting are generated in a so-called
1709 I<build directory> (see L</--build-dir>). In most cases configuration
1710 for a bootloader is generated automatically by novaboot. It is also
1711 possible to generate other files using I<heredoc> or I<"<"> syntax in
1712 novaboot scripts. Finally, novaboot can generate binaries in this phases by
1713 running C<scons> or C<make>.
1714
1715 =over 8
1716
1717 =item --build-dir=I<directory>
1718
1719 Overrides the default build directory location.
1720
1721 The default build directory location is determined as follows: If the
1722 configuration file defines the C<$builddir> variable, its value is
1723 used. Otherwise, it is the directory that contains the first processed
1724 novaboot script.
1725
1726 See also L</BUILDDIR> variable.
1727
1728 =item -g, --grub[=I<filename>]
1729
1730 Generates grub bootloader menu file. If the I<filename> is not
1731 specified, F<menu.lst> is used. The I<filename> is relative to the
1732 build directory (see B<--build-dir>).
1733
1734 =item --grub-preamble=I<prefix>
1735
1736 Specifies the I<preamble> that is at the beginning of the generated
1737 GRUB or GRUB2 config files. This is useful for specifying GRUB's
1738 timeout.
1739
1740 =item --prefix=I<prefix>
1741
1742 Specifies I<prefix> (e.g. F</srv/tftp>) that is put in front of every
1743 filename in generated bootloader configuration files (or in U-Boot
1744 commands).
1745
1746 If the I<prefix> contains string $NAME, it will be replaced with the
1747 name of the novaboot script (see also B<--name>).
1748
1749 If the I<prefix> contains string $BUILDDIR, it will be replaced with
1750 the build directory (see also B<--build-dir>).
1751
1752 =item --grub-prefix
1753
1754 Alias for B<--prefix>.
1755
1756 =item --grub2[=I<filename>]
1757
1758 Generate GRUB2 menu entry in I<filename>. If I<filename> is not
1759 specified F<./boot/grub/grub.cfg> is used. The content of the menu entry can be
1760 customized with B<--grub-preamble>, B<--grub2-prolog> or
1761 B<--grub_prefix> options.
1762
1763 GRUB2 can boot multiboot-compliant kernels and a few kernels with specific
1764 support. L</BOOT_METHOD> could be used to specify the command used by GRUB2 to
1765 load the kernel. See L<GNU GRUB Manual|https://www.gnu.org/software/grub/manual/grub/grub.html#Booting>.
1766
1767 To use the generated menu entry on your development
1768 machine that uses GRUB2, append the following snippet to
1769 F</etc/grub.d/40_custom> file and regenerate your grub configuration,
1770 i.e. run update-grub on Debian/Ubuntu.
1771
1772   if [ -f /path/to/nul/build/grub.cfg ]; then
1773     source /path/to/nul/build/grub.cfg
1774   fi
1775
1776 =item --grub2-prolog=I<prolog>
1777
1778 Specifies the text that novaboot puts at the beginning of the GRUB2 menu entry.
1779
1780 =item -m, --make[=make command]
1781
1782 Runs C<make> to build files that are not generated by novaboot itself.
1783
1784 =item --name=I<string>
1785
1786 Use the name I<string> instead of the name of the novaboot script.
1787 This name is used for things like a title of grub menu or for the
1788 server directory where the boot files are copied to.
1789
1790 =item --no-file-gen
1791
1792 Do not run external commands to generate files (i.e. "<" syntax and
1793 C<run> keyword). This switch does not influence the generation of files
1794 specified with "<<WORD" syntax.
1795
1796 =item -p, --pulsar[=mac]
1797
1798 Generates pulsar bootloader configuration file named F<config-I<mac>>
1799 The I<mac> string is typically a MAC address and defaults to
1800 I<novaboot>.
1801
1802 =item --scons[=scons command]
1803
1804 Runs C<scons> to build files that are not generated by novaboot
1805 itself.
1806
1807 =item --strip-rom
1808
1809 Strip I<rom://> prefix from command lines and generated config files.
1810 The I<rom://> prefix is used by NUL. For NRE, it has to be stripped.
1811
1812 =item --gen-only
1813
1814 Exit novaboot after file generation phase.
1815
1816 =back
1817
1818 =head2 Target connection check
1819
1820 In this phase novaboot connects to target's serial port (if it has
1821 one). If another novaboot user/instance occupies the target, novaboot
1822 exits here with an error message.
1823
1824 =over 8
1825
1826 =item --amt=I<"[user[:password]@]host[:port]>
1827
1828 Use Intel AMT technology to control the target machine. WS management
1829 is used to powercycle it and Serial-Over-Lan (SOL) for input/output.
1830 The hostname or (IP address) is given by the I<host> parameter. If the
1831 I<password> is not specified, environment variable AMT_PASSWORD is
1832 used. The I<port> specifies a TCP port for SOL. If not specified, the
1833 default is 16992. The default I<user> is admin.
1834
1835 =item --iprelay=I<addr[:port]>
1836
1837 Use TCP/IP relay and serial port to access the target's serial port
1838 and powercycle it. The I<addr> parameter specifies the IP address of
1839 the relay. If I<port> is not specified, it defaults to 23.
1840
1841 Note: This option is supposed to work with HWG-ER02a IP relays.
1842
1843 =item --iprelay-cmd=I<command>
1844
1845 Similar to B<--iprelay> but uses I<command> to talk to the iprelay
1846 rather than direct network connection.
1847
1848 =item -s, --serial[=device]
1849
1850 Target's serial line is connected to host's serial line (device). The
1851 default value for device is F</dev/ttyUSB0>.
1852
1853 The value of this option is exported in NB_NOVABOOT environment
1854 variable to all subprocesses run by C<novaboot>.
1855
1856 =item --stty=I<settings>
1857
1858 Specifies settings passed to C<stty> invoked on the serial line
1859 specified with B<--serial> option. If this option is not given,
1860 C<stty> is called with C<raw -crtscts -onlcr 115200> settings.
1861
1862 =item --remote-cmd=I<cmd>
1863
1864 Command that mediates connection to the target's serial line. For
1865 example C<ssh server 'cu -l /dev/ttyS0'>.
1866
1867 =item --remote-expect=I<string>
1868
1869 Wait for reception of I<string> after establishing the remote serial
1870 line connection. Novaboot assumes that after establishing the serial
1871 line connection, the user running novaboot has exclusive access to the
1872 target. If establishing of the serial line connection happens
1873 asynchronously (e.g. running a command remotely via SSH), we need this
1874 option to wait until the exclusive access is confirmed by the remote
1875 side.
1876
1877 Depending on target configuration, this option can solve two practical
1878 problems: 1) Overwriting of files deployed by another user currently
1879 using the target. 2) Resetting the target board before serial line
1880 connection is established and thus missing bootloader interaction.
1881
1882 Example of usage with the L<sterm
1883 tool|https://rtime.felk.cvut.cz/gitweb/sojka/sterm.git>:
1884
1885   --remote-cmd='ssh -tt example.com sterm -v /dev/ttyUSB0' --remote-expect='sterm: Connected'
1886
1887 =item --remote-expect-silent=I<string>
1888
1889 The same as B<--remote-expect> except that the remote output is not
1890 echoed to stdout while waiting for the I<string>. Everything after the
1891 matched string is printed to stdout, so you may want to include line
1892 end characters in the I<string> as well.
1893
1894 =item --remote-expect-timeout=I<seconds>
1895
1896 Timeout in seconds for B<--remote-expect> or
1897 B<--remote-expect-seconds>. When negative, waits forever. The default
1898 is -1 seconds.
1899
1900 =back
1901
1902 =head2 File deployment phase
1903
1904 In some setups, it is necessary to copy the files needed for booting
1905 to a particular location, e.g. to a TFTP boot server or to the
1906 F</boot> partition.
1907
1908 =over 8
1909
1910 =item -d, --dhcp-tftp
1911
1912 Turns your workstation into a DHCP and TFTP server so that the OS can
1913 be booted via PXE BIOS (or similar mechanism) on the test machine
1914 directly connected by a plain Ethernet cable to your workstation.
1915
1916 The DHCP and TFTP servers require root privileges and C<novaboot>
1917 uses C<sudo> command to obtain those. You can put the following to
1918 I</etc/sudoers> to allow running the necessary commands without asking
1919 for a password.
1920
1921  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
1922  your_login ALL=NOPASSWD: NOVABOOT
1923
1924 =item --tftp
1925
1926 Starts a TFTP server on your workstation. This is similar to
1927 B<--dhcp-tftp> except that DHCP server is not started.
1928
1929 The TFTP server requires root privileges and C<novaboot> uses C<sudo>
1930 command to obtain those. You can put the following to I</etc/sudoers>
1931 to allow running the necessary commands without asking for a password.
1932
1933  Cmnd_Alias NOVABOOT =  /usr/sbin/in.tftpd --listen --secure -v -v -v --pidfile tftpd.pid *, /usr/bin/pkill --pidfile=tftpd.pid
1934  your_login ALL=NOPASSWD: NOVABOOT
1935
1936 =item --tftp-port=I<port>
1937
1938 Port to run the TFTP server on. Implies B<--tftp>.
1939
1940 =item --netif=I<network interface>
1941
1942 Network interface used to deploy files to the target. This option
1943 influences the configuration of the DHCP server started by
1944 B<--dhcp-tftp> and the value that B<$NB_MYIP> get replaced with during
1945 U-Boot conversation. The default value is C<$netif> variable from
1946 configuration files, which defaults to I<eth0>.
1947
1948 =item --iso[=filename]
1949
1950 Generates the ISO image that boots NOVA system via GRUB. If no filename
1951 is given, the image is stored under I<NAME>.iso, where I<NAME> is the name
1952 of the novaboot script (see also B<--name>).
1953
1954 =item --server[=[[user@]server:]path]
1955
1956 Alias of B<--copy> (kept for backward compatibility).
1957
1958 =item --copy[=[[user@]server:]path]
1959
1960 Copy all files needed for booting to another location. The files will
1961 be copied (by B<rsync> tool) to the directory I<path>. If the I<path>
1962 contains string $NAME, it will be replaced with the name of the
1963 novaboot script (see also B<--name>).
1964
1965 =item --rsync-flags=I<flags>
1966
1967 Specifies I<flags> to append to F<rsync> command line when
1968 copying files as a result of I<--copy> option.
1969
1970 =item --concat
1971
1972 If B<--copy> is used and its value ends with $NAME, then after
1973 copying the files, a new bootloader configuration file (e.g. menu.lst)
1974 is created at I<path-wo-name>, i.e. the path specified by B<--copy>
1975 with $NAME part removed. The content of the file is created by
1976 concatenating all files of the same name from all subdirectories of
1977 I<path-wo-name> found on the "server".
1978
1979 =item --ider
1980
1981 Use Intel AMT technology for IDE redirection. This allows the target
1982 machine to boot from novaboot created ISO image. Implies B<--iso>.
1983
1984 The experimental C<amtider> utility needed by this option can be
1985 obtained from https://github.com/wentasah/amtterm.
1986
1987 =back
1988
1989 =head2 Target power-on and reset phase
1990
1991 At this point, the target is reset (or switched on/off). There are
1992 several ways how this can be accomplished. Resetting a physical target
1993 can currently be accomplished by the following options: B<--amt>,
1994 B<--iprelay>, B<--reset-cmd> and B<--reset-send>.
1995
1996 =over 8
1997
1998 =item --on, --off
1999
2000 Switch on/off the target machine and exit. The script (if any) is
2001 completely ignored. Currently, it works only with the following
2002 options: B<--iprelay>, B<--amt>, B<--ssh>.
2003
2004 =item -Q, --qemu[=I<qemu-binary>]
2005
2006 Boot the configuration in qemu. Optionally, the name of qemu binary
2007 can be specified as a parameter.
2008
2009 =item --qemu-append=I<flags>
2010
2011 Append I<flags> to the default qemu flags (QEMU_FLAGS variable or
2012 C<-cpu coreduo -smp 2>).
2013
2014 =item -q, --qemu-flags=I<flags>
2015
2016 Replace the default qemu flags (QEMU_FLAGS variable or C<-cpu coreduo
2017 -smp 2>) with I<flags> specified here.
2018
2019 =item --reset-cmd=I<cmd>
2020
2021 Runs command I<cmd> to reset the target.
2022
2023 =item --reset-send=I<string>
2024
2025 Reset the target by sending the given I<string> to the remote serial
2026 line. "\n" sequences are replaced with the newline character.
2027
2028 =item --no-reset, --reset
2029
2030 Disable/enable resetting of the target.
2031
2032 =back
2033
2034 =head2 Interaction with the bootloader on the target
2035
2036 =over 8
2037
2038 =item --uboot[=I<prompt>]
2039
2040 Interact with U-Boot bootloader to boot the thing described in the
2041 novaboot script. I<prompt> specifies the U-Boot's prompt (default is
2042 "=> ", other common prompts are "U-Boot> " or "U-Boot# ").
2043
2044 =item --no-uboot
2045
2046 Disable U-Boot interaction previously enabled with B<--uboot>.
2047
2048 =item --uboot-stop-key=I<key>
2049
2050 Character, which is sent as a response to U-Boot's "Hit any key to
2051 stop autoboot" message. The default value is newline, but some devices
2052 (e.g. TP-Link TD-W8970) require a specific key to be pressed.
2053
2054 =item --uboot-init
2055
2056 Command(s) to send the U-Boot bootloader before loading the images and
2057 booting them. This option can be given multiple times. After sending
2058 commands from each option novaboot waits for U-Boot I<prompt>.
2059
2060 If the command contains string I<$NB_MYIP> then this string is
2061 replaced by IPv4 address of eth0 interface (see also B<--netif>).
2062 Similarly, I<$NB_PREFIX> is replaced with prefix given by B<--prefix>.
2063
2064 See also C<uboot> keyword in L</"NOVABOOT SCRIPT SYNTAX">).
2065
2066 =item --uboot-addr I<name>=I<address>
2067
2068 Load address of U-Boot's C<tftpboot> command for loading I<name>,
2069 where name is one of I<kernel>, I<ramdisk> or I<fdt> (flattened device
2070 tree).
2071
2072 The default addresses are ${I<name>_addr_r}, i.e. U-Boot environment
2073 variables used by convention for this purpose.
2074
2075 =item --uboot-cmd=I<command>
2076
2077 Specifies U-Boot command used to execute the OS. If the command
2078 contains strings C<$kernel_addr>, C<$ramdisk_addr>, C<$fdt_addr>,
2079 these are replaced with the addresses configured with B<--uboot-addr>.
2080
2081 The default value is
2082
2083     bootm $kernel_addr $ramdisk_addr $fdt_addr
2084
2085 or the C<UBOOT_CMD> variable if defined in the novaboot script.
2086
2087 =back
2088
2089 =head2 Target interaction phase
2090
2091 In this phase, target's serial output is redirected to stdout and if
2092 stdin is a TTY, it is redirected to the target's serial input allowing
2093 interactive work with the target.
2094
2095 =over 8
2096
2097 =item --exiton=I<string>
2098
2099 When the I<string> is sent by the target, novaboot exits. This option can
2100 be specified multiple times, in which case novaboot exits whenever
2101 either of the specified strings is sent.
2102
2103 If the I<string> is C<-re>, then the next B<--exiton>'s I<string> is
2104 treated as a regular expression. For example:
2105
2106     --exiton -re --exiton 'error:.*failed'
2107
2108 =item --exiton-re=I<regex>
2109
2110 The same as --exiton -re --exiton I<regex>.
2111
2112 =item --exiton-timeout=I<seconds>
2113
2114 By default B<--exiton> waits for the string match forever. When this
2115 option is specified, "exiton" timeouts after the specified number of
2116 seconds and novaboot returns non-zero exit code.
2117
2118 =item -i, --interactive
2119
2120 Setup things for the interactive use of the target. Your terminal will
2121 be switched to raw mode. In raw mode, your local terminal does not
2122 process input in any way (no echoing of entered characters, no
2123 interpretation of special characters). This, among others, means that
2124 Ctrl-C is passed to the target and does not interrupt novaboot. To
2125 exit from novaboot interactive mode type "~~.".
2126
2127 =item --no-interaction, --interaction
2128
2129 Skip resp. force target interaction phase. When skipped, novaboot exits
2130 immediately after the boot is initiated.
2131
2132 =item --expect=I<string>
2133
2134 When the I<string> is received from the target, send the string specified
2135 with the subsequent B<--send*> option to the target.
2136
2137 =item --expect-re=I<regex>
2138
2139 When target's output matches regular expression I<regex>, send the
2140 string specified with the subsequent B<--send*> option to the target.
2141
2142 =item --expect-raw=I<perl-code>
2143
2144 Provides direct control over Perl's Expect module.
2145
2146 =item --send=I<string>
2147
2148 Send I<string> to the target after the previously specified
2149 B<--expect*> was matched in the target's output. The I<string> may
2150 contain escape sequences such as "\n".
2151
2152 Note that I<string> is actually interpreted by Perl, so it can contain
2153 much more that escape sequences. This behavior may change in the
2154 future.
2155
2156 Example: C<--expect='login: ' --send='root\n'>
2157
2158 =item --sendcont=I<string>
2159
2160 Similar to B<--send> but continue expecting more input.
2161
2162 Example: C<--expect='Continue?' --sendcont='yes\n'>
2163
2164 =item --final-eol, --no-final-eol
2165
2166 By default, B<novaboot> always prints an end-of-line character at the
2167 end of its execution in order to ensure that the output of programs
2168 started after novaboot appears at the beginning of the line. When this
2169 is not desired B<--no-final-eol> option can be used to override this
2170 behavior.
2171
2172 =back
2173
2174 =head1 NOVABOOT SCRIPT SYNTAX
2175
2176 The syntax tries to mimic POSIX shell syntax. The syntax is defined
2177 by the following rules.
2178
2179 Lines starting with "#" and empty lines are ignored.
2180
2181 Lines that end with "\" are concatenated with the following line after
2182 removal of the final "\" and leading whitespace of the following line.
2183
2184 Lines of the form I<VARIABLE=...> (i.e. matching '^[A-Z_]+=' regular
2185 expression) assign values to internal variables. See L</VARIABLES>
2186 section.
2187
2188 Otherwise, the first word on the line defines the meaning of the line.
2189 The following keywords are supported:
2190
2191 =over 4
2192
2193 =item C<load>
2194
2195 These lines represent modules to boot. The
2196 word after C<load> is a file name (relative to the build directory
2197 (see B<--build-dir>) of the module to load and the remaining words are
2198 passed to it as the command line parameters.
2199
2200 When booting Linux, the first C<load> line usually refers to the
2201 kernel image and its command line parameters (unless you use some
2202 special pre-loader). Other C<load> lines may refer to an initramfs
2203 image and/or a device tree blob. Their order is not important, as the
2204 device tree is recognized as the file name ending with C<.dtb>.
2205
2206 When the C<load> line ends with "<<WORD" then the subsequent lines
2207 until the line containing solely WORD are copied literally to the file
2208 named on that line. This is similar to the heredoc feature of UNIX
2209 shells.
2210
2211 When the C<load> line ends with "< CMD" then command CMD is executed
2212 with F</bin/sh> and its standard output is stored in the file named on
2213 that line. The SRCDIR variable in CMD's environment is set to the
2214 absolute path of the directory containing the interpreted novaboot
2215 script.
2216
2217 =item C<copy>
2218
2219 These lines are similar to C<load> lines. The
2220 file mentioned there is copied to the same place as in the case of C<load>
2221 (e.g. tftp server), but the file is not used in the bootloader
2222 configuration. Such a file can be used by the target for other
2223 purposes than booting, e.g. at OS runtime or for firmware update.
2224
2225 =item C<chld>
2226
2227 Chainload another bootloader. Instead of loading multiboot modules
2228 identified with C<load> keyword, run another bootloader. This is
2229 currently supported only by pulsar and can be used to load e.g. Grub
2230 as in the example below:
2231
2232  chld boot/grub/i386-pc/core.0
2233
2234
2235 =item C<run>
2236
2237 Lines starting with C<run> keyword contain shell commands that are run
2238 during file generation phase. This is the same as the "< CMD" syntax
2239 for C<load> keyboard except that the command's output is not
2240 redirected to a file. The ordering of commands is the same as they
2241 appear in the novaboot script.
2242
2243 =item C<uboot>
2244
2245 These lines represent U-Boot commands that are sent to the target if
2246 B<--uboot> option is given. Having a U-Boot line in the novaboot
2247 script is the same as giving B<--uboot-init> option to novaboot. The
2248 following syntax variants are supported:
2249
2250
2251   uboot[:<timeout>] <string> [> <file>]
2252   uboot[:<timeout>] < <shell> [> <file>]
2253
2254 C<string> is the literal U-Boot command.
2255
2256 The C<uboot> keyword can be suffixed with timeout specification. The
2257 syntax is C<uboot:Ns>, where C<N> is the whole number of seconds. If
2258 the U-Boot command prompt does not appear before the timeout, novaboot
2259 fails. The default timeout is 10 seconds.
2260
2261 In the second variant with the C<<> character the shell code is
2262 executed and its standard output is sent to U-Boot. Example:
2263
2264   uboot < printf "mmc write \$loadaddr 1 %x" $(($(/usr/bin/stat -c%s rootfs.ext4) / 512))
2265
2266 When C<E<gt> file> part is present, the output of the U-Boot command
2267 is written into the given file.
2268
2269 =back
2270
2271 Example (Linux):
2272
2273   #!/usr/bin/env novaboot
2274   load bzImage console=ttyS0,115200
2275   run  make -C buildroot
2276   load rootfs.cpio < gen_cpio buildroot/images/rootfs.cpio "myapp->/etc/init.d/S99myapp"
2277
2278 Example (NOVA User Land - NUL):
2279
2280   #!/usr/bin/env novaboot
2281   WVDESC=Example program
2282   load bin/apps/sigma0.nul S0_DEFAULT script_start:1,1 \
2283                            verbose hostkeyb:0,0x60,1,12,2
2284   load bin/apps/hello.nul
2285   load hello.nulconfig <<EOF
2286   sigma0::mem:16 name::/s0/log name::/s0/timer name::/s0/fs/rom ||
2287   rom://bin/apps/hello.nul
2288   EOF
2289
2290 This example will load three modules: F<sigma0.nul>, F<hello.nul> and
2291 F<hello.nulconfig>. sigma0 receives some command line parameters and
2292 F<hello.nulconfig> file is generated on the fly from the lines between
2293 C<<<EOF> and C<EOF>.
2294
2295 Example (Zynq system update via U-Boot):
2296
2297   #!/usr/bin/env novaboot
2298
2299   uboot dhcp
2300
2301   # Write kernel to FAT filesystem on the 1st SD card partition
2302   run mkimage -f uboot-image.its image.ub
2303   copy image.ub
2304   uboot:60s tftpboot ${loadaddr} $NB_PREFIX/image.ub
2305   uboot fatwrite mmc 0:1 ${loadaddr} image.ub $filesize
2306   uboot set bootargs console=ttyPS0,115200 root=/dev/mmcblk0p2
2307
2308   # Write root FS image to the 2nd SD card partition
2309   copy rootfs/images/rootfs.ext4
2310   uboot:60s tftpboot ${loadaddr} $NB_PREFIX/rootfs/images/rootfs.ext4
2311   uboot mmc part > mmc-part.txt
2312   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))
2313
2314   UBOOT_CMD=boot
2315
2316
2317 =head2 VARIABLES
2318
2319 The following variables are interpreted in the novaboot script:
2320
2321 =over 8
2322
2323 =item BOOT_METHOD
2324
2325 Specifies the way GRUB2 boots the kernel. For kernels with multiboot
2326 support use C<multiboot> method (the default). For Linux kernel use C<linux> method.
2327
2328 =item BUILDDIR
2329
2330 Novaboot chdir()s to this directory before file generation phase. The
2331 directory name specified here is relative to the build directory
2332 specified by other means (see L</--build-dir>).
2333
2334 =item EXITON
2335
2336 Assigning this variable has the same effect as specifying L</--exiton>
2337 option.
2338
2339 =item INTERACTION
2340
2341 Setting this variable to zero is the same as giving
2342 L</--no-interaction>, specifying to one corresponds to
2343 L</--interaction>.
2344
2345 =item HYPERVISOR_PARAMS
2346
2347 Parameters passed to the hypervisor. The default value is "serial", unless
2348 overridden in the configuration file.
2349
2350 =item KERNEL
2351
2352 The kernel to use instead of the hypervisor specified in the
2353 configuration file with the C<$hypervisor> variable. The value should
2354 contain the name of the kernel image as well as its command line
2355 parameters. If this variable is defined and non-empty, the variable
2356 HYPERVISOR_PARAMS is not used.
2357
2358 =item NO_BOOT
2359
2360 If this variable is 1, the system is not booted. This is currently
2361 only implemented for U-Boot bootloader where it is useful for
2362 interacting with the bootloader without booting the system - e.g. for
2363 flashing.
2364
2365 =item QEMU
2366
2367 Use a specific qemu binary (can be overridden with B<-Q>) and flags
2368 when booting this script under qemu. If QEMU_FLAGS variable is also
2369 specified flags specified in QEMU variable are replaced by those in
2370 QEMU_FLAGS.
2371
2372 =item QEMU_FLAGS
2373
2374 Use specific qemu flags (can be overridden with B<-q>).
2375
2376 =item UBOOT_CMD
2377
2378 See L</--uboot-cmd>.
2379
2380 =item WVDESC
2381
2382 Description of the WvTest-compliant program.
2383
2384 =item WVTEST_TIMEOUT
2385
2386 The timeout in seconds for WvTest harness. If no complete line appears
2387 in the test output within the time specified here, the test fails. It
2388 is necessary to specify this for long running tests that produce no
2389 intermediate output.
2390
2391 =back
2392
2393 =head1 CONFIGURATION FILES
2394
2395 Novaboot can read its configuration from one or more files. By
2396 default, novaboot looks for files in F</etc/novaboot.d>, file
2397 F<~/.config/novaboot> and files named F<.novaboot> as described in
2398 L</Configuration reading phase>. Alternatively, configuration file
2399 location can be specified with the B<-c> switch or with the
2400 NOVABOOT_CONFIG environment variable. The configuration file has Perl
2401 syntax (i.e. it is better to put C<1;> as the last line) and should set
2402 values of certain Perl variables. The current configuration can be
2403 dumped with the B<--dump-config> switch. Some configuration variables
2404 can be overridden by environment variables (see below) or by command
2405 line switches.
2406
2407 Supported configuration variables include:
2408
2409 =over 8
2410
2411 =item $builddir
2412
2413 Build directory location relative to the location of the configuration
2414 file.
2415
2416 =item $default_target
2417
2418 Default target (see below) to use when no target is explicitly
2419 specified with the B<--target> command line option or
2420 B<NOVABOOT_TARGET> environment variable.
2421
2422 =item $netif
2423
2424 Default value for the B<--netif> option. If not specified, it defaults
2425 to I<eth0>.
2426
2427 =item %targets
2428
2429 Hash of target definitions to be used with the B<--target> option. The
2430 key is the identifier of the target, the value is the string with
2431 command line options. For instance, if the configuration file contains:
2432
2433  $targets{'mybox'} = '--copy=boot:/tftproot --serial=/dev/ttyUSB0 --grub',
2434
2435 then the following two commands are equivalent:
2436
2437  ./myos --copy=boot:/tftproot --serial=/dev/ttyUSB0 --grub
2438  ./myos -t mybox
2439
2440 =back
2441
2442 =head1 ENVIRONMENT VARIABLES
2443
2444 Some options can be specified not only via config file or command line
2445 but also through environment variables. Environment variables override
2446 the values from the configuration file and command line parameters
2447 override the environment variables.
2448
2449 =over 8
2450
2451 =item NOVABOOT_CONFIG
2452
2453 Name of the novaboot configuration file to use instead of the default
2454 one(s).
2455
2456 =item NOVABOOT_CONFIG_DIR
2457
2458 Name of the novaboot configuration directory. When not specified
2459 F</etc/novaboot.d> is used.
2460
2461 =item NOVABOOT_TARGET
2462
2463 Name of the novaboot target to use. This overrides the value of
2464 B<$default_target> from the configuration file and can be overridden
2465 with the B<--target> command line option.
2466
2467 =item NOVABOOT_BENDER
2468
2469 Defining this variable has the same effect as using B<--bender>
2470 option.
2471
2472 =back
2473
2474 =head1 AUTHORS
2475
2476 Michal Sojka <sojka@os.inf.tu-dresden.de>
2477
2478 Latest novaboot version can be found at
2479 L<https://github.com/wentasah/novaboot>.
2480
2481 =cut
2482
2483 # LocalWords:  novaboot Novaboot NOVABOOT TFTP PXE DHCP filename stty
2484 # LocalWords:  chainloader stdout Qemu qemu preprocessing ISOLINUX bootable
2485 # LocalWords:  config subprocesses sudo sudoers tftp dhcp IDE stdin
2486 # LocalWords:  subdirectories TTY whitespace heredoc POSIX WvTest