1 // SPDX-License-Identifier: GPL-2.0
2 /****************************************************************************/
3 /*
4  *  linux/fs/binfmt_flat.c
5  *
6  *	Copyright (C) 2000-2003 David McCullough <davidm@snapgear.com>
7  *	Copyright (C) 2002 Greg Ungerer <gerg@snapgear.com>
8  *	Copyright (C) 2002 SnapGear, by Paul Dale <pauli@snapgear.com>
9  *	Copyright (C) 2000, 2001 Lineo, by David McCullough <davidm@lineo.com>
10  *  based heavily on:
11  *
12  *  linux/fs/binfmt_aout.c:
13  *      Copyright (C) 1991, 1992, 1996  Linus Torvalds
14  *  linux/fs/binfmt_flat.c for 2.0 kernel
15  *	    Copyright (C) 1998  Kenneth Albanowski <kjahds@kjahds.com>
16  *	JAN/99 -- coded full program relocation (gerg@snapgear.com)
17  */
18 
19 #define pr_fmt(fmt)	KBUILD_MODNAME ": " fmt
20 
21 #include <linux/kernel.h>
22 #include <linux/sched.h>
23 #include <linux/sched/task_stack.h>
24 #include <linux/mm.h>
25 #include <linux/mman.h>
26 #include <linux/errno.h>
27 #include <linux/signal.h>
28 #include <linux/string.h>
29 #include <linux/fs.h>
30 #include <linux/file.h>
31 #include <linux/ptrace.h>
32 #include <linux/user.h>
33 #include <linux/slab.h>
34 #include <linux/binfmts.h>
35 #include <linux/personality.h>
36 #include <linux/init.h>
37 #include <linux/flat.h>
38 #include <linux/uaccess.h>
39 #include <linux/vmalloc.h>
40 
41 #include <asm/byteorder.h>
42 #include <asm/unaligned.h>
43 #include <asm/cacheflush.h>
44 #include <asm/page.h>
45 #include <asm/flat.h>
46 
47 #ifndef flat_get_relocate_addr
48 #define flat_get_relocate_addr(rel)	(rel)
49 #endif
50 
51 /****************************************************************************/
52 
53 /*
54  * User data (data section and bss) needs to be aligned.
55  * We pick 0x20 here because it is the max value elf2flt has always
56  * used in producing FLAT files, and because it seems to be large
57  * enough to make all the gcc alignment related tests happy.
58  */
59 #define FLAT_DATA_ALIGN	(0x20)
60 
61 /*
62  * User data (stack) also needs to be aligned.
63  * Here we can be a bit looser than the data sections since this
64  * needs to only meet arch ABI requirements.
65  */
66 #define FLAT_STACK_ALIGN	max_t(unsigned long, sizeof(void *), ARCH_SLAB_MINALIGN)
67 
68 #define RELOC_FAILED 0xff00ff01		/* Relocation incorrect somewhere */
69 #define UNLOADED_LIB 0x7ff000ff		/* Placeholder for unused library */
70 
71 #ifdef CONFIG_BINFMT_SHARED_FLAT
72 #define	MAX_SHARED_LIBS			(4)
73 #else
74 #define	MAX_SHARED_LIBS			(1)
75 #endif
76 
77 struct lib_info {
78 	struct {
79 		unsigned long start_code;		/* Start of text segment */
80 		unsigned long start_data;		/* Start of data segment */
81 		unsigned long start_brk;		/* End of data segment */
82 		unsigned long text_len;			/* Length of text segment */
83 		unsigned long entry;			/* Start address for this module */
84 		unsigned long build_date;		/* When this one was compiled */
85 		bool loaded;				/* Has this library been loaded? */
86 	} lib_list[MAX_SHARED_LIBS];
87 };
88 
89 #ifdef CONFIG_BINFMT_SHARED_FLAT
90 static int load_flat_shared_library(int id, struct lib_info *p);
91 #endif
92 
93 static int load_flat_binary(struct linux_binprm *);
94 static int flat_core_dump(struct coredump_params *cprm);
95 
96 static struct linux_binfmt flat_format = {
97 	.module		= THIS_MODULE,
98 	.load_binary	= load_flat_binary,
99 	.core_dump	= flat_core_dump,
100 	.min_coredump	= PAGE_SIZE
101 };
102 
103 /****************************************************************************/
104 /*
105  * Routine writes a core dump image in the current directory.
106  * Currently only a stub-function.
107  */
108 
flat_core_dump(struct coredump_params * cprm)109 static int flat_core_dump(struct coredump_params *cprm)
110 {
111 	pr_warn("Process %s:%d received signr %d and should have core dumped\n",
112 		current->comm, current->pid, cprm->siginfo->si_signo);
113 	return 1;
114 }
115 
116 /****************************************************************************/
117 /*
118  * create_flat_tables() parses the env- and arg-strings in new user
119  * memory and creates the pointer tables from them, and puts their
120  * addresses on the "stack", recording the new stack pointer value.
121  */
122 
create_flat_tables(struct linux_binprm * bprm,unsigned long arg_start)123 static int create_flat_tables(struct linux_binprm *bprm, unsigned long arg_start)
124 {
125 	char __user *p;
126 	unsigned long __user *sp;
127 	long i, len;
128 
129 	p = (char __user *)arg_start;
130 	sp = (unsigned long __user *)current->mm->start_stack;
131 
132 	sp -= bprm->envc + 1;
133 	sp -= bprm->argc + 1;
134 	if (IS_ENABLED(CONFIG_BINFMT_FLAT_ARGVP_ENVP_ON_STACK))
135 		sp -= 2; /* argvp + envp */
136 	sp -= 1;  /* &argc */
137 
138 	current->mm->start_stack = (unsigned long)sp & -FLAT_STACK_ALIGN;
139 	sp = (unsigned long __user *)current->mm->start_stack;
140 
141 	__put_user(bprm->argc, sp++);
142 	if (IS_ENABLED(CONFIG_BINFMT_FLAT_ARGVP_ENVP_ON_STACK)) {
143 		unsigned long argv, envp;
144 		argv = (unsigned long)(sp + 2);
145 		envp = (unsigned long)(sp + 2 + bprm->argc + 1);
146 		__put_user(argv, sp++);
147 		__put_user(envp, sp++);
148 	}
149 
150 	current->mm->arg_start = (unsigned long)p;
151 	for (i = bprm->argc; i > 0; i--) {
152 		__put_user((unsigned long)p, sp++);
153 		len = strnlen_user(p, MAX_ARG_STRLEN);
154 		if (!len || len > MAX_ARG_STRLEN)
155 			return -EINVAL;
156 		p += len;
157 	}
158 	__put_user(0, sp++);
159 	current->mm->arg_end = (unsigned long)p;
160 
161 	current->mm->env_start = (unsigned long) p;
162 	for (i = bprm->envc; i > 0; i--) {
163 		__put_user((unsigned long)p, sp++);
164 		len = strnlen_user(p, MAX_ARG_STRLEN);
165 		if (!len || len > MAX_ARG_STRLEN)
166 			return -EINVAL;
167 		p += len;
168 	}
169 	__put_user(0, sp++);
170 	current->mm->env_end = (unsigned long)p;
171 
172 	return 0;
173 }
174 
175 /****************************************************************************/
176 
177 #ifdef CONFIG_BINFMT_ZFLAT
178 
179 #include <linux/zlib.h>
180 
181 #define LBUFSIZE	4000
182 
183 /* gzip flag byte */
184 #define ASCII_FLAG   0x01 /* bit 0 set: file probably ASCII text */
185 #define CONTINUATION 0x02 /* bit 1 set: continuation of multi-part gzip file */
186 #define EXTRA_FIELD  0x04 /* bit 2 set: extra field present */
187 #define ORIG_NAME    0x08 /* bit 3 set: original file name present */
188 #define COMMENT      0x10 /* bit 4 set: file comment present */
189 #define ENCRYPTED    0x20 /* bit 5 set: file is encrypted */
190 #define RESERVED     0xC0 /* bit 6,7:   reserved */
191 
decompress_exec(struct linux_binprm * bprm,loff_t fpos,char * dst,long len,int fd)192 static int decompress_exec(struct linux_binprm *bprm, loff_t fpos, char *dst,
193 		long len, int fd)
194 {
195 	unsigned char *buf;
196 	z_stream strm;
197 	int ret, retval;
198 
199 	pr_debug("decompress_exec(offset=%llx,buf=%p,len=%lx)\n", fpos, dst, len);
200 
201 	memset(&strm, 0, sizeof(strm));
202 	strm.workspace = kmalloc(zlib_inflate_workspacesize(), GFP_KERNEL);
203 	if (!strm.workspace)
204 		return -ENOMEM;
205 
206 	buf = kmalloc(LBUFSIZE, GFP_KERNEL);
207 	if (!buf) {
208 		retval = -ENOMEM;
209 		goto out_free;
210 	}
211 
212 	/* Read in first chunk of data and parse gzip header. */
213 	ret = kernel_read(bprm->file, buf, LBUFSIZE, &fpos);
214 
215 	strm.next_in = buf;
216 	strm.avail_in = ret;
217 	strm.total_in = 0;
218 
219 	retval = -ENOEXEC;
220 
221 	/* Check minimum size -- gzip header */
222 	if (ret < 10) {
223 		pr_debug("file too small?\n");
224 		goto out_free_buf;
225 	}
226 
227 	/* Check gzip magic number */
228 	if ((buf[0] != 037) || ((buf[1] != 0213) && (buf[1] != 0236))) {
229 		pr_debug("unknown compression magic?\n");
230 		goto out_free_buf;
231 	}
232 
233 	/* Check gzip method */
234 	if (buf[2] != 8) {
235 		pr_debug("unknown compression method?\n");
236 		goto out_free_buf;
237 	}
238 	/* Check gzip flags */
239 	if ((buf[3] & ENCRYPTED) || (buf[3] & CONTINUATION) ||
240 	    (buf[3] & RESERVED)) {
241 		pr_debug("unknown flags?\n");
242 		goto out_free_buf;
243 	}
244 
245 	ret = 10;
246 	if (buf[3] & EXTRA_FIELD) {
247 		ret += 2 + buf[10] + (buf[11] << 8);
248 		if (unlikely(ret >= LBUFSIZE)) {
249 			pr_debug("buffer overflow (EXTRA)?\n");
250 			goto out_free_buf;
251 		}
252 	}
253 	if (buf[3] & ORIG_NAME) {
254 		while (ret < LBUFSIZE && buf[ret++] != 0)
255 			;
256 		if (unlikely(ret == LBUFSIZE)) {
257 			pr_debug("buffer overflow (ORIG_NAME)?\n");
258 			goto out_free_buf;
259 		}
260 	}
261 	if (buf[3] & COMMENT) {
262 		while (ret < LBUFSIZE && buf[ret++] != 0)
263 			;
264 		if (unlikely(ret == LBUFSIZE)) {
265 			pr_debug("buffer overflow (COMMENT)?\n");
266 			goto out_free_buf;
267 		}
268 	}
269 
270 	strm.next_in += ret;
271 	strm.avail_in -= ret;
272 
273 	strm.next_out = dst;
274 	strm.avail_out = len;
275 	strm.total_out = 0;
276 
277 	if (zlib_inflateInit2(&strm, -MAX_WBITS) != Z_OK) {
278 		pr_debug("zlib init failed?\n");
279 		goto out_free_buf;
280 	}
281 
282 	while ((ret = zlib_inflate(&strm, Z_NO_FLUSH)) == Z_OK) {
283 		ret = kernel_read(bprm->file, buf, LBUFSIZE, &fpos);
284 		if (ret <= 0)
285 			break;
286 		len -= ret;
287 
288 		strm.next_in = buf;
289 		strm.avail_in = ret;
290 		strm.total_in = 0;
291 	}
292 
293 	if (ret < 0) {
294 		pr_debug("decompression failed (%d), %s\n",
295 			ret, strm.msg);
296 		goto out_zlib;
297 	}
298 
299 	retval = 0;
300 out_zlib:
301 	zlib_inflateEnd(&strm);
302 out_free_buf:
303 	kfree(buf);
304 out_free:
305 	kfree(strm.workspace);
306 	return retval;
307 }
308 
309 #endif /* CONFIG_BINFMT_ZFLAT */
310 
311 /****************************************************************************/
312 
313 static unsigned long
calc_reloc(unsigned long r,struct lib_info * p,int curid,int internalp)314 calc_reloc(unsigned long r, struct lib_info *p, int curid, int internalp)
315 {
316 	unsigned long addr;
317 	int id;
318 	unsigned long start_brk;
319 	unsigned long start_data;
320 	unsigned long text_len;
321 	unsigned long start_code;
322 
323 #ifdef CONFIG_BINFMT_SHARED_FLAT
324 	if (r == 0)
325 		id = curid;	/* Relocs of 0 are always self referring */
326 	else {
327 		id = (r >> 24) & 0xff;	/* Find ID for this reloc */
328 		r &= 0x00ffffff;	/* Trim ID off here */
329 	}
330 	if (id >= MAX_SHARED_LIBS) {
331 		pr_err("reference 0x%lx to shared library %d", r, id);
332 		goto failed;
333 	}
334 	if (curid != id) {
335 		if (internalp) {
336 			pr_err("reloc address 0x%lx not in same module "
337 			       "(%d != %d)", r, curid, id);
338 			goto failed;
339 		} else if (!p->lib_list[id].loaded &&
340 			   load_flat_shared_library(id, p) < 0) {
341 			pr_err("failed to load library %d", id);
342 			goto failed;
343 		}
344 		/* Check versioning information (i.e. time stamps) */
345 		if (p->lib_list[id].build_date && p->lib_list[curid].build_date &&
346 				p->lib_list[curid].build_date < p->lib_list[id].build_date) {
347 			pr_err("library %d is younger than %d", id, curid);
348 			goto failed;
349 		}
350 	}
351 #else
352 	id = 0;
353 #endif
354 
355 	start_brk = p->lib_list[id].start_brk;
356 	start_data = p->lib_list[id].start_data;
357 	start_code = p->lib_list[id].start_code;
358 	text_len = p->lib_list[id].text_len;
359 
360 	if (r > start_brk - start_data + text_len) {
361 		pr_err("reloc outside program 0x%lx (0 - 0x%lx/0x%lx)",
362 		       r, start_brk-start_data+text_len, text_len);
363 		goto failed;
364 	}
365 
366 	if (r < text_len)			/* In text segment */
367 		addr = r + start_code;
368 	else					/* In data segment */
369 		addr = r - text_len + start_data;
370 
371 	/* Range checked already above so doing the range tests is redundant...*/
372 	return addr;
373 
374 failed:
375 	pr_cont(", killing %s!\n", current->comm);
376 	send_sig(SIGSEGV, current, 0);
377 
378 	return RELOC_FAILED;
379 }
380 
381 /****************************************************************************/
382 
383 #ifdef CONFIG_BINFMT_FLAT_OLD
old_reloc(unsigned long rl)384 static void old_reloc(unsigned long rl)
385 {
386 	static const char *segment[] = { "TEXT", "DATA", "BSS", "*UNKNOWN*" };
387 	flat_v2_reloc_t	r;
388 	unsigned long __user *ptr;
389 	unsigned long val;
390 
391 	r.value = rl;
392 #if defined(CONFIG_COLDFIRE)
393 	ptr = (unsigned long __user *)(current->mm->start_code + r.reloc.offset);
394 #else
395 	ptr = (unsigned long __user *)(current->mm->start_data + r.reloc.offset);
396 #endif
397 	get_user(val, ptr);
398 
399 	pr_debug("Relocation of variable at DATASEG+%x "
400 		 "(address %p, currently %lx) into segment %s\n",
401 		 r.reloc.offset, ptr, val, segment[r.reloc.type]);
402 
403 	switch (r.reloc.type) {
404 	case OLD_FLAT_RELOC_TYPE_TEXT:
405 		val += current->mm->start_code;
406 		break;
407 	case OLD_FLAT_RELOC_TYPE_DATA:
408 		val += current->mm->start_data;
409 		break;
410 	case OLD_FLAT_RELOC_TYPE_BSS:
411 		val += current->mm->end_data;
412 		break;
413 	default:
414 		pr_err("Unknown relocation type=%x\n", r.reloc.type);
415 		break;
416 	}
417 	put_user(val, ptr);
418 
419 	pr_debug("Relocation became %lx\n", val);
420 }
421 #endif /* CONFIG_BINFMT_FLAT_OLD */
422 
423 /****************************************************************************/
424 
load_flat_file(struct linux_binprm * bprm,struct lib_info * libinfo,int id,unsigned long * extra_stack)425 static int load_flat_file(struct linux_binprm *bprm,
426 		struct lib_info *libinfo, int id, unsigned long *extra_stack)
427 {
428 	struct flat_hdr *hdr;
429 	unsigned long textpos, datapos, realdatastart;
430 	u32 text_len, data_len, bss_len, stack_len, full_data, flags;
431 	unsigned long len, memp, memp_size, extra, rlim;
432 	__be32 __user *reloc;
433 	u32 __user *rp;
434 	int i, rev, relocs;
435 	loff_t fpos;
436 	unsigned long start_code, end_code;
437 	ssize_t result;
438 	int ret;
439 
440 	hdr = ((struct flat_hdr *) bprm->buf);		/* exec-header */
441 
442 	text_len  = ntohl(hdr->data_start);
443 	data_len  = ntohl(hdr->data_end) - ntohl(hdr->data_start);
444 	bss_len   = ntohl(hdr->bss_end) - ntohl(hdr->data_end);
445 	stack_len = ntohl(hdr->stack_size);
446 	if (extra_stack) {
447 		stack_len += *extra_stack;
448 		*extra_stack = stack_len;
449 	}
450 	relocs    = ntohl(hdr->reloc_count);
451 	flags     = ntohl(hdr->flags);
452 	rev       = ntohl(hdr->rev);
453 	full_data = data_len + relocs * sizeof(unsigned long);
454 
455 	if (strncmp(hdr->magic, "bFLT", 4)) {
456 		/*
457 		 * Previously, here was a printk to tell people
458 		 *   "BINFMT_FLAT: bad header magic".
459 		 * But for the kernel which also use ELF FD-PIC format, this
460 		 * error message is confusing.
461 		 * because a lot of people do not manage to produce good
462 		 */
463 		ret = -ENOEXEC;
464 		goto err;
465 	}
466 
467 	if (flags & FLAT_FLAG_KTRACE)
468 		pr_info("Loading file: %s\n", bprm->filename);
469 
470 #ifdef CONFIG_BINFMT_FLAT_OLD
471 	if (rev != FLAT_VERSION && rev != OLD_FLAT_VERSION) {
472 		pr_err("bad flat file version 0x%x (supported 0x%lx and 0x%lx)\n",
473 		       rev, FLAT_VERSION, OLD_FLAT_VERSION);
474 		ret = -ENOEXEC;
475 		goto err;
476 	}
477 
478 	/* Don't allow old format executables to use shared libraries */
479 	if (rev == OLD_FLAT_VERSION && id != 0) {
480 		pr_err("shared libraries are not available before rev 0x%lx\n",
481 		       FLAT_VERSION);
482 		ret = -ENOEXEC;
483 		goto err;
484 	}
485 
486 	/*
487 	 * fix up the flags for the older format,  there were all kinds
488 	 * of endian hacks,  this only works for the simple cases
489 	 */
490 	if (rev == OLD_FLAT_VERSION &&
491 	   (flags || IS_ENABLED(CONFIG_BINFMT_FLAT_OLD_ALWAYS_RAM)))
492 		flags = FLAT_FLAG_RAM;
493 
494 #else /* CONFIG_BINFMT_FLAT_OLD */
495 	if (rev != FLAT_VERSION) {
496 		pr_err("bad flat file version 0x%x (supported 0x%lx)\n",
497 		       rev, FLAT_VERSION);
498 		ret = -ENOEXEC;
499 		goto err;
500 	}
501 #endif /* !CONFIG_BINFMT_FLAT_OLD */
502 
503 	/*
504 	 * Make sure the header params are sane.
505 	 * 28 bits (256 MB) is way more than reasonable in this case.
506 	 * If some top bits are set we have probable binary corruption.
507 	*/
508 	if ((text_len | data_len | bss_len | stack_len | full_data) >> 28) {
509 		pr_err("bad header\n");
510 		ret = -ENOEXEC;
511 		goto err;
512 	}
513 
514 #ifndef CONFIG_BINFMT_ZFLAT
515 	if (flags & (FLAT_FLAG_GZIP|FLAT_FLAG_GZDATA)) {
516 		pr_err("Support for ZFLAT executables is not enabled.\n");
517 		ret = -ENOEXEC;
518 		goto err;
519 	}
520 #endif
521 
522 	/*
523 	 * Check initial limits. This avoids letting people circumvent
524 	 * size limits imposed on them by creating programs with large
525 	 * arrays in the data or bss.
526 	 */
527 	rlim = rlimit(RLIMIT_DATA);
528 	if (rlim >= RLIM_INFINITY)
529 		rlim = ~0;
530 	if (data_len + bss_len > rlim) {
531 		ret = -ENOMEM;
532 		goto err;
533 	}
534 
535 	/* Flush all traces of the currently running executable */
536 	if (id == 0) {
537 		ret = flush_old_exec(bprm);
538 		if (ret)
539 			goto err;
540 
541 		/* OK, This is the point of no return */
542 		set_personality(PER_LINUX_32BIT);
543 		setup_new_exec(bprm);
544 	}
545 
546 	/*
547 	 * calculate the extra space we need to map in
548 	 */
549 	extra = max_t(unsigned long, bss_len + stack_len,
550 			relocs * sizeof(unsigned long));
551 
552 	/*
553 	 * there are a couple of cases here,  the separate code/data
554 	 * case,  and then the fully copied to RAM case which lumps
555 	 * it all together.
556 	 */
557 	if (!IS_ENABLED(CONFIG_MMU) && !(flags & (FLAT_FLAG_RAM|FLAT_FLAG_GZIP))) {
558 		/*
559 		 * this should give us a ROM ptr,  but if it doesn't we don't
560 		 * really care
561 		 */
562 		pr_debug("ROM mapping of file (we hope)\n");
563 
564 		textpos = vm_mmap(bprm->file, 0, text_len, PROT_READ|PROT_EXEC,
565 				  MAP_PRIVATE|MAP_EXECUTABLE, 0);
566 		if (!textpos || IS_ERR_VALUE(textpos)) {
567 			ret = textpos;
568 			if (!textpos)
569 				ret = -ENOMEM;
570 			pr_err("Unable to mmap process text, errno %d\n", ret);
571 			goto err;
572 		}
573 
574 		len = data_len + extra;
575 		len = PAGE_ALIGN(len);
576 		realdatastart = vm_mmap(NULL, 0, len,
577 			PROT_READ|PROT_WRITE|PROT_EXEC, MAP_PRIVATE, 0);
578 
579 		if (realdatastart == 0 || IS_ERR_VALUE(realdatastart)) {
580 			ret = realdatastart;
581 			if (!realdatastart)
582 				ret = -ENOMEM;
583 			pr_err("Unable to allocate RAM for process data, "
584 			       "errno %d\n", ret);
585 			vm_munmap(textpos, text_len);
586 			goto err;
587 		}
588 		datapos = ALIGN(realdatastart, FLAT_DATA_ALIGN);
589 
590 		pr_debug("Allocated data+bss+stack (%u bytes): %lx\n",
591 			 data_len + bss_len + stack_len, datapos);
592 
593 		fpos = ntohl(hdr->data_start);
594 #ifdef CONFIG_BINFMT_ZFLAT
595 		if (flags & FLAT_FLAG_GZDATA) {
596 			result = decompress_exec(bprm, fpos, (char *)datapos,
597 						 full_data, 0);
598 		} else
599 #endif
600 		{
601 			result = read_code(bprm->file, datapos, fpos,
602 					full_data);
603 		}
604 		if (IS_ERR_VALUE(result)) {
605 			ret = result;
606 			pr_err("Unable to read data+bss, errno %d\n", ret);
607 			vm_munmap(textpos, text_len);
608 			vm_munmap(realdatastart, len);
609 			goto err;
610 		}
611 
612 		reloc = (__be32 __user *)
613 			(datapos + (ntohl(hdr->reloc_start) - text_len));
614 		memp = realdatastart;
615 		memp_size = len;
616 	} else {
617 
618 		len = text_len + data_len + extra;
619 		len = PAGE_ALIGN(len);
620 		textpos = vm_mmap(NULL, 0, len,
621 			PROT_READ | PROT_EXEC | PROT_WRITE, MAP_PRIVATE, 0);
622 
623 		if (!textpos || IS_ERR_VALUE(textpos)) {
624 			ret = textpos;
625 			if (!textpos)
626 				ret = -ENOMEM;
627 			pr_err("Unable to allocate RAM for process text/data, "
628 			       "errno %d\n", ret);
629 			goto err;
630 		}
631 
632 		realdatastart = textpos + ntohl(hdr->data_start);
633 		datapos = ALIGN(realdatastart, FLAT_DATA_ALIGN);
634 
635 		reloc = (__be32 __user *)
636 			(datapos + (ntohl(hdr->reloc_start) - text_len));
637 		memp = textpos;
638 		memp_size = len;
639 #ifdef CONFIG_BINFMT_ZFLAT
640 		/*
641 		 * load it all in and treat it like a RAM load from now on
642 		 */
643 		if (flags & FLAT_FLAG_GZIP) {
644 #ifndef CONFIG_MMU
645 			result = decompress_exec(bprm, sizeof(struct flat_hdr),
646 					 (((char *)textpos) + sizeof(struct flat_hdr)),
647 					 (text_len + full_data
648 						  - sizeof(struct flat_hdr)),
649 					 0);
650 			if (datapos != realdatastart)
651 				memmove((void *)datapos, (void *)realdatastart,
652 						full_data);
653 #else
654 			/*
655 			 * This is used on MMU systems mainly for testing.
656 			 * Let's use a kernel buffer to simplify things.
657 			 */
658 			long unz_text_len = text_len - sizeof(struct flat_hdr);
659 			long unz_len = unz_text_len + full_data;
660 			char *unz_data = vmalloc(unz_len);
661 			if (!unz_data) {
662 				result = -ENOMEM;
663 			} else {
664 				result = decompress_exec(bprm, sizeof(struct flat_hdr),
665 							 unz_data, unz_len, 0);
666 				if (result == 0 &&
667 				    (copy_to_user((void __user *)textpos + sizeof(struct flat_hdr),
668 						  unz_data, unz_text_len) ||
669 				     copy_to_user((void __user *)datapos,
670 						  unz_data + unz_text_len, full_data)))
671 					result = -EFAULT;
672 				vfree(unz_data);
673 			}
674 #endif
675 		} else if (flags & FLAT_FLAG_GZDATA) {
676 			result = read_code(bprm->file, textpos, 0, text_len);
677 			if (!IS_ERR_VALUE(result)) {
678 #ifndef CONFIG_MMU
679 				result = decompress_exec(bprm, text_len, (char *) datapos,
680 						 full_data, 0);
681 #else
682 				char *unz_data = vmalloc(full_data);
683 				if (!unz_data) {
684 					result = -ENOMEM;
685 				} else {
686 					result = decompress_exec(bprm, text_len,
687 						       unz_data, full_data, 0);
688 					if (result == 0 &&
689 					    copy_to_user((void __user *)datapos,
690 							 unz_data, full_data))
691 						result = -EFAULT;
692 					vfree(unz_data);
693 				}
694 #endif
695 			}
696 		} else
697 #endif /* CONFIG_BINFMT_ZFLAT */
698 		{
699 			result = read_code(bprm->file, textpos, 0, text_len);
700 			if (!IS_ERR_VALUE(result))
701 				result = read_code(bprm->file, datapos,
702 						   ntohl(hdr->data_start),
703 						   full_data);
704 		}
705 		if (IS_ERR_VALUE(result)) {
706 			ret = result;
707 			pr_err("Unable to read code+data+bss, errno %d\n", ret);
708 			vm_munmap(textpos, text_len + data_len + extra);
709 			goto err;
710 		}
711 	}
712 
713 	start_code = textpos + sizeof(struct flat_hdr);
714 	end_code = textpos + text_len;
715 	text_len -= sizeof(struct flat_hdr); /* the real code len */
716 
717 	/* The main program needs a little extra setup in the task structure */
718 	if (id == 0) {
719 		current->mm->start_code = start_code;
720 		current->mm->end_code = end_code;
721 		current->mm->start_data = datapos;
722 		current->mm->end_data = datapos + data_len;
723 		/*
724 		 * set up the brk stuff, uses any slack left in data/bss/stack
725 		 * allocation.  We put the brk after the bss (between the bss
726 		 * and stack) like other platforms.
727 		 * Userspace code relies on the stack pointer starting out at
728 		 * an address right at the end of a page.
729 		 */
730 		current->mm->start_brk = datapos + data_len + bss_len;
731 		current->mm->brk = (current->mm->start_brk + 3) & ~3;
732 #ifndef CONFIG_MMU
733 		current->mm->context.end_brk = memp + memp_size - stack_len;
734 #endif
735 	}
736 
737 	if (flags & FLAT_FLAG_KTRACE) {
738 		pr_info("Mapping is %lx, Entry point is %x, data_start is %x\n",
739 			textpos, 0x00ffffff&ntohl(hdr->entry), ntohl(hdr->data_start));
740 		pr_info("%s %s: TEXT=%lx-%lx DATA=%lx-%lx BSS=%lx-%lx\n",
741 			id ? "Lib" : "Load", bprm->filename,
742 			start_code, end_code, datapos, datapos + data_len,
743 			datapos + data_len, (datapos + data_len + bss_len + 3) & ~3);
744 	}
745 
746 	/* Store the current module values into the global library structure */
747 	libinfo->lib_list[id].start_code = start_code;
748 	libinfo->lib_list[id].start_data = datapos;
749 	libinfo->lib_list[id].start_brk = datapos + data_len + bss_len;
750 	libinfo->lib_list[id].text_len = text_len;
751 	libinfo->lib_list[id].loaded = 1;
752 	libinfo->lib_list[id].entry = (0x00ffffff & ntohl(hdr->entry)) + textpos;
753 	libinfo->lib_list[id].build_date = ntohl(hdr->build_date);
754 
755 	/*
756 	 * We just load the allocations into some temporary memory to
757 	 * help simplify all this mumbo jumbo
758 	 *
759 	 * We've got two different sections of relocation entries.
760 	 * The first is the GOT which resides at the beginning of the data segment
761 	 * and is terminated with a -1.  This one can be relocated in place.
762 	 * The second is the extra relocation entries tacked after the image's
763 	 * data segment. These require a little more processing as the entry is
764 	 * really an offset into the image which contains an offset into the
765 	 * image.
766 	 */
767 	if (flags & FLAT_FLAG_GOTPIC) {
768 		for (rp = (u32 __user *)datapos; ; rp++) {
769 			u32 addr, rp_val;
770 			if (get_user(rp_val, rp))
771 				return -EFAULT;
772 			if (rp_val == 0xffffffff)
773 				break;
774 			if (rp_val) {
775 				addr = calc_reloc(rp_val, libinfo, id, 0);
776 				if (addr == RELOC_FAILED) {
777 					ret = -ENOEXEC;
778 					goto err;
779 				}
780 				if (put_user(addr, rp))
781 					return -EFAULT;
782 			}
783 		}
784 	}
785 
786 	/*
787 	 * Now run through the relocation entries.
788 	 * We've got to be careful here as C++ produces relocatable zero
789 	 * entries in the constructor and destructor tables which are then
790 	 * tested for being not zero (which will always occur unless we're
791 	 * based from address zero).  This causes an endless loop as __start
792 	 * is at zero.  The solution used is to not relocate zero addresses.
793 	 * This has the negative side effect of not allowing a global data
794 	 * reference to be statically initialised to _stext (I've moved
795 	 * __start to address 4 so that is okay).
796 	 */
797 	if (rev > OLD_FLAT_VERSION) {
798 		for (i = 0; i < relocs; i++) {
799 			u32 addr, relval;
800 			__be32 tmp;
801 
802 			/*
803 			 * Get the address of the pointer to be
804 			 * relocated (of course, the address has to be
805 			 * relocated first).
806 			 */
807 			if (get_user(tmp, reloc + i))
808 				return -EFAULT;
809 			relval = ntohl(tmp);
810 			addr = flat_get_relocate_addr(relval);
811 			rp = (u32 __user *)calc_reloc(addr, libinfo, id, 1);
812 			if (rp == (u32 __user *)RELOC_FAILED) {
813 				ret = -ENOEXEC;
814 				goto err;
815 			}
816 
817 			/* Get the pointer's value.  */
818 			ret = flat_get_addr_from_rp(rp, relval, flags, &addr);
819 			if (unlikely(ret))
820 				goto err;
821 
822 			if (addr != 0) {
823 				/*
824 				 * Do the relocation.  PIC relocs in the data section are
825 				 * already in target order
826 				 */
827 				if ((flags & FLAT_FLAG_GOTPIC) == 0) {
828 					/*
829 					 * Meh, the same value can have a different
830 					 * byte order based on a flag..
831 					 */
832 					addr = ntohl((__force __be32)addr);
833 				}
834 				addr = calc_reloc(addr, libinfo, id, 0);
835 				if (addr == RELOC_FAILED) {
836 					ret = -ENOEXEC;
837 					goto err;
838 				}
839 
840 				/* Write back the relocated pointer.  */
841 				ret = flat_put_addr_at_rp(rp, addr, relval);
842 				if (unlikely(ret))
843 					goto err;
844 			}
845 		}
846 #ifdef CONFIG_BINFMT_FLAT_OLD
847 	} else {
848 		for (i = 0; i < relocs; i++) {
849 			__be32 relval;
850 			if (get_user(relval, reloc + i))
851 				return -EFAULT;
852 			old_reloc(ntohl(relval));
853 		}
854 #endif /* CONFIG_BINFMT_FLAT_OLD */
855 	}
856 
857 	flush_icache_range(start_code, end_code);
858 
859 	/* zero the BSS,  BRK and stack areas */
860 	if (clear_user((void __user *)(datapos + data_len), bss_len +
861 		       (memp + memp_size - stack_len -		/* end brk */
862 		       libinfo->lib_list[id].start_brk) +	/* start brk */
863 		       stack_len))
864 		return -EFAULT;
865 
866 	return 0;
867 err:
868 	return ret;
869 }
870 
871 
872 /****************************************************************************/
873 #ifdef CONFIG_BINFMT_SHARED_FLAT
874 
875 /*
876  * Load a shared library into memory.  The library gets its own data
877  * segment (including bss) but not argv/argc/environ.
878  */
879 
load_flat_shared_library(int id,struct lib_info * libs)880 static int load_flat_shared_library(int id, struct lib_info *libs)
881 {
882 	/*
883 	 * This is a fake bprm struct; only the members "buf", "file" and
884 	 * "filename" are actually used.
885 	 */
886 	struct linux_binprm bprm;
887 	int res;
888 	char buf[16];
889 	loff_t pos = 0;
890 
891 	memset(&bprm, 0, sizeof(bprm));
892 
893 	/* Create the file name */
894 	sprintf(buf, "/lib/lib%d.so", id);
895 
896 	/* Open the file up */
897 	bprm.filename = buf;
898 	bprm.file = open_exec(bprm.filename);
899 	res = PTR_ERR(bprm.file);
900 	if (IS_ERR(bprm.file))
901 		return res;
902 
903 	res = kernel_read(bprm.file, bprm.buf, BINPRM_BUF_SIZE, &pos);
904 
905 	if (res >= 0)
906 		res = load_flat_file(&bprm, libs, id, NULL);
907 
908 	allow_write_access(bprm.file);
909 	fput(bprm.file);
910 
911 	return res;
912 }
913 
914 #endif /* CONFIG_BINFMT_SHARED_FLAT */
915 /****************************************************************************/
916 
917 /*
918  * These are the functions used to load flat style executables and shared
919  * libraries.  There is no binary dependent code anywhere else.
920  */
921 
load_flat_binary(struct linux_binprm * bprm)922 static int load_flat_binary(struct linux_binprm *bprm)
923 {
924 	struct lib_info libinfo;
925 	struct pt_regs *regs = current_pt_regs();
926 	unsigned long stack_len = 0;
927 	unsigned long start_addr;
928 	int res;
929 	int i, j;
930 
931 	memset(&libinfo, 0, sizeof(libinfo));
932 
933 	/*
934 	 * We have to add the size of our arguments to our stack size
935 	 * otherwise it's too easy for users to create stack overflows
936 	 * by passing in a huge argument list.  And yes,  we have to be
937 	 * pedantic and include space for the argv/envp array as it may have
938 	 * a lot of entries.
939 	 */
940 #ifndef CONFIG_MMU
941 	stack_len += PAGE_SIZE * MAX_ARG_PAGES - bprm->p; /* the strings */
942 #endif
943 	stack_len += (bprm->argc + 1) * sizeof(char *);   /* the argv array */
944 	stack_len += (bprm->envc + 1) * sizeof(char *);   /* the envp array */
945 	stack_len = ALIGN(stack_len, FLAT_STACK_ALIGN);
946 
947 	res = load_flat_file(bprm, &libinfo, 0, &stack_len);
948 	if (res < 0)
949 		return res;
950 
951 	/* Update data segment pointers for all libraries */
952 	for (i = 0; i < MAX_SHARED_LIBS; i++) {
953 		if (!libinfo.lib_list[i].loaded)
954 			continue;
955 		for (j = 0; j < MAX_SHARED_LIBS; j++) {
956 			unsigned long val = libinfo.lib_list[j].loaded ?
957 				libinfo.lib_list[j].start_data : UNLOADED_LIB;
958 			unsigned long __user *p = (unsigned long __user *)
959 				libinfo.lib_list[i].start_data;
960 			p -= j + 1;
961 			if (put_user(val, p))
962 				return -EFAULT;
963 		}
964 	}
965 
966 	install_exec_creds(bprm);
967 
968 	set_binfmt(&flat_format);
969 
970 #ifdef CONFIG_MMU
971 	res = setup_arg_pages(bprm, STACK_TOP, EXSTACK_DEFAULT);
972 	if (!res)
973 		res = create_flat_tables(bprm, bprm->p);
974 #else
975 	/* Stash our initial stack pointer into the mm structure */
976 	current->mm->start_stack =
977 		((current->mm->context.end_brk + stack_len + 3) & ~3) - 4;
978 	pr_debug("sp=%lx\n", current->mm->start_stack);
979 
980 	/* copy the arg pages onto the stack */
981 	res = transfer_args_to_stack(bprm, &current->mm->start_stack);
982 	if (!res)
983 		res = create_flat_tables(bprm, current->mm->start_stack);
984 #endif
985 	if (res)
986 		return res;
987 
988 	/* Fake some return addresses to ensure the call chain will
989 	 * initialise library in order for us.  We are required to call
990 	 * lib 1 first, then 2, ... and finally the main program (id 0).
991 	 */
992 	start_addr = libinfo.lib_list[0].entry;
993 
994 #ifdef CONFIG_BINFMT_SHARED_FLAT
995 	for (i = MAX_SHARED_LIBS-1; i > 0; i--) {
996 		if (libinfo.lib_list[i].loaded) {
997 			/* Push previos first to call address */
998 			unsigned long __user *sp;
999 			current->mm->start_stack -= sizeof(unsigned long);
1000 			sp = (unsigned long __user *)current->mm->start_stack;
1001 			__put_user(start_addr, sp);
1002 			start_addr = libinfo.lib_list[i].entry;
1003 		}
1004 	}
1005 #endif
1006 
1007 #ifdef FLAT_PLAT_INIT
1008 	FLAT_PLAT_INIT(regs);
1009 #endif
1010 
1011 	finalize_exec(bprm);
1012 	pr_debug("start_thread(regs=0x%p, entry=0x%lx, start_stack=0x%lx)\n",
1013 		 regs, start_addr, current->mm->start_stack);
1014 	start_thread(regs, start_addr, current->mm->start_stack);
1015 
1016 	return 0;
1017 }
1018 
1019 /****************************************************************************/
1020 
init_flat_binfmt(void)1021 static int __init init_flat_binfmt(void)
1022 {
1023 	register_binfmt(&flat_format);
1024 	return 0;
1025 }
1026 core_initcall(init_flat_binfmt);
1027 
1028 /****************************************************************************/
1029