Magellan Linux

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

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

revision 1692 by niro, Fri Feb 17 23:14:54 2012 UTC revision 2683 by niro, Wed Jul 16 09:51:14 2014 UTC
# Line 36  Line 36 
36  #include <signal.h>  #include <signal.h>
37  #include <blkid/blkid.h>  #include <blkid/blkid.h>
38    
39    #include "log.h"
40    
41    #ifndef DEBUG
42  #define DEBUG 0  #define DEBUG 0
43    #endif
44    
45  #if DEBUG  #if DEBUG
46  #define dbgPrintf(format, args...) fprintf(stderr, format , ## args)  #define dbgPrintf(format, args...) fprintf(stderr, format , ## args)
# Line 44  Line 48 
48  #define dbgPrintf(format, args...)  #define dbgPrintf(format, args...)
49  #endif  #endif
50    
51    int debug = 0; /* Currently just for template debugging */
52    
53  #define _(A) (A)  #define _(A) (A)
54    
55  #define MAX_EXTRA_INITRDS  16 /* code segment checked by --bootloader-probe */  #define MAX_EXTRA_INITRDS  16 /* code segment checked by --bootloader-probe */
56  #define CODE_SEG_SIZE  128 /* code segment checked by --bootloader-probe */  #define CODE_SEG_SIZE  128 /* code segment checked by --bootloader-probe */
57    
58    #define NOOP_OPCODE 0x90
59    #define JMP_SHORT_OPCODE 0xeb
60    
61    int isEfi = 0;
62    
63    char *saved_command_line = NULL;
64    
65  /* comments get lumped in with indention */  /* comments get lumped in with indention */
66  struct lineElement {  struct lineElement {
67      char * item;      char * item;
# Line 56  struct lineElement { Line 69  struct lineElement {
69  };  };
70    
71  enum lineType_e {  enum lineType_e {
72      LT_WHITESPACE = 1 << 0,      LT_WHITESPACE   = 1 << 0,
73      LT_TITLE      = 1 << 1,      LT_TITLE        = 1 << 1,
74      LT_KERNEL     = 1 << 2,      LT_KERNEL       = 1 << 2,
75      LT_INITRD     = 1 << 3,      LT_INITRD       = 1 << 3,
76      LT_HYPER      = 1 << 4,      LT_HYPER        = 1 << 4,
77      LT_DEFAULT    = 1 << 5,      LT_DEFAULT      = 1 << 5,
78      LT_MBMODULE   = 1 << 6,      LT_MBMODULE     = 1 << 6,
79      LT_ROOT       = 1 << 7,      LT_ROOT         = 1 << 7,
80      LT_FALLBACK   = 1 << 8,      LT_FALLBACK     = 1 << 8,
81      LT_KERNELARGS = 1 << 9,      LT_KERNELARGS   = 1 << 9,
82      LT_BOOT       = 1 << 10,      LT_BOOT         = 1 << 10,
83      LT_BOOTROOT   = 1 << 11,      LT_BOOTROOT     = 1 << 11,
84      LT_LBA        = 1 << 12,      LT_LBA          = 1 << 12,
85      LT_OTHER      = 1 << 13,      LT_OTHER        = 1 << 13,
86      LT_GENERIC    = 1 << 14,      LT_GENERIC      = 1 << 14,
87      LT_UNKNOWN    = 1 << 15,      LT_ECHO    = 1 << 16,
88        LT_MENUENTRY    = 1 << 17,
89        LT_ENTRY_END    = 1 << 18,
90        LT_SET_VARIABLE = 1 << 19,
91        LT_KERNEL_EFI   = 1 << 20,
92        LT_INITRD_EFI   = 1 << 21,
93        LT_KERNEL_16    = 1 << 22,
94        LT_INITRD_16    = 1 << 23,
95        LT_UNKNOWN      = 1 << 24,
96  };  };
97    
98  struct singleLine {  struct singleLine {
# Line 99  struct singleEntry { Line 120  struct singleEntry {
120  #define NEED_TITLE   (1 << 2)  #define NEED_TITLE   (1 << 2)
121  #define NEED_ARGS    (1 << 3)  #define NEED_ARGS    (1 << 3)
122  #define NEED_MB      (1 << 4)  #define NEED_MB      (1 << 4)
123    #define NEED_END     (1 << 5)
124    
125  #define MAIN_DEFAULT    (1 << 0)  #define MAIN_DEFAULT    (1 << 0)
126  #define DEFAULT_SAVED       -2  #define DEFAULT_SAVED       -2
127    #define DEFAULT_SAVED_GRUB2 -3
128    
129  struct keywordTypes {  struct keywordTypes {
130      char * key;      char * key;
# Line 110  struct keywordTypes { Line 133  struct keywordTypes {
133      char separatorChar;      char separatorChar;
134  };  };
135    
136    struct configFileInfo;
137    
138    typedef const char *(*findConfigFunc)(struct configFileInfo *);
139    typedef const int (*writeLineFunc)(struct configFileInfo *,
140     struct singleLine *line);
141    typedef char *(*getEnvFunc)(struct configFileInfo *, char *name);
142    typedef int (*setEnvFunc)(struct configFileInfo *, char *name, char *value);
143    
144  struct configFileInfo {  struct configFileInfo {
145      char * defaultConfig;      char * defaultConfig;
146        findConfigFunc findConfig;
147        writeLineFunc writeLine;
148        getEnvFunc getEnv;
149        setEnvFunc setEnv;
150      struct keywordTypes * keywords;      struct keywordTypes * keywords;
151        int caseInsensitive;
152      int defaultIsIndex;      int defaultIsIndex;
153        int defaultIsVariable;
154      int defaultSupportSaved;      int defaultSupportSaved;
155      enum lineType_e entrySeparator;      int defaultIsSaved;
156        enum lineType_e entryStart;
157        enum lineType_e entryEnd;
158      int needsBootPrefix;      int needsBootPrefix;
159      int argsInQuotes;      int argsInQuotes;
160      int maxTitleLength;      int maxTitleLength;
161      int titleBracketed;      int titleBracketed;
162        int titlePosition;
163      int mbHyperFirst;      int mbHyperFirst;
164      int mbInitRdIsModule;      int mbInitRdIsModule;
165      int mbConcatArgs;      int mbConcatArgs;
166      int mbAllowExtraInitRds;      int mbAllowExtraInitRds;
167        char *envFile;
168  };  };
169    
170  struct keywordTypes grubKeywords[] = {  struct keywordTypes grubKeywords[] = {
# Line 138  struct keywordTypes grubKeywords[] = { Line 179  struct keywordTypes grubKeywords[] = {
179      { NULL,    0, 0 },      { NULL,    0, 0 },
180  };  };
181    
182    const char *grubFindConfig(struct configFileInfo *cfi) {
183        static const char *configFiles[] = {
184     "/boot/grub/grub.conf",
185     "/boot/grub/menu.lst",
186     "/etc/grub.conf",
187     "/boot/grub2/grub.cfg",
188     "/boot/grub2-efi/grub.cfg",
189     NULL
190        };
191        static int i = -1;
192    
193        if (i == -1) {
194     for (i = 0; configFiles[i] != NULL; i++) {
195        dbgPrintf("Checking \"%s\": ", configFiles[i]);
196        if (!access(configFiles[i], R_OK)) {
197     dbgPrintf("found\n");
198     return configFiles[i];
199        }
200        dbgPrintf("not found\n");
201     }
202        }
203        return configFiles[i];
204    }
205    
206  struct configFileInfo grubConfigType = {  struct configFileInfo grubConfigType = {
207      .defaultConfig = "/boot/grub/grub.conf",      .findConfig = grubFindConfig,
208      .keywords = grubKeywords,      .keywords = grubKeywords,
209      .defaultIsIndex = 1,      .defaultIsIndex = 1,
210      .defaultSupportSaved = 1,      .defaultSupportSaved = 1,
211      .entrySeparator = LT_TITLE,      .entryStart = LT_TITLE,
212        .needsBootPrefix = 1,
213        .mbHyperFirst = 1,
214        .mbInitRdIsModule = 1,
215        .mbAllowExtraInitRds = 1,
216    };
217    
218    struct keywordTypes grub2Keywords[] = {
219        { "menuentry",  LT_MENUENTRY,   ' ' },
220        { "}",          LT_ENTRY_END,   ' ' },
221        { "echo",       LT_ECHO,        ' ' },
222        { "set",        LT_SET_VARIABLE,' ', '=' },
223        { "root",       LT_BOOTROOT,    ' ' },
224        { "default",    LT_DEFAULT,     ' ' },
225        { "fallback",   LT_FALLBACK,    ' ' },
226        { "linux",      LT_KERNEL,      ' ' },
227        { "linuxefi",   LT_KERNEL_EFI,  ' ' },
228        { "linux16",    LT_KERNEL_16,   ' ' },
229        { "initrd",     LT_INITRD,      ' ', ' ' },
230        { "initrdefi",  LT_INITRD_EFI,  ' ', ' ' },
231        { "initrd16",   LT_INITRD_16,   ' ', ' ' },
232        { "module",     LT_MBMODULE,    ' ' },
233        { "kernel",     LT_HYPER,       ' ' },
234        { NULL, 0, 0 },
235    };
236    
237    const char *grub2FindConfig(struct configFileInfo *cfi) {
238        static const char *configFiles[] = {
239     "/boot/grub/grub-efi.cfg",
240     "/boot/grub/grub.cfg",
241     NULL
242        };
243        static int i = -1;
244        static const char *grub_cfg = "/boot/grub/grub.cfg";
245        int rc = -1;
246    
247        if (i == -1) {
248     for (i = 0; configFiles[i] != NULL; i++) {
249        dbgPrintf("Checking \"%s\": ", configFiles[i]);
250        if ((rc = access(configFiles[i], R_OK))) {
251     if (errno == EACCES) {
252        printf("Unable to access bootloader configuration file "
253           "\"%s\": %m\n", configFiles[i]);
254        exit(1);
255     }
256     continue;
257        } else {
258     dbgPrintf("found\n");
259     return configFiles[i];
260        }
261     }
262        }
263    
264        /* Ubuntu renames grub2 to grub, so check for the grub.d directory
265         * that isn't in grub1, and if it exists, return the config file path
266         * that they use. */
267        if (configFiles[i] == NULL && !access("/etc/grub.d/", R_OK)) {
268     dbgPrintf("found\n");
269     return grub_cfg;
270        }
271    
272        dbgPrintf("not found\n");
273        return configFiles[i];
274    }
275    
276    /* kind of hacky.  It'll give the first 1024 bytes, ish. */
277    static char *grub2GetEnv(struct configFileInfo *info, char *name)
278    {
279        static char buf[1025];
280        char *s = NULL;
281        char *ret = NULL;
282        char *envFile = info->envFile ? info->envFile : "/boot/grub/grubenv";
283        int rc = asprintf(&s, "grub-editenv %s list | grep '^%s='", envFile, name);
284    
285        if (rc < 0)
286     return NULL;
287    
288        FILE *f = popen(s, "r");
289        if (!f)
290     goto out;
291    
292        memset(buf, '\0', sizeof (buf));
293        ret = fgets(buf, 1024, f);
294        pclose(f);
295    
296        if (ret) {
297     ret += strlen(name) + 1;
298     ret[strlen(ret) - 1] = '\0';
299        }
300        dbgPrintf("grub2GetEnv(%s): %s\n", name, ret);
301    out:
302        free(s);
303        return ret;
304    }
305    
306    static int sPopCount(const char *s, const char *c)
307    {
308        int ret = 0;
309        if (!s)
310     return -1;
311        for (int i = 0; s[i] != '\0'; i++)
312     for (int j = 0; c[j] != '\0'; j++)
313        if (s[i] == c[j])
314     ret++;
315        return ret;
316    }
317    
318    static char *shellEscape(const char *s)
319    {
320        int l = strlen(s) + sPopCount(s, "'") * 2;
321    
322        char *ret = calloc(l+1, sizeof (*ret));
323        if (!ret)
324     return NULL;
325        for (int i = 0, j = 0; s[i] != '\0'; i++, j++) {
326     if (s[i] == '\'')
327        ret[j++] = '\\';
328     ret[j] = s[i];
329        }
330        return ret;
331    }
332    
333    static void unquote(char *s)
334    {
335        int l = strlen(s);
336    
337        if ((s[l-1] == '\'' && s[0] == '\'') || (s[l-1] == '"' && s[0] == '"')) {
338     memmove(s, s+1, l-2);
339     s[l-2] = '\0';
340        }
341    }
342    
343    static int grub2SetEnv(struct configFileInfo *info, char *name, char *value)
344    {
345        char *s = NULL;
346        int rc = 0;
347        char *envFile = info->envFile ? info->envFile : "/boot/grub/grubenv";
348    
349        unquote(value);
350        value = shellEscape(value);
351        if (!value)
352        return -1;
353    
354        rc = asprintf(&s, "grub-editenv %s set '%s=%s'", envFile, name, value);
355        free(value);
356        if (rc <0)
357     return -1;
358    
359        dbgPrintf("grub2SetEnv(%s): %s\n", name, s);
360        rc = system(s);
361        free(s);
362        return rc;
363    }
364    
365    /* this is a gigantic hack to avoid clobbering grub2 variables... */
366    static int is_special_grub2_variable(const char *name)
367    {
368        if (!strcmp(name,"\"${next_entry}\""))
369     return 1;
370        if (!strcmp(name,"\"${prev_saved_entry}\""))
371     return 1;
372        return 0;
373    }
374    
375    int sizeOfSingleLine(struct singleLine * line) {
376      int count = 0;
377    
378      for (int i = 0; i < line->numElements; i++) {
379        int indentSize = 0;
380    
381        count = count + strlen(line->elements[i].item);
382    
383        indentSize = strlen(line->elements[i].indent);
384        if (indentSize > 0)
385          count = count + indentSize;
386        else
387          /* be extra safe and add room for whitespaces */
388          count = count + 1;
389      }
390    
391      /* room for trailing terminator */
392      count = count + 1;
393    
394      return count;
395    }
396    
397    static int isquote(char q)
398    {
399        if (q == '\'' || q == '\"')
400     return 1;
401        return 0;
402    }
403    
404    static int iskernel(enum lineType_e type) {
405        return (type == LT_KERNEL || type == LT_KERNEL_EFI || type == LT_KERNEL_16);
406    }
407    
408    static int isinitrd(enum lineType_e type) {
409        return (type == LT_INITRD || type == LT_INITRD_EFI || type == LT_INITRD_16);
410    }
411    
412    char *grub2ExtractTitle(struct singleLine * line) {
413        char * current;
414        char * current_indent;
415        int current_len;
416        int current_indent_len;
417        int i;
418    
419        /* bail out if line does not start with menuentry */
420        if (strcmp(line->elements[0].item, "menuentry"))
421          return NULL;
422    
423        i = 1;
424        current = line->elements[i].item;
425        current_len = strlen(current);
426    
427        /* if second word is quoted, strip the quotes and return single word */
428        if (isquote(*current) && isquote(current[current_len - 1])) {
429     char *tmp;
430    
431     tmp = strdup(current);
432     *(tmp + current_len - 1) = '\0';
433     return ++tmp;
434        }
435    
436        /* if no quotes, return second word verbatim */
437        if (!isquote(*current))
438     return current;
439    
440        /* second element start with a quote, so we have to find the element
441         * whose last character is also quote (assuming it's the closing one) */
442        int resultMaxSize;
443        char * result;
444        
445        resultMaxSize = sizeOfSingleLine(line);
446        result = malloc(resultMaxSize);
447        snprintf(result, resultMaxSize, "%s", ++current);
448        
449        i++;
450        for (; i < line->numElements; ++i) {
451     current = line->elements[i].item;
452     current_len = strlen(current);
453     current_indent = line->elements[i].indent;
454     current_indent_len = strlen(current_indent);
455    
456     strncat(result, current_indent, current_indent_len);
457     if (!isquote(current[current_len-1])) {
458        strncat(result, current, current_len);
459     } else {
460        strncat(result, current, current_len - 1);
461        break;
462     }
463        }
464        return result;
465    }
466    
467    struct configFileInfo grub2ConfigType = {
468        .findConfig = grub2FindConfig,
469        .getEnv = grub2GetEnv,
470        .setEnv = grub2SetEnv,
471        .keywords = grub2Keywords,
472        .defaultIsIndex = 1,
473        .defaultSupportSaved = 1,
474        .defaultIsVariable = 1,
475        .entryStart = LT_MENUENTRY,
476        .entryEnd = LT_ENTRY_END,
477        .titlePosition = 1,
478      .needsBootPrefix = 1,      .needsBootPrefix = 1,
479      .mbHyperFirst = 1,      .mbHyperFirst = 1,
480      .mbInitRdIsModule = 1,      .mbInitRdIsModule = 1,
# Line 247  int useextlinuxmenu; Line 578  int useextlinuxmenu;
578  struct configFileInfo eliloConfigType = {  struct configFileInfo eliloConfigType = {
579      .defaultConfig = "/boot/efi/EFI/redhat/elilo.conf",      .defaultConfig = "/boot/efi/EFI/redhat/elilo.conf",
580      .keywords = eliloKeywords,      .keywords = eliloKeywords,
581      .entrySeparator = LT_KERNEL,      .entryStart = LT_KERNEL,
582      .needsBootPrefix = 1,      .needsBootPrefix = 1,
583      .argsInQuotes = 1,      .argsInQuotes = 1,
584      .mbConcatArgs = 1,      .mbConcatArgs = 1,
# Line 256  struct configFileInfo eliloConfigType = Line 587  struct configFileInfo eliloConfigType =
587  struct configFileInfo liloConfigType = {  struct configFileInfo liloConfigType = {
588      .defaultConfig = "/etc/lilo.conf",      .defaultConfig = "/etc/lilo.conf",
589      .keywords = liloKeywords,      .keywords = liloKeywords,
590      .entrySeparator = LT_KERNEL,      .entryStart = LT_KERNEL,
591      .argsInQuotes = 1,      .argsInQuotes = 1,
592      .maxTitleLength = 15,      .maxTitleLength = 15,
593  };  };
# Line 264  struct configFileInfo liloConfigType = { Line 595  struct configFileInfo liloConfigType = {
595  struct configFileInfo yabootConfigType = {  struct configFileInfo yabootConfigType = {
596      .defaultConfig = "/etc/yaboot.conf",      .defaultConfig = "/etc/yaboot.conf",
597      .keywords = yabootKeywords,      .keywords = yabootKeywords,
598      .entrySeparator = LT_KERNEL,      .entryStart = LT_KERNEL,
599      .needsBootPrefix = 1,      .needsBootPrefix = 1,
600      .argsInQuotes = 1,      .argsInQuotes = 1,
601      .maxTitleLength = 15,      .maxTitleLength = 15,
# Line 274  struct configFileInfo yabootConfigType = Line 605  struct configFileInfo yabootConfigType =
605  struct configFileInfo siloConfigType = {  struct configFileInfo siloConfigType = {
606      .defaultConfig = "/etc/silo.conf",      .defaultConfig = "/etc/silo.conf",
607      .keywords = siloKeywords,      .keywords = siloKeywords,
608      .entrySeparator = LT_KERNEL,      .entryStart = LT_KERNEL,
609      .needsBootPrefix = 1,      .needsBootPrefix = 1,
610      .argsInQuotes = 1,      .argsInQuotes = 1,
611      .maxTitleLength = 15,      .maxTitleLength = 15,
# Line 283  struct configFileInfo siloConfigType = { Line 614  struct configFileInfo siloConfigType = {
614  struct configFileInfo ziplConfigType = {  struct configFileInfo ziplConfigType = {
615      .defaultConfig = "/etc/zipl.conf",      .defaultConfig = "/etc/zipl.conf",
616      .keywords = ziplKeywords,      .keywords = ziplKeywords,
617      .entrySeparator = LT_TITLE,      .entryStart = LT_TITLE,
618      .argsInQuotes = 1,      .argsInQuotes = 1,
619      .titleBracketed = 1,      .titleBracketed = 1,
620  };  };
# Line 291  struct configFileInfo ziplConfigType = { Line 622  struct configFileInfo ziplConfigType = {
622  struct configFileInfo extlinuxConfigType = {  struct configFileInfo extlinuxConfigType = {
623      .defaultConfig = "/boot/extlinux/extlinux.conf",      .defaultConfig = "/boot/extlinux/extlinux.conf",
624      .keywords = extlinuxKeywords,      .keywords = extlinuxKeywords,
625      .entrySeparator = LT_TITLE,      .caseInsensitive = 1,
626        .entryStart = LT_TITLE,
627      .needsBootPrefix = 1,      .needsBootPrefix = 1,
628      .maxTitleLength = 255,      .maxTitleLength = 255,
629      .mbAllowExtraInitRds = 1,      .mbAllowExtraInitRds = 1,
# Line 315  struct singleEntry * findEntryByIndex(st Line 647  struct singleEntry * findEntryByIndex(st
647  struct singleEntry * findEntryByPath(struct grubConfig * cfg,  struct singleEntry * findEntryByPath(struct grubConfig * cfg,
648       const char * path, const char * prefix,       const char * path, const char * prefix,
649       int * index);       int * index);
650    struct singleEntry * findEntryByTitle(struct grubConfig * cfg, char *title,
651          int * index);
652  static int readFile(int fd, char ** bufPtr);  static int readFile(int fd, char ** bufPtr);
653  static void lineInit(struct singleLine * line);  static void lineInit(struct singleLine * line);
654  struct singleLine * lineDup(struct singleLine * line);  struct singleLine * lineDup(struct singleLine * line);
# Line 324  static int lineWrite(FILE * out, struct Line 658  static int lineWrite(FILE * out, struct
658  static int getNextLine(char ** bufPtr, struct singleLine * line,  static int getNextLine(char ** bufPtr, struct singleLine * line,
659         struct configFileInfo * cfi);         struct configFileInfo * cfi);
660  static char * getRootSpecifier(char * str);  static char * getRootSpecifier(char * str);
661    static void requote(struct singleLine *line, struct configFileInfo * cfi);
662  static void insertElement(struct singleLine * line,  static void insertElement(struct singleLine * line,
663    const char * item, int insertHere,    const char * item, int insertHere,
664    struct configFileInfo * cfi);    struct configFileInfo * cfi);
# Line 378  static char * sdupprintf(const char *for Line 713  static char * sdupprintf(const char *for
713      return buf;      return buf;
714  }  }
715    
716    static enum lineType_e preferredLineType(enum lineType_e type,
717     struct configFileInfo *cfi) {
718        if (isEfi && cfi == &grub2ConfigType) {
719     switch (type) {
720     case LT_KERNEL:
721        return LT_KERNEL_EFI;
722     case LT_INITRD:
723        return LT_INITRD_EFI;
724     default:
725        return type;
726     }
727    #if defined(__i386__) || defined(__x86_64__)
728        } else if (cfi == &grub2ConfigType) {
729     switch (type) {
730     case LT_KERNEL:
731        return LT_KERNEL_16;
732     case LT_INITRD:
733        return LT_INITRD_16;
734     default:
735        return type;
736     }
737    #endif
738        }
739        return type;
740    }
741    
742  static struct keywordTypes * getKeywordByType(enum lineType_e type,  static struct keywordTypes * getKeywordByType(enum lineType_e type,
743        struct configFileInfo * cfi) {        struct configFileInfo * cfi) {
744      struct keywordTypes * kw;      for (struct keywordTypes *kw = cfi->keywords; kw->key; kw++) {
     for (kw = cfi->keywords; kw->key; kw++) {  
745   if (kw->type == type)   if (kw->type == type)
746      return kw;      return kw;
747      }      }
748      return NULL;      return NULL;
749  }  }
750    
751    static char *getKeyByType(enum lineType_e type, struct configFileInfo * cfi) {
752        struct keywordTypes *kt = getKeywordByType(type, cfi);
753        if (kt)
754     return kt->key;
755        return "unknown";
756    }
757    
758  static char * getpathbyspec(char *device) {  static char * getpathbyspec(char *device) {
759      if (!blkid)      if (!blkid)
760          blkid_get_cache(&blkid, NULL);          blkid_get_cache(&blkid, NULL);
# Line 404  static char * getuuidbydev(char *device) Line 771  static char * getuuidbydev(char *device)
771    
772  static enum lineType_e getTypeByKeyword(char * keyword,  static enum lineType_e getTypeByKeyword(char * keyword,
773   struct configFileInfo * cfi) {   struct configFileInfo * cfi) {
774      struct keywordTypes * kw;      for (struct keywordTypes *kw = cfi->keywords; kw->key; kw++) {
775      for (kw = cfi->keywords; kw->key; kw++) {   if (cfi->caseInsensitive) {
776   if (!strcmp(keyword, kw->key))      if (!strcasecmp(keyword, kw->key))
777      return kw->type;                  return kw->type;
778     } else {
779        if (!strcmp(keyword, kw->key))
780            return kw->type;
781     }
782      }      }
783      return LT_UNKNOWN;      return LT_UNKNOWN;
784  }  }
# Line 437  static int isBracketedTitle(struct singl Line 808  static int isBracketedTitle(struct singl
808      return 0;      return 0;
809  }  }
810    
811  static int isEntrySeparator(struct singleLine * line,  static int isEntryStart(struct singleLine * line,
812                              struct configFileInfo * cfi) {                              struct configFileInfo * cfi) {
813      return line->type == cfi->entrySeparator || line->type == LT_OTHER ||      return line->type == cfi->entryStart || line->type == LT_OTHER ||
814   (cfi->titleBracketed && isBracketedTitle(line));   (cfi->titleBracketed && isBracketedTitle(line));
815  }  }
816    
817  /* extract the title from within brackets (for zipl) */  /* extract the title from within brackets (for zipl) */
818  static char * extractTitle(struct singleLine * line) {  static char * extractTitle(struct singleLine * line) {
819      /* bracketed title... let's extract it (leaks a byte) */      /* bracketed title... let's extract it (leaks a byte) */
820      char * title;      char * title = NULL;
821      title = strdup(line->elements[0].item);      if (line->type == LT_TITLE) {
822      title++;   title = strdup(line->elements[0].item);
823      *(title + strlen(title) - 1) = '\0';   title++;
824     *(title + strlen(title) - 1) = '\0';
825        } else if (line->type == LT_MENUENTRY)
826     title = strdup(line->elements[1].item);
827        else
828     return NULL;
829      return title;      return title;
830  }  }
831    
# Line 492  static void lineInit(struct singleLine * Line 868  static void lineInit(struct singleLine *
868  }  }
869    
870  struct singleLine * lineDup(struct singleLine * line) {  struct singleLine * lineDup(struct singleLine * line) {
     int i;  
871      struct singleLine * newLine = malloc(sizeof(*newLine));      struct singleLine * newLine = malloc(sizeof(*newLine));
872    
873      newLine->indent = strdup(line->indent);      newLine->indent = strdup(line->indent);
# Line 502  struct singleLine * lineDup(struct singl Line 877  struct singleLine * lineDup(struct singl
877      newLine->elements = malloc(sizeof(*newLine->elements) *      newLine->elements = malloc(sizeof(*newLine->elements) *
878         newLine->numElements);         newLine->numElements);
879    
880      for (i = 0; i < newLine->numElements; i++) {      for (int i = 0; i < newLine->numElements; i++) {
881   newLine->elements[i].indent = strdup(line->elements[i].indent);   newLine->elements[i].indent = strdup(line->elements[i].indent);
882   newLine->elements[i].item = strdup(line->elements[i].item);   newLine->elements[i].item = strdup(line->elements[i].item);
883      }      }
# Line 511  struct singleLine * lineDup(struct singl Line 886  struct singleLine * lineDup(struct singl
886  }  }
887    
888  static void lineFree(struct singleLine * line) {  static void lineFree(struct singleLine * line) {
     int i;  
   
889      if (line->indent) free(line->indent);      if (line->indent) free(line->indent);
890    
891      for (i = 0; i < line->numElements; i++) {      for (int i = 0; i < line->numElements; i++) {
892   free(line->elements[i].item);   free(line->elements[i].item);
893   free(line->elements[i].indent);   free(line->elements[i].indent);
894      }      }
# Line 526  static void lineFree(struct singleLine * Line 899  static void lineFree(struct singleLine *
899    
900  static int lineWrite(FILE * out, struct singleLine * line,  static int lineWrite(FILE * out, struct singleLine * line,
901       struct configFileInfo * cfi) {       struct configFileInfo * cfi) {
     int i;  
   
902      if (fprintf(out, "%s", line->indent) == -1) return -1;      if (fprintf(out, "%s", line->indent) == -1) return -1;
903    
904      for (i = 0; i < line->numElements; i++) {      for (int i = 0; i < line->numElements; i++) {
905     /* Need to handle this, because we strip the quotes from
906     * menuentry when read it. */
907     if (line->type == LT_MENUENTRY && i == 1) {
908        if(!isquote(*line->elements[i].item))
909     fprintf(out, "\'%s\'", line->elements[i].item);
910        else
911     fprintf(out, "%s", line->elements[i].item);
912        fprintf(out, "%s", line->elements[i].indent);
913    
914        continue;
915     }
916    
917   if (i == 1 && line->type == LT_KERNELARGS && cfi->argsInQuotes)   if (i == 1 && line->type == LT_KERNELARGS && cfi->argsInQuotes)
918      if (fputc('"', out) == EOF) return -1;      if (fputc('"', out) == EOF) return -1;
919    
# Line 624  static int getNextLine(char ** bufPtr, s Line 1007  static int getNextLine(char ** bufPtr, s
1007      if (*line->elements[0].item == '#') {      if (*line->elements[0].item == '#') {
1008   char * fullLine;   char * fullLine;
1009   int len;   int len;
  int i;  
1010    
1011   len = strlen(line->indent);   len = strlen(line->indent);
1012   for (i = 0; i < line->numElements; i++)   for (int i = 0; i < line->numElements; i++)
1013      len += strlen(line->elements[i].item) +      len += strlen(line->elements[i].item) +
1014     strlen(line->elements[i].indent);     strlen(line->elements[i].indent);
1015    
# Line 636  static int getNextLine(char ** bufPtr, s Line 1018  static int getNextLine(char ** bufPtr, s
1018   free(line->indent);   free(line->indent);
1019   line->indent = fullLine;   line->indent = fullLine;
1020    
1021   for (i = 0; i < line->numElements; i++) {   for (int i = 0; i < line->numElements; i++) {
1022      strcat(fullLine, line->elements[i].item);      strcat(fullLine, line->elements[i].item);
1023      strcat(fullLine, line->elements[i].indent);      strcat(fullLine, line->elements[i].indent);
1024      free(line->elements[i].item);      free(line->elements[i].item);
# Line 655  static int getNextLine(char ** bufPtr, s Line 1037  static int getNextLine(char ** bufPtr, s
1037   * elements up more   * elements up more
1038   */   */
1039   if (!isspace(kw->separatorChar)) {   if (!isspace(kw->separatorChar)) {
     int i;  
1040      char indent[2] = "";      char indent[2] = "";
1041      indent[0] = kw->separatorChar;      indent[0] = kw->separatorChar;
1042      for (i = 1; i < line->numElements; i++) {      for (int i = 1; i < line->numElements; i++) {
1043   char *p;   char *p;
  int j;  
1044   int numNewElements;   int numNewElements;
1045    
1046   numNewElements = 0;   numNewElements = 0;
# Line 676  static int getNextLine(char ** bufPtr, s Line 1056  static int getNextLine(char ** bufPtr, s
1056      sizeof(*line->elements) * elementsAlloced);      sizeof(*line->elements) * elementsAlloced);
1057   }   }
1058    
1059   for (j = line->numElements; j > i; j--) {   for (int j = line->numElements; j > i; j--) {
1060   line->elements[j + numNewElements] = line->elements[j];   line->elements[j + numNewElements] = line->elements[j];
1061   }   }
1062   line->numElements += numNewElements;   line->numElements += numNewElements;
# Line 689  static int getNextLine(char ** bufPtr, s Line 1069  static int getNextLine(char ** bufPtr, s
1069   break;   break;
1070   }   }
1071    
1072   free(line->elements[i].indent);   line->elements[i + 1].indent = line->elements[i].indent;
1073   line->elements[i].indent = strdup(indent);   line->elements[i].indent = strdup(indent);
1074   *p++ = '\0';   *p++ = '\0';
1075   i++;   i++;
1076   line->elements[i].item = strdup(p);   line->elements[i].item = strdup(p);
  line->elements[i].indent = strdup("");  
  p = line->elements[i].item;  
1077   }   }
1078      }      }
1079   }   }
# Line 705  static int getNextLine(char ** bufPtr, s Line 1083  static int getNextLine(char ** bufPtr, s
1083      return 0;      return 0;
1084  }  }
1085    
1086    static int isnumber(const char *s)
1087    {
1088        int i;
1089        for (i = 0; s[i] != '\0'; i++)
1090     if (s[i] < '0' || s[i] > '9')
1091        return 0;
1092        return i;
1093    }
1094    
1095  static struct grubConfig * readConfig(const char * inName,  static struct grubConfig * readConfig(const char * inName,
1096        struct configFileInfo * cfi) {        struct configFileInfo * cfi) {
1097      int in;      int in;
# Line 716  static struct grubConfig * readConfig(co Line 1103  static struct grubConfig * readConfig(co
1103      struct singleLine * last = NULL, * line, * defaultLine = NULL;      struct singleLine * last = NULL, * line, * defaultLine = NULL;
1104      char * end;      char * end;
1105      struct singleEntry * entry = NULL;      struct singleEntry * entry = NULL;
1106      int i, len;      int len;
1107      char * buf;      char * buf;
1108    
1109      if (!strcmp(inName, "-")) {      if (inName == NULL) {
1110            printf("Could not find bootloader configuration\n");
1111            exit(1);
1112        } else if (!strcmp(inName, "-")) {
1113   in = 0;   in = 0;
1114      } else {      } else {
1115   if ((in = open(inName, O_RDONLY)) < 0) {   if ((in = open(inName, O_RDONLY)) < 0) {
# Line 762  static struct grubConfig * readConfig(co Line 1152  static struct grubConfig * readConfig(co
1152      cfg->secondaryIndent = strdup(line->indent);      cfg->secondaryIndent = strdup(line->indent);
1153   }   }
1154    
1155   if (isEntrySeparator(line, cfi)) {   if (isEntryStart(line, cfi) || (cfg->entries && !sawEntry)) {
1156      sawEntry = 1;      sawEntry = 1;
1157      if (!entry) {      if (!entry) {
1158   cfg->entries = malloc(sizeof(*entry));   cfg->entries = malloc(sizeof(*entry));
# Line 778  static struct grubConfig * readConfig(co Line 1168  static struct grubConfig * readConfig(co
1168      entry->next = NULL;      entry->next = NULL;
1169   }   }
1170    
1171   if (line->type == LT_DEFAULT && line->numElements == 2) {   if (line->type == LT_SET_VARIABLE) {
1172        dbgPrintf("found 'set' command (%d elements): ", line->numElements);
1173        dbgPrintf("%s", line->indent);
1174        for (int i = 0; i < line->numElements; i++)
1175     dbgPrintf("\"%s\"%s", line->elements[i].item, line->elements[i].indent);
1176        dbgPrintf("\n");
1177        struct keywordTypes *kwType = getKeywordByType(LT_DEFAULT, cfi);
1178        if (kwType && line->numElements == 3 &&
1179        !strcmp(line->elements[1].item, kwType->key) &&
1180        !is_special_grub2_variable(line->elements[2].item)) {
1181     dbgPrintf("Line sets default config\n");
1182     cfg->flags &= ~GRUB_CONFIG_NO_DEFAULT;
1183     defaultLine = line;
1184        }
1185     } else if (line->type == LT_DEFAULT && line->numElements == 2) {
1186      cfg->flags &= ~GRUB_CONFIG_NO_DEFAULT;      cfg->flags &= ~GRUB_CONFIG_NO_DEFAULT;
1187      defaultLine = line;      defaultLine = line;
1188    
1189          } else if (line->type == LT_KERNEL) {          } else if (iskernel(line->type)) {
1190      /* if by some freak chance this is multiboot and the "module"      /* if by some freak chance this is multiboot and the "module"
1191       * lines came earlier in the template, make sure to use LT_HYPER       * lines came earlier in the template, make sure to use LT_HYPER
1192       * instead of LT_KERNEL now       * instead of LT_KERNEL now
# Line 796  static struct grubConfig * readConfig(co Line 1200  static struct grubConfig * readConfig(co
1200       * This only applies to grub, but that's the only place we       * This only applies to grub, but that's the only place we
1201       * should find LT_MBMODULE lines anyway.       * should find LT_MBMODULE lines anyway.
1202       */       */
1203      struct singleLine * l;      for (struct singleLine *l = entry->lines; l; l = l->next) {
     for (l = entry->lines; l; l = l->next) {  
1204   if (l->type == LT_HYPER)   if (l->type == LT_HYPER)
1205      break;      break;
1206   else if (l->type == LT_KERNEL) {   else if (iskernel(l->type)) {
1207      l->type = LT_HYPER;      l->type = LT_HYPER;
1208      break;      break;
1209   }   }
# Line 817  static struct grubConfig * readConfig(co Line 1220  static struct grubConfig * readConfig(co
1220   } else if (line->type == LT_TITLE && line->numElements > 1) {   } else if (line->type == LT_TITLE && line->numElements > 1) {
1221      /* make the title a single argument (undoing our parsing) */      /* make the title a single argument (undoing our parsing) */
1222      len = 0;      len = 0;
1223      for (i = 1; i < line->numElements; i++) {      for (int i = 1; i < line->numElements; i++) {
1224   len += strlen(line->elements[i].item);   len += strlen(line->elements[i].item);
1225   len += strlen(line->elements[i].indent);   len += strlen(line->elements[i].indent);
1226      }      }
1227      buf = malloc(len + 1);      buf = malloc(len + 1);
1228      *buf = '\0';      *buf = '\0';
1229    
1230      for (i = 1; i < line->numElements; i++) {      for (int i = 1; i < line->numElements; i++) {
1231   strcat(buf, line->elements[i].item);   strcat(buf, line->elements[i].item);
1232   free(line->elements[i].item);   free(line->elements[i].item);
1233    
# Line 838  static struct grubConfig * readConfig(co Line 1241  static struct grubConfig * readConfig(co
1241      line->elements[line->numElements - 1].indent;      line->elements[line->numElements - 1].indent;
1242      line->elements[1].item = buf;      line->elements[1].item = buf;
1243      line->numElements = 2;      line->numElements = 2;
1244     } else if (line->type == LT_MENUENTRY && line->numElements > 3) {
1245        /* let --remove-kernel="TITLE=what" work */
1246        len = 0;
1247        char *extras;
1248        char *title;
1249    
1250        for (int i = 1; i < line->numElements; i++) {
1251     len += strlen(line->elements[i].item);
1252     len += strlen(line->elements[i].indent);
1253        }
1254        buf = malloc(len + 1);
1255        *buf = '\0';
1256    
1257        /* allocate mem for extra flags. */
1258        extras = malloc(len + 1);
1259        *extras = '\0';
1260    
1261        /* get title. */
1262        for (int i = 0; i < line->numElements; i++) {
1263     if (!strcmp(line->elements[i].item, "menuentry"))
1264        continue;
1265     if (isquote(*line->elements[i].item))
1266        title = line->elements[i].item + 1;
1267     else
1268        title = line->elements[i].item;
1269    
1270     len = strlen(title);
1271            if (isquote(title[len-1])) {
1272        strncat(buf, title,len-1);
1273        break;
1274     } else {
1275        strcat(buf, title);
1276        strcat(buf, line->elements[i].indent);
1277     }
1278        }
1279    
1280        /* get extras */
1281        int count = 0;
1282        for (int i = 0; i < line->numElements; i++) {
1283     if (count >= 2) {
1284        strcat(extras, line->elements[i].item);
1285        strcat(extras, line->elements[i].indent);
1286     }
1287    
1288     if (!strcmp(line->elements[i].item, "menuentry"))
1289        continue;
1290    
1291     /* count ' or ", there should be two in menuentry line. */
1292     if (isquote(*line->elements[i].item))
1293        count++;
1294    
1295     len = strlen(line->elements[i].item);
1296    
1297     if (isquote(line->elements[i].item[len -1]))
1298        count++;
1299    
1300     /* ok, we get the final ' or ", others are extras. */
1301                }
1302        line->elements[1].indent =
1303     line->elements[line->numElements - 2].indent;
1304        line->elements[1].item = buf;
1305        line->elements[2].indent =
1306     line->elements[line->numElements - 2].indent;
1307        line->elements[2].item = extras;
1308        line->numElements = 3;
1309   } else if (line->type == LT_KERNELARGS && cfi->argsInQuotes) {   } else if (line->type == LT_KERNELARGS && cfi->argsInQuotes) {
1310      /* Strip off any " which may be present; they'll be put back      /* Strip off any " which may be present; they'll be put back
1311         on write. This is one of the few (the only?) places that grubby         on write. This is one of the few (the only?) places that grubby
# Line 847  static struct grubConfig * readConfig(co Line 1314  static struct grubConfig * readConfig(co
1314      if (line->numElements >= 2) {      if (line->numElements >= 2) {
1315   int last, len;   int last, len;
1316    
1317   if (*line->elements[1].item == '"')   if (isquote(*line->elements[1].item))
1318      memmove(line->elements[1].item, line->elements[1].item + 1,      memmove(line->elements[1].item, line->elements[1].item + 1,
1319      strlen(line->elements[1].item + 1) + 1);      strlen(line->elements[1].item + 1) + 1);
1320    
1321   last = line->numElements - 1;   last = line->numElements - 1;
1322   len = strlen(line->elements[last].item) - 1;   len = strlen(line->elements[last].item) - 1;
1323   if (line->elements[last].item[len] == '"')   if (isquote(line->elements[last].item[len]))
1324      line->elements[last].item[len] = '\0';      line->elements[last].item[len] = '\0';
1325      }      }
1326   }   }
# Line 891  static struct grubConfig * readConfig(co Line 1358  static struct grubConfig * readConfig(co
1358   entry->lines = line;   entry->lines = line;
1359      else      else
1360   last->next = line;   last->next = line;
1361      dbgPrintf("readConfig added %d to %p\n", line->type, entry);      dbgPrintf("readConfig added %s to %p\n", getKeyByType(line->type, cfi), entry);
1362    
1363        /* we could have seen this outside of an entry... if so, we
1364         * ignore it like any other line we don't grok */
1365        if (line->type == LT_ENTRY_END && sawEntry)
1366     sawEntry = 0;
1367   } else {   } else {
1368      if (!cfg->theLines)      if (!cfg->theLines)
1369   cfg->theLines = line;   cfg->theLines = line;
1370      else      else
1371   last->next = line;   last->next = line;
1372      dbgPrintf("readConfig added %d to cfg\n", line->type);      dbgPrintf("readConfig added %s to cfg\n", getKeyByType(line->type, cfi));
1373   }   }
1374    
1375   last = line;   last = line;
# Line 905  static struct grubConfig * readConfig(co Line 1377  static struct grubConfig * readConfig(co
1377    
1378      free(incoming);      free(incoming);
1379    
1380        dbgPrintf("defaultLine is %s\n", defaultLine ? "set" : "unset");
1381      if (defaultLine) {      if (defaultLine) {
1382   if (cfi->defaultSupportSaved &&          if (defaultLine->numElements > 2 &&
1383        cfi->defaultSupportSaved &&
1384        !strncmp(defaultLine->elements[2].item,"\"${saved_entry}\"", 16)) {
1385     cfg->cfi->defaultIsSaved = 1;
1386     cfg->defaultImage = DEFAULT_SAVED_GRUB2;
1387     if (cfg->cfi->getEnv) {
1388        char *defTitle = cfi->getEnv(cfg->cfi, "saved_entry");
1389        if (defTitle) {
1390     int index = 0;
1391     if (isnumber(defTitle)) {
1392        index = atoi(defTitle);
1393        entry = findEntryByIndex(cfg, index);
1394     } else {
1395        entry = findEntryByTitle(cfg, defTitle, &index);
1396     }
1397     if (entry)
1398        cfg->defaultImage = index;
1399        }
1400     }
1401     } else if (cfi->defaultIsVariable) {
1402        char *value = defaultLine->elements[2].item;
1403        while (*value && (*value == '"' || *value == '\'' ||
1404        *value == ' ' || *value == '\t'))
1405     value++;
1406        cfg->defaultImage = strtol(value, &end, 10);
1407        while (*end && (*end == '"' || *end == '\'' ||
1408        *end == ' ' || *end == '\t'))
1409     end++;
1410        if (*end) cfg->defaultImage = -1;
1411     } else if (cfi->defaultSupportSaved &&
1412   !strncmp(defaultLine->elements[1].item, "saved", 5)) {   !strncmp(defaultLine->elements[1].item, "saved", 5)) {
1413      cfg->defaultImage = DEFAULT_SAVED;      cfg->defaultImage = DEFAULT_SAVED;
1414   } else if (cfi->defaultIsIndex) {   } else if (cfi->defaultIsIndex) {
1415      cfg->defaultImage = strtol(defaultLine->elements[1].item, &end, 10);      cfg->defaultImage = strtol(defaultLine->elements[1].item, &end, 10);
1416      if (*end) cfg->defaultImage = -1;      if (*end) cfg->defaultImage = -1;
1417   } else if (defaultLine->numElements >= 2) {   } else if (defaultLine->numElements >= 2) {
1418      i = 0;      int i = 0;
1419      while ((entry = findEntryByIndex(cfg, i))) {      while ((entry = findEntryByIndex(cfg, i))) {
1420   for (line = entry->lines; line; line = line->next)   for (line = entry->lines; line; line = line->next)
1421      if (line->type == LT_TITLE) break;      if (line->type == LT_TITLE) break;
# Line 936  static struct grubConfig * readConfig(co Line 1438  static struct grubConfig * readConfig(co
1438          cfg->defaultImage = -1;          cfg->defaultImage = -1;
1439      }      }
1440   }   }
1441        } else if (cfg->cfi->defaultIsSaved && cfg->cfi->getEnv) {
1442     char *defTitle = cfi->getEnv(cfg->cfi, "saved_entry");
1443     if (defTitle) {
1444        int index = 0;
1445        if (isnumber(defTitle)) {
1446     index = atoi(defTitle);
1447     entry = findEntryByIndex(cfg, index);
1448        } else {
1449     entry = findEntryByTitle(cfg, defTitle, &index);
1450        }
1451        if (entry)
1452     cfg->defaultImage = index;
1453     }
1454      } else {      } else {
1455          cfg->defaultImage = 0;          cfg->defaultImage = 0;
1456      }      }
# Line 953  static void writeDefault(FILE * out, cha Line 1468  static void writeDefault(FILE * out, cha
1468    
1469      if (cfg->defaultImage == DEFAULT_SAVED)      if (cfg->defaultImage == DEFAULT_SAVED)
1470   fprintf(out, "%sdefault%ssaved\n", indent, separator);   fprintf(out, "%sdefault%ssaved\n", indent, separator);
1471      else if (cfg->defaultImage > -1) {      else if (cfg->cfi->defaultIsSaved) {
1472     fprintf(out, "%sset default=\"${saved_entry}\"\n", indent);
1473     if (cfg->defaultImage >= 0 && cfg->cfi->setEnv) {
1474        char *title;
1475        entry = findEntryByIndex(cfg, cfg->defaultImage);
1476        line = getLineByType(LT_MENUENTRY, entry->lines);
1477        if (!line)
1478     line = getLineByType(LT_TITLE, entry->lines);
1479        if (line) {
1480     title = extractTitle(line);
1481     if (title)
1482        cfg->cfi->setEnv(cfg->cfi, "saved_entry", title);
1483        }
1484     }
1485        } else if (cfg->defaultImage > -1) {
1486   if (cfg->cfi->defaultIsIndex) {   if (cfg->cfi->defaultIsIndex) {
1487      fprintf(out, "%sdefault%s%d\n", indent, separator,      if (cfg->cfi->defaultIsVariable) {
1488      cfg->defaultImage);          fprintf(out, "%sset default=\"%d\"\n", indent,
1489     cfg->defaultImage);
1490        } else {
1491     fprintf(out, "%sdefault%s%d\n", indent, separator,
1492     cfg->defaultImage);
1493        }
1494   } else {   } else {
1495      int image = cfg->defaultImage;      int image = cfg->defaultImage;
1496    
# Line 1008  static int writeConfig(struct grubConfig Line 1542  static int writeConfig(struct grubConfig
1542    
1543      /* most likely the symlink is relative, so change our      /* most likely the symlink is relative, so change our
1544         directory to the dir of the symlink */         directory to the dir of the symlink */
1545              rc = chdir(dirname(strdupa(outName)));      char *dir = strdupa(outName);
1546        rc = chdir(dirname(dir));
1547      do {      do {
1548   buf = alloca(len + 1);   buf = alloca(len + 1);
1549   rc = readlink(basename(outName), buf, len);   rc = readlink(basename(outName), buf, len);
# Line 1046  static int writeConfig(struct grubConfig Line 1581  static int writeConfig(struct grubConfig
1581      }      }
1582    
1583      line = cfg->theLines;      line = cfg->theLines;
1584        struct keywordTypes *defaultKw = getKeywordByType(LT_DEFAULT, cfg->cfi);
1585      while (line) {      while (line) {
1586   if (line->type == LT_DEFAULT) {          if (line->type == LT_SET_VARIABLE && defaultKw &&
1587     line->numElements == 3 &&
1588     !strcmp(line->elements[1].item, defaultKw->key) &&
1589     !is_special_grub2_variable(line->elements[2].item)) {
1590        writeDefault(out, line->indent, line->elements[0].indent, cfg);
1591        needs &= ~MAIN_DEFAULT;
1592     } else if (line->type == LT_DEFAULT) {
1593      writeDefault(out, line->indent, line->elements[0].indent, cfg);      writeDefault(out, line->indent, line->elements[0].indent, cfg);
1594      needs &= ~MAIN_DEFAULT;      needs &= ~MAIN_DEFAULT;
1595   } else if (line->type == LT_FALLBACK) {   } else if (line->type == LT_FALLBACK) {
# Line 1140  static char *findDiskForRoot() Line 1682  static char *findDiskForRoot()
1682      buf[rc] = '\0';      buf[rc] = '\0';
1683      chptr = buf;      chptr = buf;
1684    
1685        char *foundanswer = NULL;
1686    
1687      while (chptr && chptr != buf+rc) {      while (chptr && chptr != buf+rc) {
1688          devname = chptr;          devname = chptr;
1689    
# Line 1167  static char *findDiskForRoot() Line 1711  static char *findDiskForRoot()
1711           * for '/' obviously.           * for '/' obviously.
1712           */           */
1713          if (*(++chptr) == '/' && *(++chptr) == ' ') {          if (*(++chptr) == '/' && *(++chptr) == ' ') {
1714              /*              /* remember the last / entry in mtab */
1715               * Move back 2, which is the first space after the device name, set             foundanswer = devname;
              * it to \0 so strdup will just get the devicename.  
              */  
             chptr -= 2;  
             *chptr = '\0';  
             return strdup(devname);  
1716          }          }
1717    
1718          /* Next line */          /* Next line */
# Line 1182  static char *findDiskForRoot() Line 1721  static char *findDiskForRoot()
1721              chptr++;              chptr++;
1722      }      }
1723    
1724        /* Return the last / entry found */
1725        if (foundanswer) {
1726            chptr = strchr(foundanswer, ' ');
1727            *chptr = '\0';
1728            return strdup(foundanswer);
1729        }
1730    
1731      return NULL;      return NULL;
1732  }  }
1733    
1734    void printEntry(struct singleEntry * entry, FILE *f) {
1735        int i;
1736        struct singleLine * line;
1737    
1738        for (line = entry->lines; line; line = line->next) {
1739     log_message(f, "DBG: %s", line->indent);
1740     for (i = 0; i < line->numElements; i++) {
1741        /* Need to handle this, because we strip the quotes from
1742         * menuentry when read it. */
1743        if (line->type == LT_MENUENTRY && i == 1) {
1744     if(!isquote(*line->elements[i].item))
1745        log_message(f, "\'%s\'", line->elements[i].item);
1746     else
1747        log_message(f, "%s", line->elements[i].item);
1748     log_message(f, "%s", line->elements[i].indent);
1749    
1750     continue;
1751        }
1752        
1753        log_message(f, "%s%s",
1754        line->elements[i].item, line->elements[i].indent);
1755     }
1756     log_message(f, "\n");
1757        }
1758    }
1759    
1760    void notSuitablePrintf(struct singleEntry * entry, int okay, const char *fmt, ...)
1761    {
1762        static int once;
1763        va_list argp, argq;
1764    
1765        va_start(argp, fmt);
1766    
1767        va_copy(argq, argp);
1768        if (!once) {
1769     log_time(NULL);
1770     log_message(NULL, "command line: %s\n", saved_command_line);
1771        }
1772        log_message(NULL, "DBG: Image entry %s: ", okay ? "succeeded" : "failed");
1773        log_vmessage(NULL, fmt, argq);
1774    
1775        printEntry(entry, NULL);
1776        va_end(argq);
1777    
1778        if (!debug) {
1779     once = 1;
1780         va_end(argp);
1781     return;
1782        }
1783    
1784        if (okay) {
1785     va_end(argp);
1786     return;
1787        }
1788    
1789        if (!once)
1790     log_message(stderr, "DBG: command line: %s\n", saved_command_line);
1791        once = 1;
1792        fprintf(stderr, "DBG: Image entry failed: ");
1793        vfprintf(stderr, fmt, argp);
1794        printEntry(entry, stderr);
1795        va_end(argp);
1796    }
1797    
1798    #define beginswith(s, c) ((s) && (s)[0] == (c))
1799    
1800    static int endswith(const char *s, char c)
1801    {
1802     int slen;
1803    
1804     if (!s || !s[0])
1805     return 0;
1806     slen = strlen(s) - 1;
1807    
1808     return s[slen] == c;
1809    }
1810    
1811  int suitableImage(struct singleEntry * entry, const char * bootPrefix,  int suitableImage(struct singleEntry * entry, const char * bootPrefix,
1812    int skipRemoved, int flags) {    int skipRemoved, int flags) {
1813      struct singleLine * line;      struct singleLine * line;
# Line 1194  int suitableImage(struct singleEntry * e Line 1817  int suitableImage(struct singleEntry * e
1817      char * rootspec;      char * rootspec;
1818      char * rootdev;      char * rootdev;
1819    
1820      if (skipRemoved && entry->skip) return 0;      if (skipRemoved && entry->skip) {
1821     notSuitablePrintf(entry, 0, "marked to skip\n");
1822     return 0;
1823        }
1824    
1825      line = getLineByType(LT_KERNEL|LT_HYPER, entry->lines);      line = getLineByType(LT_KERNEL|LT_HYPER|LT_KERNEL_EFI|LT_KERNEL_16, entry->lines);
1826      if (!line || line->numElements < 2) return 0;      if (!line) {
1827     notSuitablePrintf(entry, 0, "no line found\n");
1828     return 0;
1829        }
1830        if (line->numElements < 2) {
1831     notSuitablePrintf(entry, 0, "line has only %d elements\n",
1832        line->numElements);
1833     return 0;
1834        }
1835    
1836      if (flags & GRUBBY_BADIMAGE_OKAY) return 1;      if (flags & GRUBBY_BADIMAGE_OKAY) {
1837        notSuitablePrintf(entry, 1, "\n");
1838        return 1;
1839        }
1840    
1841      fullName = alloca(strlen(bootPrefix) +      fullName = alloca(strlen(bootPrefix) +
1842        strlen(line->elements[1].item) + 1);        strlen(line->elements[1].item) + 1);
1843      rootspec = getRootSpecifier(line->elements[1].item);      rootspec = getRootSpecifier(line->elements[1].item);
1844      sprintf(fullName, "%s%s", bootPrefix,      int rootspec_offset = rootspec ? strlen(rootspec) : 0;
1845              line->elements[1].item + (rootspec ? strlen(rootspec) : 0));      int hasslash = endswith(bootPrefix, '/') ||
1846      if (access(fullName, R_OK)) return 0;       beginswith(line->elements[1].item + rootspec_offset, '/');
1847        sprintf(fullName, "%s%s%s", bootPrefix, hasslash ? "" : "/",
1848                line->elements[1].item + rootspec_offset);
1849        if (access(fullName, R_OK)) {
1850     notSuitablePrintf(entry, 0, "access to %s failed\n", fullName);
1851     return 0;
1852        }
1853      for (i = 2; i < line->numElements; i++)      for (i = 2; i < line->numElements; i++)
1854   if (!strncasecmp(line->elements[i].item, "root=", 5)) break;   if (!strncasecmp(line->elements[i].item, "root=", 5)) break;
1855      if (i < line->numElements) {      if (i < line->numElements) {
# Line 1225  int suitableImage(struct singleEntry * e Line 1867  int suitableImage(struct singleEntry * e
1867      line = getLineByType(LT_KERNELARGS|LT_MBMODULE, entry->lines);      line = getLineByType(LT_KERNELARGS|LT_MBMODULE, entry->lines);
1868    
1869              /* failed to find one */              /* failed to find one */
1870              if (!line) return 0;              if (!line) {
1871     notSuitablePrintf(entry, 0, "no line found\n");
1872     return 0;
1873                }
1874    
1875      for (i = 1; i < line->numElements; i++)      for (i = 1; i < line->numElements; i++)
1876          if (!strncasecmp(line->elements[i].item, "root=", 5)) break;          if (!strncasecmp(line->elements[i].item, "root=", 5)) break;
1877      if (i < line->numElements)      if (i < line->numElements)
1878          dev = line->elements[i].item + 5;          dev = line->elements[i].item + 5;
1879      else {      else {
1880     notSuitablePrintf(entry, 0, "no root= entry found\n");
1881   /* it failed too...  can't find root= */   /* it failed too...  can't find root= */
1882          return 0;          return 0;
1883              }              }
# Line 1239  int suitableImage(struct singleEntry * e Line 1885  int suitableImage(struct singleEntry * e
1885      }      }
1886    
1887      dev = getpathbyspec(dev);      dev = getpathbyspec(dev);
1888      if (!dev)      if (!getpathbyspec(dev)) {
1889            notSuitablePrintf(entry, 0, "can't find blkid entry for %s\n", dev);
1890          return 0;          return 0;
1891        } else
1892     dev = getpathbyspec(dev);
1893    
1894      rootdev = findDiskForRoot();      rootdev = findDiskForRoot();
1895      if (!rootdev)      if (!rootdev) {
1896            notSuitablePrintf(entry, 0, "can't find root device\n");
1897   return 0;   return 0;
1898        }
1899    
1900      if (!getuuidbydev(rootdev) || !getuuidbydev(dev)) {      if (!getuuidbydev(rootdev) || !getuuidbydev(dev)) {
1901            notSuitablePrintf(entry, 0, "uuid missing: rootdev %s, dev %s\n",
1902     getuuidbydev(rootdev), getuuidbydev(dev));
1903          free(rootdev);          free(rootdev);
1904          return 0;          return 0;
1905      }      }
1906    
1907      if (strcmp(getuuidbydev(rootdev), getuuidbydev(dev))) {      if (strcmp(getuuidbydev(rootdev), getuuidbydev(dev))) {
1908            notSuitablePrintf(entry, 0, "uuid mismatch: rootdev %s, dev %s\n",
1909     getuuidbydev(rootdev), getuuidbydev(dev));
1910   free(rootdev);   free(rootdev);
1911          return 0;          return 0;
1912      }      }
1913    
1914      free(rootdev);      free(rootdev);
1915        notSuitablePrintf(entry, 1, "\n");
1916    
1917      return 1;      return 1;
1918  }  }
# Line 1300  struct singleEntry * findEntryByPath(str Line 1956  struct singleEntry * findEntryByPath(str
1956   entry = findEntryByIndex(config, indexVars[i]);   entry = findEntryByIndex(config, indexVars[i]);
1957   if (!entry) return NULL;   if (!entry) return NULL;
1958    
1959   line = getLineByType(LT_KERNEL|LT_HYPER, entry->lines);   line = getLineByType(LT_KERNEL|LT_HYPER|LT_KERNEL_EFI|LT_KERNEL_16, entry->lines);
1960   if (!line) return NULL;   if (!line) return NULL;
1961    
1962   if (index) *index = indexVars[i];   if (index) *index = indexVars[i];
# Line 1338  struct singleEntry * findEntryByPath(str Line 1994  struct singleEntry * findEntryByPath(str
1994    
1995   if (!strncmp(kernel, "TITLE=", 6)) {   if (!strncmp(kernel, "TITLE=", 6)) {
1996      prefix = "";      prefix = "";
1997      checkType = LT_TITLE;      checkType = LT_TITLE|LT_MENUENTRY;
1998      kernel += 6;      kernel += 6;
1999   }   }
2000    
# Line 1349  struct singleEntry * findEntryByPath(str Line 2005  struct singleEntry * findEntryByPath(str
2005    
2006      /* check all the lines matching checkType */      /* check all the lines matching checkType */
2007      for (line = entry->lines; line; line = line->next) {      for (line = entry->lines; line; line = line->next) {
2008   line = getLineByType(entry->multiboot && checkType == LT_KERNEL ?   enum lineType_e ct = checkType;
2009       LT_KERNEL|LT_MBMODULE|LT_HYPER :   if (entry->multiboot && checkType == LT_KERNEL)
2010       checkType, line);      ct = LT_KERNEL|LT_KERNEL_EFI|LT_MBMODULE|LT_HYPER|LT_KERNEL_16;
2011   if (!line) break;  /* not found in this entry */   else if (checkType & LT_KERNEL)
2012        ct = checkType | LT_KERNEL_EFI | LT_KERNEL_16;
2013     line = getLineByType(ct, line);
2014     if (!line)
2015        break;  /* not found in this entry */
2016    
2017   if (line && line->numElements >= 2) {   if (line && line->type != LT_MENUENTRY &&
2018     line->numElements >= 2) {
2019      rootspec = getRootSpecifier(line->elements[1].item);      rootspec = getRootSpecifier(line->elements[1].item);
2020      if (!strcmp(line->elements[1].item +      if (!strcmp(line->elements[1].item +
2021   ((rootspec != NULL) ? strlen(rootspec) : 0),   ((rootspec != NULL) ? strlen(rootspec) : 0),
2022   kernel + strlen(prefix)))   kernel + strlen(prefix)))
2023   break;   break;
2024   }   }
2025     if(line->type == LT_MENUENTRY &&
2026     !strcmp(line->elements[1].item, kernel))
2027        break;
2028      }      }
2029    
2030      /* make sure this entry has a kernel identifier; this skips      /* make sure this entry has a kernel identifier; this skips
2031       * non-Linux boot entries (could find netbsd etc, though, which is       * non-Linux boot entries (could find netbsd etc, though, which is
2032       * unfortunate)       * unfortunate)
2033       */       */
2034      if (line && getLineByType(LT_KERNEL|LT_HYPER, entry->lines))      if (line && getLineByType(LT_KERNEL|LT_HYPER|LT_KERNEL_EFI|LT_KERNEL_16, entry->lines))
2035   break; /* found 'im! */   break; /* found 'im! */
2036   }   }
2037    
# Line 1377  struct singleEntry * findEntryByPath(str Line 2041  struct singleEntry * findEntryByPath(str
2041      return entry;      return entry;
2042  }  }
2043    
2044    struct singleEntry * findEntryByTitle(struct grubConfig * cfg, char *title,
2045          int * index) {
2046        struct singleEntry * entry;
2047        struct singleLine * line;
2048        int i;
2049        char * newtitle;
2050    
2051        for (i = 0, entry = cfg->entries; entry; entry = entry->next, i++) {
2052     if (index && i < *index)
2053        continue;
2054     line = getLineByType(LT_TITLE, entry->lines);
2055     if (!line)
2056        line = getLineByType(LT_MENUENTRY, entry->lines);
2057     if (!line)
2058        continue;
2059     newtitle = grub2ExtractTitle(line);
2060     if (!newtitle)
2061        continue;
2062     if (!strcmp(title, newtitle))
2063        break;
2064        }
2065    
2066        if (!entry)
2067     return NULL;
2068    
2069        if (index)
2070     *index = i;
2071        return entry;
2072    }
2073    
2074  struct singleEntry * findEntryByIndex(struct grubConfig * cfg, int index) {  struct singleEntry * findEntryByIndex(struct grubConfig * cfg, int index) {
2075      struct singleEntry * entry;      struct singleEntry * entry;
2076    
# Line 1399  struct singleEntry * findTemplate(struct Line 2093  struct singleEntry * findTemplate(struct
2093      struct singleEntry * entry, * entry2;      struct singleEntry * entry, * entry2;
2094      int index;      int index;
2095    
2096      if (cfg->defaultImage > -1) {      if (cfg->cfi->defaultIsSaved) {
2097     if (cfg->cfi->getEnv) {
2098        char *defTitle = cfg->cfi->getEnv(cfg->cfi, "saved_entry");
2099        if (defTitle) {
2100     int index = 0;
2101     if (isnumber(defTitle)) {
2102        index = atoi(defTitle);
2103        entry = findEntryByIndex(cfg, index);
2104     } else {
2105        entry = findEntryByTitle(cfg, defTitle, &index);
2106     }
2107     if (entry)
2108        cfg->defaultImage = index;
2109        }
2110     }
2111        } else if (cfg->defaultImage > -1) {
2112   entry = findEntryByIndex(cfg, cfg->defaultImage);   entry = findEntryByIndex(cfg, cfg->defaultImage);
2113   if (entry && suitableImage(entry, prefix, skipRemoved, flags)) {   if (entry && suitableImage(entry, prefix, skipRemoved, flags)) {
2114      if (indexPtr) *indexPtr = cfg->defaultImage;      if (indexPtr) *indexPtr = cfg->defaultImage;
# Line 1452  void markRemovedImage(struct grubConfig Line 2161  void markRemovedImage(struct grubConfig
2161        const char * prefix) {        const char * prefix) {
2162      struct singleEntry * entry;      struct singleEntry * entry;
2163    
2164      if (!image) return;      if (!image)
2165     return;
2166    
2167        /* check and see if we're removing the default image */
2168        if (isdigit(*image)) {
2169     entry = findEntryByPath(cfg, image, prefix, NULL);
2170     if(entry)
2171        entry->skip = 1;
2172     return;
2173        }
2174    
2175      while ((entry = findEntryByPath(cfg, image, prefix, NULL)))      while ((entry = findEntryByPath(cfg, image, prefix, NULL)))
2176   entry->skip = 1;   entry->skip = 1;
# Line 1460  void markRemovedImage(struct grubConfig Line 2178  void markRemovedImage(struct grubConfig
2178    
2179  void setDefaultImage(struct grubConfig * config, int hasNew,  void setDefaultImage(struct grubConfig * config, int hasNew,
2180       const char * defaultKernelPath, int newIsDefault,       const char * defaultKernelPath, int newIsDefault,
2181       const char * prefix, int flags) {       const char * prefix, int flags, int index) {
2182      struct singleEntry * entry, * entry2, * newDefault;      struct singleEntry * entry, * entry2, * newDefault;
2183      int i, j;      int i, j;
2184    
2185      if (newIsDefault) {      if (newIsDefault) {
2186   config->defaultImage = 0;   config->defaultImage = 0;
2187   return;   return;
2188        } else if ((index >= 0) && config->cfi->defaultIsIndex) {
2189     if (findEntryByIndex(config, index))
2190        config->defaultImage = index;
2191     else
2192        config->defaultImage = -1;
2193     return;
2194      } else if (defaultKernelPath) {      } else if (defaultKernelPath) {
2195   i = 0;   i = 0;
2196   if (findEntryByPath(config, defaultKernelPath, prefix, &i)) {   if (findEntryByPath(config, defaultKernelPath, prefix, &i)) {
# Line 1479  void setDefaultImage(struct grubConfig * Line 2203  void setDefaultImage(struct grubConfig *
2203    
2204      /* 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
2205         changes */         changes */
2206      if (config->defaultImage == DEFAULT_SAVED)      if ((config->defaultImage == DEFAULT_SAVED) ||
2207     (config->defaultImage == DEFAULT_SAVED_GRUB2))
2208        /* default is set to saved, we don't want to change it */        /* default is set to saved, we don't want to change it */
2209        return;        return;
2210    
# Line 1540  void displayEntry(struct singleEntry * e Line 2265  void displayEntry(struct singleEntry * e
2265    
2266      printf("index=%d\n", index);      printf("index=%d\n", index);
2267    
2268      line = getLineByType(LT_KERNEL|LT_HYPER, entry->lines);      line = getLineByType(LT_KERNEL|LT_HYPER|LT_KERNEL_EFI|LT_KERNEL_16, entry->lines);
2269      if (!line) {      if (!line) {
2270          printf("non linux entry\n");          printf("non linux entry\n");
2271          return;          return;
2272      }      }
2273    
2274      printf("kernel=%s\n", line->elements[1].item);      if (!strncmp(prefix, line->elements[1].item, strlen(prefix)))
2275     printf("kernel=%s\n", line->elements[1].item);
2276        else
2277     printf("kernel=%s%s\n", prefix, line->elements[1].item);
2278    
2279      if (line->numElements >= 3) {      if (line->numElements >= 3) {
2280   printf("args=\"");   printf("args=\"");
# Line 1602  void displayEntry(struct singleEntry * e Line 2330  void displayEntry(struct singleEntry * e
2330   printf("root=%s\n", s);   printf("root=%s\n", s);
2331      }      }
2332    
2333      line = getLineByType(LT_INITRD, entry->lines);      line = getLineByType(LT_INITRD|LT_INITRD_EFI|LT_INITRD_16, entry->lines);
2334    
2335      if (line && line->numElements >= 2) {      if (line && line->numElements >= 2) {
2336   printf("initrd=%s", prefix);   if (!strncmp(prefix, line->elements[1].item, strlen(prefix)))
2337        printf("initrd=");
2338     else
2339        printf("initrd=%s", prefix);
2340    
2341   for (i = 1; i < line->numElements; i++)   for (i = 1; i < line->numElements; i++)
2342      printf("%s%s", line->elements[i].item, line->elements[i].indent);      printf("%s%s", line->elements[i].item, line->elements[i].indent);
2343   printf("\n");   printf("\n");
2344      }      }
2345    
2346        line = getLineByType(LT_TITLE, entry->lines);
2347        if (line) {
2348     printf("title=%s\n", line->elements[1].item);
2349        } else {
2350     char * title;
2351     line = getLineByType(LT_MENUENTRY, entry->lines);
2352     title = grub2ExtractTitle(line);
2353     if (title)
2354        printf("title=%s\n", title);
2355        }
2356    }
2357    
2358    int isSuseSystem(void) {
2359        const char * path;
2360        const static char default_path[] = "/etc/SuSE-release";
2361    
2362        if ((path = getenv("GRUBBY_SUSE_RELEASE")) == NULL)
2363     path = default_path;
2364    
2365        if (!access(path, R_OK))
2366     return 1;
2367        return 0;
2368    }
2369    
2370    int isSuseGrubConf(const char * path) {
2371        FILE * grubConf;
2372        char * line = NULL;
2373        size_t len = 0, res = 0;
2374    
2375        grubConf = fopen(path, "r");
2376        if (!grubConf) {
2377            dbgPrintf("Could not open SuSE configuration file '%s'\n", path);
2378     return 0;
2379        }
2380    
2381        while ((res = getline(&line, &len, grubConf)) != -1) {
2382     if (!strncmp(line, "setup", 5)) {
2383        fclose(grubConf);
2384        free(line);
2385        return 1;
2386     }
2387        }
2388    
2389        dbgPrintf("SuSE configuration file '%s' does not appear to be valid\n",
2390          path);
2391    
2392        fclose(grubConf);
2393        free(line);
2394        return 0;
2395    }
2396    
2397    int suseGrubConfGetLba(const char * path, int * lbaPtr) {
2398        FILE * grubConf;
2399        char * line = NULL;
2400        size_t res = 0, len = 0;
2401    
2402        if (!path) return 1;
2403        if (!lbaPtr) return 1;
2404    
2405        grubConf = fopen(path, "r");
2406        if (!grubConf) return 1;
2407    
2408        while ((res = getline(&line, &len, grubConf)) != -1) {
2409     if (line[res - 1] == '\n')
2410        line[res - 1] = '\0';
2411     else if (len > res)
2412        line[res] = '\0';
2413     else {
2414        line = realloc(line, res + 1);
2415        line[res] = '\0';
2416     }
2417    
2418     if (!strncmp(line, "setup", 5)) {
2419        if (strstr(line, "--force-lba")) {
2420            *lbaPtr = 1;
2421        } else {
2422            *lbaPtr = 0;
2423        }
2424        dbgPrintf("lba: %i\n", *lbaPtr);
2425        break;
2426     }
2427        }
2428    
2429        free(line);
2430        fclose(grubConf);
2431        return 0;
2432    }
2433    
2434    int suseGrubConfGetInstallDevice(const char * path, char ** devicePtr) {
2435        FILE * grubConf;
2436        char * line = NULL;
2437        size_t res = 0, len = 0;
2438        char * lastParamPtr = NULL;
2439        char * secLastParamPtr = NULL;
2440        char installDeviceNumber = '\0';
2441        char * bounds = NULL;
2442    
2443        if (!path) return 1;
2444        if (!devicePtr) return 1;
2445    
2446        grubConf = fopen(path, "r");
2447        if (!grubConf) return 1;
2448    
2449        while ((res = getline(&line, &len, grubConf)) != -1) {
2450     if (strncmp(line, "setup", 5))
2451        continue;
2452    
2453     if (line[res - 1] == '\n')
2454        line[res - 1] = '\0';
2455     else if (len > res)
2456        line[res] = '\0';
2457     else {
2458        line = realloc(line, res + 1);
2459        line[res] = '\0';
2460     }
2461    
2462     lastParamPtr = bounds = line + res;
2463    
2464     /* Last parameter in grub may be an optional IMAGE_DEVICE */
2465     while (!isspace(*lastParamPtr))
2466        lastParamPtr--;
2467     lastParamPtr++;
2468    
2469     secLastParamPtr = lastParamPtr - 2;
2470     dbgPrintf("lastParamPtr: %s\n", lastParamPtr);
2471    
2472     if (lastParamPtr + 3 > bounds) {
2473        dbgPrintf("lastParamPtr going over boundary");
2474        fclose(grubConf);
2475        free(line);
2476        return 1;
2477     }
2478     if (!strncmp(lastParamPtr, "(hd", 3))
2479        lastParamPtr += 3;
2480     dbgPrintf("lastParamPtr: %c\n", *lastParamPtr);
2481    
2482     /*
2483     * Second last parameter will decide wether last parameter is
2484     * an IMAGE_DEVICE or INSTALL_DEVICE
2485     */
2486     while (!isspace(*secLastParamPtr))
2487        secLastParamPtr--;
2488     secLastParamPtr++;
2489    
2490     if (secLastParamPtr + 3 > bounds) {
2491        dbgPrintf("secLastParamPtr going over boundary");
2492        fclose(grubConf);
2493        free(line);
2494        return 1;
2495     }
2496     dbgPrintf("secLastParamPtr: %s\n", secLastParamPtr);
2497     if (!strncmp(secLastParamPtr, "(hd", 3)) {
2498        secLastParamPtr += 3;
2499        dbgPrintf("secLastParamPtr: %c\n", *secLastParamPtr);
2500        installDeviceNumber = *secLastParamPtr;
2501     } else {
2502        installDeviceNumber = *lastParamPtr;
2503     }
2504    
2505     *devicePtr = malloc(6);
2506     snprintf(*devicePtr, 6, "(hd%c)", installDeviceNumber);
2507     dbgPrintf("installDeviceNumber: %c\n", installDeviceNumber);
2508     fclose(grubConf);
2509     free(line);
2510     return 0;
2511        }
2512    
2513        free(line);
2514        fclose(grubConf);
2515        return 1;
2516    }
2517    
2518    int grubGetBootFromDeviceMap(const char * device,
2519         char ** bootPtr) {
2520        FILE * deviceMap;
2521        char * line = NULL;
2522        size_t res = 0, len = 0;
2523        char * devicePtr;
2524        char * bounds = NULL;
2525        const char * path;
2526        const static char default_path[] = "/boot/grub/device.map";
2527    
2528        if (!device) return 1;
2529        if (!bootPtr) return 1;
2530    
2531        if ((path = getenv("GRUBBY_GRUB_DEVICE_MAP")) == NULL)
2532     path = default_path;
2533    
2534        dbgPrintf("opening grub device.map file from: %s\n", path);
2535        deviceMap = fopen(path, "r");
2536        if (!deviceMap)
2537     return 1;
2538    
2539        while ((res = getline(&line, &len, deviceMap)) != -1) {
2540            if (!strncmp(line, "#", 1))
2541        continue;
2542    
2543     if (line[res - 1] == '\n')
2544        line[res - 1] = '\0';
2545     else if (len > res)
2546        line[res] = '\0';
2547     else {
2548        line = realloc(line, res + 1);
2549        line[res] = '\0';
2550     }
2551    
2552     devicePtr = line;
2553     bounds = line + res;
2554    
2555     while ((isspace(*line) && ((devicePtr + 1) <= bounds)))
2556        devicePtr++;
2557     dbgPrintf("device: %s\n", devicePtr);
2558    
2559     if (!strncmp(devicePtr, device, strlen(device))) {
2560        devicePtr += strlen(device);
2561        while (isspace(*devicePtr) && ((devicePtr + 1) <= bounds))
2562            devicePtr++;
2563    
2564        *bootPtr = strdup(devicePtr);
2565        break;
2566     }
2567        }
2568    
2569        free(line);
2570        fclose(deviceMap);
2571        return 0;
2572    }
2573    
2574    int suseGrubConfGetBoot(const char * path, char ** bootPtr) {
2575        char * grubDevice;
2576    
2577        if (suseGrubConfGetInstallDevice(path, &grubDevice))
2578     dbgPrintf("error looking for grub installation device\n");
2579        else
2580     dbgPrintf("grubby installation device: %s\n", grubDevice);
2581    
2582        if (grubGetBootFromDeviceMap(grubDevice, bootPtr))
2583     dbgPrintf("error looking for grub boot device\n");
2584        else
2585     dbgPrintf("grubby boot device: %s\n", *bootPtr);
2586    
2587        free(grubDevice);
2588        return 0;
2589    }
2590    
2591    int parseSuseGrubConf(int * lbaPtr, char ** bootPtr) {
2592        /*
2593         * This SuSE grub configuration file at this location is not your average
2594         * grub configuration file, but instead the grub commands used to setup
2595         * grub on that system.
2596         */
2597        const char * path;
2598        const static char default_path[] = "/etc/grub.conf";
2599    
2600        if ((path = getenv("GRUBBY_SUSE_GRUB_CONF")) == NULL)
2601     path = default_path;
2602    
2603        if (!isSuseGrubConf(path)) return 1;
2604    
2605        if (lbaPtr) {
2606            *lbaPtr = 0;
2607            if (suseGrubConfGetLba(path, lbaPtr))
2608                return 1;
2609        }
2610    
2611        if (bootPtr) {
2612            *bootPtr = NULL;
2613            suseGrubConfGetBoot(path, bootPtr);
2614        }
2615    
2616        return 0;
2617  }  }
2618    
2619  int parseSysconfigGrub(int * lbaPtr, char ** bootPtr) {  int parseSysconfigGrub(int * lbaPtr, char ** bootPtr) {
# Line 1660  int parseSysconfigGrub(int * lbaPtr, cha Line 2664  int parseSysconfigGrub(int * lbaPtr, cha
2664  }  }
2665    
2666  void dumpSysconfigGrub(void) {  void dumpSysconfigGrub(void) {
2667      char * boot;      char * boot = NULL;
2668      int lba;      int lba;
2669    
2670      if (!parseSysconfigGrub(&lba, &boot)) {      if (isSuseSystem()) {
2671   if (lba) printf("lba\n");          if (parseSuseGrubConf(&lba, &boot)) {
2672   if (boot) printf("boot=%s\n", boot);      free(boot);
2673        return;
2674     }
2675        } else {
2676            if (parseSysconfigGrub(&lba, &boot)) {
2677        free(boot);
2678        return;
2679     }
2680        }
2681    
2682        if (lba) printf("lba\n");
2683        if (boot) {
2684     printf("boot=%s\n", boot);
2685     free(boot);
2686      }      }
2687  }  }
2688    
# Line 1714  struct singleLine * addLineTmpl(struct s Line 2731  struct singleLine * addLineTmpl(struct s
2731  {  {
2732      struct singleLine * newLine = lineDup(tmplLine);      struct singleLine * newLine = lineDup(tmplLine);
2733    
2734        if (isEfi && cfi == &grub2ConfigType) {
2735     enum lineType_e old = newLine->type;
2736     newLine->type = preferredLineType(newLine->type, cfi);
2737     if (old != newLine->type)
2738        newLine->elements[0].item = getKeyByType(newLine->type, cfi);
2739        }
2740    
2741      if (val) {      if (val) {
2742   /* override the inherited value with our own.   /* override the inherited value with our own.
2743   * This is a little weak because it only applies to elements[1]   * This is a little weak because it only applies to elements[1]
# Line 1723  struct singleLine * addLineTmpl(struct s Line 2747  struct singleLine * addLineTmpl(struct s
2747   insertElement(newLine, val, 1, cfi);   insertElement(newLine, val, 1, cfi);
2748    
2749   /* but try to keep the rootspec from the template... sigh */   /* but try to keep the rootspec from the template... sigh */
2750   if (tmplLine->type & (LT_HYPER|LT_KERNEL|LT_MBMODULE|LT_INITRD)) {   if (tmplLine->type & (LT_HYPER|LT_KERNEL|LT_MBMODULE|LT_INITRD|LT_KERNEL_EFI|LT_INITRD_EFI|LT_KERNEL_16|LT_INITRD_16)) {
2751      char * rootspec = getRootSpecifier(tmplLine->elements[1].item);      char * rootspec = getRootSpecifier(tmplLine->elements[1].item);
2752      if (rootspec != NULL) {      if (rootspec != NULL) {
2753   free(newLine->elements[1].item);   free(newLine->elements[1].item);
# Line 1760  struct singleLine *  addLine(struct sing Line 2784  struct singleLine *  addLine(struct sing
2784      /* NB: This function shouldn't allocate items on the heap, rather on the      /* NB: This function shouldn't allocate items on the heap, rather on the
2785       * stack since it calls addLineTmpl which will make copies.       * stack since it calls addLineTmpl which will make copies.
2786       */       */
   
2787      if (type == LT_TITLE && cfi->titleBracketed) {      if (type == LT_TITLE && cfi->titleBracketed) {
2788   /* we're doing a bracketed title (zipl) */   /* we're doing a bracketed title (zipl) */
2789   tmpl.type = type;   tmpl.type = type;
# Line 1770  struct singleLine *  addLine(struct sing Line 2793  struct singleLine *  addLine(struct sing
2793   sprintf(tmpl.elements[0].item, "[%s]", val);   sprintf(tmpl.elements[0].item, "[%s]", val);
2794   tmpl.elements[0].indent = "";   tmpl.elements[0].indent = "";
2795   val = NULL;   val = NULL;
2796        } else if (type == LT_MENUENTRY) {
2797     char *lineend = "--class gnu-linux --class gnu --class os {";
2798     if (!val) {
2799        fprintf(stderr, "Line type LT_MENUENTRY requires a value\n");
2800        abort();
2801     }
2802     kw = getKeywordByType(type, cfi);
2803     if (!kw) {
2804        fprintf(stderr, "Looking up keyword for unknown type %d\n", type);
2805        abort();
2806     }
2807     tmpl.indent = "";
2808     tmpl.type = type;
2809     tmpl.numElements = 3;
2810     tmpl.elements = alloca(sizeof(*tmpl.elements) * tmpl.numElements);
2811     tmpl.elements[0].item = kw->key;
2812     tmpl.elements[0].indent = alloca(2);
2813     sprintf(tmpl.elements[0].indent, "%c", kw->nextChar);
2814     tmpl.elements[1].item = (char *)val;
2815     tmpl.elements[1].indent = alloca(2);
2816     sprintf(tmpl.elements[1].indent, "%c", kw->nextChar);
2817     tmpl.elements[2].item = alloca(strlen(lineend)+1);
2818     strcpy(tmpl.elements[2].item, lineend);
2819     tmpl.elements[2].indent = "";
2820      } else {      } else {
2821   kw = getKeywordByType(type, cfi);   kw = getKeywordByType(type, cfi);
2822   if (!kw) abort();   if (!kw) {
2823        fprintf(stderr, "Looking up keyword for unknown type %d\n", type);
2824        abort();
2825     }
2826   tmpl.type = type;   tmpl.type = type;
2827   tmpl.numElements = val ? 2 : 1;   tmpl.numElements = val ? 2 : 1;
2828   tmpl.elements = alloca(sizeof(*tmpl.elements) * tmpl.numElements);   tmpl.elements = alloca(sizeof(*tmpl.elements) * tmpl.numElements);
# Line 1796  struct singleLine *  addLine(struct sing Line 2846  struct singleLine *  addLine(struct sing
2846   if (!line->next && !prev) prev = line;   if (!line->next && !prev) prev = line;
2847      }      }
2848    
2849      if (prev == entry->lines)      struct singleLine *menuEntry;
2850   tmpl.indent = defaultIndent ?: "";      menuEntry = getLineByType(LT_MENUENTRY, entry->lines);
2851      else      if (tmpl.type == LT_ENTRY_END) {
2852   tmpl.indent = prev->indent;   if (menuEntry)
2853        tmpl.indent = menuEntry->indent;
2854     else
2855        tmpl.indent = defaultIndent ?: "";
2856        } else if (tmpl.type != LT_MENUENTRY) {
2857     if (menuEntry)
2858        tmpl.indent = "\t";
2859     else if (prev == entry->lines)
2860        tmpl.indent = defaultIndent ?: "";
2861     else
2862        tmpl.indent = prev->indent;
2863        }
2864    
2865      return addLineTmpl(entry, &tmpl, prev, val, cfi);      return addLineTmpl(entry, &tmpl, prev, val, cfi);
2866  }  }
# Line 1826  void removeLine(struct singleEntry * ent Line 2887  void removeLine(struct singleEntry * ent
2887      free(line);      free(line);
2888  }  }
2889    
2890    static void requote(struct singleLine *tmplLine, struct configFileInfo * cfi)
2891    {
2892        struct singleLine newLine = {
2893     .indent = tmplLine->indent,
2894     .type = tmplLine->type,
2895     .next = tmplLine->next,
2896        };
2897        int firstQuotedItem = -1;
2898        int quoteLen = 0;
2899        int j;
2900        int element = 0;
2901        char *c;
2902    
2903        c = malloc(strlen(tmplLine->elements[0].item) + 1);
2904        strcpy(c, tmplLine->elements[0].item);
2905        insertElement(&newLine, c, element++, cfi);
2906        free(c);
2907        c = NULL;
2908    
2909        for (j = 1; j < tmplLine->numElements; j++) {
2910     if (firstQuotedItem == -1) {
2911        quoteLen += strlen(tmplLine->elements[j].item);
2912        
2913        if (isquote(tmplLine->elements[j].item[0])) {
2914     firstQuotedItem = j;
2915            quoteLen += strlen(tmplLine->elements[j].indent);
2916        } else {
2917     c = malloc(quoteLen + 1);
2918     strcpy(c, tmplLine->elements[j].item);
2919     insertElement(&newLine, c, element++, cfi);
2920     free(c);
2921     quoteLen = 0;
2922        }
2923     } else {
2924        int itemlen = strlen(tmplLine->elements[j].item);
2925        quoteLen += itemlen;
2926        quoteLen += strlen(tmplLine->elements[j].indent);
2927        
2928        if (isquote(tmplLine->elements[j].item[itemlen - 1])) {
2929     c = malloc(quoteLen + 1);
2930     c[0] = '\0';
2931     for (int i = firstQuotedItem; i < j+1; i++) {
2932        strcat(c, tmplLine->elements[i].item);
2933        strcat(c, tmplLine->elements[i].indent);
2934     }
2935     insertElement(&newLine, c, element++, cfi);
2936     free(c);
2937    
2938     firstQuotedItem = -1;
2939     quoteLen = 0;
2940        }
2941     }
2942        }
2943        while (tmplLine->numElements)
2944     removeElement(tmplLine, 0);
2945        if (tmplLine->elements)
2946     free(tmplLine->elements);
2947    
2948        tmplLine->numElements = newLine.numElements;
2949        tmplLine->elements = newLine.elements;
2950    }
2951    
2952  static void insertElement(struct singleLine * line,  static void insertElement(struct singleLine * line,
2953    const char * item, int insertHere,    const char * item, int insertHere,
2954    struct configFileInfo * cfi)    struct configFileInfo * cfi)
# Line 1994  int updateActualImage(struct grubConfig Line 3117  int updateActualImage(struct grubConfig
3117      firstElement = 2;      firstElement = 2;
3118    
3119   } else {   } else {
3120      line = getLineByType(LT_KERNEL|LT_MBMODULE, entry->lines);      line = getLineByType(LT_KERNEL|LT_MBMODULE|LT_KERNEL_EFI|LT_KERNEL_16, entry->lines);
3121      if (!line) {      if (!line) {
3122   /* no LT_KERNEL or LT_MBMODULE in this entry? */   /* no LT_KERNEL or LT_MBMODULE in this entry? */
3123   continue;   continue;
# Line 2150  int updateImage(struct grubConfig * cfg, Line 3273  int updateImage(struct grubConfig * cfg,
3273      return rc;      return rc;
3274  }  }
3275    
3276    int addMBInitrd(struct grubConfig * cfg, const char *newMBKernel,
3277     const char * image, const char * prefix, const char * initrd) {
3278        struct singleEntry * entry;
3279        struct singleLine * line, * kernelLine, *endLine = NULL;
3280        int index = 0;
3281    
3282        if (!image) return 0;
3283    
3284        for (; (entry = findEntryByPath(cfg, newMBKernel, prefix, &index)); index++) {
3285            kernelLine = getLineByType(LT_MBMODULE, entry->lines);
3286            if (!kernelLine) continue;
3287    
3288            if (prefix) {
3289                int prefixLen = strlen(prefix);
3290                if (!strncmp(initrd, prefix, prefixLen))
3291                    initrd += prefixLen;
3292            }
3293     endLine = getLineByType(LT_ENTRY_END, entry->lines);
3294     if (endLine)
3295        removeLine(entry, endLine);
3296            line = addLine(entry, cfg->cfi, preferredLineType(LT_MBMODULE,cfg->cfi),
3297     kernelLine->indent, initrd);
3298            if (!line)
3299        return 1;
3300     if (endLine) {
3301        line = addLine(entry, cfg->cfi, LT_ENTRY_END, "", NULL);
3302                if (!line)
3303     return 1;
3304     }
3305    
3306            break;
3307        }
3308    
3309        return 0;
3310    }
3311    
3312  int updateInitrd(struct grubConfig * cfg, const char * image,  int updateInitrd(struct grubConfig * cfg, const char * image,
3313                   const char * prefix, const char * initrd) {                   const char * prefix, const char * initrd) {
3314      struct singleEntry * entry;      struct singleEntry * entry;
3315      struct singleLine * line, * kernelLine;      struct singleLine * line, * kernelLine, *endLine = NULL;
3316      int index = 0;      int index = 0;
3317    
3318      if (!image) return 0;      if (!image) return 0;
3319    
3320      for (; (entry = findEntryByPath(cfg, image, prefix, &index)); index++) {      for (; (entry = findEntryByPath(cfg, image, prefix, &index)); index++) {
3321          kernelLine = getLineByType(LT_KERNEL, entry->lines);          kernelLine = getLineByType(LT_KERNEL|LT_KERNEL_EFI|LT_KERNEL_16, entry->lines);
3322          if (!kernelLine) continue;          if (!kernelLine) continue;
3323    
3324          line = getLineByType(LT_INITRD, entry->lines);          line = getLineByType(LT_INITRD|LT_INITRD_EFI|LT_INITRD_16, entry->lines);
3325          if (line)          if (line)
3326              removeLine(entry, line);              removeLine(entry, line);
3327          if (prefix) {          if (prefix) {
# Line 2170  int updateInitrd(struct grubConfig * cfg Line 3329  int updateInitrd(struct grubConfig * cfg
3329              if (!strncmp(initrd, prefix, prefixLen))              if (!strncmp(initrd, prefix, prefixLen))
3330                  initrd += prefixLen;                  initrd += prefixLen;
3331          }          }
3332          line = addLine(entry, cfg->cfi, LT_INITRD, kernelLine->indent, initrd);   endLine = getLineByType(LT_ENTRY_END, entry->lines);
3333          if (!line) return 1;   if (endLine)
3334        removeLine(entry, endLine);
3335     enum lineType_e lt;
3336     switch(kernelLine->type) {
3337        case LT_KERNEL:
3338            lt = LT_INITRD;
3339     break;
3340        case LT_KERNEL_EFI:
3341            lt = LT_INITRD_EFI;
3342     break;
3343        case LT_KERNEL_16:
3344            lt = LT_INITRD_16;
3345     break;
3346        default:
3347            lt = preferredLineType(LT_INITRD, cfg->cfi);
3348     }
3349            line = addLine(entry, cfg->cfi, lt, kernelLine->indent, initrd);
3350            if (!line)
3351        return 1;
3352     if (endLine) {
3353        line = addLine(entry, cfg->cfi, LT_ENTRY_END, "", NULL);
3354                if (!line)
3355     return 1;
3356     }
3357    
3358          break;          break;
3359      }      }
3360    
# Line 2201  int checkDeviceBootloader(const char * d Line 3384  int checkDeviceBootloader(const char * d
3384      if (memcmp(boot, bootSect, 3))      if (memcmp(boot, bootSect, 3))
3385   return 0;   return 0;
3386    
3387      if (boot[1] == 0xeb) {      if (boot[1] == JMP_SHORT_OPCODE) {
3388   offset = boot[2] + 2;   offset = boot[2] + 2;
3389      } else if (boot[1] == 0xe8 || boot[1] == 0xe9) {      } else if (boot[1] == 0xe8 || boot[1] == 0xe9) {
3390   offset = (boot[3] << 8) + boot[2] + 2;   offset = (boot[3] << 8) + boot[2] + 2;
3391      } else if (boot[0] == 0xeb) {      } else if (boot[0] == JMP_SHORT_OPCODE) {
3392   offset = boot[1] + 2;        offset = boot[1] + 2;
3393            /*
3394     * it looks like grub, when copying stage1 into the mbr, patches stage1
3395     * right after the JMP location, replacing other instructions such as
3396     * JMPs for NOOPs. So, relax the check a little bit by skipping those
3397     * different bytes.
3398     */
3399          if ((bootSect[offset + 1] == NOOP_OPCODE)
3400      && (bootSect[offset + 2] == NOOP_OPCODE)) {
3401     offset = offset + 3;
3402          }
3403      } else if (boot[0] == 0xe8 || boot[0] == 0xe9) {      } else if (boot[0] == 0xe8 || boot[0] == 0xe9) {
3404   offset = (boot[2] << 8) + boot[1] + 2;   offset = (boot[2] << 8) + boot[1] + 2;
3405      } else {      } else {
# Line 2348  int checkForLilo(struct grubConfig * con Line 3541  int checkForLilo(struct grubConfig * con
3541      return checkDeviceBootloader(line->elements[1].item, boot);      return checkDeviceBootloader(line->elements[1].item, boot);
3542  }  }
3543    
3544    int checkForGrub2(struct grubConfig * config) {
3545        if (!access("/etc/grub.d/", R_OK))
3546     return 2;
3547    
3548        return 1;
3549    }
3550    
3551  int checkForGrub(struct grubConfig * config) {  int checkForGrub(struct grubConfig * config) {
3552      int fd;      int fd;
3553      unsigned char bootSect[512];      unsigned char bootSect[512];
3554      char * boot;      char * boot;
3555        int onSuse = isSuseSystem();
3556    
3557      if (parseSysconfigGrub(NULL, &boot))  
3558   return 0;      if (onSuse) {
3559     if (parseSuseGrubConf(NULL, &boot))
3560        return 0;
3561        } else {
3562     if (parseSysconfigGrub(NULL, &boot))
3563        return 0;
3564        }
3565    
3566      /* assume grub is not installed -- not an error condition */      /* assume grub is not installed -- not an error condition */
3567      if (!boot)      if (!boot)
# Line 2373  int checkForGrub(struct grubConfig * con Line 3580  int checkForGrub(struct grubConfig * con
3580      }      }
3581      close(fd);      close(fd);
3582    
3583        /* The more elaborate checks do not work on SuSE. The checks done
3584         * seem to be reasonble (at least for now), so just return success
3585         */
3586        if (onSuse)
3587     return 2;
3588    
3589      return checkDeviceBootloader(boot, bootSect);      return checkDeviceBootloader(boot, bootSect);
3590  }  }
3591    
# Line 2406  int checkForExtLinux(struct grubConfig * Line 3619  int checkForExtLinux(struct grubConfig *
3619      return checkDeviceBootloader(boot, bootSect);      return checkDeviceBootloader(boot, bootSect);
3620  }  }
3621    
3622    int checkForYaboot(struct grubConfig * config) {
3623        /*
3624         * This is a simplistic check that we consider good enough for own puporses
3625         *
3626         * If we were to properly check if yaboot is *installed* we'd need to:
3627         * 1) get the system boot device (LT_BOOT)
3628         * 2) considering it's a raw filesystem, check if the yaboot binary matches
3629         *    the content on the boot device
3630         * 3) if not, copy the binary to a temporary file and run "addnote" on it
3631         * 4) check again if binary and boot device contents match
3632         */
3633        if (!access("/etc/yaboot.conf", R_OK))
3634     return 2;
3635    
3636        return 1;
3637    }
3638    
3639    int checkForElilo(struct grubConfig * config) {
3640        if (!access("/etc/elilo.conf", R_OK))
3641     return 2;
3642    
3643        return 1;
3644    }
3645    
3646  static char * getRootSpecifier(char * str) {  static char * getRootSpecifier(char * str) {
3647      char * idx, * rootspec = NULL;      char * idx, * rootspec = NULL;
3648    
# Line 2420  static char * getRootSpecifier(char * st Line 3657  static char * getRootSpecifier(char * st
3657  static char * getInitrdVal(struct grubConfig * config,  static char * getInitrdVal(struct grubConfig * config,
3658     const char * prefix, struct singleLine *tmplLine,     const char * prefix, struct singleLine *tmplLine,
3659     const char * newKernelInitrd,     const char * newKernelInitrd,
3660     char ** extraInitrds, int extraInitrdCount)     const char ** extraInitrds, int extraInitrdCount)
3661  {  {
3662      char *initrdVal, *end;      char *initrdVal, *end;
3663      int i;      int i;
# Line 2465  static char * getInitrdVal(struct grubCo Line 3702  static char * getInitrdVal(struct grubCo
3702    
3703  int addNewKernel(struct grubConfig * config, struct singleEntry * template,  int addNewKernel(struct grubConfig * config, struct singleEntry * template,
3704           const char * prefix,           const char * prefix,
3705   char * newKernelPath, char * newKernelTitle,   const char * newKernelPath, const char * newKernelTitle,
3706   char * newKernelArgs, char * newKernelInitrd,   const char * newKernelArgs, const char * newKernelInitrd,
3707   char ** extraInitrds, int extraInitrdCount,   const char ** extraInitrds, int extraInitrdCount,
3708                   char * newMBKernel, char * newMBKernelArgs) {                   const char * newMBKernel, const char * newMBKernelArgs) {
3709      struct singleEntry * new;      struct singleEntry * new;
3710      struct singleLine * newLine = NULL, * tmplLine = NULL, * masterLine = NULL;      struct singleLine * newLine = NULL, * tmplLine = NULL, * masterLine = NULL;
3711      int needs;      int needs;
# Line 2522  int addNewKernel(struct grubConfig * con Line 3759  int addNewKernel(struct grubConfig * con
3759      while (*chptr && isspace(*chptr)) chptr++;      while (*chptr && isspace(*chptr)) chptr++;
3760      if (*chptr == '#') continue;      if (*chptr == '#') continue;
3761    
3762      if (tmplLine->type == LT_KERNEL &&      if (iskernel(tmplLine->type) && tmplLine->numElements >= 2) {
  tmplLine->numElements >= 2) {  
3763   if (!template->multiboot && (needs & NEED_MB)) {   if (!template->multiboot && (needs & NEED_MB)) {
3764      /* it's not a multiboot template and this is the kernel      /* it's not a multiboot template and this is the kernel
3765       * line.  Try to be intelligent about inserting the       * line.  Try to be intelligent about inserting the
# Line 2600  int addNewKernel(struct grubConfig * con Line 3836  int addNewKernel(struct grubConfig * con
3836      /* template is multi but new is not,      /* template is multi but new is not,
3837       * insert the kernel in the first module slot       * insert the kernel in the first module slot
3838       */       */
3839      tmplLine->type = LT_KERNEL;      tmplLine->type = preferredLineType(LT_KERNEL, config->cfi);
3840      free(tmplLine->elements[0].item);      free(tmplLine->elements[0].item);
3841      tmplLine->elements[0].item =      tmplLine->elements[0].item =
3842   strdup(getKeywordByType(LT_KERNEL, config->cfi)->key);   strdup(getKeywordByType(tmplLine->type,
3843     config->cfi)->key);
3844      newLine = addLineTmpl(new, tmplLine, newLine,      newLine = addLineTmpl(new, tmplLine, newLine,
3845    newKernelPath + strlen(prefix), config->cfi);    newKernelPath + strlen(prefix),
3846      config->cfi);
3847      needs &= ~NEED_KERNEL;      needs &= ~NEED_KERNEL;
3848   } else if (needs & NEED_INITRD) {   } else if (needs & NEED_INITRD) {
3849      char *initrdVal;      char *initrdVal;
3850      /* template is multi but new is not,      /* template is multi but new is not,
3851       * insert the initrd in the second module slot       * insert the initrd in the second module slot
3852       */       */
3853      tmplLine->type = LT_INITRD;      tmplLine->type = preferredLineType(LT_INITRD, config->cfi);
3854      free(tmplLine->elements[0].item);      free(tmplLine->elements[0].item);
3855      tmplLine->elements[0].item =      tmplLine->elements[0].item =
3856   strdup(getKeywordByType(LT_INITRD, config->cfi)->key);   strdup(getKeywordByType(tmplLine->type,
3857     config->cfi)->key);
3858      initrdVal = getInitrdVal(config, prefix, tmplLine, newKernelInitrd, extraInitrds, extraInitrdCount);      initrdVal = getInitrdVal(config, prefix, tmplLine, newKernelInitrd, extraInitrds, extraInitrdCount);
3859      newLine = addLineTmpl(new, tmplLine, newLine, initrdVal, config->cfi);      newLine = addLineTmpl(new, tmplLine, newLine, initrdVal, config->cfi);
3860      free(initrdVal);      free(initrdVal);
3861      needs &= ~NEED_INITRD;      needs &= ~NEED_INITRD;
3862   }   }
3863    
3864      } else if (tmplLine->type == LT_INITRD &&      } else if (isinitrd(tmplLine->type) && tmplLine->numElements >= 2) {
        tmplLine->numElements >= 2) {  
3865   if (needs & NEED_INITRD &&   if (needs & NEED_INITRD &&
3866      new->multiboot && !template->multiboot &&      new->multiboot && !template->multiboot &&
3867      config->cfi->mbInitRdIsModule) {      config->cfi->mbInitRdIsModule) {
# Line 2649  int addNewKernel(struct grubConfig * con Line 3887  int addNewKernel(struct grubConfig * con
3887      needs &= ~NEED_INITRD;      needs &= ~NEED_INITRD;
3888   }   }
3889    
3890        } else if (tmplLine->type == LT_MENUENTRY &&
3891           (needs & NEED_TITLE)) {
3892     requote(tmplLine, config->cfi);
3893     char *nkt = malloc(strlen(newKernelTitle)+3);
3894     strcpy(nkt, "'");
3895     strcat(nkt, newKernelTitle);
3896     strcat(nkt, "'");
3897     newLine = addLineTmpl(new, tmplLine, newLine, nkt, config->cfi);
3898     free(nkt);
3899     needs &= ~NEED_TITLE;
3900      } else if (tmplLine->type == LT_TITLE &&      } else if (tmplLine->type == LT_TITLE &&
3901         (needs & NEED_TITLE)) {         (needs & NEED_TITLE)) {
3902   if (tmplLine->numElements >= 2) {   if (tmplLine->numElements >= 2) {
# Line 2662  int addNewKernel(struct grubConfig * con Line 3910  int addNewKernel(struct grubConfig * con
3910        tmplLine->indent, newKernelTitle);        tmplLine->indent, newKernelTitle);
3911      needs &= ~NEED_TITLE;      needs &= ~NEED_TITLE;
3912   }   }
3913        } else if (tmplLine->type == LT_ECHO) {
3914        requote(tmplLine, config->cfi);
3915        static const char *prefix = "'Loading ";
3916        if (tmplLine->numElements > 1 &&
3917        strstr(tmplLine->elements[1].item, prefix) &&
3918        masterLine->next &&
3919        iskernel(masterLine->next->type)) {
3920     char *newTitle = malloc(strlen(prefix) +
3921     strlen(newKernelTitle) + 2);
3922    
3923     strcpy(newTitle, prefix);
3924     strcat(newTitle, newKernelTitle);
3925     strcat(newTitle, "'");
3926     newLine = addLine(new, config->cfi, LT_ECHO,
3927     tmplLine->indent, newTitle);
3928     free(newTitle);
3929        } else {
3930     /* pass through other lines from the template */
3931     newLine = addLineTmpl(new, tmplLine, newLine, NULL,
3932     config->cfi);
3933        }
3934      } else {      } else {
3935   /* pass through other lines from the template */   /* pass through other lines from the template */
3936   newLine = addLineTmpl(new, tmplLine, newLine, NULL, config->cfi);   newLine = addLineTmpl(new, tmplLine, newLine, NULL, config->cfi);
# Line 2673  int addNewKernel(struct grubConfig * con Line 3941  int addNewKernel(struct grubConfig * con
3941   /* don't have a template, so start the entry with the   /* don't have a template, so start the entry with the
3942   * appropriate starting line   * appropriate starting line
3943   */   */
3944   switch (config->cfi->entrySeparator) {   switch (config->cfi->entryStart) {
3945      case LT_KERNEL:      case LT_KERNEL:
3946        case LT_KERNEL_EFI:
3947        case LT_KERNEL_16:
3948   if (new->multiboot && config->cfi->mbHyperFirst) {   if (new->multiboot && config->cfi->mbHyperFirst) {
3949      /* fall through to LT_HYPER */      /* fall through to LT_HYPER */
3950   } else {   } else {
3951      newLine = addLine(new, config->cfi, LT_KERNEL,      newLine = addLine(new, config->cfi,
3952              preferredLineType(LT_KERNEL, config->cfi),
3953        config->primaryIndent,        config->primaryIndent,
3954        newKernelPath + strlen(prefix));        newKernelPath + strlen(prefix));
3955      needs &= ~NEED_KERNEL;      needs &= ~NEED_KERNEL;
# Line 2692  int addNewKernel(struct grubConfig * con Line 3963  int addNewKernel(struct grubConfig * con
3963   needs &= ~NEED_MB;   needs &= ~NEED_MB;
3964   break;   break;
3965    
3966        case LT_MENUENTRY: {
3967     char *nkt = malloc(strlen(newKernelTitle)+3);
3968     strcpy(nkt, "'");
3969     strcat(nkt, newKernelTitle);
3970     strcat(nkt, "'");
3971            newLine = addLine(new, config->cfi, LT_MENUENTRY,
3972      config->primaryIndent, nkt);
3973     free(nkt);
3974     needs &= ~NEED_TITLE;
3975     needs |= NEED_END;
3976     break;
3977        }
3978      case LT_TITLE:      case LT_TITLE:
3979   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)
3980   char * templabel;   char * templabel;
# Line 2725  int addNewKernel(struct grubConfig * con Line 4008  int addNewKernel(struct grubConfig * con
4008    
4009      /* add the remainder of the lines, i.e. those that either      /* add the remainder of the lines, i.e. those that either
4010       * 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,
4011       * all the lines following the entrySeparator.       * all the lines following the entryStart.
4012       */       */
4013      if (needs & NEED_TITLE) {      if (needs & NEED_TITLE) {
4014   newLine = addLine(new, config->cfi, LT_TITLE,   newLine = addLine(new, config->cfi, LT_TITLE,
# Line 2742  int addNewKernel(struct grubConfig * con Line 4025  int addNewKernel(struct grubConfig * con
4025      if (needs & NEED_KERNEL) {      if (needs & NEED_KERNEL) {
4026   newLine = addLine(new, config->cfi,   newLine = addLine(new, config->cfi,
4027    (new->multiboot && getKeywordByType(LT_MBMODULE,    (new->multiboot && getKeywordByType(LT_MBMODULE,
4028        config->cfi)) ?        config->cfi))
4029    LT_MBMODULE : LT_KERNEL,     ? LT_MBMODULE
4030     : preferredLineType(LT_KERNEL, config->cfi),
4031    config->secondaryIndent,    config->secondaryIndent,
4032    newKernelPath + strlen(prefix));    newKernelPath + strlen(prefix));
4033   needs &= ~NEED_KERNEL;   needs &= ~NEED_KERNEL;
# Line 2759  int addNewKernel(struct grubConfig * con Line 4043  int addNewKernel(struct grubConfig * con
4043   initrdVal = getInitrdVal(config, prefix, NULL, newKernelInitrd, extraInitrds, extraInitrdCount);   initrdVal = getInitrdVal(config, prefix, NULL, newKernelInitrd, extraInitrds, extraInitrdCount);
4044   newLine = addLine(new, config->cfi,   newLine = addLine(new, config->cfi,
4045    (new->multiboot && getKeywordByType(LT_MBMODULE,    (new->multiboot && getKeywordByType(LT_MBMODULE,
4046        config->cfi)) ?        config->cfi))
4047    LT_MBMODULE : LT_INITRD,     ? LT_MBMODULE
4048       : preferredLineType(LT_INITRD, config->cfi),
4049    config->secondaryIndent,    config->secondaryIndent,
4050    initrdVal);    initrdVal);
4051   free(initrdVal);   free(initrdVal);
4052   needs &= ~NEED_INITRD;   needs &= ~NEED_INITRD;
4053      }      }
4054        if (needs & NEED_END) {
4055     newLine = addLine(new, config->cfi, LT_ENTRY_END,
4056     config->secondaryIndent, NULL);
4057     needs &= ~NEED_END;
4058        }
4059    
4060      if (needs) {      if (needs) {
4061   printf(_("grubby: needs=%d, aborting\n"), needs);   printf(_("grubby: needs=%d, aborting\n"), needs);
# Line 2787  static void traceback(int signum) Line 4077  static void traceback(int signum)
4077      memset(array, '\0', sizeof (array));      memset(array, '\0', sizeof (array));
4078      size = backtrace(array, 40);      size = backtrace(array, 40);
4079    
4080      fprintf(stderr, "grubby recieved SIGSEGV!  Backtrace (%ld):\n",      fprintf(stderr, "grubby received SIGSEGV!  Backtrace (%ld):\n",
4081              (unsigned long)size);              (unsigned long)size);
4082      backtrace_symbols_fd(array, size, STDERR_FILENO);      backtrace_symbols_fd(array, size, STDERR_FILENO);
4083      exit(1);      exit(1);
# Line 2795  static void traceback(int signum) Line 4085  static void traceback(int signum)
4085    
4086  int main(int argc, const char ** argv) {  int main(int argc, const char ** argv) {
4087      poptContext optCon;      poptContext optCon;
4088      char * grubConfig = NULL;      const char * grubConfig = NULL;
4089      char * outputFile = NULL;      char * outputFile = NULL;
4090      int arg = 0;      int arg = 0;
4091      int flags = 0;      int flags = 0;
4092      int badImageOkay = 0;      int badImageOkay = 0;
4093        int configureGrub2 = 0;
4094      int configureLilo = 0, configureELilo = 0, configureGrub = 0;      int configureLilo = 0, configureELilo = 0, configureGrub = 0;
4095      int configureYaboot = 0, configureSilo = 0, configureZipl = 0;      int configureYaboot = 0, configureSilo = 0, configureZipl = 0;
4096      int configureExtLinux = 0;      int configureExtLinux = 0;
# Line 2821  int main(int argc, const char ** argv) { Line 4112  int main(int argc, const char ** argv) {
4112      char * removeArgs = NULL;      char * removeArgs = NULL;
4113      char * kernelInfo = NULL;      char * kernelInfo = NULL;
4114      char * extraInitrds[MAX_EXTRA_INITRDS] = { NULL };      char * extraInitrds[MAX_EXTRA_INITRDS] = { NULL };
4115        char * envPath = NULL;
4116      const char * chptr = NULL;      const char * chptr = NULL;
4117      struct configFileInfo * cfi = NULL;      struct configFileInfo * cfi = NULL;
4118      struct grubConfig * config;      struct grubConfig * config;
4119      struct singleEntry * template = NULL;      struct singleEntry * template = NULL;
4120      int copyDefault = 0, makeDefault = 0;      int copyDefault = 0, makeDefault = 0;
4121      int displayDefault = 0;      int displayDefault = 0;
4122        int displayDefaultIndex = 0;
4123        int displayDefaultTitle = 0;
4124        int defaultIndex = -1;
4125      struct poptOption options[] = {      struct poptOption options[] = {
4126   { "add-kernel", 0, POPT_ARG_STRING, &newKernelPath, 0,   { "add-kernel", 0, POPT_ARG_STRING, &newKernelPath, 0,
4127      _("add an entry for the specified kernel"), _("kernel-path") },      _("add an entry for the specified kernel"), _("kernel-path") },
# Line 2844  int main(int argc, const char ** argv) { Line 4139  int main(int argc, const char ** argv) {
4139   { "boot-filesystem", 0, POPT_ARG_STRING, &bootPrefix, 0,   { "boot-filesystem", 0, POPT_ARG_STRING, &bootPrefix, 0,
4140      _("filestystem which contains /boot directory (for testing only)"),      _("filestystem which contains /boot directory (for testing only)"),
4141      _("bootfs") },      _("bootfs") },
4142  #if defined(__i386__) || defined(__x86_64__)  #if defined(__i386__) || defined(__x86_64__) || defined (__powerpc64__) || defined (__ia64__)
4143   { "bootloader-probe", 0, POPT_ARG_NONE, &bootloaderProbe, 0,   { "bootloader-probe", 0, POPT_ARG_NONE, &bootloaderProbe, 0,
4144      _("check if lilo is installed on lilo.conf boot sector") },      _("check which bootloader is installed on boot sector") },
4145  #endif  #endif
4146   { "config-file", 'c', POPT_ARG_STRING, &grubConfig, 0,   { "config-file", 'c', POPT_ARG_STRING, &grubConfig, 0,
4147      _("path to grub config file to update (\"-\" for stdin)"),      _("path to grub config file to update (\"-\" for stdin)"),
# Line 2857  int main(int argc, const char ** argv) { Line 4152  int main(int argc, const char ** argv) {
4152        "the kernel referenced by the default image does not exist, "        "the kernel referenced by the default image does not exist, "
4153        "the first linux entry whose kernel does exist is used as the "        "the first linux entry whose kernel does exist is used as the "
4154        "template"), NULL },        "template"), NULL },
4155     { "debug", 0, 0, &debug, 0,
4156        _("print debugging information for failures") },
4157   { "default-kernel", 0, 0, &displayDefault, 0,   { "default-kernel", 0, 0, &displayDefault, 0,
4158      _("display the path of the default kernel") },      _("display the path of the default kernel") },
4159     { "default-index", 0, 0, &displayDefaultIndex, 0,
4160        _("display the index of the default kernel") },
4161     { "default-title", 0, 0, &displayDefaultTitle, 0,
4162        _("display the title of the default kernel") },
4163   { "elilo", 0, POPT_ARG_NONE, &configureELilo, 0,   { "elilo", 0, POPT_ARG_NONE, &configureELilo, 0,
4164      _("configure elilo bootloader") },      _("configure elilo bootloader") },
4165     { "efi", 0, POPT_ARG_NONE, &isEfi, 0,
4166        _("force grub2 stanzas to use efi") },
4167     { "env", 0, POPT_ARG_STRING, &envPath, 0,
4168        _("path for environment data"),
4169        _("path") },
4170   { "extlinux", 0, POPT_ARG_NONE, &configureExtLinux, 0,   { "extlinux", 0, POPT_ARG_NONE, &configureExtLinux, 0,
4171      _("configure extlinux bootloader (from syslinux)") },      _("configure extlinux bootloader (from syslinux)") },
4172   { "grub", 0, POPT_ARG_NONE, &configureGrub, 0,   { "grub", 0, POPT_ARG_NONE, &configureGrub, 0,
4173      _("configure grub bootloader") },      _("configure grub bootloader") },
4174     { "grub2", 0, POPT_ARG_NONE, &configureGrub2, 0,
4175        _("configure grub2 bootloader") },
4176   { "info", 0, POPT_ARG_STRING, &kernelInfo, 0,   { "info", 0, POPT_ARG_STRING, &kernelInfo, 0,
4177      _("display boot information for specified kernel"),      _("display boot information for specified kernel"),
4178      _("kernel-path") },      _("kernel-path") },
4179   { "initrd", 0, POPT_ARG_STRING, &newKernelInitrd, 0,   { "initrd", 0, POPT_ARG_STRING, &newKernelInitrd, 0,
4180      _("initrd image for the new kernel"), _("initrd-path") },      _("initrd image for the new kernel"), _("initrd-path") },
4181   { "extra-initrd", 'i', POPT_ARG_STRING, NULL, 'i',   { "extra-initrd", 'i', POPT_ARG_STRING, NULL, 'i',
4182      _("auxilliary initrd image for things other than the new kernel"), _("initrd-path") },      _("auxiliary initrd image for things other than the new kernel"), _("initrd-path") },
4183   { "lilo", 0, POPT_ARG_NONE, &configureLilo, 0,   { "lilo", 0, POPT_ARG_NONE, &configureLilo, 0,
4184      _("configure lilo bootloader") },      _("configure lilo bootloader") },
4185   { "make-default", 0, 0, &makeDefault, 0,   { "make-default", 0, 0, &makeDefault, 0,
# Line 2891  int main(int argc, const char ** argv) { Line 4199  int main(int argc, const char ** argv) {
4199   { "set-default", 0, POPT_ARG_STRING, &defaultKernel, 0,   { "set-default", 0, POPT_ARG_STRING, &defaultKernel, 0,
4200      _("make the first entry referencing the specified kernel "      _("make the first entry referencing the specified kernel "
4201        "the default"), _("kernel-path") },        "the default"), _("kernel-path") },
4202     { "set-default-index", 0, POPT_ARG_INT, &defaultIndex, 0,
4203        _("make the given entry index the default entry"),
4204        _("entry-index") },
4205   { "silo", 0, POPT_ARG_NONE, &configureSilo, 0,   { "silo", 0, POPT_ARG_NONE, &configureSilo, 0,
4206      _("configure silo bootloader") },      _("configure silo bootloader") },
4207   { "title", 0, POPT_ARG_STRING, &newKernelTitle, 0,   { "title", 0, POPT_ARG_STRING, &newKernelTitle, 0,
# Line 2912  int main(int argc, const char ** argv) { Line 4223  int main(int argc, const char ** argv) {
4223    
4224      signal(SIGSEGV, traceback);      signal(SIGSEGV, traceback);
4225    
4226        int i = 0;
4227        for (int j = 1; j < argc; j++)
4228     i += strlen(argv[j]) + 1;
4229        saved_command_line = malloc(i);
4230        if (!saved_command_line) {
4231     fprintf(stderr, "grubby: %m\n");
4232     exit(1);
4233        }
4234        saved_command_line[0] = '\0';
4235        for (int j = 1; j < argc; j++) {
4236     strcat(saved_command_line, argv[j]);
4237     strncat(saved_command_line, j == argc -1 ? "" : " ", 1);
4238        }
4239    
4240      optCon = poptGetContext("grubby", argc, argv, options, 0);      optCon = poptGetContext("grubby", argc, argv, options, 0);
4241      poptReadDefaultConfig(optCon, 1);      poptReadDefaultConfig(optCon, 1);
4242    
# Line 2944  int main(int argc, const char ** argv) { Line 4269  int main(int argc, const char ** argv) {
4269   return 1;   return 1;
4270      }      }
4271    
4272      if ((configureLilo + configureGrub + configureELilo +      if ((configureLilo + configureGrub2 + configureGrub + configureELilo +
4273   configureYaboot + configureSilo + configureZipl +   configureYaboot + configureSilo + configureZipl +
4274   configureExtLinux ) > 1) {   configureExtLinux ) > 1) {
4275   fprintf(stderr, _("grubby: cannot specify multiple bootloaders\n"));   fprintf(stderr, _("grubby: cannot specify multiple bootloaders\n"));
# Line 2953  int main(int argc, const char ** argv) { Line 4278  int main(int argc, const char ** argv) {
4278   fprintf(stderr,   fprintf(stderr,
4279      _("grubby: cannot specify config file with --bootloader-probe\n"));      _("grubby: cannot specify config file with --bootloader-probe\n"));
4280   return 1;   return 1;
4281        } else if (configureGrub2) {
4282     cfi = &grub2ConfigType;
4283     if (envPath)
4284        cfi->envFile = envPath;
4285      } else if (configureLilo) {      } else if (configureLilo) {
4286   cfi = &liloConfigType;   cfi = &liloConfigType;
4287      } else if (configureGrub) {      } else if (configureGrub) {
# Line 2971  int main(int argc, const char ** argv) { Line 4300  int main(int argc, const char ** argv) {
4300      }      }
4301    
4302      if (!cfi) {      if (!cfi) {
4303            if (grub2FindConfig(&grub2ConfigType))
4304        cfi = &grub2ConfigType;
4305     else
4306        #ifdef __ia64__        #ifdef __ia64__
4307   cfi = &eliloConfigType;      cfi = &eliloConfigType;
4308        #elif __powerpc__        #elif __powerpc__
4309   cfi = &yabootConfigType;      cfi = &yabootConfigType;
4310        #elif __sparc__        #elif __sparc__
4311          cfi = &siloConfigType;              cfi = &siloConfigType;
4312        #elif __s390__        #elif __s390__
4313          cfi = &ziplConfigType;              cfi = &ziplConfigType;
4314        #elif __s390x__        #elif __s390x__
4315          cfi = &ziplConfigtype;              cfi = &ziplConfigtype;
4316        #else        #else
4317   cfi = &grubConfigType;      cfi = &grubConfigType;
4318        #endif        #endif
4319      }      }
4320    
4321      if (!grubConfig)      if (!grubConfig) {
4322   grubConfig = cfi->defaultConfig;   if (cfi->findConfig)
4323        grubConfig = cfi->findConfig(cfi);
4324     if (!grubConfig)
4325        grubConfig = cfi->defaultConfig;
4326        }
4327    
4328      if (bootloaderProbe && (displayDefault || kernelInfo || newKernelVersion ||      if (bootloaderProbe && (displayDefault || kernelInfo || newKernelVersion ||
4329    newKernelPath || removeKernelPath || makeDefault ||      newKernelPath || removeKernelPath || makeDefault ||
4330    defaultKernel)) {      defaultKernel || displayDefaultIndex || displayDefaultTitle ||
4331        (defaultIndex >= 0))) {
4332   fprintf(stderr, _("grubby: --bootloader-probe may not be used with "   fprintf(stderr, _("grubby: --bootloader-probe may not be used with "
4333    "specified option"));    "specified option"));
4334   return 1;   return 1;
# Line 3033  int main(int argc, const char ** argv) { Line 4370  int main(int argc, const char ** argv) {
4370   makeDefault = 1;   makeDefault = 1;
4371   defaultKernel = NULL;   defaultKernel = NULL;
4372      }      }
4373        else if (defaultKernel && (defaultIndex >= 0)) {
4374     fprintf(stderr, _("grubby: --set-default and --set-default-index "
4375      "may not be used together\n"));
4376     return 1;
4377        }
4378    
4379      if (!strcmp(grubConfig, "-") && !outputFile) {      if (grubConfig && !strcmp(grubConfig, "-") && !outputFile) {
4380   fprintf(stderr, _("grubby: output file must be specified if stdin "   fprintf(stderr, _("grubby: output file must be specified if stdin "
4381   "is used\n"));   "is used\n"));
4382   return 1;   return 1;
4383      }      }
4384    
4385      if (!removeKernelPath && !newKernelPath && !displayDefault && !defaultKernel      if (!removeKernelPath && !newKernelPath && !displayDefault && !defaultKernel
4386   && !kernelInfo && !bootloaderProbe && !updateKernelPath   && !kernelInfo && !bootloaderProbe && !updateKernelPath
4387          && !removeMBKernel) {   && !removeMBKernel && !displayDefaultIndex && !displayDefaultTitle
4388     && (defaultIndex == -1)) {
4389   fprintf(stderr, _("grubby: no action specified\n"));   fprintf(stderr, _("grubby: no action specified\n"));
4390   return 1;   return 1;
4391      }      }
# Line 3069  int main(int argc, const char ** argv) { Line 4412  int main(int argc, const char ** argv) {
4412      }      }
4413    
4414      if (bootloaderProbe) {      if (bootloaderProbe) {
4415   int lrc = 0, grc = 0, erc = 0;   int lrc = 0, grc = 0, gr2c = 0, extrc = 0, yrc = 0, erc = 0;
4416   struct grubConfig * lconfig, * gconfig;   struct grubConfig * lconfig, * gconfig, * yconfig, * econfig;
4417    
4418     const char *grub2config = grub2FindConfig(&grub2ConfigType);
4419     if (grub2config) {
4420        gconfig = readConfig(grub2config, &grub2ConfigType);
4421        if (!gconfig)
4422     gr2c = 1;
4423        else
4424     gr2c = checkForGrub2(gconfig);
4425     }
4426    
4427   if (!access(grubConfigType.defaultConfig, F_OK)) {   const char *grubconfig = grubFindConfig(&grubConfigType);
4428      gconfig = readConfig(grubConfigType.defaultConfig, &grubConfigType);   if (!access(grubconfig, F_OK)) {
4429        gconfig = readConfig(grubconfig, &grubConfigType);
4430      if (!gconfig)      if (!gconfig)
4431   grc = 1;   grc = 1;
4432      else      else
# Line 3088  int main(int argc, const char ** argv) { Line 4441  int main(int argc, const char ** argv) {
4441   lrc = checkForLilo(lconfig);   lrc = checkForLilo(lconfig);
4442   }   }
4443    
4444     if (!access(eliloConfigType.defaultConfig, F_OK)) {
4445        econfig = readConfig(eliloConfigType.defaultConfig,
4446     &eliloConfigType);
4447        if (!econfig)
4448     erc = 1;
4449        else
4450     erc = checkForElilo(econfig);
4451     }
4452    
4453   if (!access(extlinuxConfigType.defaultConfig, F_OK)) {   if (!access(extlinuxConfigType.defaultConfig, F_OK)) {
4454      lconfig = readConfig(extlinuxConfigType.defaultConfig, &extlinuxConfigType);      lconfig = readConfig(extlinuxConfigType.defaultConfig, &extlinuxConfigType);
4455      if (!lconfig)      if (!lconfig)
4456   erc = 1;   extrc = 1;
4457      else      else
4458   erc = checkForExtLinux(lconfig);   extrc = checkForExtLinux(lconfig);
4459   }   }
4460    
4461   if (lrc == 1 || grc == 1) return 1;  
4462     if (!access(yabootConfigType.defaultConfig, F_OK)) {
4463        yconfig = readConfig(yabootConfigType.defaultConfig,
4464     &yabootConfigType);
4465        if (!yconfig)
4466     yrc = 1;
4467        else
4468     yrc = checkForYaboot(yconfig);
4469     }
4470    
4471     if (lrc == 1 || grc == 1 || gr2c == 1 || extrc == 1 || yrc == 1 ||
4472     erc == 1)
4473        return 1;
4474    
4475   if (lrc == 2) printf("lilo\n");   if (lrc == 2) printf("lilo\n");
4476     if (gr2c == 2) printf("grub2\n");
4477   if (grc == 2) printf("grub\n");   if (grc == 2) printf("grub\n");
4478   if (erc == 2) printf("extlinux\n");   if (extrc == 2) printf("extlinux\n");
4479     if (yrc == 2) printf("yaboot\n");
4480     if (erc == 2) printf("elilo\n");
4481    
4482   return 0;   return 0;
4483      }      }
4484    
4485        if (grubConfig == NULL) {
4486     printf("Could not find bootloader configuration file.\n");
4487     exit(1);
4488        }
4489    
4490      config = readConfig(grubConfig, cfi);      config = readConfig(grubConfig, cfi);
4491      if (!config) return 1;      if (!config) return 1;
4492    
# Line 3114  int main(int argc, const char ** argv) { Line 4496  int main(int argc, const char ** argv) {
4496          char * rootspec;          char * rootspec;
4497    
4498   if (config->defaultImage == -1) return 0;   if (config->defaultImage == -1) return 0;
4499     if (config->defaultImage == DEFAULT_SAVED_GRUB2 &&
4500     cfi->defaultIsSaved)
4501        config->defaultImage = 0;
4502   entry = findEntryByIndex(config, config->defaultImage);   entry = findEntryByIndex(config, config->defaultImage);
4503   if (!entry) return 0;   if (!entry) return 0;
4504   if (!suitableImage(entry, bootPrefix, 0, flags)) return 0;   if (!suitableImage(entry, bootPrefix, 0, flags)) return 0;
4505    
4506   line = getLineByType(LT_KERNEL|LT_HYPER, entry->lines);   line = getLineByType(LT_KERNEL|LT_HYPER|LT_KERNEL_EFI|LT_KERNEL_16, entry->lines);
4507   if (!line) return 0;   if (!line) return 0;
4508    
4509          rootspec = getRootSpecifier(line->elements[1].item);          rootspec = getRootSpecifier(line->elements[1].item);
# Line 3126  int main(int argc, const char ** argv) { Line 4511  int main(int argc, const char ** argv) {
4511                 ((rootspec != NULL) ? strlen(rootspec) : 0));                 ((rootspec != NULL) ? strlen(rootspec) : 0));
4512    
4513   return 0;   return 0;
4514    
4515        } else if (displayDefaultTitle) {
4516     struct singleLine * line;
4517     struct singleEntry * entry;
4518    
4519     if (config->defaultImage == -1) return 0;
4520     if (config->defaultImage == DEFAULT_SAVED_GRUB2 &&
4521     cfi->defaultIsSaved)
4522        config->defaultImage = 0;
4523     entry = findEntryByIndex(config, config->defaultImage);
4524     if (!entry) return 0;
4525    
4526     if (!configureGrub2) {
4527      line = getLineByType(LT_TITLE, entry->lines);
4528      if (!line) return 0;
4529      printf("%s\n", line->elements[1].item);
4530    
4531     } else {
4532      char * title;
4533    
4534      dbgPrintf("This is GRUB2, default title is embeded in menuentry\n");
4535      line = getLineByType(LT_MENUENTRY, entry->lines);
4536      if (!line) return 0;
4537      title = grub2ExtractTitle(line);
4538      if (title)
4539        printf("%s\n", title);
4540     }
4541     return 0;
4542    
4543        } else if (displayDefaultIndex) {
4544            if (config->defaultImage == -1) return 0;
4545     if (config->defaultImage == DEFAULT_SAVED_GRUB2 &&
4546     cfi->defaultIsSaved)
4547        config->defaultImage = 0;
4548            printf("%i\n", config->defaultImage);
4549            return 0;
4550    
4551      } else if (kernelInfo)      } else if (kernelInfo)
4552   return displayInfo(config, kernelInfo, bootPrefix);   return displayInfo(config, kernelInfo, bootPrefix);
4553    
# Line 3137  int main(int argc, const char ** argv) { Line 4559  int main(int argc, const char ** argv) {
4559      markRemovedImage(config, removeKernelPath, bootPrefix);      markRemovedImage(config, removeKernelPath, bootPrefix);
4560      markRemovedImage(config, removeMBKernel, bootPrefix);      markRemovedImage(config, removeMBKernel, bootPrefix);
4561      setDefaultImage(config, newKernelPath != NULL, defaultKernel, makeDefault,      setDefaultImage(config, newKernelPath != NULL, defaultKernel, makeDefault,
4562      bootPrefix, flags);      bootPrefix, flags, defaultIndex);
4563      setFallbackImage(config, newKernelPath != NULL);      setFallbackImage(config, newKernelPath != NULL);
4564      if (updateImage(config, updateKernelPath, bootPrefix, newKernelArgs,      if (updateImage(config, updateKernelPath, bootPrefix, newKernelArgs,
4565                      removeArgs, newMBKernelArgs, removeMBKernelArgs)) return 1;                      removeArgs, newMBKernelArgs, removeMBKernelArgs)) return 1;
4566      if (updateKernelPath && newKernelInitrd) {      if (updateKernelPath && newKernelInitrd) {
4567              if (updateInitrd(config, updateKernelPath, bootPrefix,      if (newMBKernel) {
4568                               newKernelInitrd)) return 1;      if (addMBInitrd(config, newMBKernel, updateKernelPath,
4569     bootPrefix, newKernelInitrd))
4570        return 1;
4571        } else {
4572        if (updateInitrd(config, updateKernelPath, bootPrefix,
4573     newKernelInitrd))
4574     return 1;
4575        }
4576      }      }
4577      if (addNewKernel(config, template, bootPrefix, newKernelPath,      if (addNewKernel(config, template, bootPrefix, newKernelPath,
4578                       newKernelTitle, newKernelArgs, newKernelInitrd,                       newKernelTitle, newKernelArgs, newKernelInitrd,
4579                       extraInitrds, extraInitrdCount,                       (const char **)extraInitrds, extraInitrdCount,
4580                       newMBKernel, newMBKernelArgs)) return 1;                       newMBKernel, newMBKernelArgs)) return 1;
4581            
4582    
# Line 3158  int main(int argc, const char ** argv) { Line 4587  int main(int argc, const char ** argv) {
4587      }      }
4588    
4589      if (!outputFile)      if (!outputFile)
4590   outputFile = grubConfig;   outputFile = (char *)grubConfig;
4591    
4592      return writeConfig(config, outputFile, bootPrefix);      return writeConfig(config, outputFile, bootPrefix);
4593  }  }

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