Magellan Linux

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

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

trunk/mkinitrd-magellan/grubby/grubby.c revision 920 by niro, Wed Oct 28 09:50:42 2009 UTC trunk/grubby/grubby.c revision 1844 by niro, Mon Jul 2 12:59:07 2012 UTC
# Line 36  Line 36 
36  #include <signal.h>  #include <signal.h>
37  #include <blkid/blkid.h>  #include <blkid/blkid.h>
38    
39    #ifndef DEBUG
40  #define DEBUG 0  #define DEBUG 0
41    #endif
42    
43  #if DEBUG  #if DEBUG
44  #define dbgPrintf(format, args...) fprintf(stderr, format , ## args)  #define dbgPrintf(format, args...) fprintf(stderr, format , ## args)
# Line 44  Line 46 
46  #define dbgPrintf(format, args...)  #define dbgPrintf(format, args...)
47  #endif  #endif
48    
49    int debug = 0; /* Currently just for template debugging */
50    
51  #define _(A) (A)  #define _(A) (A)
52    
53  #define MAX_EXTRA_INITRDS  16 /* code segment checked by --bootloader-probe */  #define MAX_EXTRA_INITRDS  16 /* code segment checked by --bootloader-probe */
54  #define CODE_SEG_SIZE  128 /* code segment checked by --bootloader-probe */  #define CODE_SEG_SIZE  128 /* code segment checked by --bootloader-probe */
55    
56    #define NOOP_OPCODE 0x90
57    #define JMP_SHORT_OPCODE 0xeb
58    
59  /* comments get lumped in with indention */  /* comments get lumped in with indention */
60  struct lineElement {  struct lineElement {
61      char * item;      char * item;
# Line 56  struct lineElement { Line 63  struct lineElement {
63  };  };
64    
65  enum lineType_e {  enum lineType_e {
66      LT_WHITESPACE = 1 << 0,      LT_WHITESPACE   = 1 << 0,
67      LT_TITLE      = 1 << 1,      LT_TITLE        = 1 << 1,
68      LT_KERNEL     = 1 << 2,      LT_KERNEL       = 1 << 2,
69      LT_INITRD     = 1 << 3,      LT_INITRD       = 1 << 3,
70      LT_HYPER      = 1 << 4,      LT_HYPER        = 1 << 4,
71      LT_DEFAULT    = 1 << 5,      LT_DEFAULT      = 1 << 5,
72      LT_MBMODULE   = 1 << 6,      LT_MBMODULE     = 1 << 6,
73      LT_ROOT       = 1 << 7,      LT_ROOT         = 1 << 7,
74      LT_FALLBACK   = 1 << 8,      LT_FALLBACK     = 1 << 8,
75      LT_KERNELARGS = 1 << 9,      LT_KERNELARGS   = 1 << 9,
76      LT_BOOT       = 1 << 10,      LT_BOOT         = 1 << 10,
77      LT_BOOTROOT   = 1 << 11,      LT_BOOTROOT     = 1 << 11,
78      LT_LBA        = 1 << 12,      LT_LBA          = 1 << 12,
79      LT_OTHER      = 1 << 13,      LT_OTHER        = 1 << 13,
80      LT_GENERIC    = 1 << 14,      LT_GENERIC      = 1 << 14,
81      LT_UNKNOWN    = 1 << 15,      LT_ECHO    = 1 << 16,
82        LT_MENUENTRY    = 1 << 17,
83        LT_ENTRY_END    = 1 << 18,
84        LT_SET_VARIABLE = 1 << 19,
85        LT_UNKNOWN      = 1 << 20,
86  };  };
87    
88  struct singleLine {  struct singleLine {
# Line 99  struct singleEntry { Line 110  struct singleEntry {
110  #define NEED_TITLE   (1 << 2)  #define NEED_TITLE   (1 << 2)
111  #define NEED_ARGS    (1 << 3)  #define NEED_ARGS    (1 << 3)
112  #define NEED_MB      (1 << 4)  #define NEED_MB      (1 << 4)
113    #define NEED_END     (1 << 5)
114    
115  #define MAIN_DEFAULT    (1 << 0)  #define MAIN_DEFAULT    (1 << 0)
116  #define DEFAULT_SAVED       -2  #define DEFAULT_SAVED       -2
117    #define DEFAULT_SAVED_GRUB2 -3
118    
119  struct keywordTypes {  struct keywordTypes {
120      char * key;      char * key;
# Line 110  struct keywordTypes { Line 123  struct keywordTypes {
123      char separatorChar;      char separatorChar;
124  };  };
125    
126    struct configFileInfo;
127    
128    typedef const char *(*findConfigFunc)(struct configFileInfo *);
129    typedef const int (*writeLineFunc)(struct configFileInfo *,
130     struct singleLine *line);
131    
132  struct configFileInfo {  struct configFileInfo {
133      char * defaultConfig;      char * defaultConfig;
134        findConfigFunc findConfig;
135        writeLineFunc writeLine;
136      struct keywordTypes * keywords;      struct keywordTypes * keywords;
137      int defaultIsIndex;      int defaultIsIndex;
138        int defaultIsVariable;
139      int defaultSupportSaved;      int defaultSupportSaved;
140      enum lineType_e entrySeparator;      enum lineType_e entryStart;
141        enum lineType_e entryEnd;
142      int needsBootPrefix;      int needsBootPrefix;
143      int argsInQuotes;      int argsInQuotes;
144      int maxTitleLength;      int maxTitleLength;
145      int titleBracketed;      int titleBracketed;
146        int titlePosition;
147      int mbHyperFirst;      int mbHyperFirst;
148      int mbInitRdIsModule;      int mbInitRdIsModule;
149      int mbConcatArgs;      int mbConcatArgs;
# Line 138  struct keywordTypes grubKeywords[] = { Line 162  struct keywordTypes grubKeywords[] = {
162      { NULL,    0, 0 },      { NULL,    0, 0 },
163  };  };
164    
165    const char *grubFindConfig(struct configFileInfo *cfi) {
166        static const char *configFiles[] = {
167     "/etc/grub.conf",
168     "/boot/grub/grub.conf",
169     "/boot/grub/menu.lst",
170     NULL
171        };
172        static int i = -1;
173    
174        if (i == -1) {
175     for (i = 0; configFiles[i] != NULL; i++) {
176        dbgPrintf("Checking \"%s\": ", configFiles[i]);
177        if (!access(configFiles[i], R_OK)) {
178     dbgPrintf("found\n");
179     return configFiles[i];
180        }
181        dbgPrintf("not found\n");
182     }
183        }
184        return configFiles[i];
185    }
186    
187  struct configFileInfo grubConfigType = {  struct configFileInfo grubConfigType = {
188      "/boot/grub/grub.conf",    /* defaultConfig */      .findConfig = grubFindConfig,
189      grubKeywords,    /* keywords */      .keywords = grubKeywords,
190      1,    /* defaultIsIndex */      .defaultIsIndex = 1,
191      1,    /* defaultSupportSaved */      .defaultSupportSaved = 1,
192      LT_TITLE,    /* entrySeparator */      .entryStart = LT_TITLE,
193      1,    /* needsBootPrefix */      .needsBootPrefix = 1,
194      0,    /* argsInQuotes */      .mbHyperFirst = 1,
195      0,    /* maxTitleLength */      .mbInitRdIsModule = 1,
196      0,                                      /* titleBracketed */      .mbAllowExtraInitRds = 1,
197      1,                                      /* mbHyperFirst */  };
198      1,                                      /* mbInitRdIsModule */  
199      0,                                      /* mbConcatArgs */  struct keywordTypes grub2Keywords[] = {
200      1,                                      /* mbAllowExtraInitRds */      { "menuentry",  LT_MENUENTRY,   ' ' },
201        { "}",          LT_ENTRY_END,   ' ' },
202        { "echo",       LT_ECHO,        ' ' },
203        { "set",        LT_SET_VARIABLE,' ', '=' },
204        { "root",       LT_BOOTROOT,    ' ' },
205        { "default",    LT_DEFAULT,     ' ' },
206        { "fallback",   LT_FALLBACK,    ' ' },
207        { "linux",      LT_KERNEL,      ' ' },
208        { "initrd",     LT_INITRD,      ' ', ' ' },
209        { "module",     LT_MBMODULE,    ' ' },
210        { "kernel",     LT_HYPER,       ' ' },
211        { NULL, 0, 0 },
212    };
213    
214    const char *grub2FindConfig(struct configFileInfo *cfi) {
215        static const char *configFiles[] = {
216     "/boot/grub/grub-efi.cfg",
217     "/boot/grub/grub.cfg",
218     NULL
219        };
220        static int i = -1;
221        static const char *grub_cfg = "/boot/grub/grub.cfg";
222    
223        if (i == -1) {
224     for (i = 0; configFiles[i] != NULL; i++) {
225        dbgPrintf("Checking \"%s\": ", configFiles[i]);
226        if (!access(configFiles[i], R_OK)) {
227     dbgPrintf("found\n");
228     return configFiles[i];
229        }
230     }
231        }
232    
233        /* Ubuntu renames grub2 to grub, so check for the grub.d directory
234         * that isn't in grub1, and if it exists, return the config file path
235         * that they use. */
236        if (configFiles[i] == NULL && !access("/etc/grub.d/", R_OK)) {
237     dbgPrintf("found\n");
238     return grub_cfg;
239        }
240    
241        dbgPrintf("not found\n");
242        return configFiles[i];
243    }
244    
245    int sizeOfSingleLine(struct singleLine * line) {
246      int i;
247      int count = 0;
248    
249      for (i = 0; i < line->numElements; i++) {
250        int indentSize = 0;
251    
252        count = count + strlen(line->elements[i].item);
253    
254        indentSize = strlen(line->elements[i].indent);
255        if (indentSize > 0)
256          count = count + indentSize;
257        else
258          /* be extra safe and add room for whitespaces */
259          count = count + 1;
260      }
261    
262      /* room for trailing terminator */
263      count = count + 1;
264    
265      return count;
266    }
267    
268    static int isquote(char q)
269    {
270        if (q == '\'' || q == '\"')
271     return 1;
272        return 0;
273    }
274    
275    char *grub2ExtractTitle(struct singleLine * line) {
276        char * current;
277        char * current_indent;
278        int current_len;
279        int current_indent_len;
280        int i;
281    
282        /* bail out if line does not start with menuentry */
283        if (strcmp(line->elements[0].item, "menuentry"))
284          return NULL;
285    
286        i = 1;
287        current = line->elements[i].item;
288        current_len = strlen(current);
289    
290        /* if second word is quoted, strip the quotes and return single word */
291        if (isquote(*current) && isquote(current[current_len - 1])) {
292     char *tmp;
293    
294     tmp = strdup(current);
295     *(tmp + current_len - 1) = '\0';
296     return ++tmp;
297        }
298    
299        /* if no quotes, return second word verbatim */
300        if (!isquote(*current))
301     return current;
302    
303        /* second element start with a quote, so we have to find the element
304         * whose last character is also quote (assuming it's the closing one) */
305        int resultMaxSize;
306        char * result;
307        
308        resultMaxSize = sizeOfSingleLine(line);
309        result = malloc(resultMaxSize);
310        snprintf(result, resultMaxSize, "%s", ++current);
311        
312        i++;
313        for (; i < line->numElements; ++i) {
314     current = line->elements[i].item;
315     current_len = strlen(current);
316     current_indent = line->elements[i].indent;
317     current_indent_len = strlen(current_indent);
318    
319     strncat(result, current_indent, current_indent_len);
320     if (!isquote(current[current_len-1])) {
321        strncat(result, current, current_len);
322     } else {
323        strncat(result, current, current_len - 1);
324        break;
325     }
326        }
327        return result;
328    }
329    
330    struct configFileInfo grub2ConfigType = {
331        .findConfig = grub2FindConfig,
332        .keywords = grub2Keywords,
333        .defaultIsIndex = 1,
334        .defaultSupportSaved = 1,
335        .defaultIsVariable = 1,
336        .entryStart = LT_MENUENTRY,
337        .entryEnd = LT_ENTRY_END,
338        .titlePosition = 1,
339        .needsBootPrefix = 1,
340        .mbHyperFirst = 1,
341        .mbInitRdIsModule = 1,
342        .mbAllowExtraInitRds = 1,
343  };  };
344    
345  struct keywordTypes yabootKeywords[] = {  struct keywordTypes yabootKeywords[] = {
# Line 249  struct keywordTypes extlinuxKeywords[] = Line 437  struct keywordTypes extlinuxKeywords[] =
437  };  };
438  int useextlinuxmenu;  int useextlinuxmenu;
439  struct configFileInfo eliloConfigType = {  struct configFileInfo eliloConfigType = {
440      "/boot/efi/EFI/redhat/elilo.conf",    /* defaultConfig */      .defaultConfig = "/boot/efi/EFI/redhat/elilo.conf",
441      eliloKeywords,    /* keywords */      .keywords = eliloKeywords,
442      0,    /* defaultIsIndex */      .entryStart = LT_KERNEL,
443      0,    /* defaultSupportSaved */      .needsBootPrefix = 1,
444      LT_KERNEL,    /* entrySeparator */      .argsInQuotes = 1,
445      1,                    /* needsBootPrefix */      .mbConcatArgs = 1,
     1,    /* argsInQuotes */  
     0,    /* maxTitleLength */  
     0,                                      /* titleBracketed */  
     0,                                      /* mbHyperFirst */  
     0,                                      /* mbInitRdIsModule */  
     1,                                      /* mbConcatArgs */  
     0,                                      /* mbAllowExtraInitRds */  
446  };  };
447    
448  struct configFileInfo liloConfigType = {  struct configFileInfo liloConfigType = {
449      "/etc/lilo.conf",    /* defaultConfig */      .defaultConfig = "/etc/lilo.conf",
450      liloKeywords,    /* keywords */      .keywords = liloKeywords,
451      0,    /* defaultIsIndex */      .entryStart = LT_KERNEL,
452      0,    /* defaultSupportSaved */      .argsInQuotes = 1,
453      LT_KERNEL,    /* entrySeparator */      .maxTitleLength = 15,
     0,    /* needsBootPrefix */  
     1,    /* argsInQuotes */  
     15,    /* maxTitleLength */  
     0,                                      /* titleBracketed */  
     0,                                      /* mbHyperFirst */  
     0,                                      /* mbInitRdIsModule */  
     0,                                      /* mbConcatArgs */  
     0,                                      /* mbAllowExtraInitRds */  
454  };  };
455    
456  struct configFileInfo yabootConfigType = {  struct configFileInfo yabootConfigType = {
457      "/etc/yaboot.conf",    /* defaultConfig */      .defaultConfig = "/etc/yaboot.conf",
458      yabootKeywords,    /* keywords */      .keywords = yabootKeywords,
459      0,    /* defaultIsIndex */      .entryStart = LT_KERNEL,
460      0,    /* defaultSupportSaved */      .needsBootPrefix = 1,
461      LT_KERNEL,    /* entrySeparator */      .argsInQuotes = 1,
462      1,    /* needsBootPrefix */      .maxTitleLength = 15,
463      1,    /* argsInQuotes */      .mbAllowExtraInitRds = 1,
     15,    /* maxTitleLength */  
     0,                                      /* titleBracketed */  
     0,                                      /* mbHyperFirst */  
     0,                                      /* mbInitRdIsModule */  
     0,                                      /* mbConcatArgs */  
     1,                                      /* mbAllowExtraInitRds */  
464  };  };
465    
466  struct configFileInfo siloConfigType = {  struct configFileInfo siloConfigType = {
467      "/etc/silo.conf",    /* defaultConfig */      .defaultConfig = "/etc/silo.conf",
468      siloKeywords,    /* keywords */      .keywords = siloKeywords,
469      0,    /* defaultIsIndex */      .entryStart = LT_KERNEL,
470      0,    /* defaultSupportSaved */      .needsBootPrefix = 1,
471      LT_KERNEL,    /* entrySeparator */      .argsInQuotes = 1,
472      1,    /* needsBootPrefix */      .maxTitleLength = 15,
     1,    /* argsInQuotes */  
     15,    /* maxTitleLength */  
     0,                                      /* titleBracketed */  
     0,                                      /* mbHyperFirst */  
     0,                                      /* mbInitRdIsModule */  
     0,                                      /* mbConcatArgs */  
     0,                                      /* mbAllowExtraInitRds */  
473  };  };
474    
475  struct configFileInfo ziplConfigType = {  struct configFileInfo ziplConfigType = {
476      "/etc/zipl.conf",    /* defaultConfig */      .defaultConfig = "/etc/zipl.conf",
477      ziplKeywords,    /* keywords */      .keywords = ziplKeywords,
478      0,    /* defaultIsIndex */      .entryStart = LT_TITLE,
479      0,    /* defaultSupportSaved */      .argsInQuotes = 1,
480      LT_TITLE,    /* entrySeparator */      .titleBracketed = 1,
     0,    /* needsBootPrefix */  
     1,    /* argsInQuotes */  
     0,    /* maxTitleLength */  
     1,                                      /* titleBracketed */  
     0,                                      /* mbHyperFirst */  
     0,                                      /* mbInitRdIsModule */  
     0,                                      /* mbConcatArgs */  
     0,                                      /* mbAllowExtraInitRds */  
481  };  };
482    
483  struct configFileInfo extlinuxConfigType = {  struct configFileInfo extlinuxConfigType = {
484      "/boot/extlinux/extlinux.conf",         /* defaultConfig */      .defaultConfig = "/boot/extlinux/extlinux.conf",
485      extlinuxKeywords,                       /* keywords */      .keywords = extlinuxKeywords,
486      0,                                      /* defaultIsIndex */      .entryStart = LT_TITLE,
487      0,                                      /* defaultSupportSaved */      .needsBootPrefix = 1,
488      LT_TITLE,                               /* entrySeparator */      .maxTitleLength = 255,
489      1,                                      /* needsBootPrefix */      .mbAllowExtraInitRds = 1,
     0,                                      /* argsInQuotes */  
     255,                                    /* maxTitleLength */  
     0,                                      /* titleBracketed */  
     0,                                      /* mbHyperFirst */  
     0,                                      /* mbInitRdIsModule */  
     0,                                      /* mbConcatArgs */  
     1,                                      /* mbAllowExtraInitRds */  
490  };  };
491    
492  struct grubConfig {  struct grubConfig {
# Line 356  struct grubConfig { Line 501  struct grubConfig {
501      struct configFileInfo * cfi;      struct configFileInfo * cfi;
502  };  };
503    
504    blkid_cache blkid;
505    
506  struct singleEntry * findEntryByIndex(struct grubConfig * cfg, int index);  struct singleEntry * findEntryByIndex(struct grubConfig * cfg, int index);
507  struct singleEntry * findEntryByPath(struct grubConfig * cfg,  struct singleEntry * findEntryByPath(struct grubConfig * cfg,
508       const char * path, const char * prefix,       const char * path, const char * prefix,
# Line 369  static int lineWrite(FILE * out, struct Line 516  static int lineWrite(FILE * out, struct
516  static int getNextLine(char ** bufPtr, struct singleLine * line,  static int getNextLine(char ** bufPtr, struct singleLine * line,
517         struct configFileInfo * cfi);         struct configFileInfo * cfi);
518  static char * getRootSpecifier(char * str);  static char * getRootSpecifier(char * str);
519    static void requote(struct singleLine *line, struct configFileInfo * cfi);
520  static void insertElement(struct singleLine * line,  static void insertElement(struct singleLine * line,
521    const char * item, int insertHere,    const char * item, int insertHere,
522    struct configFileInfo * cfi);    struct configFileInfo * cfi);
# Line 433  static struct keywordTypes * getKeywordB Line 581  static struct keywordTypes * getKeywordB
581      return NULL;      return NULL;
582  }  }
583    
584  static char * getpathbyspec(char *device) {  static char *getKeyByType(enum lineType_e type, struct configFileInfo * cfi) {
585      static blkid_cache blkid;      struct keywordTypes *kt = getKeywordByType(type, cfi);
586        if (kt)
587     return kt->key;
588        return "unknown";
589    }
590    
591    static char * getpathbyspec(char *device) {
592      if (!blkid)      if (!blkid)
593          blkid_get_cache(&blkid, NULL);          blkid_get_cache(&blkid, NULL);
594    
595      return blkid_get_devname(blkid, device, NULL);      return blkid_get_devname(blkid, device, NULL);
596  }  }
597    
598    static char * getuuidbydev(char *device) {
599        if (!blkid)
600     blkid_get_cache(&blkid, NULL);
601    
602        return blkid_get_tag_value(blkid, "UUID", device);
603    }
604    
605  static enum lineType_e getTypeByKeyword(char * keyword,  static enum lineType_e getTypeByKeyword(char * keyword,
606   struct configFileInfo * cfi) {   struct configFileInfo * cfi) {
607      struct keywordTypes * kw;      struct keywordTypes * kw;
# Line 477  static int isBracketedTitle(struct singl Line 637  static int isBracketedTitle(struct singl
637      return 0;      return 0;
638  }  }
639    
640  static int isEntrySeparator(struct singleLine * line,  static int isEntryStart(struct singleLine * line,
641                              struct configFileInfo * cfi) {                              struct configFileInfo * cfi) {
642      return line->type == cfi->entrySeparator || line->type == LT_OTHER ||      return line->type == cfi->entryStart || line->type == LT_OTHER ||
643   (cfi->titleBracketed && isBracketedTitle(line));   (cfi->titleBracketed && isBracketedTitle(line));
644  }  }
645    
# Line 571  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 729  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 802  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 818  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 878  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 887  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 931  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 945  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 993  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 1086  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 1155  static int numEntries(struct grubConfig Line 1436  static int numEntries(struct grubConfig
1436      return i;      return i;
1437  }  }
1438    
1439    static char *findDiskForRoot()
1440    {
1441        int fd;
1442        char buf[65536];
1443        char *devname;
1444        char *chptr;
1445        int rc;
1446    
1447        if ((fd = open(_PATH_MOUNTED, O_RDONLY)) < 0) {
1448            fprintf(stderr, "grubby: failed to open %s: %s\n",
1449                    _PATH_MOUNTED, strerror(errno));
1450            return NULL;
1451        }
1452    
1453        rc = read(fd, buf, sizeof(buf) - 1);
1454        if (rc <= 0) {
1455            fprintf(stderr, "grubby: failed to read %s: %s\n",
1456                    _PATH_MOUNTED, strerror(errno));
1457            close(fd);
1458            return NULL;
1459        }
1460        close(fd);
1461        buf[rc] = '\0';
1462        chptr = buf;
1463    
1464        char *foundanswer = NULL;
1465    
1466        while (chptr && chptr != buf+rc) {
1467            devname = chptr;
1468    
1469            /*
1470             * The first column of a mtab entry is the device, but if the entry is a
1471             * special device it won't start with /, so move on to the next line.
1472             */
1473            if (*devname != '/') {
1474                chptr = strchr(chptr, '\n');
1475                if (chptr)
1476                    chptr++;
1477                continue;
1478            }
1479    
1480            /* Seek to the next space */
1481            chptr = strchr(chptr, ' ');
1482            if (!chptr) {
1483                fprintf(stderr, "grubby: error parsing %s: %s\n",
1484                        _PATH_MOUNTED, strerror(errno));
1485                return NULL;
1486            }
1487    
1488            /*
1489             * The second column of a mtab entry is the mount point, we are looking
1490             * for '/' obviously.
1491             */
1492            if (*(++chptr) == '/' && *(++chptr) == ' ') {
1493                /* remember the last / entry in mtab */
1494               foundanswer = devname;
1495            }
1496    
1497            /* Next line */
1498            chptr = strchr(chptr, '\n');
1499            if (chptr)
1500                chptr++;
1501        }
1502    
1503        /* Return the last / entry found */
1504        if (foundanswer) {
1505            chptr = strchr(foundanswer, ' ');
1506            *chptr = '\0';
1507            return strdup(foundanswer);
1508        }
1509    
1510        return NULL;
1511    }
1512    
1513    void printEntry(struct singleEntry * entry) {
1514        int i;
1515        struct singleLine * line;
1516    
1517        for (line = entry->lines; line; line = line->next) {
1518     fprintf(stderr, "DBG: %s", line->indent);
1519     for (i = 0; i < line->numElements; i++) {
1520        /* Need to handle this, because we strip the quotes from
1521         * menuentry when read it. */
1522        if (line->type == LT_MENUENTRY && i == 1) {
1523     if(!isquote(*line->elements[i].item))
1524        fprintf(stderr, "\'%s\'", line->elements[i].item);
1525     else
1526        fprintf(stderr, "%s", line->elements[i].item);
1527     fprintf(stderr, "%s", line->elements[i].indent);
1528    
1529     continue;
1530        }
1531        
1532        fprintf(stderr, "%s%s",
1533        line->elements[i].item, line->elements[i].indent);
1534     }
1535     fprintf(stderr, "\n");
1536        }
1537    }
1538    
1539    void notSuitablePrintf(struct singleEntry * entry, const char *fmt, ...)
1540    {
1541        va_list argp;
1542    
1543        if (!debug)
1544     return;
1545    
1546        va_start(argp, fmt);
1547        fprintf(stderr, "DBG: Image entry failed: ");
1548        vfprintf(stderr, fmt, argp);
1549        printEntry(entry);
1550        va_end(argp);
1551    }
1552    
1553    #define beginswith(s, c) ((s) && (s)[0] == (c))
1554    
1555    static int endswith(const char *s, char c)
1556    {
1557     int slen;
1558    
1559     if (!s || !s[0])
1560     return 0;
1561     slen = strlen(s) - 1;
1562    
1563     return s[slen] == c;
1564    }
1565    
1566  int suitableImage(struct singleEntry * entry, const char * bootPrefix,  int suitableImage(struct singleEntry * entry, const char * bootPrefix,
1567    int skipRemoved, int flags) {    int skipRemoved, int flags) {
1568      struct singleLine * line;      struct singleLine * line;
1569      char * fullName;      char * fullName;
1570      int i;      int i;
     struct stat sb, sb2;  
1571      char * dev;      char * dev;
1572      char * rootspec;      char * rootspec;
1573        char * rootdev;
1574    
1575      if (skipRemoved && entry->skip) return 0;      if (skipRemoved && entry->skip) {
1576     notSuitablePrintf(entry, "marked to skip\n");
1577     return 0;
1578        }
1579    
1580      line = getLineByType(LT_KERNEL|LT_HYPER, entry->lines);      line = getLineByType(LT_KERNEL|LT_HYPER, entry->lines);
1581      if (!line || line->numElements < 2) return 0;      if (!line) {
1582     notSuitablePrintf(entry, "no line found\n");
1583     return 0;
1584        }
1585        if (line->numElements < 2) {
1586     notSuitablePrintf(entry, "line has only %d elements\n",
1587        line->numElements);
1588     return 0;
1589        }
1590    
1591      if (flags & GRUBBY_BADIMAGE_OKAY) return 1;      if (flags & GRUBBY_BADIMAGE_OKAY) return 1;
1592    
1593      fullName = alloca(strlen(bootPrefix) +      fullName = alloca(strlen(bootPrefix) +
1594        strlen(line->elements[1].item) + 1);        strlen(line->elements[1].item) + 1);
1595      rootspec = getRootSpecifier(line->elements[1].item);      rootspec = getRootSpecifier(line->elements[1].item);
1596      sprintf(fullName, "%s%s", bootPrefix,      int rootspec_offset = rootspec ? strlen(rootspec) : 0;
1597              line->elements[1].item + (rootspec ? strlen(rootspec) : 0));      int hasslash = endswith(bootPrefix, '/') ||
1598      if (access(fullName, R_OK)) return 0;       beginswith(line->elements[1].item + rootspec_offset, '/');
1599        sprintf(fullName, "%s%s%s", bootPrefix, hasslash ? "" : "/",
1600                line->elements[1].item + rootspec_offset);
1601        if (access(fullName, R_OK)) {
1602     notSuitablePrintf(entry, "access to %s failed\n", fullName);
1603     return 0;
1604        }
1605      for (i = 2; i < line->numElements; i++)      for (i = 2; i < line->numElements; i++)
1606   if (!strncasecmp(line->elements[i].item, "root=", 5)) break;   if (!strncasecmp(line->elements[i].item, "root=", 5)) break;
1607      if (i < line->numElements) {      if (i < line->numElements) {
# Line 1195  int suitableImage(struct singleEntry * e Line 1619  int suitableImage(struct singleEntry * e
1619      line = getLineByType(LT_KERNELARGS|LT_MBMODULE, entry->lines);      line = getLineByType(LT_KERNELARGS|LT_MBMODULE, entry->lines);
1620    
1621              /* failed to find one */              /* failed to find one */
1622              if (!line) return 0;              if (!line) {
1623     notSuitablePrintf(entry, "no line found\n");
1624     return 0;
1625                }
1626    
1627      for (i = 1; i < line->numElements; i++)      for (i = 1; i < line->numElements; i++)
1628          if (!strncasecmp(line->elements[i].item, "root=", 5)) break;          if (!strncasecmp(line->elements[i].item, "root=", 5)) break;
1629      if (i < line->numElements)      if (i < line->numElements)
1630          dev = line->elements[i].item + 5;          dev = line->elements[i].item + 5;
1631      else {      else {
1632     notSuitablePrintf(entry, "no root= entry found\n");
1633   /* it failed too...  can't find root= */   /* it failed too...  can't find root= */
1634          return 0;          return 0;
1635              }              }
# Line 1209  int suitableImage(struct singleEntry * e Line 1637  int suitableImage(struct singleEntry * e
1637      }      }
1638    
1639      dev = getpathbyspec(dev);      dev = getpathbyspec(dev);
1640      if (!dev)      if (!getpathbyspec(dev)) {
1641            notSuitablePrintf(entry, "can't find blkid entry for %s\n", dev);
1642          return 0;          return 0;
1643        } else
1644     dev = getpathbyspec(dev);
1645    
1646      i = stat(dev, &sb);      rootdev = findDiskForRoot();
1647      if (i)      if (!rootdev) {
1648            notSuitablePrintf(entry, "can't find root device\n");
1649   return 0;   return 0;
1650        }
1651    
1652      stat("/", &sb2);      if (!getuuidbydev(rootdev) || !getuuidbydev(dev)) {
1653            notSuitablePrintf(entry, "uuid missing: rootdev %s, dev %s\n",
1654     getuuidbydev(rootdev), getuuidbydev(dev));
1655            free(rootdev);
1656            return 0;
1657        }
1658    
1659      if (sb.st_rdev != sb2.st_dev)      if (strcmp(getuuidbydev(rootdev), getuuidbydev(dev))) {
1660            notSuitablePrintf(entry, "uuid mismatch: rootdev %s, dev %s\n",
1661     getuuidbydev(rootdev), getuuidbydev(dev));
1662     free(rootdev);
1663          return 0;          return 0;
1664        }
1665    
1666        free(rootdev);
1667    
1668      return 1;      return 1;
1669  }  }
# Line 1301  struct singleEntry * findEntryByPath(str Line 1745  struct singleEntry * findEntryByPath(str
1745    
1746   if (!strncmp(kernel, "TITLE=", 6)) {   if (!strncmp(kernel, "TITLE=", 6)) {
1747      prefix = "";      prefix = "";
1748      checkType = LT_TITLE;      checkType = LT_TITLE|LT_MENUENTRY;
1749      kernel += 6;      kernel += 6;
1750   }   }
1751    
# Line 1317  struct singleEntry * findEntryByPath(str Line 1761  struct singleEntry * findEntryByPath(str
1761       checkType, line);       checkType, line);
1762   if (!line) break;  /* not found in this entry */   if (!line) break;  /* not found in this entry */
1763    
1764   if (line && line->numElements >= 2) {   if (line && line->type != LT_MENUENTRY &&
1765     line->numElements >= 2) {
1766      rootspec = getRootSpecifier(line->elements[1].item);      rootspec = getRootSpecifier(line->elements[1].item);
1767      if (!strcmp(line->elements[1].item +      if (!strcmp(line->elements[1].item +
1768   ((rootspec != NULL) ? strlen(rootspec) : 0),   ((rootspec != NULL) ? strlen(rootspec) : 0),
1769   kernel + strlen(prefix)))   kernel + strlen(prefix)))
1770   break;   break;
1771   }   }
1772     if(line->type == LT_MENUENTRY &&
1773     !strcmp(line->elements[1].item, kernel))
1774        break;
1775      }      }
1776    
1777      /* make sure this entry has a kernel identifier; this skips      /* make sure this entry has a kernel identifier; this skips
# Line 1415  void markRemovedImage(struct grubConfig Line 1863  void markRemovedImage(struct grubConfig
1863        const char * prefix) {        const char * prefix) {
1864      struct singleEntry * entry;      struct singleEntry * entry;
1865    
1866      if (!image) return;      if (!image)
1867     return;
1868    
1869        /* check and see if we're removing the default image */
1870        if (isdigit(*image)) {
1871     entry = findEntryByPath(cfg, image, prefix, NULL);
1872     if(entry)
1873        entry->skip = 1;
1874     return;
1875        }
1876    
1877      while ((entry = findEntryByPath(cfg, image, prefix, NULL)))      while ((entry = findEntryByPath(cfg, image, prefix, NULL)))
1878   entry->skip = 1;   entry->skip = 1;
# Line 1442  void setDefaultImage(struct grubConfig * Line 1899  void setDefaultImage(struct grubConfig *
1899    
1900      /* 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
1901         changes */         changes */
1902      if (config->defaultImage == DEFAULT_SAVED)      if ((config->defaultImage == DEFAULT_SAVED) ||
1903     (config->defaultImage == DEFAULT_SAVED_GRUB2))
1904        /* default is set to saved, we don't want to change it */        /* default is set to saved, we don't want to change it */
1905        return;        return;
1906    
# Line 1509  void displayEntry(struct singleEntry * e Line 1967  void displayEntry(struct singleEntry * e
1967          return;          return;
1968      }      }
1969    
1970      printf("kernel=%s\n", line->elements[1].item);      printf("kernel=%s%s\n", prefix, line->elements[1].item);
1971    
1972      if (line->numElements >= 3) {      if (line->numElements >= 3) {
1973   printf("args=\"");   printf("args=\"");
# Line 1573  void displayEntry(struct singleEntry * e Line 2031  void displayEntry(struct singleEntry * e
2031      printf("%s%s", line->elements[i].item, line->elements[i].indent);      printf("%s%s", line->elements[i].item, line->elements[i].indent);
2032   printf("\n");   printf("\n");
2033      }      }
2034    
2035        line = getLineByType(LT_TITLE, entry->lines);
2036        if (line) {
2037     printf("title=%s\n", line->elements[1].item);
2038        } else {
2039     char * title;
2040     line = getLineByType(LT_MENUENTRY, entry->lines);
2041     title = grub2ExtractTitle(line);
2042     if (title)
2043        printf("title=%s\n", title);
2044        }
2045  }  }
2046    
2047  int parseSysconfigGrub(int * lbaPtr, char ** bootPtr) {  int parseSysconfigGrub(int * lbaPtr, char ** bootPtr) {
# Line 1582  int parseSysconfigGrub(int * lbaPtr, cha Line 2051  int parseSysconfigGrub(int * lbaPtr, cha
2051      char * start;      char * start;
2052      char * param;      char * param;
2053    
2054      in = fopen("/etc/sysconfig/grub", "r");      in = fopen("/etc/conf.d/grub", "r");
2055      if (!in) return 1;      if (!in) return 1;
2056    
2057      if (lbaPtr) *lbaPtr = 0;      if (lbaPtr) *lbaPtr = 0;
# Line 1644  int displayInfo(struct grubConfig * conf Line 2113  int displayInfo(struct grubConfig * conf
2113   return 1;   return 1;
2114      }      }
2115    
2116      /* this is a horrible hack to support /etc/sysconfig/grub; there must      /* this is a horrible hack to support /etc/conf.d/grub; there must
2117         be a better way */         be a better way */
2118      if (config->cfi == &grubConfigType) {      if (config->cfi == &grubConfigType) {
2119   dumpSysconfigGrub();   dumpSysconfigGrub();
# Line 1733  struct singleLine *  addLine(struct sing Line 2202  struct singleLine *  addLine(struct sing
2202   sprintf(tmpl.elements[0].item, "[%s]", val);   sprintf(tmpl.elements[0].item, "[%s]", val);
2203   tmpl.elements[0].indent = "";   tmpl.elements[0].indent = "";
2204   val = NULL;   val = NULL;
2205        } else if (type == LT_MENUENTRY) {
2206     char *lineend = "--class gnu-linux --class gnu --class os {";
2207     if (!val) {
2208        fprintf(stderr, "Line type LT_MENUENTRY requires a value\n");
2209        abort();
2210     }
2211     kw = getKeywordByType(type, cfi);
2212     if (!kw) {
2213        fprintf(stderr, "Looking up keyword for unknown type %d\n", type);
2214        abort();
2215     }
2216     tmpl.indent = "";
2217     tmpl.type = type;
2218     tmpl.numElements = 3;
2219     tmpl.elements = alloca(sizeof(*tmpl.elements) * tmpl.numElements);
2220     tmpl.elements[0].item = kw->key;
2221     tmpl.elements[0].indent = alloca(2);
2222     sprintf(tmpl.elements[0].indent, "%c", kw->nextChar);
2223     tmpl.elements[1].item = (char *)val;
2224     tmpl.elements[1].indent = alloca(2);
2225     sprintf(tmpl.elements[1].indent, "%c", kw->nextChar);
2226     tmpl.elements[2].item = alloca(strlen(lineend)+1);
2227     strcpy(tmpl.elements[2].item, lineend);
2228     tmpl.elements[2].indent = "";
2229      } else {      } else {
2230   kw = getKeywordByType(type, cfi);   kw = getKeywordByType(type, cfi);
2231   if (!kw) abort();   if (!kw) {
2232        fprintf(stderr, "Looking up keyword for unknown type %d\n", type);
2233        abort();
2234     }
2235   tmpl.type = type;   tmpl.type = type;
2236   tmpl.numElements = val ? 2 : 1;   tmpl.numElements = val ? 2 : 1;
2237   tmpl.elements = alloca(sizeof(*tmpl.elements) * tmpl.numElements);   tmpl.elements = alloca(sizeof(*tmpl.elements) * tmpl.numElements);
# Line 1759  struct singleLine *  addLine(struct sing Line 2255  struct singleLine *  addLine(struct sing
2255   if (!line->next && !prev) prev = line;   if (!line->next && !prev) prev = line;
2256      }      }
2257    
2258      if (prev == entry->lines)      struct singleLine *menuEntry;
2259   tmpl.indent = defaultIndent ?: "";      menuEntry = getLineByType(LT_MENUENTRY, entry->lines);
2260      else      if (tmpl.type == LT_ENTRY_END) {
2261   tmpl.indent = prev->indent;   if (menuEntry)
2262        tmpl.indent = menuEntry->indent;
2263     else
2264        tmpl.indent = defaultIndent ?: "";
2265        } else if (tmpl.type != LT_MENUENTRY) {
2266     if (menuEntry)
2267        tmpl.indent = "\t";
2268     else if (prev == entry->lines)
2269        tmpl.indent = defaultIndent ?: "";
2270     else
2271        tmpl.indent = prev->indent;
2272        }
2273    
2274      return addLineTmpl(entry, &tmpl, prev, val, cfi);      return addLineTmpl(entry, &tmpl, prev, val, cfi);
2275  }  }
# Line 1789  void removeLine(struct singleEntry * ent Line 2296  void removeLine(struct singleEntry * ent
2296      free(line);      free(line);
2297  }  }
2298    
2299    static void requote(struct singleLine *tmplLine, struct configFileInfo * cfi)
2300    {
2301        struct singleLine newLine = {
2302     .indent = tmplLine->indent,
2303     .type = tmplLine->type,
2304     .next = tmplLine->next,
2305        };
2306        int firstQuotedItem = -1;
2307        int quoteLen = 0;
2308        int j;
2309        int element = 0;
2310        char *c;
2311    
2312        c = malloc(strlen(tmplLine->elements[0].item) + 1);
2313        strcpy(c, tmplLine->elements[0].item);
2314        insertElement(&newLine, c, element++, cfi);
2315        free(c);
2316        c = NULL;
2317    
2318        for (j = 1; j < tmplLine->numElements; j++) {
2319     if (firstQuotedItem == -1) {
2320        quoteLen += strlen(tmplLine->elements[j].item);
2321        
2322        if (isquote(tmplLine->elements[j].item[0])) {
2323     firstQuotedItem = j;
2324            quoteLen += strlen(tmplLine->elements[j].indent);
2325        } else {
2326     c = malloc(quoteLen + 1);
2327     strcpy(c, tmplLine->elements[j].item);
2328     insertElement(&newLine, c, element++, cfi);
2329     free(c);
2330     quoteLen = 0;
2331        }
2332     } else {
2333        int itemlen = strlen(tmplLine->elements[j].item);
2334        quoteLen += itemlen;
2335        quoteLen += strlen(tmplLine->elements[j].indent);
2336        
2337        if (isquote(tmplLine->elements[j].item[itemlen - 1])) {
2338     c = malloc(quoteLen + 1);
2339     c[0] = '\0';
2340     for (int i = firstQuotedItem; i < j+1; i++) {
2341        strcat(c, tmplLine->elements[i].item);
2342        strcat(c, tmplLine->elements[i].indent);
2343     }
2344     insertElement(&newLine, c, element++, cfi);
2345     free(c);
2346    
2347     firstQuotedItem = -1;
2348     quoteLen = 0;
2349        }
2350     }
2351        }
2352        while (tmplLine->numElements)
2353     removeElement(tmplLine, 0);
2354        if (tmplLine->elements)
2355     free(tmplLine->elements);
2356    
2357        tmplLine->numElements = newLine.numElements;
2358        tmplLine->elements = newLine.elements;
2359    }
2360    
2361  static void insertElement(struct singleLine * line,  static void insertElement(struct singleLine * line,
2362    const char * item, int insertHere,    const char * item, int insertHere,
2363    struct configFileInfo * cfi)    struct configFileInfo * cfi)
# Line 1895  int updateActualImage(struct grubConfig Line 2464  int updateActualImage(struct grubConfig
2464      const char ** arg;      const char ** arg;
2465      int useKernelArgs, useRoot;      int useKernelArgs, useRoot;
2466      int firstElement;      int firstElement;
2467      int *usedElements, *usedArgs;      int *usedElements;
2468      int doreplace;      int doreplace;
2469    
2470      if (!image) return 0;      if (!image) return 0;
# Line 1930  int updateActualImage(struct grubConfig Line 2499  int updateActualImage(struct grubConfig
2499      useRoot = (getKeywordByType(LT_ROOT, cfg->cfi)      useRoot = (getKeywordByType(LT_ROOT, cfg->cfi)
2500         && !multibootArgs);         && !multibootArgs);
2501    
     for (k = 0, arg = newArgs; *arg; arg++, k++) ;  
     usedArgs = calloc(k, sizeof(*usedArgs));  
   
