1 /* powerpc64le-darwin.macho-main.c -- loader stub for Mach-o PowerPC64LE
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>               <ezerotven+github@gmail.com>
27 
28    John F. Reiser
29    <jreiser@users.sourceforge.net>
30  */
31 
32 
33 #define __WORDSIZE 64
34 #include "include/darwin.h"
35 
36 
37 /*************************************************************************
38 // configuration section
39 **************************************************************************/
40 
41 // In order to make it much easier to move this code at runtime and execute
42 // it at an address different from it load address:  there must be no
43 // static data, and no string constants.
44 
45 
46 /*************************************************************************
47 // "file" util
48 **************************************************************************/
49 
50 typedef struct {
51     size_t size;  // must be first to match size[0] uncompressed size
52     char *buf;
53 } Extent;
54 
55 
56 static void
xread(Extent * x,char * buf,size_t count)57 xread(Extent *x, char *buf, size_t count)
58 {
59     char *p=x->buf, *q=buf;
60     size_t j;
61     if (x->size < count) {
62         exit(127);
63     }
64     for (j = count; 0!=j--; ++p, ++q) {
65         *q = *p;
66     }
67     x->buf  += count;
68     x->size -= count;
69 }
70 
71 
72 /*************************************************************************
73 // util
74 **************************************************************************/
75 
76 #if 1  //{  save space
77 #define ERR_LAB error: exit(127);
78 #define err_exit(a) goto error
79 #else  //}{  save debugging time
80 #define ERR_LAB /*empty*/
81 static void
err_exit(int a)82 err_exit(int a)
83 {
84     (void)a;  // debugging convenience
85     exit(127);
86 }
87 #endif  //}
88 
89 
90 /*************************************************************************
91 // UPX & NRV stuff
92 **************************************************************************/
93 
94 struct l_info { // 12-byte trailer for loader (after macho headers)
95     unsigned l_checksum;
96     unsigned l_magic;  // UPX_MAGIC_LE32
97     unsigned short l_lsize;
98     unsigned char l_version;
99     unsigned char l_format;
100 };
101 struct p_info { // 12-byte packed program header
102     unsigned p_progid;
103     unsigned p_filesize;
104     unsigned p_blocksize;
105 };
106 
107 struct b_info { // 12-byte header before each compressed block
108     unsigned sz_unc;  // uncompressed_size
109     unsigned sz_cpr;  //   compressed_size
110     unsigned char b_method;  // compression algorithm
111     unsigned char b_ftid;  // filter id
112     unsigned char b_cto8;  // filter parameter
113     unsigned char b_unused;
114 };
115 
116 typedef void f_unfilter(
117     nrv_byte *,  // also addvalue
118     nrv_uint,
119     unsigned cto8, // junk in high 24 bits
120     unsigned ftid
121 );
122 typedef int f_expand(
123     const nrv_byte *, nrv_uint,
124           nrv_byte *, nrv_uint *, unsigned );
125 
126 static void
unpackExtent(Extent * const xi,Extent * const xo,f_expand * const f_decompress,f_unfilter * f_unf)127 unpackExtent(
128     Extent *const xi,  // input
129     Extent *const xo,  // output
130     f_expand *const f_decompress,
131     f_unfilter *f_unf
132 )
133 {
134     while (xo->size) {
135         struct b_info h;
136         //   Note: if h.sz_unc == h.sz_cpr then the block was not
137         //   compressible and is stored in its uncompressed form.
138 
139         // Read and check block sizes.
140         xread(xi, (char *)&h, sizeof(h));
141         if (h.sz_unc == 0) {                     // uncompressed size 0 -> EOF
142             if (h.sz_cpr != UPX_MAGIC_LE32)      // h.sz_cpr must be h->magic
143                 err_exit(2);
144             if (xi->size != 0)                 // all bytes must be written
145                 err_exit(3);
146             break;
147         }
148         if (h.sz_cpr <= 0) {
149             err_exit(4);
150 ERR_LAB
151         }
152         if (h.sz_cpr > h.sz_unc
153         ||  h.sz_unc > xo->size ) {
154             err_exit(5);
155         }
156         // Now we have:
157         //   assert(h.sz_cpr <= h.sz_unc);
158         //   assert(h.sz_unc > 0 && h.sz_unc <= blocksize);
159         //   assert(h.sz_cpr > 0 && h.sz_cpr <= blocksize);
160 
161         if (h.sz_cpr < h.sz_unc) { // Decompress block
162             nrv_uint out_len = h.sz_unc;  // EOF for lzma
163             int const j = (*f_decompress)((const unsigned char *)xi->buf, h.sz_cpr,
164                 (unsigned char *)xo->buf, &out_len, h.b_method);
165             if (j != 0 || out_len != (nrv_uint)h.sz_unc)
166                 err_exit(7);
167             if (h.b_ftid!=0 && f_unf) {  // have filter
168                 (*f_unf)((unsigned char *)xo->buf, out_len, h.b_cto8, h.b_ftid);
169             }
170             xi->buf  += h.sz_cpr;
171             xi->size -= h.sz_cpr;
172         }
173         else { // copy literal block
174             xread(xi, xo->buf, h.sz_cpr);
175         }
176         xo->buf  += h.sz_unc;
177         xo->size -= h.sz_unc;
178     }
179 }
180 
181 static void
upx_bzero(char * p,size_t len)182 upx_bzero(char *p, size_t len)
183 {
184     if (len) do {
185         *p++= 0;
186     } while (--len);
187 }
188 #define bzero upx_bzero
189 
190 
191 // The PF_* and PROT_* bits are {1,2,4}; the conversion table fits in 32 bits.
192 #define REP8(x) \
193     ((x)|((x)<<4)|((x)<<8)|((x)<<12)|((x)<<16)|((x)<<20)|((x)<<24)|((x)<<28))
194 #define EXP8(y) \
195     ((1&(y)) ? 0xf0f0f0f0 : (2&(y)) ? 0xff00ff00 : (4&(y)) ? 0xffff0000 : 0)
196 #define PF_TO_PROT(pf) \
197     ((PROT_READ|PROT_WRITE|PROT_EXEC) & ( \
198         ( (REP8(PROT_EXEC ) & EXP8(PF_X)) \
199          |(REP8(PROT_READ ) & EXP8(PF_R)) \
200          |(REP8(PROT_WRITE) & EXP8(PF_W)) \
201         ) >> ((pf & (PF_R|PF_W|PF_X))<<2) ))
202 
203 typedef struct {
204     unsigned magic;
205     unsigned nfat_arch;
206 } Fat_header;
207 typedef struct {
208     unsigned cputype;
209     unsigned cpusubtype;
210     unsigned offset;
211     unsigned size;
212     unsigned align;  /* power of 2 */
213 } Fat_arch;
214     enum e8 {
215         FAT_MAGIC = 0xcafebabe
216     };
217     enum e9 {
218         CPU_TYPE_I386      =          7,
219         CPU_TYPE_POWERPC   = 0x00000012,
220         CPU_TYPE_POWERPC64 = 0x01000012
221     };
222 
223 typedef struct {
224     unsigned magic;
225     unsigned cputype;
226     unsigned cpysubtype;
227     unsigned filetype;
228     unsigned ncmds;
229     unsigned sizeofcmds;
230     unsigned flags;
231 } Mach_header;
232         enum e0 {
233             MH_MAGIC = 0xfeedface
234         };
235         enum e2 {
236             MH_EXECUTE = 2
237         };
238         enum e3 {
239             MH_NOUNDEFS = 1
240         };
241 
242 typedef struct {
243     unsigned cmd;
244     unsigned cmdsize;
245 } Mach_load_command;
246         enum e4 {
247             LC_SEGMENT       = 0x1,
248             LC_THREAD        = 0x4,
249             LC_UNIXTHREAD    = 0x5,
250             LC_LOAD_DYLINKER = 0xe
251         };
252 
253 typedef struct {
254     unsigned cmd;
255     unsigned cmdsize;
256     char segname[16];
257     unsigned vmaddr;
258     unsigned vmsize;
259     unsigned fileoff;
260     unsigned filesize;
261     unsigned maxprot;
262     unsigned initprot;
263     unsigned nsects;
264     unsigned flags;
265 } Mach_segment_command;
266         enum e5 {
267             VM_PROT_READ = 1,
268             VM_PROT_WRITE = 2,
269             VM_PROT_EXECUTE = 4
270         };
271 
272 typedef struct {
273     unsigned srr0;      /* Instruction address register (PC; entry addr) */
274     unsigned srr1;      /* Machine state register (supervisor) */
275     unsigned  r0, r1, r2, r3, r4, r5, r6, r7;
276     unsigned  r8, r9,r10,r11,r12,r13,r14,r15;
277     unsigned r16,r17,r18,r19,r20,r21,r22,r23;
278     unsigned r24,r25,r26,r27,r28,r29,r30,r31;
279 
280     unsigned cr;        /* Condition register */
281     unsigned xer;       /* User's integer exception register */
282     unsigned lr;        /* Link register */
283     unsigned ctr;       /* Count register */
284     unsigned mq;        /* MQ register (601 only) */
285 
286     unsigned vrsave;    /* Vector Save Register */
287 } Mach_ppcle_thread_state64;
288 
289 typedef struct {
290     unsigned cmd;            /* LC_THREAD or  LC_UNIXTHREAD */
291     unsigned cmdsize;        /* total size of this command */
292     unsigned flavor;
293     unsigned count;          /* sizeof(following_thread_state)/4 */
294     Mach_ppcle_thread_state64 state;
295 } Mach_thread_command;
296         enum e6 {
297             PPC_THREAD_STATE = 1
298         };
299         enum e7 {
300             PPC_THREAD_STATE_COUNT = sizeof(Mach_ppcle_thread_state64)/4
301         };
302 
303 typedef union {
304     unsigned long offset;  /* from start of load command to string */
305     char *ptr;
306 } Mach_lc_str;
307 
308 #define MAP_FIXED     0x10
309 #define MAP_PRIVATE   0x02
310 #define MAP_ANON    0x1000
311 #define PROT_READ      1
312 #define PROT_WRITE     2
313 #define PROT_EXEC      4
314 
315 /* bug in crosstool/powerpc-750-linux-gnu/gcc-3.4.1-glibc-20040827:
316    unsigned long long off_t goes into registers (9,10) instead of (8,9).
317    Adjust in mmap(), pread(), and include/darwin.h .
318 */
319 extern char *mmap(char *, size_t, unsigned, unsigned, int, off_t_upx_stub);
320 ssize_t pread(int, void *, size_t, off_t_upx_stub);
321 
322 static Mach_ppcle_thread_state64 const *
do_xmap(Mach_header const * const mhdr,off_t_upx_stub const fat_offset,Extent * const xi,int const fdi,Mach_header ** mhdrpp,f_expand * const f_decompress,f_unfilter * const f_unf)323 do_xmap(
324     Mach_header const *const mhdr,
325     off_t_upx_stub const fat_offset,
326     Extent *const xi,
327     int const fdi,
328     Mach_header **mhdrpp,
329     f_expand *const f_decompress,
330     f_unfilter *const f_unf
331 )
332 {
333     Mach_segment_command const *sc = (Mach_segment_command const *)(1+ mhdr);
334     Mach_ppcle_thread_state64 const *entry = 0;
335     unsigned j;
336 
337     for ( j=0; j < mhdr->ncmds; ++j,
338         (sc = (Mach_segment_command const *)(void const *)(sc->cmdsize + (char const *)sc))
339     ) if (LC_SEGMENT==sc->cmd) {
340         Extent xo;
341         size_t mlen = xo.size = sc->filesize;
342         char  *addr = xo.buf  =                 (char *)(long)sc->vmaddr;
343         char *haddr =           sc->vmsize +                  addr;
344         size_t frag = (long)addr &~ PAGE_MASK;
345         addr -= frag;
346         mlen += frag;
347 
348         if (0!=mlen && addr != mmap(addr, mlen, VM_PROT_READ | VM_PROT_WRITE,
349                 MAP_FIXED | MAP_PRIVATE |
350                     ((xi || 0==sc->filesize) ? MAP_ANON : 0),
351                 ((0==sc->filesize) ? -1 : fdi), sc->fileoff + fat_offset) ) {
352             err_exit(8);
353         }
354         if (xi && 0!=sc->filesize) {
355             if (0==sc->fileoff /*&& 0!=mhdrpp*/) {
356                 *mhdrpp = (Mach_header *)(void *)addr;
357             }
358             unpackExtent(xi, &xo, f_decompress, f_unf);
359         }
360         /*bzero(addr, frag);*/  // fragment at lo end
361         frag = (-mlen) &~ PAGE_MASK;  // distance to next page boundary
362         bzero(mlen+addr, frag);  // fragment at hi end
363         if (0!=mlen && 0!=mprotect(addr, mlen, sc->initprot)) {
364             err_exit(10);
365 ERR_LAB
366         }
367         addr += mlen + frag;  /* page boundary on hi end */
368         if (addr < haddr) { // need pages for .bss
369             if (addr != mmap(addr, haddr - addr, sc->initprot,
370                     MAP_FIXED | MAP_PRIVATE | MAP_ANON, -1, 0 ) ) {
371                 err_exit(9);
372             }
373         }
374     }
375     else if (LC_UNIXTHREAD==sc->cmd || LC_THREAD==sc->cmd) {
376         Mach_thread_command const *const thrc = (Mach_thread_command const *)sc;
377         if (PPC_THREAD_STATE      ==thrc->flavor
378         &&  PPC_THREAD_STATE_COUNT==thrc->count ) {
379             entry = &thrc->state;
380         }
381     }
382     return entry;
383 }
384 
385 
386 /*************************************************************************
387 // upx_main - called by our entry code
388 //
389 **************************************************************************/
390 
391 Mach_ppcle_thread_state64 const *
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)392 upx_main(
393     struct l_info const *const li,
394     size_t volatile sz_compressed,  // total length
395     Mach_header *const mhdr,  // temp char[sz_mhdr] for decompressing
396     size_t const sz_mhdr,
397     f_expand *const f_decompress,
398     f_unfilter *const f_unf,
399     Mach_header **const mhdrpp  // Out: *mhdrpp= &real Mach_header
400 )
401 {
402     Mach_ppcle_thread_state64 const *entry;
403     off_t_upx_stub fat_offset = 0;
404     Extent xi, xo, xi0;
405     xi.buf  = CONST_CAST(char *, 1+ (struct p_info const *)(1+ li));  // &b_info
406     xi.size = sz_compressed - (sizeof(struct l_info) + sizeof(struct p_info));
407     xo.buf  = (char *)mhdr;
408     xo.size = ((struct b_info const *)(void const *)xi.buf)->sz_unc;
409     xi0 = xi;
410 
411     // Uncompress Macho headers
412     unpackExtent(&xi, &xo, f_decompress, 0);  // never filtered?
413 
414     entry = do_xmap(mhdr, fat_offset, &xi0, -1, mhdrpp, f_decompress, f_unf);
415 
416   { // Map dyld dynamic loader
417     Mach_load_command const *lc = (Mach_load_command const *)(1+ mhdr);
418     unsigned j;
419 
420     for (j=0; j < mhdr->ncmds; ++j,
421         (lc = (Mach_load_command const *)(void const *)(lc->cmdsize + (char const *)lc))
422     ) if (LC_LOAD_DYLINKER==lc->cmd) {
423         char const *const dyld_name = ((Mach_lc_str const *)(void const *)(1+ lc))->offset +
424             (char const *)lc;
425         int const fdi = open(dyld_name, O_RDONLY, 0);
426         if (0 > fdi) {
427             err_exit(18);
428         }
429 fat:
430         if ((ssize_t)sz_mhdr!=pread(fdi, (void *)mhdr, sz_mhdr, fat_offset)) {
431 ERR_LAB
432             err_exit(19);
433         }
434         switch (mhdr->magic) {
435         case MH_MAGIC: break;
436         case FAT_MAGIC: {
437             // stupid Apple: waste code and a page fault on EVERY execve
438             Fat_header const *const fh = (Fat_header const *)mhdr;
439             Fat_arch const *fa = (Fat_arch const *)(1+ fh);
440             for (j= 0; j < fh->nfat_arch; ++j, ++fa) {
441                 if (CPU_TYPE_POWERPC==fa->cputype) {
442                     fat_offset= fa->offset;
443                     goto fat;
444                 }
445             }
446         } break;
447         } // switch
448         entry = do_xmap(mhdr, fat_offset, 0, fdi, 0, 0, 0);
449         close(fdi);
450         break;
451     }
452   }
453 
454     return entry;
455 }
456 
457 /* vim:set ts=4 sw=4 et: */
458