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 1750 by niro, Sat Feb 18 01:09:51 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
117    #define DEFAULT_SAVED_GRUB2 -3
118    
119  struct keywordTypes {  struct keywordTypes {
120      char * key;      char * key;
# Line 110  struct keywordTypes { Line 123  struct keywordTypes {
123      char separatorChar;      char separatorChar;
124  };  };
125    
126    struct configFileInfo;
127    
128    typedef const char *(*findConfigFunc)(struct configFileInfo *);
129    typedef const int (*writeLineFunc)(struct configFileInfo *,
130     struct singleLine *line);
131    
132  struct configFileInfo {  struct configFileInfo {
133      char * defaultConfig;      char * defaultConfig;
134        findConfigFunc findConfig;
135        writeLineFunc writeLine;
136      struct keywordTypes * keywords;      struct keywordTypes * keywords;
137      int defaultIsIndex;      int defaultIsIndex;
138        int defaultIsVariable;
139      int defaultSupportSaved;      int defaultSupportSaved;
140      enum lineType_e entrySeparator;      enum lineType_e entryStart;
141        enum lineType_e entryEnd;
142      int needsBootPrefix;      int needsBootPrefix;
143      int argsInQuotes;      int argsInQuotes;
144      int maxTitleLength;      int maxTitleLength;
145      int titleBracketed;      int titleBracketed;
146        int titlePosition;
147      int mbHyperFirst;      int mbHyperFirst;
148      int mbInitRdIsModule;      int mbInitRdIsModule;
149      int mbConcatArgs;      int mbConcatArgs;
# Line 138  struct keywordTypes grubKeywords[] = { Line 162  struct keywordTypes grubKeywords[] = {
162      { NULL,    0, 0 },      { NULL,    0, 0 },
163  };  };
164    
165    const char *grubFindConfig(struct configFileInfo *cfi) {
166        static const char *configFiles[] = {
167     "/etc/grub.conf",
168     "/boot/grub/grub.conf",
169     "/boot/grub/menu.lst",
170     NULL
171        };
172        static int i = -1;
173    
174        if (i == -1) {
175     for (i = 0; configFiles[i] != NULL; i++) {
176        dbgPrintf("Checking \"%s\": ", configFiles[i]);
177        if (!access(configFiles[i], R_OK)) {
178     dbgPrintf("found\n");
179     return configFiles[i];
180        }
181        dbgPrintf("not found\n");
182     }
183        }
184        return configFiles[i];
185    }
186    
187  struct configFileInfo grubConfigType = {  struct configFileInfo grubConfigType = {
188      "/boot/grub/grub.conf",    /* defaultConfig */      .findConfig = grubFindConfig,
189      grubKeywords,    /* keywords */      .keywords = grubKeywords,
190      1,    /* defaultIsIndex */      .defaultIsIndex = 1,
191      1,    /* defaultSupportSaved */      .defaultSupportSaved = 1,
192      LT_TITLE,    /* entrySeparator */      .entryStart = LT_TITLE,
193      1,    /* needsBootPrefix */      .needsBootPrefix = 1,
194      0,    /* argsInQuotes */      .mbHyperFirst = 1,
195      0,    /* maxTitleLength */      .mbInitRdIsModule = 1,
196      0,                                      /* titleBracketed */      .mbAllowExtraInitRds = 1,
197      1,                                      /* mbHyperFirst */  };
198      1,                                      /* mbInitRdIsModule */  
199      0,                                      /* mbConcatArgs */  struct keywordTypes grub2Keywords[] = {
200      1,                                      /* mbAllowExtraInitRds */      { "menuentry",  LT_MENUENTRY,   ' ' },
201        { "}",          LT_ENTRY_END,   ' ' },
202        { "echo",       LT_ECHO,        ' ' },
203        { "set",        LT_SET_VARIABLE,' ', '=' },
204        { "root",       LT_BOOTROOT,    ' ' },
205        { "default",    LT_DEFAULT,     ' ' },
206        { "fallback",   LT_FALLBACK,    ' ' },
207        { "linux",      LT_KERNEL,      ' ' },
208        { "initrd",     LT_INITRD,      ' ', ' ' },
209        { "module",     LT_MBMODULE,    ' ' },
210        { "kernel",     LT_HYPER,       ' ' },
211        { NULL, 0, 0 },
212    };
213    
214    const char *grub2FindConfig(struct configFileInfo *cfi) {
215        static const char *configFiles[] = {
216     "/boot/grub/grub-efi.cfg",
217     "/boot/grub/grub.cfg",
218     NULL
219        };
220        static int i = -1;
221        static const char *grub_cfg = "/boot/grub/grub.cfg";
222    
223        if (i == -1) {
224     for (i = 0; configFiles[i] != NULL; i++) {
225        dbgPrintf("Checking \"%s\": ", configFiles[i]);
226        if (!access(configFiles[i], R_OK)) {
227     dbgPrintf("found\n");
228     return configFiles[i];
229        }
230     }
231        }
232    
233        /* Ubuntu renames grub2 to grub, so check for the grub.d directory
234         * that isn't in grub1, and if it exists, return the config file path
235         * that they use. */
236        if (configFiles[i] == NULL && !access("/etc/grub.d/", R_OK)) {
237     dbgPrintf("found\n");
238     return grub_cfg;
239        }
240    
241        dbgPrintf("not found\n");
242        return configFiles[i];
243    }
244    
245    int sizeOfSingleLine(struct singleLine * line) {
246      int i;
247      int count = 0;
248    
249      for (i = 0; i < line->numElements; i++) {
250        int indentSize = 0;
251    
252        count = count + strlen(line->elements[i].item);
253    
254        indentSize = strlen(line->elements[i].indent);
255        if (indentSize > 0)
256          count = count + indentSize;
257        else
258          /* be extra safe and add room for whitespaces */
259          count = count + 1;
260      }
261    
262      /* room for trailing terminator */
263      count = count + 1;
264    
265      return count;
266    }
267    
268    char *grub2ExtractTitle(struct singleLine * line) {
269        char * current;
270        char * current_indent;
271        int current_len;
272        int current_indent_len;
273        int i;
274    
275        /* bail out if line does not start with menuentry */
276        if (strcmp(line->elements[0].item, "menuentry"))
277          return NULL;
278    
279        i = 1;
280        current = line->elements[i].item;
281        current_len = strlen(current);
282    
283        /* if second word is quoted, strip the quotes and return single word */
284        if ((*current == '\'') && (*(current + current_len - 1) == '\'')) {
285          char *tmp;
286    
287          tmp = strdup(current);
288          *(tmp + current_len - 1) = '\0';
289          return ++tmp;
290        }
291    
292        /* if no quotes, return second word verbatim */
293        if (*current != '\'') {
294          return current;
295        }
296    
297        /* second element start with a quote, so we have to find the element
298         * whose last character is also quote (assuming it's the closing one) */
299        if (*current == '\'') {
300          int resultMaxSize;
301          char * result;
302    
303          resultMaxSize = sizeOfSingleLine(line);
304          result = malloc(resultMaxSize);
305          snprintf(result, resultMaxSize, "%s", ++current);
306    
307          i++;
308          for (; i < line->numElements; ++i) {
309     current = line->elements[i].item;
310     current_len = strlen(current);
311     current_indent = line->elements[i].indent;
312     current_indent_len = strlen(current_indent);
313    
314     strncat(result, current_indent, current_indent_len);
315     if (*(current + current_len - 1) != '\'') {
316      strncat(result, current, current_len);
317     } else {
318      strncat(result, current, current_len - 1);
319      break;
320     }
321          }
322          return result;
323        }
324    
325        return NULL;
326    }
327    
328    struct configFileInfo grub2ConfigType = {
329        .findConfig = grub2FindConfig,
330        .keywords = grub2Keywords,
331        .defaultIsIndex = 1,
332        .defaultSupportSaved = 1,
333        .defaultIsVariable = 1,
334        .entryStart = LT_MENUENTRY,
335        .entryEnd = LT_ENTRY_END,
336        .titlePosition = 1,
337        .needsBootPrefix = 1,
338        .mbHyperFirst = 1,
339        .mbInitRdIsModule = 1,
340        .mbAllowExtraInitRds = 1,
341  };  };
342    
343  struct keywordTypes yabootKeywords[] = {  struct keywordTypes yabootKeywords[] = {
# Line 249  struct keywordTypes extlinuxKeywords[] = Line 435  struct keywordTypes extlinuxKeywords[] =
435  };  };
436  int useextlinuxmenu;  int useextlinuxmenu;
437  struct configFileInfo eliloConfigType = {  struct configFileInfo eliloConfigType = {
438      "/boot/efi/EFI/redhat/elilo.conf",    /* defaultConfig */      .defaultConfig = "/boot/efi/EFI/redhat/elilo.conf",
439      eliloKeywords,    /* keywords */      .keywords = eliloKeywords,
440      0,    /* defaultIsIndex */      .entryStart = LT_KERNEL,
441      0,    /* defaultSupportSaved */      .needsBootPrefix = 1,
442      LT_KERNEL,    /* entrySeparator */      .argsInQuotes = 1,
443      1,                    /* needsBootPrefix */      .mbConcatArgs = 1,
     1,    /* argsInQuotes */  
     0,    /* maxTitleLength */  
     0,                                      /* titleBracketed */  
     0,                                      /* mbHyperFirst */  
     0,                                      /* mbInitRdIsModule */  
     1,                                      /* mbConcatArgs */  
     0,                                      /* mbAllowExtraInitRds */  
444  };  };
445    
446  struct configFileInfo liloConfigType = {  struct configFileInfo liloConfigType = {
447      "/etc/lilo.conf",    /* defaultConfig */      .defaultConfig = "/etc/lilo.conf",
448      liloKeywords,    /* keywords */      .keywords = liloKeywords,
449      0,    /* defaultIsIndex */      .entryStart = LT_KERNEL,
450      0,    /* defaultSupportSaved */      .argsInQuotes = 1,
451      LT_KERNEL,    /* entrySeparator */      .maxTitleLength = 15,
     0,    /* needsBootPrefix */  
     1,    /* argsInQuotes */  
     15,    /* maxTitleLength */  
     0,                                      /* titleBracketed */  
     0,                                      /* mbHyperFirst */  
     0,                                      /* mbInitRdIsModule */  
     0,                                      /* mbConcatArgs */  
     0,                                      /* mbAllowExtraInitRds */  
452  };  };
453    
454  struct configFileInfo yabootConfigType = {  struct configFileInfo yabootConfigType = {
455      "/etc/yaboot.conf",    /* defaultConfig */      .defaultConfig = "/etc/yaboot.conf",
456      yabootKeywords,    /* keywords */      .keywords = yabootKeywords,
457      0,    /* defaultIsIndex */      .entryStart = LT_KERNEL,
458      0,    /* defaultSupportSaved */      .needsBootPrefix = 1,
459      LT_KERNEL,    /* entrySeparator */      .argsInQuotes = 1,
460      1,    /* needsBootPrefix */      .maxTitleLength = 15,
461      1,    /* argsInQuotes */      .mbAllowExtraInitRds = 1,
     15,    /* maxTitleLength */  
     0,                                      /* titleBracketed */  
     0,                                      /* mbHyperFirst */  
     0,                                      /* mbInitRdIsModule */  
     0,                                      /* mbConcatArgs */  
     1,                                      /* mbAllowExtraInitRds */  
462  };  };
463    
464  struct configFileInfo siloConfigType = {  struct configFileInfo siloConfigType = {
465      "/etc/silo.conf",    /* defaultConfig */      .defaultConfig = "/etc/silo.conf",
466      siloKeywords,    /* keywords */      .keywords = siloKeywords,
467      0,    /* defaultIsIndex */      .entryStart = LT_KERNEL,
468      0,    /* defaultSupportSaved */      .needsBootPrefix = 1,
469      LT_KERNEL,    /* entrySeparator */      .argsInQuotes = 1,
470      1,    /* needsBootPrefix */      .maxTitleLength = 15,
     1,    /* argsInQuotes */  
     15,    /* maxTitleLength */  
     0,                                      /* titleBracketed */  
     0,                                      /* mbHyperFirst */  
     0,                                      /* mbInitRdIsModule */  
     0,                                      /* mbConcatArgs */  
     0,                                      /* mbAllowExtraInitRds */  
471  };  };
472    
473  struct configFileInfo ziplConfigType = {  struct configFileInfo ziplConfigType = {
474      "/etc/zipl.conf",    /* defaultConfig */      .defaultConfig = "/etc/zipl.conf",
475      ziplKeywords,    /* keywords */      .keywords = ziplKeywords,
476      0,    /* defaultIsIndex */      .entryStart = LT_TITLE,
477      0,    /* defaultSupportSaved */      .argsInQuotes = 1,
478      LT_TITLE,    /* entrySeparator */      .titleBracketed = 1,
     0,    /* needsBootPrefix */  
     1,    /* argsInQuotes */  
     0,    /* maxTitleLength */  
     1,                                      /* titleBracketed */  
     0,                                      /* mbHyperFirst */  
     0,                                      /* mbInitRdIsModule */  
     0,                                      /* mbConcatArgs */  
     0,                                      /* mbAllowExtraInitRds */  
479  };  };
480    
481  struct configFileInfo extlinuxConfigType = {  struct configFileInfo extlinuxConfigType = {
482      "/boot/extlinux/extlinux.conf",         /* defaultConfig */      .defaultConfig = "/boot/extlinux/extlinux.conf",
483      extlinuxKeywords,                       /* keywords */      .keywords = extlinuxKeywords,
484      0,                                      /* defaultIsIndex */      .entryStart = LT_TITLE,
485      0,                                      /* defaultSupportSaved */      .needsBootPrefix = 1,
486      LT_TITLE,                               /* entrySeparator */      .maxTitleLength = 255,
487      1,                                      /* needsBootPrefix */      .mbAllowExtraInitRds = 1,
     0,                                      /* argsInQuotes */  
     255,                                    /* maxTitleLength */  
     0,                                      /* titleBracketed */  
     0,                                      /* mbHyperFirst */  
     0,                                      /* mbInitRdIsModule */  
     0,                                      /* mbConcatArgs */  
     1,                                      /* mbAllowExtraInitRds */  
488  };  };
489    
490  struct grubConfig {  struct grubConfig {
# Line 356  struct grubConfig { Line 499  struct grubConfig {
499      struct configFileInfo * cfi;      struct configFileInfo * cfi;
500  };  };
501    
502    blkid_cache blkid;
503    
504  struct singleEntry * findEntryByIndex(struct grubConfig * cfg, int index);  struct singleEntry * findEntryByIndex(struct grubConfig * cfg, int index);
505  struct singleEntry * findEntryByPath(struct grubConfig * cfg,  struct singleEntry * findEntryByPath(struct grubConfig * cfg,
506       const char * path, const char * prefix,       const char * path, const char * prefix,
# Line 369  static int lineWrite(FILE * out, struct Line 514  static int lineWrite(FILE * out, struct
514  static int getNextLine(char ** bufPtr, struct singleLine * line,  static int getNextLine(char ** bufPtr, struct singleLine * line,
515         struct configFileInfo * cfi);         struct configFileInfo * cfi);
516  static char * getRootSpecifier(char * str);  static char * getRootSpecifier(char * str);
517    static void requote(struct singleLine *line, struct configFileInfo * cfi);
518  static void insertElement(struct singleLine * line,  static void insertElement(struct singleLine * line,
519    const char * item, int insertHere,    const char * item, int insertHere,
520    struct configFileInfo * cfi);    struct configFileInfo * cfi);
# Line 433  static struct keywordTypes * getKeywordB Line 579  static struct keywordTypes * getKeywordB
579      return NULL;      return NULL;
580  }  }
581    
582  static char * getpathbyspec(char *device) {  static char *getKeyByType(enum lineType_e type, struct configFileInfo * cfi) {
583      static blkid_cache blkid;      struct keywordTypes *kt = getKeywordByType(type, cfi);
584        if (kt)
585     return kt->key;
586        return "unknown";
587    }
588    
589    static char * getpathbyspec(char *device) {
590      if (!blkid)      if (!blkid)
591          blkid_get_cache(&blkid, NULL);          blkid_get_cache(&blkid, NULL);
592    
593      return blkid_get_devname(blkid, device, NULL);      return blkid_get_devname(blkid, device, NULL);
594  }  }
595    
596    static char * getuuidbydev(char *device) {
597        if (!blkid)
598     blkid_get_cache(&blkid, NULL);
599    
600        return blkid_get_tag_value(blkid, "UUID", device);
601    }
602    
603  static enum lineType_e getTypeByKeyword(char * keyword,  static enum lineType_e getTypeByKeyword(char * keyword,
604   struct configFileInfo * cfi) {   struct configFileInfo * cfi) {
605      struct keywordTypes * kw;      struct keywordTypes * kw;
# Line 477  static int isBracketedTitle(struct singl Line 635  static int isBracketedTitle(struct singl
635      return 0;      return 0;
636  }  }
637    
638  static int isEntrySeparator(struct singleLine * line,  static int isEntryStart(struct singleLine * line,
639                              struct configFileInfo * cfi) {                              struct configFileInfo * cfi) {
640      return line->type == cfi->entrySeparator || line->type == LT_OTHER ||      return line->type == cfi->entryStart || line->type == LT_OTHER ||
641   (cfi->titleBracketed && isBracketedTitle(line));   (cfi->titleBracketed && isBracketedTitle(line));
642  }  }
643    
# Line 802  static struct grubConfig * readConfig(co Line 960  static struct grubConfig * readConfig(co
960      cfg->secondaryIndent = strdup(line->indent);      cfg->secondaryIndent = strdup(line->indent);
961   }   }
962    
963   if (isEntrySeparator(line, cfi)) {   if (isEntryStart(line, cfi) || (cfg->entries && !sawEntry)) {
964      sawEntry = 1;      sawEntry = 1;
965      if (!entry) {      if (!entry) {
966   cfg->entries = malloc(sizeof(*entry));   cfg->entries = malloc(sizeof(*entry));
# Line 818  static struct grubConfig * readConfig(co Line 976  static struct grubConfig * readConfig(co
976      entry->next = NULL;      entry->next = NULL;
977   }   }
978    
979   if (line->type == LT_DEFAULT && line->numElements == 2) {   if (line->type == LT_SET_VARIABLE) {
980        int i;
981        dbgPrintf("found 'set' command (%d elements): ", line->numElements);
982        dbgPrintf("%s", line->indent);
983        for (i = 0; i < line->numElements; i++)
984     dbgPrintf("%s\"%s\"", line->elements[i].indent, line->elements[i].item);
985        dbgPrintf("\n");
986        struct keywordTypes *kwType = getKeywordByType(LT_DEFAULT, cfi);
987        if (kwType && line->numElements == 3 &&
988        !strcmp(line->elements[1].item, kwType->key)) {
989     dbgPrintf("Line sets default config\n");
990     cfg->flags &= ~GRUB_CONFIG_NO_DEFAULT;
991     defaultLine = line;
992        }
993     } else if (line->type == LT_DEFAULT && line->numElements == 2) {
994      cfg->flags &= ~GRUB_CONFIG_NO_DEFAULT;      cfg->flags &= ~GRUB_CONFIG_NO_DEFAULT;
995      defaultLine = line;      defaultLine = line;
996    
# Line 931  static struct grubConfig * readConfig(co Line 1103  static struct grubConfig * readConfig(co
1103   entry->lines = line;   entry->lines = line;
1104      else      else
1105   last->next = line;   last->next = line;
1106      dbgPrintf("readConfig added %d to %p\n", line->type, entry);      dbgPrintf("readConfig added %s to %p\n", getKeyByType(line->type, cfi), entry);
1107    
1108        /* we could have seen this outside of an entry... if so, we
1109         * ignore it like any other line we don't grok */
1110        if (line->type == LT_ENTRY_END && sawEntry)
1111     sawEntry = 0;
1112   } else {   } else {
1113      if (!cfg->theLines)      if (!cfg->theLines)
1114   cfg->theLines = line;   cfg->theLines = line;
1115      else      else
1116   last->next = line;   last->next = line;
1117      dbgPrintf("readConfig added %d to cfg\n", line->type);      dbgPrintf("readConfig added %s to cfg\n", getKeyByType(line->type, cfi));
1118   }   }
1119    
1120   last = line;   last = line;
# Line 945  static struct grubConfig * readConfig(co Line 1122  static struct grubConfig * readConfig(co
1122    
1123      free(incoming);      free(incoming);
1124    
1125        dbgPrintf("defaultLine is %s\n", defaultLine ? "set" : "unset");
1126      if (defaultLine) {      if (defaultLine) {
1127   if (cfi->defaultSupportSaved &&          if (defaultLine->numElements > 2 &&
1128        cfi->defaultSupportSaved &&
1129        !strncmp(defaultLine->elements[2].item,"\"${saved_entry}\"", 16)) {
1130        cfg->defaultImage = DEFAULT_SAVED_GRUB2;
1131     } else if (cfi->defaultIsVariable) {
1132        char *value = defaultLine->elements[2].item;
1133        while (*value && (*value == '"' || *value == '\'' ||
1134        *value == ' ' || *value == '\t'))
1135     value++;
1136        cfg->defaultImage = strtol(value, &end, 10);
1137        while (*end && (*end == '"' || *end == '\'' ||
1138        *end == ' ' || *end == '\t'))
1139     end++;
1140        if (*end) cfg->defaultImage = -1;
1141     } else if (cfi->defaultSupportSaved &&
1142   !strncmp(defaultLine->elements[1].item, "saved", 5)) {   !strncmp(defaultLine->elements[1].item, "saved", 5)) {
1143      cfg->defaultImage = DEFAULT_SAVED;      cfg->defaultImage = DEFAULT_SAVED;
1144   } else if (cfi->defaultIsIndex) {   } else if (cfi->defaultIsIndex) {
# Line 993  static void writeDefault(FILE * out, cha Line 1185  static void writeDefault(FILE * out, cha
1185    
1186      if (cfg->defaultImage == DEFAULT_SAVED)      if (cfg->defaultImage == DEFAULT_SAVED)
1187   fprintf(out, "%sdefault%ssaved\n", indent, separator);   fprintf(out, "%sdefault%ssaved\n", indent, separator);
1188        else if (cfg->defaultImage == DEFAULT_SAVED_GRUB2)
1189     fprintf(out, "%sset default=\"${saved_entry}\"\n", indent);
1190      else if (cfg->defaultImage > -1) {      else if (cfg->defaultImage > -1) {
1191   if (cfg->cfi->defaultIsIndex) {   if (cfg->cfi->defaultIsIndex) {
1192      fprintf(out, "%sdefault%s%d\n", indent, separator,      if (cfg->cfi->defaultIsVariable) {
1193      cfg->defaultImage);          fprintf(out, "%sset default=\"%d\"\n", indent,
1194     cfg->defaultImage);
1195        } else {
1196     fprintf(out, "%sdefault%s%d\n", indent, separator,
1197     cfg->defaultImage);
1198        }
1199   } else {   } else {
1200      int image = cfg->defaultImage;      int image = cfg->defaultImage;
1201    
# Line 1086  static int writeConfig(struct grubConfig Line 1285  static int writeConfig(struct grubConfig
1285      }      }
1286    
1287      line = cfg->theLines;      line = cfg->theLines;
1288        struct keywordTypes *defaultKw = getKeywordByType(LT_DEFAULT, cfg->cfi);
1289      while (line) {      while (line) {
1290   if (line->type == LT_DEFAULT) {          if (line->type == LT_SET_VARIABLE && defaultKw &&
1291     line->numElements == 3 &&
1292     !strcmp(line->elements[1].item, defaultKw->key)) {
1293        writeDefault(out, line->indent, line->elements[0].indent, cfg);
1294        needs &= ~MAIN_DEFAULT;
1295     } else if (line->type == LT_DEFAULT) {
1296      writeDefault(out, line->indent, line->elements[0].indent, cfg);      writeDefault(out, line->indent, line->elements[0].indent, cfg);
1297      needs &= ~MAIN_DEFAULT;      needs &= ~MAIN_DEFAULT;
1298   } else if (line->type == LT_FALLBACK) {   } else if (line->type == LT_FALLBACK) {
# Line 1155  static int numEntries(struct grubConfig Line 1360  static int numEntries(struct grubConfig
1360      return i;      return i;
1361  }  }
1362    
1363    static char *findDiskForRoot()
1364    {
1365        int fd;
1366        char buf[65536];
1367        char *devname;
1368        char *chptr;
1369        int rc;
1370    
1371        if ((fd = open(_PATH_MOUNTED, O_RDONLY)) < 0) {
1372            fprintf(stderr, "grubby: failed to open %s: %s\n",
1373                    _PATH_MOUNTED, strerror(errno));
1374            return NULL;
1375        }
1376    
1377        rc = read(fd, buf, sizeof(buf) - 1);
1378        if (rc <= 0) {
1379            fprintf(stderr, "grubby: failed to read %s: %s\n",
1380                    _PATH_MOUNTED, strerror(errno));
1381            close(fd);
1382            return NULL;
1383        }
1384        close(fd);
1385        buf[rc] = '\0';
1386        chptr = buf;
1387    
1388        while (chptr && chptr != buf+rc) {
1389            devname = chptr;
1390    
1391            /*
1392             * The first column of a mtab entry is the device, but if the entry is a
1393             * special device it won't start with /, so move on to the next line.
1394             */
1395            if (*devname != '/') {
1396                chptr = strchr(chptr, '\n');
1397                if (chptr)
1398                    chptr++;
1399                continue;
1400            }
1401    
1402            /* Seek to the next space */
1403            chptr = strchr(chptr, ' ');
1404            if (!chptr) {
1405                fprintf(stderr, "grubby: error parsing %s: %s\n",
1406                        _PATH_MOUNTED, strerror(errno));
1407                return NULL;
1408            }
1409    
1410            /*
1411             * The second column of a mtab entry is the mount point, we are looking
1412             * for '/' obviously.
1413             */
1414            if (*(++chptr) == '/' && *(++chptr) == ' ') {
1415                /*
1416                 * Move back 2, which is the first space after the device name, set
1417                 * it to \0 so strdup will just get the devicename.
1418                 */
1419                chptr -= 2;
1420                *chptr = '\0';
1421                return strdup(devname);
1422            }
1423    
1424            /* Next line */
1425            chptr = strchr(chptr, '\n');
1426            if (chptr)
1427                chptr++;
1428        }
1429    
1430        return NULL;
1431    }
1432    
1433    void printEntry(struct singleEntry * entry) {
1434        int i;
1435        struct singleLine * line;
1436    
1437        for (line = entry->lines; line; line = line->next) {
1438     fprintf(stderr, "DBG: %s", line->indent);
1439     for (i = 0; i < line->numElements; i++) {
1440     fprintf(stderr, "%s%s",
1441        line->elements[i].item, line->elements[i].indent);
1442     }
1443     fprintf(stderr, "\n");
1444        }
1445    }
1446    
1447    void notSuitablePrintf(struct singleEntry * entry, const char *fmt, ...)
1448    {
1449        va_list argp;
1450    
1451        if (!debug)
1452     return;
1453    
1454        va_start(argp, fmt);
1455        fprintf(stderr, "DBG: Image entry failed: ");
1456        vfprintf(stderr, fmt, argp);
1457        printEntry(entry);
1458        va_end(argp);
1459    }
1460    
1461    #define beginswith(s, c) ((s) && (s)[0] == (c))
1462    
1463    static int endswith(const char *s, char c)
1464    {
1465     int slen;
1466    
1467     if (!s || !s[0])
1468     return 0;
1469     slen = strlen(s) - 1;
1470    
1471     return s[slen] == c;
1472    }
1473    
1474  int suitableImage(struct singleEntry * entry, const char * bootPrefix,  int suitableImage(struct singleEntry * entry, const char * bootPrefix,
1475    int skipRemoved, int flags) {    int skipRemoved, int flags) {
1476      struct singleLine * line;      struct singleLine * line;
1477      char * fullName;      char * fullName;
1478      int i;      int i;
     struct stat sb, sb2;  
1479      char * dev;      char * dev;
1480      char * rootspec;      char * rootspec;
1481        char * rootdev;
1482    
1483      if (skipRemoved && entry->skip) return 0;      if (skipRemoved && entry->skip) {
1484     notSuitablePrintf(entry, "marked to skip\n");
1485     return 0;
1486        }
1487    
1488      line = getLineByType(LT_KERNEL|LT_HYPER, entry->lines);      line = getLineByType(LT_KERNEL|LT_HYPER, entry->lines);
1489      if (!line || line->numElements < 2) return 0;      if (!line) {
1490     notSuitablePrintf(entry, "no line found\n");
1491     return 0;
1492        }
1493        if (line->numElements < 2) {
1494     notSuitablePrintf(entry, "line has only %d elements\n",
1495        line->numElements);
1496     return 0;
1497        }
1498    
1499      if (flags & GRUBBY_BADIMAGE_OKAY) return 1;      if (flags & GRUBBY_BADIMAGE_OKAY) return 1;
1500    
1501      fullName = alloca(strlen(bootPrefix) +      fullName = alloca(strlen(bootPrefix) +
1502        strlen(line->elements[1].item) + 1);        strlen(line->elements[1].item) + 1);
1503      rootspec = getRootSpecifier(line->elements[1].item);      rootspec = getRootSpecifier(line->elements[1].item);
1504      sprintf(fullName, "%s%s", bootPrefix,      int rootspec_offset = rootspec ? strlen(rootspec) : 0;
1505              line->elements[1].item + (rootspec ? strlen(rootspec) : 0));      int hasslash = endswith(bootPrefix, '/') ||
1506      if (access(fullName, R_OK)) return 0;       beginswith(line->elements[1].item + rootspec_offset, '/');
1507        sprintf(fullName, "%s%s%s", bootPrefix, hasslash ? "" : "/",
1508                line->elements[1].item + rootspec_offset);
1509        if (access(fullName, R_OK)) {
1510     notSuitablePrintf(entry, "access to %s failed\n", fullName);
1511     return 0;
1512        }
1513      for (i = 2; i < line->numElements; i++)      for (i = 2; i < line->numElements; i++)
1514   if (!strncasecmp(line->elements[i].item, "root=", 5)) break;   if (!strncasecmp(line->elements[i].item, "root=", 5)) break;
1515      if (i < line->numElements) {      if (i < line->numElements) {
# Line 1195  int suitableImage(struct singleEntry * e Line 1527  int suitableImage(struct singleEntry * e
1527      line = getLineByType(LT_KERNELARGS|LT_MBMODULE, entry->lines);      line = getLineByType(LT_KERNELARGS|LT_MBMODULE, entry->lines);
1528    
1529              /* failed to find one */              /* failed to find one */
1530              if (!line) return 0;              if (!line) {
1531     notSuitablePrintf(entry, "no line found\n");
1532     return 0;
1533                }
1534    
1535      for (i = 1; i < line->numElements; i++)      for (i = 1; i < line->numElements; i++)
1536          if (!strncasecmp(line->elements[i].item, "root=", 5)) break;          if (!strncasecmp(line->elements[i].item, "root=", 5)) break;
1537      if (i < line->numElements)      if (i < line->numElements)
1538          dev = line->elements[i].item + 5;          dev = line->elements[i].item + 5;
1539      else {      else {
1540     notSuitablePrintf(entry, "no root= entry found\n");
1541   /* it failed too...  can't find root= */   /* it failed too...  can't find root= */
1542          return 0;          return 0;
1543              }              }
# Line 1209  int suitableImage(struct singleEntry * e Line 1545  int suitableImage(struct singleEntry * e
1545      }      }
1546    
1547      dev = getpathbyspec(dev);      dev = getpathbyspec(dev);
1548      if (!dev)      if (!getpathbyspec(dev)) {
1549            notSuitablePrintf(entry, "can't find blkid entry for %s\n", dev);
1550          return 0;          return 0;
1551        } else
1552     dev = getpathbyspec(dev);
1553    
1554      i = stat(dev, &sb);      rootdev = findDiskForRoot();
1555      if (i)      if (!rootdev) {
1556            notSuitablePrintf(entry, "can't find root device\n");
1557   return 0;   return 0;
1558        }
1559    
1560      stat("/", &sb2);      if (!getuuidbydev(rootdev) || !getuuidbydev(dev)) {
1561            notSuitablePrintf(entry, "uuid missing: rootdev %s, dev %s\n",
1562     getuuidbydev(rootdev), getuuidbydev(dev));
1563            free(rootdev);
1564            return 0;
1565        }
1566    
1567      if (sb.st_rdev != sb2.st_dev)      if (strcmp(getuuidbydev(rootdev), getuuidbydev(dev))) {
1568            notSuitablePrintf(entry, "uuid mismatch: rootdev %s, dev %s\n",
1569     getuuidbydev(rootdev), getuuidbydev(dev));
1570     free(rootdev);
1571          return 0;          return 0;
1572        }
1573    
1574        free(rootdev);
1575    
1576      return 1;      return 1;
1577  }  }
# Line 1442  void setDefaultImage(struct grubConfig * Line 1794  void setDefaultImage(struct grubConfig *
1794    
1795      /* defaultImage now points to what we'd like to use, but before any order      /* defaultImage now points to what we'd like to use, but before any order
1796         changes */         changes */
1797      if (config->defaultImage == DEFAULT_SAVED)      if ((config->defaultImage == DEFAULT_SAVED) ||
1798     (config->defaultImage == DEFAULT_SAVED_GRUB2))
1799        /* default is set to saved, we don't want to change it */        /* default is set to saved, we don't want to change it */
1800        return;        return;
1801    
# Line 1509  void displayEntry(struct singleEntry * e Line 1862  void displayEntry(struct singleEntry * e
1862          return;          return;
1863      }      }
1864    
1865      printf("kernel=%s\n", line->elements[1].item);      printf("kernel=%s%s\n", prefix, line->elements[1].item);
1866    
1867      if (line->numElements >= 3) {      if (line->numElements >= 3) {
1868   printf("args=\"");   printf("args=\"");
# Line 1733  struct singleLine *  addLine(struct sing Line 2086  struct singleLine *  addLine(struct sing
2086   sprintf(tmpl.elements[0].item, "[%s]", val);   sprintf(tmpl.elements[0].item, "[%s]", val);
2087   tmpl.elements[0].indent = "";   tmpl.elements[0].indent = "";
2088   val = NULL;   val = NULL;
2089        } else if (type == LT_MENUENTRY) {
2090     char *lineend = "--class gnu-linux --class gnu --class os {";
2091     if (!val) {
2092        fprintf(stderr, "Line type LT_MENUENTRY requires a value\n");
2093        abort();
2094     }
2095     kw = getKeywordByType(type, cfi);
2096     if (!kw) {
2097        fprintf(stderr, "Looking up keyword for unknown type %d\n", type);
2098        abort();
2099     }
2100     tmpl.indent = "";
2101     tmpl.type = type;
2102     tmpl.numElements = 3;
2103     tmpl.elements = alloca(sizeof(*tmpl.elements) * tmpl.numElements);
2104     tmpl.elements[0].item = kw->key;
2105     tmpl.elements[0].indent = alloca(2);
2106     sprintf(tmpl.elements[0].indent, "%c", kw->nextChar);
2107     tmpl.elements[1].item = (char *)val;
2108     tmpl.elements[1].indent = alloca(2);
2109     sprintf(tmpl.elements[1].indent, "%c", kw->nextChar);
2110     tmpl.elements[2].item = alloca(strlen(lineend)+1);
2111     strcpy(tmpl.elements[2].item, lineend);
2112     tmpl.elements[2].indent = "";
2113      } else {      } else {
2114   kw = getKeywordByType(type, cfi);   kw = getKeywordByType(type, cfi);
2115   if (!kw) abort();   if (!kw) {
2116        fprintf(stderr, "Looking up keyword for unknown type %d\n", type);
2117        abort();
2118     }
2119   tmpl.type = type;   tmpl.type = type;
2120   tmpl.numElements = val ? 2 : 1;   tmpl.numElements = val ? 2 : 1;
2121   tmpl.elements = alloca(sizeof(*tmpl.elements) * tmpl.numElements);   tmpl.elements = alloca(sizeof(*tmpl.elements) * tmpl.numElements);
# Line 1759  struct singleLine *  addLine(struct sing Line 2139  struct singleLine *  addLine(struct sing
2139   if (!line->next && !prev) prev = line;   if (!line->next && !prev) prev = line;
2140      }      }
2141    
2142      if (prev == entry->lines)      struct singleLine *menuEntry;
2143   tmpl.indent = defaultIndent ?: "";      menuEntry = getLineByType(LT_MENUENTRY, entry->lines);
2144      else      if (tmpl.type == LT_ENTRY_END) {
2145   tmpl.indent = prev->indent;   if (menuEntry)
2146        tmpl.indent = menuEntry->indent;
2147     else
2148        tmpl.indent = defaultIndent ?: "";
2149        } else if (tmpl.type != LT_MENUENTRY) {
2150     if (menuEntry)
2151        tmpl.indent = "\t";
2152     else if (prev == entry->lines)
2153        tmpl.indent = defaultIndent ?: "";
2154     else
2155        tmpl.indent = prev->indent;
2156        }
2157    
2158      return addLineTmpl(entry, &tmpl, prev, val, cfi);      return addLineTmpl(entry, &tmpl, prev, val, cfi);
2159  }  }
# Line 1789  void removeLine(struct singleEntry * ent Line 2180  void removeLine(struct singleEntry * ent
2180      free(line);      free(line);
2181  }  }
2182    
2183    static int isquote(char q)
2184    {
2185        if (q == '\'' || q == '\"')
2186     return 1;
2187        return 0;
2188    }
2189    
2190    static void requote(struct singleLine *tmplLine, struct configFileInfo * cfi)
2191    {
2192        struct singleLine newLine = {
2193     .indent = tmplLine->indent,
2194     .type = tmplLine->type,
2195     .next = tmplLine->next,
2196        };
2197        int firstQuotedItem = -1;
2198        int quoteLen = 0;
2199        int j;
2200        int element = 0;
2201        char *c;
2202    
2203        c = malloc(strlen(tmplLine->elements[0].item) + 1);
2204        strcpy(c, tmplLine->elements[0].item);
2205        insertElement(&newLine, c, element++, cfi);
2206        free(c);
2207        c = NULL;
2208    
2209        for (j = 1; j < tmplLine->numElements; j++) {
2210     if (firstQuotedItem == -1) {
2211        quoteLen += strlen(tmplLine->elements[j].item);
2212        
2213        if (isquote(tmplLine->elements[j].item[0])) {
2214     firstQuotedItem = j;
2215            quoteLen += strlen(tmplLine->elements[j].indent);
2216        } else {
2217     c = malloc(quoteLen + 1);
2218     strcpy(c, tmplLine->elements[j].item);
2219     insertElement(&newLine, c, element++, cfi);
2220     free(c);
2221     quoteLen = 0;
2222        }
2223     } else {
2224        int itemlen = strlen(tmplLine->elements[j].item);
2225        quoteLen += itemlen;
2226        quoteLen += strlen(tmplLine->elements[j].indent);
2227        
2228        if (isquote(tmplLine->elements[j].item[itemlen - 1])) {
2229     c = malloc(quoteLen + 1);
2230     c[0] = '\0';
2231     for (int i = firstQuotedItem; i < j+1; i++) {
2232        strcat(c, tmplLine->elements[i].item);
2233        strcat(c, tmplLine->elements[i].indent);
2234     }
2235     insertElement(&newLine, c, element++, cfi);
2236     free(c);
2237    
2238     firstQuotedItem = -1;
2239     quoteLen = 0;
2240        }
2241     }
2242        }
2243        while (tmplLine->numElements)
2244     removeElement(tmplLine, 0);
2245        if (tmplLine->elements)
2246     free(tmplLine->elements);
2247    
2248        tmplLine->numElements = newLine.numElements;
2249        tmplLine->elements = newLine.elements;
2250    }
2251    
2252  static void insertElement(struct singleLine * line,  static void insertElement(struct singleLine * line,
2253    const char * item, int insertHere,    const char * item, int insertHere,
2254    struct configFileInfo * cfi)    struct configFileInfo * cfi)
# Line 1895  int updateActualImage(struct grubConfig Line 2355  int updateActualImage(struct grubConfig
2355      const char ** arg;      const char ** arg;
2356      int useKernelArgs, useRoot;      int useKernelArgs, useRoot;
2357      int firstElement;      int firstElement;
2358      int *usedElements, *usedArgs;      int *usedElements;
2359      int doreplace;      int doreplace;
2360    
2361      if (!image) return 0;      if (!image) return 0;
# Line 1930  int updateActualImage(struct grubConfig Line 2390  int updateActualImage(struct grubConfig
2390      useRoot = (getKeywordByType(LT_ROOT, cfg->cfi)      useRoot = (getKeywordByType(LT_ROOT, cfg->cfi)
2391         && !multibootArgs);         && !multibootArgs);
2392    
     for (k = 0, arg = newArgs; *arg; arg++, k++) ;  
     usedArgs = calloc(k, sizeof(*usedArgs));  
   
2393      for (; (entry = findEntryByPath(cfg, image, prefix, &index)); index++) {      for (; (entry = findEntryByPath(cfg, image, prefix, &index)); index++) {
2394    
2395   if (multibootArgs && !entry->multiboot)   if (multibootArgs && !entry->multiboot)
# Line 2008  int updateActualImage(struct grubConfig Line 2465  int updateActualImage(struct grubConfig
2465          usedElements = calloc(line->numElements, sizeof(*usedElements));          usedElements = calloc(line->numElements, sizeof(*usedElements));
2466    
2467   for (k = 0, arg = newArgs; *arg; arg++, k++) {   for (k = 0, arg = newArgs; *arg; arg++, k++) {
             if (usedArgs[k]) continue;  
2468    
2469      doreplace = 1;      doreplace = 1;
2470      for (i = firstElement; i < line->numElements; i++) {      for (i = firstElement; i < line->numElements; i++) {
# Line 2023  int updateActualImage(struct grubConfig Line 2479  int updateActualImage(struct grubConfig
2479                      continue;                      continue;
2480   if (!argMatch(line->elements[i].item, *arg)) {   if (!argMatch(line->elements[i].item, *arg)) {
2481                      usedElements[i]=1;                      usedElements[i]=1;
                     usedArgs[k]=1;  
2482      break;      break;
2483                  }                  }
2484              }              }
# Line 2093  int updateActualImage(struct grubConfig Line 2548  int updateActualImage(struct grubConfig
2548   }   }
2549      }      }
2550    
     free(usedArgs);  
2551      free(newArgs);      free(newArgs);
2552      free(oldArgs);      free(oldArgs);
2553    
# Line 2119  int updateImage(struct grubConfig * cfg, Line 2573  int updateImage(struct grubConfig * cfg,
2573      return rc;      return rc;
2574  }  }
2575    
2576    int updateInitrd(struct grubConfig * cfg, const char * image,
2577                     const char * prefix, const char * initrd) {
2578        struct singleEntry * entry;
2579        struct singleLine * line, * kernelLine, *endLine = NULL;
2580        int index = 0;
2581    
2582        if (!image) return 0;
2583    
2584        for (; (entry = findEntryByPath(cfg, image, prefix, &index)); index++) {
2585            kernelLine = getLineByType(LT_KERNEL, entry->lines);
2586            if (!kernelLine) continue;
2587    
2588            line = getLineByType(LT_INITRD, entry->lines);
2589            if (line)
2590                removeLine(entry, line);
2591            if (prefix) {
2592                int prefixLen = strlen(prefix);
2593                if (!strncmp(initrd, prefix, prefixLen))
2594                    initrd += prefixLen;
2595            }
2596     endLine = getLineByType(LT_ENTRY_END, entry->lines);
2597     if (endLine)
2598        removeLine(entry, endLine);
2599            line = addLine(entry, cfg->cfi, LT_INITRD, kernelLine->indent, initrd);
2600            if (!line)
2601        return 1;
2602     if (endLine) {
2603        line = addLine(entry, cfg->cfi, LT_ENTRY_END, "", NULL);
2604                if (!line)
2605     return 1;
2606     }
2607    
2608            break;
2609        }
2610    
2611        return 0;
2612    }
2613    
2614  int checkDeviceBootloader(const char * device, const unsigned char * boot) {  int checkDeviceBootloader(const char * device, const unsigned char * boot) {
2615      int fd;      int fd;
2616      unsigned char bootSect[512];      unsigned char bootSect[512];
# Line 2142  int checkDeviceBootloader(const char * d Line 2634  int checkDeviceBootloader(const char * d
2634      if (memcmp(boot, bootSect, 3))      if (memcmp(boot, bootSect, 3))
2635   return 0;   return 0;
2636    
2637      if (boot[1] == 0xeb) {      if (boot[1] == JMP_SHORT_OPCODE) {
2638   offset = boot[2] + 2;   offset = boot[2] + 2;
2639      } else if (boot[1] == 0xe8 || boot[1] == 0xe9) {      } else if (boot[1] == 0xe8 || boot[1] == 0xe9) {
2640   offset = (boot[3] << 8) + boot[2] + 2;   offset = (boot[3] << 8) + boot[2] + 2;
2641      } else if (boot[0] == 0xeb) {      } else if (boot[0] == JMP_SHORT_OPCODE) {
2642   offset = boot[1] + 2;        offset = boot[1] + 2;
2643            /*
2644     * it looks like grub, when copying stage1 into the mbr, patches stage1
2645     * right after the JMP location, replacing other instructions such as
2646     * JMPs for NOOPs. So, relax the check a little bit by skipping those
2647     * different bytes.
2648     */
2649          if ((bootSect[offset + 1] == NOOP_OPCODE)
2650      && (bootSect[offset + 2] == NOOP_OPCODE)) {
2651     offset = offset + 3;
2652          }
2653      } else if (boot[0] == 0xe8 || boot[0] == 0xe9) {      } else if (boot[0] == 0xe8 || boot[0] == 0xe9) {
2654   offset = (boot[2] << 8) + boot[1] + 2;   offset = (boot[2] << 8) + boot[1] + 2;
2655      } else {      } else {
# Line 2289  int checkForLilo(struct grubConfig * con Line 2791  int checkForLilo(struct grubConfig * con
2791      return checkDeviceBootloader(line->elements[1].item, boot);      return checkDeviceBootloader(line->elements[1].item, boot);
2792  }  }
2793    
2794    int checkForGrub2(struct grubConfig * config) {
2795        if (!access("/etc/grub.d/", R_OK))
2796     return 2;
2797    
2798        return 1;
2799    }
2800    
2801  int checkForGrub(struct grubConfig * config) {  int checkForGrub(struct grubConfig * config) {
2802      int fd;      int fd;
2803      unsigned char bootSect[512];      unsigned char bootSect[512];
# Line 2464  int addNewKernel(struct grubConfig * con Line 2973  int addNewKernel(struct grubConfig * con
2973      if (*chptr == '#') continue;      if (*chptr == '#') continue;
2974    
2975      if (tmplLine->type == LT_KERNEL &&      if (tmplLine->type == LT_KERNEL &&
2976   tmplLine->numElements >= 2) {      tmplLine->numElements >= 2) {
2977   if (!template->multiboot && (needs & NEED_MB)) {   if (!template->multiboot && (needs & NEED_MB)) {
2978      /* it's not a multiboot template and this is the kernel      /* it's not a multiboot template and this is the kernel
2979       * line.  Try to be intelligent about inserting the       * line.  Try to be intelligent about inserting the
# Line 2590  int addNewKernel(struct grubConfig * con Line 3099  int addNewKernel(struct grubConfig * con
3099      needs &= ~NEED_INITRD;      needs &= ~NEED_INITRD;
3100   }   }
3101    
3102        } else if (tmplLine->type == LT_MENUENTRY &&
3103           (needs & NEED_TITLE)) {
3104     requote(tmplLine, config->cfi);
3105     char *nkt = malloc(strlen(newKernelTitle)+3);
3106     strcpy(nkt, "'");
3107     strcat(nkt, newKernelTitle);
3108     strcat(nkt, "'");
3109     newLine = addLineTmpl(new, tmplLine, newLine, nkt, config->cfi);
3110     free(nkt);
3111     needs &= ~NEED_TITLE;
3112      } else if (tmplLine->type == LT_TITLE &&      } else if (tmplLine->type == LT_TITLE &&
3113         (needs & NEED_TITLE)) {         (needs & NEED_TITLE)) {
3114   if (tmplLine->numElements >= 2) {   if (tmplLine->numElements >= 2) {
# Line 2603  int addNewKernel(struct grubConfig * con Line 3122  int addNewKernel(struct grubConfig * con
3122        tmplLine->indent, newKernelTitle);        tmplLine->indent, newKernelTitle);
3123      needs &= ~NEED_TITLE;      needs &= ~NEED_TITLE;
3124   }   }
3125        } else if (tmplLine->type == LT_ECHO) {
3126        requote(tmplLine, config->cfi);
3127        static const char *prefix = "'Loading ";
3128        if (tmplLine->numElements > 1 &&
3129        strstr(tmplLine->elements[1].item, prefix) &&
3130        masterLine->next && masterLine->next->type == LT_KERNEL) {
3131     char *newTitle = malloc(strlen(prefix) +
3132     strlen(newKernelTitle) + 2);
3133    
3134     strcpy(newTitle, prefix);
3135     strcat(newTitle, newKernelTitle);
3136     strcat(newTitle, "'");
3137     newLine = addLine(new, config->cfi, LT_ECHO,
3138     tmplLine->indent, newTitle);
3139     free(newTitle);
3140        } else {
3141     /* pass through other lines from the template */
3142     newLine = addLineTmpl(new, tmplLine, newLine, NULL,
3143     config->cfi);
3144        }
3145      } else {      } else {
3146   /* pass through other lines from the template */   /* pass through other lines from the template */
3147   newLine = addLineTmpl(new, tmplLine, newLine, NULL, config->cfi);   newLine = addLineTmpl(new, tmplLine, newLine, NULL, config->cfi);
# Line 2614  int addNewKernel(struct grubConfig * con Line 3152  int addNewKernel(struct grubConfig * con
3152   /* don't have a template, so start the entry with the   /* don't have a template, so start the entry with the
3153   * appropriate starting line   * appropriate starting line
3154   */   */
3155   switch (config->cfi->entrySeparator) {   switch (config->cfi->entryStart) {
3156      case LT_KERNEL:      case LT_KERNEL:
3157   if (new->multiboot && config->cfi->mbHyperFirst) {   if (new->multiboot && config->cfi->mbHyperFirst) {
3158      /* fall through to LT_HYPER */      /* fall through to LT_HYPER */
# Line 2633  int addNewKernel(struct grubConfig * con Line 3171  int addNewKernel(struct grubConfig * con
3171   needs &= ~NEED_MB;   needs &= ~NEED_MB;
3172   break;   break;
3173    
3174        case LT_MENUENTRY: {
3175     char *nkt = malloc(strlen(newKernelTitle)+3);
3176     strcpy(nkt, "'");
3177     strcat(nkt, newKernelTitle);
3178     strcat(nkt, "'");
3179            newLine = addLine(new, config->cfi, LT_MENUENTRY,
3180      config->primaryIndent, nkt);
3181     free(nkt);
3182     needs &= ~NEED_TITLE;
3183     needs |= NEED_END;
3184     break;
3185        }
3186      case LT_TITLE:      case LT_TITLE:
3187   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)
3188   char * templabel;   char * templabel;
# Line 2666  int addNewKernel(struct grubConfig * con Line 3216  int addNewKernel(struct grubConfig * con
3216    
3217      /* add the remainder of the lines, i.e. those that either      /* add the remainder of the lines, i.e. those that either
3218       * 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,
3219       * all the lines following the entrySeparator.       * all the lines following the entryStart.
3220       */       */
3221      if (needs & NEED_TITLE) {      if (needs & NEED_TITLE) {
3222   newLine = addLine(new, config->cfi, LT_TITLE,   newLine = addLine(new, config->cfi, LT_TITLE,
# Line 2707  int addNewKernel(struct grubConfig * con Line 3257  int addNewKernel(struct grubConfig * con
3257   free(initrdVal);   free(initrdVal);
3258   needs &= ~NEED_INITRD;   needs &= ~NEED_INITRD;
3259      }      }
3260        if (needs & NEED_END) {
3261     newLine = addLine(new, config->cfi, LT_ENTRY_END,
3262     config->secondaryIndent, NULL);
3263     needs &= ~NEED_END;
3264        }
3265    
3266      if (needs) {      if (needs) {
3267   printf(_("grubby: needs=%d, aborting\n"), needs);   printf(_("grubby: needs=%d, aborting\n"), needs);
# Line 2736  static void traceback(int signum) Line 3291  static void traceback(int signum)
3291    
3292  int main(int argc, const char ** argv) {  int main(int argc, const char ** argv) {
3293      poptContext optCon;      poptContext optCon;
3294      char * grubConfig = NULL;      const char * grubConfig = NULL;
3295      char * outputFile = NULL;      char * outputFile = NULL;
3296      int arg = 0;      int arg = 0;
3297      int flags = 0;      int flags = 0;
3298      int badImageOkay = 0;      int badImageOkay = 0;
3299        int configureGrub2 = 0;
3300      int configureLilo = 0, configureELilo = 0, configureGrub = 0;      int configureLilo = 0, configureELilo = 0, configureGrub = 0;
3301      int configureYaboot = 0, configureSilo = 0, configureZipl = 0;      int configureYaboot = 0, configureSilo = 0, configureZipl = 0;
3302      int configureExtLinux = 0;      int configureExtLinux = 0;
# Line 2768  int main(int argc, const char ** argv) { Line 3324  int main(int argc, const char ** argv) {
3324      struct singleEntry * template = NULL;      struct singleEntry * template = NULL;
3325      int copyDefault = 0, makeDefault = 0;      int copyDefault = 0, makeDefault = 0;
3326      int displayDefault = 0;      int displayDefault = 0;
3327        int displayDefaultIndex = 0;
3328        int displayDefaultTitle = 0;
3329      struct poptOption options[] = {      struct poptOption options[] = {
3330   { "add-kernel", 0, POPT_ARG_STRING, &newKernelPath, 0,   { "add-kernel", 0, POPT_ARG_STRING, &newKernelPath, 0,
3331      _("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 3356  int main(int argc, const char ** argv) {
3356        "the kernel referenced by the default image does not exist, "        "the kernel referenced by the default image does not exist, "
3357        "the first linux entry whose kernel does exist is used as the "        "the first linux entry whose kernel does exist is used as the "
3358        "template"), NULL },        "template"), NULL },
3359     { "debug", 0, 0, &debug, 0,
3360        _("print debugging information for failures") },
3361   { "default-kernel", 0, 0, &displayDefault, 0,   { "default-kernel", 0, 0, &displayDefault, 0,
3362      _("display the path of the default kernel") },      _("display the path of the default kernel") },
3363     { "default-index", 0, 0, &displayDefaultIndex, 0,
3364        _("display the index of the default kernel") },
3365     { "default-title", 0, 0, &displayDefaultTitle, 0,
3366        _("display the title of the default kernel") },
3367   { "elilo", 0, POPT_ARG_NONE, &configureELilo, 0,   { "elilo", 0, POPT_ARG_NONE, &configureELilo, 0,
3368      _("configure elilo bootloader") },      _("configure elilo bootloader") },
3369   { "extlinux", 0, POPT_ARG_NONE, &configureExtLinux, 0,   { "extlinux", 0, POPT_ARG_NONE, &configureExtLinux, 0,
3370      _("configure extlinux bootloader (from syslinux)") },      _("configure extlinux bootloader (from syslinux)") },
3371   { "grub", 0, POPT_ARG_NONE, &configureGrub, 0,   { "grub", 0, POPT_ARG_NONE, &configureGrub, 0,
3372      _("configure grub bootloader") },      _("configure grub bootloader") },
3373     { "grub2", 0, POPT_ARG_NONE, &configureGrub2, 0,
3374        _("configure grub2 bootloader") },
3375   { "info", 0, POPT_ARG_STRING, &kernelInfo, 0,   { "info", 0, POPT_ARG_STRING, &kernelInfo, 0,
3376      _("display boot information for specified kernel"),      _("display boot information for specified kernel"),
3377      _("kernel-path") },      _("kernel-path") },
# Line 2885  int main(int argc, const char ** argv) { Line 3451  int main(int argc, const char ** argv) {
3451   return 1;   return 1;
3452      }      }
3453    
3454      if ((configureLilo + configureGrub + configureELilo +      if ((configureLilo + configureGrub2 + configureGrub + configureELilo +
3455   configureYaboot + configureSilo + configureZipl +   configureYaboot + configureSilo + configureZipl +
3456   configureExtLinux ) > 1) {   configureExtLinux ) > 1) {
3457   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 3460  int main(int argc, const char ** argv) {
3460   fprintf(stderr,   fprintf(stderr,
3461      _("grubby: cannot specify config file with --bootloader-probe\n"));      _("grubby: cannot specify config file with --bootloader-probe\n"));
3462   return 1;   return 1;
3463        } else if (configureGrub2) {
3464     cfi = &grub2ConfigType;
3465      } else if (configureLilo) {      } else if (configureLilo) {
3466   cfi = &liloConfigType;   cfi = &liloConfigType;
3467      } else if (configureGrub) {      } else if (configureGrub) {
# Line 2923  int main(int argc, const char ** argv) { Line 3491  int main(int argc, const char ** argv) {
3491        #elif __s390x__        #elif __s390x__
3492          cfi = &ziplConfigtype;          cfi = &ziplConfigtype;
3493        #else        #else
3494   cfi = &grubConfigType;          if (grub2FindConfig(&grub2ConfigType))
3495        cfi = &grub2ConfigType;
3496     else
3497        cfi = &grubConfigType;
3498        #endif        #endif
3499      }      }
3500    
3501      if (!grubConfig)      if (!grubConfig) {
3502   grubConfig = cfi->defaultConfig;   if (cfi->findConfig)
3503        grubConfig = cfi->findConfig(cfi);
3504     if (!grubConfig)
3505        grubConfig = cfi->defaultConfig;
3506        }
3507    
3508      if (bootloaderProbe && (displayDefault || kernelInfo || newKernelVersion ||      if (bootloaderProbe && (displayDefault || kernelInfo || newKernelVersion ||
3509    newKernelPath || removeKernelPath || makeDefault ||    newKernelPath || removeKernelPath || makeDefault ||
3510    defaultKernel)) {    defaultKernel || displayDefaultIndex || displayDefaultTitle)) {
3511   fprintf(stderr, _("grubby: --bootloader-probe may not be used with "   fprintf(stderr, _("grubby: --bootloader-probe may not be used with "
3512    "specified option"));    "specified option"));
3513   return 1;   return 1;
# Line 2948  int main(int argc, const char ** argv) { Line 3523  int main(int argc, const char ** argv) {
3523      if (newKernelPath && !newKernelTitle) {      if (newKernelPath && !newKernelTitle) {
3524   fprintf(stderr, _("grubby: kernel title must be specified\n"));   fprintf(stderr, _("grubby: kernel title must be specified\n"));
3525   return 1;   return 1;
3526      } else if (!newKernelPath && (newKernelTitle  || newKernelInitrd ||      } else if (!newKernelPath && (newKernelTitle  || copyDefault ||
3527    newKernelInitrd || copyDefault     ||    (newKernelInitrd && !updateKernelPath)||
3528    makeDefault || extraInitrdCount > 0)) {    makeDefault || extraInitrdCount > 0)) {
3529   fprintf(stderr, _("grubby: kernel path expected\n"));   fprintf(stderr, _("grubby: kernel path expected\n"));
3530   return 1;   return 1;
# Line 2975  int main(int argc, const char ** argv) { Line 3550  int main(int argc, const char ** argv) {
3550   defaultKernel = NULL;   defaultKernel = NULL;
3551      }      }
3552    
3553      if (!strcmp(grubConfig, "-") && !outputFile) {      if (grubConfig && !strcmp(grubConfig, "-") && !outputFile) {
3554   fprintf(stderr, _("grubby: output file must be specified if stdin "   fprintf(stderr, _("grubby: output file must be specified if stdin "
3555   "is used\n"));   "is used\n"));
3556   return 1;   return 1;
# Line 2983  int main(int argc, const char ** argv) { Line 3558  int main(int argc, const char ** argv) {
3558    
3559      if (!removeKernelPath && !newKernelPath && !displayDefault && !defaultKernel      if (!removeKernelPath && !newKernelPath && !displayDefault && !defaultKernel
3560   && !kernelInfo && !bootloaderProbe && !updateKernelPath   && !kernelInfo && !bootloaderProbe && !updateKernelPath
3561          && !removeMBKernel) {          && !removeMBKernel && !displayDefaultIndex && !displayDefaultTitle) {
3562   fprintf(stderr, _("grubby: no action specified\n"));   fprintf(stderr, _("grubby: no action specified\n"));
3563   return 1;   return 1;
3564      }      }
# Line 3010  int main(int argc, const char ** argv) { Line 3585  int main(int argc, const char ** argv) {
3585      }      }
3586    
3587      if (bootloaderProbe) {      if (bootloaderProbe) {
3588   int lrc = 0, grc = 0, erc = 0;   int lrc = 0, grc = 0, gr2c = 0, erc = 0;
3589   struct grubConfig * lconfig, * gconfig;   struct grubConfig * lconfig, * gconfig;
3590    
3591   if (!access(grubConfigType.defaultConfig, F_OK)) {   const char *grub2config = grub2FindConfig(&grub2ConfigType);
3592      gconfig = readConfig(grubConfigType.defaultConfig, &grubConfigType);   if (grub2config) {
3593        gconfig = readConfig(grub2config, &grub2ConfigType);
3594        if (!gconfig)
3595     gr2c = 1;
3596        else
3597     gr2c = checkForGrub2(gconfig);
3598     }
3599    
3600     const char *grubconfig = grubFindConfig(&grubConfigType);
3601     if (!access(grubconfig, F_OK)) {
3602        gconfig = readConfig(grubconfig, &grubConfigType);
3603      if (!gconfig)      if (!gconfig)
3604   grc = 1;   grc = 1;
3605      else      else
# Line 3037  int main(int argc, const char ** argv) { Line 3622  int main(int argc, const char ** argv) {
3622   erc = checkForExtLinux(lconfig);   erc = checkForExtLinux(lconfig);
3623   }   }
3624    
3625   if (lrc == 1 || grc == 1) return 1;   if (lrc == 1 || grc == 1 || gr2c == 1) return 1;
3626    
3627   if (lrc == 2) printf("lilo\n");   if (lrc == 2) printf("lilo\n");
3628     if (gr2c == 2) printf("grub2\n");
3629   if (grc == 2) printf("grub\n");   if (grc == 2) printf("grub\n");
3630   if (erc == 2) printf("extlinux\n");   if (erc == 2) printf("extlinux\n");
3631    
# Line 3067  int main(int argc, const char ** argv) { Line 3653  int main(int argc, const char ** argv) {
3653                 ((rootspec != NULL) ? strlen(rootspec) : 0));                 ((rootspec != NULL) ? strlen(rootspec) : 0));
3654    
3655   return 0;   return 0;
3656    
3657        } else if (displayDefaultTitle) {
3658     struct singleLine * line;
3659     struct singleEntry * entry;
3660    
3661     if (config->defaultImage == -1) return 0;
3662     entry = findEntryByIndex(config, config->defaultImage);
3663     if (!entry) return 0;
3664    
3665     if (!configureGrub2) {
3666      line = getLineByType(LT_TITLE, entry->lines);
3667      if (!line) return 0;
3668      printf("%s\n", line->elements[1].item);
3669    
3670     } else {
3671      char * title;
3672    
3673      dbgPrintf("This is GRUB2, default title is embeded in menuentry\n");
3674      line = getLineByType(LT_MENUENTRY, entry->lines);
3675      if (!line) return 0;
3676      title = grub2ExtractTitle(line);
3677      if (title)
3678        printf("%s\n", title);
3679     }
3680     return 0;
3681    
3682        } else if (displayDefaultIndex) {
3683            if (config->defaultImage == -1) return 0;
3684            printf("%i\n", config->defaultImage);
3685    
3686      } else if (kernelInfo)      } else if (kernelInfo)
3687   return displayInfo(config, kernelInfo, bootPrefix);   return displayInfo(config, kernelInfo, bootPrefix);
3688    
# Line 3082  int main(int argc, const char ** argv) { Line 3698  int main(int argc, const char ** argv) {
3698      setFallbackImage(config, newKernelPath != NULL);      setFallbackImage(config, newKernelPath != NULL);
3699      if (updateImage(config, updateKernelPath, bootPrefix, newKernelArgs,      if (updateImage(config, updateKernelPath, bootPrefix, newKernelArgs,
3700                      removeArgs, newMBKernelArgs, removeMBKernelArgs)) return 1;                      removeArgs, newMBKernelArgs, removeMBKernelArgs)) return 1;
3701        if (updateKernelPath && newKernelInitrd) {
3702                if (updateInitrd(config, updateKernelPath, bootPrefix,
3703                                 newKernelInitrd)) return 1;
3704        }
3705      if (addNewKernel(config, template, bootPrefix, newKernelPath,      if (addNewKernel(config, template, bootPrefix, newKernelPath,
3706                       newKernelTitle, newKernelArgs, newKernelInitrd,                       newKernelTitle, newKernelArgs, newKernelInitrd,
3707                       extraInitrds, extraInitrdCount,                       extraInitrds, extraInitrdCount,
# Line 3095  int main(int argc, const char ** argv) { Line 3715  int main(int argc, const char ** argv) {
3715      }      }
3716    
3717      if (!outputFile)      if (!outputFile)
3718   outputFile = grubConfig;   outputFile = (char *)grubConfig;
3719    
3720      return writeConfig(config, outputFile, bootPrefix);      return writeConfig(config, outputFile, bootPrefix);
3721  }  }

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