2502      for (; (entry = findEntryByPath(cfg, image, prefix, &index)); index++) {      for (; (entry = findEntryByPath(cfg, image, prefix, &index)); index++) {
2503    
2504   if (multibootArgs && !entry->multiboot)   if (multibootArgs && !entry->multiboot)
# Line 2008  int updateActualImage(struct grubConfig Line 2574  int updateActualImage(struct grubConfig
2574          usedElements = calloc(line->numElements, sizeof(*usedElements));          usedElements = calloc(line->numElements, sizeof(*usedElements));
2575    
2576   for (k = 0, arg = newArgs; *arg; arg++, k++) {   for (k = 0, arg = newArgs; *arg; arg++, k++) {
             if (usedArgs[k]) continue;  
2577    
2578      doreplace = 1;      doreplace = 1;
2579      for (i = firstElement; i < line->numElements; i++) {      for (i = firstElement; i < line->numElements; i++) {
# Line 2023  int updateActualImage(struct grubConfig Line 2588  int updateActualImage(struct grubConfig
2588                      continue;                      continue;
2589   if (!argMatch(line->elements[i].item, *arg)) {   if (!argMatch(line->elements[i].item, *arg)) {
2590                      usedElements[i]=1;                      usedElements[i]=1;
                     usedArgs[k]=1;  
2591      break;      break;
2592                  }                  }
2593              }              }
# Line 2093  int updateActualImage(struct grubConfig Line 2657  int updateActualImage(struct grubConfig
2657   }   }
2658      }      }
2659    
     free(usedArgs);  
