Magellan Linux

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

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

revision 1801 by niro, Mon Apr 16 17:48:10 2012 UTC revision 2687 by niro, Wed Jul 16 10:41:38 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_DEVTREE      = 1 << 24,
96        LT_UNKNOWN      = 1 << 25,
97  };  };
98    
99  struct singleLine {  struct singleLine {
# Line 111  struct singleEntry { Line 122  struct singleEntry {
122  #define NEED_ARGS    (1 << 3)  #define NEED_ARGS    (1 << 3)
123  #define NEED_MB      (1 << 4)  #define NEED_MB      (1 << 4)
124  #define NEED_END     (1 << 5)  #define NEED_END     (1 << 5)
125    #define NEED_DEVTREE (1 << 6)
126    
127  #define MAIN_DEFAULT    (1 << 0)  #define MAIN_DEFAULT    (1 << 0)
128  #define DEFAULT_SAVED       -2  #define DEFAULT_SAVED       -2
# Line 128  struct configFileInfo; Line 140  struct configFileInfo;
140  typedef const char *(*findConfigFunc)(struct configFileInfo *);  typedef const char *(*findConfigFunc)(struct configFileInfo *);
141  typedef const int (*writeLineFunc)(struct configFileInfo *,  typedef const int (*writeLineFunc)(struct configFileInfo *,
142   struct singleLine *line);   struct singleLine *line);
143    typedef char *(*getEnvFunc)(struct configFileInfo *, char *name);
144    typedef int (*setEnvFunc)(struct configFileInfo *, char *name, char *value);
145    
146  struct configFileInfo {  struct configFileInfo {
147      char * defaultConfig;      char * defaultConfig;
148      findConfigFunc findConfig;      findConfigFunc findConfig;
149      writeLineFunc writeLine;      writeLineFunc writeLine;
150        getEnvFunc getEnv;
151        setEnvFunc setEnv;
152      struct keywordTypes * keywords;      struct keywordTypes * keywords;
153        int caseInsensitive;
154      int defaultIsIndex;      int defaultIsIndex;
155      int defaultIsVariable;      int defaultIsVariable;
156      int defaultSupportSaved;      int defaultSupportSaved;
157        int defaultIsSaved;
158      enum lineType_e entryStart;      enum lineType_e entryStart;
159      enum lineType_e entryEnd;      enum lineType_e entryEnd;
160      int needsBootPrefix;      int needsBootPrefix;
# Line 148  struct configFileInfo { Line 166  struct configFileInfo {
166      int mbInitRdIsModule;      int mbInitRdIsModule;
167      int mbConcatArgs;      int mbConcatArgs;
168      int mbAllowExtraInitRds;      int mbAllowExtraInitRds;
169        char *envFile;
170  };  };
171    
172  struct keywordTypes grubKeywords[] = {  struct keywordTypes grubKeywords[] = {
# Line 164  struct keywordTypes grubKeywords[] = { Line 183  struct keywordTypes grubKeywords[] = {
183    
184  const char *grubFindConfig(struct configFileInfo *cfi) {  const char *grubFindConfig(struct configFileInfo *cfi) {
185      static const char *configFiles[] = {      static const char *configFiles[] = {
  "/etc/grub.conf",  
186   "/boot/grub/grub.conf",   "/boot/grub/grub.conf",
187   "/boot/grub/menu.lst",   "/boot/grub/menu.lst",
188     "/etc/grub.conf",
189     "/boot/grub2/grub.cfg",
190     "/boot/grub2-efi/grub.cfg",
191   NULL   NULL
192      };      };
193      static int i = -1;      static int i = -1;
# Line 205  struct keywordTypes grub2Keywords[] = { Line 226  struct keywordTypes grub2Keywords[] = {
226      { "default",    LT_DEFAULT,     ' ' },      { "default",    LT_DEFAULT,     ' ' },
227      { "fallback",   LT_FALLBACK,    ' ' },      { "fallback",   LT_FALLBACK,    ' ' },
228      { "linux",      LT_KERNEL,      ' ' },      { "linux",      LT_KERNEL,      ' ' },
229        { "linuxefi",   LT_KERNEL_EFI,  ' ' },
230        { "linux16",    LT_KERNEL_16,   ' ' },
231      { "initrd",     LT_INITRD,      ' ', ' ' },      { "initrd",     LT_INITRD,      ' ', ' ' },
232        { "initrdefi",  LT_INITRD_EFI,  ' ', ' ' },
233        { "initrd16",   LT_INITRD_16,   ' ', ' ' },
234      { "module",     LT_MBMODULE,    ' ' },      { "module",     LT_MBMODULE,    ' ' },
235      { "kernel",     LT_HYPER,       ' ' },      { "kernel",     LT_HYPER,       ' ' },
236        { "devicetree", LT_DEVTREE,  ' ' },
237      { NULL, 0, 0 },      { NULL, 0, 0 },
238  };  };
239    
# Line 219  const char *grub2FindConfig(struct confi Line 245  const char *grub2FindConfig(struct confi
245      };      };
246      static int i = -1;      static int i = -1;
247      static const char *grub_cfg = "/boot/grub/grub.cfg";      static const char *grub_cfg = "/boot/grub/grub.cfg";
248        int rc = -1;
249    
250      if (i == -1) {      if (i == -1) {
251   for (i = 0; configFiles[i] != NULL; i++) {   for (i = 0; configFiles[i] != NULL; i++) {
252      dbgPrintf("Checking \"%s\": ", configFiles[i]);      dbgPrintf("Checking \"%s\": ", configFiles[i]);
253      if (!access(configFiles[i], R_OK)) {      if ((rc = access(configFiles[i], R_OK))) {
254     if (errno == EACCES) {
255        printf("Unable to access bootloader configuration file "
256           "\"%s\": %m\n", configFiles[i]);
257        exit(1);
258     }
259     continue;
260        } else {
261   dbgPrintf("found\n");   dbgPrintf("found\n");
262   return configFiles[i];   return configFiles[i];
263      }      }
# Line 242  const char *grub2FindConfig(struct confi Line 276  const char *grub2FindConfig(struct confi
276      return configFiles[i];      return configFiles[i];
277  }  }
278    
279    /* kind of hacky.  It'll give the first 1024 bytes, ish. */
280    static char *grub2GetEnv(struct configFileInfo *info, char *name)
281    {
282        static char buf[1025];
283        char *s = NULL;
284        char *ret = NULL;
285        char *envFile = info->envFile ? info->envFile : "/boot/grub/grubenv";
286        int rc = asprintf(&s, "grub-editenv %s list | grep '^%s='", envFile, name);
287    
288        if (rc < 0)
289     return NULL;
290    
291        FILE *f = popen(s, "r");
292        if (!f)
293     goto out;
294    
295        memset(buf, '\0', sizeof (buf));
296        ret = fgets(buf, 1024, f);
297        pclose(f);
298    
299        if (ret) {
300     ret += strlen(name) + 1;
301     ret[strlen(ret) - 1] = '\0';
302        }
303        dbgPrintf("grub2GetEnv(%s): %s\n", name, ret);
304    out:
305        free(s);
306        return ret;
307    }
308    
309    static int sPopCount(const char *s, const char *c)
310    {
311        int ret = 0;
312        if (!s)
313     return -1;
314        for (int i = 0; s[i] != '\0'; i++)
315     for (int j = 0; c[j] != '\0'; j++)
316        if (s[i] == c[j])
317     ret++;
318        return ret;
319    }
320    
321    static char *shellEscape(const char *s)
322    {
323        int l = strlen(s) + sPopCount(s, "'") * 2;
324    
325        char *ret = calloc(l+1, sizeof (*ret));
326        if (!ret)
327     return NULL;
328        for (int i = 0, j = 0; s[i] != '\0'; i++, j++) {
329     if (s[i] == '\'')
330        ret[j++] = '\\';
331     ret[j] = s[i];
332        }
333        return ret;
334    }
335    
336    static void unquote(char *s)
337    {
338        int l = strlen(s);
339    
340        if ((s[l-1] == '\'' && s[0] == '\'') || (s[l-1] == '"' && s[0] == '"')) {
341     memmove(s, s+1, l-2);
342     s[l-2] = '\0';
343        }
344    }
345    
346    static int grub2SetEnv(struct configFileInfo *info, char *name, char *value)
347    {
348        char *s = NULL;
349        int rc = 0;
350        char *envFile = info->envFile ? info->envFile : "/boot/grub/grubenv";
351    
352        unquote(value);
353        value = shellEscape(value);
354        if (!value)
355        return -1;
356    
357        rc = asprintf(&s, "grub-editenv %s set '%s=%s'", envFile, name, value);
358        free(value);
359        if (rc <0)
360     return -1;
361    
362        dbgPrintf("grub2SetEnv(%s): %s\n", name, s);
363        rc = system(s);
364        free(s);
365        return rc;
366    }
367    
368    /* this is a gigantic hack to avoid clobbering grub2 variables... */
369    static int is_special_grub2_variable(const char *name)
370    {
371        if (!strcmp(name,"\"${next_entry}\""))
372     return 1;
373        if (!strcmp(name,"\"${prev_saved_entry}\""))
374     return 1;
375        return 0;
376    }
377    
378  int sizeOfSingleLine(struct singleLine * line) {  int sizeOfSingleLine(struct singleLine * line) {
   int i;  
379    int count = 0;    int count = 0;
380    
381    for (i = 0; i < line->numElements; i++) {    for (int i = 0; i < line->numElements; i++) {
382      int indentSize = 0;      int indentSize = 0;
383    
384      count = count + strlen(line->elements[i].item);      count = count + strlen(line->elements[i].item);
# Line 272  static int isquote(char q) Line 404  static int isquote(char q)
404      return 0;      return 0;
405  }  }
406    
407    static int iskernel(enum lineType_e type) {
408        return (type == LT_KERNEL || type == LT_KERNEL_EFI || type == LT_KERNEL_16);
409    }
410    
411    static int isinitrd(enum lineType_e type) {
412        return (type == LT_INITRD || type == LT_INITRD_EFI || type == LT_INITRD_16);
413    }
414    
415  char *grub2ExtractTitle(struct singleLine * line) {  char *grub2ExtractTitle(struct singleLine * line) {
416      char * current;      char * current;
417      char * current_indent;      char * current_indent;
# Line 329  char *grub2ExtractTitle(struct singleLin Line 469  char *grub2ExtractTitle(struct singleLin
469    
470  struct configFileInfo grub2ConfigType = {  struct configFileInfo grub2ConfigType = {
471      .findConfig = grub2FindConfig,      .findConfig = grub2FindConfig,
472        .getEnv = grub2GetEnv,
473        .setEnv = grub2SetEnv,
474      .keywords = grub2Keywords,      .keywords = grub2Keywords,
475      .defaultIsIndex = 1,      .defaultIsIndex = 1,
476      .defaultSupportSaved = 1,      .defaultSupportSaved = 1,
# Line 483  struct configFileInfo ziplConfigType = { Line 625  struct configFileInfo ziplConfigType = {
625  struct configFileInfo extlinuxConfigType = {  struct configFileInfo extlinuxConfigType = {
626      .defaultConfig = "/boot/extlinux/extlinux.conf",      .defaultConfig = "/boot/extlinux/extlinux.conf",
627      .keywords = extlinuxKeywords,      .keywords = extlinuxKeywords,
628        .caseInsensitive = 1,
629      .entryStart = LT_TITLE,      .entryStart = LT_TITLE,
630      .needsBootPrefix = 1,      .needsBootPrefix = 1,
631      .maxTitleLength = 255,      .maxTitleLength = 255,
# Line 507  struct singleEntry * findEntryByIndex(st Line 650  struct singleEntry * findEntryByIndex(st
650  struct singleEntry * findEntryByPath(struct grubConfig * cfg,  struct singleEntry * findEntryByPath(struct grubConfig * cfg,
651       const char * path, const char * prefix,       const char * path, const char * prefix,
652       int * index);       int * index);
653    struct singleEntry * findEntryByTitle(struct grubConfig * cfg, char *title,
654          int * index);
655  static int readFile(int fd, char ** bufPtr);  static int readFile(int fd, char ** bufPtr);
656  static void lineInit(struct singleLine * line);  static void lineInit(struct singleLine * line);
657  struct singleLine * lineDup(struct singleLine * line);  struct singleLine * lineDup(struct singleLine * line);
# Line 571  static char * sdupprintf(const char *for Line 716  static char * sdupprintf(const char *for
716      return buf;      return buf;
717  }  }
718    
719    static enum lineType_e preferredLineType(enum lineType_e type,
720     struct configFileInfo *cfi) {
721        if (isEfi && cfi == &grub2ConfigType) {
722     switch (type) {
723    #if defined(__aarch64__)
724     case LT_KERNEL:
725        return LT_KERNEL;
726     case LT_INITRD:
727        return LT_INITRD;
728    #else
729     case LT_KERNEL:
730        return LT_KERNEL_EFI;
731     case LT_INITRD:
732        return LT_INITRD_EFI;
733    #endif
734     default:
735        return type;
736     }
737    #if defined(__i386__) || defined(__x86_64__)
738        } else if (cfi == &grub2ConfigType) {
739     switch (type) {
740     case LT_KERNEL:
741        return LT_KERNEL_16;
742     case LT_INITRD:
743        return LT_INITRD_16;
744     default:
745        return type;
746     }
747    #endif
748        }
749        return type;
750    }
751    
752  static struct keywordTypes * getKeywordByType(enum lineType_e type,  static struct keywordTypes * getKeywordByType(enum lineType_e type,
753        struct configFileInfo * cfi) {        struct configFileInfo * cfi) {
754      struct keywordTypes * kw;      for (struct keywordTypes *kw = cfi->keywords; kw->key; kw++) {
     for (kw = cfi->keywords; kw->key; kw++) {  
755   if (kw->type == type)   if (kw->type == type)
756      return kw;      return kw;
757      }      }
# Line 604  static char * getuuidbydev(char *device) Line 781  static char * getuuidbydev(char *device)
781    
782  static enum lineType_e getTypeByKeyword(char * keyword,  static enum lineType_e getTypeByKeyword(char * keyword,
783   struct configFileInfo * cfi) {   struct configFileInfo * cfi) {
784      struct keywordTypes * kw;      for (struct keywordTypes *kw = cfi->keywords; kw->key; kw++) {
785      for (kw = cfi->keywords; kw->key; kw++) {   if (cfi->caseInsensitive) {
786   if (!strcmp(keyword, kw->key))      if (!strcasecmp(keyword, kw->key))
787      return kw->type;                  return kw->type;
788     } else {
789        if (!strcmp(keyword, kw->key))
790            return kw->type;
791     }
792      }      }
793      return LT_UNKNOWN;      return LT_UNKNOWN;
794  }  }
# Line 646  static int isEntryStart(struct singleLin Line 827  static int isEntryStart(struct singleLin
827  /* extract the title from within brackets (for zipl) */  /* extract the title from within brackets (for zipl) */
828  static char * extractTitle(struct singleLine * line) {  static char * extractTitle(struct singleLine * line) {
829      /* bracketed title... let's extract it (leaks a byte) */      /* bracketed title... let's extract it (leaks a byte) */
830      char * title;      char * title = NULL;
831      title = strdup(line->elements[0].item);      if (line->type == LT_TITLE) {
832      title++;   title = strdup(line->elements[0].item);
833      *(title + strlen(title) - 1) = '\0';   title++;
834     *(title + strlen(title) - 1) = '\0';
835        } else if (line->type == LT_MENUENTRY)
836     title = strdup(line->elements[1].item);
837        else
838     return NULL;
839      return title;      return title;
840  }  }
841    
# Line 692  static void lineInit(struct singleLine * Line 878  static void lineInit(struct singleLine *
878  }  }
879    
880  struct singleLine * lineDup(struct singleLine * line) {  struct singleLine * lineDup(struct singleLine * line) {
     int i;  
881      struct singleLine * newLine = malloc(sizeof(*newLine));      struct singleLine * newLine = malloc(sizeof(*newLine));
882    
883      newLine->indent = strdup(line->indent);      newLine->indent = strdup(line->indent);
# Line 702  struct singleLine * lineDup(struct singl Line 887  struct singleLine * lineDup(struct singl
887      newLine->elements = malloc(sizeof(*newLine->elements) *      newLine->elements = malloc(sizeof(*newLine->elements) *
888         newLine->numElements);         newLine->numElements);
889    
890      for (i = 0; i < newLine->numElements; i++) {      for (int i = 0; i < newLine->numElements; i++) {
891   newLine->elements[i].indent = strdup(line->elements[i].indent);   newLine->elements[i].indent = strdup(line->elements[i].indent);
892   newLine->elements[i].item = strdup(line->elements[i].item);   newLine->elements[i].item = strdup(line->elements[i].item);
893      }      }
# Line 711  struct singleLine * lineDup(struct singl Line 896  struct singleLine * lineDup(struct singl
896  }  }
897    
898  static void lineFree(struct singleLine * line) {  static void lineFree(struct singleLine * line) {
     int i;  
   
899      if (line->indent) free(line->indent);      if (line->indent) free(line->indent);
900    
901      for (i = 0; i < line->numElements; i++) {      for (int i = 0; i < line->numElements; i++) {
902   free(line->elements[i].item);   free(line->elements[i].item);
903   free(line->elements[i].indent);   free(line->elements[i].indent);
904      }      }
# Line 726  static void lineFree(struct singleLine * Line 909  static void lineFree(struct singleLine *
909    
910  static int lineWrite(FILE * out, struct singleLine * line,  static int lineWrite(FILE * out, struct singleLine * line,
911       struct configFileInfo * cfi) {       struct configFileInfo * cfi) {
     int i;  
   
912      if (fprintf(out, "%s", line->indent) == -1) return -1;      if (fprintf(out, "%s", line->indent) == -1) return -1;
913    
914      for (i = 0; i < line->numElements; i++) {      for (int i = 0; i < line->numElements; i++) {
915   /* Need to handle this, because we strip the quotes from   /* Need to handle this, because we strip the quotes from
916   * menuentry when read it. */   * menuentry when read it. */
917   if (line->type == LT_MENUENTRY && i == 1) {   if (line->type == LT_MENUENTRY && i == 1) {
# Line 836  static int getNextLine(char ** bufPtr, s Line 1017  static int getNextLine(char ** bufPtr, s
1017      if (*line->elements[0].item == '#') {      if (*line->elements[0].item == '#') {
1018   char * fullLine;   char * fullLine;
1019   int len;   int len;
  int i;  
1020    
1021   len = strlen(line->indent);   len = strlen(line->indent);
1022   for (i = 0; i < line->numElements; i++)   for (int i = 0; i < line->numElements; i++)
1023      len += strlen(line->elements[i].item) +      len += strlen(line->elements[i].item) +
1024     strlen(line->elements[i].indent);     strlen(line->elements[i].indent);
1025    
# Line 848  static int getNextLine(char ** bufPtr, s Line 1028  static int getNextLine(char ** bufPtr, s
1028   free(line->indent);   free(line->indent);
1029   line->indent = fullLine;   line->indent = fullLine;
1030    
1031   for (i = 0; i < line->numElements; i++) {   for (int i = 0; i < line->numElements; i++) {
1032      strcat(fullLine, line->elements[i].item);      strcat(fullLine, line->elements[i].item);
1033      strcat(fullLine, line->elements[i].indent);      strcat(fullLine, line->elements[i].indent);
1034      free(line->elements[i].item);      free(line->elements[i].item);
# Line 867  static int getNextLine(char ** bufPtr, s Line 1047  static int getNextLine(char ** bufPtr, s
1047   * elements up more   * elements up more
1048   */   */
1049   if (!isspace(kw->separatorChar)) {   if (!isspace(kw->separatorChar)) {
     int i;  
1050      char indent[2] = "";      char indent[2] = "";
1051      indent[0] = kw->separatorChar;      indent[0] = kw->separatorChar;
1052      for (i = 1; i < line->numElements; i++) {      for (int i = 1; i < line->numElements; i++) {
1053   char *p;   char *p;
  int j;  
1054   int numNewElements;   int numNewElements;
1055    
1056   numNewElements = 0;   numNewElements = 0;
# Line 888  static int getNextLine(char ** bufPtr, s Line 1066  static int getNextLine(char ** bufPtr, s
1066      sizeof(*line->elements) * elementsAlloced);      sizeof(*line->elements) * elementsAlloced);
1067   }   }
1068    
1069   for (j = line->numElements; j > i; j--) {   for (int j = line->numElements; j > i; j--) {
1070   line->elements[j + numNewElements] = line->elements[j];   line->elements[j + numNewElements] = line->elements[j];
1071   }   }
1072   line->numElements += numNewElements;   line->numElements += numNewElements;
# Line 901  static int getNextLine(char ** bufPtr, s Line 1079  static int getNextLine(char ** bufPtr, s
1079   break;   break;
1080   }   }
1081    
1082   free(line->elements[i].indent);   line->elements[i + 1].indent = line->elements[i].indent;
1083   line->elements[i].indent = strdup(indent);   line->elements[i].indent = strdup(indent);
1084   *p++ = '\0';   *p++ = '\0';
1085   i++;   i++;
1086   line->elements[i].item = strdup(p);   line->elements[i].item = strdup(p);
  line->elements[i].indent = strdup("");  
  p = line->elements[i].item;  
1087   }   }
1088      }      }
1089   }   }
# Line 917  static int getNextLine(char ** bufPtr, s Line 1093  static int getNextLine(char ** bufPtr, s
1093      return 0;      return 0;
1094  }  }
1095    
1096    static int isnumber(const char *s)
1097    {
1098        int i;
1099        for (i = 0; s[i] != '\0'; i++)
1100     if (s[i] < '0' || s[i] > '9')
1101        return 0;
1102        return i;
1103    }
1104    
1105  static struct grubConfig * readConfig(const char * inName,  static struct grubConfig * readConfig(const char * inName,
1106        struct configFileInfo * cfi) {        struct configFileInfo * cfi) {
1107      int in;      int in;
# Line 928  static struct grubConfig * readConfig(co Line 1113  static struct grubConfig * readConfig(co
1113      struct singleLine * last = NULL, * line, * defaultLine = NULL;      struct singleLine * last = NULL, * line, * defaultLine = NULL;
1114      char * end;      char * end;
1115      struct singleEntry * entry = NULL;      struct singleEntry * entry = NULL;
1116      int i, len;      int len;
1117      char * buf;      char * buf;
1118    
1119      if (!strcmp(inName, "-")) {      if (inName == NULL) {
1120            printf("Could not find bootloader configuration\n");
1121            exit(1);
1122        } else if (!strcmp(inName, "-")) {
1123   in = 0;   in = 0;
1124      } else {      } else {
1125   if ((in = open(inName, O_RDONLY)) < 0) {   if ((in = open(inName, O_RDONLY)) < 0) {
# Line 991  static struct grubConfig * readConfig(co Line 1179  static struct grubConfig * readConfig(co
1179   }   }
1180    
1181   if (line->type == LT_SET_VARIABLE) {   if (line->type == LT_SET_VARIABLE) {
     int i;  
1182      dbgPrintf("found 'set' command (%d elements): ", line->numElements);      dbgPrintf("found 'set' command (%d elements): ", line->numElements);
1183      dbgPrintf("%s", line->indent);      dbgPrintf("%s", line->indent);
1184      for (i = 0; i < line->numElements; i++)      for (int i = 0; i < line->numElements; i++)
1185   dbgPrintf("%s\"%s\"", line->elements[i].indent, line->elements[i].item);   dbgPrintf("\"%s\"%s", line->elements[i].item, line->elements[i].indent);
1186      dbgPrintf("\n");      dbgPrintf("\n");
1187      struct keywordTypes *kwType = getKeywordByType(LT_DEFAULT, cfi);      struct keywordTypes *kwType = getKeywordByType(LT_DEFAULT, cfi);
1188      if (kwType && line->numElements == 3 &&      if (kwType && line->numElements == 3 &&
1189      !strcmp(line->elements[1].item, kwType->key)) {      !strcmp(line->elements[1].item, kwType->key) &&
1190        !is_special_grub2_variable(line->elements[2].item)) {
1191   dbgPrintf("Line sets default config\n");   dbgPrintf("Line sets default config\n");
1192   cfg->flags &= ~GRUB_CONFIG_NO_DEFAULT;   cfg->flags &= ~GRUB_CONFIG_NO_DEFAULT;
1193   defaultLine = line;   defaultLine = line;
# Line 1008  static struct grubConfig * readConfig(co Line 1196  static struct grubConfig * readConfig(co
1196      cfg->flags &= ~GRUB_CONFIG_NO_DEFAULT;      cfg->flags &= ~GRUB_CONFIG_NO_DEFAULT;
1197      defaultLine = line;      defaultLine = line;
1198    
1199          } else if (line->type == LT_KERNEL) {          } else if (iskernel(line->type)) {
1200      /* if by some freak chance this is multiboot and the "module"      /* if by some freak chance this is multiboot and the "module"
1201       * lines came earlier in the template, make sure to use LT_HYPER       * lines came earlier in the template, make sure to use LT_HYPER
1202       * instead of LT_KERNEL now       * instead of LT_KERNEL now
# Line 1022  static struct grubConfig * readConfig(co Line 1210  static struct grubConfig * readConfig(co
1210       * This only applies to grub, but that's the only place we       * This only applies to grub, but that's the only place we
1211       * should find LT_MBMODULE lines anyway.       * should find LT_MBMODULE lines anyway.
1212       */       */
1213      struct singleLine * l;      for (struct singleLine *l = entry->lines; l; l = l->next) {
     for (l = entry->lines; l; l = l->next) {  
1214   if (l->type == LT_HYPER)   if (l->type == LT_HYPER)
1215      break;      break;
1216   else if (l->type == LT_KERNEL) {   else if (iskernel(l->type)) {
1217      l->type = LT_HYPER;      l->type = LT_HYPER;
1218      break;      break;
1219   }   }
# Line 1043  static struct grubConfig * readConfig(co Line 1230  static struct grubConfig * readConfig(co
1230   } else if (line->type == LT_TITLE && line->numElements > 1) {   } else if (line->type == LT_TITLE && line->numElements > 1) {
1231      /* make the title a single argument (undoing our parsing) */      /* make the title a single argument (undoing our parsing) */
1232      len = 0;      len = 0;
1233      for (i = 1; i < line->numElements; i++) {      for (int i = 1; i < line->numElements; i++) {
1234   len += strlen(line->elements[i].item);   len += strlen(line->elements[i].item);
1235   len += strlen(line->elements[i].indent);   len += strlen(line->elements[i].indent);
1236      }      }
1237      buf = malloc(len + 1);      buf = malloc(len + 1);
1238      *buf = '\0';      *buf = '\0';
1239    
1240      for (i = 1; i < line->numElements; i++) {      for (int i = 1; i < line->numElements; i++) {
1241   strcat(buf, line->elements[i].item);   strcat(buf, line->elements[i].item);
1242   free(line->elements[i].item);   free(line->elements[i].item);
1243    
# Line 1070  static struct grubConfig * readConfig(co Line 1257  static struct grubConfig * readConfig(co
1257      char *extras;      char *extras;
1258      char *title;      char *title;
1259    
1260      for (i = 1; i < line->numElements; i++) {      for (int i = 1; i < line->numElements; i++) {
1261   len += strlen(line->elements[i].item);   len += strlen(line->elements[i].item);
1262   len += strlen(line->elements[i].indent);   len += strlen(line->elements[i].indent);
1263      }      }
# Line 1082  static struct grubConfig * readConfig(co Line 1269  static struct grubConfig * readConfig(co
1269      *extras = '\0';      *extras = '\0';
1270    
1271      /* get title. */      /* get title. */
1272      for (i = 0; i < line->numElements; i++) {      for (int i = 0; i < line->numElements; i++) {
1273   if (!strcmp(line->elements[i].item, "menuentry"))   if (!strcmp(line->elements[i].item, "menuentry"))
1274      continue;      continue;
1275   if (isquote(*line->elements[i].item))   if (isquote(*line->elements[i].item))
# Line 1102  static struct grubConfig * readConfig(co Line 1289  static struct grubConfig * readConfig(co
1289    
1290      /* get extras */      /* get extras */
1291      int count = 0;      int count = 0;
1292      for (i = 0; i < line->numElements; i++) {      for (int i = 0; i < line->numElements; i++) {
1293   if (count == 2) {   if (count >= 2) {
1294      strcat(extras, line->elements[i].item);      strcat(extras, line->elements[i].item);
1295      strcat(extras, line->elements[i].indent);      strcat(extras, line->elements[i].indent);
1296   }   }
# Line 1205  static struct grubConfig * readConfig(co Line 1392  static struct grubConfig * readConfig(co
1392          if (defaultLine->numElements > 2 &&          if (defaultLine->numElements > 2 &&
1393      cfi->defaultSupportSaved &&      cfi->defaultSupportSaved &&
1394      !strncmp(defaultLine->elements[2].item,"\"${saved_entry}\"", 16)) {      !strncmp(defaultLine->elements[2].item,"\"${saved_entry}\"", 16)) {
1395      cfg->defaultImage = DEFAULT_SAVED_GRUB2;   cfg->cfi->defaultIsSaved = 1;
1396     cfg->defaultImage = DEFAULT_SAVED_GRUB2;
1397     if (cfg->cfi->getEnv) {
1398        char *defTitle = cfi->getEnv(cfg->cfi, "saved_entry");
1399        if (defTitle) {
1400     int index = 0;
1401     if (isnumber(defTitle)) {
1402        index = atoi(defTitle);
1403        entry = findEntryByIndex(cfg, index);
1404     } else {
1405        entry = findEntryByTitle(cfg, defTitle, &index);
1406     }
1407     if (entry)
1408        cfg->defaultImage = index;
1409        }
1410     }
1411   } else if (cfi->defaultIsVariable) {   } else if (cfi->defaultIsVariable) {
1412      char *value = defaultLine->elements[2].item;      char *value = defaultLine->elements[2].item;
1413      while (*value && (*value == '"' || *value == '\'' ||      while (*value && (*value == '"' || *value == '\'' ||
# Line 1223  static struct grubConfig * readConfig(co Line 1425  static struct grubConfig * readConfig(co
1425      cfg->defaultImage = strtol(defaultLine->elements[1].item, &end, 10);      cfg->defaultImage = strtol(defaultLine->elements[1].item, &end, 10);
1426      if (*end) cfg->defaultImage = -1;      if (*end) cfg->defaultImage = -1;
1427   } else if (defaultLine->numElements >= 2) {   } else if (defaultLine->numElements >= 2) {
1428      i = 0;      int i = 0;
1429      while ((entry = findEntryByIndex(cfg, i))) {      while ((entry = findEntryByIndex(cfg, i))) {
1430   for (line = entry->lines; line; line = line->next)   for (line = entry->lines; line; line = line->next)
1431      if (line->type == LT_TITLE) break;      if (line->type == LT_TITLE) break;
# Line 1246  static struct grubConfig * readConfig(co Line 1448  static struct grubConfig * readConfig(co
1448          cfg->defaultImage = -1;          cfg->defaultImage = -1;
1449      }      }
1450   }   }
1451        } else if (cfg->cfi->defaultIsSaved && cfg->cfi->getEnv) {
1452     char *defTitle = cfi->getEnv(cfg->cfi, "saved_entry");
1453     if (defTitle) {
1454        int index = 0;
1455        if (isnumber(defTitle)) {
1456     index = atoi(defTitle);
1457     entry = findEntryByIndex(cfg, index);
1458        } else {
1459     entry = findEntryByTitle(cfg, defTitle, &index);
1460        }
1461        if (entry)
1462     cfg->defaultImage = index;
1463     }
1464      } else {      } else {
1465          cfg->defaultImage = 0;          cfg->defaultImage = 0;
1466      }      }
# Line 1263  static void writeDefault(FILE * out, cha Line 1478  static void writeDefault(FILE * out, cha
1478    
1479      if (cfg->defaultImage == DEFAULT_SAVED)      if (cfg->defaultImage == DEFAULT_SAVED)
1480   fprintf(out, "%sdefault%ssaved\n", indent, separator);   fprintf(out, "%sdefault%ssaved\n", indent, separator);
1481      else if (cfg->defaultImage == DEFAULT_SAVED_GRUB2)      else if (cfg->cfi->defaultIsSaved) {
1482   fprintf(out, "%sset default=\"${saved_entry}\"\n", indent);   fprintf(out, "%sset default=\"${saved_entry}\"\n", indent);
1483      else if (cfg->defaultImage > -1) {   if (cfg->defaultImage >= 0 && cfg->cfi->setEnv) {
1484        char *title;
1485        entry = findEntryByIndex(cfg, cfg->defaultImage);
1486        line = getLineByType(LT_MENUENTRY, entry->lines);
1487        if (!line)
1488     line = getLineByType(LT_TITLE, entry->lines);
1489        if (line) {
1490     title = extractTitle(line);
1491     if (title)
1492        cfg->cfi->setEnv(cfg->cfi, "saved_entry", title);
1493        }
1494     }
1495        } else if (cfg->defaultImage > -1) {
1496   if (cfg->cfi->defaultIsIndex) {   if (cfg->cfi->defaultIsIndex) {
1497      if (cfg->cfi->defaultIsVariable) {      if (cfg->cfi->defaultIsVariable) {
1498          fprintf(out, "%sset default=\"%d\"\n", indent,          fprintf(out, "%sset default=\"%d\"\n", indent,
# Line 1325  static int writeConfig(struct grubConfig Line 1552  static int writeConfig(struct grubConfig
1552    
1553      /* most likely the symlink is relative, so change our      /* most likely the symlink is relative, so change our
1554         directory to the dir of the symlink */         directory to the dir of the symlink */
1555              rc = chdir(dirname(strdupa(outName)));      char *dir = strdupa(outName);
1556        rc = chdir(dirname(dir));
1557      do {      do {
1558   buf = alloca(len + 1);   buf = alloca(len + 1);
1559   rc = readlink(basename(outName), buf, len);   rc = readlink(basename(outName), buf, len);
# Line 1367  static int writeConfig(struct grubConfig Line 1595  static int writeConfig(struct grubConfig
1595      while (line) {      while (line) {
1596          if (line->type == LT_SET_VARIABLE && defaultKw &&          if (line->type == LT_SET_VARIABLE && defaultKw &&
1597   line->numElements == 3 &&   line->numElements == 3 &&
1598   !strcmp(line->elements[1].item, defaultKw->key)) {   !strcmp(line->elements[1].item, defaultKw->key) &&
1599     !is_special_grub2_variable(line->elements[2].item)) {
1600      writeDefault(out, line->indent, line->elements[0].indent, cfg);      writeDefault(out, line->indent, line->elements[0].indent, cfg);
1601      needs &= ~MAIN_DEFAULT;      needs &= ~MAIN_DEFAULT;
1602   } else if (line->type == LT_DEFAULT) {   } else if (line->type == LT_DEFAULT) {
# Line 1463  static char *findDiskForRoot() Line 1692  static char *findDiskForRoot()
1692      buf[rc] = '\0';      buf[rc] = '\0';
1693      chptr = buf;      chptr = buf;
1694    
1695        char *foundanswer = NULL;
1696    
1697      while (chptr && chptr != buf+rc) {      while (chptr && chptr != buf+rc) {
1698          devname = chptr;          devname = chptr;
1699    
# Line 1490  static char *findDiskForRoot() Line 1721  static char *findDiskForRoot()
1721           * for '/' obviously.           * for '/' obviously.
1722           */           */
1723          if (*(++chptr) == '/' && *(++chptr) == ' ') {          if (*(++chptr) == '/' && *(++chptr) == ' ') {
1724              /*              /* remember the last / entry in mtab */
1725               * 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);  
1726          }          }
1727    
1728          /* Next line */          /* Next line */
# Line 1505  static char *findDiskForRoot() Line 1731  static char *findDiskForRoot()
1731              chptr++;              chptr++;
1732      }      }
1733    
1734        /* Return the last / entry found */
1735        if (foundanswer) {
1736            chptr = strchr(foundanswer, ' ');
1737            *chptr = '\0';
1738            return strdup(foundanswer);
1739        }
1740    
1741      return NULL;      return NULL;
1742  }  }
1743    
1744  void printEntry(struct singleEntry * entry) {  void printEntry(struct singleEntry * entry, FILE *f) {
1745      int i;      int i;
1746      struct singleLine * line;      struct singleLine * line;
1747    
1748      for (line = entry->lines; line; line = line->next) {      for (line = entry->lines; line; line = line->next) {
1749   fprintf(stderr, "DBG: %s", line->indent);   log_message(f, "DBG: %s", line->indent);
1750   for (i = 0; i < line->numElements; i++) {   for (i = 0; i < line->numElements; i++) {
1751      /* Need to handle this, because we strip the quotes from      /* Need to handle this, because we strip the quotes from
1752       * menuentry when read it. */       * menuentry when read it. */
1753      if (line->type == LT_MENUENTRY && i == 1) {      if (line->type == LT_MENUENTRY && i == 1) {
1754   if(!isquote(*line->elements[i].item))   if(!isquote(*line->elements[i].item))
1755      fprintf(stderr, "\'%s\'", line->elements[i].item);      log_message(f, "\'%s\'", line->elements[i].item);
1756   else   else
1757      fprintf(stderr, "%s", line->elements[i].item);      log_message(f, "%s", line->elements[i].item);
1758   fprintf(stderr, "%s", line->elements[i].indent);   log_message(f, "%s", line->elements[i].indent);
1759    
1760   continue;   continue;
1761      }      }
1762            
1763      fprintf(stderr, "%s%s",      log_message(f, "%s%s",
1764      line->elements[i].item, line->elements[i].indent);      line->elements[i].item, line->elements[i].indent);
1765   }   }
1766   fprintf(stderr, "\n");   log_message(f, "\n");
1767      }      }
1768  }  }
1769    
1770  void notSuitablePrintf(struct singleEntry * entry, const char *fmt, ...)  void notSuitablePrintf(struct singleEntry * entry, int okay, const char *fmt, ...)
1771  {  {
1772      va_list argp;      static int once;
1773        va_list argp, argq;
1774    
1775        va_start(argp, fmt);
1776    
1777        va_copy(argq, argp);
1778        if (!once) {
1779     log_time(NULL);
1780     log_message(NULL, "command line: %s\n", saved_command_line);
1781        }
1782        log_message(NULL, "DBG: Image entry %s: ", okay ? "succeeded" : "failed");
1783        log_vmessage(NULL, fmt, argq);
1784    
1785        printEntry(entry, NULL);
1786        va_end(argq);
1787    
1788        if (!debug) {
1789     once = 1;
1790         va_end(argp);
1791     return;
1792        }
1793    
1794      if (!debug)      if (okay) {
1795     va_end(argp);
1796   return;   return;
1797        }
1798    
1799      va_start(argp, fmt);      if (!once)
1800     log_message(stderr, "DBG: command line: %s\n", saved_command_line);
1801        once = 1;
1802      fprintf(stderr, "DBG: Image entry failed: ");      fprintf(stderr, "DBG: Image entry failed: ");
1803      vfprintf(stderr, fmt, argp);      vfprintf(stderr, fmt, argp);
1804      printEntry(entry);      printEntry(entry, stderr);
1805      va_end(argp);      va_end(argp);
1806  }  }
1807    
# Line 1571  int suitableImage(struct singleEntry * e Line 1828  int suitableImage(struct singleEntry * e
1828      char * rootdev;      char * rootdev;
1829    
1830      if (skipRemoved && entry->skip) {      if (skipRemoved && entry->skip) {
1831   notSuitablePrintf(entry, "marked to skip\n");   notSuitablePrintf(entry, 0, "marked to skip\n");
1832   return 0;   return 0;
1833      }      }
1834    
1835      line = getLineByType(LT_KERNEL|LT_HYPER, entry->lines);      line = getLineByType(LT_KERNEL|LT_HYPER|LT_KERNEL_EFI|LT_KERNEL_16, entry->lines);
1836      if (!line) {      if (!line) {
1837   notSuitablePrintf(entry, "no line found\n");   notSuitablePrintf(entry, 0, "no line found\n");
1838   return 0;   return 0;
1839      }      }
1840      if (line->numElements < 2) {      if (line->numElements < 2) {
1841   notSuitablePrintf(entry, "line has only %d elements\n",   notSuitablePrintf(entry, 0, "line has only %d elements\n",
1842      line->numElements);      line->numElements);
1843   return 0;   return 0;
1844      }      }
1845    
1846      if (flags & GRUBBY_BADIMAGE_OKAY) return 1;      if (flags & GRUBBY_BADIMAGE_OKAY) {
1847        notSuitablePrintf(entry, 1, "\n");
1848        return 1;
1849        }
1850    
1851      fullName = alloca(strlen(bootPrefix) +      fullName = alloca(strlen(bootPrefix) +
1852        strlen(line->elements[1].item) + 1);        strlen(line->elements[1].item) + 1);
# Line 1597  int suitableImage(struct singleEntry * e Line 1857  int suitableImage(struct singleEntry * e
1857      sprintf(fullName, "%s%s%s", bootPrefix, hasslash ? "" : "/",      sprintf(fullName, "%s%s%s", bootPrefix, hasslash ? "" : "/",
1858              line->elements[1].item + rootspec_offset);              line->elements[1].item + rootspec_offset);
1859      if (access(fullName, R_OK)) {      if (access(fullName, R_OK)) {
1860   notSuitablePrintf(entry, "access to %s failed\n", fullName);   notSuitablePrintf(entry, 0, "access to %s failed\n", fullName);
1861   return 0;   return 0;
1862      }      }
1863      for (i = 2; i < line->numElements; i++)      for (i = 2; i < line->numElements; i++)
# Line 1618  int suitableImage(struct singleEntry * e Line 1878  int suitableImage(struct singleEntry * e
1878    
1879              /* failed to find one */              /* failed to find one */
1880              if (!line) {              if (!line) {
1881   notSuitablePrintf(entry, "no line found\n");   notSuitablePrintf(entry, 0, "no line found\n");
1882   return 0;   return 0;
1883              }              }
1884    
# Line 1627  int suitableImage(struct singleEntry * e Line 1887  int suitableImage(struct singleEntry * e
1887      if (i < line->numElements)      if (i < line->numElements)
1888          dev = line->elements[i].item + 5;          dev = line->elements[i].item + 5;
1889      else {      else {
1890   notSuitablePrintf(entry, "no root= entry found\n");   notSuitablePrintf(entry, 0, "no root= entry found\n");
1891   /* it failed too...  can't find root= */   /* it failed too...  can't find root= */
1892          return 0;          return 0;
1893              }              }
# Line 1636  int suitableImage(struct singleEntry * e Line 1896  int suitableImage(struct singleEntry * e
1896    
1897      dev = getpathbyspec(dev);      dev = getpathbyspec(dev);
1898      if (!getpathbyspec(dev)) {      if (!getpathbyspec(dev)) {
1899          notSuitablePrintf(entry, "can't find blkid entry for %s\n", dev);          notSuitablePrintf(entry, 0, "can't find blkid entry for %s\n", dev);
1900          return 0;          return 0;
1901      } else      } else
1902   dev = getpathbyspec(dev);   dev = getpathbyspec(dev);
1903    
1904      rootdev = findDiskForRoot();      rootdev = findDiskForRoot();
1905      if (!rootdev) {      if (!rootdev) {
1906          notSuitablePrintf(entry, "can't find root device\n");          notSuitablePrintf(entry, 0, "can't find root device\n");
1907   return 0;   return 0;
1908      }      }
1909    
1910      if (!getuuidbydev(rootdev) || !getuuidbydev(dev)) {      if (!getuuidbydev(rootdev) || !getuuidbydev(dev)) {
1911          notSuitablePrintf(entry, "uuid missing: rootdev %s, dev %s\n",          notSuitablePrintf(entry, 0, "uuid missing: rootdev %s, dev %s\n",
1912   getuuidbydev(rootdev), getuuidbydev(dev));   getuuidbydev(rootdev), getuuidbydev(dev));
1913          free(rootdev);          free(rootdev);
1914          return 0;          return 0;
1915      }      }
1916    
1917      if (strcmp(getuuidbydev(rootdev), getuuidbydev(dev))) {      if (strcmp(getuuidbydev(rootdev), getuuidbydev(dev))) {
1918          notSuitablePrintf(entry, "uuid mismatch: rootdev %s, dev %s\n",          notSuitablePrintf(entry, 0, "uuid mismatch: rootdev %s, dev %s\n",
1919   getuuidbydev(rootdev), getuuidbydev(dev));   getuuidbydev(rootdev), getuuidbydev(dev));
1920   free(rootdev);   free(rootdev);
1921          return 0;          return 0;
1922      }      }
1923    
1924      free(rootdev);      free(rootdev);
1925        notSuitablePrintf(entry, 1, "\n");
1926    
1927      return 1;      return 1;
1928  }  }
# Line 1705  struct singleEntry * findEntryByPath(str Line 1966  struct singleEntry * findEntryByPath(str
1966   entry = findEntryByIndex(config, indexVars[i]);   entry = findEntryByIndex(config, indexVars[i]);
1967   if (!entry) return NULL;   if (!entry) return NULL;
1968    
1969   line = getLineByType(LT_KERNEL|LT_HYPER, entry->lines);   line = getLineByType(LT_KERNEL|LT_HYPER|LT_KERNEL_EFI|LT_KERNEL_16, entry->lines);
1970   if (!line) return NULL;   if (!line) return NULL;
1971    
1972   if (index) *index = indexVars[i];   if (index) *index = indexVars[i];
# Line 1754  struct singleEntry * findEntryByPath(str Line 2015  struct singleEntry * findEntryByPath(str
2015    
2016      /* check all the lines matching checkType */      /* check all the lines matching checkType */
2017      for (line = entry->lines; line; line = line->next) {      for (line = entry->lines; line; line = line->next) {
2018   line = getLineByType(entry->multiboot && checkType == LT_KERNEL ?   enum lineType_e ct = checkType;
2019       LT_KERNEL|LT_MBMODULE|LT_HYPER :   if (entry->multiboot && checkType == LT_KERNEL)
2020       checkType, line);      ct = LT_KERNEL|LT_KERNEL_EFI|LT_MBMODULE|LT_HYPER|LT_KERNEL_16;
2021   if (!line) break;  /* not found in this entry */   else if (checkType & LT_KERNEL)
2022        ct = checkType | LT_KERNEL_EFI | LT_KERNEL_16;
2023     line = getLineByType(ct, line);
2024     if (!line)
2025        break;  /* not found in this entry */
2026    
2027   if (line && line->type != LT_MENUENTRY &&   if (line && line->type != LT_MENUENTRY &&
2028   line->numElements >= 2) {   line->numElements >= 2) {
# Line 1776  struct singleEntry * findEntryByPath(str Line 2041  struct singleEntry * findEntryByPath(str
2041       * non-Linux boot entries (could find netbsd etc, though, which is       * non-Linux boot entries (could find netbsd etc, though, which is
2042       * unfortunate)       * unfortunate)
2043       */       */
2044      if (line && getLineByType(LT_KERNEL|LT_HYPER, entry->lines))      if (line && getLineByType(LT_KERNEL|LT_HYPER|LT_KERNEL_EFI|LT_KERNEL_16, entry->lines))
2045   break; /* found 'im! */   break; /* found 'im! */
2046   }   }
2047    
# Line 1786  struct singleEntry * findEntryByPath(str Line 2051  struct singleEntry * findEntryByPath(str
2051      return entry;      return entry;
2052  }  }
2053    
2054    struct singleEntry * findEntryByTitle(struct grubConfig * cfg, char *title,
2055          int * index) {
2056        struct singleEntry * entry;
2057        struct singleLine * line;
2058        int i;
2059        char * newtitle;
2060    
2061        for (i = 0, entry = cfg->entries; entry; entry = entry->next, i++) {
2062     if (index && i < *index)
2063        continue;
2064     line = getLineByType(LT_TITLE, entry->lines);
2065     if (!line)
2066        line = getLineByType(LT_MENUENTRY, entry->lines);
2067     if (!line)
2068        continue;
2069     newtitle = grub2ExtractTitle(line);
2070     if (!newtitle)
2071        continue;
2072     if (!strcmp(title, newtitle))
2073        break;
2074        }
2075    
2076        if (!entry)
2077     return NULL;
2078    
2079        if (index)
2080     *index = i;
2081        return entry;
2082    }
2083    
2084  struct singleEntry * findEntryByIndex(struct grubConfig * cfg, int index) {  struct singleEntry * findEntryByIndex(struct grubConfig * cfg, int index) {
2085      struct singleEntry * entry;      struct singleEntry * entry;
2086    
# Line 1808  struct singleEntry * findTemplate(struct Line 2103  struct singleEntry * findTemplate(struct
2103      struct singleEntry * entry, * entry2;      struct singleEntry * entry, * entry2;
2104      int index;      int index;
2105    
2106      if (cfg->defaultImage > -1) {      if (cfg->cfi->defaultIsSaved) {
2107     if (cfg->cfi->getEnv) {
2108        char *defTitle = cfg->cfi->getEnv(cfg->cfi, "saved_entry");
2109        if (defTitle) {
2110     int index = 0;
2111     if (isnumber(defTitle)) {
2112        index = atoi(defTitle);
2113        entry = findEntryByIndex(cfg, index);
2114     } else {
2115        entry = findEntryByTitle(cfg, defTitle, &index);
2116     }
2117     if (entry)
2118        cfg->defaultImage = index;
2119        }
2120     }
2121        } else if (cfg->defaultImage > -1) {
2122   entry = findEntryByIndex(cfg, cfg->defaultImage);   entry = findEntryByIndex(cfg, cfg->defaultImage);
2123   if (entry && suitableImage(entry, prefix, skipRemoved, flags)) {   if (entry && suitableImage(entry, prefix, skipRemoved, flags)) {
2124      if (indexPtr) *indexPtr = cfg->defaultImage;      if (indexPtr) *indexPtr = cfg->defaultImage;
# Line 1878  void markRemovedImage(struct grubConfig Line 2188  void markRemovedImage(struct grubConfig
2188    
2189  void setDefaultImage(struct grubConfig * config, int hasNew,  void setDefaultImage(struct grubConfig * config, int hasNew,
2190       const char * defaultKernelPath, int newIsDefault,       const char * defaultKernelPath, int newIsDefault,
2191       const char * prefix, int flags) {       const char * prefix, int flags, int index) {
2192      struct singleEntry * entry, * entry2, * newDefault;      struct singleEntry * entry, * entry2, * newDefault;
2193      int i, j;      int i, j;
2194    
2195      if (newIsDefault) {      if (newIsDefault) {
2196   config->defaultImage = 0;   config->defaultImage = 0;
2197   return;   return;
2198        } else if ((index >= 0) && config->cfi->defaultIsIndex) {
2199     if (findEntryByIndex(config, index))
2200        config->defaultImage = index;
2201     else
2202        config->defaultImage = -1;
2203     return;
2204      } else if (defaultKernelPath) {      } else if (defaultKernelPath) {
2205   i = 0;   i = 0;
2206   if (findEntryByPath(config, defaultKernelPath, prefix, &i)) {   if (findEntryByPath(config, defaultKernelPath, prefix, &i)) {
# Line 1959  void displayEntry(struct singleEntry * e Line 2275  void displayEntry(struct singleEntry * e
2275    
2276      printf("index=%d\n", index);      printf("index=%d\n", index);
2277    
2278      line = getLineByType(LT_KERNEL|LT_HYPER, entry->lines);      line = getLineByType(LT_KERNEL|LT_HYPER|LT_KERNEL_EFI|LT_KERNEL_16, entry->lines);
2279      if (!line) {      if (!line) {
2280          printf("non linux entry\n");          printf("non linux entry\n");
2281          return;          return;
2282      }      }
2283    
2284      printf("kernel=%s%s\n", prefix, line->elements[1].item);      if (!strncmp(prefix, line->elements[1].item, strlen(prefix)))
2285     printf("kernel=%s\n", line->elements[1].item);
2286        else
2287     printf("kernel=%s%s\n", prefix, line->elements[1].item);
2288    
2289      if (line->numElements >= 3) {      if (line->numElements >= 3) {
2290   printf("args=\"");   printf("args=\"");
# Line 2021  void displayEntry(struct singleEntry * e Line 2340  void displayEntry(struct singleEntry * e
2340   printf("root=%s\n", s);   printf("root=%s\n", s);
2341      }      }
2342    
2343      line = getLineByType(LT_INITRD, entry->lines);      line = getLineByType(LT_INITRD|LT_INITRD_EFI|LT_INITRD_16, entry->lines);
2344    
2345      if (line && line->numElements >= 2) {      if (line && line->numElements >= 2) {
2346   printf("initrd=%s", prefix);   if (!strncmp(prefix, line->elements[1].item, strlen(prefix)))
2347        printf("initrd=");
2348     else
2349        printf("initrd=%s", prefix);
2350    
2351   for (i = 1; i < line->numElements; i++)   for (i = 1; i < line->numElements; i++)
2352      printf("%s%s", line->elements[i].item, line->elements[i].indent);      printf("%s%s", line->elements[i].item, line->elements[i].indent);
2353   printf("\n");   printf("\n");
# Line 2042  void displayEntry(struct singleEntry * e Line 2365  void displayEntry(struct singleEntry * e
2365      }      }
2366  }  }
2367    
2368    int isSuseSystem(void) {
2369        const char * path;
2370        const static char default_path[] = "/etc/SuSE-release";
2371    
2372        if ((path = getenv("GRUBBY_SUSE_RELEASE")) == NULL)
2373     path = default_path;
2374    
2375        if (!access(path, R_OK))
2376     return 1;
2377        return 0;
2378    }
2379    
2380    int isSuseGrubConf(const char * path) {
2381        FILE * grubConf;
2382        char * line = NULL;
2383        size_t len = 0, res = 0;
2384    
2385        grubConf = fopen(path, "r");
2386        if (!grubConf) {
2387            dbgPrintf("Could not open SuSE configuration file '%s'\n", path);
2388     return 0;
2389        }
2390    
2391        while ((res = getline(&line, &len, grubConf)) != -1) {
2392     if (!strncmp(line, "setup", 5)) {
2393        fclose(grubConf);
2394        free(line);
2395        return 1;
2396     }
2397        }
2398    
2399        dbgPrintf("SuSE configuration file '%s' does not appear to be valid\n",
2400          path);
2401    
2402        fclose(grubConf);
2403        free(line);
2404        return 0;
2405    }
2406    
2407    int suseGrubConfGetLba(const char * path, int * lbaPtr) {
2408        FILE * grubConf;
2409        char * line = NULL;
2410        size_t res = 0, len = 0;
2411    
2412        if (!path) return 1;
2413        if (!lbaPtr) return 1;
2414    
2415        grubConf = fopen(path, "r");
2416        if (!grubConf) return 1;
2417    
2418        while ((res = getline(&line, &len, grubConf)) != -1) {
2419     if (line[res - 1] == '\n')
2420        line[res - 1] = '\0';
2421     else if (len > res)
2422        line[res] = '\0';
2423     else {
2424        line = realloc(line, res + 1);
2425        line[res] = '\0';
2426     }
2427    
2428     if (!strncmp(line, "setup", 5)) {
2429        if (strstr(line, "--force-lba")) {
2430            *lbaPtr = 1;
2431        } else {
2432            *lbaPtr = 0;
2433        }
2434        dbgPrintf("lba: %i\n", *lbaPtr);
2435        break;
2436     }
2437        }
2438    
2439        free(line);
2440        fclose(grubConf);
2441        return 0;
2442    }
2443    
2444    int suseGrubConfGetInstallDevice(const char * path, char ** devicePtr) {
2445        FILE * grubConf;
2446        char * line = NULL;
2447        size_t res = 0, len = 0;
2448        char * lastParamPtr = NULL;
2449        char * secLastParamPtr = NULL;
2450        char installDeviceNumber = '\0';
2451        char * bounds = NULL;
2452    
2453        if (!path) return 1;
2454        if (!devicePtr) return 1;
2455    
2456        grubConf = fopen(path, "r");
2457        if (!grubConf) return 1;
2458    
2459        while ((res = getline(&line, &len, grubConf)) != -1) {
2460     if (strncmp(line, "setup", 5))
2461        continue;
2462    
2463     if (line[res - 1] == '\n')
2464        line[res - 1] = '\0';
2465     else if (len > res)
2466        line[res] = '\0';
2467     else {
2468        line = realloc(line, res + 1);
2469        line[res] = '\0';
2470     }
2471    
2472     lastParamPtr = bounds = line + res;
2473    
2474     /* Last parameter in grub may be an optional IMAGE_DEVICE */
2475     while (!isspace(*lastParamPtr))
2476        lastParamPtr--;
2477     lastParamPtr++;
2478    
2479     secLastParamPtr = lastParamPtr - 2;
2480     dbgPrintf("lastParamPtr: %s\n", lastParamPtr);
2481    
2482     if (lastParamPtr + 3 > bounds) {
2483        dbgPrintf("lastParamPtr going over boundary");
2484        fclose(grubConf);
2485        free(line);
2486        return 1;
2487     }
2488     if (!strncmp(lastParamPtr, "(hd", 3))
2489        lastParamPtr += 3;
2490     dbgPrintf("lastParamPtr: %c\n", *lastParamPtr);
2491    
2492     /*
2493     * Second last parameter will decide wether last parameter is
2494     * an IMAGE_DEVICE or INSTALL_DEVICE
2495     */
2496     while (!isspace(*secLastParamPtr))
2497        secLastParamPtr--;
2498     secLastParamPtr++;
2499    
2500     if (secLastParamPtr + 3 > bounds) {
2501        dbgPrintf("secLastParamPtr going over boundary");
2502        fclose(grubConf);
2503        free(line);
2504        return 1;
2505     }
2506     dbgPrintf("secLastParamPtr: %s\n", secLastParamPtr);
2507     if (!strncmp(secLastParamPtr, "(hd", 3)) {
2508        secLastParamPtr += 3;
2509        dbgPrintf("secLastParamPtr: %c\n", *secLastParamPtr);
2510        installDeviceNumber = *secLastParamPtr;
2511     } else {
2512        installDeviceNumber = *lastParamPtr;
2513     }
2514    
2515     *devicePtr = malloc(6);
2516     snprintf(*devicePtr, 6, "(hd%c)", installDeviceNumber);
2517     dbgPrintf("installDeviceNumber: %c\n", installDeviceNumber);
2518     fclose(grubConf);
2519     free(line);
2520     return 0;
2521        }
2522    
2523        free(line);
2524        fclose(grubConf);
2525        return 1;
2526    }
2527    
2528    int grubGetBootFromDeviceMap(const char * device,
2529         char ** bootPtr) {
2530        FILE * deviceMap;
2531        char * line = NULL;
2532        size_t res = 0, len = 0;
2533        char * devicePtr;
2534        char * bounds = NULL;
2535        const char * path;
2536        const static char default_path[] = "/boot/grub/device.map";
2537    
2538        if (!device) return 1;
2539        if (!bootPtr) return 1;
2540    
2541        if ((path = getenv("GRUBBY_GRUB_DEVICE_MAP")) == NULL)
2542     path = default_path;
2543    
2544        dbgPrintf("opening grub device.map file from: %s\n", path);
2545        deviceMap = fopen(path, "r");
2546        if (!deviceMap)
2547     return 1;
2548    
2549        while ((res = getline(&line, &len, deviceMap)) != -1) {
2550            if (!strncmp(line, "#", 1))
2551        continue;
2552    
2553     if (line[res - 1] == '\n')
2554        line[res - 1] = '\0';
2555     else if (len > res)
2556        line[res] = '\0';
2557     else {
2558        line = realloc(line, res + 1);
2559        line[res] = '\0';
2560     }
2561    
2562     devicePtr = line;
2563     bounds = line + res;
2564    
2565     while ((isspace(*line) && ((devicePtr + 1) <= bounds)))
2566        devicePtr++;
2567     dbgPrintf("device: %s\n", devicePtr);
2568    
2569     if (!strncmp(devicePtr, device, strlen(device))) {
2570        devicePtr += strlen(device);
2571        while (isspace(*devicePtr) && ((devicePtr + 1) <= bounds))
2572            devicePtr++;
2573    
2574        *bootPtr = strdup(devicePtr);
2575        break;
2576     }
2577        }
2578    
2579        free(line);
2580        fclose(deviceMap);
2581        return 0;
2582    }
2583    
2584    int suseGrubConfGetBoot(const char * path, char ** bootPtr) {
2585        char * grubDevice;
2586    
2587        if (suseGrubConfGetInstallDevice(path, &grubDevice))
2588     dbgPrintf("error looking for grub installation device\n");
2589        else
2590     dbgPrintf("grubby installation device: %s\n", grubDevice);
2591    
2592        if (grubGetBootFromDeviceMap(grubDevice, bootPtr))
2593     dbgPrintf("error looking for grub boot device\n");
2594        else
2595     dbgPrintf("grubby boot device: %s\n", *bootPtr);
2596    
2597        free(grubDevice);
2598        return 0;
2599    }
2600    
2601    int parseSuseGrubConf(int * lbaPtr, char ** bootPtr) {
2602        /*
2603         * This SuSE grub configuration file at this location is not your average
2604         * grub configuration file, but instead the grub commands used to setup
2605         * grub on that system.
2606         */
2607        const char * path;
2608        const static char default_path[] = "/etc/grub.conf";
2609    
2610        if ((path = getenv("GRUBBY_SUSE_GRUB_CONF")) == NULL)
2611     path = default_path;
2612    
2613        if (!isSuseGrubConf(path)) return 1;
2614    
2615        if (lbaPtr) {
2616            *lbaPtr = 0;
2617            if (suseGrubConfGetLba(path, lbaPtr))
2618                return 1;
2619        }
2620    
2621        if (bootPtr) {
2622            *bootPtr = NULL;
2623            suseGrubConfGetBoot(path, bootPtr);
2624        }
2625    
2626        return 0;
2627    }
2628    
2629  int parseSysconfigGrub(int * lbaPtr, char ** bootPtr) {  int parseSysconfigGrub(int * lbaPtr, char ** bootPtr) {
2630      FILE * in;      FILE * in;
2631      char buf[1024];      char buf[1024];
# Line 2090  int parseSysconfigGrub(int * lbaPtr, cha Line 2674  int parseSysconfigGrub(int * lbaPtr, cha
2674  }  }
2675    
2676  void dumpSysconfigGrub(void) {  void dumpSysconfigGrub(void) {
2677      char * boot;      char * boot = NULL;
2678      int lba;      int lba;
2679    
2680      if (!parseSysconfigGrub(&lba, &boot)) {      if (isSuseSystem()) {
2681   if (lba) printf("lba\n");          if (parseSuseGrubConf(&lba, &boot)) {
2682   if (boot) printf("boot=%s\n", boot);      free(boot);
2683        return;
2684     }
2685        } else {
2686            if (parseSysconfigGrub(&lba, &boot)) {
2687        free(boot);
2688        return;
2689     }
2690        }
2691    
2692        if (lba) printf("lba\n");
2693        if (boot) {
2694     printf("boot=%s\n", boot);
2695     free(boot);
2696      }      }
2697  }  }
2698    
# Line 2144  struct singleLine * addLineTmpl(struct s Line 2741  struct singleLine * addLineTmpl(struct s
2741  {  {
2742      struct singleLine * newLine = lineDup(tmplLine);      struct singleLine * newLine = lineDup(tmplLine);
2743    
2744        if (isEfi && cfi == &grub2ConfigType) {
2745     enum lineType_e old = newLine->type;
2746     newLine->type = preferredLineType(newLine->type, cfi);
2747     if (old != newLine->type)
2748        newLine->elements[0].item = getKeyByType(newLine->type, cfi);
2749        }
2750    
2751      if (val) {      if (val) {
2752   /* override the inherited value with our own.   /* override the inherited value with our own.
2753   * 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 2153  struct singleLine * addLineTmpl(struct s Line 2757  struct singleLine * addLineTmpl(struct s
2757   insertElement(newLine, val, 1, cfi);   insertElement(newLine, val, 1, cfi);
2758    
2759   /* but try to keep the rootspec from the template... sigh */   /* but try to keep the rootspec from the template... sigh */
2760   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)) {
2761      char * rootspec = getRootSpecifier(tmplLine->elements[1].item);      char * rootspec = getRootSpecifier(tmplLine->elements[1].item);
2762      if (rootspec != NULL) {      if (rootspec != NULL) {
2763   free(newLine->elements[1].item);   free(newLine->elements[1].item);
# Line 2190  struct singleLine *  addLine(struct sing Line 2794  struct singleLine *  addLine(struct sing
2794      /* 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
2795       * stack since it calls addLineTmpl which will make copies.       * stack since it calls addLineTmpl which will make copies.
2796       */       */
   
2797      if (type == LT_TITLE && cfi->titleBracketed) {      if (type == LT_TITLE && cfi->titleBracketed) {
2798   /* we're doing a bracketed title (zipl) */   /* we're doing a bracketed title (zipl) */
2799   tmpl.type = type;   tmpl.type = type;
# Line 2524  int updateActualImage(struct grubConfig Line 3127  int updateActualImage(struct grubConfig
3127      firstElement = 2;      firstElement = 2;
3128    
3129   } else {   } else {
3130      line = getLineByType(LT_KERNEL|LT_MBMODULE, entry->lines);      line = getLineByType(LT_KERNEL|LT_MBMODULE|LT_KERNEL_EFI|LT_KERNEL_16, entry->lines);
3131      if (!line) {      if (!line) {
3132   /* no LT_KERNEL or LT_MBMODULE in this entry? */   /* no LT_KERNEL or LT_MBMODULE in this entry? */
3133   continue;   continue;
# Line 2680  int updateImage(struct grubConfig * cfg, Line 3283  int updateImage(struct grubConfig * cfg,
3283      return rc;      return rc;
3284  }  }
3285    
3286    int addMBInitrd(struct grubConfig * cfg, const char *newMBKernel,
3287     const char * image, const char * prefix, const char * initrd) {
3288        struct singleEntry * entry;
3289        struct singleLine * line, * kernelLine, *endLine = NULL;
3290        int index = 0;
3291    
3292        if (!image) return 0;
3293    
3294        for (; (entry = findEntryByPath(cfg, newMBKernel, prefix, &index)); index++) {
3295            kernelLine = getLineByType(LT_MBMODULE, entry->lines);
3296            if (!kernelLine) continue;
3297    
3298            if (prefix) {
3299                int prefixLen = strlen(prefix);
3300                if (!strncmp(initrd, prefix, prefixLen))
3301                    initrd += prefixLen;
3302            }
3303     endLine = getLineByType(LT_ENTRY_END, entry->lines);
3304     if (endLine)
3305        removeLine(entry, endLine);
3306            line = addLine(entry, cfg->cfi, preferredLineType(LT_MBMODULE,cfg->cfi),
3307     kernelLine->indent, initrd);
3308            if (!line)
3309        return 1;
3310     if (endLine) {
3311        line = addLine(entry, cfg->cfi, LT_ENTRY_END, "", NULL);
3312                if (!line)
3313     return 1;
3314     }
3315    
3316            break;
3317        }
3318    
3319        return 0;
3320    }
3321    
3322  int updateInitrd(struct grubConfig * cfg, const char * image,  int updateInitrd(struct grubConfig * cfg, const char * image,
3323                   const char * prefix, const char * initrd) {                   const char * prefix, const char * initrd) {
3324      struct singleEntry * entry;      struct singleEntry * entry;
# Line 2689  int updateInitrd(struct grubConfig * cfg Line 3328  int updateInitrd(struct grubConfig * cfg
3328      if (!image) return 0;      if (!image) return 0;
3329    
3330      for (; (entry = findEntryByPath(cfg, image, prefix, &index)); index++) {      for (; (entry = findEntryByPath(cfg, image, prefix, &index)); index++) {
3331          kernelLine = getLineByType(LT_KERNEL, entry->lines);          kernelLine = getLineByType(LT_KERNEL|LT_KERNEL_EFI|LT_KERNEL_16, entry->lines);
3332          if (!kernelLine) continue;          if (!kernelLine) continue;
3333    
3334          line = getLineByType(LT_INITRD, entry->lines);          line = getLineByType(LT_INITRD|LT_INITRD_EFI|LT_INITRD_16, entry->lines);
3335          if (line)          if (line)
3336              removeLine(entry, line);              removeLine(entry, line);
3337          if (prefix) {          if (prefix) {
# Line 2703  int updateInitrd(struct grubConfig * cfg Line 3342  int updateInitrd(struct grubConfig * cfg
3342   endLine = getLineByType(LT_ENTRY_END, entry->lines);   endLine = getLineByType(LT_ENTRY_END, entry->lines);
3343   if (endLine)   if (endLine)
3344      removeLine(entry, endLine);      removeLine(entry, endLine);
3345          line = addLine(entry, cfg->cfi, LT_INITRD, kernelLine->indent, initrd);   enum lineType_e lt;
3346     switch(kernelLine->type) {
3347        case LT_KERNEL:
3348            lt = LT_INITRD;
3349     break;
3350        case LT_KERNEL_EFI:
3351            lt = LT_INITRD_EFI;
3352     break;
3353        case LT_KERNEL_16:
3354            lt = LT_INITRD_16;
3355     break;
3356        default:
3357            lt = preferredLineType(LT_INITRD, cfg->cfi);
3358     }
3359            line = addLine(entry, cfg->cfi, lt, kernelLine->indent, initrd);
3360          if (!line)          if (!line)
3361      return 1;      return 1;
3362   if (endLine) {   if (endLine) {
# Line 2909  int checkForGrub(struct grubConfig * con Line 3562  int checkForGrub(struct grubConfig * con
3562      int fd;      int fd;
3563      unsigned char bootSect[512];      unsigned char bootSect[512];
3564      char * boot;      char * boot;
3565        int onSuse = isSuseSystem();
3566    
3567      if (parseSysconfigGrub(NULL, &boot))  
3568   return 0;      if (onSuse) {
3569     if (parseSuseGrubConf(NULL, &boot))
3570        return 0;
3571        } else {
3572     if (parseSysconfigGrub(NULL, &boot))
3573        return 0;
3574        }
3575    
3576      /* assume grub is not installed -- not an error condition */      /* assume grub is not installed -- not an error condition */
3577      if (!boot)      if (!boot)
# Line 2930  int checkForGrub(struct grubConfig * con Line 3590  int checkForGrub(struct grubConfig * con
3590      }      }
3591      close(fd);      close(fd);
3592    
3593        /* The more elaborate checks do not work on SuSE. The checks done
3594         * seem to be reasonble (at least for now), so just return success
3595         */
3596        if (onSuse)
3597     return 2;
3598    
3599      return checkDeviceBootloader(boot, bootSect);      return checkDeviceBootloader(boot, bootSect);
3600  }  }
3601    
# Line 2963  int checkForExtLinux(struct grubConfig * Line 3629  int checkForExtLinux(struct grubConfig *
3629      return checkDeviceBootloader(boot, bootSect);      return checkDeviceBootloader(boot, bootSect);
3630  }  }
3631    
3632    int checkForYaboot(struct grubConfig * config) {
3633        /*
3634         * This is a simplistic check that we consider good enough for own puporses
3635         *
3636         * If we were to properly check if yaboot is *installed* we'd need to:
3637         * 1) get the system boot device (LT_BOOT)
3638         * 2) considering it's a raw filesystem, check if the yaboot binary matches
3639         *    the content on the boot device
3640         * 3) if not, copy the binary to a temporary file and run "addnote" on it
3641         * 4) check again if binary and boot device contents match
3642         */
3643        if (!access("/etc/yaboot.conf", R_OK))
3644     return 2;
3645    
3646        return 1;
3647    }
3648    
3649    int checkForElilo(struct grubConfig * config) {
3650        if (!access("/etc/elilo.conf", R_OK))
3651     return 2;
3652    
3653        return 1;
3654    }
3655    
3656  static char * getRootSpecifier(char * str) {  static char * getRootSpecifier(char * str) {
3657      char * idx, * rootspec = NULL;      char * idx, * rootspec = NULL;
3658    
# Line 2977  static char * getRootSpecifier(char * st Line 3667  static char * getRootSpecifier(char * st
3667  static char * getInitrdVal(struct grubConfig * config,  static char * getInitrdVal(struct grubConfig * config,
3668     const char * prefix, struct singleLine *tmplLine,     const char * prefix, struct singleLine *tmplLine,
3669     const char * newKernelInitrd,     const char * newKernelInitrd,
3670     char ** extraInitrds, int extraInitrdCount)     const char ** extraInitrds, int extraInitrdCount)
3671  {  {
3672      char *initrdVal, *end;      char *initrdVal, *end;
3673      int i;      int i;
# Line 3022  static char * getInitrdVal(struct grubCo Line 3712  static char * getInitrdVal(struct grubCo
3712    
3713  int addNewKernel(struct grubConfig * config, struct singleEntry * template,  int addNewKernel(struct grubConfig * config, struct singleEntry * template,
3714           const char * prefix,           const char * prefix,
3715   char * newKernelPath, char * newKernelTitle,   const char * newKernelPath, const char * newKernelTitle,
3716   char * newKernelArgs, char * newKernelInitrd,   const char * newKernelArgs, const char * newKernelInitrd,
3717   char ** extraInitrds, int extraInitrdCount,   const char ** extraInitrds, int extraInitrdCount,
3718                   char * newMBKernel, char * newMBKernelArgs) {                   const char * newMBKernel, const char * newMBKernelArgs,
3719     const char * newDevTreePath) {
3720      struct singleEntry * new;      struct singleEntry * new;
3721      struct singleLine * newLine = NULL, * tmplLine = NULL, * masterLine = NULL;      struct singleLine * newLine = NULL, * tmplLine = NULL, * masterLine = NULL;
3722      int needs;      int needs;
# Line 3066  int addNewKernel(struct grubConfig * con Line 3757  int addNewKernel(struct grubConfig * con
3757          needs |= NEED_MB;          needs |= NEED_MB;
3758          new->multiboot = 1;          new->multiboot = 1;
3759      }      }
3760        if (newDevTreePath && getKeywordByType(LT_DEVTREE, config->cfi))
3761     needs |= NEED_DEVTREE;
3762    
3763      if (template) {      if (template) {
3764   for (masterLine = template->lines;   for (masterLine = template->lines;
# Line 3079  int addNewKernel(struct grubConfig * con Line 3772  int addNewKernel(struct grubConfig * con
3772      while (*chptr && isspace(*chptr)) chptr++;      while (*chptr && isspace(*chptr)) chptr++;
3773      if (*chptr == '#') continue;      if (*chptr == '#') continue;
3774    
3775      if (tmplLine->type == LT_KERNEL &&      if (iskernel(tmplLine->type) && tmplLine->numElements >= 2) {
     tmplLine->numElements >= 2) {  
3776   if (!template->multiboot && (needs & NEED_MB)) {   if (!template->multiboot && (needs & NEED_MB)) {
3777      /* it's not a multiboot template and this is the kernel      /* it's not a multiboot template and this is the kernel
3778       * line.  Try to be intelligent about inserting the       * line.  Try to be intelligent about inserting the
# Line 3157  int addNewKernel(struct grubConfig * con Line 3849  int addNewKernel(struct grubConfig * con
3849      /* template is multi but new is not,      /* template is multi but new is not,
3850       * insert the kernel in the first module slot       * insert the kernel in the first module slot
3851       */       */
3852      tmplLine->type = LT_KERNEL;      tmplLine->type = preferredLineType(LT_KERNEL, config->cfi);
3853      free(tmplLine->elements[0].item);      free(tmplLine->elements[0].item);
3854      tmplLine->elements[0].item =      tmplLine->elements[0].item =
3855   strdup(getKeywordByType(LT_KERNEL, config->cfi)->key);   strdup(getKeywordByType(tmplLine->type,
3856     config->cfi)->key);
3857      newLine = addLineTmpl(new, tmplLine, newLine,      newLine = addLineTmpl(new, tmplLine, newLine,
3858    newKernelPath + strlen(prefix), config->cfi);    newKernelPath + strlen(prefix),
3859      config->cfi);
3860      needs &= ~NEED_KERNEL;      needs &= ~NEED_KERNEL;
3861   } else if (needs & NEED_INITRD) {   } else if (needs & NEED_INITRD) {
3862      char *initrdVal;      char *initrdVal;
3863      /* template is multi but new is not,      /* template is multi but new is not,
3864       * insert the initrd in the second module slot       * insert the initrd in the second module slot
3865       */       */
3866      tmplLine->type = LT_INITRD;      tmplLine->type = preferredLineType(LT_INITRD, config->cfi);
3867      free(tmplLine->elements[0].item);      free(tmplLine->elements[0].item);
3868      tmplLine->elements[0].item =      tmplLine->elements[0].item =
3869   strdup(getKeywordByType(LT_INITRD, config->cfi)->key);   strdup(getKeywordByType(tmplLine->type,
3870     config->cfi)->key);
3871      initrdVal = getInitrdVal(config, prefix, tmplLine, newKernelInitrd, extraInitrds, extraInitrdCount);      initrdVal = getInitrdVal(config, prefix, tmplLine, newKernelInitrd, extraInitrds, extraInitrdCount);
3872      newLine = addLineTmpl(new, tmplLine, newLine, initrdVal, config->cfi);      newLine = addLineTmpl(new, tmplLine, newLine, initrdVal, config->cfi);
3873      free(initrdVal);      free(initrdVal);
3874      needs &= ~NEED_INITRD;      needs &= ~NEED_INITRD;
3875   }   }
3876    
3877      } else if (tmplLine->type == LT_INITRD &&      } else if (isinitrd(tmplLine->type) && tmplLine->numElements >= 2) {
        tmplLine->numElements >= 2) {  
3878   if (needs & NEED_INITRD &&   if (needs & NEED_INITRD &&
3879      new->multiboot && !template->multiboot &&      new->multiboot && !template->multiboot &&
3880      config->cfi->mbInitRdIsModule) {      config->cfi->mbInitRdIsModule) {
# Line 3234  int addNewKernel(struct grubConfig * con Line 3928  int addNewKernel(struct grubConfig * con
3928      static const char *prefix = "'Loading ";      static const char *prefix = "'Loading ";
3929      if (tmplLine->numElements > 1 &&      if (tmplLine->numElements > 1 &&
3930      strstr(tmplLine->elements[1].item, prefix) &&      strstr(tmplLine->elements[1].item, prefix) &&
3931      masterLine->next && masterLine->next->type == LT_KERNEL) {      masterLine->next &&
3932        iskernel(masterLine->next->type)) {
3933   char *newTitle = malloc(strlen(prefix) +   char *newTitle = malloc(strlen(prefix) +
3934   strlen(newKernelTitle) + 2);   strlen(newKernelTitle) + 2);
3935    
# Line 3249  int addNewKernel(struct grubConfig * con Line 3944  int addNewKernel(struct grubConfig * con
3944   newLine = addLineTmpl(new, tmplLine, newLine, NULL,   newLine = addLineTmpl(new, tmplLine, newLine, NULL,
3945   config->cfi);   config->cfi);
3946      }      }
3947        } else if (tmplLine->type == LT_DEVTREE &&
3948           tmplLine->numElements == 2 && newDevTreePath) {
3949            newLine = addLineTmpl(new, tmplLine, newLine,
3950          newDevTreePath + strlen(prefix),
3951          config->cfi);
3952     needs &= ~NEED_DEVTREE;
3953        } else if (tmplLine->type == LT_ENTRY_END && needs & NEED_DEVTREE) {
3954     const char *ndtp = newDevTreePath;
3955     if (!strncmp(newDevTreePath, prefix, strlen(prefix)))
3956        ndtp += strlen(prefix);
3957     newLine = addLine(new, config->cfi, LT_DEVTREE,
3958      config->secondaryIndent,
3959      ndtp);
3960     needs &= ~NEED_DEVTREE;
3961     newLine = addLineTmpl(new, tmplLine, newLine, NULL, config->cfi);
3962      } else {      } else {
3963   /* pass through other lines from the template */   /* pass through other lines from the template */
3964   newLine = addLineTmpl(new, tmplLine, newLine, NULL, config->cfi);   newLine = addLineTmpl(new, tmplLine, newLine, NULL, config->cfi);
# Line 3261  int addNewKernel(struct grubConfig * con Line 3971  int addNewKernel(struct grubConfig * con
3971   */   */
3972   switch (config->cfi->entryStart) {   switch (config->cfi->entryStart) {
3973      case LT_KERNEL:      case LT_KERNEL:
3974        case LT_KERNEL_EFI:
3975        case LT_KERNEL_16:
3976   if (new->multiboot && config->cfi->mbHyperFirst) {   if (new->multiboot && config->cfi->mbHyperFirst) {
3977      /* fall through to LT_HYPER */      /* fall through to LT_HYPER */
3978   } else {   } else {
3979      newLine = addLine(new, config->cfi, LT_KERNEL,      newLine = addLine(new, config->cfi,
3980              preferredLineType(LT_KERNEL, config->cfi),
3981        config->primaryIndent,        config->primaryIndent,
3982        newKernelPath + strlen(prefix));        newKernelPath + strlen(prefix));
3983      needs &= ~NEED_KERNEL;      needs &= ~NEED_KERNEL;
# Line 3340  int addNewKernel(struct grubConfig * con Line 4053  int addNewKernel(struct grubConfig * con
4053      if (needs & NEED_KERNEL) {      if (needs & NEED_KERNEL) {
4054   newLine = addLine(new, config->cfi,   newLine = addLine(new, config->cfi,
4055    (new->multiboot && getKeywordByType(LT_MBMODULE,    (new->multiboot && getKeywordByType(LT_MBMODULE,
4056        config->cfi)) ?        config->cfi))
4057    LT_MBMODULE : LT_KERNEL,     ? LT_MBMODULE
4058     : preferredLineType(LT_KERNEL, config->cfi),
4059    config->secondaryIndent,    config->secondaryIndent,
4060    newKernelPath + strlen(prefix));    newKernelPath + strlen(prefix));
4061   needs &= ~NEED_KERNEL;   needs &= ~NEED_KERNEL;
# Line 3357  int addNewKernel(struct grubConfig * con Line 4071  int addNewKernel(struct grubConfig * con
4071   initrdVal = getInitrdVal(config, prefix, NULL, newKernelInitrd, extraInitrds, extraInitrdCount);   initrdVal = getInitrdVal(config, prefix, NULL, newKernelInitrd, extraInitrds, extraInitrdCount);
4072   newLine = addLine(new, config->cfi,   newLine = addLine(new, config->cfi,
4073    (new->multiboot && getKeywordByType(LT_MBMODULE,    (new->multiboot && getKeywordByType(LT_MBMODULE,
4074        config->cfi)) ?        config->cfi))
4075    LT_MBMODULE : LT_INITRD,     ? LT_MBMODULE
4076       : preferredLineType(LT_INITRD, config->cfi),
4077    config->secondaryIndent,    config->secondaryIndent,
4078    initrdVal);    initrdVal);
4079   free(initrdVal);   free(initrdVal);
4080   needs &= ~NEED_INITRD;   needs &= ~NEED_INITRD;
4081      }      }
4082        if (needs & NEED_DEVTREE) {
4083     newLine = addLine(new, config->cfi, LT_DEVTREE,
4084      config->secondaryIndent,
4085      newDevTreePath);
4086     needs &= ~NEED_DEVTREE;
4087        }
4088    
4089        /* NEEDS_END must be last on bootloaders that need it... */
4090      if (needs & NEED_END) {      if (needs & NEED_END) {
4091   newLine = addLine(new, config->cfi, LT_ENTRY_END,   newLine = addLine(new, config->cfi, LT_ENTRY_END,
4092   config->secondaryIndent, NULL);   config->secondaryIndent, NULL);
4093   needs &= ~NEED_END;   needs &= ~NEED_END;
4094      }      }
   
4095      if (needs) {      if (needs) {
4096   printf(_("grubby: needs=%d, aborting\n"), needs);   printf(_("grubby: needs=%d, aborting\n"), needs);
4097   abort();   abort();
# Line 3390  static void traceback(int signum) Line 4112  static void traceback(int signum)
4112      memset(array, '\0', sizeof (array));      memset(array, '\0', sizeof (array));
4113      size = backtrace(array, 40);      size = backtrace(array, 40);
4114    
4115      fprintf(stderr, "grubby recieved SIGSEGV!  Backtrace (%ld):\n",      fprintf(stderr, "grubby received SIGSEGV!  Backtrace (%ld):\n",
4116              (unsigned long)size);              (unsigned long)size);
4117      backtrace_symbols_fd(array, size, STDERR_FILENO);      backtrace_symbols_fd(array, size, STDERR_FILENO);
4118      exit(1);      exit(1);
# Line 3415  int main(int argc, const char ** argv) { Line 4137  int main(int argc, const char ** argv) {
4137      char * newKernelArgs = NULL;      char * newKernelArgs = NULL;
4138      char * newKernelInitrd = NULL;      char * newKernelInitrd = NULL;
4139      char * newKernelTitle = NULL;      char * newKernelTitle = NULL;
4140      char * newKernelVersion = NULL;      char * newDevTreePath = NULL;
4141      char * newMBKernel = NULL;      char * newMBKernel = NULL;
4142      char * newMBKernelArgs = NULL;      char * newMBKernelArgs = NULL;
4143      char * removeMBKernelArgs = NULL;      char * removeMBKernelArgs = NULL;
# Line 3425  int main(int argc, const char ** argv) { Line 4147  int main(int argc, const char ** argv) {
4147      char * removeArgs = NULL;      char * removeArgs = NULL;
4148      char * kernelInfo = NULL;      char * kernelInfo = NULL;
4149      char * extraInitrds[MAX_EXTRA_INITRDS] = { NULL };      char * extraInitrds[MAX_EXTRA_INITRDS] = { NULL };
4150        char * envPath = NULL;
4151      const char * chptr = NULL;      const char * chptr = NULL;
4152      struct configFileInfo * cfi = NULL;      struct configFileInfo * cfi = NULL;
4153      struct grubConfig * config;      struct grubConfig * config;
# Line 3433  int main(int argc, const char ** argv) { Line 4156  int main(int argc, const char ** argv) {
4156      int displayDefault = 0;      int displayDefault = 0;
4157      int displayDefaultIndex = 0;      int displayDefaultIndex = 0;
4158      int displayDefaultTitle = 0;      int displayDefaultTitle = 0;
4159        int defaultIndex = -1;
4160      struct poptOption options[] = {      struct poptOption options[] = {
4161   { "add-kernel", 0, POPT_ARG_STRING, &newKernelPath, 0,   { "add-kernel", 0, POPT_ARG_STRING, &newKernelPath, 0,
4162      _("add an entry for the specified kernel"), _("kernel-path") },      _("add an entry for the specified kernel"), _("kernel-path") },
# Line 3450  int main(int argc, const char ** argv) { Line 4174  int main(int argc, const char ** argv) {
4174   { "boot-filesystem", 0, POPT_ARG_STRING, &bootPrefix, 0,   { "boot-filesystem", 0, POPT_ARG_STRING, &bootPrefix, 0,
4175      _("filestystem which contains /boot directory (for testing only)"),      _("filestystem which contains /boot directory (for testing only)"),
4176      _("bootfs") },      _("bootfs") },
4177  #if defined(__i386__) || defined(__x86_64__)  #if defined(__i386__) || defined(__x86_64__) || defined (__powerpc64__) || defined (__ia64__)
4178   { "bootloader-probe", 0, POPT_ARG_NONE, &bootloaderProbe, 0,   { "bootloader-probe", 0, POPT_ARG_NONE, &bootloaderProbe, 0,
4179      _("check if lilo is installed on lilo.conf boot sector") },      _("check which bootloader is installed on boot sector") },
4180  #endif  #endif
4181   { "config-file", 'c', POPT_ARG_STRING, &grubConfig, 0,   { "config-file", 'c', POPT_ARG_STRING, &grubConfig, 0,
4182      _("path to grub config file to update (\"-\" for stdin)"),      _("path to grub config file to update (\"-\" for stdin)"),
# Line 3471  int main(int argc, const char ** argv) { Line 4195  int main(int argc, const char ** argv) {
4195      _("display the index of the default kernel") },      _("display the index of the default kernel") },
4196   { "default-title", 0, 0, &displayDefaultTitle, 0,   { "default-title", 0, 0, &displayDefaultTitle, 0,
4197      _("display the title of the default kernel") },      _("display the title of the default kernel") },
4198     { "devtree", 0, POPT_ARG_STRING, &newDevTreePath, 0,
4199        _("device tree file for new stanza"), _("dtb-path") },
4200   { "elilo", 0, POPT_ARG_NONE, &configureELilo, 0,   { "elilo", 0, POPT_ARG_NONE, &configureELilo, 0,
4201      _("configure elilo bootloader") },      _("configure elilo bootloader") },
4202     { "efi", 0, POPT_ARG_NONE, &isEfi, 0,
4203        _("force grub2 stanzas to use efi") },
4204     { "env", 0, POPT_ARG_STRING, &envPath, 0,
4205        _("path for environment data"),
4206        _("path") },
4207   { "extlinux", 0, POPT_ARG_NONE, &configureExtLinux, 0,   { "extlinux", 0, POPT_ARG_NONE, &configureExtLinux, 0,
4208      _("configure extlinux bootloader (from syslinux)") },      _("configure extlinux bootloader (from syslinux)") },
4209   { "grub", 0, POPT_ARG_NONE, &configureGrub, 0,   { "grub", 0, POPT_ARG_NONE, &configureGrub, 0,
# Line 3485  int main(int argc, const char ** argv) { Line 4216  int main(int argc, const char ** argv) {
4216   { "initrd", 0, POPT_ARG_STRING, &newKernelInitrd, 0,   { "initrd", 0, POPT_ARG_STRING, &newKernelInitrd, 0,
4217      _("initrd image for the new kernel"), _("initrd-path") },      _("initrd image for the new kernel"), _("initrd-path") },
4218   { "extra-initrd", 'i', POPT_ARG_STRING, NULL, 'i',   { "extra-initrd", 'i', POPT_ARG_STRING, NULL, 'i',
4219      _("auxilliary initrd image for things other than the new kernel"), _("initrd-path") },      _("auxiliary initrd image for things other than the new kernel"), _("initrd-path") },
4220   { "lilo", 0, POPT_ARG_NONE, &configureLilo, 0,   { "lilo", 0, POPT_ARG_NONE, &configureLilo, 0,
4221      _("configure lilo bootloader") },      _("configure lilo bootloader") },
4222   { "make-default", 0, 0, &makeDefault, 0,   { "make-default", 0, 0, &makeDefault, 0,
# Line 3505  int main(int argc, const char ** argv) { Line 4236  int main(int argc, const char ** argv) {
4236   { "set-default", 0, POPT_ARG_STRING, &defaultKernel, 0,   { "set-default", 0, POPT_ARG_STRING, &defaultKernel, 0,
4237      _("make the first entry referencing the specified kernel "      _("make the first entry referencing the specified kernel "
4238        "the default"), _("kernel-path") },        "the default"), _("kernel-path") },
4239     { "set-default-index", 0, POPT_ARG_INT, &defaultIndex, 0,
4240        _("make the given entry index the default entry"),
4241        _("entry-index") },
4242   { "silo", 0, POPT_ARG_NONE, &configureSilo, 0,   { "silo", 0, POPT_ARG_NONE, &configureSilo, 0,
4243      _("configure silo bootloader") },      _("configure silo bootloader") },
4244   { "title", 0, POPT_ARG_STRING, &newKernelTitle, 0,   { "title", 0, POPT_ARG_STRING, &newKernelTitle, 0,
# Line 3526  int main(int argc, const char ** argv) { Line 4260  int main(int argc, const char ** argv) {
4260    
4261      signal(SIGSEGV, traceback);      signal(SIGSEGV, traceback);
4262    
4263        int i = 0;
4264        for (int j = 1; j < argc; j++)
4265     i += strlen(argv[j]) + 1;
4266        saved_command_line = malloc(i);
4267        if (!saved_command_line) {
4268     fprintf(stderr, "grubby: %m\n");
4269     exit(1);
4270        }
4271        saved_command_line[0] = '\0';
4272        for (int j = 1; j < argc; j++) {
4273     strcat(saved_command_line, argv[j]);
4274     strncat(saved_command_line, j == argc -1 ? "" : " ", 1);
4275        }
4276    
4277      optCon = poptGetContext("grubby", argc, argv, options, 0);      optCon = poptGetContext("grubby", argc, argv, options, 0);
4278      poptReadDefaultConfig(optCon, 1);      poptReadDefaultConfig(optCon, 1);
4279    
# Line 3569  int main(int argc, const char ** argv) { Line 4317  int main(int argc, const char ** argv) {
4317   return 1;   return 1;
4318      } else if (configureGrub2) {      } else if (configureGrub2) {
4319   cfi = &grub2ConfigType;   cfi = &grub2ConfigType;
4320     if (envPath)
4321        cfi->envFile = envPath;
4322      } else if (configureLilo) {      } else if (configureLilo) {
4323   cfi = &liloConfigType;   cfi = &liloConfigType;
4324      } else if (configureGrub) {      } else if (configureGrub) {
# Line 3587  int main(int argc, const char ** argv) { Line 4337  int main(int argc, const char ** argv) {
4337      }      }
4338    
4339      if (!cfi) {      if (!cfi) {
4340            if (grub2FindConfig(&grub2ConfigType))
4341        cfi = &grub2ConfigType;
4342     else
4343        #ifdef __ia64__        #ifdef __ia64__
4344   cfi = &eliloConfigType;      cfi = &eliloConfigType;
4345        #elif __powerpc__        #elif __powerpc__
4346   cfi = &yabootConfigType;      cfi = &yabootConfigType;
4347        #elif __sparc__        #elif __sparc__
4348          cfi = &siloConfigType;              cfi = &siloConfigType;
4349        #elif __s390__        #elif __s390__
4350          cfi = &ziplConfigType;              cfi = &ziplConfigType;
4351        #elif __s390x__        #elif __s390x__
4352          cfi = &ziplConfigtype;              cfi = &ziplConfigtype;
4353        #else        #else
         if (grub2FindConfig(&grub2ConfigType))  
     cfi = &grub2ConfigType;  
  else  
4354      cfi = &grubConfigType;      cfi = &grubConfigType;
4355        #endif        #endif
4356      }      }
# Line 3612  int main(int argc, const char ** argv) { Line 4362  int main(int argc, const char ** argv) {
4362      grubConfig = cfi->defaultConfig;      grubConfig = cfi->defaultConfig;
4363      }      }
4364    
4365      if (bootloaderProbe && (displayDefault || kernelInfo || newKernelVersion ||      if (bootloaderProbe && (displayDefault || kernelInfo ||
4366    newKernelPath || removeKernelPath || makeDefault ||      newKernelPath || removeKernelPath || makeDefault ||
4367    defaultKernel || displayDefaultIndex || displayDefaultTitle)) {      defaultKernel || displayDefaultIndex || displayDefaultTitle ||
4368        (defaultIndex >= 0))) {
4369   fprintf(stderr, _("grubby: --bootloader-probe may not be used with "   fprintf(stderr, _("grubby: --bootloader-probe may not be used with "
4370    "specified option"));    "specified option"));
4371   return 1;   return 1;
4372      }      }
4373    
4374      if ((displayDefault || kernelInfo) && (newKernelVersion || newKernelPath ||      if ((displayDefault || kernelInfo) && (newKernelPath ||
4375     removeKernelPath)) {     removeKernelPath)) {
4376   fprintf(stderr, _("grubby: --default-kernel and --info may not "   fprintf(stderr, _("grubby: --default-kernel and --info may not "
4377    "be used when adding or removing kernels\n"));    "be used when adding or removing kernels\n"));
# Line 3656  int main(int argc, const char ** argv) { Line 4407  int main(int argc, const char ** argv) {
4407   makeDefault = 1;   makeDefault = 1;
4408   defaultKernel = NULL;   defaultKernel = NULL;
4409      }      }
4410        else if (defaultKernel && (defaultIndex >= 0)) {
4411     fprintf(stderr, _("grubby: --set-default and --set-default-index "
4412      "may not be used together\n"));
4413     return 1;
4414        }
4415    
4416      if (grubConfig && !strcmp(grubConfig, "-") && !outputFile) {      if (grubConfig && !strcmp(grubConfig, "-") && !outputFile) {
4417   fprintf(stderr, _("grubby: output file must be specified if stdin "   fprintf(stderr, _("grubby: output file must be specified if stdin "
# Line 3664  int main(int argc, const char ** argv) { Line 4420  int main(int argc, const char ** argv) {
4420      }      }
4421    
4422      if (!removeKernelPath && !newKernelPath && !displayDefault && !defaultKernel      if (!removeKernelPath && !newKernelPath && !displayDefault && !defaultKernel
4423   && !kernelInfo && !bootloaderProbe && !updateKernelPath   && !kernelInfo && !bootloaderProbe && !updateKernelPath
4424          && !removeMBKernel && !displayDefaultIndex && !displayDefaultTitle) {   && !removeMBKernel && !displayDefaultIndex && !displayDefaultTitle
4425     && (defaultIndex == -1)) {
4426   fprintf(stderr, _("grubby: no action specified\n"));   fprintf(stderr, _("grubby: no action specified\n"));
4427   return 1;   return 1;
4428      }      }
# Line 3692  int main(int argc, const char ** argv) { Line 4449  int main(int argc, const char ** argv) {
4449      }      }
4450    
4451      if (bootloaderProbe) {      if (bootloaderProbe) {
4452   int lrc = 0, grc = 0, gr2c = 0, erc = 0;   int lrc = 0, grc = 0, gr2c = 0, extrc = 0, yrc = 0, erc = 0;
4453   struct grubConfig * lconfig, * gconfig;   struct grubConfig * lconfig, * gconfig, * yconfig, * econfig;
4454    
4455   const char *grub2config = grub2FindConfig(&grub2ConfigType);   const char *grub2config = grub2FindConfig(&grub2ConfigType);
4456   if (grub2config) {   if (grub2config) {
# Line 3721  int main(int argc, const char ** argv) { Line 4478  int main(int argc, const char ** argv) {
4478   lrc = checkForLilo(lconfig);   lrc = checkForLilo(lconfig);
4479   }   }
4480    
4481     if (!access(eliloConfigType.defaultConfig, F_OK)) {
4482        econfig = readConfig(eliloConfigType.defaultConfig,
4483     &eliloConfigType);
4484        if (!econfig)
4485     erc = 1;
4486        else
4487     erc = checkForElilo(econfig);
4488     }
4489    
4490   if (!access(extlinuxConfigType.defaultConfig, F_OK)) {   if (!access(extlinuxConfigType.defaultConfig, F_OK)) {
4491      lconfig = readConfig(extlinuxConfigType.defaultConfig, &extlinuxConfigType);      lconfig = readConfig(extlinuxConfigType.defaultConfig, &extlinuxConfigType);
4492      if (!lconfig)      if (!lconfig)
4493   erc = 1;   extrc = 1;
4494      else      else
4495   erc = checkForExtLinux(lconfig);   extrc = checkForExtLinux(lconfig);
4496   }   }
4497    
4498   if (lrc == 1 || grc == 1 || gr2c == 1) return 1;  
4499     if (!access(yabootConfigType.defaultConfig, F_OK)) {
4500        yconfig = readConfig(yabootConfigType.defaultConfig,
4501     &yabootConfigType);
4502        if (!yconfig)
4503     yrc = 1;
4504        else
4505     yrc = checkForYaboot(yconfig);
4506     }
4507    
4508     if (lrc == 1 || grc == 1 || gr2c == 1 || extrc == 1 || yrc == 1 ||
4509     erc == 1)
4510        return 1;
4511    
4512   if (lrc == 2) printf("lilo\n");   if (lrc == 2) printf("lilo\n");
4513   if (gr2c == 2) printf("grub2\n");   if (gr2c == 2) printf("grub2\n");
4514   if (grc == 2) printf("grub\n");   if (grc == 2) printf("grub\n");
4515   if (erc == 2) printf("extlinux\n");   if (extrc == 2) printf("extlinux\n");
4516     if (yrc == 2) printf("yaboot\n");
4517     if (erc == 2) printf("elilo\n");
4518    
4519   return 0;   return 0;
4520      }      }
4521    
4522        if (grubConfig == NULL) {
4523     printf("Could not find bootloader configuration file.\n");
4524     exit(1);
4525        }
4526    
4527      config = readConfig(grubConfig, cfi);      config = readConfig(grubConfig, cfi);
4528      if (!config) return 1;      if (!config) return 1;
4529    
# Line 3748  int main(int argc, const char ** argv) { Line 4533  int main(int argc, const char ** argv) {
4533          char * rootspec;          char * rootspec;
4534    
4535   if (config->defaultImage == -1) return 0;   if (config->defaultImage == -1) return 0;
4536     if (config->defaultImage == DEFAULT_SAVED_GRUB2 &&
4537     cfi->defaultIsSaved)
4538        config->defaultImage = 0;
4539   entry = findEntryByIndex(config, config->defaultImage);   entry = findEntryByIndex(config, config->defaultImage);
4540   if (!entry) return 0;   if (!entry) return 0;
4541   if (!suitableImage(entry, bootPrefix, 0, flags)) return 0;   if (!suitableImage(entry, bootPrefix, 0, flags)) return 0;
4542    
4543   line = getLineByType(LT_KERNEL|LT_HYPER, entry->lines);   line = getLineByType(LT_KERNEL|LT_HYPER|LT_KERNEL_EFI|LT_KERNEL_16, entry->lines);
4544   if (!line) return 0;   if (!line) return 0;
4545    
4546          rootspec = getRootSpecifier(line->elements[1].item);          rootspec = getRootSpecifier(line->elements[1].item);
# Line 3766  int main(int argc, const char ** argv) { Line 4554  int main(int argc, const char ** argv) {
4554   struct singleEntry * entry;   struct singleEntry * entry;
4555    
4556   if (config->defaultImage == -1) return 0;   if (config->defaultImage == -1) return 0;
4557     if (config->defaultImage == DEFAULT_SAVED_GRUB2 &&
4558     cfi->defaultIsSaved)
4559        config->defaultImage = 0;
4560   entry = findEntryByIndex(config, config->defaultImage);   entry = findEntryByIndex(config, config->defaultImage);
4561   if (!entry) return 0;   if (!entry) return 0;
4562    
# Line 3788  int main(int argc, const char ** argv) { Line 4579  int main(int argc, const char ** argv) {
4579    
4580      } else if (displayDefaultIndex) {      } else if (displayDefaultIndex) {
4581          if (config->defaultImage == -1) return 0;          if (config->defaultImage == -1) return 0;
4582     if (config->defaultImage == DEFAULT_SAVED_GRUB2 &&
4583     cfi->defaultIsSaved)
4584        config->defaultImage = 0;
4585          printf("%i\n", config->defaultImage);          printf("%i\n", config->defaultImage);
4586            return 0;
4587    
4588      } else if (kernelInfo)      } else if (kernelInfo)
4589   return displayInfo(config, kernelInfo, bootPrefix);   return displayInfo(config, kernelInfo, bootPrefix);
# Line 3801  int main(int argc, const char ** argv) { Line 4596  int main(int argc, const char ** argv) {
4596      markRemovedImage(config, removeKernelPath, bootPrefix);      markRemovedImage(config, removeKernelPath, bootPrefix);
4597      markRemovedImage(config, removeMBKernel, bootPrefix);      markRemovedImage(config, removeMBKernel, bootPrefix);
4598      setDefaultImage(config, newKernelPath != NULL, defaultKernel, makeDefault,      setDefaultImage(config, newKernelPath != NULL, defaultKernel, makeDefault,
4599      bootPrefix, flags);      bootPrefix, flags, defaultIndex);
4600      setFallbackImage(config, newKernelPath != NULL);      setFallbackImage(config, newKernelPath != NULL);
4601      if (updateImage(config, updateKernelPath, bootPrefix, newKernelArgs,      if (updateImage(config, updateKernelPath, bootPrefix, newKernelArgs,
4602                      removeArgs, newMBKernelArgs, removeMBKernelArgs)) return 1;                      removeArgs, newMBKernelArgs, removeMBKernelArgs)) return 1;
4603      if (updateKernelPath && newKernelInitrd) {      if (updateKernelPath && newKernelInitrd) {
4604              if (updateInitrd(config, updateKernelPath, bootPrefix,      if (newMBKernel) {
4605                               newKernelInitrd)) return 1;      if (addMBInitrd(config, newMBKernel, updateKernelPath,
4606     bootPrefix, newKernelInitrd))
4607        return 1;
4608        } else {
4609        if (updateInitrd(config, updateKernelPath, bootPrefix,
4610     newKernelInitrd))
4611     return 1;
4612        }
4613      }      }
4614      if (addNewKernel(config, template, bootPrefix, newKernelPath,      if (addNewKernel(config, template, bootPrefix, newKernelPath,
4615                       newKernelTitle, newKernelArgs, newKernelInitrd,                       newKernelTitle, newKernelArgs, newKernelInitrd,
4616                       extraInitrds, extraInitrdCount,                       (const char **)extraInitrds, extraInitrdCount,
4617                       newMBKernel, newMBKernelArgs)) return 1;                       newMBKernel, newMBKernelArgs, newDevTreePath)) return 1;
4618            
4619    
4620      if (numEntries(config) == 0) {      if (numEntries(config) == 0) {

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