Magellan Linux

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

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

revision 1692 by niro, Fri Feb 17 23:14:54 2012 UTC revision 1840 by niro, Mon Jul 2 12:48:49 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      .defaultConfig = "/boot/grub/grub.conf",      .findConfig = grubFindConfig,
189      .keywords = grubKeywords,      .keywords = grubKeywords,
190      .defaultIsIndex = 1,      .defaultIsIndex = 1,
191      .defaultSupportSaved = 1,      .defaultSupportSaved = 1,
192      .entrySeparator = LT_TITLE,      .entryStart = LT_TITLE,
193        .needsBootPrefix = 1,
194        .mbHyperFirst = 1,
195        .mbInitRdIsModule = 1,
196        .mbAllowExtraInitRds = 1,
197    };
198    
199    struct keywordTypes grub2Keywords[] = {
200        { "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,      .needsBootPrefix = 1,
340      .mbHyperFirst = 1,      .mbHyperFirst = 1,
341      .mbInitRdIsModule = 1,      .mbInitRdIsModule = 1,
# Line 247  int useextlinuxmenu; Line 439  int useextlinuxmenu;
439  struct configFileInfo eliloConfigType = {  struct configFileInfo eliloConfigType = {
440      .defaultConfig = "/boot/efi/EFI/redhat/elilo.conf",      .defaultConfig = "/boot/efi/EFI/redhat/elilo.conf",
441      .keywords = eliloKeywords,      .keywords = eliloKeywords,
442      .entrySeparator = LT_KERNEL,      .entryStart = LT_KERNEL,
443      .needsBootPrefix = 1,      .needsBootPrefix = 1,
444      .argsInQuotes = 1,      .argsInQuotes = 1,
445      .mbConcatArgs = 1,      .mbConcatArgs = 1,
# Line 256  struct configFileInfo eliloConfigType = Line 448  struct configFileInfo eliloConfigType =
448  struct configFileInfo liloConfigType = {  struct configFileInfo liloConfigType = {
449      .defaultConfig = "/etc/lilo.conf",      .defaultConfig = "/etc/lilo.conf",
450      .keywords = liloKeywords,      .keywords = liloKeywords,
451      .entrySeparator = LT_KERNEL,      .entryStart = LT_KERNEL,
452      .argsInQuotes = 1,      .argsInQuotes = 1,
453      .maxTitleLength = 15,      .maxTitleLength = 15,
454  };  };
# Line 264  struct configFileInfo liloConfigType = { Line 456  struct configFileInfo liloConfigType = {
456  struct configFileInfo yabootConfigType = {  struct configFileInfo yabootConfigType = {
457      .defaultConfig = "/etc/yaboot.conf",      .defaultConfig = "/etc/yaboot.conf",
458      .keywords = yabootKeywords,      .keywords = yabootKeywords,
459      .entrySeparator = LT_KERNEL,      .entryStart = LT_KERNEL,
460      .needsBootPrefix = 1,      .needsBootPrefix = 1,
461      .argsInQuotes = 1,      .argsInQuotes = 1,
462      .maxTitleLength = 15,      .maxTitleLength = 15,
# Line 274  struct configFileInfo yabootConfigType = Line 466  struct configFileInfo yabootConfigType =
466  struct configFileInfo siloConfigType = {  struct configFileInfo siloConfigType = {
467      .defaultConfig = "/etc/silo.conf",      .defaultConfig = "/etc/silo.conf",
468      .keywords = siloKeywords,      .keywords = siloKeywords,
469      .entrySeparator = LT_KERNEL,      .entryStart = LT_KERNEL,
470      .needsBootPrefix = 1,      .needsBootPrefix = 1,
471      .argsInQuotes = 1,      .argsInQuotes = 1,
472      .maxTitleLength = 15,      .maxTitleLength = 15,
# Line 283  struct configFileInfo siloConfigType = { Line 475  struct configFileInfo siloConfigType = {
475  struct configFileInfo ziplConfigType = {  struct configFileInfo ziplConfigType = {
476      .defaultConfig = "/etc/zipl.conf",      .defaultConfig = "/etc/zipl.conf",
477      .keywords = ziplKeywords,      .keywords = ziplKeywords,
478      .entrySeparator = LT_TITLE,      .entryStart = LT_TITLE,
479      .argsInQuotes = 1,      .argsInQuotes = 1,
480      .titleBracketed = 1,      .titleBracketed = 1,
481  };  };
# Line 291  struct configFileInfo ziplConfigType = { Line 483  struct configFileInfo ziplConfigType = {
483  struct configFileInfo extlinuxConfigType = {  struct configFileInfo extlinuxConfigType = {
484      .defaultConfig = "/boot/extlinux/extlinux.conf",      .defaultConfig = "/boot/extlinux/extlinux.conf",
485      .keywords = extlinuxKeywords,      .keywords = extlinuxKeywords,
486      .entrySeparator = LT_TITLE,      .entryStart = LT_TITLE,
487      .needsBootPrefix = 1,      .needsBootPrefix = 1,
488      .maxTitleLength = 255,      .maxTitleLength = 255,
489      .mbAllowExtraInitRds = 1,      .mbAllowExtraInitRds = 1,
# Line 324  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 388  static struct keywordTypes * getKeywordB Line 581  static struct keywordTypes * getKeywordB
581      return NULL;      return NULL;
582  }  }
583    
584    static char *getKeyByType(enum lineType_e type, struct configFileInfo * cfi) {
585        struct keywordTypes *kt = getKeywordByType(type, cfi);
586        if (kt)
587     return kt->key;
588        return "unknown";
589    }
590    
591  static char * getpathbyspec(char *device) {  static char * getpathbyspec(char *device) {
592      if (!blkid)      if (!blkid)
593          blkid_get_cache(&blkid, NULL);          blkid_get_cache(&blkid, NULL);
# Line 437  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 531  static int lineWrite(FILE * out, struct Line 731  static int lineWrite(FILE * out, struct
731      if (fprintf(out, "%s", line->indent) == -1) return -1;      if (fprintf(out, "%s", line->indent) == -1) return -1;
732    
733      for (i = 0; i < line->numElements; i++) {      for (i = 0; i < line->numElements; i++) {
734     /* Need to handle this, because we strip the quotes from
735     * menuentry when read it. */
736     if (line->type == LT_MENUENTRY && i == 1) {
737        if(!isquote(*line->elements[i].item))
738     fprintf(out, "\'%s\'", line->elements[i].item);
739        else
740     fprintf(out, "%s", line->elements[i].item);
741        fprintf(out, "%s", line->elements[i].indent);
742    
743        continue;
744     }
745    
746   if (i == 1 && line->type == LT_KERNELARGS && cfi->argsInQuotes)   if (i == 1 && line->type == LT_KERNELARGS && cfi->argsInQuotes)
747      if (fputc('"', out) == EOF) return -1;      if (fputc('"', out) == EOF) return -1;
748    
# Line 689  static int getNextLine(char ** bufPtr, s Line 901  static int getNextLine(char ** bufPtr, s
901   break;   break;
902   }   }
903    
904   free(line->elements[i].indent);   line->elements[i + 1].indent = line->elements[i].indent;
905   line->elements[i].indent = strdup(indent);   line->elements[i].indent = strdup(indent);
906   *p++ = '\0';   *p++ = '\0';
907   i++;   i++;
908   line->elements[i].item = strdup(p);   line->elements[i].item = strdup(p);
  line->elements[i].indent = strdup("");  
  p = line->elements[i].item;  
909   }   }
910      }      }
911   }   }
# Line 762  static struct grubConfig * readConfig(co Line 972  static struct grubConfig * readConfig(co
972      cfg->secondaryIndent = strdup(line->indent);      cfg->secondaryIndent = strdup(line->indent);
973   }   }
974    
975   if (isEntrySeparator(line, cfi)) {   if (isEntryStart(line, cfi) || (cfg->entries && !sawEntry)) {
976      sawEntry = 1;      sawEntry = 1;
977      if (!entry) {      if (!entry) {
978   cfg->entries = malloc(sizeof(*entry));   cfg->entries = malloc(sizeof(*entry));
# Line 778  static struct grubConfig * readConfig(co Line 988  static struct grubConfig * readConfig(co
988      entry->next = NULL;      entry->next = NULL;
989   }   }
990    
991   if (line->type == LT_DEFAULT && line->numElements == 2) {   if (line->type == LT_SET_VARIABLE) {
992        int i;
993        dbgPrintf("found 'set' command (%d elements): ", line->numElements);
994        dbgPrintf("%s", line->indent);
995        for (i = 0; i < line->numElements; i++)
996     dbgPrintf("\"%s\"%s", line->elements[i].item, line->elements[i].indent);
997        dbgPrintf("\n");
998        struct keywordTypes *kwType = getKeywordByType(LT_DEFAULT, cfi);
999        if (kwType && line->numElements == 3 &&
1000        !strcmp(line->elements[1].item, kwType->key)) {
1001     dbgPrintf("Line sets default config\n");
1002     cfg->flags &= ~GRUB_CONFIG_NO_DEFAULT;
1003     defaultLine = line;
1004        }
1005     } else if (line->type == LT_DEFAULT && line->numElements == 2) {
1006      cfg->flags &= ~GRUB_CONFIG_NO_DEFAULT;      cfg->flags &= ~GRUB_CONFIG_NO_DEFAULT;
1007      defaultLine = line;      defaultLine = line;
1008    
# Line 838  static struct grubConfig * readConfig(co Line 1062  static struct grubConfig * readConfig(co
1062      line->elements[line->numElements - 1].indent;      line->elements[line->numElements - 1].indent;
1063      line->elements[1].item = buf;      line->elements[1].item = buf;
1064      line->numElements = 2;      line->numElements = 2;
1065     } else if (line->type == LT_MENUENTRY && line->numElements > 3) {
1066        /* let --remove-kernel="TITLE=what" work */
1067        len = 0;
1068        char *extras;
1069        char *title;
1070    
1071        for (i = 1; i < line->numElements; i++) {
1072     len += strlen(line->elements[i].item);
1073     len += strlen(line->elements[i].indent);
1074        }
1075        buf = malloc(len + 1);
1076        *buf = '\0';
1077    
1078        /* allocate mem for extra flags. */
1079        extras = malloc(len + 1);
1080        *extras = '\0';
1081    
1082        /* get title. */
1083        for (i = 0; i < line->numElements; i++) {
1084     if (!strcmp(line->elements[i].item, "menuentry"))
1085        continue;
1086     if (isquote(*line->elements[i].item))
1087        title = line->elements[i].item + 1;
1088     else
1089        title = line->elements[i].item;
1090    
1091     len = strlen(title);
1092            if (isquote(title[len-1])) {
1093        strncat(buf, title,len-1);
1094        break;
1095     } else {
1096        strcat(buf, title);
1097        strcat(buf, line->elements[i].indent);
1098     }
1099        }
1100    
1101        /* get extras */
1102        int count = 0;
1103        for (i = 0; i < line->numElements; i++) {
1104     if (count >= 2) {
1105        strcat(extras, line->elements[i].item);
1106        strcat(extras, line->elements[i].indent);
1107     }
1108    
1109     if (!strcmp(line->elements[i].item, "menuentry"))
1110        continue;
1111    
1112     /* count ' or ", there should be two in menuentry line. */
1113     if (isquote(*line->elements[i].item))
1114        count++;
1115    
1116     len = strlen(line->elements[i].item);
1117    
1118     if (isquote(line->elements[i].item[len -1]))
1119        count++;
1120    
1121     /* ok, we get the final ' or ", others are extras. */
1122                }
1123        line->elements[1].indent =
1124     line->elements[line->numElements - 2].indent;
1125        line->elements[1].item = buf;
1126        line->elements[2].indent =
1127     line->elements[line->numElements - 2].indent;
1128        line->elements[2].item = extras;
1129        line->numElements = 3;
1130   } else if (line->type == LT_KERNELARGS && cfi->argsInQuotes) {   } else if (line->type == LT_KERNELARGS && cfi->argsInQuotes) {
1131      /* Strip off any " which may be present; they'll be put back      /* Strip off any " which may be present; they'll be put back
1132         on write. This is one of the few (the only?) places that grubby         on write. This is one of the few (the only?) places that grubby
# Line 847  static struct grubConfig * readConfig(co Line 1135  static struct grubConfig * readConfig(co
1135      if (line->numElements >= 2) {      if (line->numElements >= 2) {
1136   int last, len;   int last, len;
1137    
1138   if (*line->elements[1].item == '"')   if (isquote(*line->elements[1].item))
1139      memmove(line->elements[1].item, line->elements[1].item + 1,      memmove(line->elements[1].item, line->elements[1].item + 1,
1140      strlen(line->elements[1].item + 1) + 1);      strlen(line->elements[1].item + 1) + 1);
1141    
1142   last = line->numElements - 1;   last = line->numElements - 1;
1143   len = strlen(line->elements[last].item) - 1;   len = strlen(line->elements[last].item) - 1;
1144   if (line->elements[last].item[len] == '"')   if (isquote(line->elements[last].item[len]))
1145      line->elements[last].item[len] = '\0';      line->elements[last].item[len] = '\0';
1146      }      }
1147   }   }
# Line 891  static struct grubConfig * readConfig(co Line 1179  static struct grubConfig * readConfig(co
1179   entry->lines = line;   entry->lines = line;
1180      else      else
1181   last->next = line;   last->next = line;
1182      dbgPrintf("readConfig added %d to %p\n", line->type, entry);      dbgPrintf("readConfig added %s to %p\n", getKeyByType(line->type, cfi), entry);
1183    
1184        /* we could have seen this outside of an entry... if so, we
1185         * ignore it like any other line we don't grok */
1186        if (line->type == LT_ENTRY_END && sawEntry)
1187     sawEntry = 0;
1188   } else {   } else {
1189      if (!cfg->theLines)      if (!cfg->theLines)
1190   cfg->theLines = line;   cfg->theLines = line;
1191      else      else
1192   last->next = line;   last->next = line;
1193      dbgPrintf("readConfig added %d to cfg\n", line->type);      dbgPrintf("readConfig added %s to cfg\n", getKeyByType(line->type, cfi));
1194   }   }
1195    
1196   last = line;   last = line;
# Line 905  static struct grubConfig * readConfig(co Line 1198  static struct grubConfig * readConfig(co
1198    
1199      free(incoming);      free(incoming);
1200    
1201        dbgPrintf("defaultLine is %s\n", defaultLine ? "set" : "unset");
1202      if (defaultLine) {      if (defaultLine) {
1203   if (cfi->defaultSupportSaved &&          if (defaultLine->numElements > 2 &&
1204        cfi->defaultSupportSaved &&
1205        !strncmp(defaultLine->elements[2].item,"\"${saved_entry}\"", 16)) {
1206        cfg->defaultImage = DEFAULT_SAVED_GRUB2;
1207     } else if (cfi->defaultIsVariable) {
1208        char *value = defaultLine->elements[2].item;
1209        while (*value && (*value == '"' || *value == '\'' ||
1210        *value == ' ' || *value == '\t'))
1211     value++;
1212        cfg->defaultImage = strtol(value, &end, 10);
1213        while (*end && (*end == '"' || *end == '\'' ||
1214        *end == ' ' || *end == '\t'))
1215     end++;
1216        if (*end) cfg->defaultImage = -1;
1217     } else if (cfi->defaultSupportSaved &&
1218   !strncmp(defaultLine->elements[1].item, "saved", 5)) {   !strncmp(defaultLine->elements[1].item, "saved", 5)) {
1219      cfg->defaultImage = DEFAULT_SAVED;      cfg->defaultImage = DEFAULT_SAVED;
1220   } else if (cfi->defaultIsIndex) {   } else if (cfi->defaultIsIndex) {
# Line 953  static void writeDefault(FILE * out, cha Line 1261  static void writeDefault(FILE * out, cha
1261    
1262      if (cfg->defaultImage == DEFAULT_SAVED)      if (cfg->defaultImage == DEFAULT_SAVED)
1263   fprintf(out, "%sdefault%ssaved\n", indent, separator);   fprintf(out, "%sdefault%ssaved\n", indent, separator);
1264        else if (cfg->defaultImage == DEFAULT_SAVED_GRUB2)
1265     fprintf(out, "%sset default=\"${saved_entry}\"\n", indent);
1266      else if (cfg->defaultImage > -1) {      else if (cfg->defaultImage > -1) {
1267   if (cfg->cfi->defaultIsIndex) {   if (cfg->cfi->defaultIsIndex) {
1268      fprintf(out, "%sdefault%s%d\n", indent, separator,      if (cfg->cfi->defaultIsVariable) {
1269      cfg->defaultImage);          fprintf(out, "%sset default=\"%d\"\n", indent,
1270     cfg->defaultImage);
1271        } else {
1272     fprintf(out, "%sdefault%s%d\n", indent, separator,
1273     cfg->defaultImage);
1274        }
1275   } else {   } else {
1276      int image = cfg->defaultImage;      int image = cfg->defaultImage;
1277    
# Line 1046  static int writeConfig(struct grubConfig Line 1361  static int writeConfig(struct grubConfig
1361      }      }
1362    
1363      line = cfg->theLines;      line = cfg->theLines;
1364        struct keywordTypes *defaultKw = getKeywordByType(LT_DEFAULT, cfg->cfi);
1365      while (line) {      while (line) {
1366   if (line->type == LT_DEFAULT) {          if (line->type == LT_SET_VARIABLE && defaultKw &&
1367     line->numElements == 3 &&
1368     !strcmp(line->elements[1].item, defaultKw->key)) {
1369        writeDefault(out, line->indent, line->elements[0].indent, cfg);
1370        needs &= ~MAIN_DEFAULT;
1371     } else if (line->type == LT_DEFAULT) {
1372      writeDefault(out, line->indent, line->elements[0].indent, cfg);      writeDefault(out, line->indent, line->elements[0].indent, cfg);
1373      needs &= ~MAIN_DEFAULT;      needs &= ~MAIN_DEFAULT;
1374   } else if (line->type == LT_FALLBACK) {   } else if (line->type == LT_FALLBACK) {
# Line 1185  static char *findDiskForRoot() Line 1506  static char *findDiskForRoot()
1506      return NULL;      return NULL;
1507  }  }
1508    
1509    void printEntry(struct singleEntry * entry) {
1510        int i;
1511        struct singleLine * line;
1512    
1513        for (line = entry->lines; line; line = line->next) {
1514     fprintf(stderr, "DBG: %s", line->indent);
1515     for (i = 0; i < line->numElements; i++) {
1516        /* Need to handle this, because we strip the quotes from
1517         * menuentry when read it. */
1518        if (line->type == LT_MENUENTRY && i == 1) {
1519     if(!isquote(*line->elements[i].item))
1520        fprintf(stderr, "\'%s\'", line->elements[i].item);
1521     else
1522        fprintf(stderr, "%s", line->elements[i].item);
1523     fprintf(stderr, "%s", line->elements[i].indent);
1524    
1525     continue;
1526        }
1527        
1528        fprintf(stderr, "%s%s",
1529        line->elements[i].item, line->elements[i].indent);
1530     }
1531     fprintf(stderr, "\n");
1532        }
1533    }
1534    
1535    void notSuitablePrintf(struct singleEntry * entry, const char *fmt, ...)
1536    {
1537        va_list argp;
1538    
1539        if (!debug)
1540     return;
1541    
1542        va_start(argp, fmt);
1543        fprintf(stderr, "DBG: Image entry failed: ");
1544        vfprintf(stderr, fmt, argp);
1545        printEntry(entry);
1546        va_end(argp);
1547    }
1548    
1549    #define beginswith(s, c) ((s) && (s)[0] == (c))
1550    
1551    static int endswith(const char *s, char c)
1552    {
1553     int slen;
1554    
1555     if (!s || !s[0])
1556     return 0;
1557     slen = strlen(s) - 1;
1558    
1559     return s[slen] == c;
1560    }
1561    
1562  int suitableImage(struct singleEntry * entry, const char * bootPrefix,  int suitableImage(struct singleEntry * entry, const char * bootPrefix,
1563    int skipRemoved, int flags) {    int skipRemoved, int flags) {
1564      struct singleLine * line;      struct singleLine * line;
# Line 1194  int suitableImage(struct singleEntry * e Line 1568  int suitableImage(struct singleEntry * e
1568      char * rootspec;      char * rootspec;
1569      char * rootdev;      char * rootdev;
1570    
1571      if (skipRemoved && entry->skip) return 0;      if (skipRemoved && entry->skip) {
1572     notSuitablePrintf(entry, "marked to skip\n");
1573     return 0;
1574        }
1575    
1576      line = getLineByType(LT_KERNEL|LT_HYPER, entry->lines);      line = getLineByType(LT_KERNEL|LT_HYPER, entry->lines);
1577      if (!line || line->numElements < 2) return 0;      if (!line) {
1578     notSuitablePrintf(entry, "no line found\n");
1579     return 0;
1580        }
1581        if (line->numElements < 2) {
1582     notSuitablePrintf(entry, "line has only %d elements\n",
1583        line->numElements);
1584     return 0;
1585        }
1586    
1587      if (flags & GRUBBY_BADIMAGE_OKAY) return 1;      if (flags & GRUBBY_BADIMAGE_OKAY) return 1;
1588    
1589      fullName = alloca(strlen(bootPrefix) +      fullName = alloca(strlen(bootPrefix) +
1590        strlen(line->elements[1].item) + 1);        strlen(line->elements[1].item) + 1);
1591      rootspec = getRootSpecifier(line->elements[1].item);      rootspec = getRootSpecifier(line->elements[1].item);
1592      sprintf(fullName, "%s%s", bootPrefix,      int rootspec_offset = rootspec ? strlen(rootspec) : 0;
1593              line->elements[1].item + (rootspec ? strlen(rootspec) : 0));      int hasslash = endswith(bootPrefix, '/') ||
1594      if (access(fullName, R_OK)) return 0;       beginswith(line->elements[1].item + rootspec_offset, '/');
1595        sprintf(fullName, "%s%s%s", bootPrefix, hasslash ? "" : "/",
1596                line->elements[1].item + rootspec_offset);
1597        if (access(fullName, R_OK)) {
1598     notSuitablePrintf(entry, "access to %s failed\n", fullName);
1599     return 0;
1600        }
1601      for (i = 2; i < line->numElements; i++)      for (i = 2; i < line->numElements; i++)
1602   if (!strncasecmp(line->elements[i].item, "root=", 5)) break;   if (!strncasecmp(line->elements[i].item, "root=", 5)) break;
1603      if (i < line->numElements) {      if (i < line->numElements) {
# Line 1225  int suitableImage(struct singleEntry * e Line 1615  int suitableImage(struct singleEntry * e
1615      line = getLineByType(LT_KERNELARGS|LT_MBMODULE, entry->lines);      line = getLineByType(LT_KERNELARGS|LT_MBMODULE, entry->lines);
1616    
1617              /* failed to find one */              /* failed to find one */
1618              if (!line) return 0;              if (!line) {
1619     notSuitablePrintf(entry, "no line found\n");
1620     return 0;
1621                }
1622    
1623      for (i = 1; i < line->numElements; i++)      for (i = 1; i < line->numElements; i++)
1624          if (!strncasecmp(line->elements[i].item, "root=", 5)) break;          if (!strncasecmp(line->elements[i].item, "root=", 5)) break;
1625      if (i < line->numElements)      if (i < line->numElements)
1626          dev = line->elements[i].item + 5;          dev = line->elements[i].item + 5;
1627      else {      else {
1628     notSuitablePrintf(entry, "no root= entry found\n");
1629   /* it failed too...  can't find root= */   /* it failed too...  can't find root= */
1630          return 0;          return 0;
1631              }              }
# Line 1239  int suitableImage(struct singleEntry * e Line 1633  int suitableImage(struct singleEntry * e
1633      }      }
1634    
1635      dev = getpathbyspec(dev);      dev = getpathbyspec(dev);
1636      if (!dev)      if (!getpathbyspec(dev)) {
1637            notSuitablePrintf(entry, "can't find blkid entry for %s\n", dev);
1638          return 0;          return 0;
1639        } else
1640     dev = getpathbyspec(dev);
1641    
1642      rootdev = findDiskForRoot();      rootdev = findDiskForRoot();
1643      if (!rootdev)      if (!rootdev) {
1644            notSuitablePrintf(entry, "can't find root device\n");
1645   return 0;   return 0;
1646        }
1647    
1648      if (!getuuidbydev(rootdev) || !getuuidbydev(dev)) {      if (!getuuidbydev(rootdev) || !getuuidbydev(dev)) {
1649            notSuitablePrintf(entry, "uuid missing: rootdev %s, dev %s\n",
1650     getuuidbydev(rootdev), getuuidbydev(dev));
1651          free(rootdev);          free(rootdev);
1652          return 0;          return 0;
1653      }      }
1654    
1655      if (strcmp(getuuidbydev(rootdev), getuuidbydev(dev))) {      if (strcmp(getuuidbydev(rootdev), getuuidbydev(dev))) {
1656            notSuitablePrintf(entry, "uuid mismatch: rootdev %s, dev %s\n",
1657     getuuidbydev(rootdev), getuuidbydev(dev));
1658   free(rootdev);   free(rootdev);
1659          return 0;          return 0;
1660      }      }
# Line 1338  struct singleEntry * findEntryByPath(str Line 1741  struct singleEntry * findEntryByPath(str
1741    
1742   if (!strncmp(kernel, "TITLE=", 6)) {   if (!strncmp(kernel, "TITLE=", 6)) {
1743      prefix = "";      prefix = "";
1744      checkType = LT_TITLE;      checkType = LT_TITLE|LT_MENUENTRY;
1745      kernel += 6;      kernel += 6;
1746   }   }
1747    
# Line 1354  struct singleEntry * findEntryByPath(str Line 1757  struct singleEntry * findEntryByPath(str
1757       checkType, line);       checkType, line);
1758   if (!line) break;  /* not found in this entry */   if (!line) break;  /* not found in this entry */
1759    
1760   if (line && line->numElements >= 2) {   if (line && line->type != LT_MENUENTRY &&
1761     line->numElements >= 2) {
1762      rootspec = getRootSpecifier(line->elements[1].item);      rootspec = getRootSpecifier(line->elements[1].item);
1763      if (!strcmp(line->elements[1].item +      if (!strcmp(line->elements[1].item +
1764   ((rootspec != NULL) ? strlen(rootspec) : 0),   ((rootspec != NULL) ? strlen(rootspec) : 0),
1765   kernel + strlen(prefix)))   kernel + strlen(prefix)))
1766   break;   break;
1767   }   }
1768     if(line->type == LT_MENUENTRY &&
1769     !strcmp(line->elements[1].item, kernel))
1770        break;
1771      }      }
1772    
1773      /* make sure this entry has a kernel identifier; this skips      /* make sure this entry has a kernel identifier; this skips
# Line 1452  void markRemovedImage(struct grubConfig Line 1859  void markRemovedImage(struct grubConfig
1859        const char * prefix) {        const char * prefix) {
1860      struct singleEntry * entry;      struct singleEntry * entry;
1861    
1862      if (!image) return;      if (!image)
1863     return;
1864    
1865        /* check and see if we're removing the default image */
1866        if (isdigit(*image)) {
1867     entry = findEntryByPath(cfg, image, prefix, NULL);
1868     if(entry)
1869        entry->skip = 1;
1870     return;
1871        }
1872    
1873      while ((entry = findEntryByPath(cfg, image, prefix, NULL)))      while ((entry = findEntryByPath(cfg, image, prefix, NULL)))
1874   entry->skip = 1;   entry->skip = 1;
# Line 1479  void setDefaultImage(struct grubConfig * Line 1895  void setDefaultImage(struct grubConfig *
1895    
1896      /* 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
1897         changes */         changes */
1898      if (config->defaultImage == DEFAULT_SAVED)      if ((config->defaultImage == DEFAULT_SAVED) ||
1899     (config->defaultImage == DEFAULT_SAVED_GRUB2))
1900        /* default is set to saved, we don't want to change it */        /* default is set to saved, we don't want to change it */
1901        return;        return;
1902    
# Line 1546  void displayEntry(struct singleEntry * e Line 1963  void displayEntry(struct singleEntry * e
1963          return;          return;
1964      }      }
1965    
1966      printf("kernel=%s\n", line->elements[1].item);      printf("kernel=%s%s\n", prefix, line->elements[1].item);
1967    
1968      if (line->numElements >= 3) {      if (line->numElements >= 3) {
1969   printf("args=\"");   printf("args=\"");
# Line 1610  void displayEntry(struct singleEntry * e Line 2027  void displayEntry(struct singleEntry * e
2027      printf("%s%s", line->elements[i].item, line->elements[i].indent);      printf("%s%s", line->elements[i].item, line->elements[i].indent);
2028   printf("\n");   printf("\n");
2029      }      }
2030    
2031        line = getLineByType(LT_TITLE, entry->lines);
2032        if (line) {
2033     printf("title=%s\n", line->elements[1].item);
2034        } else {
2035     char * title;
2036     line = getLineByType(LT_MENUENTRY, entry->lines);
2037     title = grub2ExtractTitle(line);
2038     if (title)
2039        printf("title=%s\n", title);
2040        }
2041  }  }
2042    
2043  int parseSysconfigGrub(int * lbaPtr, char ** bootPtr) {  int parseSysconfigGrub(int * lbaPtr, char ** bootPtr) {
# Line 1770  struct singleLine *  addLine(struct sing Line 2198  struct singleLine *  addLine(struct sing
2198   sprintf(tmpl.elements[0].item, "[%s]", val);   sprintf(tmpl.elements[0].item, "[%s]", val);
2199   tmpl.elements[0].indent = "";   tmpl.elements[0].indent = "";
2200   val = NULL;   val = NULL;
2201        } else if (type == LT_MENUENTRY) {
2202     char *lineend = "--class gnu-linux --class gnu --class os {";
2203     if (!val) {
2204        fprintf(stderr, "Line type LT_MENUENTRY requires a value\n");
2205        abort();
2206     }
2207     kw = getKeywordByType(type, cfi);
2208     if (!kw) {
2209        fprintf(stderr, "Looking up keyword for unknown type %d\n", type);
2210        abort();
2211     }
2212     tmpl.indent = "";
2213     tmpl.type = type;
2214     tmpl.numElements = 3;
2215     tmpl.elements = alloca(sizeof(*tmpl.elements) * tmpl.numElements);
2216     tmpl.elements[0].item = kw->key;
2217     tmpl.elements[0].indent = alloca(2);
2218     sprintf(tmpl.elements[0].indent, "%c", kw->nextChar);
2219     tmpl.elements[1].item = (char *)val;
2220     tmpl.elements[1].indent = alloca(2);
2221     sprintf(tmpl.elements[1].indent, "%c", kw->nextChar);
2222     tmpl.elements[2].item = alloca(strlen(lineend)+1);
2223     strcpy(tmpl.elements[2].item, lineend);
2224     tmpl.elements[2].indent = "";
2225      } else {      } else {
2226   kw = getKeywordByType(type, cfi);   kw = getKeywordByType(type, cfi);
2227   if (!kw) abort();   if (!kw) {
2228        fprintf(stderr, "Looking up keyword for unknown type %d\n", type);
2229        abort();
2230     }
2231   tmpl.type = type;   tmpl.type = type;
2232   tmpl.numElements = val ? 2 : 1;   tmpl.numElements = val ? 2 : 1;
2233   tmpl.elements = alloca(sizeof(*tmpl.elements) * tmpl.numElements);   tmpl.elements = alloca(sizeof(*tmpl.elements) * tmpl.numElements);
# Line 1796  struct singleLine *  addLine(struct sing Line 2251  struct singleLine *  addLine(struct sing
2251   if (!line->next && !prev) prev = line;   if (!line->next && !prev) prev = line;
2252      }      }
2253    
2254      if (prev == entry->lines)      struct singleLine *menuEntry;
2255   tmpl.indent = defaultIndent ?: "";      menuEntry = getLineByType(LT_MENUENTRY, entry->lines);
2256      else      if (tmpl.type == LT_ENTRY_END) {
2257   tmpl.indent = prev->indent;   if (menuEntry)
2258        tmpl.indent = menuEntry->indent;
2259     else
2260        tmpl.indent = defaultIndent ?: "";
2261        } else if (tmpl.type != LT_MENUENTRY) {
2262     if (menuEntry)
2263        tmpl.indent = "\t";
2264     else if (prev == entry->lines)
2265        tmpl.indent = defaultIndent ?: "";
2266     else
2267        tmpl.indent = prev->indent;
2268        }
2269    
2270      return addLineTmpl(entry, &tmpl, prev, val, cfi);      return addLineTmpl(entry, &tmpl, prev, val, cfi);
2271  }  }
# Line 1826  void removeLine(struct singleEntry * ent Line 2292  void removeLine(struct singleEntry * ent
2292      free(line);      free(line);
2293  }  }
2294    
2295    static void requote(struct singleLine *tmplLine, struct configFileInfo * cfi)
2296    {
2297        struct singleLine newLine = {
2298     .indent = tmplLine->indent,
2299     .type = tmplLine->type,
2300     .next = tmplLine->next,
2301        };
2302        int firstQuotedItem = -1;
2303        int quoteLen = 0;
2304        int j;
2305        int element = 0;
2306        char *c;
2307    
2308        c = malloc(strlen(tmplLine->elements[0].item) + 1);
2309        strcpy(c, tmplLine->elements[0].item);
2310        insertElement(&newLine, c, element++, cfi);
2311        free(c);
2312        c = NULL;
2313    
2314        for (j = 1; j < tmplLine->numElements; j++) {
2315     if (firstQuotedItem == -1) {
2316        quoteLen += strlen(tmplLine->elements[j].item);
2317        
2318        if (isquote(tmplLine->elements[j].item[0])) {
2319     firstQuotedItem = j;
2320            quoteLen += strlen(tmplLine->elements[j].indent);
2321        } else {
2322     c = malloc(quoteLen + 1);
2323     strcpy(c, tmplLine->elements[j].item);
2324     insertElement(&newLine, c, element++, cfi);
2325     free(c);
2326     quoteLen = 0;
2327        }
2328     } else {
2329        int itemlen = strlen(tmplLine->elements[j].item);
2330        quoteLen += itemlen;
2331        quoteLen += strlen(tmplLine->elements[j].indent);
2332        
2333        if (isquote(tmplLine->elements[j].item[itemlen - 1])) {
2334     c = malloc(quoteLen + 1);
2335     c[0] = '\0';
2336     for (int i = firstQuotedItem; i < j+1; i++) {
2337        strcat(c, tmplLine->elements[i].item);
2338        strcat(c, tmplLine->elements[i].indent);
2339     }
2340     insertElement(&newLine, c, element++, cfi);
2341     free(c);
2342    
2343     firstQuotedItem = -1;
2344     quoteLen = 0;
2345        }
2346     }
2347        }
2348        while (tmplLine->numElements)
2349     removeElement(tmplLine, 0);
2350        if (tmplLine->elements)
2351     free(tmplLine->elements);
2352    
2353        tmplLine->numElements = newLine.numElements;
2354        tmplLine->elements = newLine.elements;
2355    }
2356    
2357  static void insertElement(struct singleLine * line,  static void insertElement(struct singleLine * line,
2358    const char * item, int insertHere,    const char * item, int insertHere,
2359    struct configFileInfo * cfi)    struct configFileInfo * cfi)
# Line 2153  int updateImage(struct grubConfig * cfg, Line 2681  int updateImage(struct grubConfig * cfg,
2681  int updateInitrd(struct grubConfig * cfg, const char * image,  int updateInitrd(struct grubConfig * cfg, const char * image,
2682                   const char * prefix, const char * initrd) {                   const char * prefix, const char * initrd) {
2683      struct singleEntry * entry;      struct singleEntry * entry;
2684      struct singleLine * line, * kernelLine;      struct singleLine * line, * kernelLine, *endLine = NULL;
2685      int index = 0;      int index = 0;
2686    
2687      if (!image) return 0;      if (!image) return 0;
# Line 2170  int updateInitrd(struct grubConfig * cfg Line 2698  int updateInitrd(struct grubConfig * cfg
2698              if (!strncmp(initrd, prefix, prefixLen))              if (!strncmp(initrd, prefix, prefixLen))
2699                  initrd += prefixLen;                  initrd += prefixLen;
2700          }          }
2701     endLine = getLineByType(LT_ENTRY_END, entry->lines);
2702     if (endLine)
2703        removeLine(entry, endLine);
2704          line = addLine(entry, cfg->cfi, LT_INITRD, kernelLine->indent, initrd);          line = addLine(entry, cfg->cfi, LT_INITRD, kernelLine->indent, initrd);
2705          if (!line) return 1;          if (!line)
2706        return 1;
2707     if (endLine) {
2708        line = addLine(entry, cfg->cfi, LT_ENTRY_END, "", NULL);
2709                if (!line)
2710     return 1;
2711     }
2712    
2713          break;          break;
2714      }      }
2715    
# Line 2201  int checkDeviceBootloader(const char * d Line 2739  int checkDeviceBootloader(const char * d
2739      if (memcmp(boot, bootSect, 3))      if (memcmp(boot, bootSect, 3))
2740   return 0;   return 0;
2741    
2742      if (boot[1] == 0xeb) {      if (boot[1] == JMP_SHORT_OPCODE) {
2743   offset = boot[2] + 2;   offset = boot[2] + 2;
2744      } else if (boot[1] == 0xe8 || boot[1] == 0xe9) {      } else if (boot[1] == 0xe8 || boot[1] == 0xe9) {
2745   offset = (boot[3] << 8) + boot[2] + 2;   offset = (boot[3] << 8) + boot[2] + 2;
2746      } else if (boot[0] == 0xeb) {      } else if (boot[0] == JMP_SHORT_OPCODE) {
2747   offset = boot[1] + 2;        offset = boot[1] + 2;
2748            /*
2749     * it looks like grub, when copying stage1 into the mbr, patches stage1
2750     * right after the JMP location, replacing other instructions such as
2751     * JMPs for NOOPs. So, relax the check a little bit by skipping those
2752     * different bytes.
2753     */
2754          if ((bootSect[offset + 1] == NOOP_OPCODE)
2755      && (bootSect[offset + 2] == NOOP_OPCODE)) {
2756     offset = offset + 3;
2757          }
2758      } else if (boot[0] == 0xe8 || boot[0] == 0xe9) {      } else if (boot[0] == 0xe8 || boot[0] == 0xe9) {
2759   offset = (boot[2] << 8) + boot[1] + 2;   offset = (boot[2] << 8) + boot[1] + 2;
2760      } else {      } else {
# Line 2348  int checkForLilo(struct grubConfig * con Line 2896  int checkForLilo(struct grubConfig * con
2896      return checkDeviceBootloader(line->elements[1].item, boot);      return checkDeviceBootloader(line->elements[1].item, boot);
2897  }  }
2898    
2899    int checkForGrub2(struct grubConfig * config) {
2900        if (!access("/etc/grub.d/", R_OK))
2901     return 2;
2902    
2903        return 1;
2904    }
2905    
2906  int checkForGrub(struct grubConfig * config) {  int checkForGrub(struct grubConfig * config) {
2907      int fd;      int fd;
2908      unsigned char bootSect[512];      unsigned char bootSect[512];
# Line 2523  int addNewKernel(struct grubConfig * con Line 3078  int addNewKernel(struct grubConfig * con
3078      if (*chptr == '#') continue;      if (*chptr == '#') continue;
3079    
3080      if (tmplLine->type == LT_KERNEL &&      if (tmplLine->type == LT_KERNEL &&
3081   tmplLine->numElements >= 2) {      tmplLine->numElements >= 2) {
3082   if (!template->multiboot && (needs & NEED_MB)) {   if (!template->multiboot && (needs & NEED_MB)) {
3083      /* it's not a multiboot template and this is the kernel      /* it's not a multiboot template and this is the kernel
3084       * line.  Try to be intelligent about inserting the       * line.  Try to be intelligent about inserting the
# Line 2649  int addNewKernel(struct grubConfig * con Line 3204  int addNewKernel(struct grubConfig * con
3204      needs &= ~NEED_INITRD;      needs &= ~NEED_INITRD;
3205   }   }
3206    
3207        } else if (tmplLine->type == LT_MENUENTRY &&
3208           (needs & NEED_TITLE)) {
3209     requote(tmplLine, config->cfi);
3210     char *nkt = malloc(strlen(newKernelTitle)+3);
3211     strcpy(nkt, "'");
3212     strcat(nkt, newKernelTitle);
3213     strcat(nkt, "'");
3214     newLine = addLineTmpl(new, tmplLine, newLine, nkt, config->cfi);
3215     free(nkt);
3216     needs &= ~NEED_TITLE;
3217      } else if (tmplLine->type == LT_TITLE &&      } else if (tmplLine->type == LT_TITLE &&
3218         (needs & NEED_TITLE)) {         (needs & NEED_TITLE)) {
3219   if (tmplLine->numElements >= 2) {   if (tmplLine->numElements >= 2) {
# Line 2662  int addNewKernel(struct grubConfig * con Line 3227  int addNewKernel(struct grubConfig * con
3227        tmplLine->indent, newKernelTitle);        tmplLine->indent, newKernelTitle);
3228      needs &= ~NEED_TITLE;      needs &= ~NEED_TITLE;
3229   }   }
3230        } else if (tmplLine->type == LT_ECHO) {
3231        requote(tmplLine, config->cfi);
3232        static const char *prefix = "'Loading ";
3233        if (tmplLine->numElements > 1 &&
3234        strstr(tmplLine->elements[1].item, prefix) &&
3235        masterLine->next && masterLine->next->type == LT_KERNEL) {
3236     char *newTitle = malloc(strlen(prefix) +
3237     strlen(newKernelTitle) + 2);
3238    
3239     strcpy(newTitle, prefix);
3240     strcat(newTitle, newKernelTitle);
3241     strcat(newTitle, "'");
3242     newLine = addLine(new, config->cfi, LT_ECHO,
3243     tmplLine->indent, newTitle);
3244     free(newTitle);
3245        } else {
3246     /* pass through other lines from the template */
3247     newLine = addLineTmpl(new, tmplLine, newLine, NULL,
3248     config->cfi);
3249        }
3250      } else {      } else {
3251   /* pass through other lines from the template */   /* pass through other lines from the template */
3252   newLine = addLineTmpl(new, tmplLine, newLine, NULL, config->cfi);   newLine = addLineTmpl(new, tmplLine, newLine, NULL, config->cfi);
# Line 2673  int addNewKernel(struct grubConfig * con Line 3257  int addNewKernel(struct grubConfig * con
3257   /* don't have a template, so start the entry with the   /* don't have a template, so start the entry with the
3258   * appropriate starting line   * appropriate starting line
3259   */   */
3260   switch (config->cfi->entrySeparator) {   switch (config->cfi->entryStart) {
3261      case LT_KERNEL:      case LT_KERNEL:
3262   if (new->multiboot && config->cfi->mbHyperFirst) {   if (new->multiboot && config->cfi->mbHyperFirst) {
3263      /* fall through to LT_HYPER */      /* fall through to LT_HYPER */
# Line 2692  int addNewKernel(struct grubConfig * con Line 3276  int addNewKernel(struct grubConfig * con
3276   needs &= ~NEED_MB;   needs &= ~NEED_MB;
3277   break;   break;
3278    
3279        case LT_MENUENTRY: {
3280     char *nkt = malloc(strlen(newKernelTitle)+3);
3281     strcpy(nkt, "'");
3282     strcat(nkt, newKernelTitle);
3283     strcat(nkt, "'");
3284            newLine = addLine(new, config->cfi, LT_MENUENTRY,
3285      config->primaryIndent, nkt);
3286     free(nkt);
3287     needs &= ~NEED_TITLE;
3288     needs |= NEED_END;
3289     break;
3290        }
3291      case LT_TITLE:      case LT_TITLE:
3292   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)
3293   char * templabel;   char * templabel;
# Line 2725  int addNewKernel(struct grubConfig * con Line 3321  int addNewKernel(struct grubConfig * con
3321    
3322      /* add the remainder of the lines, i.e. those that either      /* add the remainder of the lines, i.e. those that either
3323       * 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,
3324       * all the lines following the entrySeparator.       * all the lines following the entryStart.
3325       */       */
3326      if (needs & NEED_TITLE) {      if (needs & NEED_TITLE) {
3327   newLine = addLine(new, config->cfi, LT_TITLE,   newLine = addLine(new, config->cfi, LT_TITLE,
# Line 2766  int addNewKernel(struct grubConfig * con Line 3362  int addNewKernel(struct grubConfig * con
3362   free(initrdVal);   free(initrdVal);
3363   needs &= ~NEED_INITRD;   needs &= ~NEED_INITRD;
3364      }      }
3365        if (needs & NEED_END) {
3366     newLine = addLine(new, config->cfi, LT_ENTRY_END,
3367     config->secondaryIndent, NULL);
3368     needs &= ~NEED_END;
3369        }
3370    
3371      if (needs) {      if (needs) {
3372   printf(_("grubby: needs=%d, aborting\n"), needs);   printf(_("grubby: needs=%d, aborting\n"), needs);
# Line 2795  static void traceback(int signum) Line 3396  static void traceback(int signum)
3396    
3397  int main(int argc, const char ** argv) {  int main(int argc, const char ** argv) {
3398      poptContext optCon;      poptContext optCon;
3399      char * grubConfig = NULL;      const char * grubConfig = NULL;
3400      char * outputFile = NULL;      char * outputFile = NULL;
3401      int arg = 0;      int arg = 0;
3402      int flags = 0;      int flags = 0;
3403      int badImageOkay = 0;      int badImageOkay = 0;
3404        int configureGrub2 = 0;
3405      int configureLilo = 0, configureELilo = 0, configureGrub = 0;      int configureLilo = 0, configureELilo = 0, configureGrub = 0;
3406      int configureYaboot = 0, configureSilo = 0, configureZipl = 0;      int configureYaboot = 0, configureSilo = 0, configureZipl = 0;
3407      int configureExtLinux = 0;      int configureExtLinux = 0;
# Line 2827  int main(int argc, const char ** argv) { Line 3429  int main(int argc, const char ** argv) {
3429      struct singleEntry * template = NULL;      struct singleEntry * template = NULL;
3430      int copyDefault = 0, makeDefault = 0;      int copyDefault = 0, makeDefault = 0;
3431      int displayDefault = 0;      int displayDefault = 0;
3432        int displayDefaultIndex = 0;
3433        int displayDefaultTitle = 0;
3434      struct poptOption options[] = {      struct poptOption options[] = {
3435   { "add-kernel", 0, POPT_ARG_STRING, &newKernelPath, 0,   { "add-kernel", 0, POPT_ARG_STRING, &newKernelPath, 0,
3436      _("add an entry for the specified kernel"), _("kernel-path") },      _("add an entry for the specified kernel"), _("kernel-path") },
# Line 2857  int main(int argc, const char ** argv) { Line 3461  int main(int argc, const char ** argv) {
3461        "the kernel referenced by the default image does not exist, "        "the kernel referenced by the default image does not exist, "
3462        "the first linux entry whose kernel does exist is used as the "        "the first linux entry whose kernel does exist is used as the "
3463        "template"), NULL },        "template"), NULL },
3464     { "debug", 0, 0, &debug, 0,
3465        _("print debugging information for failures") },
3466   { "default-kernel", 0, 0, &displayDefault, 0,   { "default-kernel", 0, 0, &displayDefault, 0,
3467      _("display the path of the default kernel") },      _("display the path of the default kernel") },
3468     { "default-index", 0, 0, &displayDefaultIndex, 0,
3469        _("display the index of the default kernel") },
3470     { "default-title", 0, 0, &displayDefaultTitle, 0,
3471        _("display the title of the default kernel") },
3472   { "elilo", 0, POPT_ARG_NONE, &configureELilo, 0,   { "elilo", 0, POPT_ARG_NONE, &configureELilo, 0,
3473      _("configure elilo bootloader") },      _("configure elilo bootloader") },
3474   { "extlinux", 0, POPT_ARG_NONE, &configureExtLinux, 0,   { "extlinux", 0, POPT_ARG_NONE, &configureExtLinux, 0,
3475      _("configure extlinux bootloader (from syslinux)") },      _("configure extlinux bootloader (from syslinux)") },
3476   { "grub", 0, POPT_ARG_NONE, &configureGrub, 0,   { "grub", 0, POPT_ARG_NONE, &configureGrub, 0,
3477      _("configure grub bootloader") },      _("configure grub bootloader") },
3478     { "grub2", 0, POPT_ARG_NONE, &configureGrub2, 0,
3479        _("configure grub2 bootloader") },
3480   { "info", 0, POPT_ARG_STRING, &kernelInfo, 0,   { "info", 0, POPT_ARG_STRING, &kernelInfo, 0,
3481      _("display boot information for specified kernel"),      _("display boot information for specified kernel"),
3482      _("kernel-path") },      _("kernel-path") },
# Line 2944  int main(int argc, const char ** argv) { Line 3556  int main(int argc, const char ** argv) {
3556   return 1;   return 1;
3557      }      }
3558    
3559      if ((configureLilo + configureGrub + configureELilo +      if ((configureLilo + configureGrub2 + configureGrub + configureELilo +
3560   configureYaboot + configureSilo + configureZipl +   configureYaboot + configureSilo + configureZipl +
3561   configureExtLinux ) > 1) {   configureExtLinux ) > 1) {
3562   fprintf(stderr, _("grubby: cannot specify multiple bootloaders\n"));   fprintf(stderr, _("grubby: cannot specify multiple bootloaders\n"));
# Line 2953  int main(int argc, const char ** argv) { Line 3565  int main(int argc, const char ** argv) {
3565   fprintf(stderr,   fprintf(stderr,
3566      _("grubby: cannot specify config file with --bootloader-probe\n"));      _("grubby: cannot specify config file with --bootloader-probe\n"));
3567   return 1;   return 1;
3568        } else if (configureGrub2) {
3569     cfi = &grub2ConfigType;
3570      } else if (configureLilo) {      } else if (configureLilo) {
3571   cfi = &liloConfigType;   cfi = &liloConfigType;
3572      } else if (configureGrub) {      } else if (configureGrub) {
# Line 2971  int main(int argc, const char ** argv) { Line 3585  int main(int argc, const char ** argv) {
3585      }      }
3586    
3587      if (!cfi) {      if (!cfi) {
3588            if (grub2FindConfig(&grub2ConfigType))
3589        cfi = &grub2ConfigType;
3590     else
3591        #ifdef __ia64__        #ifdef __ia64__
3592   cfi = &eliloConfigType;      cfi = &eliloConfigType;
3593        #elif __powerpc__        #elif __powerpc__
3594   cfi = &yabootConfigType;      cfi = &yabootConfigType;
3595        #elif __sparc__        #elif __sparc__
3596          cfi = &siloConfigType;              cfi = &siloConfigType;
3597        #elif __s390__        #elif __s390__
3598          cfi = &ziplConfigType;              cfi = &ziplConfigType;
3599        #elif __s390x__        #elif __s390x__
3600          cfi = &ziplConfigtype;              cfi = &ziplConfigtype;
3601        #else        #else
3602   cfi = &grubConfigType;      cfi = &grubConfigType;
3603        #endif        #endif
3604      }      }
3605    
3606      if (!grubConfig)      if (!grubConfig) {
3607   grubConfig = cfi->defaultConfig;   if (cfi->findConfig)
3608        grubConfig = cfi->findConfig(cfi);
3609     if (!grubConfig)
3610        grubConfig = cfi->defaultConfig;
3611        }
3612    
3613      if (bootloaderProbe && (displayDefault || kernelInfo || newKernelVersion ||      if (bootloaderProbe && (displayDefault || kernelInfo || newKernelVersion ||
3614    newKernelPath || removeKernelPath || makeDefault ||    newKernelPath || removeKernelPath || makeDefault ||
3615    defaultKernel)) {    defaultKernel || displayDefaultIndex || displayDefaultTitle)) {
3616   fprintf(stderr, _("grubby: --bootloader-probe may not be used with "   fprintf(stderr, _("grubby: --bootloader-probe may not be used with "
3617    "specified option"));    "specified option"));
3618   return 1;   return 1;
# Line 3034  int main(int argc, const char ** argv) { Line 3655  int main(int argc, const char ** argv) {
3655   defaultKernel = NULL;   defaultKernel = NULL;
3656      }      }
3657    
3658      if (!strcmp(grubConfig, "-") && !outputFile) {      if (grubConfig && !strcmp(grubConfig, "-") && !outputFile) {
3659   fprintf(stderr, _("grubby: output file must be specified if stdin "   fprintf(stderr, _("grubby: output file must be specified if stdin "
3660   "is used\n"));   "is used\n"));
3661   return 1;   return 1;
# Line 3042  int main(int argc, const char ** argv) { Line 3663  int main(int argc, const char ** argv) {
3663    
3664      if (!removeKernelPath && !newKernelPath && !displayDefault && !defaultKernel      if (!removeKernelPath && !newKernelPath && !displayDefault && !defaultKernel
3665   && !kernelInfo && !bootloaderProbe && !updateKernelPath   && !kernelInfo && !bootloaderProbe && !updateKernelPath
3666          && !removeMBKernel) {          && !removeMBKernel && !displayDefaultIndex && !displayDefaultTitle) {
3667   fprintf(stderr, _("grubby: no action specified\n"));   fprintf(stderr, _("grubby: no action specified\n"));
3668   return 1;   return 1;
3669      }      }
# Line 3069  int main(int argc, const char ** argv) { Line 3690  int main(int argc, const char ** argv) {
3690      }      }
3691    
3692      if (bootloaderProbe) {      if (bootloaderProbe) {
3693   int lrc = 0, grc = 0, erc = 0;   int lrc = 0, grc = 0, gr2c = 0, erc = 0;
3694   struct grubConfig * lconfig, * gconfig;   struct grubConfig * lconfig, * gconfig;
3695    
3696   if (!access(grubConfigType.defaultConfig, F_OK)) {   const char *grub2config = grub2FindConfig(&grub2ConfigType);
3697      gconfig = readConfig(grubConfigType.defaultConfig, &grubConfigType);   if (grub2config) {
3698        gconfig = readConfig(grub2config, &grub2ConfigType);
3699        if (!gconfig)
3700     gr2c = 1;
3701        else
3702     gr2c = checkForGrub2(gconfig);
3703     }
3704    
3705     const char *grubconfig = grubFindConfig(&grubConfigType);
3706     if (!access(grubconfig, F_OK)) {
3707        gconfig = readConfig(grubconfig, &grubConfigType);
3708      if (!gconfig)      if (!gconfig)
3709   grc = 1;   grc = 1;
3710      else      else
# Line 3096  int main(int argc, const char ** argv) { Line 3727  int main(int argc, const char ** argv) {
3727   erc = checkForExtLinux(lconfig);   erc = checkForExtLinux(lconfig);
3728   }   }
3729    
3730   if (lrc == 1 || grc == 1) return 1;   if (lrc == 1 || grc == 1 || gr2c == 1) return 1;
3731    
3732   if (lrc == 2) printf("lilo\n");   if (lrc == 2) printf("lilo\n");
3733     if (gr2c == 2) printf("grub2\n");
3734   if (grc == 2) printf("grub\n");   if (grc == 2) printf("grub\n");
3735   if (erc == 2) printf("extlinux\n");   if (erc == 2) printf("extlinux\n");
3736    
# Line 3126  int main(int argc, const char ** argv) { Line 3758  int main(int argc, const char ** argv) {
3758                 ((rootspec != NULL) ? strlen(rootspec) : 0));                 ((rootspec != NULL) ? strlen(rootspec) : 0));
3759    
3760   return 0;   return 0;
3761    
3762        } else if (displayDefaultTitle) {
3763     struct singleLine * line;
3764     struct singleEntry * entry;
3765    
3766     if (config->defaultImage == -1) return 0;
3767     entry = findEntryByIndex(config, config->defaultImage);
3768     if (!entry) return 0;
3769    
3770     if (!configureGrub2) {
3771      line = getLineByType(LT_TITLE, entry->lines);
3772      if (!line) return 0;
3773      printf("%s\n", line->elements[1].item);
3774    
3775     } else {
3776      char * title;
3777    
3778      dbgPrintf("This is GRUB2, default title is embeded in menuentry\n");
3779      line = getLineByType(LT_MENUENTRY, entry->lines);
3780      if (!line) return 0;
3781      title = grub2ExtractTitle(line);
3782      if (title)
3783        printf("%s\n", title);
3784     }
3785     return 0;
3786    
3787        } else if (displayDefaultIndex) {
3788            if (config->defaultImage == -1) return 0;
3789            printf("%i\n", config->defaultImage);
3790    
3791      } else if (kernelInfo)      } else if (kernelInfo)
3792   return displayInfo(config, kernelInfo, bootPrefix);   return displayInfo(config, kernelInfo, bootPrefix);
3793    
# Line 3158  int main(int argc, const char ** argv) { Line 3820  int main(int argc, const char ** argv) {
3820      }      }
3821    
3822      if (!outputFile)      if (!outputFile)
3823   outputFile = grubConfig;   outputFile = (char *)grubConfig;
3824    
3825      return writeConfig(config, outputFile, bootPrefix);      return writeConfig(config, outputFile, bootPrefix);
3826  }  }

Legend:
Removed from v.1692  
changed lines
  Added in v.1840