2660      free(newArgs);      free(newArgs);
2661      free(oldArgs);      free(oldArgs);
2662    
# Line 2119  int updateImage(struct grubConfig * cfg, Line 2682  int updateImage(struct grubConfig * cfg,
2682      return rc;      return rc;
2683  }  }
2684    
2685    int updateInitrd(struct grubConfig * cfg, const char * image,
2686                     const char * prefix, const char * initrd) {
2687        struct singleEntry * entry;
2688        struct singleLine * line, * kernelLine, *endLine = NULL;
2689        int index = 0;
2690    
2691        if (!image) return 0;
2692    
2693        for (; (entry = findEntryByPath(cfg, image, prefix, &index)); index++) {
2694            kernelLine = getLineByType(LT_KERNEL, entry->lines);
2695            if (!kernelLine) continue;
2696    
2697            line = getLineByType(LT_INITRD, entry->lines);
2698            if (line)
2699                removeLine(entry, line);
2700            if (prefix) {
2701                int prefixLen = strlen(prefix);
2702                if (!strncmp(initrd, prefix, prefixLen))
2703                    initrd += prefixLen;
2704            }
2705     endLine = getLineByType(LT_ENTRY_END, entry->lines);
2706     if (endLine)
2707        removeLine(entry, endLine);
2708            line = addLine(entry, cfg->cfi, LT_INITRD, kernelLine->indent, initrd);
2709            if (!line)
2710        return 1;
2711     if (endLine) {
2712        line = addLine(entry, cfg->cfi, LT_ENTRY_END, "", NULL);
2713                if (!line)
2714     return 1;
2715     }
2716    
2717            break;
2718        }
2719    
2720        return 0;
2721    }
2722    
2723  int checkDeviceBootloader(const char * device, const unsigned char * boot) {  int checkDeviceBootloader(const char * device, const unsigned char * boot) {
2724      int fd;      int fd;
2725      unsigned char bootSect[512];      unsigned char bootSect[512];
# Line 2142  int checkDeviceBootloader(const char * d Line 2743  int checkDeviceBootloader(const char * d
2743      if (memcmp(boot, bootSect, 3))      if (memcmp(boot, bootSect, 3))
2744   return 0;   return 0;
2745    
2746      if (boot[1] == 0xeb) {      if (boot[1] == JMP_SHORT_OPCODE) {
2747   offset = boot[2] + 2;   offset = boot[2] + 2;
2748      } else if (boot[1] == 0xe8 || boot[1] == 0xe9) {      } else if (boot[1] == 0xe8 || boot[1] == 0xe9) {
2749   offset = (boot[3] << 8) + boot[2] + 2;   offset = (boot[3] << 8) + boot[2] + 2;
2750      } else if (boot[0] == 0xeb) {      } else if (boot[0] == JMP_SHORT_OPCODE) {
2751   offset = boot[1] + 2;        offset = boot[1] + 2;
2752            /*
2753     * it looks like grub, when copying stage1 into the mbr, patches stage1
2754     * right after the JMP location, replacing other instructions such as
2755     * JMPs for NOOPs. So, relax the check a little bit by skipping those
2756     * different bytes.
2757     */
2758          if ((bootSect[offset + 1] == NOOP_OPCODE)
2759      && (bootSect[offset + 2] == NOOP_OPCODE)) {
2760     offset = offset + 3;
2761          }
2762      } else if (boot[0] == 0xe8 || boot[0] == 0xe9) {      } else if (boot[0] == 0xe8 || boot[0] == 0xe9) {
2763   offset = (boot[2] << 8) + boot[1] + 2;   offset = (boot[2] << 8) + boot[1] + 2;
2764      } else {      } else {
# Line 2289  int checkForLilo(struct grubConfig * con Line 2900  int checkForLilo(struct grubConfig * con
2900      return checkDeviceBootloader(line->elements[1].item, boot);      return checkDeviceBootloader(line->elements[1].item, boot);
2901  }  }
2902    
2903    int checkForGrub2(struct grubConfig * config) {
2904        if (!access("/etc/grub.d/", R_OK))
2905     return 2;
2906    
2907        return 1;
2908    }
2909    
2910  int checkForGrub(struct grubConfig * config) {  int checkForGrub(struct grubConfig * config) {
2911      int fd;      int fd;
2912      unsigned char bootSect[512];      unsigned char bootSect[512];
# Line 2361  static char * getRootSpecifier(char * st Line 2979  static char * getRootSpecifier(char * st
2979  static char * getInitrdVal(struct grubConfig * config,  static char * getInitrdVal(struct grubConfig * config,
2980     const char * prefix, struct singleLine *tmplLine,     const char * prefix, struct singleLine *tmplLine,
2981     const char * newKernelInitrd,     const char * newKernelInitrd,
2982     char ** extraInitrds, int extraInitrdCount)     const char ** extraInitrds, int extraInitrdCount)
2983  {  {
2984      char *initrdVal, *end;      char *initrdVal, *end;
2985      int i;      int i;
# Line 2406  static char * getInitrdVal(struct grubCo Line 3024  static char * getInitrdVal(struct grubCo
3024    
3025  int addNewKernel(struct grubConfig * config, struct singleEntry * template,  int addNewKernel(struct grubConfig * config, struct singleEntry * template,
3026           const char * prefix,           const char * prefix,
3027   char * newKernelPath, char * newKernelTitle,   const char * newKernelPath, const char * newKernelTitle,
3028   char * newKernelArgs, char * newKernelInitrd,   const char * newKernelArgs, const char * newKernelInitrd,
3029   char ** extraInitrds, int extraInitrdCount,   const char ** extraInitrds, int extraInitrdCount,
3030                   char * newMBKernel, char * newMBKernelArgs) {                   const char * newMBKernel, const char * newMBKernelArgs) {
3031      struct singleEntry * new;      struct singleEntry * new;
3032      struct singleLine * newLine = NULL, * tmplLine = NULL, * masterLine = NULL;      struct singleLine * newLine = NULL, * tmplLine = NULL, * masterLine = NULL;
3033      int needs;      int needs;
# Line 2464  int addNewKernel(struct grubConfig * con Line 3082  int addNewKernel(struct grubConfig * con
3082      if (*chptr == '#') continue;      if (*chptr == '#') continue;
3083    
3084      if (tmplLine->type == LT_KERNEL &&      if (tmplLine->type == LT_KERNEL &&
3085   tmplLine->numElements >= 2) {      tmplLine->numElements >= 2) {
3086   if (!template->multiboot && (needs & NEED_MB)) {   if (!template->multiboot && (needs & NEED_MB)) {
3087      /* it's not a multiboot template and this is the kernel      /* it's not a multiboot template and this is the kernel
3088       * line.  Try to be intelligent about inserting the       * line.  Try to be intelligent about inserting the
# Line 2590  int addNewKernel(struct grubConfig * con Line 3208  int addNewKernel(struct grubConfig * con
3208      needs &= ~NEED_INITRD;      needs &= ~NEED_INITRD;
3209   }   }
3210    
3211        } else if (tmplLine->type == LT_MENUENTRY &&
3212           (needs & NEED_TITLE)) {
3213     requote(tmplLine, config->cfi);
3214     char *nkt = malloc(strlen(newKernelTitle)+3);
3215     strcpy(nkt, "'");
3216     strcat(nkt, newKernelTitle);
3217     strcat(nkt, "'");
3218     newLine = addLineTmpl(new, tmplLine, newLine, nkt, config->cfi);
3219     free(nkt);
3220     needs &= ~NEED_TITLE;
3221      } else if (tmplLine->type == LT_TITLE &&      } else if (tmplLine->type == LT_TITLE &&
3222         (needs & NEED_TITLE)) {         (needs & NEED_TITLE)) {
3223   if (tmplLine->numElements >= 2) {   if (tmplLine->numElements >= 2) {
# Line 2603  int addNewKernel(struct grubConfig * con Line 3231  int addNewKernel(struct grubConfig * con
3231        tmplLine->indent, newKernelTitle);        tmplLine->indent, newKernelTitle);
3232      needs &= ~NEED_TITLE;      needs &= ~NEED_TITLE;
3233   }   }
3234        } else if (tmplLine->type == LT_ECHO) {
3235        requote(tmplLine, config->cfi);
3236        static const char *prefix = "'Loading ";
3237        if (tmplLine->numElements > 1 &&
3238        strstr(tmplLine->elements[1].item, prefix) &&
3239        masterLine->next && masterLine->next->type == LT_KERNEL) {
3240     char *newTitle = malloc(strlen(prefix) +
3241     strlen(newKernelTitle) + 2);
3242    
3243     strcpy(newTitle, prefix);
3244     strcat(newTitle, newKernelTitle);
3245     strcat(newTitle, "'");
3246     newLine = addLine(new, config->cfi, LT_ECHO,
3247     tmplLine->indent, newTitle);
3248     free(newTitle);
3249        } else {
3250     /* pass through other lines from the template */
3251     newLine = addLineTmpl(new, tmplLine, newLine, NULL,
3252     config->cfi);
3253        }
3254      } else {      } else {
3255   /* pass through other lines from the template */   /* pass through other lines from the template */
3256   newLine = addLineTmpl(new, tmplLine, newLine, NULL, config->cfi);   newLine = addLineTmpl(new, tmplLine, newLine, NULL, config->cfi);
# Line 2614  int addNewKernel(struct grubConfig * con Line 3261  int addNewKernel(struct grubConfig * con
3261   /* don't have a template, so start the entry with the   /* don't have a template, so start the entry with the
3262   * appropriate starting line   * appropriate starting line
3263   */   */
3264   switch (config->cfi->entrySeparator) {   switch (config->cfi->entryStart) {
3265      case LT_KERNEL:      case LT_KERNEL:
3266   if (new->multiboot && config->cfi->mbHyperFirst) {   if (new->multiboot && config->cfi->mbHyperFirst) {
3267      /* fall through to LT_HYPER */      /* fall through to LT_HYPER */
# Line 2633  int addNewKernel(struct grubConfig * con Line 3280  int addNewKernel(struct grubConfig * con
3280   needs &= ~NEED_MB;   needs &= ~NEED_MB;
3281   break;   break;
3282    
3283        case LT_MENUENTRY: {
3284     char *nkt = malloc(strlen(newKernelTitle)+3);
3285     strcpy(nkt, "'");
3286     strcat(nkt, newKernelTitle);
3287     strcat(nkt, "'");
3288            newLine = addLine(new, config->cfi, LT_MENUENTRY,
3289      config->primaryIndent, nkt);
3290     free(nkt);
3291     needs &= ~NEED_TITLE;
3292     needs |= NEED_END;
3293     break;
3294        }
3295      case LT_TITLE:      case LT_TITLE:
3296   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)
3297   char * templabel;   char * templabel;
# Line 2666  int addNewKernel(struct grubConfig * con Line 3325  int addNewKernel(struct grubConfig * con
3325    
3326      /* add the remainder of the lines, i.e. those that either      /* add the remainder of the lines, i.e. those that either
3327       * 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,
3328       * all the lines following the entrySeparator.       * all the lines following the entryStart.
3329       */       */
3330      if (needs & NEED_TITLE) {      if (needs & NEED_TITLE) {
3331   newLine = addLine(new, config->cfi, LT_TITLE,   newLine = addLine(new, config->cfi, LT_TITLE,
# Line 2707  int addNewKernel(struct grubConfig * con Line 3366  int addNewKernel(struct grubConfig * con
3366   free(initrdVal);   free(initrdVal);
3367   needs &= ~NEED_INITRD;   needs &= ~NEED_INITRD;
3368      }      }
3369        if (needs & NEED_END) {
3370     newLine = addLine(new, config->cfi, LT_ENTRY_END,
3371     config->secondaryIndent, NULL);
3372     needs &= ~NEED_END;
3373        }
3374    
3375      if (needs) {      if (needs) {
3376   printf(_("grubby: needs=%d, aborting\n"), needs);   printf(_("grubby: needs=%d, aborting\n"), needs);
# Line 2736  static void traceback(int signum) Line 3400  static void traceback(int signum)
3400    
3401  int main(int argc, const char ** argv) {  int main(int argc, const char ** argv) {
3402      poptContext optCon;      poptContext optCon;
3403      char * grubConfig = NULL;      const char * grubConfig = NULL;
3404      char * outputFile = NULL;      char * outputFile = NULL;
3405      int arg = 0;      int arg = 0;
3406      int flags = 0;      int flags = 0;
3407      int badImageOkay = 0;      int badImageOkay = 0;
3408        int configureGrub2 = 0;
3409      int configureLilo = 0, configureELilo = 0, configureGrub = 0;      int configureLilo = 0, configureELilo = 0, configureGrub = 0;
3410      int configureYaboot = 0, configureSilo = 0, configureZipl = 0;      int configureYaboot = 0, configureSilo = 0, configureZipl = 0;
3411      int configureExtLinux = 0;      int configureExtLinux = 0;
# Line 2768  int main(int argc, const char ** argv) { Line 3433  int main(int argc, const char ** argv) {
3433      struct singleEntry * template = NULL;      struct singleEntry * template = NULL;
3434      int copyDefault = 0, makeDefault = 0;      int copyDefault = 0, makeDefault = 0;
3435      int displayDefault = 0;      int displayDefault = 0;
3436        int displayDefaultIndex = 0;
3437        int displayDefaultTitle = 0;
3438      struct poptOption options[] = {      struct poptOption options[] = {
3439   { "add-kernel", 0, POPT_ARG_STRING, &newKernelPath, 0,   { "add-kernel", 0, POPT_ARG_STRING, &newKernelPath, 0,
3440      _("add an entry for the specified kernel"), _("kernel-path") },      _("add an entry for the specified kernel"), _("kernel-path") },
# Line 2798  int main(int argc, const char ** argv) { Line 3465  int main(int argc, const char ** argv) {
3465        "the kernel referenced by the default image does not exist, "        "the kernel referenced by the default image does not exist, "
3466        "the first linux entry whose kernel does exist is used as the "        "the first linux entry whose kernel does exist is used as the "
3467        "template"), NULL },        "template"), NULL },
3468     { "debug", 0, 0, &debug, 0,
3469        _("print debugging information for failures") },
3470   { "default-kernel", 0, 0, &displayDefault, 0,   { "default-kernel", 0, 0, &displayDefault, 0,
3471      _("display the path of the default kernel") },      _("display the path of the default kernel") },
3472     { "default-index", 0, 0, &displayDefaultIndex, 0,
3473        _("display the index of the default kernel") },
3474     { "default-title", 0, 0, &displayDefaultTitle, 0,
3475        _("display the title of the default kernel") },
3476   { "elilo", 0, POPT_ARG_NONE, &configureELilo, 0,   { "elilo", 0, POPT_ARG_NONE, &configureELilo, 0,
3477      _("configure elilo bootloader") },      _("configure elilo bootloader") },
3478   { "extlinux", 0, POPT_ARG_NONE, &configureExtLinux, 0,   { "extlinux", 0, POPT_ARG_NONE, &configureExtLinux, 0,
3479      _("configure extlinux bootloader (from syslinux)") },      _("configure extlinux bootloader (from syslinux)") },
3480   { "grub", 0, POPT_ARG_NONE, &configureGrub, 0,   { "grub", 0, POPT_ARG_NONE, &configureGrub, 0,
3481      _("configure grub bootloader") },      _("configure grub bootloader") },
3482     { "grub2", 0, POPT_ARG_NONE, &configureGrub2, 0,
3483        _("configure grub2 bootloader") },
3484   { "info", 0, POPT_ARG_STRING, &kernelInfo, 0,   { "info", 0, POPT_ARG_STRING, &kernelInfo, 0,
3485      _("display boot information for specified kernel"),      _("display boot information for specified kernel"),
3486      _("kernel-path") },      _("kernel-path") },
# Line 2885  int main(int argc, const char ** argv) { Line 3560  int main(int argc, const char ** argv) {
3560   return 1;   return 1;
3561      }      }
3562    
3563      if ((configureLilo + configureGrub + configureELilo +      if ((configureLilo + configureGrub2 + configureGrub + configureELilo +
3564   configureYaboot + configureSilo + configureZipl +   configureYaboot + configureSilo + configureZipl +
3565   configureExtLinux ) > 1) {   configureExtLinux ) > 1) {
3566   fprintf(stderr, _("grubby: cannot specify multiple bootloaders\n"));   fprintf(stderr, _("grubby: cannot specify multiple bootloaders\n"));
# Line 2894  int main(int argc, const char ** argv) { Line 3569  int main(int argc, const char ** argv) {
3569   fprintf(stderr,   fprintf(stderr,
3570      _("grubby: cannot specify config file with --bootloader-probe\n"));      _("grubby: cannot specify config file with --bootloader-probe\n"));
3571   return 1;   return 1;
3572        } else if (configureGrub2) {
3573     cfi = &grub2ConfigType;
3574      } else if (configureLilo) {      } else if (configureLilo) {
3575   cfi = &liloConfigType;   cfi = &liloConfigType;
3576      } else if (configureGrub) {      } else if (configureGrub) {
# Line 2912  int main(int argc, const char ** argv) { Line 3589  int main(int argc, const char ** argv) {
3589      }      }
3590    
3591      if (!cfi) {      if (!cfi) {
3592            if (grub2FindConfig(&grub2ConfigType))
3593        cfi = &grub2ConfigType;
3594     else
3595        #ifdef __ia64__        #ifdef __ia64__
3596   cfi = &eliloConfigType;      cfi = &eliloConfigType;
3597        #elif __powerpc__        #elif __powerpc__
3598   cfi = &yabootConfigType;      cfi = &yabootConfigType;
3599        #elif __sparc__        #elif __sparc__
3600          cfi = &siloConfigType;              cfi = &siloConfigType;
3601        #elif __s390__        #elif __s390__
3602          cfi = &ziplConfigType;              cfi = &ziplConfigType;
3603        #elif __s390x__        #elif __s390x__
3604          cfi = &ziplConfigtype;              cfi = &ziplConfigtype;
3605        #else        #else
3606   cfi = &grubConfigType;      cfi = &grubConfigType;
3607        #endif        #endif
3608      }      }
3609    
3610      if (!grubConfig)      if (!grubConfig) {
3611   grubConfig = cfi->defaultConfig;   if (cfi->findConfig)
3612        grubConfig = cfi->findConfig(cfi);
3613     if (!grubConfig)
3614        grubConfig = cfi->defaultConfig;
3615        }
3616    
3617      if (bootloaderProbe && (displayDefault || kernelInfo || newKernelVersion ||      if (bootloaderProbe && (displayDefault || kernelInfo || newKernelVersion ||
3618    newKernelPath || removeKernelPath || makeDefault ||    newKernelPath || removeKernelPath || makeDefault ||
3619    defaultKernel)) {    defaultKernel || displayDefaultIndex || displayDefaultTitle)) {
3620   fprintf(stderr, _("grubby: --bootloader-probe may not be used with "   fprintf(stderr, _("grubby: --bootloader-probe may not be used with "
3621    "specified option"));    "specified option"));
3622   return 1;   return 1;
# Line 2948  int main(int argc, const char ** argv) { Line 3632  int main(int argc, const char ** argv) {
3632      if (newKernelPath && !newKernelTitle) {      if (newKernelPath && !newKernelTitle) {
3633   fprintf(stderr, _("grubby: kernel title must be specified\n"));   fprintf(stderr, _("grubby: kernel title must be specified\n"));
3634   return 1;   return 1;
3635      } else if (!newKernelPath && (newKernelTitle  || newKernelInitrd ||      } else if (!newKernelPath && (newKernelTitle  || copyDefault ||
3636    newKernelInitrd || copyDefault     ||    (newKernelInitrd && !updateKernelPath)||
3637    makeDefault || extraInitrdCount > 0)) {    makeDefault || extraInitrdCount > 0)) {
3638   fprintf(stderr, _("grubby: kernel path expected\n"));   fprintf(stderr, _("grubby: kernel path expected\n"));
3639   return 1;   return 1;
# Line 2975  int main(int argc, const char ** argv) { Line 3659  int main(int argc, const char ** argv) {
3659   defaultKernel = NULL;   defaultKernel = NULL;
3660      }      }
3661    
3662      if (!strcmp(grubConfig, "-") && !outputFile) {      if (grubConfig && !strcmp(grubConfig, "-") && !outputFile) {
3663   fprintf(stderr, _("grubby: output file must be specified if stdin "   fprintf(stderr, _("grubby: output file must be specified if stdin "
3664   "is used\n"));   "is used\n"));
3665   return 1;   return 1;
# Line 2983  int main(int argc, const char ** argv) { Line 3667  int main(int argc, const char ** argv) {
3667    
3668      if (!removeKernelPath && !newKernelPath && !displayDefault && !defaultKernel      if (!removeKernelPath && !newKernelPath && !displayDefault && !defaultKernel
3669   && !kernelInfo && !bootloaderProbe && !updateKernelPath   && !kernelInfo && !bootloaderProbe && !updateKernelPath
3670          && !removeMBKernel) {          && !removeMBKernel && !displayDefaultIndex && !displayDefaultTitle) {
3671   fprintf(stderr, _("grubby: no action specified\n"));   fprintf(stderr, _("grubby: no action specified\n"));
3672   return 1;   return 1;
3673      }      }
# Line 3010  int main(int argc, const char ** argv) { Line 3694  int main(int argc, const char ** argv) {
3694      }      }
3695    
3696      if (bootloaderProbe) {      if (bootloaderProbe) {
3697   int lrc = 0, grc = 0, erc = 0;   int lrc = 0, grc = 0, gr2c = 0, erc = 0;
3698   struct grubConfig * lconfig, * gconfig;   struct grubConfig * lconfig, * gconfig;
3699    
3700   if (!access(grubConfigType.defaultConfig, F_OK)) {   const char *grub2config = grub2FindConfig(&grub2ConfigType);
3701      gconfig = readConfig(grubConfigType.defaultConfig, &grubConfigType);   if (grub2config) {
3702        gconfig = readConfig(grub2config, &grub2ConfigType);
3703        if (!gconfig)
3704     gr2c = 1;
3705        else
3706     gr2c = checkForGrub2(gconfig);
3707     }
3708    
3709     const char *grubconfig = grubFindConfig(&grubConfigType);
3710     if (!access(grubconfig, F_OK)) {
3711        gconfig = readConfig(grubconfig, &grubConfigType);
3712      if (!gconfig)      if (!gconfig)
3713   grc = 1;   grc = 1;
3714      else      else
# Line 3037  int main(int argc, const char ** argv) { Line 3731  int main(int argc, const char ** argv) {
3731   erc = checkForExtLinux(lconfig);   erc = checkForExtLinux(lconfig);
3732   }   }
3733    
3734   if (lrc == 1 || grc == 1) return 1;   if (lrc == 1 || grc == 1 || gr2c == 1) return 1;
3735    
3736   if (lrc == 2) printf("lilo\n");   if (lrc == 2) printf("lilo\n");
3737     if (gr2c == 2) printf("grub2\n");
3738   if (grc == 2) printf("grub\n");   if (grc == 2) printf("grub\n");
3739   if (erc == 2) printf("extlinux\n");   if (erc == 2) printf("extlinux\n");
3740    
# Line 3067  int main(int argc, const char ** argv) { Line 3762  int main(int argc, const char ** argv) {
3762                 ((rootspec != NULL) ? strlen(rootspec) : 0));                 ((rootspec != NULL) ? strlen(rootspec) : 0));
3763    
3764   return 0;   return 0;
3765    
3766        } else if (displayDefaultTitle) {
3767     struct singleLine * line;
3768     struct singleEntry * entry;
3769    
3770     if (config->defaultImage == -1) return 0;
3771     entry = findEntryByIndex(config, config->defaultImage);
3772     if (!entry) return 0;
3773    
3774     if (!configureGrub2) {
3775      line = getLineByType(LT_TITLE, entry->lines);
3776      if (!line) return 0;
3777      printf("%s\n", line->elements[1].item);
3778    
3779     } else {
3780      char * title;
3781    
3782      dbgPrintf("This is GRUB2, default title is embeded in menuentry\n");
3783      line = getLineByType(LT_MENUENTRY, entry->lines);
3784      if (!line) return 0;
3785      title = grub2ExtractTitle(line);
3786      if (title)
3787        printf("%s\n", title);
3788     }
3789     return 0;
3790    
3791        } else if (displayDefaultIndex) {
3792            if (config->defaultImage == -1) return 0;
3793            printf("%i\n", config->defaultImage);
3794    
3795      } else if (kernelInfo)      } else if (kernelInfo)
3796   return displayInfo(config, kernelInfo, bootPrefix);   return displayInfo(config, kernelInfo, bootPrefix);
3797    
# Line 3082  int main(int argc, const char ** argv) { Line 3807  int main(int argc, const char ** argv) {
3807      setFallbackImage(config, newKernelPath != NULL);      setFallbackImage(config, newKernelPath != NULL);
3808      if (updateImage(config, updateKernelPath, bootPrefix, newKernelArgs,      if (updateImage(config, updateKernelPath, bootPrefix, newKernelArgs,
3809                      removeArgs, newMBKernelArgs, removeMBKernelArgs)) return 1;                      removeArgs, newMBKernelArgs, removeMBKernelArgs)) return 1;
3810        if (updateKernelPath && newKernelInitrd) {
3811                if (updateInitrd(config, updateKernelPath, bootPrefix,
3812                                 newKernelInitrd)) return 1;
3813        }
3814      if (addNewKernel(config, template, bootPrefix, newKernelPath,      if (addNewKernel(config, template, bootPrefix, newKernelPath,
3815                       newKernelTitle, newKernelArgs, newKernelInitrd,                       newKernelTitle, newKernelArgs, newKernelInitrd,
3816                       extraInitrds, extraInitrdCount,                       (const char **)extraInitrds, extraInitrdCount,
3817                       newMBKernel, newMBKernelArgs)) return 1;                       newMBKernel, newMBKernelArgs)) return 1;
3818            
3819    
# Line 3095  int main(int argc, const char ** argv) { Line 3824  int main(int argc, const char ** argv) {
3824      }      }
3825    
3826      if (!outputFile)      if (!outputFile)
3827   outputFile = grubConfig;   outputFile = (char *)grubConfig;
3828    
3829      return writeConfig(config, outputFile, bootPrefix);      return writeConfig(config, outputFile, bootPrefix);
3830  }  }

Legend:
Removed from v.920  
changed lines
  Added in v.1844