Magellan Linux

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

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

revision 1717 by niro, Sat Feb 18 00:47:17 2012 UTC revision 2252 by niro, Mon Oct 21 13:59:08 2013 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  #ifndef DEBUG
42  #define DEBUG 0  #define DEBUG 0
43  #endif  #endif
# Line 46  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 77  enum lineType_e { Line 88  enum lineType_e {
88      LT_MENUENTRY    = 1 << 17,      LT_MENUENTRY    = 1 << 17,
89      LT_ENTRY_END    = 1 << 18,      LT_ENTRY_END    = 1 << 18,
90      LT_SET_VARIABLE = 1 << 19,      LT_SET_VARIABLE = 1 << 19,
91      LT_UNKNOWN      = 1 << 20,      LT_KERNEL_EFI   = 1 << 20,
92        LT_INITRD_EFI   = 1 << 21,
93        LT_UNKNOWN      = 1 << 22,
94  };  };
95    
96  struct singleLine {  struct singleLine {
# Line 109  struct singleEntry { Line 122  struct singleEntry {
122    
123  #define MAIN_DEFAULT    (1 << 0)  #define MAIN_DEFAULT    (1 << 0)
124  #define DEFAULT_SAVED       -2  #define DEFAULT_SAVED       -2
125    #define DEFAULT_SAVED_GRUB2 -3
126    
127  struct keywordTypes {  struct keywordTypes {
128      char * key;      char * key;
# Line 122  struct configFileInfo; Line 136  struct configFileInfo;
136  typedef const char *(*findConfigFunc)(struct configFileInfo *);  typedef const char *(*findConfigFunc)(struct configFileInfo *);
137  typedef const int (*writeLineFunc)(struct configFileInfo *,  typedef const int (*writeLineFunc)(struct configFileInfo *,
138   struct singleLine *line);   struct singleLine *line);
139    typedef char *(*getEnvFunc)(struct configFileInfo *, char *name);
140    typedef int (*setEnvFunc)(struct configFileInfo *, char *name, char *value);
141    
142  struct configFileInfo {  struct configFileInfo {
143      char * defaultConfig;      char * defaultConfig;
144      findConfigFunc findConfig;      findConfigFunc findConfig;
145      writeLineFunc writeLine;      writeLineFunc writeLine;
146        getEnvFunc getEnv;
147        setEnvFunc setEnv;
148      struct keywordTypes * keywords;      struct keywordTypes * keywords;
149        int caseInsensitive;
150      int defaultIsIndex;      int defaultIsIndex;
151      int defaultIsVariable;      int defaultIsVariable;
152      int defaultSupportSaved;      int defaultSupportSaved;
153        int defaultIsSaved;
154      enum lineType_e entryStart;      enum lineType_e entryStart;
155      enum lineType_e entryEnd;      enum lineType_e entryEnd;
156      int needsBootPrefix;      int needsBootPrefix;
# Line 142  struct configFileInfo { Line 162  struct configFileInfo {
162      int mbInitRdIsModule;      int mbInitRdIsModule;
163      int mbConcatArgs;      int mbConcatArgs;
164      int mbAllowExtraInitRds;      int mbAllowExtraInitRds;
165        char *envFile;
166  };  };
167    
168  struct keywordTypes grubKeywords[] = {  struct keywordTypes grubKeywords[] = {
# Line 158  struct keywordTypes grubKeywords[] = { Line 179  struct keywordTypes grubKeywords[] = {
179    
180  const char *grubFindConfig(struct configFileInfo *cfi) {  const char *grubFindConfig(struct configFileInfo *cfi) {
181      static const char *configFiles[] = {      static const char *configFiles[] = {
  "/etc/grub.conf",  
182   "/boot/grub/grub.conf",   "/boot/grub/grub.conf",
183   "/boot/grub/menu.lst",   "/boot/grub/menu.lst",
184     "/etc/grub.conf",
185   NULL   NULL
186      };      };
187      static int i = -1;      static int i = -1;
# Line 199  struct keywordTypes grub2Keywords[] = { Line 220  struct keywordTypes grub2Keywords[] = {
220      { "default",    LT_DEFAULT,     ' ' },      { "default",    LT_DEFAULT,     ' ' },
221      { "fallback",   LT_FALLBACK,    ' ' },      { "fallback",   LT_FALLBACK,    ' ' },
222      { "linux",      LT_KERNEL,      ' ' },      { "linux",      LT_KERNEL,      ' ' },
223        { "linuxefi",   LT_KERNEL_EFI,  ' ' },
224      { "initrd",     LT_INITRD,      ' ', ' ' },      { "initrd",     LT_INITRD,      ' ', ' ' },
225        { "initrdefi",  LT_INITRD_EFI,  ' ', ' ' },
226      { "module",     LT_MBMODULE,    ' ' },      { "module",     LT_MBMODULE,    ' ' },
227      { "kernel",     LT_HYPER,       ' ' },      { "kernel",     LT_HYPER,       ' ' },
228      { NULL, 0, 0 },      { NULL, 0, 0 },
# Line 213  const char *grub2FindConfig(struct confi Line 236  const char *grub2FindConfig(struct confi
236      };      };
237      static int i = -1;      static int i = -1;
238      static const char *grub_cfg = "/boot/grub/grub.cfg";      static const char *grub_cfg = "/boot/grub/grub.cfg";
239        int rc = -1;
240    
241      if (i == -1) {      if (i == -1) {
242   for (i = 0; configFiles[i] != NULL; i++) {   for (i = 0; configFiles[i] != NULL; i++) {
243      dbgPrintf("Checking \"%s\": ", configFiles[i]);      dbgPrintf("Checking \"%s\": ", configFiles[i]);
244      if (!access(configFiles[i], R_OK)) {      if ((rc = access(configFiles[i], R_OK))) {
245     if (errno == EACCES) {
246        printf("Unable to access bootloader configuration file "
247           "\"%s\": %m\n", configFiles[i]);
248        exit(1);
249     }
250     continue;
251        } else {
252   dbgPrintf("found\n");   dbgPrintf("found\n");
253   return configFiles[i];   return configFiles[i];
254      }      }
# Line 236  const char *grub2FindConfig(struct confi Line 267  const char *grub2FindConfig(struct confi
267      return configFiles[i];      return configFiles[i];
268  }  }
269    
270    /* kind of hacky.  It'll give the first 1024 bytes, ish. */
271    static char *grub2GetEnv(struct configFileInfo *info, char *name)
272    {
273        static char buf[1025];
274        char *s = NULL;
275        char *ret = NULL;
276        char *envFile = info->envFile ? info->envFile : "/boot/grub2/grubenv";
277        int rc = asprintf(&s, "grub2-editenv %s list | grep '^%s='", envFile, name);
278    
279        if (rc < 0)
280     return NULL;
281    
282        FILE *f = popen(s, "r");
283        if (!f)
284     goto out;
285    
286        memset(buf, '\0', sizeof (buf));
287        ret = fgets(buf, 1024, f);
288        pclose(f);
289    
290        if (ret) {
291     ret += strlen(name) + 1;
292     ret[strlen(ret) - 1] = '\0';
293        }
294        dbgPrintf("grub2GetEnv(%s): %s\n", name, ret);
295    out:
296        free(s);
297        return ret;
298    }
299    
300    static int grub2SetEnv(struct configFileInfo *info, char *name, char *value)
301    {
302        char *s = NULL;
303        int rc = 0;
304        char *envFile = info->envFile ? info->envFile : "/boot/grub2/grubenv";
305    
306        rc = asprintf(&s, "grub2-editenv %s set '%s=%s'", envFile, name, value);
307        if (rc <0)
308     return -1;
309    
310        dbgPrintf("grub2SetEnv(%s): %s\n", name, s);
311        rc = system(s);
312        free(s);
313        return rc;
314    }
315    
316    /* this is a gigantic hack to avoid clobbering grub2 variables... */
317    static int is_special_grub2_variable(const char *name)
318    {
319        if (!strcmp(name,"\"${next_entry}\""))
320     return 1;
321        if (!strcmp(name,"\"${prev_saved_entry}\""))
322     return 1;
323        return 0;
324    }
325    
326    int sizeOfSingleLine(struct singleLine * line) {
327      int count = 0;
328    
329      for (int i = 0; i < line->numElements; i++) {
330        int indentSize = 0;
331    
332        count = count + strlen(line->elements[i].item);
333    
334        indentSize = strlen(line->elements[i].indent);
335        if (indentSize > 0)
336          count = count + indentSize;
337        else
338          /* be extra safe and add room for whitespaces */
339          count = count + 1;
340      }
341    
342      /* room for trailing terminator */
343      count = count + 1;
344    
345      return count;
346    }
347    
348    static int isquote(char q)
349    {
350        if (q == '\'' || q == '\"')
351     return 1;
352        return 0;
353    }
354    
355    static int iskernel(enum lineType_e type) {
356        return (type == LT_KERNEL || type == LT_KERNEL_EFI);
357    }
358    
359    static int isinitrd(enum lineType_e type) {
360        return (type == LT_INITRD || type == LT_INITRD_EFI);
361    }
362    
363    char *grub2ExtractTitle(struct singleLine * line) {
364        char * current;
365        char * current_indent;
366        int current_len;
367        int current_indent_len;
368        int i;
369    
370        /* bail out if line does not start with menuentry */
371        if (strcmp(line->elements[0].item, "menuentry"))
372          return NULL;
373    
374        i = 1;
375        current = line->elements[i].item;
376        current_len = strlen(current);
377    
378        /* if second word is quoted, strip the quotes and return single word */
379        if (isquote(*current) && isquote(current[current_len - 1])) {
380     char *tmp;
381    
382     tmp = strdup(current);
383     *(tmp + current_len - 1) = '\0';
384     return ++tmp;
385        }
386    
387        /* if no quotes, return second word verbatim */
388        if (!isquote(*current))
389     return current;
390    
391        /* second element start with a quote, so we have to find the element
392         * whose last character is also quote (assuming it's the closing one) */
393        int resultMaxSize;
394        char * result;
395        
396        resultMaxSize = sizeOfSingleLine(line);
397        result = malloc(resultMaxSize);
398        snprintf(result, resultMaxSize, "%s", ++current);
399        
400        i++;
401        for (; i < line->numElements; ++i) {
402     current = line->elements[i].item;
403     current_len = strlen(current);
404     current_indent = line->elements[i].indent;
405     current_indent_len = strlen(current_indent);
406    
407     strncat(result, current_indent, current_indent_len);
408     if (!isquote(current[current_len-1])) {
409        strncat(result, current, current_len);
410     } else {
411        strncat(result, current, current_len - 1);
412        break;
413     }
414        }
415        return result;
416    }
417    
418  struct configFileInfo grub2ConfigType = {  struct configFileInfo grub2ConfigType = {
419      .findConfig = grub2FindConfig,      .findConfig = grub2FindConfig,
420        .getEnv = grub2GetEnv,
421        .setEnv = grub2SetEnv,
422      .keywords = grub2Keywords,      .keywords = grub2Keywords,
423      .defaultIsIndex = 1,      .defaultIsIndex = 1,
424      .defaultSupportSaved = 0,      .defaultSupportSaved = 1,
425      .defaultIsVariable = 1,      .defaultIsVariable = 1,
426      .entryStart = LT_MENUENTRY,      .entryStart = LT_MENUENTRY,
427      .entryEnd = LT_ENTRY_END,      .entryEnd = LT_ENTRY_END,
# Line 392  struct configFileInfo ziplConfigType = { Line 573  struct configFileInfo ziplConfigType = {
573  struct configFileInfo extlinuxConfigType = {  struct configFileInfo extlinuxConfigType = {
574      .defaultConfig = "/boot/extlinux/extlinux.conf",      .defaultConfig = "/boot/extlinux/extlinux.conf",
575      .keywords = extlinuxKeywords,      .keywords = extlinuxKeywords,
576        .caseInsensitive = 1,
577      .entryStart = LT_TITLE,      .entryStart = LT_TITLE,
578      .needsBootPrefix = 1,      .needsBootPrefix = 1,
579      .maxTitleLength = 255,      .maxTitleLength = 255,
# Line 416  struct singleEntry * findEntryByIndex(st Line 598  struct singleEntry * findEntryByIndex(st
598  struct singleEntry * findEntryByPath(struct grubConfig * cfg,  struct singleEntry * findEntryByPath(struct grubConfig * cfg,
599       const char * path, const char * prefix,       const char * path, const char * prefix,
600       int * index);       int * index);
601    struct singleEntry * findEntryByTitle(struct grubConfig * cfg, char *title,
602          int * index);
603  static int readFile(int fd, char ** bufPtr);  static int readFile(int fd, char ** bufPtr);
604  static void lineInit(struct singleLine * line);  static void lineInit(struct singleLine * line);
605  struct singleLine * lineDup(struct singleLine * line);  struct singleLine * lineDup(struct singleLine * line);
# Line 480  static char * sdupprintf(const char *for Line 664  static char * sdupprintf(const char *for
664      return buf;      return buf;
665  }  }
666    
667    static enum lineType_e preferredLineType(enum lineType_e type,
668     struct configFileInfo *cfi) {
669        if (isEfi && cfi == &grub2ConfigType) {
670     switch (type) {
671     case LT_KERNEL:
672        return LT_KERNEL_EFI;
673     case LT_INITRD:
674        return LT_INITRD_EFI;
675     default:
676        return type;
677     }
678        }
679        return type;
680    }
681    
682  static struct keywordTypes * getKeywordByType(enum lineType_e type,  static struct keywordTypes * getKeywordByType(enum lineType_e type,
683        struct configFileInfo * cfi) {        struct configFileInfo * cfi) {
684      struct keywordTypes * kw;      for (struct keywordTypes *kw = cfi->keywords; kw->key; kw++) {
     for (kw = cfi->keywords; kw->key; kw++) {  
685   if (kw->type == type)   if (kw->type == type)
686      return kw;      return kw;
687      }      }
# Line 513  static char * getuuidbydev(char *device) Line 711  static char * getuuidbydev(char *device)
711    
712  static enum lineType_e getTypeByKeyword(char * keyword,  static enum lineType_e getTypeByKeyword(char * keyword,
713   struct configFileInfo * cfi) {   struct configFileInfo * cfi) {
714      struct keywordTypes * kw;      for (struct keywordTypes *kw = cfi->keywords; kw->key; kw++) {
715      for (kw = cfi->keywords; kw->key; kw++) {   if (cfi->caseInsensitive) {
716   if (!strcmp(keyword, kw->key))      if (!strcasecmp(keyword, kw->key))
717      return kw->type;                  return kw->type;
718     } else {
719        if (!strcmp(keyword, kw->key))
720            return kw->type;
721     }
722      }      }
723      return LT_UNKNOWN;      return LT_UNKNOWN;
724  }  }
# Line 555  static int isEntryStart(struct singleLin Line 757  static int isEntryStart(struct singleLin
757  /* extract the title from within brackets (for zipl) */  /* extract the title from within brackets (for zipl) */
758  static char * extractTitle(struct singleLine * line) {  static char * extractTitle(struct singleLine * line) {
759      /* bracketed title... let's extract it (leaks a byte) */      /* bracketed title... let's extract it (leaks a byte) */
760      char * title;      char * title = NULL;
761      title = strdup(line->elements[0].item);      if (line->type == LT_TITLE) {
762      title++;   title = strdup(line->elements[0].item);
763      *(title + strlen(title) - 1) = '\0';   title++;
764     *(title + strlen(title) - 1) = '\0';
765        } else if (line->type == LT_MENUENTRY)
766     title = strdup(line->elements[1].item);
767        else
768     return NULL;
769      return title;      return title;
770  }  }
771    
# Line 601  static void lineInit(struct singleLine * Line 808  static void lineInit(struct singleLine *
808  }  }
809    
810  struct singleLine * lineDup(struct singleLine * line) {  struct singleLine * lineDup(struct singleLine * line) {
     int i;  
811      struct singleLine * newLine = malloc(sizeof(*newLine));      struct singleLine * newLine = malloc(sizeof(*newLine));
812    
813      newLine->indent = strdup(line->indent);      newLine->indent = strdup(line->indent);
# Line 611  struct singleLine * lineDup(struct singl Line 817  struct singleLine * lineDup(struct singl
817      newLine->elements = malloc(sizeof(*newLine->elements) *      newLine->elements = malloc(sizeof(*newLine->elements) *
818         newLine->numElements);         newLine->numElements);
819    
820      for (i = 0; i < newLine->numElements; i++) {      for (int i = 0; i < newLine->numElements; i++) {
821   newLine->elements[i].indent = strdup(line->elements[i].indent);   newLine->elements[i].indent = strdup(line->elements[i].indent);
822   newLine->elements[i].item = strdup(line->elements[i].item);   newLine->elements[i].item = strdup(line->elements[i].item);
823      }      }
# Line 620  struct singleLine * lineDup(struct singl Line 826  struct singleLine * lineDup(struct singl
826  }  }
827    
828  static void lineFree(struct singleLine * line) {  static void lineFree(struct singleLine * line) {
     int i;  
   
829      if (line->indent) free(line->indent);      if (line->indent) free(line->indent);
830    
831      for (i = 0; i < line->numElements; i++) {      for (int i = 0; i < line->numElements; i++) {
832   free(line->elements[i].item);   free(line->elements[i].item);
833   free(line->elements[i].indent);   free(line->elements[i].indent);
834      }      }
# Line 635  static void lineFree(struct singleLine * Line 839  static void lineFree(struct singleLine *
839    
840  static int lineWrite(FILE * out, struct singleLine * line,  static int lineWrite(FILE * out, struct singleLine * line,
841       struct configFileInfo * cfi) {       struct configFileInfo * cfi) {
     int i;  
   
842      if (fprintf(out, "%s", line->indent) == -1) return -1;      if (fprintf(out, "%s", line->indent) == -1) return -1;
843    
844      for (i = 0; i < line->numElements; i++) {      for (int i = 0; i < line->numElements; i++) {
845     /* Need to handle this, because we strip the quotes from
846     * menuentry when read it. */
847     if (line->type == LT_MENUENTRY && i == 1) {
848        if(!isquote(*line->elements[i].item))
849     fprintf(out, "\'%s\'", line->elements[i].item);
850        else
851     fprintf(out, "%s", line->elements[i].item);
852        fprintf(out, "%s", line->elements[i].indent);
853    
854        continue;
855     }
856    
857   if (i == 1 && line->type == LT_KERNELARGS && cfi->argsInQuotes)   if (i == 1 && line->type == LT_KERNELARGS && cfi->argsInQuotes)
858      if (fputc('"', out) == EOF) return -1;      if (fputc('"', out) == EOF) return -1;
859    
# Line 733  static int getNextLine(char ** bufPtr, s Line 947  static int getNextLine(char ** bufPtr, s
947      if (*line->elements[0].item == '#') {      if (*line->elements[0].item == '#') {
948   char * fullLine;   char * fullLine;
949   int len;   int len;
  int i;  
950    
951   len = strlen(line->indent);   len = strlen(line->indent);
952   for (i = 0; i < line->numElements; i++)   for (int i = 0; i < line->numElements; i++)
953      len += strlen(line->elements[i].item) +      len += strlen(line->elements[i].item) +
954     strlen(line->elements[i].indent);     strlen(line->elements[i].indent);
955    
# Line 745  static int getNextLine(char ** bufPtr, s Line 958  static int getNextLine(char ** bufPtr, s
958   free(line->indent);   free(line->indent);
959   line->indent = fullLine;   line->indent = fullLine;
960    
961   for (i = 0; i < line->numElements; i++) {   for (int i = 0; i < line->numElements; i++) {
962      strcat(fullLine, line->elements[i].item);      strcat(fullLine, line->elements[i].item);
963      strcat(fullLine, line->elements[i].indent);      strcat(fullLine, line->elements[i].indent);
964      free(line->elements[i].item);      free(line->elements[i].item);
# Line 764  static int getNextLine(char ** bufPtr, s Line 977  static int getNextLine(char ** bufPtr, s
977   * elements up more   * elements up more
978   */   */
979   if (!isspace(kw->separatorChar)) {   if (!isspace(kw->separatorChar)) {
     int i;  
980      char indent[2] = "";      char indent[2] = "";
981      indent[0] = kw->separatorChar;      indent[0] = kw->separatorChar;
982      for (i = 1; i < line->numElements; i++) {      for (int i = 1; i < line->numElements; i++) {
983   char *p;   char *p;
  int j;  
984   int numNewElements;   int numNewElements;
985    
986   numNewElements = 0;   numNewElements = 0;
# Line 785  static int getNextLine(char ** bufPtr, s Line 996  static int getNextLine(char ** bufPtr, s
996      sizeof(*line->elements) * elementsAlloced);      sizeof(*line->elements) * elementsAlloced);
997   }   }
998    
999   for (j = line->numElements; j > i; j--) {   for (int j = line->numElements; j > i; j--) {
1000   line->elements[j + numNewElements] = line->elements[j];   line->elements[j + numNewElements] = line->elements[j];
1001   }   }
1002   line->numElements += numNewElements;   line->numElements += numNewElements;
# Line 798  static int getNextLine(char ** bufPtr, s Line 1009  static int getNextLine(char ** bufPtr, s
1009   break;   break;
1010   }   }
1011    
1012   free(line->elements[i].indent);   line->elements[i + 1].indent = line->elements[i].indent;
1013   line->elements[i].indent = strdup(indent);   line->elements[i].indent = strdup(indent);
1014   *p++ = '\0';   *p++ = '\0';
1015   i++;   i++;
1016   line->elements[i].item = strdup(p);   line->elements[i].item = strdup(p);
  line->elements[i].indent = strdup("");  
  p = line->elements[i].item;  
1017   }   }
1018      }      }
1019   }   }
# Line 825  static struct grubConfig * readConfig(co Line 1034  static struct grubConfig * readConfig(co
1034      struct singleLine * last = NULL, * line, * defaultLine = NULL;      struct singleLine * last = NULL, * line, * defaultLine = NULL;
1035      char * end;      char * end;
1036      struct singleEntry * entry = NULL;      struct singleEntry * entry = NULL;
1037      int i, len;      int len;
1038      char * buf;      char * buf;
1039    
1040      if (!strcmp(inName, "-")) {      if (inName == NULL) {
1041            printf("Could not find bootloader configuration\n");
1042            exit(1);
1043        } else if (!strcmp(inName, "-")) {
1044   in = 0;   in = 0;
1045      } else {      } else {
1046   if ((in = open(inName, O_RDONLY)) < 0) {   if ((in = open(inName, O_RDONLY)) < 0) {
# Line 871  static struct grubConfig * readConfig(co Line 1083  static struct grubConfig * readConfig(co
1083      cfg->secondaryIndent = strdup(line->indent);      cfg->secondaryIndent = strdup(line->indent);
1084   }   }
1085    
1086   if (isEntryStart(line, cfi)) {   if (isEntryStart(line, cfi) || (cfg->entries && !sawEntry)) {
1087      sawEntry = 1;      sawEntry = 1;
1088      if (!entry) {      if (!entry) {
1089   cfg->entries = malloc(sizeof(*entry));   cfg->entries = malloc(sizeof(*entry));
# Line 888  static struct grubConfig * readConfig(co Line 1100  static struct grubConfig * readConfig(co
1100   }   }
1101    
1102   if (line->type == LT_SET_VARIABLE) {   if (line->type == LT_SET_VARIABLE) {
     int i;  
1103      dbgPrintf("found 'set' command (%d elements): ", line->numElements);      dbgPrintf("found 'set' command (%d elements): ", line->numElements);
1104      dbgPrintf("%s", line->indent);      dbgPrintf("%s", line->indent);
1105      for (i = 0; i < line->numElements; i++)      for (int i = 0; i < line->numElements; i++)
1106   dbgPrintf("%s\"%s\"", line->elements[i].indent, line->elements[i].item);   dbgPrintf("\"%s\"%s", line->elements[i].item, line->elements[i].indent);
1107      dbgPrintf("\n");      dbgPrintf("\n");
1108      struct keywordTypes *kwType = getKeywordByType(LT_DEFAULT, cfi);      struct keywordTypes *kwType = getKeywordByType(LT_DEFAULT, cfi);
1109      if (kwType && line->numElements == 3 &&      if (kwType && line->numElements == 3 &&
1110      !strcmp(line->elements[1].item, kwType->key)) {      !strcmp(line->elements[1].item, kwType->key) &&
1111        !is_special_grub2_variable(line->elements[2].item)) {
1112   dbgPrintf("Line sets default config\n");   dbgPrintf("Line sets default config\n");
1113   cfg->flags &= ~GRUB_CONFIG_NO_DEFAULT;   cfg->flags &= ~GRUB_CONFIG_NO_DEFAULT;
1114   defaultLine = line;   defaultLine = line;
# Line 905  static struct grubConfig * readConfig(co Line 1117  static struct grubConfig * readConfig(co
1117      cfg->flags &= ~GRUB_CONFIG_NO_DEFAULT;      cfg->flags &= ~GRUB_CONFIG_NO_DEFAULT;
1118      defaultLine = line;      defaultLine = line;
1119    
1120          } else if (line->type == LT_KERNEL) {          } else if (iskernel(line->type)) {
1121      /* if by some freak chance this is multiboot and the "module"      /* if by some freak chance this is multiboot and the "module"
1122       * lines came earlier in the template, make sure to use LT_HYPER       * lines came earlier in the template, make sure to use LT_HYPER
1123       * instead of LT_KERNEL now       * instead of LT_KERNEL now
# Line 919  static struct grubConfig * readConfig(co Line 1131  static struct grubConfig * readConfig(co
1131       * This only applies to grub, but that's the only place we       * This only applies to grub, but that's the only place we
1132       * should find LT_MBMODULE lines anyway.       * should find LT_MBMODULE lines anyway.
1133       */       */
1134      struct singleLine * l;      for (struct singleLine *l = entry->lines; l; l = l->next) {
     for (l = entry->lines; l; l = l->next) {  
1135   if (l->type == LT_HYPER)   if (l->type == LT_HYPER)
1136      break;      break;
1137   else if (l->type == LT_KERNEL) {   else if (iskernel(l->type)) {
1138      l->type = LT_HYPER;      l->type = LT_HYPER;
1139      break;      break;
1140   }   }
# Line 940  static struct grubConfig * readConfig(co Line 1151  static struct grubConfig * readConfig(co
1151   } else if (line->type == LT_TITLE && line->numElements > 1) {   } else if (line->type == LT_TITLE && line->numElements > 1) {
1152      /* make the title a single argument (undoing our parsing) */      /* make the title a single argument (undoing our parsing) */
1153      len = 0;      len = 0;
1154      for (i = 1; i < line->numElements; i++) {      for (int i = 1; i < line->numElements; i++) {
1155   len += strlen(line->elements[i].item);   len += strlen(line->elements[i].item);
1156   len += strlen(line->elements[i].indent);   len += strlen(line->elements[i].indent);
1157      }      }
1158      buf = malloc(len + 1);      buf = malloc(len + 1);
1159      *buf = '\0';      *buf = '\0';
1160    
1161      for (i = 1; i < line->numElements; i++) {      for (int i = 1; i < line->numElements; i++) {
1162   strcat(buf, line->elements[i].item);   strcat(buf, line->elements[i].item);
1163   free(line->elements[i].item);   free(line->elements[i].item);
1164    
# Line 961  static struct grubConfig * readConfig(co Line 1172  static struct grubConfig * readConfig(co
1172      line->elements[line->numElements - 1].indent;      line->elements[line->numElements - 1].indent;
1173      line->elements[1].item = buf;      line->elements[1].item = buf;
1174      line->numElements = 2;      line->numElements = 2;
1175     } else if (line->type == LT_MENUENTRY && line->numElements > 3) {
1176        /* let --remove-kernel="TITLE=what" work */
1177        len = 0;
1178        char *extras;
1179        char *title;
1180    
1181        for (int i = 1; i < line->numElements; i++) {
1182     len += strlen(line->elements[i].item);
1183     len += strlen(line->elements[i].indent);
1184        }
1185        buf = malloc(len + 1);
1186        *buf = '\0';
1187    
1188        /* allocate mem for extra flags. */
1189        extras = malloc(len + 1);
1190        *extras = '\0';
1191    
1192        /* get title. */
1193        for (int i = 0; i < line->numElements; i++) {
1194     if (!strcmp(line->elements[i].item, "menuentry"))
1195        continue;
1196     if (isquote(*line->elements[i].item))
1197        title = line->elements[i].item + 1;
1198     else
1199        title = line->elements[i].item;
1200    
1201     len = strlen(title);
1202            if (isquote(title[len-1])) {
1203        strncat(buf, title,len-1);
1204        break;
1205     } else {
1206        strcat(buf, title);
1207        strcat(buf, line->elements[i].indent);
1208     }
1209        }
1210    
1211        /* get extras */
1212        int count = 0;
1213        for (int i = 0; i < line->numElements; i++) {
1214     if (count >= 2) {
1215        strcat(extras, line->elements[i].item);
1216        strcat(extras, line->elements[i].indent);
1217     }
1218    
1219     if (!strcmp(line->elements[i].item, "menuentry"))
1220        continue;
1221    
1222     /* count ' or ", there should be two in menuentry line. */
1223     if (isquote(*line->elements[i].item))
1224        count++;
1225    
1226     len = strlen(line->elements[i].item);
1227    
1228     if (isquote(line->elements[i].item[len -1]))
1229        count++;
1230    
1231     /* ok, we get the final ' or ", others are extras. */
1232                }
1233        line->elements[1].indent =
1234     line->elements[line->numElements - 2].indent;
1235        line->elements[1].item = buf;
1236        line->elements[2].indent =
1237     line->elements[line->numElements - 2].indent;
1238        line->elements[2].item = extras;
1239        line->numElements = 3;
1240   } else if (line->type == LT_KERNELARGS && cfi->argsInQuotes) {   } else if (line->type == LT_KERNELARGS && cfi->argsInQuotes) {
1241      /* Strip off any " which may be present; they'll be put back      /* Strip off any " which may be present; they'll be put back
1242         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 970  static struct grubConfig * readConfig(co Line 1245  static struct grubConfig * readConfig(co
1245      if (line->numElements >= 2) {      if (line->numElements >= 2) {
1246   int last, len;   int last, len;
1247    
1248   if (*line->elements[1].item == '"')   if (isquote(*line->elements[1].item))
1249      memmove(line->elements[1].item, line->elements[1].item + 1,      memmove(line->elements[1].item, line->elements[1].item + 1,
1250      strlen(line->elements[1].item + 1) + 1);      strlen(line->elements[1].item + 1) + 1);
1251    
1252   last = line->numElements - 1;   last = line->numElements - 1;
1253   len = strlen(line->elements[last].item) - 1;   len = strlen(line->elements[last].item) - 1;
1254   if (line->elements[last].item[len] == '"')   if (isquote(line->elements[last].item[len]))
1255      line->elements[last].item[len] = '\0';      line->elements[last].item[len] = '\0';
1256      }      }
1257   }   }
# Line 1035  static struct grubConfig * readConfig(co Line 1310  static struct grubConfig * readConfig(co
1310    
1311      dbgPrintf("defaultLine is %s\n", defaultLine ? "set" : "unset");      dbgPrintf("defaultLine is %s\n", defaultLine ? "set" : "unset");
1312      if (defaultLine) {      if (defaultLine) {
1313   if (cfi->defaultIsVariable) {          if (defaultLine->numElements > 2 &&
1314        cfi->defaultSupportSaved &&
1315        !strncmp(defaultLine->elements[2].item,"\"${saved_entry}\"", 16)) {
1316     cfg->cfi->defaultIsSaved = 1;
1317     cfg->defaultImage = DEFAULT_SAVED_GRUB2;
1318     if (cfg->cfi->getEnv) {
1319        char *defTitle = cfi->getEnv(cfg->cfi, "saved_entry");
1320        if (defTitle) {
1321     int index = 0;
1322     entry = findEntryByTitle(cfg, defTitle, &index);
1323     if (entry)
1324        cfg->defaultImage = index;
1325        }
1326     }
1327     } else if (cfi->defaultIsVariable) {
1328      char *value = defaultLine->elements[2].item;      char *value = defaultLine->elements[2].item;
1329      while (*value && (*value == '"' || *value == '\'' ||      while (*value && (*value == '"' || *value == '\'' ||
1330      *value == ' ' || *value == '\t'))      *value == ' ' || *value == '\t'))
# Line 1052  static struct grubConfig * readConfig(co Line 1341  static struct grubConfig * readConfig(co
1341      cfg->defaultImage = strtol(defaultLine->elements[1].item, &end, 10);      cfg->defaultImage = strtol(defaultLine->elements[1].item, &end, 10);
1342      if (*end) cfg->defaultImage = -1;      if (*end) cfg->defaultImage = -1;
1343   } else if (defaultLine->numElements >= 2) {   } else if (defaultLine->numElements >= 2) {
1344      i = 0;      int i = 0;
1345      while ((entry = findEntryByIndex(cfg, i))) {      while ((entry = findEntryByIndex(cfg, i))) {
1346   for (line = entry->lines; line; line = line->next)   for (line = entry->lines; line; line = line->next)
1347      if (line->type == LT_TITLE) break;      if (line->type == LT_TITLE) break;
# Line 1075  static struct grubConfig * readConfig(co Line 1364  static struct grubConfig * readConfig(co
1364          cfg->defaultImage = -1;          cfg->defaultImage = -1;
1365      }      }
1366   }   }
1367        } else if (cfg->cfi->defaultIsSaved && cfg->cfi->getEnv) {
1368     char *defTitle = cfi->getEnv(cfg->cfi, "saved_entry");
1369     if (defTitle) {
1370        int index = 0;
1371        entry = findEntryByTitle(cfg, defTitle, &index);
1372        if (entry)
1373     cfg->defaultImage = index;
1374     }
1375      } else {      } else {
1376          cfg->defaultImage = 0;          cfg->defaultImage = 0;
1377      }      }
# Line 1092  static void writeDefault(FILE * out, cha Line 1389  static void writeDefault(FILE * out, cha
1389    
1390      if (cfg->defaultImage == DEFAULT_SAVED)      if (cfg->defaultImage == DEFAULT_SAVED)
1391   fprintf(out, "%sdefault%ssaved\n", indent, separator);   fprintf(out, "%sdefault%ssaved\n", indent, separator);
1392      else if (cfg->defaultImage > -1) {      else if (cfg->cfi->defaultIsSaved) {
1393     fprintf(out, "%sset default=\"${saved_entry}\"\n", indent);
1394     if (cfg->defaultImage >= 0 && cfg->cfi->setEnv) {
1395        char *title;
1396        entry = findEntryByIndex(cfg, cfg->defaultImage);
1397        line = getLineByType(LT_MENUENTRY, entry->lines);
1398        if (!line)
1399     line = getLineByType(LT_TITLE, entry->lines);
1400        if (line) {
1401     title = extractTitle(line);
1402     if (title)
1403        cfg->cfi->setEnv(cfg->cfi, "saved_entry", title);
1404        }
1405     }
1406        } else if (cfg->defaultImage > -1) {
1407   if (cfg->cfi->defaultIsIndex) {   if (cfg->cfi->defaultIsIndex) {
1408      if (cfg->cfi->defaultIsVariable) {      if (cfg->cfi->defaultIsVariable) {
1409          fprintf(out, "%sset default=\"%d\"\n", indent,          fprintf(out, "%sset default=\"%d\"\n", indent,
# Line 1152  static int writeConfig(struct grubConfig Line 1463  static int writeConfig(struct grubConfig
1463    
1464      /* most likely the symlink is relative, so change our      /* most likely the symlink is relative, so change our
1465         directory to the dir of the symlink */         directory to the dir of the symlink */
1466              rc = chdir(dirname(strdupa(outName)));      char *dir = strdupa(outName);
1467        rc = chdir(dirname(dir));
1468      do {      do {
1469   buf = alloca(len + 1);   buf = alloca(len + 1);
1470   rc = readlink(basename(outName), buf, len);   rc = readlink(basename(outName), buf, len);
# Line 1194  static int writeConfig(struct grubConfig Line 1506  static int writeConfig(struct grubConfig
1506      while (line) {      while (line) {
1507          if (line->type == LT_SET_VARIABLE && defaultKw &&          if (line->type == LT_SET_VARIABLE && defaultKw &&
1508   line->numElements == 3 &&   line->numElements == 3 &&
1509   !strcmp(line->elements[1].item, defaultKw->key)) {   !strcmp(line->elements[1].item, defaultKw->key) &&
1510     !is_special_grub2_variable(line->elements[2].item)) {
1511      writeDefault(out, line->indent, line->elements[0].indent, cfg);      writeDefault(out, line->indent, line->elements[0].indent, cfg);
1512      needs &= ~MAIN_DEFAULT;      needs &= ~MAIN_DEFAULT;
1513   } else if (line->type == LT_DEFAULT) {   } else if (line->type == LT_DEFAULT) {
# Line 1290  static char *findDiskForRoot() Line 1603  static char *findDiskForRoot()
1603      buf[rc] = '\0';      buf[rc] = '\0';
1604      chptr = buf;      chptr = buf;
1605    
1606        char *foundanswer = NULL;
1607    
1608      while (chptr && chptr != buf+rc) {      while (chptr && chptr != buf+rc) {
1609          devname = chptr;          devname = chptr;
1610    
# Line 1317  static char *findDiskForRoot() Line 1632  static char *findDiskForRoot()
1632           * for '/' obviously.           * for '/' obviously.
1633           */           */
1634          if (*(++chptr) == '/' && *(++chptr) == ' ') {          if (*(++chptr) == '/' && *(++chptr) == ' ') {
1635              /*              /* remember the last / entry in mtab */
1636               * 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);  
1637          }          }
1638    
1639          /* Next line */          /* Next line */
# Line 1332  static char *findDiskForRoot() Line 1642  static char *findDiskForRoot()
1642              chptr++;              chptr++;
1643      }      }
1644    
1645        /* Return the last / entry found */
1646        if (foundanswer) {
1647            chptr = strchr(foundanswer, ' ');
1648            *chptr = '\0';
1649            return strdup(foundanswer);
1650        }
1651    
1652      return NULL;      return NULL;
1653  }  }
1654    
1655    void printEntry(struct singleEntry * entry, FILE *f) {
1656        int i;
1657        struct singleLine * line;
1658    
1659        for (line = entry->lines; line; line = line->next) {
1660     log_message(f, "DBG: %s", line->indent);
1661     for (i = 0; i < line->numElements; i++) {
1662        /* Need to handle this, because we strip the quotes from
1663         * menuentry when read it. */
1664        if (line->type == LT_MENUENTRY && i == 1) {
1665     if(!isquote(*line->elements[i].item))
1666        log_message(f, "\'%s\'", line->elements[i].item);
1667     else
1668        log_message(f, "%s", line->elements[i].item);
1669     log_message(f, "%s", line->elements[i].indent);
1670    
1671     continue;
1672        }
1673        
1674        log_message(f, "%s%s",
1675        line->elements[i].item, line->elements[i].indent);
1676     }
1677     log_message(f, "\n");
1678        }
1679    }
1680    
1681    void notSuitablePrintf(struct singleEntry * entry, int okay, const char *fmt, ...)
1682    {
1683        static int once;
1684        va_list argp, argq;
1685    
1686        va_start(argp, fmt);
1687    
1688        va_copy(argq, argp);
1689        if (!once) {
1690     log_time(NULL);
1691     log_message(NULL, "command line: %s\n", saved_command_line);
1692        }
1693        log_message(NULL, "DBG: Image entry %s: ", okay ? "succeeded" : "failed");
1694        log_vmessage(NULL, fmt, argq);
1695    
1696        printEntry(entry, NULL);
1697        va_end(argq);
1698    
1699        if (!debug) {
1700     once = 1;
1701         va_end(argp);
1702     return;
1703        }
1704    
1705        if (okay) {
1706     va_end(argp);
1707     return;
1708        }
1709    
1710        if (!once)
1711     log_message(stderr, "DBG: command line: %s\n", saved_command_line);
1712        once = 1;
1713        fprintf(stderr, "DBG: Image entry failed: ");
1714        vfprintf(stderr, fmt, argp);
1715        printEntry(entry, stderr);
1716        va_end(argp);
1717    }
1718    
1719    #define beginswith(s, c) ((s) && (s)[0] == (c))
1720    
1721    static int endswith(const char *s, char c)
1722    {
1723     int slen;
1724    
1725     if (!s || !s[0])
1726     return 0;
1727     slen = strlen(s) - 1;
1728    
1729     return s[slen] == c;
1730    }
1731    
1732  int suitableImage(struct singleEntry * entry, const char * bootPrefix,  int suitableImage(struct singleEntry * entry, const char * bootPrefix,
1733    int skipRemoved, int flags) {    int skipRemoved, int flags) {
1734      struct singleLine * line;      struct singleLine * line;
# Line 1344  int suitableImage(struct singleEntry * e Line 1738  int suitableImage(struct singleEntry * e
1738      char * rootspec;      char * rootspec;
1739      char * rootdev;      char * rootdev;
1740    
1741      if (skipRemoved && entry->skip) return 0;      if (skipRemoved && entry->skip) {
1742     notSuitablePrintf(entry, 0, "marked to skip\n");
1743     return 0;
1744        }
1745    
1746      line = getLineByType(LT_KERNEL|LT_HYPER, entry->lines);      line = getLineByType(LT_KERNEL|LT_HYPER|LT_KERNEL_EFI, entry->lines);
1747      if (!line || line->numElements < 2) return 0;      if (!line) {
1748     notSuitablePrintf(entry, 0, "no line found\n");
1749     return 0;
1750        }
1751        if (line->numElements < 2) {
1752     notSuitablePrintf(entry, 0, "line has only %d elements\n",
1753        line->numElements);
1754     return 0;
1755        }
1756    
1757      if (flags & GRUBBY_BADIMAGE_OKAY) return 1;      if (flags & GRUBBY_BADIMAGE_OKAY) {
1758        notSuitablePrintf(entry, 1, "\n");
1759        return 1;
1760        }
1761    
1762      fullName = alloca(strlen(bootPrefix) +      fullName = alloca(strlen(bootPrefix) +
1763        strlen(line->elements[1].item) + 1);        strlen(line->elements[1].item) + 1);
1764      rootspec = getRootSpecifier(line->elements[1].item);      rootspec = getRootSpecifier(line->elements[1].item);
1765      sprintf(fullName, "%s%s", bootPrefix,      int rootspec_offset = rootspec ? strlen(rootspec) : 0;
1766              line->elements[1].item + (rootspec ? strlen(rootspec) : 0));      int hasslash = endswith(bootPrefix, '/') ||
1767      if (access(fullName, R_OK)) return 0;       beginswith(line->elements[1].item + rootspec_offset, '/');
1768        sprintf(fullName, "%s%s%s", bootPrefix, hasslash ? "" : "/",
1769                line->elements[1].item + rootspec_offset);
1770        if (access(fullName, R_OK)) {
1771     notSuitablePrintf(entry, 0, "access to %s failed\n", fullName);
1772     return 0;
1773        }
1774      for (i = 2; i < line->numElements; i++)      for (i = 2; i < line->numElements; i++)
1775   if (!strncasecmp(line->elements[i].item, "root=", 5)) break;   if (!strncasecmp(line->elements[i].item, "root=", 5)) break;
1776      if (i < line->numElements) {      if (i < line->numElements) {
# Line 1375  int suitableImage(struct singleEntry * e Line 1788  int suitableImage(struct singleEntry * e
1788      line = getLineByType(LT_KERNELARGS|LT_MBMODULE, entry->lines);      line = getLineByType(LT_KERNELARGS|LT_MBMODULE, entry->lines);
1789    
1790              /* failed to find one */              /* failed to find one */
1791              if (!line) return 0;              if (!line) {
1792     notSuitablePrintf(entry, 0, "no line found\n");
1793     return 0;
1794                }
1795    
1796      for (i = 1; i < line->numElements; i++)      for (i = 1; i < line->numElements; i++)
1797          if (!strncasecmp(line->elements[i].item, "root=", 5)) break;          if (!strncasecmp(line->elements[i].item, "root=", 5)) break;
1798      if (i < line->numElements)      if (i < line->numElements)
1799          dev = line->elements[i].item + 5;          dev = line->elements[i].item + 5;
1800      else {      else {
1801     notSuitablePrintf(entry, 0, "no root= entry found\n");
1802   /* it failed too...  can't find root= */   /* it failed too...  can't find root= */
1803          return 0;          return 0;
1804              }              }
# Line 1389  int suitableImage(struct singleEntry * e Line 1806  int suitableImage(struct singleEntry * e
1806      }      }
1807    
1808      dev = getpathbyspec(dev);      dev = getpathbyspec(dev);
1809      if (!dev)      if (!getpathbyspec(dev)) {
1810            notSuitablePrintf(entry, 0, "can't find blkid entry for %s\n", dev);
1811          return 0;          return 0;
1812        } else
1813     dev = getpathbyspec(dev);
1814    
1815      rootdev = findDiskForRoot();      rootdev = findDiskForRoot();
1816      if (!rootdev)      if (!rootdev) {
1817            notSuitablePrintf(entry, 0, "can't find root device\n");
1818   return 0;   return 0;
1819        }
1820    
1821      if (!getuuidbydev(rootdev) || !getuuidbydev(dev)) {      if (!getuuidbydev(rootdev) || !getuuidbydev(dev)) {
1822            notSuitablePrintf(entry, 0, "uuid missing: rootdev %s, dev %s\n",
1823     getuuidbydev(rootdev), getuuidbydev(dev));
1824          free(rootdev);          free(rootdev);
1825          return 0;          return 0;
1826      }      }
1827    
1828      if (strcmp(getuuidbydev(rootdev), getuuidbydev(dev))) {      if (strcmp(getuuidbydev(rootdev), getuuidbydev(dev))) {
1829            notSuitablePrintf(entry, 0, "uuid mismatch: rootdev %s, dev %s\n",
1830     getuuidbydev(rootdev), getuuidbydev(dev));
1831   free(rootdev);   free(rootdev);
1832          return 0;          return 0;
1833      }      }
1834    
1835      free(rootdev);      free(rootdev);
1836        notSuitablePrintf(entry, 1, "\n");
1837    
1838      return 1;      return 1;
1839  }  }
# Line 1450  struct singleEntry * findEntryByPath(str Line 1877  struct singleEntry * findEntryByPath(str
1877   entry = findEntryByIndex(config, indexVars[i]);   entry = findEntryByIndex(config, indexVars[i]);
1878   if (!entry) return NULL;   if (!entry) return NULL;
1879    
1880   line = getLineByType(LT_KERNEL|LT_HYPER, entry->lines);   line = getLineByType(LT_KERNEL|LT_HYPER|LT_KERNEL_EFI, entry->lines);
1881   if (!line) return NULL;   if (!line) return NULL;
1882    
1883   if (index) *index = indexVars[i];   if (index) *index = indexVars[i];
# Line 1488  struct singleEntry * findEntryByPath(str Line 1915  struct singleEntry * findEntryByPath(str
1915    
1916   if (!strncmp(kernel, "TITLE=", 6)) {   if (!strncmp(kernel, "TITLE=", 6)) {
1917      prefix = "";      prefix = "";
1918      checkType = LT_TITLE;      checkType = LT_TITLE|LT_MENUENTRY;
1919      kernel += 6;      kernel += 6;
1920   }   }
1921    
# Line 1499  struct singleEntry * findEntryByPath(str Line 1926  struct singleEntry * findEntryByPath(str
1926    
1927      /* check all the lines matching checkType */      /* check all the lines matching checkType */
1928      for (line = entry->lines; line; line = line->next) {      for (line = entry->lines; line; line = line->next) {
1929   line = getLineByType(entry->multiboot && checkType == LT_KERNEL ?   enum lineType_e ct = checkType;
1930       LT_KERNEL|LT_MBMODULE|LT_HYPER :   if (entry->multiboot && checkType == LT_KERNEL)
1931       checkType, line);      ct = LT_KERNEL|LT_KERNEL_EFI|LT_MBMODULE|LT_HYPER;
1932   if (!line) break;  /* not found in this entry */   else if (checkType & LT_KERNEL)
1933        ct = checkType | LT_KERNEL_EFI;
1934     line = getLineByType(ct, line);
1935     if (!line)
1936        break;  /* not found in this entry */
1937    
1938   if (line && line->numElements >= 2) {   if (line && line->type != LT_MENUENTRY &&
1939     line->numElements >= 2) {
1940      rootspec = getRootSpecifier(line->elements[1].item);      rootspec = getRootSpecifier(line->elements[1].item);
1941      if (!strcmp(line->elements[1].item +      if (!strcmp(line->elements[1].item +
1942   ((rootspec != NULL) ? strlen(rootspec) : 0),   ((rootspec != NULL) ? strlen(rootspec) : 0),
1943   kernel + strlen(prefix)))   kernel + strlen(prefix)))
1944   break;   break;
1945   }   }
1946     if(line->type == LT_MENUENTRY &&
1947     !strcmp(line->elements[1].item, kernel))
1948        break;
1949      }      }
1950    
1951      /* make sure this entry has a kernel identifier; this skips      /* make sure this entry has a kernel identifier; this skips
1952       * non-Linux boot entries (could find netbsd etc, though, which is       * non-Linux boot entries (could find netbsd etc, though, which is
1953       * unfortunate)       * unfortunate)
1954       */       */
1955      if (line && getLineByType(LT_KERNEL|LT_HYPER, entry->lines))      if (line && getLineByType(LT_KERNEL|LT_HYPER|LT_KERNEL_EFI, entry->lines))
1956   break; /* found 'im! */   break; /* found 'im! */
1957   }   }
1958    
# Line 1527  struct singleEntry * findEntryByPath(str Line 1962  struct singleEntry * findEntryByPath(str
1962      return entry;      return entry;
1963  }  }
1964    
1965    struct singleEntry * findEntryByTitle(struct grubConfig * cfg, char *title,
1966          int * index) {
1967        struct singleEntry * entry;
1968        struct singleLine * line;
1969        int i;
1970        char * newtitle;
1971    
1972        for (i = 0, entry = cfg->entries; entry; entry = entry->next, i++) {
1973     if (index && i < *index)
1974        continue;
1975     line = getLineByType(LT_TITLE, entry->lines);
1976     if (!line)
1977        line = getLineByType(LT_MENUENTRY, entry->lines);
1978     if (!line)
1979        continue;
1980     newtitle = grub2ExtractTitle(line);
1981     if (!newtitle)
1982        continue;
1983     if (!strcmp(title, newtitle))
1984        break;
1985        }
1986    
1987        if (!entry)
1988     return NULL;
1989    
1990        if (index)
1991     *index = i;
1992        return entry;
1993    }
1994    
1995  struct singleEntry * findEntryByIndex(struct grubConfig * cfg, int index) {  struct singleEntry * findEntryByIndex(struct grubConfig * cfg, int index) {
1996      struct singleEntry * entry;      struct singleEntry * entry;
1997    
# Line 1549  struct singleEntry * findTemplate(struct Line 2014  struct singleEntry * findTemplate(struct
2014      struct singleEntry * entry, * entry2;      struct singleEntry * entry, * entry2;
2015      int index;      int index;
2016    
2017      if (cfg->defaultImage > -1) {      if (cfg->cfi->defaultIsSaved) {
2018     if (cfg->cfi->getEnv) {
2019        char *defTitle = cfg->cfi->getEnv(cfg->cfi, "saved_entry");
2020        if (defTitle) {
2021     int index = 0;
2022     entry = findEntryByTitle(cfg, defTitle, &index);
2023        }
2024     }
2025        } else if (cfg->defaultImage > -1) {
2026   entry = findEntryByIndex(cfg, cfg->defaultImage);   entry = findEntryByIndex(cfg, cfg->defaultImage);
2027   if (entry && suitableImage(entry, prefix, skipRemoved, flags)) {   if (entry && suitableImage(entry, prefix, skipRemoved, flags)) {
2028      if (indexPtr) *indexPtr = cfg->defaultImage;      if (indexPtr) *indexPtr = cfg->defaultImage;
# Line 1602  void markRemovedImage(struct grubConfig Line 2075  void markRemovedImage(struct grubConfig
2075        const char * prefix) {        const char * prefix) {
2076      struct singleEntry * entry;      struct singleEntry * entry;
2077    
2078      if (!image) return;      if (!image)
2079     return;
2080    
2081        /* check and see if we're removing the default image */
2082        if (isdigit(*image)) {
2083     entry = findEntryByPath(cfg, image, prefix, NULL);
2084     if(entry)
2085        entry->skip = 1;
2086     return;
2087        }
2088    
2089      while ((entry = findEntryByPath(cfg, image, prefix, NULL)))      while ((entry = findEntryByPath(cfg, image, prefix, NULL)))
2090   entry->skip = 1;   entry->skip = 1;
# Line 1610  void markRemovedImage(struct grubConfig Line 2092  void markRemovedImage(struct grubConfig
2092    
2093  void setDefaultImage(struct grubConfig * config, int hasNew,  void setDefaultImage(struct grubConfig * config, int hasNew,
2094       const char * defaultKernelPath, int newIsDefault,       const char * defaultKernelPath, int newIsDefault,
2095       const char * prefix, int flags) {       const char * prefix, int flags, int index) {
2096      struct singleEntry * entry, * entry2, * newDefault;      struct singleEntry * entry, * entry2, * newDefault;
2097      int i, j;      int i, j;
2098    
2099      if (newIsDefault) {      if (newIsDefault) {
2100   config->defaultImage = 0;   config->defaultImage = 0;
2101   return;   return;
2102        } else if ((index >= 0) && config->cfi->defaultIsIndex) {
2103     if (findEntryByIndex(config, index))
2104        config->defaultImage = index;
2105     else
2106        config->defaultImage = -1;
2107     return;
2108      } else if (defaultKernelPath) {      } else if (defaultKernelPath) {
2109   i = 0;   i = 0;
2110   if (findEntryByPath(config, defaultKernelPath, prefix, &i)) {   if (findEntryByPath(config, defaultKernelPath, prefix, &i)) {
# Line 1629  void setDefaultImage(struct grubConfig * Line 2117  void setDefaultImage(struct grubConfig *
2117    
2118      /* 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
2119         changes */         changes */
2120      if (config->defaultImage == DEFAULT_SAVED)      if ((config->defaultImage == DEFAULT_SAVED) ||
2121     (config->defaultImage == DEFAULT_SAVED_GRUB2))
2122        /* default is set to saved, we don't want to change it */        /* default is set to saved, we don't want to change it */
2123        return;        return;
2124    
# Line 1690  void displayEntry(struct singleEntry * e Line 2179  void displayEntry(struct singleEntry * e
2179    
2180      printf("index=%d\n", index);      printf("index=%d\n", index);
2181    
2182      line = getLineByType(LT_KERNEL|LT_HYPER, entry->lines);      line = getLineByType(LT_KERNEL|LT_HYPER|LT_KERNEL_EFI, entry->lines);
2183      if (!line) {      if (!line) {
2184          printf("non linux entry\n");          printf("non linux entry\n");
2185          return;          return;
2186      }      }
2187    
2188      printf("kernel=%s\n", line->elements[1].item);      if (!strncmp(prefix, line->elements[1].item, strlen(prefix)))
2189     printf("kernel=%s\n", line->elements[1].item);
2190        else
2191     printf("kernel=%s%s\n", prefix, line->elements[1].item);
2192    
2193      if (line->numElements >= 3) {      if (line->numElements >= 3) {
2194   printf("args=\"");   printf("args=\"");
# Line 1752  void displayEntry(struct singleEntry * e Line 2244  void displayEntry(struct singleEntry * e
2244   printf("root=%s\n", s);   printf("root=%s\n", s);
2245      }      }
2246    
2247      line = getLineByType(LT_INITRD, entry->lines);      line = getLineByType(LT_INITRD|LT_INITRD_EFI, entry->lines);
2248    
2249      if (line && line->numElements >= 2) {      if (line && line->numElements >= 2) {
2250   printf("initrd=%s", prefix);   if (!strncmp(prefix, line->elements[1].item, strlen(prefix)))
2251        printf("initrd=");
2252     else
2253        printf("initrd=%s", prefix);
2254    
2255   for (i = 1; i < line->numElements; i++)   for (i = 1; i < line->numElements; i++)
2256      printf("%s%s", line->elements[i].item, line->elements[i].indent);      printf("%s%s", line->elements[i].item, line->elements[i].indent);
2257   printf("\n");   printf("\n");
2258      }      }
2259    
2260        line = getLineByType(LT_TITLE, entry->lines);
2261        if (line) {
2262     printf("title=%s\n", line->elements[1].item);
2263        } else {
2264     char * title;
2265     line = getLineByType(LT_MENUENTRY, entry->lines);
2266     title = grub2ExtractTitle(line);
2267     if (title)
2268        printf("title=%s\n", title);
2269        }
2270    }
2271    
2272    int isSuseSystem(void) {
2273        const char * path;
2274        const static char default_path[] = "/etc/SuSE-release";
2275    
2276        if ((path = getenv("GRUBBY_SUSE_RELEASE")) == NULL)
2277     path = default_path;
2278    
2279        if (!access(path, R_OK))
2280     return 1;
2281        return 0;
2282    }
2283    
2284    int isSuseGrubConf(const char * path) {
2285        FILE * grubConf;
2286        char * line = NULL;
2287        size_t len = 0, res = 0;
2288    
2289        grubConf = fopen(path, "r");
2290        if (!grubConf) {
2291            dbgPrintf("Could not open SuSE configuration file '%s'\n", path);
2292     return 0;
2293        }
2294    
2295        while ((res = getline(&line, &len, grubConf)) != -1) {
2296     if (!strncmp(line, "setup", 5)) {
2297        fclose(grubConf);
2298        free(line);
2299        return 1;
2300     }
2301        }
2302    
2303        dbgPrintf("SuSE configuration file '%s' does not appear to be valid\n",
2304          path);
2305    
2306        fclose(grubConf);
2307        free(line);
2308        return 0;
2309    }
2310    
2311    int suseGrubConfGetLba(const char * path, int * lbaPtr) {
2312        FILE * grubConf;
2313        char * line = NULL;
2314        size_t res = 0, len = 0;
2315    
2316        if (!path) return 1;
2317        if (!lbaPtr) return 1;
2318    
2319        grubConf = fopen(path, "r");
2320        if (!grubConf) return 1;
2321    
2322        while ((res = getline(&line, &len, grubConf)) != -1) {
2323     if (line[res - 1] == '\n')
2324        line[res - 1] = '\0';
2325     else if (len > res)
2326        line[res] = '\0';
2327     else {
2328        line = realloc(line, res + 1);
2329        line[res] = '\0';
2330     }
2331    
2332     if (!strncmp(line, "setup", 5)) {
2333        if (strstr(line, "--force-lba")) {
2334            *lbaPtr = 1;
2335        } else {
2336            *lbaPtr = 0;
2337        }
2338        dbgPrintf("lba: %i\n", *lbaPtr);
2339        break;
2340     }
2341        }
2342    
2343        free(line);
2344        fclose(grubConf);
2345        return 0;
2346    }
2347    
2348    int suseGrubConfGetInstallDevice(const char * path, char ** devicePtr) {
2349        FILE * grubConf;
2350        char * line = NULL;
2351        size_t res = 0, len = 0;
2352        char * lastParamPtr = NULL;
2353        char * secLastParamPtr = NULL;
2354        char installDeviceNumber = '\0';
2355        char * bounds = NULL;
2356    
2357        if (!path) return 1;
2358        if (!devicePtr) return 1;
2359    
2360        grubConf = fopen(path, "r");
2361        if (!grubConf) return 1;
2362    
2363        while ((res = getline(&line, &len, grubConf)) != -1) {
2364     if (strncmp(line, "setup", 5))
2365        continue;
2366    
2367     if (line[res - 1] == '\n')
2368        line[res - 1] = '\0';
2369     else if (len > res)
2370        line[res] = '\0';
2371     else {
2372        line = realloc(line, res + 1);
2373        line[res] = '\0';
2374     }
2375    
2376     lastParamPtr = bounds = line + res;
2377    
2378     /* Last parameter in grub may be an optional IMAGE_DEVICE */
2379     while (!isspace(*lastParamPtr))
2380        lastParamPtr--;
2381     lastParamPtr++;
2382    
2383     secLastParamPtr = lastParamPtr - 2;
2384     dbgPrintf("lastParamPtr: %s\n", lastParamPtr);
2385    
2386     if (lastParamPtr + 3 > bounds) {
2387        dbgPrintf("lastParamPtr going over boundary");
2388        fclose(grubConf);
2389        free(line);
2390        return 1;
2391     }
2392     if (!strncmp(lastParamPtr, "(hd", 3))
2393        lastParamPtr += 3;
2394     dbgPrintf("lastParamPtr: %c\n", *lastParamPtr);
2395    
2396     /*
2397     * Second last parameter will decide wether last parameter is
2398     * an IMAGE_DEVICE or INSTALL_DEVICE
2399     */
2400     while (!isspace(*secLastParamPtr))
2401        secLastParamPtr--;
2402     secLastParamPtr++;
2403    
2404     if (secLastParamPtr + 3 > bounds) {
2405        dbgPrintf("secLastParamPtr going over boundary");
2406        fclose(grubConf);
2407        free(line);
2408        return 1;
2409     }
2410     dbgPrintf("secLastParamPtr: %s\n", secLastParamPtr);
2411     if (!strncmp(secLastParamPtr, "(hd", 3)) {
2412        secLastParamPtr += 3;
2413        dbgPrintf("secLastParamPtr: %c\n", *secLastParamPtr);
2414        installDeviceNumber = *secLastParamPtr;
2415     } else {
2416        installDeviceNumber = *lastParamPtr;
2417     }
2418    
2419     *devicePtr = malloc(6);
2420     snprintf(*devicePtr, 6, "(hd%c)", installDeviceNumber);
2421     dbgPrintf("installDeviceNumber: %c\n", installDeviceNumber);
2422     fclose(grubConf);
2423     free(line);
2424     return 0;
2425        }
2426    
2427        free(line);
2428        fclose(grubConf);
2429        return 1;
2430    }
2431    
2432    int grubGetBootFromDeviceMap(const char * device,
2433         char ** bootPtr) {
2434        FILE * deviceMap;
2435        char * line = NULL;
2436        size_t res = 0, len = 0;
2437        char * devicePtr;
2438        char * bounds = NULL;
2439        const char * path;
2440        const static char default_path[] = "/boot/grub/device.map";
2441    
2442        if (!device) return 1;
2443        if (!bootPtr) return 1;
2444    
2445        if ((path = getenv("GRUBBY_GRUB_DEVICE_MAP")) == NULL)
2446     path = default_path;
2447    
2448        dbgPrintf("opening grub device.map file from: %s\n", path);
2449        deviceMap = fopen(path, "r");
2450        if (!deviceMap)
2451     return 1;
2452    
2453        while ((res = getline(&line, &len, deviceMap)) != -1) {
2454            if (!strncmp(line, "#", 1))
2455        continue;
2456    
2457     if (line[res - 1] == '\n')
2458        line[res - 1] = '\0';
2459     else if (len > res)
2460        line[res] = '\0';
2461     else {
2462        line = realloc(line, res + 1);
2463        line[res] = '\0';
2464     }
2465    
2466     devicePtr = line;
2467     bounds = line + res;
2468    
2469     while ((isspace(*line) && ((devicePtr + 1) <= bounds)))
2470        devicePtr++;
2471     dbgPrintf("device: %s\n", devicePtr);
2472    
2473     if (!strncmp(devicePtr, device, strlen(device))) {
2474        devicePtr += strlen(device);
2475        while (isspace(*devicePtr) && ((devicePtr + 1) <= bounds))
2476            devicePtr++;
2477    
2478        *bootPtr = strdup(devicePtr);
2479        break;
2480     }
2481        }
2482    
2483        free(line);
2484        fclose(deviceMap);
2485        return 0;
2486    }
2487    
2488    int suseGrubConfGetBoot(const char * path, char ** bootPtr) {
2489        char * grubDevice;
2490    
2491        if (suseGrubConfGetInstallDevice(path, &grubDevice))
2492     dbgPrintf("error looking for grub installation device\n");
2493        else
2494     dbgPrintf("grubby installation device: %s\n", grubDevice);
2495    
2496        if (grubGetBootFromDeviceMap(grubDevice, bootPtr))
2497     dbgPrintf("error looking for grub boot device\n");
2498        else
2499     dbgPrintf("grubby boot device: %s\n", *bootPtr);
2500    
2501        free(grubDevice);
2502        return 0;
2503    }
2504    
2505    int parseSuseGrubConf(int * lbaPtr, char ** bootPtr) {
2506        /*
2507         * This SuSE grub configuration file at this location is not your average
2508         * grub configuration file, but instead the grub commands used to setup
2509         * grub on that system.
2510         */
2511        const char * path;
2512        const static char default_path[] = "/etc/grub.conf";
2513    
2514        if ((path = getenv("GRUBBY_SUSE_GRUB_CONF")) == NULL)
2515     path = default_path;
2516    
2517        if (!isSuseGrubConf(path)) return 1;
2518    
2519        if (lbaPtr) {
2520            *lbaPtr = 0;
2521            if (suseGrubConfGetLba(path, lbaPtr))
2522                return 1;
2523        }
2524    
2525        if (bootPtr) {
2526            *bootPtr = NULL;
2527            suseGrubConfGetBoot(path, bootPtr);
2528        }
2529    
2530        return 0;
2531  }  }
2532    
2533  int parseSysconfigGrub(int * lbaPtr, char ** bootPtr) {  int parseSysconfigGrub(int * lbaPtr, char ** bootPtr) {
# Line 1810  int parseSysconfigGrub(int * lbaPtr, cha Line 2578  int parseSysconfigGrub(int * lbaPtr, cha
2578  }  }
2579    
2580  void dumpSysconfigGrub(void) {  void dumpSysconfigGrub(void) {
2581      char * boot;      char * boot = NULL;
2582      int lba;      int lba;
2583    
2584      if (!parseSysconfigGrub(&lba, &boot)) {      if (isSuseSystem()) {
2585   if (lba) printf("lba\n");          if (parseSuseGrubConf(&lba, &boot)) {
2586   if (boot) printf("boot=%s\n", boot);      free(boot);
2587        return;
2588     }
2589        } else {
2590            if (parseSysconfigGrub(&lba, &boot)) {
2591        free(boot);
2592        return;
2593     }
2594        }
2595    
2596        if (lba) printf("lba\n");
2597        if (boot) {
2598     printf("boot=%s\n", boot);
2599     free(boot);
2600      }      }
2601  }  }
2602    
# Line 1864  struct singleLine * addLineTmpl(struct s Line 2645  struct singleLine * addLineTmpl(struct s
2645  {  {
2646      struct singleLine * newLine = lineDup(tmplLine);      struct singleLine * newLine = lineDup(tmplLine);
2647    
2648        if (isEfi && cfi == &grub2ConfigType) {
2649     enum lineType_e old = newLine->type;
2650     newLine->type = preferredLineType(newLine->type, cfi);
2651     if (old != newLine->type)
2652        newLine->elements[0].item = getKeyByType(newLine->type, cfi);
2653        }
2654    
2655      if (val) {      if (val) {
2656   /* override the inherited value with our own.   /* override the inherited value with our own.
2657   * 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 1873  struct singleLine * addLineTmpl(struct s Line 2661  struct singleLine * addLineTmpl(struct s
2661   insertElement(newLine, val, 1, cfi);   insertElement(newLine, val, 1, cfi);
2662    
2663   /* but try to keep the rootspec from the template... sigh */   /* but try to keep the rootspec from the template... sigh */
2664   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)) {
2665      char * rootspec = getRootSpecifier(tmplLine->elements[1].item);      char * rootspec = getRootSpecifier(tmplLine->elements[1].item);
2666      if (rootspec != NULL) {      if (rootspec != NULL) {
2667   free(newLine->elements[1].item);   free(newLine->elements[1].item);
# Line 1910  struct singleLine *  addLine(struct sing Line 2698  struct singleLine *  addLine(struct sing
2698      /* 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
2699       * stack since it calls addLineTmpl which will make copies.       * stack since it calls addLineTmpl which will make copies.
2700       */       */
   
2701      if (type == LT_TITLE && cfi->titleBracketed) {      if (type == LT_TITLE && cfi->titleBracketed) {
2702   /* we're doing a bracketed title (zipl) */   /* we're doing a bracketed title (zipl) */
2703   tmpl.type = type;   tmpl.type = type;
# Line 2014  void removeLine(struct singleEntry * ent Line 2801  void removeLine(struct singleEntry * ent
2801      free(line);      free(line);
2802  }  }
2803    
 static int isquote(char q)  
 {  
     if (q == '\'' || q == '\"')  
  return 1;  
     return 0;  
 }  
   
2804  static void requote(struct singleLine *tmplLine, struct configFileInfo * cfi)  static void requote(struct singleLine *tmplLine, struct configFileInfo * cfi)
2805  {  {
2806      struct singleLine newLine = {      struct singleLine newLine = {
# Line 2251  int updateActualImage(struct grubConfig Line 3031  int updateActualImage(struct grubConfig
3031      firstElement = 2;      firstElement = 2;
3032    
3033   } else {   } else {
3034      line = getLineByType(LT_KERNEL|LT_MBMODULE, entry->lines);      line = getLineByType(LT_KERNEL|LT_MBMODULE|LT_KERNEL_EFI, entry->lines);
3035      if (!line) {      if (!line) {
3036   /* no LT_KERNEL or LT_MBMODULE in this entry? */   /* no LT_KERNEL or LT_MBMODULE in this entry? */
3037   continue;   continue;
# Line 2416  int updateInitrd(struct grubConfig * cfg Line 3196  int updateInitrd(struct grubConfig * cfg
3196      if (!image) return 0;      if (!image) return 0;
3197    
3198      for (; (entry = findEntryByPath(cfg, image, prefix, &index)); index++) {      for (; (entry = findEntryByPath(cfg, image, prefix, &index)); index++) {
3199          kernelLine = getLineByType(LT_KERNEL, entry->lines);          kernelLine = getLineByType(LT_KERNEL|LT_KERNEL_EFI, entry->lines);
3200          if (!kernelLine) continue;          if (!kernelLine) continue;
3201    
3202          line = getLineByType(LT_INITRD, entry->lines);          line = getLineByType(LT_INITRD|LT_INITRD_EFI, entry->lines);
3203          if (line)          if (line)
3204              removeLine(entry, line);              removeLine(entry, line);
3205          if (prefix) {          if (prefix) {
# Line 2430  int updateInitrd(struct grubConfig * cfg Line 3210  int updateInitrd(struct grubConfig * cfg
3210   endLine = getLineByType(LT_ENTRY_END, entry->lines);   endLine = getLineByType(LT_ENTRY_END, entry->lines);
3211   if (endLine)   if (endLine)
3212      removeLine(entry, endLine);      removeLine(entry, endLine);
3213          line = addLine(entry, cfg->cfi, LT_INITRD, kernelLine->indent, initrd);          line = addLine(entry, cfg->cfi, preferredLineType(LT_INITRD, cfg->cfi),
3214     kernelLine->indent, initrd);
3215          if (!line)          if (!line)
3216      return 1;      return 1;
3217   if (endLine) {   if (endLine) {
# Line 2468  int checkDeviceBootloader(const char * d Line 3249  int checkDeviceBootloader(const char * d
3249      if (memcmp(boot, bootSect, 3))      if (memcmp(boot, bootSect, 3))
3250   return 0;   return 0;
3251    
3252      if (boot[1] == 0xeb) {      if (boot[1] == JMP_SHORT_OPCODE) {
3253   offset = boot[2] + 2;   offset = boot[2] + 2;
3254      } else if (boot[1] == 0xe8 || boot[1] == 0xe9) {      } else if (boot[1] == 0xe8 || boot[1] == 0xe9) {
3255   offset = (boot[3] << 8) + boot[2] + 2;   offset = (boot[3] << 8) + boot[2] + 2;
3256      } else if (boot[0] == 0xeb) {      } else if (boot[0] == JMP_SHORT_OPCODE) {
3257   offset = boot[1] + 2;        offset = boot[1] + 2;
3258            /*
3259     * it looks like grub, when copying stage1 into the mbr, patches stage1
3260     * right after the JMP location, replacing other instructions such as
3261     * JMPs for NOOPs. So, relax the check a little bit by skipping those
3262     * different bytes.
3263     */
3264          if ((bootSect[offset + 1] == NOOP_OPCODE)
3265      && (bootSect[offset + 2] == NOOP_OPCODE)) {
3266     offset = offset + 3;
3267          }
3268      } else if (boot[0] == 0xe8 || boot[0] == 0xe9) {      } else if (boot[0] == 0xe8 || boot[0] == 0xe9) {
3269   offset = (boot[2] << 8) + boot[1] + 2;   offset = (boot[2] << 8) + boot[1] + 2;
3270      } else {      } else {
# Line 2626  int checkForGrub(struct grubConfig * con Line 3417  int checkForGrub(struct grubConfig * con
3417      int fd;      int fd;
3418      unsigned char bootSect[512];      unsigned char bootSect[512];
3419      char * boot;      char * boot;
3420        int onSuse = isSuseSystem();
3421    
3422      if (parseSysconfigGrub(NULL, &boot))  
3423   return 0;      if (onSuse) {
3424     if (parseSuseGrubConf(NULL, &boot))
3425        return 0;
3426        } else {
3427     if (parseSysconfigGrub(NULL, &boot))
3428        return 0;
3429        }
3430    
3431      /* assume grub is not installed -- not an error condition */      /* assume grub is not installed -- not an error condition */
3432      if (!boot)      if (!boot)
# Line 2647  int checkForGrub(struct grubConfig * con Line 3445  int checkForGrub(struct grubConfig * con
3445      }      }
3446      close(fd);      close(fd);
3447    
3448        /* The more elaborate checks do not work on SuSE. The checks done
3449         * seem to be reasonble (at least for now), so just return success
3450         */
3451        if (onSuse)
3452     return 2;
3453    
3454      return checkDeviceBootloader(boot, bootSect);      return checkDeviceBootloader(boot, bootSect);
3455  }  }
3456    
# Line 2680  int checkForExtLinux(struct grubConfig * Line 3484  int checkForExtLinux(struct grubConfig *
3484      return checkDeviceBootloader(boot, bootSect);      return checkDeviceBootloader(boot, bootSect);
3485  }  }
3486    
3487    int checkForYaboot(struct grubConfig * config) {
3488        /*
3489         * This is a simplistic check that we consider good enough for own puporses
3490         *
3491         * If we were to properly check if yaboot is *installed* we'd need to:
3492         * 1) get the system boot device (LT_BOOT)
3493         * 2) considering it's a raw filesystem, check if the yaboot binary matches
3494         *    the content on the boot device
3495         * 3) if not, copy the binary to a temporary file and run "addnote" on it
3496         * 4) check again if binary and boot device contents match
3497         */
3498        if (!access("/etc/yaboot.conf", R_OK))
3499     return 2;
3500    
3501        return 1;
3502    }
3503    
3504    int checkForElilo(struct grubConfig * config) {
3505        if (!access("/etc/elilo.conf", R_OK))
3506     return 2;
3507    
3508        return 1;
3509    }
3510    
3511  static char * getRootSpecifier(char * str) {  static char * getRootSpecifier(char * str) {
3512      char * idx, * rootspec = NULL;      char * idx, * rootspec = NULL;
3513    
# Line 2694  static char * getRootSpecifier(char * st Line 3522  static char * getRootSpecifier(char * st
3522  static char * getInitrdVal(struct grubConfig * config,  static char * getInitrdVal(struct grubConfig * config,
3523     const char * prefix, struct singleLine *tmplLine,     const char * prefix, struct singleLine *tmplLine,
3524     const char * newKernelInitrd,     const char * newKernelInitrd,
3525     char ** extraInitrds, int extraInitrdCount)     const char ** extraInitrds, int extraInitrdCount)
3526  {  {
3527      char *initrdVal, *end;      char *initrdVal, *end;
3528      int i;      int i;
# Line 2739  static char * getInitrdVal(struct grubCo Line 3567  static char * getInitrdVal(struct grubCo
3567    
3568  int addNewKernel(struct grubConfig * config, struct singleEntry * template,  int addNewKernel(struct grubConfig * config, struct singleEntry * template,
3569           const char * prefix,           const char * prefix,
3570   char * newKernelPath, char * newKernelTitle,   const char * newKernelPath, const char * newKernelTitle,
3571   char * newKernelArgs, char * newKernelInitrd,   const char * newKernelArgs, const char * newKernelInitrd,
3572   char ** extraInitrds, int extraInitrdCount,   const char ** extraInitrds, int extraInitrdCount,
3573                   char * newMBKernel, char * newMBKernelArgs) {                   const char * newMBKernel, const char * newMBKernelArgs) {
3574      struct singleEntry * new;      struct singleEntry * new;
3575      struct singleLine * newLine = NULL, * tmplLine = NULL, * masterLine = NULL;      struct singleLine * newLine = NULL, * tmplLine = NULL, * masterLine = NULL;
3576      int needs;      int needs;
# Line 2796  int addNewKernel(struct grubConfig * con Line 3624  int addNewKernel(struct grubConfig * con
3624      while (*chptr && isspace(*chptr)) chptr++;      while (*chptr && isspace(*chptr)) chptr++;
3625      if (*chptr == '#') continue;      if (*chptr == '#') continue;
3626    
3627      if (tmplLine->type == LT_KERNEL &&      if (iskernel(tmplLine->type) && tmplLine->numElements >= 2) {
     tmplLine->numElements >= 2) {  
3628   if (!template->multiboot && (needs & NEED_MB)) {   if (!template->multiboot && (needs & NEED_MB)) {
3629      /* it's not a multiboot template and this is the kernel      /* it's not a multiboot template and this is the kernel
3630       * line.  Try to be intelligent about inserting the       * line.  Try to be intelligent about inserting the
# Line 2874  int addNewKernel(struct grubConfig * con Line 3701  int addNewKernel(struct grubConfig * con
3701      /* template is multi but new is not,      /* template is multi but new is not,
3702       * insert the kernel in the first module slot       * insert the kernel in the first module slot
3703       */       */
3704      tmplLine->type = LT_KERNEL;      tmplLine->type = preferredLineType(LT_KERNEL, config->cfi);
3705      free(tmplLine->elements[0].item);      free(tmplLine->elements[0].item);
3706      tmplLine->elements[0].item =      tmplLine->elements[0].item =
3707   strdup(getKeywordByType(LT_KERNEL, config->cfi)->key);   strdup(getKeywordByType(tmplLine->type,
3708     config->cfi)->key);
3709      newLine = addLineTmpl(new, tmplLine, newLine,      newLine = addLineTmpl(new, tmplLine, newLine,
3710    newKernelPath + strlen(prefix), config->cfi);    newKernelPath + strlen(prefix),
3711      config->cfi);
3712      needs &= ~NEED_KERNEL;      needs &= ~NEED_KERNEL;
3713   } else if (needs & NEED_INITRD) {   } else if (needs & NEED_INITRD) {
3714      char *initrdVal;      char *initrdVal;
3715      /* template is multi but new is not,      /* template is multi but new is not,
3716       * insert the initrd in the second module slot       * insert the initrd in the second module slot
3717       */       */
3718      tmplLine->type = LT_INITRD;      tmplLine->type = preferredLineType(LT_INITRD, config->cfi);
3719      free(tmplLine->elements[0].item);      free(tmplLine->elements[0].item);
3720      tmplLine->elements[0].item =      tmplLine->elements[0].item =
3721   strdup(getKeywordByType(LT_INITRD, config->cfi)->key);   strdup(getKeywordByType(tmplLine->type,
3722     config->cfi)->key);
3723      initrdVal = getInitrdVal(config, prefix, tmplLine, newKernelInitrd, extraInitrds, extraInitrdCount);      initrdVal = getInitrdVal(config, prefix, tmplLine, newKernelInitrd, extraInitrds, extraInitrdCount);
3724      newLine = addLineTmpl(new, tmplLine, newLine, initrdVal, config->cfi);      newLine = addLineTmpl(new, tmplLine, newLine, initrdVal, config->cfi);
3725      free(initrdVal);      free(initrdVal);
3726      needs &= ~NEED_INITRD;      needs &= ~NEED_INITRD;
3727   }   }
3728    
3729      } else if (tmplLine->type == LT_INITRD &&      } else if (isinitrd(tmplLine->type) && tmplLine->numElements >= 2) {
        tmplLine->numElements >= 2) {  
3730   if (needs & NEED_INITRD &&   if (needs & NEED_INITRD &&
3731      new->multiboot && !template->multiboot &&      new->multiboot && !template->multiboot &&
3732      config->cfi->mbInitRdIsModule) {      config->cfi->mbInitRdIsModule) {
# Line 2948  int addNewKernel(struct grubConfig * con Line 3777  int addNewKernel(struct grubConfig * con
3777   }   }
3778      } else if (tmplLine->type == LT_ECHO) {      } else if (tmplLine->type == LT_ECHO) {
3779      requote(tmplLine, config->cfi);      requote(tmplLine, config->cfi);
3780        static const char *prefix = "'Loading ";
3781      if (tmplLine->numElements > 1 &&      if (tmplLine->numElements > 1 &&
3782      strstr(tmplLine->elements[1].item, "'Loading Linux ")) {      strstr(tmplLine->elements[1].item, prefix) &&
3783   char *prefix = "'Loading ";      masterLine->next &&
3784        iskernel(masterLine->next->type)) {
3785   char *newTitle = malloc(strlen(prefix) +   char *newTitle = malloc(strlen(prefix) +
3786   strlen(newKernelTitle) + 2);   strlen(newKernelTitle) + 2);
3787    
# Line 2977  int addNewKernel(struct grubConfig * con Line 3808  int addNewKernel(struct grubConfig * con
3808   */   */
3809   switch (config->cfi->entryStart) {   switch (config->cfi->entryStart) {
3810      case LT_KERNEL:      case LT_KERNEL:
3811        case LT_KERNEL_EFI:
3812   if (new->multiboot && config->cfi->mbHyperFirst) {   if (new->multiboot && config->cfi->mbHyperFirst) {
3813      /* fall through to LT_HYPER */      /* fall through to LT_HYPER */
3814   } else {   } else {
3815      newLine = addLine(new, config->cfi, LT_KERNEL,      newLine = addLine(new, config->cfi,
3816              preferredLineType(LT_KERNEL, config->cfi),
3817        config->primaryIndent,        config->primaryIndent,
3818        newKernelPath + strlen(prefix));        newKernelPath + strlen(prefix));
3819      needs &= ~NEED_KERNEL;      needs &= ~NEED_KERNEL;
# Line 3056  int addNewKernel(struct grubConfig * con Line 3889  int addNewKernel(struct grubConfig * con
3889      if (needs & NEED_KERNEL) {      if (needs & NEED_KERNEL) {
3890   newLine = addLine(new, config->cfi,   newLine = addLine(new, config->cfi,
3891    (new->multiboot && getKeywordByType(LT_MBMODULE,    (new->multiboot && getKeywordByType(LT_MBMODULE,
3892        config->cfi)) ?        config->cfi))
3893    LT_MBMODULE : LT_KERNEL,     ? LT_MBMODULE
3894     : preferredLineType(LT_KERNEL, config->cfi),
3895    config->secondaryIndent,    config->secondaryIndent,
3896    newKernelPath + strlen(prefix));    newKernelPath + strlen(prefix));
3897   needs &= ~NEED_KERNEL;   needs &= ~NEED_KERNEL;
# Line 3073  int addNewKernel(struct grubConfig * con Line 3907  int addNewKernel(struct grubConfig * con
3907   initrdVal = getInitrdVal(config, prefix, NULL, newKernelInitrd, extraInitrds, extraInitrdCount);   initrdVal = getInitrdVal(config, prefix, NULL, newKernelInitrd, extraInitrds, extraInitrdCount);
3908   newLine = addLine(new, config->cfi,   newLine = addLine(new, config->cfi,
3909    (new->multiboot && getKeywordByType(LT_MBMODULE,    (new->multiboot && getKeywordByType(LT_MBMODULE,
3910        config->cfi)) ?        config->cfi))
3911    LT_MBMODULE : LT_INITRD,     ? LT_MBMODULE
3912       : preferredLineType(LT_INITRD, config->cfi),
3913    config->secondaryIndent,    config->secondaryIndent,
3914    initrdVal);    initrdVal);
3915   free(initrdVal);   free(initrdVal);
# Line 3106  static void traceback(int signum) Line 3941  static void traceback(int signum)
3941      memset(array, '\0', sizeof (array));      memset(array, '\0', sizeof (array));
3942      size = backtrace(array, 40);      size = backtrace(array, 40);
3943    
3944      fprintf(stderr, "grubby recieved SIGSEGV!  Backtrace (%ld):\n",      fprintf(stderr, "grubby received SIGSEGV!  Backtrace (%ld):\n",
3945              (unsigned long)size);              (unsigned long)size);
3946      backtrace_symbols_fd(array, size, STDERR_FILENO);      backtrace_symbols_fd(array, size, STDERR_FILENO);
3947      exit(1);      exit(1);
# Line 3141  int main(int argc, const char ** argv) { Line 3976  int main(int argc, const char ** argv) {
3976      char * removeArgs = NULL;      char * removeArgs = NULL;
3977      char * kernelInfo = NULL;      char * kernelInfo = NULL;
3978      char * extraInitrds[MAX_EXTRA_INITRDS] = { NULL };      char * extraInitrds[MAX_EXTRA_INITRDS] = { NULL };
3979        char * envPath = NULL;
3980      const char * chptr = NULL;      const char * chptr = NULL;
3981      struct configFileInfo * cfi = NULL;      struct configFileInfo * cfi = NULL;
3982      struct grubConfig * config;      struct grubConfig * config;
3983      struct singleEntry * template = NULL;      struct singleEntry * template = NULL;
3984      int copyDefault = 0, makeDefault = 0;      int copyDefault = 0, makeDefault = 0;
3985      int displayDefault = 0;      int displayDefault = 0;
3986        int displayDefaultIndex = 0;
3987        int displayDefaultTitle = 0;
3988        int defaultIndex = -1;
3989      struct poptOption options[] = {      struct poptOption options[] = {
3990   { "add-kernel", 0, POPT_ARG_STRING, &newKernelPath, 0,   { "add-kernel", 0, POPT_ARG_STRING, &newKernelPath, 0,
3991      _("add an entry for the specified kernel"), _("kernel-path") },      _("add an entry for the specified kernel"), _("kernel-path") },
# Line 3164  int main(int argc, const char ** argv) { Line 4003  int main(int argc, const char ** argv) {
4003   { "boot-filesystem", 0, POPT_ARG_STRING, &bootPrefix, 0,   { "boot-filesystem", 0, POPT_ARG_STRING, &bootPrefix, 0,
4004      _("filestystem which contains /boot directory (for testing only)"),      _("filestystem which contains /boot directory (for testing only)"),
4005      _("bootfs") },      _("bootfs") },
4006  #if defined(__i386__) || defined(__x86_64__)  #if defined(__i386__) || defined(__x86_64__) || defined (__powerpc64__) || defined (__ia64__)
4007   { "bootloader-probe", 0, POPT_ARG_NONE, &bootloaderProbe, 0,   { "bootloader-probe", 0, POPT_ARG_NONE, &bootloaderProbe, 0,
4008      _("check if lilo is installed on lilo.conf boot sector") },      _("check which bootloader is installed on boot sector") },
4009  #endif  #endif
4010   { "config-file", 'c', POPT_ARG_STRING, &grubConfig, 0,   { "config-file", 'c', POPT_ARG_STRING, &grubConfig, 0,
4011      _("path to grub config file to update (\"-\" for stdin)"),      _("path to grub config file to update (\"-\" for stdin)"),
# Line 3177  int main(int argc, const char ** argv) { Line 4016  int main(int argc, const char ** argv) {
4016        "the kernel referenced by the default image does not exist, "        "the kernel referenced by the default image does not exist, "
4017        "the first linux entry whose kernel does exist is used as the "        "the first linux entry whose kernel does exist is used as the "
4018        "template"), NULL },        "template"), NULL },
4019     { "debug", 0, 0, &debug, 0,
4020        _("print debugging information for failures") },
4021   { "default-kernel", 0, 0, &displayDefault, 0,   { "default-kernel", 0, 0, &displayDefault, 0,
4022      _("display the path of the default kernel") },      _("display the path of the default kernel") },
4023     { "default-index", 0, 0, &displayDefaultIndex, 0,
4024        _("display the index of the default kernel") },
4025     { "default-title", 0, 0, &displayDefaultTitle, 0,
4026        _("display the title of the default kernel") },
4027   { "elilo", 0, POPT_ARG_NONE, &configureELilo, 0,   { "elilo", 0, POPT_ARG_NONE, &configureELilo, 0,
4028      _("configure elilo bootloader") },      _("configure elilo bootloader") },
4029     { "efi", 0, POPT_ARG_NONE, &isEfi, 0,
4030        _("force grub2 stanzas to use efi") },
4031     { "env", 0, POPT_ARG_STRING, &envPath, 0,
4032        _("path for environment data"),
4033        _("path") },
4034   { "extlinux", 0, POPT_ARG_NONE, &configureExtLinux, 0,   { "extlinux", 0, POPT_ARG_NONE, &configureExtLinux, 0,
4035      _("configure extlinux bootloader (from syslinux)") },      _("configure extlinux bootloader (from syslinux)") },
4036   { "grub", 0, POPT_ARG_NONE, &configureGrub, 0,   { "grub", 0, POPT_ARG_NONE, &configureGrub, 0,
# Line 3193  int main(int argc, const char ** argv) { Line 4043  int main(int argc, const char ** argv) {
4043   { "initrd", 0, POPT_ARG_STRING, &newKernelInitrd, 0,   { "initrd", 0, POPT_ARG_STRING, &newKernelInitrd, 0,
4044      _("initrd image for the new kernel"), _("initrd-path") },      _("initrd image for the new kernel"), _("initrd-path") },
4045   { "extra-initrd", 'i', POPT_ARG_STRING, NULL, 'i',   { "extra-initrd", 'i', POPT_ARG_STRING, NULL, 'i',
4046      _("auxilliary initrd image for things other than the new kernel"), _("initrd-path") },      _("auxiliary initrd image for things other than the new kernel"), _("initrd-path") },
4047   { "lilo", 0, POPT_ARG_NONE, &configureLilo, 0,   { "lilo", 0, POPT_ARG_NONE, &configureLilo, 0,
4048      _("configure lilo bootloader") },      _("configure lilo bootloader") },
4049   { "make-default", 0, 0, &makeDefault, 0,   { "make-default", 0, 0, &makeDefault, 0,
# Line 3213  int main(int argc, const char ** argv) { Line 4063  int main(int argc, const char ** argv) {
4063   { "set-default", 0, POPT_ARG_STRING, &defaultKernel, 0,   { "set-default", 0, POPT_ARG_STRING, &defaultKernel, 0,
4064      _("make the first entry referencing the specified kernel "      _("make the first entry referencing the specified kernel "
4065        "the default"), _("kernel-path") },        "the default"), _("kernel-path") },
4066     { "set-default-index", 0, POPT_ARG_INT, &defaultIndex, 0,
4067        _("make the given entry index the default entry"),
4068        _("entry-index") },
4069   { "silo", 0, POPT_ARG_NONE, &configureSilo, 0,   { "silo", 0, POPT_ARG_NONE, &configureSilo, 0,
4070      _("configure silo bootloader") },      _("configure silo bootloader") },
4071   { "title", 0, POPT_ARG_STRING, &newKernelTitle, 0,   { "title", 0, POPT_ARG_STRING, &newKernelTitle, 0,
# Line 3234  int main(int argc, const char ** argv) { Line 4087  int main(int argc, const char ** argv) {
4087    
4088      signal(SIGSEGV, traceback);      signal(SIGSEGV, traceback);
4089    
4090        int i = 0;
4091        for (int j = 1; j < argc; j++)
4092     i += strlen(argv[j]) + 1;
4093        saved_command_line = malloc(i);
4094        if (!saved_command_line) {
4095     fprintf(stderr, "grubby: %m\n");
4096     exit(1);
4097        }
4098        saved_command_line[0] = '\0';
4099        for (int j = 1; j < argc; j++) {
4100     strcat(saved_command_line, argv[j]);
4101     strncat(saved_command_line, j == argc -1 ? "" : " ", 1);
4102        }
4103    
4104      optCon = poptGetContext("grubby", argc, argv, options, 0);      optCon = poptGetContext("grubby", argc, argv, options, 0);
4105      poptReadDefaultConfig(optCon, 1);      poptReadDefaultConfig(optCon, 1);
4106    
# Line 3277  int main(int argc, const char ** argv) { Line 4144  int main(int argc, const char ** argv) {
4144   return 1;   return 1;
4145      } else if (configureGrub2) {      } else if (configureGrub2) {
4146   cfi = &grub2ConfigType;   cfi = &grub2ConfigType;
4147     if (envPath)
4148        cfi->envFile = envPath;
4149      } else if (configureLilo) {      } else if (configureLilo) {
4150   cfi = &liloConfigType;   cfi = &liloConfigType;
4151      } else if (configureGrub) {      } else if (configureGrub) {
# Line 3295  int main(int argc, const char ** argv) { Line 4164  int main(int argc, const char ** argv) {
4164      }      }
4165    
4166      if (!cfi) {      if (!cfi) {
4167            if (grub2FindConfig(&grub2ConfigType))
4168        cfi = &grub2ConfigType;
4169     else
4170        #ifdef __ia64__        #ifdef __ia64__
4171   cfi = &eliloConfigType;      cfi = &eliloConfigType;
4172        #elif __powerpc__        #elif __powerpc__
4173   cfi = &yabootConfigType;      cfi = &yabootConfigType;
4174        #elif __sparc__        #elif __sparc__
4175          cfi = &siloConfigType;              cfi = &siloConfigType;
4176        #elif __s390__        #elif __s390__
4177          cfi = &ziplConfigType;              cfi = &ziplConfigType;
4178        #elif __s390x__        #elif __s390x__
4179          cfi = &ziplConfigtype;              cfi = &ziplConfigtype;
4180        #else        #else
         if (grub2FindConfig(&grub2ConfigType))  
     cfi = &grub2ConfigType;  
  else  
4181      cfi = &grubConfigType;      cfi = &grubConfigType;
4182        #endif        #endif
4183      }      }
# Line 3321  int main(int argc, const char ** argv) { Line 4190  int main(int argc, const char ** argv) {
4190      }      }
4191    
4192      if (bootloaderProbe && (displayDefault || kernelInfo || newKernelVersion ||      if (bootloaderProbe && (displayDefault || kernelInfo || newKernelVersion ||
4193    newKernelPath || removeKernelPath || makeDefault ||      newKernelPath || removeKernelPath || makeDefault ||
4194    defaultKernel)) {      defaultKernel || displayDefaultIndex || displayDefaultTitle ||
4195        (defaultIndex >= 0))) {
4196   fprintf(stderr, _("grubby: --bootloader-probe may not be used with "   fprintf(stderr, _("grubby: --bootloader-probe may not be used with "
4197    "specified option"));    "specified option"));
4198   return 1;   return 1;
# Line 3364  int main(int argc, const char ** argv) { Line 4234  int main(int argc, const char ** argv) {
4234   makeDefault = 1;   makeDefault = 1;
4235   defaultKernel = NULL;   defaultKernel = NULL;
4236      }      }
4237        else if (defaultKernel && (defaultIndex >= 0)) {
4238     fprintf(stderr, _("grubby: --set-default and --set-default-index "
4239      "may not be used together\n"));
4240     return 1;
4241        }
4242    
4243      if (grubConfig && !strcmp(grubConfig, "-") && !outputFile) {      if (grubConfig && !strcmp(grubConfig, "-") && !outputFile) {
4244   fprintf(stderr, _("grubby: output file must be specified if stdin "   fprintf(stderr, _("grubby: output file must be specified if stdin "
# Line 3372  int main(int argc, const char ** argv) { Line 4247  int main(int argc, const char ** argv) {
4247      }      }
4248    
4249      if (!removeKernelPath && !newKernelPath && !displayDefault && !defaultKernel      if (!removeKernelPath && !newKernelPath && !displayDefault && !defaultKernel
4250   && !kernelInfo && !bootloaderProbe && !updateKernelPath   && !kernelInfo && !bootloaderProbe && !updateKernelPath
4251          && !removeMBKernel) {   && !removeMBKernel && !displayDefaultIndex && !displayDefaultTitle
4252     && (defaultIndex == -1)) {
4253   fprintf(stderr, _("grubby: no action specified\n"));   fprintf(stderr, _("grubby: no action specified\n"));
4254   return 1;   return 1;
4255      }      }
# Line 3400  int main(int argc, const char ** argv) { Line 4276  int main(int argc, const char ** argv) {
4276      }      }
4277    
4278      if (bootloaderProbe) {      if (bootloaderProbe) {
4279   int lrc = 0, grc = 0, gr2c = 0, erc = 0;   int lrc = 0, grc = 0, gr2c = 0, extrc = 0, yrc = 0, erc = 0;
4280   struct grubConfig * lconfig, * gconfig;   struct grubConfig * lconfig, * gconfig, * yconfig, * econfig;
4281    
4282   const char *grub2config = grub2FindConfig(&grub2ConfigType);   const char *grub2config = grub2FindConfig(&grub2ConfigType);
4283   if (grub2config) {   if (grub2config) {
# Line 3429  int main(int argc, const char ** argv) { Line 4305  int main(int argc, const char ** argv) {
4305   lrc = checkForLilo(lconfig);   lrc = checkForLilo(lconfig);
4306   }   }
4307    
4308     if (!access(eliloConfigType.defaultConfig, F_OK)) {
4309        econfig = readConfig(eliloConfigType.defaultConfig,
4310     &eliloConfigType);
4311        if (!econfig)
4312     erc = 1;
4313        else
4314     erc = checkForElilo(econfig);
4315     }
4316    
4317   if (!access(extlinuxConfigType.defaultConfig, F_OK)) {   if (!access(extlinuxConfigType.defaultConfig, F_OK)) {
4318      lconfig = readConfig(extlinuxConfigType.defaultConfig, &extlinuxConfigType);      lconfig = readConfig(extlinuxConfigType.defaultConfig, &extlinuxConfigType);
4319      if (!lconfig)      if (!lconfig)
4320   erc = 1;   extrc = 1;
4321      else      else
4322   erc = checkForExtLinux(lconfig);   extrc = checkForExtLinux(lconfig);
4323   }   }
4324    
4325   if (lrc == 1 || grc == 1 || gr2c == 1) return 1;  
4326     if (!access(yabootConfigType.defaultConfig, F_OK)) {
4327        yconfig = readConfig(yabootConfigType.defaultConfig,
4328     &yabootConfigType);
4329        if (!yconfig)
4330     yrc = 1;
4331        else
4332     yrc = checkForYaboot(yconfig);
4333     }
4334    
4335     if (lrc == 1 || grc == 1 || gr2c == 1 || extrc == 1 || yrc == 1 ||
4336     erc == 1)
4337        return 1;
4338    
4339   if (lrc == 2) printf("lilo\n");   if (lrc == 2) printf("lilo\n");
4340   if (gr2c == 2) printf("grub2\n");   if (gr2c == 2) printf("grub2\n");
4341   if (grc == 2) printf("grub\n");   if (grc == 2) printf("grub\n");
4342   if (erc == 2) printf("extlinux\n");   if (extrc == 2) printf("extlinux\n");
4343     if (yrc == 2) printf("yaboot\n");
4344     if (erc == 2) printf("elilo\n");
4345    
4346   return 0;   return 0;
4347      }      }
4348    
4349        if (grubConfig == NULL) {
4350     printf("Could not find bootloader configuration file.\n");
4351     exit(1);
4352        }
4353    
4354      config = readConfig(grubConfig, cfi);      config = readConfig(grubConfig, cfi);
4355      if (!config) return 1;      if (!config) return 1;
4356    
# Line 3460  int main(int argc, const char ** argv) { Line 4364  int main(int argc, const char ** argv) {
4364   if (!entry) return 0;   if (!entry) return 0;
4365   if (!suitableImage(entry, bootPrefix, 0, flags)) return 0;   if (!suitableImage(entry, bootPrefix, 0, flags)) return 0;
4366    
4367   line = getLineByType(LT_KERNEL|LT_HYPER, entry->lines);   line = getLineByType(LT_KERNEL|LT_HYPER|LT_KERNEL_EFI, entry->lines);
4368   if (!line) return 0;   if (!line) return 0;
4369    
4370          rootspec = getRootSpecifier(line->elements[1].item);          rootspec = getRootSpecifier(line->elements[1].item);
# Line 3468  int main(int argc, const char ** argv) { Line 4372  int main(int argc, const char ** argv) {
4372                 ((rootspec != NULL) ? strlen(rootspec) : 0));                 ((rootspec != NULL) ? strlen(rootspec) : 0));
4373    
4374   return 0;   return 0;
4375    
4376        } else if (displayDefaultTitle) {
4377     struct singleLine * line;
4378     struct singleEntry * entry;
4379    
4380     if (config->defaultImage == -1) return 0;
4381     entry = findEntryByIndex(config, config->defaultImage);
4382     if (!entry) return 0;
4383    
4384     if (!configureGrub2) {
4385      line = getLineByType(LT_TITLE, entry->lines);
4386      if (!line) return 0;
4387      printf("%s\n", line->elements[1].item);
4388    
4389     } else {
4390      char * title;
4391    
4392      dbgPrintf("This is GRUB2, default title is embeded in menuentry\n");
4393      line = getLineByType(LT_MENUENTRY, entry->lines);
4394      if (!line) return 0;
4395      title = grub2ExtractTitle(line);
4396      if (title)
4397        printf("%s\n", title);
4398     }
4399     return 0;
4400    
4401        } else if (displayDefaultIndex) {
4402            if (config->defaultImage == -1) return 0;
4403            printf("%i\n", config->defaultImage);
4404            return 0;
4405    
4406      } else if (kernelInfo)      } else if (kernelInfo)
4407   return displayInfo(config, kernelInfo, bootPrefix);   return displayInfo(config, kernelInfo, bootPrefix);
4408    
# Line 3479  int main(int argc, const char ** argv) { Line 4414  int main(int argc, const char ** argv) {
4414      markRemovedImage(config, removeKernelPath, bootPrefix);      markRemovedImage(config, removeKernelPath, bootPrefix);
4415      markRemovedImage(config, removeMBKernel, bootPrefix);      markRemovedImage(config, removeMBKernel, bootPrefix);
4416      setDefaultImage(config, newKernelPath != NULL, defaultKernel, makeDefault,      setDefaultImage(config, newKernelPath != NULL, defaultKernel, makeDefault,
4417      bootPrefix, flags);      bootPrefix, flags, defaultIndex);
4418      setFallbackImage(config, newKernelPath != NULL);      setFallbackImage(config, newKernelPath != NULL);
4419      if (updateImage(config, updateKernelPath, bootPrefix, newKernelArgs,      if (updateImage(config, updateKernelPath, bootPrefix, newKernelArgs,
4420                      removeArgs, newMBKernelArgs, removeMBKernelArgs)) return 1;                      removeArgs, newMBKernelArgs, removeMBKernelArgs)) return 1;
# Line 3489  int main(int argc, const char ** argv) { Line 4424  int main(int argc, const char ** argv) {
4424      }      }
4425      if (addNewKernel(config, template, bootPrefix, newKernelPath,      if (addNewKernel(config, template, bootPrefix, newKernelPath,
4426                       newKernelTitle, newKernelArgs, newKernelInitrd,                       newKernelTitle, newKernelArgs, newKernelInitrd,
4427                       extraInitrds, extraInitrdCount,                       (const char **)extraInitrds, extraInitrdCount,
4428                       newMBKernel, newMBKernelArgs)) return 1;                       newMBKernel, newMBKernelArgs)) return 1;
4429            
4430    

Legend:
Removed from v.1717  
changed lines
  Added in v.2252