xref: /titanic_44/usr/src/grub/grub-0.97/stage2/builtins.c (revision 44bc9120699af80bb18366ca474cb2c618608ca9)
1 /* builtins.c - the GRUB builtin commands */
2 /*
3  *  GRUB  --  GRand Unified Bootloader
4  *  Copyright (C) 1999,2000,2001,2002,2003,2004  Free Software Foundation, Inc.
5  *
6  *  This program is free software; you can redistribute it and/or modify
7  *  it under the terms of the GNU General Public License as published by
8  *  the Free Software Foundation; either version 2 of the License, or
9  *  (at your option) any later version.
10  *
11  *  This program is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *  GNU General Public License for more details.
15  *
16  *  You should have received a copy of the GNU General Public License
17  *  along with this program; if not, write to the Free Software
18  *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19  */
20 
21 /* Include stdio.h before shared.h, because we can't define
22    WITHOUT_LIBC_STUBS here.  */
23 #ifdef GRUB_UTIL
24 # include <stdio.h>
25 #endif
26 
27 #include <shared.h>
28 #include <filesys.h>
29 #include <term.h>
30 
31 #ifdef SUPPORT_NETBOOT
32 # include <grub.h>
33 #endif
34 
35 #ifdef SUPPORT_SERIAL
36 # include <serial.h>
37 # include <terminfo.h>
38 #endif
39 
40 #ifdef GRUB_UTIL
41 # include <device.h>
42 #else /* ! GRUB_UTIL */
43 # include <apic.h>
44 # include <smp-imps.h>
45 #endif /* ! GRUB_UTIL */
46 
47 #ifdef USE_MD5_PASSWORDS
48 # include <md5.h>
49 #endif
50 
51 #include <cpu.h>
52 #include <expand.h>
53 
54 /* The type of kernel loaded.  */
55 kernel_t kernel_type;
56 /* The boot device.  */
57 static int bootdev;
58 /* True when the debug mode is turned on, and false
59    when it is turned off.  */
60 int debug = 0;
61 /* The default entry.  */
62 int default_entry = 0;
63 /* The fallback entry.  */
64 int fallback_entryno;
65 int fallback_entries[MAX_FALLBACK_ENTRIES];
66 /* The number of current entry.  */
67 int current_entryno;
68 /* The address for Multiboot command-line buffer.  */
69 static char *mb_cmdline;
70 /* The password.  */
71 char *password;
72 /* The password type.  */
73 password_t password_type;
74 /* The flag for indicating that the user is authoritative.  */
75 int auth = 0;
76 /* The timeout.  */
77 int grub_timeout = -1;
78 /* Whether to show the menu or not.  */
79 int show_menu = 1;
80 /* The BIOS drive map.  */
81 static unsigned short bios_drive_map[DRIVE_MAP_SIZE + 1];
82 
83 /* Prototypes for allowing straightfoward calling of builtins functions
84    inside other functions.  */
85 static int configfile_func (char *arg, int flags);
86 #ifdef SUPPORT_NETBOOT
87 static void solaris_config_file (void);
88 #endif
89 
90 unsigned int min_mem64 = 0;
91 
92 #if defined(__sun) && !defined(GRUB_UTIL)
93 extern void __enable_execute_stack (void *);
94 void
__enable_execute_stack(void * addr)95 __enable_execute_stack (void *addr)
96 {
97 }
98 #endif /* __sun && !GRUB_UTIL */
99 
100 /* Initialize the data for builtins.  */
101 void
init_builtins(void)102 init_builtins (void)
103 {
104   kernel_type = KERNEL_TYPE_NONE;
105   /* BSD and chainloading evil hacks!  */
106   bootdev = set_bootdev (0);
107   mb_cmdline = (char *) MB_CMDLINE_BUF;
108 }
109 
110 /* Initialize the data for the configuration file.  */
111 void
init_config(void)112 init_config (void)
113 {
114   default_entry = 0;
115   password = 0;
116   fallback_entryno = -1;
117   fallback_entries[0] = -1;
118   grub_timeout = -1;
119   current_rootpool[0] = '\0';
120   current_bootfs[0] = '\0';
121   current_bootpath[0] = '\0';
122   current_bootfs_obj = 0;
123   current_devid[0] = '\0';
124   is_zfs_mount = 0;
125 }
126 
127 /* Check a password for correctness.  Returns 0 if password was
128    correct, and a value != 0 for error, similarly to strcmp. */
129 int
check_password(char * entered,char * expected,password_t type)130 check_password (char *entered, char* expected, password_t type)
131 {
132   switch (type)
133     {
134     case PASSWORD_PLAIN:
135       return strcmp (entered, expected);
136 
137 #ifdef USE_MD5_PASSWORDS
138     case PASSWORD_MD5:
139       return check_md5_password (entered, expected);
140 #endif
141     default:
142       /* unsupported password type: be secure */
143       return 1;
144     }
145 }
146 
147 /* Print which sector is read when loading a file.  */
148 static void
disk_read_print_func(unsigned int sector,int offset,int length)149 disk_read_print_func(unsigned int sector, int offset, int length)
150 {
151   grub_printf ("[%u,%d,%d]", sector, offset, length);
152 }
153 
154 
155 /* blocklist */
156 static int
blocklist_func(char * arg,int flags)157 blocklist_func (char *arg, int flags)
158 {
159   char *dummy = (char *) RAW_ADDR (0x100000);
160   unsigned int start_sector = 0;
161   int num_sectors = 0;
162   int num_entries = 0;
163   int last_length = 0;
164 
165   auto void disk_read_blocklist_func (unsigned int sector, int offset,
166       int length);
167 
168   /* Collect contiguous blocks into one entry as many as possible,
169      and print the blocklist notation on the screen.  */
170   auto void disk_read_blocklist_func (unsigned int sector, int offset,
171       int length)
172     {
173       if (num_sectors > 0)
174 	{
175 	  if (start_sector + num_sectors == sector
176 	      && offset == 0 && last_length == SECTOR_SIZE)
177 	    {
178 	      num_sectors++;
179 	      last_length = length;
180 	      return;
181 	    }
182 	  else
183 	    {
184 	      if (last_length == SECTOR_SIZE)
185 		grub_printf ("%s%d+%d", num_entries ? "," : "",
186 			     start_sector - part_start, num_sectors);
187 	      else if (num_sectors > 1)
188 		grub_printf ("%s%d+%d,%d[0-%d]", num_entries ? "," : "",
189 			     start_sector - part_start, num_sectors-1,
190 			     start_sector + num_sectors-1 - part_start,
191 			     last_length);
192 	      else
193 		grub_printf ("%s%d[0-%d]", num_entries ? "," : "",
194 			     start_sector - part_start, last_length);
195 	      num_entries++;
196 	      num_sectors = 0;
197 	    }
198 	}
199 
200       if (offset > 0)
201 	{
202 	  grub_printf("%s%u[%d-%d]", num_entries ? "," : "",
203 		      sector-part_start, offset, offset+length);
204 	  num_entries++;
205 	}
206       else
207 	{
208 	  start_sector = sector;
209 	  num_sectors = 1;
210 	  last_length = length;
211 	}
212     }
213 
214   /* Open the file.  */
215   if (! grub_open (arg))
216     return 1;
217 
218   /* Print the device name.  */
219   grub_printf ("(%cd%d",
220 	       (current_drive & 0x80) ? 'h' : 'f',
221 	       current_drive & ~0x80);
222 
223   if ((current_partition & 0xFF0000) != 0xFF0000)
224     grub_printf (",%d", (current_partition >> 16) & 0xFF);
225 
226   if ((current_partition & 0x00FF00) != 0x00FF00)
227     grub_printf (",%c", 'a' + ((current_partition >> 8) & 0xFF));
228 
229   grub_printf (")");
230 
231   /* Read in the whole file to DUMMY.  */
232   disk_read_hook = disk_read_blocklist_func;
233   if (! grub_read (dummy, -1))
234     goto fail;
235 
236   /* The last entry may not be printed yet.  Don't check if it is a
237    * full sector, since it doesn't matter if we read too much. */
238   if (num_sectors > 0)
239     grub_printf ("%s%d+%d", num_entries ? "," : "",
240 		 start_sector - part_start, num_sectors);
241 
242   grub_printf ("\n");
243 
244  fail:
245   disk_read_hook = 0;
246   grub_close ();
247   return errnum;
248 }
249 
250 static struct builtin builtin_blocklist =
251 {
252   "blocklist",
253   blocklist_func,
254   BUILTIN_CMDLINE | BUILTIN_HELP_LIST,
255   "blocklist FILE",
256   "Print the blocklist notation of the file FILE."
257 };
258 
259 /* boot */
260 static int
boot_func(char * arg,int flags)261 boot_func (char *arg, int flags)
262 {
263   /* Clear the int15 handler if we can boot the kernel successfully.
264      This assumes that the boot code never fails only if KERNEL_TYPE is
265      not KERNEL_TYPE_NONE. Is this assumption is bad?  */
266   if (kernel_type != KERNEL_TYPE_NONE)
267     unset_int15_handler ();
268 
269 #ifdef SUPPORT_NETBOOT
270   /* Shut down the networking.  */
271   cleanup_net ();
272 #endif
273 
274   switch (kernel_type)
275     {
276     case KERNEL_TYPE_FREEBSD:
277     case KERNEL_TYPE_NETBSD:
278       /* *BSD */
279       bsd_boot (kernel_type, bootdev, (char *) mbi.cmdline);
280       break;
281 
282     case KERNEL_TYPE_LINUX:
283       /* Linux */
284       linux_boot ();
285       break;
286 
287     case KERNEL_TYPE_BIG_LINUX:
288       /* Big Linux */
289       big_linux_boot ();
290       break;
291 
292     case KERNEL_TYPE_CHAINLOADER:
293       /* Chainloader */
294 
295       /* Check if we should set the int13 handler.  */
296       if (bios_drive_map[0] != 0)
297 	{
298 	  int i;
299 
300 	  /* Search for SAVED_DRIVE.  */
301 	  for (i = 0; i < DRIVE_MAP_SIZE; i++)
302 	    {
303 	      if (! bios_drive_map[i])
304 		break;
305 	      else if ((bios_drive_map[i] & 0xFF) == saved_drive)
306 		{
307 		  /* Exchage SAVED_DRIVE with the mapped drive.  */
308 		  saved_drive = (bios_drive_map[i] >> 8) & 0xFF;
309 		  break;
310 		}
311 	    }
312 
313 	  /* Set the handler. This is somewhat dangerous.  */
314 	  set_int13_handler (bios_drive_map);
315 	}
316 
317       gateA20 (0);
318       boot_drive = saved_drive;
319       chain_stage1 (0, BOOTSEC_LOCATION, boot_part_addr);
320       break;
321 
322     case KERNEL_TYPE_MULTIBOOT:
323       /* Multiboot */
324 #ifdef SUPPORT_NETBOOT
325 #ifdef SOLARIS_NETBOOT
326       if (current_drive == NETWORK_DRIVE) {
327     	/*
328 	 *  XXX Solaris hack: use drive_info to pass network information
329 	 *  Turn off the flag bit to the loader is technically
330 	 *  multiboot compliant.
331 	 */
332     	mbi.flags &= ~MB_INFO_DRIVE_INFO;
333   	mbi.drives_length = dhcpack_length;
334   	mbi.drives_addr = dhcpack_buf;
335       }
336 #endif /* SOLARIS_NETBOOT */
337 #endif
338       multi_boot ((int) entry_addr, (int) &mbi);
339       break;
340 
341     default:
342       errnum = ERR_BOOT_COMMAND;
343       return 1;
344     }
345 
346   return 0;
347 }
348 
349 static struct builtin builtin_boot =
350 {
351   "boot",
352   boot_func,
353   BUILTIN_CMDLINE | BUILTIN_HELP_LIST,
354   "boot",
355   "Boot the OS/chain-loader which has been loaded."
356 };
357 
358 
359 #ifdef SUPPORT_NETBOOT
360 /* bootp */
361 static int
bootp_func(char * arg,int flags)362 bootp_func (char *arg, int flags)
363 {
364   int with_configfile = 0;
365 
366   if (grub_memcmp (arg, "--with-configfile", sizeof ("--with-configfile") - 1)
367       == 0)
368     {
369       with_configfile = 1;
370       arg = skip_to (0, arg);
371     }
372 
373   if (! bootp ())
374     {
375       if (errnum == ERR_NONE)
376 	errnum = ERR_DEV_VALUES;
377 
378       return 1;
379     }
380 
381   /* Notify the configuration.  */
382   print_network_configuration ();
383 
384   /* XXX: this can cause an endless loop, but there is no easy way to
385      detect such a loop unfortunately.  */
386   if (with_configfile)
387     configfile_func (config_file, flags);
388 
389   return 0;
390 }
391 
392 static struct builtin builtin_bootp =
393 {
394   "bootp",
395   bootp_func,
396   BUILTIN_CMDLINE | BUILTIN_MENU | BUILTIN_HELP_LIST,
397   "bootp [--with-configfile]",
398   "Initialize a network device via BOOTP. If the option `--with-configfile'"
399   " is given, try to load a configuration file specified by the 150 vendor"
400   " tag."
401 };
402 #endif /* SUPPORT_NETBOOT */
403 
404 
405 /* cat */
406 static int
cat_func(char * arg,int flags)407 cat_func (char *arg, int flags)
408 {
409   char c;
410 
411   if (! grub_open (arg))
412     return 1;
413 
414   while (grub_read (&c, 1))
415     {
416       /* Because running "cat" with a binary file can confuse the terminal,
417 	 print only some characters as they are.  */
418       if (grub_isspace (c) || (c >= ' ' && c <= '~'))
419 	grub_putchar (c);
420       else
421 	grub_putchar ('?');
422     }
423 
424   grub_close ();
425   return 0;
426 }
427 
428 static struct builtin builtin_cat =
429 {
430   "cat",
431   cat_func,
432   BUILTIN_CMDLINE | BUILTIN_HELP_LIST,
433   "cat FILE",
434   "Print the contents of the file FILE."
435 };
436 
437 
438 /* chainloader */
439 static int
chainloader_func(char * arg,int flags)440 chainloader_func (char *arg, int flags)
441 {
442   int force = 0;
443   char *file = arg;
444 
445   /* If the option `--force' is specified?  */
446   if (substring ("--force", arg) <= 0)
447     {
448       force = 1;
449       file = skip_to (0, arg);
450     }
451 
452   /* Open the file.  */
453   if (! grub_open (file))
454     {
455       kernel_type = KERNEL_TYPE_NONE;
456       return 1;
457     }
458 
459   /* Read the first block.  */
460   if (grub_read ((char *) BOOTSEC_LOCATION, SECTOR_SIZE) != SECTOR_SIZE)
461     {
462       grub_close ();
463       kernel_type = KERNEL_TYPE_NONE;
464 
465       /* This below happens, if a file whose size is less than 512 bytes
466 	 is loaded.  */
467       if (errnum == ERR_NONE)
468 	errnum = ERR_EXEC_FORMAT;
469 
470       return 1;
471     }
472 
473   /* If not loading it forcibly, check for the signature.  */
474   if (! force
475       && (*((unsigned short *) (BOOTSEC_LOCATION + BOOTSEC_SIG_OFFSET))
476 	  != BOOTSEC_SIGNATURE))
477     {
478       grub_close ();
479       errnum = ERR_EXEC_FORMAT;
480       kernel_type = KERNEL_TYPE_NONE;
481       return 1;
482     }
483 
484   grub_close ();
485   kernel_type = KERNEL_TYPE_CHAINLOADER;
486 
487   /* XXX: Windows evil hack. For now, only the first five letters are
488      checked.  */
489   if (IS_PC_SLICE_TYPE_FAT (current_slice)
490       && ! grub_memcmp ((char *) BOOTSEC_LOCATION + BOOTSEC_BPB_SYSTEM_ID,
491 			"MSWIN", 5))
492     *((unsigned long *) (BOOTSEC_LOCATION + BOOTSEC_BPB_HIDDEN_SECTORS))
493       = part_start;
494 
495   errnum = ERR_NONE;
496 
497   return 0;
498 }
499 
500 static struct builtin builtin_chainloader =
501 {
502   "chainloader",
503   chainloader_func,
504   BUILTIN_CMDLINE | BUILTIN_HELP_LIST,
505   "chainloader [--force] FILE",
506   "Load the chain-loader FILE. If --force is specified, then load it"
507   " forcibly, whether the boot loader signature is present or not."
508 };
509 
510 
511 /* This function could be used to debug new filesystem code. Put a file
512    in the new filesystem and the same file in a well-tested filesystem.
513    Then, run "cmp" with the files. If no output is obtained, probably
514    the code is good, otherwise investigate what's wrong...  */
515 /* cmp FILE1 FILE2 */
516 static int
cmp_func(char * arg,int flags)517 cmp_func (char *arg, int flags)
518 {
519   /* The filenames.  */
520   char *file1, *file2;
521   /* The addresses.  */
522   char *addr1, *addr2;
523   int i;
524   /* The size of the file.  */
525   int size;
526 
527   /* Get the filenames from ARG.  */
528   file1 = arg;
529   file2 = skip_to (0, arg);
530   if (! *file1 || ! *file2)
531     {
532       errnum = ERR_BAD_ARGUMENT;
533       return 1;
534     }
535 
536   /* Terminate the filenames for convenience.  */
537   nul_terminate (file1);
538   nul_terminate (file2);
539 
540   /* Read the whole data from FILE1.  */
541   addr1 = (char *) RAW_ADDR (0x100000);
542   if (! grub_open (file1))
543     return 1;
544 
545   /* Get the size.  */
546   size = filemax;
547   if (grub_read (addr1, -1) != size)
548     {
549       grub_close ();
550       return 1;
551     }
552 
553   grub_close ();
554 
555   /* Read the whole data from FILE2.  */
556   addr2 = addr1 + size;
557   if (! grub_open (file2))
558     return 1;
559 
560   /* Check if the size of FILE2 is equal to the one of FILE2.  */
561   if (size != filemax)
562     {
563       grub_printf ("Differ in size: 0x%x [%s], 0x%x [%s]\n",
564 		   size, file1, filemax, file2);
565       grub_close ();
566       return 0;
567     }
568 
569   if (! grub_read (addr2, -1))
570     {
571       grub_close ();
572       return 1;
573     }
574 
575   grub_close ();
576 
577   /* Now compare ADDR1 with ADDR2.  */
578   for (i = 0; i < size; i++)
579     {
580       if (addr1[i] != addr2[i])
581 	grub_printf ("Differ at the offset %d: 0x%x [%s], 0x%x [%s]\n",
582 		     i, (unsigned) addr1[i], file1,
583 		     (unsigned) addr2[i], file2);
584     }
585 
586   return 0;
587 }
588 
589 static struct builtin builtin_cmp =
590 {
591   "cmp",
592   cmp_func,
593   BUILTIN_CMDLINE,
594   "cmp FILE1 FILE2",
595   "Compare the file FILE1 with the FILE2 and inform the different values"
596   " if any."
597 };
598 
599 
600 /* color */
601 /* Set new colors used for the menu interface. Support two methods to
602    specify a color name: a direct integer representation and a symbolic
603    color name. An example of the latter is "blink-light-gray/blue".  */
604 static int
color_func(char * arg,int flags)605 color_func (char *arg, int flags)
606 {
607   char *normal;
608   char *highlight;
609   int new_normal_color;
610   int new_highlight_color;
611   static char *color_list[16] =
612   {
613     "black",
614     "blue",
615     "green",
616     "cyan",
617     "red",
618     "magenta",
619     "brown",
620     "light-gray",
621     "dark-gray",
622     "light-blue",
623     "light-green",
624     "light-cyan",
625     "light-red",
626     "light-magenta",
627     "yellow",
628     "white"
629   };
630 
631   auto int color_number (char *str);
632 
633   /* Convert the color name STR into the magical number.  */
634   auto int color_number (char *str)
635     {
636       char *ptr;
637       int i;
638       int color = 0;
639 
640       /* Find the separator.  */
641       for (ptr = str; *ptr && *ptr != '/'; ptr++)
642 	;
643 
644       /* If not found, return -1.  */
645       if (! *ptr)
646 	return -1;
647 
648       /* Terminate the string STR.  */
649       *ptr++ = 0;
650 
651       /* If STR contains the prefix "blink-", then set the `blink' bit
652 	 in COLOR.  */
653       if (substring ("blink-", str) <= 0)
654 	{
655 	  color = 0x80;
656 	  str += 6;
657 	}
658 
659       /* Search for the color name.  */
660       for (i = 0; i < 16; i++)
661 	if (grub_strcmp (color_list[i], str) == 0)
662 	  {
663 	    color |= i;
664 	    break;
665 	  }
666 
667       if (i == 16)
668 	return -1;
669 
670       str = ptr;
671       nul_terminate (str);
672 
673       /* Search for the color name.  */
674       for (i = 0; i < 8; i++)
675 	if (grub_strcmp (color_list[i], str) == 0)
676 	  {
677 	    color |= i << 4;
678 	    break;
679 	  }
680 
681       if (i == 8)
682 	return -1;
683 
684       return color;
685     }
686 
687   normal = arg;
688   highlight = skip_to (0, arg);
689 
690   new_normal_color = color_number (normal);
691   if (new_normal_color < 0 && ! safe_parse_maxint (&normal, &new_normal_color))
692     return 1;
693 
694   /* The second argument is optional, so set highlight_color
695      to inverted NORMAL_COLOR.  */
696   if (! *highlight)
697     new_highlight_color = ((new_normal_color >> 4)
698 			   | ((new_normal_color & 0xf) << 4));
699   else
700     {
701       new_highlight_color = color_number (highlight);
702       if (new_highlight_color < 0
703 	  && ! safe_parse_maxint (&highlight, &new_highlight_color))
704 	return 1;
705     }
706 
707   if (current_term->setcolor)
708     current_term->setcolor (new_normal_color, new_highlight_color);
709 
710   return 0;
711 }
712 
713 static struct builtin builtin_color =
714 {
715   "color",
716   color_func,
717   BUILTIN_CMDLINE | BUILTIN_MENU | BUILTIN_HELP_LIST,
718   "color NORMAL [HIGHLIGHT]",
719   "Change the menu colors. The color NORMAL is used for most"
720   " lines in the menu, and the color HIGHLIGHT is used to highlight the"
721   " line where the cursor points. If you omit HIGHLIGHT, then the"
722   " inverted color of NORMAL is used for the highlighted line."
723   " The format of a color is \"FG/BG\". FG and BG are symbolic color names."
724   " A symbolic color name must be one of these: black, blue, green,"
725   " cyan, red, magenta, brown, light-gray, dark-gray, light-blue,"
726   " light-green, light-cyan, light-red, light-magenta, yellow and white."
727   " But only the first eight names can be used for BG. You can prefix"
728   " \"blink-\" to FG if you want a blinking foreground color."
729 };
730 
731 
732 /* configfile */
733 static int
configfile_func(char * arg,int flags)734 configfile_func (char *arg, int flags)
735 {
736   char *new_config = config_file;
737 
738   /* Check if the file ARG is present.  */
739   if (! grub_open (arg))
740     return 1;
741 
742   grub_close ();
743 
744   /* Copy ARG to CONFIG_FILE.  */
745   while ((*new_config++ = *arg++) != 0)
746     ;
747 
748 #ifdef GRUB_UTIL
749   /* Force to load the configuration file.  */
750   use_config_file = 1;
751 #endif
752 
753   /* Make sure that the user will not be authoritative.  */
754   auth = 0;
755 
756   /* Restart cmain.  */
757   grub_longjmp (restart_env, 0);
758 
759   /* Never reach here.  */
760   return 0;
761 }
762 
763 static struct builtin builtin_configfile =
764 {
765   "configfile",
766   configfile_func,
767   BUILTIN_CMDLINE | BUILTIN_HELP_LIST,
768   "configfile FILE",
769   "Load FILE as the configuration file."
770 };
771 
772 
773 /* debug */
774 static int
debug_func(char * arg,int flags)775 debug_func (char *arg, int flags)
776 {
777   if (debug)
778     {
779       debug = 0;
780       grub_printf (" Debug mode is turned off\n");
781     }
782   else
783     {
784       debug = 1;
785       grub_printf (" Debug mode is turned on\n");
786     }
787 
788   return 0;
789 }
790 
791 static struct builtin builtin_debug =
792 {
793   "debug",
794   debug_func,
795   BUILTIN_CMDLINE,
796   "debug",
797   "Turn on/off the debug mode."
798 };
799 
800 
801 /* default */
802 static int
default_func(char * arg,int flags)803 default_func (char *arg, int flags)
804 {
805 #ifndef SUPPORT_DISKLESS
806   if (grub_strcmp (arg, "saved") == 0)
807     {
808       default_entry = saved_entryno;
809       return 0;
810     }
811 #endif /* SUPPORT_DISKLESS */
812 
813   if (! safe_parse_maxint (&arg, &default_entry))
814     return 1;
815 
816   return 0;
817 }
818 
819 static struct builtin builtin_default =
820 {
821   "default",
822   default_func,
823   BUILTIN_MENU,
824 #if 0
825   "default [NUM | `saved']",
826   "Set the default entry to entry number NUM (if not specified, it is"
827   " 0, the first entry) or the entry number saved by savedefault."
828 #endif
829 };
830 
831 
832 #ifdef GRUB_UTIL
833 /* device */
834 static int
device_func(char * arg,int flags)835 device_func (char *arg, int flags)
836 {
837   char *drive = arg;
838   char *device;
839 
840   /* Get the drive number from DRIVE.  */
841   if (! set_device (drive))
842     return 1;
843 
844   /* Get the device argument.  */
845   device = skip_to (0, drive);
846 
847   /* Terminate DEVICE.  */
848   nul_terminate (device);
849 
850   if (! *device || ! check_device (device))
851     {
852       errnum = ERR_FILE_NOT_FOUND;
853       return 1;
854     }
855 
856   assign_device_name (current_drive, device);
857 
858   return 0;
859 }
860 
861 static struct builtin builtin_device =
862 {
863   "device",
864   device_func,
865   BUILTIN_MENU | BUILTIN_CMDLINE | BUILTIN_HELP_LIST,
866   "device DRIVE DEVICE",
867   "Specify DEVICE as the actual drive for a BIOS drive DRIVE. This command"
868   " can be used only in the grub shell."
869 };
870 #endif /* GRUB_UTIL */
871 
872 #ifdef SUPPORT_NETBOOT
873 /* Debug Function for RPC */
874 #ifdef RPC_DEBUG
875 /* portmap */
876 static int
portmap_func(char * arg,int flags)877 portmap_func (char *arg, int flags)
878 {
879 	int port, prog, ver;
880 	if (! grub_eth_probe ()){
881 		grub_printf ("No ethernet card found.\n");
882 		errnum = ERR_DEV_VALUES;
883 		return 1;
884 	}
885 	if ((prog = getdec(&arg)) == -1){
886 		grub_printf("Error prog number\n");
887 		return 1;
888 	}
889 	arg = skip_to (0, arg);
890 	if ((ver = getdec(&arg)) == -1){
891 		grub_printf("Error ver number\n");
892 		return 1;
893 	}
894 	port = __pmapudp_getport(ARP_SERVER, prog, ver);
895 	printf("portmap getport %d", port);
896 	return 0;
897 }
898 
899 static struct builtin builtin_portmap =
900 {
901 	"portmap",
902 	portmap_func,
903 	BUILTIN_CMDLINE | BUILTIN_HELP_LIST,
904 	"portmap prog_number vers_number",
905 	"Do portmap with the prog_number and vers_number"
906 };
907 #endif /* RPC_DEBUG */
908 
909 /* dhcp */
910 static int
dhcp_func(char * arg,int flags)911 dhcp_func (char *arg, int flags)
912 {
913   int with_configfile = 0;
914 
915   if (grub_memcmp (arg, "--with-configfile", sizeof ("--with-configfile") - 1)
916       == 0)
917     {
918       with_configfile = 1;
919       arg = skip_to (0, arg);
920     }
921 
922   if (! dhcp ())
923     {
924       if (errnum == ERR_NONE)
925 	errnum = ERR_DEV_VALUES;
926 
927       return 1;
928     }
929 
930   /* Notify the configuration.  */
931   print_network_configuration ();
932 
933   /* XXX: this can cause an endless loop, but there is no easy way to
934      detect such a loop unfortunately.  */
935   if (with_configfile)
936     configfile_func (config_file, flags);
937   else
938     solaris_config_file();
939 
940   return 0;
941 }
942 
943 static int
test_config_file(char * menufile)944 test_config_file(char *menufile)
945 {
946 	int err;
947 
948 	/*
949 	 * If the file exists, make it the default. Else, fallback
950 	 * to what it was.  Make sure we don't change errnum in the
951 	 * process.
952 	 */
953 	err = errnum;
954 	if (grub_open(menufile)) {
955 		grub_strcpy(config_file, menufile);
956 		grub_close();
957 		errnum = err;
958 		return (1);
959 	}
960 	errnum = err;
961 	return (0);
962 }
963 
solaris_config_file(void)964 static void solaris_config_file (void)
965 {
966 	static char menufile[64];
967 	static char hexdigit[] = "0123456789ABCDEF";
968 	char *c = menufile;
969 	int i;
970 
971 	/*
972 	 * if DHCP option 150 has been provided, config_file will
973 	 * already contain the string, try it.
974 	 */
975 	if (configfile_origin == CFG_150) {
976 		if (test_config_file(config_file))
977 			return;
978 	}
979 
980 	/*
981 	 * try to find host (MAC address) specific configfile:
982 	 * menu.lst.01<ether_addr>
983 	 */
984 	grub_strcpy(c, "menu.lst.01");
985 	c += grub_strlen(c);
986 	for (i = 0; i < ETH_ALEN; i++) {
987 		unsigned char b = arptable[ARP_CLIENT].node[i];
988 		*c++ = hexdigit[b >> 4];
989 		*c++ = hexdigit[b & 0xf];
990 	}
991 	*c = 0;
992 	configfile_origin = CFG_MAC;
993 	if (test_config_file(menufile))
994 		return;
995 
996 	/*
997 	 * try to find a configfile derived from the DHCP/bootp
998 	 * BootFile string: menu.lst.<BootFile>
999 	 */
1000 	if (bootfile != NULL && bootfile[0] != 0) {
1001 		c = menufile;
1002 		grub_strcpy(c, "menu.lst.");
1003 		c += grub_strlen("menu.lst.");
1004 		i = grub_strlen("pxegrub.");
1005 		if (grub_memcmp(bootfile, "pxegrub.", i) == 0)
1006 			grub_strcpy(c, bootfile + i);
1007 		else
1008 			grub_strcpy(c, bootfile);
1009 		configfile_origin = CFG_BOOTFILE;
1010 		if (test_config_file(menufile))
1011 			return;
1012 	}
1013 
1014 	/*
1015 	 * Default to hard coded "/boot/grub/menu.lst" config file.
1016 	 * This is the last resort, so there's no need to test it,
1017 	 * as there's nothing else to try.
1018 	 */
1019 	char *cp = config_file;
1020 	/* skip leading slashes for tftp */
1021 	while (*cp == '/')
1022 		++cp;
1023   	grub_memmove (config_file, cp, strlen(cp) + 1);
1024 	configfile_origin = CFG_HARDCODED;
1025 }
1026 
1027 static struct builtin builtin_dhcp =
1028 {
1029   "dhcp",
1030   dhcp_func,
1031   BUILTIN_CMDLINE | BUILTIN_MENU | BUILTIN_HELP_LIST,
1032   "dhcp",
1033   "Initialize a network device via DHCP."
1034 };
1035 #endif /* SUPPORT_NETBOOT */
1036 
1037 static int terminal_func (char *arg, int flags);
1038 
verbose_func(char * arg,int flags)1039 static int verbose_func(char *arg, int flags) {
1040 
1041     if (grub_strcmp(arg, "off") == 0) {
1042       silent.status = DEFER_SILENT;
1043       return;
1044     } else
1045         if (flags == BUILTIN_CMDLINE) {
1046           silent.status = DEFER_VERBOSE;
1047           return;
1048         }
1049 
1050   silent.status = VERBOSE;
1051 
1052   /* get back to text console */
1053   if (current_term->shutdown) {
1054     (*current_term->shutdown)();
1055     current_term = term_table; /* assumption: console is first */
1056   }
1057 
1058   /* dump the buffer */
1059   if (!silent.looped) {
1060     /* if the buffer hasn't looped, just print it */
1061     printf("%s", silent.buffer);
1062   } else {
1063     /*
1064      * If the buffer has looped, first print the oldest part of the buffer,
1065      * which is one past the current null. Then print the newer part which
1066      * starts at the beginning of the buffer.
1067      */
1068     printf("%s", silent.buffer_start + 1);
1069     printf("%s", silent.buffer);
1070   }
1071 
1072   return 0;
1073 }
1074 
1075 static struct builtin builtin_verbose =
1076 {
1077   "verbose",
1078   verbose_func,
1079   BUILTIN_CMDLINE | BUILTIN_MENU | BUILTIN_SCRIPT | BUILTIN_HELP_LIST,
1080   "verbose",
1081   "Verbose output during menu entry (script) execution."
1082 };
1083 
1084 #ifdef SUPPORT_GRAPHICS
1085 
splashimage_func(char * arg,int flags)1086 static int splashimage_func(char *arg, int flags) {
1087     char splashimage[64];
1088     int i;
1089 
1090     /* filename can only be 64 characters due to our buffer size */
1091     if (strlen(arg) > 63)
1092 	return 1;
1093 
1094     if (flags == BUILTIN_SCRIPT)
1095         flags = BUILTIN_CMDLINE;
1096 
1097     if (flags == BUILTIN_CMDLINE) {
1098 	if (!grub_open(arg))
1099 	    return 1;
1100 	grub_close();
1101     }
1102 
1103     strcpy(splashimage, arg);
1104 
1105     /* get rid of TERM_NEED_INIT from the graphics terminal. */
1106     for (i = 0; term_table[i].name; i++) {
1107 	if (grub_strcmp (term_table[i].name, "graphics") == 0) {
1108 	    term_table[i].flags &= ~TERM_NEED_INIT;
1109 	    break;
1110 	}
1111     }
1112 
1113     graphics_set_splash(splashimage);
1114 
1115     if (flags == BUILTIN_CMDLINE && graphics_inited) {
1116 	/*
1117 	 * calling graphics_end() here flickers the screen black. OTOH not
1118 	 * calling it gets us odd plane interlacing / early palette switching ?
1119 	 * ideally one should figure out how to double buffer and switch...
1120 	 */
1121 	graphics_end();
1122 	graphics_init();
1123 	graphics_cls();
1124     }
1125 
1126     /*
1127      * This call does not explicitly initialize graphics mode, but rather
1128      * simply sets the terminal type unless we're in command line mode and
1129      * call this function while in terminal mode.
1130      */
1131     terminal_func("graphics", flags);
1132 
1133     reset_term = 0;
1134 
1135     return 0;
1136 }
1137 
1138 static struct builtin builtin_splashimage =
1139 {
1140   "splashimage",
1141   splashimage_func,
1142   BUILTIN_CMDLINE | BUILTIN_MENU | BUILTIN_SCRIPT | BUILTIN_HELP_LIST,
1143   "splashimage FILE",
1144   "Load FILE as the background image when in graphics mode."
1145 };
1146 
1147 
1148 /* foreground */
1149 static int
foreground_func(char * arg,int flags)1150 foreground_func(char *arg, int flags)
1151 {
1152     if (grub_strlen(arg) == 6) {
1153 	int r = ((hex(arg[0]) << 4) | hex(arg[1])) >> 2;
1154 	int g = ((hex(arg[2]) << 4) | hex(arg[3])) >> 2;
1155 	int b = ((hex(arg[4]) << 4) | hex(arg[5])) >> 2;
1156 
1157 	foreground = (r << 16) | (g << 8) | b;
1158 	if (graphics_inited)
1159 	    graphics_set_palette(15, r, g, b);
1160 
1161 	return (0);
1162     }
1163 
1164     return (1);
1165 }
1166 
1167 static struct builtin builtin_foreground =
1168 {
1169   "foreground",
1170   foreground_func,
1171   BUILTIN_CMDLINE | BUILTIN_MENU | BUILTIN_HELP_LIST | BUILTIN_SCRIPT,
1172   "foreground RRGGBB",
1173   "Sets the foreground color when in graphics mode."
1174   "RR is red, GG is green, and BB blue. Numbers must be in hexadecimal."
1175 };
1176 
1177 
1178 /* background */
1179 static int
background_func(char * arg,int flags)1180 background_func(char *arg, int flags)
1181 {
1182     if (grub_strlen(arg) == 6) {
1183 	int r = ((hex(arg[0]) << 4) | hex(arg[1])) >> 2;
1184 	int g = ((hex(arg[2]) << 4) | hex(arg[3])) >> 2;
1185 	int b = ((hex(arg[4]) << 4) | hex(arg[5])) >> 2;
1186 
1187 	background = (r << 16) | (g << 8) | b;
1188 	if (graphics_inited)
1189 	    graphics_set_palette(0, r, g, b);
1190 	return (0);
1191     }
1192 
1193     return (1);
1194 }
1195 
1196 static struct builtin builtin_background =
1197 {
1198   "background",
1199   background_func,
1200   BUILTIN_CMDLINE | BUILTIN_MENU | BUILTIN_HELP_LIST | BUILTIN_SCRIPT,
1201   "background RRGGBB",
1202   "Sets the background color when in graphics mode."
1203   "RR is red, GG is green, and BB blue. Numbers must be in hexadecimal."
1204 };
1205 
1206 #endif /* SUPPORT_GRAPHICS */
1207 
1208 
1209 /* clear */
1210 static int
clear_func()1211 clear_func()
1212 {
1213   if (current_term->cls)
1214     current_term->cls();
1215 
1216   return 0;
1217 }
1218 
1219 static struct builtin builtin_clear =
1220 {
1221   "clear",
1222   clear_func,
1223   BUILTIN_CMDLINE | BUILTIN_HELP_LIST,
1224   "clear",
1225   "Clear the screen"
1226 };
1227 
1228 /* displayapm */
1229 static int
displayapm_func(char * arg,int flags)1230 displayapm_func (char *arg, int flags)
1231 {
1232   if (mbi.flags & MB_INFO_APM_TABLE)
1233     {
1234       grub_printf ("APM BIOS information:\n"
1235 		   " Version:          0x%x\n"
1236 		   " 32-bit CS:        0x%x\n"
1237 		   " Offset:           0x%x\n"
1238 		   " 16-bit CS:        0x%x\n"
1239 		   " 16-bit DS:        0x%x\n"
1240 		   " 32-bit CS length: 0x%x\n"
1241 		   " 16-bit CS length: 0x%x\n"
1242 		   " 16-bit DS length: 0x%x\n",
1243 		   (unsigned) apm_bios_info.version,
1244 		   (unsigned) apm_bios_info.cseg,
1245 		   apm_bios_info.offset,
1246 		   (unsigned) apm_bios_info.cseg_16,
1247 		   (unsigned) apm_bios_info.dseg_16,
1248 		   (unsigned) apm_bios_info.cseg_len,
1249 		   (unsigned) apm_bios_info.cseg_16_len,
1250 		   (unsigned) apm_bios_info.dseg_16_len);
1251     }
1252   else
1253     {
1254       grub_printf ("No APM BIOS found or probe failed\n");
1255     }
1256 
1257   return 0;
1258 }
1259 
1260 static struct builtin builtin_displayapm =
1261 {
1262   "displayapm",
1263   displayapm_func,
1264   BUILTIN_CMDLINE | BUILTIN_HELP_LIST,
1265   "displayapm",
1266   "Display APM BIOS information."
1267 };
1268 
1269 
1270 /* displaymem */
1271 static int
displaymem_func(char * arg,int flags)1272 displaymem_func (char *arg, int flags)
1273 {
1274   if (get_eisamemsize () != -1)
1275     grub_printf (" EISA Memory BIOS Interface is present\n");
1276   if (get_mmap_entry ((void *) SCRATCHADDR, 0) != 0
1277       || *((int *) SCRATCHADDR) != 0)
1278     grub_printf (" Address Map BIOS Interface is present\n");
1279 
1280   grub_printf (" Lower memory: %uK, "
1281 	       "Upper memory (to first chipset hole): %uK\n",
1282 	       mbi.mem_lower, mbi.mem_upper);
1283 
1284   if (min_mem64 != 0)
1285   	grub_printf (" Memory limit for 64-bit ISADIR expansion: %uMB\n",
1286 	    min_mem64);
1287 
1288   if (mbi.flags & MB_INFO_MEM_MAP)
1289     {
1290       struct AddrRangeDesc *map = (struct AddrRangeDesc *) mbi.mmap_addr;
1291       int end_addr = mbi.mmap_addr + mbi.mmap_length;
1292 
1293       grub_printf (" [Address Range Descriptor entries "
1294 		   "immediately follow (values are 64-bit)]\n");
1295       while (end_addr > (int) map)
1296 	{
1297 	  char *str;
1298 
1299 	  if (map->Type == MB_ARD_MEMORY)
1300 	    str = "Usable RAM";
1301 	  else
1302 	    str = "Reserved";
1303 	  grub_printf ("   %s:  Base Address:  0x%x X 4GB + 0x%x,\n"
1304 		"      Length:   0x%x X 4GB + 0x%x bytes\n",
1305 		str,
1306 		(unsigned long) (map->BaseAddr >> 32),
1307 		(unsigned long) (map->BaseAddr & 0xFFFFFFFF),
1308 		(unsigned long) (map->Length >> 32),
1309 		(unsigned long) (map->Length & 0xFFFFFFFF));
1310 
1311 	  map = ((struct AddrRangeDesc *) (((int) map) + 4 + map->size));
1312 	}
1313     }
1314 
1315   return 0;
1316 }
1317 
1318 static struct builtin builtin_displaymem =
1319 {
1320   "displaymem",
1321   displaymem_func,
1322   BUILTIN_CMDLINE | BUILTIN_HELP_LIST,
1323   "displaymem",
1324   "Display what GRUB thinks the system address space map of the"
1325   " machine is, including all regions of physical RAM installed."
1326 };
1327 
1328 
1329 /* dump FROM TO */
1330 #ifdef GRUB_UTIL
1331 static int
dump_func(char * arg,int flags)1332 dump_func (char *arg, int flags)
1333 {
1334   char *from, *to;
1335   FILE *fp;
1336   char c;
1337 
1338   from = arg;
1339   to = skip_to (0, arg);
1340   if (! *from || ! *to)
1341     {
1342       errnum = ERR_BAD_ARGUMENT;
1343       return 1;
1344     }
1345 
1346   nul_terminate (from);
1347   nul_terminate (to);
1348 
1349   if (! grub_open (from))
1350     return 1;
1351 
1352   fp = fopen (to, "w");
1353   if (! fp)
1354     {
1355       errnum = ERR_WRITE;
1356       return 1;
1357     }
1358 
1359   while (grub_read (&c, 1))
1360     if (fputc (c, fp) == EOF)
1361       {
1362 	errnum = ERR_WRITE;
1363 	fclose (fp);
1364 	return 1;
1365       }
1366 
1367   if (fclose (fp) == EOF)
1368     {
1369       errnum = ERR_WRITE;
1370       return 1;
1371     }
1372 
1373   grub_close ();
1374   return 0;
1375 }
1376 
1377 static struct builtin builtin_dump =
1378   {
1379     "dump",
1380     dump_func,
1381     BUILTIN_CMDLINE,
1382     "dump FROM TO",
1383     "Dump the contents of the file FROM to the file TO. FROM must be"
1384     " a GRUB file and TO must be an OS file."
1385   };
1386 #endif /* GRUB_UTIL */
1387 
1388 
1389 static char embed_info[32];
1390 /* embed */
1391 /* Embed a Stage 1.5 in the first cylinder after MBR or in the
1392    bootloader block in a FFS.  */
1393 static int
embed_func(char * arg,int flags)1394 embed_func (char *arg, int flags)
1395 {
1396   char *stage1_5;
1397   char *device;
1398   char *stage1_5_buffer = (char *) RAW_ADDR (0x100000);
1399   int len, size;
1400   int sector;
1401 
1402   stage1_5 = arg;
1403   device = skip_to (0, stage1_5);
1404 
1405   /* Open a Stage 1.5.  */
1406   if (! grub_open (stage1_5))
1407     return 1;
1408 
1409   /* Read the whole of the Stage 1.5.  */
1410   len = grub_read (stage1_5_buffer, -1);
1411   grub_close ();
1412 
1413   if (errnum)
1414     return 1;
1415 
1416   size = (len + SECTOR_SIZE - 1) / SECTOR_SIZE;
1417 
1418   /* Get the device where the Stage 1.5 will be embedded.  */
1419   set_device (device);
1420   if (errnum)
1421     return 1;
1422 
1423   if (current_partition == 0xFFFFFF)
1424     {
1425       /* Embed it after the MBR.  */
1426 
1427       char mbr[SECTOR_SIZE];
1428       char ezbios_check[2*SECTOR_SIZE];
1429       int i;
1430 
1431       /* Open the partition.  */
1432       if (! open_partition ())
1433 	return 1;
1434 
1435       /* No floppy has MBR.  */
1436       if (! (current_drive & 0x80))
1437 	{
1438 	  errnum = ERR_DEV_VALUES;
1439 	  return 1;
1440 	}
1441 
1442       /* Read the MBR of CURRENT_DRIVE.  */
1443       if (! rawread (current_drive, PC_MBR_SECTOR, 0, SECTOR_SIZE, mbr))
1444 	return 1;
1445 
1446       /* Sanity check.  */
1447       if (! PC_MBR_CHECK_SIG (mbr))
1448 	{
1449 	  errnum = ERR_BAD_PART_TABLE;
1450 	  return 1;
1451 	}
1452 
1453       /* Check if the disk can store the Stage 1.5.  */
1454       for (i = 0; i < 4; i++)
1455 	if (PC_SLICE_TYPE (mbr, i) && PC_SLICE_START (mbr, i) - 1 < size)
1456 	  {
1457 	    errnum = ERR_NO_DISK_SPACE;
1458 	    return 1;
1459 	  }
1460 
1461       /* Check for EZ-BIOS signature. It should be in the third
1462        * sector, but due to remapping it can appear in the second, so
1463        * load and check both.
1464        */
1465       if (! rawread (current_drive, 1, 0, 2 * SECTOR_SIZE, ezbios_check))
1466 	return 1;
1467 
1468       if (! memcmp (ezbios_check + 3, "AERMH", 5)
1469 	  || ! memcmp (ezbios_check + 512 + 3, "AERMH", 5))
1470 	{
1471 	  /* The space after the MBR is used by EZ-BIOS which we must
1472 	   * not overwrite.
1473 	   */
1474 	  errnum = ERR_NO_DISK_SPACE;
1475 	  return 1;
1476 	}
1477 
1478       sector = 1;
1479     }
1480   else
1481     {
1482       /* Embed it in the bootloader block in the filesystem.  */
1483       int start_sector;
1484 
1485       /* Open the partition.  */
1486       if (! open_device ())
1487 	return 1;
1488 
1489       /* Check if the current slice supports embedding.  */
1490       if (fsys_table[fsys_type].embed_func == 0
1491 	  || ! fsys_table[fsys_type].embed_func (&start_sector, size))
1492 	{
1493 	  errnum = ERR_DEV_VALUES;
1494 	  return 1;
1495 	}
1496 
1497       sector = part_start + start_sector;
1498     }
1499 
1500   /* Clear the cache.  */
1501   buf_track = BUF_CACHE_INVALID;
1502 
1503   /* Now perform the embedding.  */
1504   if (! devwrite (sector - part_start, size, stage1_5_buffer))
1505     return 1;
1506 
1507   grub_printf (" %d sectors are embedded.\n", size);
1508   grub_sprintf (embed_info, "%d+%d", sector - part_start, size);
1509   return 0;
1510 }
1511 
1512 static struct builtin builtin_embed =
1513 {
1514   "embed",
1515   embed_func,
1516   BUILTIN_CMDLINE,
1517   "embed STAGE1_5 DEVICE",
1518   "Embed the Stage 1.5 STAGE1_5 in the sectors after MBR if DEVICE"
1519   " is a drive, or in the \"bootloader\" area if DEVICE is a FFS partition."
1520   " Print the number of sectors which STAGE1_5 occupies if successful."
1521 };
1522 
1523 
1524 /* fallback */
1525 static int
fallback_func(char * arg,int flags)1526 fallback_func (char *arg, int flags)
1527 {
1528   int i = 0;
1529 
1530   while (*arg)
1531     {
1532       int entry;
1533       int j;
1534 
1535       if (! safe_parse_maxint (&arg, &entry))
1536 	return 1;
1537 
1538       /* Remove duplications to prevent infinite looping.  */
1539       for (j = 0; j < i; j++)
1540 	if (entry == fallback_entries[j])
1541 	  break;
1542       if (j != i)
1543 	continue;
1544 
1545       fallback_entries[i++] = entry;
1546       if (i == MAX_FALLBACK_ENTRIES)
1547 	break;
1548 
1549       arg = skip_to (0, arg);
1550     }
1551 
1552   if (i < MAX_FALLBACK_ENTRIES)
1553     fallback_entries[i] = -1;
1554 
1555   fallback_entryno = (i == 0) ? -1 : 0;
1556 
1557   return 0;
1558 }
1559 
1560 static struct builtin builtin_fallback =
1561 {
1562   "fallback",
1563   fallback_func,
1564   BUILTIN_MENU,
1565 #if 0
1566   "fallback NUM...",
1567   "Go into unattended boot mode: if the default boot entry has any"
1568   " errors, instead of waiting for the user to do anything, it"
1569   " immediately starts over using the NUM entry (same numbering as the"
1570   " `default' command). This obviously won't help if the machine"
1571   " was rebooted by a kernel that GRUB loaded."
1572 #endif
1573 };
1574 
1575 
1576 
1577 void
set_root(char * root,unsigned long drive,unsigned long part)1578 set_root (char *root, unsigned long drive, unsigned long part)
1579 {
1580   int bsd_part = (part >> 8) & 0xFF;
1581   int pc_slice = part >> 16;
1582 
1583   if (bsd_part == 0xFF) {
1584     grub_sprintf (root, "(hd%d,%d)\n", drive - 0x80, pc_slice);
1585   } else {
1586     grub_sprintf (root, "(hd%d,%d,%c)\n",
1587 		 drive - 0x80, pc_slice, bsd_part + 'a');
1588   }
1589 }
1590 
1591 static int
find_common(char * arg,char * root,int for_root,int flags)1592 find_common (char *arg, char *root, int for_root, int flags)
1593 {
1594   char *filename = NULL;
1595   static char argpart[32];
1596   static char device[32];
1597   char *tmp_argpart = NULL;
1598   unsigned long drive;
1599   unsigned long tmp_drive = saved_drive;
1600   unsigned long tmp_partition = saved_partition;
1601   int got_file = 0;
1602   static char bootsign[BOOTSIGN_LEN];
1603 
1604   /*
1605    * If argument has partition information (findroot command only), then
1606    * it can't be a floppy
1607    */
1608   if (for_root && arg[0] == '(') {
1609 	tmp_argpart = grub_strchr(arg + 1, ',');
1610         if (tmp_argpart == NULL)
1611 		goto out;
1612 	grub_strcpy(argpart, tmp_argpart);
1613 	*tmp_argpart = '\0';
1614 	arg++;
1615         grub_sprintf(bootsign, "%s/%s", BOOTSIGN_DIR, arg);
1616 	filename = bootsign;
1617 	goto harddisk;
1618   } else if (for_root && !grub_strchr(arg, '/')) {
1619 	/* Boot signature without partition/slice information */
1620         grub_sprintf(bootsign, "%s/%s", BOOTSIGN_DIR, arg);
1621 	filename = bootsign;
1622   } else {
1623 	/* plain vanilla find cmd */
1624 	filename = arg;
1625   }
1626 
1627   /* Floppies.  */
1628   for (drive = 0; drive < 8; drive++)
1629     {
1630       current_drive = drive;
1631       current_partition = 0xFFFFFF;
1632 
1633       if (open_device ())
1634 	{
1635 	  saved_drive = current_drive;
1636 	  saved_partition = current_partition;
1637 	  if (grub_open (filename))
1638 	    {
1639 	      grub_close ();
1640 	      got_file = 1;
1641 	      if (for_root) {
1642 		 grub_sprintf(root, "(fd%d)", drive);
1643 		 goto out;
1644 	      } else
1645 	         grub_printf (" (fd%d)\n", drive);
1646 	    }
1647 	}
1648 
1649       errnum = ERR_NONE;
1650     }
1651 
1652 harddisk:
1653   /* Hard disks.  */
1654   for (drive = 0x80; drive < 0x88; drive++)
1655     {
1656       unsigned long part = 0xFFFFFF;
1657       unsigned long start, len, offset, ext_offset, gpt_offset;
1658       int type, entry, gpt_count, gpt_size;
1659       char buf[SECTOR_SIZE];
1660 
1661       if (for_root && tmp_argpart) {
1662 	grub_sprintf(device, "(hd%d%s", drive - 0x80, argpart);
1663 	set_device(device);
1664         errnum = ERR_NONE;
1665 	part = current_partition;
1666 	if (open_device ()) {
1667 	   saved_drive = current_drive;
1668 	   saved_partition = current_partition;
1669            errnum = ERR_NONE;
1670 	   if (grub_open (filename)) {
1671 	      grub_close ();
1672 	      got_file = 1;
1673 	      if (is_zfs_mount == 0) {
1674 	        set_root(root, current_drive, current_partition);
1675 	        goto out;
1676 	      } else {
1677 		best_drive = current_drive;
1678 		best_part = current_partition;
1679 	      }
1680            }
1681 	}
1682         errnum = ERR_NONE;
1683 	continue;
1684       }
1685       current_drive = drive;
1686       while (next_partition (drive, 0xFFFFFF, &part, &type,
1687 			     &start, &len, &offset, &entry,
1688 			     &ext_offset, &gpt_offset,
1689 			     &gpt_count, &gpt_size, buf))
1690 	{
1691 	  if (type != PC_SLICE_TYPE_NONE
1692 	      && ! IS_PC_SLICE_TYPE_BSD (type)
1693 	      && ! IS_PC_SLICE_TYPE_EXTENDED (type))
1694 	    {
1695 	      current_partition = part;
1696 	      if (open_device ())
1697 		{
1698 		  saved_drive = current_drive;
1699 		  saved_partition = current_partition;
1700 		  if (grub_open (filename))
1701 		    {
1702 		      char tmproot[32];
1703 
1704 		      grub_close ();
1705 		      got_file = 1;
1706 		      set_root(tmproot, drive, part);
1707 		      if (for_root) {
1708 		 	grub_memcpy(root, tmproot, sizeof(tmproot));
1709 			if (is_zfs_mount == 0) {
1710 			      goto out;
1711 			} else {
1712 			      best_drive = current_drive;
1713 			      best_part = current_partition;
1714 			}
1715 		      } else {
1716 			grub_printf("%s", tmproot);
1717 		      }
1718 		    }
1719 		}
1720 	    }
1721 
1722 	  /* We want to ignore any error here.  */
1723 	  errnum = ERR_NONE;
1724 	}
1725 
1726       /* next_partition always sets ERRNUM in the last call, so clear
1727 	 it.  */
1728       errnum = ERR_NONE;
1729     }
1730 
1731 out:
1732   if (is_zfs_mount && for_root) {
1733         set_root(root, best_drive, best_part);
1734 	buf_drive = -1;
1735   } else {
1736 	saved_drive = tmp_drive;
1737 	saved_partition = tmp_partition;
1738   }
1739   if (tmp_argpart)
1740 	*tmp_argpart = ',';
1741 
1742   if (got_file)
1743     {
1744       errnum = ERR_NONE;
1745       return 0;
1746     }
1747 
1748   errnum = ERR_FILE_NOT_FOUND;
1749   return 1;
1750 }
1751 
1752 /* find */
1753 /* Search for the filename ARG in all of partitions.  */
1754 static int
find_func(char * arg,int flags)1755 find_func (char *arg, int flags)
1756 {
1757 	return (find_common(arg, NULL, 0, flags));
1758 }
1759 
1760 static struct builtin builtin_find =
1761 {
1762   "find",
1763   find_func,
1764   BUILTIN_CMDLINE | BUILTIN_HELP_LIST,
1765   "find FILENAME",
1766   "Search for the filename FILENAME in all of partitions and print the list of"
1767   " the devices which contain the file."
1768 };
1769 
1770 
1771 /* fstest */
1772 static int
fstest_func(char * arg,int flags)1773 fstest_func (char *arg, int flags)
1774 {
1775   if (disk_read_hook)
1776     {
1777       disk_read_hook = NULL;
1778       printf (" Filesystem tracing is now off\n");
1779     }
1780   else
1781     {
1782       disk_read_hook = disk_read_print_func;
1783       printf (" Filesystem tracing is now on\n");
1784     }
1785 
1786   return 0;
1787 }
1788 
1789 static struct builtin builtin_fstest =
1790 {
1791   "fstest",
1792   fstest_func,
1793   BUILTIN_CMDLINE,
1794   "fstest",
1795   "Toggle filesystem test mode."
1796 };
1797 
1798 
1799 /* geometry */
1800 static int
geometry_func(char * arg,int flags)1801 geometry_func (char *arg, int flags)
1802 {
1803   struct geometry geom;
1804   char *msg;
1805   char *device = arg;
1806 #ifdef GRUB_UTIL
1807   char *ptr;
1808 #endif
1809 
1810   /* Get the device number.  */
1811   set_device (device);
1812   if (errnum)
1813     return 1;
1814 
1815   /* Check for the geometry.  */
1816   if (get_diskinfo (current_drive, &geom))
1817     {
1818       errnum = ERR_NO_DISK;
1819       return 1;
1820     }
1821 
1822   /* Attempt to read the first sector, because some BIOSes turns out not
1823      to support LBA even though they set the bit 0 in the support
1824      bitmap, only after reading something actually.  */
1825   if (biosdisk (BIOSDISK_READ, current_drive, &geom, 0, 1, SCRATCHSEG))
1826     {
1827       errnum = ERR_READ;
1828       return 1;
1829     }
1830 
1831 #ifdef GRUB_UTIL
1832   ptr = skip_to (0, device);
1833   if (*ptr)
1834     {
1835       char *cylinder, *head, *sector, *total_sector;
1836       int num_cylinder, num_head, num_sector, num_total_sector;
1837 
1838       cylinder = ptr;
1839       head = skip_to (0, cylinder);
1840       sector = skip_to (0, head);
1841       total_sector = skip_to (0, sector);
1842       if (! safe_parse_maxint (&cylinder, &num_cylinder)
1843 	  || ! safe_parse_maxint (&head, &num_head)
1844 	  || ! safe_parse_maxint (&sector, &num_sector))
1845 	return 1;
1846 
1847       disks[current_drive].cylinders = num_cylinder;
1848       disks[current_drive].heads = num_head;
1849       disks[current_drive].sectors = num_sector;
1850 
1851       if (safe_parse_maxint (&total_sector, &num_total_sector))
1852 	disks[current_drive].total_sectors = num_total_sector;
1853       else
1854 	disks[current_drive].total_sectors
1855 	  = num_cylinder * num_head * num_sector;
1856       errnum = 0;
1857 
1858       geom = disks[current_drive];
1859       buf_drive = -1;
1860     }
1861 #endif /* GRUB_UTIL */
1862 
1863 #ifdef GRUB_UTIL
1864   msg = device_map[current_drive];
1865 #else
1866   if (geom.flags & BIOSDISK_FLAG_LBA_EXTENSION)
1867     msg = "LBA";
1868   else
1869     msg = "CHS";
1870 #endif
1871 
1872   grub_printf ("drive 0x%x: C/H/S = %d/%d/%d, "
1873 	       "The number of sectors = %u, %s\n",
1874 	       current_drive,
1875 	       geom.cylinders, geom.heads, geom.sectors,
1876 	       geom.total_sectors, msg);
1877   real_open_partition (1);
1878 
1879   return 0;
1880 }
1881 
1882 static struct builtin builtin_geometry =
1883 {
1884   "geometry",
1885   geometry_func,
1886   BUILTIN_CMDLINE | BUILTIN_HELP_LIST,
1887   "geometry DRIVE [CYLINDER HEAD SECTOR [TOTAL_SECTOR]]",
1888   "Print the information for a drive DRIVE. In the grub shell, you can"
1889   " set the geometry of the drive arbitrarily. The number of the cylinders,"
1890   " the one of the heads, the one of the sectors and the one of the total"
1891   " sectors are set to CYLINDER, HEAD, SECTOR and TOTAL_SECTOR,"
1892   " respectively. If you omit TOTAL_SECTOR, then it will be calculated based"
1893   " on the C/H/S values automatically."
1894 };
1895 
1896 
1897 /* halt */
1898 static int
halt_func(char * arg,int flags)1899 halt_func (char *arg, int flags)
1900 {
1901   int no_apm;
1902 
1903   no_apm = (grub_memcmp (arg, "--no-apm", 8) == 0);
1904   grub_halt (no_apm);
1905 
1906   /* Never reach here.  */
1907   return 1;
1908 }
1909 
1910 static struct builtin builtin_halt =
1911 {
1912   "halt",
1913   halt_func,
1914   BUILTIN_CMDLINE | BUILTIN_HELP_LIST,
1915   "halt [--no-apm]",
1916   "Halt your system. If APM is avaiable on it, turn off the power using"
1917   " the APM BIOS, unless you specify the option `--no-apm'."
1918 };
1919 
1920 
1921 /* help */
1922 #define MAX_SHORT_DOC_LEN	39
1923 #define MAX_LONG_DOC_LEN	66
1924 
1925 static int
help_func(char * arg,int flags)1926 help_func (char *arg, int flags)
1927 {
1928   int all = 0;
1929 
1930   if (grub_memcmp (arg, "--all", sizeof ("--all") - 1) == 0)
1931     {
1932       all = 1;
1933       arg = skip_to (0, arg);
1934     }
1935 
1936   if (! *arg)
1937     {
1938       /* Invoked with no argument. Print the list of the short docs.  */
1939       struct builtin **builtin;
1940       int left = 1;
1941 
1942       for (builtin = builtin_table; *builtin != 0; builtin++)
1943 	{
1944 	  int len;
1945 	  int i;
1946 
1947 	  /* If this cannot be used in the command-line interface,
1948 	     skip this.  */
1949 	  if (! ((*builtin)->flags & BUILTIN_CMDLINE))
1950 	    continue;
1951 
1952 	  /* If this doesn't need to be listed automatically and "--all"
1953 	     is not specified, skip this.  */
1954 	  if (! all && ! ((*builtin)->flags & BUILTIN_HELP_LIST))
1955 	    continue;
1956 
1957 	  len = grub_strlen ((*builtin)->short_doc);
1958 	  /* If the length of SHORT_DOC is too long, truncate it.  */
1959 	  if (len > MAX_SHORT_DOC_LEN - 1)
1960 	    len = MAX_SHORT_DOC_LEN - 1;
1961 
1962 	  for (i = 0; i < len; i++)
1963 	    grub_putchar ((*builtin)->short_doc[i]);
1964 
1965 	  for (; i < MAX_SHORT_DOC_LEN; i++)
1966 	    grub_putchar (' ');
1967 
1968 	  if (! left)
1969 	    grub_putchar ('\n');
1970 
1971 	  left = ! left;
1972 	}
1973 
1974       /* If the last entry was at the left column, no newline was printed
1975 	 at the end.  */
1976       if (! left)
1977 	grub_putchar ('\n');
1978     }
1979   else
1980     {
1981       /* Invoked with one or more patterns.  */
1982       do
1983 	{
1984 	  struct builtin **builtin;
1985 	  char *next_arg;
1986 
1987 	  /* Get the next argument.  */
1988 	  next_arg = skip_to (0, arg);
1989 
1990 	  /* Terminate ARG.  */
1991 	  nul_terminate (arg);
1992 
1993 	  for (builtin = builtin_table; *builtin; builtin++)
1994 	    {
1995 	      /* Skip this if this is only for the configuration file.  */
1996 	      if (! ((*builtin)->flags & BUILTIN_CMDLINE))
1997 		continue;
1998 
1999 	      if (substring (arg, (*builtin)->name) < 1)
2000 		{
2001 		  char *doc = (*builtin)->long_doc;
2002 
2003 		  /* At first, print the name and the short doc.  */
2004 		  grub_printf ("%s: %s\n",
2005 			       (*builtin)->name, (*builtin)->short_doc);
2006 
2007 		  /* Print the long doc.  */
2008 		  while (*doc)
2009 		    {
2010 		      int len = grub_strlen (doc);
2011 		      int i;
2012 
2013 		      /* If LEN is too long, fold DOC.  */
2014 		      if (len > MAX_LONG_DOC_LEN)
2015 			{
2016 			  /* Fold this line at the position of a space.  */
2017 			  for (len = MAX_LONG_DOC_LEN; len > 0; len--)
2018 			    if (doc[len - 1] == ' ')
2019 			      break;
2020 			}
2021 
2022 		      grub_printf ("    ");
2023 		      for (i = 0; i < len; i++)
2024 			grub_putchar (*doc++);
2025 		      grub_putchar ('\n');
2026 		    }
2027 		}
2028 	    }
2029 
2030 	  arg = next_arg;
2031 	}
2032       while (*arg);
2033     }
2034 
2035   return 0;
2036 }
2037 
2038 static struct builtin builtin_help =
2039 {
2040   "help",
2041   help_func,
2042   BUILTIN_CMDLINE | BUILTIN_HELP_LIST,
2043   "help [--all] [PATTERN ...]",
2044   "Display helpful information about builtin commands. Not all commands"
2045   " aren't shown without the option `--all'."
2046 };
2047 
2048 
2049 /* hiddenmenu */
2050 static int
hiddenmenu_func(char * arg,int flags)2051 hiddenmenu_func (char *arg, int flags)
2052 {
2053   show_menu = 0;
2054   return 0;
2055 }
2056 
2057 static struct builtin builtin_hiddenmenu =
2058 {
2059   "hiddenmenu",
2060   hiddenmenu_func,
2061   BUILTIN_MENU,
2062 #if 0
2063   "hiddenmenu",
2064   "Hide the menu."
2065 #endif
2066 };
2067 
2068 
2069 /* hide */
2070 static int
hide_func(char * arg,int flags)2071 hide_func (char *arg, int flags)
2072 {
2073   if (! set_device (arg))
2074     return 1;
2075 
2076   if (! set_partition_hidden_flag (1))
2077     return 1;
2078 
2079   return 0;
2080 }
2081 
2082 static struct builtin builtin_hide =
2083 {
2084   "hide",
2085   hide_func,
2086   BUILTIN_CMDLINE | BUILTIN_MENU | BUILTIN_HELP_LIST,
2087   "hide PARTITION",
2088   "Hide PARTITION by setting the \"hidden\" bit in"
2089   " its partition type code."
2090 };
2091 
2092 
2093 #ifdef SUPPORT_NETBOOT
2094 /* ifconfig */
2095 static int
ifconfig_func(char * arg,int flags)2096 ifconfig_func (char *arg, int flags)
2097 {
2098   char *svr = 0, *ip = 0, *gw = 0, *sm = 0;
2099 
2100   if (! grub_eth_probe ())
2101     {
2102       grub_printf ("No ethernet card found.\n");
2103       errnum = ERR_DEV_VALUES;
2104       return 1;
2105     }
2106 
2107   while (*arg)
2108     {
2109       if (! grub_memcmp ("--server=", arg, sizeof ("--server=") - 1))
2110 	svr = arg + sizeof("--server=") - 1;
2111       else if (! grub_memcmp ("--address=", arg, sizeof ("--address=") - 1))
2112 	ip = arg + sizeof ("--address=") - 1;
2113       else if (! grub_memcmp ("--gateway=", arg, sizeof ("--gateway=") - 1))
2114 	gw = arg + sizeof ("--gateway=") - 1;
2115       else if (! grub_memcmp ("--mask=", arg, sizeof("--mask=") - 1))
2116 	sm = arg + sizeof ("--mask=") - 1;
2117       else
2118 	{
2119 	  errnum = ERR_BAD_ARGUMENT;
2120 	  return 1;
2121 	}
2122 
2123       arg = skip_to (0, arg);
2124     }
2125 
2126   if (! ifconfig (ip, sm, gw, svr))
2127     {
2128       errnum = ERR_BAD_ARGUMENT;
2129       return 1;
2130     }
2131 
2132   print_network_configuration ();
2133   return 0;
2134 }
2135 
2136 static struct builtin builtin_ifconfig =
2137 {
2138   "ifconfig",
2139   ifconfig_func,
2140   BUILTIN_CMDLINE | BUILTIN_MENU | BUILTIN_HELP_LIST,
2141   "ifconfig [--address=IP] [--gateway=IP] [--mask=MASK] [--server=IP]",
2142   "Configure the IP address, the netmask, the gateway and the server"
2143   " address or print current network configuration."
2144 };
2145 #endif /* SUPPORT_NETBOOT */
2146 
2147 
2148 /* impsprobe */
2149 static int
impsprobe_func(char * arg,int flags)2150 impsprobe_func (char *arg, int flags)
2151 {
2152 #ifdef GRUB_UTIL
2153   /* In the grub shell, we cannot probe IMPS.  */
2154   errnum = ERR_UNRECOGNIZED;
2155   return 1;
2156 #else /* ! GRUB_UTIL */
2157   if (!imps_probe ())
2158     printf (" No MPS information found or probe failed\n");
2159 
2160   return 0;
2161 #endif /* ! GRUB_UTIL */
2162 }
2163 
2164 static struct builtin builtin_impsprobe =
2165 {
2166   "impsprobe",
2167   impsprobe_func,
2168   BUILTIN_CMDLINE,
2169   "impsprobe",
2170   "Probe the Intel Multiprocessor Specification 1.1 or 1.4"
2171   " configuration table and boot the various CPUs which are found into"
2172   " a tight loop."
2173 };
2174 
2175 /* initrd */
2176 static int
initrd_func(char * arg,int flags)2177 initrd_func (char *arg, int flags)
2178 {
2179   switch (kernel_type)
2180     {
2181     case KERNEL_TYPE_LINUX:
2182     case KERNEL_TYPE_BIG_LINUX:
2183       if (! load_initrd (arg))
2184 	return 1;
2185       break;
2186 
2187     default:
2188       errnum = ERR_NEED_LX_KERNEL;
2189       return 1;
2190     }
2191 
2192   return 0;
2193 }
2194 
2195 static struct builtin builtin_initrd =
2196 {
2197   "initrd",
2198   initrd_func,
2199   BUILTIN_CMDLINE | BUILTIN_HELP_LIST,
2200   "initrd FILE [ARG ...]",
2201   "Load an initial ramdisk FILE for a Linux format boot image and set the"
2202   " appropriate parameters in the Linux setup area in memory."
2203 };
2204 
2205 
2206 /* install */
2207 static int
install_func(char * arg,int flags)2208 install_func (char *arg, int flags)
2209 {
2210   char *stage1_file, *dest_dev, *file, *addr;
2211   char *stage1_buffer = (char *) RAW_ADDR (0x100000);
2212   char *stage2_buffer = stage1_buffer + SECTOR_SIZE;
2213   char *old_sect = stage2_buffer + SECTOR_SIZE;
2214   char *stage2_first_buffer = old_sect + SECTOR_SIZE;
2215   char *stage2_second_buffer = stage2_first_buffer + SECTOR_SIZE;
2216   /* XXX: Probably SECTOR_SIZE is reasonable.  */
2217   char *config_filename = stage2_second_buffer + SECTOR_SIZE;
2218   char *dummy = config_filename + SECTOR_SIZE;
2219   int new_drive = GRUB_INVALID_DRIVE;
2220   int dest_drive, dest_partition;
2221   unsigned int dest_sector;
2222   int src_drive, src_partition, src_part_start;
2223   int i;
2224   struct geometry dest_geom, src_geom;
2225   unsigned int saved_sector;
2226   unsigned int stage2_first_sector, stage2_second_sector;
2227   char *ptr;
2228   int installaddr, installlist;
2229   /* Point to the location of the name of a configuration file in Stage 2.  */
2230   char *config_file_location;
2231   /* If FILE is a Stage 1.5?  */
2232   int is_stage1_5 = 0;
2233   /* Must call grub_close?  */
2234   int is_open = 0;
2235   /* If LBA is forced?  */
2236   int is_force_lba = 0;
2237   /* Was the last sector full? */
2238   int last_length = SECTOR_SIZE;
2239 
2240 #ifdef GRUB_UTIL
2241   /* If the Stage 2 is in a partition mounted by an OS, this will store
2242      the filename under the OS.  */
2243   char *stage2_os_file = 0;
2244 #endif /* GRUB_UTIL */
2245 
2246   auto void disk_read_savesect_func (unsigned int sector, int offset,
2247       int length);
2248   auto void disk_read_blocklist_func (unsigned int sector, int offset,
2249       int length);
2250 
2251   /* Save the first sector of Stage2 in STAGE2_SECT.  */
2252   auto void disk_read_savesect_func (unsigned int sector, int offset,
2253       int length)
2254     {
2255       if (debug)
2256 	printf ("[%u]", sector);
2257 
2258       /* ReiserFS has files which sometimes contain data not aligned
2259          on sector boundaries.  Returning an error is better than
2260          silently failing. */
2261       if (offset != 0 || length != SECTOR_SIZE)
2262 	errnum = ERR_UNALIGNED;
2263 
2264       saved_sector = sector;
2265     }
2266 
2267   /* Write SECTOR to INSTALLLIST, and update INSTALLADDR and
2268      INSTALLSECT.  */
2269   auto void disk_read_blocklist_func (unsigned int sector, int offset,
2270       int length)
2271     {
2272       if (debug)
2273 	printf("[%u]", sector);
2274 
2275       if (offset != 0 || last_length != SECTOR_SIZE)
2276 	{
2277 	  /* We found a non-sector-aligned data block. */
2278 	  errnum = ERR_UNALIGNED;
2279 	  return;
2280 	}
2281 
2282       last_length = length;
2283 
2284       if (*((unsigned long *) (installlist - 4))
2285 	  + *((unsigned short *) installlist) != sector
2286 	  || installlist == (int) stage2_first_buffer + SECTOR_SIZE + 4)
2287 	{
2288 	  installlist -= 8;
2289 
2290 	  if (*((unsigned long *) (installlist - 8)))
2291 	    errnum = ERR_WONT_FIT;
2292 	  else
2293 	    {
2294 	      *((unsigned short *) (installlist + 2)) = (installaddr >> 4);
2295 	      *((unsigned long *) (installlist - 4)) = sector;
2296 	    }
2297 	}
2298 
2299       *((unsigned short *) installlist) += 1;
2300       installaddr += 512;
2301     }
2302 
2303   /* First, check the GNU-style long option.  */
2304   while (1)
2305     {
2306       if (grub_memcmp ("--force-lba", arg, sizeof ("--force-lba") - 1) == 0)
2307 	{
2308 	  is_force_lba = 1;
2309 	  arg = skip_to (0, arg);
2310 	}
2311 #ifdef GRUB_UTIL
2312       else if (grub_memcmp ("--stage2=", arg, sizeof ("--stage2=") - 1) == 0)
2313 	{
2314 	  stage2_os_file = arg + sizeof ("--stage2=") - 1;
2315 	  arg = skip_to (0, arg);
2316 	  nul_terminate (stage2_os_file);
2317 	}
2318 #endif /* GRUB_UTIL */
2319       else
2320 	break;
2321     }
2322 
2323   stage1_file = arg;
2324   dest_dev = skip_to (0, stage1_file);
2325   if (*dest_dev == 'd')
2326     {
2327       new_drive = 0;
2328       dest_dev = skip_to (0, dest_dev);
2329     }
2330   file = skip_to (0, dest_dev);
2331   addr = skip_to (0, file);
2332 
2333   /* Get the installation address.  */
2334   if (! safe_parse_maxint (&addr, &installaddr))
2335     {
2336       /* ADDR is not specified.  */
2337       installaddr = 0;
2338       ptr = addr;
2339       errnum = 0;
2340     }
2341   else
2342     ptr = skip_to (0, addr);
2343 
2344 #ifndef NO_DECOMPRESSION
2345   /* Do not decompress Stage 1 or Stage 2.  */
2346   no_decompression = 1;
2347 #endif
2348 
2349   /* Read Stage 1.  */
2350   is_open = grub_open (stage1_file);
2351   if (! is_open
2352       || ! grub_read (stage1_buffer, SECTOR_SIZE) == SECTOR_SIZE)
2353     goto fail;
2354 
2355   /* Read the old sector from DEST_DEV.  */
2356   if (! set_device (dest_dev)
2357       || ! open_partition ()
2358       || ! devread (0, 0, SECTOR_SIZE, old_sect))
2359     goto fail;
2360 
2361   /* Store the information for the destination device.  */
2362   dest_drive = current_drive;
2363   dest_partition = current_partition;
2364   dest_geom = buf_geom;
2365   dest_sector = part_start;
2366 
2367   /* Copy the possible DOS BPB, 59 bytes at byte offset 3.  */
2368   grub_memmove (stage1_buffer + BOOTSEC_BPB_OFFSET,
2369 		old_sect + BOOTSEC_BPB_OFFSET,
2370 		BOOTSEC_BPB_LENGTH);
2371 
2372   /* If for a hard disk, copy the possible MBR/extended part table.  */
2373   if (dest_drive & 0x80)
2374     grub_memmove (stage1_buffer + STAGE1_WINDOWS_NT_MAGIC,
2375 		  old_sect + STAGE1_WINDOWS_NT_MAGIC,
2376 		  STAGE1_PARTEND - STAGE1_WINDOWS_NT_MAGIC);
2377 
2378   /* Check for the version and the signature of Stage 1.  */
2379   if (*((short *)(stage1_buffer + STAGE1_VER_MAJ_OFFS)) != COMPAT_VERSION
2380       || (*((unsigned short *) (stage1_buffer + BOOTSEC_SIG_OFFSET))
2381 	  != BOOTSEC_SIGNATURE))
2382     {
2383       errnum = ERR_BAD_VERSION;
2384       goto fail;
2385     }
2386 
2387   /* This below is not true any longer. But should we leave this alone?  */
2388 
2389   /* If DEST_DRIVE is a floppy, Stage 2 must have the iteration probe
2390      routine.  */
2391   if (! (dest_drive & 0x80)
2392       && (*((unsigned char *) (stage1_buffer + BOOTSEC_PART_OFFSET)) == 0x80
2393 	  || stage1_buffer[BOOTSEC_PART_OFFSET] == 0))
2394     {
2395       errnum = ERR_BAD_VERSION;
2396       goto fail;
2397     }
2398 
2399   grub_close ();
2400 
2401   /* Open Stage 2.  */
2402   is_open = grub_open (file);
2403   if (! is_open)
2404     goto fail;
2405 
2406   src_drive = current_drive;
2407   src_partition = current_partition;
2408   src_part_start = part_start;
2409   src_geom = buf_geom;
2410 
2411   if (! new_drive)
2412     new_drive = src_drive;
2413   else if (src_drive != dest_drive)
2414     grub_printf ("Warning: the option `d' was not used, but the Stage 1 will"
2415 		 " be installed on a\ndifferent drive than the drive where"
2416 		 " the Stage 2 resides.\n");
2417 
2418   /* Set the boot drive.  */
2419   *((unsigned char *) (stage1_buffer + STAGE1_BOOT_DRIVE)) = new_drive;
2420 
2421   /* Set the "force LBA" flag.  */
2422   *((unsigned char *) (stage1_buffer + STAGE1_FORCE_LBA)) = is_force_lba;
2423 
2424   /* If DEST_DRIVE is a hard disk, enable the workaround, which is
2425      for buggy BIOSes which don't pass boot drive correctly. Instead,
2426      they pass 0x00 or 0x01 even when booted from 0x80.  */
2427   if (dest_drive & BIOS_FLAG_FIXED_DISK)
2428     /* Replace the jmp (2 bytes) with double nop's.  */
2429     *((unsigned short *) (stage1_buffer + STAGE1_BOOT_DRIVE_CHECK))
2430       = 0x9090;
2431 
2432   /* Read the first sector of Stage 2.  */
2433   disk_read_hook = disk_read_savesect_func;
2434   if (grub_read (stage2_first_buffer, SECTOR_SIZE) != SECTOR_SIZE)
2435     goto fail;
2436 
2437   stage2_first_sector = saved_sector;
2438 
2439   /* Read the second sector of Stage 2.  */
2440   if (grub_read (stage2_second_buffer, SECTOR_SIZE) != SECTOR_SIZE)
2441     goto fail;
2442 
2443   stage2_second_sector = saved_sector;
2444 
2445   /* Check for the version of Stage 2.  */
2446   if (*((short *) (stage2_second_buffer + STAGE2_VER_MAJ_OFFS))
2447       != COMPAT_VERSION)
2448     {
2449       errnum = ERR_BAD_VERSION;
2450       goto fail;
2451     }
2452 
2453   /* Check for the Stage 2 id.  */
2454   if (stage2_second_buffer[STAGE2_STAGE2_ID] != STAGE2_ID_STAGE2)
2455     is_stage1_5 = 1;
2456 
2457   /* If INSTALLADDR is not specified explicitly in the command-line,
2458      determine it by the Stage 2 id.  */
2459   if (! installaddr)
2460     {
2461       if (! is_stage1_5)
2462 	/* Stage 2.  */
2463 	installaddr = 0x8000;
2464       else
2465 	/* Stage 1.5.  */
2466 	installaddr = 0x2000;
2467     }
2468 
2469   *((unsigned long *) (stage1_buffer + STAGE1_STAGE2_SECTOR))
2470     = stage2_first_sector;
2471   *((unsigned short *) (stage1_buffer + STAGE1_STAGE2_ADDRESS))
2472     = installaddr;
2473   *((unsigned short *) (stage1_buffer + STAGE1_STAGE2_SEGMENT))
2474     = installaddr >> 4;
2475 
2476   i = (int) stage2_first_buffer + SECTOR_SIZE - 4;
2477   while (*((unsigned long *) i))
2478     {
2479       if (i < (int) stage2_first_buffer
2480 	  || (*((int *) (i - 4)) & 0x80000000)
2481 	  || *((unsigned short *) i) >= 0xA00
2482 	  || *((short *) (i + 2)) == 0)
2483 	{
2484 	  errnum = ERR_BAD_VERSION;
2485 	  goto fail;
2486 	}
2487 
2488       *((int *) i) = 0;
2489       *((int *) (i - 4)) = 0;
2490       i -= 8;
2491     }
2492 
2493   installlist = (int) stage2_first_buffer + SECTOR_SIZE + 4;
2494   installaddr += SECTOR_SIZE;
2495 
2496   /* Read the whole of Stage2 except for the first sector.  */
2497   grub_seek (SECTOR_SIZE);
2498 
2499   disk_read_hook = disk_read_blocklist_func;
2500   if (! grub_read (dummy, -1))
2501     goto fail;
2502 
2503   disk_read_hook = 0;
2504 
2505   /* Find a string for the configuration filename.  */
2506   config_file_location = stage2_second_buffer + STAGE2_VER_STR_OFFS;
2507   while (*(config_file_location++))
2508     ;
2509 
2510   /* Set the "force LBA" flag for Stage2.  */
2511   *((unsigned char *) (stage2_second_buffer + STAGE2_FORCE_LBA))
2512     = is_force_lba;
2513 
2514   if (*ptr == 'p')
2515     {
2516       *((long *) (stage2_second_buffer + STAGE2_INSTALLPART))
2517 	= src_partition;
2518       if (is_stage1_5)
2519 	{
2520 	  /* Reset the device information in FILE if it is a Stage 1.5.  */
2521 	  unsigned long device = 0xFFFFFFFF;
2522 
2523 	  grub_memmove (config_file_location, (char *) &device,
2524 			sizeof (device));
2525 	}
2526 
2527       ptr = skip_to (0, ptr);
2528     }
2529 
2530   if (*ptr)
2531     {
2532       grub_strcpy (config_filename, ptr);
2533       nul_terminate (config_filename);
2534 
2535       if (! is_stage1_5)
2536 	/* If it is a Stage 2, just copy PTR to CONFIG_FILE_LOCATION.  */
2537 	grub_strcpy (config_file_location, ptr);
2538       else
2539 	{
2540 	  char *real_config;
2541 	  unsigned long device;
2542 
2543 	  /* Translate the external device syntax to the internal device
2544 	     syntax.  */
2545 	  if (! (real_config = set_device (ptr)))
2546 	    {
2547 	      /* The Stage 2 PTR does not contain the device name, so
2548 		 use the root device instead.  */
2549 	      errnum = ERR_NONE;
2550 	      current_drive = saved_drive;
2551 	      current_partition = saved_partition;
2552 	      real_config = ptr;
2553 	    }
2554 
2555 	  if (current_drive == src_drive)
2556 	    {
2557 	      /* If the drive where the Stage 2 resides is the same as
2558 		 the one where the Stage 1.5 resides, do not embed the
2559 		 drive number.  */
2560 	      current_drive = GRUB_INVALID_DRIVE;
2561 	    }
2562 
2563 	  device = (current_drive << 24) | current_partition;
2564 	  grub_memmove (config_file_location, (char *) &device,
2565 			sizeof (device));
2566 	  grub_strcpy (config_file_location + sizeof (device),
2567 		       real_config);
2568 	}
2569 
2570       /* If a Stage 1.5 is used, then we need to modify the Stage2.  */
2571       if (is_stage1_5)
2572 	{
2573 	  char *real_config_filename = skip_to (0, ptr);
2574 
2575 	  is_open = grub_open (config_filename);
2576 	  if (! is_open)
2577 	    goto fail;
2578 
2579 	  /* Skip the first sector.  */
2580 	  grub_seek (SECTOR_SIZE);
2581 
2582 	  disk_read_hook = disk_read_savesect_func;
2583 	  if (grub_read (stage2_buffer, SECTOR_SIZE) != SECTOR_SIZE)
2584 	    goto fail;
2585 
2586 	  disk_read_hook = 0;
2587 	  grub_close ();
2588 	  is_open = 0;
2589 
2590 	  /* Sanity check.  */
2591 	  if (*(stage2_buffer + STAGE2_STAGE2_ID) != STAGE2_ID_STAGE2)
2592 	    {
2593 	      errnum = ERR_BAD_VERSION;
2594 	      goto fail;
2595 	    }
2596 
2597 	  /* Set the "force LBA" flag for Stage2.  */
2598 	  *(stage2_buffer + STAGE2_FORCE_LBA) = is_force_lba;
2599 
2600 	  /* If REAL_CONFIG_FILENAME is specified, copy it to the Stage2.  */
2601 	  if (*real_config_filename)
2602 	    {
2603 	      /* Specified */
2604 	      char *location;
2605 
2606 	      /* Find a string for the configuration filename.  */
2607 	      location = stage2_buffer + STAGE2_VER_STR_OFFS;
2608 	      while (*(location++))
2609 		;
2610 
2611 	      /* Copy the name.  */
2612 	      grub_strcpy (location, real_config_filename);
2613 	    }
2614 
2615 	  /* Write it to the disk.  */
2616 	  buf_track = BUF_CACHE_INVALID;
2617 
2618 #ifdef GRUB_UTIL
2619 	  /* In the grub shell, access the Stage 2 via the OS filesystem
2620 	     service, if possible.  */
2621 	  if (stage2_os_file)
2622 	    {
2623 	      FILE *fp;
2624 
2625 	      fp = fopen (stage2_os_file, "r+");
2626 	      if (! fp)
2627 		{
2628 		  errnum = ERR_FILE_NOT_FOUND;
2629 		  goto fail;
2630 		}
2631 
2632 	      if (fseek (fp, SECTOR_SIZE, SEEK_SET) != 0)
2633 		{
2634 		  fclose (fp);
2635 		  errnum = ERR_BAD_VERSION;
2636 		  goto fail;
2637 		}
2638 
2639 	      if (fwrite (stage2_buffer, 1, SECTOR_SIZE, fp)
2640 		  != SECTOR_SIZE)
2641 		{
2642 		  fclose (fp);
2643 		  errnum = ERR_WRITE;
2644 		  goto fail;
2645 		}
2646 
2647 	      fclose (fp);
2648 	    }
2649 	  else
2650 #endif /* GRUB_UTIL */
2651 	    {
2652 	      if (! devwrite (saved_sector - part_start, 1, stage2_buffer))
2653 		goto fail;
2654 	    }
2655 	}
2656     }
2657 
2658   /* Clear the cache.  */
2659   buf_track = BUF_CACHE_INVALID;
2660 
2661   /* Write the modified sectors of Stage2 to the disk.  */
2662 #ifdef GRUB_UTIL
2663   if (! is_stage1_5 && stage2_os_file)
2664     {
2665       FILE *fp;
2666 
2667       fp = fopen (stage2_os_file, "r+");
2668       if (! fp)
2669 	{
2670 	  errnum = ERR_FILE_NOT_FOUND;
2671 	  goto fail;
2672 	}
2673 
2674       if (fwrite (stage2_first_buffer, 1, SECTOR_SIZE, fp) != SECTOR_SIZE)
2675 	{
2676 	  fclose (fp);
2677 	  errnum = ERR_WRITE;
2678 	  goto fail;
2679 	}
2680 
2681       if (fwrite (stage2_second_buffer, 1, SECTOR_SIZE, fp) != SECTOR_SIZE)
2682 	{
2683 	  fclose (fp);
2684 	  errnum = ERR_WRITE;
2685 	  goto fail;
2686 	}
2687 
2688       fclose (fp);
2689     }
2690   else
2691 #endif /* GRUB_UTIL */
2692     {
2693       /* The first.  */
2694       current_drive = src_drive;
2695       current_partition = src_partition;
2696 
2697       if (! open_partition ())
2698 	goto fail;
2699 
2700       if (! devwrite (stage2_first_sector - src_part_start, 1,
2701 		      stage2_first_buffer))
2702 	goto fail;
2703 
2704       if (! devwrite (stage2_second_sector - src_part_start, 1,
2705 		      stage2_second_buffer))
2706 	goto fail;
2707     }
2708 
2709   /* Write the modified sector of Stage 1 to the disk.  */
2710   current_drive = dest_drive;
2711   current_partition = dest_partition;
2712   if (! open_partition ())
2713     goto fail;
2714 
2715   devwrite (0, 1, stage1_buffer);
2716 
2717  fail:
2718   if (is_open)
2719     grub_close ();
2720 
2721   disk_read_hook = 0;
2722 
2723 #ifndef NO_DECOMPRESSION
2724   no_decompression = 0;
2725 #endif
2726 
2727   return errnum;
2728 }
2729 
2730 static struct builtin builtin_install =
2731 {
2732   "install",
2733   install_func,
2734   BUILTIN_CMDLINE,
2735   "install [--stage2=STAGE2_FILE] [--force-lba] STAGE1 [d] DEVICE STAGE2 [ADDR] [p] [CONFIG_FILE] [REAL_CONFIG_FILE]",
2736   "Install STAGE1 on DEVICE, and install a blocklist for loading STAGE2"
2737   " as a Stage 2. If the option `d' is present, the Stage 1 will always"
2738   " look for the disk where STAGE2 was installed, rather than using"
2739   " the booting drive. The Stage 2 will be loaded at address ADDR, which"
2740   " will be determined automatically if you don't specify it. If"
2741   " the option `p' or CONFIG_FILE is present, then the first block"
2742   " of Stage 2 is patched with new values of the partition and name"
2743   " of the configuration file used by the true Stage 2 (for a Stage 1.5,"
2744   " this is the name of the true Stage 2) at boot time. If STAGE2 is a Stage"
2745   " 1.5 and REAL_CONFIG_FILE is present, then the Stage 2 CONFIG_FILE is"
2746   " patched with the configuration filename REAL_CONFIG_FILE."
2747   " If the option `--force-lba' is specified, disable some sanity checks"
2748   " for LBA mode. If the option `--stage2' is specified, rewrite the Stage"
2749   " 2 via your OS's filesystem instead of the raw device."
2750 };
2751 
2752 
2753 /* ioprobe */
2754 static int
ioprobe_func(char * arg,int flags)2755 ioprobe_func (char *arg, int flags)
2756 {
2757 #ifdef GRUB_UTIL
2758 
2759   errnum = ERR_UNRECOGNIZED;
2760   return 1;
2761 
2762 #else /* ! GRUB_UTIL */
2763 
2764   unsigned short *port;
2765 
2766   /* Get the drive number.  */
2767   set_device (arg);
2768   if (errnum)
2769     return 1;
2770 
2771   /* Clean out IO_MAP.  */
2772   grub_memset ((char *) io_map, 0, IO_MAP_SIZE * sizeof (unsigned short));
2773 
2774   /* Track the int13 handler.  */
2775   track_int13 (current_drive);
2776 
2777   /* Print out the result.  */
2778   for (port = io_map; *port != 0; port++)
2779     grub_printf (" 0x%x", (unsigned int) *port);
2780 
2781   return 0;
2782 
2783 #endif /* ! GRUB_UTIL */
2784 }
2785 
2786 static struct builtin builtin_ioprobe =
2787 {
2788   "ioprobe",
2789   ioprobe_func,
2790   BUILTIN_CMDLINE,
2791   "ioprobe DRIVE",
2792   "Probe I/O ports used for the drive DRIVE."
2793 };
2794 
2795 
2796 /* kernel */
2797 static int
kernel_func(char * arg,int flags)2798 kernel_func (char *arg, int flags)
2799 {
2800   int len;
2801   kernel_t suggested_type = KERNEL_TYPE_NONE;
2802   unsigned long load_flags = 0;
2803 
2804 #ifndef AUTO_LINUX_MEM_OPT
2805   load_flags |= KERNEL_LOAD_NO_MEM_OPTION;
2806 #endif
2807 
2808   /* Deal with GNU-style long options.  */
2809   while (1)
2810     {
2811       /* If the option `--type=TYPE' is specified, convert the string to
2812 	 a kernel type.  */
2813       if (grub_memcmp (arg, "--type=", 7) == 0)
2814 	{
2815 	  arg += 7;
2816 
2817 	  if (grub_memcmp (arg, "netbsd", 6) == 0)
2818 	    suggested_type = KERNEL_TYPE_NETBSD;
2819 	  else if (grub_memcmp (arg, "freebsd", 7) == 0)
2820 	    suggested_type = KERNEL_TYPE_FREEBSD;
2821 	  else if (grub_memcmp (arg, "openbsd", 7) == 0)
2822 	    /* XXX: For now, OpenBSD is identical to NetBSD, from GRUB's
2823 	       point of view.  */
2824 	    suggested_type = KERNEL_TYPE_NETBSD;
2825 	  else if (grub_memcmp (arg, "linux", 5) == 0)
2826 	    suggested_type = KERNEL_TYPE_LINUX;
2827 	  else if (grub_memcmp (arg, "biglinux", 8) == 0)
2828 	    suggested_type = KERNEL_TYPE_BIG_LINUX;
2829 	  else if (grub_memcmp (arg, "multiboot", 9) == 0)
2830 	    suggested_type = KERNEL_TYPE_MULTIBOOT;
2831 	  else
2832 	    {
2833 	      errnum = ERR_BAD_ARGUMENT;
2834 	      return 1;
2835 	    }
2836 	}
2837       /* If the `--no-mem-option' is specified, don't pass a Linux's mem
2838 	 option automatically. If the kernel is another type, this flag
2839 	 has no effect.  */
2840       else if (grub_memcmp (arg, "--no-mem-option", 15) == 0)
2841 	load_flags |= KERNEL_LOAD_NO_MEM_OPTION;
2842       else
2843 	break;
2844 
2845       /* Try the next.  */
2846       arg = skip_to (0, arg);
2847     }
2848 
2849   len = grub_strlen (arg);
2850 
2851   /* Reset MB_CMDLINE.  */
2852   mb_cmdline = (char *) MB_CMDLINE_BUF;
2853   if (len + 1 > MB_CMDLINE_BUFLEN)
2854     {
2855       errnum = ERR_WONT_FIT;
2856       return 1;
2857     }
2858 
2859   /* Copy the command-line to MB_CMDLINE.  */
2860   grub_memmove (mb_cmdline, arg, len + 1);
2861   kernel_type = load_image (arg, mb_cmdline, suggested_type, load_flags);
2862   if (kernel_type == KERNEL_TYPE_NONE)
2863     return 1;
2864 
2865   mb_cmdline += grub_strlen(mb_cmdline) + 1;
2866   return 0;
2867 }
2868 
2869 static struct builtin builtin_kernel =
2870 {
2871   "kernel",
2872   kernel_func,
2873   BUILTIN_CMDLINE | BUILTIN_HELP_LIST,
2874   "kernel [--no-mem-option] [--type=TYPE] FILE [ARG ...]",
2875   "Attempt to load the primary boot image from FILE. The rest of the"
2876   " line is passed verbatim as the \"kernel command line\".  Any modules"
2877   " must be reloaded after using this command. The option --type is used"
2878   " to suggest what type of kernel to be loaded. TYPE must be either of"
2879   " \"netbsd\", \"freebsd\", \"openbsd\", \"linux\", \"biglinux\" and"
2880   " \"multiboot\". The option --no-mem-option tells GRUB not to pass a"
2881   " Linux's mem option automatically."
2882 };
2883 
2884 int
min_mem64_func(char * arg,int flags)2885 min_mem64_func(char *arg, int flags)
2886 {
2887 	if (!safe_parse_maxint(&arg, &min_mem64))
2888 		return (1);
2889 }
2890 
2891 static struct builtin builtin_min_mem64 =
2892 {
2893 	"min_mem64",
2894 	min_mem64_func,
2895 	BUILTIN_CMDLINE | BUILTIN_MENU | BUILTIN_SCRIPT | BUILTIN_HELP_LIST,
2896 	"min_mem64 <memory in MB>",
2897 	"Sets minimum memory (in MB) required for $ISADIR to expand to amd64, "
2898 	"even on 64-bit capable hardware."
2899 };
2900 
2901 static int
kernel_dollar_func(char * arg,int flags)2902 kernel_dollar_func (char *arg, int flags)
2903 {
2904   int err;
2905   char newarg[MAX_CMDLINE];
2906 
2907   /*
2908    * We're going to expand the arguments twice.  The first expansion, which
2909    * occurs without the benefit of knowing the ZFS object ID of the filesystem
2910    * we're booting from (if we're booting from ZFS, of course), must be
2911    * sufficient to find and read the kernel.  The second expansion will
2912    * then overwrite the command line actually set in the multiboot header with
2913    * the newly-expanded one.  Since $ZFS-BOOTFS expands differently after
2914    * zfs_open() has been called (kernel_func() -> load_image() -> grub_open() ->
2915    * zfs_open()), we need to do the second expansion so that the kernel is
2916    * given the right object ID argument.  Note that the pointer to the
2917    * command line set in the multiboot header is always MB_CMDLINE_BUF.
2918    */
2919   grub_printf("loading '%s' ...\n", arg);
2920   if ((err = expand_string(arg, newarg, MAX_CMDLINE)) != 0) {
2921     errnum = err;
2922     return (1);
2923   }
2924 
2925   if ((err = kernel_func(newarg, flags)) != 0)
2926     return (err);
2927 
2928   mb_cmdline = (char *)MB_CMDLINE_BUF;
2929   if ((err = expand_string(arg, mb_cmdline, MAX_CMDLINE)) != 0) {
2930     errnum = err;
2931     return (1);
2932   }
2933 
2934   grub_printf("loading '%s' ...\n", mb_cmdline);
2935   mb_cmdline += grub_strlen(mb_cmdline) + 1;
2936   return (0);
2937 }
2938 
2939 static struct builtin builtin_kernel_dollar =
2940 {
2941   "kernel$",
2942   kernel_dollar_func,
2943   BUILTIN_CMDLINE | BUILTIN_HELP_LIST,
2944   "kernel$ [--no-mem-option] [--type=TYPE] FILE [ARG ...]",
2945   " Just like kernel, but with variable expansion, including the legacy"
2946   " (and nonconforming) variables $ISADIR and $ZFS-BOOTFS."
2947 };
2948 
2949 
2950 /* lock */
2951 static int
lock_func(char * arg,int flags)2952 lock_func (char *arg, int flags)
2953 {
2954   if (! auth && password)
2955     {
2956       errnum = ERR_PRIVILEGED;
2957       return 1;
2958     }
2959 
2960   return 0;
2961 }
2962 
2963 static struct builtin builtin_lock =
2964 {
2965   "lock",
2966   lock_func,
2967   BUILTIN_CMDLINE,
2968   "lock",
2969   "Break a command execution unless the user is authenticated."
2970 };
2971 
2972 
2973 /* makeactive */
2974 static int
makeactive_func(char * arg,int flags)2975 makeactive_func (char *arg, int flags)
2976 {
2977   if (! make_saved_active ())
2978     return 1;
2979 
2980   return 0;
2981 }
2982 
2983 static struct builtin builtin_makeactive =
2984 {
2985   "makeactive",
2986   makeactive_func,
2987   BUILTIN_CMDLINE | BUILTIN_HELP_LIST,
2988   "makeactive",
2989   "Set the active partition on the root disk to GRUB's root device."
2990   " This command is limited to _primary_ PC partitions on a hard disk."
2991 };
2992 
2993 
2994 /* map */
2995 /* Map FROM_DRIVE to TO_DRIVE.  */
2996 static int
map_func(char * arg,int flags)2997 map_func (char *arg, int flags)
2998 {
2999   char *to_drive;
3000   char *from_drive;
3001   unsigned long to, from;
3002   int i;
3003 
3004   to_drive = arg;
3005   from_drive = skip_to (0, arg);
3006 
3007   /* Get the drive number for TO_DRIVE.  */
3008   set_device (to_drive);
3009   if (errnum)
3010     return 1;
3011   to = current_drive;
3012 
3013   /* Get the drive number for FROM_DRIVE.  */
3014   set_device (from_drive);
3015   if (errnum)
3016     return 1;
3017   from = current_drive;
3018 
3019   /* Search for an empty slot in BIOS_DRIVE_MAP.  */
3020   for (i = 0; i < DRIVE_MAP_SIZE; i++)
3021     {
3022       /* Perhaps the user wants to override the map.  */
3023       if ((bios_drive_map[i] & 0xff) == from)
3024 	break;
3025 
3026       if (! bios_drive_map[i])
3027 	break;
3028     }
3029 
3030   if (i == DRIVE_MAP_SIZE)
3031     {
3032       errnum = ERR_WONT_FIT;
3033       return 1;
3034     }
3035 
3036   if (to == from)
3037     /* If TO is equal to FROM, delete the entry.  */
3038     grub_memmove ((char *) &bios_drive_map[i], (char *) &bios_drive_map[i + 1],
3039 		  sizeof (unsigned short) * (DRIVE_MAP_SIZE - i));
3040   else
3041     bios_drive_map[i] = from | (to << 8);
3042 
3043   return 0;
3044 }
3045 
3046 static struct builtin builtin_map =
3047 {
3048   "map",
3049   map_func,
3050   BUILTIN_CMDLINE | BUILTIN_HELP_LIST,
3051   "map TO_DRIVE FROM_DRIVE",
3052   "Map the drive FROM_DRIVE to the drive TO_DRIVE. This is necessary"
3053   " when you chain-load some operating systems, such as DOS, if such an"
3054   " OS resides at a non-first drive."
3055 };
3056 
3057 
3058 #ifdef USE_MD5_PASSWORDS
3059 /* md5crypt */
3060 static int
md5crypt_func(char * arg,int flags)3061 md5crypt_func (char *arg, int flags)
3062 {
3063   char crypted[36];
3064   char key[32];
3065   unsigned int seed;
3066   int i;
3067   const char *const seedchars =
3068     "./0123456789ABCDEFGHIJKLMNOPQRST"
3069     "UVWXYZabcdefghijklmnopqrstuvwxyz";
3070 
3071   /* First create a salt.  */
3072 
3073   /* The magical prefix.  */
3074   grub_memset (crypted, 0, sizeof (crypted));
3075   grub_memmove (crypted, "$1$", 3);
3076 
3077   /* Create the length of a salt.  */
3078   seed = currticks ();
3079 
3080   /* Generate a salt.  */
3081   for (i = 0; i < 8 && seed; i++)
3082     {
3083       /* FIXME: This should be more random.  */
3084       crypted[3 + i] = seedchars[seed & 0x3f];
3085       seed >>= 6;
3086     }
3087 
3088   /* A salt must be terminated with `$', if it is less than 8 chars.  */
3089   crypted[3 + i] = '$';
3090 
3091 #ifdef DEBUG_MD5CRYPT
3092   grub_printf ("salt = %s\n", crypted);
3093 #endif
3094 
3095   /* Get a password.  */
3096   grub_memset (key, 0, sizeof (key));
3097   get_cmdline ("Password: ", key, sizeof (key) - 1, '*', 0);
3098 
3099   /* Crypt the key.  */
3100   make_md5_password (key, crypted);
3101 
3102   grub_printf ("Encrypted: %s\n", crypted);
3103   return 0;
3104 }
3105 
3106 static struct builtin builtin_md5crypt =
3107 {
3108   "md5crypt",
3109   md5crypt_func,
3110   BUILTIN_CMDLINE | BUILTIN_HELP_LIST,
3111   "md5crypt",
3112   "Generate a password in MD5 format."
3113 };
3114 #endif /* USE_MD5_PASSWORDS */
3115 
3116 
3117 /* module */
3118 static int
module_func(char * arg,int flags)3119 module_func (char *arg, int flags)
3120 {
3121   int len = grub_strlen (arg);
3122 
3123   switch (kernel_type)
3124     {
3125     case KERNEL_TYPE_MULTIBOOT:
3126       if (mb_cmdline + len + 1 > (char *) MB_CMDLINE_BUF + MB_CMDLINE_BUFLEN)
3127 	{
3128 	  errnum = ERR_WONT_FIT;
3129 	  return 1;
3130 	}
3131       grub_memmove (mb_cmdline, arg, len + 1);
3132       if (! load_module (arg, mb_cmdline))
3133 	return 1;
3134 
3135       mb_cmdline += grub_strlen(mb_cmdline) + 1;
3136       break;
3137 
3138     case KERNEL_TYPE_LINUX:
3139     case KERNEL_TYPE_BIG_LINUX:
3140       if (! load_initrd (arg))
3141 	return 1;
3142       break;
3143 
3144     default:
3145       errnum = ERR_NEED_MB_KERNEL;
3146       return 1;
3147     }
3148 
3149   return 0;
3150 }
3151 
3152 static struct builtin builtin_module =
3153 {
3154   "module",
3155   module_func,
3156   BUILTIN_CMDLINE | BUILTIN_HELP_LIST,
3157   "module FILE [ARG ...]",
3158   "Load a boot module FILE for a Multiboot format boot image (no"
3159   " interpretation of the file contents is made, so users of this"
3160   " command must know what the kernel in question expects). The"
3161   " rest of the line is passed as the \"module command line\", like"
3162   " the `kernel' command."
3163 };
3164 
3165 /* module$ */
3166 static int
module_dollar_func(char * arg,int flags)3167 module_dollar_func (char *arg, int flags)
3168 {
3169   char newarg[MAX_CMDLINE];
3170   char *cmdline_sav = mb_cmdline;
3171   int err;
3172 
3173   grub_printf("loading '%s' ...\n", arg);
3174   if ((err = expand_string(arg, newarg, MAX_CMDLINE)) != 0) {
3175     errnum = err;
3176     return (1);
3177   }
3178 
3179   if ((err = module_func(newarg, flags)) != 0)
3180     return (err);
3181 
3182   if ((err = expand_string(arg, cmdline_sav, MAX_CMDLINE)) != 0) {
3183     errnum = err;
3184     return (1);
3185   }
3186 
3187   grub_printf("loading '%s' ...\n", cmdline_sav);
3188   mb_cmdline += grub_strlen(cmdline_sav) + 1;
3189   return (0);
3190 }
3191 
3192 static struct builtin builtin_module_dollar =
3193 {
3194   "module$",
3195   module_dollar_func,
3196   BUILTIN_CMDLINE | BUILTIN_HELP_LIST,
3197   "module FILE [ARG ...]",
3198   " Just like module, but with $ISADIR expansion."
3199 };
3200 
3201 
3202 /* modulenounzip */
3203 static int
modulenounzip_func(char * arg,int flags)3204 modulenounzip_func (char *arg, int flags)
3205 {
3206   int ret;
3207 
3208 #ifndef NO_DECOMPRESSION
3209   no_decompression = 1;
3210 #endif
3211 
3212   ret = module_func (arg, flags);
3213 
3214 #ifndef NO_DECOMPRESSION
3215   no_decompression = 0;
3216 #endif
3217 
3218   return ret;
3219 }
3220 
3221 static struct builtin builtin_modulenounzip =
3222 {
3223   "modulenounzip",
3224   modulenounzip_func,
3225   BUILTIN_CMDLINE | BUILTIN_HELP_LIST,
3226   "modulenounzip FILE [ARG ...]",
3227   "The same as `module', except that automatic decompression is"
3228   " disabled."
3229 };
3230 
3231 
3232 /* pager [on|off] */
3233 static int
pager_func(char * arg,int flags)3234 pager_func (char *arg, int flags)
3235 {
3236   /* If ARG is empty, toggle the flag.  */
3237   if (! *arg)
3238     use_pager = ! use_pager;
3239   else if (grub_memcmp (arg, "on", 2) == 0)
3240     use_pager = 1;
3241   else if (grub_memcmp (arg, "off", 3) == 0)
3242     use_pager = 0;
3243   else
3244     {
3245       errnum = ERR_BAD_ARGUMENT;
3246       return 1;
3247     }
3248 
3249   grub_printf (" Internal pager is now %s\n", use_pager ? "on" : "off");
3250   return 0;
3251 }
3252 
3253 static struct builtin builtin_pager =
3254 {
3255   "pager",
3256   pager_func,
3257   BUILTIN_CMDLINE | BUILTIN_MENU | BUILTIN_HELP_LIST,
3258   "pager [FLAG]",
3259   "Toggle pager mode with no argument. If FLAG is given and its value"
3260   " is `on', turn on the mode. If FLAG is `off', turn off the mode."
3261 };
3262 
3263 
3264 /* partnew PART TYPE START LEN */
3265 static int
partnew_func(char * arg,int flags)3266 partnew_func (char *arg, int flags)
3267 {
3268   int new_type, new_start, new_len;
3269   int start_cl, start_ch, start_dh;
3270   int end_cl, end_ch, end_dh;
3271   int entry;
3272   char mbr[512];
3273 
3274   /* Convert a LBA address to a CHS address in the INT 13 format.  */
3275   auto void lba_to_chs (int lba, int *cl, int *ch, int *dh);
3276   void lba_to_chs (int lba, int *cl, int *ch, int *dh)
3277     {
3278       int cylinder, head, sector;
3279 
3280       sector = lba % buf_geom.sectors + 1;
3281       head = (lba / buf_geom.sectors) % buf_geom.heads;
3282       cylinder = lba / (buf_geom.sectors * buf_geom.heads);
3283 
3284       if (cylinder >= buf_geom.cylinders)
3285 	cylinder = buf_geom.cylinders - 1;
3286 
3287       *cl = sector | ((cylinder & 0x300) >> 2);
3288       *ch = cylinder & 0xFF;
3289       *dh = head;
3290     }
3291 
3292   /* Get the drive and the partition.  */
3293   if (! set_device (arg))
3294     return 1;
3295 
3296   /* The drive must be a hard disk.  */
3297   if (! (current_drive & 0x80))
3298     {
3299       errnum = ERR_BAD_ARGUMENT;
3300       return 1;
3301     }
3302 
3303   /* The partition must a primary partition.  */
3304   if ((current_partition >> 16) > 3
3305       || (current_partition & 0xFFFF) != 0xFFFF)
3306     {
3307       errnum = ERR_BAD_ARGUMENT;
3308       return 1;
3309     }
3310 
3311   entry = current_partition >> 16;
3312 
3313   /* Get the new partition type.  */
3314   arg = skip_to (0, arg);
3315   if (! safe_parse_maxint (&arg, &new_type))
3316     return 1;
3317 
3318   /* The partition type is unsigned char.  */
3319   if (new_type > 0xFF)
3320     {
3321       errnum = ERR_BAD_ARGUMENT;
3322       return 1;
3323     }
3324 
3325   /* Get the new partition start.  */
3326   arg = skip_to (0, arg);
3327   if (! safe_parse_maxint (&arg, &new_start))
3328     return 1;
3329 
3330   /* Get the new partition length.  */
3331   arg = skip_to (0, arg);
3332   if (! safe_parse_maxint (&arg, &new_len))
3333     return 1;
3334 
3335   /* Read the MBR.  */
3336   if (! rawread (current_drive, 0, 0, SECTOR_SIZE, mbr))
3337     return 1;
3338 
3339   /* Store the partition information in the MBR.  */
3340   lba_to_chs (new_start, &start_cl, &start_ch, &start_dh);
3341   lba_to_chs (new_start + new_len - 1, &end_cl, &end_ch, &end_dh);
3342 
3343   PC_SLICE_FLAG (mbr, entry) = 0;
3344   PC_SLICE_HEAD (mbr, entry) = start_dh;
3345   PC_SLICE_SEC (mbr, entry) = start_cl;
3346   PC_SLICE_CYL (mbr, entry) = start_ch;
3347   PC_SLICE_TYPE (mbr, entry) = new_type;
3348   PC_SLICE_EHEAD (mbr, entry) = end_dh;
3349   PC_SLICE_ESEC (mbr, entry) = end_cl;
3350   PC_SLICE_ECYL (mbr, entry) = end_ch;
3351   PC_SLICE_START (mbr, entry) = new_start;
3352   PC_SLICE_LENGTH (mbr, entry) = new_len;
3353 
3354   /* Make sure that the MBR has a valid signature.  */
3355   PC_MBR_SIG (mbr) = PC_MBR_SIGNATURE;
3356 
3357   /* Write back the MBR to the disk.  */
3358   buf_track = BUF_CACHE_INVALID;
3359   if (! rawwrite (current_drive, 0, mbr))
3360     return 1;
3361 
3362   return 0;
3363 }
3364 
3365 static struct builtin builtin_partnew =
3366 {
3367   "partnew",
3368   partnew_func,
3369   BUILTIN_CMDLINE | BUILTIN_MENU | BUILTIN_HELP_LIST,
3370   "partnew PART TYPE START LEN",
3371   "Create a primary partition at the starting address START with the"
3372   " length LEN, with the type TYPE. START and LEN are in sector units."
3373 };
3374 
3375 
3376 /* parttype PART TYPE */
3377 static int
parttype_func(char * arg,int flags)3378 parttype_func (char *arg, int flags)
3379 {
3380   int new_type;
3381   unsigned long part = 0xFFFFFF;
3382   unsigned long start, len, offset, ext_offset, gpt_offset;
3383   int entry, type, gpt_count, gpt_size;
3384   char mbr[512];
3385 
3386   /* Get the drive and the partition.  */
3387   if (! set_device (arg))
3388     return 1;
3389 
3390   /* The drive must be a hard disk.  */
3391   if (! (current_drive & 0x80))
3392     {
3393       errnum = ERR_BAD_ARGUMENT;
3394       return 1;
3395     }
3396 
3397   /* The partition must be a PC slice.  */
3398   if ((current_partition >> 16) == 0xFF
3399       || (current_partition & 0xFFFF) != 0xFFFF)
3400     {
3401       errnum = ERR_BAD_ARGUMENT;
3402       return 1;
3403     }
3404 
3405   /* Get the new partition type.  */
3406   arg = skip_to (0, arg);
3407   if (! safe_parse_maxint (&arg, &new_type))
3408     return 1;
3409 
3410   /* The partition type is unsigned char.  */
3411   if (new_type > 0xFF)
3412     {
3413       errnum = ERR_BAD_ARGUMENT;
3414       return 1;
3415     }
3416 
3417   /* Look for the partition.  */
3418   while (next_partition (current_drive, 0xFFFFFF, &part, &type,
3419 			 &start, &len, &offset, &entry,
3420 			 &ext_offset, &gpt_offset, &gpt_count, &gpt_size, mbr))
3421     {
3422 	  /* The partition may not be a GPT partition.  */
3423 	  if (gpt_offset != 0)
3424 	    {
3425 		errnum = ERR_BAD_ARGUMENT;
3426 		return 1;
3427 	    }
3428 
3429       if (part == current_partition)
3430 	{
3431 	  /* Found.  */
3432 
3433 	  /* Set the type to NEW_TYPE.  */
3434 	  PC_SLICE_TYPE (mbr, entry) = new_type;
3435 
3436 	  /* Write back the MBR to the disk.  */
3437 	  buf_track = BUF_CACHE_INVALID;
3438 	  if (! rawwrite (current_drive, offset, mbr))
3439 	    return 1;
3440 
3441 	  /* Succeed.  */
3442 	  return 0;
3443 	}
3444     }
3445 
3446   /* The partition was not found.  ERRNUM was set by next_partition.  */
3447   return 1;
3448 }
3449 
3450 static struct builtin builtin_parttype =
3451 {
3452   "parttype",
3453   parttype_func,
3454   BUILTIN_CMDLINE | BUILTIN_MENU | BUILTIN_HELP_LIST,
3455   "parttype PART TYPE",
3456   "Change the type of the partition PART to TYPE."
3457 };
3458 
3459 
3460 /* password */
3461 static int
password_func(char * arg,int flags)3462 password_func (char *arg, int flags)
3463 {
3464   int len;
3465   password_t type = PASSWORD_PLAIN;
3466 
3467 #ifdef USE_MD5_PASSWORDS
3468   if (grub_memcmp (arg, "--md5", 5) == 0)
3469     {
3470       type = PASSWORD_MD5;
3471       arg = skip_to (0, arg);
3472     }
3473 #endif
3474   if (grub_memcmp (arg, "--", 2) == 0)
3475     {
3476       type = PASSWORD_UNSUPPORTED;
3477       arg = skip_to (0, arg);
3478     }
3479 
3480   if ((flags & (BUILTIN_CMDLINE | BUILTIN_SCRIPT)) != 0)
3481     {
3482       /* Do password check! */
3483       char entered[32];
3484 
3485       /* Wipe out any previously entered password */
3486       entered[0] = 0;
3487       get_cmdline ("Password: ", entered, 31, '*', 0);
3488 
3489       nul_terminate (arg);
3490       if (check_password (entered, arg, type) != 0)
3491 	{
3492 	  errnum = ERR_PRIVILEGED;
3493 	  return 1;
3494 	}
3495     }
3496   else
3497     {
3498       len = grub_strlen (arg);
3499 
3500       /* PASSWORD NUL NUL ... */
3501       if (len + 2 > PASSWORD_BUFLEN)
3502 	{
3503 	  errnum = ERR_WONT_FIT;
3504 	  return 1;
3505 	}
3506 
3507       /* Copy the password and clear the rest of the buffer.  */
3508       password = (char *) PASSWORD_BUF;
3509       grub_memmove (password, arg, len);
3510       grub_memset (password + len, 0, PASSWORD_BUFLEN - len);
3511       password_type = type;
3512     }
3513   return 0;
3514 }
3515 
3516 static struct builtin builtin_password =
3517 {
3518   "password",
3519   password_func,
3520   BUILTIN_MENU | BUILTIN_CMDLINE | BUILTIN_NO_ECHO,
3521   "password [--md5] PASSWD [FILE]",
3522   "If used in the first section of a menu file, disable all"
3523   " interactive editing control (menu entry editor and"
3524   " command line). If the password PASSWD is entered, it loads the"
3525   " FILE as a new config file and restarts the GRUB Stage 2. If you"
3526   " omit the argument FILE, then GRUB just unlocks privileged"
3527   " instructions.  You can also use it in the script section, in"
3528   " which case it will ask for the password, before continueing."
3529   " The option --md5 tells GRUB that PASSWD is encrypted with"
3530   " md5crypt."
3531 };
3532 
3533 
3534 /* pause */
3535 static int
pause_func(char * arg,int flags)3536 pause_func (char *arg, int flags)
3537 {
3538   printf("%s\n", arg);
3539 
3540   /* If ESC is returned, then abort this entry.  */
3541   if (ASCII_CHAR (getkey ()) == 27)
3542     return 1;
3543 
3544   return 0;
3545 }
3546 
3547 static struct builtin builtin_pause =
3548 {
3549   "pause",
3550   pause_func,
3551   BUILTIN_CMDLINE | BUILTIN_NO_ECHO,
3552   "pause [MESSAGE ...]",
3553   "Print MESSAGE, then wait until a key is pressed."
3554 };
3555 
3556 
3557 #ifdef GRUB_UTIL
3558 /* quit */
3559 static int
quit_func(char * arg,int flags)3560 quit_func (char *arg, int flags)
3561 {
3562   stop ();
3563 
3564   /* Never reach here.  */
3565   return 0;
3566 }
3567 
3568 static struct builtin builtin_quit =
3569 {
3570   "quit",
3571   quit_func,
3572   BUILTIN_CMDLINE | BUILTIN_HELP_LIST,
3573   "quit",
3574   "Exit from the GRUB shell."
3575 };
3576 #endif /* GRUB_UTIL */
3577 
3578 
3579 #ifdef SUPPORT_NETBOOT
3580 /* rarp */
3581 static int
rarp_func(char * arg,int flags)3582 rarp_func (char *arg, int flags)
3583 {
3584   if (! rarp ())
3585     {
3586       if (errnum == ERR_NONE)
3587 	errnum = ERR_DEV_VALUES;
3588 
3589       return 1;
3590     }
3591 
3592   /* Notify the configuration.  */
3593   print_network_configuration ();
3594   return 0;
3595 }
3596 
3597 static struct builtin builtin_rarp =
3598 {
3599   "rarp",
3600   rarp_func,
3601   BUILTIN_CMDLINE | BUILTIN_MENU | BUILTIN_HELP_LIST,
3602   "rarp",
3603   "Initialize a network device via RARP."
3604 };
3605 #endif /* SUPPORT_NETBOOT */
3606 
3607 
3608 static int
read_func(char * arg,int flags)3609 read_func (char *arg, int flags)
3610 {
3611   int addr;
3612 
3613   if (! safe_parse_maxint (&arg, &addr))
3614     return 1;
3615 
3616   grub_printf ("Address 0x%x: Value 0x%x\n",
3617 	       addr, *((unsigned *) RAW_ADDR (addr)));
3618   return 0;
3619 }
3620 
3621 static struct builtin builtin_read =
3622 {
3623   "read",
3624   read_func,
3625   BUILTIN_CMDLINE,
3626   "read ADDR",
3627   "Read a 32-bit value from memory at address ADDR and"
3628   " display it in hex format."
3629 };
3630 
3631 
3632 /* reboot */
3633 static int
reboot_func(char * arg,int flags)3634 reboot_func (char *arg, int flags)
3635 {
3636   grub_reboot ();
3637 
3638   /* Never reach here.  */
3639   return 1;
3640 }
3641 
3642 static struct builtin builtin_reboot =
3643 {
3644   "reboot",
3645   reboot_func,
3646   BUILTIN_CMDLINE | BUILTIN_HELP_LIST,
3647   "reboot",
3648   "Reboot your system."
3649 };
3650 
3651 
3652 /* Print the root device information.  */
3653 static void
print_root_device(void)3654 print_root_device (void)
3655 {
3656   if (saved_drive == NETWORK_DRIVE)
3657     {
3658       /* Network drive.  */
3659       grub_printf (" (nd):");
3660     }
3661   else if (saved_drive & 0x80)
3662     {
3663       /* Hard disk drive.  */
3664       grub_printf (" (hd%d", saved_drive - 0x80);
3665 
3666       if ((saved_partition & 0xFF0000) != 0xFF0000)
3667 	grub_printf (",%d", saved_partition >> 16);
3668 
3669       if ((saved_partition & 0x00FF00) != 0x00FF00)
3670 	grub_printf (",%c", ((saved_partition >> 8) & 0xFF) + 'a');
3671 
3672       grub_printf ("):");
3673     }
3674   else
3675     {
3676       /* Floppy disk drive.  */
3677       grub_printf (" (fd%d):", saved_drive);
3678     }
3679 
3680   /* Print the filesystem information.  */
3681   current_partition = saved_partition;
3682   current_drive = saved_drive;
3683   print_fsys_type ();
3684 }
3685 
3686 static int
real_root_func(char * arg,int attempt_mount)3687 real_root_func (char *arg, int attempt_mount)
3688 {
3689   int hdbias = 0;
3690   char *biasptr;
3691   char *next;
3692 
3693   /* If ARG is empty, just print the current root device.  */
3694   if (! *arg)
3695     {
3696       print_root_device ();
3697       return 0;
3698     }
3699 
3700   /* Call set_device to get the drive and the partition in ARG.  */
3701   next = set_device (arg);
3702   if (! next)
3703     return 1;
3704 
3705   /* Ignore ERR_FSYS_MOUNT.  */
3706   if (attempt_mount)
3707     {
3708       if (! open_device () && errnum != ERR_FSYS_MOUNT)
3709 	return 1;
3710     }
3711   else
3712     {
3713       /* This is necessary, because the location of a partition table
3714 	 must be set appropriately.  */
3715       if (open_partition ())
3716 	{
3717 	  set_bootdev (0);
3718 	  if (errnum)
3719 	    return 1;
3720 	}
3721     }
3722 
3723   /* Clear ERRNUM.  */
3724   errnum = 0;
3725   saved_partition = current_partition;
3726   saved_drive = current_drive;
3727 
3728   if (attempt_mount)
3729     {
3730       /* BSD and chainloading evil hacks !!  */
3731       biasptr = skip_to (0, next);
3732       safe_parse_maxint (&biasptr, &hdbias);
3733       errnum = 0;
3734       bootdev = set_bootdev (hdbias);
3735       if (errnum)
3736 	return 1;
3737 
3738       /* Print the type of the filesystem.  */
3739       print_fsys_type ();
3740     }
3741 
3742   return 0;
3743 }
3744 
3745 static int
root_func(char * arg,int flags)3746 root_func (char *arg, int flags)
3747 {
3748   is_zfs_mount = 0;
3749   return real_root_func (arg, 1);
3750 }
3751 
3752 static struct builtin builtin_root =
3753 {
3754   "root",
3755   root_func,
3756   BUILTIN_CMDLINE | BUILTIN_HELP_LIST,
3757   "root [DEVICE [HDBIAS]]",
3758   "Set the current \"root device\" to the device DEVICE, then"
3759   " attempt to mount it to get the partition size (for passing the"
3760   " partition descriptor in `ES:ESI', used by some chain-loaded"
3761   " bootloaders), the BSD drive-type (for booting BSD kernels using"
3762   " their native boot format), and correctly determine "
3763   " the PC partition where a BSD sub-partition is located. The"
3764   " optional HDBIAS parameter is a number to tell a BSD kernel"
3765   " how many BIOS drive numbers are on controllers before the current"
3766   " one. For example, if there is an IDE disk and a SCSI disk, and your"
3767   " FreeBSD root partition is on the SCSI disk, then use a `1' for HDBIAS."
3768 };
3769 
3770 
3771 /* findroot */
3772 int
findroot_func(char * arg,int flags)3773 findroot_func (char *arg, int flags)
3774 {
3775   int ret;
3776   char root[32];
3777 
3778   if (grub_strlen(arg) >= BOOTSIGN_ARGLEN) {
3779   	errnum = ERR_BAD_ARGUMENT;
3780 	return 1;
3781   }
3782 
3783   if (arg[0] == '\0') {
3784   	errnum = ERR_BAD_ARGUMENT;
3785 	return 1;
3786   }
3787 
3788   find_best_root = 1;
3789   best_drive = 0;
3790   best_part = 0;
3791   ret = find_common(arg, root, 1, flags);
3792   if (ret != 0)
3793 	return (ret);
3794   find_best_root = 0;
3795 
3796   return real_root_func (root, 1);
3797 }
3798 
3799 static struct builtin builtin_findroot =
3800 {
3801   "findroot",
3802   findroot_func,
3803   BUILTIN_CMDLINE | BUILTIN_HELP_LIST,
3804   "findroot  <SIGNATURE | (SIGNATURE,partition[,slice])>",
3805   "Searches across all partitions for the file name SIGNATURE."
3806   " GRUB looks only in the directory /boot/grub/bootsign for the"
3807   " filename and it stops as soon as it finds the first instance of"
3808   " the file - so to be useful the name of the signature file must be"
3809   " unique across all partitions. Once the signature file is found,"
3810   " GRUB invokes the \"root\" command on that partition."
3811   " An optional partition and slice may be specified to optimize the search."
3812 };
3813 
3814 
3815 /*
3816  * COMMAND to override the default root filesystem for ZFS
3817  *	bootfs pool/fs
3818  */
3819 static int
bootfs_func(char * arg,int flags)3820 bootfs_func (char *arg, int flags)
3821 {
3822 	int hdbias = 0;
3823 	char *biasptr;
3824 	char *next;
3825 
3826 	if (! *arg) {
3827 	    if (current_bootfs[0] != '\0')
3828 		grub_printf ("The zfs boot filesystem is set to '%s'.\n",
3829 				current_bootfs);
3830 	    else if (current_rootpool[0] != 0 && current_bootfs_obj != 0)
3831 		grub_printf("The zfs boot filesystem is <default: %s/%u>.",
3832 				current_rootpool, current_bootfs_obj);
3833 	    else
3834 		grub_printf ("The zfs boot filesystem will be derived from "
3835 			"the default bootfs pool property.\n");
3836 
3837 	    return (1);
3838 	}
3839 
3840 	/* Verify the zfs filesystem name */
3841 	if (arg[0] == '/' || arg[0] == '\0') {
3842 		errnum = ERR_BAD_ARGUMENT;
3843 		return 0;
3844 	}
3845 	if (current_rootpool[0] != 0 && grub_strncmp(arg,
3846 	    current_rootpool, strlen(current_rootpool))) {
3847 		errnum = ERR_BAD_ARGUMENT;
3848 		return 0;
3849 	}
3850 
3851 	grub_memmove(current_bootfs, arg, MAXNAMELEN);
3852 
3853 	return (1);
3854 }
3855 
3856 static struct builtin builtin_bootfs =
3857 {
3858   "bootfs",
3859   bootfs_func,
3860   BUILTIN_CMDLINE | BUILTIN_HELP_LIST,
3861   "bootfs [ZFSBOOTFS]",
3862   "Set the current zfs boot filesystem to ZFSBOOTFS (rootpool/rootfs)."
3863 };
3864 
3865 
3866 /* rootnoverify */
3867 static int
rootnoverify_func(char * arg,int flags)3868 rootnoverify_func (char *arg, int flags)
3869 {
3870   return real_root_func (arg, 0);
3871 }
3872 
3873 static struct builtin builtin_rootnoverify =
3874 {
3875   "rootnoverify",
3876   rootnoverify_func,
3877   BUILTIN_CMDLINE | BUILTIN_HELP_LIST,
3878   "rootnoverify [DEVICE [HDBIAS]]",
3879   "Similar to `root', but don't attempt to mount the partition. This"
3880   " is useful for when an OS is outside of the area of the disk that"
3881   " GRUB can read, but setting the correct root device is still"
3882   " desired. Note that the items mentioned in `root' which"
3883   " derived from attempting the mount will NOT work correctly."
3884 };
3885 
3886 
3887 /* savedefault */
3888 static int
savedefault_func(char * arg,int flags)3889 savedefault_func (char *arg, int flags)
3890 {
3891 #if !defined(SUPPORT_DISKLESS) && !defined(GRUB_UTIL)
3892   unsigned long tmp_drive = saved_drive;
3893   unsigned long tmp_partition = saved_partition;
3894   char *default_file = (char *) DEFAULT_FILE_BUF;
3895   char buf[10];
3896   char sect[SECTOR_SIZE];
3897   int entryno;
3898   int sector_count = 0;
3899   unsigned int saved_sectors[2];
3900   int saved_offsets[2];
3901   int saved_lengths[2];
3902 
3903   /* not supported for zfs root */
3904   if (is_zfs_mount == 1) {
3905 	return (0); /* no-op */
3906   }
3907 
3908   /* Save sector information about at most two sectors.  */
3909   auto void disk_read_savesect_func (unsigned int sector, int offset,
3910       int length);
3911   void disk_read_savesect_func (unsigned int sector, int offset, int length)
3912     {
3913       if (sector_count < 2)
3914 	{
3915 	  saved_sectors[sector_count] = sector;
3916 	  saved_offsets[sector_count] = offset;
3917 	  saved_lengths[sector_count] = length;
3918 	}
3919       sector_count++;
3920     }
3921 
3922   /* This command is only useful when you boot an entry from the menu
3923      interface.  */
3924   if (! (flags & BUILTIN_SCRIPT))
3925     {
3926       errnum = ERR_UNRECOGNIZED;
3927       return 1;
3928     }
3929 
3930   /* Determine a saved entry number.  */
3931   if (*arg)
3932     {
3933       if (grub_memcmp (arg, "fallback", sizeof ("fallback") - 1) == 0)
3934 	{
3935 	  int i;
3936 	  int index = 0;
3937 
3938 	  for (i = 0; i < MAX_FALLBACK_ENTRIES; i++)
3939 	    {
3940 	      if (fallback_entries[i] < 0)
3941 		break;
3942 	      if (fallback_entries[i] == current_entryno)
3943 		{
3944 		  index = i + 1;
3945 		  break;
3946 		}
3947 	    }
3948 
3949 	  if (index >= MAX_FALLBACK_ENTRIES || fallback_entries[index] < 0)
3950 	    {
3951 	      /* This is the last.  */
3952 	      errnum = ERR_BAD_ARGUMENT;
3953 	      return 1;
3954 	    }
3955 
3956 	  entryno = fallback_entries[index];
3957 	}
3958       else if (! safe_parse_maxint (&arg, &entryno))
3959 	return 1;
3960     }
3961   else
3962     entryno = current_entryno;
3963 
3964   /* Open the default file.  */
3965   saved_drive = boot_drive;
3966   saved_partition = install_partition;
3967   if (grub_open (default_file))
3968     {
3969       int len;
3970 
3971       disk_read_hook = disk_read_savesect_func;
3972       len = grub_read (buf, sizeof (buf));
3973       disk_read_hook = 0;
3974       grub_close ();
3975 
3976       if (len != sizeof (buf))
3977 	{
3978 	  /* This is too small. Do not modify the file manually, please!  */
3979 	  errnum = ERR_READ;
3980 	  goto fail;
3981 	}
3982 
3983       if (sector_count > 2)
3984 	{
3985 	  /* Is this possible?! Too fragmented!  */
3986 	  errnum = ERR_FSYS_CORRUPT;
3987 	  goto fail;
3988 	}
3989 
3990       /* Set up a string to be written.  */
3991       grub_memset (buf, '\n', sizeof (buf));
3992       grub_sprintf (buf, "%d", entryno);
3993 
3994       if (saved_lengths[0] < sizeof (buf))
3995 	{
3996 	  /* The file is anchored to another file and the first few bytes
3997 	     are spanned in two sectors. Uggh...  */
3998 	  if (! rawread (current_drive, saved_sectors[0], 0, SECTOR_SIZE,
3999 			 sect))
4000 	    goto fail;
4001 	  grub_memmove (sect + saved_offsets[0], buf, saved_lengths[0]);
4002 	  if (! rawwrite (current_drive, saved_sectors[0], sect))
4003 	    goto fail;
4004 
4005 	  if (! rawread (current_drive, saved_sectors[1], 0, SECTOR_SIZE,
4006 			 sect))
4007 	    goto fail;
4008 	  grub_memmove (sect + saved_offsets[1],
4009 			buf + saved_lengths[0],
4010 			sizeof (buf) - saved_lengths[0]);
4011 	  if (! rawwrite (current_drive, saved_sectors[1], sect))
4012 	    goto fail;
4013 	}
4014       else
4015 	{
4016 	  /* This is a simple case. It fits into a single sector.  */
4017 	  if (! rawread (current_drive, saved_sectors[0], 0, SECTOR_SIZE,
4018 			 sect))
4019 	    goto fail;
4020 	  grub_memmove (sect + saved_offsets[0], buf, sizeof (buf));
4021 	  if (! rawwrite (current_drive, saved_sectors[0], sect))
4022 	    goto fail;
4023 	}
4024 
4025       /* Clear the cache.  */
4026       buf_track = BUF_CACHE_INVALID;
4027     }
4028 
4029  fail:
4030   saved_drive = tmp_drive;
4031   saved_partition = tmp_partition;
4032   return errnum;
4033 #else /* ! SUPPORT_DISKLESS && ! GRUB_UTIL */
4034   errnum = ERR_UNRECOGNIZED;
4035   return 1;
4036 #endif /* ! SUPPORT_DISKLESS && ! GRUB_UTIL */
4037 }
4038 
4039 static struct builtin builtin_savedefault =
4040 {
4041   "savedefault",
4042   savedefault_func,
4043   BUILTIN_CMDLINE,
4044   "savedefault [NUM | `fallback']",
4045   "Save the current entry as the default boot entry if no argument is"
4046   " specified. If a number is specified, this number is saved. If"
4047   " `fallback' is used, next fallback entry is saved."
4048 };
4049 
4050 
4051 #ifdef SUPPORT_SERIAL
4052 /* serial */
4053 static int
serial_func(char * arg,int flags)4054 serial_func (char *arg, int flags)
4055 {
4056   unsigned short port = serial_hw_get_port (0);
4057   unsigned int speed = 9600;
4058   int word_len = UART_8BITS_WORD;
4059   int parity = UART_NO_PARITY;
4060   int stop_bit_len = UART_1_STOP_BIT;
4061 
4062   /* Process GNU-style long options.
4063      FIXME: We should implement a getopt-like function, to avoid
4064      duplications.  */
4065   while (1)
4066     {
4067       if (grub_memcmp (arg, "--unit=", sizeof ("--unit=") - 1) == 0)
4068 	{
4069 	  char *p = arg + sizeof ("--unit=") - 1;
4070 	  int unit;
4071 
4072 	  if (! safe_parse_maxint (&p, &unit))
4073 	    return 1;
4074 
4075 	  if (unit < 0 || unit > 3)
4076 	    {
4077 	      errnum = ERR_DEV_VALUES;
4078 	      return 1;
4079 	    }
4080 
4081 	  port = serial_hw_get_port (unit);
4082 	}
4083       else if (grub_memcmp (arg, "--speed=", sizeof ("--speed=") - 1) == 0)
4084 	{
4085 	  char *p = arg + sizeof ("--speed=") - 1;
4086 	  int num;
4087 
4088 	  if (! safe_parse_maxint (&p, &num))
4089 	    return 1;
4090 
4091 	  speed = (unsigned int) num;
4092 	}
4093       else if (grub_memcmp (arg, "--port=", sizeof ("--port=") - 1) == 0)
4094 	{
4095 	  char *p = arg + sizeof ("--port=") - 1;
4096 	  int num;
4097 
4098 	  if (! safe_parse_maxint (&p, &num))
4099 	    return 1;
4100 
4101 	  port = (unsigned short) num;
4102 	}
4103       else if (grub_memcmp (arg, "--word=", sizeof ("--word=") - 1) == 0)
4104 	{
4105 	  char *p = arg + sizeof ("--word=") - 1;
4106 	  int len;
4107 
4108 	  if (! safe_parse_maxint (&p, &len))
4109 	    return 1;
4110 
4111 	  switch (len)
4112 	    {
4113 	    case 5: word_len = UART_5BITS_WORD; break;
4114 	    case 6: word_len = UART_6BITS_WORD; break;
4115 	    case 7: word_len = UART_7BITS_WORD; break;
4116 	    case 8: word_len = UART_8BITS_WORD; break;
4117 	    default:
4118 	      errnum = ERR_BAD_ARGUMENT;
4119 	      return 1;
4120 	    }
4121 	}
4122       else if (grub_memcmp (arg, "--stop=", sizeof ("--stop=") - 1) == 0)
4123 	{
4124 	  char *p = arg + sizeof ("--stop=") - 1;
4125 	  int len;
4126 
4127 	  if (! safe_parse_maxint (&p, &len))
4128 	    return 1;
4129 
4130 	  switch (len)
4131 	    {
4132 	    case 1: stop_bit_len = UART_1_STOP_BIT; break;
4133 	    case 2: stop_bit_len = UART_2_STOP_BITS; break;
4134 	    default:
4135 	      errnum = ERR_BAD_ARGUMENT;
4136 	      return 1;
4137 	    }
4138 	}
4139       else if (grub_memcmp (arg, "--parity=", sizeof ("--parity=") - 1) == 0)
4140 	{
4141 	  char *p = arg + sizeof ("--parity=") - 1;
4142 
4143 	  if (grub_memcmp (p, "no", sizeof ("no") - 1) == 0)
4144 	    parity = UART_NO_PARITY;
4145 	  else if (grub_memcmp (p, "odd", sizeof ("odd") - 1) == 0)
4146 	    parity = UART_ODD_PARITY;
4147 	  else if (grub_memcmp (p, "even", sizeof ("even") - 1) == 0)
4148 	    parity = UART_EVEN_PARITY;
4149 	  else
4150 	    {
4151 	      errnum = ERR_BAD_ARGUMENT;
4152 	      return 1;
4153 	    }
4154 	}
4155 # ifdef GRUB_UTIL
4156       /* In the grub shell, don't use any port number but open a tty
4157 	 device instead.  */
4158       else if (grub_memcmp (arg, "--device=", sizeof ("--device=") - 1) == 0)
4159 	{
4160 	  char *p = arg + sizeof ("--device=") - 1;
4161 	  char dev[256];	/* XXX */
4162 	  char *q = dev;
4163 
4164 	  while (*p && ! grub_isspace (*p))
4165 	    *q++ = *p++;
4166 
4167 	  *q = 0;
4168 	  serial_set_device (dev);
4169 	}
4170 # endif /* GRUB_UTIL */
4171       else
4172 	break;
4173 
4174       arg = skip_to (0, arg);
4175     }
4176 
4177   /* Initialize the serial unit.  */
4178   if (! serial_hw_init (port, speed, word_len, parity, stop_bit_len))
4179     {
4180       errnum = ERR_BAD_ARGUMENT;
4181       return 1;
4182     }
4183 
4184   return 0;
4185 }
4186 
4187 static struct builtin builtin_serial =
4188 {
4189   "serial",
4190   serial_func,
4191   BUILTIN_MENU | BUILTIN_CMDLINE | BUILTIN_HELP_LIST,
4192   "serial [--unit=UNIT] [--port=PORT] [--speed=SPEED] [--word=WORD] [--parity=PARITY] [--stop=STOP] [--device=DEV]",
4193   "Initialize a serial device. UNIT is a digit that specifies which serial"
4194   " device is used (e.g. 0 == COM1). If you need to specify the port number,"
4195   " set it by --port. SPEED is the DTE-DTE speed. WORD is the word length,"
4196   " PARITY is the type of parity, which is one of `no', `odd' and `even'."
4197   " STOP is the length of stop bit(s). The option --device can be used only"
4198   " in the grub shell, which specifies the file name of a tty device. The"
4199   " default values are COM1, 9600, 8N1."
4200 };
4201 #endif /* SUPPORT_SERIAL */
4202 
4203 
4204 /* setkey */
4205 struct keysym
4206 {
4207   char *unshifted_name;			/* the name in unshifted state */
4208   char *shifted_name;			/* the name in shifted state */
4209   unsigned char unshifted_ascii;	/* the ascii code in unshifted state */
4210   unsigned char shifted_ascii;		/* the ascii code in shifted state */
4211   unsigned char keycode;		/* keyboard scancode */
4212 };
4213 
4214 /* The table for key symbols. If the "shifted" member of an entry is
4215    NULL, the entry does not have shifted state.  */
4216 static struct keysym keysym_table[] =
4217 {
4218   {"escape",		0,		0x1b,	0,	0x01},
4219   {"1",			"exclam",	'1',	'!',	0x02},
4220   {"2",			"at",		'2',	'@',	0x03},
4221   {"3",			"numbersign",	'3',	'#',	0x04},
4222   {"4",			"dollar",	'4',	'$',	0x05},
4223   {"5",			"percent",	'5',	'%',	0x06},
4224   {"6",			"caret",	'6',	'^',	0x07},
4225   {"7",			"ampersand",	'7',	'&',	0x08},
4226   {"8",			"asterisk",	'8',	'*',	0x09},
4227   {"9",			"parenleft",	'9',	'(',	0x0a},
4228   {"0",			"parenright",	'0',	')',	0x0b},
4229   {"minus",		"underscore",	'-',	'_',	0x0c},
4230   {"equal",		"plus",		'=',	'+',	0x0d},
4231   {"backspace",		0,		'\b',	0,	0x0e},
4232   {"tab",		0,		'\t',	0,	0x0f},
4233   {"q",			"Q",		'q',	'Q',	0x10},
4234   {"w",			"W",		'w',	'W',	0x11},
4235   {"e",			"E",		'e',	'E',	0x12},
4236   {"r",			"R",		'r',	'R',	0x13},
4237   {"t",			"T",		't',	'T',	0x14},
4238   {"y",			"Y",		'y',	'Y',	0x15},
4239   {"u",			"U",		'u',	'U',	0x16},
4240   {"i",			"I",		'i',	'I',	0x17},
4241   {"o",			"O",		'o',	'O',	0x18},
4242   {"p",			"P",		'p',	'P',	0x19},
4243   {"bracketleft",	"braceleft",	'[',	'{',	0x1a},
4244   {"bracketright",	"braceright",	']',	'}',	0x1b},
4245   {"enter",		0,		'\n',	0,	0x1c},
4246   {"control",		0,		0,	0,	0x1d},
4247   {"a",			"A",		'a',	'A',	0x1e},
4248   {"s",			"S",		's',	'S',	0x1f},
4249   {"d",			"D",		'd',	'D',	0x20},
4250   {"f",			"F",		'f',	'F',	0x21},
4251   {"g",			"G",		'g',	'G',	0x22},
4252   {"h",			"H",		'h',	'H',	0x23},
4253   {"j",			"J",		'j',	'J',	0x24},
4254   {"k",			"K",		'k',	'K',	0x25},
4255   {"l",			"L",		'l',	'L',	0x26},
4256   {"semicolon",		"colon",	';',	':',	0x27},
4257   {"quote",		"doublequote",	'\'',	'"',	0x28},
4258   {"backquote",		"tilde",	'`',	'~',	0x29},
4259   {"shift",		0,		0,	0,	0x2a},
4260   {"backslash",		"bar",		'\\',	'|',	0x2b},
4261   {"z",			"Z",		'z',	'Z',	0x2c},
4262   {"x",			"X",		'x',	'X',	0x2d},
4263   {"c",			"C",		'c',	'C',	0x2e},
4264   {"v",			"V",		'v',	'V',	0x2f},
4265   {"b",			"B",		'b',	'B',	0x30},
4266   {"n",			"N",		'n',	'N',	0x31},
4267   {"m",			"M",		'm',	'M',	0x32},
4268   {"comma",		"less",		',',	'<',	0x33},
4269   {"period",		"greater",	'.',	'>',	0x34},
4270   {"slash",		"question",	'/',	'?',	0x35},
4271   {"alt",		0,		0,	0,	0x38},
4272   {"space",		0,		' ',	0,	0x39},
4273   {"capslock",		0,		0,	0,	0x3a},
4274   {"F1",		0,		0,	0,	0x3b},
4275   {"F2",		0,		0,	0,	0x3c},
4276   {"F3",		0,		0,	0,	0x3d},
4277   {"F4",		0,		0,	0,	0x3e},
4278   {"F5",		0,		0,	0,	0x3f},
4279   {"F6",		0,		0,	0,	0x40},
4280   {"F7",		0,		0,	0,	0x41},
4281   {"F8",		0,		0,	0,	0x42},
4282   {"F9",		0,		0,	0,	0x43},
4283   {"F10",		0,		0,	0,	0x44},
4284   /* Caution: do not add NumLock here! we cannot deal with it properly.  */
4285   {"delete",		0,		0x7f,	0,	0x53}
4286 };
4287 
4288 static int
setkey_func(char * arg,int flags)4289 setkey_func (char *arg, int flags)
4290 {
4291   char *to_key, *from_key;
4292   int to_code, from_code;
4293   int map_in_interrupt = 0;
4294 
4295   auto int find_key_code (char *key);
4296   auto int find_ascii_code (char *key);
4297 
4298   auto int find_key_code (char *key)
4299     {
4300       int i;
4301 
4302       for (i = 0; i < sizeof (keysym_table) / sizeof (keysym_table[0]); i++)
4303 	{
4304 	  if (keysym_table[i].unshifted_name &&
4305 	      grub_strcmp (key, keysym_table[i].unshifted_name) == 0)
4306 	    return keysym_table[i].keycode;
4307 	  else if (keysym_table[i].shifted_name &&
4308 		   grub_strcmp (key, keysym_table[i].shifted_name) == 0)
4309 	    return keysym_table[i].keycode;
4310 	}
4311 
4312       return 0;
4313     }
4314 
4315   auto int find_ascii_code (char *key)
4316     {
4317       int i;
4318 
4319       for (i = 0; i < sizeof (keysym_table) / sizeof (keysym_table[0]); i++)
4320 	{
4321 	  if (keysym_table[i].unshifted_name &&
4322 	      grub_strcmp (key, keysym_table[i].unshifted_name) == 0)
4323 	    return keysym_table[i].unshifted_ascii;
4324 	  else if (keysym_table[i].shifted_name &&
4325 		   grub_strcmp (key, keysym_table[i].shifted_name) == 0)
4326 	    return keysym_table[i].shifted_ascii;
4327 	}
4328 
4329       return 0;
4330     }
4331 
4332   to_key = arg;
4333   from_key = skip_to (0, to_key);
4334 
4335   if (! *to_key)
4336     {
4337       /* If the user specifies no argument, reset the key mappings.  */
4338       grub_memset (bios_key_map, 0, KEY_MAP_SIZE * sizeof (unsigned short));
4339       grub_memset (ascii_key_map, 0, KEY_MAP_SIZE * sizeof (unsigned short));
4340 
4341       return 0;
4342     }
4343   else if (! *from_key)
4344     {
4345       /* The user must specify two arguments or zero argument.  */
4346       errnum = ERR_BAD_ARGUMENT;
4347       return 1;
4348     }
4349 
4350   nul_terminate (to_key);
4351   nul_terminate (from_key);
4352 
4353   to_code = find_ascii_code (to_key);
4354   from_code = find_ascii_code (from_key);
4355   if (! to_code || ! from_code)
4356     {
4357       map_in_interrupt = 1;
4358       to_code = find_key_code (to_key);
4359       from_code = find_key_code (from_key);
4360       if (! to_code || ! from_code)
4361 	{
4362 	  errnum = ERR_BAD_ARGUMENT;
4363 	  return 1;
4364 	}
4365     }
4366 
4367   if (map_in_interrupt)
4368     {
4369       int i;
4370 
4371       /* Find an empty slot.  */
4372       for (i = 0; i < KEY_MAP_SIZE; i++)
4373 	{
4374 	  if ((bios_key_map[i] & 0xff) == from_code)
4375 	    /* Perhaps the user wants to overwrite the map.  */
4376 	    break;
4377 
4378 	  if (! bios_key_map[i])
4379 	    break;
4380 	}
4381 
4382       if (i == KEY_MAP_SIZE)
4383 	{
4384 	  errnum = ERR_WONT_FIT;
4385 	  return 1;
4386 	}
4387 
4388       if (to_code == from_code)
4389 	/* If TO is equal to FROM, delete the entry.  */
4390 	grub_memmove ((char *) &bios_key_map[i],
4391 		      (char *) &bios_key_map[i + 1],
4392 		      sizeof (unsigned short) * (KEY_MAP_SIZE - i));
4393       else
4394 	bios_key_map[i] = (to_code << 8) | from_code;
4395 
4396       /* Ugly but should work.  */
4397       unset_int15_handler ();
4398       set_int15_handler ();
4399     }
4400   else
4401     {
4402       int i;
4403 
4404       /* Find an empty slot.  */
4405       for (i = 0; i < KEY_MAP_SIZE; i++)
4406 	{
4407 	  if ((ascii_key_map[i] & 0xff) == from_code)
4408 	    /* Perhaps the user wants to overwrite the map.  */
4409 	    break;
4410 
4411 	  if (! ascii_key_map[i])
4412 	    break;
4413 	}
4414 
4415       if (i == KEY_MAP_SIZE)
4416 	{
4417 	  errnum = ERR_WONT_FIT;
4418 	  return 1;
4419 	}
4420 
4421       if (to_code == from_code)
4422 	/* If TO is equal to FROM, delete the entry.  */
4423 	grub_memmove ((char *) &ascii_key_map[i],
4424 		      (char *) &ascii_key_map[i + 1],
4425 		      sizeof (unsigned short) * (KEY_MAP_SIZE - i));
4426       else
4427 	ascii_key_map[i] = (to_code << 8) | from_code;
4428     }
4429 
4430   return 0;
4431 }
4432 
4433 static struct builtin builtin_setkey =
4434 {
4435   "setkey",
4436   setkey_func,
4437   BUILTIN_CMDLINE | BUILTIN_MENU | BUILTIN_HELP_LIST,
4438   "setkey [TO_KEY FROM_KEY]",
4439   "Change the keyboard map. The key FROM_KEY is mapped to the key TO_KEY."
4440   " A key must be an alphabet, a digit, or one of these: escape, exclam,"
4441   " at, numbersign, dollar, percent, caret, ampersand, asterisk, parenleft,"
4442   " parenright, minus, underscore, equal, plus, backspace, tab, bracketleft,"
4443   " braceleft, bracketright, braceright, enter, control, semicolon, colon,"
4444   " quote, doublequote, backquote, tilde, shift, backslash, bar, comma,"
4445   " less, period, greater, slash, question, alt, space, capslock, FX (X"
4446   " is a digit), and delete. If no argument is specified, reset key"
4447   " mappings."
4448 };
4449 
4450 
4451 /* setup */
4452 static int
setup_func(char * arg,int flags)4453 setup_func (char *arg, int flags)
4454 {
4455   /* Point to the string of the installed drive/partition.  */
4456   char *install_ptr;
4457   /* Point to the string of the drive/parition where the GRUB images
4458      reside.  */
4459   char *image_ptr;
4460   unsigned long installed_drive, installed_partition;
4461   unsigned long image_drive, image_partition;
4462   unsigned long tmp_drive, tmp_partition;
4463   char stage1[64];
4464   char stage2[64];
4465   char config_filename[64];
4466   char real_config_filename[64];
4467   char cmd_arg[256];
4468   char device[16];
4469   char *buffer = (char *) RAW_ADDR (0x100000);
4470   int is_force_lba = 0;
4471   char *stage2_arg = 0;
4472   char *prefix = 0;
4473 
4474   auto int check_file (char *file);
4475   auto void sprint_device (int drive, int partition);
4476   auto int embed_stage1_5 (char * stage1_5, int drive, int partition);
4477 
4478   /* Check if the file FILE exists like Autoconf.  */
4479   int check_file (char *file)
4480     {
4481       int ret;
4482 
4483       grub_printf (" Checking if \"%s\" exists... ", file);
4484       ret = grub_open (file);
4485       if (ret)
4486 	{
4487 	  grub_close ();
4488 	  grub_printf ("yes\n");
4489 	}
4490       else
4491 	grub_printf ("no\n");
4492 
4493       return ret;
4494     }
4495 
4496   /* Construct a device name in DEVICE.  */
4497   void sprint_device (int drive, int partition)
4498     {
4499       grub_sprintf (device, "(%cd%d",
4500 		    (drive & 0x80) ? 'h' : 'f',
4501 		    drive & ~0x80);
4502       if ((partition & 0xFF0000) != 0xFF0000)
4503 	{
4504 	  char tmp[16];
4505 	  grub_sprintf (tmp, ",%d", (partition >> 16) & 0xFF);
4506 	  grub_strncat (device, tmp, sizeof (device));
4507 	}
4508       if ((partition & 0x00FF00) != 0x00FF00)
4509 	{
4510 	  char tmp[16];
4511 	  grub_sprintf (tmp, ",%c", 'a' + ((partition >> 8) & 0xFF));
4512 	  grub_strncat (device, tmp, sizeof (device));
4513 	}
4514       grub_strncat (device, ")", sizeof (device));
4515     }
4516 
4517   int embed_stage1_5 (char *stage1_5, int drive, int partition)
4518     {
4519       /* We install GRUB into the MBR, so try to embed the
4520 	 Stage 1.5 in the sectors right after the MBR.  */
4521       sprint_device (drive, partition);
4522       grub_sprintf (cmd_arg, "%s %s", stage1_5, device);
4523 
4524       /* Notify what will be run.  */
4525       grub_printf (" Running \"embed %s\"... ", cmd_arg);
4526 
4527       embed_func (cmd_arg, flags);
4528       if (! errnum)
4529 	{
4530 	  /* Construct the blocklist representation.  */
4531 	  grub_sprintf (buffer, "%s%s", device, embed_info);
4532 	  grub_printf ("succeeded\n");
4533 	  return 1;
4534 	}
4535       else
4536 	{
4537 	  grub_printf ("failed (this is not fatal)\n");
4538 	  return 0;
4539 	}
4540     }
4541 
4542   struct stage1_5_map {
4543     char *fsys;
4544     char *name;
4545   };
4546   struct stage1_5_map stage1_5_map[] =
4547   {
4548     {"ext2fs",   "/e2fs_stage1_5"},
4549     {"fat",      "/fat_stage1_5"},
4550     {"ufs2",     "/ufs2_stage1_5"},
4551     {"ffs",      "/ffs_stage1_5"},
4552     {"iso9660",  "/iso9660_stage1_5"},
4553     {"jfs",      "/jfs_stage1_5"},
4554     {"minix",    "/minix_stage1_5"},
4555     {"reiserfs", "/reiserfs_stage1_5"},
4556     {"vstafs",   "/vstafs_stage1_5"},
4557     {"xfs",      "/xfs_stage1_5"},
4558     {"ufs",      "/ufs_stage1_5"}
4559   };
4560 
4561   tmp_drive = saved_drive;
4562   tmp_partition = saved_partition;
4563 
4564   /* Check if the user specifies --force-lba.  */
4565   while (1)
4566     {
4567       if (grub_memcmp ("--force-lba", arg, sizeof ("--force-lba") - 1) == 0)
4568 	{
4569 	  is_force_lba = 1;
4570 	  arg = skip_to (0, arg);
4571 	}
4572       else if (grub_memcmp ("--prefix=", arg, sizeof ("--prefix=") - 1) == 0)
4573 	{
4574 	  prefix = arg + sizeof ("--prefix=") - 1;
4575 	  arg = skip_to (0, arg);
4576 	  nul_terminate (prefix);
4577 	}
4578 #ifdef GRUB_UTIL
4579       else if (grub_memcmp ("--stage2=", arg, sizeof ("--stage2=") - 1) == 0)
4580 	{
4581 	  stage2_arg = arg;
4582 	  arg = skip_to (0, arg);
4583 	  nul_terminate (stage2_arg);
4584 	}
4585 #endif /* GRUB_UTIL */
4586       else
4587 	break;
4588     }
4589 
4590   install_ptr = arg;
4591   image_ptr = skip_to (0, install_ptr);
4592 
4593   /* Make sure that INSTALL_PTR is valid.  */
4594   set_device (install_ptr);
4595   if (errnum)
4596     return 1;
4597 
4598   installed_drive = current_drive;
4599   installed_partition = current_partition;
4600 
4601   /* Mount the drive pointed by IMAGE_PTR.  */
4602   if (*image_ptr)
4603     {
4604       /* If the drive/partition where the images reside is specified,
4605 	 get the drive and the partition.  */
4606       set_device (image_ptr);
4607       if (errnum)
4608 	return 1;
4609     }
4610   else
4611     {
4612       /* If omitted, use SAVED_PARTITION and SAVED_DRIVE.  */
4613       current_drive = saved_drive;
4614       current_partition = saved_partition;
4615     }
4616 
4617   image_drive = saved_drive = current_drive;
4618   image_partition = saved_partition = current_partition;
4619 
4620   /* Open it.  */
4621   if (! open_device ())
4622     goto fail;
4623 
4624   /* Check if stage1 exists. If the user doesn't specify the option
4625      `--prefix', attempt /boot/grub and /grub.  */
4626   /* NOTE: It is dangerous to run this command without `--prefix' in the
4627      grub shell, since that affects `--stage2'.  */
4628   if (! prefix)
4629     {
4630       prefix = "/boot/grub";
4631       grub_sprintf (stage1, "%s%s", prefix, "/stage1");
4632       if (! check_file (stage1))
4633 	{
4634 	  errnum = ERR_NONE;
4635 	  prefix = "/grub";
4636 	  grub_sprintf (stage1, "%s%s", prefix, "/stage1");
4637 	  if (! check_file (stage1))
4638 	    goto fail;
4639 	}
4640     }
4641   else
4642     {
4643       grub_sprintf (stage1, "%s%s", prefix, "/stage1");
4644       if (! check_file (stage1))
4645 	goto fail;
4646     }
4647 
4648   /* The prefix was determined.  */
4649   grub_sprintf (stage2, "%s%s", prefix, "/stage2");
4650   grub_sprintf (config_filename, "%s%s", prefix, "/menu.lst");
4651   *real_config_filename = 0;
4652 
4653   /* Check if stage2 exists.  */
4654   if (! check_file (stage2))
4655     goto fail;
4656 
4657   {
4658     char *fsys = fsys_table[fsys_type].name;
4659     int i;
4660     int size = sizeof (stage1_5_map) / sizeof (stage1_5_map[0]);
4661 
4662     /* Iterate finding the same filesystem name as FSYS.  */
4663     for (i = 0; i < size; i++)
4664       if (grub_strcmp (fsys, stage1_5_map[i].fsys) == 0)
4665 	{
4666 	  /* OK, check if the Stage 1.5 exists.  */
4667 	  char stage1_5[64];
4668 
4669 	  grub_sprintf (stage1_5, "%s%s", prefix, stage1_5_map[i].name);
4670 	  if (check_file (stage1_5))
4671 	    {
4672 	      if (embed_stage1_5 (stage1_5,
4673 				    installed_drive, installed_partition)
4674 		  || embed_stage1_5 (stage1_5,
4675 				     image_drive, image_partition))
4676 		{
4677 		  grub_strcpy (real_config_filename, config_filename);
4678 		  sprint_device (image_drive, image_partition);
4679 		  grub_sprintf (config_filename, "%s%s", device, stage2);
4680 		  grub_strcpy (stage2, buffer);
4681 		}
4682 	    }
4683 	  errnum = 0;
4684 	  break;
4685 	}
4686   }
4687 
4688   /* Construct a string that is used by the command "install" as its
4689      arguments.  */
4690   sprint_device (installed_drive, installed_partition);
4691 
4692 #if 1
4693   /* Don't embed a drive number unnecessarily.  */
4694   grub_sprintf (cmd_arg, "%s%s%s%s %s%s %s p %s %s",
4695 		is_force_lba? "--force-lba " : "",
4696 		stage2_arg? stage2_arg : "",
4697 		stage2_arg? " " : "",
4698 		stage1,
4699 		(installed_drive != image_drive) ? "d " : "",
4700 		device,
4701 		stage2,
4702 		config_filename,
4703 		real_config_filename);
4704 #else /* NOT USED */
4705   /* This code was used, because we belived some BIOSes had a problem
4706      that they didn't pass a booting drive correctly. It turned out,
4707      however, stage1 could trash a booting drive when checking LBA support,
4708      because some BIOSes modified the register %dx in INT 13H, AH=48H.
4709      So it becamed unclear whether GRUB should use a pre-defined booting
4710      drive or not. If the problem still exists, it would be necessary to
4711      switch back to this code.  */
4712   grub_sprintf (cmd_arg, "%s%s%s%s d %s %s p %s %s",
4713 		is_force_lba? "--force-lba " : "",
4714 		stage2_arg? stage2_arg : "",
4715 		stage2_arg? " " : "",
4716 		stage1,
4717 		device,
4718 		stage2,
4719 		config_filename,
4720 		real_config_filename);
4721 #endif /* NOT USED */
4722 
4723   /* Notify what will be run.  */
4724   grub_printf (" Running \"install %s\"... ", cmd_arg);
4725 
4726   /* Make sure that SAVED_DRIVE and SAVED_PARTITION are identical
4727      with IMAGE_DRIVE and IMAGE_PARTITION, respectively.  */
4728   saved_drive = image_drive;
4729   saved_partition = image_partition;
4730 
4731   /* Run the command.  */
4732   if (! install_func (cmd_arg, flags))
4733     grub_printf ("succeeded\nDone.\n");
4734   else
4735     grub_printf ("failed\n");
4736 
4737  fail:
4738   saved_drive = tmp_drive;
4739   saved_partition = tmp_partition;
4740   return errnum;
4741 }
4742 
4743 static struct builtin builtin_setup =
4744 {
4745   "setup",
4746   setup_func,
4747   BUILTIN_CMDLINE | BUILTIN_HELP_LIST,
4748   "setup [--prefix=DIR] [--stage2=STAGE2_FILE] [--force-lba] INSTALL_DEVICE [IMAGE_DEVICE]",
4749   "Set up the installation of GRUB automatically. This command uses"
4750   " the more flexible command \"install\" in the backend and installs"
4751   " GRUB into the device INSTALL_DEVICE. If IMAGE_DEVICE is specified,"
4752   " then find the GRUB images in the device IMAGE_DEVICE, otherwise"
4753   " use the current \"root device\", which can be set by the command"
4754   " \"root\". If you know that your BIOS should support LBA but GRUB"
4755   " doesn't work in LBA mode, specify the option `--force-lba'."
4756   " If you install GRUB under the grub shell and you cannot unmount the"
4757   " partition where GRUB images reside, specify the option `--stage2'"
4758   " to tell GRUB the file name under your OS."
4759 };
4760 
4761 
4762 #if defined(SUPPORT_SERIAL) || defined(SUPPORT_HERCULES) || defined(SUPPORT_GRAPHICS)
4763 /* terminal */
4764 static int
terminal_func(char * arg,int flags)4765 terminal_func (char *arg, int flags)
4766 {
4767   /* The index of the default terminal in TERM_TABLE.  */
4768   int default_term = -1;
4769   struct term_entry *prev_term = current_term;
4770   int to = -1;
4771   int lines = 0;
4772   int no_message = 0;
4773   unsigned long term_flags = 0;
4774   /* XXX: Assume less than 32 terminals.  */
4775   unsigned long term_bitmap = 0;
4776 
4777   /* Get GNU-style long options.  */
4778   while (1)
4779     {
4780       if (grub_memcmp (arg, "--dumb", sizeof ("--dumb") - 1) == 0)
4781 	term_flags |= TERM_DUMB;
4782       else if (grub_memcmp (arg, "--no-echo", sizeof ("--no-echo") - 1) == 0)
4783 	/* ``--no-echo'' implies ``--no-edit''.  */
4784 	term_flags |= (TERM_NO_ECHO | TERM_NO_EDIT);
4785       else if (grub_memcmp (arg, "--no-edit", sizeof ("--no-edit") - 1) == 0)
4786 	term_flags |= TERM_NO_EDIT;
4787       else if (grub_memcmp (arg, "--timeout=", sizeof ("--timeout=") - 1) == 0)
4788 	{
4789 	  char *val = arg + sizeof ("--timeout=") - 1;
4790 
4791 	  if (! safe_parse_maxint (&val, &to))
4792 	    return 1;
4793 	}
4794       else if (grub_memcmp (arg, "--lines=", sizeof ("--lines=") - 1) == 0)
4795 	{
4796 	  char *val = arg + sizeof ("--lines=") - 1;
4797 
4798 	  if (! safe_parse_maxint (&val, &lines))
4799 	    return 1;
4800 
4801 	  /* Probably less than four is meaningless....  */
4802 	  if (lines < 4)
4803 	    {
4804 	      errnum = ERR_BAD_ARGUMENT;
4805 	      return 1;
4806 	    }
4807 	}
4808       else if (grub_memcmp (arg, "--silent", sizeof ("--silent") - 1) == 0)
4809 	no_message = 1;
4810       else
4811 	break;
4812 
4813       arg = skip_to (0, arg);
4814     }
4815 
4816   /* If no argument is specified, show current setting.  */
4817   if (! *arg)
4818     {
4819       grub_printf ("%s%s%s%s\n",
4820 		   current_term->name,
4821 		   current_term->flags & TERM_DUMB ? " (dumb)" : "",
4822 		   current_term->flags & TERM_NO_EDIT ? " (no edit)" : "",
4823 		   current_term->flags & TERM_NO_ECHO ? " (no echo)" : "");
4824       return 0;
4825     }
4826 
4827   while (*arg)
4828     {
4829       int i;
4830       char *next = skip_to (0, arg);
4831 
4832       nul_terminate (arg);
4833 
4834       for (i = 0; term_table[i].name; i++)
4835 	{
4836 	  if (grub_strcmp (arg, term_table[i].name) == 0)
4837 	    {
4838 	      if (term_table[i].flags & TERM_NEED_INIT)
4839 		{
4840 		  errnum = ERR_DEV_NEED_INIT;
4841 		  return 1;
4842 		}
4843 
4844 	      if (default_term < 0)
4845 		default_term = i;
4846 
4847 	      term_bitmap |= (1 << i);
4848 	      break;
4849 	    }
4850 	}
4851 
4852       if (! term_table[i].name)
4853 	{
4854 	  errnum = ERR_BAD_ARGUMENT;
4855 	  return 1;
4856 	}
4857 
4858       arg = next;
4859     }
4860 
4861   /* If multiple terminals are specified, wait until the user pushes any
4862      key on one of the terminals.  */
4863   if (term_bitmap & ~(1 << default_term))
4864     {
4865       int time1, time2 = -1;
4866 
4867       /* XXX: Disable the pager.  */
4868       count_lines = -1;
4869 
4870       /* Get current time.  */
4871       while ((time1 = getrtsecs ()) == 0xFF)
4872 	;
4873 
4874       /* Wait for a key input.  */
4875       while (to)
4876 	{
4877 	  int i;
4878 
4879 	  for (i = 0; term_table[i].name; i++)
4880 	    {
4881 	      if (term_bitmap & (1 << i))
4882 		{
4883 		  if (term_table[i].checkkey () >= 0)
4884 		    {
4885 		      (void) term_table[i].getkey ();
4886 		      default_term = i;
4887 
4888 		      goto end;
4889 		    }
4890 		}
4891 	    }
4892 
4893 	  /* Prompt the user, once per sec.  */
4894 	  if ((time1 = getrtsecs ()) != time2 && time1 != 0xFF)
4895 	    {
4896 	      if (! no_message)
4897 		{
4898 		  /* Need to set CURRENT_TERM to each of selected
4899 		     terminals.  */
4900 		  for (i = 0; term_table[i].name; i++)
4901 		    if (term_bitmap & (1 << i))
4902 		      {
4903 			current_term = term_table + i;
4904 			grub_printf ("\rPress any key to continue.\n");
4905 		      }
4906 
4907 		  /* Restore CURRENT_TERM.  */
4908 		  current_term = prev_term;
4909 		}
4910 
4911 	      time2 = time1;
4912 	      if (to > 0)
4913 		to--;
4914 	    }
4915 	}
4916     }
4917 
4918  end:
4919   current_term = term_table + default_term;
4920   current_term->flags = term_flags;
4921 
4922   if (lines)
4923     max_lines = lines;
4924   else
4925     max_lines = current_term->max_lines;
4926 
4927   /* If the interface is currently the command-line,
4928      restart it to repaint the screen.  */
4929   if ((current_term != prev_term) && (flags & BUILTIN_CMDLINE)){
4930     if (prev_term->shutdown)
4931       prev_term->shutdown();
4932     if (current_term->startup)
4933       current_term->startup();
4934     grub_longjmp (restart_cmdline_env, 0);
4935   }
4936 
4937   return 0;
4938 }
4939 
4940 static struct builtin builtin_terminal =
4941 {
4942   "terminal",
4943   terminal_func,
4944   BUILTIN_MENU | BUILTIN_CMDLINE | BUILTIN_HELP_LIST,
4945   "terminal [--dumb] [--no-echo] [--no-edit] [--timeout=SECS] [--lines=LINES] [--silent] [console] [serial] [hercules] [graphics] [composite]",
4946   "Select a terminal. When multiple terminals are specified, wait until"
4947   " you push any key to continue. If both console and serial are specified,"
4948   " the terminal to which you input a key first will be selected. If no"
4949   " argument is specified, print current setting. To accomodate systems"
4950   " where console redirection may or may not be present, the composite"
4951   " console will direct output to the serial and BIOS consoles, and accept"
4952   " input from either one, without requiring selection. The option --dumb"
4953   " specifies that your terminal is dumb, otherwise, vt100-compatibility"
4954   " is assumed. If you specify --no-echo, input characters won't be echoed."
4955   " If you specify --no-edit, the BASH-like editing feature will be disabled."
4956   " If --timeout is present, this command will wait at most for SECS"
4957   " seconds. The option --lines specifies the maximum number of lines."
4958   " The option --silent is used to suppress messages."
4959 };
4960 #endif /* SUPPORT_SERIAL || SUPPORT_HERCULES || SUPPORT_GRAPHICS */
4961 
4962 
4963 #ifdef SUPPORT_SERIAL
4964 static int
terminfo_func(char * arg,int flags)4965 terminfo_func (char *arg, int flags)
4966 {
4967   struct terminfo term;
4968 
4969   if (*arg)
4970     {
4971       struct
4972       {
4973 	const char *name;
4974 	char *var;
4975       }
4976       options[] =
4977 	{
4978 	  {"--name=", term.name},
4979 	  {"--cursor-address=", term.cursor_address},
4980 	  {"--clear-screen=", term.clear_screen},
4981 	  {"--enter-standout-mode=", term.enter_standout_mode},
4982 	  {"--exit-standout-mode=", term.exit_standout_mode}
4983 	};
4984 
4985       grub_memset (&term, 0, sizeof (term));
4986 
4987       while (*arg)
4988 	{
4989 	  int i;
4990 	  char *next = skip_to (0, arg);
4991 
4992 	  nul_terminate (arg);
4993 
4994 	  for (i = 0; i < sizeof (options) / sizeof (options[0]); i++)
4995 	    {
4996 	      const char *name = options[i].name;
4997 	      int len = grub_strlen (name);
4998 
4999 	      if (! grub_memcmp (arg, name, len))
5000 		{
5001 		  grub_strcpy (options[i].var, ti_unescape_string (arg + len));
5002 		  break;
5003 		}
5004 	    }
5005 
5006 	  if (i == sizeof (options) / sizeof (options[0]))
5007 	    {
5008 	      errnum = ERR_BAD_ARGUMENT;
5009 	      return errnum;
5010 	    }
5011 
5012 	  arg = next;
5013 	}
5014 
5015       if (term.name[0] == 0 || term.cursor_address[0] == 0)
5016 	{
5017 	  errnum = ERR_BAD_ARGUMENT;
5018 	  return errnum;
5019 	}
5020 
5021       ti_set_term (&term);
5022     }
5023   else
5024     {
5025       /* No option specifies printing out current settings.  */
5026       ti_get_term (&term);
5027 
5028       grub_printf ("name=%s\n",
5029 		   ti_escape_string (term.name));
5030       grub_printf ("cursor_address=%s\n",
5031 		   ti_escape_string (term.cursor_address));
5032       grub_printf ("clear_screen=%s\n",
5033 		   ti_escape_string (term.clear_screen));
5034       grub_printf ("enter_standout_mode=%s\n",
5035 		   ti_escape_string (term.enter_standout_mode));
5036       grub_printf ("exit_standout_mode=%s\n",
5037 		   ti_escape_string (term.exit_standout_mode));
5038     }
5039 
5040   return 0;
5041 }
5042 
5043 static struct builtin builtin_terminfo =
5044 {
5045   "terminfo",
5046   terminfo_func,
5047   BUILTIN_MENU | BUILTIN_CMDLINE | BUILTIN_HELP_LIST,
5048   "terminfo [--name=NAME --cursor-address=SEQ [--clear-screen=SEQ]"
5049   " [--enter-standout-mode=SEQ] [--exit-standout-mode=SEQ]]",
5050 
5051   "Define the capabilities of your terminal. Use this command to"
5052   " define escape sequences, if it is not vt100-compatible."
5053   " You may use \\e for ESC and ^X for a control character."
5054   " If no option is specified, the current settings are printed."
5055 };
5056 #endif /* SUPPORT_SERIAL */
5057 
5058 
5059 /* testload */
5060 static int
testload_func(char * arg,int flags)5061 testload_func (char *arg, int flags)
5062 {
5063   int i;
5064 
5065   kernel_type = KERNEL_TYPE_NONE;
5066 
5067   if (! grub_open (arg))
5068     return 1;
5069 
5070   disk_read_hook = disk_read_print_func;
5071 
5072   /* Perform filesystem test on the specified file.  */
5073   /* Read whole file first. */
5074   grub_printf ("Whole file: ");
5075 
5076   grub_read ((char *) RAW_ADDR (0x100000), -1);
5077 
5078   /* Now compare two sections of the file read differently.  */
5079 
5080   for (i = 0; i < 0x10ac0; i++)
5081     {
5082       *((unsigned char *) RAW_ADDR (0x200000 + i)) = 0;
5083       *((unsigned char *) RAW_ADDR (0x300000 + i)) = 1;
5084     }
5085 
5086   /* First partial read.  */
5087   grub_printf ("\nPartial read 1: ");
5088 
5089   grub_seek (0);
5090   grub_read ((char *) RAW_ADDR (0x200000), 0x7);
5091   grub_read ((char *) RAW_ADDR (0x200007), 0x100);
5092   grub_read ((char *) RAW_ADDR (0x200107), 0x10);
5093   grub_read ((char *) RAW_ADDR (0x200117), 0x999);
5094   grub_read ((char *) RAW_ADDR (0x200ab0), 0x10);
5095   grub_read ((char *) RAW_ADDR (0x200ac0), 0x10000);
5096 
5097   /* Second partial read.  */
5098   grub_printf ("\nPartial read 2: ");
5099 
5100   grub_seek (0);
5101   grub_read ((char *) RAW_ADDR (0x300000), 0x10000);
5102   grub_read ((char *) RAW_ADDR (0x310000), 0x10);
5103   grub_read ((char *) RAW_ADDR (0x310010), 0x7);
5104   grub_read ((char *) RAW_ADDR (0x310017), 0x10);
5105   grub_read ((char *) RAW_ADDR (0x310027), 0x999);
5106   grub_read ((char *) RAW_ADDR (0x3109c0), 0x100);
5107 
5108   grub_printf ("\nHeader1 = 0x%x, next = 0x%x, next = 0x%x, next = 0x%x\n",
5109 	       *((int *) RAW_ADDR (0x200000)),
5110 	       *((int *) RAW_ADDR (0x200004)),
5111 	       *((int *) RAW_ADDR (0x200008)),
5112 	       *((int *) RAW_ADDR (0x20000c)));
5113 
5114   grub_printf ("Header2 = 0x%x, next = 0x%x, next = 0x%x, next = 0x%x\n",
5115 	       *((int *) RAW_ADDR (0x300000)),
5116 	       *((int *) RAW_ADDR (0x300004)),
5117 	       *((int *) RAW_ADDR (0x300008)),
5118 	       *((int *) RAW_ADDR (0x30000c)));
5119 
5120   for (i = 0; i < 0x10ac0; i++)
5121     if (*((unsigned char *) RAW_ADDR (0x200000 + i))
5122 	!= *((unsigned char *) RAW_ADDR (0x300000 + i)))
5123       break;
5124 
5125   grub_printf ("Max is 0x10ac0: i=0x%x, filepos=0x%x\n", i, filepos);
5126   disk_read_hook = 0;
5127   grub_close ();
5128   return 0;
5129 }
5130 
5131 static struct builtin builtin_testload =
5132 {
5133   "testload",
5134   testload_func,
5135   BUILTIN_CMDLINE,
5136   "testload FILE",
5137   "Read the entire contents of FILE in several different ways and"
5138   " compares them, to test the filesystem code. The output is somewhat"
5139   " cryptic, but if no errors are reported and the final `i=X,"
5140   " filepos=Y' reading has X and Y equal, then it is definitely"
5141   " consistent, and very likely works correctly subject to a"
5142   " consistent offset error. If this test succeeds, then a good next"
5143   " step is to try loading a kernel."
5144 };
5145 
5146 
5147 /* testvbe MODE */
5148 static int
testvbe_func(char * arg,int flags)5149 testvbe_func (char *arg, int flags)
5150 {
5151   int mode_number;
5152   struct vbe_controller controller;
5153   struct vbe_mode mode;
5154 
5155   if (! *arg)
5156     {
5157       errnum = ERR_BAD_ARGUMENT;
5158       return 1;
5159     }
5160 
5161   if (! safe_parse_maxint (&arg, &mode_number))
5162     return 1;
5163 
5164   /* Preset `VBE2'.  */
5165   grub_memmove (controller.signature, "VBE2", 4);
5166 
5167   /* Detect VBE BIOS.  */
5168   if (get_vbe_controller_info (&controller) != 0x004F)
5169     {
5170       grub_printf (" VBE BIOS is not present.\n");
5171       return 0;
5172     }
5173 
5174   if (controller.version < 0x0200)
5175     {
5176       grub_printf (" VBE version %d.%d is not supported.\n",
5177 		   (int) (controller.version >> 8),
5178 		   (int) (controller.version & 0xFF));
5179       return 0;
5180     }
5181 
5182   if (get_vbe_mode_info (mode_number, &mode) != 0x004F
5183       || (mode.mode_attributes & 0x0091) != 0x0091)
5184     {
5185       grub_printf (" Mode 0x%x is not supported.\n", mode_number);
5186       return 0;
5187     }
5188 
5189   /* Now trip to the graphics mode.  */
5190   if (set_vbe_mode (mode_number | (1 << 14)) != 0x004F)
5191     {
5192       grub_printf (" Switching to Mode 0x%x failed.\n", mode_number);
5193       return 0;
5194     }
5195 
5196   /* Draw something on the screen...  */
5197   {
5198     unsigned char *base_buf = (unsigned char *) mode.phys_base;
5199     int scanline = controller.version >= 0x0300
5200       ? mode.linear_bytes_per_scanline : mode.bytes_per_scanline;
5201     /* FIXME: this assumes that any depth is a modulo of 8.  */
5202     int bpp = mode.bits_per_pixel / 8;
5203     int width = mode.x_resolution;
5204     int height = mode.y_resolution;
5205     int x, y;
5206     unsigned color = 0;
5207 
5208     /* Iterate drawing on the screen, until the user hits any key.  */
5209     while (checkkey () == -1)
5210       {
5211 	for (y = 0; y < height; y++)
5212 	  {
5213 	    unsigned char *line_buf = base_buf + scanline * y;
5214 
5215 	    for (x = 0; x < width; x++)
5216 	      {
5217 		unsigned char *buf = line_buf + bpp * x;
5218 		int i;
5219 
5220 		for (i = 0; i < bpp; i++, buf++)
5221 		  *buf = (color >> (i * 8)) & 0xff;
5222 	      }
5223 
5224 	    color++;
5225 	  }
5226       }
5227 
5228     /* Discard the input.  */
5229     getkey ();
5230   }
5231 
5232   /* Back to the default text mode.  */
5233   if (set_vbe_mode (0x03) != 0x004F)
5234     {
5235       /* Why?!  */
5236       grub_reboot ();
5237     }
5238 
5239   return 0;
5240 }
5241 
5242 static struct builtin builtin_testvbe =
5243 {
5244   "testvbe",
5245   testvbe_func,
5246   BUILTIN_CMDLINE | BUILTIN_HELP_LIST,
5247   "testvbe MODE",
5248   "Test the VBE mode MODE. Hit any key to return."
5249 };
5250 
5251 
5252 #ifdef SUPPORT_NETBOOT
5253 /* tftpserver */
5254 static int
tftpserver_func(char * arg,int flags)5255 tftpserver_func (char *arg, int flags)
5256 {
5257   if (! *arg || ! ifconfig (0, 0, 0, arg))
5258     {
5259       errnum = ERR_BAD_ARGUMENT;
5260       return 1;
5261     }
5262 
5263   print_network_configuration ();
5264   return 0;
5265 }
5266 
5267 static struct builtin builtin_tftpserver =
5268 {
5269   "tftpserver",
5270   tftpserver_func,
5271   BUILTIN_CMDLINE | BUILTIN_MENU | BUILTIN_HELP_LIST,
5272   "tftpserver IPADDR",
5273   "Override the TFTP server address."
5274 };
5275 #endif /* SUPPORT_NETBOOT */
5276 
5277 
5278 /* timeout */
5279 static int
timeout_func(char * arg,int flags)5280 timeout_func (char *arg, int flags)
5281 {
5282   if (! safe_parse_maxint (&arg, &grub_timeout))
5283     return 1;
5284 
5285   return 0;
5286 }
5287 
5288 static struct builtin builtin_timeout =
5289 {
5290   "timeout",
5291   timeout_func,
5292   BUILTIN_MENU,
5293 #if 0
5294   "timeout SEC",
5295   "Set a timeout, in SEC seconds, before automatically booting the"
5296   " default entry (normally the first entry defined)."
5297 #endif
5298 };
5299 
5300 
5301 /* title */
5302 static int
title_func(char * arg,int flags)5303 title_func (char *arg, int flags)
5304 {
5305   /* This function is not actually used at least currently.  */
5306   return 0;
5307 }
5308 
5309 static struct builtin builtin_title =
5310 {
5311   "title",
5312   title_func,
5313   BUILTIN_TITLE,
5314 #if 0
5315   "title [NAME ...]",
5316   "Start a new boot entry, and set its name to the contents of the"
5317   " rest of the line, starting with the first non-space character."
5318 #endif
5319 };
5320 
5321 
5322 /* unhide */
5323 static int
unhide_func(char * arg,int flags)5324 unhide_func (char *arg, int flags)
5325 {
5326   if (! set_device (arg))
5327     return 1;
5328 
5329   if (! set_partition_hidden_flag (0))
5330     return 1;
5331 
5332   return 0;
5333 }
5334 
5335 static struct builtin builtin_unhide =
5336 {
5337   "unhide",
5338   unhide_func,
5339   BUILTIN_CMDLINE | BUILTIN_MENU | BUILTIN_HELP_LIST,
5340   "unhide PARTITION",
5341   "Unhide PARTITION by clearing the \"hidden\" bit in its"
5342   " partition type code."
5343 };
5344 
5345 
5346 /* uppermem */
5347 static int
uppermem_func(char * arg,int flags)5348 uppermem_func (char *arg, int flags)
5349 {
5350   if (! safe_parse_maxint (&arg, (int *) &mbi.mem_upper))
5351     return 1;
5352 
5353   mbi.flags &= ~MB_INFO_MEM_MAP;
5354   return 0;
5355 }
5356 
5357 static struct builtin builtin_uppermem =
5358 {
5359   "uppermem",
5360   uppermem_func,
5361   BUILTIN_CMDLINE | BUILTIN_HELP_LIST,
5362   "uppermem KBYTES",
5363   "Force GRUB to assume that only KBYTES kilobytes of upper memory are"
5364   " installed.  Any system address range maps are discarded."
5365 };
5366 
5367 
5368 /* vbeprobe */
5369 static int
vbeprobe_func(char * arg,int flags)5370 vbeprobe_func (char *arg, int flags)
5371 {
5372   struct vbe_controller controller;
5373   unsigned short *mode_list;
5374   int mode_number = -1;
5375 
5376   auto unsigned long vbe_far_ptr_to_linear (unsigned long);
5377 
5378   unsigned long vbe_far_ptr_to_linear (unsigned long ptr)
5379     {
5380       unsigned short seg = (ptr >> 16);
5381       unsigned short off = (ptr & 0xFFFF);
5382 
5383       return (seg << 4) + off;
5384     }
5385 
5386   if (*arg)
5387     {
5388       if (! safe_parse_maxint (&arg, &mode_number))
5389 	return 1;
5390     }
5391 
5392   /* Set the signature to `VBE2', to obtain VBE 3.0 information.  */
5393   grub_memmove (controller.signature, "VBE2", 4);
5394 
5395   if (get_vbe_controller_info (&controller) != 0x004F)
5396     {
5397       grub_printf (" VBE BIOS is not present.\n");
5398       return 0;
5399     }
5400 
5401   /* Check the version.  */
5402   if (controller.version < 0x0200)
5403     {
5404       grub_printf (" VBE version %d.%d is not supported.\n",
5405 		   (int) (controller.version >> 8),
5406 		   (int) (controller.version & 0xFF));
5407       return 0;
5408     }
5409 
5410   /* Print some information.  */
5411   grub_printf (" VBE version %d.%d\n",
5412 	       (int) (controller.version >> 8),
5413 	       (int) (controller.version & 0xFF));
5414 
5415   /* Iterate probing modes.  */
5416   for (mode_list
5417 	 = (unsigned short *) vbe_far_ptr_to_linear (controller.video_mode);
5418        *mode_list != 0xFFFF;
5419        mode_list++)
5420     {
5421       struct vbe_mode mode;
5422 
5423       if (get_vbe_mode_info (*mode_list, &mode) != 0x004F)
5424 	continue;
5425 
5426       /* Skip this, if this is not supported or linear frame buffer
5427 	 mode is not support.  */
5428       if ((mode.mode_attributes & 0x0081) != 0x0081)
5429 	continue;
5430 
5431       if (mode_number == -1 || mode_number == *mode_list)
5432 	{
5433 	  char *model;
5434 	  switch (mode.memory_model)
5435 	    {
5436 	    case 0x00: model = "Text"; break;
5437 	    case 0x01: model = "CGA graphics"; break;
5438 	    case 0x02: model = "Hercules graphics"; break;
5439 	    case 0x03: model = "Planar"; break;
5440 	    case 0x04: model = "Packed pixel"; break;
5441 	    case 0x05: model = "Non-chain 4, 256 color"; break;
5442 	    case 0x06: model = "Direct Color"; break;
5443 	    case 0x07: model = "YUV"; break;
5444 	    default: model = "Unknown"; break;
5445 	    }
5446 
5447 	  grub_printf ("  0x%x: %s, %ux%ux%u\n",
5448 		       (unsigned) *mode_list,
5449 		       model,
5450 		       (unsigned) mode.x_resolution,
5451 		       (unsigned) mode.y_resolution,
5452 		       (unsigned) mode.bits_per_pixel);
5453 
5454 	  if (mode_number != -1)
5455 	    break;
5456 	}
5457     }
5458 
5459   if (mode_number != -1 && mode_number != *mode_list)
5460     grub_printf ("  Mode 0x%x is not found or supported.\n", mode_number);
5461 
5462   return 0;
5463 }
5464 
5465 static struct builtin builtin_vbeprobe =
5466 {
5467   "vbeprobe",
5468   vbeprobe_func,
5469   BUILTIN_CMDLINE | BUILTIN_HELP_LIST,
5470   "vbeprobe [MODE]",
5471   "Probe VBE information. If the mode number MODE is specified, show only"
5472   " the information about only the mode."
5473 };
5474 
5475 static int
variable_func(char * arg,int flags)5476 variable_func(char *arg, int flags)
5477 {
5478 	char name[EV_NAMELEN];
5479 	char *val;
5480 	int err;
5481 
5482 	if (*arg == '\0') {
5483 		dump_variables();
5484 		return (0);
5485 	}
5486 
5487 	if ((val = grub_strchr(arg, ' ')) != NULL) {
5488 		if (val - arg >= sizeof (name)) {
5489 			errnum = ERR_WONT_FIT;
5490 			return (1);
5491 		}
5492 		(void) grub_memcpy(name, arg, (val - arg));
5493 		name[val - arg] = '\0';
5494 		val = skip_to(0, arg);
5495 	} else {
5496 		if (grub_strlen(arg) >= sizeof (name)) {
5497 			errnum = ERR_WONT_FIT;
5498 			return (1);
5499 		}
5500 		(void) grub_strcpy(name, arg);
5501 	}
5502 
5503 	if ((err = set_variable(name, val)) != 0) {
5504 		errnum = err;
5505 		return (1);
5506 	}
5507 
5508 	return (0);
5509 }
5510 
5511 static struct builtin builtin_variable =
5512 {
5513   "variable",
5514   variable_func,
5515   BUILTIN_CMDLINE | BUILTIN_MENU | BUILTIN_SCRIPT | BUILTIN_HELP_LIST,
5516   "variable NAME [VALUE]",
5517   "Set the variable NAME to VALUE, or to the empty string if no value is"
5518   " given. NAME must contain no spaces. There is no quoting mechanism"
5519   " and nested variable references are not allowed. Variable values may"
5520   " be substituted into the kernel$ and module$ commands using ${NAME}."
5521 };
5522 
5523 
5524 /* The table of builtin commands. Sorted in dictionary order.  */
5525 struct builtin *builtin_table[] =
5526 {
5527 #ifdef SUPPORT_GRAPHICS
5528   &builtin_background,
5529 #endif
5530   &builtin_blocklist,
5531   &builtin_boot,
5532   &builtin_bootfs,
5533 #ifdef SUPPORT_NETBOOT
5534   &builtin_bootp,
5535 #endif /* SUPPORT_NETBOOT */
5536   &builtin_cat,
5537   &builtin_chainloader,
5538   &builtin_clear,
5539   &builtin_cmp,
5540   &builtin_color,
5541   &builtin_configfile,
5542   &builtin_debug,
5543   &builtin_default,
5544 #ifdef GRUB_UTIL
5545   &builtin_device,
5546 #endif /* GRUB_UTIL */
5547 #ifdef SUPPORT_NETBOOT
5548   &builtin_dhcp,
5549 #endif /* SUPPORT_NETBOOT */
5550   &builtin_displayapm,
5551   &builtin_displaymem,
5552 #ifdef GRUB_UTIL
5553   &builtin_dump,
5554 #endif /* GRUB_UTIL */
5555   &builtin_embed,
5556   &builtin_fallback,
5557   &builtin_find,
5558   &builtin_findroot,
5559 #ifdef SUPPORT_GRAPHICS
5560   &builtin_foreground,
5561 #endif
5562   &builtin_fstest,
5563   &builtin_geometry,
5564   &builtin_halt,
5565   &builtin_help,
5566   &builtin_hiddenmenu,
5567   &builtin_hide,
5568 #ifdef SUPPORT_NETBOOT
5569   &builtin_ifconfig,
5570 #endif /* SUPPORT_NETBOOT */
5571   &builtin_impsprobe,
5572   &builtin_initrd,
5573   &builtin_install,
5574   &builtin_ioprobe,
5575   &builtin_kernel,
5576   &builtin_kernel_dollar,
5577   &builtin_lock,
5578   &builtin_makeactive,
5579   &builtin_map,
5580 #ifdef USE_MD5_PASSWORDS
5581   &builtin_md5crypt,
5582 #endif /* USE_MD5_PASSWORDS */
5583   &builtin_min_mem64,
5584   &builtin_module,
5585   &builtin_module_dollar,
5586   &builtin_modulenounzip,
5587   &builtin_pager,
5588   &builtin_partnew,
5589   &builtin_parttype,
5590   &builtin_password,
5591   &builtin_pause,
5592 #if defined(RPC_DEBUG) && defined(SUPPORT_NETBOOT)
5593   &builtin_portmap,
5594 #endif /* RPC_DEBUG && SUPPORT_NETBOOT */
5595 #ifdef GRUB_UTIL
5596   &builtin_quit,
5597 #endif /* GRUB_UTIL */
5598 #ifdef SUPPORT_NETBOOT
5599   &builtin_rarp,
5600 #endif /* SUPPORT_NETBOOT */
5601   &builtin_read,
5602   &builtin_reboot,
5603   &builtin_root,
5604   &builtin_rootnoverify,
5605   &builtin_savedefault,
5606 #ifdef SUPPORT_SERIAL
5607   &builtin_serial,
5608 #endif /* SUPPORT_SERIAL */
5609   &builtin_setkey,
5610   &builtin_setup,
5611 #ifdef SUPPORT_GRAPHICS
5612   &builtin_splashimage,
5613 #endif /* SUPPORT_GRAPHICS */
5614 #if defined(SUPPORT_SERIAL) || defined(SUPPORT_HERCULES) || defined(SUPPORT_GRAPHICS)
5615   &builtin_terminal,
5616 #endif /* SUPPORT_SERIAL || SUPPORT_HERCULES || SUPPORT_GRAPHICS */
5617 #ifdef SUPPORT_SERIAL
5618   &builtin_terminfo,
5619 #endif /* SUPPORT_SERIAL */
5620   &builtin_testload,
5621   &builtin_testvbe,
5622 #ifdef SUPPORT_NETBOOT
5623   &builtin_tftpserver,
5624 #endif /* SUPPORT_NETBOOT */
5625   &builtin_timeout,
5626   &builtin_title,
5627   &builtin_unhide,
5628   &builtin_uppermem,
5629   &builtin_variable,
5630   &builtin_vbeprobe,
5631   &builtin_verbose,
5632   0
5633 };
5634