Magellan Linux

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

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

trunk/mkinitrd-magellan/grubby/grubby.c revision 926 by niro, Wed Oct 28 13:29:38 2009 UTC trunk/grubby/grubby.c revision 2056 by niro, Wed Feb 20 14:04:28 2013 UTC
# Line 36  Line 36 
36  #include <signal.h>  #include <signal.h>
37  #include <blkid/blkid.h>  #include <blkid/blkid.h>
38    
39    #ifndef DEBUG
40  #define DEBUG 0  #define DEBUG 0
41    #endif
42    
43  #if DEBUG  #if DEBUG
44  #define dbgPrintf(format, args...) fprintf(stderr, format , ## args)  #define dbgPrintf(format, args...) fprintf(stderr, format , ## args)
# Line 44  Line 46 
46  #define dbgPrintf(format, args...)  #define dbgPrintf(format, args...)
47  #endif  #endif
48    
49    int debug = 0; /* Currently just for template debugging */
50    
51  #define _(A) (A)  #define _(A) (A)
52    
53  #define MAX_EXTRA_INITRDS  16 /* code segment checked by --bootloader-probe */  #define MAX_EXTRA_INITRDS  16 /* code segment checked by --bootloader-probe */
54  #define CODE_SEG_SIZE  128 /* code segment checked by --bootloader-probe */  #define CODE_SEG_SIZE  128 /* code segment checked by --bootloader-probe */
55    
56    #define NOOP_OPCODE 0x90
57    #define JMP_SHORT_OPCODE 0xeb
58    
59    int isEfi = 0;
60    
61  /* comments get lumped in with indention */  /* comments get lumped in with indention */
62  struct lineElement {  struct lineElement {
63      char * item;      char * item;
# Line 56  struct lineElement { Line 65  struct lineElement {
65  };  };
66    
67  enum lineType_e {  enum lineType_e {
68      LT_WHITESPACE = 1 << 0,      LT_WHITESPACE   = 1 << 0,
69      LT_TITLE      = 1 << 1,      LT_TITLE        = 1 << 1,
70      LT_KERNEL     = 1 << 2,      LT_KERNEL       = 1 << 2,
71      LT_INITRD     = 1 << 3,      LT_INITRD       = 1 << 3,
72      LT_HYPER      = 1 << 4,      LT_HYPER        = 1 << 4,
73      LT_DEFAULT    = 1 << 5,      LT_DEFAULT      = 1 << 5,
74      LT_MBMODULE   = 1 << 6,      LT_MBMODULE     = 1 << 6,
75      LT_ROOT       = 1 << 7,      LT_ROOT         = 1 << 7,
76      LT_FALLBACK   = 1 << 8,      LT_FALLBACK     = 1 << 8,
77      LT_KERNELARGS = 1 << 9,      LT_KERNELARGS   = 1 << 9,
78      LT_BOOT       = 1 << 10,      LT_BOOT         = 1 << 10,
79      LT_BOOTROOT   = 1 << 11,      LT_BOOTROOT     = 1 << 11,
80      LT_LBA        = 1 << 12,      LT_LBA          = 1 << 12,
81      LT_OTHER      = 1 << 13,      LT_OTHER        = 1 << 13,
82      LT_GENERIC    = 1 << 14,      LT_GENERIC      = 1 << 14,
83      LT_UNKNOWN    = 1 << 15,      LT_ECHO    = 1 << 16,
84        LT_MENUENTRY    = 1 << 17,
85        LT_ENTRY_END    = 1 << 18,
86        LT_SET_VARIABLE = 1 << 19,
87        LT_KERNEL_EFI   = 1 << 20,
88        LT_INITRD_EFI   = 1 << 21,
89        LT_UNKNOWN      = 1 << 22,
90  };  };
91    
92  struct singleLine {  struct singleLine {
# Line 99  struct singleEntry { Line 114  struct singleEntry {
114  #define NEED_TITLE   (1 << 2)  #define NEED_TITLE   (1 << 2)
115  #define NEED_ARGS    (1 << 3)  #define NEED_ARGS    (1 << 3)
116  #define NEED_MB      (1 << 4)  #define NEED_MB      (1 << 4)
117    #define NEED_END     (1 << 5)
118    
119  #define MAIN_DEFAULT    (1 << 0)  #define MAIN_DEFAULT    (1 << 0)
120  #define DEFAULT_SAVED       -2  #define DEFAULT_SAVED       -2
121    #define DEFAULT_SAVED_GRUB2 -3
122    
123  struct keywordTypes {  struct keywordTypes {
124      char * key;      char * key;
# Line 110  struct keywordTypes { Line 127  struct keywordTypes {
127      char separatorChar;      char separatorChar;
128  };  };
129    
130    struct configFileInfo;
131    
132    typedef const char *(*findConfigFunc)(struct configFileInfo *);
133    typedef const int (*writeLineFunc)(struct configFileInfo *,
134     struct singleLine *line);
135    
136  struct configFileInfo {  struct configFileInfo {
137      char * defaultConfig;      char * defaultConfig;
138        findConfigFunc findConfig;
139        writeLineFunc writeLine;
140      struct keywordTypes * keywords;      struct keywordTypes * keywords;
141        int caseInsensitive;
142      int defaultIsIndex;      int defaultIsIndex;
143        int defaultIsVariable;
144      int defaultSupportSaved;      int defaultSupportSaved;
145      enum lineType_e entrySeparator;      enum lineType_e entryStart;
146        enum lineType_e entryEnd;
147      int needsBootPrefix;      int needsBootPrefix;
148      int argsInQuotes;      int argsInQuotes;
149      int maxTitleLength;      int maxTitleLength;
150      int titleBracketed;      int titleBracketed;
151        int titlePosition;
152      int mbHyperFirst;      int mbHyperFirst;
153      int mbInitRdIsModule;      int mbInitRdIsModule;
154      int mbConcatArgs;      int mbConcatArgs;
# Line 138  struct keywordTypes grubKeywords[] = { Line 167  struct keywordTypes grubKeywords[] = {
167      { NULL,    0, 0 },      { NULL,    0, 0 },
168  };  };
169    
170    const char *grubFindConfig(struct configFileInfo *cfi) {
171        static const char *configFiles[] = {
172     "/boot/grub/grub.conf",
173     "/boot/grub/menu.lst",
174     "/etc/grub.conf",
175     NULL
176        };
177        static int i = -1;
178    
179        if (i == -1) {
180     for (i = 0; configFiles[i] != NULL; i++) {
181        dbgPrintf("Checking \"%s\": ", configFiles[i]);
182        if (!access(configFiles[i], R_OK)) {
183     dbgPrintf("found\n");
184     return configFiles[i];
185        }
186        dbgPrintf("not found\n");
187     }
188        }
189        return configFiles[i];
190    }
191    
192  struct configFileInfo grubConfigType = {  struct configFileInfo grubConfigType = {
193      "/boot/grub/grub.conf",    /* defaultConfig */      .findConfig = grubFindConfig,
194      grubKeywords,    /* keywords */      .keywords = grubKeywords,
195      1,    /* defaultIsIndex */      .defaultIsIndex = 1,
196      1,    /* defaultSupportSaved */      .defaultSupportSaved = 1,
197      LT_TITLE,    /* entrySeparator */      .entryStart = LT_TITLE,
198      1,    /* needsBootPrefix */      .needsBootPrefix = 1,
199      0,    /* argsInQuotes */      .mbHyperFirst = 1,
200      0,    /* maxTitleLength */      .mbInitRdIsModule = 1,
201      0,                                      /* titleBracketed */      .mbAllowExtraInitRds = 1,
202      1,                                      /* mbHyperFirst */  };
203      1,                                      /* mbInitRdIsModule */  
204      0,                                      /* mbConcatArgs */  struct keywordTypes grub2Keywords[] = {
205      1,                                      /* mbAllowExtraInitRds */      { "menuentry",  LT_MENUENTRY,   ' ' },
206        { "}",          LT_ENTRY_END,   ' ' },
207        { "echo",       LT_ECHO,        ' ' },
208        { "set",        LT_SET_VARIABLE,' ', '=' },
209        { "root",       LT_BOOTROOT,    ' ' },
210        { "default",    LT_DEFAULT,     ' ' },
211        { "fallback",   LT_FALLBACK,    ' ' },
212        { "linux",      LT_KERNEL,      ' ' },
213        { "linuxefi",   LT_KERNEL_EFI,  ' ' },
214        { "initrd",     LT_INITRD,      ' ', ' ' },
215        { "initrdefi",  LT_INITRD_EFI,  ' ', ' ' },
216        { "module",     LT_MBMODULE,    ' ' },
217        { "kernel",     LT_HYPER,       ' ' },
218        { NULL, 0, 0 },
219    };
220    
221    const char *grub2FindConfig(struct configFileInfo *cfi) {
222        static const char *configFiles[] = {
223     "/boot/grub/grub-efi.cfg",
224     "/boot/grub/grub.cfg",
225     NULL
226        };
227        static int i = -1;
228        static const char *grub_cfg = "/boot/grub/grub.cfg";
229    
230        if (i == -1) {
231     for (i = 0; configFiles[i] != NULL; i++) {
232        dbgPrintf("Checking \"%s\": ", configFiles[i]);
233        if (!access(configFiles[i], R_OK)) {
234     dbgPrintf("found\n");
235     return configFiles[i];
236        }
237     }
238        }
239    
240        /* Ubuntu renames grub2 to grub, so check for the grub.d directory
241         * that isn't in grub1, and if it exists, return the config file path
242         * that they use. */
243        if (configFiles[i] == NULL && !access("/etc/grub.d/", R_OK)) {
244     dbgPrintf("found\n");
245     return grub_cfg;
246        }
247    
248        dbgPrintf("not found\n");
249        return configFiles[i];
250    }
251    
252    int sizeOfSingleLine(struct singleLine * line) {
253      int count = 0;
254    
255      for (int i = 0; i < line->numElements; i++) {
256        int indentSize = 0;
257    
258        count = count + strlen(line->elements[i].item);
259    
260        indentSize = strlen(line->elements[i].indent);
261        if (indentSize > 0)
262          count = count + indentSize;
263        else
264          /* be extra safe and add room for whitespaces */
265          count = count + 1;
266      }
267    
268      /* room for trailing terminator */
269      count = count + 1;
270    
271      return count;
272    }
273    
274    static int isquote(char q)
275    {
276        if (q == '\'' || q == '\"')
277     return 1;
278        return 0;
279    }
280    
281    static int iskernel(enum lineType_e type) {
282        return (type == LT_KERNEL || type == LT_KERNEL_EFI);
283    }
284    
285    static int isinitrd(enum lineType_e type) {
286        return (type == LT_INITRD || type == LT_INITRD_EFI);
287    }
288    
289    char *grub2ExtractTitle(struct singleLine * line) {
290        char * current;
291        char * current_indent;
292        int current_len;
293        int current_indent_len;
294        int i;
295    
296        /* bail out if line does not start with menuentry */
297        if (strcmp(line->elements[0].item, "menuentry"))
298          return NULL;
299    
300        i = 1;
301        current = line->elements[i].item;
302        current_len = strlen(current);
303    
304        /* if second word is quoted, strip the quotes and return single word */
305        if (isquote(*current) && isquote(current[current_len - 1])) {
306     char *tmp;
307    
308     tmp = strdup(current);
309     *(tmp + current_len - 1) = '\0';
310     return ++tmp;
311        }
312    
313        /* if no quotes, return second word verbatim */
314        if (!isquote(*current))
315     return current;
316    
317        /* second element start with a quote, so we have to find the element
318         * whose last character is also quote (assuming it's the closing one) */
319        int resultMaxSize;
320        char * result;
321        
322        resultMaxSize = sizeOfSingleLine(line);
323        result = malloc(resultMaxSize);
324        snprintf(result, resultMaxSize, "%s", ++current);
325        
326        i++;
327        for (; i < line->numElements; ++i) {
328     current = line->elements[i].item;
329     current_len = strlen(current);
330     current_indent = line->elements[i].indent;
331     current_indent_len = strlen(current_indent);
332    
333     strncat(result, current_indent, current_indent_len);
334     if (!isquote(current[current_len-1])) {
335        strncat(result, current, current_len);
336     } else {
337        strncat(result, current, current_len - 1);
338        break;
339     }
340        }
341        return result;
342    }
343    
344    struct configFileInfo grub2ConfigType = {
345        .findConfig = grub2FindConfig,
346        .keywords = grub2Keywords,
347        .defaultIsIndex = 1,
348        .defaultSupportSaved = 1,
349        .defaultIsVariable = 1,
350        .entryStart = LT_MENUENTRY,
351        .entryEnd = LT_ENTRY_END,
352        .titlePosition = 1,
353        .needsBootPrefix = 1,
354        .mbHyperFirst = 1,
355        .mbInitRdIsModule = 1,
356        .mbAllowExtraInitRds = 1,
357  };  };
358    
359  struct keywordTypes yabootKeywords[] = {  struct keywordTypes yabootKeywords[] = {
# Line 249  struct keywordTypes extlinuxKeywords[] = Line 451  struct keywordTypes extlinuxKeywords[] =
451  };  };
452  int useextlinuxmenu;  int useextlinuxmenu;
453  struct configFileInfo eliloConfigType = {  struct configFileInfo eliloConfigType = {
454      "/boot/efi/EFI/redhat/elilo.conf",    /* defaultConfig */      .defaultConfig = "/boot/efi/EFI/redhat/elilo.conf",
455      eliloKeywords,    /* keywords */      .keywords = eliloKeywords,
456      0,    /* defaultIsIndex */      .entryStart = LT_KERNEL,
457      0,    /* defaultSupportSaved */      .needsBootPrefix = 1,
458      LT_KERNEL,    /* entrySeparator */      .argsInQuotes = 1,
459      1,                    /* needsBootPrefix */      .mbConcatArgs = 1,
     1,    /* argsInQuotes */  
     0,    /* maxTitleLength */  
     0,                                      /* titleBracketed */  
     0,                                      /* mbHyperFirst */  
     0,                                      /* mbInitRdIsModule */  
     1,                                      /* mbConcatArgs */  
     0,                                      /* mbAllowExtraInitRds */  
460  };  };
461    
462  struct configFileInfo liloConfigType = {  struct configFileInfo liloConfigType = {
463      "/etc/lilo.conf",    /* defaultConfig */      .defaultConfig = "/etc/lilo.conf",
464      liloKeywords,    /* keywords */      .keywords = liloKeywords,
465      0,    /* defaultIsIndex */      .entryStart = LT_KERNEL,
466      0,    /* defaultSupportSaved */      .argsInQuotes = 1,
467      LT_KERNEL,    /* entrySeparator */      .maxTitleLength = 15,
     0,    /* needsBootPrefix */  
     1,    /* argsInQuotes */  
     15,    /* maxTitleLength */  
     0,                                      /* titleBracketed */  
     0,                                      /* mbHyperFirst */  
     0,                                      /* mbInitRdIsModule */  
     0,                                      /* mbConcatArgs */  
     0,                                      /* mbAllowExtraInitRds */  
468  };  };
469    
470  struct configFileInfo yabootConfigType = {  struct configFileInfo yabootConfigType = {
471      "/etc/yaboot.conf",    /* defaultConfig */      .defaultConfig = "/etc/yaboot.conf",
472      yabootKeywords,    /* keywords */      .keywords = yabootKeywords,
473      0,    /* defaultIsIndex */      .entryStart = LT_KERNEL,
474      0,    /* defaultSupportSaved */      .needsBootPrefix = 1,
475      LT_KERNEL,    /* entrySeparator */      .argsInQuotes = 1,
476      1,    /* needsBootPrefix */      .maxTitleLength = 15,
477      1,    /* argsInQuotes */      .mbAllowExtraInitRds = 1,
     15,    /* maxTitleLength */  
     0,                                      /* titleBracketed */  
     0,                                      /* mbHyperFirst */  
     0,                                      /* mbInitRdIsModule */  
     0,                                      /* mbConcatArgs */  
     1,                                      /* mbAllowExtraInitRds */  
478  };  };
479    
480  struct configFileInfo siloConfigType = {  struct configFileInfo siloConfigType = {
481      "/etc/silo.conf",    /* defaultConfig */      .defaultConfig = "/etc/silo.conf",
482      siloKeywords,    /* keywords */      .keywords = siloKeywords,
483      0,    /* defaultIsIndex */      .entryStart = LT_KERNEL,
484      0,    /* defaultSupportSaved */      .needsBootPrefix = 1,
485      LT_KERNEL,    /* entrySeparator */      .argsInQuotes = 1,
486      1,    /* needsBootPrefix */      .maxTitleLength = 15,
     1,    /* argsInQuotes */  
     15,    /* maxTitleLength */  
     0,                                      /* titleBracketed */  
     0,                                      /* mbHyperFirst */  
     0,                                      /* mbInitRdIsModule */  
     0,                                      /* mbConcatArgs */  
     0,                                      /* mbAllowExtraInitRds */  
487  };  };
488    
489  struct configFileInfo ziplConfigType = {  struct configFileInfo ziplConfigType = {
490      "/etc/zipl.conf",    /* defaultConfig */      .defaultConfig = "/etc/zipl.conf",
491      ziplKeywords,    /* keywords */      .keywords = ziplKeywords,
492      0,    /* defaultIsIndex */      .entryStart = LT_TITLE,
493      0,    /* defaultSupportSaved */      .argsInQuotes = 1,
494      LT_TITLE,    /* entrySeparator */      .titleBracketed = 1,
     0,    /* needsBootPrefix */  
     1,    /* argsInQuotes */  
     0,    /* maxTitleLength */  
     1,                                      /* titleBracketed */  
     0,                                      /* mbHyperFirst */  
     0,                                      /* mbInitRdIsModule */  
     0,                                      /* mbConcatArgs */  
     0,                                      /* mbAllowExtraInitRds */  
495  };  };
496    
497  struct configFileInfo extlinuxConfigType = {  struct configFileInfo extlinuxConfigType = {
498      "/boot/extlinux/extlinux.conf",         /* defaultConfig */      .defaultConfig = "/boot/extlinux/extlinux.conf",
499      extlinuxKeywords,                       /* keywords */      .keywords = extlinuxKeywords,
500      0,                                      /* defaultIsIndex */      .caseInsensitive = 1,
501      0,                                      /* defaultSupportSaved */      .entryStart = LT_TITLE,
502      LT_TITLE,                               /* entrySeparator */      .needsBootPrefix = 1,
503      1,                                      /* needsBootPrefix */      .maxTitleLength = 255,
504      0,                                      /* argsInQuotes */      .mbAllowExtraInitRds = 1,
     255,                                    /* maxTitleLength */  
     0,                                      /* titleBracketed */  
     0,                                      /* mbHyperFirst */  
     0,                                      /* mbInitRdIsModule */  
     0,                                      /* mbConcatArgs */  
     1,                                      /* mbAllowExtraInitRds */  
505  };  };
506    
507  struct grubConfig {  struct grubConfig {
# Line 356  struct grubConfig { Line 516  struct grubConfig {
516      struct configFileInfo * cfi;      struct configFileInfo * cfi;
517  };  };
518    
519    blkid_cache blkid;
520    
521  struct singleEntry * findEntryByIndex(struct grubConfig * cfg, int index);  struct singleEntry * findEntryByIndex(struct grubConfig * cfg, int index);
522  struct singleEntry * findEntryByPath(struct grubConfig * cfg,  struct singleEntry * findEntryByPath(struct grubConfig * cfg,
523       const char * path, const char * prefix,       const char * path, const char * prefix,
# Line 369  static int lineWrite(FILE * out, struct Line 531  static int lineWrite(FILE * out, struct
531  static int getNextLine(char ** bufPtr, struct singleLine * line,  static int getNextLine(char ** bufPtr, struct singleLine * line,
532         struct configFileInfo * cfi);         struct configFileInfo * cfi);
533  static char * getRootSpecifier(char * str);  static char * getRootSpecifier(char * str);
534    static void requote(struct singleLine *line, struct configFileInfo * cfi);
535  static void insertElement(struct singleLine * line,  static void insertElement(struct singleLine * line,
536    const char * item, int insertHere,    const char * item, int insertHere,
537    struct configFileInfo * cfi);    struct configFileInfo * cfi);
# Line 423  static char * sdupprintf(const char *for Line 586  static char * sdupprintf(const char *for
586      return buf;      return buf;
587  }  }
588    
589    static enum lineType_e preferredLineType(enum lineType_e type,
590     struct configFileInfo *cfi) {
591        if (isEfi && cfi == &grub2ConfigType) {
592     switch (type) {
593     case LT_KERNEL:
594        return LT_KERNEL_EFI;
595     case LT_INITRD:
596        return LT_INITRD_EFI;
597     default:
598        return type;
599     }
600        }
601        return type;
602    }
603    
604  static struct keywordTypes * getKeywordByType(enum lineType_e type,  static struct keywordTypes * getKeywordByType(enum lineType_e type,
605        struct configFileInfo * cfi) {        struct configFileInfo * cfi) {
606      struct keywordTypes * kw;      for (struct keywordTypes *kw = cfi->keywords; kw->key; kw++) {
     for (kw = cfi->keywords; kw->key; kw++) {  
607   if (kw->type == type)   if (kw->type == type)
608      return kw;      return kw;
609      }      }
610      return NULL;      return NULL;
611  }  }
612    
613  static char * getpathbyspec(char *device) {  static char *getKeyByType(enum lineType_e type, struct configFileInfo * cfi) {
614      static blkid_cache blkid;      struct keywordTypes *kt = getKeywordByType(type, cfi);
615        if (kt)
616     return kt->key;
617        return "unknown";
618    }
619    
620    static char * getpathbyspec(char *device) {
621      if (!blkid)      if (!blkid)
622          blkid_get_cache(&blkid, NULL);          blkid_get_cache(&blkid, NULL);
623    
624      return blkid_get_devname(blkid, device, NULL);      return blkid_get_devname(blkid, device, NULL);
625  }  }
626    
627    static char * getuuidbydev(char *device) {
628        if (!blkid)
629     blkid_get_cache(&blkid, NULL);
630    
631        return blkid_get_tag_value(blkid, "UUID", device);
632    }
633    
634  static enum lineType_e getTypeByKeyword(char * keyword,  static enum lineType_e getTypeByKeyword(char * keyword,
635   struct configFileInfo * cfi) {   struct configFileInfo * cfi) {
636      struct keywordTypes * kw;      for (struct keywordTypes *kw = cfi->keywords; kw->key; kw++) {
637      for (kw = cfi->keywords; kw->key; kw++) {   if (cfi->caseInsensitive) {
638   if (!strcmp(keyword, kw->key))      if (!strcasecmp(keyword, kw->key))
639      return kw->type;                  return kw->type;
640     } else {
641        if (!strcmp(keyword, kw->key))
642            return kw->type;
643     }
644      }      }
645      return LT_UNKNOWN;      return LT_UNKNOWN;
646  }  }
# Line 477  static int isBracketedTitle(struct singl Line 670  static int isBracketedTitle(struct singl
670      return 0;      return 0;
671  }  }
672    
673  static int isEntrySeparator(struct singleLine * line,  static int isEntryStart(struct singleLine * line,
674                              struct configFileInfo * cfi) {                              struct configFileInfo * cfi) {
675      return line->type == cfi->entrySeparator || line->type == LT_OTHER ||      return line->type == cfi->entryStart || line->type == LT_OTHER ||
676   (cfi->titleBracketed && isBracketedTitle(line));   (cfi->titleBracketed && isBracketedTitle(line));
677  }  }
678    
# Line 532  static void lineInit(struct singleLine * Line 725  static void lineInit(struct singleLine *
725  }  }
726    
727  struct singleLine * lineDup(struct singleLine * line) {  struct singleLine * lineDup(struct singleLine * line) {
     int i;  
728      struct singleLine * newLine = malloc(sizeof(*newLine));      struct singleLine * newLine = malloc(sizeof(*newLine));
729    
730      newLine->indent = strdup(line->indent);      newLine->indent = strdup(line->indent);
# Line 542  struct singleLine * lineDup(struct singl Line 734  struct singleLine * lineDup(struct singl
734      newLine->elements = malloc(sizeof(*newLine->elements) *      newLine->elements = malloc(sizeof(*newLine->elements) *
735         newLine->numElements);         newLine->numElements);
736    
737      for (i = 0; i < newLine->numElements; i++) {      for (int i = 0; i < newLine->numElements; i++) {
738   newLine->elements[i].indent = strdup(line->elements[i].indent);   newLine->elements[i].indent = strdup(line->elements[i].indent);
739   newLine->elements[i].item = strdup(line->elements[i].item);   newLine->elements[i].item = strdup(line->elements[i].item);
740      }      }
# Line 551  struct singleLine * lineDup(struct singl Line 743  struct singleLine * lineDup(struct singl
743  }  }
744    
745  static void lineFree(struct singleLine * line) {  static void lineFree(struct singleLine * line) {
     int i;  
   
746      if (line->indent) free(line->indent);      if (line->indent) free(line->indent);
747    
748      for (i = 0; i < line->numElements; i++) {      for (int i = 0; i < line->numElements; i++) {
749   free(line->elements[i].item);   free(line->elements[i].item);
750   free(line->elements[i].indent);   free(line->elements[i].indent);
751      }      }
# Line 566  static void lineFree(struct singleLine * Line 756  static void lineFree(struct singleLine *
756    
757  static int lineWrite(FILE * out, struct singleLine * line,  static int lineWrite(FILE * out, struct singleLine * line,
758       struct configFileInfo * cfi) {       struct configFileInfo * cfi) {
     int i;  
   
759      if (fprintf(out, "%s", line->indent) == -1) return -1;      if (fprintf(out, "%s", line->indent) == -1) return -1;
760    
761      for (i = 0; i < line->numElements; i++) {      for (int i = 0; i < line->numElements; i++) {
762     /* Need to handle this, because we strip the quotes from
763     * menuentry when read it. */
764     if (line->type == LT_MENUENTRY && i == 1) {
765        if(!isquote(*line->elements[i].item))
766     fprintf(out, "\'%s\'", line->elements[i].item);
767        else
768     fprintf(out, "%s", line->elements[i].item);
769        fprintf(out, "%s", line->elements[i].indent);
770    
771        continue;
772     }
773    
774   if (i == 1 && line->type == LT_KERNELARGS && cfi->argsInQuotes)   if (i == 1 && line->type == LT_KERNELARGS && cfi->argsInQuotes)
775      if (fputc('"', out) == EOF) return -1;      if (fputc('"', out) == EOF) return -1;
776    
# Line 664  static int getNextLine(char ** bufPtr, s Line 864  static int getNextLine(char ** bufPtr, s
864      if (*line->elements[0].item == '#') {      if (*line->elements[0].item == '#') {
865   char * fullLine;   char * fullLine;
866   int len;   int len;
  int i;  
867    
868   len = strlen(line->indent);   len = strlen(line->indent);
869   for (i = 0; i < line->numElements; i++)   for (int i = 0; i < line->numElements; i++)
870      len += strlen(line->elements[i].item) +      len += strlen(line->elements[i].item) +
871     strlen(line->elements[i].indent);     strlen(line->elements[i].indent);
872    
# Line 676  static int getNextLine(char ** bufPtr, s Line 875  static int getNextLine(char ** bufPtr, s
875   free(line->indent);   free(line->indent);
876   line->indent = fullLine;   line->indent = fullLine;
877    
878   for (i = 0; i < line->numElements; i++) {   for (int i = 0; i < line->numElements; i++) {
879      strcat(fullLine, line->elements[i].item);      strcat(fullLine, line->elements[i].item);
880      strcat(fullLine, line->elements[i].indent);      strcat(fullLine, line->elements[i].indent);
881      free(line->elements[i].item);      free(line->elements[i].item);
# Line 695  static int getNextLine(char ** bufPtr, s Line 894  static int getNextLine(char ** bufPtr, s
894   * elements up more   * elements up more
895   */   */
896   if (!isspace(kw->separatorChar)) {   if (!isspace(kw->separatorChar)) {
     int i;  
897      char indent[2] = "";      char indent[2] = "";
898      indent[0] = kw->separatorChar;      indent[0] = kw->separatorChar;
899      for (i = 1; i < line->numElements; i++) {      for (int i = 1; i < line->numElements; i++) {
900   char *p;   char *p;
  int j;  
901   int numNewElements;   int numNewElements;
902    
903   numNewElements = 0;   numNewElements = 0;
# Line 716  static int getNextLine(char ** bufPtr, s Line 913  static int getNextLine(char ** bufPtr, s
913      sizeof(*line->elements) * elementsAlloced);      sizeof(*line->elements) * elementsAlloced);
914   }   }
915    
916   for (j = line->numElements; j > i; j--) {   for (int j = line->numElements; j > i; j--) {
917   line->elements[j + numNewElements] = line->elements[j];   line->elements[j + numNewElements] = line->elements[j];
918   }   }
919   line->numElements += numNewElements;   line->numElements += numNewElements;
# Line 729  static int getNextLine(char ** bufPtr, s Line 926  static int getNextLine(char ** bufPtr, s
926   break;   break;
927   }   }
928    
929   free(line->elements[i].indent);   line->elements[i + 1].indent = line->elements[i].indent;
930   line->elements[i].indent = strdup(indent);   line->elements[i].indent = strdup(indent);
931   *p++ = '\0';   *p++ = '\0';
932   i++;   i++;
933   line->elements[i].item = strdup(p);   line->elements[i].item = strdup(p);
  line->elements[i].indent = strdup("");  
  p = line->elements[i].item;  
934   }   }
935      }      }
936   }   }
# Line 756  static struct grubConfig * readConfig(co Line 951  static struct grubConfig * readConfig(co
951      struct singleLine * last = NULL, * line, * defaultLine = NULL;      struct singleLine * last = NULL, * line, * defaultLine = NULL;
952      char * end;      char * end;
953      struct singleEntry * entry = NULL;      struct singleEntry * entry = NULL;
954      int i, len;      int len;
955      char * buf;      char * buf;
956    
957      if (!strcmp(inName, "-")) {      if (!strcmp(inName, "-")) {
# Line 802  static struct grubConfig * readConfig(co Line 997  static struct grubConfig * readConfig(co
997      cfg->secondaryIndent = strdup(line->indent);      cfg->secondaryIndent = strdup(line->indent);
998   }   }
999    
1000   if (isEntrySeparator(line, cfi)) {   if (isEntryStart(line, cfi) || (cfg->entries && !sawEntry)) {
1001      sawEntry = 1;      sawEntry = 1;
1002      if (!entry) {      if (!entry) {
1003   cfg->entries = malloc(sizeof(*entry));   cfg->entries = malloc(sizeof(*entry));
# Line 818  static struct grubConfig * readConfig(co Line 1013  static struct grubConfig * readConfig(co
1013      entry->next = NULL;      entry->next = NULL;
1014   }   }
1015    
1016   if (line->type == LT_DEFAULT && line->numElements == 2) {   if (line->type == LT_SET_VARIABLE) {
1017        dbgPrintf("found 'set' command (%d elements): ", line->numElements);
1018        dbgPrintf("%s", line->indent);
1019        for (int i = 0; i < line->numElements; i++)
1020     dbgPrintf("\"%s\"%s", line->elements[i].item, line->elements[i].indent);
1021        dbgPrintf("\n");
1022        struct keywordTypes *kwType = getKeywordByType(LT_DEFAULT, cfi);
1023        if (kwType && line->numElements == 3 &&
1024        !strcmp(line->elements[1].item, kwType->key)) {
1025     dbgPrintf("Line sets default config\n");
1026     cfg->flags &= ~GRUB_CONFIG_NO_DEFAULT;
1027     defaultLine = line;
1028        }
1029     } else if (line->type == LT_DEFAULT && line->numElements == 2) {
1030      cfg->flags &= ~GRUB_CONFIG_NO_DEFAULT;      cfg->flags &= ~GRUB_CONFIG_NO_DEFAULT;
1031      defaultLine = line;      defaultLine = line;
1032    
1033          } else if (line->type == LT_KERNEL) {          } else if (iskernel(line->type)) {
1034      /* if by some freak chance this is multiboot and the "module"      /* if by some freak chance this is multiboot and the "module"
1035       * lines came earlier in the template, make sure to use LT_HYPER       * lines came earlier in the template, make sure to use LT_HYPER
1036       * instead of LT_KERNEL now       * instead of LT_KERNEL now
# Line 836  static struct grubConfig * readConfig(co Line 1044  static struct grubConfig * readConfig(co
1044       * This only applies to grub, but that's the only place we       * This only applies to grub, but that's the only place we
1045       * should find LT_MBMODULE lines anyway.       * should find LT_MBMODULE lines anyway.
1046       */       */
1047      struct singleLine * l;      for (struct singleLine *l = entry->lines; l; l = l->next) {
     for (l = entry->lines; l; l = l->next) {  
1048   if (l->type == LT_HYPER)   if (l->type == LT_HYPER)
1049      break;      break;
1050   else if (l->type == LT_KERNEL) {   else if (iskernel(l->type)) {
1051      l->type = LT_HYPER;      l->type = LT_HYPER;
1052      break;      break;
1053   }   }
# Line 857  static struct grubConfig * readConfig(co Line 1064  static struct grubConfig * readConfig(co
1064   } else if (line->type == LT_TITLE && line->numElements > 1) {   } else if (line->type == LT_TITLE && line->numElements > 1) {
1065      /* make the title a single argument (undoing our parsing) */      /* make the title a single argument (undoing our parsing) */
1066      len = 0;      len = 0;
1067      for (i = 1; i < line->numElements; i++) {      for (int i = 1; i < line->numElements; i++) {
1068   len += strlen(line->elements[i].item);   len += strlen(line->elements[i].item);
1069   len += strlen(line->elements[i].indent);   len += strlen(line->elements[i].indent);
1070      }      }
1071      buf = malloc(len + 1);      buf = malloc(len + 1);
1072      *buf = '\0';      *buf = '\0';
1073    
1074      for (i = 1; i < line->numElements; i++) {      for (int i = 1; i < line->numElements; i++) {
1075   strcat(buf, line->elements[i].item);   strcat(buf, line->elements[i].item);
1076   free(line->elements[i].item);   free(line->elements[i].item);
1077    
# Line 878  static struct grubConfig * readConfig(co Line 1085  static struct grubConfig * readConfig(co
1085      line->elements[line->numElements - 1].indent;      line->elements[line->numElements - 1].indent;
1086      line->elements[1].item = buf;      line->elements[1].item = buf;
1087      line->numElements = 2;      line->numElements = 2;
1088     } else if (line->type == LT_MENUENTRY && line->numElements > 3) {
1089        /* let --remove-kernel="TITLE=what" work */
1090        len = 0;
1091        char *extras;
1092        char *title;
1093    
1094        for (int i = 1; i < line->numElements; i++) {
1095     len += strlen(line->elements[i].item);
1096     len += strlen(line->elements[i].indent);
1097        }
1098        buf = malloc(len + 1);
1099        *buf = '\0';
1100    
1101        /* allocate mem for extra flags. */
1102        extras = malloc(len + 1);
1103        *extras = '\0';
1104    
1105        /* get title. */
1106        for (int i = 0; i < line->numElements; i++) {
1107     if (!strcmp(line->elements[i].item, "menuentry"))
1108        continue;
1109     if (isquote(*line->elements[i].item))
1110        title = line->elements[i].item + 1;
1111     else
1112        title = line->elements[i].item;
1113    
1114     len = strlen(title);
1115            if (isquote(title[len-1])) {
1116        strncat(buf, title,len-1);
1117        break;
1118     } else {
1119        strcat(buf, title);
1120        strcat(buf, line->elements[i].indent);
1121     }
1122        }
1123    
1124        /* get extras */
1125        int count = 0;
1126        for (int i = 0; i < line->numElements; i++) {
1127     if (count >= 2) {
1128        strcat(extras, line->elements[i].item);
1129        strcat(extras, line->elements[i].indent);
1130     }
1131    
1132     if (!strcmp(line->elements[i].item, "menuentry"))
1133        continue;
1134    
1135     /* count ' or ", there should be two in menuentry line. */
1136     if (isquote(*line->elements[i].item))
1137        count++;
1138    
1139     len = strlen(line->elements[i].item);
1140    
1141     if (isquote(line->elements[i].item[len -1]))
1142        count++;
1143    
1144     /* ok, we get the final ' or ", others are extras. */
1145                }
1146        line->elements[1].indent =
1147     line->elements[line->numElements - 2].indent;
1148        line->elements[1].item = buf;
1149        line->elements[2].indent =
1150     line->elements[line->numElements - 2].indent;
1151        line->elements[2].item = extras;
1152        line->numElements = 3;
1153   } else if (line->type == LT_KERNELARGS && cfi->argsInQuotes) {   } else if (line->type == LT_KERNELARGS && cfi->argsInQuotes) {
1154      /* Strip off any " which may be present; they'll be put back      /* Strip off any " which may be present; they'll be put back
1155         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 887  static struct grubConfig * readConfig(co Line 1158  static struct grubConfig * readConfig(co
1158      if (line->numElements >= 2) {      if (line->numElements >= 2) {
1159   int last, len;   int last, len;
1160    
1161   if (*line->elements[1].item == '"')   if (isquote(*line->elements[1].item))
1162      memmove(line->elements[1].item, line->elements[1].item + 1,      memmove(line->elements[1].item, line->elements[1].item + 1,
1163      strlen(line->elements[1].item + 1) + 1);      strlen(line->elements[1].item + 1) + 1);
1164    
1165   last = line->numElements - 1;   last = line->numElements - 1;
1166   len = strlen(line->elements[last].item) - 1;   len = strlen(line->elements[last].item) - 1;
1167   if (line->elements[last].item[len] == '"')   if (isquote(line->elements[last].item[len]))
1168      line->elements[last].item[len] = '\0';      line->elements[last].item[len] = '\0';
1169      }      }
1170   }   }
# Line 931  static struct grubConfig * readConfig(co Line 1202  static struct grubConfig * readConfig(co
1202   entry->lines = line;   entry->lines = line;
1203      else      else
1204   last->next = line;   last->next = line;
1205      dbgPrintf("readConfig added %d to %p\n", line->type, entry);      dbgPrintf("readConfig added %s to %p\n", getKeyByType(line->type, cfi), entry);
1206    
1207        /* we could have seen this outside of an entry... if so, we
1208         * ignore it like any other line we don't grok */
1209        if (line->type == LT_ENTRY_END && sawEntry)
1210     sawEntry = 0;
1211   } else {   } else {
1212      if (!cfg->theLines)      if (!cfg->theLines)
1213   cfg->theLines = line;   cfg->theLines = line;
1214      else      else
1215   last->next = line;   last->next = line;
1216      dbgPrintf("readConfig added %d to cfg\n", line->type);      dbgPrintf("readConfig added %s to cfg\n", getKeyByType(line->type, cfi));
1217   }   }
1218    
1219   last = line;   last = line;
# Line 945  static struct grubConfig * readConfig(co Line 1221  static struct grubConfig * readConfig(co
1221    
1222      free(incoming);      free(incoming);
1223    
1224        dbgPrintf("defaultLine is %s\n", defaultLine ? "set" : "unset");
1225      if (defaultLine) {      if (defaultLine) {
1226   if (cfi->defaultSupportSaved &&          if (defaultLine->numElements > 2 &&
1227        cfi->defaultSupportSaved &&
1228        !strncmp(defaultLine->elements[2].item,"\"${saved_entry}\"", 16)) {
1229        cfg->defaultImage = DEFAULT_SAVED_GRUB2;
1230     } else if (cfi->defaultIsVariable) {
1231        char *value = defaultLine->elements[2].item;
1232        while (*value && (*value == '"' || *value == '\'' ||
1233        *value == ' ' || *value == '\t'))
1234     value++;
1235        cfg->defaultImage = strtol(value, &end, 10);
1236        while (*end && (*end == '"' || *end == '\'' ||
1237        *end == ' ' || *end == '\t'))
1238     end++;
1239        if (*end) cfg->defaultImage = -1;
1240     } else if (cfi->defaultSupportSaved &&
1241   !strncmp(defaultLine->elements[1].item, "saved", 5)) {   !strncmp(defaultLine->elements[1].item, "saved", 5)) {
1242      cfg->defaultImage = DEFAULT_SAVED;      cfg->defaultImage = DEFAULT_SAVED;
1243   } else if (cfi->defaultIsIndex) {   } else if (cfi->defaultIsIndex) {
1244      cfg->defaultImage = strtol(defaultLine->elements[1].item, &end, 10);      cfg->defaultImage = strtol(defaultLine->elements[1].item, &end, 10);
1245      if (*end) cfg->defaultImage = -1;      if (*end) cfg->defaultImage = -1;
1246   } else if (defaultLine->numElements >= 2) {   } else if (defaultLine->numElements >= 2) {
1247      i = 0;      int i = 0;
1248      while ((entry = findEntryByIndex(cfg, i))) {      while ((entry = findEntryByIndex(cfg, i))) {
1249   for (line = entry->lines; line; line = line->next)   for (line = entry->lines; line; line = line->next)
1250      if (line->type == LT_TITLE) break;      if (line->type == LT_TITLE) break;
# Line 993  static void writeDefault(FILE * out, cha Line 1284  static void writeDefault(FILE * out, cha
1284    
1285      if (cfg->defaultImage == DEFAULT_SAVED)      if (cfg->defaultImage == DEFAULT_SAVED)
1286   fprintf(out, "%sdefault%ssaved\n", indent, separator);   fprintf(out, "%sdefault%ssaved\n", indent, separator);
1287        else if (cfg->defaultImage == DEFAULT_SAVED_GRUB2)
1288     fprintf(out, "%sset default=\"${saved_entry}\"\n", indent);
1289      else if (cfg->defaultImage > -1) {      else if (cfg->defaultImage > -1) {
1290   if (cfg->cfi->defaultIsIndex) {   if (cfg->cfi->defaultIsIndex) {
1291      fprintf(out, "%sdefault%s%d\n", indent, separator,      if (cfg->cfi->defaultIsVariable) {
1292      cfg->defaultImage);          fprintf(out, "%sset default=\"%d\"\n", indent,
1293     cfg->defaultImage);
1294        } else {
1295     fprintf(out, "%sdefault%s%d\n", indent, separator,
1296     cfg->defaultImage);
1297        }
1298   } else {   } else {
1299      int image = cfg->defaultImage;      int image = cfg->defaultImage;
1300    
# Line 1048  static int writeConfig(struct grubConfig Line 1346  static int writeConfig(struct grubConfig
1346    
1347      /* most likely the symlink is relative, so change our      /* most likely the symlink is relative, so change our
1348         directory to the dir of the symlink */         directory to the dir of the symlink */
1349              rc = chdir(dirname(strdupa(outName)));      char *dir = strdupa(outName);
1350        rc = chdir(dirname(dir));
1351      do {      do {
1352   buf = alloca(len + 1);   buf = alloca(len + 1);
1353   rc = readlink(basename(outName), buf, len);   rc = readlink(basename(outName), buf, len);
# Line 1086  static int writeConfig(struct grubConfig Line 1385  static int writeConfig(struct grubConfig
1385      }      }
1386    
1387      line = cfg->theLines;      line = cfg->theLines;
1388        struct keywordTypes *defaultKw = getKeywordByType(LT_DEFAULT, cfg->cfi);
1389      while (line) {      while (line) {
1390   if (line->type == LT_DEFAULT) {          if (line->type == LT_SET_VARIABLE && defaultKw &&
1391     line->numElements == 3 &&
1392     !strcmp(line->elements[1].item, defaultKw->key)) {
1393        writeDefault(out, line->indent, line->elements[0].indent, cfg);
1394        needs &= ~MAIN_DEFAULT;
1395     } else if (line->type == LT_DEFAULT) {
1396      writeDefault(out, line->indent, line->elements[0].indent, cfg);      writeDefault(out, line->indent, line->elements[0].indent, cfg);
1397      needs &= ~MAIN_DEFAULT;      needs &= ~MAIN_DEFAULT;
1398   } else if (line->type == LT_FALLBACK) {   } else if (line->type == LT_FALLBACK) {
# Line 1155  static int numEntries(struct grubConfig Line 1460  static int numEntries(struct grubConfig
1460      return i;      return i;
1461  }  }
1462    
1463    static char *findDiskForRoot()
1464    {
1465        int fd;
1466        char buf[65536];
1467        char *devname;
1468        char *chptr;
1469        int rc;
1470    
1471        if ((fd = open(_PATH_MOUNTED, O_RDONLY)) < 0) {
1472            fprintf(stderr, "grubby: failed to open %s: %s\n",
1473                    _PATH_MOUNTED, strerror(errno));
1474            return NULL;
1475        }
1476    
1477        rc = read(fd, buf, sizeof(buf) - 1);
1478        if (rc <= 0) {
1479            fprintf(stderr, "grubby: failed to read %s: %s\n",
1480                    _PATH_MOUNTED, strerror(errno));
1481            close(fd);
1482            return NULL;
1483        }
1484        close(fd);
1485        buf[rc] = '\0';
1486        chptr = buf;
1487    
1488        char *foundanswer = NULL;
1489    
1490        while (chptr && chptr != buf+rc) {
1491            devname = chptr;
1492    
1493            /*
1494             * The first column of a mtab entry is the device, but if the entry is a
1495             * special device it won't start with /, so move on to the next line.
1496             */
1497            if (*devname != '/') {
1498                chptr = strchr(chptr, '\n');
1499                if (chptr)
1500                    chptr++;
1501                continue;
1502            }
1503    
1504            /* Seek to the next space */
1505            chptr = strchr(chptr, ' ');
1506            if (!chptr) {
1507                fprintf(stderr, "grubby: error parsing %s: %s\n",
1508                        _PATH_MOUNTED, strerror(errno));
1509                return NULL;
1510            }
1511    
1512            /*
1513             * The second column of a mtab entry is the mount point, we are looking
1514             * for '/' obviously.
1515             */
1516            if (*(++chptr) == '/' && *(++chptr) == ' ') {
1517                /* remember the last / entry in mtab */
1518               foundanswer = devname;
1519            }
1520    
1521            /* Next line */
1522            chptr = strchr(chptr, '\n');
1523            if (chptr)
1524                chptr++;
1525        }
1526    
1527        /* Return the last / entry found */
1528        if (foundanswer) {
1529            chptr = strchr(foundanswer, ' ');
1530            *chptr = '\0';
1531            return strdup(foundanswer);
1532        }
1533    
1534        return NULL;
1535    }
1536    
1537    void printEntry(struct singleEntry * entry) {
1538        int i;
1539        struct singleLine * line;
1540    
1541        for (line = entry->lines; line; line = line->next) {
1542     fprintf(stderr, "DBG: %s", line->indent);
1543     for (i = 0; i < line->numElements; i++) {
1544        /* Need to handle this, because we strip the quotes from
1545         * menuentry when read it. */
1546        if (line->type == LT_MENUENTRY && i == 1) {
1547     if(!isquote(*line->elements[i].item))
1548        fprintf(stderr, "\'%s\'", line->elements[i].item);
1549     else
1550        fprintf(stderr, "%s", line->elements[i].item);
1551     fprintf(stderr, "%s", line->elements[i].indent);
1552    
1553     continue;
1554        }
1555        
1556        fprintf(stderr, "%s%s",
1557        line->elements[i].item, line->elements[i].indent);
1558     }
1559     fprintf(stderr, "\n");
1560        }
1561    }
1562    
1563    void notSuitablePrintf(struct singleEntry * entry, const char *fmt, ...)
1564    {
1565        va_list argp;
1566    
1567        if (!debug)
1568     return;
1569    
1570        va_start(argp, fmt);
1571        fprintf(stderr, "DBG: Image entry failed: ");
1572        vfprintf(stderr, fmt, argp);
1573        printEntry(entry);
1574        va_end(argp);
1575    }
1576    
1577    #define beginswith(s, c) ((s) && (s)[0] == (c))
1578    
1579    static int endswith(const char *s, char c)
1580    {
1581     int slen;
1582    
1583     if (!s || !s[0])
1584     return 0;
1585     slen = strlen(s) - 1;
1586    
1587     return s[slen] == c;
1588    }
1589    
1590  int suitableImage(struct singleEntry * entry, const char * bootPrefix,  int suitableImage(struct singleEntry * entry, const char * bootPrefix,
1591    int skipRemoved, int flags) {    int skipRemoved, int flags) {
1592      struct singleLine * line;      struct singleLine * line;
1593      char * fullName;      char * fullName;
1594      int i;      int i;
     struct stat sb, sb2;  
1595      char * dev;      char * dev;
1596      char * rootspec;      char * rootspec;
1597        char * rootdev;
1598    
1599      if (skipRemoved && entry->skip) return 0;      if (skipRemoved && entry->skip) {
1600     notSuitablePrintf(entry, "marked to skip\n");
1601     return 0;
1602        }
1603    
1604      line = getLineByType(LT_KERNEL|LT_HYPER, entry->lines);      line = getLineByType(LT_KERNEL|LT_HYPER|LT_KERNEL_EFI, entry->lines);
1605      if (!line || line->numElements < 2) return 0;      if (!line) {
1606     notSuitablePrintf(entry, "no line found\n");
1607     return 0;
1608        }
1609        if (line->numElements < 2) {
1610     notSuitablePrintf(entry, "line has only %d elements\n",
1611        line->numElements);
1612     return 0;
1613        }
1614    
1615      if (flags & GRUBBY_BADIMAGE_OKAY) return 1;      if (flags & GRUBBY_BADIMAGE_OKAY) return 1;
1616    
1617      fullName = alloca(strlen(bootPrefix) +      fullName = alloca(strlen(bootPrefix) +
1618        strlen(line->elements[1].item) + 1);        strlen(line->elements[1].item) + 1);
1619      rootspec = getRootSpecifier(line->elements[1].item);      rootspec = getRootSpecifier(line->elements[1].item);
1620      sprintf(fullName, "%s%s", bootPrefix,      int rootspec_offset = rootspec ? strlen(rootspec) : 0;
1621              line->elements[1].item + (rootspec ? strlen(rootspec) : 0));      int hasslash = endswith(bootPrefix, '/') ||
1622      if (access(fullName, R_OK)) return 0;       beginswith(line->elements[1].item + rootspec_offset, '/');
1623        sprintf(fullName, "%s%s%s", bootPrefix, hasslash ? "" : "/",
1624                line->elements[1].item + rootspec_offset);
1625        if (access(fullName, R_OK)) {
1626     notSuitablePrintf(entry, "access to %s failed\n", fullName);
1627     return 0;
1628        }
1629      for (i = 2; i < line->numElements; i++)      for (i = 2; i < line->numElements; i++)
1630   if (!strncasecmp(line->elements[i].item, "root=", 5)) break;   if (!strncasecmp(line->elements[i].item, "root=", 5)) break;
1631      if (i < line->numElements) {      if (i < line->numElements) {
# Line 1195  int suitableImage(struct singleEntry * e Line 1643  int suitableImage(struct singleEntry * e
1643      line = getLineByType(LT_KERNELARGS|LT_MBMODULE, entry->lines);      line = getLineByType(LT_KERNELARGS|LT_MBMODULE, entry->lines);
1644    
1645              /* failed to find one */              /* failed to find one */
1646              if (!line) return 0;              if (!line) {
1647     notSuitablePrintf(entry, "no line found\n");
1648     return 0;
1649                }
1650    
1651      for (i = 1; i < line->numElements; i++)      for (i = 1; i < line->numElements; i++)
1652          if (!strncasecmp(line->elements[i].item, "root=", 5)) break;          if (!strncasecmp(line->elements[i].item, "root=", 5)) break;
1653      if (i < line->numElements)      if (i < line->numElements)
1654          dev = line->elements[i].item + 5;          dev = line->elements[i].item + 5;
1655      else {      else {
1656     notSuitablePrintf(entry, "no root= entry found\n");
1657   /* it failed too...  can't find root= */   /* it failed too...  can't find root= */
1658          return 0;          return 0;
1659              }              }
# Line 1209  int suitableImage(struct singleEntry * e Line 1661  int suitableImage(struct singleEntry * e
1661      }      }
1662    
1663      dev = getpathbyspec(dev);      dev = getpathbyspec(dev);
1664      if (!dev)      if (!getpathbyspec(dev)) {
1665            notSuitablePrintf(entry, "can't find blkid entry for %s\n", dev);
1666          return 0;          return 0;
1667        } else
1668     dev = getpathbyspec(dev);
1669    
1670      i = stat(dev, &sb);      rootdev = findDiskForRoot();
1671      if (i)      if (!rootdev) {
1672            notSuitablePrintf(entry, "can't find root device\n");
1673   return 0;   return 0;
1674        }
1675    
1676      stat("/", &sb2);      if (!getuuidbydev(rootdev) || !getuuidbydev(dev)) {
1677            notSuitablePrintf(entry, "uuid missing: rootdev %s, dev %s\n",
1678     getuuidbydev(rootdev), getuuidbydev(dev));
1679            free(rootdev);
1680            return 0;
1681        }
1682    
1683      if (sb.st_rdev != sb2.st_dev)      if (strcmp(getuuidbydev(rootdev), getuuidbydev(dev))) {
1684            notSuitablePrintf(entry, "uuid mismatch: rootdev %s, dev %s\n",
1685     getuuidbydev(rootdev), getuuidbydev(dev));
1686     free(rootdev);
1687          return 0;          return 0;
1688        }
1689    
1690        free(rootdev);
1691    
1692      return 1;      return 1;
1693  }  }
# Line 1263  struct singleEntry * findEntryByPath(str Line 1731  struct singleEntry * findEntryByPath(str
1731   entry = findEntryByIndex(config, indexVars[i]);   entry = findEntryByIndex(config, indexVars[i]);
1732   if (!entry) return NULL;   if (!entry) return NULL;
1733    
1734   line = getLineByType(LT_KERNEL|LT_HYPER, entry->lines);   line = getLineByType(LT_KERNEL|LT_HYPER|LT_KERNEL_EFI, entry->lines);
1735   if (!line) return NULL;   if (!line) return NULL;
1736    
1737   if (index) *index = indexVars[i];   if (index) *index = indexVars[i];
# Line 1301  struct singleEntry * findEntryByPath(str Line 1769  struct singleEntry * findEntryByPath(str
1769    
1770   if (!strncmp(kernel, "TITLE=", 6)) {   if (!strncmp(kernel, "TITLE=", 6)) {
1771      prefix = "";      prefix = "";
1772      checkType = LT_TITLE;      checkType = LT_TITLE|LT_MENUENTRY;
1773      kernel += 6;      kernel += 6;
1774   }   }
1775    
# Line 1312  struct singleEntry * findEntryByPath(str Line 1780  struct singleEntry * findEntryByPath(str
1780    
1781      /* check all the lines matching checkType */      /* check all the lines matching checkType */
1782      for (line = entry->lines; line; line = line->next) {      for (line = entry->lines; line; line = line->next) {
1783   line = getLineByType(entry->multiboot && checkType == LT_KERNEL ?   enum lineType_e ct = checkType;
1784       LT_KERNEL|LT_MBMODULE|LT_HYPER :   if (entry->multiboot && checkType == LT_KERNEL)
1785       checkType, line);      ct = LT_KERNEL|LT_KERNEL_EFI|LT_MBMODULE|LT_HYPER;
1786   if (!line) break;  /* not found in this entry */   else if (checkType & LT_KERNEL)
1787        ct = checkType | LT_KERNEL_EFI;
1788     line = getLineByType(ct, line);
1789     if (!line)
1790        break;  /* not found in this entry */
1791    
1792   if (line && line->numElements >= 2) {   if (line && line->type != LT_MENUENTRY &&
1793     line->numElements >= 2) {
1794      rootspec = getRootSpecifier(line->elements[1].item);      rootspec = getRootSpecifier(line->elements[1].item);
1795      if (!strcmp(line->elements[1].item +      if (!strcmp(line->elements[1].item +
1796   ((rootspec != NULL) ? strlen(rootspec) : 0),   ((rootspec != NULL) ? strlen(rootspec) : 0),
1797   kernel + strlen(prefix)))   kernel + strlen(prefix)))
1798   break;   break;
1799   }   }
1800     if(line->type == LT_MENUENTRY &&
1801     !strcmp(line->elements[1].item, kernel))
1802        break;
1803      }      }
1804    
1805      /* make sure this entry has a kernel identifier; this skips      /* make sure this entry has a kernel identifier; this skips
1806       * non-Linux boot entries (could find netbsd etc, though, which is       * non-Linux boot entries (could find netbsd etc, though, which is
1807       * unfortunate)       * unfortunate)
1808       */       */
1809      if (line && getLineByType(LT_KERNEL|LT_HYPER, entry->lines))      if (line && getLineByType(LT_KERNEL|LT_HYPER|LT_KERNEL_EFI, entry->lines))
1810   break; /* found 'im! */   break; /* found 'im! */
1811   }   }
1812    
# Line 1415  void markRemovedImage(struct grubConfig Line 1891  void markRemovedImage(struct grubConfig
1891        const char * prefix) {        const char * prefix) {
1892      struct singleEntry * entry;      struct singleEntry * entry;
1893    
1894      if (!image) return;      if (!image)
1895     return;
1896    
1897        /* check and see if we're removing the default image */
1898        if (isdigit(*image)) {
1899     entry = findEntryByPath(cfg, image, prefix, NULL);
1900     if(entry)
1901        entry->skip = 1;
1902     return;
1903        }
1904    
1905      while ((entry = findEntryByPath(cfg, image, prefix, NULL)))      while ((entry = findEntryByPath(cfg, image, prefix, NULL)))
1906   entry->skip = 1;   entry->skip = 1;
# Line 1423  void markRemovedImage(struct grubConfig Line 1908  void markRemovedImage(struct grubConfig
1908    
1909  void setDefaultImage(struct grubConfig * config, int hasNew,  void setDefaultImage(struct grubConfig * config, int hasNew,
1910       const char * defaultKernelPath, int newIsDefault,       const char * defaultKernelPath, int newIsDefault,
1911       const char * prefix, int flags) {       const char * prefix, int flags, int index) {
1912      struct singleEntry * entry, * entry2, * newDefault;      struct singleEntry * entry, * entry2, * newDefault;
1913      int i, j;      int i, j;
1914    
1915      if (newIsDefault) {      if (newIsDefault) {
1916   config->defaultImage = 0;   config->defaultImage = 0;
1917   return;   return;
1918        } else if ((index >= 0) && config->cfi->defaultIsIndex) {
1919     if (findEntryByIndex(config, index))
1920        config->defaultImage = index;
1921     else
1922        config->defaultImage = -1;
1923     return;
1924      } else if (defaultKernelPath) {      } else if (defaultKernelPath) {
1925   i = 0;   i = 0;
1926   if (findEntryByPath(config, defaultKernelPath, prefix, &i)) {   if (findEntryByPath(config, defaultKernelPath, prefix, &i)) {
# Line 1442  void setDefaultImage(struct grubConfig * Line 1933  void setDefaultImage(struct grubConfig *
1933    
1934      /* 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
1935         changes */         changes */
1936      if (config->defaultImage == DEFAULT_SAVED)      if ((config->defaultImage == DEFAULT_SAVED) ||
1937     (config->defaultImage == DEFAULT_SAVED_GRUB2))
1938        /* default is set to saved, we don't want to change it */        /* default is set to saved, we don't want to change it */
1939        return;        return;
1940    
# Line 1503  void displayEntry(struct singleEntry * e Line 1995  void displayEntry(struct singleEntry * e
1995    
1996      printf("index=%d\n", index);      printf("index=%d\n", index);
1997    
1998      line = getLineByType(LT_KERNEL|LT_HYPER, entry->lines);      line = getLineByType(LT_KERNEL|LT_HYPER|LT_KERNEL_EFI, entry->lines);
1999      if (!line) {      if (!line) {
2000          printf("non linux entry\n");          printf("non linux entry\n");
2001          return;          return;
2002      }      }
2003    
2004      printf("kernel=%s\n", line->elements[1].item);      if (!strncmp(prefix, line->elements[1].item, strlen(prefix)))
2005     printf("kernel=%s\n", line->elements[1].item);
2006        else
2007     printf("kernel=%s%s\n", prefix, line->elements[1].item);
2008    
2009      if (line->numElements >= 3) {      if (line->numElements >= 3) {
2010   printf("args=\"");   printf("args=\"");
# Line 1565  void displayEntry(struct singleEntry * e Line 2060  void displayEntry(struct singleEntry * e
2060   printf("root=%s\n", s);   printf("root=%s\n", s);
2061      }      }
2062    
2063      line = getLineByType(LT_INITRD, entry->lines);      line = getLineByType(LT_INITRD|LT_INITRD_EFI, entry->lines);
2064    
2065      if (line && line->numElements >= 2) {      if (line && line->numElements >= 2) {
2066   printf("initrd=%s", prefix);   if (!strncmp(prefix, line->elements[1].item, strlen(prefix)))
2067        printf("initrd=");
2068     else
2069        printf("initrd=%s", prefix);
2070    
2071   for (i = 1; i < line->numElements; i++)   for (i = 1; i < line->numElements; i++)
2072      printf("%s%s", line->elements[i].item, line->elements[i].indent);      printf("%s%s", line->elements[i].item, line->elements[i].indent);
2073   printf("\n");   printf("\n");
2074      }      }
2075    
2076        line = getLineByType(LT_TITLE, entry->lines);
2077        if (line) {
2078     printf("title=%s\n", line->elements[1].item);
2079        } else {
2080     char * title;
2081     line = getLineByType(LT_MENUENTRY, entry->lines);
2082     title = grub2ExtractTitle(line);
2083     if (title)
2084        printf("title=%s\n", title);
2085        }
2086    }
2087    
2088    int isSuseSystem(void) {
2089        const char * path;
2090        const static char default_path[] = "/etc/SuSE-release";
2091    
2092        if ((path = getenv("GRUBBY_SUSE_RELEASE")) == NULL)
2093     path = default_path;
2094    
2095        if (!access(path, R_OK))
2096     return 1;
2097        return 0;
2098    }
2099    
2100    int isSuseGrubConf(const char * path) {
2101        FILE * grubConf;
2102        char * line = NULL;
2103        size_t len = 0, res = 0;
2104    
2105        grubConf = fopen(path, "r");
2106        if (!grubConf) {
2107            dbgPrintf("Could not open SuSE configuration file '%s'\n", path);
2108     return 0;
2109        }
2110    
2111        while ((res = getline(&line, &len, grubConf)) != -1) {
2112     if (!strncmp(line, "setup", 5)) {
2113        fclose(grubConf);
2114        free(line);
2115        return 1;
2116     }
2117        }
2118    
2119        dbgPrintf("SuSE configuration file '%s' does not appear to be valid\n",
2120          path);
2121    
2122        fclose(grubConf);
2123        free(line);
2124        return 0;
2125    }
2126    
2127    int suseGrubConfGetLba(const char * path, int * lbaPtr) {
2128        FILE * grubConf;
2129        char * line = NULL;
2130        size_t res = 0, len = 0;
2131    
2132        if (!path) return 1;
2133        if (!lbaPtr) return 1;
2134    
2135        grubConf = fopen(path, "r");
2136        if (!grubConf) return 1;
2137    
2138        while ((res = getline(&line, &len, grubConf)) != -1) {
2139     if (line[res - 1] == '\n')
2140        line[res - 1] = '\0';
2141     else if (len > res)
2142        line[res] = '\0';
2143     else {
2144        line = realloc(line, res + 1);
2145        line[res] = '\0';
2146     }
2147    
2148     if (!strncmp(line, "setup", 5)) {
2149        if (strstr(line, "--force-lba")) {
2150            *lbaPtr = 1;
2151        } else {
2152            *lbaPtr = 0;
2153        }
2154        dbgPrintf("lba: %i\n", *lbaPtr);
2155        break;
2156     }
2157        }
2158    
2159        free(line);
2160        fclose(grubConf);
2161        return 0;
2162    }
2163    
2164    int suseGrubConfGetInstallDevice(const char * path, char ** devicePtr) {
2165        FILE * grubConf;
2166        char * line = NULL;
2167        size_t res = 0, len = 0;
2168        char * lastParamPtr = NULL;
2169        char * secLastParamPtr = NULL;
2170        char installDeviceNumber = '\0';
2171        char * bounds = NULL;
2172    
2173        if (!path) return 1;
2174        if (!devicePtr) return 1;
2175    
2176        grubConf = fopen(path, "r");
2177        if (!grubConf) return 1;
2178    
2179        while ((res = getline(&line, &len, grubConf)) != -1) {
2180     if (strncmp(line, "setup", 5))
2181        continue;
2182    
2183     if (line[res - 1] == '\n')
2184        line[res - 1] = '\0';
2185     else if (len > res)
2186        line[res] = '\0';
2187     else {
2188        line = realloc(line, res + 1);
2189        line[res] = '\0';
2190     }
2191    
2192     lastParamPtr = bounds = line + res;
2193    
2194     /* Last parameter in grub may be an optional IMAGE_DEVICE */
2195     while (!isspace(*lastParamPtr))
2196        lastParamPtr--;
2197     lastParamPtr++;
2198    
2199     secLastParamPtr = lastParamPtr - 2;
2200     dbgPrintf("lastParamPtr: %s\n", lastParamPtr);
2201    
2202     if (lastParamPtr + 3 > bounds) {
2203        dbgPrintf("lastParamPtr going over boundary");
2204        fclose(grubConf);
2205        free(line);
2206        return 1;
2207     }
2208     if (!strncmp(lastParamPtr, "(hd", 3))
2209        lastParamPtr += 3;
2210     dbgPrintf("lastParamPtr: %c\n", *lastParamPtr);
2211    
2212     /*
2213     * Second last parameter will decide wether last parameter is
2214     * an IMAGE_DEVICE or INSTALL_DEVICE
2215     */
2216     while (!isspace(*secLastParamPtr))
2217        secLastParamPtr--;
2218     secLastParamPtr++;
2219    
2220     if (secLastParamPtr + 3 > bounds) {
2221        dbgPrintf("secLastParamPtr going over boundary");
2222        fclose(grubConf);
2223        free(line);
2224        return 1;
2225     }
2226     dbgPrintf("secLastParamPtr: %s\n", secLastParamPtr);
2227     if (!strncmp(secLastParamPtr, "(hd", 3)) {
2228        secLastParamPtr += 3;
2229        dbgPrintf("secLastParamPtr: %c\n", *secLastParamPtr);
2230        installDeviceNumber = *secLastParamPtr;
2231     } else {
2232        installDeviceNumber = *lastParamPtr;
2233     }
2234    
2235     *devicePtr = malloc(6);
2236     snprintf(*devicePtr, 6, "(hd%c)", installDeviceNumber);
2237     dbgPrintf("installDeviceNumber: %c\n", installDeviceNumber);
2238     fclose(grubConf);
2239     free(line);
2240     return 0;
2241        }
2242    
2243        free(line);
2244        fclose(grubConf);
2245        return 1;
2246    }
2247    
2248    int grubGetBootFromDeviceMap(const char * device,
2249         char ** bootPtr) {
2250        FILE * deviceMap;
2251        char * line = NULL;
2252        size_t res = 0, len = 0;
2253        char * devicePtr;
2254        char * bounds = NULL;
2255        const char * path;
2256        const static char default_path[] = "/boot/grub/device.map";
2257    
2258        if (!device) return 1;
2259        if (!bootPtr) return 1;
2260    
2261        if ((path = getenv("GRUBBY_GRUB_DEVICE_MAP")) == NULL)
2262     path = default_path;
2263    
2264        dbgPrintf("opening grub device.map file from: %s\n", path);
2265        deviceMap = fopen(path, "r");
2266        if (!deviceMap)
2267     return 1;
2268    
2269        while ((res = getline(&line, &len, deviceMap)) != -1) {
2270            if (!strncmp(line, "#", 1))
2271        continue;
2272    
2273     if (line[res - 1] == '\n')
2274        line[res - 1] = '\0';
2275     else if (len > res)
2276        line[res] = '\0';
2277     else {
2278        line = realloc(line, res + 1);
2279        line[res] = '\0';
2280     }
2281    
2282     devicePtr = line;
2283     bounds = line + res;
2284    
2285     while ((isspace(*line) && ((devicePtr + 1) <= bounds)))
2286        devicePtr++;
2287     dbgPrintf("device: %s\n", devicePtr);
2288    
2289     if (!strncmp(devicePtr, device, strlen(device))) {
2290        devicePtr += strlen(device);
2291        while (isspace(*devicePtr) && ((devicePtr + 1) <= bounds))
2292            devicePtr++;
2293    
2294        *bootPtr = strdup(devicePtr);
2295        break;
2296     }
2297        }
2298    
2299        free(line);
2300        fclose(deviceMap);
2301        return 0;
2302    }
2303    
2304    int suseGrubConfGetBoot(const char * path, char ** bootPtr) {
2305        char * grubDevice;
2306    
2307        if (suseGrubConfGetInstallDevice(path, &grubDevice))
2308     dbgPrintf("error looking for grub installation device\n");
2309        else
2310     dbgPrintf("grubby installation device: %s\n", grubDevice);
2311    
2312        if (grubGetBootFromDeviceMap(grubDevice, bootPtr))
2313     dbgPrintf("error looking for grub boot device\n");
2314        else
2315     dbgPrintf("grubby boot device: %s\n", *bootPtr);
2316    
2317        free(grubDevice);
2318        return 0;
2319    }
2320    
2321    int parseSuseGrubConf(int * lbaPtr, char ** bootPtr) {
2322        /*
2323         * This SuSE grub configuration file at this location is not your average
2324         * grub configuration file, but instead the grub commands used to setup
2325         * grub on that system.
2326         */
2327        const char * path;
2328        const static char default_path[] = "/etc/grub.conf";
2329    
2330        if ((path = getenv("GRUBBY_SUSE_GRUB_CONF")) == NULL)
2331     path = default_path;
2332    
2333        if (!isSuseGrubConf(path)) return 1;
2334    
2335        if (lbaPtr) {
2336            *lbaPtr = 0;
2337            if (suseGrubConfGetLba(path, lbaPtr))
2338                return 1;
2339        }
2340    
2341        if (bootPtr) {
2342            *bootPtr = NULL;
2343            suseGrubConfGetBoot(path, bootPtr);
2344        }
2345    
2346        return 0;
2347  }  }
2348    
2349  int parseSysconfigGrub(int * lbaPtr, char ** bootPtr) {  int parseSysconfigGrub(int * lbaPtr, char ** bootPtr) {
# Line 1623  int parseSysconfigGrub(int * lbaPtr, cha Line 2394  int parseSysconfigGrub(int * lbaPtr, cha
2394  }  }
2395    
2396  void dumpSysconfigGrub(void) {  void dumpSysconfigGrub(void) {
2397      char * boot;      char * boot = NULL;
2398      int lba;      int lba;
2399    
2400      if (!parseSysconfigGrub(&lba, &boot)) {      if (isSuseSystem()) {
2401   if (lba) printf("lba\n");          if (parseSuseGrubConf(&lba, &boot)) {
2402   if (boot) printf("boot=%s\n", boot);      free(boot);
2403        return;
2404     }
2405        } else {
2406            if (parseSysconfigGrub(&lba, &boot)) {
2407        free(boot);
2408        return;
2409     }
2410        }
2411    
2412        if (lba) printf("lba\n");
2413        if (boot) {
2414     printf("boot=%s\n", boot);
2415     free(boot);
2416      }      }
2417  }  }
2418    
# Line 1677  struct singleLine * addLineTmpl(struct s Line 2461  struct singleLine * addLineTmpl(struct s
2461  {  {
2462      struct singleLine * newLine = lineDup(tmplLine);      struct singleLine * newLine = lineDup(tmplLine);
2463    
2464        if (isEfi && cfi == &grub2ConfigType) {
2465     enum lineType_e old = newLine->type;
2466     newLine->type = preferredLineType(newLine->type, cfi);
2467     if (old != newLine->type)
2468        newLine->elements[0].item = getKeyByType(newLine->type, cfi);
2469        }
2470    
2471      if (val) {      if (val) {
2472   /* override the inherited value with our own.   /* override the inherited value with our own.
2473   * 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 1686  struct singleLine * addLineTmpl(struct s Line 2477  struct singleLine * addLineTmpl(struct s
2477   insertElement(newLine, val, 1, cfi);   insertElement(newLine, val, 1, cfi);
2478    
2479   /* but try to keep the rootspec from the template... sigh */   /* but try to keep the rootspec from the template... sigh */
2480   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)) {
2481      char * rootspec = getRootSpecifier(tmplLine->elements[1].item);      char * rootspec = getRootSpecifier(tmplLine->elements[1].item);
2482      if (rootspec != NULL) {      if (rootspec != NULL) {
2483   free(newLine->elements[1].item);   free(newLine->elements[1].item);
# Line 1723  struct singleLine *  addLine(struct sing Line 2514  struct singleLine *  addLine(struct sing
2514      /* 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
2515       * stack since it calls addLineTmpl which will make copies.       * stack since it calls addLineTmpl which will make copies.
2516       */       */
   
2517      if (type == LT_TITLE && cfi->titleBracketed) {      if (type == LT_TITLE && cfi->titleBracketed) {
2518   /* we're doing a bracketed title (zipl) */   /* we're doing a bracketed title (zipl) */
2519   tmpl.type = type;   tmpl.type = type;
# Line 1733  struct singleLine *  addLine(struct sing Line 2523  struct singleLine *  addLine(struct sing
2523   sprintf(tmpl.elements[0].item, "[%s]", val);   sprintf(tmpl.elements[0].item, "[%s]", val);
2524   tmpl.elements[0].indent = "";   tmpl.elements[0].indent = "";
2525   val = NULL;   val = NULL;
2526        } else if (type == LT_MENUENTRY) {
2527     char *lineend = "--class gnu-linux --class gnu --class os {";
2528     if (!val) {
2529        fprintf(stderr, "Line type LT_MENUENTRY requires a value\n");
2530        abort();
2531     }
2532     kw = getKeywordByType(type, cfi);
2533     if (!kw) {
2534        fprintf(stderr, "Looking up keyword for unknown type %d\n", type);
2535        abort();
2536     }
2537     tmpl.indent = "";
2538     tmpl.type = type;
2539     tmpl.numElements = 3;
2540     tmpl.elements = alloca(sizeof(*tmpl.elements) * tmpl.numElements);
2541     tmpl.elements[0].item = kw->key;
2542     tmpl.elements[0].indent = alloca(2);
2543     sprintf(tmpl.elements[0].indent, "%c", kw->nextChar);
2544     tmpl.elements[1].item = (char *)val;
2545     tmpl.elements[1].indent = alloca(2);
2546     sprintf(tmpl.elements[1].indent, "%c", kw->nextChar);
2547     tmpl.elements[2].item = alloca(strlen(lineend)+1);
2548     strcpy(tmpl.elements[2].item, lineend);
2549     tmpl.elements[2].indent = "";
2550      } else {      } else {
2551   kw = getKeywordByType(type, cfi);   kw = getKeywordByType(type, cfi);
2552   if (!kw) abort();   if (!kw) {
2553        fprintf(stderr, "Looking up keyword for unknown type %d\n", type);
2554        abort();
2555     }
2556   tmpl.type = type;   tmpl.type = type;
2557   tmpl.numElements = val ? 2 : 1;   tmpl.numElements = val ? 2 : 1;
2558   tmpl.elements = alloca(sizeof(*tmpl.elements) * tmpl.numElements);   tmpl.elements = alloca(sizeof(*tmpl.elements) * tmpl.numElements);
# Line 1759  struct singleLine *  addLine(struct sing Line 2576  struct singleLine *  addLine(struct sing
2576   if (!line->next && !prev) prev = line;   if (!line->next && !prev) prev = line;
2577      }      }
2578    
2579      if (prev == entry->lines)      struct singleLine *menuEntry;
2580   tmpl.indent = defaultIndent ?: "";      menuEntry = getLineByType(LT_MENUENTRY, entry->lines);
2581      else      if (tmpl.type == LT_ENTRY_END) {
2582   tmpl.indent = prev->indent;   if (menuEntry)
2583        tmpl.indent = menuEntry->indent;
2584     else
2585        tmpl.indent = defaultIndent ?: "";
2586        } else if (tmpl.type != LT_MENUENTRY) {
2587     if (menuEntry)
2588        tmpl.indent = "\t";
2589     else if (prev == entry->lines)
2590        tmpl.indent = defaultIndent ?: "";
2591     else
2592        tmpl.indent = prev->indent;
2593        }
2594    
2595      return addLineTmpl(entry, &tmpl, prev, val, cfi);      return addLineTmpl(entry, &tmpl, prev, val, cfi);
2596  }  }
# Line 1789  void removeLine(struct singleEntry * ent Line 2617  void removeLine(struct singleEntry * ent
2617      free(line);      free(line);
2618  }  }
2619    
2620    static void requote(struct singleLine *tmplLine, struct configFileInfo * cfi)
2621    {
2622        struct singleLine newLine = {
2623     .indent = tmplLine->indent,
2624     .type = tmplLine->type,
2625     .next = tmplLine->next,
2626        };
2627        int firstQuotedItem = -1;
2628        int quoteLen = 0;
2629        int j;
2630        int element = 0;
2631        char *c;
2632    
2633        c = malloc(strlen(tmplLine->elements[0].item) + 1);
2634        strcpy(c, tmplLine->elements[0].item);
2635        insertElement(&newLine, c, element++, cfi);
2636        free(c);
2637        c = NULL;
2638    
2639        for (j = 1; j < tmplLine->numElements; j++) {
2640     if (firstQuotedItem == -1) {
2641        quoteLen += strlen(tmplLine->elements[j].item);
2642        
2643        if (isquote(tmplLine->elements[j].item[0])) {
2644     firstQuotedItem = j;
2645            quoteLen += strlen(tmplLine->elements[j].indent);
2646        } else {
2647     c = malloc(quoteLen + 1);
2648     strcpy(c, tmplLine->elements[j].item);
2649     insertElement(&newLine, c, element++, cfi);
2650     free(c);
2651     quoteLen = 0;
2652        }
2653     } else {
2654        int itemlen = strlen(tmplLine->elements[j].item);
2655        quoteLen += itemlen;
2656        quoteLen += strlen(tmplLine->elements[j].indent);
2657        
2658        if (isquote(tmplLine->elements[j].item[itemlen - 1])) {
2659     c = malloc(quoteLen + 1);
2660     c[0] = '\0';
2661     for (int i = firstQuotedItem; i < j+1; i++) {
2662        strcat(c, tmplLine->elements[i].item);
2663        strcat(c, tmplLine->elements[i].indent);
2664     }
2665     insertElement(&newLine, c, element++, cfi);
2666     free(c);
2667    
2668     firstQuotedItem = -1;
2669     quoteLen = 0;
2670        }
2671     }
2672        }
2673        while (tmplLine->numElements)
2674     removeElement(tmplLine, 0);
2675        if (tmplLine->elements)
2676     free(tmplLine->elements);
2677    
2678        tmplLine->numElements = newLine.numElements;
2679        tmplLine->elements = newLine.elements;
2680    }
2681    
2682  static void insertElement(struct singleLine * line,  static void insertElement(struct singleLine * line,
2683    const char * item, int insertHere,    const char * item, int insertHere,
2684    struct configFileInfo * cfi)    struct configFileInfo * cfi)
# Line 1895  int updateActualImage(struct grubConfig Line 2785  int updateActualImage(struct grubConfig
2785      const char ** arg;      const char ** arg;
2786      int useKernelArgs, useRoot;      int useKernelArgs, useRoot;
2787      int firstElement;      int firstElement;
2788      int *usedElements, *usedArgs;      int *usedElements;
2789      int doreplace;      int doreplace;
2790    
2791      if (!image) return 0;      if (!image) return 0;
# Line 1930  int updateActualImage(struct grubConfig Line 2820  int updateActualImage(struct grubConfig
2820      useRoot = (getKeywordByType(LT_ROOT, cfg->cfi)      useRoot = (getKeywordByType(LT_ROOT, cfg->cfi)
2821         && !multibootArgs);         && !multibootArgs);
2822    
     for (k = 0, arg = newArgs; *arg; arg++, k++) ;  
     usedArgs = calloc(k, sizeof(*usedArgs));  
   
2823      for (; (entry = findEntryByPath(cfg, image, prefix, &index)); index++) {      for (; (entry = findEntryByPath(cfg, image, prefix, &index)); index++) {
2824    
2825   if (multibootArgs && !entry->multiboot)   if (multibootArgs && !entry->multiboot)
# Line 1960  int updateActualImage(struct grubConfig Line 2847  int updateActualImage(struct grubConfig
2847      firstElement = 2;      firstElement = 2;
2848    
2849   } else {   } else {
2850      line = getLineByType(LT_KERNEL|LT_MBMODULE, entry->lines);      line = getLineByType(LT_KERNEL|LT_MBMODULE|LT_KERNEL_EFI, entry->lines);
2851      if (!line) {      if (!line) {
2852   /* no LT_KERNEL or LT_MBMODULE in this entry? */   /* no LT_KERNEL or LT_MBMODULE in this entry? */
2853   continue;   continue;
# Line 2008  int updateActualImage(struct grubConfig Line 2895  int updateActualImage(struct grubConfig
2895          usedElements = calloc(line->numElements, sizeof(*usedElements));          usedElements = calloc(line->numElements, sizeof(*usedElements));
2896    
2897   for (k = 0, arg = newArgs; *arg; arg++, k++) {   for (k = 0, arg = newArgs; *arg; arg++, k++) {
             if (usedArgs[k]) continue;  
2898    
2899      doreplace = 1;      doreplace = 1;
2900      for (i = firstElement; i < line->numElements; i++) {      for (i = firstElement; i < line->numElements; i++) {
# Line 2023  int updateActualImage(struct grubConfig Line 2909  int updateActualImage(struct grubConfig
2909                      continue;                      continue;
2910   if (!argMatch(line->elements[i].item, *arg)) {   if (!argMatch(line->elements[i].item, *arg)) {
2911                      usedElements[i]=1;                      usedElements[i]=1;
                     usedArgs[k]=1;  
2912      break;      break;
2913                  }                  }
2914              }              }
# Line 2093  int updateActualImage(struct grubConfig Line 2978  int updateActualImage(struct grubConfig
2978   }   }
2979      }      }
2980    
     free(usedArgs);  
2981      free(newArgs);      free(newArgs);
2982      free(oldArgs);      free(oldArgs);
2983    
# Line 2119  int updateImage(struct grubConfig * cfg, Line 3003  int updateImage(struct grubConfig * cfg,
3003      return rc;      return rc;
3004  }  }
3005    
3006    int updateInitrd(struct grubConfig * cfg, const char * image,
3007                     const char * prefix, const char * initrd) {
3008        struct singleEntry * entry;
3009        struct singleLine * line, * kernelLine, *endLine = NULL;
3010        int index = 0;
3011    
3012        if (!image) return 0;
3013    
3014        for (; (entry = findEntryByPath(cfg, image, prefix, &index)); index++) {
3015            kernelLine = getLineByType(LT_KERNEL|LT_KERNEL_EFI, entry->lines);
3016            if (!kernelLine) continue;
3017    
3018            line = getLineByType(LT_INITRD|LT_INITRD_EFI, entry->lines);
3019            if (line)
3020                removeLine(entry, line);
3021            if (prefix) {
3022                int prefixLen = strlen(prefix);
3023                if (!strncmp(initrd, prefix, prefixLen))
3024                    initrd += prefixLen;
3025            }
3026     endLine = getLineByType(LT_ENTRY_END, entry->lines);
3027     if (endLine)
3028        removeLine(entry, endLine);
3029            line = addLine(entry, cfg->cfi, preferredLineType(LT_INITRD, cfg->cfi),
3030     kernelLine->indent, initrd);
3031            if (!line)
3032        return 1;
3033     if (endLine) {
3034        line = addLine(entry, cfg->cfi, LT_ENTRY_END, "", NULL);
3035                if (!line)
3036     return 1;
3037     }
3038    
3039            break;
3040        }
3041    
3042        return 0;
3043    }
3044    
3045  int checkDeviceBootloader(const char * device, const unsigned char * boot) {  int checkDeviceBootloader(const char * device, const unsigned char * boot) {
3046      int fd;      int fd;
3047      unsigned char bootSect[512];      unsigned char bootSect[512];
# Line 2142  int checkDeviceBootloader(const char * d Line 3065  int checkDeviceBootloader(const char * d
3065      if (memcmp(boot, bootSect, 3))      if (memcmp(boot, bootSect, 3))
3066   return 0;   return 0;
3067    
3068      if (boot[1] == 0xeb) {      if (boot[1] == JMP_SHORT_OPCODE) {
3069   offset = boot[2] + 2;   offset = boot[2] + 2;
3070      } else if (boot[1] == 0xe8 || boot[1] == 0xe9) {      } else if (boot[1] == 0xe8 || boot[1] == 0xe9) {
3071   offset = (boot[3] << 8) + boot[2] + 2;   offset = (boot[3] << 8) + boot[2] + 2;
3072      } else if (boot[0] == 0xeb) {      } else if (boot[0] == JMP_SHORT_OPCODE) {
3073   offset = boot[1] + 2;        offset = boot[1] + 2;
3074            /*
3075     * it looks like grub, when copying stage1 into the mbr, patches stage1
3076     * right after the JMP location, replacing other instructions such as
3077     * JMPs for NOOPs. So, relax the check a little bit by skipping those
3078     * different bytes.
3079     */
3080          if ((bootSect[offset + 1] == NOOP_OPCODE)
3081      && (bootSect[offset + 2] == NOOP_OPCODE)) {
3082     offset = offset + 3;
3083          }
3084      } else if (boot[0] == 0xe8 || boot[0] == 0xe9) {      } else if (boot[0] == 0xe8 || boot[0] == 0xe9) {
3085   offset = (boot[2] << 8) + boot[1] + 2;   offset = (boot[2] << 8) + boot[1] + 2;
3086      } else {      } else {
# Line 2289  int checkForLilo(struct grubConfig * con Line 3222  int checkForLilo(struct grubConfig * con
3222      return checkDeviceBootloader(line->elements[1].item, boot);      return checkDeviceBootloader(line->elements[1].item, boot);
3223  }  }
3224    
3225    int checkForGrub2(struct grubConfig * config) {
3226        if (!access("/etc/grub.d/", R_OK))
3227     return 2;
3228    
3229        return 1;
3230    }
3231    
3232  int checkForGrub(struct grubConfig * config) {  int checkForGrub(struct grubConfig * config) {
3233      int fd;      int fd;
3234      unsigned char bootSect[512];      unsigned char bootSect[512];
3235      char * boot;      char * boot;
3236        int onSuse = isSuseSystem();
3237    
3238      if (parseSysconfigGrub(NULL, &boot))  
3239   return 0;      if (onSuse) {
3240     if (parseSuseGrubConf(NULL, &boot))
3241        return 0;
3242        } else {
3243     if (parseSysconfigGrub(NULL, &boot))
3244        return 0;
3245        }
3246    
3247      /* assume grub is not installed -- not an error condition */      /* assume grub is not installed -- not an error condition */
3248      if (!boot)      if (!boot)
# Line 2314  int checkForGrub(struct grubConfig * con Line 3261  int checkForGrub(struct grubConfig * con
3261      }      }
3262      close(fd);      close(fd);
3263    
3264        /* The more elaborate checks do not work on SuSE. The checks done
3265         * seem to be reasonble (at least for now), so just return success
3266         */
3267        if (onSuse)
3268     return 2;
3269    
3270      return checkDeviceBootloader(boot, bootSect);      return checkDeviceBootloader(boot, bootSect);
3271  }  }
3272    
# Line 2347  int checkForExtLinux(struct grubConfig * Line 3300  int checkForExtLinux(struct grubConfig *
3300      return checkDeviceBootloader(boot, bootSect);      return checkDeviceBootloader(boot, bootSect);
3301  }  }
3302    
3303    int checkForYaboot(struct grubConfig * config) {
3304        /*
3305         * This is a simplistic check that we consider good enough for own puporses
3306         *
3307         * If we were to properly check if yaboot is *installed* we'd need to:
3308         * 1) get the system boot device (LT_BOOT)
3309         * 2) considering it's a raw filesystem, check if the yaboot binary matches
3310         *    the content on the boot device
3311         * 3) if not, copy the binary to a temporary file and run "addnote" on it
3312         * 4) check again if binary and boot device contents match
3313         */
3314        if (!access("/etc/yaboot.conf", R_OK))
3315     return 2;
3316    
3317        return 1;
3318    }
3319    
3320    int checkForElilo(struct grubConfig * config) {
3321        if (!access("/etc/elilo.conf", R_OK))
3322     return 2;
3323    
3324        return 1;
3325    }
3326    
3327  static char * getRootSpecifier(char * str) {  static char * getRootSpecifier(char * str) {
3328      char * idx, * rootspec = NULL;      char * idx, * rootspec = NULL;
3329    
# Line 2361  static char * getRootSpecifier(char * st Line 3338  static char * getRootSpecifier(char * st
3338  static char * getInitrdVal(struct grubConfig * config,  static char * getInitrdVal(struct grubConfig * config,
3339     const char * prefix, struct singleLine *tmplLine,     const char * prefix, struct singleLine *tmplLine,
3340     const char * newKernelInitrd,     const char * newKernelInitrd,
3341     char ** extraInitrds, int extraInitrdCount)     const char ** extraInitrds, int extraInitrdCount)
3342  {  {
3343      char *initrdVal, *end;      char *initrdVal, *end;
3344      int i;      int i;
# Line 2406  static char * getInitrdVal(struct grubCo Line 3383  static char * getInitrdVal(struct grubCo
3383    
3384  int addNewKernel(struct grubConfig * config, struct singleEntry * template,  int addNewKernel(struct grubConfig * config, struct singleEntry * template,
3385           const char * prefix,           const char * prefix,
3386   char * newKernelPath, char * newKernelTitle,   const char * newKernelPath, const char * newKernelTitle,
3387   char * newKernelArgs, char * newKernelInitrd,   const char * newKernelArgs, const char * newKernelInitrd,
3388   char ** extraInitrds, int extraInitrdCount,   const char ** extraInitrds, int extraInitrdCount,
3389                   char * newMBKernel, char * newMBKernelArgs) {                   const char * newMBKernel, const char * newMBKernelArgs) {
3390      struct singleEntry * new;      struct singleEntry * new;
3391      struct singleLine * newLine = NULL, * tmplLine = NULL, * masterLine = NULL;      struct singleLine * newLine = NULL, * tmplLine = NULL, * masterLine = NULL;
3392      int needs;      int needs;
# Line 2463  int addNewKernel(struct grubConfig * con Line 3440  int addNewKernel(struct grubConfig * con
3440      while (*chptr && isspace(*chptr)) chptr++;      while (*chptr && isspace(*chptr)) chptr++;
3441      if (*chptr == '#') continue;      if (*chptr == '#') continue;
3442    
3443      if (tmplLine->type == LT_KERNEL &&      if (iskernel(tmplLine->type) && tmplLine->numElements >= 2) {
  tmplLine->numElements >= 2) {  
3444   if (!template->multiboot && (needs & NEED_MB)) {   if (!template->multiboot && (needs & NEED_MB)) {
3445      /* it's not a multiboot template and this is the kernel      /* it's not a multiboot template and this is the kernel
3446       * line.  Try to be intelligent about inserting the       * line.  Try to be intelligent about inserting the
# Line 2541  int addNewKernel(struct grubConfig * con Line 3517  int addNewKernel(struct grubConfig * con
3517      /* template is multi but new is not,      /* template is multi but new is not,
3518       * insert the kernel in the first module slot       * insert the kernel in the first module slot
3519       */       */
3520      tmplLine->type = LT_KERNEL;      tmplLine->type = preferredLineType(LT_KERNEL, config->cfi);
3521      free(tmplLine->elements[0].item);      free(tmplLine->elements[0].item);
3522      tmplLine->elements[0].item =      tmplLine->elements[0].item =
3523   strdup(getKeywordByType(LT_KERNEL, config->cfi)->key);   strdup(getKeywordByType(tmplLine->type,
3524     config->cfi)->key);
3525      newLine = addLineTmpl(new, tmplLine, newLine,      newLine = addLineTmpl(new, tmplLine, newLine,
3526    newKernelPath + strlen(prefix), config->cfi);    newKernelPath + strlen(prefix),
3527      config->cfi);
3528      needs &= ~NEED_KERNEL;      needs &= ~NEED_KERNEL;
3529   } else if (needs & NEED_INITRD) {   } else if (needs & NEED_INITRD) {
3530      char *initrdVal;      char *initrdVal;
3531      /* template is multi but new is not,      /* template is multi but new is not,
3532       * insert the initrd in the second module slot       * insert the initrd in the second module slot
3533       */       */
3534      tmplLine->type = LT_INITRD;      tmplLine->type = preferredLineType(LT_INITRD, config->cfi);
3535      free(tmplLine->elements[0].item);      free(tmplLine->elements[0].item);
3536      tmplLine->elements[0].item =      tmplLine->elements[0].item =
3537   strdup(getKeywordByType(LT_INITRD, config->cfi)->key);   strdup(getKeywordByType(tmplLine->type,
3538     config->cfi)->key);
3539      initrdVal = getInitrdVal(config, prefix, tmplLine, newKernelInitrd, extraInitrds, extraInitrdCount);      initrdVal = getInitrdVal(config, prefix, tmplLine, newKernelInitrd, extraInitrds, extraInitrdCount);
3540      newLine = addLineTmpl(new, tmplLine, newLine, initrdVal, config->cfi);      newLine = addLineTmpl(new, tmplLine, newLine, initrdVal, config->cfi);
3541      free(initrdVal);      free(initrdVal);
3542      needs &= ~NEED_INITRD;      needs &= ~NEED_INITRD;
3543   }   }
3544    
3545      } else if (tmplLine->type == LT_INITRD &&      } else if (isinitrd(tmplLine->type) && tmplLine->numElements >= 2) {
        tmplLine->numElements >= 2) {  
3546   if (needs & NEED_INITRD &&   if (needs & NEED_INITRD &&
3547      new->multiboot && !template->multiboot &&      new->multiboot && !template->multiboot &&
3548      config->cfi->mbInitRdIsModule) {      config->cfi->mbInitRdIsModule) {
# Line 2590  int addNewKernel(struct grubConfig * con Line 3568  int addNewKernel(struct grubConfig * con
3568      needs &= ~NEED_INITRD;      needs &= ~NEED_INITRD;
3569   }   }
3570    
3571        } else if (tmplLine->type == LT_MENUENTRY &&
3572           (needs & NEED_TITLE)) {
3573     requote(tmplLine, config->cfi);
3574     char *nkt = malloc(strlen(newKernelTitle)+3);
3575     strcpy(nkt, "'");
3576     strcat(nkt, newKernelTitle);
3577     strcat(nkt, "'");
3578     newLine = addLineTmpl(new, tmplLine, newLine, nkt, config->cfi);
3579     free(nkt);
3580     needs &= ~NEED_TITLE;
3581      } else if (tmplLine->type == LT_TITLE &&      } else if (tmplLine->type == LT_TITLE &&
3582         (needs & NEED_TITLE)) {         (needs & NEED_TITLE)) {
3583   if (tmplLine->numElements >= 2) {   if (tmplLine->numElements >= 2) {
# Line 2603  int addNewKernel(struct grubConfig * con Line 3591  int addNewKernel(struct grubConfig * con
3591        tmplLine->indent, newKernelTitle);        tmplLine->indent, newKernelTitle);
3592      needs &= ~NEED_TITLE;      needs &= ~NEED_TITLE;
3593   }   }
3594        } else if (tmplLine->type == LT_ECHO) {
3595        requote(tmplLine, config->cfi);
3596        static const char *prefix = "'Loading ";
3597        if (tmplLine->numElements > 1 &&
3598        strstr(tmplLine->elements[1].item, prefix) &&
3599        masterLine->next &&
3600        iskernel(masterLine->next->type)) {
3601     char *newTitle = malloc(strlen(prefix) +
3602     strlen(newKernelTitle) + 2);
3603    
3604     strcpy(newTitle, prefix);
3605     strcat(newTitle, newKernelTitle);
3606     strcat(newTitle, "'");
3607     newLine = addLine(new, config->cfi, LT_ECHO,
3608     tmplLine->indent, newTitle);
3609     free(newTitle);
3610        } else {
3611     /* pass through other lines from the template */
3612     newLine = addLineTmpl(new, tmplLine, newLine, NULL,
3613     config->cfi);
3614        }
3615      } else {      } else {
3616   /* pass through other lines from the template */   /* pass through other lines from the template */
3617   newLine = addLineTmpl(new, tmplLine, newLine, NULL, config->cfi);   newLine = addLineTmpl(new, tmplLine, newLine, NULL, config->cfi);
# Line 2614  int addNewKernel(struct grubConfig * con Line 3622  int addNewKernel(struct grubConfig * con
3622   /* don't have a template, so start the entry with the   /* don't have a template, so start the entry with the
3623   * appropriate starting line   * appropriate starting line
3624   */   */
3625   switch (config->cfi->entrySeparator) {   switch (config->cfi->entryStart) {
3626      case LT_KERNEL:      case LT_KERNEL:
3627        case LT_KERNEL_EFI:
3628   if (new->multiboot && config->cfi->mbHyperFirst) {   if (new->multiboot && config->cfi->mbHyperFirst) {
3629      /* fall through to LT_HYPER */      /* fall through to LT_HYPER */
3630   } else {   } else {
3631      newLine = addLine(new, config->cfi, LT_KERNEL,      newLine = addLine(new, config->cfi,
3632              preferredLineType(LT_KERNEL, config->cfi),
3633        config->primaryIndent,        config->primaryIndent,
3634        newKernelPath + strlen(prefix));        newKernelPath + strlen(prefix));
3635      needs &= ~NEED_KERNEL;      needs &= ~NEED_KERNEL;
# Line 2633  int addNewKernel(struct grubConfig * con Line 3643  int addNewKernel(struct grubConfig * con
3643   needs &= ~NEED_MB;   needs &= ~NEED_MB;
3644   break;   break;
3645    
3646        case LT_MENUENTRY: {
3647     char *nkt = malloc(strlen(newKernelTitle)+3);
3648     strcpy(nkt, "'");
3649     strcat(nkt, newKernelTitle);
3650     strcat(nkt, "'");
3651            newLine = addLine(new, config->cfi, LT_MENUENTRY,
3652      config->primaryIndent, nkt);
3653     free(nkt);
3654     needs &= ~NEED_TITLE;
3655     needs |= NEED_END;
3656     break;
3657        }
3658      case LT_TITLE:      case LT_TITLE:
3659   if( useextlinuxmenu != 0 ){ // We just need useextlinuxmenu to not be zero (set above)   if( useextlinuxmenu != 0 ){ // We just need useextlinuxmenu to not be zero (set above)
3660   char * templabel;   char * templabel;
# Line 2666  int addNewKernel(struct grubConfig * con Line 3688  int addNewKernel(struct grubConfig * con
3688    
3689      /* add the remainder of the lines, i.e. those that either      /* add the remainder of the lines, i.e. those that either
3690       * weren't present in the template, or in the case of no template,       * weren't present in the template, or in the case of no template,
3691       * all the lines following the entrySeparator.       * all the lines following the entryStart.
3692       */       */
3693      if (needs & NEED_TITLE) {      if (needs & NEED_TITLE) {
3694   newLine = addLine(new, config->cfi, LT_TITLE,   newLine = addLine(new, config->cfi, LT_TITLE,
# Line 2683  int addNewKernel(struct grubConfig * con Line 3705  int addNewKernel(struct grubConfig * con
3705      if (needs & NEED_KERNEL) {      if (needs & NEED_KERNEL) {
3706   newLine = addLine(new, config->cfi,   newLine = addLine(new, config->cfi,
3707    (new->multiboot && getKeywordByType(LT_MBMODULE,    (new->multiboot && getKeywordByType(LT_MBMODULE,
3708        config->cfi)) ?        config->cfi))
3709    LT_MBMODULE : LT_KERNEL,     ? LT_MBMODULE
3710     : preferredLineType(LT_KERNEL, config->cfi),
3711    config->secondaryIndent,    config->secondaryIndent,
3712    newKernelPath + strlen(prefix));    newKernelPath + strlen(prefix));
3713   needs &= ~NEED_KERNEL;   needs &= ~NEED_KERNEL;
# Line 2700  int addNewKernel(struct grubConfig * con Line 3723  int addNewKernel(struct grubConfig * con
3723   initrdVal = getInitrdVal(config, prefix, NULL, newKernelInitrd, extraInitrds, extraInitrdCount);   initrdVal = getInitrdVal(config, prefix, NULL, newKernelInitrd, extraInitrds, extraInitrdCount);
3724   newLine = addLine(new, config->cfi,   newLine = addLine(new, config->cfi,
3725    (new->multiboot && getKeywordByType(LT_MBMODULE,    (new->multiboot && getKeywordByType(LT_MBMODULE,
3726        config->cfi)) ?        config->cfi))
3727    LT_MBMODULE : LT_INITRD,     ? LT_MBMODULE
3728       : preferredLineType(LT_INITRD, config->cfi),
3729    config->secondaryIndent,    config->secondaryIndent,
3730    initrdVal);    initrdVal);
3731   free(initrdVal);   free(initrdVal);
3732   needs &= ~NEED_INITRD;   needs &= ~NEED_INITRD;
3733      }      }
3734        if (needs & NEED_END) {
3735     newLine = addLine(new, config->cfi, LT_ENTRY_END,
3736     config->secondaryIndent, NULL);
3737     needs &= ~NEED_END;
3738        }
3739    
3740      if (needs) {      if (needs) {
3741   printf(_("grubby: needs=%d, aborting\n"), needs);   printf(_("grubby: needs=%d, aborting\n"), needs);
# Line 2736  static void traceback(int signum) Line 3765  static void traceback(int signum)
3765    
3766  int main(int argc, const char ** argv) {  int main(int argc, const char ** argv) {
3767      poptContext optCon;      poptContext optCon;
3768      char * grubConfig = NULL;      const char * grubConfig = NULL;
3769      char * outputFile = NULL;      char * outputFile = NULL;
3770      int arg = 0;      int arg = 0;
3771      int flags = 0;      int flags = 0;
3772      int badImageOkay = 0;      int badImageOkay = 0;
3773        int configureGrub2 = 0;
3774      int configureLilo = 0, configureELilo = 0, configureGrub = 0;      int configureLilo = 0, configureELilo = 0, configureGrub = 0;
3775      int configureYaboot = 0, configureSilo = 0, configureZipl = 0;      int configureYaboot = 0, configureSilo = 0, configureZipl = 0;
3776      int configureExtLinux = 0;      int configureExtLinux = 0;
# Line 2768  int main(int argc, const char ** argv) { Line 3798  int main(int argc, const char ** argv) {
3798      struct singleEntry * template = NULL;      struct singleEntry * template = NULL;
3799      int copyDefault = 0, makeDefault = 0;      int copyDefault = 0, makeDefault = 0;
3800      int displayDefault = 0;      int displayDefault = 0;
3801        int displayDefaultIndex = 0;
3802        int displayDefaultTitle = 0;
3803        int defaultIndex = -1;
3804      struct poptOption options[] = {      struct poptOption options[] = {
3805   { "add-kernel", 0, POPT_ARG_STRING, &newKernelPath, 0,   { "add-kernel", 0, POPT_ARG_STRING, &newKernelPath, 0,
3806      _("add an entry for the specified kernel"), _("kernel-path") },      _("add an entry for the specified kernel"), _("kernel-path") },
# Line 2785  int main(int argc, const char ** argv) { Line 3818  int main(int argc, const char ** argv) {
3818   { "boot-filesystem", 0, POPT_ARG_STRING, &bootPrefix, 0,   { "boot-filesystem", 0, POPT_ARG_STRING, &bootPrefix, 0,
3819      _("filestystem which contains /boot directory (for testing only)"),      _("filestystem which contains /boot directory (for testing only)"),
3820      _("bootfs") },      _("bootfs") },
3821  #if defined(__i386__) || defined(__x86_64__)  #if defined(__i386__) || defined(__x86_64__) || defined (__powerpc64__) || defined (__ia64__)
3822   { "bootloader-probe", 0, POPT_ARG_NONE, &bootloaderProbe, 0,   { "bootloader-probe", 0, POPT_ARG_NONE, &bootloaderProbe, 0,
3823      _("check if lilo is installed on lilo.conf boot sector") },      _("check which bootloader is installed on boot sector") },
3824  #endif  #endif
3825   { "config-file", 'c', POPT_ARG_STRING, &grubConfig, 0,   { "config-file", 'c', POPT_ARG_STRING, &grubConfig, 0,
3826      _("path to grub config file to update (\"-\" for stdin)"),      _("path to grub config file to update (\"-\" for stdin)"),
# Line 2798  int main(int argc, const char ** argv) { Line 3831  int main(int argc, const char ** argv) {
3831        "the kernel referenced by the default image does not exist, "        "the kernel referenced by the default image does not exist, "
3832        "the first linux entry whose kernel does exist is used as the "        "the first linux entry whose kernel does exist is used as the "
3833        "template"), NULL },        "template"), NULL },
3834     { "debug", 0, 0, &debug, 0,
3835        _("print debugging information for failures") },
3836   { "default-kernel", 0, 0, &displayDefault, 0,   { "default-kernel", 0, 0, &displayDefault, 0,
3837      _("display the path of the default kernel") },      _("display the path of the default kernel") },
3838     { "default-index", 0, 0, &displayDefaultIndex, 0,
3839        _("display the index of the default kernel") },
3840     { "default-title", 0, 0, &displayDefaultTitle, 0,
3841        _("display the title of the default kernel") },
3842   { "elilo", 0, POPT_ARG_NONE, &configureELilo, 0,   { "elilo", 0, POPT_ARG_NONE, &configureELilo, 0,
3843      _("configure elilo bootloader") },      _("configure elilo bootloader") },
3844     { "efi", 0, POPT_ARG_NONE, &isEfi, 0,
3845        _("force grub2 stanzas to use efi") },
3846   { "extlinux", 0, POPT_ARG_NONE, &configureExtLinux, 0,   { "extlinux", 0, POPT_ARG_NONE, &configureExtLinux, 0,
3847      _("configure extlinux bootloader (from syslinux)") },      _("configure extlinux bootloader (from syslinux)") },
3848   { "grub", 0, POPT_ARG_NONE, &configureGrub, 0,   { "grub", 0, POPT_ARG_NONE, &configureGrub, 0,
3849      _("configure grub bootloader") },      _("configure grub bootloader") },
3850     { "grub2", 0, POPT_ARG_NONE, &configureGrub2, 0,
3851        _("configure grub2 bootloader") },
3852   { "info", 0, POPT_ARG_STRING, &kernelInfo, 0,   { "info", 0, POPT_ARG_STRING, &kernelInfo, 0,
3853      _("display boot information for specified kernel"),      _("display boot information for specified kernel"),
3854      _("kernel-path") },      _("kernel-path") },
# Line 2832  int main(int argc, const char ** argv) { Line 3875  int main(int argc, const char ** argv) {
3875   { "set-default", 0, POPT_ARG_STRING, &defaultKernel, 0,   { "set-default", 0, POPT_ARG_STRING, &defaultKernel, 0,
3876      _("make the first entry referencing the specified kernel "      _("make the first entry referencing the specified kernel "
3877        "the default"), _("kernel-path") },        "the default"), _("kernel-path") },
3878     { "set-default-index", 0, POPT_ARG_INT, &defaultIndex, 0,
3879        _("make the given entry index the default entry"),
3880        _("entry-index") },
3881   { "silo", 0, POPT_ARG_NONE, &configureSilo, 0,   { "silo", 0, POPT_ARG_NONE, &configureSilo, 0,
3882      _("configure silo bootloader") },      _("configure silo bootloader") },
3883   { "title", 0, POPT_ARG_STRING, &newKernelTitle, 0,   { "title", 0, POPT_ARG_STRING, &newKernelTitle, 0,
# Line 2885  int main(int argc, const char ** argv) { Line 3931  int main(int argc, const char ** argv) {
3931   return 1;   return 1;
3932      }      }
3933    
3934      if ((configureLilo + configureGrub + configureELilo +      if ((configureLilo + configureGrub2 + configureGrub + configureELilo +
3935   configureYaboot + configureSilo + configureZipl +   configureYaboot + configureSilo + configureZipl +
3936   configureExtLinux ) > 1) {   configureExtLinux ) > 1) {
3937   fprintf(stderr, _("grubby: cannot specify multiple bootloaders\n"));   fprintf(stderr, _("grubby: cannot specify multiple bootloaders\n"));
# Line 2894  int main(int argc, const char ** argv) { Line 3940  int main(int argc, const char ** argv) {
3940   fprintf(stderr,   fprintf(stderr,
3941      _("grubby: cannot specify config file with --bootloader-probe\n"));      _("grubby: cannot specify config file with --bootloader-probe\n"));
3942   return 1;   return 1;
3943        } else if (configureGrub2) {
3944     cfi = &grub2ConfigType;
3945      } else if (configureLilo) {      } else if (configureLilo) {
3946   cfi = &liloConfigType;   cfi = &liloConfigType;
3947      } else if (configureGrub) {      } else if (configureGrub) {
# Line 2912  int main(int argc, const char ** argv) { Line 3960  int main(int argc, const char ** argv) {
3960      }      }
3961    
3962      if (!cfi) {      if (!cfi) {
3963            if (grub2FindConfig(&grub2ConfigType))
3964        cfi = &grub2ConfigType;
3965     else
3966        #ifdef __ia64__        #ifdef __ia64__
3967   cfi = &eliloConfigType;      cfi = &eliloConfigType;
3968        #elif __powerpc__        #elif __powerpc__
3969   cfi = &yabootConfigType;      cfi = &yabootConfigType;
3970        #elif __sparc__        #elif __sparc__
3971          cfi = &siloConfigType;              cfi = &siloConfigType;
3972        #elif __s390__        #elif __s390__
3973          cfi = &ziplConfigType;              cfi = &ziplConfigType;
3974        #elif __s390x__        #elif __s390x__
3975          cfi = &ziplConfigtype;              cfi = &ziplConfigtype;
3976        #else        #else
3977   cfi = &grubConfigType;      cfi = &grubConfigType;
3978        #endif        #endif
3979      }      }
3980    
3981      if (!grubConfig)      if (!grubConfig) {
3982   grubConfig = cfi->defaultConfig;   if (cfi->findConfig)
3983        grubConfig = cfi->findConfig(cfi);
3984     if (!grubConfig)
3985        grubConfig = cfi->defaultConfig;
3986        }
3987    
3988      if (bootloaderProbe && (displayDefault || kernelInfo || newKernelVersion ||      if (bootloaderProbe && (displayDefault || kernelInfo || newKernelVersion ||
3989    newKernelPath || removeKernelPath || makeDefault ||      newKernelPath || removeKernelPath || makeDefault ||
3990    defaultKernel)) {      defaultKernel || displayDefaultIndex || displayDefaultTitle ||
3991        (defaultIndex >= 0))) {
3992   fprintf(stderr, _("grubby: --bootloader-probe may not be used with "   fprintf(stderr, _("grubby: --bootloader-probe may not be used with "
3993    "specified option"));    "specified option"));
3994   return 1;   return 1;
# Line 2948  int main(int argc, const char ** argv) { Line 4004  int main(int argc, const char ** argv) {
4004      if (newKernelPath && !newKernelTitle) {      if (newKernelPath && !newKernelTitle) {
4005   fprintf(stderr, _("grubby: kernel title must be specified\n"));   fprintf(stderr, _("grubby: kernel title must be specified\n"));
4006   return 1;   return 1;
4007      } else if (!newKernelPath && (newKernelTitle  || newKernelInitrd ||      } else if (!newKernelPath && (newKernelTitle  || copyDefault ||
4008    newKernelInitrd || copyDefault     ||    (newKernelInitrd && !updateKernelPath)||
4009    makeDefault || extraInitrdCount > 0)) {    makeDefault || extraInitrdCount > 0)) {
4010   fprintf(stderr, _("grubby: kernel path expected\n"));   fprintf(stderr, _("grubby: kernel path expected\n"));
4011   return 1;   return 1;
# Line 2974  int main(int argc, const char ** argv) { Line 4030  int main(int argc, const char ** argv) {
4030   makeDefault = 1;   makeDefault = 1;
4031   defaultKernel = NULL;   defaultKernel = NULL;
4032      }      }
4033        else if (defaultKernel && (defaultIndex >= 0)) {
4034     fprintf(stderr, _("grubby: --set-default and --set-default-index "
4035      "may not be used together\n"));
4036     return 1;
4037        }
4038    
4039      if (!strcmp(grubConfig, "-") && !outputFile) {      if (grubConfig && !strcmp(grubConfig, "-") && !outputFile) {
4040   fprintf(stderr, _("grubby: output file must be specified if stdin "   fprintf(stderr, _("grubby: output file must be specified if stdin "
4041   "is used\n"));   "is used\n"));
4042   return 1;   return 1;
4043      }      }
4044    
4045      if (!removeKernelPath && !newKernelPath && !displayDefault && !defaultKernel      if (!removeKernelPath && !newKernelPath && !displayDefault && !defaultKernel
4046   && !kernelInfo && !bootloaderProbe && !updateKernelPath   && !kernelInfo && !bootloaderProbe && !updateKernelPath
4047          && !removeMBKernel) {   && !removeMBKernel && !displayDefaultIndex && !displayDefaultTitle
4048     && (defaultIndex == -1)) {
4049   fprintf(stderr, _("grubby: no action specified\n"));   fprintf(stderr, _("grubby: no action specified\n"));
4050   return 1;   return 1;
4051      }      }
# Line 3010  int main(int argc, const char ** argv) { Line 4072  int main(int argc, const char ** argv) {
4072      }      }
4073    
4074      if (bootloaderProbe) {      if (bootloaderProbe) {
4075   int lrc = 0, grc = 0, erc = 0;   int lrc = 0, grc = 0, gr2c = 0, extrc = 0, yrc = 0, erc = 0;
4076   struct grubConfig * lconfig, * gconfig;   struct grubConfig * lconfig, * gconfig, * yconfig, * econfig;
4077    
4078     const char *grub2config = grub2FindConfig(&grub2ConfigType);
4079     if (grub2config) {
4080        gconfig = readConfig(grub2config, &grub2ConfigType);
4081        if (!gconfig)
4082     gr2c = 1;
4083        else
4084     gr2c = checkForGrub2(gconfig);
4085     }
4086    
4087   if (!access(grubConfigType.defaultConfig, F_OK)) {   const char *grubconfig = grubFindConfig(&grubConfigType);
4088      gconfig = readConfig(grubConfigType.defaultConfig, &grubConfigType);   if (!access(grubconfig, F_OK)) {
4089        gconfig = readConfig(grubconfig, &grubConfigType);
4090      if (!gconfig)      if (!gconfig)
4091   grc = 1;   grc = 1;
4092      else      else
# Line 3029  int main(int argc, const char ** argv) { Line 4101  int main(int argc, const char ** argv) {
4101   lrc = checkForLilo(lconfig);   lrc = checkForLilo(lconfig);
4102   }   }
4103    
4104     if (!access(eliloConfigType.defaultConfig, F_OK)) {
4105        econfig = readConfig(eliloConfigType.defaultConfig,
4106     &eliloConfigType);
4107        if (!econfig)
4108     erc = 1;
4109        else
4110     erc = checkForElilo(econfig);
4111     }
4112    
4113   if (!access(extlinuxConfigType.defaultConfig, F_OK)) {   if (!access(extlinuxConfigType.defaultConfig, F_OK)) {
4114      lconfig = readConfig(extlinuxConfigType.defaultConfig, &extlinuxConfigType);      lconfig = readConfig(extlinuxConfigType.defaultConfig, &extlinuxConfigType);
4115      if (!lconfig)      if (!lconfig)
4116   erc = 1;   extrc = 1;
4117      else      else
4118   erc = checkForExtLinux(lconfig);   extrc = checkForExtLinux(lconfig);
4119   }   }
4120    
4121   if (lrc == 1 || grc == 1) return 1;  
4122     if (!access(yabootConfigType.defaultConfig, F_OK)) {
4123        yconfig = readConfig(yabootConfigType.defaultConfig,
4124     &yabootConfigType);
4125        if (!yconfig)
4126     yrc = 1;
4127        else
4128     yrc = checkForYaboot(yconfig);
4129     }
4130    
4131     if (lrc == 1 || grc == 1 || gr2c == 1 || extrc == 1 || yrc == 1 ||
4132     erc == 1)
4133        return 1;
4134    
4135   if (lrc == 2) printf("lilo\n");   if (lrc == 2) printf("lilo\n");
4136     if (gr2c == 2) printf("grub2\n");
4137   if (grc == 2) printf("grub\n");   if (grc == 2) printf("grub\n");
4138   if (erc == 2) printf("extlinux\n");   if (extrc == 2) printf("extlinux\n");
4139     if (yrc == 2) printf("yaboot\n");
4140     if (erc == 2) printf("elilo\n");
4141    
4142   return 0;   return 0;
4143      }      }
# Line 3059  int main(int argc, const char ** argv) { Line 4155  int main(int argc, const char ** argv) {
4155   if (!entry) return 0;   if (!entry) return 0;
4156   if (!suitableImage(entry, bootPrefix, 0, flags)) return 0;   if (!suitableImage(entry, bootPrefix, 0, flags)) return 0;
4157    
4158   line = getLineByType(LT_KERNEL|LT_HYPER, entry->lines);   line = getLineByType(LT_KERNEL|LT_HYPER|LT_KERNEL_EFI, entry->lines);
4159   if (!line) return 0;   if (!line) return 0;
4160    
4161          rootspec = getRootSpecifier(line->elements[1].item);          rootspec = getRootSpecifier(line->elements[1].item);
# Line 3067  int main(int argc, const char ** argv) { Line 4163  int main(int argc, const char ** argv) {
4163                 ((rootspec != NULL) ? strlen(rootspec) : 0));                 ((rootspec != NULL) ? strlen(rootspec) : 0));
4164    
4165   return 0;   return 0;
4166    
4167        } else if (displayDefaultTitle) {
4168     struct singleLine * line;
4169     struct singleEntry * entry;
4170    
4171     if (config->defaultImage == -1) return 0;
4172     entry = findEntryByIndex(config, config->defaultImage);
4173     if (!entry) return 0;
4174    
4175     if (!configureGrub2) {
4176      line = getLineByType(LT_TITLE, entry->lines);
4177      if (!line) return 0;
4178      printf("%s\n", line->elements[1].item);
4179    
4180     } else {
4181      char * title;
4182    
4183      dbgPrintf("This is GRUB2, default title is embeded in menuentry\n");
4184      line = getLineByType(LT_MENUENTRY, entry->lines);
4185      if (!line) return 0;
4186      title = grub2ExtractTitle(line);
4187      if (title)
4188        printf("%s\n", title);
4189     }
4190     return 0;
4191    
4192        } else if (displayDefaultIndex) {
4193            if (config->defaultImage == -1) return 0;
4194            printf("%i\n", config->defaultImage);
4195    
4196      } else if (kernelInfo)      } else if (kernelInfo)
4197   return displayInfo(config, kernelInfo, bootPrefix);   return displayInfo(config, kernelInfo, bootPrefix);
4198    
# Line 3078  int main(int argc, const char ** argv) { Line 4204  int main(int argc, const char ** argv) {
4204      markRemovedImage(config, removeKernelPath, bootPrefix);      markRemovedImage(config, removeKernelPath, bootPrefix);
4205      markRemovedImage(config, removeMBKernel, bootPrefix);      markRemovedImage(config, removeMBKernel, bootPrefix);
4206      setDefaultImage(config, newKernelPath != NULL, defaultKernel, makeDefault,      setDefaultImage(config, newKernelPath != NULL, defaultKernel, makeDefault,
4207      bootPrefix, flags);      bootPrefix, flags, defaultIndex);
4208      setFallbackImage(config, newKernelPath != NULL);      setFallbackImage(config, newKernelPath != NULL);
4209      if (updateImage(config, updateKernelPath, bootPrefix, newKernelArgs,      if (updateImage(config, updateKernelPath, bootPrefix, newKernelArgs,
4210                      removeArgs, newMBKernelArgs, removeMBKernelArgs)) return 1;                      removeArgs, newMBKernelArgs, removeMBKernelArgs)) return 1;
4211        if (updateKernelPath && newKernelInitrd) {
4212                if (updateInitrd(config, updateKernelPath, bootPrefix,
4213                                 newKernelInitrd)) return 1;
4214        }
4215      if (addNewKernel(config, template, bootPrefix, newKernelPath,      if (addNewKernel(config, template, bootPrefix, newKernelPath,
4216                       newKernelTitle, newKernelArgs, newKernelInitrd,                       newKernelTitle, newKernelArgs, newKernelInitrd,
4217                       extraInitrds, extraInitrdCount,                       (const char **)extraInitrds, extraInitrdCount,
4218                       newMBKernel, newMBKernelArgs)) return 1;                       newMBKernel, newMBKernelArgs)) return 1;
4219            
4220    
# Line 3095  int main(int argc, const char ** argv) { Line 4225  int main(int argc, const char ** argv) {
4225      }      }
4226    
4227      if (!outputFile)      if (!outputFile)
4228   outputFile = grubConfig;   outputFile = (char *)grubConfig;
4229    
4230      return writeConfig(config, outputFile, bootPrefix);      return writeConfig(config, outputFile, bootPrefix);
4231  }  }

Legend:
Removed from v.926  
changed lines
  Added in v.2056