1 /* powerpc-darwin.macho-upxmain.c -- loader hack for Mach-o powerpc
2
3 This file is part of the UPX executable compressor.
4
5 Copyright (C) 1996-2020 Markus Franz Xaver Johannes Oberhumer
6 Copyright (C) 1996-2020 Laszlo Molnar
7 Copyright (C) 2000-2020 John F. Reiser
8 All Rights Reserved.
9
10 UPX and the UCL library are free software; you can redistribute them
11 and/or modify them under the terms of the GNU General Public License as
12 published by the Free Software Foundation; either version 2 of
13 the License, or (at your option) any later version.
14
15 This program 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 this program; see the file COPYING.
22 If not, write to the Free Software Foundation, Inc.,
23 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
24
25 Markus F.X.J. Oberhumer Laszlo Molnar
26 <markus@oberhumer.com> <ml1050@users.sourceforge.net>
27
28 John F. Reiser
29 <jreiser@users.sourceforge.net>
30 */
31
32 #define __WORDSIZE 32
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include "include/darwin.h"
36
37 #ifndef DEBUG /*{*/
38 #define DEBUG 0
39 #endif /*}*/
40
41 /*************************************************************************
42 // configuration section
43 **************************************************************************/
44
45 // In order to make it much easier to move this code at runtime and execute
46 // it at an address different from it load address: there must be no
47 // static data, and no string constants.
48
49 #if !DEBUG /*{*/
50 #define DPRINTF(a) /* empty: no debug drivel */
51 #define DEBUG_STRCON(name, value) /* empty */
52 #else /*}{ DEBUG */
53 extern int write(int, void const *, size_t);
54 #if 0
55 #include "stdarg.h"
56 #else
57 #define va_arg __builtin_va_arg
58 #define va_end __builtin_va_end
59 #define va_list __builtin_va_list
60 #define va_start __builtin_va_start
61 #endif
62
63 #if defined(__i386__) || defined(__x86_64__) /*{*/
64 #define PIC_STRING(value, var) \
65 __asm__ __volatile__ ( \
66 "call 0f; .asciz \"" value "\"; \
67 0: pop %0;" : "=r"(var) : \
68 )
69 #elif defined(__arm__) /*}{*/
70 #define PIC_STRING(value, var) \
71 __asm__ __volatile__ ( \
72 "mov %0,pc; b 0f; \
73 .asciz \"" value "\"; .balign 4; \
74 0: " : "=r"(var) \
75 )
76 #elif defined(__mips__) /*}{*/
77 #define PIC_STRING(value, var) \
78 __asm__ __volatile__ ( \
79 ".set noreorder; bal 0f; move %0,$31; .set reorder; \
80 .asciz \"" value "\"; .balign 4; \
81 0: " \
82 : "=r"(var) : : "ra" \
83 )
84 #endif /*}*/
85
86
87 #define DEBUG_STRCON(name, strcon) \
88 static char const *name(void) { \
89 register char const *rv; PIC_STRING(strcon, rv); \
90 return rv; \
91 }
92
93
94 #ifdef __arm__ /*{*/
95 extern unsigned div10(unsigned);
96 #else /*}{*/
97 static unsigned
div10(unsigned x)98 div10(unsigned x)
99 {
100 return x / 10u;
101 }
102 #endif /*}*/
103
104 static int
unsimal(unsigned x,char * ptr,int n)105 unsimal(unsigned x, char *ptr, int n)
106 {
107 if (10<=x) {
108 unsigned const q = div10(x);
109 x -= 10 * q;
110 n = unsimal(q, ptr, n);
111 }
112 ptr[n] = '0' + x;
113 return 1+ n;
114 }
115
116 static int
decimal(int x,char * ptr,int n)117 decimal(int x, char *ptr, int n)
118 {
119 if (x < 0) {
120 x = -x;
121 ptr[n++] = '-';
122 }
123 return unsimal(x, ptr, n);
124 }
125
126 DEBUG_STRCON(STR_hex, "0123456789abcdef");
127
128 static int
heximal(unsigned long x,char * ptr,int n)129 heximal(unsigned long x, char *ptr, int n)
130 {
131 if (16<=x) {
132 n = heximal(x>>4, ptr, n);
133 x &= 0xf;
134 }
135 ptr[n] = STR_hex()[x];
136 return 1+ n;
137 }
138
139
140 #define DPRINTF(a) my_printf a
141
142 static int
my_printf(char const * fmt,...)143 my_printf(char const *fmt, ...)
144 {
145 char c;
146 int n= 0;
147 char *ptr;
148 char buf[20];
149 va_list va; va_start(va, fmt);
150 ptr= &buf[0];
151 while (0!=(c= *fmt++)) if ('%'!=c) goto literal;
152 else switch (c= *fmt++) {
153 default: {
154 literal:
155 n+= write(2, fmt-1, 1);
156 } break;
157 case 0: goto done; /* early */
158 case 'u': {
159 n+= write(2, buf, unsimal(va_arg(va, unsigned), buf, 0));
160 } break;
161 case 'd': {
162 n+= write(2, buf, decimal(va_arg(va, int), buf, 0));
163 } break;
164 case 'p': {
165 buf[0] = '0';
166 buf[1] = 'x';
167 n+= write(2, buf, heximal((unsigned long)va_arg(va, void *), buf, 2));
168 } break;
169 case 'x': {
170 buf[0] = '0';
171 buf[1] = 'x';
172 n+= write(2, buf, heximal(va_arg(va, int), buf, 2));
173 } break;
174 }
175 done:
176 va_end(va);
177 return n;
178 }
179 #endif /*}*/
180
181
182 /*************************************************************************
183 // "file" util
184 **************************************************************************/
185
186 typedef struct {
187 size_t size; // must be first to match size[0] uncompressed size
188 void *buf;
189 } Extent;
190
191 DEBUG_STRCON(STR_xread, "xread %%p(%%x %%p) %%p %%x\\n")
192 DEBUG_STRCON(STR_xreadfail, "xreadfail %%p(%%x %%p) %%p %%x\\n")
193
194 static void
xread(Extent * x,void * buf,size_t count)195 xread(Extent *x, void *buf, size_t count)
196 {
197 unsigned char *p=x->buf, *q=buf;
198 size_t j;
199 DPRINTF((STR_xread(), x, x->size, x->buf, buf, count));
200 if (x->size < count) {
201 DPRINTF((STR_xreadfail(), x, x->size, x->buf, buf, count));
202 exit(127);
203 }
204 for (j = count; 0!=j--; ++p, ++q) {
205 *q = *p;
206 }
207 x->buf += count;
208 x->size -= count;
209 }
210
211
212 /*************************************************************************
213 // util
214 **************************************************************************/
215
216 #if 1 //{ save space
217 #define ERR_LAB error: exit(127);
218 #define err_exit(a) goto error
219 #else //}{ save debugging time
220 #define ERR_LAB /*empty*/
221 DEBUG_STRCON(STR_exit, "err_exit %%x\\n");
222
223 static void
err_exit(int a)224 err_exit(int a)
225 {
226 DPRINTF((STR_exit(), a));
227 (void)a; // debugging convenience
228 exit(127);
229 }
230 #endif //}
231
232
233 /*************************************************************************
234 // UPX & NRV stuff
235 **************************************************************************/
236
237 struct l_info { // 12-byte trailer for loader (after macho headers)
238 unsigned l_checksum;
239 unsigned l_magic; // UPX_MAGIC_LE32
240 unsigned short l_lsize;
241 unsigned char l_version;
242 unsigned char l_format;
243 };
244 struct p_info { // 12-byte packed program header
245 unsigned p_progid;
246 unsigned p_filesize;
247 unsigned p_blocksize;
248 };
249
250 struct b_info { // 12-byte header before each compressed block
251 unsigned sz_unc; // uncompressed_size
252 unsigned sz_cpr; // compressed_size
253 unsigned char b_method; // compression algorithm
254 unsigned char b_ftid; // filter id
255 unsigned char b_cto8; // filter parameter
256 unsigned char b_unused;
257 };
258
259 typedef void f_unfilter(
260 nrv_byte *, // also addvalue
261 nrv_uint,
262 unsigned cto8, // junk in high 24 bits
263 unsigned ftid
264 );
265 typedef int f_expand(
266 const nrv_byte *, nrv_uint,
267 nrv_byte *, nrv_uint *, unsigned );
268
269 DEBUG_STRCON(STR_unpackExtent,
270 "unpackExtent in=%%p(%%x %%p) out=%%p(%%x %%p) %%p %%p\\n");
271 DEBUG_STRCON(STR_err5, "sz_cpr=%%x sz_unc=%%x xo->size=%%x\\n");
272
273 static void
unpackExtent(Extent * const xi,Extent * const xo,f_expand * const f_decompress,f_unfilter * f_unf)274 unpackExtent(
275 Extent *const xi, // input
276 Extent *const xo, // output
277 f_expand *const f_decompress,
278 f_unfilter *f_unf
279 )
280 {
281 DPRINTF((STR_unpackExtent(),
282 xi, xi->size, xi->buf, xo, xo->size, xo->buf, f_decompress, f_unf));
283 while (xo->size) {
284 struct b_info h;
285 // Note: if h.sz_unc == h.sz_cpr then the block was not
286 // compressible and is stored in its uncompressed form.
287
288 // Read and check block sizes.
289 xread(xi, (unsigned char *)&h, sizeof(h));
290 if (h.sz_unc == 0) { // uncompressed size 0 -> EOF
291 if (h.sz_cpr != UPX_MAGIC_LE32) // h.sz_cpr must be h->magic
292 err_exit(2);
293 if (xi->size != 0) // all bytes must be written
294 err_exit(3);
295 break;
296 }
297 if (h.sz_cpr <= 0) {
298 err_exit(4);
299 ERR_LAB
300 }
301 if (h.sz_cpr > h.sz_unc
302 || h.sz_unc > xo->size ) {
303 DPRINTF((STR_err5(), h.sz_cpr, h.sz_unc, xo->size));
304 err_exit(5);
305 }
306 // Now we have:
307 // assert(h.sz_cpr <= h.sz_unc);
308 // assert(h.sz_unc > 0 && h.sz_unc <= blocksize);
309 // assert(h.sz_cpr > 0 && h.sz_cpr <= blocksize);
310
311 if (h.sz_cpr < h.sz_unc) { // Decompress block
312 nrv_uint out_len = h.sz_unc; // EOF for lzma
313 int const j = (*f_decompress)(xi->buf, h.sz_cpr,
314 xo->buf, &out_len, h.b_method);
315 if (j != 0 || out_len != (nrv_uint)h.sz_unc)
316 err_exit(7);
317 if (h.b_ftid!=0 && f_unf) { // have filter
318 (*f_unf)(xo->buf, out_len, h.b_cto8, h.b_ftid);
319 }
320 xi->buf += h.sz_cpr;
321 xi->size -= h.sz_cpr;
322 }
323 else { // copy literal block
324 xread(xi, xo->buf, h.sz_cpr);
325 }
326 xo->buf += h.sz_unc;
327 xo->size -= h.sz_unc;
328 }
329 }
330
331 static void
upx_bzero(unsigned char * p,size_t len)332 upx_bzero(unsigned char *p, size_t len)
333 {
334 if (len) do {
335 *p++= 0;
336 } while (--len);
337 }
338 #define bzero upx_bzero
339
340
341 // The PF_* and PROT_* bits are {1,2,4}; the conversion table fits in 32 bits.
342 #define REP8(x) \
343 ((x)|((x)<<4)|((x)<<8)|((x)<<12)|((x)<<16)|((x)<<20)|((x)<<24)|((x)<<28))
344 #define EXP8(y) \
345 ((1&(y)) ? 0xf0f0f0f0 : (2&(y)) ? 0xff00ff00 : (4&(y)) ? 0xffff0000 : 0)
346 #define PF_TO_PROT(pf) \
347 ((PROT_READ|PROT_WRITE|PROT_EXEC) & ( \
348 ( (REP8(PROT_EXEC ) & EXP8(PF_X)) \
349 |(REP8(PROT_READ ) & EXP8(PF_R)) \
350 |(REP8(PROT_WRITE) & EXP8(PF_W)) \
351 ) >> ((pf & (PF_R|PF_W|PF_X))<<2) ))
352
353 typedef struct {
354 unsigned magic;
355 unsigned nfat_arch;
356 } Fat_header;
357 typedef struct {
358 unsigned cputype;
359 unsigned cpusubtype;
360 unsigned offset;
361 unsigned size;
362 unsigned align; /* shift count (log base 2) */
363 } Fat_arch;
364 enum e8 {
365 FAT_MAGIC = 0xcafebabe,
366 FAT_CIGAM = 0xbebafeca
367 };
368 enum e9 {
369 CPU_TYPE_I386 = 7,
370 CPU_TYPE_AMD64 = 0x01000007,
371 CPU_TYPE_ARM = 12,
372 CPU_TYPE_POWERPC = 0x00000012,
373 CPU_TYPE_POWERPC64 = 0x01000012
374 };
375
376 typedef struct {
377 unsigned magic;
378 unsigned cputype;
379 unsigned cpysubtype;
380 unsigned filetype;
381 unsigned ncmds;
382 unsigned sizeofcmds;
383 unsigned flags;
384 } Mach_header;
385 enum e0 {
386 MH_MAGIC = 0xfeedface,
387 MH_MAGIC64 = 1+0xfeedface
388 };
389 enum e2 {
390 MH_EXECUTE = 2
391 };
392 enum e3 {
393 MH_NOUNDEFS = 1
394 };
395
396 typedef struct {
397 unsigned cmd;
398 unsigned cmdsize;
399 } Mach_load_command;
400 enum e4 {
401 LC_REQ_DYLD = 0x80000000, // OR'ed ==> must not ignore
402 LC_SEGMENT = 0x1,
403 LC_SEGMENT_64 = 0x19,
404 LC_THREAD = 0x4,
405 LC_UNIXTHREAD = 0x5,
406 LC_LOAD_DYLINKER = 0xe,
407 LC_MAIN = (0x28|LC_REQ_DYLD)
408 };
409
410 typedef struct {
411 unsigned cmd;
412 unsigned cmdsize;
413 char segname[16];
414 uint32_t vmaddr;
415 uint32_t vmsize;
416 uint32_t fileoff;
417 uint32_t filesize;
418 unsigned maxprot;
419 unsigned initprot;
420 unsigned nsects;
421 unsigned flags;
422 } Mach_segment_command;
423 enum e5 {
424 VM_PROT_READ = 1,
425 VM_PROT_WRITE = 2,
426 VM_PROT_EXECUTE = 4
427 };
428
429 typedef struct {
430 char sectname[16];
431 char segname[16];
432 uint32_t addr; /* memory address */
433 uint32_t size; /* size in bytes */
434 unsigned offset; /* file offset */
435 unsigned align; /* power of 2 */
436 unsigned reloff; /* file offset of relocation entries */
437 unsigned nreloc; /* number of relocation entries */
438 unsigned flags; /* section type and attributes */
439 unsigned reserved1; /* for offset or index */
440 unsigned reserved2; /* for count or sizeof */
441 } Mach_section_command;
442
443 typedef struct {
444 uint32_t cmd; // LC_MAIN; MH_EXECUTE only
445 uint32_t cmdsize; // 24
446 uint64_t entryoff; // file offset of main() [expected in __TEXT]
447 uint64_t stacksize; // non-default initial stack size
448 } Mach_main_command;
449
450 typedef struct {
451 uint32_t srr0; /* Instruction address register (PC; entry addr) */
452 uint32_t srr1; /* Machine state register (supervisor) */
453 uint32_t r0, r1, r2, r3, r4, r5, r6, r7;
454 uint32_t r8, r9,r10,r11,r12,r13,r14,r15;
455 uint32_t r16,r17,r18,r19,r20,r21,r22,r23;
456 uint32_t r24,r25,r26,r27,r28,r29,r30,r31;
457
458 uint32_t cr; /* Condition register */ // FIXME: Word?
459 uint32_t xer; /* User's integer exception register */
460 uint32_t lr; /* Link register */
461 uint32_t ctr; /* Count register */
462 uint32_t mq; /* MQ register (601 only) */
463
464 uint32_t vrsave; /* Vector Save Register */
465 } Mach_ppc_thread_state;
466
467 typedef struct {
468 unsigned cmd; /* LC_THREAD or LC_UNIXTHREAD */
469 unsigned cmdsize; /* total size of this command */
470 unsigned flavor;
471 unsigned count; /* sizeof(following_thread_state)/4 */
472 Mach_ppc_thread_state state;
473 } Mach_thread_command;
474 enum e6 {
475 PPC_THREAD_STATE = 1
476 };
477 enum e7 {
478 PPC_THREAD_STATE_COUNT = sizeof(Mach_ppc_thread_state)/4
479 };
480
481 typedef union {
482 unsigned offset; /* from start of load command to string */
483 } Mach_lc_str;
484
485 #define MAP_FIXED 0x10
486 #define MAP_PRIVATE 0x02
487 #define MAP_ANON 0x1000
488 //#define MAP_ANON 0x20 // x86 DEBUG ONLY
489 #define PROT_READ 1
490 #define PROT_WRITE 2
491 #define PROT_EXEC 4
492 #define MAP_ANON_FD -1
493 #define MAP_FAILED ((void *) -1)
494
495 extern void *mmap(void *, size_t, unsigned, unsigned, int, off_t);
496 ssize_t pread(int, void *, size_t, off_t);
497 //extern void bswap(void *, unsigned);
498
499 DEBUG_STRCON(STR_mmap,
500 "mmap addr=%%p len=%%p prot=%%x flags=%%x fd=%%d off=%%p\\n");
501 DEBUG_STRCON(STR_do_xmap,
502 "do_xmap fdi=%%x mhdr=%%p xi=%%p(%%x %%p) f_unf=%%p\\n")
503
504 static uint32_t // entry address
do_xmap(Mach_header const * const mhdr,off_t const fat_offset,Extent * const xi,int const fdi,Mach_header ** mhdrpp,f_expand * const f_decompress,f_unfilter * const f_unf)505 do_xmap(
506 Mach_header const *const mhdr,
507 off_t const fat_offset,
508 Extent *const xi,
509 int const fdi,
510 Mach_header **mhdrpp,
511 f_expand *const f_decompress,
512 f_unfilter *const f_unf
513 )
514 {
515 Mach_segment_command const *sc = (Mach_segment_command const *)(1+ mhdr);
516 Mach_segment_command const *segTEXT = 0;
517 uint32_t entry = 0;
518 unsigned long base = 0;
519 unsigned j;
520
521 DPRINTF((STR_do_xmap(),
522 fdi, mhdr, xi, (xi? xi->size: 0), (xi? xi->buf: 0), f_unf));
523
524 for ( j=0; j < mhdr->ncmds; ++j,
525 (sc = (Mach_segment_command const *)(sc->cmdsize + (void const *)sc))
526 ) if (LC_SEGMENT==sc->cmd && sc->vmsize!=0) {
527 Extent xo;
528 size_t mlen = xo.size = sc->filesize;
529 unsigned char *addr = xo.buf = base + (unsigned char *)sc->vmaddr;
530 unsigned char *haddr = sc->vmsize + addr;
531 size_t frag = (int)(uint32_t)addr &~ PAGE_MASK;
532 addr -= frag;
533 mlen += frag;
534
535 if (0!=mlen) { // In particular, omitted for __PAGEZERO
536 unsigned const prot = VM_PROT_READ | VM_PROT_WRITE;
537 unsigned const flags = (addr ? MAP_FIXED : 0) | MAP_PRIVATE |
538 ((xi || 0==sc->filesize) ? MAP_ANON : 0);
539 int const fdm = ((0==sc->filesize) ? MAP_ANON_FD : fdi);
540 off_t const offset = sc->fileoff + fat_offset;
541
542 DPRINTF((STR_mmap(), addr, mlen, prot, flags, fdm, offset));
543 unsigned char *mapa = mmap(addr, mlen, prot, flags, fdm, offset);
544 if (MAP_FAILED == mapa) {
545 err_exit(8);
546 }
547 if (0 == addr) { // dyld auto-relocate
548 base = (unsigned long)mapa; // relocation constant
549 }
550 addr = mapa;
551 }
552 if (xi && 0!=sc->filesize) {
553 if (0==sc->fileoff /*&& 0!=mhdrpp*/) {
554 segTEXT = sc;
555 *mhdrpp = (Mach_header *)(void *)addr;
556 }
557 unpackExtent(xi, &xo, f_decompress, f_unf);
558 }
559 /*bzero(addr, frag);*/ // fragment at lo end
560 frag = (-mlen) &~ PAGE_MASK; // distance to next page boundary
561 bzero(mlen+addr, frag); // fragment at hi end
562 if (0!=mlen && 0!=mprotect(addr, mlen, sc->initprot)) {
563 err_exit(10);
564 ERR_LAB
565 }
566 addr += mlen + frag; /* page boundary on hi end */
567 if (
568 #if defined(SIMULATE_ON_DEBIAN_EABI4) /*{*/
569 0!=addr &&
570 #endif /*}*/
571 addr < haddr) { // need pages for .bss
572 if (0!=addr && addr != mmap(addr, haddr - addr, sc->initprot,
573 MAP_FIXED | MAP_PRIVATE | MAP_ANON, MAP_ANON_FD, 0 ) ) {
574 err_exit(9);
575 }
576 }
577 }
578 else if (LC_UNIXTHREAD==sc->cmd || LC_THREAD==sc->cmd) {
579 Mach_thread_command const *const thrc = (Mach_thread_command const *)sc;
580 if (PPC_THREAD_STATE ==thrc->flavor
581 && PPC_THREAD_STATE_COUNT ==thrc->count ) {
582 entry = thrc->state.srr0 + base; // JMP
583 }
584 }
585 else if (LC_MAIN==sc->cmd) {
586 entry = ((Mach_main_command const *)sc)->entryoff;
587 if (segTEXT->fileoff <= entry && entry < segTEXT->filesize) {
588 entry += segTEXT->vmaddr; // CALL
589 }
590 // XXX FIXME TODO: if entry not in segTEXT?
591 // XXX FIXME TODO: LC_MAIN is a CALL; LC_*THREAD is a JMP
592 }
593 return entry;
594 }
595
596 static off_t
fat_find(Fat_header * fh)597 fat_find(Fat_header *fh) // *fh suffers bswap()
598 {
599 Fat_arch *fa = (Fat_arch *)(1+ fh);
600 //POWERPC NATIVE; do not need: bswap(fh, sizeof(*fh) + (fh->nfat_arch>>24)*sizeof(*fa));
601 unsigned j;
602 for (j= 0; j < fh->nfat_arch; ++j, ++fa) {
603 if (CPU_TYPE_POWERPC==fa->cputype) {
604 return fa->offset; // should not be 0 because of header
605 }
606 }
607 return 0;
608 }
609
610 /*************************************************************************
611 // upx_main - called by our entry code
612 //
613 **************************************************************************/
614
615 DEBUG_STRCON(STR_upx_main,
616 "upx_main szc=%%x f_dec=%%p f_unf=%%p "
617 " xo=%%p(%%x %%p) xi=%%p(%%x %%p) mhdrpp=%%p\\n")
618
619 uint32_t // entry address
upx_main(struct l_info const * const li,size_t volatile sz_compressed,Mach_header * const mhdr,size_t const sz_mhdr,f_expand * const f_decompress,f_unfilter * const f_unf,Mach_header ** const mhdrpp)620 upx_main(
621 struct l_info const *const li,
622 size_t volatile sz_compressed, // total length
623 Mach_header *const mhdr, // temp char[sz_mhdr] for decompressing
624 size_t const sz_mhdr,
625 f_expand *const f_decompress,
626 f_unfilter *const f_unf,
627 Mach_header **const mhdrpp // Out: *mhdrpp= &real Mach_header
628 )
629 {
630 uint32_t entry;
631 off_t fat_offset = 0;
632 Extent xi, xo, xi0;
633 xi.buf = CONST_CAST(unsigned char *, 1+ (struct p_info const *)(1+ li)); // &b_info
634 xi.size = sz_compressed - (sizeof(struct l_info) + sizeof(struct p_info));
635 xo.buf = (unsigned char *)mhdr;
636 xo.size = ((struct b_info const *)(void const *)xi.buf)->sz_unc;
637 xi0 = xi;
638
639 DPRINTF((STR_upx_main(),
640 sz_compressed, f_decompress, f_unf, &xo, xo.size, xo.buf,
641 &xi, xi.size, xi.buf, mhdrpp));
642
643 // Uncompress Macho headers
644 unpackExtent(&xi, &xo, f_decompress, 0); // never filtered?
645
646 entry = do_xmap(mhdr, fat_offset, &xi0, MAP_ANON_FD, mhdrpp, f_decompress, f_unf);
647
648 { // Map dyld dynamic loader
649 Mach_load_command const *lc = (Mach_load_command const *)(1+ mhdr);
650 unsigned j;
651
652 for (j=0; j < mhdr->ncmds; ++j,
653 (lc = (Mach_load_command const *)(lc->cmdsize + (void const *)lc))
654 ) if (LC_LOAD_DYLINKER==lc->cmd) {
655 char const *const dyld_name = ((Mach_lc_str const *)(1+ lc))->offset +
656 (char const *)lc;
657 int const fdi = open(dyld_name, O_RDONLY, 0);
658 if (0 > fdi) {
659 err_exit(18);
660 }
661 for (;;) { // possibly 2 times for 'fat' binary
662 if (sz_mhdr!=pread(fdi, (void *)mhdr, sz_mhdr, fat_offset)) {
663 ERR_LAB
664 err_exit(19);
665 }
666 switch (mhdr->magic) {
667 case MH_MAGIC: break; // i686 on x86_64 ?
668 case MH_MAGIC64: break;
669
670 case FAT_CIGAM:
671 case FAT_MAGIC: {
672 // stupid Apple: waste code and a page fault on EVERY execve
673 fat_offset = fat_find((Fat_header *)mhdr);
674 if (fat_offset) {
675 continue; // the 'for' loop
676 }
677 err_exit(20); // no other choice
678 } break;
679 } // switch
680 break;
681 }
682 entry = do_xmap(mhdr, fat_offset, 0, fdi, 0, 0, 0);
683 close(fdi);
684 break;
685 }
686 }
687
688 return entry;
689 }
690
691 typedef struct {
692 uint32_t cmd;
693 uint32_t cmdsize;
694 uint32_t data[2]; // because cmdsize >= 16
695 } Mach_command; // generic prefix
696
697 // Build on PowerPC Macintosh:
698 // gcc -c -v -save-temps \
699 // powerpc-darwin.macho-upxsubr.S \
700 // powerpc-darwin.macho-upxmain.c
701 //
702 // /usr/libexec/gcc/powerpc-apple-darwin8/4.0.0/collect2 -arch ppc -weak_reference_mismatches non-weak \
703 // -o powerpc-darwin.macho-upxmain.exe \
704 // powerpc-darwin.macho-upxsubr.o \
705 // powerpc-darwin.macho-upxmain.o \
706 // -pagezero_size 0x1000 -bind_at_load -headerpad 0x300
707 //# -unexported_symbols_list unexport-upxload.txt
708 //
709 // strip -u -r powerpc-darwin.macho-upxmain.exe
710
711 int
main(int argc,char * argv[])712 main(int argc, char *argv[])
713 {
714 Mach_header const *mhdr0 = (Mach_header const *)((~0ul<<12) & (unsigned long)&main);
715 Mach_command const *ptr = (Mach_command const *)(1+ mhdr0);
716 f_unfilter *f_unf;
717 f_expand *f_exp;
718 char *payload;
719 size_t paysize;
720
721 unsigned j;
722 for (j=0; j < mhdr0->ncmds; ++j,
723 ptr = (Mach_command const *)(ptr->cmdsize + (char const *)ptr))
724 if (LC_SEGMENT==ptr->cmd) {
725 Mach_segment_command const *const seg = (Mach_segment_command const *)ptr;
726 // Compare 8 characters
727 if (*(uint64_t const *)(&"__LINKEDIT"[2]) == *(uint64_t const *)(&seg->segname[2])) {
728 f_unf = (f_unfilter *)(sizeof(unsigned) + seg->vmaddr);
729 f_exp = (f_expand *)(*(unsigned const *)seg->vmaddr + seg->vmaddr);
730 unsigned const *q = (unsigned const *)seg->vmaddr;
731 while (!(paysize = *--q)) /*empty*/ ;
732 payload = (char *)(-paysize + (char const *)q);
733 break;
734 }
735 }
736 char mhdr[16384];
737 uint32_t entry = upx_main((struct l_info const *)payload, paysize,
738 (Mach_header *)mhdr, sizeof(mhdr),
739 f_exp, f_unf, (Mach_header **)&argv[-2]);
740
741 //bzero(mhdr, sizeof(mhdr)); // paranoia
742 munmap(payload, paysize); // leaving __LINKEDIT
743 return entry;
744 }
745
746 /* vim:set ts=4 sw=4 et: */
747