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 920 by niro, Wed Oct 28 09:50:42 2009 UTC trunk/grubby/grubby.c revision 1746 by niro, Sat Feb 18 01:06:20 2012 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  /* comments get lumped in with indention */  /* comments get lumped in with indention */
60  struct lineElement {  struct lineElement {
61      char * item;      char * item;
# Line 56  struct lineElement { Line 63  struct lineElement {
63  };  };
64    
65  enum lineType_e {  enum lineType_e {
66      LT_WHITESPACE = 1 << 0,      LT_WHITESPACE   = 1 << 0,
67      LT_TITLE      = 1 << 1,      LT_TITLE        = 1 << 1,
68      LT_KERNEL     = 1 << 2,      LT_KERNEL       = 1 << 2,
69      LT_INITRD     = 1 << 3,      LT_INITRD       = 1 << 3,
70      LT_HYPER      = 1 << 4,      LT_HYPER        = 1 << 4,
71      LT_DEFAULT    = 1 << 5,      LT_DEFAULT      = 1 << 5,
72      LT_MBMODULE   = 1 << 6,      LT_MBMODULE     = 1 << 6,
73      LT_ROOT       = 1 << 7,      LT_ROOT         = 1 << 7,
74      LT_FALLBACK   = 1 << 8,      LT_FALLBACK     = 1 << 8,
75      LT_KERNELARGS = 1 << 9,      LT_KERNELARGS   = 1 << 9,
76      LT_BOOT       = 1 << 10,      LT_BOOT         = 1 << 10,
77      LT_BOOTROOT   = 1 << 11,      LT_BOOTROOT     = 1 << 11,
78      LT_LBA        = 1 << 12,      LT_LBA          = 1 << 12,
79      LT_OTHER      = 1 << 13,      LT_OTHER        = 1 << 13,
80      LT_GENERIC    = 1 << 14,      LT_GENERIC      = 1 << 14,
81      LT_UNKNOWN    = 1 << 15,      LT_ECHO    = 1 << 16,
82        LT_MENUENTRY    = 1 << 17,
83        LT_ENTRY_END    = 1 << 18,
84        LT_SET_VARIABLE = 1 << 19,
85        LT_UNKNOWN      = 1 << 20,
86  };  };
87    
88  struct singleLine {  struct singleLine {
# Line 99  struct singleEntry { Line 110  struct singleEntry {
110  #define NEED_TITLE   (1 << 2)  #define NEED_TITLE   (1 << 2)
111  #define NEED_ARGS    (1 << 3)  #define NEED_ARGS    (1 << 3)
112  #define NEED_MB      (1 << 4)  #define NEED_MB      (1 << 4)
113    #define NEED_END     (1 << 5)
114    
115  #define MAIN_DEFAULT    (1 << 0)  #define MAIN_DEFAULT    (1 << 0)
116  #define DEFAULT_SAVED       -2  #define DEFAULT_SAVED       -2
# Line 110  struct keywordTypes { Line 122  struct keywordTypes {
122      char separatorChar;      char separatorChar;
123  };  };
124    
125    struct configFileInfo;
126    
127    typedef const char *(*findConfigFunc)(struct configFileInfo *);
128    typedef const int (*writeLineFunc)(struct configFileInfo *,
129     struct singleLine *line);
130    
131  struct configFileInfo {  struct configFileInfo {
132      char * defaultConfig;      char * defaultConfig;
133        findConfigFunc findConfig;
134        writeLineFunc writeLine;
135      struct keywordTypes * keywords;      struct keywordTypes * keywords;
136      int defaultIsIndex;      int defaultIsIndex;
137        int defaultIsVariable;
138      int defaultSupportSaved;      int defaultSupportSaved;
139      enum lineType_e entrySeparator;      enum lineType_e entryStart;
140        enum lineType_e entryEnd;
141      int needsBootPrefix;      int needsBootPrefix;
142      int argsInQuotes;      int argsInQuotes;
143      int maxTitleLength;      int maxTitleLength;
144      int titleBracketed;      int titleBracketed;
145        int titlePosition;
146      int mbHyperFirst;      int mbHyperFirst;
147      int mbInitRdIsModule;      int mbInitRdIsModule;
148      int mbConcatArgs;      int mbConcatArgs;
# Line 138  struct keywordTypes grubKeywords[] = { Line 161  struct keywordTypes grubKeywords[] = {
161      { NULL,    0, 0 },      { NULL,    0, 0 },
162  };  };
163    
164    const char *grubFindConfig(struct configFileInfo *cfi) {
165        static const char *configFiles[] = {
166     "/etc/grub.conf",
167     "/boot/grub/grub.conf",
168     "/boot/grub/menu.lst",
169     NULL
170        };
171        static int i = -1;
172    
173        if (i == -1) {
174     for (i = 0; configFiles[i] != NULL; i++) {
175        dbgPrintf("Checking \"%s\": ", configFiles[i]);
176        if (!access(configFiles[i], R_OK)) {
177     dbgPrintf("found\n");
178     return configFiles[i];
179        }
180        dbgPrintf("not found\n");
181     }
182        }
183        return configFiles[i];
184    }
185    
186  struct configFileInfo grubConfigType = {  struct configFileInfo grubConfigType = {
187      "/boot/grub/grub.conf",    /* defaultConfig */      .findConfig = grubFindConfig,
188      grubKeywords,    /* keywords */      .keywords = grubKeywords,
189      1,    /* defaultIsIndex */      .defaultIsIndex = 1,
190      1,    /* defaultSupportSaved */      .defaultSupportSaved = 1,
191      LT_TITLE,    /* entrySeparator */      .entryStart = LT_TITLE,
192      1,    /* needsBootPrefix */      .needsBootPrefix = 1,
193      0,    /* argsInQuotes */      .mbHyperFirst = 1,
194      0,    /* maxTitleLength */      .mbInitRdIsModule = 1,
195      0,                                      /* titleBracketed */      .mbAllowExtraInitRds = 1,
196      1,                                      /* mbHyperFirst */  };
197      1,                                      /* mbInitRdIsModule */  
198      0,                                      /* mbConcatArgs */  struct keywordTypes grub2Keywords[] = {
199      1,                                      /* mbAllowExtraInitRds */      { "menuentry",  LT_MENUENTRY,   ' ' },
200        { "}",          LT_ENTRY_END,   ' ' },
201        { "echo",       LT_ECHO,        ' ' },
202        { "set",        LT_SET_VARIABLE,' ', '=' },
203        { "root",       LT_BOOTROOT,    ' ' },
204        { "default",    LT_DEFAULT,     ' ' },
205        { "fallback",   LT_FALLBACK,    ' ' },
206        { "linux",      LT_KERNEL,      ' ' },
207        { "initrd",     LT_INITRD,      ' ', ' ' },
208        { "module",     LT_MBMODULE,    ' ' },
209        { "kernel",     LT_HYPER,       ' ' },
210        { NULL, 0, 0 },
211    };
212    
213    const char *grub2FindConfig(struct configFileInfo *cfi) {
214        static const char *configFiles[] = {
215     "/boot/grub/grub-efi.cfg",
216     "/boot/grub/grub.cfg",
217     NULL
218        };
219        static int i = -1;
220        static const char *grub_cfg = "/boot/grub/grub.cfg";
221    
222        if (i == -1) {
223     for (i = 0; configFiles[i] != NULL; i++) {
224        dbgPrintf("Checking \"%s\": ", configFiles[i]);
225        if (!access(configFiles[i], R_OK)) {
226     dbgPrintf("found\n");
227     return configFiles[i];
228        }
229     }
230        }
231    
232        /* Ubuntu renames grub2 to grub, so check for the grub.d directory
233         * that isn't in grub1, and if it exists, return the config file path
234         * that they use. */
235        if (configFiles[i] == NULL && !access("/etc/grub.d/", R_OK)) {
236     dbgPrintf("found\n");
237     return grub_cfg;
238        }
239    
240        dbgPrintf("not found\n");
241        return configFiles[i];
242    }
243    
244    int sizeOfSingleLine(struct singleLine * line) {
245      int i;
246      int count = 0;
247    
248      for (i = 0; i < line->numElements; i++) {
249        int indentSize = 0;
250    
251        count = count + strlen(line->elements[i].item);
252    
253        indentSize = strlen(line->elements[i].indent);
254        if (indentSize > 0)
255          count = count + indentSize;
256        else
257          /* be extra safe and add room for whitespaces */
258          count = count + 1;
259      }
260    
261      /* room for trailing terminator */
262      count = count + 1;
263    
264      return count;
265    }
266    
267    char *grub2ExtractTitle(struct singleLine * line) {
268        char * current;
269        char * current_indent;
270        int current_len;
271        int current_indent_len;
272        int i;
273    
274        /* bail out if line does not start with menuentry */
275        if (strcmp(line->elements[0].item, "menuentry"))
276          return NULL;
277    
278        i = 1;
279        current = line->elements[i].item;
280        current_len = strlen(current);
281    
282        /* if second word is quoted, strip the quotes and return single word */
283        if ((*current == '\'') && (*(current + current_len - 1) == '\'')) {
284          char *tmp;
285    
286          tmp = strdup(current);
287          *(tmp + current_len - 1) = '\0';
288          return ++tmp;
289        }
290    
291        /* if no quotes, return second word verbatim */
292        if (*current != '\'') {
293          return current;
294        }
295    
296        /* second element start with a quote, so we have to find the element
297         * whose last character is also quote (assuming it's the closing one) */
298        if (*current == '\'') {
299          int resultMaxSize;
300          char * result;
301    
302          resultMaxSize = sizeOfSingleLine(line);
303          result = malloc(resultMaxSize);
304          snprintf(result, resultMaxSize, "%s", ++current);
305    
306          i++;
307          for (; i < line->numElements; ++i) {
308     current = line->elements[i].item;
309     current_len = strlen(current);
310     current_indent = line->elements[i].indent;
311     current_indent_len = strlen(current_indent);
312    
313     strncat(result, current_indent, current_indent_len);
314     if (*(current + current_len - 1) != '\'') {
315      strncat(result, current, current_len);
316     } else {
317      strncat(result, current, current_len - 1);
318      break;
319     }
320          }
321          return result;
322        }
323    
324        return NULL;
325    }
326    
327    struct configFileInfo grub2ConfigType = {
328        .findConfig = grub2FindConfig,
329        .keywords = grub2Keywords,
330        .defaultIsIndex = 1,
331        .defaultSupportSaved = 0,
332        .defaultIsVariable = 1,
333        .entryStart = LT_MENUENTRY,
334        .entryEnd = LT_ENTRY_END,
335        .titlePosition = 1,
336        .needsBootPrefix = 1,
337        .mbHyperFirst = 1,
338        .mbInitRdIsModule = 1,
339        .mbAllowExtraInitRds = 1,
340  };  };
341    
342  struct keywordTypes yabootKeywords[] = {  struct keywordTypes yabootKeywords[] = {
# Line 249  struct keywordTypes extlinuxKeywords[] = Line 434  struct keywordTypes extlinuxKeywords[] =
434  };  };
435  int useextlinuxmenu;  int useextlinuxmenu;
436  struct configFileInfo eliloConfigType = {  struct configFileInfo eliloConfigType = {
437      "/boot/efi/EFI/redhat/elilo.conf",    /* defaultConfig */      .defaultConfig = "/boot/efi/EFI/redhat/elilo.conf",
438      eliloKeywords,    /* keywords */      .keywords = eliloKeywords,
439      0,    /* defaultIsIndex */      .entryStart = LT_KERNEL,
440      0,    /* defaultSupportSaved */      .needsBootPrefix = 1,
441      LT_KERNEL,    /* entrySeparator */      .argsInQuotes = 1,
442      1,                    /* needsBootPrefix */      .mbConcatArgs = 1,
     1,    /* argsInQuotes */  
     0,    /* maxTitleLength */  
     0,                                      /* titleBracketed */  
     0,                                      /* mbHyperFirst */  
     0,                                      /* mbInitRdIsModule */  
     1,                                      /* mbConcatArgs */  
     0,                                      /* mbAllowExtraInitRds */  
443  };  };
444    
445  struct configFileInfo liloConfigType = {  struct configFileInfo liloConfigType = {
446      "/etc/lilo.conf",    /* defaultConfig */      .defaultConfig = "/etc/lilo.conf",
447      liloKeywords,    /* keywords */      .keywords = liloKeywords,
448      0,    /* defaultIsIndex */      .entryStart = LT_KERNEL,
449      0,    /* defaultSupportSaved */      .argsInQuotes = 1,
450      LT_KERNEL,    /* entrySeparator */      .maxTitleLength = 15,
     0,    /* needsBootPrefix */  
     1,    /* argsInQuotes */  
     15,    /* maxTitleLength */  
     0,                                      /* titleBracketed */  
     0,                                      /* mbHyperFirst */  
     0,                                      /* mbInitRdIsModule */  
     0,                                      /* mbConcatArgs */  
     0,                                      /* mbAllowExtraInitRds */  
451  };  };
452    
453  struct configFileInfo yabootConfigType = {  struct configFileInfo yabootConfigType = {
454      "/etc/yaboot.conf",    /* defaultConfig */      .defaultConfig = "/etc/yaboot.conf",
455      yabootKeywords,    /* keywords */      .keywords = yabootKeywords,
456      0,    /* defaultIsIndex */      .entryStart = LT_KERNEL,
457      0,    /* defaultSupportSaved */      .needsBootPrefix = 1,
458      LT_KERNEL,    /* entrySeparator */      .argsInQuotes = 1,
459      1,    /* needsBootPrefix */      .maxTitleLength = 15,
460      1,    /* argsInQuotes */      .mbAllowExtraInitRds = 1,
     15,    /* maxTitleLength */  
     0,                                      /* titleBracketed */  
     0,                                      /* mbHyperFirst */  
     0,                                      /* mbInitRdIsModule */  
     0,                                      /* mbConcatArgs */  
     1,                                      /* mbAllowExtraInitRds */  
461  };  };
462    
463  struct configFileInfo siloConfigType = {  struct configFileInfo siloConfigType = {
464      "/etc/silo.conf",    /* defaultConfig */      .defaultConfig = "/etc/silo.conf",
465      siloKeywords,    /* keywords */      .keywords = siloKeywords,
466      0,    /* defaultIsIndex */      .entryStart = LT_KERNEL,
467      0,    /* defaultSupportSaved */      .needsBootPrefix = 1,
468      LT_KERNEL,    /* entrySeparator */      .argsInQuotes = 1,
469      1,    /* needsBootPrefix */      .maxTitleLength = 15,
     1,    /* argsInQuotes */  
     15,    /* maxTitleLength */  
     0,                                      /* titleBracketed */  
     0,                                      /* mbHyperFirst */  
     0,                                      /* mbInitRdIsModule */  
     0,                                      /* mbConcatArgs */  
     0,                                      /* mbAllowExtraInitRds */  
470  };  };
471    
472  struct configFileInfo ziplConfigType = {  struct configFileInfo ziplConfigType = {
473      "/etc/zipl.conf",    /* defaultConfig */      .defaultConfig = "/etc/zipl.conf",
474      ziplKeywords,    /* keywords */      .keywords = ziplKeywords,
475      0,    /* defaultIsIndex */      .entryStart = LT_TITLE,
476      0,    /* defaultSupportSaved */      .argsInQuotes = 1,
477      LT_TITLE,    /* entrySeparator */      .titleBracketed = 1,
     0,    /* needsBootPrefix */  
     1,    /* argsInQuotes */  
     0,    /* maxTitleLength */  
     1,                                      /* titleBracketed */  
     0,                                      /* mbHyperFirst */  
     0,                                      /* mbInitRdIsModule */  
     0,                                      /* mbConcatArgs */  
     0,                                      /* mbAllowExtraInitRds */  
478  };  };
479    
480  struct configFileInfo extlinuxConfigType = {  struct configFileInfo extlinuxConfigType = {
481      "/boot/extlinux/extlinux.conf",         /* defaultConfig */      .defaultConfig = "/boot/extlinux/extlinux.conf",
482      extlinuxKeywords,                       /* keywords */      .keywords = extlinuxKeywords,
483      0,                                      /* defaultIsIndex */      .entryStart = LT_TITLE,
484      0,                                      /* defaultSupportSaved */      .needsBootPrefix = 1,
485      LT_TITLE,                               /* entrySeparator */      .maxTitleLength = 255,
486      1,                                      /* needsBootPrefix */      .mbAllowExtraInitRds = 1,
     0,                                      /* argsInQuotes */  
     255,                                    /* maxTitleLength */  
     0,                                      /* titleBracketed */  
     0,                                      /* mbHyperFirst */  
     0,                                      /* mbInitRdIsModule */  
     0,                                      /* mbConcatArgs */  
     1,                                      /* mbAllowExtraInitRds */  
487  };  };
488    
489  struct grubConfig {  struct grubConfig {
# Line 356  struct grubConfig { Line 498  struct grubConfig {
498      struct configFileInfo * cfi;      struct configFileInfo * cfi;
499  };  };
500    
501    blkid_cache blkid;
502    
503  struct singleEntry * findEntryByIndex(struct grubConfig * cfg, int index);  struct singleEntry * findEntryByIndex(struct grubConfig * cfg, int index);
504  struct singleEntry * findEntryByPath(struct grubConfig * cfg,  struct singleEntry * findEntryByPath(struct grubConfig * cfg,
505       const char * path, const char * prefix,       const char * path, const char * prefix,
# Line 369  static int lineWrite(FILE * out, struct Line 513  static int lineWrite(FILE * out, struct
513  static int getNextLine(char ** bufPtr, struct singleLine * line,  static int getNextLine(char ** bufPtr, struct singleLine * line,
514         struct configFileInfo * cfi);         struct configFileInfo * cfi);
515  static char * getRootSpecifier(char * str);  static char * getRootSpecifier(char * str);
516    static void requote(struct singleLine *line, struct configFileInfo * cfi);
517  static void insertElement(struct singleLine * line,  static void insertElement(struct singleLine * line,
518    const char * item, int insertHere,    const char * item, int insertHere,
519    struct configFileInfo * cfi);    struct configFileInfo * cfi);
# Line 433  static struct keywordTypes * getKeywordB Line 578  static struct keywordTypes * getKeywordB
578      return NULL;      return NULL;
579  }  }
580    
581  static char * getpathbyspec(char *device) {  static char *getKeyByType(enum lineType_e type, struct configFileInfo * cfi) {
582      static blkid_cache blkid;      struct keywordTypes *kt = getKeywordByType(type, cfi);
583        if (kt)
584     return kt->key;
585        return "unknown";
586    }
587    
588    static char * getpathbyspec(char *device) {
589      if (!blkid)      if (!blkid)
590          blkid_get_cache(&blkid, NULL);          blkid_get_cache(&blkid, NULL);
591    
592      return blkid_get_devname(blkid, device, NULL);      return blkid_get_devname(blkid, device, NULL);
593  }  }
594    
595    static char * getuuidbydev(char *device) {
596        if (!blkid)
597     blkid_get_cache(&blkid, NULL);
598    
599        return blkid_get_tag_value(blkid, "UUID", device);
600    }
601    
602  static enum lineType_e getTypeByKeyword(char * keyword,  static enum lineType_e getTypeByKeyword(char * keyword,
603   struct configFileInfo * cfi) {   struct configFileInfo * cfi) {
604      struct keywordTypes * kw;      struct keywordTypes * kw;
# Line 477  static int isBracketedTitle(struct singl Line 634  static int isBracketedTitle(struct singl
634      return 0;      return 0;
635  }  }
636    
637  static int isEntrySeparator(struct singleLine * line,  static int isEntryStart(struct singleLine * line,
638                              struct configFileInfo * cfi) {                              struct configFileInfo * cfi) {
639      return line->type == cfi->entrySeparator || line->type == LT_OTHER ||      return line->type == cfi->entryStart || line->type == LT_OTHER ||
640   (cfi->titleBracketed && isBracketedTitle(line));   (cfi->titleBracketed && isBracketedTitle(line));
641  }  }
642    
# Line 802  static struct grubConfig * readConfig(co Line 959  static struct grubConfig * readConfig(co
959      cfg->secondaryIndent = strdup(line->indent);      cfg->secondaryIndent = strdup(line->indent);
960   }   }
961    
962   if (isEntrySeparator(line, cfi)) {   if (isEntryStart(line, cfi) || (cfg->entries && !sawEntry)) {
963      sawEntry = 1;      sawEntry = 1;
964      if (!entry) {      if (!entry) {
965   cfg->entries = malloc(sizeof(*entry));   cfg->entries = malloc(sizeof(*entry));
# Line 818  static struct grubConfig * readConfig(co Line 975  static struct grubConfig * readConfig(co
975      entry->next = NULL;      entry->next = NULL;
976   }   }
977    
978   if (line->type == LT_DEFAULT && line->numElements == 2) {   if (line->type == LT_SET_VARIABLE) {
979        int i;
980        dbgPrintf("found 'set' command (%d elements): ", line->numElements);
981        dbgPrintf("%s", line->indent);
982        for (i = 0; i < line->numElements; i++)
983     dbgPrintf("%s\"%s\"", line->elements[i].indent, line->elements[i].item);
984        dbgPrintf("\n");
985        struct keywordTypes *kwType = getKeywordByType(LT_DEFAULT, cfi);
986        if (kwType && line->numElements == 3 &&
987        !strcmp(line->elements[1].item, kwType->key)) {
988     dbgPrintf("Line sets default config\n");
989     cfg->flags &= ~GRUB_CONFIG_NO_DEFAULT;
990     defaultLine = line;
991        }
992     } else if (line->type == LT_DEFAULT && line->numElements == 2) {
993      cfg->flags &= ~GRUB_CONFIG_NO_DEFAULT;      cfg->flags &= ~GRUB_CONFIG_NO_DEFAULT;
994      defaultLine = line;      defaultLine = line;
995    
# Line 931  static struct grubConfig * readConfig(co Line 1102  static struct grubConfig * readConfig(co
1102   entry->lines = line;   entry->lines = line;
1103      else      else
1104   last->next = line;   last->next = line;
1105      dbgPrintf("readConfig added %d to %p\n", line->type, entry);      dbgPrintf("readConfig added %s to %p\n", getKeyByType(line->type, cfi), entry);
1106    
1107        /* we could have seen this outside of an entry... if so, we
1108         * ignore it like any other line we don't grok */
1109        if (line->type == LT_ENTRY_END && sawEntry)
1110     sawEntry = 0;
1111   } else {   } else {
1112      if (!cfg->theLines)      if (!cfg->theLines)
1113   cfg->theLines = line;   cfg->theLines = line;
1114      else      else
1115   last->next = line;   last->next = line;
1116      dbgPrintf("readConfig added %d to cfg\n", line->type);      dbgPrintf("readConfig added %s to cfg\n", getKeyByType(line->type, cfi));
1117   }   }
1118    
1119   last = line;   last = line;
# Line 945  static struct grubConfig * readConfig(co Line 1121  static struct grubConfig * readConfig(co
1121    
1122      free(incoming);      free(incoming);
1123    
1124        dbgPrintf("defaultLine is %s\n", defaultLine ? "set" : "unset");
1125      if (defaultLine) {      if (defaultLine) {
1126   if (cfi->defaultSupportSaved &&   if (cfi->defaultIsVariable) {
1127        char *value = defaultLine->elements[2].item;
1128        while (*value && (*value == '"' || *value == '\'' ||
1129        *value == ' ' || *value == '\t'))
1130     value++;
1131        cfg->defaultImage = strtol(value, &end, 10);
1132        while (*end && (*end == '"' || *end == '\'' ||
1133        *end == ' ' || *end == '\t'))
1134     end++;
1135        if (*end) cfg->defaultImage = -1;
1136     } else if (cfi->defaultSupportSaved &&
1137   !strncmp(defaultLine->elements[1].item, "saved", 5)) {   !strncmp(defaultLine->elements[1].item, "saved", 5)) {
1138      cfg->defaultImage = DEFAULT_SAVED;      cfg->defaultImage = DEFAULT_SAVED;
1139   } else if (cfi->defaultIsIndex) {   } else if (cfi->defaultIsIndex) {
# Line 995  static void writeDefault(FILE * out, cha Line 1182  static void writeDefault(FILE * out, cha
1182   fprintf(out, "%sdefault%ssaved\n", indent, separator);   fprintf(out, "%sdefault%ssaved\n", indent, separator);
1183      else if (cfg->defaultImage > -1) {      else if (cfg->defaultImage > -1) {
1184   if (cfg->cfi->defaultIsIndex) {   if (cfg->cfi->defaultIsIndex) {
1185      fprintf(out, "%sdefault%s%d\n", indent, separator,      if (cfg->cfi->defaultIsVariable) {
1186      cfg->defaultImage);          fprintf(out, "%sset default=\"%d\"\n", indent,
1187     cfg->defaultImage);
1188        } else {
1189     fprintf(out, "%sdefault%s%d\n", indent, separator,
1190     cfg->defaultImage);
1191        }
1192   } else {   } else {
1193      int image = cfg->defaultImage;      int image = cfg->defaultImage;
1194    
# Line 1086  static int writeConfig(struct grubConfig Line 1278  static int writeConfig(struct grubConfig
1278      }      }
1279    
1280      line = cfg->theLines;      line = cfg->theLines;
1281        struct keywordTypes *defaultKw = getKeywordByType(LT_DEFAULT, cfg->cfi);
1282      while (line) {      while (line) {
1283   if (line->type == LT_DEFAULT) {          if (line->type == LT_SET_VARIABLE && defaultKw &&
1284     line->numElements == 3 &&
1285     !strcmp(line->elements[1].item, defaultKw->key)) {
1286        writeDefault(out, line->indent, line->elements[0].indent, cfg);
1287        needs &= ~MAIN_DEFAULT;
1288     } else if (line->type == LT_DEFAULT) {
1289      writeDefault(out, line->indent, line->elements[0].indent, cfg);      writeDefault(out, line->indent, line->elements[0].indent, cfg);
1290      needs &= ~MAIN_DEFAULT;      needs &= ~MAIN_DEFAULT;
1291   } else if (line->type == LT_FALLBACK) {   } else if (line->type == LT_FALLBACK) {
# Line 1155  static int numEntries(struct grubConfig Line 1353  static int numEntries(struct grubConfig
1353      return i;      return i;
1354  }  }
1355    
1356    static char *findDiskForRoot()
1357    {
1358        int fd;
1359        char buf[65536];
1360        char *devname;
1361        char *chptr;
1362        int rc;
1363    
1364        if ((fd = open(_PATH_MOUNTED, O_RDONLY)) < 0) {
1365            fprintf(stderr, "grubby: failed to open %s: %s\n",
1366                    _PATH_MOUNTED, strerror(errno));
1367            return NULL;
1368        }
1369    
1370        rc = read(fd, buf, sizeof(buf) - 1);
1371        if (rc <= 0) {
1372            fprintf(stderr, "grubby: failed to read %s: %s\n",
1373                    _PATH_MOUNTED, strerror(errno));
1374            close(fd);
1375            return NULL;
1376        }
1377        close(fd);
1378        buf[rc] = '\0';
1379        chptr = buf;
1380    
1381        while (chptr && chptr != buf+rc) {
1382            devname = chptr;
1383    
1384            /*
1385             * The first column of a mtab entry is the device, but if the entry is a
1386             * special device it won't start with /, so move on to the next line.
1387             */
1388            if (*devname != '/') {
1389                chptr = strchr(chptr, '\n');
1390                if (chptr)
1391                    chptr++;
1392                continue;
1393            }
1394    
1395            /* Seek to the next space */
1396            chptr = strchr(chptr, ' ');
1397            if (!chptr) {
1398                fprintf(stderr, "grubby: error parsing %s: %s\n",
1399                        _PATH_MOUNTED, strerror(errno));
1400                return NULL;
1401            }
1402    
1403            /*
1404             * The second column of a mtab entry is the mount point, we are looking
1405             * for '/' obviously.
1406             */
1407            if (*(++chptr) == '/' && *(++chptr) == ' ') {
1408                /*
1409                 * Move back 2, which is the first space after the device name, set
1410                 * it to \0 so strdup will just get the devicename.
1411                 */
1412                chptr -= 2;
1413                *chptr = '\0';
1414                return strdup(devname);
1415            }
1416    
1417            /* Next line */
1418            chptr = strchr(chptr, '\n');
1419            if (chptr)
1420                chptr++;
1421        }
1422    
1423        return NULL;
1424    }
1425    
1426    void printEntry(struct singleEntry * entry) {
1427        int i;
1428        struct singleLine * line;
1429    
1430        for (line = entry->lines; line; line = line->next) {
1431     fprintf(stderr, "DBG: %s", line->indent);
1432     for (i = 0; i < line->numElements; i++) {
1433     fprintf(stderr, "%s%s",
1434        line->elements[i].item, line->elements[i].indent);
1435     }
1436     fprintf(stderr, "\n");
1437        }
1438    }
1439    
1440    void notSuitablePrintf(struct singleEntry * entry, const char *fmt, ...)
1441    {
1442        va_list argp;
1443    
1444        if (!debug)
1445     return;
1446    
1447        va_start(argp, fmt);
1448        fprintf(stderr, "DBG: Image entry failed: ");
1449        vfprintf(stderr, fmt, argp);
1450        printEntry(entry);
1451        va_end(argp);
1452    }
1453    
1454    #define beginswith(s, c) ((s) && (s)[0] == (c))
1455    
1456    static int endswith(const char *s, char c)
1457    {
1458     int slen;
1459    
1460     if (!s && !s[0])
1461     return 0;
1462     slen = strlen(s) - 1;
1463    
1464     return s[slen] == c;
1465    }
1466    
1467  int suitableImage(struct singleEntry * entry, const char * bootPrefix,  int suitableImage(struct singleEntry * entry, const char * bootPrefix,
1468    int skipRemoved, int flags) {    int skipRemoved, int flags) {
1469      struct singleLine * line;      struct singleLine * line;
1470      char * fullName;      char * fullName;
1471      int i;      int i;
     struct stat sb, sb2;  
1472      char * dev;      char * dev;
1473      char * rootspec;      char * rootspec;
1474        char * rootdev;
1475    
1476      if (skipRemoved && entry->skip) return 0;      if (skipRemoved && entry->skip) {
1477     notSuitablePrintf(entry, "marked to skip\n");
1478     return 0;
1479        }
1480    
1481      line = getLineByType(LT_KERNEL|LT_HYPER, entry->lines);      line = getLineByType(LT_KERNEL|LT_HYPER, entry->lines);
1482      if (!line || line->numElements < 2) return 0;      if (!line) {
1483     notSuitablePrintf(entry, "no line found\n");
1484     return 0;
1485        }
1486        if (line->numElements < 2) {
1487     notSuitablePrintf(entry, "line has only %d elements\n",
1488        line->numElements);
1489     return 0;
1490        }
1491    
1492      if (flags & GRUBBY_BADIMAGE_OKAY) return 1;      if (flags & GRUBBY_BADIMAGE_OKAY) return 1;
1493    
1494      fullName = alloca(strlen(bootPrefix) +      fullName = alloca(strlen(bootPrefix) +
1495        strlen(line->elements[1].item) + 1);        strlen(line->elements[1].item) + 1);
1496      rootspec = getRootSpecifier(line->elements[1].item);      rootspec = getRootSpecifier(line->elements[1].item);
1497      sprintf(fullName, "%s%s", bootPrefix,      int rootspec_offset = rootspec ? strlen(rootspec) : 0;
1498              line->elements[1].item + (rootspec ? strlen(rootspec) : 0));      int hasslash = endswith(bootPrefix, '/') ||
1499      if (access(fullName, R_OK)) return 0;       beginswith(line->elements[1].item + rootspec_offset, '/');
1500        sprintf(fullName, "%s%s%s", bootPrefix, hasslash ? "" : "/",
1501                line->elements[1].item + rootspec_offset);
1502        if (access(fullName, R_OK)) {
1503     notSuitablePrintf(entry, "access to %s failed\n", fullName);
1504     return 0;
1505        }
1506      for (i = 2; i < line->numElements; i++)      for (i = 2; i < line->numElements; i++)
1507   if (!strncasecmp(line->elements[i].item, "root=", 5)) break;   if (!strncasecmp(line->elements[i].item, "root=", 5)) break;
1508      if (i < line->numElements) {      if (i < line->numElements) {
# Line 1195  int suitableImage(struct singleEntry * e Line 1520  int suitableImage(struct singleEntry * e
1520      line = getLineByType(LT_KERNELARGS|LT_MBMODULE, entry->lines);      line = getLineByType(LT_KERNELARGS|LT_MBMODULE, entry->lines);
1521    
1522              /* failed to find one */              /* failed to find one */
1523              if (!line) return 0;              if (!line) {
1524     notSuitablePrintf(entry, "no line found\n");
1525     return 0;
1526                }
1527    
1528      for (i = 1; i < line->numElements; i++)      for (i = 1; i < line->numElements; i++)
1529          if (!strncasecmp(line->elements[i].item, "root=", 5)) break;          if (!strncasecmp(line->elements[i].item, "root=", 5)) break;
1530      if (i < line->numElements)      if (i < line->numElements)
1531          dev = line->elements[i].item + 5;          dev = line->elements[i].item + 5;
1532      else {      else {
1533     notSuitablePrintf(entry, "no root= entry found\n");
1534   /* it failed too...  can't find root= */   /* it failed too...  can't find root= */
1535          return 0;          return 0;
1536              }              }
# Line 1209  int suitableImage(struct singleEntry * e Line 1538  int suitableImage(struct singleEntry * e
1538      }      }
1539    
1540      dev = getpathbyspec(dev);      dev = getpathbyspec(dev);
1541      if (!dev)      if (!getpathbyspec(dev)) {
1542            notSuitablePrintf(entry, "can't find blkid entry for %s\n", dev);
1543          return 0;          return 0;
1544        } else
1545     dev = getpathbyspec(dev);
1546    
1547      i = stat(dev, &sb);      rootdev = findDiskForRoot();
1548      if (i)      if (!rootdev) {
1549            notSuitablePrintf(entry, "can't find root device\n");
1550   return 0;   return 0;
1551        }
1552    
1553      stat("/", &sb2);      if (!getuuidbydev(rootdev) || !getuuidbydev(dev)) {
1554            notSuitablePrintf(entry, "uuid missing: rootdev %s, dev %s\n",
1555     getuuidbydev(rootdev), getuuidbydev(dev));
1556            free(rootdev);
1557            return 0;
1558        }
1559    
1560      if (sb.st_rdev != sb2.st_dev)      if (strcmp(getuuidbydev(rootdev), getuuidbydev(dev))) {
1561            notSuitablePrintf(entry, "uuid mismatch: rootdev %s, dev %s\n",
1562     getuuidbydev(rootdev), getuuidbydev(dev));
1563     free(rootdev);
1564          return 0;          return 0;
1565        }
1566    
1567        free(rootdev);
1568    
1569      return 1;      return 1;
1570  }  }
# Line 1582  int parseSysconfigGrub(int * lbaPtr, cha Line 1927  int parseSysconfigGrub(int * lbaPtr, cha
1927      char * start;      char * start;
1928      char * param;      char * param;
1929    
1930      in = fopen("/etc/sysconfig/grub", "r");      in = fopen("/etc/conf.d/grub", "r");
1931      if (!in) return 1;      if (!in) return 1;
1932    
1933      if (lbaPtr) *lbaPtr = 0;      if (lbaPtr) *lbaPtr = 0;
# Line 1644  int displayInfo(struct grubConfig * conf Line 1989  int displayInfo(struct grubConfig * conf
1989   return 1;   return 1;
1990      }      }
1991    
1992      /* this is a horrible hack to support /etc/sysconfig/grub; there must      /* this is a horrible hack to support /etc/conf.d/grub; there must
1993         be a better way */         be a better way */
1994      if (config->cfi == &grubConfigType) {      if (config->cfi == &grubConfigType) {
1995   dumpSysconfigGrub();   dumpSysconfigGrub();
# Line 1733  struct singleLine *  addLine(struct sing Line 2078  struct singleLine *  addLine(struct sing
2078   sprintf(tmpl.elements[0].item, "[%s]", val);   sprintf(tmpl.elements[0].item, "[%s]", val);
2079   tmpl.elements[0].indent = "";   tmpl.elements[0].indent = "";
2080   val = NULL;   val = NULL;
2081        } else if (type == LT_MENUENTRY) {
2082     char *lineend = "--class gnu-linux --class gnu --class os {";
2083     if (!val) {
2084        fprintf(stderr, "Line type LT_MENUENTRY requires a value\n");
2085        abort();
2086     }
2087     kw = getKeywordByType(type, cfi);
2088     if (!kw) {
2089        fprintf(stderr, "Looking up keyword for unknown type %d\n", type);
2090        abort();
2091     }
2092     tmpl.indent = "";
2093     tmpl.type = type;
2094     tmpl.numElements = 3;
2095     tmpl.elements = alloca(sizeof(*tmpl.elements) * tmpl.numElements);
2096     tmpl.elements[0].item = kw->key;
2097     tmpl.elements[0].indent = alloca(2);
2098     sprintf(tmpl.elements[0].indent, "%c", kw->nextChar);
2099     tmpl.elements[1].item = (char *)val;
2100     tmpl.elements[1].indent = alloca(2);
2101     sprintf(tmpl.elements[1].indent, "%c", kw->nextChar);
2102     tmpl.elements[2].item = alloca(strlen(lineend)+1);
2103     strcpy(tmpl.elements[2].item, lineend);
2104     tmpl.elements[2].indent = "";
2105      } else {      } else {
2106   kw = getKeywordByType(type, cfi);   kw = getKeywordByType(type, cfi);
2107   if (!kw) abort();   if (!kw) {
2108        fprintf(stderr, "Looking up keyword for unknown type %d\n", type);
2109        abort();
2110     }
2111   tmpl.type = type;   tmpl.type = type;
2112   tmpl.numElements = val ? 2 : 1;   tmpl.numElements = val ? 2 : 1;
2113   tmpl.elements = alloca(sizeof(*tmpl.elements) * tmpl.numElements);   tmpl.elements = alloca(sizeof(*tmpl.elements) * tmpl.numElements);
# Line 1759  struct singleLine *  addLine(struct sing Line 2131  struct singleLine *  addLine(struct sing
2131   if (!line->next && !prev) prev = line;   if (!line->next && !prev) prev = line;
2132      }      }
2133    
2134      if (prev == entry->lines)      struct singleLine *menuEntry;
2135   tmpl.indent = defaultIndent ?: "";      menuEntry = getLineByType(LT_MENUENTRY, entry->lines);
2136      else      if (tmpl.type == LT_ENTRY_END) {
2137   tmpl.indent = prev->indent;   if (menuEntry)
2138        tmpl.indent = menuEntry->indent;
2139     else
2140        tmpl.indent = defaultIndent ?: "";
2141        } else if (tmpl.type != LT_MENUENTRY) {
2142     if (menuEntry)
2143        tmpl.indent = "\t";
2144     else if (prev == entry->lines)
2145        tmpl.indent = defaultIndent ?: "";
2146     else
2147        tmpl.indent = prev->indent;
2148        }
2149    
2150      return addLineTmpl(entry, &tmpl, prev, val, cfi);      return addLineTmpl(entry, &tmpl, prev, val, cfi);
2151  }  }
# Line 1789  void removeLine(struct singleEntry * ent Line 2172  void removeLine(struct singleEntry * ent
2172      free(line);      free(line);
2173  }  }
2174    
2175    static int isquote(char q)
2176    {
2177        if (q == '\'' || q == '\"')
2178     return 1;
2179        return 0;
2180    }
2181    
2182    static void requote(struct singleLine *tmplLine, struct configFileInfo * cfi)
2183    {
2184        struct singleLine newLine = {
2185     .indent = tmplLine->indent,
2186     .type = tmplLine->type,
2187     .next = tmplLine->next,
2188        };
2189        int firstQuotedItem = -1;
2190        int quoteLen = 0;
2191        int j;
2192        int element = 0;
2193        char *c;
2194    
2195        c = malloc(strlen(tmplLine->elements[0].item) + 1);
2196        strcpy(c, tmplLine->elements[0].item);
2197        insertElement(&newLine, c, element++, cfi);
2198        free(c);
2199        c = NULL;
2200    
2201        for (j = 1; j < tmplLine->numElements; j++) {
2202     if (firstQuotedItem == -1) {
2203        quoteLen += strlen(tmplLine->elements[j].item);
2204        
2205        if (isquote(tmplLine->elements[j].item[0])) {
2206     firstQuotedItem = j;
2207            quoteLen += strlen(tmplLine->elements[j].indent);
2208        } else {
2209     c = malloc(quoteLen + 1);
2210     strcpy(c, tmplLine->elements[j].item);
2211     insertElement(&newLine, c, element++, cfi);
2212     free(c);
2213     quoteLen = 0;
2214        }
2215     } else {
2216        int itemlen = strlen(tmplLine->elements[j].item);
2217        quoteLen += itemlen;
2218        quoteLen += strlen(tmplLine->elements[j].indent);
2219        
2220        if (isquote(tmplLine->elements[j].item[itemlen - 1])) {
2221     c = malloc(quoteLen + 1);
2222     c[0] = '\0';
2223     for (int i = firstQuotedItem; i < j+1; i++) {
2224        strcat(c, tmplLine->elements[i].item);
2225        strcat(c, tmplLine->elements[i].indent);
2226     }
2227     insertElement(&newLine, c, element++, cfi);
2228     free(c);
2229    
2230     firstQuotedItem = -1;
2231     quoteLen = 0;
2232        }
2233     }
2234        }
2235        while (tmplLine->numElements)
2236     removeElement(tmplLine, 0);
2237        if (tmplLine->elements)
2238     free(tmplLine->elements);
2239    
2240        tmplLine->numElements = newLine.numElements;
2241        tmplLine->elements = newLine.elements;
2242    }
2243    
2244  static void insertElement(struct singleLine * line,  static void insertElement(struct singleLine * line,
2245    const char * item, int insertHere,    const char * item, int insertHere,
2246    struct configFileInfo * cfi)    struct configFileInfo * cfi)
# Line 1895  int updateActualImage(struct grubConfig Line 2347  int updateActualImage(struct grubConfig
2347      const char ** arg;      const char ** arg;
2348      int useKernelArgs, useRoot;      int useKernelArgs, useRoot;
2349      int firstElement;      int firstElement;
2350      int *usedElements, *usedArgs;      int *usedElements;
2351      int doreplace;      int doreplace;
2352    
2353      if (!image) return 0;      if (!image) return 0;
# Line 1930  int updateActualImage(struct grubConfig Line 2382  int updateActualImage(struct grubConfig
2382      useRoot = (getKeywordByType(LT_ROOT, cfg->cfi)      useRoot = (getKeywordByType(LT_ROOT, cfg->cfi)
2383         && !multibootArgs);         && !multibootArgs);
2384    
     for (k = 0, arg = newArgs; *arg; arg++, k++) ;  
     usedArgs = calloc(k, sizeof(*usedArgs));  
   
2385      for (; (entry = findEntryByPath(cfg, image, prefix, &index)); index++) {      for (; (entry = findEntryByPath(cfg, image, prefix, &index)); index++) {
2386    
2387   if (multibootArgs && !entry->multiboot)   if (multibootArgs && !entry->multiboot)
# Line 2008  int updateActualImage(struct grubConfig Line 2457  int updateActualImage(struct grubConfig
2457          usedElements = calloc(line->numElements, sizeof(*usedElements));          usedElements = calloc(line->numElements, sizeof(*usedElements));
2458    
2459   for (k = 0, arg = newArgs; *arg; arg++, k++) {   for (k = 0, arg = newArgs; *arg; arg++, k++) {
             if (usedArgs[k]) continue;  
2460    
2461      doreplace = 1;      doreplace = 1;
2462      for (i = firstElement; i < line->numElements; i++) {      for (i = firstElement; i < line->numElements; i++) {
# Line 2023  int updateActualImage(struct grubConfig Line 2471  int updateActualImage(struct grubConfig
2471                      continue;                      continue;
2472   if (!argMatch(line->elements[i].item, *arg)) {   if (!argMatch(line->elements[i].item, *arg)) {
2473                      usedElements[i]=1;                      usedElements[i]=1;
                     usedArgs[k]=1;  
2474      break;      break;
2475                  }                  }
2476              }              }
# Line 2093  int updateActualImage(struct grubConfig Line 2540  int updateActualImage(struct grubConfig
2540   }   }
2541      }      }
2542    
     free(usedArgs);  
2543      free(newArgs);      free(newArgs);
2544      free(oldArgs);      free(oldArgs);
2545    
# Line 2119  int updateImage(struct grubConfig * cfg, Line 2565  int updateImage(struct grubConfig * cfg,
2565      return rc;      return rc;
2566  }  }
2567    
2568    int updateInitrd(struct grubConfig * cfg, const char * image,
2569                     const char * prefix, const char * initrd) {
2570        struct singleEntry * entry;
2571        struct singleLine * line, * kernelLine, *endLine = NULL;
2572        int index = 0;
2573    
2574        if (!image) return 0;
2575    
2576        for (; (entry = findEntryByPath(cfg, image, prefix, &index)); index++) {
2577            kernelLine = getLineByType(LT_KERNEL, entry->lines);
2578            if (!kernelLine) continue;
2579    
2580            line = getLineByType(LT_INITRD, entry->lines);
2581            if (line)
2582                removeLine(entry, line);
2583            if (prefix) {
2584                int prefixLen = strlen(prefix);
2585                if (!strncmp(initrd, prefix, prefixLen))
2586                    initrd += prefixLen;
2587            }
2588     endLine = getLineByType(LT_ENTRY_END, entry->lines);
2589     if (endLine)
2590        removeLine(entry, endLine);
2591            line = addLine(entry, cfg->cfi, LT_INITRD, kernelLine->indent, initrd);
2592            if (!line)
2593        return 1;
2594     if (endLine) {
2595        line = addLine(entry, cfg->cfi, LT_ENTRY_END, "", NULL);
2596                if (!line)
2597     return 1;
2598     }
2599    
2600            break;
2601        }
2602    
2603        return 0;
2604    }
2605    
2606  int checkDeviceBootloader(const char * device, const unsigned char * boot) {  int checkDeviceBootloader(const char * device, const unsigned char * boot) {
2607      int fd;      int fd;
2608      unsigned char bootSect[512];      unsigned char bootSect[512];
# Line 2142  int checkDeviceBootloader(const char * d Line 2626  int checkDeviceBootloader(const char * d
2626      if (memcmp(boot, bootSect, 3))      if (memcmp(boot, bootSect, 3))
2627   return 0;   return 0;
2628    
2629      if (boot[1] == 0xeb) {      if (boot[1] == JMP_SHORT_OPCODE) {
2630   offset = boot[2] + 2;   offset = boot[2] + 2;
2631      } else if (boot[1] == 0xe8 || boot[1] == 0xe9) {      } else if (boot[1] == 0xe8 || boot[1] == 0xe9) {
2632   offset = (boot[3] << 8) + boot[2] + 2;   offset = (boot[3] << 8) + boot[2] + 2;
2633      } else if (boot[0] == 0xeb) {      } else if (boot[0] == JMP_SHORT_OPCODE) {
2634   offset = boot[1] + 2;        offset = boot[1] + 2;
2635            /*
2636     * it looks like grub, when copying stage1 into the mbr, patches stage1
2637     * right after the JMP location, replacing other instructions such as
2638     * JMPs for NOOPs. So, relax the check a little bit by skipping those
2639     * different bytes.
2640     */
2641          if ((bootSect[offset + 1] == NOOP_OPCODE)
2642      && (bootSect[offset + 2] == NOOP_OPCODE)) {
2643     offset = offset + 3;
2644          }
2645      } else if (boot[0] == 0xe8 || boot[0] == 0xe9) {      } else if (boot[0] == 0xe8 || boot[0] == 0xe9) {
2646   offset = (boot[2] << 8) + boot[1] + 2;   offset = (boot[2] << 8) + boot[1] + 2;
2647      } else {      } else {
# Line 2289  int checkForLilo(struct grubConfig * con Line 2783  int checkForLilo(struct grubConfig * con
2783      return checkDeviceBootloader(line->elements[1].item, boot);      return checkDeviceBootloader(line->elements[1].item, boot);
2784  }  }
2785    
2786    int checkForGrub2(struct grubConfig * config) {
2787        if (!access("/etc/grub.d/", R_OK))
2788     return 2;
2789    
2790        return 1;
2791    }
2792    
2793  int checkForGrub(struct grubConfig * config) {  int checkForGrub(struct grubConfig * config) {
2794      int fd;      int fd;
2795      unsigned char bootSect[512];      unsigned char bootSect[512];
# Line 2464  int addNewKernel(struct grubConfig * con Line 2965  int addNewKernel(struct grubConfig * con
2965      if (*chptr == '#') continue;      if (*chptr == '#') continue;
2966    
2967      if (tmplLine->type == LT_KERNEL &&      if (tmplLine->type == LT_KERNEL &&
2968   tmplLine->numElements >= 2) {      tmplLine->numElements >= 2) {
2969   if (!template->multiboot && (needs & NEED_MB)) {   if (!template->multiboot && (needs & NEED_MB)) {
2970      /* it's not a multiboot template and this is the kernel      /* it's not a multiboot template and this is the kernel
2971       * line.  Try to be intelligent about inserting the       * line.  Try to be intelligent about inserting the
# Line 2590  int addNewKernel(struct grubConfig * con Line 3091  int addNewKernel(struct grubConfig * con
3091      needs &= ~NEED_INITRD;      needs &= ~NEED_INITRD;
3092   }   }
3093    
3094        } else if (tmplLine->type == LT_MENUENTRY &&
3095           (needs & NEED_TITLE)) {
3096     requote(tmplLine, config->cfi);
3097     char *nkt = malloc(strlen(newKernelTitle)+3);
3098     strcpy(nkt, "'");
3099     strcat(nkt, newKernelTitle);
3100     strcat(nkt, "'");
3101     newLine = addLineTmpl(new, tmplLine, newLine, nkt, config->cfi);
3102     free(nkt);
3103     needs &= ~NEED_TITLE;
3104      } else if (tmplLine->type == LT_TITLE &&      } else if (tmplLine->type == LT_TITLE &&
3105         (needs & NEED_TITLE)) {         (needs & NEED_TITLE)) {
3106   if (tmplLine->numElements >= 2) {   if (tmplLine->numElements >= 2) {
# Line 2603  int addNewKernel(struct grubConfig * con Line 3114  int addNewKernel(struct grubConfig * con
3114        tmplLine->indent, newKernelTitle);        tmplLine->indent, newKernelTitle);
3115      needs &= ~NEED_TITLE;      needs &= ~NEED_TITLE;
3116   }   }
3117        } else if (tmplLine->type == LT_ECHO) {
3118        requote(tmplLine, config->cfi);
3119        static const char *prefix = "'Loading ";
3120        if (tmplLine->numElements > 1 &&
3121        strstr(tmplLine->elements[1].item, prefix) &&
3122        masterLine->next && masterLine->next->type == LT_KERNEL) {
3123     char *newTitle = malloc(strlen(prefix) +
3124     strlen(newKernelTitle) + 2);
3125    
3126     strcpy(newTitle, prefix);
3127     strcat(newTitle, newKernelTitle);
3128     strcat(newTitle, "'");
3129     newLine = addLine(new, config->cfi, LT_ECHO,
3130     tmplLine->indent, newTitle);
3131     free(newTitle);
3132        } else {
3133     /* pass through other lines from the template */
3134     newLine = addLineTmpl(new, tmplLine, newLine, NULL,
3135     config->cfi);
3136        }
3137      } else {      } else {
3138   /* pass through other lines from the template */   /* pass through other lines from the template */
3139   newLine = addLineTmpl(new, tmplLine, newLine, NULL, config->cfi);   newLine = addLineTmpl(new, tmplLine, newLine, NULL, config->cfi);
# Line 2614  int addNewKernel(struct grubConfig * con Line 3144  int addNewKernel(struct grubConfig * con
3144   /* don't have a template, so start the entry with the   /* don't have a template, so start the entry with the
3145   * appropriate starting line   * appropriate starting line
3146   */   */
3147   switch (config->cfi->entrySeparator) {   switch (config->cfi->entryStart) {
3148      case LT_KERNEL:      case LT_KERNEL:
3149   if (new->multiboot && config->cfi->mbHyperFirst) {   if (new->multiboot && config->cfi->mbHyperFirst) {
3150      /* fall through to LT_HYPER */      /* fall through to LT_HYPER */
# Line 2633  int addNewKernel(struct grubConfig * con Line 3163  int addNewKernel(struct grubConfig * con
3163   needs &= ~NEED_MB;   needs &= ~NEED_MB;
3164   break;   break;
3165    
3166        case LT_MENUENTRY: {
3167     char *nkt = malloc(strlen(newKernelTitle)+3);
3168     strcpy(nkt, "'");
3169     strcat(nkt, newKernelTitle);
3170     strcat(nkt, "'");
3171            newLine = addLine(new, config->cfi, LT_MENUENTRY,
3172      config->primaryIndent, nkt);
3173     free(nkt);
3174     needs &= ~NEED_TITLE;
3175     needs |= NEED_END;
3176     break;
3177        }
3178      case LT_TITLE:      case LT_TITLE:
3179   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)
3180   char * templabel;   char * templabel;
# Line 2666  int addNewKernel(struct grubConfig * con Line 3208  int addNewKernel(struct grubConfig * con
3208    
3209      /* add the remainder of the lines, i.e. those that either      /* add the remainder of the lines, i.e. those that either
3210       * 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,
3211       * all the lines following the entrySeparator.       * all the lines following the entryStart.
3212       */       */
3213      if (needs & NEED_TITLE) {      if (needs & NEED_TITLE) {
3214   newLine = addLine(new, config->cfi, LT_TITLE,   newLine = addLine(new, config->cfi, LT_TITLE,
# Line 2707  int addNewKernel(struct grubConfig * con Line 3249  int addNewKernel(struct grubConfig * con
3249   free(initrdVal);   free(initrdVal);
3250   needs &= ~NEED_INITRD;   needs &= ~NEED_INITRD;
3251      }      }
3252        if (needs & NEED_END) {
3253     newLine = addLine(new, config->cfi, LT_ENTRY_END,
3254     config->secondaryIndent, NULL);
3255     needs &= ~NEED_END;
3256        }
3257    
3258      if (needs) {      if (needs) {
3259   printf(_("grubby: needs=%d, aborting\n"), needs);   printf(_("grubby: needs=%d, aborting\n"), needs);
# Line 2736  static void traceback(int signum) Line 3283  static void traceback(int signum)
3283    
3284  int main(int argc, const char ** argv) {  int main(int argc, const char ** argv) {
3285      poptContext optCon;      poptContext optCon;
3286      char * grubConfig = NULL;      const char * grubConfig = NULL;
3287      char * outputFile = NULL;      char * outputFile = NULL;
3288      int arg = 0;      int arg = 0;
3289      int flags = 0;      int flags = 0;
3290      int badImageOkay = 0;      int badImageOkay = 0;
3291        int configureGrub2 = 0;
3292      int configureLilo = 0, configureELilo = 0, configureGrub = 0;      int configureLilo = 0, configureELilo = 0, configureGrub = 0;
3293      int configureYaboot = 0, configureSilo = 0, configureZipl = 0;      int configureYaboot = 0, configureSilo = 0, configureZipl = 0;
3294      int configureExtLinux = 0;      int configureExtLinux = 0;
# Line 2768  int main(int argc, const char ** argv) { Line 3316  int main(int argc, const char ** argv) {
3316      struct singleEntry * template = NULL;      struct singleEntry * template = NULL;
3317      int copyDefault = 0, makeDefault = 0;      int copyDefault = 0, makeDefault = 0;
3318      int displayDefault = 0;      int displayDefault = 0;
3319        int displayDefaultIndex = 0;
3320        int displayDefaultTitle = 0;
3321      struct poptOption options[] = {      struct poptOption options[] = {
3322   { "add-kernel", 0, POPT_ARG_STRING, &newKernelPath, 0,   { "add-kernel", 0, POPT_ARG_STRING, &newKernelPath, 0,
3323      _("add an entry for the specified kernel"), _("kernel-path") },      _("add an entry for the specified kernel"), _("kernel-path") },
# Line 2798  int main(int argc, const char ** argv) { Line 3348  int main(int argc, const char ** argv) {
3348        "the kernel referenced by the default image does not exist, "        "the kernel referenced by the default image does not exist, "
3349        "the first linux entry whose kernel does exist is used as the "        "the first linux entry whose kernel does exist is used as the "
3350        "template"), NULL },        "template"), NULL },
3351     { "debug", 0, 0, &debug, 0,
3352        _("print debugging information for failures") },
3353   { "default-kernel", 0, 0, &displayDefault, 0,   { "default-kernel", 0, 0, &displayDefault, 0,
3354      _("display the path of the default kernel") },      _("display the path of the default kernel") },
3355     { "default-index", 0, 0, &displayDefaultIndex, 0,
3356        _("display the index of the default kernel") },
3357     { "default-title", 0, 0, &displayDefaultTitle, 0,
3358        _("display the title of the default kernel") },
3359   { "elilo", 0, POPT_ARG_NONE, &configureELilo, 0,   { "elilo", 0, POPT_ARG_NONE, &configureELilo, 0,
3360      _("configure elilo bootloader") },      _("configure elilo bootloader") },
3361   { "extlinux", 0, POPT_ARG_NONE, &configureExtLinux, 0,   { "extlinux", 0, POPT_ARG_NONE, &configureExtLinux, 0,
3362      _("configure extlinux bootloader (from syslinux)") },      _("configure extlinux bootloader (from syslinux)") },
3363   { "grub", 0, POPT_ARG_NONE, &configureGrub, 0,   { "grub", 0, POPT_ARG_NONE, &configureGrub, 0,
3364      _("configure grub bootloader") },      _("configure grub bootloader") },
3365     { "grub2", 0, POPT_ARG_NONE, &configureGrub2, 0,
3366        _("configure grub2 bootloader") },
3367   { "info", 0, POPT_ARG_STRING, &kernelInfo, 0,   { "info", 0, POPT_ARG_STRING, &kernelInfo, 0,
3368      _("display boot information for specified kernel"),      _("display boot information for specified kernel"),
3369      _("kernel-path") },      _("kernel-path") },
# Line 2885  int main(int argc, const char ** argv) { Line 3443  int main(int argc, const char ** argv) {
3443   return 1;   return 1;
3444      }      }
3445    
3446      if ((configureLilo + configureGrub + configureELilo +      if ((configureLilo + configureGrub2 + configureGrub + configureELilo +
3447   configureYaboot + configureSilo + configureZipl +   configureYaboot + configureSilo + configureZipl +
3448   configureExtLinux ) > 1) {   configureExtLinux ) > 1) {
3449   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 3452  int main(int argc, const char ** argv) {
3452   fprintf(stderr,   fprintf(stderr,
3453      _("grubby: cannot specify config file with --bootloader-probe\n"));      _("grubby: cannot specify config file with --bootloader-probe\n"));
3454   return 1;   return 1;
3455        } else if (configureGrub2) {
3456     cfi = &grub2ConfigType;
3457      } else if (configureLilo) {      } else if (configureLilo) {
3458   cfi = &liloConfigType;   cfi = &liloConfigType;
3459      } else if (configureGrub) {      } else if (configureGrub) {
# Line 2923  int main(int argc, const char ** argv) { Line 3483  int main(int argc, const char ** argv) {
3483        #elif __s390x__        #elif __s390x__
3484          cfi = &ziplConfigtype;          cfi = &ziplConfigtype;
3485        #else        #else
3486   cfi = &grubConfigType;          if (grub2FindConfig(&grub2ConfigType))
3487        cfi = &grub2ConfigType;
3488     else
3489        cfi = &grubConfigType;
3490        #endif        #endif
3491      }      }
3492    
3493      if (!grubConfig)      if (!grubConfig) {
3494   grubConfig = cfi->defaultConfig;   if (cfi->findConfig)
3495        grubConfig = cfi->findConfig(cfi);
3496     if (!grubConfig)
3497        grubConfig = cfi->defaultConfig;
3498        }
3499    
3500      if (bootloaderProbe && (displayDefault || kernelInfo || newKernelVersion ||      if (bootloaderProbe && (displayDefault || kernelInfo || newKernelVersion ||
3501    newKernelPath || removeKernelPath || makeDefault ||    newKernelPath || removeKernelPath || makeDefault ||
3502    defaultKernel)) {    defaultKernel || displayDefaultIndex || displayDefaultTitle)) {
3503   fprintf(stderr, _("grubby: --bootloader-probe may not be used with "   fprintf(stderr, _("grubby: --bootloader-probe may not be used with "
3504    "specified option"));    "specified option"));
3505   return 1;   return 1;
# Line 2948  int main(int argc, const char ** argv) { Line 3515  int main(int argc, const char ** argv) {
3515      if (newKernelPath && !newKernelTitle) {      if (newKernelPath && !newKernelTitle) {
3516   fprintf(stderr, _("grubby: kernel title must be specified\n"));   fprintf(stderr, _("grubby: kernel title must be specified\n"));
3517   return 1;   return 1;
3518      } else if (!newKernelPath && (newKernelTitle  || newKernelInitrd ||      } else if (!newKernelPath && (newKernelTitle  || copyDefault ||
3519    newKernelInitrd || copyDefault     ||    (newKernelInitrd && !updateKernelPath)||
3520    makeDefault || extraInitrdCount > 0)) {    makeDefault || extraInitrdCount > 0)) {
3521   fprintf(stderr, _("grubby: kernel path expected\n"));   fprintf(stderr, _("grubby: kernel path expected\n"));
3522   return 1;   return 1;
# Line 2975  int main(int argc, const char ** argv) { Line 3542  int main(int argc, const char ** argv) {
3542   defaultKernel = NULL;   defaultKernel = NULL;
3543      }      }
3544    
3545      if (!strcmp(grubConfig, "-") && !outputFile) {      if (grubConfig && !strcmp(grubConfig, "-") && !outputFile) {
3546   fprintf(stderr, _("grubby: output file must be specified if stdin "   fprintf(stderr, _("grubby: output file must be specified if stdin "
3547   "is used\n"));   "is used\n"));
3548   return 1;   return 1;
# Line 2983  int main(int argc, const char ** argv) { Line 3550  int main(int argc, const char ** argv) {
3550    
3551      if (!removeKernelPath && !newKernelPath && !displayDefault && !defaultKernel      if (!removeKernelPath && !newKernelPath && !displayDefault && !defaultKernel
3552   && !kernelInfo && !bootloaderProbe && !updateKernelPath   && !kernelInfo && !bootloaderProbe && !updateKernelPath
3553          && !removeMBKernel) {          && !removeMBKernel && !displayDefaultIndex && !displayDefaultTitle) {
3554   fprintf(stderr, _("grubby: no action specified\n"));   fprintf(stderr, _("grubby: no action specified\n"));
3555   return 1;   return 1;
3556      }      }
# Line 3010  int main(int argc, const char ** argv) { Line 3577  int main(int argc, const char ** argv) {
3577      }      }
3578    
3579      if (bootloaderProbe) {      if (bootloaderProbe) {
3580   int lrc = 0, grc = 0, erc = 0;   int lrc = 0, grc = 0, gr2c = 0, erc = 0;
3581   struct grubConfig * lconfig, * gconfig;   struct grubConfig * lconfig, * gconfig;
3582    
3583   if (!access(grubConfigType.defaultConfig, F_OK)) {   const char *grub2config = grub2FindConfig(&grub2ConfigType);
3584      gconfig = readConfig(grubConfigType.defaultConfig, &grubConfigType);   if (grub2config) {
3585        gconfig = readConfig(grub2config, &grub2ConfigType);
3586        if (!gconfig)
3587     gr2c = 1;
3588        else
3589     gr2c = checkForGrub2(gconfig);
3590     }
3591    
3592     const char *grubconfig = grubFindConfig(&grubConfigType);
3593     if (!access(grubconfig, F_OK)) {
3594        gconfig = readConfig(grubconfig, &grubConfigType);
3595      if (!gconfig)      if (!gconfig)
3596   grc = 1;   grc = 1;
3597      else      else
# Line 3037  int main(int argc, const char ** argv) { Line 3614  int main(int argc, const char ** argv) {
3614   erc = checkForExtLinux(lconfig);   erc = checkForExtLinux(lconfig);
3615   }   }
3616    
3617   if (lrc == 1 || grc == 1) return 1;   if (lrc == 1 || grc == 1 || gr2c == 1) return 1;
3618    
3619   if (lrc == 2) printf("lilo\n");   if (lrc == 2) printf("lilo\n");
3620     if (gr2c == 2) printf("grub2\n");
3621   if (grc == 2) printf("grub\n");   if (grc == 2) printf("grub\n");
3622   if (erc == 2) printf("extlinux\n");   if (erc == 2) printf("extlinux\n");
3623    
# Line 3067  int main(int argc, const char ** argv) { Line 3645  int main(int argc, const char ** argv) {
3645                 ((rootspec != NULL) ? strlen(rootspec) : 0));                 ((rootspec != NULL) ? strlen(rootspec) : 0));
3646    
3647   return 0;   return 0;
3648    
3649        } else if (displayDefaultTitle) {
3650     struct singleLine * line;
3651     struct singleEntry * entry;
3652    
3653     if (config->defaultImage == -1) return 0;
3654     entry = findEntryByIndex(config, config->defaultImage);
3655     if (!entry) return 0;
3656    
3657     if (!configureGrub2) {
3658      line = getLineByType(LT_TITLE, entry->lines);
3659      if (!line) return 0;
3660      printf("%s\n", line->elements[1].item);
3661    
3662     } else {
3663      char * title;
3664    
3665      dbgPrintf("This is GRUB2, default title is embeded in menuentry\n");
3666      line = getLineByType(LT_MENUENTRY, entry->lines);
3667      if (!line) return 0;
3668      title = grub2ExtractTitle(line);
3669      if (title)
3670        printf("%s\n", title);
3671     }
3672     return 0;
3673    
3674        } else if (displayDefaultIndex) {
3675            if (config->defaultImage == -1) return 0;
3676            printf("%i\n", config->defaultImage);
3677    
3678      } else if (kernelInfo)      } else if (kernelInfo)
3679   return displayInfo(config, kernelInfo, bootPrefix);   return displayInfo(config, kernelInfo, bootPrefix);
3680    
# Line 3082  int main(int argc, const char ** argv) { Line 3690  int main(int argc, const char ** argv) {
3690      setFallbackImage(config, newKernelPath != NULL);      setFallbackImage(config, newKernelPath != NULL);
3691      if (updateImage(config, updateKernelPath, bootPrefix, newKernelArgs,      if (updateImage(config, updateKernelPath, bootPrefix, newKernelArgs,
3692                      removeArgs, newMBKernelArgs, removeMBKernelArgs)) return 1;                      removeArgs, newMBKernelArgs, removeMBKernelArgs)) return 1;
3693        if (updateKernelPath && newKernelInitrd) {
3694                if (updateInitrd(config, updateKernelPath, bootPrefix,
3695                                 newKernelInitrd)) return 1;
3696        }
3697      if (addNewKernel(config, template, bootPrefix, newKernelPath,      if (addNewKernel(config, template, bootPrefix, newKernelPath,
3698                       newKernelTitle, newKernelArgs, newKernelInitrd,                       newKernelTitle, newKernelArgs, newKernelInitrd,
3699                       extraInitrds, extraInitrdCount,                       extraInitrds, extraInitrdCount,
# Line 3095  int main(int argc, const char ** argv) { Line 3707  int main(int argc, const char ** argv) {
3707      }      }
3708    
3709      if (!outputFile)      if (!outputFile)
3710   outputFile = grubConfig;   outputFile = (char *)grubConfig;
3711    
3712      return writeConfig(config, outputFile, bootPrefix);      return writeConfig(config, outputFile, bootPrefix);
3713  }  }

Legend:
Removed from v.920  
changed lines
  Added in v.1746