Magellan Linux

Diff of /tags/grubby-8_32/grubby.c

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 1717 by niro, Sat Feb 18 00:47:17 2012 UTC revision 2688 by niro, Wed Jul 16 10:42:34 2014 UTC
# Line 36  Line 36 
36  #include <signal.h>  #include <signal.h>
37  #include <blkid/blkid.h>  #include <blkid/blkid.h>
38    
39    #include "log.h"
40    
41  #ifndef DEBUG  #ifndef DEBUG
42  #define DEBUG 0  #define DEBUG 0
43  #endif  #endif
# Line 46  Line 48 
48  #define dbgPrintf(format, args...)  #define dbgPrintf(format, args...)
49  #endif  #endif
50    
51    int debug = 0; /* Currently just for template debugging */
52    
53  #define _(A) (A)  #define _(A) (A)
54    
55  #define MAX_EXTRA_INITRDS  16 /* code segment checked by --bootloader-probe */  #define MAX_EXTRA_INITRDS  16 /* code segment checked by --bootloader-probe */
56  #define CODE_SEG_SIZE  128 /* code segment checked by --bootloader-probe */  #define CODE_SEG_SIZE  128 /* code segment checked by --bootloader-probe */
57    
58    #define NOOP_OPCODE 0x90
59    #define JMP_SHORT_OPCODE 0xeb
60    
61    int isEfi = 0;
62    
63    #if defined(__arch64__)
64    #define isEfiOnly 1
65    #else
66    #define isEfiOnly 0
67    #endif
68    
69    char *saved_command_line = NULL;
70    
71  /* comments get lumped in with indention */  /* comments get lumped in with indention */
72  struct lineElement {  struct lineElement {
73      char * item;      char * item;
# Line 77  enum lineType_e { Line 94  enum lineType_e {
94      LT_MENUENTRY    = 1 << 17,      LT_MENUENTRY    = 1 << 17,
95      LT_ENTRY_END    = 1 << 18,      LT_ENTRY_END    = 1 << 18,
96      LT_SET_VARIABLE = 1 << 19,      LT_SET_VARIABLE = 1 << 19,
97      LT_UNKNOWN      = 1 << 20,      LT_KERNEL_EFI   = 1 << 20,
98        LT_INITRD_EFI   = 1 << 21,
99        LT_KERNEL_16    = 1 << 22,
100        LT_INITRD_16    = 1 << 23,
101        LT_DEVTREE      = 1 << 24,
102        LT_UNKNOWN      = 1 << 25,
103  };  };
104    
105  struct singleLine {  struct singleLine {
# Line 106  struct singleEntry { Line 128  struct singleEntry {
128  #define NEED_ARGS    (1 << 3)  #define NEED_ARGS    (1 << 3)
129  #define NEED_MB      (1 << 4)  #define NEED_MB      (1 << 4)
130  #define NEED_END     (1 << 5)  #define NEED_END     (1 << 5)
131    #define NEED_DEVTREE (1 << 6)
132    
133  #define MAIN_DEFAULT    (1 << 0)  #define MAIN_DEFAULT    (1 << 0)
134  #define DEFAULT_SAVED       -2  #define DEFAULT_SAVED       -2
135    #define DEFAULT_SAVED_GRUB2 -3
136    
137  struct keywordTypes {  struct keywordTypes {
138      char * key;      char * key;
# Line 122  struct configFileInfo; Line 146  struct configFileInfo;
146  typedef const char *(*findConfigFunc)(struct configFileInfo *);  typedef const char *(*findConfigFunc)(struct configFileInfo *);
147  typedef const int (*writeLineFunc)(struct configFileInfo *,  typedef const int (*writeLineFunc)(struct configFileInfo *,
148   struct singleLine *line);   struct singleLine *line);
149    typedef char *(*getEnvFunc)(struct configFileInfo *, char *name);
150    typedef int (*setEnvFunc)(struct configFileInfo *, char *name, char *value);
151    
152  struct configFileInfo {  struct configFileInfo {
153      char * defaultConfig;      char * defaultConfig;
154      findConfigFunc findConfig;      findConfigFunc findConfig;
155      writeLineFunc writeLine;      writeLineFunc writeLine;
156        getEnvFunc getEnv;
157        setEnvFunc setEnv;
158      struct keywordTypes * keywords;      struct keywordTypes * keywords;
159        int caseInsensitive;
160      int defaultIsIndex;      int defaultIsIndex;
161      int defaultIsVariable;      int defaultIsVariable;
162      int defaultSupportSaved;      int defaultSupportSaved;
163        int defaultIsSaved;
164      enum lineType_e entryStart;      enum lineType_e entryStart;
165      enum lineType_e entryEnd;      enum lineType_e entryEnd;
166      int needsBootPrefix;      int needsBootPrefix;
# Line 142  struct configFileInfo { Line 172  struct configFileInfo {
172      int mbInitRdIsModule;      int mbInitRdIsModule;
173      int mbConcatArgs;      int mbConcatArgs;
174      int mbAllowExtraInitRds;      int mbAllowExtraInitRds;
175        char *envFile;
176  };  };
177    
178  struct keywordTypes grubKeywords[] = {  struct keywordTypes grubKeywords[] = {
# Line 158  struct keywordTypes grubKeywords[] = { Line 189  struct keywordTypes grubKeywords[] = {
189    
190  const char *grubFindConfig(struct configFileInfo *cfi) {  const char *grubFindConfig(struct configFileInfo *cfi) {
191      static const char *configFiles[] = {      static const char *configFiles[] = {
  "/etc/grub.conf",  
192   "/boot/grub/grub.conf",   "/boot/grub/grub.conf",
193   "/boot/grub/menu.lst",   "/boot/grub/menu.lst",
194     "/etc/grub.conf",
195     "/boot/grub2/grub.cfg",
196     "/boot/grub2-efi/grub.cfg",
197   NULL   NULL
198      };      };
199      static int i = -1;      static int i = -1;
# Line 199  struct keywordTypes grub2Keywords[] = { Line 232  struct keywordTypes grub2Keywords[] = {
232      { "default",    LT_DEFAULT,     ' ' },      { "default",    LT_DEFAULT,     ' ' },
233      { "fallback",   LT_FALLBACK,    ' ' },      { "fallback",   LT_FALLBACK,    ' ' },
234      { "linux",      LT_KERNEL,      ' ' },      { "linux",      LT_KERNEL,      ' ' },
235        { "linuxefi",   LT_KERNEL_EFI,  ' ' },
236        { "linux16",    LT_KERNEL_16,   ' ' },
237      { "initrd",     LT_INITRD,      ' ', ' ' },      { "initrd",     LT_INITRD,      ' ', ' ' },
238        { "initrdefi",  LT_INITRD_EFI,  ' ', ' ' },
239        { "initrd16",   LT_INITRD_16,   ' ', ' ' },
240      { "module",     LT_MBMODULE,    ' ' },      { "module",     LT_MBMODULE,    ' ' },
241      { "kernel",     LT_HYPER,       ' ' },      { "kernel",     LT_HYPER,       ' ' },
242        { "devicetree", LT_DEVTREE,  ' ' },
243      { NULL, 0, 0 },      { NULL, 0, 0 },
244  };  };
245    
# Line 213  const char *grub2FindConfig(struct confi Line 251  const char *grub2FindConfig(struct confi
251      };      };
252      static int i = -1;      static int i = -1;
253      static const char *grub_cfg = "/boot/grub/grub.cfg";      static const char *grub_cfg = "/boot/grub/grub.cfg";
254        int rc = -1;
255    
256      if (i == -1) {      if (i == -1) {
257   for (i = 0; configFiles[i] != NULL; i++) {   for (i = 0; configFiles[i] != NULL; i++) {
258      dbgPrintf("Checking \"%s\": ", configFiles[i]);      dbgPrintf("Checking \"%s\": ", configFiles[i]);
259      if (!access(configFiles[i], R_OK)) {      if ((rc = access(configFiles[i], R_OK))) {
260     if (errno == EACCES) {
261        printf("Unable to access bootloader configuration file "
262           "\"%s\": %m\n", configFiles[i]);
263        exit(1);
264     }
265     continue;
266        } else {
267   dbgPrintf("found\n");   dbgPrintf("found\n");
268   return configFiles[i];   return configFiles[i];
269      }      }
# Line 236  const char *grub2FindConfig(struct confi Line 282  const char *grub2FindConfig(struct confi
282      return configFiles[i];      return configFiles[i];
283  }  }
284    
285    /* kind of hacky.  It'll give the first 1024 bytes, ish. */
286    static char *grub2GetEnv(struct configFileInfo *info, char *name)
287    {
288        static char buf[1025];
289        char *s = NULL;
290        char *ret = NULL;
291        char *envFile = info->envFile ? info->envFile : "/boot/grub/grubenv";
292        int rc = asprintf(&s, "grub-editenv %s list | grep '^%s='", envFile, name);
293    
294        if (rc < 0)
295     return NULL;
296    
297        FILE *f = popen(s, "r");
298        if (!f)
299     goto out;
300    
301        memset(buf, '\0', sizeof (buf));
302        ret = fgets(buf, 1024, f);
303        pclose(f);
304    
305        if (ret) {
306     ret += strlen(name) + 1;
307     ret[strlen(ret) - 1] = '\0';
308        }
309        dbgPrintf("grub2GetEnv(%s): %s\n", name, ret);
310    out:
311        free(s);
312        return ret;
313    }
314    
315    static int sPopCount(const char *s, const char *c)
316    {
317        int ret = 0;
318        if (!s)
319     return -1;
320        for (int i = 0; s[i] != '\0'; i++)
321     for (int j = 0; c[j] != '\0'; j++)
322        if (s[i] == c[j])
323     ret++;
324        return ret;
325    }
326    
327    static char *shellEscape(const char *s)
328    {
329        int l = strlen(s) + sPopCount(s, "'") * 2;
330    
331        char *ret = calloc(l+1, sizeof (*ret));
332        if (!ret)
333     return NULL;
334        for (int i = 0, j = 0; s[i] != '\0'; i++, j++) {
335     if (s[i] == '\'')
336        ret[j++] = '\\';
337     ret[j] = s[i];
338        }
339        return ret;
340    }
341    
342    static void unquote(char *s)
343    {
344        int l = strlen(s);
345    
346        if ((s[l-1] == '\'' && s[0] == '\'') || (s[l-1] == '"' && s[0] == '"')) {
347     memmove(s, s+1, l-2);
348     s[l-2] = '\0';
349        }
350    }
351    
352    static int grub2SetEnv(struct configFileInfo *info, char *name, char *value)
353    {
354        char *s = NULL;
355        int rc = 0;
356        char *envFile = info->envFile ? info->envFile : "/boot/grub/grubenv";
357    
358        unquote(value);
359        value = shellEscape(value);
360        if (!value)
361        return -1;
362    
363        rc = asprintf(&s, "grub-editenv %s set '%s=%s'", envFile, name, value);
364        free(value);
365        if (rc <0)
366     return -1;
367    
368        dbgPrintf("grub2SetEnv(%s): %s\n", name, s);
369        rc = system(s);
370        free(s);
371        return rc;
372    }
373    
374    /* this is a gigantic hack to avoid clobbering grub2 variables... */
375    static int is_special_grub2_variable(const char *name)
376    {
377        if (!strcmp(name,"\"${next_entry}\""))
378     return 1;
379        if (!strcmp(name,"\"${prev_saved_entry}\""))
380     return 1;
381        return 0;
382    }
383    
384    int sizeOfSingleLine(struct singleLine * line) {
385      int count = 0;
386    
387      for (int i = 0; i < line->numElements; i++) {
388        int indentSize = 0;
389    
390        count = count + strlen(line->elements[i].item);
391    
392        indentSize = strlen(line->elements[i].indent);
393        if (indentSize > 0)
394          count = count + indentSize;
395        else
396          /* be extra safe and add room for whitespaces */
397          count = count + 1;
398      }
399    
400      /* room for trailing terminator */
401      count = count + 1;
402    
403      return count;
404    }
405    
406    static int isquote(char q)
407    {
408        if (q == '\'' || q == '\"')
409     return 1;
410        return 0;
411    }
412    
413    static int iskernel(enum lineType_e type) {
414        return (type == LT_KERNEL || type == LT_KERNEL_EFI || type == LT_KERNEL_16);
415    }
416    
417    static int isinitrd(enum lineType_e type) {
418        return (type == LT_INITRD || type == LT_INITRD_EFI || type == LT_INITRD_16);
419    }
420    
421    char *grub2ExtractTitle(struct singleLine * line) {
422        char * current;
423        char * current_indent;
424        int current_len;
425        int current_indent_len;
426        int i;
427    
428        /* bail out if line does not start with menuentry */
429        if (strcmp(line->elements[0].item, "menuentry"))
430          return NULL;
431    
432        i = 1;
433        current = line->elements[i].item;
434        current_len = strlen(current);
435    
436        /* if second word is quoted, strip the quotes and return single word */
437        if (isquote(*current) && isquote(current[current_len - 1])) {
438     char *tmp;
439    
440     tmp = strdup(current);
441     *(tmp + current_len - 1) = '\0';
442     return ++tmp;
443        }
444    
445        /* if no quotes, return second word verbatim */
446        if (!isquote(*current))
447     return current;
448    
449        /* second element start with a quote, so we have to find the element
450         * whose last character is also quote (assuming it's the closing one) */
451        int resultMaxSize;
452        char * result;
453        
454        resultMaxSize = sizeOfSingleLine(line);
455        result = malloc(resultMaxSize);
456        snprintf(result, resultMaxSize, "%s", ++current);
457        
458        i++;
459        for (; i < line->numElements; ++i) {
460     current = line->elements[i].item;
461     current_len = strlen(current);
462     current_indent = line->elements[i].indent;
463     current_indent_len = strlen(current_indent);
464    
465     strncat(result, current_indent, current_indent_len);
466     if (!isquote(current[current_len-1])) {
467        strncat(result, current, current_len);
468     } else {
469        strncat(result, current, current_len - 1);
470        break;
471     }
472        }
473        return result;
474    }
475    
476  struct configFileInfo grub2ConfigType = {  struct configFileInfo grub2ConfigType = {
477      .findConfig = grub2FindConfig,      .findConfig = grub2FindConfig,
478        .getEnv = grub2GetEnv,
479        .setEnv = grub2SetEnv,
480      .keywords = grub2Keywords,      .keywords = grub2Keywords,
481      .defaultIsIndex = 1,      .defaultIsIndex = 1,
482      .defaultSupportSaved = 0,      .defaultSupportSaved = 1,
483      .defaultIsVariable = 1,      .defaultIsVariable = 1,
484      .entryStart = LT_MENUENTRY,      .entryStart = LT_MENUENTRY,
485      .entryEnd = LT_ENTRY_END,      .entryEnd = LT_ENTRY_END,
# Line 392  struct configFileInfo ziplConfigType = { Line 631  struct configFileInfo ziplConfigType = {
631  struct configFileInfo extlinuxConfigType = {  struct configFileInfo extlinuxConfigType = {
632      .defaultConfig = "/boot/extlinux/extlinux.conf",      .defaultConfig = "/boot/extlinux/extlinux.conf",
633      .keywords = extlinuxKeywords,      .keywords = extlinuxKeywords,
634        .caseInsensitive = 1,
635      .entryStart = LT_TITLE,      .entryStart = LT_TITLE,
636      .needsBootPrefix = 1,      .needsBootPrefix = 1,
637      .maxTitleLength = 255,      .maxTitleLength = 255,
# Line 416  struct singleEntry * findEntryByIndex(st Line 656  struct singleEntry * findEntryByIndex(st
656  struct singleEntry * findEntryByPath(struct grubConfig * cfg,  struct singleEntry * findEntryByPath(struct grubConfig * cfg,
657       const char * path, const char * prefix,       const char * path, const char * prefix,
658       int * index);       int * index);
659    struct singleEntry * findEntryByTitle(struct grubConfig * cfg, char *title,
660          int * index);
661  static int readFile(int fd, char ** bufPtr);  static int readFile(int fd, char ** bufPtr);
662  static void lineInit(struct singleLine * line);  static void lineInit(struct singleLine * line);
663  struct singleLine * lineDup(struct singleLine * line);  struct singleLine * lineDup(struct singleLine * line);
# Line 480  static char * sdupprintf(const char *for Line 722  static char * sdupprintf(const char *for
722      return buf;      return buf;
723  }  }
724    
725    static enum lineType_e preferredLineType(enum lineType_e type,
726     struct configFileInfo *cfi) {
727        if (isEfi && cfi == &grub2ConfigType) {
728     switch (type) {
729     case LT_KERNEL:
730        return isEfiOnly ? LT_KERNEL : LT_KERNEL_EFI;
731     case LT_INITRD:
732        return isEfiOnly ? LT_INITRD : LT_INITRD_EFI;
733     default:
734        return type;
735     }
736    #if defined(__i386__) || defined(__x86_64__)
737        } else if (cfi == &grub2ConfigType) {
738     switch (type) {
739     case LT_KERNEL:
740        return LT_KERNEL_16;
741     case LT_INITRD:
742        return LT_INITRD_16;
743     default:
744        return type;
745     }
746    #endif
747        }
748        return type;
749    }
750    
751  static struct keywordTypes * getKeywordByType(enum lineType_e type,  static struct keywordTypes * getKeywordByType(enum lineType_e type,
752        struct configFileInfo * cfi) {        struct configFileInfo * cfi) {
753      struct keywordTypes * kw;      for (struct keywordTypes *kw = cfi->keywords; kw->key; kw++) {
     for (kw = cfi->keywords; kw->key; kw++) {  
754   if (kw->type == type)   if (kw->type == type)
755      return kw;      return kw;
756      }      }
# Line 513  static char * getuuidbydev(char *device) Line 780  static char * getuuidbydev(char *device)
780    
781  static enum lineType_e getTypeByKeyword(char * keyword,  static enum lineType_e getTypeByKeyword(char * keyword,
782   struct configFileInfo * cfi) {   struct configFileInfo * cfi) {
783      struct keywordTypes * kw;      for (struct keywordTypes *kw = cfi->keywords; kw->key; kw++) {
784      for (kw = cfi->keywords; kw->key; kw++) {   if (cfi->caseInsensitive) {
785   if (!strcmp(keyword, kw->key))      if (!strcasecmp(keyword, kw->key))
786      return kw->type;                  return kw->type;
787     } else {
788        if (!strcmp(keyword, kw->key))
789            return kw->type;
790     }
791      }      }
792      return LT_UNKNOWN;      return LT_UNKNOWN;
793  }  }
# Line 555  static int isEntryStart(struct singleLin Line 826  static int isEntryStart(struct singleLin
826  /* extract the title from within brackets (for zipl) */  /* extract the title from within brackets (for zipl) */
827  static char * extractTitle(struct singleLine * line) {  static char * extractTitle(struct singleLine * line) {
828      /* bracketed title... let's extract it (leaks a byte) */      /* bracketed title... let's extract it (leaks a byte) */
829      char * title;      char * title = NULL;
830      title = strdup(line->elements[0].item);      if (line->type == LT_TITLE) {
831      title++;   title = strdup(line->elements[0].item);
832      *(title + strlen(title) - 1) = '\0';   title++;
833     *(title + strlen(title) - 1) = '\0';
834        } else if (line->type == LT_MENUENTRY)
835     title = strdup(line->elements[1].item);
836        else
837     return NULL;
838      return title;      return title;
839  }  }
840    
# Line 601  static void lineInit(struct singleLine * Line 877  static void lineInit(struct singleLine *
877  }  }
878    
879  struct singleLine * lineDup(struct singleLine * line) {  struct singleLine * lineDup(struct singleLine * line) {
     int i;  
880      struct singleLine * newLine = malloc(sizeof(*newLine));      struct singleLine * newLine = malloc(sizeof(*newLine));
881    
882      newLine->indent = strdup(line->indent);      newLine->indent = strdup(line->indent);
# Line 611  struct singleLine * lineDup(struct singl Line 886  struct singleLine * lineDup(struct singl
886      newLine->elements = malloc(sizeof(*newLine->elements) *      newLine->elements = malloc(sizeof(*newLine->elements) *
887         newLine->numElements);         newLine->numElements);
888    
889      for (i = 0; i < newLine->numElements; i++) {      for (int i = 0; i < newLine->numElements; i++) {
890   newLine->elements[i].indent = strdup(line->elements[i].indent);   newLine->elements[i].indent = strdup(line->elements[i].indent);
891   newLine->elements[i].item = strdup(line->elements[i].item);   newLine->elements[i].item = strdup(line->elements[i].item);
892      }      }
# Line 620  struct singleLine * lineDup(struct singl Line 895  struct singleLine * lineDup(struct singl
895  }  }
896    
897  static void lineFree(struct singleLine * line) {  static void lineFree(struct singleLine * line) {
     int i;  
   
898      if (line->indent) free(line->indent);      if (line->indent) free(line->indent);
899    
900      for (i = 0; i < line->numElements; i++) {      for (int i = 0; i < line->numElements; i++) {
901   free(line->elements[i].item);   free(line->elements[i].item);
902   free(line->elements[i].indent);   free(line->elements[i].indent);
903      }      }
# Line 635  static void lineFree(struct singleLine * Line 908  static void lineFree(struct singleLine *
908    
909  static int lineWrite(FILE * out, struct singleLine * line,  static int lineWrite(FILE * out, struct singleLine * line,
910       struct configFileInfo * cfi) {       struct configFileInfo * cfi) {
     int i;  
   
911      if (fprintf(out, "%s", line->indent) == -1) return -1;      if (fprintf(out, "%s", line->indent) == -1) return -1;
912    
913      for (i = 0; i < line->numElements; i++) {      for (int i = 0; i < line->numElements; i++) {
914     /* Need to handle this, because we strip the quotes from
915     * menuentry when read it. */
916     if (line->type == LT_MENUENTRY && i == 1) {
917        if(!isquote(*line->elements[i].item))
918     fprintf(out, "\'%s\'", line->elements[i].item);
919        else
920     fprintf(out, "%s", line->elements[i].item);
921        fprintf(out, "%s", line->elements[i].indent);
922    
923        continue;
924     }
925    
926   if (i == 1 && line->type == LT_KERNELARGS && cfi->argsInQuotes)   if (i == 1 && line->type == LT_KERNELARGS && cfi->argsInQuotes)
927      if (fputc('"', out) == EOF) return -1;      if (fputc('"', out) == EOF) return -1;
928    
# Line 733  static int getNextLine(char ** bufPtr, s Line 1016  static int getNextLine(char ** bufPtr, s
1016      if (*line->elements[0].item == '#') {      if (*line->elements[0].item == '#') {
1017   char * fullLine;   char * fullLine;
1018   int len;   int len;
  int i;  
1019    
1020   len = strlen(line->indent);   len = strlen(line->indent);
1021   for (i = 0; i < line->numElements; i++)   for (int i = 0; i < line->numElements; i++)
1022      len += strlen(line->elements[i].item) +      len += strlen(line->elements[i].item) +
1023     strlen(line->elements[i].indent);     strlen(line->elements[i].indent);
1024    
# Line 745  static int getNextLine(char ** bufPtr, s Line 1027  static int getNextLine(char ** bufPtr, s
1027   free(line->indent);   free(line->indent);
1028   line->indent = fullLine;   line->indent = fullLine;
1029    
1030   for (i = 0; i < line->numElements; i++) {   for (int i = 0; i < line->numElements; i++) {
1031      strcat(fullLine, line->elements[i].item);      strcat(fullLine, line->elements[i].item);
1032      strcat(fullLine, line->elements[i].indent);      strcat(fullLine, line->elements[i].indent);
1033      free(line->elements[i].item);      free(line->elements[i].item);
# Line 764  static int getNextLine(char ** bufPtr, s Line 1046  static int getNextLine(char ** bufPtr, s
1046   * elements up more   * elements up more
1047   */   */
1048   if (!isspace(kw->separatorChar)) {   if (!isspace(kw->separatorChar)) {
     int i;  
1049      char indent[2] = "";      char indent[2] = "";
1050      indent[0] = kw->separatorChar;      indent[0] = kw->separatorChar;
1051      for (i = 1; i < line->numElements; i++) {      for (int i = 1; i < line->numElements; i++) {
1052   char *p;   char *p;
  int j;  
1053   int numNewElements;   int numNewElements;
1054    
1055   numNewElements = 0;   numNewElements = 0;
# Line 785  static int getNextLine(char ** bufPtr, s Line 1065  static int getNextLine(char ** bufPtr, s
1065      sizeof(*line->elements) * elementsAlloced);      sizeof(*line->elements) * elementsAlloced);
1066   }   }
1067    
1068   for (j = line->numElements; j > i; j--) {   for (int j = line->numElements; j > i; j--) {
1069   line->elements[j + numNewElements] = line->elements[j];   line->elements[j + numNewElements] = line->elements[j];
1070   }   }
1071   line->numElements += numNewElements;   line->numElements += numNewElements;
# Line 798  static int getNextLine(char ** bufPtr, s Line 1078  static int getNextLine(char ** bufPtr, s
1078   break;   break;
1079   }   }
1080    
1081   free(line->elements[i].indent);   line->elements[i + 1].indent = line->elements[i].indent;
1082   line->elements[i].indent = strdup(indent);   line->elements[i].indent = strdup(indent);
1083   *p++ = '\0';   *p++ = '\0';
1084   i++;   i++;
1085   line->elements[i].item = strdup(p);   line->elements[i].item = strdup(p);
  line->elements[i].indent = strdup("");  
  p = line->elements[i].item;  
1086   }   }
1087      }      }
1088   }   }
# Line 814  static int getNextLine(char ** bufPtr, s Line 1092  static int getNextLine(char ** bufPtr, s
1092      return 0;      return 0;
1093  }  }
1094    
1095    static int isnumber(const char *s)
1096    {
1097        int i;
1098        for (i = 0; s[i] != '\0'; i++)
1099     if (s[i] < '0' || s[i] > '9')
1100        return 0;
1101        return i;
1102    }
1103    
1104  static struct grubConfig * readConfig(const char * inName,  static struct grubConfig * readConfig(const char * inName,
1105        struct configFileInfo * cfi) {        struct configFileInfo * cfi) {
1106      int in;      int in;
# Line 825  static struct grubConfig * readConfig(co Line 1112  static struct grubConfig * readConfig(co
1112      struct singleLine * last = NULL, * line, * defaultLine = NULL;      struct singleLine * last = NULL, * line, * defaultLine = NULL;
1113      char * end;      char * end;
1114      struct singleEntry * entry = NULL;      struct singleEntry * entry = NULL;
1115      int i, len;      int len;
1116      char * buf;      char * buf;
1117    
1118      if (!strcmp(inName, "-")) {      if (inName == NULL) {
1119            printf("Could not find bootloader configuration\n");
1120            exit(1);
1121        } else if (!strcmp(inName, "-")) {
1122   in = 0;   in = 0;
1123      } else {      } else {
1124   if ((in = open(inName, O_RDONLY)) < 0) {   if ((in = open(inName, O_RDONLY)) < 0) {
# Line 871  static struct grubConfig * readConfig(co Line 1161  static struct grubConfig * readConfig(co
1161      cfg->secondaryIndent = strdup(line->indent);      cfg->secondaryIndent = strdup(line->indent);
1162   }   }
1163    
1164   if (isEntryStart(line, cfi)) {   if (isEntryStart(line, cfi) || (cfg->entries && !sawEntry)) {
1165      sawEntry = 1;      sawEntry = 1;
1166      if (!entry) {      if (!entry) {
1167   cfg->entries = malloc(sizeof(*entry));   cfg->entries = malloc(sizeof(*entry));
# Line 888  static struct grubConfig * readConfig(co Line 1178  static struct grubConfig * readConfig(co
1178   }   }
1179    
1180   if (line->type == LT_SET_VARIABLE) {   if (line->type == LT_SET_VARIABLE) {
     int i;  
1181      dbgPrintf("found 'set' command (%d elements): ", line->numElements);      dbgPrintf("found 'set' command (%d elements): ", line->numElements);
1182      dbgPrintf("%s", line->indent);      dbgPrintf("%s", line->indent);
1183      for (i = 0; i < line->numElements; i++)      for (int i = 0; i < line->numElements; i++)
1184   dbgPrintf("%s\"%s\"", line->elements[i].indent, line->elements[i].item);   dbgPrintf("\"%s\"%s", line->elements[i].item, line->elements[i].indent);
1185      dbgPrintf("\n");      dbgPrintf("\n");
1186      struct keywordTypes *kwType = getKeywordByType(LT_DEFAULT, cfi);      struct keywordTypes *kwType = getKeywordByType(LT_DEFAULT, cfi);
1187      if (kwType && line->numElements == 3 &&      if (kwType && line->numElements == 3 &&
1188      !strcmp(line->elements[1].item, kwType->key)) {      !strcmp(line->elements[1].item, kwType->key) &&
1189        !is_special_grub2_variable(line->elements[2].item)) {
1190   dbgPrintf("Line sets default config\n");   dbgPrintf("Line sets default config\n");
1191   cfg->flags &= ~GRUB_CONFIG_NO_DEFAULT;   cfg->flags &= ~GRUB_CONFIG_NO_DEFAULT;
1192   defaultLine = line;   defaultLine = line;
# Line 905  static struct grubConfig * readConfig(co Line 1195  static struct grubConfig * readConfig(co
1195      cfg->flags &= ~GRUB_CONFIG_NO_DEFAULT;      cfg->flags &= ~GRUB_CONFIG_NO_DEFAULT;
1196      defaultLine = line;      defaultLine = line;
1197    
1198          } else if (line->type == LT_KERNEL) {          } else if (iskernel(line->type)) {
1199      /* if by some freak chance this is multiboot and the "module"      /* if by some freak chance this is multiboot and the "module"
1200       * lines came earlier in the template, make sure to use LT_HYPER       * lines came earlier in the template, make sure to use LT_HYPER
1201       * instead of LT_KERNEL now       * instead of LT_KERNEL now
# Line 919  static struct grubConfig * readConfig(co Line 1209  static struct grubConfig * readConfig(co
1209       * This only applies to grub, but that's the only place we       * This only applies to grub, but that's the only place we
1210       * should find LT_MBMODULE lines anyway.       * should find LT_MBMODULE lines anyway.
1211       */       */
1212      struct singleLine * l;      for (struct singleLine *l = entry->lines; l; l = l->next) {
     for (l = entry->lines; l; l = l->next) {  
1213   if (l->type == LT_HYPER)   if (l->type == LT_HYPER)
1214      break;      break;
1215   else if (l->type == LT_KERNEL) {   else if (iskernel(l->type)) {
1216      l->type = LT_HYPER;      l->type = LT_HYPER;
1217      break;      break;
1218   }   }
# Line 940  static struct grubConfig * readConfig(co Line 1229  static struct grubConfig * readConfig(co
1229   } else if (line->type == LT_TITLE && line->numElements > 1) {   } else if (line->type == LT_TITLE && line->numElements > 1) {
1230      /* make the title a single argument (undoing our parsing) */      /* make the title a single argument (undoing our parsing) */
1231      len = 0;      len = 0;
1232      for (i = 1; i < line->numElements; i++) {      for (int i = 1; i < line->numElements; i++) {
1233   len += strlen(line->elements[i].item);   len += strlen(line->elements[i].item);
1234   len += strlen(line->elements[i].indent);   len += strlen(line->elements[i].indent);
1235      }      }
1236      buf = malloc(len + 1);      buf = malloc(len + 1);
1237      *buf = '\0';      *buf = '\0';
1238    
1239      for (i = 1; i < line->numElements; i++) {      for (int i = 1; i < line->numElements; i++) {
1240   strcat(buf, line->elements[i].item);   strcat(buf, line->elements[i].item);
1241   free(line->elements[i].item);   free(line->elements[i].item);
1242    
# Line 961  static struct grubConfig * readConfig(co Line 1250  static struct grubConfig * readConfig(co
1250      line->elements[line->numElements - 1].indent;      line->elements[line->numElements - 1].indent;
1251      line->elements[1].item = buf;      line->elements[1].item = buf;
1252      line->numElements = 2;      line->numElements = 2;
1253     } else if (line->type == LT_MENUENTRY && line->numElements > 3) {
1254        /* let --remove-kernel="TITLE=what" work */
1255        len = 0;
1256        char *extras;
1257        char *title;
1258    
1259        for (int i = 1; i < line->numElements; i++) {
1260     len += strlen(line->elements[i].item);
1261     len += strlen(line->elements[i].indent);
1262        }
1263        buf = malloc(len + 1);
1264        *buf = '\0';
1265    
1266        /* allocate mem for extra flags. */
1267        extras = malloc(len + 1);
1268        *extras = '\0';
1269    
1270        /* get title. */
1271        for (int i = 0; i < line->numElements; i++) {
1272     if (!strcmp(line->elements[i].item, "menuentry"))
1273        continue;
1274     if (isquote(*line->elements[i].item))
1275        title = line->elements[i].item + 1;
1276     else
1277        title = line->elements[i].item;
1278    
1279     len = strlen(title);
1280            if (isquote(title[len-1])) {
1281        strncat(buf, title,len-1);
1282        break;
1283     } else {
1284        strcat(buf, title);
1285        strcat(buf, line->elements[i].indent);
1286     }
1287        }
1288    
1289        /* get extras */
1290        int count = 0;
1291        for (int i = 0; i < line->numElements; i++) {
1292     if (count >= 2) {
1293        strcat(extras, line->elements[i].item);
1294        strcat(extras, line->elements[i].indent);
1295     }
1296    
1297     if (!strcmp(line->elements[i].item, "menuentry"))
1298        continue;
1299    
1300     /* count ' or ", there should be two in menuentry line. */
1301     if (isquote(*line->elements[i].item))
1302        count++;
1303    
1304     len = strlen(line->elements[i].item);
1305    
1306     if (isquote(line->elements[i].item[len -1]))
1307        count++;
1308    
1309     /* ok, we get the final ' or ", others are extras. */
1310                }
1311        line->elements[1].indent =
1312     line->elements[line->numElements - 2].indent;
1313        line->elements[1].item = buf;
1314        line->elements[2].indent =
1315     line->elements[line->numElements - 2].indent;
1316        line->elements[2].item = extras;
1317        line->numElements = 3;
1318   } else if (line->type == LT_KERNELARGS && cfi->argsInQuotes) {   } else if (line->type == LT_KERNELARGS && cfi->argsInQuotes) {
1319      /* Strip off any " which may be present; they'll be put back      /* Strip off any " which may be present; they'll be put back
1320         on write. This is one of the few (the only?) places that grubby         on write. This is one of the few (the only?) places that grubby
# Line 970  static struct grubConfig * readConfig(co Line 1323  static struct grubConfig * readConfig(co
1323      if (line->numElements >= 2) {      if (line->numElements >= 2) {
1324   int last, len;   int last, len;
1325    
1326   if (*line->elements[1].item == '"')   if (isquote(*line->elements[1].item))
1327      memmove(line->elements[1].item, line->elements[1].item + 1,      memmove(line->elements[1].item, line->elements[1].item + 1,
1328      strlen(line->elements[1].item + 1) + 1);      strlen(line->elements[1].item + 1) + 1);
1329    
1330   last = line->numElements - 1;   last = line->numElements - 1;
1331   len = strlen(line->elements[last].item) - 1;   len = strlen(line->elements[last].item) - 1;
1332   if (line->elements[last].item[len] == '"')   if (isquote(line->elements[last].item[len]))
1333      line->elements[last].item[len] = '\0';      line->elements[last].item[len] = '\0';
1334      }      }
1335   }   }
# Line 1035  static struct grubConfig * readConfig(co Line 1388  static struct grubConfig * readConfig(co
1388    
1389      dbgPrintf("defaultLine is %s\n", defaultLine ? "set" : "unset");      dbgPrintf("defaultLine is %s\n", defaultLine ? "set" : "unset");
1390      if (defaultLine) {      if (defaultLine) {
1391   if (cfi->defaultIsVariable) {          if (defaultLine->numElements > 2 &&
1392        cfi->defaultSupportSaved &&
1393        !strncmp(defaultLine->elements[2].item,"\"${saved_entry}\"", 16)) {
1394     cfg->cfi->defaultIsSaved = 1;
1395     cfg->defaultImage = DEFAULT_SAVED_GRUB2;
1396     if (cfg->cfi->getEnv) {
1397        char *defTitle = cfi->getEnv(cfg->cfi, "saved_entry");
1398        if (defTitle) {
1399     int index = 0;
1400     if (isnumber(defTitle)) {
1401        index = atoi(defTitle);
1402        entry = findEntryByIndex(cfg, index);
1403     } else {
1404        entry = findEntryByTitle(cfg, defTitle, &index);
1405     }
1406     if (entry)
1407        cfg->defaultImage = index;
1408        }
1409     }
1410     } else if (cfi->defaultIsVariable) {
1411      char *value = defaultLine->elements[2].item;      char *value = defaultLine->elements[2].item;
1412      while (*value && (*value == '"' || *value == '\'' ||      while (*value && (*value == '"' || *value == '\'' ||
1413      *value == ' ' || *value == '\t'))      *value == ' ' || *value == '\t'))
# Line 1052  static struct grubConfig * readConfig(co Line 1424  static struct grubConfig * readConfig(co
1424      cfg->defaultImage = strtol(defaultLine->elements[1].item, &end, 10);      cfg->defaultImage = strtol(defaultLine->elements[1].item, &end, 10);
1425      if (*end) cfg->defaultImage = -1;      if (*end) cfg->defaultImage = -1;
1426   } else if (defaultLine->numElements >= 2) {   } else if (defaultLine->numElements >= 2) {
1427      i = 0;      int i = 0;
1428      while ((entry = findEntryByIndex(cfg, i))) {      while ((entry = findEntryByIndex(cfg, i))) {
1429   for (line = entry->lines; line; line = line->next)   for (line = entry->lines; line; line = line->next)
1430      if (line->type == LT_TITLE) break;      if (line->type == LT_TITLE) break;
# Line 1075  static struct grubConfig * readConfig(co Line 1447  static struct grubConfig * readConfig(co
1447          cfg->defaultImage = -1;          cfg->defaultImage = -1;
1448      }      }
1449   }   }
1450        } else if (cfg->cfi->defaultIsSaved && cfg->cfi->getEnv) {
1451     char *defTitle = cfi->getEnv(cfg->cfi, "saved_entry");
1452     if (defTitle) {
1453        int index = 0;
1454        if (isnumber(defTitle)) {
1455     index = atoi(defTitle);
1456     entry = findEntryByIndex(cfg, index);
1457        } else {
1458     entry = findEntryByTitle(cfg, defTitle, &index);
1459        }
1460        if (entry)
1461     cfg->defaultImage = index;
1462     }
1463      } else {      } else {
1464          cfg->defaultImage = 0;          cfg->defaultImage = 0;
1465      }      }
# Line 1092  static void writeDefault(FILE * out, cha Line 1477  static void writeDefault(FILE * out, cha
1477    
1478      if (cfg->defaultImage == DEFAULT_SAVED)      if (cfg->defaultImage == DEFAULT_SAVED)
1479   fprintf(out, "%sdefault%ssaved\n", indent, separator);   fprintf(out, "%sdefault%ssaved\n", indent, separator);
1480      else if (cfg->defaultImage > -1) {      else if (cfg->cfi->defaultIsSaved) {
1481     fprintf(out, "%sset default=\"${saved_entry}\"\n", indent);
1482     if (cfg->defaultImage >= 0 && cfg->cfi->setEnv) {
1483        char *title;
1484        entry = findEntryByIndex(cfg, cfg->defaultImage);
1485        line = getLineByType(LT_MENUENTRY, entry->lines);
1486        if (!line)
1487     line = getLineByType(LT_TITLE, entry->lines);
1488        if (line) {
1489     title = extractTitle(line);
1490     if (title)
1491        cfg->cfi->setEnv(cfg->cfi, "saved_entry", title);
1492        }
1493     }
1494        } else if (cfg->defaultImage > -1) {
1495   if (cfg->cfi->defaultIsIndex) {   if (cfg->cfi->defaultIsIndex) {
1496      if (cfg->cfi->defaultIsVariable) {      if (cfg->cfi->defaultIsVariable) {
1497          fprintf(out, "%sset default=\"%d\"\n", indent,          fprintf(out, "%sset default=\"%d\"\n", indent,
# Line 1152  static int writeConfig(struct grubConfig Line 1551  static int writeConfig(struct grubConfig
1551    
1552      /* most likely the symlink is relative, so change our      /* most likely the symlink is relative, so change our
1553         directory to the dir of the symlink */         directory to the dir of the symlink */
1554              rc = chdir(dirname(strdupa(outName)));      char *dir = strdupa(outName);
1555        rc = chdir(dirname(dir));
1556      do {      do {
1557   buf = alloca(len + 1);   buf = alloca(len + 1);
1558   rc = readlink(basename(outName), buf, len);   rc = readlink(basename(outName), buf, len);
# Line 1194  static int writeConfig(struct grubConfig Line 1594  static int writeConfig(struct grubConfig
1594      while (line) {      while (line) {
1595          if (line->type == LT_SET_VARIABLE && defaultKw &&          if (line->type == LT_SET_VARIABLE && defaultKw &&
1596   line->numElements == 3 &&   line->numElements == 3 &&
1597   !strcmp(line->elements[1].item, defaultKw->key)) {   !strcmp(line->elements[1].item, defaultKw->key) &&
1598     !is_special_grub2_variable(line->elements[2].item)) {
1599      writeDefault(out, line->indent, line->elements[0].indent, cfg);      writeDefault(out, line->indent, line->elements[0].indent, cfg);
1600      needs &= ~MAIN_DEFAULT;      needs &= ~MAIN_DEFAULT;
1601   } else if (line->type == LT_DEFAULT) {   } else if (line->type == LT_DEFAULT) {
# Line 1290  static char *findDiskForRoot() Line 1691  static char *findDiskForRoot()
1691      buf[rc] = '\0';      buf[rc] = '\0';
1692      chptr = buf;      chptr = buf;
1693    
1694        char *foundanswer = NULL;
1695    
1696      while (chptr && chptr != buf+rc) {      while (chptr && chptr != buf+rc) {
1697          devname = chptr;          devname = chptr;
1698    
# Line 1317  static char *findDiskForRoot() Line 1720  static char *findDiskForRoot()
1720           * for '/' obviously.           * for '/' obviously.
1721           */           */
1722          if (*(++chptr) == '/' && *(++chptr) == ' ') {          if (*(++chptr) == '/' && *(++chptr) == ' ') {
1723              /*              /* remember the last / entry in mtab */
1724               * Move back 2, which is the first space after the device name, set             foundanswer = devname;
              * it to \0 so strdup will just get the devicename.  
              */  
             chptr -= 2;  
             *chptr = '\0';  
             return strdup(devname);  
1725          }          }
1726    
1727          /* Next line */          /* Next line */
# Line 1332  static char *findDiskForRoot() Line 1730  static char *findDiskForRoot()
1730              chptr++;              chptr++;
1731      }      }
1732    
1733        /* Return the last / entry found */
1734        if (foundanswer) {
1735            chptr = strchr(foundanswer, ' ');
1736            *chptr = '\0';
1737            return strdup(foundanswer);
1738        }
1739    
1740      return NULL;      return NULL;
1741  }  }
1742    
1743    void printEntry(struct singleEntry * entry, FILE *f) {
1744        int i;
1745        struct singleLine * line;
1746    
1747        for (line = entry->lines; line; line = line->next) {
1748     log_message(f, "DBG: %s", line->indent);
1749     for (i = 0; i < line->numElements; i++) {
1750        /* Need to handle this, because we strip the quotes from
1751         * menuentry when read it. */
1752        if (line->type == LT_MENUENTRY && i == 1) {
1753     if(!isquote(*line->elements[i].item))
1754        log_message(f, "\'%s\'", line->elements[i].item);
1755     else
1756        log_message(f, "%s", line->elements[i].item);
1757     log_message(f, "%s", line->elements[i].indent);
1758    
1759     continue;
1760        }
1761        
1762        log_message(f, "%s%s",
1763        line->elements[i].item, line->elements[i].indent);
1764     }
1765     log_message(f, "\n");
1766        }
1767    }
1768    
1769    void notSuitablePrintf(struct singleEntry * entry, int okay, const char *fmt, ...)
1770    {
1771        static int once;
1772        va_list argp, argq;
1773    
1774        va_start(argp, fmt);
1775    
1776        va_copy(argq, argp);
1777        if (!once) {
1778     log_time(NULL);
1779     log_message(NULL, "command line: %s\n", saved_command_line);
1780        }
1781        log_message(NULL, "DBG: Image entry %s: ", okay ? "succeeded" : "failed");
1782        log_vmessage(NULL, fmt, argq);
1783    
1784        printEntry(entry, NULL);
1785        va_end(argq);
1786    
1787        if (!debug) {
1788     once = 1;
1789         va_end(argp);
1790     return;
1791        }
1792    
1793        if (okay) {
1794     va_end(argp);
1795     return;
1796        }
1797    
1798        if (!once)
1799     log_message(stderr, "DBG: command line: %s\n", saved_command_line);
1800        once = 1;
1801        fprintf(stderr, "DBG: Image entry failed: ");
1802        vfprintf(stderr, fmt, argp);
1803        printEntry(entry, stderr);
1804        va_end(argp);
1805    }
1806    
1807    #define beginswith(s, c) ((s) && (s)[0] == (c))
1808    
1809    static int endswith(const char *s, char c)
1810    {
1811     int slen;
1812    
1813     if (!s || !s[0])
1814     return 0;
1815     slen = strlen(s) - 1;
1816    
1817     return s[slen] == c;
1818    }
1819    
1820  int suitableImage(struct singleEntry * entry, const char * bootPrefix,  int suitableImage(struct singleEntry * entry, const char * bootPrefix,
1821    int skipRemoved, int flags) {    int skipRemoved, int flags) {
1822      struct singleLine * line;      struct singleLine * line;
# Line 1344  int suitableImage(struct singleEntry * e Line 1826  int suitableImage(struct singleEntry * e
1826      char * rootspec;      char * rootspec;
1827      char * rootdev;      char * rootdev;
1828    
1829      if (skipRemoved && entry->skip) return 0;      if (skipRemoved && entry->skip) {
1830     notSuitablePrintf(entry, 0, "marked to skip\n");
1831     return 0;
1832        }
1833    
1834      line = getLineByType(LT_KERNEL|LT_HYPER, entry->lines);      line = getLineByType(LT_KERNEL|LT_HYPER|LT_KERNEL_EFI|LT_KERNEL_16, entry->lines);
1835      if (!line || line->numElements < 2) return 0;      if (!line) {
1836     notSuitablePrintf(entry, 0, "no line found\n");
1837     return 0;
1838        }
1839        if (line->numElements < 2) {
1840     notSuitablePrintf(entry, 0, "line has only %d elements\n",
1841        line->numElements);
1842     return 0;
1843        }
1844    
1845      if (flags & GRUBBY_BADIMAGE_OKAY) return 1;      if (flags & GRUBBY_BADIMAGE_OKAY) {
1846        notSuitablePrintf(entry, 1, "\n");
1847        return 1;
1848        }
1849    
1850      fullName = alloca(strlen(bootPrefix) +      fullName = alloca(strlen(bootPrefix) +
1851        strlen(line->elements[1].item) + 1);        strlen(line->elements[1].item) + 1);
1852      rootspec = getRootSpecifier(line->elements[1].item);      rootspec = getRootSpecifier(line->elements[1].item);
1853      sprintf(fullName, "%s%s", bootPrefix,      int rootspec_offset = rootspec ? strlen(rootspec) : 0;
1854              line->elements[1].item + (rootspec ? strlen(rootspec) : 0));      int hasslash = endswith(bootPrefix, '/') ||
1855      if (access(fullName, R_OK)) return 0;       beginswith(line->elements[1].item + rootspec_offset, '/');
1856        sprintf(fullName, "%s%s%s", bootPrefix, hasslash ? "" : "/",
1857                line->elements[1].item + rootspec_offset);
1858        if (access(fullName, R_OK)) {
1859     notSuitablePrintf(entry, 0, "access to %s failed\n", fullName);
1860     return 0;
1861        }
1862      for (i = 2; i < line->numElements; i++)      for (i = 2; i < line->numElements; i++)
1863   if (!strncasecmp(line->elements[i].item, "root=", 5)) break;   if (!strncasecmp(line->elements[i].item, "root=", 5)) break;
1864      if (i < line->numElements) {      if (i < line->numElements) {
# Line 1375  int suitableImage(struct singleEntry * e Line 1876  int suitableImage(struct singleEntry * e
1876      line = getLineByType(LT_KERNELARGS|LT_MBMODULE, entry->lines);      line = getLineByType(LT_KERNELARGS|LT_MBMODULE, entry->lines);
1877    
1878              /* failed to find one */              /* failed to find one */
1879              if (!line) return 0;              if (!line) {
1880     notSuitablePrintf(entry, 0, "no line found\n");
1881     return 0;
1882                }
1883    
1884      for (i = 1; i < line->numElements; i++)      for (i = 1; i < line->numElements; i++)
1885          if (!strncasecmp(line->elements[i].item, "root=", 5)) break;          if (!strncasecmp(line->elements[i].item, "root=", 5)) break;
1886      if (i < line->numElements)      if (i < line->numElements)
1887          dev = line->elements[i].item + 5;          dev = line->elements[i].item + 5;
1888      else {      else {
1889     notSuitablePrintf(entry, 0, "no root= entry found\n");
1890   /* it failed too...  can't find root= */   /* it failed too...  can't find root= */
1891          return 0;          return 0;
1892              }              }
# Line 1389  int suitableImage(struct singleEntry * e Line 1894  int suitableImage(struct singleEntry * e
1894      }      }
1895    
1896      dev = getpathbyspec(dev);      dev = getpathbyspec(dev);
1897      if (!dev)      if (!getpathbyspec(dev)) {
1898            notSuitablePrintf(entry, 0, "can't find blkid entry for %s\n", dev);
1899          return 0;          return 0;
1900        } else
1901     dev = getpathbyspec(dev);
1902    
1903      rootdev = findDiskForRoot();      rootdev = findDiskForRoot();
1904      if (!rootdev)      if (!rootdev) {
1905            notSuitablePrintf(entry, 0, "can't find root device\n");
1906   return 0;   return 0;
1907        }
1908    
1909      if (!getuuidbydev(rootdev) || !getuuidbydev(dev)) {      if (!getuuidbydev(rootdev) || !getuuidbydev(dev)) {
1910            notSuitablePrintf(entry, 0, "uuid missing: rootdev %s, dev %s\n",
1911     getuuidbydev(rootdev), getuuidbydev(dev));
1912          free(rootdev);          free(rootdev);
1913          return 0;          return 0;
1914      }      }
1915    
1916      if (strcmp(getuuidbydev(rootdev), getuuidbydev(dev))) {      if (strcmp(getuuidbydev(rootdev), getuuidbydev(dev))) {
1917            notSuitablePrintf(entry, 0, "uuid mismatch: rootdev %s, dev %s\n",
1918     getuuidbydev(rootdev), getuuidbydev(dev));
1919   free(rootdev);   free(rootdev);
1920          return 0;          return 0;
1921      }      }
1922    
1923      free(rootdev);      free(rootdev);
1924        notSuitablePrintf(entry, 1, "\n");
1925    
1926      return 1;      return 1;
1927  }  }
# Line 1450  struct singleEntry * findEntryByPath(str Line 1965  struct singleEntry * findEntryByPath(str
1965   entry = findEntryByIndex(config, indexVars[i]);   entry = findEntryByIndex(config, indexVars[i]);
1966   if (!entry) return NULL;   if (!entry) return NULL;
1967    
1968   line = getLineByType(LT_KERNEL|LT_HYPER, entry->lines);   line = getLineByType(LT_KERNEL|LT_HYPER|LT_KERNEL_EFI|LT_KERNEL_16, entry->lines);
1969   if (!line) return NULL;   if (!line) return NULL;
1970    
1971   if (index) *index = indexVars[i];   if (index) *index = indexVars[i];
# Line 1488  struct singleEntry * findEntryByPath(str Line 2003  struct singleEntry * findEntryByPath(str
2003    
2004   if (!strncmp(kernel, "TITLE=", 6)) {   if (!strncmp(kernel, "TITLE=", 6)) {
2005      prefix = "";      prefix = "";
2006      checkType = LT_TITLE;      checkType = LT_TITLE|LT_MENUENTRY;
2007      kernel += 6;      kernel += 6;
2008   }   }
2009    
# Line 1499  struct singleEntry * findEntryByPath(str Line 2014  struct singleEntry * findEntryByPath(str
2014    
2015      /* check all the lines matching checkType */      /* check all the lines matching checkType */
2016      for (line = entry->lines; line; line = line->next) {      for (line = entry->lines; line; line = line->next) {
2017   line = getLineByType(entry->multiboot && checkType == LT_KERNEL ?   enum lineType_e ct = checkType;
2018       LT_KERNEL|LT_MBMODULE|LT_HYPER :   if (entry->multiboot && checkType == LT_KERNEL)
2019       checkType, line);      ct = LT_KERNEL|LT_KERNEL_EFI|LT_MBMODULE|LT_HYPER|LT_KERNEL_16;
2020   if (!line) break;  /* not found in this entry */   else if (checkType & LT_KERNEL)
2021        ct = checkType | LT_KERNEL_EFI | LT_KERNEL_16;
2022     line = getLineByType(ct, line);
2023     if (!line)
2024        break;  /* not found in this entry */
2025    
2026   if (line && line->numElements >= 2) {   if (line && line->type != LT_MENUENTRY &&
2027     line->numElements >= 2) {
2028      rootspec = getRootSpecifier(line->elements[1].item);      rootspec = getRootSpecifier(line->elements[1].item);
2029      if (!strcmp(line->elements[1].item +      if (!strcmp(line->elements[1].item +
2030   ((rootspec != NULL) ? strlen(rootspec) : 0),   ((rootspec != NULL) ? strlen(rootspec) : 0),
2031   kernel + strlen(prefix)))   kernel + strlen(prefix)))
2032   break;   break;
2033   }   }
2034     if(line->type == LT_MENUENTRY &&
2035     !strcmp(line->elements[1].item, kernel))
2036        break;
2037      }      }
2038    
2039      /* make sure this entry has a kernel identifier; this skips      /* make sure this entry has a kernel identifier; this skips
2040       * non-Linux boot entries (could find netbsd etc, though, which is       * non-Linux boot entries (could find netbsd etc, though, which is
2041       * unfortunate)       * unfortunate)
2042       */       */
2043      if (line && getLineByType(LT_KERNEL|LT_HYPER, entry->lines))      if (line && getLineByType(LT_KERNEL|LT_HYPER|LT_KERNEL_EFI|LT_KERNEL_16, entry->lines))
2044   break; /* found 'im! */   break; /* found 'im! */
2045   }   }
2046    
# Line 1527  struct singleEntry * findEntryByPath(str Line 2050  struct singleEntry * findEntryByPath(str
2050      return entry;      return entry;
2051  }  }
2052    
2053    struct singleEntry * findEntryByTitle(struct grubConfig * cfg, char *title,
2054          int * index) {
2055        struct singleEntry * entry;
2056        struct singleLine * line;
2057        int i;
2058        char * newtitle;
2059    
2060        for (i = 0, entry = cfg->entries; entry; entry = entry->next, i++) {
2061     if (index && i < *index)
2062        continue;
2063     line = getLineByType(LT_TITLE, entry->lines);
2064     if (!line)
2065        line = getLineByType(LT_MENUENTRY, entry->lines);
2066     if (!line)
2067        continue;
2068     newtitle = grub2ExtractTitle(line);
2069     if (!newtitle)
2070        continue;
2071     if (!strcmp(title, newtitle))
2072        break;
2073        }
2074    
2075        if (!entry)
2076     return NULL;
2077    
2078        if (index)
2079     *index = i;
2080        return entry;
2081    }
2082    
2083  struct singleEntry * findEntryByIndex(struct grubConfig * cfg, int index) {  struct singleEntry * findEntryByIndex(struct grubConfig * cfg, int index) {
2084      struct singleEntry * entry;      struct singleEntry * entry;
2085    
# Line 1549  struct singleEntry * findTemplate(struct Line 2102  struct singleEntry * findTemplate(struct
2102      struct singleEntry * entry, * entry2;      struct singleEntry * entry, * entry2;
2103      int index;      int index;
2104    
2105      if (cfg->defaultImage > -1) {      if (cfg->cfi->defaultIsSaved) {
2106     if (cfg->cfi->getEnv) {
2107        char *defTitle = cfg->cfi->getEnv(cfg->cfi, "saved_entry");
2108        if (defTitle) {
2109     int index = 0;
2110     if (isnumber(defTitle)) {
2111        index = atoi(defTitle);
2112        entry = findEntryByIndex(cfg, index);
2113     } else {
2114        entry = findEntryByTitle(cfg, defTitle, &index);
2115     }
2116     if (entry)
2117        cfg->defaultImage = index;
2118        }
2119     }
2120        } else if (cfg->defaultImage > -1) {
2121   entry = findEntryByIndex(cfg, cfg->defaultImage);   entry = findEntryByIndex(cfg, cfg->defaultImage);
2122   if (entry && suitableImage(entry, prefix, skipRemoved, flags)) {   if (entry && suitableImage(entry, prefix, skipRemoved, flags)) {
2123      if (indexPtr) *indexPtr = cfg->defaultImage;      if (indexPtr) *indexPtr = cfg->defaultImage;
# Line 1602  void markRemovedImage(struct grubConfig Line 2170  void markRemovedImage(struct grubConfig
2170        const char * prefix) {        const char * prefix) {
2171      struct singleEntry * entry;      struct singleEntry * entry;
2172    
2173      if (!image) return;      if (!image)
2174     return;
2175    
2176        /* check and see if we're removing the default image */
2177        if (isdigit(*image)) {
2178     entry = findEntryByPath(cfg, image, prefix, NULL);
2179     if(entry)
2180        entry->skip = 1;
2181     return;
2182        }
2183    
2184      while ((entry = findEntryByPath(cfg, image, prefix, NULL)))      while ((entry = findEntryByPath(cfg, image, prefix, NULL)))
2185   entry->skip = 1;   entry->skip = 1;
# Line 1610  void markRemovedImage(struct grubConfig Line 2187  void markRemovedImage(struct grubConfig
2187    
2188  void setDefaultImage(struct grubConfig * config, int hasNew,  void setDefaultImage(struct grubConfig * config, int hasNew,
2189       const char * defaultKernelPath, int newIsDefault,       const char * defaultKernelPath, int newIsDefault,
2190       const char * prefix, int flags) {       const char * prefix, int flags, int index) {
2191      struct singleEntry * entry, * entry2, * newDefault;      struct singleEntry * entry, * entry2, * newDefault;
2192      int i, j;      int i, j;
2193    
2194      if (newIsDefault) {      if (newIsDefault) {
2195   config->defaultImage = 0;   config->defaultImage = 0;
2196   return;   return;
2197        } else if ((index >= 0) && config->cfi->defaultIsIndex) {
2198     if (findEntryByIndex(config, index))
2199        config->defaultImage = index;
2200     else
2201        config->defaultImage = -1;
2202     return;
2203      } else if (defaultKernelPath) {      } else if (defaultKernelPath) {
2204   i = 0;   i = 0;
2205   if (findEntryByPath(config, defaultKernelPath, prefix, &i)) {   if (findEntryByPath(config, defaultKernelPath, prefix, &i)) {
# Line 1629  void setDefaultImage(struct grubConfig * Line 2212  void setDefaultImage(struct grubConfig *
2212    
2213      /* defaultImage now points to what we'd like to use, but before any order      /* defaultImage now points to what we'd like to use, but before any order
2214         changes */         changes */
2215      if (config->defaultImage == DEFAULT_SAVED)      if ((config->defaultImage == DEFAULT_SAVED) ||
2216     (config->defaultImage == DEFAULT_SAVED_GRUB2))
2217        /* default is set to saved, we don't want to change it */        /* default is set to saved, we don't want to change it */
2218        return;        return;
2219    
# Line 1690  void displayEntry(struct singleEntry * e Line 2274  void displayEntry(struct singleEntry * e
2274    
2275      printf("index=%d\n", index);      printf("index=%d\n", index);
2276    
2277      line = getLineByType(LT_KERNEL|LT_HYPER, entry->lines);      line = getLineByType(LT_KERNEL|LT_HYPER|LT_KERNEL_EFI|LT_KERNEL_16, entry->lines);
2278      if (!line) {      if (!line) {
2279          printf("non linux entry\n");          printf("non linux entry\n");
2280          return;          return;
2281      }      }
2282    
2283      printf("kernel=%s\n", line->elements[1].item);      if (!strncmp(prefix, line->elements[1].item, strlen(prefix)))
2284     printf("kernel=%s\n", line->elements[1].item);
2285        else
2286     printf("kernel=%s%s\n", prefix, line->elements[1].item);
2287    
2288      if (line->numElements >= 3) {      if (line->numElements >= 3) {
2289   printf("args=\"");   printf("args=\"");
# Line 1752  void displayEntry(struct singleEntry * e Line 2339  void displayEntry(struct singleEntry * e
2339   printf("root=%s\n", s);   printf("root=%s\n", s);
2340      }      }
2341    
2342      line = getLineByType(LT_INITRD, entry->lines);      line = getLineByType(LT_INITRD|LT_INITRD_EFI|LT_INITRD_16, entry->lines);
2343    
2344      if (line && line->numElements >= 2) {      if (line && line->numElements >= 2) {
2345   printf("initrd=%s", prefix);   if (!strncmp(prefix, line->elements[1].item, strlen(prefix)))
2346        printf("initrd=");
2347     else
2348        printf("initrd=%s", prefix);
2349    
2350   for (i = 1; i < line->numElements; i++)   for (i = 1; i < line->numElements; i++)
2351      printf("%s%s", line->elements[i].item, line->elements[i].indent);      printf("%s%s", line->elements[i].item, line->elements[i].indent);
2352   printf("\n");   printf("\n");
2353      }      }
2354    
2355        line = getLineByType(LT_TITLE, entry->lines);
2356        if (line) {
2357     printf("title=%s\n", line->elements[1].item);
2358        } else {
2359     char * title;
2360     line = getLineByType(LT_MENUENTRY, entry->lines);
2361     title = grub2ExtractTitle(line);
2362     if (title)
2363        printf("title=%s\n", title);
2364        }
2365    }
2366    
2367    int isSuseSystem(void) {
2368        const char * path;
2369        const static char default_path[] = "/etc/SuSE-release";
2370    
2371        if ((path = getenv("GRUBBY_SUSE_RELEASE")) == NULL)
2372     path = default_path;
2373    
2374        if (!access(path, R_OK))
2375     return 1;
2376        return 0;
2377    }
2378    
2379    int isSuseGrubConf(const char * path) {
2380        FILE * grubConf;
2381        char * line = NULL;
2382        size_t len = 0, res = 0;
2383    
2384        grubConf = fopen(path, "r");
2385        if (!grubConf) {
2386            dbgPrintf("Could not open SuSE configuration file '%s'\n", path);
2387     return 0;
2388        }
2389    
2390        while ((res = getline(&line, &len, grubConf)) != -1) {
2391     if (!strncmp(line, "setup", 5)) {
2392        fclose(grubConf);
2393        free(line);
2394        return 1;
2395     }
2396        }
2397    
2398        dbgPrintf("SuSE configuration file '%s' does not appear to be valid\n",
2399          path);
2400    
2401        fclose(grubConf);
2402        free(line);
2403        return 0;
2404    }
2405    
2406    int suseGrubConfGetLba(const char * path, int * lbaPtr) {
2407        FILE * grubConf;
2408        char * line = NULL;
2409        size_t res = 0, len = 0;
2410    
2411        if (!path) return 1;
2412        if (!lbaPtr) return 1;
2413    
2414        grubConf = fopen(path, "r");
2415        if (!grubConf) return 1;
2416    
2417        while ((res = getline(&line, &len, grubConf)) != -1) {
2418     if (line[res - 1] == '\n')
2419        line[res - 1] = '\0';
2420     else if (len > res)
2421        line[res] = '\0';
2422     else {
2423        line = realloc(line, res + 1);
2424        line[res] = '\0';
2425     }
2426    
2427     if (!strncmp(line, "setup", 5)) {
2428        if (strstr(line, "--force-lba")) {
2429            *lbaPtr = 1;
2430        } else {
2431            *lbaPtr = 0;
2432        }
2433        dbgPrintf("lba: %i\n", *lbaPtr);
2434        break;
2435     }
2436        }
2437    
2438        free(line);
2439        fclose(grubConf);
2440        return 0;
2441    }
2442    
2443    int suseGrubConfGetInstallDevice(const char * path, char ** devicePtr) {
2444        FILE * grubConf;
2445        char * line = NULL;
2446        size_t res = 0, len = 0;
2447        char * lastParamPtr = NULL;
2448        char * secLastParamPtr = NULL;
2449        char installDeviceNumber = '\0';
2450        char * bounds = NULL;
2451    
2452        if (!path) return 1;
2453        if (!devicePtr) return 1;
2454    
2455        grubConf = fopen(path, "r");
2456        if (!grubConf) return 1;
2457    
2458        while ((res = getline(&line, &len, grubConf)) != -1) {
2459     if (strncmp(line, "setup", 5))
2460        continue;
2461    
2462     if (line[res - 1] == '\n')
2463        line[res - 1] = '\0';
2464     else if (len > res)
2465        line[res] = '\0';
2466     else {
2467        line = realloc(line, res + 1);
2468        line[res] = '\0';
2469     }
2470    
2471     lastParamPtr = bounds = line + res;
2472    
2473     /* Last parameter in grub may be an optional IMAGE_DEVICE */
2474     while (!isspace(*lastParamPtr))
2475        lastParamPtr--;
2476     lastParamPtr++;
2477    
2478     secLastParamPtr = lastParamPtr - 2;
2479     dbgPrintf("lastParamPtr: %s\n", lastParamPtr);
2480    
2481     if (lastParamPtr + 3 > bounds) {
2482        dbgPrintf("lastParamPtr going over boundary");
2483        fclose(grubConf);
2484        free(line);
2485        return 1;
2486     }
2487     if (!strncmp(lastParamPtr, "(hd", 3))
2488        lastParamPtr += 3;
2489     dbgPrintf("lastParamPtr: %c\n", *lastParamPtr);
2490    
2491     /*
2492     * Second last parameter will decide wether last parameter is
2493     * an IMAGE_DEVICE or INSTALL_DEVICE
2494     */
2495     while (!isspace(*secLastParamPtr))
2496        secLastParamPtr--;
2497     secLastParamPtr++;
2498    
2499     if (secLastParamPtr + 3 > bounds) {
2500        dbgPrintf("secLastParamPtr going over boundary");
2501        fclose(grubConf);
2502        free(line);
2503        return 1;
2504     }
2505     dbgPrintf("secLastParamPtr: %s\n", secLastParamPtr);
2506     if (!strncmp(secLastParamPtr, "(hd", 3)) {
2507        secLastParamPtr += 3;
2508        dbgPrintf("secLastParamPtr: %c\n", *secLastParamPtr);
2509        installDeviceNumber = *secLastParamPtr;
2510     } else {
2511        installDeviceNumber = *lastParamPtr;
2512     }
2513    
2514     *devicePtr = malloc(6);
2515     snprintf(*devicePtr, 6, "(hd%c)", installDeviceNumber);
2516     dbgPrintf("installDeviceNumber: %c\n", installDeviceNumber);
2517     fclose(grubConf);
2518     free(line);
2519     return 0;
2520        }
2521    
2522        free(line);
2523        fclose(grubConf);
2524        return 1;
2525    }
2526    
2527    int grubGetBootFromDeviceMap(const char * device,
2528         char ** bootPtr) {
2529        FILE * deviceMap;
2530        char * line = NULL;
2531        size_t res = 0, len = 0;
2532        char * devicePtr;
2533        char * bounds = NULL;
2534        const char * path;
2535        const static char default_path[] = "/boot/grub/device.map";
2536    
2537        if (!device) return 1;
2538        if (!bootPtr) return 1;
2539    
2540        if ((path = getenv("GRUBBY_GRUB_DEVICE_MAP")) == NULL)
2541     path = default_path;
2542    
2543        dbgPrintf("opening grub device.map file from: %s\n", path);
2544        deviceMap = fopen(path, "r");
2545        if (!deviceMap)
2546     return 1;
2547    
2548        while ((res = getline(&line, &len, deviceMap)) != -1) {
2549            if (!strncmp(line, "#", 1))
2550        continue;
2551    
2552     if (line[res - 1] == '\n')
2553        line[res - 1] = '\0';
2554     else if (len > res)
2555        line[res] = '\0';
2556     else {
2557        line = realloc(line, res + 1);
2558        line[res] = '\0';
2559     }
2560    
2561     devicePtr = line;
2562     bounds = line + res;
2563    
2564     while ((isspace(*line) && ((devicePtr + 1) <= bounds)))
2565        devicePtr++;
2566     dbgPrintf("device: %s\n", devicePtr);
2567    
2568     if (!strncmp(devicePtr, device, strlen(device))) {
2569        devicePtr += strlen(device);
2570        while (isspace(*devicePtr) && ((devicePtr + 1) <= bounds))
2571            devicePtr++;
2572    
2573        *bootPtr = strdup(devicePtr);
2574        break;
2575     }
2576        }
2577    
2578        free(line);
2579        fclose(deviceMap);
2580        return 0;
2581    }
2582    
2583    int suseGrubConfGetBoot(const char * path, char ** bootPtr) {
2584        char * grubDevice;
2585    
2586        if (suseGrubConfGetInstallDevice(path, &grubDevice))
2587     dbgPrintf("error looking for grub installation device\n");
2588        else
2589     dbgPrintf("grubby installation device: %s\n", grubDevice);
2590    
2591        if (grubGetBootFromDeviceMap(grubDevice, bootPtr))
2592     dbgPrintf("error looking for grub boot device\n");
2593        else
2594     dbgPrintf("grubby boot device: %s\n", *bootPtr);
2595    
2596        free(grubDevice);
2597        return 0;
2598    }
2599    
2600    int parseSuseGrubConf(int * lbaPtr, char ** bootPtr) {
2601        /*
2602         * This SuSE grub configuration file at this location is not your average
2603         * grub configuration file, but instead the grub commands used to setup
2604         * grub on that system.
2605         */
2606        const char * path;
2607        const static char default_path[] = "/etc/grub.conf";
2608    
2609        if ((path = getenv("GRUBBY_SUSE_GRUB_CONF")) == NULL)
2610     path = default_path;
2611    
2612        if (!isSuseGrubConf(path)) return 1;
2613    
2614        if (lbaPtr) {
2615            *lbaPtr = 0;
2616            if (suseGrubConfGetLba(path, lbaPtr))
2617                return 1;
2618        }
2619    
2620        if (bootPtr) {
2621            *bootPtr = NULL;
2622            suseGrubConfGetBoot(path, bootPtr);
2623        }
2624    
2625        return 0;
2626  }  }
2627    
2628  int parseSysconfigGrub(int * lbaPtr, char ** bootPtr) {  int parseSysconfigGrub(int * lbaPtr, char ** bootPtr) {
# Line 1810  int parseSysconfigGrub(int * lbaPtr, cha Line 2673  int parseSysconfigGrub(int * lbaPtr, cha
2673  }  }
2674    
2675  void dumpSysconfigGrub(void) {  void dumpSysconfigGrub(void) {
2676      char * boot;      char * boot = NULL;
2677      int lba;      int lba;
2678    
2679      if (!parseSysconfigGrub(&lba, &boot)) {      if (isSuseSystem()) {
2680   if (lba) printf("lba\n");          if (parseSuseGrubConf(&lba, &boot)) {
2681   if (boot) printf("boot=%s\n", boot);      free(boot);
2682        return;
2683     }
2684        } else {
2685            if (parseSysconfigGrub(&lba, &boot)) {
2686        free(boot);
2687        return;
2688     }
2689        }
2690    
2691        if (lba) printf("lba\n");
2692        if (boot) {
2693     printf("boot=%s\n", boot);
2694     free(boot);
2695      }      }
2696  }  }
2697    
# Line 1864  struct singleLine * addLineTmpl(struct s Line 2740  struct singleLine * addLineTmpl(struct s
2740  {  {
2741      struct singleLine * newLine = lineDup(tmplLine);      struct singleLine * newLine = lineDup(tmplLine);
2742    
2743        if (isEfi && cfi == &grub2ConfigType) {
2744     enum lineType_e old = newLine->type;
2745     newLine->type = preferredLineType(newLine->type, cfi);
2746     if (old != newLine->type)
2747        newLine->elements[0].item = getKeyByType(newLine->type, cfi);
2748        }
2749    
2750      if (val) {      if (val) {
2751   /* override the inherited value with our own.   /* override the inherited value with our own.
2752   * This is a little weak because it only applies to elements[1]   * This is a little weak because it only applies to elements[1]
# Line 1873  struct singleLine * addLineTmpl(struct s Line 2756  struct singleLine * addLineTmpl(struct s
2756   insertElement(newLine, val, 1, cfi);   insertElement(newLine, val, 1, cfi);
2757    
2758   /* but try to keep the rootspec from the template... sigh */   /* but try to keep the rootspec from the template... sigh */
2759   if (tmplLine->type & (LT_HYPER|LT_KERNEL|LT_MBMODULE|LT_INITRD)) {   if (tmplLine->type & (LT_HYPER|LT_KERNEL|LT_MBMODULE|LT_INITRD|LT_KERNEL_EFI|LT_INITRD_EFI|LT_KERNEL_16|LT_INITRD_16)) {
2760      char * rootspec = getRootSpecifier(tmplLine->elements[1].item);      char * rootspec = getRootSpecifier(tmplLine->elements[1].item);
2761      if (rootspec != NULL) {      if (rootspec != NULL) {
2762   free(newLine->elements[1].item);   free(newLine->elements[1].item);
# Line 1910  struct singleLine *  addLine(struct sing Line 2793  struct singleLine *  addLine(struct sing
2793      /* NB: This function shouldn't allocate items on the heap, rather on the      /* NB: This function shouldn't allocate items on the heap, rather on the
2794       * stack since it calls addLineTmpl which will make copies.       * stack since it calls addLineTmpl which will make copies.
2795       */       */
   
2796      if (type == LT_TITLE && cfi->titleBracketed) {      if (type == LT_TITLE && cfi->titleBracketed) {
2797   /* we're doing a bracketed title (zipl) */   /* we're doing a bracketed title (zipl) */
2798   tmpl.type = type;   tmpl.type = type;
# Line 2014  void removeLine(struct singleEntry * ent Line 2896  void removeLine(struct singleEntry * ent
2896      free(line);      free(line);
2897  }  }
2898    
 static int isquote(char q)  
 {  
     if (q == '\'' || q == '\"')  
  return 1;  
     return 0;  
 }  
   
2899  static void requote(struct singleLine *tmplLine, struct configFileInfo * cfi)  static void requote(struct singleLine *tmplLine, struct configFileInfo * cfi)
2900  {  {
2901      struct singleLine newLine = {      struct singleLine newLine = {
# Line 2251  int updateActualImage(struct grubConfig Line 3126  int updateActualImage(struct grubConfig
3126      firstElement = 2;      firstElement = 2;
3127    
3128   } else {   } else {
3129      line = getLineByType(LT_KERNEL|LT_MBMODULE, entry->lines);      line = getLineByType(LT_KERNEL|LT_MBMODULE|LT_KERNEL_EFI|LT_KERNEL_16, entry->lines);
3130      if (!line) {      if (!line) {
3131   /* no LT_KERNEL or LT_MBMODULE in this entry? */   /* no LT_KERNEL or LT_MBMODULE in this entry? */
3132   continue;   continue;
# Line 2407  int updateImage(struct grubConfig * cfg, Line 3282  int updateImage(struct grubConfig * cfg,
3282      return rc;      return rc;
3283  }  }
3284    
3285    int addMBInitrd(struct grubConfig * cfg, const char *newMBKernel,
3286     const char * image, const char * prefix, const char * initrd) {
3287        struct singleEntry * entry;
3288        struct singleLine * line, * kernelLine, *endLine = NULL;
3289        int index = 0;
3290    
3291        if (!image) return 0;
3292    
3293        for (; (entry = findEntryByPath(cfg, newMBKernel, prefix, &index)); index++) {
3294            kernelLine = getLineByType(LT_MBMODULE, entry->lines);
3295            if (!kernelLine) continue;
3296    
3297            if (prefix) {
3298                int prefixLen = strlen(prefix);
3299                if (!strncmp(initrd, prefix, prefixLen))
3300                    initrd += prefixLen;
3301            }
3302     endLine = getLineByType(LT_ENTRY_END, entry->lines);
3303     if (endLine)
3304        removeLine(entry, endLine);
3305            line = addLine(entry, cfg->cfi, preferredLineType(LT_MBMODULE,cfg->cfi),
3306     kernelLine->indent, initrd);
3307            if (!line)
3308        return 1;
3309     if (endLine) {
3310        line = addLine(entry, cfg->cfi, LT_ENTRY_END, "", NULL);
3311                if (!line)
3312     return 1;
3313     }
3314    
3315            break;
3316        }
3317    
3318        return 0;
3319    }
3320    
3321  int updateInitrd(struct grubConfig * cfg, const char * image,  int updateInitrd(struct grubConfig * cfg, const char * image,
3322                   const char * prefix, const char * initrd) {                   const char * prefix, const char * initrd) {
3323      struct singleEntry * entry;      struct singleEntry * entry;
# Line 2416  int updateInitrd(struct grubConfig * cfg Line 3327  int updateInitrd(struct grubConfig * cfg
3327      if (!image) return 0;      if (!image) return 0;
3328    
3329      for (; (entry = findEntryByPath(cfg, image, prefix, &index)); index++) {      for (; (entry = findEntryByPath(cfg, image, prefix, &index)); index++) {
3330          kernelLine = getLineByType(LT_KERNEL, entry->lines);          kernelLine = getLineByType(LT_KERNEL|LT_KERNEL_EFI|LT_KERNEL_16, entry->lines);
3331          if (!kernelLine) continue;          if (!kernelLine) continue;
3332    
3333          line = getLineByType(LT_INITRD, entry->lines);          line = getLineByType(LT_INITRD|LT_INITRD_EFI|LT_INITRD_16, entry->lines);
3334          if (line)          if (line)
3335              removeLine(entry, line);              removeLine(entry, line);
3336          if (prefix) {          if (prefix) {
# Line 2430  int updateInitrd(struct grubConfig * cfg Line 3341  int updateInitrd(struct grubConfig * cfg
3341   endLine = getLineByType(LT_ENTRY_END, entry->lines);   endLine = getLineByType(LT_ENTRY_END, entry->lines);
3342   if (endLine)   if (endLine)
3343      removeLine(entry, endLine);      removeLine(entry, endLine);
3344          line = addLine(entry, cfg->cfi, LT_INITRD, kernelLine->indent, initrd);   enum lineType_e lt;
3345     switch(kernelLine->type) {
3346        case LT_KERNEL:
3347            lt = LT_INITRD;
3348     break;
3349        case LT_KERNEL_EFI:
3350            lt = LT_INITRD_EFI;
3351     break;
3352        case LT_KERNEL_16:
3353            lt = LT_INITRD_16;
3354     break;
3355        default:
3356            lt = preferredLineType(LT_INITRD, cfg->cfi);
3357     }
3358            line = addLine(entry, cfg->cfi, lt, kernelLine->indent, initrd);
3359          if (!line)          if (!line)
3360      return 1;      return 1;
3361   if (endLine) {   if (endLine) {
# Line 2468  int checkDeviceBootloader(const char * d Line 3393  int checkDeviceBootloader(const char * d
3393      if (memcmp(boot, bootSect, 3))      if (memcmp(boot, bootSect, 3))
3394   return 0;   return 0;
3395    
3396      if (boot[1] == 0xeb) {      if (boot[1] == JMP_SHORT_OPCODE) {
3397   offset = boot[2] + 2;   offset = boot[2] + 2;
3398      } else if (boot[1] == 0xe8 || boot[1] == 0xe9) {      } else if (boot[1] == 0xe8 || boot[1] == 0xe9) {
3399   offset = (boot[3] << 8) + boot[2] + 2;   offset = (boot[3] << 8) + boot[2] + 2;
3400      } else if (boot[0] == 0xeb) {      } else if (boot[0] == JMP_SHORT_OPCODE) {
3401   offset = boot[1] + 2;        offset = boot[1] + 2;
3402            /*
3403     * it looks like grub, when copying stage1 into the mbr, patches stage1
3404     * right after the JMP location, replacing other instructions such as
3405     * JMPs for NOOPs. So, relax the check a little bit by skipping those
3406     * different bytes.
3407     */
3408          if ((bootSect[offset + 1] == NOOP_OPCODE)
3409      && (bootSect[offset + 2] == NOOP_OPCODE)) {
3410     offset = offset + 3;
3411          }
3412      } else if (boot[0] == 0xe8 || boot[0] == 0xe9) {      } else if (boot[0] == 0xe8 || boot[0] == 0xe9) {
3413   offset = (boot[2] << 8) + boot[1] + 2;   offset = (boot[2] << 8) + boot[1] + 2;
3414      } else {      } else {
# Line 2626  int checkForGrub(struct grubConfig * con Line 3561  int checkForGrub(struct grubConfig * con
3561      int fd;      int fd;
3562      unsigned char bootSect[512];      unsigned char bootSect[512];
3563      char * boot;      char * boot;
3564        int onSuse = isSuseSystem();
3565    
3566      if (parseSysconfigGrub(NULL, &boot))  
3567   return 0;      if (onSuse) {
3568     if (parseSuseGrubConf(NULL, &boot))
3569        return 0;
3570        } else {
3571     if (parseSysconfigGrub(NULL, &boot))
3572        return 0;
3573        }
3574    
3575      /* assume grub is not installed -- not an error condition */      /* assume grub is not installed -- not an error condition */
3576      if (!boot)      if (!boot)
# Line 2647  int checkForGrub(struct grubConfig * con Line 3589  int checkForGrub(struct grubConfig * con
3589      }      }
3590      close(fd);      close(fd);
3591    
3592        /* The more elaborate checks do not work on SuSE. The checks done
3593         * seem to be reasonble (at least for now), so just return success
3594         */
3595        if (onSuse)
3596     return 2;
3597    
3598      return checkDeviceBootloader(boot, bootSect);      return checkDeviceBootloader(boot, bootSect);
3599  }  }
3600    
# Line 2680  int checkForExtLinux(struct grubConfig * Line 3628  int checkForExtLinux(struct grubConfig *
3628      return checkDeviceBootloader(boot, bootSect);      return checkDeviceBootloader(boot, bootSect);
3629  }  }
3630    
3631    int checkForYaboot(struct grubConfig * config) {
3632        /*
3633         * This is a simplistic check that we consider good enough for own puporses
3634         *
3635         * If we were to properly check if yaboot is *installed* we'd need to:
3636         * 1) get the system boot device (LT_BOOT)
3637         * 2) considering it's a raw filesystem, check if the yaboot binary matches
3638         *    the content on the boot device
3639         * 3) if not, copy the binary to a temporary file and run "addnote" on it
3640         * 4) check again if binary and boot device contents match
3641         */
3642        if (!access("/etc/yaboot.conf", R_OK))
3643     return 2;
3644    
3645        return 1;
3646    }
3647    
3648    int checkForElilo(struct grubConfig * config) {
3649        if (!access("/etc/elilo.conf", R_OK))
3650     return 2;
3651    
3652        return 1;
3653    }
3654    
3655  static char * getRootSpecifier(char * str) {  static char * getRootSpecifier(char * str) {
3656      char * idx, * rootspec = NULL;      char * idx, * rootspec = NULL;
3657    
# Line 2694  static char * getRootSpecifier(char * st Line 3666  static char * getRootSpecifier(char * st
3666  static char * getInitrdVal(struct grubConfig * config,  static char * getInitrdVal(struct grubConfig * config,
3667     const char * prefix, struct singleLine *tmplLine,     const char * prefix, struct singleLine *tmplLine,
3668     const char * newKernelInitrd,     const char * newKernelInitrd,
3669     char ** extraInitrds, int extraInitrdCount)     const char ** extraInitrds, int extraInitrdCount)
3670  {  {
3671      char *initrdVal, *end;      char *initrdVal, *end;
3672      int i;      int i;
# Line 2739  static char * getInitrdVal(struct grubCo Line 3711  static char * getInitrdVal(struct grubCo
3711    
3712  int addNewKernel(struct grubConfig * config, struct singleEntry * template,  int addNewKernel(struct grubConfig * config, struct singleEntry * template,
3713           const char * prefix,           const char * prefix,
3714   char * newKernelPath, char * newKernelTitle,   const char * newKernelPath, const char * newKernelTitle,
3715   char * newKernelArgs, char * newKernelInitrd,   const char * newKernelArgs, const char * newKernelInitrd,
3716   char ** extraInitrds, int extraInitrdCount,   const char ** extraInitrds, int extraInitrdCount,
3717                   char * newMBKernel, char * newMBKernelArgs) {                   const char * newMBKernel, const char * newMBKernelArgs,
3718     const char * newDevTreePath) {
3719      struct singleEntry * new;      struct singleEntry * new;
3720      struct singleLine * newLine = NULL, * tmplLine = NULL, * masterLine = NULL;      struct singleLine * newLine = NULL, * tmplLine = NULL, * masterLine = NULL;
3721      int needs;      int needs;
# Line 2783  int addNewKernel(struct grubConfig * con Line 3756  int addNewKernel(struct grubConfig * con
3756          needs |= NEED_MB;          needs |= NEED_MB;
3757          new->multiboot = 1;          new->multiboot = 1;
3758      }      }
3759        if (newDevTreePath && getKeywordByType(LT_DEVTREE, config->cfi))
3760     needs |= NEED_DEVTREE;
3761    
3762      if (template) {      if (template) {
3763   for (masterLine = template->lines;   for (masterLine = template->lines;
# Line 2796  int addNewKernel(struct grubConfig * con Line 3771  int addNewKernel(struct grubConfig * con
3771      while (*chptr && isspace(*chptr)) chptr++;      while (*chptr && isspace(*chptr)) chptr++;
3772      if (*chptr == '#') continue;      if (*chptr == '#') continue;
3773    
3774      if (tmplLine->type == LT_KERNEL &&      if (iskernel(tmplLine->type) && tmplLine->numElements >= 2) {
     tmplLine->numElements >= 2) {  
3775   if (!template->multiboot && (needs & NEED_MB)) {   if (!template->multiboot && (needs & NEED_MB)) {
3776      /* it's not a multiboot template and this is the kernel      /* it's not a multiboot template and this is the kernel
3777       * line.  Try to be intelligent about inserting the       * line.  Try to be intelligent about inserting the
# Line 2874  int addNewKernel(struct grubConfig * con Line 3848  int addNewKernel(struct grubConfig * con
3848      /* template is multi but new is not,      /* template is multi but new is not,
3849       * insert the kernel in the first module slot       * insert the kernel in the first module slot
3850       */       */
3851      tmplLine->type = LT_KERNEL;      tmplLine->type = preferredLineType(LT_KERNEL, config->cfi);
3852      free(tmplLine->elements[0].item);      free(tmplLine->elements[0].item);
3853      tmplLine->elements[0].item =      tmplLine->elements[0].item =
3854   strdup(getKeywordByType(LT_KERNEL, config->cfi)->key);   strdup(getKeywordByType(tmplLine->type,
3855     config->cfi)->key);
3856      newLine = addLineTmpl(new, tmplLine, newLine,      newLine = addLineTmpl(new, tmplLine, newLine,
3857    newKernelPath + strlen(prefix), config->cfi);    newKernelPath + strlen(prefix),
3858      config->cfi);
3859      needs &= ~NEED_KERNEL;      needs &= ~NEED_KERNEL;
3860   } else if (needs & NEED_INITRD) {   } else if (needs & NEED_INITRD) {
3861      char *initrdVal;      char *initrdVal;
3862      /* template is multi but new is not,      /* template is multi but new is not,
3863       * insert the initrd in the second module slot       * insert the initrd in the second module slot
3864       */       */
3865      tmplLine->type = LT_INITRD;      tmplLine->type = preferredLineType(LT_INITRD, config->cfi);
3866      free(tmplLine->elements[0].item);      free(tmplLine->elements[0].item);
3867      tmplLine->elements[0].item =      tmplLine->elements[0].item =
3868   strdup(getKeywordByType(LT_INITRD, config->cfi)->key);   strdup(getKeywordByType(tmplLine->type,
3869     config->cfi)->key);
3870      initrdVal = getInitrdVal(config, prefix, tmplLine, newKernelInitrd, extraInitrds, extraInitrdCount);      initrdVal = getInitrdVal(config, prefix, tmplLine, newKernelInitrd, extraInitrds, extraInitrdCount);
3871      newLine = addLineTmpl(new, tmplLine, newLine, initrdVal, config->cfi);      newLine = addLineTmpl(new, tmplLine, newLine, initrdVal, config->cfi);
3872      free(initrdVal);      free(initrdVal);
3873      needs &= ~NEED_INITRD;      needs &= ~NEED_INITRD;
3874   }   }
3875    
3876      } else if (tmplLine->type == LT_INITRD &&      } else if (isinitrd(tmplLine->type) && tmplLine->numElements >= 2) {
        tmplLine->numElements >= 2) {  
3877   if (needs & NEED_INITRD &&   if (needs & NEED_INITRD &&
3878      new->multiboot && !template->multiboot &&      new->multiboot && !template->multiboot &&
3879      config->cfi->mbInitRdIsModule) {      config->cfi->mbInitRdIsModule) {
# Line 2948  int addNewKernel(struct grubConfig * con Line 3924  int addNewKernel(struct grubConfig * con
3924   }   }
3925      } else if (tmplLine->type == LT_ECHO) {      } else if (tmplLine->type == LT_ECHO) {
3926      requote(tmplLine, config->cfi);      requote(tmplLine, config->cfi);
3927        static const char *prefix = "'Loading ";
3928      if (tmplLine->numElements > 1 &&      if (tmplLine->numElements > 1 &&
3929      strstr(tmplLine->elements[1].item, "'Loading Linux ")) {      strstr(tmplLine->elements[1].item, prefix) &&
3930   char *prefix = "'Loading ";      masterLine->next &&
3931        iskernel(masterLine->next->type)) {
3932   char *newTitle = malloc(strlen(prefix) +   char *newTitle = malloc(strlen(prefix) +
3933   strlen(newKernelTitle) + 2);   strlen(newKernelTitle) + 2);
3934    
# Line 2965  int addNewKernel(struct grubConfig * con Line 3943  int addNewKernel(struct grubConfig * con
3943   newLine = addLineTmpl(new, tmplLine, newLine, NULL,   newLine = addLineTmpl(new, tmplLine, newLine, NULL,
3944   config->cfi);   config->cfi);
3945      }      }
3946        } else if (tmplLine->type == LT_DEVTREE &&
3947           tmplLine->numElements == 2 && newDevTreePath) {
3948            newLine = addLineTmpl(new, tmplLine, newLine,
3949          newDevTreePath + strlen(prefix),
3950          config->cfi);
3951     needs &= ~NEED_DEVTREE;
3952        } else if (tmplLine->type == LT_ENTRY_END && needs & NEED_DEVTREE) {
3953     const char *ndtp = newDevTreePath;
3954     if (!strncmp(newDevTreePath, prefix, strlen(prefix)))
3955        ndtp += strlen(prefix);
3956     newLine = addLine(new, config->cfi, LT_DEVTREE,
3957      config->secondaryIndent,
3958      ndtp);
3959     needs &= ~NEED_DEVTREE;
3960     newLine = addLineTmpl(new, tmplLine, newLine, NULL, config->cfi);
3961      } else {      } else {
3962   /* pass through other lines from the template */   /* pass through other lines from the template */
3963   newLine = addLineTmpl(new, tmplLine, newLine, NULL, config->cfi);   newLine = addLineTmpl(new, tmplLine, newLine, NULL, config->cfi);
# Line 2977  int addNewKernel(struct grubConfig * con Line 3970  int addNewKernel(struct grubConfig * con
3970   */   */
3971   switch (config->cfi->entryStart) {   switch (config->cfi->entryStart) {
3972      case LT_KERNEL:      case LT_KERNEL:
3973        case LT_KERNEL_EFI:
3974        case LT_KERNEL_16:
3975   if (new->multiboot && config->cfi->mbHyperFirst) {   if (new->multiboot && config->cfi->mbHyperFirst) {
3976      /* fall through to LT_HYPER */      /* fall through to LT_HYPER */
3977   } else {   } else {
3978      newLine = addLine(new, config->cfi, LT_KERNEL,      newLine = addLine(new, config->cfi,
3979              preferredLineType(LT_KERNEL, config->cfi),
3980        config->primaryIndent,        config->primaryIndent,
3981        newKernelPath + strlen(prefix));        newKernelPath + strlen(prefix));
3982      needs &= ~NEED_KERNEL;      needs &= ~NEED_KERNEL;
# Line 3056  int addNewKernel(struct grubConfig * con Line 4052  int addNewKernel(struct grubConfig * con
4052      if (needs & NEED_KERNEL) {      if (needs & NEED_KERNEL) {
4053   newLine = addLine(new, config->cfi,   newLine = addLine(new, config->cfi,
4054    (new->multiboot && getKeywordByType(LT_MBMODULE,    (new->multiboot && getKeywordByType(LT_MBMODULE,
4055        config->cfi)) ?        config->cfi))
4056    LT_MBMODULE : LT_KERNEL,     ? LT_MBMODULE
4057     : preferredLineType(LT_KERNEL, config->cfi),
4058    config->secondaryIndent,    config->secondaryIndent,
4059    newKernelPath + strlen(prefix));    newKernelPath + strlen(prefix));
4060   needs &= ~NEED_KERNEL;   needs &= ~NEED_KERNEL;
# Line 3073  int addNewKernel(struct grubConfig * con Line 4070  int addNewKernel(struct grubConfig * con
4070   initrdVal = getInitrdVal(config, prefix, NULL, newKernelInitrd, extraInitrds, extraInitrdCount);   initrdVal = getInitrdVal(config, prefix, NULL, newKernelInitrd, extraInitrds, extraInitrdCount);
4071   newLine = addLine(new, config->cfi,   newLine = addLine(new, config->cfi,
4072    (new->multiboot && getKeywordByType(LT_MBMODULE,    (new->multiboot && getKeywordByType(LT_MBMODULE,
4073        config->cfi)) ?        config->cfi))
4074    LT_MBMODULE : LT_INITRD,     ? LT_MBMODULE
4075       : preferredLineType(LT_INITRD, config->cfi),
4076    config->secondaryIndent,    config->secondaryIndent,
4077    initrdVal);    initrdVal);
4078   free(initrdVal);   free(initrdVal);
4079   needs &= ~NEED_INITRD;   needs &= ~NEED_INITRD;
4080      }      }
4081        if (needs & NEED_DEVTREE) {
4082     newLine = addLine(new, config->cfi, LT_DEVTREE,
4083      config->secondaryIndent,
4084      newDevTreePath);
4085     needs &= ~NEED_DEVTREE;
4086        }
4087    
4088        /* NEEDS_END must be last on bootloaders that need it... */
4089      if (needs & NEED_END) {      if (needs & NEED_END) {
4090   newLine = addLine(new, config->cfi, LT_ENTRY_END,   newLine = addLine(new, config->cfi, LT_ENTRY_END,
4091   config->secondaryIndent, NULL);   config->secondaryIndent, NULL);
4092   needs &= ~NEED_END;   needs &= ~NEED_END;
4093      }      }
   
4094      if (needs) {      if (needs) {
4095   printf(_("grubby: needs=%d, aborting\n"), needs);   printf(_("grubby: needs=%d, aborting\n"), needs);
4096   abort();   abort();
# Line 3106  static void traceback(int signum) Line 4111  static void traceback(int signum)
4111      memset(array, '\0', sizeof (array));      memset(array, '\0', sizeof (array));
4112      size = backtrace(array, 40);      size = backtrace(array, 40);
4113    
4114      fprintf(stderr, "grubby recieved SIGSEGV!  Backtrace (%ld):\n",      fprintf(stderr, "grubby received SIGSEGV!  Backtrace (%ld):\n",
4115              (unsigned long)size);              (unsigned long)size);
4116      backtrace_symbols_fd(array, size, STDERR_FILENO);      backtrace_symbols_fd(array, size, STDERR_FILENO);
4117      exit(1);      exit(1);
# Line 3131  int main(int argc, const char ** argv) { Line 4136  int main(int argc, const char ** argv) {
4136      char * newKernelArgs = NULL;      char * newKernelArgs = NULL;
4137      char * newKernelInitrd = NULL;      char * newKernelInitrd = NULL;
4138      char * newKernelTitle = NULL;      char * newKernelTitle = NULL;
4139      char * newKernelVersion = NULL;      char * newDevTreePath = NULL;
4140      char * newMBKernel = NULL;      char * newMBKernel = NULL;
4141      char * newMBKernelArgs = NULL;      char * newMBKernelArgs = NULL;
4142      char * removeMBKernelArgs = NULL;      char * removeMBKernelArgs = NULL;
# Line 3141  int main(int argc, const char ** argv) { Line 4146  int main(int argc, const char ** argv) {
4146      char * removeArgs = NULL;      char * removeArgs = NULL;
4147      char * kernelInfo = NULL;      char * kernelInfo = NULL;
4148      char * extraInitrds[MAX_EXTRA_INITRDS] = { NULL };      char * extraInitrds[MAX_EXTRA_INITRDS] = { NULL };
4149        char * envPath = NULL;
4150      const char * chptr = NULL;      const char * chptr = NULL;
4151      struct configFileInfo * cfi = NULL;      struct configFileInfo * cfi = NULL;
4152      struct grubConfig * config;      struct grubConfig * config;
4153      struct singleEntry * template = NULL;      struct singleEntry * template = NULL;
4154      int copyDefault = 0, makeDefault = 0;      int copyDefault = 0, makeDefault = 0;
4155      int displayDefault = 0;      int displayDefault = 0;
4156        int displayDefaultIndex = 0;
4157        int displayDefaultTitle = 0;
4158        int defaultIndex = -1;
4159      struct poptOption options[] = {      struct poptOption options[] = {
4160   { "add-kernel", 0, POPT_ARG_STRING, &newKernelPath, 0,   { "add-kernel", 0, POPT_ARG_STRING, &newKernelPath, 0,
4161      _("add an entry for the specified kernel"), _("kernel-path") },      _("add an entry for the specified kernel"), _("kernel-path") },
# Line 3164  int main(int argc, const char ** argv) { Line 4173  int main(int argc, const char ** argv) {
4173   { "boot-filesystem", 0, POPT_ARG_STRING, &bootPrefix, 0,   { "boot-filesystem", 0, POPT_ARG_STRING, &bootPrefix, 0,
4174      _("filestystem which contains /boot directory (for testing only)"),      _("filestystem which contains /boot directory (for testing only)"),
4175      _("bootfs") },      _("bootfs") },
4176  #if defined(__i386__) || defined(__x86_64__)  #if defined(__i386__) || defined(__x86_64__) || defined (__powerpc64__) || defined (__ia64__)
4177   { "bootloader-probe", 0, POPT_ARG_NONE, &bootloaderProbe, 0,   { "bootloader-probe", 0, POPT_ARG_NONE, &bootloaderProbe, 0,
4178      _("check if lilo is installed on lilo.conf boot sector") },      _("check which bootloader is installed on boot sector") },
4179  #endif  #endif
4180   { "config-file", 'c', POPT_ARG_STRING, &grubConfig, 0,   { "config-file", 'c', POPT_ARG_STRING, &grubConfig, 0,
4181      _("path to grub config file to update (\"-\" for stdin)"),      _("path to grub config file to update (\"-\" for stdin)"),
# Line 3177  int main(int argc, const char ** argv) { Line 4186  int main(int argc, const char ** argv) {
4186        "the kernel referenced by the default image does not exist, "        "the kernel referenced by the default image does not exist, "
4187        "the first linux entry whose kernel does exist is used as the "        "the first linux entry whose kernel does exist is used as the "
4188        "template"), NULL },        "template"), NULL },
4189     { "debug", 0, 0, &debug, 0,
4190        _("print debugging information for failures") },
4191   { "default-kernel", 0, 0, &displayDefault, 0,   { "default-kernel", 0, 0, &displayDefault, 0,
4192      _("display the path of the default kernel") },      _("display the path of the default kernel") },
4193     { "default-index", 0, 0, &displayDefaultIndex, 0,
4194        _("display the index of the default kernel") },
4195     { "default-title", 0, 0, &displayDefaultTitle, 0,
4196        _("display the title of the default kernel") },
4197     { "devtree", 0, POPT_ARG_STRING, &newDevTreePath, 0,
4198        _("device tree file for new stanza"), _("dtb-path") },
4199   { "elilo", 0, POPT_ARG_NONE, &configureELilo, 0,   { "elilo", 0, POPT_ARG_NONE, &configureELilo, 0,
4200      _("configure elilo bootloader") },      _("configure elilo bootloader") },
4201     { "efi", 0, POPT_ARG_NONE, &isEfi, 0,
4202        _("force grub2 stanzas to use efi") },
4203     { "env", 0, POPT_ARG_STRING, &envPath, 0,
4204        _("path for environment data"),
4205        _("path") },
4206   { "extlinux", 0, POPT_ARG_NONE, &configureExtLinux, 0,   { "extlinux", 0, POPT_ARG_NONE, &configureExtLinux, 0,
4207      _("configure extlinux bootloader (from syslinux)") },      _("configure extlinux bootloader (from syslinux)") },
4208   { "grub", 0, POPT_ARG_NONE, &configureGrub, 0,   { "grub", 0, POPT_ARG_NONE, &configureGrub, 0,
# Line 3193  int main(int argc, const char ** argv) { Line 4215  int main(int argc, const char ** argv) {
4215   { "initrd", 0, POPT_ARG_STRING, &newKernelInitrd, 0,   { "initrd", 0, POPT_ARG_STRING, &newKernelInitrd, 0,
4216      _("initrd image for the new kernel"), _("initrd-path") },      _("initrd image for the new kernel"), _("initrd-path") },
4217   { "extra-initrd", 'i', POPT_ARG_STRING, NULL, 'i',   { "extra-initrd", 'i', POPT_ARG_STRING, NULL, 'i',
4218      _("auxilliary initrd image for things other than the new kernel"), _("initrd-path") },      _("auxiliary initrd image for things other than the new kernel"), _("initrd-path") },
4219   { "lilo", 0, POPT_ARG_NONE, &configureLilo, 0,   { "lilo", 0, POPT_ARG_NONE, &configureLilo, 0,
4220      _("configure lilo bootloader") },      _("configure lilo bootloader") },
4221   { "make-default", 0, 0, &makeDefault, 0,   { "make-default", 0, 0, &makeDefault, 0,
# Line 3213  int main(int argc, const char ** argv) { Line 4235  int main(int argc, const char ** argv) {
4235   { "set-default", 0, POPT_ARG_STRING, &defaultKernel, 0,   { "set-default", 0, POPT_ARG_STRING, &defaultKernel, 0,
4236      _("make the first entry referencing the specified kernel "      _("make the first entry referencing the specified kernel "
4237        "the default"), _("kernel-path") },        "the default"), _("kernel-path") },
4238     { "set-default-index", 0, POPT_ARG_INT, &defaultIndex, 0,
4239        _("make the given entry index the default entry"),
4240        _("entry-index") },
4241   { "silo", 0, POPT_ARG_NONE, &configureSilo, 0,   { "silo", 0, POPT_ARG_NONE, &configureSilo, 0,
4242      _("configure silo bootloader") },      _("configure silo bootloader") },
4243   { "title", 0, POPT_ARG_STRING, &newKernelTitle, 0,   { "title", 0, POPT_ARG_STRING, &newKernelTitle, 0,
# Line 3234  int main(int argc, const char ** argv) { Line 4259  int main(int argc, const char ** argv) {
4259    
4260      signal(SIGSEGV, traceback);      signal(SIGSEGV, traceback);
4261    
4262        int i = 0;
4263        for (int j = 1; j < argc; j++)
4264     i += strlen(argv[j]) + 1;
4265        saved_command_line = malloc(i);
4266        if (!saved_command_line) {
4267     fprintf(stderr, "grubby: %m\n");
4268     exit(1);
4269        }
4270        saved_command_line[0] = '\0';
4271        for (int j = 1; j < argc; j++) {
4272     strcat(saved_command_line, argv[j]);
4273     strncat(saved_command_line, j == argc -1 ? "" : " ", 1);
4274        }
4275    
4276      optCon = poptGetContext("grubby", argc, argv, options, 0);      optCon = poptGetContext("grubby", argc, argv, options, 0);
4277      poptReadDefaultConfig(optCon, 1);      poptReadDefaultConfig(optCon, 1);
4278    
# Line 3277  int main(int argc, const char ** argv) { Line 4316  int main(int argc, const char ** argv) {
4316   return 1;   return 1;
4317      } else if (configureGrub2) {      } else if (configureGrub2) {
4318   cfi = &grub2ConfigType;   cfi = &grub2ConfigType;
4319     if (envPath)
4320        cfi->envFile = envPath;
4321      } else if (configureLilo) {      } else if (configureLilo) {
4322   cfi = &liloConfigType;   cfi = &liloConfigType;
4323      } else if (configureGrub) {      } else if (configureGrub) {
# Line 3295  int main(int argc, const char ** argv) { Line 4336  int main(int argc, const char ** argv) {
4336      }      }
4337    
4338      if (!cfi) {      if (!cfi) {
4339            if (grub2FindConfig(&grub2ConfigType))
4340        cfi = &grub2ConfigType;
4341     else
4342        #ifdef __ia64__        #ifdef __ia64__
4343   cfi = &eliloConfigType;      cfi = &eliloConfigType;
4344        #elif __powerpc__        #elif __powerpc__
4345   cfi = &yabootConfigType;      cfi = &yabootConfigType;
4346        #elif __sparc__        #elif __sparc__
4347          cfi = &siloConfigType;              cfi = &siloConfigType;
4348        #elif __s390__        #elif __s390__
4349          cfi = &ziplConfigType;              cfi = &ziplConfigType;
4350        #elif __s390x__        #elif __s390x__
4351          cfi = &ziplConfigtype;              cfi = &ziplConfigtype;
4352        #else        #else
         if (grub2FindConfig(&grub2ConfigType))  
     cfi = &grub2ConfigType;  
  else  
4353      cfi = &grubConfigType;      cfi = &grubConfigType;
4354        #endif        #endif
4355      }      }
# Line 3320  int main(int argc, const char ** argv) { Line 4361  int main(int argc, const char ** argv) {
4361      grubConfig = cfi->defaultConfig;      grubConfig = cfi->defaultConfig;
4362      }      }
4363    
4364      if (bootloaderProbe && (displayDefault || kernelInfo || newKernelVersion ||      if (bootloaderProbe && (displayDefault || kernelInfo ||
4365    newKernelPath || removeKernelPath || makeDefault ||      newKernelPath || removeKernelPath || makeDefault ||
4366    defaultKernel)) {      defaultKernel || displayDefaultIndex || displayDefaultTitle ||
4367        (defaultIndex >= 0))) {
4368   fprintf(stderr, _("grubby: --bootloader-probe may not be used with "   fprintf(stderr, _("grubby: --bootloader-probe may not be used with "
4369    "specified option"));    "specified option"));
4370   return 1;   return 1;
4371      }      }
4372    
4373      if ((displayDefault || kernelInfo) && (newKernelVersion || newKernelPath ||      if ((displayDefault || kernelInfo) && (newKernelPath ||
4374     removeKernelPath)) {     removeKernelPath)) {
4375   fprintf(stderr, _("grubby: --default-kernel and --info may not "   fprintf(stderr, _("grubby: --default-kernel and --info may not "
4376    "be used when adding or removing kernels\n"));    "be used when adding or removing kernels\n"));
# Line 3364  int main(int argc, const char ** argv) { Line 4406  int main(int argc, const char ** argv) {
4406   makeDefault = 1;   makeDefault = 1;
4407   defaultKernel = NULL;   defaultKernel = NULL;
4408      }      }
4409        else if (defaultKernel && (defaultIndex >= 0)) {
4410     fprintf(stderr, _("grubby: --set-default and --set-default-index "
4411      "may not be used together\n"));
4412     return 1;
4413        }
4414    
4415      if (grubConfig && !strcmp(grubConfig, "-") && !outputFile) {      if (grubConfig && !strcmp(grubConfig, "-") && !outputFile) {
4416   fprintf(stderr, _("grubby: output file must be specified if stdin "   fprintf(stderr, _("grubby: output file must be specified if stdin "
# Line 3372  int main(int argc, const char ** argv) { Line 4419  int main(int argc, const char ** argv) {
4419      }      }
4420    
4421      if (!removeKernelPath && !newKernelPath && !displayDefault && !defaultKernel      if (!removeKernelPath && !newKernelPath && !displayDefault && !defaultKernel
4422   && !kernelInfo && !bootloaderProbe && !updateKernelPath   && !kernelInfo && !bootloaderProbe && !updateKernelPath
4423          && !removeMBKernel) {   && !removeMBKernel && !displayDefaultIndex && !displayDefaultTitle
4424     && (defaultIndex == -1)) {
4425   fprintf(stderr, _("grubby: no action specified\n"));   fprintf(stderr, _("grubby: no action specified\n"));
4426   return 1;   return 1;
4427      }      }
# Line 3400  int main(int argc, const char ** argv) { Line 4448  int main(int argc, const char ** argv) {
4448      }      }
4449    
4450      if (bootloaderProbe) {      if (bootloaderProbe) {
4451   int lrc = 0, grc = 0, gr2c = 0, erc = 0;   int lrc = 0, grc = 0, gr2c = 0, extrc = 0, yrc = 0, erc = 0;
4452   struct grubConfig * lconfig, * gconfig;   struct grubConfig * lconfig, * gconfig, * yconfig, * econfig;
4453    
4454   const char *grub2config = grub2FindConfig(&grub2ConfigType);   const char *grub2config = grub2FindConfig(&grub2ConfigType);
4455   if (grub2config) {   if (grub2config) {
# Line 3429  int main(int argc, const char ** argv) { Line 4477  int main(int argc, const char ** argv) {
4477   lrc = checkForLilo(lconfig);   lrc = checkForLilo(lconfig);
4478   }   }
4479    
4480     if (!access(eliloConfigType.defaultConfig, F_OK)) {
4481        econfig = readConfig(eliloConfigType.defaultConfig,
4482     &eliloConfigType);
4483        if (!econfig)
4484     erc = 1;
4485        else
4486     erc = checkForElilo(econfig);
4487     }
4488    
4489   if (!access(extlinuxConfigType.defaultConfig, F_OK)) {   if (!access(extlinuxConfigType.defaultConfig, F_OK)) {
4490      lconfig = readConfig(extlinuxConfigType.defaultConfig, &extlinuxConfigType);      lconfig = readConfig(extlinuxConfigType.defaultConfig, &extlinuxConfigType);
4491      if (!lconfig)      if (!lconfig)
4492   erc = 1;   extrc = 1;
4493      else      else
4494   erc = checkForExtLinux(lconfig);   extrc = checkForExtLinux(lconfig);
4495   }   }
4496    
4497   if (lrc == 1 || grc == 1 || gr2c == 1) return 1;  
4498     if (!access(yabootConfigType.defaultConfig, F_OK)) {
4499        yconfig = readConfig(yabootConfigType.defaultConfig,
4500     &yabootConfigType);
4501        if (!yconfig)
4502     yrc = 1;
4503        else
4504     yrc = checkForYaboot(yconfig);
4505     }
4506    
4507     if (lrc == 1 || grc == 1 || gr2c == 1 || extrc == 1 || yrc == 1 ||
4508     erc == 1)
4509        return 1;
4510    
4511   if (lrc == 2) printf("lilo\n");   if (lrc == 2) printf("lilo\n");
4512   if (gr2c == 2) printf("grub2\n");   if (gr2c == 2) printf("grub2\n");
4513   if (grc == 2) printf("grub\n");   if (grc == 2) printf("grub\n");
4514   if (erc == 2) printf("extlinux\n");   if (extrc == 2) printf("extlinux\n");
4515     if (yrc == 2) printf("yaboot\n");
4516     if (erc == 2) printf("elilo\n");
4517    
4518   return 0;   return 0;
4519      }      }
4520    
4521        if (grubConfig == NULL) {
4522     printf("Could not find bootloader configuration file.\n");
4523     exit(1);
4524        }
4525    
4526      config = readConfig(grubConfig, cfi);      config = readConfig(grubConfig, cfi);
4527      if (!config) return 1;      if (!config) return 1;
4528    
# Line 3456  int main(int argc, const char ** argv) { Line 4532  int main(int argc, const char ** argv) {
4532          char * rootspec;          char * rootspec;
4533    
4534   if (config->defaultImage == -1) return 0;   if (config->defaultImage == -1) return 0;
4535     if (config->defaultImage == DEFAULT_SAVED_GRUB2 &&
4536     cfi->defaultIsSaved)
4537        config->defaultImage = 0;
4538   entry = findEntryByIndex(config, config->defaultImage);   entry = findEntryByIndex(config, config->defaultImage);
4539   if (!entry) return 0;   if (!entry) return 0;
4540   if (!suitableImage(entry, bootPrefix, 0, flags)) return 0;   if (!suitableImage(entry, bootPrefix, 0, flags)) return 0;
4541    
4542   line = getLineByType(LT_KERNEL|LT_HYPER, entry->lines);   line = getLineByType(LT_KERNEL|LT_HYPER|LT_KERNEL_EFI|LT_KERNEL_16, entry->lines);
4543   if (!line) return 0;   if (!line) return 0;
4544    
4545          rootspec = getRootSpecifier(line->elements[1].item);          rootspec = getRootSpecifier(line->elements[1].item);
# Line 3468  int main(int argc, const char ** argv) { Line 4547  int main(int argc, const char ** argv) {
4547                 ((rootspec != NULL) ? strlen(rootspec) : 0));                 ((rootspec != NULL) ? strlen(rootspec) : 0));
4548    
4549   return 0;   return 0;
4550    
4551        } else if (displayDefaultTitle) {
4552     struct singleLine * line;
4553     struct singleEntry * entry;
4554    
4555     if (config->defaultImage == -1) return 0;
4556     if (config->defaultImage == DEFAULT_SAVED_GRUB2 &&
4557     cfi->defaultIsSaved)
4558        config->defaultImage = 0;
4559     entry = findEntryByIndex(config, config->defaultImage);
4560     if (!entry) return 0;
4561    
4562     if (!configureGrub2) {
4563      line = getLineByType(LT_TITLE, entry->lines);
4564      if (!line) return 0;
4565      printf("%s\n", line->elements[1].item);
4566    
4567     } else {
4568      char * title;
4569    
4570      dbgPrintf("This is GRUB2, default title is embeded in menuentry\n");
4571      line = getLineByType(LT_MENUENTRY, entry->lines);
4572      if (!line) return 0;
4573      title = grub2ExtractTitle(line);
4574      if (title)
4575        printf("%s\n", title);
4576     }
4577     return 0;
4578    
4579        } else if (displayDefaultIndex) {
4580            if (config->defaultImage == -1) return 0;
4581     if (config->defaultImage == DEFAULT_SAVED_GRUB2 &&
4582     cfi->defaultIsSaved)
4583        config->defaultImage = 0;
4584            printf("%i\n", config->defaultImage);
4585            return 0;
4586    
4587      } else if (kernelInfo)      } else if (kernelInfo)
4588   return displayInfo(config, kernelInfo, bootPrefix);   return displayInfo(config, kernelInfo, bootPrefix);
4589    
# Line 3479  int main(int argc, const char ** argv) { Line 4595  int main(int argc, const char ** argv) {
4595      markRemovedImage(config, removeKernelPath, bootPrefix);      markRemovedImage(config, removeKernelPath, bootPrefix);
4596      markRemovedImage(config, removeMBKernel, bootPrefix);      markRemovedImage(config, removeMBKernel, bootPrefix);
4597      setDefaultImage(config, newKernelPath != NULL, defaultKernel, makeDefault,      setDefaultImage(config, newKernelPath != NULL, defaultKernel, makeDefault,
4598      bootPrefix, flags);      bootPrefix, flags, defaultIndex);
4599      setFallbackImage(config, newKernelPath != NULL);      setFallbackImage(config, newKernelPath != NULL);
4600      if (updateImage(config, updateKernelPath, bootPrefix, newKernelArgs,      if (updateImage(config, updateKernelPath, bootPrefix, newKernelArgs,
4601                      removeArgs, newMBKernelArgs, removeMBKernelArgs)) return 1;                      removeArgs, newMBKernelArgs, removeMBKernelArgs)) return 1;
4602      if (updateKernelPath && newKernelInitrd) {      if (updateKernelPath && newKernelInitrd) {
4603              if (updateInitrd(config, updateKernelPath, bootPrefix,      if (newMBKernel) {
4604                               newKernelInitrd)) return 1;      if (addMBInitrd(config, newMBKernel, updateKernelPath,
4605     bootPrefix, newKernelInitrd))
4606        return 1;
4607        } else {
4608        if (updateInitrd(config, updateKernelPath, bootPrefix,
4609     newKernelInitrd))
4610     return 1;
4611        }
4612      }      }
4613      if (addNewKernel(config, template, bootPrefix, newKernelPath,      if (addNewKernel(config, template, bootPrefix, newKernelPath,
4614                       newKernelTitle, newKernelArgs, newKernelInitrd,                       newKernelTitle, newKernelArgs, newKernelInitrd,
4615                       extraInitrds, extraInitrdCount,                       (const char **)extraInitrds, extraInitrdCount,
4616                       newMBKernel, newMBKernelArgs)) return 1;                       newMBKernel, newMBKernelArgs, newDevTreePath)) return 1;
4617            
4618    
4619      if (numEntries(config) == 0) {      if (numEntries(config) == 0) {

Legend:
Removed from v.1717  
changed lines
  Added in v.2688