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 1745 by niro, Sat Feb 18 01:05:52 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    struct configFileInfo grub2ConfigType = {
245        .findConfig = grub2FindConfig,
246        .keywords = grub2Keywords,
247        .defaultIsIndex = 1,
248        .defaultSupportSaved = 0,
249        .defaultIsVariable = 1,
250        .entryStart = LT_MENUENTRY,
251        .entryEnd = LT_ENTRY_END,
252        .titlePosition = 1,
253        .needsBootPrefix = 1,
254        .mbHyperFirst = 1,
255        .mbInitRdIsModule = 1,
256        .mbAllowExtraInitRds = 1,
257  };  };
258    
259  struct keywordTypes yabootKeywords[] = {  struct keywordTypes yabootKeywords[] = {
# Line 249  struct keywordTypes extlinuxKeywords[] = Line 351  struct keywordTypes extlinuxKeywords[] =
351  };  };
352  int useextlinuxmenu;  int useextlinuxmenu;
353  struct configFileInfo eliloConfigType = {  struct configFileInfo eliloConfigType = {
354      "/boot/efi/EFI/redhat/elilo.conf",    /* defaultConfig */      .defaultConfig = "/boot/efi/EFI/redhat/elilo.conf",
355      eliloKeywords,    /* keywords */      .keywords = eliloKeywords,
356      0,    /* defaultIsIndex */      .entryStart = LT_KERNEL,
357      0,    /* defaultSupportSaved */      .needsBootPrefix = 1,
358      LT_KERNEL,    /* entrySeparator */      .argsInQuotes = 1,
359      1,                    /* needsBootPrefix */      .mbConcatArgs = 1,
     1,    /* argsInQuotes */  
     0,    /* maxTitleLength */  
     0,                                      /* titleBracketed */  
     0,                                      /* mbHyperFirst */  
     0,                                      /* mbInitRdIsModule */  
     1,                                      /* mbConcatArgs */  
     0,                                      /* mbAllowExtraInitRds */  
360  };  };
361    
362  struct configFileInfo liloConfigType = {  struct configFileInfo liloConfigType = {
363      "/etc/lilo.conf",    /* defaultConfig */      .defaultConfig = "/etc/lilo.conf",
364      liloKeywords,    /* keywords */      .keywords = liloKeywords,
365      0,    /* defaultIsIndex */      .entryStart = LT_KERNEL,
366      0,    /* defaultSupportSaved */      .argsInQuotes = 1,
367      LT_KERNEL,    /* entrySeparator */      .maxTitleLength = 15,
     0,    /* needsBootPrefix */  
     1,    /* argsInQuotes */  
     15,    /* maxTitleLength */  
     0,                                      /* titleBracketed */  
     0,                                      /* mbHyperFirst */  
     0,                                      /* mbInitRdIsModule */  
     0,                                      /* mbConcatArgs */  
     0,                                      /* mbAllowExtraInitRds */  
368  };  };
369    
370  struct configFileInfo yabootConfigType = {  struct configFileInfo yabootConfigType = {
371      "/etc/yaboot.conf",    /* defaultConfig */      .defaultConfig = "/etc/yaboot.conf",
372      yabootKeywords,    /* keywords */      .keywords = yabootKeywords,
373      0,    /* defaultIsIndex */      .entryStart = LT_KERNEL,
374      0,    /* defaultSupportSaved */      .needsBootPrefix = 1,
375      LT_KERNEL,    /* entrySeparator */      .argsInQuotes = 1,
376      1,    /* needsBootPrefix */      .maxTitleLength = 15,
377      1,    /* argsInQuotes */      .mbAllowExtraInitRds = 1,
     15,    /* maxTitleLength */  
     0,                                      /* titleBracketed */  
     0,                                      /* mbHyperFirst */  
     0,                                      /* mbInitRdIsModule */  
     0,                                      /* mbConcatArgs */  
     1,                                      /* mbAllowExtraInitRds */  
378  };  };
379    
380  struct configFileInfo siloConfigType = {  struct configFileInfo siloConfigType = {
381      "/etc/silo.conf",    /* defaultConfig */      .defaultConfig = "/etc/silo.conf",
382      siloKeywords,    /* keywords */      .keywords = siloKeywords,
383      0,    /* defaultIsIndex */      .entryStart = LT_KERNEL,
384      0,    /* defaultSupportSaved */      .needsBootPrefix = 1,
385      LT_KERNEL,    /* entrySeparator */      .argsInQuotes = 1,
386      1,    /* needsBootPrefix */      .maxTitleLength = 15,
     1,    /* argsInQuotes */  
     15,    /* maxTitleLength */  
     0,                                      /* titleBracketed */  
     0,                                      /* mbHyperFirst */  
     0,                                      /* mbInitRdIsModule */  
     0,                                      /* mbConcatArgs */  
     0,                                      /* mbAllowExtraInitRds */  
387  };  };
388    
389  struct configFileInfo ziplConfigType = {  struct configFileInfo ziplConfigType = {
390      "/etc/zipl.conf",    /* defaultConfig */      .defaultConfig = "/etc/zipl.conf",
391      ziplKeywords,    /* keywords */      .keywords = ziplKeywords,
392      0,    /* defaultIsIndex */      .entryStart = LT_TITLE,
393      0,    /* defaultSupportSaved */      .argsInQuotes = 1,
394      LT_TITLE,    /* entrySeparator */      .titleBracketed = 1,
     0,    /* needsBootPrefix */  
     1,    /* argsInQuotes */  
     0,    /* maxTitleLength */  
     1,                                      /* titleBracketed */  
     0,                                      /* mbHyperFirst */  
     0,                                      /* mbInitRdIsModule */  
     0,                                      /* mbConcatArgs */  
     0,                                      /* mbAllowExtraInitRds */  
395  };  };
396    
397  struct configFileInfo extlinuxConfigType = {  struct configFileInfo extlinuxConfigType = {
398      "/boot/extlinux/extlinux.conf",         /* defaultConfig */      .defaultConfig = "/boot/extlinux/extlinux.conf",
399      extlinuxKeywords,                       /* keywords */      .keywords = extlinuxKeywords,
400      0,                                      /* defaultIsIndex */      .entryStart = LT_TITLE,
401      0,                                      /* defaultSupportSaved */      .needsBootPrefix = 1,
402      LT_TITLE,                               /* entrySeparator */      .maxTitleLength = 255,
403      1,                                      /* needsBootPrefix */      .mbAllowExtraInitRds = 1,
     0,                                      /* argsInQuotes */  
     255,                                    /* maxTitleLength */  
     0,                                      /* titleBracketed */  
     0,                                      /* mbHyperFirst */  
     0,                                      /* mbInitRdIsModule */  
     0,                                      /* mbConcatArgs */  
     1,                                      /* mbAllowExtraInitRds */  
404  };  };
405    
406  struct grubConfig {  struct grubConfig {
# Line 356  struct grubConfig { Line 415  struct grubConfig {
415      struct configFileInfo * cfi;      struct configFileInfo * cfi;
416  };  };
417    
418    blkid_cache blkid;
419    
420  struct singleEntry * findEntryByIndex(struct grubConfig * cfg, int index);  struct singleEntry * findEntryByIndex(struct grubConfig * cfg, int index);
421  struct singleEntry * findEntryByPath(struct grubConfig * cfg,  struct singleEntry * findEntryByPath(struct grubConfig * cfg,
422       const char * path, const char * prefix,       const char * path, const char * prefix,
# Line 369  static int lineWrite(FILE * out, struct Line 430  static int lineWrite(FILE * out, struct
430  static int getNextLine(char ** bufPtr, struct singleLine * line,  static int getNextLine(char ** bufPtr, struct singleLine * line,
431         struct configFileInfo * cfi);         struct configFileInfo * cfi);
432  static char * getRootSpecifier(char * str);  static char * getRootSpecifier(char * str);
433    static void requote(struct singleLine *line, struct configFileInfo * cfi);
434  static void insertElement(struct singleLine * line,  static void insertElement(struct singleLine * line,
435    const char * item, int insertHere,    const char * item, int insertHere,
436    struct configFileInfo * cfi);    struct configFileInfo * cfi);
# Line 433  static struct keywordTypes * getKeywordB Line 495  static struct keywordTypes * getKeywordB
495      return NULL;      return NULL;
496  }  }
497    
498  static char * getpathbyspec(char *device) {  static char *getKeyByType(enum lineType_e type, struct configFileInfo * cfi) {
499      static blkid_cache blkid;      struct keywordTypes *kt = getKeywordByType(type, cfi);
500        if (kt)
501     return kt->key;
502        return "unknown";
503    }
504    
505    static char * getpathbyspec(char *device) {
506      if (!blkid)      if (!blkid)
507          blkid_get_cache(&blkid, NULL);          blkid_get_cache(&blkid, NULL);
508    
509      return blkid_get_devname(blkid, device, NULL);      return blkid_get_devname(blkid, device, NULL);
510  }  }
511    
512    static char * getuuidbydev(char *device) {
513        if (!blkid)
514     blkid_get_cache(&blkid, NULL);
515    
516        return blkid_get_tag_value(blkid, "UUID", device);
517    }
518    
519  static enum lineType_e getTypeByKeyword(char * keyword,  static enum lineType_e getTypeByKeyword(char * keyword,
520   struct configFileInfo * cfi) {   struct configFileInfo * cfi) {
521      struct keywordTypes * kw;      struct keywordTypes * kw;
# Line 477  static int isBracketedTitle(struct singl Line 551  static int isBracketedTitle(struct singl
551      return 0;      return 0;
552  }  }
553    
554  static int isEntrySeparator(struct singleLine * line,  static int isEntryStart(struct singleLine * line,
555                              struct configFileInfo * cfi) {                              struct configFileInfo * cfi) {
556      return line->type == cfi->entrySeparator || line->type == LT_OTHER ||      return line->type == cfi->entryStart || line->type == LT_OTHER ||
557   (cfi->titleBracketed && isBracketedTitle(line));   (cfi->titleBracketed && isBracketedTitle(line));
558  }  }
559    
# Line 802  static struct grubConfig * readConfig(co Line 876  static struct grubConfig * readConfig(co
876      cfg->secondaryIndent = strdup(line->indent);      cfg->secondaryIndent = strdup(line->indent);
877   }   }
878    
879   if (isEntrySeparator(line, cfi)) {   if (isEntryStart(line, cfi) || (cfg->entries && !sawEntry)) {
880      sawEntry = 1;      sawEntry = 1;
881      if (!entry) {      if (!entry) {
882   cfg->entries = malloc(sizeof(*entry));   cfg->entries = malloc(sizeof(*entry));
# Line 818  static struct grubConfig * readConfig(co Line 892  static struct grubConfig * readConfig(co
892      entry->next = NULL;      entry->next = NULL;
893   }   }
894    
895   if (line->type == LT_DEFAULT && line->numElements == 2) {   if (line->type == LT_SET_VARIABLE) {
896        int i;
897        dbgPrintf("found 'set' command (%d elements): ", line->numElements);
898        dbgPrintf("%s", line->indent);
899        for (i = 0; i < line->numElements; i++)
900     dbgPrintf("%s\"%s\"", line->elements[i].indent, line->elements[i].item);
901        dbgPrintf("\n");
902        struct keywordTypes *kwType = getKeywordByType(LT_DEFAULT, cfi);
903        if (kwType && line->numElements == 3 &&
904        !strcmp(line->elements[1].item, kwType->key)) {
905     dbgPrintf("Line sets default config\n");
906     cfg->flags &= ~GRUB_CONFIG_NO_DEFAULT;
907     defaultLine = line;
908        }
909     } else if (line->type == LT_DEFAULT && line->numElements == 2) {
910      cfg->flags &= ~GRUB_CONFIG_NO_DEFAULT;      cfg->flags &= ~GRUB_CONFIG_NO_DEFAULT;
911      defaultLine = line;      defaultLine = line;
912    
# Line 931  static struct grubConfig * readConfig(co Line 1019  static struct grubConfig * readConfig(co
1019   entry->lines = line;   entry->lines = line;
1020      else      else
1021   last->next = line;   last->next = line;
1022      dbgPrintf("readConfig added %d to %p\n", line->type, entry);      dbgPrintf("readConfig added %s to %p\n", getKeyByType(line->type, cfi), entry);
1023    
1024        /* we could have seen this outside of an entry... if so, we
1025         * ignore it like any other line we don't grok */
1026        if (line->type == LT_ENTRY_END && sawEntry)
1027     sawEntry = 0;
1028   } else {   } else {
1029      if (!cfg->theLines)      if (!cfg->theLines)
1030   cfg->theLines = line;   cfg->theLines = line;
1031      else      else
1032   last->next = line;   last->next = line;
1033      dbgPrintf("readConfig added %d to cfg\n", line->type);      dbgPrintf("readConfig added %s to cfg\n", getKeyByType(line->type, cfi));
1034   }   }
1035    
1036   last = line;   last = line;
# Line 945  static struct grubConfig * readConfig(co Line 1038  static struct grubConfig * readConfig(co
1038    
1039      free(incoming);      free(incoming);
1040    
1041        dbgPrintf("defaultLine is %s\n", defaultLine ? "set" : "unset");
1042      if (defaultLine) {      if (defaultLine) {
1043   if (cfi->defaultSupportSaved &&   if (cfi->defaultIsVariable) {
1044        char *value = defaultLine->elements[2].item;
1045        while (*value && (*value == '"' || *value == '\'' ||
1046        *value == ' ' || *value == '\t'))
1047     value++;
1048        cfg->defaultImage = strtol(value, &end, 10);
1049        while (*end && (*end == '"' || *end == '\'' ||
1050        *end == ' ' || *end == '\t'))
1051     end++;
1052        if (*end) cfg->defaultImage = -1;
1053     } else if (cfi->defaultSupportSaved &&
1054   !strncmp(defaultLine->elements[1].item, "saved", 5)) {   !strncmp(defaultLine->elements[1].item, "saved", 5)) {
1055      cfg->defaultImage = DEFAULT_SAVED;      cfg->defaultImage = DEFAULT_SAVED;
1056   } else if (cfi->defaultIsIndex) {   } else if (cfi->defaultIsIndex) {
# Line 995  static void writeDefault(FILE * out, cha Line 1099  static void writeDefault(FILE * out, cha
1099   fprintf(out, "%sdefault%ssaved\n", indent, separator);   fprintf(out, "%sdefault%ssaved\n", indent, separator);
1100      else if (cfg->defaultImage > -1) {      else if (cfg->defaultImage > -1) {
1101   if (cfg->cfi->defaultIsIndex) {   if (cfg->cfi->defaultIsIndex) {
1102      fprintf(out, "%sdefault%s%d\n", indent, separator,      if (cfg->cfi->defaultIsVariable) {
1103      cfg->defaultImage);          fprintf(out, "%sset default=\"%d\"\n", indent,
1104     cfg->defaultImage);
1105        } else {
1106     fprintf(out, "%sdefault%s%d\n", indent, separator,
1107     cfg->defaultImage);
1108        }
1109   } else {   } else {
1110      int image = cfg->defaultImage;      int image = cfg->defaultImage;
1111    
# Line 1086  static int writeConfig(struct grubConfig Line 1195  static int writeConfig(struct grubConfig
1195      }      }
1196    
1197      line = cfg->theLines;      line = cfg->theLines;
1198        struct keywordTypes *defaultKw = getKeywordByType(LT_DEFAULT, cfg->cfi);
1199      while (line) {      while (line) {
1200   if (line->type == LT_DEFAULT) {          if (line->type == LT_SET_VARIABLE && defaultKw &&
1201     line->numElements == 3 &&
1202     !strcmp(line->elements[1].item, defaultKw->key)) {
1203        writeDefault(out, line->indent, line->elements[0].indent, cfg);
1204        needs &= ~MAIN_DEFAULT;
1205     } else if (line->type == LT_DEFAULT) {
1206      writeDefault(out, line->indent, line->elements[0].indent, cfg);      writeDefault(out, line->indent, line->elements[0].indent, cfg);
1207      needs &= ~MAIN_DEFAULT;      needs &= ~MAIN_DEFAULT;
1208   } else if (line->type == LT_FALLBACK) {   } else if (line->type == LT_FALLBACK) {
# Line 1155  static int numEntries(struct grubConfig Line 1270  static int numEntries(struct grubConfig
1270      return i;      return i;
1271  }  }
1272    
1273    static char *findDiskForRoot()
1274    {
1275        int fd;
1276        char buf[65536];
1277        char *devname;
1278        char *chptr;
1279        int rc;
1280    
1281        if ((fd = open(_PATH_MOUNTED, O_RDONLY)) < 0) {
1282            fprintf(stderr, "grubby: failed to open %s: %s\n",
1283                    _PATH_MOUNTED, strerror(errno));
1284            return NULL;
1285        }
1286    
1287        rc = read(fd, buf, sizeof(buf) - 1);
1288        if (rc <= 0) {
1289            fprintf(stderr, "grubby: failed to read %s: %s\n",
1290                    _PATH_MOUNTED, strerror(errno));
1291            close(fd);
1292            return NULL;
1293        }
1294        close(fd);
1295        buf[rc] = '\0';
1296        chptr = buf;
1297    
1298        while (chptr && chptr != buf+rc) {
1299            devname = chptr;
1300    
1301            /*
1302             * The first column of a mtab entry is the device, but if the entry is a
1303             * special device it won't start with /, so move on to the next line.
1304             */
1305            if (*devname != '/') {
1306                chptr = strchr(chptr, '\n');
1307                if (chptr)
1308                    chptr++;
1309                continue;
1310            }
1311    
1312            /* Seek to the next space */
1313            chptr = strchr(chptr, ' ');
1314            if (!chptr) {
1315                fprintf(stderr, "grubby: error parsing %s: %s\n",
1316                        _PATH_MOUNTED, strerror(errno));
1317                return NULL;
1318            }
1319    
1320            /*
1321             * The second column of a mtab entry is the mount point, we are looking
1322             * for '/' obviously.
1323             */
1324            if (*(++chptr) == '/' && *(++chptr) == ' ') {
1325                /*
1326                 * Move back 2, which is the first space after the device name, set
1327                 * it to \0 so strdup will just get the devicename.
1328                 */
1329                chptr -= 2;
1330                *chptr = '\0';
1331                return strdup(devname);
1332            }
1333    
1334            /* Next line */
1335            chptr = strchr(chptr, '\n');
1336            if (chptr)
1337                chptr++;
1338        }
1339    
1340        return NULL;
1341    }
1342    
1343    void printEntry(struct singleEntry * entry) {
1344        int i;
1345        struct singleLine * line;
1346    
1347        for (line = entry->lines; line; line = line->next) {
1348     fprintf(stderr, "DBG: %s", line->indent);
1349     for (i = 0; i < line->numElements; i++) {
1350     fprintf(stderr, "%s%s",
1351        line->elements[i].item, line->elements[i].indent);
1352     }
1353     fprintf(stderr, "\n");
1354        }
1355    }
1356    
1357    void notSuitablePrintf(struct singleEntry * entry, const char *fmt, ...)
1358    {
1359        va_list argp;
1360    
1361        if (!debug)
1362     return;
1363    
1364        va_start(argp, fmt);
1365        fprintf(stderr, "DBG: Image entry failed: ");
1366        vfprintf(stderr, fmt, argp);
1367        printEntry(entry);
1368        va_end(argp);
1369    }
1370    
1371    #define beginswith(s, c) ((s) && (s)[0] == (c))
1372    
1373    static int endswith(const char *s, char c)
1374    {
1375     int slen;
1376    
1377     if (!s && !s[0])
1378     return 0;
1379     slen = strlen(s) - 1;
1380    
1381     return s[slen] == c;
1382    }
1383    
1384  int suitableImage(struct singleEntry * entry, const char * bootPrefix,  int suitableImage(struct singleEntry * entry, const char * bootPrefix,
1385    int skipRemoved, int flags) {    int skipRemoved, int flags) {
1386      struct singleLine * line;      struct singleLine * line;
1387      char * fullName;      char * fullName;
1388      int i;      int i;
     struct stat sb, sb2;  
1389      char * dev;      char * dev;
1390      char * rootspec;      char * rootspec;
1391        char * rootdev;
1392    
1393      if (skipRemoved && entry->skip) return 0;      if (skipRemoved && entry->skip) {
1394     notSuitablePrintf(entry, "marked to skip\n");
1395     return 0;
1396        }
1397    
1398      line = getLineByType(LT_KERNEL|LT_HYPER, entry->lines);      line = getLineByType(LT_KERNEL|LT_HYPER, entry->lines);
1399      if (!line || line->numElements < 2) return 0;      if (!line) {
1400     notSuitablePrintf(entry, "no line found\n");
1401     return 0;
1402        }
1403        if (line->numElements < 2) {
1404     notSuitablePrintf(entry, "line has only %d elements\n",
1405        line->numElements);
1406     return 0;
1407        }
1408    
1409      if (flags & GRUBBY_BADIMAGE_OKAY) return 1;      if (flags & GRUBBY_BADIMAGE_OKAY) return 1;
1410    
1411      fullName = alloca(strlen(bootPrefix) +      fullName = alloca(strlen(bootPrefix) +
1412        strlen(line->elements[1].item) + 1);        strlen(line->elements[1].item) + 1);
1413      rootspec = getRootSpecifier(line->elements[1].item);      rootspec = getRootSpecifier(line->elements[1].item);
1414      sprintf(fullName, "%s%s", bootPrefix,      int rootspec_offset = rootspec ? strlen(rootspec) : 0;
1415              line->elements[1].item + (rootspec ? strlen(rootspec) : 0));      int hasslash = endswith(bootPrefix, '/') ||
1416      if (access(fullName, R_OK)) return 0;       beginswith(line->elements[1].item + rootspec_offset, '/');
1417        sprintf(fullName, "%s%s%s", bootPrefix, hasslash ? "" : "/",
1418                line->elements[1].item + rootspec_offset);
1419        if (access(fullName, R_OK)) {
1420     notSuitablePrintf(entry, "access to %s failed\n", fullName);
1421     return 0;
1422        }
1423      for (i = 2; i < line->numElements; i++)      for (i = 2; i < line->numElements; i++)
1424   if (!strncasecmp(line->elements[i].item, "root=", 5)) break;   if (!strncasecmp(line->elements[i].item, "root=", 5)) break;
1425      if (i < line->numElements) {      if (i < line->numElements) {
# Line 1195  int suitableImage(struct singleEntry * e Line 1437  int suitableImage(struct singleEntry * e
1437      line = getLineByType(LT_KERNELARGS|LT_MBMODULE, entry->lines);      line = getLineByType(LT_KERNELARGS|LT_MBMODULE, entry->lines);
1438    
1439              /* failed to find one */              /* failed to find one */
1440              if (!line) return 0;              if (!line) {
1441     notSuitablePrintf(entry, "no line found\n");
1442     return 0;
1443                }
1444    
1445      for (i = 1; i < line->numElements; i++)      for (i = 1; i < line->numElements; i++)
1446          if (!strncasecmp(line->elements[i].item, "root=", 5)) break;          if (!strncasecmp(line->elements[i].item, "root=", 5)) break;
1447      if (i < line->numElements)      if (i < line->numElements)
1448          dev = line->elements[i].item + 5;          dev = line->elements[i].item + 5;
1449      else {      else {
1450     notSuitablePrintf(entry, "no root= entry found\n");
1451   /* it failed too...  can't find root= */   /* it failed too...  can't find root= */
1452          return 0;          return 0;
1453              }              }
# Line 1209  int suitableImage(struct singleEntry * e Line 1455  int suitableImage(struct singleEntry * e
1455      }      }
1456    
1457      dev = getpathbyspec(dev);      dev = getpathbyspec(dev);
1458      if (!dev)      if (!getpathbyspec(dev)) {
1459            notSuitablePrintf(entry, "can't find blkid entry for %s\n", dev);
1460          return 0;          return 0;
1461        } else
1462     dev = getpathbyspec(dev);
1463    
1464      i = stat(dev, &sb);      rootdev = findDiskForRoot();
1465      if (i)      if (!rootdev) {
1466            notSuitablePrintf(entry, "can't find root device\n");
1467   return 0;   return 0;
1468        }
1469    
1470      stat("/", &sb2);      if (!getuuidbydev(rootdev) || !getuuidbydev(dev)) {
1471            notSuitablePrintf(entry, "uuid missing: rootdev %s, dev %s\n",
1472     getuuidbydev(rootdev), getuuidbydev(dev));
1473            free(rootdev);
1474            return 0;
1475        }
1476    
1477      if (sb.st_rdev != sb2.st_dev)      if (strcmp(getuuidbydev(rootdev), getuuidbydev(dev))) {
1478            notSuitablePrintf(entry, "uuid mismatch: rootdev %s, dev %s\n",
1479     getuuidbydev(rootdev), getuuidbydev(dev));
1480     free(rootdev);
1481          return 0;          return 0;
1482        }
1483    
1484        free(rootdev);
1485    
1486      return 1;      return 1;
1487  }  }
# Line 1733  struct singleLine *  addLine(struct sing Line 1995  struct singleLine *  addLine(struct sing
1995   sprintf(tmpl.elements[0].item, "[%s]", val);   sprintf(tmpl.elements[0].item, "[%s]", val);
1996   tmpl.elements[0].indent = "";   tmpl.elements[0].indent = "";
1997   val = NULL;   val = NULL;
1998        } else if (type == LT_MENUENTRY) {
1999     char *lineend = "--class gnu-linux --class gnu --class os {";
2000     if (!val) {
2001        fprintf(stderr, "Line type LT_MENUENTRY requires a value\n");
2002        abort();
2003     }
2004     kw = getKeywordByType(type, cfi);
2005     if (!kw) {
2006        fprintf(stderr, "Looking up keyword for unknown type %d\n", type);
2007        abort();
2008     }
2009     tmpl.indent = "";
2010     tmpl.type = type;
2011     tmpl.numElements = 3;
2012     tmpl.elements = alloca(sizeof(*tmpl.elements) * tmpl.numElements);
2013     tmpl.elements[0].item = kw->key;
2014     tmpl.elements[0].indent = alloca(2);
2015     sprintf(tmpl.elements[0].indent, "%c", kw->nextChar);
2016     tmpl.elements[1].item = (char *)val;
2017     tmpl.elements[1].indent = alloca(2);
2018     sprintf(tmpl.elements[1].indent, "%c", kw->nextChar);
2019     tmpl.elements[2].item = alloca(strlen(lineend)+1);
2020     strcpy(tmpl.elements[2].item, lineend);
2021     tmpl.elements[2].indent = "";
2022      } else {      } else {
2023   kw = getKeywordByType(type, cfi);   kw = getKeywordByType(type, cfi);
2024   if (!kw) abort();   if (!kw) {
2025        fprintf(stderr, "Looking up keyword for unknown type %d\n", type);
2026        abort();
2027     }
2028   tmpl.type = type;   tmpl.type = type;
2029   tmpl.numElements = val ? 2 : 1;   tmpl.numElements = val ? 2 : 1;
2030   tmpl.elements = alloca(sizeof(*tmpl.elements) * tmpl.numElements);   tmpl.elements = alloca(sizeof(*tmpl.elements) * tmpl.numElements);
# Line 1759  struct singleLine *  addLine(struct sing Line 2048  struct singleLine *  addLine(struct sing
2048   if (!line->next && !prev) prev = line;   if (!line->next && !prev) prev = line;
2049      }      }
2050    
2051      if (prev == entry->lines)      struct singleLine *menuEntry;
2052   tmpl.indent = defaultIndent ?: "";      menuEntry = getLineByType(LT_MENUENTRY, entry->lines);
2053      else      if (tmpl.type == LT_ENTRY_END) {
2054   tmpl.indent = prev->indent;   if (menuEntry)
2055        tmpl.indent = menuEntry->indent;
2056     else
2057        tmpl.indent = defaultIndent ?: "";
2058        } else if (tmpl.type != LT_MENUENTRY) {
2059     if (menuEntry)
2060        tmpl.indent = "\t";
2061     else if (prev == entry->lines)
2062        tmpl.indent = defaultIndent ?: "";
2063     else
2064        tmpl.indent = prev->indent;
2065        }
2066    
2067      return addLineTmpl(entry, &tmpl, prev, val, cfi);      return addLineTmpl(entry, &tmpl, prev, val, cfi);
2068  }  }
# Line 1789  void removeLine(struct singleEntry * ent Line 2089  void removeLine(struct singleEntry * ent
2089      free(line);      free(line);
2090  }  }
2091    
2092    static int isquote(char q)
2093    {
2094        if (q == '\'' || q == '\"')
2095     return 1;
2096        return 0;
2097    }
2098    
2099    static void requote(struct singleLine *tmplLine, struct configFileInfo * cfi)
2100    {
2101        struct singleLine newLine = {
2102     .indent = tmplLine->indent,
2103     .type = tmplLine->type,
2104     .next = tmplLine->next,
2105        };
2106        int firstQuotedItem = -1;
2107        int quoteLen = 0;
2108        int j;
2109        int element = 0;
2110        char *c;
2111    
2112        c = malloc(strlen(tmplLine->elements[0].item) + 1);
2113        strcpy(c, tmplLine->elements[0].item);
2114        insertElement(&newLine, c, element++, cfi);
2115        free(c);
2116        c = NULL;
2117    
2118        for (j = 1; j < tmplLine->numElements; j++) {
2119     if (firstQuotedItem == -1) {
2120        quoteLen += strlen(tmplLine->elements[j].item);
2121        
2122        if (isquote(tmplLine->elements[j].item[0])) {
2123     firstQuotedItem = j;
2124            quoteLen += strlen(tmplLine->elements[j].indent);
2125        } else {
2126     c = malloc(quoteLen + 1);
2127     strcpy(c, tmplLine->elements[j].item);
2128     insertElement(&newLine, c, element++, cfi);
2129     free(c);
2130     quoteLen = 0;
2131        }
2132     } else {
2133        int itemlen = strlen(tmplLine->elements[j].item);
2134        quoteLen += itemlen;
2135        quoteLen += strlen(tmplLine->elements[j].indent);
2136        
2137        if (isquote(tmplLine->elements[j].item[itemlen - 1])) {
2138     c = malloc(quoteLen + 1);
2139     c[0] = '\0';
2140     for (int i = firstQuotedItem; i < j+1; i++) {
2141        strcat(c, tmplLine->elements[i].item);
2142        strcat(c, tmplLine->elements[i].indent);
2143     }
2144     insertElement(&newLine, c, element++, cfi);
2145     free(c);
2146    
2147     firstQuotedItem = -1;
2148     quoteLen = 0;
2149        }
2150     }
2151        }
2152        while (tmplLine->numElements)
2153     removeElement(tmplLine, 0);
2154        if (tmplLine->elements)
2155     free(tmplLine->elements);
2156    
2157        tmplLine->numElements = newLine.numElements;
2158        tmplLine->elements = newLine.elements;
2159    }
2160    
2161  static void insertElement(struct singleLine * line,  static void insertElement(struct singleLine * line,
2162    const char * item, int insertHere,    const char * item, int insertHere,
2163    struct configFileInfo * cfi)    struct configFileInfo * cfi)
# Line 1895  int updateActualImage(struct grubConfig Line 2264  int updateActualImage(struct grubConfig
2264      const char ** arg;      const char ** arg;
2265      int useKernelArgs, useRoot;      int useKernelArgs, useRoot;
2266      int firstElement;      int firstElement;
2267      int *usedElements, *usedArgs;      int *usedElements;
2268      int doreplace;      int doreplace;
2269    
2270      if (!image) return 0;      if (!image) return 0;
# Line 1930  int updateActualImage(struct grubConfig Line 2299  int updateActualImage(struct grubConfig
2299      useRoot = (getKeywordByType(LT_ROOT, cfg->cfi)      useRoot = (getKeywordByType(LT_ROOT, cfg->cfi)
2300         && !multibootArgs);         && !multibootArgs);
2301    
     for (k = 0, arg = newArgs; *arg; arg++, k++) ;  
     usedArgs = calloc(k, sizeof(*usedArgs));  
   
2302      for (; (entry = findEntryByPath(cfg, image, prefix, &index)); index++) {      for (; (entry = findEntryByPath(cfg, image, prefix, &index)); index++) {
2303    
2304   if (multibootArgs && !entry->multiboot)   if (multibootArgs && !entry->multiboot)
# Line 2008  int updateActualImage(struct grubConfig Line 2374  int updateActualImage(struct grubConfig
2374          usedElements = calloc(line->numElements, sizeof(*usedElements));          usedElements = calloc(line->numElements, sizeof(*usedElements));
2375    
2376   for (k = 0, arg = newArgs; *arg; arg++, k++) {   for (k = 0, arg = newArgs; *arg; arg++, k++) {
             if (usedArgs[k]) continue;  
2377    
2378      doreplace = 1;      doreplace = 1;
2379      for (i = firstElement; i < line->numElements; i++) {      for (i = firstElement; i < line->numElements; i++) {
# Line 2023  int updateActualImage(struct grubConfig Line 2388  int updateActualImage(struct grubConfig
2388                      continue;                      continue;
2389   if (!argMatch(line->elements[i].item, *arg)) {   if (!argMatch(line->elements[i].item, *arg)) {
2390                      usedElements[i]=1;                      usedElements[i]=1;
                     usedArgs[k]=1;  
2391      break;      break;
2392                  }                  }
2393              }              }
# Line 2093  int updateActualImage(struct grubConfig Line 2457  int updateActualImage(struct grubConfig
2457   }   }
2458      }      }
2459    
     free(usedArgs);  
2460      free(newArgs);      free(newArgs);
2461      free(oldArgs);      free(oldArgs);
2462    
# Line 2119  int updateImage(struct grubConfig * cfg, Line 2482  int updateImage(struct grubConfig * cfg,
2482      return rc;      return rc;
2483  }  }
2484    
2485    int updateInitrd(struct grubConfig * cfg, const char * image,
2486                     const char * prefix, const char * initrd) {
2487        struct singleEntry * entry;
2488        struct singleLine * line, * kernelLine, *endLine = NULL;
2489        int index = 0;
2490    
2491        if (!image) return 0;
2492    
2493        for (; (entry = findEntryByPath(cfg, image, prefix, &index)); index++) {
2494            kernelLine = getLineByType(LT_KERNEL, entry->lines);
2495            if (!kernelLine) continue;
2496    
2497            line = getLineByType(LT_INITRD, entry->lines);
2498            if (line)
2499                removeLine(entry, line);
2500            if (prefix) {
2501                int prefixLen = strlen(prefix);
2502                if (!strncmp(initrd, prefix, prefixLen))
2503                    initrd += prefixLen;
2504            }
2505     endLine = getLineByType(LT_ENTRY_END, entry->lines);
2506     if (endLine)
2507        removeLine(entry, endLine);
2508            line = addLine(entry, cfg->cfi, LT_INITRD, kernelLine->indent, initrd);
2509            if (!line)
2510        return 1;
2511     if (endLine) {
2512        line = addLine(entry, cfg->cfi, LT_ENTRY_END, "", NULL);
2513                if (!line)
2514     return 1;
2515     }
2516    
2517            break;
2518        }
2519    
2520        return 0;
2521    }
2522    
2523  int checkDeviceBootloader(const char * device, const unsigned char * boot) {  int checkDeviceBootloader(const char * device, const unsigned char * boot) {
2524      int fd;      int fd;
2525      unsigned char bootSect[512];      unsigned char bootSect[512];
# Line 2142  int checkDeviceBootloader(const char * d Line 2543  int checkDeviceBootloader(const char * d
2543      if (memcmp(boot, bootSect, 3))      if (memcmp(boot, bootSect, 3))
2544   return 0;   return 0;
2545    
2546      if (boot[1] == 0xeb) {      if (boot[1] == JMP_SHORT_OPCODE) {
2547   offset = boot[2] + 2;   offset = boot[2] + 2;
2548      } else if (boot[1] == 0xe8 || boot[1] == 0xe9) {      } else if (boot[1] == 0xe8 || boot[1] == 0xe9) {
2549   offset = (boot[3] << 8) + boot[2] + 2;   offset = (boot[3] << 8) + boot[2] + 2;
2550      } else if (boot[0] == 0xeb) {      } else if (boot[0] == JMP_SHORT_OPCODE) {
2551   offset = boot[1] + 2;        offset = boot[1] + 2;
2552            /*
2553     * it looks like grub, when copying stage1 into the mbr, patches stage1
2554     * right after the JMP location, replacing other instructions such as
2555     * JMPs for NOOPs. So, relax the check a little bit by skipping those
2556     * different bytes.
2557     */
2558          if ((bootSect[offset + 1] == NOOP_OPCODE)
2559      && (bootSect[offset + 2] == NOOP_OPCODE)) {
2560     offset = offset + 3;
2561          }
2562      } else if (boot[0] == 0xe8 || boot[0] == 0xe9) {      } else if (boot[0] == 0xe8 || boot[0] == 0xe9) {
2563   offset = (boot[2] << 8) + boot[1] + 2;   offset = (boot[2] << 8) + boot[1] + 2;
2564      } else {      } else {
# Line 2289  int checkForLilo(struct grubConfig * con Line 2700  int checkForLilo(struct grubConfig * con
2700      return checkDeviceBootloader(line->elements[1].item, boot);      return checkDeviceBootloader(line->elements[1].item, boot);
2701  }  }
2702    
2703    int checkForGrub2(struct grubConfig * config) {
2704        if (!access("/etc/grub.d/", R_OK))
2705     return 2;
2706    
2707        return 1;
2708    }
2709    
2710  int checkForGrub(struct grubConfig * config) {  int checkForGrub(struct grubConfig * config) {
2711      int fd;      int fd;
2712      unsigned char bootSect[512];      unsigned char bootSect[512];
# Line 2464  int addNewKernel(struct grubConfig * con Line 2882  int addNewKernel(struct grubConfig * con
2882      if (*chptr == '#') continue;      if (*chptr == '#') continue;
2883    
2884      if (tmplLine->type == LT_KERNEL &&      if (tmplLine->type == LT_KERNEL &&
2885   tmplLine->numElements >= 2) {      tmplLine->numElements >= 2) {
2886   if (!template->multiboot && (needs & NEED_MB)) {   if (!template->multiboot && (needs & NEED_MB)) {
2887      /* it's not a multiboot template and this is the kernel      /* it's not a multiboot template and this is the kernel
2888       * line.  Try to be intelligent about inserting the       * line.  Try to be intelligent about inserting the
# Line 2590  int addNewKernel(struct grubConfig * con Line 3008  int addNewKernel(struct grubConfig * con
3008      needs &= ~NEED_INITRD;      needs &= ~NEED_INITRD;
3009   }   }
3010    
3011        } else if (tmplLine->type == LT_MENUENTRY &&
3012           (needs & NEED_TITLE)) {
3013     requote(tmplLine, config->cfi);
3014     char *nkt = malloc(strlen(newKernelTitle)+3);
3015     strcpy(nkt, "'");
3016     strcat(nkt, newKernelTitle);
3017     strcat(nkt, "'");
3018     newLine = addLineTmpl(new, tmplLine, newLine, nkt, config->cfi);
3019     free(nkt);
3020     needs &= ~NEED_TITLE;
3021      } else if (tmplLine->type == LT_TITLE &&      } else if (tmplLine->type == LT_TITLE &&
3022         (needs & NEED_TITLE)) {         (needs & NEED_TITLE)) {
3023   if (tmplLine->numElements >= 2) {   if (tmplLine->numElements >= 2) {
# Line 2603  int addNewKernel(struct grubConfig * con Line 3031  int addNewKernel(struct grubConfig * con
3031        tmplLine->indent, newKernelTitle);        tmplLine->indent, newKernelTitle);
3032      needs &= ~NEED_TITLE;      needs &= ~NEED_TITLE;
3033   }   }
3034        } else if (tmplLine->type == LT_ECHO) {
3035        requote(tmplLine, config->cfi);
3036        static const char *prefix = "'Loading ";
3037        if (tmplLine->numElements > 1 &&
3038        strstr(tmplLine->elements[1].item, prefix) &&
3039        masterLine->next && masterLine->next->type == LT_KERNEL) {
3040     char *newTitle = malloc(strlen(prefix) +
3041     strlen(newKernelTitle) + 2);
3042    
3043     strcpy(newTitle, prefix);
3044     strcat(newTitle, newKernelTitle);
3045     strcat(newTitle, "'");
3046     newLine = addLine(new, config->cfi, LT_ECHO,
3047     tmplLine->indent, newTitle);
3048     free(newTitle);
3049        } else {
3050     /* pass through other lines from the template */
3051     newLine = addLineTmpl(new, tmplLine, newLine, NULL,
3052     config->cfi);
3053        }
3054      } else {      } else {
3055   /* pass through other lines from the template */   /* pass through other lines from the template */
3056   newLine = addLineTmpl(new, tmplLine, newLine, NULL, config->cfi);   newLine = addLineTmpl(new, tmplLine, newLine, NULL, config->cfi);
# Line 2614  int addNewKernel(struct grubConfig * con Line 3061  int addNewKernel(struct grubConfig * con
3061   /* don't have a template, so start the entry with the   /* don't have a template, so start the entry with the
3062   * appropriate starting line   * appropriate starting line
3063   */   */
3064   switch (config->cfi->entrySeparator) {   switch (config->cfi->entryStart) {
3065      case LT_KERNEL:      case LT_KERNEL:
3066   if (new->multiboot && config->cfi->mbHyperFirst) {   if (new->multiboot && config->cfi->mbHyperFirst) {
3067      /* fall through to LT_HYPER */      /* fall through to LT_HYPER */
# Line 2633  int addNewKernel(struct grubConfig * con Line 3080  int addNewKernel(struct grubConfig * con
3080   needs &= ~NEED_MB;   needs &= ~NEED_MB;
3081   break;   break;
3082    
3083        case LT_MENUENTRY: {
3084     char *nkt = malloc(strlen(newKernelTitle)+3);
3085     strcpy(nkt, "'");
3086     strcat(nkt, newKernelTitle);
3087     strcat(nkt, "'");
3088            newLine = addLine(new, config->cfi, LT_MENUENTRY,
3089      config->primaryIndent, nkt);
3090     free(nkt);
3091     needs &= ~NEED_TITLE;
3092     needs |= NEED_END;
3093     break;
3094        }
3095      case LT_TITLE:      case LT_TITLE:
3096   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)
3097   char * templabel;   char * templabel;
# Line 2666  int addNewKernel(struct grubConfig * con Line 3125  int addNewKernel(struct grubConfig * con
3125    
3126      /* add the remainder of the lines, i.e. those that either      /* add the remainder of the lines, i.e. those that either
3127       * 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,
3128       * all the lines following the entrySeparator.       * all the lines following the entryStart.
3129       */       */
3130      if (needs & NEED_TITLE) {      if (needs & NEED_TITLE) {
3131   newLine = addLine(new, config->cfi, LT_TITLE,   newLine = addLine(new, config->cfi, LT_TITLE,
# Line 2707  int addNewKernel(struct grubConfig * con Line 3166  int addNewKernel(struct grubConfig * con
3166   free(initrdVal);   free(initrdVal);
3167   needs &= ~NEED_INITRD;   needs &= ~NEED_INITRD;
3168      }      }
3169        if (needs & NEED_END) {
3170     newLine = addLine(new, config->cfi, LT_ENTRY_END,
3171     config->secondaryIndent, NULL);
3172     needs &= ~NEED_END;
3173        }
3174    
3175      if (needs) {      if (needs) {
3176   printf(_("grubby: needs=%d, aborting\n"), needs);   printf(_("grubby: needs=%d, aborting\n"), needs);
# Line 2736  static void traceback(int signum) Line 3200  static void traceback(int signum)
3200    
3201  int main(int argc, const char ** argv) {  int main(int argc, const char ** argv) {
3202      poptContext optCon;      poptContext optCon;
3203      char * grubConfig = NULL;      const char * grubConfig = NULL;
3204      char * outputFile = NULL;      char * outputFile = NULL;
3205      int arg = 0;      int arg = 0;
3206      int flags = 0;      int flags = 0;
3207      int badImageOkay = 0;      int badImageOkay = 0;
3208        int configureGrub2 = 0;
3209      int configureLilo = 0, configureELilo = 0, configureGrub = 0;      int configureLilo = 0, configureELilo = 0, configureGrub = 0;
3210      int configureYaboot = 0, configureSilo = 0, configureZipl = 0;      int configureYaboot = 0, configureSilo = 0, configureZipl = 0;
3211      int configureExtLinux = 0;      int configureExtLinux = 0;
# Line 2768  int main(int argc, const char ** argv) { Line 3233  int main(int argc, const char ** argv) {
3233      struct singleEntry * template = NULL;      struct singleEntry * template = NULL;
3234      int copyDefault = 0, makeDefault = 0;      int copyDefault = 0, makeDefault = 0;
3235      int displayDefault = 0;      int displayDefault = 0;
3236        int displayDefaultIndex = 0;
3237        int displayDefaultTitle = 0;
3238      struct poptOption options[] = {      struct poptOption options[] = {
3239   { "add-kernel", 0, POPT_ARG_STRING, &newKernelPath, 0,   { "add-kernel", 0, POPT_ARG_STRING, &newKernelPath, 0,
3240      _("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 3265  int main(int argc, const char ** argv) {
3265        "the kernel referenced by the default image does not exist, "        "the kernel referenced by the default image does not exist, "
3266        "the first linux entry whose kernel does exist is used as the "        "the first linux entry whose kernel does exist is used as the "
3267        "template"), NULL },        "template"), NULL },
3268     { "debug", 0, 0, &debug, 0,
3269        _("print debugging information for failures") },
3270   { "default-kernel", 0, 0, &displayDefault, 0,   { "default-kernel", 0, 0, &displayDefault, 0,
3271      _("display the path of the default kernel") },      _("display the path of the default kernel") },
3272     { "default-index", 0, 0, &displayDefaultIndex, 0,
3273        _("display the index of the default kernel") },
3274     { "default-title", 0, 0, &displayDefaultTitle, 0,
3275        _("display the title of the default kernel") },
3276   { "elilo", 0, POPT_ARG_NONE, &configureELilo, 0,   { "elilo", 0, POPT_ARG_NONE, &configureELilo, 0,
3277      _("configure elilo bootloader") },      _("configure elilo bootloader") },
3278   { "extlinux", 0, POPT_ARG_NONE, &configureExtLinux, 0,   { "extlinux", 0, POPT_ARG_NONE, &configureExtLinux, 0,
3279      _("configure extlinux bootloader (from syslinux)") },      _("configure extlinux bootloader (from syslinux)") },
3280   { "grub", 0, POPT_ARG_NONE, &configureGrub, 0,   { "grub", 0, POPT_ARG_NONE, &configureGrub, 0,
3281      _("configure grub bootloader") },      _("configure grub bootloader") },
3282     { "grub2", 0, POPT_ARG_NONE, &configureGrub2, 0,
3283        _("configure grub2 bootloader") },
3284   { "info", 0, POPT_ARG_STRING, &kernelInfo, 0,   { "info", 0, POPT_ARG_STRING, &kernelInfo, 0,
3285      _("display boot information for specified kernel"),      _("display boot information for specified kernel"),
3286      _("kernel-path") },      _("kernel-path") },
# Line 2885  int main(int argc, const char ** argv) { Line 3360  int main(int argc, const char ** argv) {
3360   return 1;   return 1;
3361      }      }
3362    
3363      if ((configureLilo + configureGrub + configureELilo +      if ((configureLilo + configureGrub2 + configureGrub + configureELilo +
3364   configureYaboot + configureSilo + configureZipl +   configureYaboot + configureSilo + configureZipl +
3365   configureExtLinux ) > 1) {   configureExtLinux ) > 1) {
3366   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 3369  int main(int argc, const char ** argv) {
3369   fprintf(stderr,   fprintf(stderr,
3370      _("grubby: cannot specify config file with --bootloader-probe\n"));      _("grubby: cannot specify config file with --bootloader-probe\n"));
3371   return 1;   return 1;
3372        } else if (configureGrub2) {
3373     cfi = &grub2ConfigType;
3374      } else if (configureLilo) {      } else if (configureLilo) {
3375   cfi = &liloConfigType;   cfi = &liloConfigType;
3376      } else if (configureGrub) {      } else if (configureGrub) {
# Line 2923  int main(int argc, const char ** argv) { Line 3400  int main(int argc, const char ** argv) {
3400        #elif __s390x__        #elif __s390x__
3401          cfi = &ziplConfigtype;          cfi = &ziplConfigtype;
3402        #else        #else
3403   cfi = &grubConfigType;          if (grub2FindConfig(&grub2ConfigType))
3404        cfi = &grub2ConfigType;
3405     else
3406        cfi = &grubConfigType;
3407        #endif        #endif
3408      }      }
3409    
3410      if (!grubConfig)      if (!grubConfig) {
3411   grubConfig = cfi->defaultConfig;   if (cfi->findConfig)
3412        grubConfig = cfi->findConfig(cfi);
3413     if (!grubConfig)
3414        grubConfig = cfi->defaultConfig;
3415        }
3416    
3417      if (bootloaderProbe && (displayDefault || kernelInfo || newKernelVersion ||      if (bootloaderProbe && (displayDefault || kernelInfo || newKernelVersion ||
3418    newKernelPath || removeKernelPath || makeDefault ||    newKernelPath || removeKernelPath || makeDefault ||
3419    defaultKernel)) {    defaultKernel || displayDefaultIndex || displayDefaultTitle)) {
3420   fprintf(stderr, _("grubby: --bootloader-probe may not be used with "   fprintf(stderr, _("grubby: --bootloader-probe may not be used with "
3421    "specified option"));    "specified option"));
3422   return 1;   return 1;
# Line 2948  int main(int argc, const char ** argv) { Line 3432  int main(int argc, const char ** argv) {
3432      if (newKernelPath && !newKernelTitle) {      if (newKernelPath && !newKernelTitle) {
3433   fprintf(stderr, _("grubby: kernel title must be specified\n"));   fprintf(stderr, _("grubby: kernel title must be specified\n"));
3434   return 1;   return 1;
3435      } else if (!newKernelPath && (newKernelTitle  || newKernelInitrd ||      } else if (!newKernelPath && (newKernelTitle  || copyDefault ||
3436    newKernelInitrd || copyDefault     ||    (newKernelInitrd && !updateKernelPath)||
3437    makeDefault || extraInitrdCount > 0)) {    makeDefault || extraInitrdCount > 0)) {
3438   fprintf(stderr, _("grubby: kernel path expected\n"));   fprintf(stderr, _("grubby: kernel path expected\n"));
3439   return 1;   return 1;
# Line 2975  int main(int argc, const char ** argv) { Line 3459  int main(int argc, const char ** argv) {
3459   defaultKernel = NULL;   defaultKernel = NULL;
3460      }      }
3461    
3462      if (!strcmp(grubConfig, "-") && !outputFile) {      if (grubConfig && !strcmp(grubConfig, "-") && !outputFile) {
3463   fprintf(stderr, _("grubby: output file must be specified if stdin "   fprintf(stderr, _("grubby: output file must be specified if stdin "
3464   "is used\n"));   "is used\n"));
3465   return 1;   return 1;
# Line 2983  int main(int argc, const char ** argv) { Line 3467  int main(int argc, const char ** argv) {
3467    
3468      if (!removeKernelPath && !newKernelPath && !displayDefault && !defaultKernel      if (!removeKernelPath && !newKernelPath && !displayDefault && !defaultKernel
3469   && !kernelInfo && !bootloaderProbe && !updateKernelPath   && !kernelInfo && !bootloaderProbe && !updateKernelPath
3470          && !removeMBKernel) {          && !removeMBKernel && !displayDefaultIndex && !displayDefaultTitle) {
3471   fprintf(stderr, _("grubby: no action specified\n"));   fprintf(stderr, _("grubby: no action specified\n"));
3472   return 1;   return 1;
3473      }      }
# Line 3010  int main(int argc, const char ** argv) { Line 3494  int main(int argc, const char ** argv) {
3494      }      }
3495    
3496      if (bootloaderProbe) {      if (bootloaderProbe) {
3497   int lrc = 0, grc = 0, erc = 0;   int lrc = 0, grc = 0, gr2c = 0, erc = 0;
3498   struct grubConfig * lconfig, * gconfig;   struct grubConfig * lconfig, * gconfig;
3499    
3500   if (!access(grubConfigType.defaultConfig, F_OK)) {   const char *grub2config = grub2FindConfig(&grub2ConfigType);
3501      gconfig = readConfig(grubConfigType.defaultConfig, &grubConfigType);   if (grub2config) {
3502        gconfig = readConfig(grub2config, &grub2ConfigType);
3503        if (!gconfig)
3504     gr2c = 1;
3505        else
3506     gr2c = checkForGrub2(gconfig);
3507     }
3508    
3509     const char *grubconfig = grubFindConfig(&grubConfigType);
3510     if (!access(grubconfig, F_OK)) {
3511        gconfig = readConfig(grubconfig, &grubConfigType);
3512      if (!gconfig)      if (!gconfig)
3513   grc = 1;   grc = 1;
3514      else      else
# Line 3037  int main(int argc, const char ** argv) { Line 3531  int main(int argc, const char ** argv) {
3531   erc = checkForExtLinux(lconfig);   erc = checkForExtLinux(lconfig);
3532   }   }
3533    
3534   if (lrc == 1 || grc == 1) return 1;   if (lrc == 1 || grc == 1 || gr2c == 1) return 1;
3535    
3536   if (lrc == 2) printf("lilo\n");   if (lrc == 2) printf("lilo\n");
3537     if (gr2c == 2) printf("grub2\n");
3538   if (grc == 2) printf("grub\n");   if (grc == 2) printf("grub\n");
3539   if (erc == 2) printf("extlinux\n");   if (erc == 2) printf("extlinux\n");
3540    
# Line 3067  int main(int argc, const char ** argv) { Line 3562  int main(int argc, const char ** argv) {
3562                 ((rootspec != NULL) ? strlen(rootspec) : 0));                 ((rootspec != NULL) ? strlen(rootspec) : 0));
3563    
3564   return 0;   return 0;
3565    
3566        } else if (displayDefaultTitle) {
3567     struct singleLine * line;
3568     struct singleEntry * entry;
3569    
3570     if (config->defaultImage == -1) return 0;
3571     entry = findEntryByIndex(config, config->defaultImage);
3572     if (!entry) return 0;
3573    
3574     if (!configureGrub2) {
3575      line = getLineByType(LT_TITLE, entry->lines);
3576      if (!line) return 0;
3577      printf("%s\n", line->elements[1].item);
3578    
3579     } else {
3580      int i;
3581      size_t len;
3582      char * start;
3583      char * tmp;
3584    
3585      dbgPrintf("This is GRUB2, default title is embeded in menuentry\n");
3586      line = getLineByType(LT_MENUENTRY, entry->lines);
3587      if (!line) return 0;
3588    
3589      for (i = 0; i < line->numElements; i++) {
3590    
3591        if (!strcmp(line->elements[i].item, "menuentry"))
3592          continue;
3593    
3594        if (*line->elements[i].item == '\'')
3595          start = line->elements[i].item + 1;
3596        else
3597          start = line->elements[i].item;
3598    
3599        len = strlen(start);
3600        if (*(start + len - 1) == '\'') {
3601          tmp = strdup(start);
3602          *(tmp + len - 1) = '\0';
3603          printf("%s", tmp);
3604          free(tmp);
3605          break;
3606        } else {
3607          printf("%s ", start);
3608        }
3609      }
3610      printf("\n");
3611     }
3612     return 0;
3613    
3614        } else if (displayDefaultIndex) {
3615            if (config->defaultImage == -1) return 0;
3616            printf("%i\n", config->defaultImage);
3617    
3618      } else if (kernelInfo)      } else if (kernelInfo)
3619   return displayInfo(config, kernelInfo, bootPrefix);   return displayInfo(config, kernelInfo, bootPrefix);
3620    
# Line 3082  int main(int argc, const char ** argv) { Line 3630  int main(int argc, const char ** argv) {
3630      setFallbackImage(config, newKernelPath != NULL);      setFallbackImage(config, newKernelPath != NULL);
3631      if (updateImage(config, updateKernelPath, bootPrefix, newKernelArgs,      if (updateImage(config, updateKernelPath, bootPrefix, newKernelArgs,
3632                      removeArgs, newMBKernelArgs, removeMBKernelArgs)) return 1;                      removeArgs, newMBKernelArgs, removeMBKernelArgs)) return 1;
3633        if (updateKernelPath && newKernelInitrd) {
3634                if (updateInitrd(config, updateKernelPath, bootPrefix,
3635                                 newKernelInitrd)) return 1;
3636        }
3637      if (addNewKernel(config, template, bootPrefix, newKernelPath,      if (addNewKernel(config, template, bootPrefix, newKernelPath,
3638                       newKernelTitle, newKernelArgs, newKernelInitrd,                       newKernelTitle, newKernelArgs, newKernelInitrd,
3639                       extraInitrds, extraInitrdCount,                       extraInitrds, extraInitrdCount,
# Line 3095  int main(int argc, const char ** argv) { Line 3647  int main(int argc, const char ** argv) {
3647      }      }
3648    
3649      if (!outputFile)      if (!outputFile)
3650   outputFile = grubConfig;   outputFile = (char *)grubConfig;
3651    
3652      return writeConfig(config, outputFile, bootPrefix);      return writeConfig(config, outputFile, bootPrefix);
3653  }  }

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