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 long long sector,int offset,int length)149 disk_read_print_func(unsigned long long sector, int offset, int length)
150 {
151   grub_printf ("[%llu,%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 long long 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 long long 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 long long 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%llu+%d", num_entries ? "," : "",
186 			     start_sector - part_start, num_sectors);
187 	      else if (num_sectors > 1)
188 		grub_printf ("%s%llu+%d,%lld[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%llu[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%llu[%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%llu+%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   unsigned long long 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       unsigned long long 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, "%llu+%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 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 = %llu, %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 long long saved_sector;
2226   unsigned long long 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 long long sector, int offset,
2247       int length);
2248   auto void disk_read_blocklist_func (unsigned long long 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 long long sector, int offset,
2253       int length)
2254     {
2255       if (debug)
2256 	printf ("[%llu]", 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 long long sector, int offset,
2270       int length)
2271     {
2272       if (debug)
2273 	printf("[%llu]", 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   if (stage2_first_sector >= 0xffffffffUL) {
2439     grub_printf ("Error: stage2 first sector must be below 2TB\n");
2440     goto fail;
2441   }
2442 
2443   /* Read the second sector of Stage 2.  */
2444   if (grub_read (stage2_second_buffer, SECTOR_SIZE) != SECTOR_SIZE)
2445     goto fail;
2446 
2447   stage2_second_sector = saved_sector;
2448 
2449   /* Check for the version of Stage 2.  */
2450   if (*((short *) (stage2_second_buffer + STAGE2_VER_MAJ_OFFS))
2451       != COMPAT_VERSION)
2452     {
2453       errnum = ERR_BAD_VERSION;
2454       goto fail;
2455     }
2456 
2457   /* Check for the Stage 2 id.  */
2458   if (stage2_second_buffer[STAGE2_STAGE2_ID] != STAGE2_ID_STAGE2)
2459     is_stage1_5 = 1;
2460 
2461   /* If INSTALLADDR is not specified explicitly in the command-line,
2462      determine it by the Stage 2 id.  */
2463   if (! installaddr)
2464     {
2465       if (! is_stage1_5)
2466 	/* Stage 2.  */
2467 	installaddr = 0x8000;
2468       else
2469 	/* Stage 1.5.  */
2470 	installaddr = 0x2000;
2471     }
2472 
2473   *((unsigned long *) (stage1_buffer + STAGE1_STAGE2_SECTOR))
2474     = stage2_first_sector;
2475   *((unsigned short *) (stage1_buffer + STAGE1_STAGE2_ADDRESS))
2476     = installaddr;
2477   *((unsigned short *) (stage1_buffer + STAGE1_STAGE2_SEGMENT))
2478     = installaddr >> 4;
2479 
2480   i = (int) stage2_first_buffer + SECTOR_SIZE - 4;
2481   while (*((unsigned long *) i))
2482     {
2483       if (i < (int) stage2_first_buffer
2484 	  || (*((int *) (i - 4)) & 0x80000000)
2485 	  || *((unsigned short *) i) >= 0xA00
2486 	  || *((short *) (i + 2)) == 0)
2487 	{
2488 	  errnum = ERR_BAD_VERSION;
2489 	  goto fail;
2490 	}
2491 
2492       *((int *) i) = 0;
2493       *((int *) (i - 4)) = 0;
2494       i -= 8;
2495     }
2496 
2497   installlist = (int) stage2_first_buffer + SECTOR_SIZE + 4;
2498   installaddr += SECTOR_SIZE;
2499 
2500   /* Read the whole of Stage2 except for the first sector.  */
2501   grub_seek (SECTOR_SIZE);
2502 
2503   disk_read_hook = disk_read_blocklist_func;
2504   if (! grub_read (dummy, -1))
2505     goto fail;
2506 
2507   disk_read_hook = 0;
2508 
2509   /* Find a string for the configuration filename.  */
2510   config_file_location = stage2_second_buffer + STAGE2_VER_STR_OFFS;
2511   while (*(config_file_location++))
2512     ;
2513 
2514   /* Set the "force LBA" flag for Stage2.  */
2515   *((unsigned char *) (stage2_second_buffer + STAGE2_FORCE_LBA))
2516     = is_force_lba;
2517 
2518   if (*ptr == 'p')
2519     {
2520       *((long *) (stage2_second_buffer + STAGE2_INSTALLPART))
2521 	= src_partition;
2522       if (is_stage1_5)
2523 	{
2524 	  /* Reset the device information in FILE if it is a Stage 1.5.  */
2525 	  unsigned long device = 0xFFFFFFFF;
2526 
2527 	  grub_memmove (config_file_location, (char *) &device,
2528 			sizeof (device));
2529 	}
2530 
2531       ptr = skip_to (0, ptr);
2532     }
2533 
2534   if (*ptr)
2535     {
2536       grub_strcpy (config_filename, ptr);
2537       nul_terminate (config_filename);
2538 
2539       if (! is_stage1_5)
2540 	/* If it is a Stage 2, just copy PTR to CONFIG_FILE_LOCATION.  */
2541 	grub_strcpy (config_file_location, ptr);
2542       else
2543 	{
2544 	  char *real_config;
2545 	  unsigned long device;
2546 
2547 	  /* Translate the external device syntax to the internal device
2548 	     syntax.  */
2549 	  if (! (real_config = set_device (ptr)))
2550 	    {
2551 	      /* The Stage 2 PTR does not contain the device name, so
2552 		 use the root device instead.  */
2553 	      errnum = ERR_NONE;
2554 	      current_drive = saved_drive;
2555 	      current_partition = saved_partition;
2556 	      real_config = ptr;
2557 	    }
2558 
2559 	  if (current_drive == src_drive)
2560 	    {
2561 	      /* If the drive where the Stage 2 resides is the same as
2562 		 the one where the Stage 1.5 resides, do not embed the
2563 		 drive number.  */
2564 	      current_drive = GRUB_INVALID_DRIVE;
2565 	    }
2566 
2567 	  device = (current_drive << 24) | current_partition;
2568 	  grub_memmove (config_file_location, (char *) &device,
2569 			sizeof (device));
2570 	  grub_strcpy (config_file_location + sizeof (device),
2571 		       real_config);
2572 	}
2573 
2574       /* If a Stage 1.5 is used, then we need to modify the Stage2.  */
2575       if (is_stage1_5)
2576 	{
2577 	  char *real_config_filename = skip_to (0, ptr);
2578 
2579 	  is_open = grub_open (config_filename);
2580 	  if (! is_open)
2581 	    goto fail;
2582 
2583 	  /* Skip the first sector.  */
2584 	  grub_seek (SECTOR_SIZE);
2585 
2586 	  disk_read_hook = disk_read_savesect_func;
2587 	  if (grub_read (stage2_buffer, SECTOR_SIZE) != SECTOR_SIZE)
2588 	    goto fail;
2589 
2590 	  disk_read_hook = 0;
2591 	  grub_close ();
2592 	  is_open = 0;
2593 
2594 	  /* Sanity check.  */
2595 	  if (*(stage2_buffer + STAGE2_STAGE2_ID) != STAGE2_ID_STAGE2)
2596 	    {
2597 	      errnum = ERR_BAD_VERSION;
2598 	      goto fail;
2599 	    }
2600 
2601 	  /* Set the "force LBA" flag for Stage2.  */
2602 	  *(stage2_buffer + STAGE2_FORCE_LBA) = is_force_lba;
2603 
2604 	  /* If REAL_CONFIG_FILENAME is specified, copy it to the Stage2.  */
2605 	  if (*real_config_filename)
2606 	    {
2607 	      /* Specified */
2608 	      char *location;
2609 
2610 	      /* Find a string for the configuration filename.  */
2611 	      location = stage2_buffer + STAGE2_VER_STR_OFFS;
2612 	      while (*(location++))
2613 		;
2614 
2615 	      /* Copy the name.  */
2616 	      grub_strcpy (location, real_config_filename);
2617 	    }
2618 
2619 	  /* Write it to the disk.  */
2620 	  buf_track = BUF_CACHE_INVALID;
2621 
2622 #ifdef GRUB_UTIL
2623 	  /* In the grub shell, access the Stage 2 via the OS filesystem
2624 	     service, if possible.  */
2625 	  if (stage2_os_file)
2626 	    {
2627 	      FILE *fp;
2628 
2629 	      fp = fopen (stage2_os_file, "r+");
2630 	      if (! fp)
2631 		{
2632 		  errnum = ERR_FILE_NOT_FOUND;
2633 		  goto fail;
2634 		}
2635 
2636 	      if (fseek (fp, SECTOR_SIZE, SEEK_SET) != 0)
2637 		{
2638 		  fclose (fp);
2639 		  errnum = ERR_BAD_VERSION;
2640 		  goto fail;
2641 		}
2642 
2643 	      if (fwrite (stage2_buffer, 1, SECTOR_SIZE, fp)
2644 		  != SECTOR_SIZE)
2645 		{
2646 		  fclose (fp);
2647 		  errnum = ERR_WRITE;
2648 		  goto fail;
2649 		}
2650 
2651 	      fclose (fp);
2652 	    }
2653 	  else
2654 #endif /* GRUB_UTIL */
2655 	    {
2656 	      if (! devwrite (saved_sector - part_start, 1, stage2_buffer))
2657 		goto fail;
2658 	    }
2659 	}
2660     }
2661 
2662   /* Clear the cache.  */
2663   buf_track = BUF_CACHE_INVALID;
2664 
2665   /* Write the modified sectors of Stage2 to the disk.  */
2666 #ifdef GRUB_UTIL
2667   if (! is_stage1_5 && stage2_os_file)
2668     {
2669       FILE *fp;
2670 
2671       fp = fopen (stage2_os_file, "r+");
2672       if (! fp)
2673 	{
2674 	  errnum = ERR_FILE_NOT_FOUND;
2675 	  goto fail;
2676 	}
2677 
2678       if (fwrite (stage2_first_buffer, 1, SECTOR_SIZE, fp) != SECTOR_SIZE)
2679 	{
2680 	  fclose (fp);
2681 	  errnum = ERR_WRITE;
2682 	  goto fail;
2683 	}
2684 
2685       if (fwrite (stage2_second_buffer, 1, SECTOR_SIZE, fp) != SECTOR_SIZE)
2686 	{
2687 	  fclose (fp);
2688 	  errnum = ERR_WRITE;
2689 	  goto fail;
2690 	}
2691 
2692       fclose (fp);
2693     }
2694   else
2695 #endif /* GRUB_UTIL */
2696     {
2697       /* The first.  */
2698       current_drive = src_drive;
2699       current_partition = src_partition;
2700 
2701       if (! open_partition ())
2702 	goto fail;
2703 
2704       if (! devwrite (stage2_first_sector - src_part_start, 1,
2705 		      stage2_first_buffer))
2706 	goto fail;
2707 
2708       if (! devwrite (stage2_second_sector - src_part_start, 1,
2709 		      stage2_second_buffer))
2710 	goto fail;
2711     }
2712 
2713   /* Write the modified sector of Stage 1 to the disk.  */
2714   current_drive = dest_drive;
2715   current_partition = dest_partition;
2716   if (! open_partition ())
2717     goto fail;
2718 
2719   devwrite (0, 1, stage1_buffer);
2720 
2721  fail:
2722   if (is_open)
2723     grub_close ();
2724 
2725   disk_read_hook = 0;
2726 
2727 #ifndef NO_DECOMPRESSION
2728   no_decompression = 0;
2729 #endif
2730 
2731   return errnum;
2732 }
2733 
2734 static struct builtin builtin_install =
2735 {
2736   "install",
2737   install_func,
2738   BUILTIN_CMDLINE,
2739   "install [--stage2=STAGE2_FILE] [--force-lba] STAGE1 [d] DEVICE STAGE2 [ADDR] [p] [CONFIG_FILE] [REAL_CONFIG_FILE]",
2740   "Install STAGE1 on DEVICE, and install a blocklist for loading STAGE2"
2741   " as a Stage 2. If the option `d' is present, the Stage 1 will always"
2742   " look for the disk where STAGE2 was installed, rather than using"
2743   " the booting drive. The Stage 2 will be loaded at address ADDR, which"
2744   " will be determined automatically if you don't specify it. If"
2745   " the option `p' or CONFIG_FILE is present, then the first block"
2746   " of Stage 2 is patched with new values of the partition and name"
2747   " of the configuration file used by the true Stage 2 (for a Stage 1.5,"
2748   " this is the name of the true Stage 2) at boot time. If STAGE2 is a Stage"
2749   " 1.5 and REAL_CONFIG_FILE is present, then the Stage 2 CONFIG_FILE is"
2750   " patched with the configuration filename REAL_CONFIG_FILE."
2751   " If the option `--force-lba' is specified, disable some sanity checks"
2752   " for LBA mode. If the option `--stage2' is specified, rewrite the Stage"
2753   " 2 via your OS's filesystem instead of the raw device."
2754 };
2755 
2756 
2757 /* ioprobe */
2758 static int
ioprobe_func(char * arg,int flags)2759 ioprobe_func (char *arg, int flags)
2760 {
2761 #ifdef GRUB_UTIL
2762 
2763   errnum = ERR_UNRECOGNIZED;
2764   return 1;
2765 
2766 #else /* ! GRUB_UTIL */
2767 
2768   unsigned short *port;
2769 
2770   /* Get the drive number.  */
2771   set_device (arg);
2772   if (errnum)
2773     return 1;
2774 
2775   /* Clean out IO_MAP.  */
2776   grub_memset ((char *) io_map, 0, IO_MAP_SIZE * sizeof (unsigned short));
2777 
2778   /* Track the int13 handler.  */
2779   track_int13 (current_drive);
2780 
2781   /* Print out the result.  */
2782   for (port = io_map; *port != 0; port++)
2783     grub_printf (" 0x%x", (unsigned int) *port);
2784 
2785   return 0;
2786 
2787 #endif /* ! GRUB_UTIL */
2788 }
2789 
2790 static struct builtin builtin_ioprobe =
2791 {
2792   "ioprobe",
2793   ioprobe_func,
2794   BUILTIN_CMDLINE,
2795   "ioprobe DRIVE",
2796   "Probe I/O ports used for the drive DRIVE."
2797 };
2798 
2799 
2800 /* kernel */
2801 static int
kernel_func(char * arg,int flags)2802 kernel_func (char *arg, int flags)
2803 {
2804   int len;
2805   kernel_t suggested_type = KERNEL_TYPE_NONE;
2806   unsigned long load_flags = 0;
2807 
2808 #ifndef AUTO_LINUX_MEM_OPT
2809   load_flags |= KERNEL_LOAD_NO_MEM_OPTION;
2810 #endif
2811 
2812   /* Deal with GNU-style long options.  */
2813   while (1)
2814     {
2815       /* If the option `--type=TYPE' is specified, convert the string to
2816 	 a kernel type.  */
2817       if (grub_memcmp (arg, "--type=", 7) == 0)
2818 	{
2819 	  arg += 7;
2820 
2821 	  if (grub_memcmp (arg, "netbsd", 6) == 0)
2822 	    suggested_type = KERNEL_TYPE_NETBSD;
2823 	  else if (grub_memcmp (arg, "freebsd", 7) == 0)
2824 	    suggested_type = KERNEL_TYPE_FREEBSD;
2825 	  else if (grub_memcmp (arg, "openbsd", 7) == 0)
2826 	    /* XXX: For now, OpenBSD is identical to NetBSD, from GRUB's
2827 	       point of view.  */
2828 	    suggested_type = KERNEL_TYPE_NETBSD;
2829 	  else if (grub_memcmp (arg, "linux", 5) == 0)
2830 	    suggested_type = KERNEL_TYPE_LINUX;
2831 	  else if (grub_memcmp (arg, "biglinux", 8) == 0)
2832 	    suggested_type = KERNEL_TYPE_BIG_LINUX;
2833 	  else if (grub_memcmp (arg, "multiboot", 9) == 0)
2834 	    suggested_type = KERNEL_TYPE_MULTIBOOT;
2835 	  else
2836 	    {
2837 	      errnum = ERR_BAD_ARGUMENT;
2838 	      return 1;
2839 	    }
2840 	}
2841       /* If the `--no-mem-option' is specified, don't pass a Linux's mem
2842 	 option automatically. If the kernel is another type, this flag
2843 	 has no effect.  */
2844       else if (grub_memcmp (arg, "--no-mem-option", 15) == 0)
2845 	load_flags |= KERNEL_LOAD_NO_MEM_OPTION;
2846       else
2847 	break;
2848 
2849       /* Try the next.  */
2850       arg = skip_to (0, arg);
2851     }
2852 
2853   len = grub_strlen (arg);
2854 
2855   /* Reset MB_CMDLINE.  */
2856   mb_cmdline = (char *) MB_CMDLINE_BUF;
2857   if (len + 1 > MB_CMDLINE_BUFLEN)
2858     {
2859       errnum = ERR_WONT_FIT;
2860       return 1;
2861     }
2862 
2863   /* Copy the command-line to MB_CMDLINE.  */
2864   grub_memmove (mb_cmdline, arg, len + 1);
2865   kernel_type = load_image (arg, mb_cmdline, suggested_type, load_flags);
2866   if (kernel_type == KERNEL_TYPE_NONE)
2867     return 1;
2868 
2869   mb_cmdline += grub_strlen(mb_cmdline) + 1;
2870   return 0;
2871 }
2872 
2873 static struct builtin builtin_kernel =
2874 {
2875   "kernel",
2876   kernel_func,
2877   BUILTIN_CMDLINE | BUILTIN_HELP_LIST,
2878   "kernel [--no-mem-option] [--type=TYPE] FILE [ARG ...]",
2879   "Attempt to load the primary boot image from FILE. The rest of the"
2880   " line is passed verbatim as the \"kernel command line\".  Any modules"
2881   " must be reloaded after using this command. The option --type is used"
2882   " to suggest what type of kernel to be loaded. TYPE must be either of"
2883   " \"netbsd\", \"freebsd\", \"openbsd\", \"linux\", \"biglinux\" and"
2884   " \"multiboot\". The option --no-mem-option tells GRUB not to pass a"
2885   " Linux's mem option automatically."
2886 };
2887 
2888 int
min_mem64_func(char * arg,int flags)2889 min_mem64_func(char *arg, int flags)
2890 {
2891 	if (!safe_parse_maxint(&arg, &min_mem64))
2892 		return (1);
2893 }
2894 
2895 static struct builtin builtin_min_mem64 =
2896 {
2897 	"min_mem64",
2898 	min_mem64_func,
2899 	BUILTIN_CMDLINE | BUILTIN_MENU | BUILTIN_SCRIPT | BUILTIN_HELP_LIST,
2900 	"min_mem64 <memory in MB>",
2901 	"Sets minimum memory (in MB) required for $ISADIR to expand to amd64, "
2902 	"even on 64-bit capable hardware."
2903 };
2904 
2905 static int
kernel_dollar_func(char * arg,int flags)2906 kernel_dollar_func (char *arg, int flags)
2907 {
2908   int err;
2909   char newarg[MAX_CMDLINE];
2910 
2911   /*
2912    * We're going to expand the arguments twice.  The first expansion, which
2913    * occurs without the benefit of knowing the ZFS object ID of the filesystem
2914    * we're booting from (if we're booting from ZFS, of course), must be
2915    * sufficient to find and read the kernel.  The second expansion will
2916    * then overwrite the command line actually set in the multiboot header with
2917    * the newly-expanded one.  Since $ZFS-BOOTFS expands differently after
2918    * zfs_open() has been called (kernel_func() -> load_image() -> grub_open() ->
2919    * zfs_open()), we need to do the second expansion so that the kernel is
2920    * given the right object ID argument.  Note that the pointer to the
2921    * command line set in the multiboot header is always MB_CMDLINE_BUF.
2922    */
2923   grub_printf("loading '%s' ...\n", arg);
2924   if ((err = expand_string(arg, newarg, MAX_CMDLINE)) != 0) {
2925     errnum = err;
2926     return (1);
2927   }
2928 
2929   if ((err = kernel_func(newarg, flags)) != 0)
2930     return (err);
2931 
2932   mb_cmdline = (char *)MB_CMDLINE_BUF;
2933   if ((err = expand_string(arg, mb_cmdline, MAX_CMDLINE)) != 0) {
2934     errnum = err;
2935     return (1);
2936   }
2937 
2938   grub_printf("loading '%s' ...\n", mb_cmdline);
2939   mb_cmdline += grub_strlen(mb_cmdline) + 1;
2940   return (0);
2941 }
2942 
2943 static struct builtin builtin_kernel_dollar =
2944 {
2945   "kernel$",
2946   kernel_dollar_func,
2947   BUILTIN_CMDLINE | BUILTIN_HELP_LIST,
2948   "kernel$ [--no-mem-option] [--type=TYPE] FILE [ARG ...]",
2949   " Just like kernel, but with variable expansion, including the legacy"
2950   " (and nonconforming) variables $ISADIR and $ZFS-BOOTFS."
2951 };
2952 
2953 
2954 /* lock */
2955 static int
lock_func(char * arg,int flags)2956 lock_func (char *arg, int flags)
2957 {
2958   if (! auth && password)
2959     {
2960       errnum = ERR_PRIVILEGED;
2961       return 1;
2962     }
2963 
2964   return 0;
2965 }
2966 
2967 static struct builtin builtin_lock =
2968 {
2969   "lock",
2970   lock_func,
2971   BUILTIN_CMDLINE,
2972   "lock",
2973   "Break a command execution unless the user is authenticated."
2974 };
2975 
2976 
2977 /* makeactive */
2978 static int
makeactive_func(char * arg,int flags)2979 makeactive_func (char *arg, int flags)
2980 {
2981   if (! make_saved_active ())
2982     return 1;
2983 
2984   return 0;
2985 }
2986 
2987 static struct builtin builtin_makeactive =
2988 {
2989   "makeactive",
2990   makeactive_func,
2991   BUILTIN_CMDLINE | BUILTIN_HELP_LIST,
2992   "makeactive",
2993   "Set the active partition on the root disk to GRUB's root device."
2994   " This command is limited to _primary_ PC partitions on a hard disk."
2995 };
2996 
2997 
2998 /* map */
2999 /* Map FROM_DRIVE to TO_DRIVE.  */
3000 static int
map_func(char * arg,int flags)3001 map_func (char *arg, int flags)
3002 {
3003   char *to_drive;
3004   char *from_drive;
3005   unsigned long to, from;
3006   int i;
3007 
3008   to_drive = arg;
3009   from_drive = skip_to (0, arg);
3010 
3011   /* Get the drive number for TO_DRIVE.  */
3012   set_device (to_drive);
3013   if (errnum)
3014     return 1;
3015   to = current_drive;
3016 
3017   /* Get the drive number for FROM_DRIVE.  */
3018   set_device (from_drive);
3019   if (errnum)
3020     return 1;
3021   from = current_drive;
3022 
3023   /* Search for an empty slot in BIOS_DRIVE_MAP.  */
3024   for (i = 0; i < DRIVE_MAP_SIZE; i++)
3025     {
3026       /* Perhaps the user wants to override the map.  */
3027       if ((bios_drive_map[i] & 0xff) == from)
3028 	break;
3029 
3030       if (! bios_drive_map[i])
3031 	break;
3032     }
3033 
3034   if (i == DRIVE_MAP_SIZE)
3035     {
3036       errnum = ERR_WONT_FIT;
3037       return 1;
3038     }
3039 
3040   if (to == from)
3041     /* If TO is equal to FROM, delete the entry.  */
3042     grub_memmove ((char *) &bios_drive_map[i], (char *) &bios_drive_map[i + 1],
3043 		  sizeof (unsigned short) * (DRIVE_MAP_SIZE - i));
3044   else
3045     bios_drive_map[i] = from | (to << 8);
3046 
3047   return 0;
3048 }
3049 
3050 static struct builtin builtin_map =
3051 {
3052   "map",
3053   map_func,
3054   BUILTIN_CMDLINE | BUILTIN_HELP_LIST,
3055   "map TO_DRIVE FROM_DRIVE",
3056   "Map the drive FROM_DRIVE to the drive TO_DRIVE. This is necessary"
3057   " when you chain-load some operating systems, such as DOS, if such an"
3058   " OS resides at a non-first drive."
3059 };
3060 
3061 
3062 #ifdef USE_MD5_PASSWORDS
3063 /* md5crypt */
3064 static int
md5crypt_func(char * arg,int flags)3065 md5crypt_func (char *arg, int flags)
3066 {
3067   char crypted[36];
3068   char key[32];
3069   unsigned int seed;
3070   int i;
3071   const char *const seedchars =
3072     "./0123456789ABCDEFGHIJKLMNOPQRST"
3073     "UVWXYZabcdefghijklmnopqrstuvwxyz";
3074 
3075   /* First create a salt.  */
3076 
3077   /* The magical prefix.  */
3078   grub_memset (crypted, 0, sizeof (crypted));
3079   grub_memmove (crypted, "$1$", 3);
3080 
3081   /* Create the length of a salt.  */
3082   seed = currticks ();
3083 
3084   /* Generate a salt.  */
3085   for (i = 0; i < 8 && seed; i++)
3086     {
3087       /* FIXME: This should be more random.  */
3088       crypted[3 + i] = seedchars[seed & 0x3f];
3089       seed >>= 6;
3090     }
3091 
3092   /* A salt must be terminated with `$', if it is less than 8 chars.  */
3093   crypted[3 + i] = '$';
3094 
3095 #ifdef DEBUG_MD5CRYPT
3096   grub_printf ("salt = %s\n", crypted);
3097 #endif
3098 
3099   /* Get a password.  */
3100   grub_memset (key, 0, sizeof (key));
3101   get_cmdline ("Password: ", key, sizeof (key) - 1, '*', 0);
3102 
3103   /* Crypt the key.  */
3104   make_md5_password (key, crypted);
3105 
3106   grub_printf ("Encrypted: %s\n", crypted);
3107   return 0;
3108 }
3109 
3110 static struct builtin builtin_md5crypt =
3111 {
3112   "md5crypt",
3113   md5crypt_func,
3114   BUILTIN_CMDLINE | BUILTIN_HELP_LIST,
3115   "md5crypt",
3116   "Generate a password in MD5 format."
3117 };
3118 #endif /* USE_MD5_PASSWORDS */
3119 
3120 
3121 /* module */
3122 static int
module_func(char * arg,int flags)3123 module_func (char *arg, int flags)
3124 {
3125   int len = grub_strlen (arg);
3126 
3127   switch (kernel_type)
3128     {
3129     case KERNEL_TYPE_MULTIBOOT:
3130       if (mb_cmdline + len + 1 > (char *) MB_CMDLINE_BUF + MB_CMDLINE_BUFLEN)
3131 	{
3132 	  errnum = ERR_WONT_FIT;
3133 	  return 1;
3134 	}
3135       grub_memmove (mb_cmdline, arg, len + 1);
3136       if (! load_module (arg, mb_cmdline))
3137 	return 1;
3138 
3139       mb_cmdline += grub_strlen(mb_cmdline) + 1;
3140       break;
3141 
3142     case KERNEL_TYPE_LINUX:
3143     case KERNEL_TYPE_BIG_LINUX:
3144       if (! load_initrd (arg))
3145 	return 1;
3146       break;
3147 
3148     default:
3149       errnum = ERR_NEED_MB_KERNEL;
3150       return 1;
3151     }
3152 
3153   return 0;
3154 }
3155 
3156 static struct builtin builtin_module =
3157 {
3158   "module",
3159   module_func,
3160   BUILTIN_CMDLINE | BUILTIN_HELP_LIST,
3161   "module FILE [ARG ...]",
3162   "Load a boot module FILE for a Multiboot format boot image (no"
3163   " interpretation of the file contents is made, so users of this"
3164   " command must know what the kernel in question expects). The"
3165   " rest of the line is passed as the \"module command line\", like"
3166   " the `kernel' command."
3167 };
3168 
3169 /* module$ */
3170 static int
module_dollar_func(char * arg,int flags)3171 module_dollar_func (char *arg, int flags)
3172 {
3173   char newarg[MAX_CMDLINE];
3174   char *cmdline_sav = mb_cmdline;
3175   int err;
3176 
3177   grub_printf("loading '%s' ...\n", arg);
3178   if ((err = expand_string(arg, newarg, MAX_CMDLINE)) != 0) {
3179     errnum = err;
3180     return (1);
3181   }
3182 
3183   if ((err = module_func(newarg, flags)) != 0)
3184     return (err);
3185 
3186   if ((err = expand_string(arg, cmdline_sav, MAX_CMDLINE)) != 0) {
3187     errnum = err;
3188     return (1);
3189   }
3190 
3191   grub_printf("loading '%s' ...\n", cmdline_sav);
3192   mb_cmdline += grub_strlen(cmdline_sav) + 1;
3193   return (0);
3194 }
3195 
3196 static struct builtin builtin_module_dollar =
3197 {
3198   "module$",
3199   module_dollar_func,
3200   BUILTIN_CMDLINE | BUILTIN_HELP_LIST,
3201   "module FILE [ARG ...]",
3202   " Just like module, but with $ISADIR expansion."
3203 };
3204 
3205 
3206 /* modulenounzip */
3207 static int
modulenounzip_func(char * arg,int flags)3208 modulenounzip_func (char *arg, int flags)
3209 {
3210   int ret;
3211 
3212 #ifndef NO_DECOMPRESSION
3213   no_decompression = 1;
3214 #endif
3215 
3216   ret = module_func (arg, flags);
3217 
3218 #ifndef NO_DECOMPRESSION
3219   no_decompression = 0;
3220 #endif
3221 
3222   return ret;
3223 }
3224 
3225 static struct builtin builtin_modulenounzip =
3226 {
3227   "modulenounzip",
3228   modulenounzip_func,
3229   BUILTIN_CMDLINE | BUILTIN_HELP_LIST,
3230   "modulenounzip FILE [ARG ...]",
3231   "The same as `module', except that automatic decompression is"
3232   " disabled."
3233 };
3234 
3235 
3236 /* pager [on|off] */
3237 static int
pager_func(char * arg,int flags)3238 pager_func (char *arg, int flags)
3239 {
3240   /* If ARG is empty, toggle the flag.  */
3241   if (! *arg)
3242     use_pager = ! use_pager;
3243   else if (grub_memcmp (arg, "on", 2) == 0)
3244     use_pager = 1;
3245   else if (grub_memcmp (arg, "off", 3) == 0)
3246     use_pager = 0;
3247   else
3248     {
3249       errnum = ERR_BAD_ARGUMENT;
3250       return 1;
3251     }
3252 
3253   grub_printf (" Internal pager is now %s\n", use_pager ? "on" : "off");
3254   return 0;
3255 }
3256 
3257 static struct builtin builtin_pager =
3258 {
3259   "pager",
3260   pager_func,
3261   BUILTIN_CMDLINE | BUILTIN_MENU | BUILTIN_HELP_LIST,
3262   "pager [FLAG]",
3263   "Toggle pager mode with no argument. If FLAG is given and its value"
3264   " is `on', turn on the mode. If FLAG is `off', turn off the mode."
3265 };
3266 
3267 
3268 /* partnew PART TYPE START LEN */
3269 static int
partnew_func(char * arg,int flags)3270 partnew_func (char *arg, int flags)
3271 {
3272   int new_type, new_start, new_len;
3273   int start_cl, start_ch, start_dh;
3274   int end_cl, end_ch, end_dh;
3275   int entry;
3276   char mbr[512];
3277 
3278   /* Convert a LBA address to a CHS address in the INT 13 format.  */
3279   auto void lba_to_chs (int lba, int *cl, int *ch, int *dh);
3280   void lba_to_chs (int lba, int *cl, int *ch, int *dh)
3281     {
3282       int cylinder, head, sector;
3283 
3284       sector = lba % buf_geom.sectors + 1;
3285       head = (lba / buf_geom.sectors) % buf_geom.heads;
3286       cylinder = lba / (buf_geom.sectors * buf_geom.heads);
3287 
3288       if (cylinder >= buf_geom.cylinders)
3289 	cylinder = buf_geom.cylinders - 1;
3290 
3291       *cl = sector | ((cylinder & 0x300) >> 2);
3292       *ch = cylinder & 0xFF;
3293       *dh = head;
3294     }
3295 
3296   /* Get the drive and the partition.  */
3297   if (! set_device (arg))
3298     return 1;
3299 
3300   /* The drive must be a hard disk.  */
3301   if (! (current_drive & 0x80))
3302     {
3303       errnum = ERR_BAD_ARGUMENT;
3304       return 1;
3305     }
3306 
3307   /* The partition must a primary partition.  */
3308   if ((current_partition >> 16) > 3
3309       || (current_partition & 0xFFFF) != 0xFFFF)
3310     {
3311       errnum = ERR_BAD_ARGUMENT;
3312       return 1;
3313     }
3314 
3315   entry = current_partition >> 16;
3316 
3317   /* Get the new partition type.  */
3318   arg = skip_to (0, arg);
3319   if (! safe_parse_maxint (&arg, &new_type))
3320     return 1;
3321 
3322   /* The partition type is unsigned char.  */
3323   if (new_type > 0xFF)
3324     {
3325       errnum = ERR_BAD_ARGUMENT;
3326       return 1;
3327     }
3328 
3329   /* Get the new partition start.  */
3330   arg = skip_to (0, arg);
3331   if (! safe_parse_maxint (&arg, &new_start))
3332     return 1;
3333 
3334   /* Get the new partition length.  */
3335   arg = skip_to (0, arg);
3336   if (! safe_parse_maxint (&arg, &new_len))
3337     return 1;
3338 
3339   /* Read the MBR.  */
3340   if (! rawread (current_drive, 0, 0, SECTOR_SIZE, mbr))
3341     return 1;
3342 
3343   /* Store the partition information in the MBR.  */
3344   lba_to_chs (new_start, &start_cl, &start_ch, &start_dh);
3345   lba_to_chs (new_start + new_len - 1, &end_cl, &end_ch, &end_dh);
3346 
3347   PC_SLICE_FLAG (mbr, entry) = 0;
3348   PC_SLICE_HEAD (mbr, entry) = start_dh;
3349   PC_SLICE_SEC (mbr, entry) = start_cl;
3350   PC_SLICE_CYL (mbr, entry) = start_ch;
3351   PC_SLICE_TYPE (mbr, entry) = new_type;
3352   PC_SLICE_EHEAD (mbr, entry) = end_dh;
3353   PC_SLICE_ESEC (mbr, entry) = end_cl;
3354   PC_SLICE_ECYL (mbr, entry) = end_ch;
3355   PC_SLICE_START (mbr, entry) = new_start;
3356   PC_SLICE_LENGTH (mbr, entry) = new_len;
3357 
3358   /* Make sure that the MBR has a valid signature.  */
3359   PC_MBR_SIG (mbr) = PC_MBR_SIGNATURE;
3360 
3361   /* Write back the MBR to the disk.  */
3362   buf_track = BUF_CACHE_INVALID;
3363   if (! rawwrite (current_drive, 0, mbr))
3364     return 1;
3365 
3366   return 0;
3367 }
3368 
3369 static struct builtin builtin_partnew =
3370 {
3371   "partnew",
3372   partnew_func,
3373   BUILTIN_CMDLINE | BUILTIN_MENU | BUILTIN_HELP_LIST,
3374   "partnew PART TYPE START LEN",
3375   "Create a primary partition at the starting address START with the"
3376   " length LEN, with the type TYPE. START and LEN are in sector units."
3377 };
3378 
3379 
3380 /* parttype PART TYPE */
3381 static int
parttype_func(char * arg,int flags)3382 parttype_func (char *arg, int flags)
3383 {
3384   int new_type;
3385   unsigned long part = 0xFFFFFF;
3386   unsigned long long start, len, offset, ext_offset, gpt_offset;
3387   int entry, type, gpt_count, gpt_size;
3388   char mbr[512];
3389 
3390   /* Get the drive and the partition.  */
3391   if (! set_device (arg))
3392     return 1;
3393 
3394   /* The drive must be a hard disk.  */
3395   if (! (current_drive & 0x80))
3396     {
3397       errnum = ERR_BAD_ARGUMENT;
3398       return 1;
3399     }
3400 
3401   /* The partition must be a PC slice.  */
3402   if ((current_partition >> 16) == 0xFF
3403       || (current_partition & 0xFFFF) != 0xFFFF)
3404     {
3405       errnum = ERR_BAD_ARGUMENT;
3406       return 1;
3407     }
3408 
3409   /* Get the new partition type.  */
3410   arg = skip_to (0, arg);
3411   if (! safe_parse_maxint (&arg, &new_type))
3412     return 1;
3413 
3414   /* The partition type is unsigned char.  */
3415   if (new_type > 0xFF)
3416     {
3417       errnum = ERR_BAD_ARGUMENT;
3418       return 1;
3419     }
3420 
3421   /* Look for the partition.  */
3422   while (next_partition (current_drive, 0xFFFFFF, &part, &type,
3423 			 &start, &len, &offset, &entry,
3424 			 &ext_offset, &gpt_offset, &gpt_count, &gpt_size, mbr))
3425     {
3426 	  /* The partition may not be a GPT partition.  */
3427 	  if (gpt_offset != 0)
3428 	    {
3429 		errnum = ERR_BAD_ARGUMENT;
3430 		return 1;
3431 	    }
3432 
3433       if (part == current_partition)
3434 	{
3435 	  /* Found.  */
3436 
3437 	  /* Set the type to NEW_TYPE.  */
3438 	  PC_SLICE_TYPE (mbr, entry) = new_type;
3439 
3440 	  /* Write back the MBR to the disk.  */
3441 	  buf_track = BUF_CACHE_INVALID;
3442 	  if (! rawwrite (current_drive, offset, mbr))
3443 	    return 1;
3444 
3445 	  /* Succeed.  */
3446 	  return 0;
3447 	}
3448     }
3449 
3450   /* The partition was not found.  ERRNUM was set by next_partition.  */
3451   return 1;
3452 }
3453 
3454 static struct builtin builtin_parttype =
3455 {
3456   "parttype",
3457   parttype_func,
3458   BUILTIN_CMDLINE | BUILTIN_MENU | BUILTIN_HELP_LIST,
3459   "parttype PART TYPE",
3460   "Change the type of the partition PART to TYPE."
3461 };
3462 
3463 
3464 /* password */
3465 static int
password_func(char * arg,int flags)3466 password_func (char *arg, int flags)
3467 {
3468   int len;
3469   password_t type = PASSWORD_PLAIN;
3470 
3471 #ifdef USE_MD5_PASSWORDS
3472   if (grub_memcmp (arg, "--md5", 5) == 0)
3473     {
3474       type = PASSWORD_MD5;
3475       arg = skip_to (0, arg);
3476     }
3477 #endif
3478   if (grub_memcmp (arg, "--", 2) == 0)
3479     {
3480       type = PASSWORD_UNSUPPORTED;
3481       arg = skip_to (0, arg);
3482     }
3483 
3484   if ((flags & (BUILTIN_CMDLINE | BUILTIN_SCRIPT)) != 0)
3485     {
3486       /* Do password check! */
3487       char entered[32];
3488 
3489       /* Wipe out any previously entered password */
3490       entered[0] = 0;
3491       get_cmdline ("Password: ", entered, 31, '*', 0);
3492 
3493       nul_terminate (arg);
3494       if (check_password (entered, arg, type) != 0)
3495 	{
3496 	  errnum = ERR_PRIVILEGED;
3497 	  return 1;
3498 	}
3499     }
3500   else
3501     {
3502       len = grub_strlen (arg);
3503 
3504       /* PASSWORD NUL NUL ... */
3505       if (len + 2 > PASSWORD_BUFLEN)
3506 	{
3507 	  errnum = ERR_WONT_FIT;
3508 	  return 1;
3509 	}
3510 
3511       /* Copy the password and clear the rest of the buffer.  */
3512       password = (char *) PASSWORD_BUF;
3513       grub_memmove (password, arg, len);
3514       grub_memset (password + len, 0, PASSWORD_BUFLEN - len);
3515       password_type = type;
3516     }
3517   return 0;
3518 }
3519 
3520 static struct builtin builtin_password =
3521 {
3522   "password",
3523   password_func,
3524   BUILTIN_MENU | BUILTIN_CMDLINE | BUILTIN_NO_ECHO,
3525   "password [--md5] PASSWD [FILE]",
3526   "If used in the first section of a menu file, disable all"
3527   " interactive editing control (menu entry editor and"
3528   " command line). If the password PASSWD is entered, it loads the"
3529   " FILE as a new config file and restarts the GRUB Stage 2. If you"
3530   " omit the argument FILE, then GRUB just unlocks privileged"
3531   " instructions.  You can also use it in the script section, in"
3532   " which case it will ask for the password, before continueing."
3533   " The option --md5 tells GRUB that PASSWD is encrypted with"
3534   " md5crypt."
3535 };
3536 
3537 
3538 /* pause */
3539 static int
pause_func(char * arg,int flags)3540 pause_func (char *arg, int flags)
3541 {
3542   printf("%s\n", arg);
3543 
3544   /* If ESC is returned, then abort this entry.  */
3545   if (ASCII_CHAR (getkey ()) == 27)
3546     return 1;
3547 
3548   return 0;
3549 }
3550 
3551 static struct builtin builtin_pause =
3552 {
3553   "pause",
3554   pause_func,
3555   BUILTIN_CMDLINE | BUILTIN_NO_ECHO,
3556   "pause [MESSAGE ...]",
3557   "Print MESSAGE, then wait until a key is pressed."
3558 };
3559 
3560 
3561 #ifdef GRUB_UTIL
3562 /* quit */
3563 static int
quit_func(char * arg,int flags)3564 quit_func (char *arg, int flags)
3565 {
3566   stop ();
3567 
3568   /* Never reach here.  */
3569   return 0;
3570 }
3571 
3572 static struct builtin builtin_quit =
3573 {
3574   "quit",
3575   quit_func,
3576   BUILTIN_CMDLINE | BUILTIN_HELP_LIST,
3577   "quit",
3578   "Exit from the GRUB shell."
3579 };
3580 #endif /* GRUB_UTIL */
3581 
3582 
3583 #ifdef SUPPORT_NETBOOT
3584 /* rarp */
3585 static int
rarp_func(char * arg,int flags)3586 rarp_func (char *arg, int flags)
3587 {
3588   if (! rarp ())
3589     {
3590       if (errnum == ERR_NONE)
3591 	errnum = ERR_DEV_VALUES;
3592 
3593       return 1;
3594     }
3595 
3596   /* Notify the configuration.  */
3597   print_network_configuration ();
3598   return 0;
3599 }
3600 
3601 static struct builtin builtin_rarp =
3602 {
3603   "rarp",
3604   rarp_func,
3605   BUILTIN_CMDLINE | BUILTIN_MENU | BUILTIN_HELP_LIST,
3606   "rarp",
3607   "Initialize a network device via RARP."
3608 };
3609 #endif /* SUPPORT_NETBOOT */
3610 
3611 
3612 static int
read_func(char * arg,int flags)3613 read_func (char *arg, int flags)
3614 {
3615   int addr;
3616 
3617   if (! safe_parse_maxint (&arg, &addr))
3618     return 1;
3619 
3620   grub_printf ("Address 0x%x: Value 0x%x\n",
3621 	       addr, *((unsigned *) RAW_ADDR (addr)));
3622   return 0;
3623 }
3624 
3625 static struct builtin builtin_read =
3626 {
3627   "read",
3628   read_func,
3629   BUILTIN_CMDLINE,
3630   "read ADDR",
3631   "Read a 32-bit value from memory at address ADDR and"
3632   " display it in hex format."
3633 };
3634 
3635 
3636 /* reboot */
3637 static int
reboot_func(char * arg,int flags)3638 reboot_func (char *arg, int flags)
3639 {
3640   grub_reboot ();
3641 
3642   /* Never reach here.  */
3643   return 1;
3644 }
3645 
3646 static struct builtin builtin_reboot =
3647 {
3648   "reboot",
3649   reboot_func,
3650   BUILTIN_CMDLINE | BUILTIN_HELP_LIST,
3651   "reboot",
3652   "Reboot your system."
3653 };
3654 
3655 
3656 /* Print the root device information.  */
3657 static void
print_root_device(void)3658 print_root_device (void)
3659 {
3660   if (saved_drive == NETWORK_DRIVE)
3661     {
3662       /* Network drive.  */
3663       grub_printf (" (nd):");
3664     }
3665   else if (saved_drive & 0x80)
3666     {
3667       /* Hard disk drive.  */
3668       grub_printf (" (hd%d", saved_drive - 0x80);
3669 
3670       if ((saved_partition & 0xFF0000) != 0xFF0000)
3671 	grub_printf (",%d", saved_partition >> 16);
3672 
3673       if ((saved_partition & 0x00FF00) != 0x00FF00)
3674 	grub_printf (",%c", ((saved_partition >> 8) & 0xFF) + 'a');
3675 
3676       grub_printf ("):");
3677     }
3678   else
3679     {
3680       /* Floppy disk drive.  */
3681       grub_printf (" (fd%d):", saved_drive);
3682     }
3683 
3684   /* Print the filesystem information.  */
3685   current_partition = saved_partition;
3686   current_drive = saved_drive;
3687   print_fsys_type ();
3688 }
3689 
3690 static int
real_root_func(char * arg,int attempt_mount)3691 real_root_func (char *arg, int attempt_mount)
3692 {
3693   int hdbias = 0;
3694   char *biasptr;
3695   char *next;
3696 
3697   /* If ARG is empty, just print the current root device.  */
3698   if (! *arg)
3699     {
3700       print_root_device ();
3701       return 0;
3702     }
3703 
3704   /* Call set_device to get the drive and the partition in ARG.  */
3705   next = set_device (arg);
3706   if (! next)
3707     return 1;
3708 
3709   /* Ignore ERR_FSYS_MOUNT.  */
3710   if (attempt_mount)
3711     {
3712       if (! open_device () && errnum != ERR_FSYS_MOUNT)
3713 	return 1;
3714     }
3715   else
3716     {
3717       /* This is necessary, because the location of a partition table
3718 	 must be set appropriately.  */
3719       if (open_partition ())
3720 	{
3721 	  set_bootdev (0);
3722 	  if (errnum)
3723 	    return 1;
3724 	}
3725     }
3726 
3727   /* Clear ERRNUM.  */
3728   errnum = 0;
3729   saved_partition = current_partition;
3730   saved_drive = current_drive;
3731 
3732   if (attempt_mount)
3733     {
3734       /* BSD and chainloading evil hacks !!  */
3735       biasptr = skip_to (0, next);
3736       safe_parse_maxint (&biasptr, &hdbias);
3737       errnum = 0;
3738       bootdev = set_bootdev (hdbias);
3739       if (errnum)
3740 	return 1;
3741 
3742       /* Print the type of the filesystem.  */
3743       print_fsys_type ();
3744     }
3745 
3746   return 0;
3747 }
3748 
3749 static int
root_func(char * arg,int flags)3750 root_func (char *arg, int flags)
3751 {
3752   is_zfs_mount = 0;
3753   return real_root_func (arg, 1);
3754 }
3755 
3756 static struct builtin builtin_root =
3757 {
3758   "root",
3759   root_func,
3760   BUILTIN_CMDLINE | BUILTIN_HELP_LIST,
3761   "root [DEVICE [HDBIAS]]",
3762   "Set the current \"root device\" to the device DEVICE, then"
3763   " attempt to mount it to get the partition size (for passing the"
3764   " partition descriptor in `ES:ESI', used by some chain-loaded"
3765   " bootloaders), the BSD drive-type (for booting BSD kernels using"
3766   " their native boot format), and correctly determine "
3767   " the PC partition where a BSD sub-partition is located. The"
3768   " optional HDBIAS parameter is a number to tell a BSD kernel"
3769   " how many BIOS drive numbers are on controllers before the current"
3770   " one. For example, if there is an IDE disk and a SCSI disk, and your"
3771   " FreeBSD root partition is on the SCSI disk, then use a `1' for HDBIAS."
3772 };
3773 
3774 
3775 /* findroot */
3776 int
findroot_func(char * arg,int flags)3777 findroot_func (char *arg, int flags)
3778 {
3779   int ret;
3780   char root[32];
3781 
3782   if (grub_strlen(arg) >= BOOTSIGN_ARGLEN) {
3783   	errnum = ERR_BAD_ARGUMENT;
3784 	return 1;
3785   }
3786 
3787   if (arg[0] == '\0') {
3788   	errnum = ERR_BAD_ARGUMENT;
3789 	return 1;
3790   }
3791 
3792   find_best_root = 1;
3793   best_drive = 0;
3794   best_part = 0;
3795   ret = find_common(arg, root, 1, flags);
3796   if (ret != 0)
3797 	return (ret);
3798   find_best_root = 0;
3799 
3800   return real_root_func (root, 1);
3801 }
3802 
3803 static struct builtin builtin_findroot =
3804 {
3805   "findroot",
3806   findroot_func,
3807   BUILTIN_CMDLINE | BUILTIN_HELP_LIST,
3808   "findroot  <SIGNATURE | (SIGNATURE,partition[,slice])>",
3809   "Searches across all partitions for the file name SIGNATURE."
3810   " GRUB looks only in the directory /boot/grub/bootsign for the"
3811   " filename and it stops as soon as it finds the first instance of"
3812   " the file - so to be useful the name of the signature file must be"
3813   " unique across all partitions. Once the signature file is found,"
3814   " GRUB invokes the \"root\" command on that partition."
3815   " An optional partition and slice may be specified to optimize the search."
3816 };
3817 
3818 
3819 /*
3820  * COMMAND to override the default root filesystem for ZFS
3821  *	bootfs pool/fs
3822  */
3823 static int
bootfs_func(char * arg,int flags)3824 bootfs_func (char *arg, int flags)
3825 {
3826 	int hdbias = 0;
3827 	char *biasptr;
3828 	char *next;
3829 
3830 	if (! *arg) {
3831 	    if (current_bootfs[0] != '\0')
3832 		grub_printf ("The zfs boot filesystem is set to '%s'.\n",
3833 				current_bootfs);
3834 	    else if (current_rootpool[0] != 0 && current_bootfs_obj != 0)
3835 		grub_printf("The zfs boot filesystem is <default: %s/%u>.",
3836 				current_rootpool, current_bootfs_obj);
3837 	    else
3838 		grub_printf ("The zfs boot filesystem will be derived from "
3839 			"the default bootfs pool property.\n");
3840 
3841 	    return (1);
3842 	}
3843 
3844 	/* Verify the zfs filesystem name */
3845 	if (arg[0] == '/' || arg[0] == '\0') {
3846 		errnum = ERR_BAD_ARGUMENT;
3847 		return 0;
3848 	}
3849 	if (current_rootpool[0] != 0 && grub_strncmp(arg,
3850 	    current_rootpool, strlen(current_rootpool))) {
3851 		errnum = ERR_BAD_ARGUMENT;
3852 		return 0;
3853 	}
3854 
3855 	grub_memmove(current_bootfs, arg, MAXNAMELEN);
3856 
3857 	return (1);
3858 }
3859 
3860 static struct builtin builtin_bootfs =
3861 {
3862   "bootfs",
3863   bootfs_func,
3864   BUILTIN_CMDLINE | BUILTIN_HELP_LIST,
3865   "bootfs [ZFSBOOTFS]",
3866   "Set the current zfs boot filesystem to ZFSBOOTFS (rootpool/rootfs)."
3867 };
3868 
3869 
3870 /* rootnoverify */
3871 static int
rootnoverify_func(char * arg,int flags)3872 rootnoverify_func (char *arg, int flags)
3873 {
3874   return real_root_func (arg, 0);
3875 }
3876 
3877 static struct builtin builtin_rootnoverify =
3878 {
3879   "rootnoverify",
3880   rootnoverify_func,
3881   BUILTIN_CMDLINE | BUILTIN_HELP_LIST,
3882   "rootnoverify [DEVICE [HDBIAS]]",
3883   "Similar to `root', but don't attempt to mount the partition. This"
3884   " is useful for when an OS is outside of the area of the disk that"
3885   " GRUB can read, but setting the correct root device is still"
3886   " desired. Note that the items mentioned in `root' which"
3887   " derived from attempting the mount will NOT work correctly."
3888 };
3889 
3890 
3891 /* savedefault */
3892 static int
savedefault_func(char * arg,int flags)3893 savedefault_func (char *arg, int flags)
3894 {
3895 #if !defined(SUPPORT_DISKLESS) && !defined(GRUB_UTIL)
3896   unsigned long tmp_drive = saved_drive;
3897   unsigned long tmp_partition = saved_partition;
3898   char *default_file = (char *) DEFAULT_FILE_BUF;
3899   char buf[10];
3900   char sect[SECTOR_SIZE];
3901   int entryno;
3902   int sector_count = 0;
3903   unsigned long long saved_sectors[2];
3904   int saved_offsets[2];
3905   int saved_lengths[2];
3906 
3907   /* not supported for zfs root */
3908   if (is_zfs_mount == 1) {
3909 	return (0); /* no-op */
3910   }
3911 
3912   /* Save sector information about at most two sectors.  */
3913   auto void disk_read_savesect_func (unsigned long long sector, int offset,
3914       int length);
3915   void disk_read_savesect_func (unsigned long long sector, int offset, int length)
3916     {
3917       if (sector_count < 2)
3918 	{
3919 	  saved_sectors[sector_count] = sector;
3920 	  saved_offsets[sector_count] = offset;
3921 	  saved_lengths[sector_count] = length;
3922 	}
3923       sector_count++;
3924     }
3925 
3926   /* This command is only useful when you boot an entry from the menu
3927      interface.  */
3928   if (! (flags & BUILTIN_SCRIPT))
3929     {
3930       errnum = ERR_UNRECOGNIZED;
3931       return 1;
3932     }
3933 
3934   /* Determine a saved entry number.  */
3935   if (*arg)
3936     {
3937       if (grub_memcmp (arg, "fallback", sizeof ("fallback") - 1) == 0)
3938 	{
3939 	  int i;
3940 	  int index = 0;
3941 
3942 	  for (i = 0; i < MAX_FALLBACK_ENTRIES; i++)
3943 	    {
3944 	      if (fallback_entries[i] < 0)
3945 		break;
3946 	      if (fallback_entries[i] == current_entryno)
3947 		{
3948 		  index = i + 1;
3949 		  break;
3950 		}
3951 	    }
3952 
3953 	  if (index >= MAX_FALLBACK_ENTRIES || fallback_entries[index] < 0)
3954 	    {
3955 	      /* This is the last.  */
3956 	      errnum = ERR_BAD_ARGUMENT;
3957 	      return 1;
3958 	    }
3959 
3960 	  entryno = fallback_entries[index];
3961 	}
3962       else if (! safe_parse_maxint (&arg, &entryno))
3963 	return 1;
3964     }
3965   else
3966     entryno = current_entryno;
3967 
3968   /* Open the default file.  */
3969   saved_drive = boot_drive;
3970   saved_partition = install_partition;
3971   if (grub_open (default_file))
3972     {
3973       int len;
3974 
3975       disk_read_hook = disk_read_savesect_func;
3976       len = grub_read (buf, sizeof (buf));
3977       disk_read_hook = 0;
3978       grub_close ();
3979 
3980       if (len != sizeof (buf))
3981 	{
3982 	  /* This is too small. Do not modify the file manually, please!  */
3983 	  errnum = ERR_READ;
3984 	  goto fail;
3985 	}
3986 
3987       if (sector_count > 2)
3988 	{
3989 	  /* Is this possible?! Too fragmented!  */
3990 	  errnum = ERR_FSYS_CORRUPT;
3991 	  goto fail;
3992 	}
3993 
3994       /* Set up a string to be written.  */
3995       grub_memset (buf, '\n', sizeof (buf));
3996       grub_sprintf (buf, "%d", entryno);
3997 
3998       if (saved_lengths[0] < sizeof (buf))
3999 	{
4000 	  /* The file is anchored to another file and the first few bytes
4001 	     are spanned in two sectors. Uggh...  */
4002 	  if (! rawread (current_drive, saved_sectors[0], 0, SECTOR_SIZE,
4003 			 sect))
4004 	    goto fail;
4005 	  grub_memmove (sect + saved_offsets[0], buf, saved_lengths[0]);
4006 	  if (! rawwrite (current_drive, saved_sectors[0], sect))
4007 	    goto fail;
4008 
4009 	  if (! rawread (current_drive, saved_sectors[1], 0, SECTOR_SIZE,
4010 			 sect))
4011 	    goto fail;
4012 	  grub_memmove (sect + saved_offsets[1],
4013 			buf + saved_lengths[0],
4014 			sizeof (buf) - saved_lengths[0]);
4015 	  if (! rawwrite (current_drive, saved_sectors[1], sect))
4016 	    goto fail;
4017 	}
4018       else
4019 	{
4020 	  /* This is a simple case. It fits into a single sector.  */
4021 	  if (! rawread (current_drive, saved_sectors[0], 0, SECTOR_SIZE,
4022 			 sect))
4023 	    goto fail;
4024 	  grub_memmove (sect + saved_offsets[0], buf, sizeof (buf));
4025 	  if (! rawwrite (current_drive, saved_sectors[0], sect))
4026 	    goto fail;
4027 	}
4028 
4029       /* Clear the cache.  */
4030       buf_track = BUF_CACHE_INVALID;
4031     }
4032 
4033  fail:
4034   saved_drive = tmp_drive;
4035   saved_partition = tmp_partition;
4036   return errnum;
4037 #else /* ! SUPPORT_DISKLESS && ! GRUB_UTIL */
4038   errnum = ERR_UNRECOGNIZED;
4039   return 1;
4040 #endif /* ! SUPPORT_DISKLESS && ! GRUB_UTIL */
4041 }
4042 
4043 static struct builtin builtin_savedefault =
4044 {
4045   "savedefault",
4046   savedefault_func,
4047   BUILTIN_CMDLINE,
4048   "savedefault [NUM | `fallback']",
4049   "Save the current entry as the default boot entry if no argument is"
4050   " specified. If a number is specified, this number is saved. If"
4051   " `fallback' is used, next fallback entry is saved."
4052 };
4053 
4054 
4055 #ifdef SUPPORT_SERIAL
4056 /* serial */
4057 static int
serial_func(char * arg,int flags)4058 serial_func (char *arg, int flags)
4059 {
4060   int i;
4061   int units[SERIAL_MAX_PORTS];
4062   unsigned short ports[SERIAL_MAX_PORTS];
4063   unsigned int speed = 9600;
4064   int word_len = UART_8BITS_WORD;
4065   int parity = UART_NO_PARITY;
4066   int stop_bit_len = UART_1_STOP_BIT;
4067 
4068   for (i = 0; i < SERIAL_MAX_PORTS; ++i)
4069     {
4070       units[i] = -1;
4071       ports[i] = 0;
4072     }
4073 
4074   /* Process GNU-style long options.
4075      FIXME: We should implement a getopt-like function, to avoid
4076      duplications.  */
4077   while (1)
4078     {
4079       if (grub_memcmp (arg, "--unit=", sizeof ("--unit=") - 1) == 0)
4080 	{
4081 	  char *p = arg + sizeof ("--unit=") - 1;
4082 	  int unit;
4083 
4084 	  i = 0;
4085 	  do
4086 	    {
4087 	      if (i >= SERIAL_MAX_PORTS)
4088 		{
4089 		  errnum = ERR_DEV_FORMAT;
4090 		  return 1;
4091 		}
4092 
4093 	      if (! safe_parse_maxint (&p, &unit))
4094 	        return 1;
4095 
4096 	      if (unit < 0 || unit > 3)
4097 	        {
4098 	          errnum = ERR_DEV_VALUES;
4099 	          return 1;
4100 	        }
4101 
4102 	      units[i++] = unit;
4103 	    }
4104 	  while (*p++ == ',');
4105 	}
4106       else if (grub_memcmp (arg, "--speed=", sizeof ("--speed=") - 1) == 0)
4107 	{
4108 	  char *p = arg + sizeof ("--speed=") - 1;
4109 	  int num;
4110 
4111 	  if (! safe_parse_maxint (&p, &num))
4112 	    return 1;
4113 
4114 	  speed = (unsigned int) num;
4115 	}
4116       else if (grub_memcmp (arg, "--port=", sizeof ("--port=") - 1) == 0)
4117 	{
4118 	  char *p = arg + sizeof ("--port=") - 1;
4119 	  int num;
4120 
4121 	  i = 0;
4122 	  do
4123 	    {
4124 	      if (i >= SERIAL_MAX_PORTS)
4125 		{
4126 		  errnum = ERR_DEV_FORMAT;
4127 		  return 1;
4128 		}
4129 
4130 	      if (! safe_parse_maxint (&p, &num))
4131 	        return 1;
4132 
4133 	      if (num > 0xffff || num <= 0)
4134 		{
4135 		  errnum = ERR_DEV_VALUES;
4136 		  return 1;
4137 		}
4138 
4139 	      ports[i++] = (unsigned short) num;
4140 	    }
4141 	  while (*p++ == ',');
4142 	}
4143       else if (grub_memcmp (arg, "--word=", sizeof ("--word=") - 1) == 0)
4144 	{
4145 	  char *p = arg + sizeof ("--word=") - 1;
4146 	  int len;
4147 
4148 	  if (! safe_parse_maxint (&p, &len))
4149 	    return 1;
4150 
4151 	  switch (len)
4152 	    {
4153 	    case 5: word_len = UART_5BITS_WORD; break;
4154 	    case 6: word_len = UART_6BITS_WORD; break;
4155 	    case 7: word_len = UART_7BITS_WORD; break;
4156 	    case 8: word_len = UART_8BITS_WORD; break;
4157 	    default:
4158 	      errnum = ERR_BAD_ARGUMENT;
4159 	      return 1;
4160 	    }
4161 	}
4162       else if (grub_memcmp (arg, "--stop=", sizeof ("--stop=") - 1) == 0)
4163 	{
4164 	  char *p = arg + sizeof ("--stop=") - 1;
4165 	  int len;
4166 
4167 	  if (! safe_parse_maxint (&p, &len))
4168 	    return 1;
4169 
4170 	  switch (len)
4171 	    {
4172 	    case 1: stop_bit_len = UART_1_STOP_BIT; break;
4173 	    case 2: stop_bit_len = UART_2_STOP_BITS; break;
4174 	    default:
4175 	      errnum = ERR_BAD_ARGUMENT;
4176 	      return 1;
4177 	    }
4178 	}
4179       else if (grub_memcmp (arg, "--parity=", sizeof ("--parity=") - 1) == 0)
4180 	{
4181 	  char *p = arg + sizeof ("--parity=") - 1;
4182 
4183 	  if (grub_memcmp (p, "no", sizeof ("no") - 1) == 0)
4184 	    parity = UART_NO_PARITY;
4185 	  else if (grub_memcmp (p, "odd", sizeof ("odd") - 1) == 0)
4186 	    parity = UART_ODD_PARITY;
4187 	  else if (grub_memcmp (p, "even", sizeof ("even") - 1) == 0)
4188 	    parity = UART_EVEN_PARITY;
4189 	  else
4190 	    {
4191 	      errnum = ERR_BAD_ARGUMENT;
4192 	      return 1;
4193 	    }
4194 	}
4195 # ifdef GRUB_UTIL
4196       /* In the grub shell, don't use any port number but open a tty
4197 	 device instead.  */
4198       else if (grub_memcmp (arg, "--device=", sizeof ("--device=") - 1) == 0)
4199 	{
4200 	  char *p = arg + sizeof ("--device=") - 1;
4201 	  char dev[256];	/* XXX */
4202 	  char *q = dev;
4203 
4204 	  while (*p && ! grub_isspace (*p))
4205 	    *q++ = *p++;
4206 
4207 	  *q = 0;
4208 	  serial_set_device (dev);
4209 	}
4210 # endif /* GRUB_UTIL */
4211       else
4212 	break;
4213 
4214       arg = skip_to (0, arg);
4215     }
4216 
4217   if (units[0] == -1 && ports[0] == 0)
4218     units[0] = 0;
4219 
4220   for (i = 0; i < SERIAL_MAX_PORTS; ++i)
4221     {
4222       if (units[i] != -1)
4223 	ports[i] = serial_hw_get_port (units[i]);
4224       if (ports[i] == 0)
4225 	continue;
4226 
4227       if (serial_hw_init (ports[i], speed, word_len, parity, stop_bit_len))
4228 	break;
4229     }
4230 
4231   if (i >= SERIAL_MAX_PORTS)
4232     {
4233       errnum = ERR_BAD_ARGUMENT;
4234       return 1;
4235     }
4236 
4237   return 0;
4238 }
4239 
4240 static struct builtin builtin_serial =
4241 {
4242   "serial",
4243   serial_func,
4244   BUILTIN_MENU | BUILTIN_CMDLINE | BUILTIN_HELP_LIST,
4245   "serial [[--unit=UNIT[,UNIT...]] | [--port=PORT[,PORT...]]] [--speed=SPEED] [--word=WORD] [--parity=PARITY] [--stop=STOP] [--device=DEV]",
4246   "Initialize a serial device. UNIT is a digit that specifies which serial"
4247   " device is used (e.g. 0 == ttya (aka COM1)). If you need to specify the port"
4248   " number, set it by --port. Either but not both of --unit and --port is"
4249   " permitted; --unit takes precedence. Multiple devices may be specified,"
4250   " separated by commas; the first working device in the list will be used"
4251   " and the rest ignored. SPEED is the DTE-DTE speed. WORD is the word length,"
4252   " PARITY is the type of parity, which is one of `no', `odd' and `even'."
4253   " STOP is the length of stop bit(s). The option --device can be used only"
4254   " in the grub shell, which specifies the file name of a tty device. The"
4255   " default values are ttya, 9600, 8N1."
4256 };
4257 #endif /* SUPPORT_SERIAL */
4258 
4259 
4260 /* setkey */
4261 struct keysym
4262 {
4263   char *unshifted_name;			/* the name in unshifted state */
4264   char *shifted_name;			/* the name in shifted state */
4265   unsigned char unshifted_ascii;	/* the ascii code in unshifted state */
4266   unsigned char shifted_ascii;		/* the ascii code in shifted state */
4267   unsigned char keycode;		/* keyboard scancode */
4268 };
4269 
4270 /* The table for key symbols. If the "shifted" member of an entry is
4271    NULL, the entry does not have shifted state.  */
4272 static struct keysym keysym_table[] =
4273 {
4274   {"escape",		0,		0x1b,	0,	0x01},
4275   {"1",			"exclam",	'1',	'!',	0x02},
4276   {"2",			"at",		'2',	'@',	0x03},
4277   {"3",			"numbersign",	'3',	'#',	0x04},
4278   {"4",			"dollar",	'4',	'$',	0x05},
4279   {"5",			"percent",	'5',	'%',	0x06},
4280   {"6",			"caret",	'6',	'^',	0x07},
4281   {"7",			"ampersand",	'7',	'&',	0x08},
4282   {"8",			"asterisk",	'8',	'*',	0x09},
4283   {"9",			"parenleft",	'9',	'(',	0x0a},
4284   {"0",			"parenright",	'0',	')',	0x0b},
4285   {"minus",		"underscore",	'-',	'_',	0x0c},
4286   {"equal",		"plus",		'=',	'+',	0x0d},
4287   {"backspace",		0,		'\b',	0,	0x0e},
4288   {"tab",		0,		'\t',	0,	0x0f},
4289   {"q",			"Q",		'q',	'Q',	0x10},
4290   {"w",			"W",		'w',	'W',	0x11},
4291   {"e",			"E",		'e',	'E',	0x12},
4292   {"r",			"R",		'r',	'R',	0x13},
4293   {"t",			"T",		't',	'T',	0x14},
4294   {"y",			"Y",		'y',	'Y',	0x15},
4295   {"u",			"U",		'u',	'U',	0x16},
4296   {"i",			"I",		'i',	'I',	0x17},
4297   {"o",			"O",		'o',	'O',	0x18},
4298   {"p",			"P",		'p',	'P',	0x19},
4299   {"bracketleft",	"braceleft",	'[',	'{',	0x1a},
4300   {"bracketright",	"braceright",	']',	'}',	0x1b},
4301   {"enter",		0,		'\n',	0,	0x1c},
4302   {"control",		0,		0,	0,	0x1d},
4303   {"a",			"A",		'a',	'A',	0x1e},
4304   {"s",			"S",		's',	'S',	0x1f},
4305   {"d",			"D",		'd',	'D',	0x20},
4306   {"f",			"F",		'f',	'F',	0x21},
4307   {"g",			"G",		'g',	'G',	0x22},
4308   {"h",			"H",		'h',	'H',	0x23},
4309   {"j",			"J",		'j',	'J',	0x24},
4310   {"k",			"K",		'k',	'K',	0x25},
4311   {"l",			"L",		'l',	'L',	0x26},
4312   {"semicolon",		"colon",	';',	':',	0x27},
4313   {"quote",		"doublequote",	'\'',	'"',	0x28},
4314   {"backquote",		"tilde",	'`',	'~',	0x29},
4315   {"shift",		0,		0,	0,	0x2a},
4316   {"backslash",		"bar",		'\\',	'|',	0x2b},
4317   {"z",			"Z",		'z',	'Z',	0x2c},
4318   {"x",			"X",		'x',	'X',	0x2d},
4319   {"c",			"C",		'c',	'C',	0x2e},
4320   {"v",			"V",		'v',	'V',	0x2f},
4321   {"b",			"B",		'b',	'B',	0x30},
4322   {"n",			"N",		'n',	'N',	0x31},
4323   {"m",			"M",		'm',	'M',	0x32},
4324   {"comma",		"less",		',',	'<',	0x33},
4325   {"period",		"greater",	'.',	'>',	0x34},
4326   {"slash",		"question",	'/',	'?',	0x35},
4327   {"alt",		0,		0,	0,	0x38},
4328   {"space",		0,		' ',	0,	0x39},
4329   {"capslock",		0,		0,	0,	0x3a},
4330   {"F1",		0,		0,	0,	0x3b},
4331   {"F2",		0,		0,	0,	0x3c},
4332   {"F3",		0,		0,	0,	0x3d},
4333   {"F4",		0,		0,	0,	0x3e},
4334   {"F5",		0,		0,	0,	0x3f},
4335   {"F6",		0,		0,	0,	0x40},
4336   {"F7",		0,		0,	0,	0x41},
4337   {"F8",		0,		0,	0,	0x42},
4338   {"F9",		0,		0,	0,	0x43},
4339   {"F10",		0,		0,	0,	0x44},
4340   /* Caution: do not add NumLock here! we cannot deal with it properly.  */
4341   {"delete",		0,		0x7f,	0,	0x53}
4342 };
4343 
4344 static int
setkey_func(char * arg,int flags)4345 setkey_func (char *arg, int flags)
4346 {
4347   char *to_key, *from_key;
4348   int to_code, from_code;
4349   int map_in_interrupt = 0;
4350 
4351   auto int find_key_code (char *key);
4352   auto int find_ascii_code (char *key);
4353 
4354   auto int find_key_code (char *key)
4355     {
4356       int i;
4357 
4358       for (i = 0; i < sizeof (keysym_table) / sizeof (keysym_table[0]); i++)
4359 	{
4360 	  if (keysym_table[i].unshifted_name &&
4361 	      grub_strcmp (key, keysym_table[i].unshifted_name) == 0)
4362 	    return keysym_table[i].keycode;
4363 	  else if (keysym_table[i].shifted_name &&
4364 		   grub_strcmp (key, keysym_table[i].shifted_name) == 0)
4365 	    return keysym_table[i].keycode;
4366 	}
4367 
4368       return 0;
4369     }
4370 
4371   auto int find_ascii_code (char *key)
4372     {
4373       int i;
4374 
4375       for (i = 0; i < sizeof (keysym_table) / sizeof (keysym_table[0]); i++)
4376 	{
4377 	  if (keysym_table[i].unshifted_name &&
4378 	      grub_strcmp (key, keysym_table[i].unshifted_name) == 0)
4379 	    return keysym_table[i].unshifted_ascii;
4380 	  else if (keysym_table[i].shifted_name &&
4381 		   grub_strcmp (key, keysym_table[i].shifted_name) == 0)
4382 	    return keysym_table[i].shifted_ascii;
4383 	}
4384 
4385       return 0;
4386     }
4387 
4388   to_key = arg;
4389   from_key = skip_to (0, to_key);
4390 
4391   if (! *to_key)
4392     {
4393       /* If the user specifies no argument, reset the key mappings.  */
4394       grub_memset (bios_key_map, 0, KEY_MAP_SIZE * sizeof (unsigned short));
4395       grub_memset (ascii_key_map, 0, KEY_MAP_SIZE * sizeof (unsigned short));
4396 
4397       return 0;
4398     }
4399   else if (! *from_key)
4400     {
4401       /* The user must specify two arguments or zero argument.  */
4402       errnum = ERR_BAD_ARGUMENT;
4403       return 1;
4404     }
4405 
4406   nul_terminate (to_key);
4407   nul_terminate (from_key);
4408 
4409   to_code = find_ascii_code (to_key);
4410   from_code = find_ascii_code (from_key);
4411   if (! to_code || ! from_code)
4412     {
4413       map_in_interrupt = 1;
4414       to_code = find_key_code (to_key);
4415       from_code = find_key_code (from_key);
4416       if (! to_code || ! from_code)
4417 	{
4418 	  errnum = ERR_BAD_ARGUMENT;
4419 	  return 1;
4420 	}
4421     }
4422 
4423   if (map_in_interrupt)
4424     {
4425       int i;
4426 
4427       /* Find an empty slot.  */
4428       for (i = 0; i < KEY_MAP_SIZE; i++)
4429 	{
4430 	  if ((bios_key_map[i] & 0xff) == from_code)
4431 	    /* Perhaps the user wants to overwrite the map.  */
4432 	    break;
4433 
4434 	  if (! bios_key_map[i])
4435 	    break;
4436 	}
4437 
4438       if (i ==