Magellan Linux

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

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

revision 1844 by niro, Mon Jul 2 12:59:07 2012 UTC revision 2683 by niro, Wed Jul 16 09:51:14 2014 UTC
# Line 36  Line 36 
36  #include <signal.h>  #include <signal.h>
37  #include <blkid/blkid.h>  #include <blkid/blkid.h>
38    
39    #include "log.h"
40    
41  #ifndef DEBUG  #ifndef DEBUG
42  #define DEBUG 0  #define DEBUG 0
43  #endif  #endif
# Line 56  int debug = 0; /* Currently just for tem Line 58  int debug = 0; /* Currently just for tem
58  #define NOOP_OPCODE 0x90  #define NOOP_OPCODE 0x90
59  #define JMP_SHORT_OPCODE 0xeb  #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 82  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_KERNEL_16    = 1 << 22,
94        LT_INITRD_16    = 1 << 23,
95        LT_UNKNOWN      = 1 << 24,
96  };  };
97    
98  struct singleLine {  struct singleLine {
# Line 128  struct configFileInfo; Line 138  struct configFileInfo;
138  typedef const char *(*findConfigFunc)(struct configFileInfo *);  typedef const char *(*findConfigFunc)(struct configFileInfo *);
139  typedef const int (*writeLineFunc)(struct configFileInfo *,  typedef const int (*writeLineFunc)(struct configFileInfo *,
140   struct singleLine *line);   struct singleLine *line);
141    typedef char *(*getEnvFunc)(struct configFileInfo *, char *name);
142    typedef int (*setEnvFunc)(struct configFileInfo *, char *name, char *value);
143    
144  struct configFileInfo {  struct configFileInfo {
145      char * defaultConfig;      char * defaultConfig;
146      findConfigFunc findConfig;      findConfigFunc findConfig;
147      writeLineFunc writeLine;      writeLineFunc writeLine;
148        getEnvFunc getEnv;
149        setEnvFunc setEnv;
150      struct keywordTypes * keywords;      struct keywordTypes * keywords;
151        int caseInsensitive;
152      int defaultIsIndex;      int defaultIsIndex;
153      int defaultIsVariable;      int defaultIsVariable;
154      int defaultSupportSaved;      int defaultSupportSaved;
155        int defaultIsSaved;
156      enum lineType_e entryStart;      enum lineType_e entryStart;
157      enum lineType_e entryEnd;      enum lineType_e entryEnd;
158      int needsBootPrefix;      int needsBootPrefix;
# Line 148  struct configFileInfo { Line 164  struct configFileInfo {
164      int mbInitRdIsModule;      int mbInitRdIsModule;
165      int mbConcatArgs;      int mbConcatArgs;
166      int mbAllowExtraInitRds;      int mbAllowExtraInitRds;
167        char *envFile;
168  };  };
169    
170  struct keywordTypes grubKeywords[] = {  struct keywordTypes grubKeywords[] = {
# Line 164  struct keywordTypes grubKeywords[] = { Line 181  struct keywordTypes grubKeywords[] = {
181    
182  const char *grubFindConfig(struct configFileInfo *cfi) {  const char *grubFindConfig(struct configFileInfo *cfi) {
183      static const char *configFiles[] = {      static const char *configFiles[] = {
  "/etc/grub.conf",  
184   "/boot/grub/grub.conf",   "/boot/grub/grub.conf",
185   "/boot/grub/menu.lst",   "/boot/grub/menu.lst",
186     "/etc/grub.conf",
187     "/boot/grub2/grub.cfg",
188     "/boot/grub2-efi/grub.cfg",
189   NULL   NULL
190      };      };
191      static int i = -1;      static int i = -1;
# Line 205  struct keywordTypes grub2Keywords[] = { Line 224  struct keywordTypes grub2Keywords[] = {
224      { "default",    LT_DEFAULT,     ' ' },      { "default",    LT_DEFAULT,     ' ' },
225      { "fallback",   LT_FALLBACK,    ' ' },      { "fallback",   LT_FALLBACK,    ' ' },
226      { "linux",      LT_KERNEL,      ' ' },      { "linux",      LT_KERNEL,      ' ' },
227        { "linuxefi",   LT_KERNEL_EFI,  ' ' },
228        { "linux16",    LT_KERNEL_16,   ' ' },
229      { "initrd",     LT_INITRD,      ' ', ' ' },      { "initrd",     LT_INITRD,      ' ', ' ' },
230        { "initrdefi",  LT_INITRD_EFI,  ' ', ' ' },
231        { "initrd16",   LT_INITRD_16,   ' ', ' ' },
232      { "module",     LT_MBMODULE,    ' ' },      { "module",     LT_MBMODULE,    ' ' },
233      { "kernel",     LT_HYPER,       ' ' },      { "kernel",     LT_HYPER,       ' ' },
234      { NULL, 0, 0 },      { NULL, 0, 0 },
# Line 219  const char *grub2FindConfig(struct confi Line 242  const char *grub2FindConfig(struct confi
242      };      };
243      static int i = -1;      static int i = -1;
244      static const char *grub_cfg = "/boot/grub/grub.cfg";      static const char *grub_cfg = "/boot/grub/grub.cfg";
245        int rc = -1;
246    
247      if (i == -1) {      if (i == -1) {
248   for (i = 0; configFiles[i] != NULL; i++) {   for (i = 0; configFiles[i] != NULL; i++) {
249      dbgPrintf("Checking \"%s\": ", configFiles[i]);      dbgPrintf("Checking \"%s\": ", configFiles[i]);
250      if (!access(configFiles[i], R_OK)) {      if ((rc = access(configFiles[i], R_OK))) {
251     if (errno == EACCES) {
252        printf("Unable to access bootloader configuration file "
253           "\"%s\": %m\n", configFiles[i]);
254        exit(1);
255     }
256     continue;
257        } else {
258   dbgPrintf("found\n");   dbgPrintf("found\n");
259   return configFiles[i];   return configFiles[i];
260      }      }
# Line 242  const char *grub2FindConfig(struct confi Line 273  const char *grub2FindConfig(struct confi
273      return configFiles[i];      return configFiles[i];
274  }  }
275    
276    /* kind of hacky.  It'll give the first 1024 bytes, ish. */
277    static char *grub2GetEnv(struct configFileInfo *info, char *name)
278    {
279        static char buf[1025];
280        char *s = NULL;
281        char *ret = NULL;
282        char *envFile = info->envFile ? info->envFile : "/boot/grub/grubenv";
283        int rc = asprintf(&s, "grub-editenv %s list | grep '^%s='", envFile, name);
284    
285        if (rc < 0)
286     return NULL;
287    
288        FILE *f = popen(s, "r");
289        if (!f)
290     goto out;
291    
292        memset(buf, '\0', sizeof (buf));
293        ret = fgets(buf, 1024, f);
294        pclose(f);
295    
296        if (ret) {
297     ret += strlen(name) + 1;
298     ret[strlen(ret) - 1] = '\0';
299        }
300        dbgPrintf("grub2GetEnv(%s): %s\n", name, ret);
301    out:
302        free(s);
303        return ret;
304    }
305    
306    static int sPopCount(const char *s, const char *c)
307    {
308        int ret = 0;
309        if (!s)
310     return -1;
311        for (int i = 0; s[i] != '\0'; i++)
312     for (int j = 0; c[j] != '\0'; j++)
313        if (s[i] == c[j])
314     ret++;
315        return ret;
316    }
317    
318    static char *shellEscape(const char *s)
319    {
320        int l = strlen(s) + sPopCount(s, "'") * 2;
321    
322        char *ret = calloc(l+1, sizeof (*ret));
323        if (!ret)
324     return NULL;
325        for (int i = 0, j = 0; s[i] != '\0'; i++, j++) {
326     if (s[i] == '\'')
327        ret[j++] = '\\';
328     ret[j] = s[i];
329        }
330        return ret;
331    }
332    
333    static void unquote(char *s)
334    {
335        int l = strlen(s);
336    
337        if ((s[l-1] == '\'' && s[0] == '\'') || (s[l-1] == '"' && s[0] == '"')) {
338     memmove(s, s+1, l-2);
339     s[l-2] = '\0';
340        }
341    }
342    
343    static int grub2SetEnv(struct configFileInfo *info, char *name, char *value)
344    {
345        char *s = NULL;
346        int rc = 0;
347        char *envFile = info->envFile ? info->envFile : "/boot/grub/grubenv";
348    
349        unquote(value);
350        value = shellEscape(value);
351        if (!value)
352        return -1;
353    
354        rc = asprintf(&s, "grub-editenv %s set '%s=%s'", envFile, name, value);
355        free(value);
356        if (rc <0)
357     return -1;
358    
359        dbgPrintf("grub2SetEnv(%s): %s\n", name, s);
360        rc = system(s);
361        free(s);
362        return rc;
363    }
364    
365    /* this is a gigantic hack to avoid clobbering grub2 variables... */
366    static int is_special_grub2_variable(const char *name)
367    {
368        if (!strcmp(name,"\"${next_entry}\""))
369     return 1;
370        if (!strcmp(name,"\"${prev_saved_entry}\""))
371     return 1;
372        return 0;
373    }
374    
375  int sizeOfSingleLine(struct singleLine * line) {  int sizeOfSingleLine(struct singleLine * line) {
   int i;  
376    int count = 0;    int count = 0;
377    
378    for (i = 0; i < line->numElements; i++) {    for (int i = 0; i < line->numElements; i++) {
379      int indentSize = 0;      int indentSize = 0;
380    
381      count = count + strlen(line->elements[i].item);      count = count + strlen(line->elements[i].item);
# Line 272  static int isquote(char q) Line 401  static int isquote(char q)
401      return 0;      return 0;
402  }  }
403    
404    static int iskernel(enum lineType_e type) {
405        return (type == LT_KERNEL || type == LT_KERNEL_EFI || type == LT_KERNEL_16);
406    }
407    
408    static int isinitrd(enum lineType_e type) {
409        return (type == LT_INITRD || type == LT_INITRD_EFI || type == LT_INITRD_16);
410    }
411    
412  char *grub2ExtractTitle(struct singleLine * line) {  char *grub2ExtractTitle(struct singleLine * line) {
413      char * current;      char * current;
414      char * current_indent;      char * current_indent;
# Line 329  char *grub2ExtractTitle(struct singleLin Line 466  char *grub2ExtractTitle(struct singleLin
466    
467  struct configFileInfo grub2ConfigType = {  struct configFileInfo grub2ConfigType = {
468      .findConfig = grub2FindConfig,      .findConfig = grub2FindConfig,
469        .getEnv = grub2GetEnv,
470        .setEnv = grub2SetEnv,
471      .keywords = grub2Keywords,      .keywords = grub2Keywords,
472      .defaultIsIndex = 1,      .defaultIsIndex = 1,
473      .defaultSupportSaved = 1,      .defaultSupportSaved = 1,
# Line 483  struct configFileInfo ziplConfigType = { Line 622  struct configFileInfo ziplConfigType = {
622  struct configFileInfo extlinuxConfigType = {  struct configFileInfo extlinuxConfigType = {
623      .defaultConfig = "/boot/extlinux/extlinux.conf",      .defaultConfig = "/boot/extlinux/extlinux.conf",
624      .keywords = extlinuxKeywords,      .keywords = extlinuxKeywords,
625        .caseInsensitive = 1,
626      .entryStart = LT_TITLE,      .entryStart = LT_TITLE,
627      .needsBootPrefix = 1,      .needsBootPrefix = 1,
628      .maxTitleLength = 255,      .maxTitleLength = 255,
# Line 507  struct singleEntry * findEntryByIndex(st Line 647  struct singleEntry * findEntryByIndex(st
647  struct singleEntry * findEntryByPath(struct grubConfig * cfg,  struct singleEntry * findEntryByPath(struct grubConfig * cfg,
648       const char * path, const char * prefix,       const char * path, const char * prefix,
649       int * index);       int * index);
650    struct singleEntry * findEntryByTitle(struct grubConfig * cfg, char *title,
651          int * index);
652  static int readFile(int fd, char ** bufPtr);  static int readFile(int fd, char ** bufPtr);
653  static void lineInit(struct singleLine * line);  static void lineInit(struct singleLine * line);
654  struct singleLine * lineDup(struct singleLine * line);  struct singleLine * lineDup(struct singleLine * line);
# Line 571  static char * sdupprintf(const char *for Line 713  static char * sdupprintf(const char *for
713      return buf;      return buf;
714  }  }
715    
716    static enum lineType_e preferredLineType(enum lineType_e type,
717     struct configFileInfo *cfi) {
718        if (isEfi && cfi == &grub2ConfigType) {
719     switch (type) {
720     case LT_KERNEL:
721        return LT_KERNEL_EFI;
722     case LT_INITRD:
723        return LT_INITRD_EFI;
724     default:
725        return type;
726     }
727    #if defined(__i386__) || defined(__x86_64__)
728        } else if (cfi == &grub2ConfigType) {
729     switch (type) {
730     case LT_KERNEL:
731        return LT_KERNEL_16;
732     case LT_INITRD:
733        return LT_INITRD_16;
734     default:
735        return type;
736     }
737    #endif
738        }
739        return type;
740    }
741    
742  static struct keywordTypes * getKeywordByType(enum lineType_e type,  static struct keywordTypes * getKeywordByType(enum lineType_e type,
743        struct configFileInfo * cfi) {        struct configFileInfo * cfi) {
744      struct keywordTypes * kw;      for (struct keywordTypes *kw = cfi->keywords; kw->key; kw++) {
     for (kw = cfi->keywords; kw->key; kw++) {  
745   if (kw->type == type)   if (kw->type == type)
746      return kw;      return kw;
747      }      }
# Line 604  static char * getuuidbydev(char *device) Line 771  static char * getuuidbydev(char *device)
771    
772  static enum lineType_e getTypeByKeyword(char * keyword,  static enum lineType_e getTypeByKeyword(char * keyword,
773   struct configFileInfo * cfi) {   struct configFileInfo * cfi) {
774      struct keywordTypes * kw;      for (struct keywordTypes *kw = cfi->keywords; kw->key; kw++) {
775      for (kw = cfi->keywords; kw->key; kw++) {   if (cfi->caseInsensitive) {
776   if (!strcmp(keyword, kw->key))      if (!strcasecmp(keyword, kw->key))
777      return kw->type;                  return kw->type;
778     } else {
779        if (!strcmp(keyword, kw->key))
780            return kw->type;
781     }
782      }      }
783      return LT_UNKNOWN;      return LT_UNKNOWN;
784  }  }
# Line 646  static int isEntryStart(struct singleLin Line 817  static int isEntryStart(struct singleLin
817  /* extract the title from within brackets (for zipl) */  /* extract the title from within brackets (for zipl) */
818  static char * extractTitle(struct singleLine * line) {  static char * extractTitle(struct singleLine * line) {
819      /* bracketed title... let's extract it (leaks a byte) */      /* bracketed title... let's extract it (leaks a byte) */
820      char * title;      char * title = NULL;
821      title = strdup(line->elements[0].item);      if (line->type == LT_TITLE) {
822      title++;   title = strdup(line->elements[0].item);
823      *(title + strlen(title) - 1) = '\0';   title++;
824     *(title + strlen(title) - 1) = '\0';
825        } else if (line->type == LT_MENUENTRY)
826     title = strdup(line->elements[1].item);
827        else
828     return NULL;
829      return title;      return title;
830  }  }
831    
# Line 692  static void lineInit(struct singleLine * Line 868  static void lineInit(struct singleLine *
868  }  }
869    
870  struct singleLine * lineDup(struct singleLine * line) {  struct singleLine * lineDup(struct singleLine * line) {
     int i;  
871      struct singleLine * newLine = malloc(sizeof(*newLine));      struct singleLine * newLine = malloc(sizeof(*newLine));
872    
873      newLine->indent = strdup(line->indent);      newLine->indent = strdup(line->indent);
# Line 702  struct singleLine * lineDup(struct singl Line 877  struct singleLine * lineDup(struct singl
877      newLine->elements = malloc(sizeof(*newLine->elements) *      newLine->elements = malloc(sizeof(*newLine->elements) *
878         newLine->numElements);         newLine->numElements);
879    
880      for (i = 0; i < newLine->numElements; i++) {      for (int i = 0; i < newLine->numElements; i++) {
881   newLine->elements[i].indent = strdup(line->elements[i].indent);   newLine->elements[i].indent = strdup(line->elements[i].indent);
882   newLine->elements[i].item = strdup(line->elements[i].item);   newLine->elements[i].item = strdup(line->elements[i].item);
883      }      }
# Line 711  struct singleLine * lineDup(struct singl Line 886  struct singleLine * lineDup(struct singl
886  }  }
887    
888  static void lineFree(struct singleLine * line) {  static void lineFree(struct singleLine * line) {
     int i;  
   
889      if (line->indent) free(line->indent);      if (line->indent) free(line->indent);
890    
891      for (i = 0; i < line->numElements; i++) {      for (int i = 0; i < line->numElements; i++) {
892   free(line->elements[i].item);   free(line->elements[i].item);
893   free(line->elements[i].indent);   free(line->elements[i].indent);
894      }      }
# Line 726  static void lineFree(struct singleLine * Line 899  static void lineFree(struct singleLine *
899    
900  static int lineWrite(FILE * out, struct singleLine * line,  static int lineWrite(FILE * out, struct singleLine * line,
901       struct configFileInfo * cfi) {       struct configFileInfo * cfi) {
     int i;  
   
902      if (fprintf(out, "%s", line->indent) == -1) return -1;      if (fprintf(out, "%s", line->indent) == -1) return -1;
903    
904      for (i = 0; i < line->numElements; i++) {      for (int i = 0; i < line->numElements; i++) {
905   /* Need to handle this, because we strip the quotes from   /* Need to handle this, because we strip the quotes from
906   * menuentry when read it. */   * menuentry when read it. */
907   if (line->type == LT_MENUENTRY && i == 1) {   if (line->type == LT_MENUENTRY && i == 1) {
# Line 836  static int getNextLine(char ** bufPtr, s Line 1007  static int getNextLine(char ** bufPtr, s
1007      if (*line->elements[0].item == '#') {      if (*line->elements[0].item == '#') {
1008   char * fullLine;   char * fullLine;
1009   int len;   int len;
  int i;  
1010    
1011   len = strlen(line->indent);   len = strlen(line->indent);
1012   for (i = 0; i < line->numElements; i++)   for (int i = 0; i < line->numElements; i++)
1013      len += strlen(line->elements[i].item) +      len += strlen(line->elements[i].item) +
1014     strlen(line->elements[i].indent);     strlen(line->elements[i].indent);
1015    
# Line 848  static int getNextLine(char ** bufPtr, s Line 1018  static int getNextLine(char ** bufPtr, s
1018   free(line->indent);   free(line->indent);
1019   line->indent = fullLine;   line->indent = fullLine;
1020    
1021   for (i = 0; i < line->numElements; i++) {   for (int i = 0; i < line->numElements; i++) {
1022      strcat(fullLine, line->elements[i].item);      strcat(fullLine, line->elements[i].item);
1023      strcat(fullLine, line->elements[i].indent);      strcat(fullLine, line->elements[i].indent);
1024      free(line->elements[i].item);      free(line->elements[i].item);
# Line 867  static int getNextLine(char ** bufPtr, s Line 1037  static int getNextLine(char ** bufPtr, s
1037   * elements up more   * elements up more
1038   */   */
1039   if (!isspace(kw->separatorChar)) {   if (!isspace(kw->separatorChar)) {
     int i;  
1040      char indent[2] = "";      char indent[2] = "";
1041      indent[0] = kw->separatorChar;      indent[0] = kw->separatorChar;
1042      for (i = 1; i < line->numElements; i++) {      for (int i = 1; i < line->numElements; i++) {
1043   char *p;   char *p;
  int j;  
1044   int numNewElements;   int numNewElements;
1045    
1046   numNewElements = 0;   numNewElements = 0;
# Line 888  static int getNextLine(char ** bufPtr, s Line 1056  static int getNextLine(char ** bufPtr, s
1056      sizeof(*line->elements) * elementsAlloced);      sizeof(*line->elements) * elementsAlloced);
1057   }   }
1058    
1059   for (j = line->numElements; j > i; j--) {   for (int j = line->numElements; j > i; j--) {
1060   line->elements[j + numNewElements] = line->elements[j];   line->elements[j + numNewElements] = line->elements[j];
1061   }   }
1062   line->numElements += numNewElements;   line->numElements += numNewElements;
# Line 915  static int getNextLine(char ** bufPtr, s Line 1083  static int getNextLine(char ** bufPtr, s
1083      return 0;      return 0;
1084  }  }
1085    
1086    static int isnumber(const char *s)
1087    {
1088        int i;
1089        for (i = 0; s[i] != '\0'; i++)
1090     if (s[i] < '0' || s[i] > '9')
1091        return 0;
1092        return i;
1093    }
1094    
1095  static struct grubConfig * readConfig(const char * inName,  static struct grubConfig * readConfig(const char * inName,
1096        struct configFileInfo * cfi) {        struct configFileInfo * cfi) {
1097      int in;      int in;
# Line 926  static struct grubConfig * readConfig(co Line 1103  static struct grubConfig * readConfig(co
1103      struct singleLine * last = NULL, * line, * defaultLine = NULL;      struct singleLine * last = NULL, * line, * defaultLine = NULL;
1104      char * end;      char * end;
1105      struct singleEntry * entry = NULL;      struct singleEntry * entry = NULL;
1106      int i, len;      int len;
1107      char * buf;      char * buf;
1108    
1109      if (!strcmp(inName, "-")) {      if (inName == NULL) {
1110            printf("Could not find bootloader configuration\n");
1111            exit(1);
1112        } else if (!strcmp(inName, "-")) {
1113   in = 0;   in = 0;
1114      } else {      } else {
1115   if ((in = open(inName, O_RDONLY)) < 0) {   if ((in = open(inName, O_RDONLY)) < 0) {
# Line 989  static struct grubConfig * readConfig(co Line 1169  static struct grubConfig * readConfig(co
1169   }   }
1170    
1171   if (line->type == LT_SET_VARIABLE) {   if (line->type == LT_SET_VARIABLE) {
     int i;  
1172      dbgPrintf("found 'set' command (%d elements): ", line->numElements);      dbgPrintf("found 'set' command (%d elements): ", line->numElements);
1173      dbgPrintf("%s", line->indent);      dbgPrintf("%s", line->indent);
1174      for (i = 0; i < line->numElements; i++)      for (int i = 0; i < line->numElements; i++)
1175   dbgPrintf("\"%s\"%s", line->elements[i].item, line->elements[i].indent);   dbgPrintf("\"%s\"%s", line->elements[i].item, line->elements[i].indent);
1176      dbgPrintf("\n");      dbgPrintf("\n");
1177      struct keywordTypes *kwType = getKeywordByType(LT_DEFAULT, cfi);      struct keywordTypes *kwType = getKeywordByType(LT_DEFAULT, cfi);
1178      if (kwType && line->numElements == 3 &&      if (kwType && line->numElements == 3 &&
1179      !strcmp(line->elements[1].item, kwType->key)) {      !strcmp(line->elements[1].item, kwType->key) &&
1180        !is_special_grub2_variable(line->elements[2].item)) {
1181   dbgPrintf("Line sets default config\n");   dbgPrintf("Line sets default config\n");
1182   cfg->flags &= ~GRUB_CONFIG_NO_DEFAULT;   cfg->flags &= ~GRUB_CONFIG_NO_DEFAULT;
1183   defaultLine = line;   defaultLine = line;
# Line 1006  static struct grubConfig * readConfig(co Line 1186  static struct grubConfig * readConfig(co
1186      cfg->flags &= ~GRUB_CONFIG_NO_DEFAULT;      cfg->flags &= ~GRUB_CONFIG_NO_DEFAULT;
1187      defaultLine = line;      defaultLine = line;
1188    
1189          } else if (line->type == LT_KERNEL) {          } else if (iskernel(line->type)) {
1190      /* if by some freak chance this is multiboot and the "module"      /* if by some freak chance this is multiboot and the "module"
1191       * lines came earlier in the template, make sure to use LT_HYPER       * lines came earlier in the template, make sure to use LT_HYPER
1192       * instead of LT_KERNEL now       * instead of LT_KERNEL now
# Line 1020  static struct grubConfig * readConfig(co Line 1200  static struct grubConfig * readConfig(co
1200       * This only applies to grub, but that's the only place we       * This only applies to grub, but that's the only place we
1201       * should find LT_MBMODULE lines anyway.       * should find LT_MBMODULE lines anyway.
1202       */       */
1203      struct singleLine * l;      for (struct singleLine *l = entry->lines; l; l = l->next) {
     for (l = entry->lines; l; l = l->next) {  
1204   if (l->type == LT_HYPER)   if (l->type == LT_HYPER)
1205      break;      break;
1206   else if (l->type == LT_KERNEL) {   else if (iskernel(l->type)) {
1207      l->type = LT_HYPER;      l->type = LT_HYPER;
1208      break;      break;
1209   }   }
# Line 1041  static struct grubConfig * readConfig(co Line 1220  static struct grubConfig * readConfig(co
1220   } else if (line->type == LT_TITLE && line->numElements > 1) {   } else if (line->type == LT_TITLE && line->numElements > 1) {
1221      /* make the title a single argument (undoing our parsing) */      /* make the title a single argument (undoing our parsing) */
1222      len = 0;      len = 0;
1223      for (i = 1; i < line->numElements; i++) {      for (int i = 1; i < line->numElements; i++) {
1224   len += strlen(line->elements[i].item);   len += strlen(line->elements[i].item);
1225   len += strlen(line->elements[i].indent);   len += strlen(line->elements[i].indent);
1226      }      }
1227      buf = malloc(len + 1);      buf = malloc(len + 1);
1228      *buf = '\0';      *buf = '\0';
1229    
1230      for (i = 1; i < line->numElements; i++) {      for (int i = 1; i < line->numElements; i++) {
1231   strcat(buf, line->elements[i].item);   strcat(buf, line->elements[i].item);
1232   free(line->elements[i].item);   free(line->elements[i].item);
1233    
# Line 1068  static struct grubConfig * readConfig(co Line 1247  static struct grubConfig * readConfig(co
1247      char *extras;      char *extras;
1248      char *title;      char *title;
1249    
1250      for (i = 1; i < line->numElements; i++) {      for (int i = 1; i < line->numElements; i++) {
1251   len += strlen(line->elements[i].item);   len += strlen(line->elements[i].item);
1252   len += strlen(line->elements[i].indent);   len += strlen(line->elements[i].indent);
1253      }      }
# Line 1080  static struct grubConfig * readConfig(co Line 1259  static struct grubConfig * readConfig(co
1259      *extras = '\0';      *extras = '\0';
1260    
1261      /* get title. */      /* get title. */
1262      for (i = 0; i < line->numElements; i++) {      for (int i = 0; i < line->numElements; i++) {
1263   if (!strcmp(line->elements[i].item, "menuentry"))   if (!strcmp(line->elements[i].item, "menuentry"))
1264      continue;      continue;
1265   if (isquote(*line->elements[i].item))   if (isquote(*line->elements[i].item))
# Line 1100  static struct grubConfig * readConfig(co Line 1279  static struct grubConfig * readConfig(co
1279    
1280      /* get extras */      /* get extras */
1281      int count = 0;      int count = 0;
1282      for (i = 0; i < line->numElements; i++) {      for (int i = 0; i < line->numElements; i++) {
1283   if (count >= 2) {   if (count >= 2) {
1284      strcat(extras, line->elements[i].item);      strcat(extras, line->elements[i].item);
1285      strcat(extras, line->elements[i].indent);      strcat(extras, line->elements[i].indent);
# Line 1203  static struct grubConfig * readConfig(co Line 1382  static struct grubConfig * readConfig(co
1382          if (defaultLine->numElements > 2 &&          if (defaultLine->numElements > 2 &&
1383      cfi->defaultSupportSaved &&      cfi->defaultSupportSaved &&
1384      !strncmp(defaultLine->elements[2].item,"\"${saved_entry}\"", 16)) {      !strncmp(defaultLine->elements[2].item,"\"${saved_entry}\"", 16)) {
1385      cfg->defaultImage = DEFAULT_SAVED_GRUB2;   cfg->cfi->defaultIsSaved = 1;
1386     cfg->defaultImage = DEFAULT_SAVED_GRUB2;
1387     if (cfg->cfi->getEnv) {
1388        char *defTitle = cfi->getEnv(cfg->cfi, "saved_entry");
1389        if (defTitle) {
1390     int index = 0;
1391     if (isnumber(defTitle)) {
1392        index = atoi(defTitle);
1393        entry = findEntryByIndex(cfg, index);
1394     } else {
1395        entry = findEntryByTitle(cfg, defTitle, &index);
1396     }
1397     if (entry)
1398        cfg->defaultImage = index;
1399        }
1400     }
1401   } else if (cfi->defaultIsVariable) {   } else if (cfi->defaultIsVariable) {
1402      char *value = defaultLine->elements[2].item;      char *value = defaultLine->elements[2].item;
1403      while (*value && (*value == '"' || *value == '\'' ||      while (*value && (*value == '"' || *value == '\'' ||
# Line 1221  static struct grubConfig * readConfig(co Line 1415  static struct grubConfig * readConfig(co
1415      cfg->defaultImage = strtol(defaultLine->elements[1].item, &end, 10);      cfg->defaultImage = strtol(defaultLine->elements[1].item, &end, 10);
1416      if (*end) cfg->defaultImage = -1;      if (*end) cfg->defaultImage = -1;
1417   } else if (defaultLine->numElements >= 2) {   } else if (defaultLine->numElements >= 2) {
1418      i = 0;      int i = 0;
1419      while ((entry = findEntryByIndex(cfg, i))) {      while ((entry = findEntryByIndex(cfg, i))) {
1420   for (line = entry->lines; line; line = line->next)   for (line = entry->lines; line; line = line->next)
1421      if (line->type == LT_TITLE) break;      if (line->type == LT_TITLE) break;
# Line 1244  static struct grubConfig * readConfig(co Line 1438  static struct grubConfig * readConfig(co
1438          cfg->defaultImage = -1;          cfg->defaultImage = -1;
1439      }      }
1440   }   }
1441        } else if (cfg->cfi->defaultIsSaved && cfg->cfi->getEnv) {
1442     char *defTitle = cfi->getEnv(cfg->cfi, "saved_entry");
1443     if (defTitle) {
1444        int index = 0;
1445        if (isnumber(defTitle)) {
1446     index = atoi(defTitle);
1447     entry = findEntryByIndex(cfg, index);
1448        } else {
1449     entry = findEntryByTitle(cfg, defTitle, &index);
1450        }
1451        if (entry)
1452     cfg->defaultImage = index;
1453     }
1454      } else {      } else {
1455          cfg->defaultImage = 0;          cfg->defaultImage = 0;
1456      }      }
# Line 1261  static void writeDefault(FILE * out, cha Line 1468  static void writeDefault(FILE * out, cha
1468    
1469      if (cfg->defaultImage == DEFAULT_SAVED)      if (cfg->defaultImage == DEFAULT_SAVED)
1470   fprintf(out, "%sdefault%ssaved\n", indent, separator);   fprintf(out, "%sdefault%ssaved\n", indent, separator);
1471      else if (cfg->defaultImage == DEFAULT_SAVED_GRUB2)      else if (cfg->cfi->defaultIsSaved) {
1472   fprintf(out, "%sset default=\"${saved_entry}\"\n", indent);   fprintf(out, "%sset default=\"${saved_entry}\"\n", indent);
1473      else if (cfg->defaultImage > -1) {   if (cfg->defaultImage >= 0 && cfg->cfi->setEnv) {
1474        char *title;
1475        entry = findEntryByIndex(cfg, cfg->defaultImage);
1476        line = getLineByType(LT_MENUENTRY, entry->lines);
1477        if (!line)
1478     line = getLineByType(LT_TITLE, entry->lines);
1479        if (line) {
1480     title = extractTitle(line);
1481     if (title)
1482        cfg->cfi->setEnv(cfg->cfi, "saved_entry", title);
1483        }
1484     }
1485        } else if (cfg->defaultImage > -1) {
1486   if (cfg->cfi->defaultIsIndex) {   if (cfg->cfi->defaultIsIndex) {
1487      if (cfg->cfi->defaultIsVariable) {      if (cfg->cfi->defaultIsVariable) {
1488          fprintf(out, "%sset default=\"%d\"\n", indent,          fprintf(out, "%sset default=\"%d\"\n", indent,
# Line 1323  static int writeConfig(struct grubConfig Line 1542  static int writeConfig(struct grubConfig
1542    
1543      /* most likely the symlink is relative, so change our      /* most likely the symlink is relative, so change our
1544         directory to the dir of the symlink */         directory to the dir of the symlink */
1545              rc = chdir(dirname(strdupa(outName)));      char *dir = strdupa(outName);
1546        rc = chdir(dirname(dir));
1547      do {      do {
1548   buf = alloca(len + 1);   buf = alloca(len + 1);
1549   rc = readlink(basename(outName), buf, len);   rc = readlink(basename(outName), buf, len);
# Line 1365  static int writeConfig(struct grubConfig Line 1585  static int writeConfig(struct grubConfig
1585      while (line) {      while (line) {
1586          if (line->type == LT_SET_VARIABLE && defaultKw &&          if (line->type == LT_SET_VARIABLE && defaultKw &&
1587   line->numElements == 3 &&   line->numElements == 3 &&
1588   !strcmp(line->elements[1].item, defaultKw->key)) {   !strcmp(line->elements[1].item, defaultKw->key) &&
1589     !is_special_grub2_variable(line->elements[2].item)) {
1590      writeDefault(out, line->indent, line->elements[0].indent, cfg);      writeDefault(out, line->indent, line->elements[0].indent, cfg);
1591      needs &= ~MAIN_DEFAULT;      needs &= ~MAIN_DEFAULT;
1592   } else if (line->type == LT_DEFAULT) {   } else if (line->type == LT_DEFAULT) {
# Line 1510  static char *findDiskForRoot() Line 1731  static char *findDiskForRoot()
1731      return NULL;      return NULL;
1732  }  }
1733    
1734  void printEntry(struct singleEntry * entry) {  void printEntry(struct singleEntry * entry, FILE *f) {
1735      int i;      int i;
1736      struct singleLine * line;      struct singleLine * line;
1737    
1738      for (line = entry->lines; line; line = line->next) {      for (line = entry->lines; line; line = line->next) {
1739   fprintf(stderr, "DBG: %s", line->indent);   log_message(f, "DBG: %s", line->indent);
1740   for (i = 0; i < line->numElements; i++) {   for (i = 0; i < line->numElements; i++) {
1741      /* Need to handle this, because we strip the quotes from      /* Need to handle this, because we strip the quotes from
1742       * menuentry when read it. */       * menuentry when read it. */
1743      if (line->type == LT_MENUENTRY && i == 1) {      if (line->type == LT_MENUENTRY && i == 1) {
1744   if(!isquote(*line->elements[i].item))   if(!isquote(*line->elements[i].item))
1745      fprintf(stderr, "\'%s\'", line->elements[i].item);      log_message(f, "\'%s\'", line->elements[i].item);
1746   else   else
1747      fprintf(stderr, "%s", line->elements[i].item);      log_message(f, "%s", line->elements[i].item);
1748   fprintf(stderr, "%s", line->elements[i].indent);   log_message(f, "%s", line->elements[i].indent);
1749    
1750   continue;   continue;
1751      }      }
1752            
1753      fprintf(stderr, "%s%s",      log_message(f, "%s%s",
1754      line->elements[i].item, line->elements[i].indent);      line->elements[i].item, line->elements[i].indent);
1755   }   }
1756   fprintf(stderr, "\n");   log_message(f, "\n");
1757      }      }
1758  }  }
1759    
1760  void notSuitablePrintf(struct singleEntry * entry, const char *fmt, ...)  void notSuitablePrintf(struct singleEntry * entry, int okay, const char *fmt, ...)
1761  {  {
1762      va_list argp;      static int once;
1763        va_list argp, argq;
1764    
1765      if (!debug)      va_start(argp, fmt);
1766    
1767        va_copy(argq, argp);
1768        if (!once) {
1769     log_time(NULL);
1770     log_message(NULL, "command line: %s\n", saved_command_line);
1771        }
1772        log_message(NULL, "DBG: Image entry %s: ", okay ? "succeeded" : "failed");
1773        log_vmessage(NULL, fmt, argq);
1774    
1775        printEntry(entry, NULL);
1776        va_end(argq);
1777    
1778        if (!debug) {
1779     once = 1;
1780         va_end(argp);
1781   return;   return;
1782        }
1783    
1784      va_start(argp, fmt);      if (okay) {
1785     va_end(argp);
1786     return;
1787        }
1788    
1789        if (!once)
1790     log_message(stderr, "DBG: command line: %s\n", saved_command_line);
1791        once = 1;
1792      fprintf(stderr, "DBG: Image entry failed: ");      fprintf(stderr, "DBG: Image entry failed: ");
1793      vfprintf(stderr, fmt, argp);      vfprintf(stderr, fmt, argp);
1794      printEntry(entry);      printEntry(entry, stderr);
1795      va_end(argp);      va_end(argp);
1796  }  }
1797    
# Line 1573  int suitableImage(struct singleEntry * e Line 1818  int suitableImage(struct singleEntry * e
1818      char * rootdev;      char * rootdev;
1819    
1820      if (skipRemoved && entry->skip) {      if (skipRemoved && entry->skip) {
1821   notSuitablePrintf(entry, "marked to skip\n");   notSuitablePrintf(entry, 0, "marked to skip\n");
1822   return 0;   return 0;
1823      }      }
1824    
1825      line = getLineByType(LT_KERNEL|LT_HYPER, entry->lines);      line = getLineByType(LT_KERNEL|LT_HYPER|LT_KERNEL_EFI|LT_KERNEL_16, entry->lines);
1826      if (!line) {      if (!line) {
1827   notSuitablePrintf(entry, "no line found\n");   notSuitablePrintf(entry, 0, "no line found\n");
1828   return 0;   return 0;
1829      }      }
1830      if (line->numElements < 2) {      if (line->numElements < 2) {
1831   notSuitablePrintf(entry, "line has only %d elements\n",   notSuitablePrintf(entry, 0, "line has only %d elements\n",
1832      line->numElements);      line->numElements);
1833   return 0;   return 0;
1834      }      }
1835    
1836      if (flags & GRUBBY_BADIMAGE_OKAY) return 1;      if (flags & GRUBBY_BADIMAGE_OKAY) {
1837        notSuitablePrintf(entry, 1, "\n");
1838        return 1;
1839        }
1840    
1841      fullName = alloca(strlen(bootPrefix) +      fullName = alloca(strlen(bootPrefix) +
1842        strlen(line->elements[1].item) + 1);        strlen(line->elements[1].item) + 1);
# Line 1599  int suitableImage(struct singleEntry * e Line 1847  int suitableImage(struct singleEntry * e
1847      sprintf(fullName, "%s%s%s", bootPrefix, hasslash ? "" : "/",      sprintf(fullName, "%s%s%s", bootPrefix, hasslash ? "" : "/",
1848              line->elements[1].item + rootspec_offset);              line->elements[1].item + rootspec_offset);
1849      if (access(fullName, R_OK)) {      if (access(fullName, R_OK)) {
1850   notSuitablePrintf(entry, "access to %s failed\n", fullName);   notSuitablePrintf(entry, 0, "access to %s failed\n", fullName);
1851   return 0;   return 0;
1852      }      }
1853      for (i = 2; i < line->numElements; i++)      for (i = 2; i < line->numElements; i++)
# Line 1620  int suitableImage(struct singleEntry * e Line 1868  int suitableImage(struct singleEntry * e
1868    
1869              /* failed to find one */              /* failed to find one */
1870              if (!line) {              if (!line) {
1871   notSuitablePrintf(entry, "no line found\n");   notSuitablePrintf(entry, 0, "no line found\n");
1872   return 0;   return 0;
1873              }              }
1874    
# Line 1629  int suitableImage(struct singleEntry * e Line 1877  int suitableImage(struct singleEntry * e
1877      if (i < line->numElements)      if (i < line->numElements)
1878          dev = line->elements[i].item + 5;          dev = line->elements[i].item + 5;
1879      else {      else {
1880   notSuitablePrintf(entry, "no root= entry found\n");   notSuitablePrintf(entry, 0, "no root= entry found\n");
1881   /* it failed too...  can't find root= */   /* it failed too...  can't find root= */
1882          return 0;          return 0;
1883              }              }
# Line 1638  int suitableImage(struct singleEntry * e Line 1886  int suitableImage(struct singleEntry * e
1886    
1887      dev = getpathbyspec(dev);      dev = getpathbyspec(dev);
1888      if (!getpathbyspec(dev)) {      if (!getpathbyspec(dev)) {
1889          notSuitablePrintf(entry, "can't find blkid entry for %s\n", dev);          notSuitablePrintf(entry, 0, "can't find blkid entry for %s\n", dev);
1890          return 0;          return 0;
1891      } else      } else
1892   dev = getpathbyspec(dev);   dev = getpathbyspec(dev);
1893    
1894      rootdev = findDiskForRoot();      rootdev = findDiskForRoot();
1895      if (!rootdev) {      if (!rootdev) {
1896          notSuitablePrintf(entry, "can't find root device\n");          notSuitablePrintf(entry, 0, "can't find root device\n");
1897   return 0;   return 0;
1898      }      }
1899    
1900      if (!getuuidbydev(rootdev) || !getuuidbydev(dev)) {      if (!getuuidbydev(rootdev) || !getuuidbydev(dev)) {
1901          notSuitablePrintf(entry, "uuid missing: rootdev %s, dev %s\n",          notSuitablePrintf(entry, 0, "uuid missing: rootdev %s, dev %s\n",
1902   getuuidbydev(rootdev), getuuidbydev(dev));   getuuidbydev(rootdev), getuuidbydev(dev));
1903          free(rootdev);          free(rootdev);
1904          return 0;          return 0;
1905      }      }
1906    
1907      if (strcmp(getuuidbydev(rootdev), getuuidbydev(dev))) {      if (strcmp(getuuidbydev(rootdev), getuuidbydev(dev))) {
1908          notSuitablePrintf(entry, "uuid mismatch: rootdev %s, dev %s\n",          notSuitablePrintf(entry, 0, "uuid mismatch: rootdev %s, dev %s\n",
1909   getuuidbydev(rootdev), getuuidbydev(dev));   getuuidbydev(rootdev), getuuidbydev(dev));
1910   free(rootdev);   free(rootdev);
1911          return 0;          return 0;
1912      }      }
1913    
1914      free(rootdev);      free(rootdev);
1915        notSuitablePrintf(entry, 1, "\n");
1916    
1917      return 1;      return 1;
1918  }  }
# Line 1707  struct singleEntry * findEntryByPath(str Line 1956  struct singleEntry * findEntryByPath(str
1956   entry = findEntryByIndex(config, indexVars[i]);   entry = findEntryByIndex(config, indexVars[i]);
1957   if (!entry) return NULL;   if (!entry) return NULL;
1958    
1959   line = getLineByType(LT_KERNEL|LT_HYPER, entry->lines);   line = getLineByType(LT_KERNEL|LT_HYPER|LT_KERNEL_EFI|LT_KERNEL_16, entry->lines);
1960   if (!line) return NULL;   if (!line) return NULL;
1961    
1962   if (index) *index = indexVars[i];   if (index) *index = indexVars[i];
# Line 1756  struct singleEntry * findEntryByPath(str Line 2005  struct singleEntry * findEntryByPath(str
2005    
2006      /* check all the lines matching checkType */      /* check all the lines matching checkType */
2007      for (line = entry->lines; line; line = line->next) {      for (line = entry->lines; line; line = line->next) {
2008   line = getLineByType(entry->multiboot && checkType == LT_KERNEL ?   enum lineType_e ct = checkType;
2009       LT_KERNEL|LT_MBMODULE|LT_HYPER :   if (entry->multiboot && checkType == LT_KERNEL)
2010       checkType, line);      ct = LT_KERNEL|LT_KERNEL_EFI|LT_MBMODULE|LT_HYPER|LT_KERNEL_16;
2011   if (!line) break;  /* not found in this entry */   else if (checkType & LT_KERNEL)
2012        ct = checkType | LT_KERNEL_EFI | LT_KERNEL_16;
2013     line = getLineByType(ct, line);
2014     if (!line)
2015        break;  /* not found in this entry */
2016    
2017   if (line && line->type != LT_MENUENTRY &&   if (line && line->type != LT_MENUENTRY &&
2018   line->numElements >= 2) {   line->numElements >= 2) {
# Line 1778  struct singleEntry * findEntryByPath(str Line 2031  struct singleEntry * findEntryByPath(str
2031       * non-Linux boot entries (could find netbsd etc, though, which is       * non-Linux boot entries (could find netbsd etc, though, which is
2032       * unfortunate)       * unfortunate)
2033       */       */
2034      if (line && getLineByType(LT_KERNEL|LT_HYPER, entry->lines))      if (line && getLineByType(LT_KERNEL|LT_HYPER|LT_KERNEL_EFI|LT_KERNEL_16, entry->lines))
2035   break; /* found 'im! */   break; /* found 'im! */
2036   }   }
2037    
# Line 1788  struct singleEntry * findEntryByPath(str Line 2041  struct singleEntry * findEntryByPath(str
2041      return entry;      return entry;
2042  }  }
2043    
2044    struct singleEntry * findEntryByTitle(struct grubConfig * cfg, char *title,
2045          int * index) {
2046        struct singleEntry * entry;
2047        struct singleLine * line;
2048        int i;
2049        char * newtitle;
2050    
2051        for (i = 0, entry = cfg->entries; entry; entry = entry->next, i++) {
2052     if (index && i < *index)
2053        continue;
2054     line = getLineByType(LT_TITLE, entry->lines);
2055     if (!line)
2056        line = getLineByType(LT_MENUENTRY, entry->lines);
2057     if (!line)
2058        continue;
2059     newtitle = grub2ExtractTitle(line);
2060     if (!newtitle)
2061        continue;
2062     if (!strcmp(title, newtitle))
2063        break;
2064        }
2065    
2066        if (!entry)
2067     return NULL;
2068    
2069        if (index)
2070     *index = i;
2071        return entry;
2072    }
2073    
2074  struct singleEntry * findEntryByIndex(struct grubConfig * cfg, int index) {  struct singleEntry * findEntryByIndex(struct grubConfig * cfg, int index) {
2075      struct singleEntry * entry;      struct singleEntry * entry;
2076    
# Line 1810  struct singleEntry * findTemplate(struct Line 2093  struct singleEntry * findTemplate(struct
2093      struct singleEntry * entry, * entry2;      struct singleEntry * entry, * entry2;
2094      int index;      int index;
2095    
2096      if (cfg->defaultImage > -1) {      if (cfg->cfi->defaultIsSaved) {
2097     if (cfg->cfi->getEnv) {
2098        char *defTitle = cfg->cfi->getEnv(cfg->cfi, "saved_entry");
2099        if (defTitle) {
2100     int index = 0;
2101     if (isnumber(defTitle)) {
2102        index = atoi(defTitle);
2103        entry = findEntryByIndex(cfg, index);
2104     } else {
2105        entry = findEntryByTitle(cfg, defTitle, &index);
2106     }
2107     if (entry)
2108        cfg->defaultImage = index;
2109        }
2110     }
2111        } else if (cfg->defaultImage > -1) {
2112   entry = findEntryByIndex(cfg, cfg->defaultImage);   entry = findEntryByIndex(cfg, cfg->defaultImage);
2113   if (entry && suitableImage(entry, prefix, skipRemoved, flags)) {   if (entry && suitableImage(entry, prefix, skipRemoved, flags)) {
2114      if (indexPtr) *indexPtr = cfg->defaultImage;      if (indexPtr) *indexPtr = cfg->defaultImage;
# Line 1880  void markRemovedImage(struct grubConfig Line 2178  void markRemovedImage(struct grubConfig
2178    
2179  void setDefaultImage(struct grubConfig * config, int hasNew,  void setDefaultImage(struct grubConfig * config, int hasNew,
2180       const char * defaultKernelPath, int newIsDefault,       const char * defaultKernelPath, int newIsDefault,
2181       const char * prefix, int flags) {       const char * prefix, int flags, int index) {
2182      struct singleEntry * entry, * entry2, * newDefault;      struct singleEntry * entry, * entry2, * newDefault;
2183      int i, j;      int i, j;
2184    
2185      if (newIsDefault) {      if (newIsDefault) {
2186   config->defaultImage = 0;   config->defaultImage = 0;
2187   return;   return;
2188        } else if ((index >= 0) && config->cfi->defaultIsIndex) {
2189     if (findEntryByIndex(config, index))
2190        config->defaultImage = index;
2191     else
2192        config->defaultImage = -1;
2193     return;
2194      } else if (defaultKernelPath) {      } else if (defaultKernelPath) {
2195   i = 0;   i = 0;
2196   if (findEntryByPath(config, defaultKernelPath, prefix, &i)) {   if (findEntryByPath(config, defaultKernelPath, prefix, &i)) {
# Line 1961  void displayEntry(struct singleEntry * e Line 2265  void displayEntry(struct singleEntry * e
2265    
2266      printf("index=%d\n", index);      printf("index=%d\n", index);
2267    
2268      line = getLineByType(LT_KERNEL|LT_HYPER, entry->lines);      line = getLineByType(LT_KERNEL|LT_HYPER|LT_KERNEL_EFI|LT_KERNEL_16, entry->lines);
2269      if (!line) {      if (!line) {
2270          printf("non linux entry\n");          printf("non linux entry\n");
2271          return;          return;
2272      }      }
2273    
2274      printf("kernel=%s%s\n", prefix, line->elements[1].item);      if (!strncmp(prefix, line->elements[1].item, strlen(prefix)))
2275     printf("kernel=%s\n", line->elements[1].item);
2276        else
2277     printf("kernel=%s%s\n", prefix, line->elements[1].item);
2278    
2279      if (line->numElements >= 3) {      if (line->numElements >= 3) {
2280   printf("args=\"");   printf("args=\"");
# Line 2023  void displayEntry(struct singleEntry * e Line 2330  void displayEntry(struct singleEntry * e
2330   printf("root=%s\n", s);   printf("root=%s\n", s);
2331      }      }
2332    
2333      line = getLineByType(LT_INITRD, entry->lines);      line = getLineByType(LT_INITRD|LT_INITRD_EFI|LT_INITRD_16, entry->lines);
2334    
2335      if (line && line->numElements >= 2) {      if (line && line->numElements >= 2) {
2336   printf("initrd=%s", prefix);   if (!strncmp(prefix, line->elements[1].item, strlen(prefix)))
2337        printf("initrd=");
2338     else
2339        printf("initrd=%s", prefix);
2340    
2341   for (i = 1; i < line->numElements; i++)   for (i = 1; i < line->numElements; i++)
2342      printf("%s%s", line->elements[i].item, line->elements[i].indent);      printf("%s%s", line->elements[i].item, line->elements[i].indent);
2343   printf("\n");   printf("\n");
# Line 2044  void displayEntry(struct singleEntry * e Line 2355  void displayEntry(struct singleEntry * e
2355      }      }
2356  }  }
2357    
2358    int isSuseSystem(void) {
2359        const char * path;
2360        const static char default_path[] = "/etc/SuSE-release";
2361    
2362        if ((path = getenv("GRUBBY_SUSE_RELEASE")) == NULL)
2363     path = default_path;
2364    
2365        if (!access(path, R_OK))
2366     return 1;
2367        return 0;
2368    }
2369    
2370    int isSuseGrubConf(const char * path) {
2371        FILE * grubConf;
2372        char * line = NULL;
2373        size_t len = 0, res = 0;
2374    
2375        grubConf = fopen(path, "r");
2376        if (!grubConf) {
2377            dbgPrintf("Could not open SuSE configuration file '%s'\n", path);
2378     return 0;
2379        }
2380    
2381        while ((res = getline(&line, &len, grubConf)) != -1) {
2382     if (!strncmp(line, "setup", 5)) {
2383        fclose(grubConf);
2384        free(line);
2385        return 1;
2386     }
2387        }
2388    
2389        dbgPrintf("SuSE configuration file '%s' does not appear to be valid\n",
2390          path);
2391    
2392        fclose(grubConf);
2393        free(line);
2394        return 0;
2395    }
2396    
2397    int suseGrubConfGetLba(const char * path, int * lbaPtr) {
2398        FILE * grubConf;
2399        char * line = NULL;
2400        size_t res = 0, len = 0;
2401    
2402        if (!path) return 1;
2403        if (!lbaPtr) return 1;
2404    
2405        grubConf = fopen(path, "r");
2406        if (!grubConf) return 1;
2407    
2408        while ((res = getline(&line, &len, grubConf)) != -1) {
2409     if (line[res - 1] == '\n')
2410        line[res - 1] = '\0';
2411     else if (len > res)
2412        line[res] = '\0';
2413     else {
2414        line = realloc(line, res + 1);
2415        line[res] = '\0';
2416     }
2417    
2418     if (!strncmp(line, "setup", 5)) {
2419        if (strstr(line, "--force-lba")) {
2420            *lbaPtr = 1;
2421        } else {
2422            *lbaPtr = 0;
2423        }
2424        dbgPrintf("lba: %i\n", *lbaPtr);
2425        break;
2426     }
2427        }
2428    
2429        free(line);
2430        fclose(grubConf);
2431        return 0;
2432    }
2433    
2434    int suseGrubConfGetInstallDevice(const char * path, char ** devicePtr) {
2435        FILE * grubConf;
2436        char * line = NULL;
2437        size_t res = 0, len = 0;
2438        char * lastParamPtr = NULL;
2439        char * secLastParamPtr = NULL;
2440        char installDeviceNumber = '\0';
2441        char * bounds = NULL;
2442    
2443        if (!path) return 1;
2444        if (!devicePtr) return 1;
2445    
2446        grubConf = fopen(path, "r");
2447        if (!grubConf) return 1;
2448    
2449        while ((res = getline(&line, &len, grubConf)) != -1) {
2450     if (strncmp(line, "setup", 5))
2451        continue;
2452    
2453     if (line[res - 1] == '\n')
2454        line[res - 1] = '\0';
2455     else if (len > res)
2456        line[res] = '\0';
2457     else {
2458        line = realloc(line, res + 1);
2459        line[res] = '\0';
2460     }
2461    
2462     lastParamPtr = bounds = line + res;
2463    
2464     /* Last parameter in grub may be an optional IMAGE_DEVICE */
2465     while (!isspace(*lastParamPtr))
2466        lastParamPtr--;
2467     lastParamPtr++;
2468    
2469     secLastParamPtr = lastParamPtr - 2;
2470     dbgPrintf("lastParamPtr: %s\n", lastParamPtr);
2471    
2472     if (lastParamPtr + 3 > bounds) {
2473        dbgPrintf("lastParamPtr going over boundary");
2474        fclose(grubConf);
2475        free(line);
2476        return 1;
2477     }
2478     if (!strncmp(lastParamPtr, "(hd", 3))
2479        lastParamPtr += 3;
2480     dbgPrintf("lastParamPtr: %c\n", *lastParamPtr);
2481    
2482     /*
2483     * Second last parameter will decide wether last parameter is
2484     * an IMAGE_DEVICE or INSTALL_DEVICE
2485     */
2486     while (!isspace(*secLastParamPtr))
2487        secLastParamPtr--;
2488     secLastParamPtr++;
2489    
2490     if (secLastParamPtr + 3 > bounds) {
2491        dbgPrintf("secLastParamPtr going over boundary");
2492        fclose(grubConf);
2493        free(line);
2494        return 1;
2495     }
2496     dbgPrintf("secLastParamPtr: %s\n", secLastParamPtr);
2497     if (!strncmp(secLastParamPtr, "(hd", 3)) {
2498        secLastParamPtr += 3;
2499        dbgPrintf("secLastParamPtr: %c\n", *secLastParamPtr);
2500        installDeviceNumber = *secLastParamPtr;
2501     } else {
2502        installDeviceNumber = *lastParamPtr;
2503     }
2504    
2505     *devicePtr = malloc(6);
2506     snprintf(*devicePtr, 6, "(hd%c)", installDeviceNumber);
2507     dbgPrintf("installDeviceNumber: %c\n", installDeviceNumber);
2508     fclose(grubConf);
2509     free(line);
2510     return 0;
2511        }
2512    
2513        free(line);
2514        fclose(grubConf);
2515        return 1;
2516    }
2517    
2518    int grubGetBootFromDeviceMap(const char * device,
2519         char ** bootPtr) {
2520        FILE * deviceMap;
2521        char * line = NULL;
2522        size_t res = 0, len = 0;
2523        char * devicePtr;
2524        char * bounds = NULL;
2525        const char * path;
2526        const static char default_path[] = "/boot/grub/device.map";
2527    
2528        if (!device) return 1;
2529        if (!bootPtr) return 1;
2530    
2531        if ((path = getenv("GRUBBY_GRUB_DEVICE_MAP")) == NULL)
2532     path = default_path;
2533    
2534        dbgPrintf("opening grub device.map file from: %s\n", path);
2535        deviceMap = fopen(path, "r");
2536        if (!deviceMap)
2537     return 1;
2538    
2539        while ((res = getline(&line, &len, deviceMap)) != -1) {
2540            if (!strncmp(line, "#", 1))
2541        continue;
2542    
2543     if (line[res - 1] == '\n')
2544        line[res - 1] = '\0';
2545     else if (len > res)
2546        line[res] = '\0';
2547     else {
2548        line = realloc(line, res + 1);
2549        line[res] = '\0';
2550     }
2551    
2552     devicePtr = line;
2553     bounds = line + res;
2554    
2555     while ((isspace(*line) && ((devicePtr + 1) <= bounds)))
2556        devicePtr++;
2557     dbgPrintf("device: %s\n", devicePtr);
2558    
2559     if (!strncmp(devicePtr, device, strlen(device))) {
2560        devicePtr += strlen(device);
2561        while (isspace(*devicePtr) && ((devicePtr + 1) <= bounds))
2562            devicePtr++;
2563    
2564        *bootPtr = strdup(devicePtr);
2565        break;
2566     }
2567        }
2568    
2569        free(line);
2570        fclose(deviceMap);
2571        return 0;
2572    }
2573    
2574    int suseGrubConfGetBoot(const char * path, char ** bootPtr) {
2575        char * grubDevice;
2576    
2577        if (suseGrubConfGetInstallDevice(path, &grubDevice))
2578     dbgPrintf("error looking for grub installation device\n");
2579        else
2580     dbgPrintf("grubby installation device: %s\n", grubDevice);
2581    
2582        if (grubGetBootFromDeviceMap(grubDevice, bootPtr))
2583     dbgPrintf("error looking for grub boot device\n");
2584        else
2585     dbgPrintf("grubby boot device: %s\n", *bootPtr);
2586    
2587        free(grubDevice);
2588        return 0;
2589    }
2590    
2591    int parseSuseGrubConf(int * lbaPtr, char ** bootPtr) {
2592        /*
2593         * This SuSE grub configuration file at this location is not your average
2594         * grub configuration file, but instead the grub commands used to setup
2595         * grub on that system.
2596         */
2597        const char * path;
2598        const static char default_path[] = "/etc/grub.conf";
2599    
2600        if ((path = getenv("GRUBBY_SUSE_GRUB_CONF")) == NULL)
2601     path = default_path;
2602    
2603        if (!isSuseGrubConf(path)) return 1;
2604    
2605        if (lbaPtr) {
2606            *lbaPtr = 0;
2607            if (suseGrubConfGetLba(path, lbaPtr))
2608                return 1;
2609        }
2610    
2611        if (bootPtr) {
2612            *bootPtr = NULL;
2613            suseGrubConfGetBoot(path, bootPtr);
2614        }
2615    
2616        return 0;
2617    }
2618    
2619  int parseSysconfigGrub(int * lbaPtr, char ** bootPtr) {  int parseSysconfigGrub(int * lbaPtr, char ** bootPtr) {
2620      FILE * in;      FILE * in;
2621      char buf[1024];      char buf[1024];
# Line 2092  int parseSysconfigGrub(int * lbaPtr, cha Line 2664  int parseSysconfigGrub(int * lbaPtr, cha
2664  }  }
2665    
2666  void dumpSysconfigGrub(void) {  void dumpSysconfigGrub(void) {
2667      char * boot;      char * boot = NULL;
2668      int lba;      int lba;
2669    
2670      if (!parseSysconfigGrub(&lba, &boot)) {      if (isSuseSystem()) {
2671   if (lba) printf("lba\n");          if (parseSuseGrubConf(&lba, &boot)) {
2672   if (boot) printf("boot=%s\n", boot);      free(boot);
2673        return;
2674     }
2675        } else {
2676            if (parseSysconfigGrub(&lba, &boot)) {
2677        free(boot);
2678        return;
2679     }
2680        }
2681    
2682        if (lba) printf("lba\n");
2683        if (boot) {
2684     printf("boot=%s\n", boot);
2685     free(boot);
2686      }      }
2687  }  }
2688    
# Line 2146  struct singleLine * addLineTmpl(struct s Line 2731  struct singleLine * addLineTmpl(struct s
2731  {  {
2732      struct singleLine * newLine = lineDup(tmplLine);      struct singleLine * newLine = lineDup(tmplLine);
2733    
2734        if (isEfi && cfi == &grub2ConfigType) {
2735     enum lineType_e old = newLine->type;
2736     newLine->type = preferredLineType(newLine->type, cfi);
2737     if (old != newLine->type)
2738        newLine->elements[0].item = getKeyByType(newLine->type, cfi);
2739        }
2740    
2741      if (val) {      if (val) {
2742   /* override the inherited value with our own.   /* override the inherited value with our own.
2743   * This is a little weak because it only applies to elements[1]   * This is a little weak because it only applies to elements[1]
# Line 2155  struct singleLine * addLineTmpl(struct s Line 2747  struct singleLine * addLineTmpl(struct s
2747   insertElement(newLine, val, 1, cfi);   insertElement(newLine, val, 1, cfi);
2748    
2749   /* but try to keep the rootspec from the template... sigh */   /* but try to keep the rootspec from the template... sigh */
2750   if (tmplLine->type & (LT_HYPER|LT_KERNEL|LT_MBMODULE|LT_INITRD)) {   if (tmplLine->type & (LT_HYPER|LT_KERNEL|LT_MBMODULE|LT_INITRD|LT_KERNEL_EFI|LT_INITRD_EFI|LT_KERNEL_16|LT_INITRD_16)) {
2751      char * rootspec = getRootSpecifier(tmplLine->elements[1].item);      char * rootspec = getRootSpecifier(tmplLine->elements[1].item);
2752      if (rootspec != NULL) {      if (rootspec != NULL) {
2753   free(newLine->elements[1].item);   free(newLine->elements[1].item);
# Line 2192  struct singleLine *  addLine(struct sing Line 2784  struct singleLine *  addLine(struct sing
2784      /* NB: This function shouldn't allocate items on the heap, rather on the      /* NB: This function shouldn't allocate items on the heap, rather on the
2785       * stack since it calls addLineTmpl which will make copies.       * stack since it calls addLineTmpl which will make copies.
2786       */       */
   
2787      if (type == LT_TITLE && cfi->titleBracketed) {      if (type == LT_TITLE && cfi->titleBracketed) {
2788   /* we're doing a bracketed title (zipl) */   /* we're doing a bracketed title (zipl) */
2789   tmpl.type = type;   tmpl.type = type;
# Line 2526  int updateActualImage(struct grubConfig Line 3117  int updateActualImage(struct grubConfig
3117      firstElement = 2;      firstElement = 2;
3118    
3119   } else {   } else {
3120      line = getLineByType(LT_KERNEL|LT_MBMODULE, entry->lines);      line = getLineByType(LT_KERNEL|LT_MBMODULE|LT_KERNEL_EFI|LT_KERNEL_16, entry->lines);
3121      if (!line) {      if (!line) {
3122   /* no LT_KERNEL or LT_MBMODULE in this entry? */   /* no LT_KERNEL or LT_MBMODULE in this entry? */
3123   continue;   continue;
# Line 2682  int updateImage(struct grubConfig * cfg, Line 3273  int updateImage(struct grubConfig * cfg,
3273      return rc;      return rc;
3274  }  }
3275    
3276    int addMBInitrd(struct grubConfig * cfg, const char *newMBKernel,
3277     const char * image, const char * prefix, const char * initrd) {
3278        struct singleEntry * entry;
3279        struct singleLine * line, * kernelLine, *endLine = NULL;
3280        int index = 0;
3281    
3282        if (!image) return 0;
3283    
3284        for (; (entry = findEntryByPath(cfg, newMBKernel, prefix, &index)); index++) {
3285            kernelLine = getLineByType(LT_MBMODULE, entry->lines);
3286            if (!kernelLine) continue;
3287    
3288            if (prefix) {
3289                int prefixLen = strlen(prefix);
3290                if (!strncmp(initrd, prefix, prefixLen))
3291                    initrd += prefixLen;
3292            }
3293     endLine = getLineByType(LT_ENTRY_END, entry->lines);
3294     if (endLine)
3295        removeLine(entry, endLine);
3296            line = addLine(entry, cfg->cfi, preferredLineType(LT_MBMODULE,cfg->cfi),
3297     kernelLine->indent, initrd);
3298            if (!line)
3299        return 1;
3300     if (endLine) {
3301        line = addLine(entry, cfg->cfi, LT_ENTRY_END, "", NULL);
3302                if (!line)
3303     return 1;
3304     }
3305    
3306            break;
3307        }
3308    
3309        return 0;
3310    }
3311    
3312  int updateInitrd(struct grubConfig * cfg, const char * image,  int updateInitrd(struct grubConfig * cfg, const char * image,
3313                   const char * prefix, const char * initrd) {                   const char * prefix, const char * initrd) {
3314      struct singleEntry * entry;      struct singleEntry * entry;
# Line 2691  int updateInitrd(struct grubConfig * cfg Line 3318  int updateInitrd(struct grubConfig * cfg
3318      if (!image) return 0;      if (!image) return 0;
3319    
3320      for (; (entry = findEntryByPath(cfg, image, prefix, &index)); index++) {      for (; (entry = findEntryByPath(cfg, image, prefix, &index)); index++) {
3321          kernelLine = getLineByType(LT_KERNEL, entry->lines);          kernelLine = getLineByType(LT_KERNEL|LT_KERNEL_EFI|LT_KERNEL_16, entry->lines);
3322          if (!kernelLine) continue;          if (!kernelLine) continue;
3323    
3324          line = getLineByType(LT_INITRD, entry->lines);          line = getLineByType(LT_INITRD|LT_INITRD_EFI|LT_INITRD_16, entry->lines);
3325          if (line)          if (line)
3326              removeLine(entry, line);              removeLine(entry, line);
3327          if (prefix) {          if (prefix) {
# Line 2705  int updateInitrd(struct grubConfig * cfg Line 3332  int updateInitrd(struct grubConfig * cfg
3332   endLine = getLineByType(LT_ENTRY_END, entry->lines);   endLine = getLineByType(LT_ENTRY_END, entry->lines);
3333   if (endLine)   if (endLine)
3334      removeLine(entry, endLine);      removeLine(entry, endLine);
3335          line = addLine(entry, cfg->cfi, LT_INITRD, kernelLine->indent, initrd);   enum lineType_e lt;
3336     switch(kernelLine->type) {
3337        case LT_KERNEL:
3338            lt = LT_INITRD;
3339     break;
3340        case LT_KERNEL_EFI:
3341            lt = LT_INITRD_EFI;
3342     break;
3343        case LT_KERNEL_16:
3344            lt = LT_INITRD_16;
3345     break;
3346        default:
3347            lt = preferredLineType(LT_INITRD, cfg->cfi);
3348     }
3349            line = addLine(entry, cfg->cfi, lt, kernelLine->indent, initrd);
3350          if (!line)          if (!line)
3351      return 1;      return 1;
3352   if (endLine) {   if (endLine) {
# Line 2911  int checkForGrub(struct grubConfig * con Line 3552  int checkForGrub(struct grubConfig * con
3552      int fd;      int fd;
3553      unsigned char bootSect[512];      unsigned char bootSect[512];
3554      char * boot;      char * boot;
3555        int onSuse = isSuseSystem();
3556    
3557      if (parseSysconfigGrub(NULL, &boot))  
3558   return 0;      if (onSuse) {
3559     if (parseSuseGrubConf(NULL, &boot))
3560        return 0;
3561        } else {
3562     if (parseSysconfigGrub(NULL, &boot))
3563        return 0;
3564        }
3565    
3566      /* assume grub is not installed -- not an error condition */      /* assume grub is not installed -- not an error condition */
3567      if (!boot)      if (!boot)
# Line 2932  int checkForGrub(struct grubConfig * con Line 3580  int checkForGrub(struct grubConfig * con
3580      }      }
3581      close(fd);      close(fd);
3582    
3583        /* The more elaborate checks do not work on SuSE. The checks done
3584         * seem to be reasonble (at least for now), so just return success
3585         */
3586        if (onSuse)
3587     return 2;
3588    
3589      return checkDeviceBootloader(boot, bootSect);      return checkDeviceBootloader(boot, bootSect);
3590  }  }
3591    
# Line 2965  int checkForExtLinux(struct grubConfig * Line 3619  int checkForExtLinux(struct grubConfig *
3619      return checkDeviceBootloader(boot, bootSect);      return checkDeviceBootloader(boot, bootSect);
3620  }  }
3621    
3622    int checkForYaboot(struct grubConfig * config) {
3623        /*
3624         * This is a simplistic check that we consider good enough for own puporses
3625         *
3626         * If we were to properly check if yaboot is *installed* we'd need to:
3627         * 1) get the system boot device (LT_BOOT)
3628         * 2) considering it's a raw filesystem, check if the yaboot binary matches
3629         *    the content on the boot device
3630         * 3) if not, copy the binary to a temporary file and run "addnote" on it
3631         * 4) check again if binary and boot device contents match
3632         */
3633        if (!access("/etc/yaboot.conf", R_OK))
3634     return 2;
3635    
3636        return 1;
3637    }
3638    
3639    int checkForElilo(struct grubConfig * config) {
3640        if (!access("/etc/elilo.conf", R_OK))
3641     return 2;
3642    
3643        return 1;
3644    }
3645    
3646  static char * getRootSpecifier(char * str) {  static char * getRootSpecifier(char * str) {
3647      char * idx, * rootspec = NULL;      char * idx, * rootspec = NULL;
3648    
# Line 3081  int addNewKernel(struct grubConfig * con Line 3759  int addNewKernel(struct grubConfig * con
3759      while (*chptr && isspace(*chptr)) chptr++;      while (*chptr && isspace(*chptr)) chptr++;
3760      if (*chptr == '#') continue;      if (*chptr == '#') continue;
3761    
3762      if (tmplLine->type == LT_KERNEL &&      if (iskernel(tmplLine->type) && tmplLine->numElements >= 2) {
     tmplLine->numElements >= 2) {  
3763   if (!template->multiboot && (needs & NEED_MB)) {   if (!template->multiboot && (needs & NEED_MB)) {
3764      /* it's not a multiboot template and this is the kernel      /* it's not a multiboot template and this is the kernel
3765       * line.  Try to be intelligent about inserting the       * line.  Try to be intelligent about inserting the
# Line 3159  int addNewKernel(struct grubConfig * con Line 3836  int addNewKernel(struct grubConfig * con
3836      /* template is multi but new is not,      /* template is multi but new is not,
3837       * insert the kernel in the first module slot       * insert the kernel in the first module slot
3838       */       */
3839      tmplLine->type = LT_KERNEL;      tmplLine->type = preferredLineType(LT_KERNEL, config->cfi);
3840      free(tmplLine->elements[0].item);      free(tmplLine->elements[0].item);
3841      tmplLine->elements[0].item =      tmplLine->elements[0].item =
3842   strdup(getKeywordByType(LT_KERNEL, config->cfi)->key);   strdup(getKeywordByType(tmplLine->type,
3843     config->cfi)->key);
3844      newLine = addLineTmpl(new, tmplLine, newLine,      newLine = addLineTmpl(new, tmplLine, newLine,
3845    newKernelPath + strlen(prefix), config->cfi);    newKernelPath + strlen(prefix),
3846      config->cfi);
3847      needs &= ~NEED_KERNEL;      needs &= ~NEED_KERNEL;
3848   } else if (needs & NEED_INITRD) {   } else if (needs & NEED_INITRD) {
3849      char *initrdVal;      char *initrdVal;
3850      /* template is multi but new is not,      /* template is multi but new is not,
3851       * insert the initrd in the second module slot       * insert the initrd in the second module slot
3852       */       */
3853      tmplLine->type = LT_INITRD;      tmplLine->type = preferredLineType(LT_INITRD, config->cfi);
3854      free(tmplLine->elements[0].item);      free(tmplLine->elements[0].item);
3855      tmplLine->elements[0].item =      tmplLine->elements[0].item =
3856   strdup(getKeywordByType(LT_INITRD, config->cfi)->key);   strdup(getKeywordByType(tmplLine->type,
3857     config->cfi)->key);
3858      initrdVal = getInitrdVal(config, prefix, tmplLine, newKernelInitrd, extraInitrds, extraInitrdCount);      initrdVal = getInitrdVal(config, prefix, tmplLine, newKernelInitrd, extraInitrds, extraInitrdCount);
3859      newLine = addLineTmpl(new, tmplLine, newLine, initrdVal, config->cfi);      newLine = addLineTmpl(new, tmplLine, newLine, initrdVal, config->cfi);
3860      free(initrdVal);      free(initrdVal);
3861      needs &= ~NEED_INITRD;      needs &= ~NEED_INITRD;
3862   }   }
3863    
3864      } else if (tmplLine->type == LT_INITRD &&      } else if (isinitrd(tmplLine->type) && tmplLine->numElements >= 2) {
        tmplLine->numElements >= 2) {  
3865   if (needs & NEED_INITRD &&   if (needs & NEED_INITRD &&
3866      new->multiboot && !template->multiboot &&      new->multiboot && !template->multiboot &&
3867      config->cfi->mbInitRdIsModule) {      config->cfi->mbInitRdIsModule) {
# Line 3236  int addNewKernel(struct grubConfig * con Line 3915  int addNewKernel(struct grubConfig * con
3915      static const char *prefix = "'Loading ";      static const char *prefix = "'Loading ";
3916      if (tmplLine->numElements > 1 &&      if (tmplLine->numElements > 1 &&
3917      strstr(tmplLine->elements[1].item, prefix) &&      strstr(tmplLine->elements[1].item, prefix) &&
3918      masterLine->next && masterLine->next->type == LT_KERNEL) {      masterLine->next &&
3919        iskernel(masterLine->next->type)) {
3920   char *newTitle = malloc(strlen(prefix) +   char *newTitle = malloc(strlen(prefix) +
3921   strlen(newKernelTitle) + 2);   strlen(newKernelTitle) + 2);
3922    
# Line 3263  int addNewKernel(struct grubConfig * con Line 3943  int addNewKernel(struct grubConfig * con
3943   */   */
3944   switch (config->cfi->entryStart) {   switch (config->cfi->entryStart) {
3945      case LT_KERNEL:      case LT_KERNEL:
3946        case LT_KERNEL_EFI:
3947        case LT_KERNEL_16:
3948   if (new->multiboot && config->cfi->mbHyperFirst) {   if (new->multiboot && config->cfi->mbHyperFirst) {
3949      /* fall through to LT_HYPER */      /* fall through to LT_HYPER */
3950   } else {   } else {
3951      newLine = addLine(new, config->cfi, LT_KERNEL,      newLine = addLine(new, config->cfi,
3952              preferredLineType(LT_KERNEL, config->cfi),
3953        config->primaryIndent,        config->primaryIndent,
3954        newKernelPath + strlen(prefix));        newKernelPath + strlen(prefix));
3955      needs &= ~NEED_KERNEL;      needs &= ~NEED_KERNEL;
# Line 3342  int addNewKernel(struct grubConfig * con Line 4025  int addNewKernel(struct grubConfig * con
4025      if (needs & NEED_KERNEL) {      if (needs & NEED_KERNEL) {
4026   newLine = addLine(new, config->cfi,   newLine = addLine(new, config->cfi,
4027    (new->multiboot && getKeywordByType(LT_MBMODULE,    (new->multiboot && getKeywordByType(LT_MBMODULE,
4028        config->cfi)) ?        config->cfi))
4029    LT_MBMODULE : LT_KERNEL,     ? LT_MBMODULE
4030     : preferredLineType(LT_KERNEL, config->cfi),
4031    config->secondaryIndent,    config->secondaryIndent,
4032    newKernelPath + strlen(prefix));    newKernelPath + strlen(prefix));
4033   needs &= ~NEED_KERNEL;   needs &= ~NEED_KERNEL;
# Line 3359  int addNewKernel(struct grubConfig * con Line 4043  int addNewKernel(struct grubConfig * con
4043   initrdVal = getInitrdVal(config, prefix, NULL, newKernelInitrd, extraInitrds, extraInitrdCount);   initrdVal = getInitrdVal(config, prefix, NULL, newKernelInitrd, extraInitrds, extraInitrdCount);
4044   newLine = addLine(new, config->cfi,   newLine = addLine(new, config->cfi,
4045    (new->multiboot && getKeywordByType(LT_MBMODULE,    (new->multiboot && getKeywordByType(LT_MBMODULE,
4046        config->cfi)) ?        config->cfi))
4047    LT_MBMODULE : LT_INITRD,     ? LT_MBMODULE
4048       : preferredLineType(LT_INITRD, config->cfi),
4049    config->secondaryIndent,    config->secondaryIndent,
4050    initrdVal);    initrdVal);
4051   free(initrdVal);   free(initrdVal);
# Line 3392  static void traceback(int signum) Line 4077  static void traceback(int signum)
4077      memset(array, '\0', sizeof (array));      memset(array, '\0', sizeof (array));
4078      size = backtrace(array, 40);      size = backtrace(array, 40);
4079    
4080      fprintf(stderr, "grubby recieved SIGSEGV!  Backtrace (%ld):\n",      fprintf(stderr, "grubby received SIGSEGV!  Backtrace (%ld):\n",
4081              (unsigned long)size);              (unsigned long)size);
4082      backtrace_symbols_fd(array, size, STDERR_FILENO);      backtrace_symbols_fd(array, size, STDERR_FILENO);
4083      exit(1);      exit(1);
# Line 3427  int main(int argc, const char ** argv) { Line 4112  int main(int argc, const char ** argv) {
4112      char * removeArgs = NULL;      char * removeArgs = NULL;
4113      char * kernelInfo = NULL;      char * kernelInfo = NULL;
4114      char * extraInitrds[MAX_EXTRA_INITRDS] = { NULL };      char * extraInitrds[MAX_EXTRA_INITRDS] = { NULL };
4115        char * envPath = NULL;
4116      const char * chptr = NULL;      const char * chptr = NULL;
4117      struct configFileInfo * cfi = NULL;      struct configFileInfo * cfi = NULL;
4118      struct grubConfig * config;      struct grubConfig * config;
# Line 3435  int main(int argc, const char ** argv) { Line 4121  int main(int argc, const char ** argv) {
4121      int displayDefault = 0;      int displayDefault = 0;
4122      int displayDefaultIndex = 0;      int displayDefaultIndex = 0;
4123      int displayDefaultTitle = 0;      int displayDefaultTitle = 0;
4124        int defaultIndex = -1;
4125      struct poptOption options[] = {      struct poptOption options[] = {
4126   { "add-kernel", 0, POPT_ARG_STRING, &newKernelPath, 0,   { "add-kernel", 0, POPT_ARG_STRING, &newKernelPath, 0,
4127      _("add an entry for the specified kernel"), _("kernel-path") },      _("add an entry for the specified kernel"), _("kernel-path") },
# Line 3452  int main(int argc, const char ** argv) { Line 4139  int main(int argc, const char ** argv) {
4139   { "boot-filesystem", 0, POPT_ARG_STRING, &bootPrefix, 0,   { "boot-filesystem", 0, POPT_ARG_STRING, &bootPrefix, 0,
4140      _("filestystem which contains /boot directory (for testing only)"),      _("filestystem which contains /boot directory (for testing only)"),
4141      _("bootfs") },      _("bootfs") },
4142  #if defined(__i386__) || defined(__x86_64__)  #if defined(__i386__) || defined(__x86_64__) || defined (__powerpc64__) || defined (__ia64__)
4143   { "bootloader-probe", 0, POPT_ARG_NONE, &bootloaderProbe, 0,   { "bootloader-probe", 0, POPT_ARG_NONE, &bootloaderProbe, 0,
4144      _("check if lilo is installed on lilo.conf boot sector") },      _("check which bootloader is installed on boot sector") },
4145  #endif  #endif
4146   { "config-file", 'c', POPT_ARG_STRING, &grubConfig, 0,   { "config-file", 'c', POPT_ARG_STRING, &grubConfig, 0,
4147      _("path to grub config file to update (\"-\" for stdin)"),      _("path to grub config file to update (\"-\" for stdin)"),
# Line 3475  int main(int argc, const char ** argv) { Line 4162  int main(int argc, const char ** argv) {
4162      _("display the title of the default kernel") },      _("display the title of the default kernel") },
4163   { "elilo", 0, POPT_ARG_NONE, &configureELilo, 0,   { "elilo", 0, POPT_ARG_NONE, &configureELilo, 0,
4164      _("configure elilo bootloader") },      _("configure elilo bootloader") },
4165     { "efi", 0, POPT_ARG_NONE, &isEfi, 0,
4166        _("force grub2 stanzas to use efi") },
4167     { "env", 0, POPT_ARG_STRING, &envPath, 0,
4168        _("path for environment data"),
4169        _("path") },
4170   { "extlinux", 0, POPT_ARG_NONE, &configureExtLinux, 0,   { "extlinux", 0, POPT_ARG_NONE, &configureExtLinux, 0,
4171      _("configure extlinux bootloader (from syslinux)") },      _("configure extlinux bootloader (from syslinux)") },
4172   { "grub", 0, POPT_ARG_NONE, &configureGrub, 0,   { "grub", 0, POPT_ARG_NONE, &configureGrub, 0,
# Line 3487  int main(int argc, const char ** argv) { Line 4179  int main(int argc, const char ** argv) {
4179   { "initrd", 0, POPT_ARG_STRING, &newKernelInitrd, 0,   { "initrd", 0, POPT_ARG_STRING, &newKernelInitrd, 0,
4180      _("initrd image for the new kernel"), _("initrd-path") },      _("initrd image for the new kernel"), _("initrd-path") },
4181   { "extra-initrd", 'i', POPT_ARG_STRING, NULL, 'i',   { "extra-initrd", 'i', POPT_ARG_STRING, NULL, 'i',
4182      _("auxilliary initrd image for things other than the new kernel"), _("initrd-path") },      _("auxiliary initrd image for things other than the new kernel"), _("initrd-path") },
4183   { "lilo", 0, POPT_ARG_NONE, &configureLilo, 0,   { "lilo", 0, POPT_ARG_NONE, &configureLilo, 0,
4184      _("configure lilo bootloader") },      _("configure lilo bootloader") },
4185   { "make-default", 0, 0, &makeDefault, 0,   { "make-default", 0, 0, &makeDefault, 0,
# Line 3507  int main(int argc, const char ** argv) { Line 4199  int main(int argc, const char ** argv) {
4199   { "set-default", 0, POPT_ARG_STRING, &defaultKernel, 0,   { "set-default", 0, POPT_ARG_STRING, &defaultKernel, 0,
4200      _("make the first entry referencing the specified kernel "      _("make the first entry referencing the specified kernel "
4201        "the default"), _("kernel-path") },        "the default"), _("kernel-path") },
4202     { "set-default-index", 0, POPT_ARG_INT, &defaultIndex, 0,
4203        _("make the given entry index the default entry"),
4204        _("entry-index") },
4205   { "silo", 0, POPT_ARG_NONE, &configureSilo, 0,   { "silo", 0, POPT_ARG_NONE, &configureSilo, 0,
4206      _("configure silo bootloader") },      _("configure silo bootloader") },
4207   { "title", 0, POPT_ARG_STRING, &newKernelTitle, 0,   { "title", 0, POPT_ARG_STRING, &newKernelTitle, 0,
# Line 3528  int main(int argc, const char ** argv) { Line 4223  int main(int argc, const char ** argv) {
4223    
4224      signal(SIGSEGV, traceback);      signal(SIGSEGV, traceback);
4225    
4226        int i = 0;
4227        for (int j = 1; j < argc; j++)
4228     i += strlen(argv[j]) + 1;
4229        saved_command_line = malloc(i);
4230        if (!saved_command_line) {
4231     fprintf(stderr, "grubby: %m\n");
4232     exit(1);
4233        }
4234        saved_command_line[0] = '\0';
4235        for (int j = 1; j < argc; j++) {
4236     strcat(saved_command_line, argv[j]);
4237     strncat(saved_command_line, j == argc -1 ? "" : " ", 1);
4238        }
4239    
4240      optCon = poptGetContext("grubby", argc, argv, options, 0);      optCon = poptGetContext("grubby", argc, argv, options, 0);
4241      poptReadDefaultConfig(optCon, 1);      poptReadDefaultConfig(optCon, 1);
4242    
# Line 3571  int main(int argc, const char ** argv) { Line 4280  int main(int argc, const char ** argv) {
4280   return 1;   return 1;
4281      } else if (configureGrub2) {      } else if (configureGrub2) {
4282   cfi = &grub2ConfigType;   cfi = &grub2ConfigType;
4283     if (envPath)
4284        cfi->envFile = envPath;
4285      } else if (configureLilo) {      } else if (configureLilo) {
4286   cfi = &liloConfigType;   cfi = &liloConfigType;
4287      } else if (configureGrub) {      } else if (configureGrub) {
# Line 3615  int main(int argc, const char ** argv) { Line 4326  int main(int argc, const char ** argv) {
4326      }      }
4327    
4328      if (bootloaderProbe && (displayDefault || kernelInfo || newKernelVersion ||      if (bootloaderProbe && (displayDefault || kernelInfo || newKernelVersion ||
4329    newKernelPath || removeKernelPath || makeDefault ||      newKernelPath || removeKernelPath || makeDefault ||
4330    defaultKernel || displayDefaultIndex || displayDefaultTitle)) {      defaultKernel || displayDefaultIndex || displayDefaultTitle ||
4331        (defaultIndex >= 0))) {
4332   fprintf(stderr, _("grubby: --bootloader-probe may not be used with "   fprintf(stderr, _("grubby: --bootloader-probe may not be used with "
4333    "specified option"));    "specified option"));
4334   return 1;   return 1;
# Line 3658  int main(int argc, const char ** argv) { Line 4370  int main(int argc, const char ** argv) {
4370   makeDefault = 1;   makeDefault = 1;
4371   defaultKernel = NULL;   defaultKernel = NULL;
4372      }      }
4373        else if (defaultKernel && (defaultIndex >= 0)) {
4374     fprintf(stderr, _("grubby: --set-default and --set-default-index "
4375      "may not be used together\n"));
4376     return 1;
4377        }
4378    
4379      if (grubConfig && !strcmp(grubConfig, "-") && !outputFile) {      if (grubConfig && !strcmp(grubConfig, "-") && !outputFile) {
4380   fprintf(stderr, _("grubby: output file must be specified if stdin "   fprintf(stderr, _("grubby: output file must be specified if stdin "
# Line 3666  int main(int argc, const char ** argv) { Line 4383  int main(int argc, const char ** argv) {
4383      }      }
4384    
4385      if (!removeKernelPath && !newKernelPath && !displayDefault && !defaultKernel      if (!removeKernelPath && !newKernelPath && !displayDefault && !defaultKernel
4386   && !kernelInfo && !bootloaderProbe && !updateKernelPath   && !kernelInfo && !bootloaderProbe && !updateKernelPath
4387          && !removeMBKernel && !displayDefaultIndex && !displayDefaultTitle) {   && !removeMBKernel && !displayDefaultIndex && !displayDefaultTitle
4388     && (defaultIndex == -1)) {
4389   fprintf(stderr, _("grubby: no action specified\n"));   fprintf(stderr, _("grubby: no action specified\n"));
4390   return 1;   return 1;
4391      }      }
# Line 3694  int main(int argc, const char ** argv) { Line 4412  int main(int argc, const char ** argv) {
4412      }      }
4413    
4414      if (bootloaderProbe) {      if (bootloaderProbe) {
4415   int lrc = 0, grc = 0, gr2c = 0, erc = 0;   int lrc = 0, grc = 0, gr2c = 0, extrc = 0, yrc = 0, erc = 0;
4416   struct grubConfig * lconfig, * gconfig;   struct grubConfig * lconfig, * gconfig, * yconfig, * econfig;
4417    
4418   const char *grub2config = grub2FindConfig(&grub2ConfigType);   const char *grub2config = grub2FindConfig(&grub2ConfigType);
4419   if (grub2config) {   if (grub2config) {
# Line 3723  int main(int argc, const char ** argv) { Line 4441  int main(int argc, const char ** argv) {
4441   lrc = checkForLilo(lconfig);   lrc = checkForLilo(lconfig);
4442   }   }
4443    
4444     if (!access(eliloConfigType.defaultConfig, F_OK)) {
4445        econfig = readConfig(eliloConfigType.defaultConfig,
4446     &eliloConfigType);
4447        if (!econfig)
4448     erc = 1;
4449        else
4450     erc = checkForElilo(econfig);
4451     }
4452    
4453   if (!access(extlinuxConfigType.defaultConfig, F_OK)) {   if (!access(extlinuxConfigType.defaultConfig, F_OK)) {
4454      lconfig = readConfig(extlinuxConfigType.defaultConfig, &extlinuxConfigType);      lconfig = readConfig(extlinuxConfigType.defaultConfig, &extlinuxConfigType);
4455      if (!lconfig)      if (!lconfig)
4456   erc = 1;   extrc = 1;
4457      else      else
4458   erc = checkForExtLinux(lconfig);   extrc = checkForExtLinux(lconfig);
4459   }   }
4460    
4461   if (lrc == 1 || grc == 1 || gr2c == 1) return 1;  
4462     if (!access(yabootConfigType.defaultConfig, F_OK)) {
4463        yconfig = readConfig(yabootConfigType.defaultConfig,
4464     &yabootConfigType);
4465        if (!yconfig)
4466     yrc = 1;
4467        else
4468     yrc = checkForYaboot(yconfig);
4469     }
4470    
4471     if (lrc == 1 || grc == 1 || gr2c == 1 || extrc == 1 || yrc == 1 ||
4472     erc == 1)
4473        return 1;
4474    
4475   if (lrc == 2) printf("lilo\n");   if (lrc == 2) printf("lilo\n");
4476   if (gr2c == 2) printf("grub2\n");   if (gr2c == 2) printf("grub2\n");
4477   if (grc == 2) printf("grub\n");   if (grc == 2) printf("grub\n");
4478   if (erc == 2) printf("extlinux\n");   if (extrc == 2) printf("extlinux\n");
4479     if (yrc == 2) printf("yaboot\n");
4480     if (erc == 2) printf("elilo\n");
4481    
4482   return 0;   return 0;
4483      }      }
4484    
4485        if (grubConfig == NULL) {
4486     printf("Could not find bootloader configuration file.\n");
4487     exit(1);
4488        }
4489    
4490      config = readConfig(grubConfig, cfi);      config = readConfig(grubConfig, cfi);
4491      if (!config) return 1;      if (!config) return 1;
4492    
# Line 3750  int main(int argc, const char ** argv) { Line 4496  int main(int argc, const char ** argv) {
4496          char * rootspec;          char * rootspec;
4497    
4498   if (config->defaultImage == -1) return 0;   if (config->defaultImage == -1) return 0;
4499     if (config->defaultImage == DEFAULT_SAVED_GRUB2 &&
4500     cfi->defaultIsSaved)
4501        config->defaultImage = 0;
4502   entry = findEntryByIndex(config, config->defaultImage);   entry = findEntryByIndex(config, config->defaultImage);
4503   if (!entry) return 0;   if (!entry) return 0;
4504   if (!suitableImage(entry, bootPrefix, 0, flags)) return 0;   if (!suitableImage(entry, bootPrefix, 0, flags)) return 0;
4505    
4506   line = getLineByType(LT_KERNEL|LT_HYPER, entry->lines);   line = getLineByType(LT_KERNEL|LT_HYPER|LT_KERNEL_EFI|LT_KERNEL_16, entry->lines);
4507   if (!line) return 0;   if (!line) return 0;
4508    
4509          rootspec = getRootSpecifier(line->elements[1].item);          rootspec = getRootSpecifier(line->elements[1].item);
# Line 3768  int main(int argc, const char ** argv) { Line 4517  int main(int argc, const char ** argv) {
4517   struct singleEntry * entry;   struct singleEntry * entry;
4518    
4519   if (config->defaultImage == -1) return 0;   if (config->defaultImage == -1) return 0;
4520     if (config->defaultImage == DEFAULT_SAVED_GRUB2 &&
4521     cfi->defaultIsSaved)
4522        config->defaultImage = 0;
4523   entry = findEntryByIndex(config, config->defaultImage);   entry = findEntryByIndex(config, config->defaultImage);
4524   if (!entry) return 0;   if (!entry) return 0;
4525    
# Line 3790  int main(int argc, const char ** argv) { Line 4542  int main(int argc, const char ** argv) {
4542    
4543      } else if (displayDefaultIndex) {      } else if (displayDefaultIndex) {
4544          if (config->defaultImage == -1) return 0;          if (config->defaultImage == -1) return 0;
4545     if (config->defaultImage == DEFAULT_SAVED_GRUB2 &&
4546     cfi->defaultIsSaved)
4547        config->defaultImage = 0;
4548          printf("%i\n", config->defaultImage);          printf("%i\n", config->defaultImage);
4549            return 0;
4550    
4551      } else if (kernelInfo)      } else if (kernelInfo)
4552   return displayInfo(config, kernelInfo, bootPrefix);   return displayInfo(config, kernelInfo, bootPrefix);
# Line 3803  int main(int argc, const char ** argv) { Line 4559  int main(int argc, const char ** argv) {
4559      markRemovedImage(config, removeKernelPath, bootPrefix);      markRemovedImage(config, removeKernelPath, bootPrefix);
4560      markRemovedImage(config, removeMBKernel, bootPrefix);      markRemovedImage(config, removeMBKernel, bootPrefix);
4561      setDefaultImage(config, newKernelPath != NULL, defaultKernel, makeDefault,      setDefaultImage(config, newKernelPath != NULL, defaultKernel, makeDefault,
4562      bootPrefix, flags);      bootPrefix, flags, defaultIndex);
4563      setFallbackImage(config, newKernelPath != NULL);      setFallbackImage(config, newKernelPath != NULL);
4564      if (updateImage(config, updateKernelPath, bootPrefix, newKernelArgs,      if (updateImage(config, updateKernelPath, bootPrefix, newKernelArgs,
4565                      removeArgs, newMBKernelArgs, removeMBKernelArgs)) return 1;                      removeArgs, newMBKernelArgs, removeMBKernelArgs)) return 1;
4566      if (updateKernelPath && newKernelInitrd) {      if (updateKernelPath && newKernelInitrd) {
4567              if (updateInitrd(config, updateKernelPath, bootPrefix,      if (newMBKernel) {
4568                               newKernelInitrd)) return 1;      if (addMBInitrd(config, newMBKernel, updateKernelPath,
4569     bootPrefix, newKernelInitrd))
4570        return 1;
4571        } else {
4572        if (updateInitrd(config, updateKernelPath, bootPrefix,
4573     newKernelInitrd))
4574     return 1;
4575        }
4576      }      }
4577      if (addNewKernel(config, template, bootPrefix, newKernelPath,      if (addNewKernel(config, template, bootPrefix, newKernelPath,
4578                       newKernelTitle, newKernelArgs, newKernelInitrd,                       newKernelTitle, newKernelArgs, newKernelInitrd,

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