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 1800 by niro, Mon Apr 16 17:46:40 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    static int isquote(char q)
269    {
270        if (q == '\'' || q == '\"')
271     return 1;
272        return 0;
273    }
274    
275    char *grub2ExtractTitle(struct singleLine * line) {
276        char * current;
277        char * current_indent;
278        int current_len;
279        int current_indent_len;
280        int i;
281    
282        /* bail out if line does not start with menuentry */
283        if (strcmp(line->elements[0].item, "menuentry"))
284          return NULL;
285    
286        i = 1;
287        current = line->elements[i].item;
288        current_len = strlen(current);
289    
290        /* if second word is quoted, strip the quotes and return single word */
291        if (isquote(*current) && isquote(current[current_len - 1])) {
292     char *tmp;
293    
294     tmp = strdup(current);
295     *(tmp + current_len - 1) = '\0';
296     return ++tmp;
297        }
298    
299        /* if no quotes, return second word verbatim */
300        if (!isquote(*current))
301     return current;
302    
303        /* second element start with a quote, so we have to find the element
304         * whose last character is also quote (assuming it's the closing one) */
305        int resultMaxSize;
306        char * result;
307        
308        resultMaxSize = sizeOfSingleLine(line);
309        result = malloc(resultMaxSize);
310        snprintf(result, resultMaxSize, "%s", ++current);
311        
312        i++;
313        for (; i < line->numElements; ++i) {
314     current = line->elements[i].item;
315     current_len = strlen(current);
316     current_indent = line->elements[i].indent;
317     current_indent_len = strlen(current_indent);
318    
319     strncat(result, current_indent, current_indent_len);
320     if (!isquote(current[current_len-1])) {
321        strncat(result, current, current_len);
322     } else {
323        strncat(result, current, current_len - 1);
324        break;
325     }
326        }
327        return result;
328    }
329    
330    struct configFileInfo grub2ConfigType = {
331        .findConfig = grub2FindConfig,
332        .keywords = grub2Keywords,
333        .defaultIsIndex = 1,
334        .defaultSupportSaved = 1,
335        .defaultIsVariable = 1,
336        .entryStart = LT_MENUENTRY,
337        .entryEnd = LT_ENTRY_END,
338        .titlePosition = 1,
339        .needsBootPrefix = 1,
340        .mbHyperFirst = 1,
341        .mbInitRdIsModule = 1,
342        .mbAllowExtraInitRds = 1,
343  };  };
344    
345  struct keywordTypes yabootKeywords[] = {  struct keywordTypes yabootKeywords[] = {
# Line 249  struct keywordTypes extlinuxKeywords[] = Line 437  struct keywordTypes extlinuxKeywords[] =
437  };  };
438  int useextlinuxmenu;  int useextlinuxmenu;
439  struct configFileInfo eliloConfigType = {  struct configFileInfo eliloConfigType = {
440      "/boot/efi/EFI/redhat/elilo.conf",    /* defaultConfig */      .defaultConfig = "/boot/efi/EFI/redhat/elilo.conf",
441      eliloKeywords,    /* keywords */      .keywords = eliloKeywords,
442      0,    /* defaultIsIndex */      .entryStart = LT_KERNEL,
443      0,    /* defaultSupportSaved */      .needsBootPrefix = 1,
444      LT_KERNEL,    /* entrySeparator */      .argsInQuotes = 1,
445      1,                    /* needsBootPrefix */      .mbConcatArgs = 1,
     1,    /* argsInQuotes */  
     0,    /* maxTitleLength */  
     0,                                      /* titleBracketed */  
     0,                                      /* mbHyperFirst */  
     0,                                      /* mbInitRdIsModule */  
     1,                                      /* mbConcatArgs */  
     0,                                      /* mbAllowExtraInitRds */  
446  };  };
447    
448  struct configFileInfo liloConfigType = {  struct configFileInfo liloConfigType = {
449      "/etc/lilo.conf",    /* defaultConfig */      .defaultConfig = "/etc/lilo.conf",
450      liloKeywords,    /* keywords */      .keywords = liloKeywords,
451      0,    /* defaultIsIndex */      .entryStart = LT_KERNEL,
452      0,    /* defaultSupportSaved */      .argsInQuotes = 1,
453      LT_KERNEL,    /* entrySeparator */      .maxTitleLength = 15,
     0,    /* needsBootPrefix */  
     1,    /* argsInQuotes */  
     15,    /* maxTitleLength */  
     0,                                      /* titleBracketed */  
     0,                                      /* mbHyperFirst */  
     0,                                      /* mbInitRdIsModule */  
     0,                                      /* mbConcatArgs */  
     0,                                      /* mbAllowExtraInitRds */  
454  };  };
455    
456  struct configFileInfo yabootConfigType = {  struct configFileInfo yabootConfigType = {
457      "/etc/yaboot.conf",    /* defaultConfig */      .defaultConfig = "/etc/yaboot.conf",
458      yabootKeywords,    /* keywords */      .keywords = yabootKeywords,
459      0,    /* defaultIsIndex */      .entryStart = LT_KERNEL,
460      0,    /* defaultSupportSaved */      .needsBootPrefix = 1,
461      LT_KERNEL,    /* entrySeparator */      .argsInQuotes = 1,
462      1,    /* needsBootPrefix */      .maxTitleLength = 15,
463      1,    /* argsInQuotes */      .mbAllowExtraInitRds = 1,
     15,    /* maxTitleLength */  
     0,                                      /* titleBracketed */  
     0,                                      /* mbHyperFirst */  
     0,                                      /* mbInitRdIsModule */  
     0,                                      /* mbConcatArgs */  
     1,                                      /* mbAllowExtraInitRds */  
464  };  };
465    
466  struct configFileInfo siloConfigType = {  struct configFileInfo siloConfigType = {
467      "/etc/silo.conf",    /* defaultConfig */      .defaultConfig = "/etc/silo.conf",
468      siloKeywords,    /* keywords */      .keywords = siloKeywords,
469      0,    /* defaultIsIndex */      .entryStart = LT_KERNEL,
470      0,    /* defaultSupportSaved */      .needsBootPrefix = 1,
471      LT_KERNEL,    /* entrySeparator */      .argsInQuotes = 1,
472      1,    /* needsBootPrefix */      .maxTitleLength = 15,
     1,    /* argsInQuotes */  
     15,    /* maxTitleLength */  
     0,                                      /* titleBracketed */  
     0,                                      /* mbHyperFirst */  
     0,                                      /* mbInitRdIsModule */  
     0,                                      /* mbConcatArgs */  
     0,                                      /* mbAllowExtraInitRds */  
473  };  };
474    
475  struct configFileInfo ziplConfigType = {  struct configFileInfo ziplConfigType = {
476      "/etc/zipl.conf",    /* defaultConfig */      .defaultConfig = "/etc/zipl.conf",
477      ziplKeywords,    /* keywords */      .keywords = ziplKeywords,
478      0,    /* defaultIsIndex */      .entryStart = LT_TITLE,
479      0,    /* defaultSupportSaved */      .argsInQuotes = 1,
480      LT_TITLE,    /* entrySeparator */      .titleBracketed = 1,
     0,    /* needsBootPrefix */  
     1,    /* argsInQuotes */  
     0,    /* maxTitleLength */  
     1,                                      /* titleBracketed */  
     0,                                      /* mbHyperFirst */  
     0,                                      /* mbInitRdIsModule */  
     0,                                      /* mbConcatArgs */  
     0,                                      /* mbAllowExtraInitRds */  
481  };  };
482    
483  struct configFileInfo extlinuxConfigType = {  struct configFileInfo extlinuxConfigType = {
484      "/boot/extlinux/extlinux.conf",         /* defaultConfig */      .defaultConfig = "/boot/extlinux/extlinux.conf",
485      extlinuxKeywords,                       /* keywords */      .keywords = extlinuxKeywords,
486      0,                                      /* defaultIsIndex */      .entryStart = LT_TITLE,
487      0,                                      /* defaultSupportSaved */      .needsBootPrefix = 1,
488      LT_TITLE,                               /* entrySeparator */      .maxTitleLength = 255,
489      1,                                      /* needsBootPrefix */      .mbAllowExtraInitRds = 1,
     0,                                      /* argsInQuotes */  
     255,                                    /* maxTitleLength */  
     0,                                      /* titleBracketed */  
     0,                                      /* mbHyperFirst */  
     0,                                      /* mbInitRdIsModule */  
     0,                                      /* mbConcatArgs */  
     1,                                      /* mbAllowExtraInitRds */  
490  };  };
491    
492  struct grubConfig {  struct grubConfig {
# Line 356  struct grubConfig { Line 501  struct grubConfig {
501      struct configFileInfo * cfi;      struct configFileInfo * cfi;
502  };  };
503    
504    blkid_cache blkid;
505    
506  struct singleEntry * findEntryByIndex(struct grubConfig * cfg, int index);  struct singleEntry * findEntryByIndex(struct grubConfig * cfg, int index);
507  struct singleEntry * findEntryByPath(struct grubConfig * cfg,  struct singleEntry * findEntryByPath(struct grubConfig * cfg,
508       const char * path, const char * prefix,       const char * path, const char * prefix,
# Line 369  static int lineWrite(FILE * out, struct Line 516  static int lineWrite(FILE * out, struct
516  static int getNextLine(char ** bufPtr, struct singleLine * line,  static int getNextLine(char ** bufPtr, struct singleLine * line,
517         struct configFileInfo * cfi);         struct configFileInfo * cfi);
518  static char * getRootSpecifier(char * str);  static char * getRootSpecifier(char * str);
519    static void requote(struct singleLine *line, struct configFileInfo * cfi);
520  static void insertElement(struct singleLine * line,  static void insertElement(struct singleLine * line,
521    const char * item, int insertHere,    const char * item, int insertHere,
522    struct configFileInfo * cfi);    struct configFileInfo * cfi);
# Line 433  static struct keywordTypes * getKeywordB Line 581  static struct keywordTypes * getKeywordB
581      return NULL;      return NULL;
582  }  }
583    
584  static char * getpathbyspec(char *device) {  static char *getKeyByType(enum lineType_e type, struct configFileInfo * cfi) {
585      static blkid_cache blkid;      struct keywordTypes *kt = getKeywordByType(type, cfi);
586        if (kt)
587     return kt->key;
588        return "unknown";
589    }
590    
591    static char * getpathbyspec(char *device) {
592      if (!blkid)      if (!blkid)
593          blkid_get_cache(&blkid, NULL);          blkid_get_cache(&blkid, NULL);
594    
595      return blkid_get_devname(blkid, device, NULL);      return blkid_get_devname(blkid, device, NULL);
596  }  }
597    
598    static char * getuuidbydev(char *device) {
599        if (!blkid)
600     blkid_get_cache(&blkid, NULL);
601    
602        return blkid_get_tag_value(blkid, "UUID", device);
603    }
604    
605  static enum lineType_e getTypeByKeyword(char * keyword,  static enum lineType_e getTypeByKeyword(char * keyword,
606   struct configFileInfo * cfi) {   struct configFileInfo * cfi) {
607      struct keywordTypes * kw;      struct keywordTypes * kw;
# Line 477  static int isBracketedTitle(struct singl Line 637  static int isBracketedTitle(struct singl
637      return 0;      return 0;
638  }  }
639    
640  static int isEntrySeparator(struct singleLine * line,  static int isEntryStart(struct singleLine * line,
641                              struct configFileInfo * cfi) {                              struct configFileInfo * cfi) {
642      return line->type == cfi->entrySeparator || line->type == LT_OTHER ||      return line->type == cfi->entryStart || line->type == LT_OTHER ||
643   (cfi->titleBracketed && isBracketedTitle(line));   (cfi->titleBracketed && isBracketedTitle(line));
644  }  }
645    
# Line 802  static struct grubConfig * readConfig(co Line 962  static struct grubConfig * readConfig(co
962      cfg->secondaryIndent = strdup(line->indent);      cfg->secondaryIndent = strdup(line->indent);
963   }   }
964    
965   if (isEntrySeparator(line, cfi)) {   if (isEntryStart(line, cfi) || (cfg->entries && !sawEntry)) {
966      sawEntry = 1;      sawEntry = 1;
967      if (!entry) {      if (!entry) {
968   cfg->entries = malloc(sizeof(*entry));   cfg->entries = malloc(sizeof(*entry));
# Line 818  static struct grubConfig * readConfig(co Line 978  static struct grubConfig * readConfig(co
978      entry->next = NULL;      entry->next = NULL;
979   }   }
980    
981   if (line->type == LT_DEFAULT && line->numElements == 2) {   if (line->type == LT_SET_VARIABLE) {
982        int i;
983        dbgPrintf("found 'set' command (%d elements): ", line->numElements);
984        dbgPrintf("%s", line->indent);
985        for (i = 0; i < line->numElements; i++)
986     dbgPrintf("%s\"%s\"", line->elements[i].indent, line->elements[i].item);
987        dbgPrintf("\n");
988        struct keywordTypes *kwType = getKeywordByType(LT_DEFAULT, cfi);
989        if (kwType && line->numElements == 3 &&
990        !strcmp(line->elements[1].item, kwType->key)) {
991     dbgPrintf("Line sets default config\n");
992     cfg->flags &= ~GRUB_CONFIG_NO_DEFAULT;
993     defaultLine = line;
994        }
995     } else if (line->type == LT_DEFAULT && line->numElements == 2) {
996      cfg->flags &= ~GRUB_CONFIG_NO_DEFAULT;      cfg->flags &= ~GRUB_CONFIG_NO_DEFAULT;
997      defaultLine = line;      defaultLine = line;
998    
# Line 931  static struct grubConfig * readConfig(co Line 1105  static struct grubConfig * readConfig(co
1105   entry->lines = line;   entry->lines = line;
1106      else      else
1107   last->next = line;   last->next = line;
1108      dbgPrintf("readConfig added %d to %p\n", line->type, entry);      dbgPrintf("readConfig added %s to %p\n", getKeyByType(line->type, cfi), entry);
1109    
1110        /* we could have seen this outside of an entry... if so, we
1111         * ignore it like any other line we don't grok */
1112        if (line->type == LT_ENTRY_END && sawEntry)
1113     sawEntry = 0;
1114   } else {   } else {
1115      if (!cfg->theLines)      if (!cfg->theLines)
1116   cfg->theLines = line;   cfg->theLines = line;
1117      else      else
1118   last->next = line;   last->next = line;
1119      dbgPrintf("readConfig added %d to cfg\n", line->type);      dbgPrintf("readConfig added %s to cfg\n", getKeyByType(line->type, cfi));
1120   }   }
1121    
1122   last = line;   last = line;
# Line 945  static struct grubConfig * readConfig(co Line 1124  static struct grubConfig * readConfig(co
1124    
1125      free(incoming);      free(incoming);
1126    
1127        dbgPrintf("defaultLine is %s\n", defaultLine ? "set" : "unset");
1128      if (defaultLine) {      if (defaultLine) {
1129   if (cfi->defaultSupportSaved &&          if (defaultLine->numElements > 2 &&
1130        cfi->defaultSupportSaved &&
1131        !strncmp(defaultLine->elements[2].item,"\"${saved_entry}\"", 16)) {
1132        cfg->defaultImage = DEFAULT_SAVED_GRUB2;
1133     } else if (cfi->defaultIsVariable) {
1134        char *value = defaultLine->elements[2].item;
1135        while (*value && (*value == '"' || *value == '\'' ||
1136        *value == ' ' || *value == '\t'))
1137     value++;
1138        cfg->defaultImage = strtol(value, &end, 10);
1139        while (*end && (*end == '"' || *end == '\'' ||
1140        *end == ' ' || *end == '\t'))
1141     end++;
1142        if (*end) cfg->defaultImage = -1;
1143     } else if (cfi->defaultSupportSaved &&
1144   !strncmp(defaultLine->elements[1].item, "saved", 5)) {   !strncmp(defaultLine->elements[1].item, "saved", 5)) {
1145      cfg->defaultImage = DEFAULT_SAVED;      cfg->defaultImage = DEFAULT_SAVED;
1146   } else if (cfi->defaultIsIndex) {   } else if (cfi->defaultIsIndex) {
# Line 993  static void writeDefault(FILE * out, cha Line 1187  static void writeDefault(FILE * out, cha
1187    
1188      if (cfg->defaultImage == DEFAULT_SAVED)      if (cfg->defaultImage == DEFAULT_SAVED)
1189   fprintf(out, "%sdefault%ssaved\n", indent, separator);   fprintf(out, "%sdefault%ssaved\n", indent, separator);
1190        else if (cfg->defaultImage == DEFAULT_SAVED_GRUB2)
1191     fprintf(out, "%sset default=\"${saved_entry}\"\n", indent);
1192      else if (cfg->defaultImage > -1) {      else if (cfg->defaultImage > -1) {
1193   if (cfg->cfi->defaultIsIndex) {   if (cfg->cfi->defaultIsIndex) {
1194      fprintf(out, "%sdefault%s%d\n", indent, separator,      if (cfg->cfi->defaultIsVariable) {
1195      cfg->defaultImage);          fprintf(out, "%sset default=\"%d\"\n", indent,
1196     cfg->defaultImage);
1197        } else {
1198     fprintf(out, "%sdefault%s%d\n", indent, separator,
1199     cfg->defaultImage);
1200        }
1201   } else {   } else {
1202      int image = cfg->defaultImage;      int image = cfg->defaultImage;
1203    
# Line 1086  static int writeConfig(struct grubConfig Line 1287  static int writeConfig(struct grubConfig
1287      }      }
1288    
1289      line = cfg->theLines;      line = cfg->theLines;
1290        struct keywordTypes *defaultKw = getKeywordByType(LT_DEFAULT, cfg->cfi);
1291      while (line) {      while (line) {
1292   if (line->type == LT_DEFAULT) {          if (line->type == LT_SET_VARIABLE && defaultKw &&
1293     line->numElements == 3 &&
1294     !strcmp(line->elements[1].item, defaultKw->key)) {
1295        writeDefault(out, line->indent, line->elements[0].indent, cfg);
1296        needs &= ~MAIN_DEFAULT;
1297     } else if (line->type == LT_DEFAULT) {
1298      writeDefault(out, line->indent, line->elements[0].indent, cfg);      writeDefault(out, line->indent, line->elements[0].indent, cfg);
1299      needs &= ~MAIN_DEFAULT;      needs &= ~MAIN_DEFAULT;
1300   } else if (line->type == LT_FALLBACK) {   } else if (line->type == LT_FALLBACK) {
# Line 1155  static int numEntries(struct grubConfig Line 1362  static int numEntries(struct grubConfig
1362      return i;      return i;
1363  }  }
1364    
1365    static char *findDiskForRoot()
1366    {
1367        int fd;
1368        char buf[65536];
1369        char *devname;
1370        char *chptr;
1371        int rc;
1372    
1373        if ((fd = open(_PATH_MOUNTED, O_RDONLY)) < 0) {
1374            fprintf(stderr, "grubby: failed to open %s: %s\n",
1375                    _PATH_MOUNTED, strerror(errno));
1376            return NULL;
1377        }
1378    
1379        rc = read(fd, buf, sizeof(buf) - 1);
1380        if (rc <= 0) {
1381            fprintf(stderr, "grubby: failed to read %s: %s\n",
1382                    _PATH_MOUNTED, strerror(errno));
1383            close(fd);
1384            return NULL;
1385        }
1386        close(fd);
1387        buf[rc] = '\0';
1388        chptr = buf;
1389    
1390        while (chptr && chptr != buf+rc) {
1391            devname = chptr;
1392    
1393            /*
1394             * The first column of a mtab entry is the device, but if the entry is a
1395             * special device it won't start with /, so move on to the next line.
1396             */
1397            if (*devname != '/') {
1398                chptr = strchr(chptr, '\n');
1399                if (chptr)
1400                    chptr++;
1401                continue;
1402            }
1403    
1404            /* Seek to the next space */
1405            chptr = strchr(chptr, ' ');
1406            if (!chptr) {
1407                fprintf(stderr, "grubby: error parsing %s: %s\n",
1408                        _PATH_MOUNTED, strerror(errno));
1409                return NULL;
1410            }
1411    
1412            /*
1413             * The second column of a mtab entry is the mount point, we are looking
1414             * for '/' obviously.
1415             */
1416            if (*(++chptr) == '/' && *(++chptr) == ' ') {
1417                /*
1418                 * Move back 2, which is the first space after the device name, set
1419                 * it to \0 so strdup will just get the devicename.
1420                 */
1421                chptr -= 2;
1422                *chptr = '\0';
1423                return strdup(devname);
1424            }
1425    
1426            /* Next line */
1427            chptr = strchr(chptr, '\n');
1428            if (chptr)
1429                chptr++;
1430        }
1431    
1432        return NULL;
1433    }
1434    
1435    void printEntry(struct singleEntry * entry) {
1436        int i;
1437        struct singleLine * line;
1438    
1439        for (line = entry->lines; line; line = line->next) {
1440     fprintf(stderr, "DBG: %s", line->indent);
1441     for (i = 0; i < line->numElements; i++) {
1442     fprintf(stderr, "%s%s",
1443        line->elements[i].item, line->elements[i].indent);
1444     }
1445     fprintf(stderr, "\n");
1446        }
1447    }
1448    
1449    void notSuitablePrintf(struct singleEntry * entry, const char *fmt, ...)
1450    {
1451        va_list argp;
1452    
1453        if (!debug)
1454     return;
1455    
1456        va_start(argp, fmt);
1457        fprintf(stderr, "DBG: Image entry failed: ");
1458        vfprintf(stderr, fmt, argp);
1459        printEntry(entry);
1460        va_end(argp);
1461    }
1462    
1463    #define beginswith(s, c) ((s) && (s)[0] == (c))
1464    
1465    static int endswith(const char *s, char c)
1466    {
1467     int slen;
1468    
1469     if (!s || !s[0])
1470     return 0;
1471     slen = strlen(s) - 1;
1472    
1473     return s[slen] == c;
1474    }
1475    
1476  int suitableImage(struct singleEntry * entry, const char * bootPrefix,  int suitableImage(struct singleEntry * entry, const char * bootPrefix,
1477    int skipRemoved, int flags) {    int skipRemoved, int flags) {
1478      struct singleLine * line;      struct singleLine * line;
1479      char * fullName;      char * fullName;
1480      int i;      int i;
     struct stat sb, sb2;  
1481      char * dev;      char * dev;
1482      char * rootspec;      char * rootspec;
1483        char * rootdev;
1484    
1485      if (skipRemoved && entry->skip) return 0;      if (skipRemoved && entry->skip) {
1486     notSuitablePrintf(entry, "marked to skip\n");
1487     return 0;
1488        }
1489    
1490      line = getLineByType(LT_KERNEL|LT_HYPER, entry->lines);      line = getLineByType(LT_KERNEL|LT_HYPER, entry->lines);
1491      if (!line || line->numElements < 2) return 0;      if (!line) {
1492     notSuitablePrintf(entry, "no line found\n");
1493     return 0;
1494        }
1495        if (line->numElements < 2) {
1496     notSuitablePrintf(entry, "line has only %d elements\n",
1497        line->numElements);
1498     return 0;
1499        }
1500    
1501      if (flags & GRUBBY_BADIMAGE_OKAY) return 1;      if (flags & GRUBBY_BADIMAGE_OKAY) return 1;
1502    
1503      fullName = alloca(strlen(bootPrefix) +      fullName = alloca(strlen(bootPrefix) +
1504        strlen(line->elements[1].item) + 1);        strlen(line->elements[1].item) + 1);
1505      rootspec = getRootSpecifier(line->elements[1].item);      rootspec = getRootSpecifier(line->elements[1].item);
1506      sprintf(fullName, "%s%s", bootPrefix,      int rootspec_offset = rootspec ? strlen(rootspec) : 0;
1507              line->elements[1].item + (rootspec ? strlen(rootspec) : 0));      int hasslash = endswith(bootPrefix, '/') ||
1508      if (access(fullName, R_OK)) return 0;       beginswith(line->elements[1].item + rootspec_offset, '/');
1509        sprintf(fullName, "%s%s%s", bootPrefix, hasslash ? "" : "/",
1510                line->elements[1].item + rootspec_offset);
1511        if (access(fullName, R_OK)) {
1512     notSuitablePrintf(entry, "access to %s failed\n", fullName);
1513     return 0;
1514        }
1515      for (i = 2; i < line->numElements; i++)      for (i = 2; i < line->numElements; i++)
1516   if (!strncasecmp(line->elements[i].item, "root=", 5)) break;   if (!strncasecmp(line->elements[i].item, "root=", 5)) break;
1517      if (i < line->numElements) {      if (i < line->numElements) {
# Line 1195  int suitableImage(struct singleEntry * e Line 1529  int suitableImage(struct singleEntry * e
1529      line = getLineByType(LT_KERNELARGS|LT_MBMODULE, entry->lines);      line = getLineByType(LT_KERNELARGS|LT_MBMODULE, entry->lines);
1530    
1531              /* failed to find one */              /* failed to find one */
1532              if (!line) return 0;              if (!line) {
1533     notSuitablePrintf(entry, "no line found\n");
1534     return 0;
1535                }
1536    
1537      for (i = 1; i < line->numElements; i++)      for (i = 1; i < line->numElements; i++)
1538          if (!strncasecmp(line->elements[i].item, "root=", 5)) break;          if (!strncasecmp(line->elements[i].item, "root=", 5)) break;
1539      if (i < line->numElements)      if (i < line->numElements)
1540          dev = line->elements[i].item + 5;          dev = line->elements[i].item + 5;
1541      else {      else {
1542     notSuitablePrintf(entry, "no root= entry found\n");
1543   /* it failed too...  can't find root= */   /* it failed too...  can't find root= */
1544          return 0;          return 0;
1545              }              }
# Line 1209  int suitableImage(struct singleEntry * e Line 1547  int suitableImage(struct singleEntry * e
1547      }      }
1548    
1549      dev = getpathbyspec(dev);      dev = getpathbyspec(dev);
1550      if (!dev)      if (!getpathbyspec(dev)) {
1551            notSuitablePrintf(entry, "can't find blkid entry for %s\n", dev);
1552          return 0;          return 0;
1553        } else
1554     dev = getpathbyspec(dev);
1555    
1556      i = stat(dev, &sb);      rootdev = findDiskForRoot();
1557      if (i)      if (!rootdev) {
1558            notSuitablePrintf(entry, "can't find root device\n");
1559   return 0;   return 0;
1560        }
1561    
1562      stat("/", &sb2);      if (!getuuidbydev(rootdev) || !getuuidbydev(dev)) {
1563            notSuitablePrintf(entry, "uuid missing: rootdev %s, dev %s\n",
1564     getuuidbydev(rootdev), getuuidbydev(dev));
1565            free(rootdev);
1566            return 0;
1567        }
1568    
1569      if (sb.st_rdev != sb2.st_dev)      if (strcmp(getuuidbydev(rootdev), getuuidbydev(dev))) {
1570            notSuitablePrintf(entry, "uuid mismatch: rootdev %s, dev %s\n",
1571     getuuidbydev(rootdev), getuuidbydev(dev));
1572     free(rootdev);
1573          return 0;          return 0;
1574        }
1575    
1576        free(rootdev);
1577    
1578      return 1;      return 1;
1579  }  }
# Line 1442  void setDefaultImage(struct grubConfig * Line 1796  void setDefaultImage(struct grubConfig *
1796    
1797      /* 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
1798         changes */         changes */
1799      if (config->defaultImage == DEFAULT_SAVED)      if ((config->defaultImage == DEFAULT_SAVED) ||
1800     (config->defaultImage == DEFAULT_SAVED_GRUB2))
1801        /* default is set to saved, we don't want to change it */        /* default is set to saved, we don't want to change it */
1802        return;        return;
1803    
# Line 1509  void displayEntry(struct singleEntry * e Line 1864  void displayEntry(struct singleEntry * e
1864          return;          return;
1865      }      }
1866    
1867      printf("kernel=%s\n", line->elements[1].item);      printf("kernel=%s%s\n", prefix, line->elements[1].item);
1868    
1869      if (line->numElements >= 3) {      if (line->numElements >= 3) {
1870   printf("args=\"");   printf("args=\"");
# Line 1573  void displayEntry(struct singleEntry * e Line 1928  void displayEntry(struct singleEntry * e
1928      printf("%s%s", line->elements[i].item, line->elements[i].indent);      printf("%s%s", line->elements[i].item, line->elements[i].indent);
1929   printf("\n");   printf("\n");
1930      }      }
1931    
1932        line = getLineByType(LT_TITLE, entry->lines);
1933        if (line) {
1934     printf("title=%s\n", line->elements[1].item);
1935        } else {
1936     char * title;
1937     line = getLineByType(LT_MENUENTRY, entry->lines);
1938     title = grub2ExtractTitle(line);
1939     if (title)
1940        printf("title=%s\n", title);
1941        }
1942  }  }
1943    
1944  int parseSysconfigGrub(int * lbaPtr, char ** bootPtr) {  int parseSysconfigGrub(int * lbaPtr, char ** bootPtr) {
# Line 1733  struct singleLine *  addLine(struct sing Line 2099  struct singleLine *  addLine(struct sing
2099   sprintf(tmpl.elements[0].item, "[%s]", val);   sprintf(tmpl.elements[0].item, "[%s]", val);
2100   tmpl.elements[0].indent = "";   tmpl.elements[0].indent = "";
2101   val = NULL;   val = NULL;
2102        } else if (type == LT_MENUENTRY) {
2103     char *lineend = "--class gnu-linux --class gnu --class os {";
2104     if (!val) {
2105        fprintf(stderr, "Line type LT_MENUENTRY requires a value\n");
2106        abort();
2107     }
2108     kw = getKeywordByType(type, cfi);
2109     if (!kw) {
2110        fprintf(stderr, "Looking up keyword for unknown type %d\n", type);
2111        abort();
2112     }
2113     tmpl.indent = "";
2114     tmpl.type = type;
2115     tmpl.numElements = 3;
2116     tmpl.elements = alloca(sizeof(*tmpl.elements) * tmpl.numElements);
2117     tmpl.elements[0].item = kw->key;
2118     tmpl.elements[0].indent = alloca(2);
2119     sprintf(tmpl.elements[0].indent, "%c", kw->nextChar);
2120     tmpl.elements[1].item = (char *)val;
2121     tmpl.elements[1].indent = alloca(2);
2122     sprintf(tmpl.elements[1].indent, "%c", kw->nextChar);
2123     tmpl.elements[2].item = alloca(strlen(lineend)+1);
2124     strcpy(tmpl.elements[2].item, lineend);
2125     tmpl.elements[2].indent = "";
2126      } else {      } else {
2127   kw = getKeywordByType(type, cfi);   kw = getKeywordByType(type, cfi);
2128   if (!kw) abort();   if (!kw) {
2129        fprintf(stderr, "Looking up keyword for unknown type %d\n", type);
2130        abort();
2131     }
2132   tmpl.type = type;   tmpl.type = type;
2133   tmpl.numElements = val ? 2 : 1;   tmpl.numElements = val ? 2 : 1;
2134   tmpl.elements = alloca(sizeof(*tmpl.elements) * tmpl.numElements);   tmpl.elements = alloca(sizeof(*tmpl.elements) * tmpl.numElements);
# Line 1759  struct singleLine *  addLine(struct sing Line 2152  struct singleLine *  addLine(struct sing
2152   if (!line->next && !prev) prev = line;   if (!line->next && !prev) prev = line;
2153      }      }
2154    
2155      if (prev == entry->lines)      struct singleLine *menuEntry;
2156   tmpl.indent = defaultIndent ?: "";      menuEntry = getLineByType(LT_MENUENTRY, entry->lines);
2157      else      if (tmpl.type == LT_ENTRY_END) {
2158   tmpl.indent = prev->indent;   if (menuEntry)
2159        tmpl.indent = menuEntry->indent;
2160     else
2161        tmpl.indent = defaultIndent ?: "";
2162        } else if (tmpl.type != LT_MENUENTRY) {
2163     if (menuEntry)
2164        tmpl.indent = "\t";
2165     else if (prev == entry->lines)
2166        tmpl.indent = defaultIndent ?: "";
2167     else
2168        tmpl.indent = prev->indent;
2169        }
2170    
2171      return addLineTmpl(entry, &tmpl, prev, val, cfi);      return addLineTmpl(entry, &tmpl, prev, val, cfi);
2172  }  }
# Line 1789  void removeLine(struct singleEntry * ent Line 2193  void removeLine(struct singleEntry * ent
2193      free(line);      free(line);
2194  }  }
2195    
2196    static void requote(struct singleLine *tmplLine, struct configFileInfo * cfi)
2197    {
2198        struct singleLine newLine = {
2199     .indent = tmplLine->indent,
2200     .type = tmplLine->type,
2201     .next = tmplLine->next,
2202        };
2203        int firstQuotedItem = -1;
2204        int quoteLen = 0;
2205        int j;
2206        int element = 0;
2207        char *c;
2208    
2209        c = malloc(strlen(tmplLine->elements[0].item) + 1);
2210        strcpy(c, tmplLine->elements[0].item);
2211        insertElement(&newLine, c, element++, cfi);
2212        free(c);
2213        c = NULL;
2214    
2215        for (j = 1; j < tmplLine->numElements; j++) {
2216     if (firstQuotedItem == -1) {
2217        quoteLen += strlen(tmplLine->elements[j].item);
2218        
2219        if (isquote(tmplLine->elements[j].item[0])) {
2220     firstQuotedItem = j;
2221            quoteLen += strlen(tmplLine->elements[j].indent);
2222        } else {
2223     c = malloc(quoteLen + 1);
2224     strcpy(c, tmplLine->elements[j].item);
2225     insertElement(&newLine, c, element++, cfi);
2226     free(c);
2227     quoteLen = 0;
2228        }
2229     } else {
2230        int itemlen = strlen(tmplLine->elements[j].item);
2231        quoteLen += itemlen;
2232        quoteLen += strlen(tmplLine->elements[j].indent);
2233        
2234        if (isquote(tmplLine->elements[j].item[itemlen - 1])) {
2235     c = malloc(quoteLen + 1);
2236     c[0] = '\0';
2237     for (int i = firstQuotedItem; i < j+1; i++) {
2238        strcat(c, tmplLine->elements[i].item);
2239        strcat(c, tmplLine->elements[i].indent);
2240     }
2241     insertElement(&newLine, c, element++, cfi);
2242     free(c);
2243    
2244     firstQuotedItem = -1;
2245     quoteLen = 0;
2246        }
2247     }
2248        }
2249        while (tmplLine->numElements)
2250     removeElement(tmplLine, 0);
2251        if (tmplLine->elements)
2252     free(tmplLine->elements);
2253    
2254        tmplLine->numElements = newLine.numElements;
2255        tmplLine->elements = newLine.elements;
2256    }
2257    
2258  static void insertElement(struct singleLine * line,  static void insertElement(struct singleLine * line,
2259    const char * item, int insertHere,    const char * item, int insertHere,
2260    struct configFileInfo * cfi)    struct configFileInfo * cfi)
# Line 1895  int updateActualImage(struct grubConfig Line 2361  int updateActualImage(struct grubConfig
2361      const char ** arg;      const char ** arg;
2362      int useKernelArgs, useRoot;      int useKernelArgs, useRoot;
2363      int firstElement;      int firstElement;
2364      int *usedElements, *usedArgs;      int *usedElements;
2365      int doreplace;      int doreplace;
2366    
2367      if (!image) return 0;      if (!image) return 0;
# Line 1930  int updateActualImage(struct grubConfig Line 2396  int updateActualImage(struct grubConfig
2396      useRoot = (getKeywordByType(LT_ROOT, cfg->cfi)      useRoot = (getKeywordByType(LT_ROOT, cfg->cfi)
2397         && !multibootArgs);         && !multibootArgs);
2398    
     for (k = 0, arg = newArgs; *arg; arg++, k++) ;  
     usedArgs = calloc(k, sizeof(*usedArgs));  
   
2399      for (; (entry = findEntryByPath(cfg, image, prefix, &index)); index++) {      for (; (entry = findEntryByPath(cfg, image, prefix, &index)); index++) {
2400    
2401   if (multibootArgs && !entry->multiboot)   if (multibootArgs && !entry->multiboot)
# Line 2008  int updateActualImage(struct grubConfig Line 2471  int updateActualImage(struct grubConfig
2471          usedElements = calloc(line->numElements, sizeof(*usedElements));          usedElements = calloc(line->numElements, sizeof(*usedElements));
2472    
2473   for (k = 0, arg = newArgs; *arg; arg++, k++) {   for (k = 0, arg = newArgs; *arg; arg++, k++) {
             if (usedArgs[k]) continue;  
2474    
2475      doreplace = 1;      doreplace = 1;
2476      for (i = firstElement; i < line->numElements; i++) {      for (i = firstElement; i < line->numElements; i++) {
# Line 2023  int updateActualImage(struct grubConfig Line 2485  int updateActualImage(struct grubConfig
2485                      continue;                      continue;
2486   if (!argMatch(line->elements[i].item, *arg)) {   if (!argMatch(line->elements[i].item, *arg)) {
2487                      usedElements[i]=1;                      usedElements[i]=1;
                     usedArgs[k]=1;  
2488      break;      break;
2489                  }                  }
2490              }              }
# Line 2093  int updateActualImage(struct grubConfig Line 2554  int updateActualImage(struct grubConfig
2554   }   }
2555      }      }
2556    
     free(usedArgs);  
2557      free(newArgs);      free(newArgs);
2558      free(oldArgs);      free(oldArgs);
2559    
# Line 2119  int updateImage(struct grubConfig * cfg, Line 2579  int updateImage(struct grubConfig * cfg,
2579      return rc;      return rc;
2580  }  }
2581    
2582    int updateInitrd(struct grubConfig * cfg, const char * image,
2583                     const char * prefix, const char * initrd) {
2584        struct singleEntry * entry;
2585        struct singleLine * line, * kernelLine, *endLine = NULL;
2586        int index = 0;
2587    
2588        if (!image) return 0;
2589    
2590        for (; (entry = findEntryByPath(cfg, image, prefix, &index)); index++) {
2591            kernelLine = getLineByType(LT_KERNEL, entry->lines);
2592            if (!kernelLine) continue;
2593    
2594            line = getLineByType(LT_INITRD, entry->lines);
2595            if (line)
2596                removeLine(entry, line);
2597            if (prefix) {
2598                int prefixLen = strlen(prefix);
2599                if (!strncmp(initrd, prefix, prefixLen))
2600                    initrd += prefixLen;
2601            }
2602     endLine = getLineByType(LT_ENTRY_END, entry->lines);
2603     if (endLine)
2604        removeLine(entry, endLine);
2605            line = addLine(entry, cfg->cfi, LT_INITRD, kernelLine->indent, initrd);
2606            if (!line)
2607        return 1;
2608     if (endLine) {
2609        line = addLine(entry, cfg->cfi, LT_ENTRY_END, "", NULL);
2610                if (!line)
2611     return 1;
2612     }
2613    
2614            break;
2615        }
2616    
2617        return 0;
2618    }
2619    
2620  int checkDeviceBootloader(const char * device, const unsigned char * boot) {  int checkDeviceBootloader(const char * device, const unsigned char * boot) {
2621      int fd;      int fd;
2622      unsigned char bootSect[512];      unsigned char bootSect[512];
# Line 2142  int checkDeviceBootloader(const char * d Line 2640  int checkDeviceBootloader(const char * d
2640      if (memcmp(boot, bootSect, 3))      if (memcmp(boot, bootSect, 3))
2641   return 0;   return 0;
2642    
2643      if (boot[1] == 0xeb) {      if (boot[1] == JMP_SHORT_OPCODE) {
2644   offset = boot[2] + 2;   offset = boot[2] + 2;
2645      } else if (boot[1] == 0xe8 || boot[1] == 0xe9) {      } else if (boot[1] == 0xe8 || boot[1] == 0xe9) {
2646   offset = (boot[3] << 8) + boot[2] + 2;   offset = (boot[3] << 8) + boot[2] + 2;
2647      } else if (boot[0] == 0xeb) {      } else if (boot[0] == JMP_SHORT_OPCODE) {
2648   offset = boot[1] + 2;        offset = boot[1] + 2;
2649            /*
2650     * it looks like grub, when copying stage1 into the mbr, patches stage1
2651     * right after the JMP location, replacing other instructions such as
2652     * JMPs for NOOPs. So, relax the check a little bit by skipping those
2653     * different bytes.
2654     */
2655          if ((bootSect[offset + 1] == NOOP_OPCODE)
2656      && (bootSect[offset + 2] == NOOP_OPCODE)) {
2657     offset = offset + 3;
2658          }
2659      } else if (boot[0] == 0xe8 || boot[0] == 0xe9) {      } else if (boot[0] == 0xe8 || boot[0] == 0xe9) {
2660   offset = (boot[2] << 8) + boot[1] + 2;   offset = (boot[2] << 8) + boot[1] + 2;
2661      } else {      } else {
# Line 2289  int checkForLilo(struct grubConfig * con Line 2797  int checkForLilo(struct grubConfig * con
2797      return checkDeviceBootloader(line->elements[1].item, boot);      return checkDeviceBootloader(line->elements[1].item, boot);
2798  }  }
2799    
2800    int checkForGrub2(struct grubConfig * config) {
2801        if (!access("/etc/grub.d/", R_OK))
2802     return 2;
2803    
2804        return 1;
2805    }
2806    
2807  int checkForGrub(struct grubConfig * config) {  int checkForGrub(struct grubConfig * config) {
2808      int fd;      int fd;
2809      unsigned char bootSect[512];      unsigned char bootSect[512];
# Line 2464  int addNewKernel(struct grubConfig * con Line 2979  int addNewKernel(struct grubConfig * con
2979      if (*chptr == '#') continue;      if (*chptr == '#') continue;
2980    
2981      if (tmplLine->type == LT_KERNEL &&      if (tmplLine->type == LT_KERNEL &&
2982   tmplLine->numElements >= 2) {      tmplLine->numElements >= 2) {
2983   if (!template->multiboot && (needs & NEED_MB)) {   if (!template->multiboot && (needs & NEED_MB)) {
2984      /* it's not a multiboot template and this is the kernel      /* it's not a multiboot template and this is the kernel
2985       * line.  Try to be intelligent about inserting the       * line.  Try to be intelligent about inserting the
# Line 2590  int addNewKernel(struct grubConfig * con Line 3105  int addNewKernel(struct grubConfig * con
3105      needs &= ~NEED_INITRD;      needs &= ~NEED_INITRD;
3106   }   }
3107    
3108        } else if (tmplLine->type == LT_MENUENTRY &&
3109           (needs & NEED_TITLE)) {
3110     requote(tmplLine, config->cfi);
3111     char *nkt = malloc(strlen(newKernelTitle)+3);
3112     strcpy(nkt, "'");
3113     strcat(nkt, newKernelTitle);
3114     strcat(nkt, "'");
3115     newLine = addLineTmpl(new, tmplLine, newLine, nkt, config->cfi);
3116     free(nkt);
3117     needs &= ~NEED_TITLE;
3118      } else if (tmplLine->type == LT_TITLE &&      } else if (tmplLine->type == LT_TITLE &&
3119         (needs & NEED_TITLE)) {         (needs & NEED_TITLE)) {
3120   if (tmplLine->numElements >= 2) {   if (tmplLine->numElements >= 2) {
# Line 2603  int addNewKernel(struct grubConfig * con Line 3128  int addNewKernel(struct grubConfig * con
3128        tmplLine->indent, newKernelTitle);        tmplLine->indent, newKernelTitle);
3129      needs &= ~NEED_TITLE;      needs &= ~NEED_TITLE;
3130   }   }
3131        } else if (tmplLine->type == LT_ECHO) {
3132        requote(tmplLine, config->cfi);
3133        static const char *prefix = "'Loading ";
3134        if (tmplLine->numElements > 1 &&
3135        strstr(tmplLine->elements[1].item, prefix) &&
3136        masterLine->next && masterLine->next->type == LT_KERNEL) {
3137     char *newTitle = malloc(strlen(prefix) +
3138     strlen(newKernelTitle) + 2);
3139    
3140     strcpy(newTitle, prefix);
3141     strcat(newTitle, newKernelTitle);
3142     strcat(newTitle, "'");
3143     newLine = addLine(new, config->cfi, LT_ECHO,
3144     tmplLine->indent, newTitle);
3145     free(newTitle);
3146        } else {
3147     /* pass through other lines from the template */
3148     newLine = addLineTmpl(new, tmplLine, newLine, NULL,
3149     config->cfi);
3150        }
3151      } else {      } else {
3152   /* pass through other lines from the template */   /* pass through other lines from the template */
3153   newLine = addLineTmpl(new, tmplLine, newLine, NULL, config->cfi);   newLine = addLineTmpl(new, tmplLine, newLine, NULL, config->cfi);
# Line 2614  int addNewKernel(struct grubConfig * con Line 3158  int addNewKernel(struct grubConfig * con
3158   /* don't have a template, so start the entry with the   /* don't have a template, so start the entry with the
3159   * appropriate starting line   * appropriate starting line
3160   */   */
3161   switch (config->cfi->entrySeparator) {   switch (config->cfi->entryStart) {
3162      case LT_KERNEL:      case LT_KERNEL:
3163   if (new->multiboot && config->cfi->mbHyperFirst) {   if (new->multiboot && config->cfi->mbHyperFirst) {
3164      /* fall through to LT_HYPER */      /* fall through to LT_HYPER */
# Line 2633  int addNewKernel(struct grubConfig * con Line 3177  int addNewKernel(struct grubConfig * con
3177   needs &= ~NEED_MB;   needs &= ~NEED_MB;
3178   break;   break;
3179    
3180        case LT_MENUENTRY: {
3181     char *nkt = malloc(strlen(newKernelTitle)+3);
3182     strcpy(nkt, "'");
3183     strcat(nkt, newKernelTitle);
3184     strcat(nkt, "'");
3185            newLine = addLine(new, config->cfi, LT_MENUENTRY,
3186      config->primaryIndent, nkt);
3187     free(nkt);
3188     needs &= ~NEED_TITLE;
3189     needs |= NEED_END;
3190     break;
3191        }
3192      case LT_TITLE:      case LT_TITLE:
3193   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)
3194   char * templabel;   char * templabel;
# Line 2666  int addNewKernel(struct grubConfig * con Line 3222  int addNewKernel(struct grubConfig * con
3222    
3223      /* add the remainder of the lines, i.e. those that either      /* add the remainder of the lines, i.e. those that either
3224       * 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,
3225       * all the lines following the entrySeparator.       * all the lines following the entryStart.
3226       */       */
3227      if (needs & NEED_TITLE) {      if (needs & NEED_TITLE) {
3228   newLine = addLine(new, config->cfi, LT_TITLE,   newLine = addLine(new, config->cfi, LT_TITLE,
# Line 2707  int addNewKernel(struct grubConfig * con Line 3263  int addNewKernel(struct grubConfig * con
3263   free(initrdVal);   free(initrdVal);
3264   needs &= ~NEED_INITRD;   needs &= ~NEED_INITRD;
3265      }      }
3266        if (needs & NEED_END) {
3267     newLine = addLine(new, config->cfi, LT_ENTRY_END,
3268     config->secondaryIndent, NULL);
3269     needs &= ~NEED_END;
3270        }
3271    
3272      if (needs) {      if (needs) {
3273   printf(_("grubby: needs=%d, aborting\n"), needs);   printf(_("grubby: needs=%d, aborting\n"), needs);
# Line 2736  static void traceback(int signum) Line 3297  static void traceback(int signum)
3297    
3298  int main(int argc, const char ** argv) {  int main(int argc, const char ** argv) {
3299      poptContext optCon;      poptContext optCon;
3300      char * grubConfig = NULL;      const char * grubConfig = NULL;
3301      char * outputFile = NULL;      char * outputFile = NULL;
3302      int arg = 0;      int arg = 0;
3303      int flags = 0;      int flags = 0;
3304      int badImageOkay = 0;      int badImageOkay = 0;
3305        int configureGrub2 = 0;
3306      int configureLilo = 0, configureELilo = 0, configureGrub = 0;      int configureLilo = 0, configureELilo = 0, configureGrub = 0;
3307      int configureYaboot = 0, configureSilo = 0, configureZipl = 0;      int configureYaboot = 0, configureSilo = 0, configureZipl = 0;
3308      int configureExtLinux = 0;      int configureExtLinux = 0;
# Line 2768  int main(int argc, const char ** argv) { Line 3330  int main(int argc, const char ** argv) {
3330      struct singleEntry * template = NULL;      struct singleEntry * template = NULL;
3331      int copyDefault = 0, makeDefault = 0;      int copyDefault = 0, makeDefault = 0;
3332      int displayDefault = 0;      int displayDefault = 0;
3333        int displayDefaultIndex = 0;
3334        int displayDefaultTitle = 0;
3335      struct poptOption options[] = {      struct poptOption options[] = {
3336   { "add-kernel", 0, POPT_ARG_STRING, &newKernelPath, 0,   { "add-kernel", 0, POPT_ARG_STRING, &newKernelPath, 0,
3337      _("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 3362  int main(int argc, const char ** argv) {
3362        "the kernel referenced by the default image does not exist, "        "the kernel referenced by the default image does not exist, "
3363        "the first linux entry whose kernel does exist is used as the "        "the first linux entry whose kernel does exist is used as the "
3364        "template"), NULL },        "template"), NULL },
3365     { "debug", 0, 0, &debug, 0,
3366        _("print debugging information for failures") },
3367   { "default-kernel", 0, 0, &displayDefault, 0,   { "default-kernel", 0, 0, &displayDefault, 0,
3368      _("display the path of the default kernel") },      _("display the path of the default kernel") },
3369     { "default-index", 0, 0, &displayDefaultIndex, 0,
3370        _("display the index of the default kernel") },
3371     { "default-title", 0, 0, &displayDefaultTitle, 0,
3372        _("display the title of the default kernel") },
3373   { "elilo", 0, POPT_ARG_NONE, &configureELilo, 0,   { "elilo", 0, POPT_ARG_NONE, &configureELilo, 0,
3374      _("configure elilo bootloader") },      _("configure elilo bootloader") },
3375   { "extlinux", 0, POPT_ARG_NONE, &configureExtLinux, 0,   { "extlinux", 0, POPT_ARG_NONE, &configureExtLinux, 0,
3376      _("configure extlinux bootloader (from syslinux)") },      _("configure extlinux bootloader (from syslinux)") },
3377   { "grub", 0, POPT_ARG_NONE, &configureGrub, 0,   { "grub", 0, POPT_ARG_NONE, &configureGrub, 0,
3378      _("configure grub bootloader") },      _("configure grub bootloader") },
3379     { "grub2", 0, POPT_ARG_NONE, &configureGrub2, 0,
3380        _("configure grub2 bootloader") },
3381   { "info", 0, POPT_ARG_STRING, &kernelInfo, 0,   { "info", 0, POPT_ARG_STRING, &kernelInfo, 0,
3382      _("display boot information for specified kernel"),      _("display boot information for specified kernel"),
3383      _("kernel-path") },      _("kernel-path") },
# Line 2885  int main(int argc, const char ** argv) { Line 3457  int main(int argc, const char ** argv) {
3457   return 1;   return 1;
3458      }      }
3459    
3460      if ((configureLilo + configureGrub + configureELilo +      if ((configureLilo + configureGrub2 + configureGrub + configureELilo +
3461   configureYaboot + configureSilo + configureZipl +   configureYaboot + configureSilo + configureZipl +
3462   configureExtLinux ) > 1) {   configureExtLinux ) > 1) {
3463   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 3466  int main(int argc, const char ** argv) {
3466   fprintf(stderr,   fprintf(stderr,
3467      _("grubby: cannot specify config file with --bootloader-probe\n"));      _("grubby: cannot specify config file with --bootloader-probe\n"));
3468   return 1;   return 1;
3469        } else if (configureGrub2) {
3470     cfi = &grub2ConfigType;
3471      } else if (configureLilo) {      } else if (configureLilo) {
3472   cfi = &liloConfigType;   cfi = &liloConfigType;
3473      } else if (configureGrub) {      } else if (configureGrub) {
# Line 2923  int main(int argc, const char ** argv) { Line 3497  int main(int argc, const char ** argv) {
3497        #elif __s390x__        #elif __s390x__
3498          cfi = &ziplConfigtype;          cfi = &ziplConfigtype;
3499        #else        #else
3500   cfi = &grubConfigType;          if (grub2FindConfig(&grub2ConfigType))
3501        cfi = &grub2ConfigType;
3502     else
3503        cfi = &grubConfigType;
3504        #endif        #endif
3505      }      }
3506    
3507      if (!grubConfig)      if (!grubConfig) {
3508   grubConfig = cfi->defaultConfig;   if (cfi->findConfig)
3509        grubConfig = cfi->findConfig(cfi);
3510     if (!grubConfig)
3511        grubConfig = cfi->defaultConfig;
3512        }
3513    
3514      if (bootloaderProbe && (displayDefault || kernelInfo || newKernelVersion ||      if (bootloaderProbe && (displayDefault || kernelInfo || newKernelVersion ||
3515    newKernelPath || removeKernelPath || makeDefault ||    newKernelPath || removeKernelPath || makeDefault ||
3516    defaultKernel)) {    defaultKernel || displayDefaultIndex || displayDefaultTitle)) {
3517   fprintf(stderr, _("grubby: --bootloader-probe may not be used with "   fprintf(stderr, _("grubby: --bootloader-probe may not be used with "
3518    "specified option"));    "specified option"));
3519   return 1;   return 1;
# Line 2948  int main(int argc, const char ** argv) { Line 3529  int main(int argc, const char ** argv) {
3529      if (newKernelPath && !newKernelTitle) {      if (newKernelPath && !newKernelTitle) {
3530   fprintf(stderr, _("grubby: kernel title must be specified\n"));   fprintf(stderr, _("grubby: kernel title must be specified\n"));
3531   return 1;   return 1;
3532      } else if (!newKernelPath && (newKernelTitle  || newKernelInitrd ||      } else if (!newKernelPath && (newKernelTitle  || copyDefault ||
3533    newKernelInitrd || copyDefault     ||    (newKernelInitrd && !updateKernelPath)||
3534    makeDefault || extraInitrdCount > 0)) {    makeDefault || extraInitrdCount > 0)) {
3535   fprintf(stderr, _("grubby: kernel path expected\n"));   fprintf(stderr, _("grubby: kernel path expected\n"));
3536   return 1;   return 1;
# Line 2975  int main(int argc, const char ** argv) { Line 3556  int main(int argc, const char ** argv) {
3556   defaultKernel = NULL;   defaultKernel = NULL;
3557      }      }
3558    
3559      if (!strcmp(grubConfig, "-") && !outputFile) {      if (grubConfig && !strcmp(grubConfig, "-") && !outputFile) {
3560   fprintf(stderr, _("grubby: output file must be specified if stdin "   fprintf(stderr, _("grubby: output file must be specified if stdin "
3561   "is used\n"));   "is used\n"));
3562   return 1;   return 1;
# Line 2983  int main(int argc, const char ** argv) { Line 3564  int main(int argc, const char ** argv) {
3564    
3565      if (!removeKernelPath && !newKernelPath && !displayDefault && !defaultKernel      if (!removeKernelPath && !newKernelPath && !displayDefault && !defaultKernel
3566   && !kernelInfo && !bootloaderProbe && !updateKernelPath   && !kernelInfo && !bootloaderProbe && !updateKernelPath
3567          && !removeMBKernel) {          && !removeMBKernel && !displayDefaultIndex && !displayDefaultTitle) {
3568   fprintf(stderr, _("grubby: no action specified\n"));   fprintf(stderr, _("grubby: no action specified\n"));
3569   return 1;   return 1;
3570      }      }
# Line 3010  int main(int argc, const char ** argv) { Line 3591  int main(int argc, const char ** argv) {
3591      }      }
3592    
3593      if (bootloaderProbe) {      if (bootloaderProbe) {
3594   int lrc = 0, grc = 0, erc = 0;   int lrc = 0, grc = 0, gr2c = 0, erc = 0;
3595   struct grubConfig * lconfig, * gconfig;   struct grubConfig * lconfig, * gconfig;
3596    
3597   if (!access(grubConfigType.defaultConfig, F_OK)) {   const char *grub2config = grub2FindConfig(&grub2ConfigType);
3598      gconfig = readConfig(grubConfigType.defaultConfig, &grubConfigType);   if (grub2config) {
3599        gconfig = readConfig(grub2config, &grub2ConfigType);
3600        if (!gconfig)
3601     gr2c = 1;
3602        else
3603     gr2c = checkForGrub2(gconfig);
3604     }
3605    
3606     const char *grubconfig = grubFindConfig(&grubConfigType);
3607     if (!access(grubconfig, F_OK)) {
3608        gconfig = readConfig(grubconfig, &grubConfigType);
3609      if (!gconfig)      if (!gconfig)
3610   grc = 1;   grc = 1;
3611      else      else
# Line 3037  int main(int argc, const char ** argv) { Line 3628  int main(int argc, const char ** argv) {
3628   erc = checkForExtLinux(lconfig);   erc = checkForExtLinux(lconfig);
3629   }   }
3630    
3631   if (lrc == 1 || grc == 1) return 1;   if (lrc == 1 || grc == 1 || gr2c == 1) return 1;
3632    
3633   if (lrc == 2) printf("lilo\n");   if (lrc == 2) printf("lilo\n");
3634     if (gr2c == 2) printf("grub2\n");
3635   if (grc == 2) printf("grub\n");   if (grc == 2) printf("grub\n");
3636   if (erc == 2) printf("extlinux\n");   if (erc == 2) printf("extlinux\n");
3637    
# Line 3067  int main(int argc, const char ** argv) { Line 3659  int main(int argc, const char ** argv) {
3659                 ((rootspec != NULL) ? strlen(rootspec) : 0));                 ((rootspec != NULL) ? strlen(rootspec) : 0));
3660    
3661   return 0;   return 0;
3662    
3663        } else if (displayDefaultTitle) {
3664     struct singleLine * line;
3665     struct singleEntry * entry;
3666    
3667     if (config->defaultImage == -1) return 0;
3668     entry = findEntryByIndex(config, config->defaultImage);
3669     if (!entry) return 0;
3670    
3671     if (!configureGrub2) {
3672      line = getLineByType(LT_TITLE, entry->lines);
3673      if (!line) return 0;
3674      printf("%s\n", line->elements[1].item);
3675    
3676     } else {
3677      char * title;
3678    
3679      dbgPrintf("This is GRUB2, default title is embeded in menuentry\n");
3680      line = getLineByType(LT_MENUENTRY, entry->lines);
3681      if (!line) return 0;
3682      title = grub2ExtractTitle(line);
3683      if (title)
3684        printf("%s\n", title);
3685     }
3686     return 0;
3687    
3688        } else if (displayDefaultIndex) {
3689            if (config->defaultImage == -1) return 0;
3690            printf("%i\n", config->defaultImage);
3691    
3692      } else if (kernelInfo)      } else if (kernelInfo)
3693   return displayInfo(config, kernelInfo, bootPrefix);   return displayInfo(config, kernelInfo, bootPrefix);
3694    
# Line 3082  int main(int argc, const char ** argv) { Line 3704  int main(int argc, const char ** argv) {
3704      setFallbackImage(config, newKernelPath != NULL);      setFallbackImage(config, newKernelPath != NULL);
3705      if (updateImage(config, updateKernelPath, bootPrefix, newKernelArgs,      if (updateImage(config, updateKernelPath, bootPrefix, newKernelArgs,
3706                      removeArgs, newMBKernelArgs, removeMBKernelArgs)) return 1;                      removeArgs, newMBKernelArgs, removeMBKernelArgs)) return 1;
3707        if (updateKernelPath && newKernelInitrd) {
3708                if (updateInitrd(config, updateKernelPath, bootPrefix,
3709                                 newKernelInitrd)) return 1;
3710        }
3711      if (addNewKernel(config, template, bootPrefix, newKernelPath,      if (addNewKernel(config, template, bootPrefix, newKernelPath,
3712                       newKernelTitle, newKernelArgs, newKernelInitrd,                       newKernelTitle, newKernelArgs, newKernelInitrd,
3713                       extraInitrds, extraInitrdCount,                       extraInitrds, extraInitrdCount,
# Line 3095  int main(int argc, const char ** argv) { Line 3721  int main(int argc, const char ** argv) {
3721      }      }
3722    
3723      if (!outputFile)      if (!outputFile)
3724   outputFile = grubConfig;   outputFile = (char *)grubConfig;
3725    
3726      return writeConfig(config, outputFile, bootPrefix);      return writeConfig(config, outputFile, bootPrefix);
3727  }  }

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