Magellan Linux

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

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

revision 1720 by niro, Sat Feb 18 00:51:28 2012 UTC revision 2236 by niro, Mon Oct 21 13:19:07 2013 UTC
# Line 36  Line 36 
36  #include <signal.h>  #include <signal.h>
37  #include <blkid/blkid.h>  #include <blkid/blkid.h>
38    
39    #include "log.h"
40    
41  #ifndef DEBUG  #ifndef DEBUG
42  #define DEBUG 0  #define DEBUG 0
43  #endif  #endif
# Line 46  Line 48 
48  #define dbgPrintf(format, args...)  #define dbgPrintf(format, args...)
49  #endif  #endif
50    
51    int debug = 0; /* Currently just for template debugging */
52    
53  #define _(A) (A)  #define _(A) (A)
54    
55  #define MAX_EXTRA_INITRDS  16 /* code segment checked by --bootloader-probe */  #define MAX_EXTRA_INITRDS  16 /* code segment checked by --bootloader-probe */
# Line 54  Line 58 
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 80  enum lineType_e { Line 88  enum lineType_e {
88      LT_MENUENTRY    = 1 << 17,      LT_MENUENTRY    = 1 << 17,
89      LT_ENTRY_END    = 1 << 18,      LT_ENTRY_END    = 1 << 18,
90      LT_SET_VARIABLE = 1 << 19,      LT_SET_VARIABLE = 1 << 19,
91      LT_UNKNOWN      = 1 << 20,      LT_KERNEL_EFI   = 1 << 20,
92        LT_INITRD_EFI   = 1 << 21,
93        LT_UNKNOWN      = 1 << 22,
94  };  };
95    
96  struct singleLine {  struct singleLine {
# Line 112  struct singleEntry { Line 122  struct singleEntry {
122    
123  #define MAIN_DEFAULT    (1 << 0)  #define MAIN_DEFAULT    (1 << 0)
124  #define DEFAULT_SAVED       -2  #define DEFAULT_SAVED       -2
125    #define DEFAULT_SAVED_GRUB2 -3
126    
127  struct keywordTypes {  struct keywordTypes {
128      char * key;      char * key;
# Line 131  struct configFileInfo { Line 142  struct configFileInfo {
142      findConfigFunc findConfig;      findConfigFunc findConfig;
143      writeLineFunc writeLine;      writeLineFunc writeLine;
144      struct keywordTypes * keywords;      struct keywordTypes * keywords;
145        int caseInsensitive;
146      int defaultIsIndex;      int defaultIsIndex;
147      int defaultIsVariable;      int defaultIsVariable;
148      int defaultSupportSaved;      int defaultSupportSaved;
# Line 161  struct keywordTypes grubKeywords[] = { Line 173  struct keywordTypes grubKeywords[] = {
173    
174  const char *grubFindConfig(struct configFileInfo *cfi) {  const char *grubFindConfig(struct configFileInfo *cfi) {
175      static const char *configFiles[] = {      static const char *configFiles[] = {
  "/etc/grub.conf",  
176   "/boot/grub/grub.conf",   "/boot/grub/grub.conf",
177   "/boot/grub/menu.lst",   "/boot/grub/menu.lst",
178     "/etc/grub.conf",
179   NULL   NULL
180      };      };
181      static int i = -1;      static int i = -1;
# Line 202  struct keywordTypes grub2Keywords[] = { Line 214  struct keywordTypes grub2Keywords[] = {
214      { "default",    LT_DEFAULT,     ' ' },      { "default",    LT_DEFAULT,     ' ' },
215      { "fallback",   LT_FALLBACK,    ' ' },      { "fallback",   LT_FALLBACK,    ' ' },
216      { "linux",      LT_KERNEL,      ' ' },      { "linux",      LT_KERNEL,      ' ' },
217        { "linuxefi",   LT_KERNEL_EFI,  ' ' },
218      { "initrd",     LT_INITRD,      ' ', ' ' },      { "initrd",     LT_INITRD,      ' ', ' ' },
219        { "initrdefi",  LT_INITRD_EFI,  ' ', ' ' },
220      { "module",     LT_MBMODULE,    ' ' },      { "module",     LT_MBMODULE,    ' ' },
221      { "kernel",     LT_HYPER,       ' ' },      { "kernel",     LT_HYPER,       ' ' },
222      { NULL, 0, 0 },      { NULL, 0, 0 },
# Line 239  const char *grub2FindConfig(struct confi Line 253  const char *grub2FindConfig(struct confi
253      return configFiles[i];      return configFiles[i];
254  }  }
255    
256    int sizeOfSingleLine(struct singleLine * line) {
257      int count = 0;
258    
259      for (int i = 0; i < line->numElements; i++) {
260        int indentSize = 0;
261    
262        count = count + strlen(line->elements[i].item);
263    
264        indentSize = strlen(line->elements[i].indent);
265        if (indentSize > 0)
266          count = count + indentSize;
267        else
268          /* be extra safe and add room for whitespaces */
269          count = count + 1;
270      }
271    
272      /* room for trailing terminator */
273      count = count + 1;
274    
275      return count;
276    }
277    
278    static int isquote(char q)
279    {
280        if (q == '\'' || q == '\"')
281     return 1;
282        return 0;
283    }
284    
285    static int iskernel(enum lineType_e type) {
286        return (type == LT_KERNEL || type == LT_KERNEL_EFI);
287    }
288    
289    static int isinitrd(enum lineType_e type) {
290        return (type == LT_INITRD || type == LT_INITRD_EFI);
291    }
292    
293    char *grub2ExtractTitle(struct singleLine * line) {
294        char * current;
295        char * current_indent;
296        int current_len;
297        int current_indent_len;
298        int i;
299    
300        /* bail out if line does not start with menuentry */
301        if (strcmp(line->elements[0].item, "menuentry"))
302          return NULL;
303    
304        i = 1;
305        current = line->elements[i].item;
306        current_len = strlen(current);
307    
308        /* if second word is quoted, strip the quotes and return single word */
309        if (isquote(*current) && isquote(current[current_len - 1])) {
310     char *tmp;
311    
312     tmp = strdup(current);
313     *(tmp + current_len - 1) = '\0';
314     return ++tmp;
315        }
316    
317        /* if no quotes, return second word verbatim */
318        if (!isquote(*current))
319     return current;
320    
321        /* second element start with a quote, so we have to find the element
322         * whose last character is also quote (assuming it's the closing one) */
323        int resultMaxSize;
324        char * result;
325        
326        resultMaxSize = sizeOfSingleLine(line);
327        result = malloc(resultMaxSize);
328        snprintf(result, resultMaxSize, "%s", ++current);
329        
330        i++;
331        for (; i < line->numElements; ++i) {
332     current = line->elements[i].item;
333     current_len = strlen(current);
334     current_indent = line->elements[i].indent;
335     current_indent_len = strlen(current_indent);
336    
337     strncat(result, current_indent, current_indent_len);
338     if (!isquote(current[current_len-1])) {
339        strncat(result, current, current_len);
340     } else {
341        strncat(result, current, current_len - 1);
342        break;
343     }
344        }
345        return result;
346    }
347    
348  struct configFileInfo grub2ConfigType = {  struct configFileInfo grub2ConfigType = {
349      .findConfig = grub2FindConfig,      .findConfig = grub2FindConfig,
350      .keywords = grub2Keywords,      .keywords = grub2Keywords,
351      .defaultIsIndex = 1,      .defaultIsIndex = 1,
352      .defaultSupportSaved = 0,      .defaultSupportSaved = 1,
353      .defaultIsVariable = 1,      .defaultIsVariable = 1,
354      .entryStart = LT_MENUENTRY,      .entryStart = LT_MENUENTRY,
355      .entryEnd = LT_ENTRY_END,      .entryEnd = LT_ENTRY_END,
# Line 395  struct configFileInfo ziplConfigType = { Line 501  struct configFileInfo ziplConfigType = {
501  struct configFileInfo extlinuxConfigType = {  struct configFileInfo extlinuxConfigType = {
502      .defaultConfig = "/boot/extlinux/extlinux.conf",      .defaultConfig = "/boot/extlinux/extlinux.conf",
503      .keywords = extlinuxKeywords,      .keywords = extlinuxKeywords,
504        .caseInsensitive = 1,
505      .entryStart = LT_TITLE,      .entryStart = LT_TITLE,
506      .needsBootPrefix = 1,      .needsBootPrefix = 1,
507      .maxTitleLength = 255,      .maxTitleLength = 255,
# Line 483  static char * sdupprintf(const char *for Line 590  static char * sdupprintf(const char *for
590      return buf;      return buf;
591  }  }
592    
593    static enum lineType_e preferredLineType(enum lineType_e type,
594     struct configFileInfo *cfi) {
595        if (isEfi && cfi == &grub2ConfigType) {
596     switch (type) {
597     case LT_KERNEL:
598        return LT_KERNEL_EFI;
599     case LT_INITRD:
600        return LT_INITRD_EFI;
601     default:
602        return type;
603     }
604        }
605        return type;
606    }
607    
608  static struct keywordTypes * getKeywordByType(enum lineType_e type,  static struct keywordTypes * getKeywordByType(enum lineType_e type,
609        struct configFileInfo * cfi) {        struct configFileInfo * cfi) {
610      struct keywordTypes * kw;      for (struct keywordTypes *kw = cfi->keywords; kw->key; kw++) {
     for (kw = cfi->keywords; kw->key; kw++) {  
611   if (kw->type == type)   if (kw->type == type)
612      return kw;      return kw;
613      }      }
# Line 516  static char * getuuidbydev(char *device) Line 637  static char * getuuidbydev(char *device)
637    
638  static enum lineType_e getTypeByKeyword(char * keyword,  static enum lineType_e getTypeByKeyword(char * keyword,
639   struct configFileInfo * cfi) {   struct configFileInfo * cfi) {
640      struct keywordTypes * kw;      for (struct keywordTypes *kw = cfi->keywords; kw->key; kw++) {
641      for (kw = cfi->keywords; kw->key; kw++) {   if (cfi->caseInsensitive) {
642   if (!strcmp(keyword, kw->key))      if (!strcasecmp(keyword, kw->key))
643      return kw->type;                  return kw->type;
644     } else {
645        if (!strcmp(keyword, kw->key))
646            return kw->type;
647     }
648      }      }
649      return LT_UNKNOWN;      return LT_UNKNOWN;
650  }  }
# Line 604  static void lineInit(struct singleLine * Line 729  static void lineInit(struct singleLine *
729  }  }
730    
731  struct singleLine * lineDup(struct singleLine * line) {  struct singleLine * lineDup(struct singleLine * line) {
     int i;  
732      struct singleLine * newLine = malloc(sizeof(*newLine));      struct singleLine * newLine = malloc(sizeof(*newLine));
733    
734      newLine->indent = strdup(line->indent);      newLine->indent = strdup(line->indent);
# Line 614  struct singleLine * lineDup(struct singl Line 738  struct singleLine * lineDup(struct singl
738      newLine->elements = malloc(sizeof(*newLine->elements) *      newLine->elements = malloc(sizeof(*newLine->elements) *
739         newLine->numElements);         newLine->numElements);
740    
741      for (i = 0; i < newLine->numElements; i++) {      for (int i = 0; i < newLine->numElements; i++) {
742   newLine->elements[i].indent = strdup(line->elements[i].indent);   newLine->elements[i].indent = strdup(line->elements[i].indent);
743   newLine->elements[i].item = strdup(line->elements[i].item);   newLine->elements[i].item = strdup(line->elements[i].item);
744      }      }
# Line 623  struct singleLine * lineDup(struct singl Line 747  struct singleLine * lineDup(struct singl
747  }  }
748    
749  static void lineFree(struct singleLine * line) {  static void lineFree(struct singleLine * line) {
     int i;  
   
750      if (line->indent) free(line->indent);      if (line->indent) free(line->indent);
751    
752      for (i = 0; i < line->numElements; i++) {      for (int i = 0; i < line->numElements; i++) {
753   free(line->elements[i].item);   free(line->elements[i].item);
754   free(line->elements[i].indent);   free(line->elements[i].indent);
755      }      }
# Line 638  static void lineFree(struct singleLine * Line 760  static void lineFree(struct singleLine *
760    
761  static int lineWrite(FILE * out, struct singleLine * line,  static int lineWrite(FILE * out, struct singleLine * line,
762       struct configFileInfo * cfi) {       struct configFileInfo * cfi) {
     int i;  
   
763      if (fprintf(out, "%s", line->indent) == -1) return -1;      if (fprintf(out, "%s", line->indent) == -1) return -1;
764    
765      for (i = 0; i < line->numElements; i++) {      for (int i = 0; i < line->numElements; i++) {
766     /* Need to handle this, because we strip the quotes from
767     * menuentry when read it. */
768     if (line->type == LT_MENUENTRY && i == 1) {
769        if(!isquote(*line->elements[i].item))
770     fprintf(out, "\'%s\'", line->elements[i].item);
771        else
772     fprintf(out, "%s", line->elements[i].item);
773        fprintf(out, "%s", line->elements[i].indent);
774    
775        continue;
776     }
777    
778   if (i == 1 && line->type == LT_KERNELARGS && cfi->argsInQuotes)   if (i == 1 && line->type == LT_KERNELARGS && cfi->argsInQuotes)
779      if (fputc('"', out) == EOF) return -1;      if (fputc('"', out) == EOF) return -1;
780    
# Line 736  static int getNextLine(char ** bufPtr, s Line 868  static int getNextLine(char ** bufPtr, s
868      if (*line->elements[0].item == '#') {      if (*line->elements[0].item == '#') {
869   char * fullLine;   char * fullLine;
870   int len;   int len;
  int i;  
871    
872   len = strlen(line->indent);   len = strlen(line->indent);
873   for (i = 0; i < line->numElements; i++)   for (int i = 0; i < line->numElements; i++)
874      len += strlen(line->elements[i].item) +      len += strlen(line->elements[i].item) +
875     strlen(line->elements[i].indent);     strlen(line->elements[i].indent);
876    
# Line 748  static int getNextLine(char ** bufPtr, s Line 879  static int getNextLine(char ** bufPtr, s
879   free(line->indent);   free(line->indent);
880   line->indent = fullLine;   line->indent = fullLine;
881    
882   for (i = 0; i < line->numElements; i++) {   for (int i = 0; i < line->numElements; i++) {
883      strcat(fullLine, line->elements[i].item);      strcat(fullLine, line->elements[i].item);
884      strcat(fullLine, line->elements[i].indent);      strcat(fullLine, line->elements[i].indent);
885      free(line->elements[i].item);      free(line->elements[i].item);
# Line 767  static int getNextLine(char ** bufPtr, s Line 898  static int getNextLine(char ** bufPtr, s
898   * elements up more   * elements up more
899   */   */
900   if (!isspace(kw->separatorChar)) {   if (!isspace(kw->separatorChar)) {
     int i;  
901      char indent[2] = "";      char indent[2] = "";
902      indent[0] = kw->separatorChar;      indent[0] = kw->separatorChar;
903      for (i = 1; i < line->numElements; i++) {      for (int i = 1; i < line->numElements; i++) {
904   char *p;   char *p;
  int j;  
905   int numNewElements;   int numNewElements;
906    
907   numNewElements = 0;   numNewElements = 0;
# Line 788  static int getNextLine(char ** bufPtr, s Line 917  static int getNextLine(char ** bufPtr, s
917      sizeof(*line->elements) * elementsAlloced);      sizeof(*line->elements) * elementsAlloced);
918   }   }
919    
920   for (j = line->numElements; j > i; j--) {   for (int j = line->numElements; j > i; j--) {
921   line->elements[j + numNewElements] = line->elements[j];   line->elements[j + numNewElements] = line->elements[j];
922   }   }
923   line->numElements += numNewElements;   line->numElements += numNewElements;
# Line 801  static int getNextLine(char ** bufPtr, s Line 930  static int getNextLine(char ** bufPtr, s
930   break;   break;
931   }   }
932    
933   free(line->elements[i].indent);   line->elements[i + 1].indent = line->elements[i].indent;
934   line->elements[i].indent = strdup(indent);   line->elements[i].indent = strdup(indent);
935   *p++ = '\0';   *p++ = '\0';
936   i++;   i++;
937   line->elements[i].item = strdup(p);   line->elements[i].item = strdup(p);
  line->elements[i].indent = strdup("");  
  p = line->elements[i].item;  
938   }   }
939      }      }
940   }   }
# Line 828  static struct grubConfig * readConfig(co Line 955  static struct grubConfig * readConfig(co
955      struct singleLine * last = NULL, * line, * defaultLine = NULL;      struct singleLine * last = NULL, * line, * defaultLine = NULL;
956      char * end;      char * end;
957      struct singleEntry * entry = NULL;      struct singleEntry * entry = NULL;
958      int i, len;      int len;
959      char * buf;      char * buf;
960    
961      if (!strcmp(inName, "-")) {      if (!strcmp(inName, "-")) {
# Line 874  static struct grubConfig * readConfig(co Line 1001  static struct grubConfig * readConfig(co
1001      cfg->secondaryIndent = strdup(line->indent);      cfg->secondaryIndent = strdup(line->indent);
1002   }   }
1003    
1004   if (isEntryStart(line, cfi)) {   if (isEntryStart(line, cfi) || (cfg->entries && !sawEntry)) {
1005      sawEntry = 1;      sawEntry = 1;
1006      if (!entry) {      if (!entry) {
1007   cfg->entries = malloc(sizeof(*entry));   cfg->entries = malloc(sizeof(*entry));
# Line 891  static struct grubConfig * readConfig(co Line 1018  static struct grubConfig * readConfig(co
1018   }   }
1019    
1020   if (line->type == LT_SET_VARIABLE) {   if (line->type == LT_SET_VARIABLE) {
     int i;  
1021      dbgPrintf("found 'set' command (%d elements): ", line->numElements);      dbgPrintf("found 'set' command (%d elements): ", line->numElements);
1022      dbgPrintf("%s", line->indent);      dbgPrintf("%s", line->indent);
1023      for (i = 0; i < line->numElements; i++)      for (int i = 0; i < line->numElements; i++)
1024   dbgPrintf("%s\"%s\"", line->elements[i].indent, line->elements[i].item);   dbgPrintf("\"%s\"%s", line->elements[i].item, line->elements[i].indent);
1025      dbgPrintf("\n");      dbgPrintf("\n");
1026      struct keywordTypes *kwType = getKeywordByType(LT_DEFAULT, cfi);      struct keywordTypes *kwType = getKeywordByType(LT_DEFAULT, cfi);
1027      if (kwType && line->numElements == 3 &&      if (kwType && line->numElements == 3 &&
# Line 908  static struct grubConfig * readConfig(co Line 1034  static struct grubConfig * readConfig(co
1034      cfg->flags &= ~GRUB_CONFIG_NO_DEFAULT;      cfg->flags &= ~GRUB_CONFIG_NO_DEFAULT;
1035      defaultLine = line;      defaultLine = line;
1036    
1037          } else if (line->type == LT_KERNEL) {          } else if (iskernel(line->type)) {
1038      /* if by some freak chance this is multiboot and the "module"      /* if by some freak chance this is multiboot and the "module"
1039       * lines came earlier in the template, make sure to use LT_HYPER       * lines came earlier in the template, make sure to use LT_HYPER
1040       * instead of LT_KERNEL now       * instead of LT_KERNEL now
# Line 922  static struct grubConfig * readConfig(co Line 1048  static struct grubConfig * readConfig(co
1048       * This only applies to grub, but that's the only place we       * This only applies to grub, but that's the only place we
1049       * should find LT_MBMODULE lines anyway.       * should find LT_MBMODULE lines anyway.
1050       */       */
1051      struct singleLine * l;      for (struct singleLine *l = entry->lines; l; l = l->next) {
     for (l = entry->lines; l; l = l->next) {  
1052   if (l->type == LT_HYPER)   if (l->type == LT_HYPER)
1053      break;      break;
1054   else if (l->type == LT_KERNEL) {   else if (iskernel(l->type)) {
1055      l->type = LT_HYPER;      l->type = LT_HYPER;
1056      break;      break;
1057   }   }
# Line 943  static struct grubConfig * readConfig(co Line 1068  static struct grubConfig * readConfig(co
1068   } else if (line->type == LT_TITLE && line->numElements > 1) {   } else if (line->type == LT_TITLE && line->numElements > 1) {
1069      /* make the title a single argument (undoing our parsing) */      /* make the title a single argument (undoing our parsing) */
1070      len = 0;      len = 0;
1071      for (i = 1; i < line->numElements; i++) {      for (int i = 1; i < line->numElements; i++) {
1072   len += strlen(line->elements[i].item);   len += strlen(line->elements[i].item);
1073   len += strlen(line->elements[i].indent);   len += strlen(line->elements[i].indent);
1074      }      }
1075      buf = malloc(len + 1);      buf = malloc(len + 1);
1076      *buf = '\0';      *buf = '\0';
1077    
1078      for (i = 1; i < line->numElements; i++) {      for (int i = 1; i < line->numElements; i++) {
1079   strcat(buf, line->elements[i].item);   strcat(buf, line->elements[i].item);
1080   free(line->elements[i].item);   free(line->elements[i].item);
1081    
# Line 964  static struct grubConfig * readConfig(co Line 1089  static struct grubConfig * readConfig(co
1089      line->elements[line->numElements - 1].indent;      line->elements[line->numElements - 1].indent;
1090      line->elements[1].item = buf;      line->elements[1].item = buf;
1091      line->numElements = 2;      line->numElements = 2;
1092     } else if (line->type == LT_MENUENTRY && line->numElements > 3) {
1093        /* let --remove-kernel="TITLE=what" work */
1094        len = 0;
1095        char *extras;
1096        char *title;
1097    
1098        for (int i = 1; i < line->numElements; i++) {
1099     len += strlen(line->elements[i].item);
1100     len += strlen(line->elements[i].indent);
1101        }
1102        buf = malloc(len + 1);
1103        *buf = '\0';
1104    
1105        /* allocate mem for extra flags. */
1106        extras = malloc(len + 1);
1107        *extras = '\0';
1108    
1109        /* get title. */
1110        for (int i = 0; i < line->numElements; i++) {
1111     if (!strcmp(line->elements[i].item, "menuentry"))
1112        continue;
1113     if (isquote(*line->elements[i].item))
1114        title = line->elements[i].item + 1;
1115     else
1116        title = line->elements[i].item;
1117    
1118     len = strlen(title);
1119            if (isquote(title[len-1])) {
1120        strncat(buf, title,len-1);
1121        break;
1122     } else {
1123        strcat(buf, title);
1124        strcat(buf, line->elements[i].indent);
1125     }
1126        }
1127    
1128        /* get extras */
1129        int count = 0;
1130        for (int i = 0; i < line->numElements; i++) {
1131     if (count >= 2) {
1132        strcat(extras, line->elements[i].item);
1133        strcat(extras, line->elements[i].indent);
1134     }
1135    
1136     if (!strcmp(line->elements[i].item, "menuentry"))
1137        continue;
1138    
1139     /* count ' or ", there should be two in menuentry line. */
1140     if (isquote(*line->elements[i].item))
1141        count++;
1142    
1143     len = strlen(line->elements[i].item);
1144    
1145     if (isquote(line->elements[i].item[len -1]))
1146        count++;
1147    
1148     /* ok, we get the final ' or ", others are extras. */
1149                }
1150        line->elements[1].indent =
1151     line->elements[line->numElements - 2].indent;
1152        line->elements[1].item = buf;
1153        line->elements[2].indent =
1154     line->elements[line->numElements - 2].indent;
1155        line->elements[2].item = extras;
1156        line->numElements = 3;
1157   } else if (line->type == LT_KERNELARGS && cfi->argsInQuotes) {   } else if (line->type == LT_KERNELARGS && cfi->argsInQuotes) {
1158      /* Strip off any " which may be present; they'll be put back      /* Strip off any " which may be present; they'll be put back
1159         on write. This is one of the few (the only?) places that grubby         on write. This is one of the few (the only?) places that grubby
# Line 973  static struct grubConfig * readConfig(co Line 1162  static struct grubConfig * readConfig(co
1162      if (line->numElements >= 2) {      if (line->numElements >= 2) {
1163   int last, len;   int last, len;
1164    
1165   if (*line->elements[1].item == '"')   if (isquote(*line->elements[1].item))
1166      memmove(line->elements[1].item, line->elements[1].item + 1,      memmove(line->elements[1].item, line->elements[1].item + 1,
1167      strlen(line->elements[1].item + 1) + 1);      strlen(line->elements[1].item + 1) + 1);
1168    
1169   last = line->numElements - 1;   last = line->numElements - 1;
1170   len = strlen(line->elements[last].item) - 1;   len = strlen(line->elements[last].item) - 1;
1171   if (line->elements[last].item[len] == '"')   if (isquote(line->elements[last].item[len]))
1172      line->elements[last].item[len] = '\0';      line->elements[last].item[len] = '\0';
1173      }      }
1174   }   }
# Line 1038  static struct grubConfig * readConfig(co Line 1227  static struct grubConfig * readConfig(co
1227    
1228      dbgPrintf("defaultLine is %s\n", defaultLine ? "set" : "unset");      dbgPrintf("defaultLine is %s\n", defaultLine ? "set" : "unset");
1229      if (defaultLine) {      if (defaultLine) {
1230   if (cfi->defaultIsVariable) {          if (defaultLine->numElements > 2 &&
1231        cfi->defaultSupportSaved &&
1232        !strncmp(defaultLine->elements[2].item,"\"${saved_entry}\"", 16)) {
1233        cfg->defaultImage = DEFAULT_SAVED_GRUB2;
1234     } else if (cfi->defaultIsVariable) {
1235      char *value = defaultLine->elements[2].item;      char *value = defaultLine->elements[2].item;
1236      while (*value && (*value == '"' || *value == '\'' ||      while (*value && (*value == '"' || *value == '\'' ||
1237      *value == ' ' || *value == '\t'))      *value == ' ' || *value == '\t'))
# Line 1055  static struct grubConfig * readConfig(co Line 1248  static struct grubConfig * readConfig(co
1248      cfg->defaultImage = strtol(defaultLine->elements[1].item, &end, 10);      cfg->defaultImage = strtol(defaultLine->elements[1].item, &end, 10);
1249      if (*end) cfg->defaultImage = -1;      if (*end) cfg->defaultImage = -1;
1250   } else if (defaultLine->numElements >= 2) {   } else if (defaultLine->numElements >= 2) {
1251      i = 0;      int i = 0;
1252      while ((entry = findEntryByIndex(cfg, i))) {      while ((entry = findEntryByIndex(cfg, i))) {
1253   for (line = entry->lines; line; line = line->next)   for (line = entry->lines; line; line = line->next)
1254      if (line->type == LT_TITLE) break;      if (line->type == LT_TITLE) break;
# Line 1095  static void writeDefault(FILE * out, cha Line 1288  static void writeDefault(FILE * out, cha
1288    
1289      if (cfg->defaultImage == DEFAULT_SAVED)      if (cfg->defaultImage == DEFAULT_SAVED)
1290   fprintf(out, "%sdefault%ssaved\n", indent, separator);   fprintf(out, "%sdefault%ssaved\n", indent, separator);
1291        else if (cfg->defaultImage == DEFAULT_SAVED_GRUB2)
1292     fprintf(out, "%sset default=\"${saved_entry}\"\n", indent);
1293      else if (cfg->defaultImage > -1) {      else if (cfg->defaultImage > -1) {
1294   if (cfg->cfi->defaultIsIndex) {   if (cfg->cfi->defaultIsIndex) {
1295      if (cfg->cfi->defaultIsVariable) {      if (cfg->cfi->defaultIsVariable) {
# Line 1155  static int writeConfig(struct grubConfig Line 1350  static int writeConfig(struct grubConfig
1350    
1351      /* most likely the symlink is relative, so change our      /* most likely the symlink is relative, so change our
1352         directory to the dir of the symlink */         directory to the dir of the symlink */
1353              rc = chdir(dirname(strdupa(outName)));      char *dir = strdupa(outName);
1354        rc = chdir(dirname(dir));
1355      do {      do {
1356   buf = alloca(len + 1);   buf = alloca(len + 1);
1357   rc = readlink(basename(outName), buf, len);   rc = readlink(basename(outName), buf, len);
# Line 1293  static char *findDiskForRoot() Line 1489  static char *findDiskForRoot()
1489      buf[rc] = '\0';      buf[rc] = '\0';
1490      chptr = buf;      chptr = buf;
1491    
1492        char *foundanswer = NULL;
1493    
1494      while (chptr && chptr != buf+rc) {      while (chptr && chptr != buf+rc) {
1495          devname = chptr;          devname = chptr;
1496    
# Line 1320  static char *findDiskForRoot() Line 1518  static char *findDiskForRoot()
1518           * for '/' obviously.           * for '/' obviously.
1519           */           */
1520          if (*(++chptr) == '/' && *(++chptr) == ' ') {          if (*(++chptr) == '/' && *(++chptr) == ' ') {
1521              /*              /* remember the last / entry in mtab */
1522               * 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);  
1523          }          }
1524    
1525          /* Next line */          /* Next line */
# Line 1335  static char *findDiskForRoot() Line 1528  static char *findDiskForRoot()
1528              chptr++;              chptr++;
1529      }      }
1530    
1531        /* Return the last / entry found */
1532        if (foundanswer) {
1533            chptr = strchr(foundanswer, ' ');
1534            *chptr = '\0';
1535            return strdup(foundanswer);
1536        }
1537    
1538      return NULL;      return NULL;
1539  }  }
1540    
1541    void printEntry(struct singleEntry * entry, FILE *f) {
1542        int i;
1543        struct singleLine * line;
1544    
1545        for (line = entry->lines; line; line = line->next) {
1546     log_message(f, "DBG: %s", line->indent);
1547     for (i = 0; i < line->numElements; i++) {
1548        /* Need to handle this, because we strip the quotes from
1549         * menuentry when read it. */
1550        if (line->type == LT_MENUENTRY && i == 1) {
1551     if(!isquote(*line->elements[i].item))
1552        log_message(f, "\'%s\'", line->elements[i].item);
1553     else
1554        log_message(f, "%s", line->elements[i].item);
1555     log_message(f, "%s", line->elements[i].indent);
1556    
1557     continue;
1558        }
1559        
1560        log_message(f, "%s%s",
1561        line->elements[i].item, line->elements[i].indent);
1562     }
1563     log_message(f, "\n");
1564        }
1565    }
1566    
1567    void notSuitablePrintf(struct singleEntry * entry, int okay, const char *fmt, ...)
1568    {
1569        static int once;
1570        va_list argp, argq;
1571    
1572        va_start(argp, fmt);
1573    
1574        va_copy(argq, argp);
1575        if (!once) {
1576     log_time(NULL);
1577     log_message(NULL, "command line: %s\n", saved_command_line);
1578        }
1579        log_message(NULL, "DBG: Image entry %s: ", okay ? "succeeded" : "failed");
1580        log_vmessage(NULL, fmt, argq);
1581    
1582        printEntry(entry, NULL);
1583        va_end(argq);
1584    
1585        if (!debug) {
1586     once = 1;
1587         va_end(argp);
1588     return;
1589        }
1590    
1591        if (okay) {
1592     va_end(argp);
1593     return;
1594        }
1595    
1596        if (!once)
1597     log_message(stderr, "DBG: command line: %s\n", saved_command_line);
1598        once = 1;
1599        fprintf(stderr, "DBG: Image entry failed: ");
1600        vfprintf(stderr, fmt, argp);
1601        printEntry(entry, stderr);
1602        va_end(argp);
1603    }
1604    
1605    #define beginswith(s, c) ((s) && (s)[0] == (c))
1606    
1607    static int endswith(const char *s, char c)
1608    {
1609     int slen;
1610    
1611     if (!s || !s[0])
1612     return 0;
1613     slen = strlen(s) - 1;
1614    
1615     return s[slen] == c;
1616    }
1617    
1618  int suitableImage(struct singleEntry * entry, const char * bootPrefix,  int suitableImage(struct singleEntry * entry, const char * bootPrefix,
1619    int skipRemoved, int flags) {    int skipRemoved, int flags) {
1620      struct singleLine * line;      struct singleLine * line;
# Line 1347  int suitableImage(struct singleEntry * e Line 1624  int suitableImage(struct singleEntry * e
1624      char * rootspec;      char * rootspec;
1625      char * rootdev;      char * rootdev;
1626    
1627      if (skipRemoved && entry->skip) return 0;      if (skipRemoved && entry->skip) {
1628     notSuitablePrintf(entry, 0, "marked to skip\n");
1629     return 0;
1630        }
1631    
1632      line = getLineByType(LT_KERNEL|LT_HYPER, entry->lines);      line = getLineByType(LT_KERNEL|LT_HYPER|LT_KERNEL_EFI, entry->lines);
1633      if (!line || line->numElements < 2) return 0;      if (!line) {
1634     notSuitablePrintf(entry, 0, "no line found\n");
1635     return 0;
1636        }
1637        if (line->numElements < 2) {
1638     notSuitablePrintf(entry, 0, "line has only %d elements\n",
1639        line->numElements);
1640     return 0;
1641        }
1642    
1643      if (flags & GRUBBY_BADIMAGE_OKAY) return 1;      if (flags & GRUBBY_BADIMAGE_OKAY) {
1644        notSuitablePrintf(entry, 1, "\n");
1645        return 1;
1646        }
1647    
1648      fullName = alloca(strlen(bootPrefix) +      fullName = alloca(strlen(bootPrefix) +
1649        strlen(line->elements[1].item) + 1);        strlen(line->elements[1].item) + 1);
1650      rootspec = getRootSpecifier(line->elements[1].item);      rootspec = getRootSpecifier(line->elements[1].item);
1651      sprintf(fullName, "%s%s", bootPrefix,      int rootspec_offset = rootspec ? strlen(rootspec) : 0;
1652              line->elements[1].item + (rootspec ? strlen(rootspec) : 0));      int hasslash = endswith(bootPrefix, '/') ||
1653      if (access(fullName, R_OK)) return 0;       beginswith(line->elements[1].item + rootspec_offset, '/');
1654        sprintf(fullName, "%s%s%s", bootPrefix, hasslash ? "" : "/",
1655                line->elements[1].item + rootspec_offset);
1656        if (access(fullName, R_OK)) {
1657     notSuitablePrintf(entry, 0, "access to %s failed\n", fullName);
1658     return 0;
1659        }
1660      for (i = 2; i < line->numElements; i++)      for (i = 2; i < line->numElements; i++)
1661   if (!strncasecmp(line->elements[i].item, "root=", 5)) break;   if (!strncasecmp(line->elements[i].item, "root=", 5)) break;
1662      if (i < line->numElements) {      if (i < line->numElements) {
# Line 1378  int suitableImage(struct singleEntry * e Line 1674  int suitableImage(struct singleEntry * e
1674      line = getLineByType(LT_KERNELARGS|LT_MBMODULE, entry->lines);      line = getLineByType(LT_KERNELARGS|LT_MBMODULE, entry->lines);
1675    
1676              /* failed to find one */              /* failed to find one */
1677              if (!line) return 0;              if (!line) {
1678     notSuitablePrintf(entry, 0, "no line found\n");
1679     return 0;
1680                }
1681    
1682      for (i = 1; i < line->numElements; i++)      for (i = 1; i < line->numElements; i++)
1683          if (!strncasecmp(line->elements[i].item, "root=", 5)) break;          if (!strncasecmp(line->elements[i].item, "root=", 5)) break;
1684      if (i < line->numElements)      if (i < line->numElements)
1685          dev = line->elements[i].item + 5;          dev = line->elements[i].item + 5;
1686      else {      else {
1687     notSuitablePrintf(entry, 0, "no root= entry found\n");
1688   /* it failed too...  can't find root= */   /* it failed too...  can't find root= */
1689          return 0;          return 0;
1690              }              }
# Line 1392  int suitableImage(struct singleEntry * e Line 1692  int suitableImage(struct singleEntry * e
1692      }      }
1693    
1694      dev = getpathbyspec(dev);      dev = getpathbyspec(dev);
1695      if (!dev)      if (!getpathbyspec(dev)) {
1696            notSuitablePrintf(entry, 0, "can't find blkid entry for %s\n", dev);
1697          return 0;          return 0;
1698        } else
1699     dev = getpathbyspec(dev);
1700    
1701      rootdev = findDiskForRoot();      rootdev = findDiskForRoot();
1702      if (!rootdev)      if (!rootdev) {
1703            notSuitablePrintf(entry, 0, "can't find root device\n");
1704   return 0;   return 0;
1705        }
1706    
1707      if (!getuuidbydev(rootdev) || !getuuidbydev(dev)) {      if (!getuuidbydev(rootdev) || !getuuidbydev(dev)) {
1708            notSuitablePrintf(entry, 0, "uuid missing: rootdev %s, dev %s\n",
1709     getuuidbydev(rootdev), getuuidbydev(dev));
1710          free(rootdev);          free(rootdev);
1711          return 0;          return 0;
1712      }      }
1713    
1714      if (strcmp(getuuidbydev(rootdev), getuuidbydev(dev))) {      if (strcmp(getuuidbydev(rootdev), getuuidbydev(dev))) {
1715            notSuitablePrintf(entry, 0, "uuid mismatch: rootdev %s, dev %s\n",
1716     getuuidbydev(rootdev), getuuidbydev(dev));
1717   free(rootdev);   free(rootdev);
1718          return 0;          return 0;
1719      }      }
1720    
1721      free(rootdev);      free(rootdev);
1722        notSuitablePrintf(entry, 1, "\n");
1723    
1724      return 1;      return 1;
1725  }  }
# Line 1453  struct singleEntry * findEntryByPath(str Line 1763  struct singleEntry * findEntryByPath(str
1763   entry = findEntryByIndex(config, indexVars[i]);   entry = findEntryByIndex(config, indexVars[i]);
1764   if (!entry) return NULL;   if (!entry) return NULL;
1765    
1766   line = getLineByType(LT_KERNEL|LT_HYPER, entry->lines);   line = getLineByType(LT_KERNEL|LT_HYPER|LT_KERNEL_EFI, entry->lines);
1767   if (!line) return NULL;   if (!line) return NULL;
1768    
1769   if (index) *index = indexVars[i];   if (index) *index = indexVars[i];
# Line 1491  struct singleEntry * findEntryByPath(str Line 1801  struct singleEntry * findEntryByPath(str
1801    
1802   if (!strncmp(kernel, "TITLE=", 6)) {   if (!strncmp(kernel, "TITLE=", 6)) {
1803      prefix = "";      prefix = "";
1804      checkType = LT_TITLE;      checkType = LT_TITLE|LT_MENUENTRY;
1805      kernel += 6;      kernel += 6;
1806   }   }
1807    
# Line 1502  struct singleEntry * findEntryByPath(str Line 1812  struct singleEntry * findEntryByPath(str
1812    
1813      /* check all the lines matching checkType */      /* check all the lines matching checkType */
1814      for (line = entry->lines; line; line = line->next) {      for (line = entry->lines; line; line = line->next) {
1815   line = getLineByType(entry->multiboot && checkType == LT_KERNEL ?   enum lineType_e ct = checkType;
1816       LT_KERNEL|LT_MBMODULE|LT_HYPER :   if (entry->multiboot && checkType == LT_KERNEL)
1817       checkType, line);      ct = LT_KERNEL|LT_KERNEL_EFI|LT_MBMODULE|LT_HYPER;
1818   if (!line) break;  /* not found in this entry */   else if (checkType & LT_KERNEL)
1819        ct = checkType | LT_KERNEL_EFI;
1820     line = getLineByType(ct, line);
1821     if (!line)
1822        break;  /* not found in this entry */
1823    
1824   if (line && line->numElements >= 2) {   if (line && line->type != LT_MENUENTRY &&
1825     line->numElements >= 2) {
1826      rootspec = getRootSpecifier(line->elements[1].item);      rootspec = getRootSpecifier(line->elements[1].item);
1827      if (!strcmp(line->elements[1].item +      if (!strcmp(line->elements[1].item +
1828   ((rootspec != NULL) ? strlen(rootspec) : 0),   ((rootspec != NULL) ? strlen(rootspec) : 0),
1829   kernel + strlen(prefix)))   kernel + strlen(prefix)))
1830   break;   break;
1831   }   }
1832     if(line->type == LT_MENUENTRY &&
1833     !strcmp(line->elements[1].item, kernel))
1834        break;
1835      }      }
1836    
1837      /* make sure this entry has a kernel identifier; this skips      /* make sure this entry has a kernel identifier; this skips
1838       * non-Linux boot entries (could find netbsd etc, though, which is       * non-Linux boot entries (could find netbsd etc, though, which is
1839       * unfortunate)       * unfortunate)
1840       */       */
1841      if (line && getLineByType(LT_KERNEL|LT_HYPER, entry->lines))      if (line && getLineByType(LT_KERNEL|LT_HYPER|LT_KERNEL_EFI, entry->lines))
1842   break; /* found 'im! */   break; /* found 'im! */
1843   }   }
1844    
# Line 1605  void markRemovedImage(struct grubConfig Line 1923  void markRemovedImage(struct grubConfig
1923        const char * prefix) {        const char * prefix) {
1924      struct singleEntry * entry;      struct singleEntry * entry;
1925    
1926      if (!image) return;      if (!image)
1927     return;
1928    
1929        /* check and see if we're removing the default image */
1930        if (isdigit(*image)) {
1931     entry = findEntryByPath(cfg, image, prefix, NULL);
1932     if(entry)
1933        entry->skip = 1;
1934     return;
1935        }
1936    
1937      while ((entry = findEntryByPath(cfg, image, prefix, NULL)))      while ((entry = findEntryByPath(cfg, image, prefix, NULL)))
1938   entry->skip = 1;   entry->skip = 1;
# Line 1613  void markRemovedImage(struct grubConfig Line 1940  void markRemovedImage(struct grubConfig
1940    
1941  void setDefaultImage(struct grubConfig * config, int hasNew,  void setDefaultImage(struct grubConfig * config, int hasNew,
1942       const char * defaultKernelPath, int newIsDefault,       const char * defaultKernelPath, int newIsDefault,
1943       const char * prefix, int flags) {       const char * prefix, int flags, int index) {
1944      struct singleEntry * entry, * entry2, * newDefault;      struct singleEntry * entry, * entry2, * newDefault;
1945      int i, j;      int i, j;
1946    
1947      if (newIsDefault) {      if (newIsDefault) {
1948   config->defaultImage = 0;   config->defaultImage = 0;
1949   return;   return;
1950        } else if ((index >= 0) && config->cfi->defaultIsIndex) {
1951     if (findEntryByIndex(config, index))
1952        config->defaultImage = index;
1953     else
1954        config->defaultImage = -1;
1955     return;
1956      } else if (defaultKernelPath) {      } else if (defaultKernelPath) {
1957   i = 0;   i = 0;
1958   if (findEntryByPath(config, defaultKernelPath, prefix, &i)) {   if (findEntryByPath(config, defaultKernelPath, prefix, &i)) {
# Line 1632  void setDefaultImage(struct grubConfig * Line 1965  void setDefaultImage(struct grubConfig *
1965    
1966      /* defaultImage now points to what we'd like to use, but before any order      /* defaultImage now points to what we'd like to use, but before any order
1967         changes */         changes */
1968      if (config->defaultImage == DEFAULT_SAVED)      if ((config->defaultImage == DEFAULT_SAVED) ||
1969     (config->defaultImage == DEFAULT_SAVED_GRUB2))
1970        /* default is set to saved, we don't want to change it */        /* default is set to saved, we don't want to change it */
1971        return;        return;
1972    
# Line 1693  void displayEntry(struct singleEntry * e Line 2027  void displayEntry(struct singleEntry * e
2027    
2028      printf("index=%d\n", index);      printf("index=%d\n", index);
2029    
2030      line = getLineByType(LT_KERNEL|LT_HYPER, entry->lines);      line = getLineByType(LT_KERNEL|LT_HYPER|LT_KERNEL_EFI, entry->lines);
2031      if (!line) {      if (!line) {
2032          printf("non linux entry\n");          printf("non linux entry\n");
2033          return;          return;
2034      }      }
2035    
2036      printf("kernel=%s\n", line->elements[1].item);      if (!strncmp(prefix, line->elements[1].item, strlen(prefix)))
2037     printf("kernel=%s\n", line->elements[1].item);
2038        else
2039     printf("kernel=%s%s\n", prefix, line->elements[1].item);
2040    
2041      if (line->numElements >= 3) {      if (line->numElements >= 3) {
2042   printf("args=\"");   printf("args=\"");
# Line 1755  void displayEntry(struct singleEntry * e Line 2092  void displayEntry(struct singleEntry * e
2092   printf("root=%s\n", s);   printf("root=%s\n", s);
2093      }      }
2094    
2095      line = getLineByType(LT_INITRD, entry->lines);      line = getLineByType(LT_INITRD|LT_INITRD_EFI, entry->lines);
2096    
2097      if (line && line->numElements >= 2) {      if (line && line->numElements >= 2) {
2098   printf("initrd=%s", prefix);   if (!strncmp(prefix, line->elements[1].item, strlen(prefix)))
2099        printf("initrd=");
2100     else
2101        printf("initrd=%s", prefix);
2102    
2103   for (i = 1; i < line->numElements; i++)   for (i = 1; i < line->numElements; i++)
2104      printf("%s%s", line->elements[i].item, line->elements[i].indent);      printf("%s%s", line->elements[i].item, line->elements[i].indent);
2105   printf("\n");   printf("\n");
2106      }      }
2107    
2108        line = getLineByType(LT_TITLE, entry->lines);
2109        if (line) {
2110     printf("title=%s\n", line->elements[1].item);
2111        } else {
2112     char * title;
2113     line = getLineByType(LT_MENUENTRY, entry->lines);
2114     title = grub2ExtractTitle(line);
2115     if (title)
2116        printf("title=%s\n", title);
2117        }
2118    }
2119    
2120    int isSuseSystem(void) {
2121        const char * path;
2122        const static char default_path[] = "/etc/SuSE-release";
2123    
2124        if ((path = getenv("GRUBBY_SUSE_RELEASE")) == NULL)
2125     path = default_path;
2126    
2127        if (!access(path, R_OK))
2128     return 1;
2129        return 0;
2130    }
2131    
2132    int isSuseGrubConf(const char * path) {
2133        FILE * grubConf;
2134        char * line = NULL;
2135        size_t len = 0, res = 0;
2136    
2137        grubConf = fopen(path, "r");
2138        if (!grubConf) {
2139            dbgPrintf("Could not open SuSE configuration file '%s'\n", path);
2140     return 0;
2141        }
2142    
2143        while ((res = getline(&line, &len, grubConf)) != -1) {
2144     if (!strncmp(line, "setup", 5)) {
2145        fclose(grubConf);
2146        free(line);
2147        return 1;
2148     }
2149        }
2150    
2151        dbgPrintf("SuSE configuration file '%s' does not appear to be valid\n",
2152          path);
2153    
2154        fclose(grubConf);
2155        free(line);
2156        return 0;
2157    }
2158    
2159    int suseGrubConfGetLba(const char * path, int * lbaPtr) {
2160        FILE * grubConf;
2161        char * line = NULL;
2162        size_t res = 0, len = 0;
2163    
2164        if (!path) return 1;
2165        if (!lbaPtr) return 1;
2166    
2167        grubConf = fopen(path, "r");
2168        if (!grubConf) return 1;
2169    
2170        while ((res = getline(&line, &len, grubConf)) != -1) {
2171     if (line[res - 1] == '\n')
2172        line[res - 1] = '\0';
2173     else if (len > res)
2174        line[res] = '\0';
2175     else {
2176        line = realloc(line, res + 1);
2177        line[res] = '\0';
2178     }
2179    
2180     if (!strncmp(line, "setup", 5)) {
2181        if (strstr(line, "--force-lba")) {
2182            *lbaPtr = 1;
2183        } else {
2184            *lbaPtr = 0;
2185        }
2186        dbgPrintf("lba: %i\n", *lbaPtr);
2187        break;
2188     }
2189        }
2190    
2191        free(line);
2192        fclose(grubConf);
2193        return 0;
2194    }
2195    
2196    int suseGrubConfGetInstallDevice(const char * path, char ** devicePtr) {
2197        FILE * grubConf;
2198        char * line = NULL;
2199        size_t res = 0, len = 0;
2200        char * lastParamPtr = NULL;
2201        char * secLastParamPtr = NULL;
2202        char installDeviceNumber = '\0';
2203        char * bounds = NULL;
2204    
2205        if (!path) return 1;
2206        if (!devicePtr) return 1;
2207    
2208        grubConf = fopen(path, "r");
2209        if (!grubConf) return 1;
2210    
2211        while ((res = getline(&line, &len, grubConf)) != -1) {
2212     if (strncmp(line, "setup", 5))
2213        continue;
2214    
2215     if (line[res - 1] == '\n')
2216        line[res - 1] = '\0';
2217     else if (len > res)
2218        line[res] = '\0';
2219     else {
2220        line = realloc(line, res + 1);
2221        line[res] = '\0';
2222     }
2223    
2224     lastParamPtr = bounds = line + res;
2225    
2226     /* Last parameter in grub may be an optional IMAGE_DEVICE */
2227     while (!isspace(*lastParamPtr))
2228        lastParamPtr--;
2229     lastParamPtr++;
2230    
2231     secLastParamPtr = lastParamPtr - 2;
2232     dbgPrintf("lastParamPtr: %s\n", lastParamPtr);
2233    
2234     if (lastParamPtr + 3 > bounds) {
2235        dbgPrintf("lastParamPtr going over boundary");
2236        fclose(grubConf);
2237        free(line);
2238        return 1;
2239     }
2240     if (!strncmp(lastParamPtr, "(hd", 3))
2241        lastParamPtr += 3;
2242     dbgPrintf("lastParamPtr: %c\n", *lastParamPtr);
2243    
2244     /*
2245     * Second last parameter will decide wether last parameter is
2246     * an IMAGE_DEVICE or INSTALL_DEVICE
2247     */
2248     while (!isspace(*secLastParamPtr))
2249        secLastParamPtr--;
2250     secLastParamPtr++;
2251    
2252     if (secLastParamPtr + 3 > bounds) {
2253        dbgPrintf("secLastParamPtr going over boundary");
2254        fclose(grubConf);
2255        free(line);
2256        return 1;
2257     }
2258     dbgPrintf("secLastParamPtr: %s\n", secLastParamPtr);
2259     if (!strncmp(secLastParamPtr, "(hd", 3)) {
2260        secLastParamPtr += 3;
2261        dbgPrintf("secLastParamPtr: %c\n", *secLastParamPtr);
2262        installDeviceNumber = *secLastParamPtr;
2263     } else {
2264        installDeviceNumber = *lastParamPtr;
2265     }
2266    
2267     *devicePtr = malloc(6);
2268     snprintf(*devicePtr, 6, "(hd%c)", installDeviceNumber);
2269     dbgPrintf("installDeviceNumber: %c\n", installDeviceNumber);
2270     fclose(grubConf);
2271     free(line);
2272     return 0;
2273        }
2274    
2275        free(line);
2276        fclose(grubConf);
2277        return 1;
2278    }
2279    
2280    int grubGetBootFromDeviceMap(const char * device,
2281         char ** bootPtr) {
2282        FILE * deviceMap;
2283        char * line = NULL;
2284        size_t res = 0, len = 0;
2285        char * devicePtr;
2286        char * bounds = NULL;
2287        const char * path;
2288        const static char default_path[] = "/boot/grub/device.map";
2289    
2290        if (!device) return 1;
2291        if (!bootPtr) return 1;
2292    
2293        if ((path = getenv("GRUBBY_GRUB_DEVICE_MAP")) == NULL)
2294     path = default_path;
2295    
2296        dbgPrintf("opening grub device.map file from: %s\n", path);
2297        deviceMap = fopen(path, "r");
2298        if (!deviceMap)
2299     return 1;
2300    
2301        while ((res = getline(&line, &len, deviceMap)) != -1) {
2302            if (!strncmp(line, "#", 1))
2303        continue;
2304    
2305     if (line[res - 1] == '\n')
2306        line[res - 1] = '\0';
2307     else if (len > res)
2308        line[res] = '\0';
2309     else {
2310        line = realloc(line, res + 1);
2311        line[res] = '\0';
2312     }
2313    
2314     devicePtr = line;
2315     bounds = line + res;
2316    
2317     while ((isspace(*line) && ((devicePtr + 1) <= bounds)))
2318        devicePtr++;
2319     dbgPrintf("device: %s\n", devicePtr);
2320    
2321     if (!strncmp(devicePtr, device, strlen(device))) {
2322        devicePtr += strlen(device);
2323        while (isspace(*devicePtr) && ((devicePtr + 1) <= bounds))
2324            devicePtr++;
2325    
2326        *bootPtr = strdup(devicePtr);
2327        break;
2328     }
2329        }
2330    
2331        free(line);
2332        fclose(deviceMap);
2333        return 0;
2334    }
2335    
2336    int suseGrubConfGetBoot(const char * path, char ** bootPtr) {
2337        char * grubDevice;
2338    
2339        if (suseGrubConfGetInstallDevice(path, &grubDevice))
2340     dbgPrintf("error looking for grub installation device\n");
2341        else
2342     dbgPrintf("grubby installation device: %s\n", grubDevice);
2343    
2344        if (grubGetBootFromDeviceMap(grubDevice, bootPtr))
2345     dbgPrintf("error looking for grub boot device\n");
2346        else
2347     dbgPrintf("grubby boot device: %s\n", *bootPtr);
2348    
2349        free(grubDevice);
2350        return 0;
2351    }
2352    
2353    int parseSuseGrubConf(int * lbaPtr, char ** bootPtr) {
2354        /*
2355         * This SuSE grub configuration file at this location is not your average
2356         * grub configuration file, but instead the grub commands used to setup
2357         * grub on that system.
2358         */
2359        const char * path;
2360        const static char default_path[] = "/etc/grub.conf";
2361    
2362        if ((path = getenv("GRUBBY_SUSE_GRUB_CONF")) == NULL)
2363     path = default_path;
2364    
2365        if (!isSuseGrubConf(path)) return 1;
2366    
2367        if (lbaPtr) {
2368            *lbaPtr = 0;
2369            if (suseGrubConfGetLba(path, lbaPtr))
2370                return 1;
2371        }
2372    
2373        if (bootPtr) {
2374            *bootPtr = NULL;
2375            suseGrubConfGetBoot(path, bootPtr);
2376        }
2377    
2378        return 0;
2379  }  }
2380    
2381  int parseSysconfigGrub(int * lbaPtr, char ** bootPtr) {  int parseSysconfigGrub(int * lbaPtr, char ** bootPtr) {
# Line 1813  int parseSysconfigGrub(int * lbaPtr, cha Line 2426  int parseSysconfigGrub(int * lbaPtr, cha
2426  }  }
2427    
2428  void dumpSysconfigGrub(void) {  void dumpSysconfigGrub(void) {
2429      char * boot;      char * boot = NULL;
2430      int lba;      int lba;
2431    
2432      if (!parseSysconfigGrub(&lba, &boot)) {      if (isSuseSystem()) {
2433   if (lba) printf("lba\n");          if (parseSuseGrubConf(&lba, &boot)) {
2434   if (boot) printf("boot=%s\n", boot);      free(boot);
2435        return;
2436     }
2437        } else {
2438            if (parseSysconfigGrub(&lba, &boot)) {
2439        free(boot);
2440        return;
2441     }
2442        }
2443    
2444        if (lba) printf("lba\n");
2445        if (boot) {
2446     printf("boot=%s\n", boot);
2447     free(boot);
2448      }      }
2449  }  }
2450    
# Line 1867  struct singleLine * addLineTmpl(struct s Line 2493  struct singleLine * addLineTmpl(struct s
2493  {  {
2494      struct singleLine * newLine = lineDup(tmplLine);      struct singleLine * newLine = lineDup(tmplLine);
2495    
2496        if (isEfi && cfi == &grub2ConfigType) {
2497     enum lineType_e old = newLine->type;
2498     newLine->type = preferredLineType(newLine->type, cfi);
2499     if (old != newLine->type)
2500        newLine->elements[0].item = getKeyByType(newLine->type, cfi);
2501        }
2502    
2503      if (val) {      if (val) {
2504   /* override the inherited value with our own.   /* override the inherited value with our own.
2505   * 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 1876  struct singleLine * addLineTmpl(struct s Line 2509  struct singleLine * addLineTmpl(struct s
2509   insertElement(newLine, val, 1, cfi);   insertElement(newLine, val, 1, cfi);
2510    
2511   /* but try to keep the rootspec from the template... sigh */   /* but try to keep the rootspec from the template... sigh */
2512   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)) {
2513      char * rootspec = getRootSpecifier(tmplLine->elements[1].item);      char * rootspec = getRootSpecifier(tmplLine->elements[1].item);
2514      if (rootspec != NULL) {      if (rootspec != NULL) {
2515   free(newLine->elements[1].item);   free(newLine->elements[1].item);
# Line 1913  struct singleLine *  addLine(struct sing Line 2546  struct singleLine *  addLine(struct sing
2546      /* 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
2547       * stack since it calls addLineTmpl which will make copies.       * stack since it calls addLineTmpl which will make copies.
2548       */       */
   
2549      if (type == LT_TITLE && cfi->titleBracketed) {      if (type == LT_TITLE && cfi->titleBracketed) {
2550   /* we're doing a bracketed title (zipl) */   /* we're doing a bracketed title (zipl) */
2551   tmpl.type = type;   tmpl.type = type;
# Line 2017  void removeLine(struct singleEntry * ent Line 2649  void removeLine(struct singleEntry * ent
2649      free(line);      free(line);
2650  }  }
2651    
 static int isquote(char q)  
 {  
     if (q == '\'' || q == '\"')  
  return 1;  
     return 0;  
 }  
   
2652  static void requote(struct singleLine *tmplLine, struct configFileInfo * cfi)  static void requote(struct singleLine *tmplLine, struct configFileInfo * cfi)
2653  {  {
2654      struct singleLine newLine = {      struct singleLine newLine = {
# Line 2254  int updateActualImage(struct grubConfig Line 2879  int updateActualImage(struct grubConfig
2879      firstElement = 2;      firstElement = 2;
2880    
2881   } else {   } else {
2882      line = getLineByType(LT_KERNEL|LT_MBMODULE, entry->lines);      line = getLineByType(LT_KERNEL|LT_MBMODULE|LT_KERNEL_EFI, entry->lines);
2883      if (!line) {      if (!line) {
2884   /* no LT_KERNEL or LT_MBMODULE in this entry? */   /* no LT_KERNEL or LT_MBMODULE in this entry? */
2885   continue;   continue;
# Line 2419  int updateInitrd(struct grubConfig * cfg Line 3044  int updateInitrd(struct grubConfig * cfg
3044      if (!image) return 0;      if (!image) return 0;
3045    
3046      for (; (entry = findEntryByPath(cfg, image, prefix, &index)); index++) {      for (; (entry = findEntryByPath(cfg, image, prefix, &index)); index++) {
3047          kernelLine = getLineByType(LT_KERNEL, entry->lines);          kernelLine = getLineByType(LT_KERNEL|LT_KERNEL_EFI, entry->lines);
3048          if (!kernelLine) continue;          if (!kernelLine) continue;
3049    
3050          line = getLineByType(LT_INITRD, entry->lines);          line = getLineByType(LT_INITRD|LT_INITRD_EFI, entry->lines);
3051          if (line)          if (line)
3052              removeLine(entry, line);              removeLine(entry, line);
3053          if (prefix) {          if (prefix) {
# Line 2433  int updateInitrd(struct grubConfig * cfg Line 3058  int updateInitrd(struct grubConfig * cfg
3058   endLine = getLineByType(LT_ENTRY_END, entry->lines);   endLine = getLineByType(LT_ENTRY_END, entry->lines);
3059   if (endLine)   if (endLine)
3060      removeLine(entry, endLine);      removeLine(entry, endLine);
3061          line = addLine(entry, cfg->cfi, LT_INITRD, kernelLine->indent, initrd);          line = addLine(entry, cfg->cfi, preferredLineType(LT_INITRD, cfg->cfi),
3062     kernelLine->indent, initrd);
3063          if (!line)          if (!line)
3064      return 1;      return 1;
3065   if (endLine) {   if (endLine) {
# Line 2639  int checkForGrub(struct grubConfig * con Line 3265  int checkForGrub(struct grubConfig * con
3265      int fd;      int fd;
3266      unsigned char bootSect[512];      unsigned char bootSect[512];
3267      char * boot;      char * boot;
3268        int onSuse = isSuseSystem();
3269    
3270      if (parseSysconfigGrub(NULL, &boot))  
3271   return 0;      if (onSuse) {
3272     if (parseSuseGrubConf(NULL, &boot))
3273        return 0;
3274        } else {
3275     if (parseSysconfigGrub(NULL, &boot))
3276        return 0;
3277        }
3278    
3279      /* assume grub is not installed -- not an error condition */      /* assume grub is not installed -- not an error condition */
3280      if (!boot)      if (!boot)
# Line 2660  int checkForGrub(struct grubConfig * con Line 3293  int checkForGrub(struct grubConfig * con
3293      }      }
3294      close(fd);      close(fd);
3295    
3296        /* The more elaborate checks do not work on SuSE. The checks done
3297         * seem to be reasonble (at least for now), so just return success
3298         */
3299        if (onSuse)
3300     return 2;
3301    
3302      return checkDeviceBootloader(boot, bootSect);      return checkDeviceBootloader(boot, bootSect);
3303  }  }
3304    
# Line 2693  int checkForExtLinux(struct grubConfig * Line 3332  int checkForExtLinux(struct grubConfig *
3332      return checkDeviceBootloader(boot, bootSect);      return checkDeviceBootloader(boot, bootSect);
3333  }  }
3334    
3335    int checkForYaboot(struct grubConfig * config) {
3336        /*
3337         * This is a simplistic check that we consider good enough for own puporses
3338         *
3339         * If we were to properly check if yaboot is *installed* we'd need to:
3340         * 1) get the system boot device (LT_BOOT)
3341         * 2) considering it's a raw filesystem, check if the yaboot binary matches
3342         *    the content on the boot device
3343         * 3) if not, copy the binary to a temporary file and run "addnote" on it
3344         * 4) check again if binary and boot device contents match
3345         */
3346        if (!access("/etc/yaboot.conf", R_OK))
3347     return 2;
3348    
3349        return 1;
3350    }
3351    
3352    int checkForElilo(struct grubConfig * config) {
3353        if (!access("/etc/elilo.conf", R_OK))
3354     return 2;
3355    
3356        return 1;
3357    }
3358    
3359  static char * getRootSpecifier(char * str) {  static char * getRootSpecifier(char * str) {
3360      char * idx, * rootspec = NULL;      char * idx, * rootspec = NULL;
3361    
# Line 2707  static char * getRootSpecifier(char * st Line 3370  static char * getRootSpecifier(char * st
3370  static char * getInitrdVal(struct grubConfig * config,  static char * getInitrdVal(struct grubConfig * config,
3371     const char * prefix, struct singleLine *tmplLine,     const char * prefix, struct singleLine *tmplLine,
3372     const char * newKernelInitrd,     const char * newKernelInitrd,
3373     char ** extraInitrds, int extraInitrdCount)     const char ** extraInitrds, int extraInitrdCount)
3374  {  {
3375      char *initrdVal, *end;      char *initrdVal, *end;
3376      int i;      int i;
# Line 2752  static char * getInitrdVal(struct grubCo Line 3415  static char * getInitrdVal(struct grubCo
3415    
3416  int addNewKernel(struct grubConfig * config, struct singleEntry * template,  int addNewKernel(struct grubConfig * config, struct singleEntry * template,
3417           const char * prefix,           const char * prefix,
3418   char * newKernelPath, char * newKernelTitle,   const char * newKernelPath, const char * newKernelTitle,
3419   char * newKernelArgs, char * newKernelInitrd,   const char * newKernelArgs, const char * newKernelInitrd,
3420   char ** extraInitrds, int extraInitrdCount,   const char ** extraInitrds, int extraInitrdCount,
3421                   char * newMBKernel, char * newMBKernelArgs) {                   const char * newMBKernel, const char * newMBKernelArgs) {
3422      struct singleEntry * new;      struct singleEntry * new;
3423      struct singleLine * newLine = NULL, * tmplLine = NULL, * masterLine = NULL;      struct singleLine * newLine = NULL, * tmplLine = NULL, * masterLine = NULL;
3424      int needs;      int needs;
# Line 2809  int addNewKernel(struct grubConfig * con Line 3472  int addNewKernel(struct grubConfig * con
3472      while (*chptr && isspace(*chptr)) chptr++;      while (*chptr && isspace(*chptr)) chptr++;
3473      if (*chptr == '#') continue;      if (*chptr == '#') continue;
3474    
3475      if (tmplLine->type == LT_KERNEL &&      if (iskernel(tmplLine->type) && tmplLine->numElements >= 2) {
     tmplLine->numElements >= 2) {  
3476   if (!template->multiboot && (needs & NEED_MB)) {   if (!template->multiboot && (needs & NEED_MB)) {
3477      /* it's not a multiboot template and this is the kernel      /* it's not a multiboot template and this is the kernel
3478       * line.  Try to be intelligent about inserting the       * line.  Try to be intelligent about inserting the
# Line 2887  int addNewKernel(struct grubConfig * con Line 3549  int addNewKernel(struct grubConfig * con
3549      /* template is multi but new is not,      /* template is multi but new is not,
3550       * insert the kernel in the first module slot       * insert the kernel in the first module slot
3551       */       */
3552      tmplLine->type = LT_KERNEL;      tmplLine->type = preferredLineType(LT_KERNEL, config->cfi);
3553      free(tmplLine->elements[0].item);      free(tmplLine->elements[0].item);
3554      tmplLine->elements[0].item =      tmplLine->elements[0].item =
3555   strdup(getKeywordByType(LT_KERNEL, config->cfi)->key);   strdup(getKeywordByType(tmplLine->type,
3556     config->cfi)->key);
3557      newLine = addLineTmpl(new, tmplLine, newLine,      newLine = addLineTmpl(new, tmplLine, newLine,
3558    newKernelPath + strlen(prefix), config->cfi);    newKernelPath + strlen(prefix),
3559      config->cfi);
3560      needs &= ~NEED_KERNEL;      needs &= ~NEED_KERNEL;
3561   } else if (needs & NEED_INITRD) {   } else if (needs & NEED_INITRD) {
3562      char *initrdVal;      char *initrdVal;
3563      /* template is multi but new is not,      /* template is multi but new is not,
3564       * insert the initrd in the second module slot       * insert the initrd in the second module slot
3565       */       */
3566      tmplLine->type = LT_INITRD;      tmplLine->type = preferredLineType(LT_INITRD, config->cfi);
3567      free(tmplLine->elements[0].item);      free(tmplLine->elements[0].item);
3568      tmplLine->elements[0].item =      tmplLine->elements[0].item =
3569   strdup(getKeywordByType(LT_INITRD, config->cfi)->key);   strdup(getKeywordByType(tmplLine->type,
3570     config->cfi)->key);
3571      initrdVal = getInitrdVal(config, prefix, tmplLine, newKernelInitrd, extraInitrds, extraInitrdCount);      initrdVal = getInitrdVal(config, prefix, tmplLine, newKernelInitrd, extraInitrds, extraInitrdCount);
3572      newLine = addLineTmpl(new, tmplLine, newLine, initrdVal, config->cfi);      newLine = addLineTmpl(new, tmplLine, newLine, initrdVal, config->cfi);
3573      free(initrdVal);      free(initrdVal);
3574      needs &= ~NEED_INITRD;      needs &= ~NEED_INITRD;
3575   }   }
3576    
3577      } else if (tmplLine->type == LT_INITRD &&      } else if (isinitrd(tmplLine->type) && tmplLine->numElements >= 2) {
        tmplLine->numElements >= 2) {  
3578   if (needs & NEED_INITRD &&   if (needs & NEED_INITRD &&
3579      new->multiboot && !template->multiboot &&      new->multiboot && !template->multiboot &&
3580      config->cfi->mbInitRdIsModule) {      config->cfi->mbInitRdIsModule) {
# Line 2961  int addNewKernel(struct grubConfig * con Line 3625  int addNewKernel(struct grubConfig * con
3625   }   }
3626      } else if (tmplLine->type == LT_ECHO) {      } else if (tmplLine->type == LT_ECHO) {
3627      requote(tmplLine, config->cfi);      requote(tmplLine, config->cfi);
3628        static const char *prefix = "'Loading ";
3629      if (tmplLine->numElements > 1 &&      if (tmplLine->numElements > 1 &&
3630      strstr(tmplLine->elements[1].item, "'Loading Linux ")) {      strstr(tmplLine->elements[1].item, prefix) &&
3631   char *prefix = "'Loading ";      masterLine->next &&
3632        iskernel(masterLine->next->type)) {
3633   char *newTitle = malloc(strlen(prefix) +   char *newTitle = malloc(strlen(prefix) +
3634   strlen(newKernelTitle) + 2);   strlen(newKernelTitle) + 2);
3635    
# Line 2990  int addNewKernel(struct grubConfig * con Line 3656  int addNewKernel(struct grubConfig * con
3656   */   */
3657   switch (config->cfi->entryStart) {   switch (config->cfi->entryStart) {
3658      case LT_KERNEL:      case LT_KERNEL:
3659        case LT_KERNEL_EFI:
3660   if (new->multiboot && config->cfi->mbHyperFirst) {   if (new->multiboot && config->cfi->mbHyperFirst) {
3661      /* fall through to LT_HYPER */      /* fall through to LT_HYPER */
3662   } else {   } else {
3663      newLine = addLine(new, config->cfi, LT_KERNEL,      newLine = addLine(new, config->cfi,
3664              preferredLineType(LT_KERNEL, config->cfi),
3665        config->primaryIndent,        config->primaryIndent,
3666        newKernelPath + strlen(prefix));        newKernelPath + strlen(prefix));
3667      needs &= ~NEED_KERNEL;      needs &= ~NEED_KERNEL;
# Line 3069  int addNewKernel(struct grubConfig * con Line 3737  int addNewKernel(struct grubConfig * con
3737      if (needs & NEED_KERNEL) {      if (needs & NEED_KERNEL) {
3738   newLine = addLine(new, config->cfi,   newLine = addLine(new, config->cfi,
3739    (new->multiboot && getKeywordByType(LT_MBMODULE,    (new->multiboot && getKeywordByType(LT_MBMODULE,
3740        config->cfi)) ?        config->cfi))
3741    LT_MBMODULE : LT_KERNEL,     ? LT_MBMODULE
3742     : preferredLineType(LT_KERNEL, config->cfi),
3743    config->secondaryIndent,    config->secondaryIndent,
3744    newKernelPath + strlen(prefix));    newKernelPath + strlen(prefix));
3745   needs &= ~NEED_KERNEL;   needs &= ~NEED_KERNEL;
# Line 3086  int addNewKernel(struct grubConfig * con Line 3755  int addNewKernel(struct grubConfig * con
3755   initrdVal = getInitrdVal(config, prefix, NULL, newKernelInitrd, extraInitrds, extraInitrdCount);   initrdVal = getInitrdVal(config, prefix, NULL, newKernelInitrd, extraInitrds, extraInitrdCount);
3756   newLine = addLine(new, config->cfi,   newLine = addLine(new, config->cfi,
3757    (new->multiboot && getKeywordByType(LT_MBMODULE,    (new->multiboot && getKeywordByType(LT_MBMODULE,
3758        config->cfi)) ?        config->cfi))
3759    LT_MBMODULE : LT_INITRD,     ? LT_MBMODULE
3760       : preferredLineType(LT_INITRD, config->cfi),
3761    config->secondaryIndent,    config->secondaryIndent,
3762    initrdVal);    initrdVal);
3763   free(initrdVal);   free(initrdVal);
# Line 3119  static void traceback(int signum) Line 3789  static void traceback(int signum)
3789      memset(array, '\0', sizeof (array));      memset(array, '\0', sizeof (array));
3790      size = backtrace(array, 40);      size = backtrace(array, 40);
3791    
3792      fprintf(stderr, "grubby recieved SIGSEGV!  Backtrace (%ld):\n",      fprintf(stderr, "grubby received SIGSEGV!  Backtrace (%ld):\n",
3793              (unsigned long)size);              (unsigned long)size);
3794      backtrace_symbols_fd(array, size, STDERR_FILENO);      backtrace_symbols_fd(array, size, STDERR_FILENO);
3795      exit(1);      exit(1);
# Line 3161  int main(int argc, const char ** argv) { Line 3831  int main(int argc, const char ** argv) {
3831      int copyDefault = 0, makeDefault = 0;      int copyDefault = 0, makeDefault = 0;
3832      int displayDefault = 0;      int displayDefault = 0;
3833      int displayDefaultIndex = 0;      int displayDefaultIndex = 0;
3834        int displayDefaultTitle = 0;
3835        int defaultIndex = -1;
3836      struct poptOption options[] = {      struct poptOption options[] = {
3837   { "add-kernel", 0, POPT_ARG_STRING, &newKernelPath, 0,   { "add-kernel", 0, POPT_ARG_STRING, &newKernelPath, 0,
3838      _("add an entry for the specified kernel"), _("kernel-path") },      _("add an entry for the specified kernel"), _("kernel-path") },
# Line 3178  int main(int argc, const char ** argv) { Line 3850  int main(int argc, const char ** argv) {
3850   { "boot-filesystem", 0, POPT_ARG_STRING, &bootPrefix, 0,   { "boot-filesystem", 0, POPT_ARG_STRING, &bootPrefix, 0,
3851      _("filestystem which contains /boot directory (for testing only)"),      _("filestystem which contains /boot directory (for testing only)"),
3852      _("bootfs") },      _("bootfs") },
3853  #if defined(__i386__) || defined(__x86_64__)  #if defined(__i386__) || defined(__x86_64__) || defined (__powerpc64__) || defined (__ia64__)
3854   { "bootloader-probe", 0, POPT_ARG_NONE, &bootloaderProbe, 0,   { "bootloader-probe", 0, POPT_ARG_NONE, &bootloaderProbe, 0,
3855      _("check if lilo is installed on lilo.conf boot sector") },      _("check which bootloader is installed on boot sector") },
3856  #endif  #endif
3857   { "config-file", 'c', POPT_ARG_STRING, &grubConfig, 0,   { "config-file", 'c', POPT_ARG_STRING, &grubConfig, 0,
3858      _("path to grub config file to update (\"-\" for stdin)"),      _("path to grub config file to update (\"-\" for stdin)"),
# Line 3191  int main(int argc, const char ** argv) { Line 3863  int main(int argc, const char ** argv) {
3863        "the kernel referenced by the default image does not exist, "        "the kernel referenced by the default image does not exist, "
3864        "the first linux entry whose kernel does exist is used as the "        "the first linux entry whose kernel does exist is used as the "
3865        "template"), NULL },        "template"), NULL },
3866     { "debug", 0, 0, &debug, 0,
3867        _("print debugging information for failures") },
3868   { "default-kernel", 0, 0, &displayDefault, 0,   { "default-kernel", 0, 0, &displayDefault, 0,
3869      _("display the path of the default kernel") },      _("display the path of the default kernel") },
3870   { "default-index", 0, 0, &displayDefaultIndex, 0,   { "default-index", 0, 0, &displayDefaultIndex, 0,
3871      _("display the index of the default kernel") },      _("display the index of the default kernel") },
3872     { "default-title", 0, 0, &displayDefaultTitle, 0,
3873        _("display the title of the default kernel") },
3874   { "elilo", 0, POPT_ARG_NONE, &configureELilo, 0,   { "elilo", 0, POPT_ARG_NONE, &configureELilo, 0,
3875      _("configure elilo bootloader") },      _("configure elilo bootloader") },
3876     { "efi", 0, POPT_ARG_NONE, &isEfi, 0,
3877        _("force grub2 stanzas to use efi") },
3878   { "extlinux", 0, POPT_ARG_NONE, &configureExtLinux, 0,   { "extlinux", 0, POPT_ARG_NONE, &configureExtLinux, 0,
3879      _("configure extlinux bootloader (from syslinux)") },      _("configure extlinux bootloader (from syslinux)") },
3880   { "grub", 0, POPT_ARG_NONE, &configureGrub, 0,   { "grub", 0, POPT_ARG_NONE, &configureGrub, 0,
# Line 3209  int main(int argc, const char ** argv) { Line 3887  int main(int argc, const char ** argv) {
3887   { "initrd", 0, POPT_ARG_STRING, &newKernelInitrd, 0,   { "initrd", 0, POPT_ARG_STRING, &newKernelInitrd, 0,
3888      _("initrd image for the new kernel"), _("initrd-path") },      _("initrd image for the new kernel"), _("initrd-path") },
3889   { "extra-initrd", 'i', POPT_ARG_STRING, NULL, 'i',   { "extra-initrd", 'i', POPT_ARG_STRING, NULL, 'i',
3890      _("auxilliary initrd image for things other than the new kernel"), _("initrd-path") },      _("auxiliary initrd image for things other than the new kernel"), _("initrd-path") },
3891   { "lilo", 0, POPT_ARG_NONE, &configureLilo, 0,   { "lilo", 0, POPT_ARG_NONE, &configureLilo, 0,
3892      _("configure lilo bootloader") },      _("configure lilo bootloader") },
3893   { "make-default", 0, 0, &makeDefault, 0,   { "make-default", 0, 0, &makeDefault, 0,
# Line 3229  int main(int argc, const char ** argv) { Line 3907  int main(int argc, const char ** argv) {
3907   { "set-default", 0, POPT_ARG_STRING, &defaultKernel, 0,   { "set-default", 0, POPT_ARG_STRING, &defaultKernel, 0,
3908      _("make the first entry referencing the specified kernel "      _("make the first entry referencing the specified kernel "
3909        "the default"), _("kernel-path") },        "the default"), _("kernel-path") },
3910     { "set-default-index", 0, POPT_ARG_INT, &defaultIndex, 0,
3911        _("make the given entry index the default entry"),
3912        _("entry-index") },
3913   { "silo", 0, POPT_ARG_NONE, &configureSilo, 0,   { "silo", 0, POPT_ARG_NONE, &configureSilo, 0,
3914      _("configure silo bootloader") },      _("configure silo bootloader") },
3915   { "title", 0, POPT_ARG_STRING, &newKernelTitle, 0,   { "title", 0, POPT_ARG_STRING, &newKernelTitle, 0,
# Line 3250  int main(int argc, const char ** argv) { Line 3931  int main(int argc, const char ** argv) {
3931    
3932      signal(SIGSEGV, traceback);      signal(SIGSEGV, traceback);
3933    
3934        int i = 0;
3935        for (int j = 1; j < argc; j++)
3936     i += strlen(argv[j]) + 1;
3937        saved_command_line = malloc(i);
3938        if (!saved_command_line) {
3939     fprintf(stderr, "grubby: %m\n");
3940     exit(1);
3941        }
3942        saved_command_line[0] = '\0';
3943        for (int j = 1; j < argc; j++) {
3944     strcat(saved_command_line, argv[j]);
3945     strncat(saved_command_line, j == argc -1 ? "" : " ", 1);
3946        }
3947    
3948      optCon = poptGetContext("grubby", argc, argv, options, 0);      optCon = poptGetContext("grubby", argc, argv, options, 0);
3949      poptReadDefaultConfig(optCon, 1);      poptReadDefaultConfig(optCon, 1);
3950    
# Line 3311  int main(int argc, const char ** argv) { Line 4006  int main(int argc, const char ** argv) {
4006      }      }
4007    
4008      if (!cfi) {      if (!cfi) {
4009            if (grub2FindConfig(&grub2ConfigType))
4010        cfi = &grub2ConfigType;
4011     else
4012        #ifdef __ia64__        #ifdef __ia64__
4013   cfi = &eliloConfigType;      cfi = &eliloConfigType;
4014        #elif __powerpc__        #elif __powerpc__
4015   cfi = &yabootConfigType;      cfi = &yabootConfigType;
4016        #elif __sparc__        #elif __sparc__
4017          cfi = &siloConfigType;              cfi = &siloConfigType;
4018        #elif __s390__        #elif __s390__
4019          cfi = &ziplConfigType;              cfi = &ziplConfigType;
4020        #elif __s390x__        #elif __s390x__
4021          cfi = &ziplConfigtype;              cfi = &ziplConfigtype;
4022        #else        #else
         if (grub2FindConfig(&grub2ConfigType))  
     cfi = &grub2ConfigType;  
  else  
4023      cfi = &grubConfigType;      cfi = &grubConfigType;
4024        #endif        #endif
4025      }      }
# Line 3337  int main(int argc, const char ** argv) { Line 4032  int main(int argc, const char ** argv) {
4032      }      }
4033    
4034      if (bootloaderProbe && (displayDefault || kernelInfo || newKernelVersion ||      if (bootloaderProbe && (displayDefault || kernelInfo || newKernelVersion ||
4035    newKernelPath || removeKernelPath || makeDefault ||      newKernelPath || removeKernelPath || makeDefault ||
4036    defaultKernel || displayDefaultIndex)) {      defaultKernel || displayDefaultIndex || displayDefaultTitle ||
4037        (defaultIndex >= 0))) {
4038   fprintf(stderr, _("grubby: --bootloader-probe may not be used with "   fprintf(stderr, _("grubby: --bootloader-probe may not be used with "
4039    "specified option"));    "specified option"));
4040   return 1;   return 1;
# Line 3380  int main(int argc, const char ** argv) { Line 4076  int main(int argc, const char ** argv) {
4076   makeDefault = 1;   makeDefault = 1;
4077   defaultKernel = NULL;   defaultKernel = NULL;
4078      }      }
4079        else if (defaultKernel && (defaultIndex >= 0)) {
4080     fprintf(stderr, _("grubby: --set-default and --set-default-index "
4081      "may not be used together\n"));
4082     return 1;
4083        }
4084    
4085      if (grubConfig && !strcmp(grubConfig, "-") && !outputFile) {      if (grubConfig && !strcmp(grubConfig, "-") && !outputFile) {
4086   fprintf(stderr, _("grubby: output file must be specified if stdin "   fprintf(stderr, _("grubby: output file must be specified if stdin "
# Line 3388  int main(int argc, const char ** argv) { Line 4089  int main(int argc, const char ** argv) {
4089      }      }
4090    
4091      if (!removeKernelPath && !newKernelPath && !displayDefault && !defaultKernel      if (!removeKernelPath && !newKernelPath && !displayDefault && !defaultKernel
4092   && !kernelInfo && !bootloaderProbe && !updateKernelPath   && !kernelInfo && !bootloaderProbe && !updateKernelPath
4093          && !removeMBKernel && !displayDefaultIndex) {   && !removeMBKernel && !displayDefaultIndex && !displayDefaultTitle
4094     && (defaultIndex == -1)) {
4095   fprintf(stderr, _("grubby: no action specified\n"));   fprintf(stderr, _("grubby: no action specified\n"));
4096   return 1;   return 1;
4097      }      }
# Line 3416  int main(int argc, const char ** argv) { Line 4118  int main(int argc, const char ** argv) {
4118      }      }
4119    
4120      if (bootloaderProbe) {      if (bootloaderProbe) {
4121   int lrc = 0, grc = 0, gr2c = 0, erc = 0;   int lrc = 0, grc = 0, gr2c = 0, extrc = 0, yrc = 0, erc = 0;
4122   struct grubConfig * lconfig, * gconfig;   struct grubConfig * lconfig, * gconfig, * yconfig, * econfig;
4123    
4124   const char *grub2config = grub2FindConfig(&grub2ConfigType);   const char *grub2config = grub2FindConfig(&grub2ConfigType);
4125   if (grub2config) {   if (grub2config) {
# Line 3445  int main(int argc, const char ** argv) { Line 4147  int main(int argc, const char ** argv) {
4147   lrc = checkForLilo(lconfig);   lrc = checkForLilo(lconfig);
4148   }   }
4149    
4150     if (!access(eliloConfigType.defaultConfig, F_OK)) {
4151        econfig = readConfig(eliloConfigType.defaultConfig,
4152     &eliloConfigType);
4153        if (!econfig)
4154     erc = 1;
4155        else
4156     erc = checkForElilo(econfig);
4157     }
4158    
4159   if (!access(extlinuxConfigType.defaultConfig, F_OK)) {   if (!access(extlinuxConfigType.defaultConfig, F_OK)) {
4160      lconfig = readConfig(extlinuxConfigType.defaultConfig, &extlinuxConfigType);      lconfig = readConfig(extlinuxConfigType.defaultConfig, &extlinuxConfigType);
4161      if (!lconfig)      if (!lconfig)
4162   erc = 1;   extrc = 1;
4163      else      else
4164   erc = checkForExtLinux(lconfig);   extrc = checkForExtLinux(lconfig);
4165   }   }
4166    
4167   if (lrc == 1 || grc == 1 || gr2c == 1) return 1;  
4168     if (!access(yabootConfigType.defaultConfig, F_OK)) {
4169        yconfig = readConfig(yabootConfigType.defaultConfig,
4170     &yabootConfigType);
4171        if (!yconfig)
4172     yrc = 1;
4173        else
4174     yrc = checkForYaboot(yconfig);
4175     }
4176    
4177     if (lrc == 1 || grc == 1 || gr2c == 1 || extrc == 1 || yrc == 1 ||
4178     erc == 1)
4179        return 1;
4180    
4181   if (lrc == 2) printf("lilo\n");   if (lrc == 2) printf("lilo\n");
4182   if (gr2c == 2) printf("grub2\n");   if (gr2c == 2) printf("grub2\n");
4183   if (grc == 2) printf("grub\n");   if (grc == 2) printf("grub\n");
4184   if (erc == 2) printf("extlinux\n");   if (extrc == 2) printf("extlinux\n");
4185     if (yrc == 2) printf("yaboot\n");
4186     if (erc == 2) printf("elilo\n");
4187    
4188   return 0;   return 0;
4189      }      }
# Line 3476  int main(int argc, const char ** argv) { Line 4201  int main(int argc, const char ** argv) {
4201   if (!entry) return 0;   if (!entry) return 0;
4202   if (!suitableImage(entry, bootPrefix, 0, flags)) return 0;   if (!suitableImage(entry, bootPrefix, 0, flags)) return 0;
4203    
4204   line = getLineByType(LT_KERNEL|LT_HYPER, entry->lines);   line = getLineByType(LT_KERNEL|LT_HYPER|LT_KERNEL_EFI, entry->lines);
4205   if (!line) return 0;   if (!line) return 0;
4206    
4207          rootspec = getRootSpecifier(line->elements[1].item);          rootspec = getRootSpecifier(line->elements[1].item);
# Line 3485  int main(int argc, const char ** argv) { Line 4210  int main(int argc, const char ** argv) {
4210    
4211   return 0;   return 0;
4212    
4213        } else if (displayDefaultTitle) {
4214     struct singleLine * line;
4215     struct singleEntry * entry;
4216    
4217     if (config->defaultImage == -1) return 0;
4218     entry = findEntryByIndex(config, config->defaultImage);
4219     if (!entry) return 0;
4220    
4221     if (!configureGrub2) {
4222      line = getLineByType(LT_TITLE, entry->lines);
4223      if (!line) return 0;
4224      printf("%s\n", line->elements[1].item);
4225    
4226     } else {
4227      char * title;
4228    
4229      dbgPrintf("This is GRUB2, default title is embeded in menuentry\n");
4230      line = getLineByType(LT_MENUENTRY, entry->lines);
4231      if (!line) return 0;
4232      title = grub2ExtractTitle(line);
4233      if (title)
4234        printf("%s\n", title);
4235     }
4236     return 0;
4237    
4238      } else if (displayDefaultIndex) {      } else if (displayDefaultIndex) {
4239          if (config->defaultImage == -1) return 0;          if (config->defaultImage == -1) return 0;
4240          printf("%i\n", config->defaultImage);          printf("%i\n", config->defaultImage);
# Line 3500  int main(int argc, const char ** argv) { Line 4250  int main(int argc, const char ** argv) {
4250      markRemovedImage(config, removeKernelPath, bootPrefix);      markRemovedImage(config, removeKernelPath, bootPrefix);
4251      markRemovedImage(config, removeMBKernel, bootPrefix);      markRemovedImage(config, removeMBKernel, bootPrefix);
4252      setDefaultImage(config, newKernelPath != NULL, defaultKernel, makeDefault,      setDefaultImage(config, newKernelPath != NULL, defaultKernel, makeDefault,
4253      bootPrefix, flags);      bootPrefix, flags, defaultIndex);
4254      setFallbackImage(config, newKernelPath != NULL);      setFallbackImage(config, newKernelPath != NULL);
4255      if (updateImage(config, updateKernelPath, bootPrefix, newKernelArgs,      if (updateImage(config, updateKernelPath, bootPrefix, newKernelArgs,
4256                      removeArgs, newMBKernelArgs, removeMBKernelArgs)) return 1;                      removeArgs, newMBKernelArgs, removeMBKernelArgs)) return 1;
# Line 3510  int main(int argc, const char ** argv) { Line 4260  int main(int argc, const char ** argv) {
4260      }      }
4261      if (addNewKernel(config, template, bootPrefix, newKernelPath,      if (addNewKernel(config, template, bootPrefix, newKernelPath,
4262                       newKernelTitle, newKernelArgs, newKernelInitrd,                       newKernelTitle, newKernelArgs, newKernelInitrd,
4263                       extraInitrds, extraInitrdCount,                       (const char **)extraInitrds, extraInitrdCount,
4264                       newMBKernel, newMBKernelArgs)) return 1;                       newMBKernel, newMBKernelArgs)) return 1;
4265            
4266    

Legend:
Removed from v.1720  
changed lines
  Added in v.2236