From d0bf58c1c71a1e192fa955e9786432bcdcb31bf1 Mon Sep 17 00:00:00 2001
From: Andrei Borzenkov <arvidjaar@gmail.com>
Date: Thu, 7 May 2015 20:24:24 +0300
Subject: [PATCH 197/237] loader/linux: do not pad initrd with zeroes at the
 end

Syslinux memdisk is using initrd image and needs to know uncompressed
size in advance. For gzip uncompressed size is at the end of compressed
stream. Grub padded each input file to 4 bytes at the end, which means
syslinux got wrong size.

Linux initramfs loader apparently does not care about trailing alignment.
So change code to align beginning of each file instead which atomatically
gives us the correct size for single file.

Reported-By: David Shaw <dshaw@jabberwocky.com>

(cherry picked from commit a8c473288d3f0a5e17a903a5121dea1a695dda3b)

Resolves: rhbz#1219864
---
 grub-core/loader/linux.c | 11 +++++++----
 1 file changed, 7 insertions(+), 4 deletions(-)

diff --git a/grub-core/loader/linux.c b/grub-core/loader/linux.c
index 117232f..d2cd591 100644
--- a/grub-core/loader/linux.c
+++ b/grub-core/loader/linux.c
@@ -161,6 +161,9 @@ grub_initrd_init (int argc, char *argv[],
   for (i = 0; i < argc; i++)
     {
       const char *fname = argv[i];
+
+      initrd_ctx->size = ALIGN_UP (initrd_ctx->size, 4);
+
       if (grub_memcmp (argv[i], "newc:", 5) == 0)
 	{
 	  const char *ptr, *eptr;
@@ -205,7 +208,7 @@ grub_initrd_init (int argc, char *argv[],
       initrd_ctx->nfiles++;
       initrd_ctx->components[i].size
 	= grub_file_size (initrd_ctx->components[i].file);
-      initrd_ctx->size += ALIGN_UP (initrd_ctx->components[i].size, 4);
+      initrd_ctx->size += initrd_ctx->components[i].size;
     }
 
   if (newc)
@@ -248,10 +251,12 @@ grub_initrd_load (struct grub_linux_initrd_context *initrd_ctx,
   int i;
   int newc = 0;
   struct dir *root = 0;
+  grub_ssize_t cursize = 0;
 
   for (i = 0; i < initrd_ctx->nfiles; i++)
     {
-      grub_ssize_t cursize;
+      grub_memset (ptr, 0, ALIGN_UP_OVERHEAD (cursize, 4));
+      ptr += ALIGN_UP_OVERHEAD (cursize, 4);
 
       if (initrd_ctx->components[i].newc_name)
 	{
@@ -283,8 +288,6 @@ grub_initrd_load (struct grub_linux_initrd_context *initrd_ctx,
 	  return grub_errno;
 	}
       ptr += cursize;
-      grub_memset (ptr, 0, ALIGN_UP_OVERHEAD (cursize, 4));
-      ptr += ALIGN_UP_OVERHEAD (cursize, 4);
     }
   if (newc)
     ptr = make_header (ptr, "TRAILER!!!", sizeof ("TRAILER!!!") - 1, 0, 0);
-- 
2.9.3

