Imported Upstream version 3.4
[debian/elilo] / ia64 / gzip.c
1 /*
2  *  Copyright (C) 2001-2003 Hewlett-Packard Co.
3  *      Contributed by Stephane Eranian <eranian@hpl.hp.com>
4  *
5  *  Copyright (C) 2001 Silicon Graphics, Inc.
6  *      Contributed by Brent Casavant <bcasavan@sgi.com>
7  *
8  * This file is part of the ELILO, the EFI Linux boot loader.
9  *
10  *  ELILO is free software; you can redistribute it and/or modify
11  *  it under the terms of the GNU General Public License as published by
12  *  the Free Software Foundation; either version 2, or (at your option)
13  *  any later version.
14  *
15  *  ELILO is distributed in the hope that it will be useful,
16  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
17  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  *  GNU General Public License for more details.
19  *
20  *  You should have received a copy of the GNU General Public License
21  *  along with ELILO; see the file COPYING.  If not, write to the Free
22  *  Software Foundation, 59 Temple Place - Suite 330, Boston, MA
23  *  02111-1307, USA.
24  *
25  * Please check out the elilo.txt for complete documentation on how
26  * to use this program.
27  */
28
29 #include <efi.h>
30 #include <efilib.h>
31
32 #include "elf.h"
33 #include "elilo.h"
34
35 #include "gzip.h"
36
37 #include "private.h"
38 #include "setjmp.h"
39
40 #define memzero(s, n)   Memset((VOID *)(s), 0, (n))
41 #define memcpy(a,b,n)   Memcpy((VOID *)(a),(b),(n))
42
43 /* size of output buffer */
44 #define WSIZE 0x8000            /* Window size must be at least 32k, */
45                                 /* and a power of two */
46 /* size of input buffer */
47 #define INBUFSIZE 0x8000
48
49 /*
50  * gzip declarations
51  */
52
53 #define OF(args)  args
54 #define FUNC_STATIC static
55
56 typedef unsigned char  uch;
57 typedef unsigned short ush;
58 typedef unsigned long  ulg;
59
60
61 typedef struct segment {
62         unsigned long addr;     /* start address */
63         unsigned long offset;   /* file offset   */
64         unsigned long size;     /* file size     */
65         unsigned long bss_sz;   /* BSS size      */
66         UINT8   flags;  /* indicates whether to load or not */
67 } segment_t;
68
69 #define CHUNK_FL_VALID          0x1
70 #define CHUNK_FL_LOAD           0x2
71
72 #define CHUNK_CAN_LOAD(n)       chunks[(n)].flags |= CHUNK_FL_LOAD
73 #define CHUNK_NO_LOAD(n)        chunks[(n)].flags &= ~CHUNK_FL_LOAD
74 #define CHUNK_IS_LOAD(n)        (chunks[(n)].flags & CHUNK_FL_LOAD)
75
76 #define CHUNK_VALIDATE(n)       chunks[(n)].flags |= CHUNK_FL_VALID
77 #define CHUNK_INVALIDATE(n)     chunks[(n)].flags = 0
78 #define CHUNK_IS_VALID(n)       (chunks[(n)].flags & CHUNK_FL_VALID)
79
80 /*
81  * static parameters to gzip helper functions
82  * we cannot use paramters because API was not
83  * designed that way
84  */
85 static segment_t *chunks;       /* holds the list of segments */
86 static segment_t *cur_chunk;
87 static UINTN nchunks;
88 static UINTN chunk;                 /* current segment */
89 static UINTN input_fd;
90 static VOID *kernel_entry, *kernel_base, *kernel_end;
91
92 static uch *inbuf;              /* input buffer (compressed data) */
93 static uch *window;             /* output buffer (uncompressed data) */
94 static unsigned long file_offset;       /* position in the file */
95
96 static unsigned insize = 0;  /* valid bytes in inbuf */
97 static unsigned inptr  = 0;   /* index of next byte to be processed in inbuf */
98 static unsigned outcnt = 0;  /* bytes in output buffer */
99
100 /* gzip flag byte */
101 #define ASCII_FLAG   0x01 /* bit 0 set: file probably ASCII text */
102 #define CONTINUATION 0x02 /* bit 1 set: continuation of multi-part gzip file */
103 #define EXTRA_FIELD  0x04 /* bit 2 set: extra field present */
104 #define ORIG_NAME    0x08 /* bit 3 set: original file name present */
105 #define COMMENT      0x10 /* bit 4 set: file comment present */
106 #define ENCRYPTED    0x20 /* bit 5 set: file is encrypted */
107 #define RESERVED     0xC0 /* bit 6,7:   reserved */
108
109 #define get_byte()  (inptr < insize ? inbuf[inptr++] : fill_inbuf())
110
111 /* Diagnostic functions */
112 #ifdef INFLATE_DEBUG
113 #  define Assert(cond,msg) {if(!(cond)) error(msg);}
114 int stderr;
115 #  define Trace(x) Print(L"line %d:\n", __LINE__);
116 #  define Tracev(x) {if (verbose) Print(L"line %d:\n", __LINE__) ;}
117 #  define Tracevv(x) {if (verbose>1) Print(L"line %d:\n", __LINE__)  ;}
118 #  define Tracec(c,x) {if (verbose && (c))  Print(L"line %d:\n", __LINE__) ;}
119 #  define Tracecv(c,x) {if (verbose>1 && (c))  Print(L"line %d:\n", __LINE__) ;}
120 #else
121 #  define Assert(cond,msg)
122 #  define Trace(x)
123 #  define Tracev(x)
124 #  define Tracevv(x)
125 #  define Tracec(c,x)
126 #  define Tracecv(c,x)
127 #endif
128
129 static int  fill_inbuf(void);
130 static void flush_window(void);
131 static void error(char *m);
132 static long bytes_out;
133
134 static void error(char *m);
135
136 static jmp_buf jbuf;
137 static int error_return;
138 static UINTN elf_is_big_endian; /* true if ELF file is big endian */
139
140 static void *
141 gzip_malloc(int size)
142 {
143         return (void *)alloc(size, 0);
144 }
145
146 static void
147 gzip_free(void *where)
148 {       
149         return free(where);
150 }
151
152 #include "inflate.c"
153
154 /*
155  * Fill the input buffer and return the first byte in it. This is called
156  * only when the buffer is empty and at least one byte is really needed.
157  */
158 int
159 fill_inbuf(void)
160 {
161         INTN expected, nread;
162         EFI_STATUS status;
163
164         expected = nread = INBUFSIZE;
165
166         status = fops_read(input_fd, inbuf, &nread);
167         if (EFI_ERROR(status)) {
168                 error("elilo: Read failed");
169         }
170         DBG_PRT((L"%s : read %d bytes of %d bytes\n", LD_NAME, nread, expected));
171
172         insize = nread;
173         inptr = 1;
174
175         return inbuf[0];
176 }
177
178 /* ===========================================================================
179  * Write the output window window[0..outcnt-1] and update crc and bytes_out.
180  * (Used for the decompressed data only.)
181  */
182
183 /*
184  * Run a set of bytes through the crc shift register.  If s is a NULL
185  * pointer, then initialize the crc shift register contents instead.
186  * Return the current crc in either case.
187  *
188  * Input:
189  *      S       pointer to bytes to pump through.
190  *      N       number of bytes in S[].
191  */
192 unsigned long
193 updcrc(unsigned char *s, unsigned n)
194 {
195         register unsigned long c;
196         /* crc is defined in inflate.c */
197
198         if (!s) {
199                 c = 0xffffffffL;
200         } else {
201                 c = crc;
202                 while (n--) {
203                         c = crc_32_tab[((int)c ^ (*s++)) & 0xff] ^ (c >> 8);
204                 }
205         }
206         crc = c;
207         return c ^ 0xffffffffUL;       /* (instead of ~c for 64-bit machines) */
208 }
209
210
211 /*
212  * Clear input and output buffers
213  */
214 void
215 clear_bufs(void)
216 {
217         outcnt = 0;
218         inptr = 0;
219         chunk = 0;
220         cur_chunk = NULL;
221         file_offset = 0;
222 }
223
224
225 static inline UINT64 
226 bswap64(UINT64 v)
227 {
228         if(elf_is_big_endian) v = __ia64_swab64(v);
229         return v;
230 }
231
232 static inline UINT32
233 bswap32(UINT32 v)
234 {
235         if(elf_is_big_endian) v = __ia64_swab32(v);
236         return v;
237 }
238
239 static inline UINT16
240 bswap16(UINT16 v)
241 {
242         if(elf_is_big_endian) v = __ia64_swab16(v);
243         return v;
244 }
245
246 static INTN
247 is_valid_header(Elf64_Ehdr *ehdr)
248 {
249         UINT16 type, machine;
250
251         if (ehdr->e_ident[EI_DATA] == ELFDATA2MSB) {
252                 type    = __ia64_swab16(ehdr->e_type);
253                 machine = __ia64_swab16(ehdr->e_machine);
254         } else {
255                 type    = ehdr->e_type;
256                 machine = ehdr->e_machine;
257         }
258         VERB_PRT(3, Print(L"class=%d type=%d data=%d machine=%d\n", 
259                 ehdr->e_ident[EI_CLASS],
260                 type,
261                 ehdr->e_ident[EI_DATA],
262                 machine));
263
264         return    ehdr->e_ident[EI_MAG0]  == 0x7f 
265                && ehdr->e_ident[EI_MAG1]  == 'E'
266                && ehdr->e_ident[EI_MAG2]  == 'L'
267                && ehdr->e_ident[EI_MAG3]  == 'F'
268                && ehdr->e_ident[EI_CLASS] == ELFCLASS64 
269                && type                    == ET_EXEC    /* must be executable */
270                && machine                 == EM_IA_64 ? 0 : -1;
271 }
272
273 /*
274  * will invalidate loadble segments which overlap with others
275  */ 
276 void
277 check_overlap(int i)
278 {
279         int j;
280         unsigned long iend = chunks[i].addr + chunks[i].size;
281
282         for(j=0; j < nchunks; j++) {
283                 if (j ==i) continue;
284                 if (chunks[i].addr >= chunks[j].addr && iend < (chunks[j].addr + chunks[j].size)) {
285                         DBG_PRT((L"%s : segment %d fully included in segment %d\n", LD_NAME, i, j));
286                         CHUNK_INVALIDATE(i); /* nullyify segment */
287                         break;
288                 }
289         }
290 }
291
292 void
293 analyze_chunks(void)
294 {
295         INTN i;
296
297         for(i=0; i < nchunks; i++) {
298                 if (CHUNK_IS_VALID(i) && !CHUNK_IS_LOAD(i)) check_overlap(i);
299         }
300 }
301
302
303 /*
304  * The decompression code calls this function after decompressing the
305  * first block of the object file.  The first block must contain all
306  * the relevant header information.
307  */
308 int
309 first_block (const char *buf, long blocksize)
310 {
311         Elf64_Ehdr *elf;
312         Elf64_Phdr *phdrs;
313         UINTN total_size, pages;
314         UINTN low_addr, max_addr;
315         UINTN load_offset = 0;
316         UINTN offs = 0;
317         UINT16 phnum;
318         UINTN paddr, memsz;
319         INTN i;
320
321         elf  = (Elf64_Ehdr *)buf;
322         
323         if (is_valid_header(elf) == -1) return -1;
324
325         /* determine file endianess */
326         elf_is_big_endian = elf->e_ident[EI_DATA] == ELFDATA2MSB ? 1 : 0;
327
328         
329         offs  = bswap64(elf->e_phoff);
330         phnum = bswap16(elf->e_phnum);
331
332         VERB_PRT(3, { 
333                         Print(L"ELF file is %s\n", elf_is_big_endian ? L"big endian" : L"little endian");
334                         Print(L"Entry point 0x%lx\n", bswap64(elf->e_entry));
335                         Print(L"%d program headers\n", phnum);
336                         Print(L"%d segment headers\n", bswap16(elf->e_shnum));
337                    });
338
339
340         /* XXX: need to check on this */
341         if (offs + phnum * sizeof(*phdrs) > (unsigned) blocksize) {
342                 ERR_PRT((L"%s : ELF program headers not in first block (%ld)\n", LD_NAME, offs));
343                 return -1;
344         }
345
346         kernel_entry = (void *)bswap64(elf->e_entry);
347
348         if (((UINTN)kernel_entry >> 61) != 0) {
349                 ERR_PRT((L"%s:  <<ERROR>> entry point is a virtual address 0x%lx : not supported anymore\n", LD_NAME, kernel_entry));
350         }
351
352         phdrs = (Elf64_Phdr *) (buf + offs);
353
354         low_addr = ~0;
355         max_addr = 0;
356
357         /*
358          * allocate chunk table
359          * Convention: a segment that does not need loading will
360          * have chunk[].addr = 0.
361          */
362         chunks = (void *)alloc(sizeof(struct segment)*phnum, 0);
363         if (chunks == NULL) {
364                 ERR_PRT((L"%s : failed alloc chunks %r\n", LD_NAME));
365                 return -1;
366         }
367         nchunks = phnum;
368         /*
369          * find lowest and higest virtual addresses
370          * don't assume FULLY sorted !
371          */
372         for (i = 0; i < phnum; ++i) {
373
374                 /* 
375                  * record chunk no matter what because no load may happen
376                  * anywhere in archive, not just as the last segment
377                  */
378                 paddr = bswap64(phdrs[i].p_paddr);
379                 memsz = bswap64(phdrs[i].p_memsz),
380
381                 chunks[i].addr   = paddr;
382                 chunks[i].offset = bswap64(phdrs[i].p_offset);
383                 chunks[i].size   = bswap64(phdrs[i].p_filesz);
384                 chunks[i].bss_sz = bswap64(phdrs[i].p_memsz) - bswap64(phdrs[i].p_filesz);
385
386                 CHUNK_VALIDATE(i);
387
388                 if (bswap32(phdrs[i].p_type) != PT_LOAD) {
389                         CHUNK_NO_LOAD(i); /* mark no load chunk */
390                         DBG_PRT((L"%s : skipping segment %ld\n", LD_NAME, i));
391                         continue;
392                 }
393
394                 CHUNK_CAN_LOAD(i); /* mark no load chunk */
395
396                 VERB_PRT(3, 
397                 Print(L"\n%s : segment %ld vaddr [0x%lx-0x%lx] offset %ld filesz %ld memsz=%ld bss_sz=%ld\n",
398                                 LD_NAME,
399                                 1+i, 
400                                 chunks[i].addr, 
401                                 chunks[i].addr+bswap64(phdrs[i].p_filesz), 
402                                 chunks[i].offset, 
403                                 chunks[i].size,
404                                 memsz,
405                                 chunks[i].bss_sz));
406                 
407                 if (paddr < low_addr) low_addr = paddr;
408
409                 if (paddr + memsz > max_addr) max_addr = paddr + memsz;
410         }
411
412         if (low_addr & (EFI_PAGE_SIZE - 1)) {
413                 ERR_PRT((L"%s : low_addr not page aligned 0x%lx\n", LD_NAME, low_addr));
414                 goto error;
415         }
416
417         analyze_chunks();
418
419         DBG_PRT((L"%s : %d program headers entry=0x%lx\nlowest_addr=0x%lx highest_addr=0x%lx\n", 
420                         LD_NAME,
421                         phnum, kernel_entry, low_addr, max_addr));
422
423         total_size = (UINTN)max_addr - (UINTN)low_addr;
424         pages = EFI_SIZE_TO_PAGES(total_size);
425
426         /*
427          * Record end of kernel for initrd
428          */
429         kernel_base = (void *)low_addr;
430         kernel_end  = (void *)(low_addr + (pages << EFI_PAGE_SHIFT));
431
432         /* allocate memory for the kernel */
433         if (alloc_kmem((void *)low_addr, pages) == -1) {
434                 VOID *new_addr;
435
436                 ERR_PRT((L"%s : AllocatePages(%d, 0x%lx) for kernel failed\n", LD_NAME, pages, low_addr));
437
438                 if (ia64_can_relocate() == 0) {
439                         ERR_PRT((L"relocation is disabled, cannot load kernel"));
440                         goto error;
441                 }
442
443                 /*
444                  * could not allocate at requested spot, try to find a
445                  * suitable location to relocate the kernel
446                  *
447                  * The maximum sized Itanium TLB translation entry is 256 MB.
448                  * If we relocate the kernel by this amount we know for sure
449                  * that alignment constraints will be satisified, regardless
450                  * of the kernel used.
451                  */
452                 VERB_PRT(1, Print(L"Attempting to relocate kernel.\n"));
453
454                 if (find_kernel_memory((VOID*) low_addr, (VOID*) max_addr, 256*MB, &new_addr) == -1) {
455                         ERR_PRT((L"%s : find_kernel_memory(0x%lx, 0x%lx, 0x%lx, 0x%lx) failed\n", LD_NAME, low_addr, max_addr, 256*MB, &load_offset));
456                         goto error;
457                 }
458                 /* unsigned arithmetic */
459                 load_offset = (UINTN) (new_addr - ROUNDDOWN((UINTN) low_addr,256*MB));
460
461                 ERR_PRT((L"low_addr=0x%lx new_addr=0x%lx offset=0x%lx", low_addr, new_addr, load_offset));
462
463                 /*
464                  * correct various addresses for non-zero load_offset
465                  */
466                 kernel_base = (void *) ((UINTN) kernel_base + load_offset);
467                 kernel_end  = (void *) ((UINTN) kernel_end + load_offset);
468                 kernel_entry = (void*) ((UINTN) kernel_entry + load_offset);
469
470                 for (i = 0; i < phnum; ++i) {
471                         chunks[i].addr += load_offset;
472                         phdrs[i].p_paddr = (Elf64_Addr) ((UINT64) phdrs[i].p_paddr + load_offset);
473                 }
474
475                 /*
476                  * try one last time to get memory for the kernel
477                  */
478                 if (alloc_kmem((void *)low_addr+load_offset, pages) == -1) {
479                         ERR_PRT((L"%s : AllocatePages(%d, 0x%lx) for kernel failed\n", LD_NAME, pages, low_addr+load_offset));
480                         ERR_PRT((L"Relocation by 0x%lx bytes failed.\n", load_offset));
481                         goto error;
482                 }
483         }
484         return 0;
485 error:
486         if (chunks) free(chunks);
487         return -1;
488 }
489
490 /*
491  * Determine which chunk in the Elf file will be coming out of the expand
492  * code next.
493  */
494 static void
495 nextchunk(void)
496 {
497         int i;
498         segment_t *cp;
499
500         cp = NULL;
501         for(i=0; i < nchunks; i++) {
502
503                 if (!CHUNK_IS_VALID(i) || !CHUNK_IS_LOAD(i)) continue;
504
505                 if (file_offset > chunks[i].offset) continue;
506
507                 if (cp == NULL || chunks[i].offset < cp->offset) cp = &chunks[i];
508         }
509         cur_chunk = cp;
510 }
511
512
513 /*
514  * Write the output window window[0..outcnt-1] holding uncompressed
515  * data and update crc.
516  */
517 void
518 flush_window(void)
519 {
520         static const CHAR8 helicopter[4] = { '|' , '/' , '-' , '\\' };
521         static UINTN heli_count;
522         struct segment *cp;
523         char    *src, *dst;
524         long    cnt;
525
526         if (!outcnt) return;
527
528         DBG_PRT((L"%s : flush_window outnct=%d file_offset=%ld\n", LD_NAME, outcnt, file_offset));
529
530         Print(L"%c\b",helicopter[heli_count++%4]);
531
532         updcrc(window, outcnt);
533
534         /*
535          * first time, we extract the headers
536          */
537         if (!bytes_out) {
538                 if (first_block(window, outcnt) < 0) error("invalid exec header"); 
539                 nextchunk();
540         }
541
542         bytes_out += outcnt;
543         src = window;
544 tail:
545         /* check if user wants to abort */
546         if (check_abort() == EFI_SUCCESS) goto load_abort;
547
548         cp = cur_chunk;
549         if (cp == NULL || file_offset + outcnt <= cp->offset) {
550                 file_offset += outcnt;
551                 return;
552         }
553
554         // Does this window begin before the current chunk?
555         if (file_offset < cp->offset) {
556                 unsigned long skip = cp->offset - file_offset;
557
558                 src         += skip;
559                 file_offset += skip;
560                 outcnt      -= skip;
561         }
562         dst = (char *)cp->addr + (file_offset - cp->offset);
563
564         cnt = cp->offset + cp->size - file_offset;
565
566         if (cnt > outcnt) cnt = outcnt;
567
568         Memcpy(dst, src, cnt);
569
570         file_offset += cnt;
571         outcnt      -= cnt;
572         src         += cnt;
573
574         /* See if we are at the end of this chunk */
575         if (file_offset == cp->offset + cp->size) {
576                 if (cp->bss_sz) {
577                         dst = (char *)cp->addr + cp->size;
578                         Memset(dst, 0, cp->bss_sz);
579                 }
580                 nextchunk();
581                 /* handle remaining bytes */
582                 if (outcnt) goto tail; 
583         }
584         return;
585 load_abort:
586         free_kmem();
587         error_return = ELILO_LOAD_ABORTED;
588         longjmp(jbuf, 1);
589 }
590
591 static void
592 error(char *x)
593 {
594         ERR_PRT((L"%s : %a", LD_NAME, x));
595         /* will eventually exit with error from gunzip() */
596         longjmp(jbuf,1);
597 }
598
599 INT32
600 decompress_kernel(VOID)
601 {
602         INT32 ret;
603
604         clear_bufs();
605         makecrc();
606         Print(L"Uncompressing Linux... ");
607         ret = gunzip();
608         if (ret == 0) Print(L"done\n");
609         return ret == 0 ? 0 : -1;
610 }
611
612 int
613 gunzip_kernel(fops_fd_t fd, kdesc_t *kd)
614 {
615         int ret = -1;
616
617         error_return = ELILO_LOAD_ERROR;
618         
619         window = (void *)alloc(WSIZE, 0);
620         if (window == NULL) {
621                 ERR_PRT((L"%s : allocate output window failed\n", LD_NAME));
622                 return -1;
623         }
624
625         inbuf = (void *)alloc(INBUFSIZE, 0);
626         if (inbuf == NULL) {
627                 ERR_PRT((L"%s : allocate input window failedr\n", LD_NAME));
628                 goto error;
629         }
630
631         input_fd   = fd;
632         insize     = 0;
633         bytes_out  = 0;
634
635         if (setjmp(jbuf) == 1) goto error;
636
637
638         ret = decompress_kernel();
639
640 error:
641         if (window) free(window);
642         if (inbuf) free(inbuf);
643
644         if (ret == 0) {
645                 kd->kentry = kernel_entry;
646                 kd->kend   = kernel_end;
647                 kd->kstart = kernel_base;
648                 error_return = ELILO_LOAD_SUCCESS;
649         }
650         return error_return;
651 }