Magellan Linux

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

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

revision 1332 by niro, Fri Jun 3 20:32:19 2011 UTC revision 1801 by niro, Mon Apr 16 17:48:10 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 371  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 435  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 484  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 578  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 809  static struct grubConfig * readConfig(co Line 974  static struct grubConfig * readConfig(co
974      cfg->secondaryIndent = strdup(line->indent);      cfg->secondaryIndent = strdup(line->indent);
975   }   }
976    
977   if (isEntrySeparator(line, cfi)) {   if (isEntryStart(line, cfi) || (cfg->entries && !sawEntry)) {
978      sawEntry = 1;      sawEntry = 1;
979      if (!entry) {      if (!entry) {
980   cfg->entries = malloc(sizeof(*entry));   cfg->entries = malloc(sizeof(*entry));
# Line 825  static struct grubConfig * readConfig(co Line 990  static struct grubConfig * readConfig(co
990      entry->next = NULL;      entry->next = NULL;
991   }   }
992    
993   if (line->type == LT_DEFAULT && line->numElements == 2) {   if (line->type == LT_SET_VARIABLE) {
994        int i;
995        dbgPrintf("found 'set' command (%d elements): ", line->numElements);
996        dbgPrintf("%s", line->indent);
997        for (i = 0; i < line->numElements; i++)
998     dbgPrintf("%s\"%s\"", line->elements[i].indent, line->elements[i].item);
999        dbgPrintf("\n");
1000        struct keywordTypes *kwType = getKeywordByType(LT_DEFAULT, cfi);
1001        if (kwType && line->numElements == 3 &&
1002        !strcmp(line->elements[1].item, kwType->key)) {
1003     dbgPrintf("Line sets default config\n");
1004     cfg->flags &= ~GRUB_CONFIG_NO_DEFAULT;
1005     defaultLine = line;
1006        }
1007     } else if (line->type == LT_DEFAULT && line->numElements == 2) {
1008      cfg->flags &= ~GRUB_CONFIG_NO_DEFAULT;      cfg->flags &= ~GRUB_CONFIG_NO_DEFAULT;
1009      defaultLine = line;      defaultLine = line;
1010    
# Line 885  static struct grubConfig * readConfig(co Line 1064  static struct grubConfig * readConfig(co
1064      line->elements[line->numElements - 1].indent;      line->elements[line->numElements - 1].indent;
1065      line->elements[1].item = buf;      line->elements[1].item = buf;
1066      line->numElements = 2;      line->numElements = 2;
1067     } else if (line->type == LT_MENUENTRY && line->numElements > 3) {
1068        /* let --remove-kernel="TITLE=what" work */
1069        len = 0;
1070        char *extras;
1071        char *title;
1072    
1073        for (i = 1; i < line->numElements; i++) {
1074     len += strlen(line->elements[i].item);
1075     len += strlen(line->elements[i].indent);
1076        }
1077        buf = malloc(len + 1);
1078        *buf = '\0';
1079    
1080        /* allocate mem for extra flags. */
1081        extras = malloc(len + 1);
1082        *extras = '\0';
1083    
1084        /* get title. */
1085        for (i = 0; i < line->numElements; i++) {
1086     if (!strcmp(line->elements[i].item, "menuentry"))
1087        continue;
1088     if (isquote(*line->elements[i].item))
1089        title = line->elements[i].item + 1;
1090     else
1091        title = line->elements[i].item;
1092    
1093     len = strlen(title);
1094            if (isquote(title[len-1])) {
1095        strncat(buf, title,len-1);
1096        break;
1097     } else {
1098        strcat(buf, title);
1099        strcat(buf, line->elements[i].indent);
1100     }
1101        }
1102    
1103        /* get extras */
1104        int count = 0;
1105        for (i = 0; i < line->numElements; i++) {
1106     if (count == 2) {
1107        strcat(extras, line->elements[i].item);
1108        strcat(extras, line->elements[i].indent);
1109     }
1110    
1111     if (!strcmp(line->elements[i].item, "menuentry"))
1112        continue;
1113    
1114     /* count ' or ", there should be two in menuentry line. */
1115     if (isquote(*line->elements[i].item))
1116        count++;
1117    
1118     len = strlen(line->elements[i].item);
1119    
1120     if (isquote(line->elements[i].item[len -1]))
1121        count++;
1122    
1123     /* ok, we get the final ' or ", others are extras. */
1124                }
1125        line->elements[1].indent =
1126     line->elements[line->numElements - 2].indent;
1127        line->elements[1].item = buf;
1128        line->elements[2].indent =
1129     line->elements[line->numElements - 2].indent;
1130        line->elements[2].item = extras;
1131        line->numElements = 3;
1132   } else if (line->type == LT_KERNELARGS && cfi->argsInQuotes) {   } else if (line->type == LT_KERNELARGS && cfi->argsInQuotes) {
1133      /* Strip off any " which may be present; they'll be put back      /* Strip off any " which may be present; they'll be put back
1134         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 894  static struct grubConfig * readConfig(co Line 1137  static struct grubConfig * readConfig(co
1137      if (line->numElements >= 2) {      if (line->numElements >= 2) {
1138   int last, len;   int last, len;
1139    
1140   if (*line->elements[1].item == '"')   if (isquote(*line->elements[1].item))
1141      memmove(line->elements[1].item, line->elements[1].item + 1,      memmove(line->elements[1].item, line->elements[1].item + 1,
1142      strlen(line->elements[1].item + 1) + 1);      strlen(line->elements[1].item + 1) + 1);
1143    
1144   last = line->numElements - 1;   last = line->numElements - 1;
1145   len = strlen(line->elements[last].item) - 1;   len = strlen(line->elements[last].item) - 1;
1146   if (line->elements[last].item[len] == '"')   if (isquote(line->elements[last].item[len]))
1147      line->elements[last].item[len] = '\0';      line->elements[last].item[len] = '\0';
1148      }      }
1149   }   }
# Line 938  static struct grubConfig * readConfig(co Line 1181  static struct grubConfig * readConfig(co
1181   entry->lines = line;   entry->lines = line;
1182      else      else
1183   last->next = line;   last->next = line;
1184      dbgPrintf("readConfig added %d to %p\n", line->type, entry);      dbgPrintf("readConfig added %s to %p\n", getKeyByType(line->type, cfi), entry);
1185    
1186        /* we could have seen this outside of an entry... if so, we
1187         * ignore it like any other line we don't grok */
1188        if (line->type == LT_ENTRY_END && sawEntry)
1189     sawEntry = 0;
1190   } else {   } else {
1191      if (!cfg->theLines)      if (!cfg->theLines)
1192   cfg->theLines = line;   cfg->theLines = line;
1193      else      else
1194   last->next = line;   last->next = line;
1195      dbgPrintf("readConfig added %d to cfg\n", line->type);      dbgPrintf("readConfig added %s to cfg\n", getKeyByType(line->type, cfi));
1196   }   }
1197    
1198   last = line;   last = line;
# Line 952  static struct grubConfig * readConfig(co Line 1200  static struct grubConfig * readConfig(co
1200    
1201      free(incoming);      free(incoming);
1202    
1203        dbgPrintf("defaultLine is %s\n", defaultLine ? "set" : "unset");
1204      if (defaultLine) {      if (defaultLine) {
1205   if (cfi->defaultSupportSaved &&          if (defaultLine->numElements > 2 &&
1206        cfi->defaultSupportSaved &&
1207        !strncmp(defaultLine->elements[2].item,"\"${saved_entry}\"", 16)) {
1208        cfg->defaultImage = DEFAULT_SAVED_GRUB2;
1209     } else if (cfi->defaultIsVariable) {
1210        char *value = defaultLine->elements[2].item;
1211        while (*value && (*value == '"' || *value == '\'' ||
1212        *value == ' ' || *value == '\t'))
1213     value++;
1214        cfg->defaultImage = strtol(value, &end, 10);
1215        while (*end && (*end == '"' || *end == '\'' ||
1216        *end == ' ' || *end == '\t'))
1217     end++;
1218        if (*end) cfg->defaultImage = -1;
1219     } else if (cfi->defaultSupportSaved &&
1220   !strncmp(defaultLine->elements[1].item, "saved", 5)) {   !strncmp(defaultLine->elements[1].item, "saved", 5)) {
1221      cfg->defaultImage = DEFAULT_SAVED;      cfg->defaultImage = DEFAULT_SAVED;
1222   } else if (cfi->defaultIsIndex) {   } else if (cfi->defaultIsIndex) {
# Line 1000  static void writeDefault(FILE * out, cha Line 1263  static void writeDefault(FILE * out, cha
1263    
1264      if (cfg->defaultImage == DEFAULT_SAVED)      if (cfg->defaultImage == DEFAULT_SAVED)
1265   fprintf(out, "%sdefault%ssaved\n", indent, separator);   fprintf(out, "%sdefault%ssaved\n", indent, separator);
1266        else if (cfg->defaultImage == DEFAULT_SAVED_GRUB2)
1267     fprintf(out, "%sset default=\"${saved_entry}\"\n", indent);
1268      else if (cfg->defaultImage > -1) {      else if (cfg->defaultImage > -1) {
1269   if (cfg->cfi->defaultIsIndex) {   if (cfg->cfi->defaultIsIndex) {
1270      fprintf(out, "%sdefault%s%d\n", indent, separator,      if (cfg->cfi->defaultIsVariable) {
1271      cfg->defaultImage);          fprintf(out, "%sset default=\"%d\"\n", indent,
1272     cfg->defaultImage);
1273        } else {
1274     fprintf(out, "%sdefault%s%d\n", indent, separator,
1275     cfg->defaultImage);
1276        }
1277   } else {   } else {
1278      int image = cfg->defaultImage;      int image = cfg->defaultImage;
1279    
# Line 1093  static int writeConfig(struct grubConfig Line 1363  static int writeConfig(struct grubConfig
1363      }      }
1364    
1365      line = cfg->theLines;      line = cfg->theLines;
1366        struct keywordTypes *defaultKw = getKeywordByType(LT_DEFAULT, cfg->cfi);
1367      while (line) {      while (line) {
1368   if (line->type == LT_DEFAULT) {          if (line->type == LT_SET_VARIABLE && defaultKw &&
1369     line->numElements == 3 &&
1370     !strcmp(line->elements[1].item, defaultKw->key)) {
1371        writeDefault(out, line->indent, line->elements[0].indent, cfg);
1372        needs &= ~MAIN_DEFAULT;
1373     } else if (line->type == LT_DEFAULT) {
1374      writeDefault(out, line->indent, line->elements[0].indent, cfg);      writeDefault(out, line->indent, line->elements[0].indent, cfg);
1375      needs &= ~MAIN_DEFAULT;      needs &= ~MAIN_DEFAULT;
1376   } else if (line->type == LT_FALLBACK) {   } else if (line->type == LT_FALLBACK) {
# Line 1232  static char *findDiskForRoot() Line 1508  static char *findDiskForRoot()
1508      return NULL;      return NULL;
1509  }  }
1510    
1511    void printEntry(struct singleEntry * entry) {
1512        int i;
1513        struct singleLine * line;
1514    
1515        for (line = entry->lines; line; line = line->next) {
1516     fprintf(stderr, "DBG: %s", line->indent);
1517     for (i = 0; i < line->numElements; i++) {
1518        /* Need to handle this, because we strip the quotes from
1519         * menuentry when read it. */
1520        if (line->type == LT_MENUENTRY && i == 1) {
1521     if(!isquote(*line->elements[i].item))
1522        fprintf(stderr, "\'%s\'", line->elements[i].item);
1523     else
1524        fprintf(stderr, "%s", line->elements[i].item);
1525     fprintf(stderr, "%s", line->elements[i].indent);
1526    
1527     continue;
1528        }
1529        
1530        fprintf(stderr, "%s%s",
1531        line->elements[i].item, line->elements[i].indent);
1532     }
1533     fprintf(stderr, "\n");
1534        }
1535    }
1536    
1537    void notSuitablePrintf(struct singleEntry * entry, const char *fmt, ...)
1538    {
1539        va_list argp;
1540    
1541        if (!debug)
1542     return;
1543    
1544        va_start(argp, fmt);
1545        fprintf(stderr, "DBG: Image entry failed: ");
1546        vfprintf(stderr, fmt, argp);
1547        printEntry(entry);
1548        va_end(argp);
1549    }
1550    
1551    #define beginswith(s, c) ((s) && (s)[0] == (c))
1552    
1553    static int endswith(const char *s, char c)
1554    {
1555     int slen;
1556    
1557     if (!s || !s[0])
1558     return 0;
1559     slen = strlen(s) - 1;
1560    
1561     return s[slen] == c;
1562    }
1563    
1564  int suitableImage(struct singleEntry * entry, const char * bootPrefix,  int suitableImage(struct singleEntry * entry, const char * bootPrefix,
1565    int skipRemoved, int flags) {    int skipRemoved, int flags) {
1566      struct singleLine * line;      struct singleLine * line;
# Line 1241  int suitableImage(struct singleEntry * e Line 1570  int suitableImage(struct singleEntry * e
1570      char * rootspec;      char * rootspec;
1571      char * rootdev;      char * rootdev;
1572    
1573      if (skipRemoved && entry->skip) return 0;      if (skipRemoved && entry->skip) {
1574     notSuitablePrintf(entry, "marked to skip\n");
1575     return 0;
1576        }
1577    
1578      line = getLineByType(LT_KERNEL|LT_HYPER, entry->lines);      line = getLineByType(LT_KERNEL|LT_HYPER, entry->lines);
1579      if (!line || line->numElements < 2) return 0;      if (!line) {
1580     notSuitablePrintf(entry, "no line found\n");
1581     return 0;
1582        }
1583        if (line->numElements < 2) {
1584     notSuitablePrintf(entry, "line has only %d elements\n",
1585        line->numElements);
1586     return 0;
1587        }
1588    
1589      if (flags & GRUBBY_BADIMAGE_OKAY) return 1;      if (flags & GRUBBY_BADIMAGE_OKAY) return 1;
1590    
1591      fullName = alloca(strlen(bootPrefix) +      fullName = alloca(strlen(bootPrefix) +
1592        strlen(line->elements[1].item) + 1);        strlen(line->elements[1].item) + 1);
1593      rootspec = getRootSpecifier(line->elements[1].item);      rootspec = getRootSpecifier(line->elements[1].item);
1594      sprintf(fullName, "%s%s", bootPrefix,      int rootspec_offset = rootspec ? strlen(rootspec) : 0;
1595              line->elements[1].item + (rootspec ? strlen(rootspec) : 0));      int hasslash = endswith(bootPrefix, '/') ||
1596      if (access(fullName, R_OK)) return 0;       beginswith(line->elements[1].item + rootspec_offset, '/');
1597        sprintf(fullName, "%s%s%s", bootPrefix, hasslash ? "" : "/",
1598                line->elements[1].item + rootspec_offset);
1599        if (access(fullName, R_OK)) {
1600     notSuitablePrintf(entry, "access to %s failed\n", fullName);
1601     return 0;
1602        }
1603      for (i = 2; i < line->numElements; i++)      for (i = 2; i < line->numElements; i++)
1604   if (!strncasecmp(line->elements[i].item, "root=", 5)) break;   if (!strncasecmp(line->elements[i].item, "root=", 5)) break;
1605      if (i < line->numElements) {      if (i < line->numElements) {
# Line 1272  int suitableImage(struct singleEntry * e Line 1617  int suitableImage(struct singleEntry * e
1617      line = getLineByType(LT_KERNELARGS|LT_MBMODULE, entry->lines);      line = getLineByType(LT_KERNELARGS|LT_MBMODULE, entry->lines);
1618    
1619              /* failed to find one */              /* failed to find one */
1620              if (!line) return 0;              if (!line) {
1621     notSuitablePrintf(entry, "no line found\n");
1622     return 0;
1623                }
1624    
1625      for (i = 1; i < line->numElements; i++)      for (i = 1; i < line->numElements; i++)
1626          if (!strncasecmp(line->elements[i].item, "root=", 5)) break;          if (!strncasecmp(line->elements[i].item, "root=", 5)) break;
1627      if (i < line->numElements)      if (i < line->numElements)
1628          dev = line->elements[i].item + 5;          dev = line->elements[i].item + 5;
1629      else {      else {
1630     notSuitablePrintf(entry, "no root= entry found\n");
1631   /* it failed too...  can't find root= */   /* it failed too...  can't find root= */
1632          return 0;          return 0;
1633              }              }
# Line 1286  int suitableImage(struct singleEntry * e Line 1635  int suitableImage(struct singleEntry * e
1635      }      }
1636    
1637      dev = getpathbyspec(dev);      dev = getpathbyspec(dev);
1638      if (!dev)      if (!getpathbyspec(dev)) {
1639            notSuitablePrintf(entry, "can't find blkid entry for %s\n", dev);
1640          return 0;          return 0;
1641        } else
1642     dev = getpathbyspec(dev);
1643    
1644      rootdev = findDiskForRoot();      rootdev = findDiskForRoot();
1645      if (!rootdev)      if (!rootdev) {
1646            notSuitablePrintf(entry, "can't find root device\n");
1647   return 0;   return 0;
1648        }
1649    
1650      if (!getuuidbydev(rootdev) || !getuuidbydev(dev)) {      if (!getuuidbydev(rootdev) || !getuuidbydev(dev)) {
1651            notSuitablePrintf(entry, "uuid missing: rootdev %s, dev %s\n",
1652     getuuidbydev(rootdev), getuuidbydev(dev));
1653          free(rootdev);          free(rootdev);
1654          return 0;          return 0;
1655      }      }
1656    
1657      if (strcmp(getuuidbydev(rootdev), getuuidbydev(dev))) {      if (strcmp(getuuidbydev(rootdev), getuuidbydev(dev))) {
1658            notSuitablePrintf(entry, "uuid mismatch: rootdev %s, dev %s\n",
1659     getuuidbydev(rootdev), getuuidbydev(dev));
1660   free(rootdev);   free(rootdev);
1661          return 0;          return 0;
1662      }      }
# Line 1385  struct singleEntry * findEntryByPath(str Line 1743  struct singleEntry * findEntryByPath(str
1743    
1744   if (!strncmp(kernel, "TITLE=", 6)) {   if (!strncmp(kernel, "TITLE=", 6)) {
1745      prefix = "";      prefix = "";
1746      checkType = LT_TITLE;      checkType = LT_TITLE|LT_MENUENTRY;
1747      kernel += 6;      kernel += 6;
1748   }   }
1749    
# Line 1401  struct singleEntry * findEntryByPath(str Line 1759  struct singleEntry * findEntryByPath(str
1759       checkType, line);       checkType, line);
1760   if (!line) break;  /* not found in this entry */   if (!line) break;  /* not found in this entry */
1761    
1762   if (line && line->numElements >= 2) {   if (line && line->type != LT_MENUENTRY &&
1763     line->numElements >= 2) {
1764      rootspec = getRootSpecifier(line->elements[1].item);      rootspec = getRootSpecifier(line->elements[1].item);
1765      if (!strcmp(line->elements[1].item +      if (!strcmp(line->elements[1].item +
1766   ((rootspec != NULL) ? strlen(rootspec) : 0),   ((rootspec != NULL) ? strlen(rootspec) : 0),
1767   kernel + strlen(prefix)))   kernel + strlen(prefix)))
1768   break;   break;
1769   }   }
1770     if(line->type == LT_MENUENTRY &&
1771     !strcmp(line->elements[1].item, kernel))
1772        break;
1773      }      }
1774    
1775      /* make sure this entry has a kernel identifier; this skips      /* make sure this entry has a kernel identifier; this skips
# Line 1499  void markRemovedImage(struct grubConfig Line 1861  void markRemovedImage(struct grubConfig
1861        const char * prefix) {        const char * prefix) {
1862      struct singleEntry * entry;      struct singleEntry * entry;
1863    
1864      if (!image) return;      if (!image)
1865     return;
1866    
1867        /* check and see if we're removing the default image */
1868        if (isdigit(*image)) {
1869     entry = findEntryByPath(cfg, image, prefix, NULL);
1870     if(entry)
1871        entry->skip = 1;
1872     return;
1873        }
1874    
1875      while ((entry = findEntryByPath(cfg, image, prefix, NULL)))      while ((entry = findEntryByPath(cfg, image, prefix, NULL)))
1876   entry->skip = 1;   entry->skip = 1;
# Line 1526  void setDefaultImage(struct grubConfig * Line 1897  void setDefaultImage(struct grubConfig *
1897    
1898      /* 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
1899         changes */         changes */
1900      if (config->defaultImage == DEFAULT_SAVED)      if ((config->defaultImage == DEFAULT_SAVED) ||
1901     (config->defaultImage == DEFAULT_SAVED_GRUB2))
1902        /* default is set to saved, we don't want to change it */        /* default is set to saved, we don't want to change it */
1903        return;        return;
1904    
# Line 1593  void displayEntry(struct singleEntry * e Line 1965  void displayEntry(struct singleEntry * e
1965          return;          return;
1966      }      }
1967    
1968      printf("kernel=%s\n", line->elements[1].item);      printf("kernel=%s%s\n", prefix, line->elements[1].item);
1969    
1970      if (line->numElements >= 3) {      if (line->numElements >= 3) {
1971   printf("args=\"");   printf("args=\"");
# Line 1657  void displayEntry(struct singleEntry * e Line 2029  void displayEntry(struct singleEntry * e
2029      printf("%s%s", line->elements[i].item, line->elements[i].indent);      printf("%s%s", line->elements[i].item, line->elements[i].indent);
2030   printf("\n");   printf("\n");
2031      }      }
2032    
2033        line = getLineByType(LT_TITLE, entry->lines);
2034        if (line) {
2035     printf("title=%s\n", line->elements[1].item);
2036        } else {
2037     char * title;
2038     line = getLineByType(LT_MENUENTRY, entry->lines);
2039     title = grub2ExtractTitle(line);
2040     if (title)
2041        printf("title=%s\n", title);
2042        }
2043  }  }
2044    
2045  int parseSysconfigGrub(int * lbaPtr, char ** bootPtr) {  int parseSysconfigGrub(int * lbaPtr, char ** bootPtr) {
# Line 1817  struct singleLine *  addLine(struct sing Line 2200  struct singleLine *  addLine(struct sing
2200   sprintf(tmpl.elements[0].item, "[%s]", val);   sprintf(tmpl.elements[0].item, "[%s]", val);
2201   tmpl.elements[0].indent = "";   tmpl.elements[0].indent = "";
2202   val = NULL;   val = NULL;
2203        } else if (type == LT_MENUENTRY) {
2204     char *lineend = "--class gnu-linux --class gnu --class os {";
2205     if (!val) {
2206        fprintf(stderr, "Line type LT_MENUENTRY requires a value\n");
2207        abort();
2208     }
2209     kw = getKeywordByType(type, cfi);
2210     if (!kw) {
2211        fprintf(stderr, "Looking up keyword for unknown type %d\n", type);
2212        abort();
2213     }
2214     tmpl.indent = "";
2215     tmpl.type = type;
2216     tmpl.numElements = 3;
2217     tmpl.elements = alloca(sizeof(*tmpl.elements) * tmpl.numElements);
2218     tmpl.elements[0].item = kw->key;
2219     tmpl.elements[0].indent = alloca(2);
2220     sprintf(tmpl.elements[0].indent, "%c", kw->nextChar);
2221     tmpl.elements[1].item = (char *)val;
2222     tmpl.elements[1].indent = alloca(2);
2223     sprintf(tmpl.elements[1].indent, "%c", kw->nextChar);
2224     tmpl.elements[2].item = alloca(strlen(lineend)+1);
2225     strcpy(tmpl.elements[2].item, lineend);
2226     tmpl.elements[2].indent = "";
2227      } else {      } else {
2228   kw = getKeywordByType(type, cfi);   kw = getKeywordByType(type, cfi);
2229   if (!kw) abort();   if (!kw) {
2230        fprintf(stderr, "Looking up keyword for unknown type %d\n", type);
2231        abort();
2232     }
2233   tmpl.type = type;   tmpl.type = type;
2234   tmpl.numElements = val ? 2 : 1;   tmpl.numElements = val ? 2 : 1;
2235   tmpl.elements = alloca(sizeof(*tmpl.elements) * tmpl.numElements);   tmpl.elements = alloca(sizeof(*tmpl.elements) * tmpl.numElements);
# Line 1843  struct singleLine *  addLine(struct sing Line 2253  struct singleLine *  addLine(struct sing
2253   if (!line->next && !prev) prev = line;   if (!line->next && !prev) prev = line;
2254      }      }
2255    
2256      if (prev == entry->lines)      struct singleLine *menuEntry;
2257   tmpl.indent = defaultIndent ?: "";      menuEntry = getLineByType(LT_MENUENTRY, entry->lines);
2258      else      if (tmpl.type == LT_ENTRY_END) {
2259   tmpl.indent = prev->indent;   if (menuEntry)
2260        tmpl.indent = menuEntry->indent;
2261     else
2262        tmpl.indent = defaultIndent ?: "";
2263        } else if (tmpl.type != LT_MENUENTRY) {
2264     if (menuEntry)
2265        tmpl.indent = "\t";
2266     else if (prev == entry->lines)
2267        tmpl.indent = defaultIndent ?: "";
2268     else
2269        tmpl.indent = prev->indent;
2270        }
2271    
2272      return addLineTmpl(entry, &tmpl, prev, val, cfi);      return addLineTmpl(entry, &tmpl, prev, val, cfi);
2273  }  }
# Line 1873  void removeLine(struct singleEntry * ent Line 2294  void removeLine(struct singleEntry * ent
2294      free(line);      free(line);
2295  }  }
2296    
2297    static void requote(struct singleLine *tmplLine, struct configFileInfo * cfi)
2298    {
2299        struct singleLine newLine = {
2300     .indent = tmplLine->indent,
2301     .type = tmplLine->type,
2302     .next = tmplLine->next,
2303        };
2304        int firstQuotedItem = -1;
2305        int quoteLen = 0;
2306        int j;
2307        int element = 0;
2308        char *c;
2309    
2310        c = malloc(strlen(tmplLine->elements[0].item) + 1);
2311        strcpy(c, tmplLine->elements[0].item);
2312        insertElement(&newLine, c, element++, cfi);
2313        free(c);
2314        c = NULL;
2315    
2316        for (j = 1; j < tmplLine->numElements; j++) {
2317     if (firstQuotedItem == -1) {
2318        quoteLen += strlen(tmplLine->elements[j].item);
2319        
2320        if (isquote(tmplLine->elements[j].item[0])) {
2321     firstQuotedItem = j;
2322            quoteLen += strlen(tmplLine->elements[j].indent);
2323        } else {
2324     c = malloc(quoteLen + 1);
2325     strcpy(c, tmplLine->elements[j].item);
2326     insertElement(&newLine, c, element++, cfi);
2327     free(c);
2328     quoteLen = 0;
2329        }
2330     } else {
2331        int itemlen = strlen(tmplLine->elements[j].item);
2332        quoteLen += itemlen;
2333        quoteLen += strlen(tmplLine->elements[j].indent);
2334        
2335        if (isquote(tmplLine->elements[j].item[itemlen - 1])) {
2336     c = malloc(quoteLen + 1);
2337     c[0] = '\0';
2338     for (int i = firstQuotedItem; i < j+1; i++) {
2339        strcat(c, tmplLine->elements[i].item);
2340        strcat(c, tmplLine->elements[i].indent);
2341     }
2342     insertElement(&newLine, c, element++, cfi);
2343     free(c);
2344    
2345     firstQuotedItem = -1;
2346     quoteLen = 0;
2347        }
2348     }
2349        }
2350        while (tmplLine->numElements)
2351     removeElement(tmplLine, 0);
2352        if (tmplLine->elements)
2353     free(tmplLine->elements);
2354    
2355        tmplLine->numElements = newLine.numElements;
2356        tmplLine->elements = newLine.elements;
2357    }
2358    
2359  static void insertElement(struct singleLine * line,  static void insertElement(struct singleLine * line,
2360    const char * item, int insertHere,    const char * item, int insertHere,
2361    struct configFileInfo * cfi)    struct configFileInfo * cfi)
# Line 2200  int updateImage(struct grubConfig * cfg, Line 2683  int updateImage(struct grubConfig * cfg,
2683  int updateInitrd(struct grubConfig * cfg, const char * image,  int updateInitrd(struct grubConfig * cfg, const char * image,
2684                   const char * prefix, const char * initrd) {                   const char * prefix, const char * initrd) {
2685      struct singleEntry * entry;      struct singleEntry * entry;
2686      struct singleLine * line, * kernelLine;      struct singleLine * line, * kernelLine, *endLine = NULL;
2687      int index = 0;      int index = 0;
2688    
2689      if (!image) return 0;      if (!image) return 0;
# Line 2217  int updateInitrd(struct grubConfig * cfg Line 2700  int updateInitrd(struct grubConfig * cfg
2700              if (!strncmp(initrd, prefix, prefixLen))              if (!strncmp(initrd, prefix, prefixLen))
2701                  initrd += prefixLen;                  initrd += prefixLen;
2702          }          }
2703     endLine = getLineByType(LT_ENTRY_END, entry->lines);
2704     if (endLine)
2705        removeLine(entry, endLine);
2706          line = addLine(entry, cfg->cfi, LT_INITRD, kernelLine->indent, initrd);          line = addLine(entry, cfg->cfi, LT_INITRD, kernelLine->indent, initrd);
2707          if (!line) return 1;          if (!line)
2708        return 1;
2709     if (endLine) {
2710        line = addLine(entry, cfg->cfi, LT_ENTRY_END, "", NULL);
2711                if (!line)
2712     return 1;
2713     }
2714    
2715          break;          break;
2716      }      }
2717    
# Line 2248  int checkDeviceBootloader(const char * d Line 2741  int checkDeviceBootloader(const char * d
2741      if (memcmp(boot, bootSect, 3))      if (memcmp(boot, bootSect, 3))
2742   return 0;   return 0;
2743    
2744      if (boot[1] == 0xeb) {      if (boot[1] == JMP_SHORT_OPCODE) {
2745   offset = boot[2] + 2;   offset = boot[2] + 2;
2746      } else if (boot[1] == 0xe8 || boot[1] == 0xe9) {      } else if (boot[1] == 0xe8 || boot[1] == 0xe9) {
2747   offset = (boot[3] << 8) + boot[2] + 2;   offset = (boot[3] << 8) + boot[2] + 2;
2748      } else if (boot[0] == 0xeb) {      } else if (boot[0] == JMP_SHORT_OPCODE) {
2749   offset = boot[1] + 2;        offset = boot[1] + 2;
2750            /*
2751     * it looks like grub, when copying stage1 into the mbr, patches stage1
2752     * right after the JMP location, replacing other instructions such as
2753     * JMPs for NOOPs. So, relax the check a little bit by skipping those
2754     * different bytes.
2755     */
2756          if ((bootSect[offset + 1] == NOOP_OPCODE)
2757      && (bootSect[offset + 2] == NOOP_OPCODE)) {
2758     offset = offset + 3;
2759          }
2760      } else if (boot[0] == 0xe8 || boot[0] == 0xe9) {      } else if (boot[0] == 0xe8 || boot[0] == 0xe9) {
2761   offset = (boot[2] << 8) + boot[1] + 2;   offset = (boot[2] << 8) + boot[1] + 2;
2762      } else {      } else {
# Line 2395  int checkForLilo(struct grubConfig * con Line 2898  int checkForLilo(struct grubConfig * con
2898      return checkDeviceBootloader(line->elements[1].item, boot);      return checkDeviceBootloader(line->elements[1].item, boot);
2899  }  }
2900    
2901    int checkForGrub2(struct grubConfig * config) {
2902        if (!access("/etc/grub.d/", R_OK))
2903     return 2;
2904    
2905        return 1;
2906    }
2907    
2908  int checkForGrub(struct grubConfig * config) {  int checkForGrub(struct grubConfig * config) {
2909      int fd;      int fd;
2910      unsigned char bootSect[512];      unsigned char bootSect[512];
# Line 2570  int addNewKernel(struct grubConfig * con Line 3080  int addNewKernel(struct grubConfig * con
3080      if (*chptr == '#') continue;      if (*chptr == '#') continue;
3081    
3082      if (tmplLine->type == LT_KERNEL &&      if (tmplLine->type == LT_KERNEL &&
3083   tmplLine->numElements >= 2) {      tmplLine->numElements >= 2) {
3084   if (!template->multiboot && (needs & NEED_MB)) {   if (!template->multiboot && (needs & NEED_MB)) {
3085      /* it's not a multiboot template and this is the kernel      /* it's not a multiboot template and this is the kernel
3086       * line.  Try to be intelligent about inserting the       * line.  Try to be intelligent about inserting the
# Line 2696  int addNewKernel(struct grubConfig * con Line 3206  int addNewKernel(struct grubConfig * con
3206      needs &= ~NEED_INITRD;      needs &= ~NEED_INITRD;
3207   }   }
3208    
3209        } else if (tmplLine->type == LT_MENUENTRY &&
3210           (needs & NEED_TITLE)) {
3211     requote(tmplLine, config->cfi);
3212     char *nkt = malloc(strlen(newKernelTitle)+3);
3213     strcpy(nkt, "'");
3214     strcat(nkt, newKernelTitle);
3215     strcat(nkt, "'");
3216     newLine = addLineTmpl(new, tmplLine, newLine, nkt, config->cfi);
3217     free(nkt);
3218     needs &= ~NEED_TITLE;
3219      } else if (tmplLine->type == LT_TITLE &&      } else if (tmplLine->type == LT_TITLE &&
3220         (needs & NEED_TITLE)) {         (needs & NEED_TITLE)) {
3221   if (tmplLine->numElements >= 2) {   if (tmplLine->numElements >= 2) {
# Line 2709  int addNewKernel(struct grubConfig * con Line 3229  int addNewKernel(struct grubConfig * con
3229        tmplLine->indent, newKernelTitle);        tmplLine->indent, newKernelTitle);
3230      needs &= ~NEED_TITLE;      needs &= ~NEED_TITLE;
3231   }   }
3232        } else if (tmplLine->type == LT_ECHO) {
3233        requote(tmplLine, config->cfi);
3234        static const char *prefix = "'Loading ";
3235        if (tmplLine->numElements > 1 &&
3236        strstr(tmplLine->elements[1].item, prefix) &&
3237        masterLine->next && masterLine->next->type == LT_KERNEL) {
3238     char *newTitle = malloc(strlen(prefix) +
3239     strlen(newKernelTitle) + 2);
3240    
3241     strcpy(newTitle, prefix);
3242     strcat(newTitle, newKernelTitle);
3243     strcat(newTitle, "'");
3244     newLine = addLine(new, config->cfi, LT_ECHO,
3245     tmplLine->indent, newTitle);
3246     free(newTitle);
3247        } else {
3248     /* pass through other lines from the template */
3249     newLine = addLineTmpl(new, tmplLine, newLine, NULL,
3250     config->cfi);
3251        }
3252      } else {      } else {
3253   /* pass through other lines from the template */   /* pass through other lines from the template */
3254   newLine = addLineTmpl(new, tmplLine, newLine, NULL, config->cfi);   newLine = addLineTmpl(new, tmplLine, newLine, NULL, config->cfi);
# Line 2720  int addNewKernel(struct grubConfig * con Line 3259  int addNewKernel(struct grubConfig * con
3259   /* don't have a template, so start the entry with the   /* don't have a template, so start the entry with the
3260   * appropriate starting line   * appropriate starting line
3261   */   */
3262   switch (config->cfi->entrySeparator) {   switch (config->cfi->entryStart) {
3263      case LT_KERNEL:      case LT_KERNEL:
3264   if (new->multiboot && config->cfi->mbHyperFirst) {   if (new->multiboot && config->cfi->mbHyperFirst) {
3265      /* fall through to LT_HYPER */      /* fall through to LT_HYPER */
# Line 2739  int addNewKernel(struct grubConfig * con Line 3278  int addNewKernel(struct grubConfig * con
3278   needs &= ~NEED_MB;   needs &= ~NEED_MB;
3279   break;   break;
3280    
3281        case LT_MENUENTRY: {
3282     char *nkt = malloc(strlen(newKernelTitle)+3);
3283     strcpy(nkt, "'");
3284     strcat(nkt, newKernelTitle);
3285     strcat(nkt, "'");
3286            newLine = addLine(new, config->cfi, LT_MENUENTRY,
3287      config->primaryIndent, nkt);
3288     free(nkt);
3289     needs &= ~NEED_TITLE;
3290     needs |= NEED_END;
3291     break;
3292        }
3293      case LT_TITLE:      case LT_TITLE:
3294   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)
3295   char * templabel;   char * templabel;
# Line 2772  int addNewKernel(struct grubConfig * con Line 3323  int addNewKernel(struct grubConfig * con
3323    
3324      /* add the remainder of the lines, i.e. those that either      /* add the remainder of the lines, i.e. those that either
3325       * 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,
3326       * all the lines following the entrySeparator.       * all the lines following the entryStart.
3327       */       */
3328      if (needs & NEED_TITLE) {      if (needs & NEED_TITLE) {
3329   newLine = addLine(new, config->cfi, LT_TITLE,   newLine = addLine(new, config->cfi, LT_TITLE,
# Line 2813  int addNewKernel(struct grubConfig * con Line 3364  int addNewKernel(struct grubConfig * con
3364   free(initrdVal);   free(initrdVal);
3365   needs &= ~NEED_INITRD;   needs &= ~NEED_INITRD;
3366      }      }
3367        if (needs & NEED_END) {
3368     newLine = addLine(new, config->cfi, LT_ENTRY_END,
3369     config->secondaryIndent, NULL);
3370     needs &= ~NEED_END;
3371        }
3372    
3373      if (needs) {      if (needs) {
3374   printf(_("grubby: needs=%d, aborting\n"), needs);   printf(_("grubby: needs=%d, aborting\n"), needs);
# Line 2842  static void traceback(int signum) Line 3398  static void traceback(int signum)
3398    
3399  int main(int argc, const char ** argv) {  int main(int argc, const char ** argv) {
3400      poptContext optCon;      poptContext optCon;
3401      char * grubConfig = NULL;      const char * grubConfig = NULL;
3402      char * outputFile = NULL;      char * outputFile = NULL;
3403      int arg = 0;      int arg = 0;
3404      int flags = 0;      int flags = 0;
3405      int badImageOkay = 0;      int badImageOkay = 0;
3406        int configureGrub2 = 0;
3407      int configureLilo = 0, configureELilo = 0, configureGrub = 0;      int configureLilo = 0, configureELilo = 0, configureGrub = 0;
3408      int configureYaboot = 0, configureSilo = 0, configureZipl = 0;      int configureYaboot = 0, configureSilo = 0, configureZipl = 0;
3409      int configureExtLinux = 0;      int configureExtLinux = 0;
# Line 2874  int main(int argc, const char ** argv) { Line 3431  int main(int argc, const char ** argv) {
3431      struct singleEntry * template = NULL;      struct singleEntry * template = NULL;
3432      int copyDefault = 0, makeDefault = 0;      int copyDefault = 0, makeDefault = 0;
3433      int displayDefault = 0;      int displayDefault = 0;
3434        int displayDefaultIndex = 0;
3435        int displayDefaultTitle = 0;
3436      struct poptOption options[] = {      struct poptOption options[] = {
3437   { "add-kernel", 0, POPT_ARG_STRING, &newKernelPath, 0,   { "add-kernel", 0, POPT_ARG_STRING, &newKernelPath, 0,
3438      _("add an entry for the specified kernel"), _("kernel-path") },      _("add an entry for the specified kernel"), _("kernel-path") },
# Line 2904  int main(int argc, const char ** argv) { Line 3463  int main(int argc, const char ** argv) {
3463        "the kernel referenced by the default image does not exist, "        "the kernel referenced by the default image does not exist, "
3464        "the first linux entry whose kernel does exist is used as the "        "the first linux entry whose kernel does exist is used as the "
3465        "template"), NULL },        "template"), NULL },
3466     { "debug", 0, 0, &debug, 0,
3467        _("print debugging information for failures") },
3468   { "default-kernel", 0, 0, &displayDefault, 0,   { "default-kernel", 0, 0, &displayDefault, 0,
3469      _("display the path of the default kernel") },      _("display the path of the default kernel") },
3470     { "default-index", 0, 0, &displayDefaultIndex, 0,
3471        _("display the index of the default kernel") },
3472     { "default-title", 0, 0, &displayDefaultTitle, 0,
3473        _("display the title of the default kernel") },
3474   { "elilo", 0, POPT_ARG_NONE, &configureELilo, 0,   { "elilo", 0, POPT_ARG_NONE, &configureELilo, 0,
3475      _("configure elilo bootloader") },      _("configure elilo bootloader") },
3476   { "extlinux", 0, POPT_ARG_NONE, &configureExtLinux, 0,   { "extlinux", 0, POPT_ARG_NONE, &configureExtLinux, 0,
3477      _("configure extlinux bootloader (from syslinux)") },      _("configure extlinux bootloader (from syslinux)") },
3478   { "grub", 0, POPT_ARG_NONE, &configureGrub, 0,   { "grub", 0, POPT_ARG_NONE, &configureGrub, 0,
3479      _("configure grub bootloader") },      _("configure grub bootloader") },
3480     { "grub2", 0, POPT_ARG_NONE, &configureGrub2, 0,
3481        _("configure grub2 bootloader") },
3482   { "info", 0, POPT_ARG_STRING, &kernelInfo, 0,   { "info", 0, POPT_ARG_STRING, &kernelInfo, 0,
3483      _("display boot information for specified kernel"),      _("display boot information for specified kernel"),
3484      _("kernel-path") },      _("kernel-path") },
# Line 2991  int main(int argc, const char ** argv) { Line 3558  int main(int argc, const char ** argv) {
3558   return 1;   return 1;
3559      }      }
3560    
3561      if ((configureLilo + configureGrub + configureELilo +      if ((configureLilo + configureGrub2 + configureGrub + configureELilo +
3562   configureYaboot + configureSilo + configureZipl +   configureYaboot + configureSilo + configureZipl +
3563   configureExtLinux ) > 1) {   configureExtLinux ) > 1) {
3564   fprintf(stderr, _("grubby: cannot specify multiple bootloaders\n"));   fprintf(stderr, _("grubby: cannot specify multiple bootloaders\n"));
# Line 3000  int main(int argc, const char ** argv) { Line 3567  int main(int argc, const char ** argv) {
3567   fprintf(stderr,   fprintf(stderr,
3568      _("grubby: cannot specify config file with --bootloader-probe\n"));      _("grubby: cannot specify config file with --bootloader-probe\n"));
3569   return 1;   return 1;
3570        } else if (configureGrub2) {
3571     cfi = &grub2ConfigType;
3572      } else if (configureLilo) {      } else if (configureLilo) {
3573   cfi = &liloConfigType;   cfi = &liloConfigType;
3574      } else if (configureGrub) {      } else if (configureGrub) {
# Line 3029  int main(int argc, const char ** argv) { Line 3598  int main(int argc, const char ** argv) {
3598        #elif __s390x__        #elif __s390x__
3599          cfi = &ziplConfigtype;          cfi = &ziplConfigtype;
3600        #else        #else
3601   cfi = &grubConfigType;          if (grub2FindConfig(&grub2ConfigType))
3602        cfi = &grub2ConfigType;
3603     else
3604        cfi = &grubConfigType;
3605        #endif        #endif
3606      }      }
3607    
3608      if (!grubConfig)      if (!grubConfig) {
3609   grubConfig = cfi->defaultConfig;   if (cfi->findConfig)
3610        grubConfig = cfi->findConfig(cfi);
3611     if (!grubConfig)
3612        grubConfig = cfi->defaultConfig;
3613        }
3614    
3615      if (bootloaderProbe && (displayDefault || kernelInfo || newKernelVersion ||      if (bootloaderProbe && (displayDefault || kernelInfo || newKernelVersion ||
3616    newKernelPath || removeKernelPath || makeDefault ||    newKernelPath || removeKernelPath || makeDefault ||
3617    defaultKernel)) {    defaultKernel || displayDefaultIndex || displayDefaultTitle)) {
3618   fprintf(stderr, _("grubby: --bootloader-probe may not be used with "   fprintf(stderr, _("grubby: --bootloader-probe may not be used with "
3619    "specified option"));    "specified option"));
3620   return 1;   return 1;
# Line 3081  int main(int argc, const char ** argv) { Line 3657  int main(int argc, const char ** argv) {
3657   defaultKernel = NULL;   defaultKernel = NULL;
3658      }      }
3659    
3660      if (!strcmp(grubConfig, "-") && !outputFile) {      if (grubConfig && !strcmp(grubConfig, "-") && !outputFile) {
3661   fprintf(stderr, _("grubby: output file must be specified if stdin "   fprintf(stderr, _("grubby: output file must be specified if stdin "
3662   "is used\n"));   "is used\n"));
3663   return 1;   return 1;
# Line 3089  int main(int argc, const char ** argv) { Line 3665  int main(int argc, const char ** argv) {
3665    
3666      if (!removeKernelPath && !newKernelPath && !displayDefault && !defaultKernel      if (!removeKernelPath && !newKernelPath && !displayDefault && !defaultKernel
3667   && !kernelInfo && !bootloaderProbe && !updateKernelPath   && !kernelInfo && !bootloaderProbe && !updateKernelPath
3668          && !removeMBKernel) {          && !removeMBKernel && !displayDefaultIndex && !displayDefaultTitle) {
3669   fprintf(stderr, _("grubby: no action specified\n"));   fprintf(stderr, _("grubby: no action specified\n"));
3670   return 1;   return 1;
3671      }      }
# Line 3116  int main(int argc, const char ** argv) { Line 3692  int main(int argc, const char ** argv) {
3692      }      }
3693    
3694      if (bootloaderProbe) {      if (bootloaderProbe) {
3695   int lrc = 0, grc = 0, erc = 0;   int lrc = 0, grc = 0, gr2c = 0, erc = 0;
3696   struct grubConfig * lconfig, * gconfig;   struct grubConfig * lconfig, * gconfig;
3697    
3698   if (!access(grubConfigType.defaultConfig, F_OK)) {   const char *grub2config = grub2FindConfig(&grub2ConfigType);
3699      gconfig = readConfig(grubConfigType.defaultConfig, &grubConfigType);   if (grub2config) {
3700        gconfig = readConfig(grub2config, &grub2ConfigType);
3701        if (!gconfig)
3702     gr2c = 1;
3703        else
3704     gr2c = checkForGrub2(gconfig);
3705     }
3706    
3707     const char *grubconfig = grubFindConfig(&grubConfigType);
3708     if (!access(grubconfig, F_OK)) {
3709        gconfig = readConfig(grubconfig, &grubConfigType);
3710      if (!gconfig)      if (!gconfig)
3711   grc = 1;   grc = 1;
3712      else      else
# Line 3143  int main(int argc, const char ** argv) { Line 3729  int main(int argc, const char ** argv) {
3729   erc = checkForExtLinux(lconfig);   erc = checkForExtLinux(lconfig);
3730   }   }
3731    
3732   if (lrc == 1 || grc == 1) return 1;   if (lrc == 1 || grc == 1 || gr2c == 1) return 1;
3733    
3734   if (lrc == 2) printf("lilo\n");   if (lrc == 2) printf("lilo\n");
3735     if (gr2c == 2) printf("grub2\n");
3736   if (grc == 2) printf("grub\n");   if (grc == 2) printf("grub\n");
3737   if (erc == 2) printf("extlinux\n");   if (erc == 2) printf("extlinux\n");
3738    
# Line 3173  int main(int argc, const char ** argv) { Line 3760  int main(int argc, const char ** argv) {
3760                 ((rootspec != NULL) ? strlen(rootspec) : 0));                 ((rootspec != NULL) ? strlen(rootspec) : 0));
3761    
3762   return 0;   return 0;
3763    
3764        } else if (displayDefaultTitle) {
3765     struct singleLine * line;
3766     struct singleEntry * entry;
3767    
3768     if (config->defaultImage == -1) return 0;
3769     entry = findEntryByIndex(config, config->defaultImage);
3770     if (!entry) return 0;
3771    
3772     if (!configureGrub2) {
3773      line = getLineByType(LT_TITLE, entry->lines);
3774      if (!line) return 0;
3775      printf("%s\n", line->elements[1].item);
3776    
3777     } else {
3778      char * title;
3779    
3780      dbgPrintf("This is GRUB2, default title is embeded in menuentry\n");
3781      line = getLineByType(LT_MENUENTRY, entry->lines);
3782      if (!line) return 0;
3783      title = grub2ExtractTitle(line);
3784      if (title)
3785        printf("%s\n", title);
3786     }
3787     return 0;
3788    
3789        } else if (displayDefaultIndex) {
3790            if (config->defaultImage == -1) return 0;
3791            printf("%i\n", config->defaultImage);
3792    
3793      } else if (kernelInfo)      } else if (kernelInfo)
3794   return displayInfo(config, kernelInfo, bootPrefix);   return displayInfo(config, kernelInfo, bootPrefix);
3795    
# Line 3205  int main(int argc, const char ** argv) { Line 3822  int main(int argc, const char ** argv) {
3822      }      }
3823    
3824      if (!outputFile)      if (!outputFile)
3825   outputFile = grubConfig;   outputFile = (char *)grubConfig;
3826    
3827      return writeConfig(config, outputFile, bootPrefix);      return writeConfig(config, outputFile, bootPrefix);
3828  }  }

Legend:
Removed from v.1332  
changed lines
  Added in v.1801