Magellan Linux

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

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

revision 1934 by niro, Mon Oct 1 12:08:46 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 167  const char *grubFindConfig(struct config Line 186  const char *grubFindConfig(struct config
186   "/boot/grub/grub.conf",   "/boot/grub/grub.conf",
187   "/boot/grub/menu.lst",   "/boot/grub/menu.lst",
188   "/etc/grub.conf",   "/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,      ' ' },      { "linuxefi",   LT_KERNEL_EFI,  ' ' },
230        { "linux16",    LT_KERNEL_16,   ' ' },
231      { "initrd",     LT_INITRD,      ' ', ' ' },      { "initrd",     LT_INITRD,      ' ', ' ' },
232      { "initrdefi",  LT_INITRD,      ' ', ' ' },      { "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 221  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 244  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) {
379    int count = 0;    int count = 0;
380    
# Line 273  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 330  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 484  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 508  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 572  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      for (struct keywordTypes *kw = cfi->keywords; kw->key; kw++) {      for (struct keywordTypes *kw = cfi->keywords; kw->key; kw++) {
# Line 605  static char * getuuidbydev(char *device) Line 782  static char * getuuidbydev(char *device)
782  static enum lineType_e getTypeByKeyword(char * keyword,  static enum lineType_e getTypeByKeyword(char * keyword,
783   struct configFileInfo * cfi) {   struct configFileInfo * cfi) {
784      for (struct keywordTypes *kw = cfi->keywords; kw->key; kw++) {      for (struct keywordTypes *kw = cfi->keywords; kw->key; kw++) {
785   if (!strcmp(keyword, kw->key))   if (cfi->caseInsensitive) {
786      return kw->type;      if (!strcasecmp(keyword, kw->key))
787                    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 645  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 906  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 920  static struct grubConfig * readConfig(co Line 1116  static struct grubConfig * readConfig(co
1116      int 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 987  static struct grubConfig * readConfig(co Line 1186  static struct grubConfig * readConfig(co
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 996  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 1013  static struct grubConfig * readConfig(co Line 1213  static struct grubConfig * readConfig(co
1213      for (struct singleLine *l = entry->lines; l; l = l->next) {      for (struct singleLine *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 1192  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 1233  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 1250  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 1355  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 1500  static char *findDiskForRoot() Line 1741  static char *findDiskForRoot()
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      if (!debug)      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;   return;
1792        }
1793    
1794      va_start(argp, fmt);      if (okay) {
1795     va_end(argp);
1796     return;
1797        }
1798    
1799        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 1563  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 1589  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 1610  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 1619  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 1628  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 1697  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 1746  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 1768  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 1778  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 1800  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 1957  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;
# Line 2022  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   if (!strncmp(prefix, line->elements[1].item, strlen(prefix)))   if (!strncmp(prefix, line->elements[1].item, strlen(prefix)))
# Line 2423  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 2432  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 2469  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 2803  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 2959  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 2968  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 2982  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 3341  int addNewKernel(struct grubConfig * con Line 3715  int addNewKernel(struct grubConfig * con
3715   const char * newKernelPath, const char * newKernelTitle,   const char * newKernelPath, const char * newKernelTitle,
3716   const char * newKernelArgs, const char * newKernelInitrd,   const char * newKernelArgs, const char * newKernelInitrd,
3717   const char ** extraInitrds, int extraInitrdCount,   const char ** extraInitrds, int extraInitrdCount,
3718                   const char * newMBKernel, const 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 3382  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 3395  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 3473  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 3550  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 3565  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 3577  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 3656  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 3673  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 3706  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 3731  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 3741  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 3788  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 3802  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 3846  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 3889  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 3932  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))) {      (defaultIndex >= 0))) {
# Line 3941  int main(int argc, const char ** argv) { Line 4371  int main(int argc, const char ** argv) {
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 4089  int main(int argc, const char ** argv) { Line 4519  int main(int argc, const char ** argv) {
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 4098  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 4116  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 4138  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 4156  int main(int argc, const char ** argv) { Line 4601  int main(int argc, const char ** argv) {
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                       (const char **)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.1934  
changed lines
  Added in v.2687