1/*
2 * Copyright (c) 2000-2006 Apple Computer, Inc. All rights reserved.
3 *
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
14 *
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
17 *
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
25 *
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27 */
28/* Copyright (c) 1991 NeXT Computer, Inc.  All rights reserved.
29 *
30 *	File:	bsd/kern/kern_core.c
31 *
32 *	This file contains machine independent code for performing core dumps.
33 *
34 */
35
36#include <mach/vm_param.h>
37#include <mach/thread_status.h>
38
39#include <sys/param.h>
40#include <sys/systm.h>
41#include <sys/signalvar.h>
42#include <sys/resourcevar.h>
43#include <sys/namei.h>
44#include <sys/vnode_internal.h>
45#include <sys/proc_internal.h>
46#include <sys/kauth.h>
47#include <sys/timeb.h>
48#include <sys/times.h>
49#include <sys/acct.h>
50#include <sys/file_internal.h>
51#include <sys/uio.h>
52#include <sys/kernel.h>
53#include <sys/stat.h>
54
55#include <mach-o/loader.h>
56#include <mach/vm_region.h>
57#include <mach/vm_statistics.h>
58
59#include <vm/vm_kern.h>
60#include <vm/vm_protos.h> /* last */
61#include <vm/vm_map.h>		/* current_map() */
62#include <mach/mach_vm.h>	/* mach_vm_region_recurse() */
63#include <mach/task.h>		/* task_suspend() */
64#include <kern/task.h>		/* get_task_numacts() */
65
66#include <security/audit/audit.h>
67
68typedef struct {
69	int	flavor;			/* the number for this flavor */
70	mach_msg_type_number_t	count;	/* count of ints in this flavor */
71} mythread_state_flavor_t;
72
73#if defined (__i386__) || defined (__x86_64__)
74mythread_state_flavor_t thread_flavor_array [] = {
75		{x86_THREAD_STATE, x86_THREAD_STATE_COUNT},
76		{x86_FLOAT_STATE, x86_FLOAT_STATE_COUNT},
77		{x86_EXCEPTION_STATE, x86_EXCEPTION_STATE_COUNT},
78		};
79int mynum_flavors=3;
80#elif defined(__arm__)
81mythread_state_flavor_t thread_flavor_array [] = {
82		{ARM_THREAD_STATE, ARM_THREAD_STATE_COUNT},
83		{ARM_VFP_STATE, ARM_VFP_STATE_COUNT},
84		{ARM_EXCEPTION_STATE, ARM_EXCEPTION_STATE_COUNT},
85        {ARM_DEBUG_STATE, ARM_DEBUG_STATE_COUNT}
86		};
87int mynum_flavors=4;
88#else
89#error architecture not supported
90#endif
91
92
93typedef struct {
94	vm_offset_t header;
95	int  hoffset;
96	mythread_state_flavor_t *flavors;
97	int tstate_size;
98	int flavor_count;
99} tir_t;
100
101/* XXX should be static */
102void collectth_state(thread_t th_act, void *tirp);
103
104/* XXX not in a Mach header anywhere */
105kern_return_t thread_getstatus(register thread_t act, int flavor,
106	thread_state_t tstate, mach_msg_type_number_t *count);
107void task_act_iterate_wth_args(task_t, void(*)(thread_t, void *), void *);
108
109static cpu_type_t process_cpu_type(proc_t proc);
110static cpu_type_t process_cpu_subtype(proc_t proc);
111
112#ifdef SECURE_KERNEL
113__private_extern__ int do_coredump = 0;	/* default: don't dump cores */
114#else
115__private_extern__ int do_coredump = 1;	/* default: dump cores */
116#endif
117__private_extern__ int sugid_coredump = 0; /* default: but not SGUID binaries */
118
119
120/* cpu_type returns only the most generic indication of the current CPU. */
121/* in a core we want to know the kind of process. */
122
123static cpu_type_t
124process_cpu_type(proc_t core_proc)
125{
126	cpu_type_t what_we_think;
127#if defined (__i386__) || defined (__x86_64__)
128    if (IS_64BIT_PROCESS(core_proc)) {
129		what_we_think = CPU_TYPE_X86_64;
130	} else {
131		what_we_think = CPU_TYPE_I386;
132	}
133#elif defined (__arm__)
134	what_we_think = CPU_TYPE_ARM;
135#endif
136	return what_we_think;
137}
138
139static cpu_type_t
140process_cpu_subtype(proc_t core_proc)
141{
142	cpu_type_t what_we_think;
143#if defined (__i386__) || defined (__x86_64__)
144    if (IS_64BIT_PROCESS(core_proc)) {
145		what_we_think = CPU_SUBTYPE_X86_64_ALL;
146	} else {
147		what_we_think = CPU_SUBTYPE_I386_ALL;
148	}
149#elif defined (__arm__)
150	what_we_think = CPU_SUBTYPE_ARM_ALL;
151#endif
152	return what_we_think;
153}
154
155void
156collectth_state(thread_t th_act, void *tirp)
157{
158	vm_offset_t	header;
159	int  hoffset, i ;
160	mythread_state_flavor_t *flavors;
161	struct thread_command	*tc;
162	tir_t *t = (tir_t *)tirp;
163
164		/*
165		 *	Fill in thread command structure.
166		 */
167		header = t->header;
168		hoffset = t->hoffset;
169		flavors = t->flavors;
170
171		tc = (struct thread_command *) (header + hoffset);
172		tc->cmd = LC_THREAD;
173		tc->cmdsize = sizeof(struct thread_command)
174				+ t->tstate_size;
175		hoffset += sizeof(struct thread_command);
176		/*
177		 * Follow with a struct thread_state_flavor and
178		 * the appropriate thread state struct for each
179		 * thread state flavor.
180		 */
181		for (i = 0; i < t->flavor_count; i++) {
182			*(mythread_state_flavor_t *)(header+hoffset) =
183			  flavors[i];
184			hoffset += sizeof(mythread_state_flavor_t);
185			thread_getstatus(th_act, flavors[i].flavor,
186					(thread_state_t)(header+hoffset),
187					&flavors[i].count);
188			hoffset += flavors[i].count*sizeof(int);
189		}
190
191		t->hoffset = hoffset;
192}
193
194
195/*
196 * coredump
197 *
198 * Description:	Create a core image on the file "core" for the process
199 *		indicated
200 *
201 * Parameters:	core_proc			Process to dump core [*]
202 *
203 * Returns:	0				Success
204 *		EFAULT				Failed
205 *
206 * IMPORTANT:	This function can only be called on the current process, due
207 *		to assumptions below; see variable declaration section for
208 *		details.
209 */
210#define	MAX_TSTATE_FLAVORS	10
211int
212coredump(proc_t core_proc)
213{
214/* Begin assumptions that limit us to only the current process */
215	vfs_context_t ctx = vfs_context_current();
216	vm_map_t	map = current_map();
217	task_t		task = current_task();
218/* End assumptions */
219	kauth_cred_t cred = vfs_context_ucred(ctx);
220	int error = 0;
221	struct vnode_attr va;
222	int		thread_count, segment_count;
223	int		command_size, header_size, tstate_size;
224	int		hoffset;
225	off_t		foffset;
226	mach_vm_offset_t vmoffset;
227	vm_offset_t	header;
228	mach_vm_size_t	vmsize;
229	vm_prot_t	prot;
230	vm_prot_t	maxprot;
231	vm_inherit_t	inherit;
232	int		error1 = 0;
233	char		stack_name[MAXCOMLEN+6];
234	char		*alloced_name = NULL;
235	char		*name;
236	mythread_state_flavor_t flavors[MAX_TSTATE_FLAVORS];
237	vm_size_t	mapsize;
238	int		i;
239	uint32_t nesting_depth = 0;
240	kern_return_t	kret;
241	struct vm_region_submap_info_64 vbr;
242	mach_msg_type_number_t vbrcount = 0;
243	tir_t tir1;
244	struct vnode * vp;
245	struct mach_header	*mh = NULL;	/* protected by is_64 */
246	struct mach_header_64	*mh64 = NULL;	/* protected by is_64 */
247	int		is_64 = 0;
248	size_t		mach_header_sz = sizeof(struct mach_header);
249	size_t		segment_command_sz = sizeof(struct segment_command);
250
251	if (do_coredump == 0 ||		/* Not dumping at all */
252	    ( (sugid_coredump == 0) &&	/* Not dumping SUID/SGID binaries */
253	      ( (kauth_cred_getsvuid(cred) != kauth_cred_getruid(cred)) ||
254	        (kauth_cred_getsvgid(cred) != kauth_cred_getrgid(cred))))) {
255
256#if CONFIG_AUDIT
257		audit_proc_coredump(core_proc, NULL, EFAULT);
258#endif
259		return (EFAULT);
260	}
261
262	if (IS_64BIT_PROCESS(core_proc)) {
263		is_64 = 1;
264		mach_header_sz = sizeof(struct mach_header_64);
265		segment_command_sz = sizeof(struct segment_command_64);
266	}
267
268	mapsize = get_vmmap_size(map);
269
270	if (mapsize >=  core_proc->p_rlimit[RLIMIT_CORE].rlim_cur)
271		return (EFAULT);
272	(void) task_suspend(task);
273
274	MALLOC(alloced_name, char *, MAXPATHLEN, M_TEMP, M_NOWAIT | M_ZERO);
275
276	/* create name according to sysctl'able format string */
277	/* if name creation fails, fall back to historical behaviour... */
278	if (alloced_name == NULL ||
279	    proc_core_name(core_proc->p_comm, kauth_cred_getuid(cred),
280			   core_proc->p_pid, alloced_name, MAXPATHLEN)) {
281		snprintf(stack_name, sizeof(stack_name),
282			 "/cores/core.%d", core_proc->p_pid);
283		name = stack_name;
284	} else
285		name = alloced_name;
286
287	if ((error = vnode_open(name, (O_CREAT | FWRITE | O_NOFOLLOW), S_IRUSR, VNODE_LOOKUP_NOFOLLOW, &vp, ctx)))
288		goto out2;
289
290	VATTR_INIT(&va);
291	VATTR_WANTED(&va, va_nlink);
292	/* Don't dump to non-regular files or files with links. */
293	if (vp->v_type != VREG ||
294	    vnode_getattr(vp, &va, ctx) || va.va_nlink != 1) {
295		error = EFAULT;
296		goto out;
297	}
298
299	VATTR_INIT(&va);	/* better to do it here than waste more stack in vnode_setsize */
300	VATTR_SET(&va, va_data_size, 0);
301	vnode_setattr(vp, &va, ctx);
302	core_proc->p_acflag |= ACORE;
303
304	/*
305	 *	If the task is modified while dumping the file
306	 *	(e.g., changes in threads or VM, the resulting
307	 *	file will not necessarily be correct.
308	 */
309
310	thread_count = get_task_numacts(task);
311	segment_count = get_vmmap_entries(map);	/* XXX */
312	tir1.flavor_count = sizeof(thread_flavor_array)/sizeof(mythread_state_flavor_t);
313	bcopy(thread_flavor_array, flavors,sizeof(thread_flavor_array));
314	tstate_size = 0;
315	for (i = 0; i < tir1.flavor_count; i++)
316		tstate_size += sizeof(mythread_state_flavor_t) +
317		  (flavors[i].count * sizeof(int));
318	command_size = segment_count * segment_command_sz +
319	  thread_count*sizeof(struct thread_command) +
320	  tstate_size*thread_count;
321
322	header_size = command_size + mach_header_sz;
323
324	if (kmem_alloc(kernel_map, &header, (vm_size_t)header_size) != KERN_SUCCESS) {
325		error = ENOMEM;
326		goto out;
327	}
328
329	/*
330	 *	Set up Mach-O header.
331	 */
332	if (is_64) {
333		mh64 = (struct mach_header_64 *)header;
334		mh64->magic = MH_MAGIC_64;
335		mh64->cputype = process_cpu_type(core_proc);
336		mh64->cpusubtype = process_cpu_subtype(core_proc);
337		mh64->filetype = MH_CORE;
338		mh64->ncmds = segment_count + thread_count;
339		mh64->sizeofcmds = command_size;
340		mh64->reserved = 0;		/* 8 byte alignment */
341	} else {
342		mh = (struct mach_header *)header;
343		mh->magic = MH_MAGIC;
344		mh->cputype = process_cpu_type(core_proc);
345		mh->cpusubtype = process_cpu_subtype(core_proc);
346		mh->filetype = MH_CORE;
347		mh->ncmds = segment_count + thread_count;
348		mh->sizeofcmds = command_size;
349	}
350
351	hoffset = mach_header_sz;	/* offset into header */
352	foffset = round_page(header_size);	/* offset into file */
353	vmoffset = MACH_VM_MIN_ADDRESS;		/* offset into VM */
354
355	/*
356	 * We use to check for an error, here, now we try and get
357	 * as much as we can
358	 */
359	while (segment_count > 0) {
360		struct segment_command		*sc;
361		struct segment_command_64	*sc64;
362
363		/*
364		 *	Get region information for next region.
365		 */
366
367		while (1) {
368			vbrcount = VM_REGION_SUBMAP_INFO_COUNT_64;
369			if((kret = mach_vm_region_recurse(map,
370					&vmoffset, &vmsize, &nesting_depth,
371					(vm_region_recurse_info_t)&vbr,
372					&vbrcount)) != KERN_SUCCESS) {
373				break;
374			}
375			/*
376			 * If we get a valid mapping back, but we're dumping
377			 * a 32 bit process,  and it's over the allowable
378			 * address space of a 32 bit process, it's the same
379			 * as if mach_vm_region_recurse() failed.
380			 */
381			if (!(is_64) &&
382			    (vmoffset + vmsize > VM_MAX_ADDRESS)) {
383			    	kret = KERN_INVALID_ADDRESS;
384				break;
385			}
386			if(vbr.is_submap) {
387				nesting_depth++;
388				continue;
389			} else {
390				break;
391			}
392		}
393		if(kret != KERN_SUCCESS)
394			break;
395
396		prot = vbr.protection;
397		maxprot = vbr.max_protection;
398		inherit = vbr.inheritance;
399		/*
400		 *	Fill in segment command structure.
401		 */
402		if (is_64) {
403			sc64 = (struct segment_command_64 *)(header + hoffset);
404			sc64->cmd = LC_SEGMENT_64;
405			sc64->cmdsize = sizeof(struct segment_command_64);
406			/* segment name is zeroed by kmem_alloc */
407			sc64->segname[0] = 0;
408			sc64->vmaddr = vmoffset;
409			sc64->vmsize = vmsize;
410			sc64->fileoff = foffset;
411			sc64->filesize = vmsize;
412			sc64->maxprot = maxprot;
413			sc64->initprot = prot;
414			sc64->nsects = 0;
415		} else  {
416			sc = (struct segment_command *) (header + hoffset);
417			sc->cmd = LC_SEGMENT;
418			sc->cmdsize = sizeof(struct segment_command);
419			/* segment name is zeroed by kmem_alloc */
420			sc->segname[0] = 0;
421			sc->vmaddr = CAST_DOWN_EXPLICIT(vm_offset_t,vmoffset);
422			sc->vmsize = CAST_DOWN_EXPLICIT(vm_size_t,vmsize);
423			sc->fileoff = CAST_DOWN_EXPLICIT(uint32_t,foffset); /* will never truncate */
424			sc->filesize = CAST_DOWN_EXPLICIT(uint32_t,vmsize); /* will never truncate */
425			sc->maxprot = maxprot;
426			sc->initprot = prot;
427			sc->nsects = 0;
428		}
429
430		/*
431		 *	Write segment out.  Try as hard as possible to
432		 *	get read access to the data.
433		 */
434		if ((prot & VM_PROT_READ) == 0) {
435			mach_vm_protect(map, vmoffset, vmsize, FALSE,
436					   prot|VM_PROT_READ);
437		}
438		/*
439		 *	Only actually perform write if we can read.
440		 *	Note: if we can't read, then we end up with
441		 *	a hole in the file.
442		 */
443		if ((maxprot & VM_PROT_READ) == VM_PROT_READ
444			&& vbr.user_tag != VM_MEMORY_IOKIT
445			&& coredumpok(map,vmoffset)) {
446
447			error = vn_rdwr_64(UIO_WRITE, vp, vmoffset, vmsize, foffset,
448					(IS_64BIT_PROCESS(core_proc) ? UIO_USERSPACE64 : UIO_USERSPACE32),
449					IO_NOCACHE|IO_NODELOCKED|IO_UNIT, cred, (int64_t *) 0, core_proc);
450
451		}
452
453		hoffset += segment_command_sz;
454		foffset += vmsize;
455		vmoffset += vmsize;
456		segment_count--;
457	}
458
459	/*
460	 * If there are remaining segments which have not been written
461	 * out because break in the loop above, then they were not counted
462	 * because they exceed the real address space of the executable
463	 * type: remove them from the header's count.  This is OK, since
464	 * we are allowed to have a sparse area following the segments.
465	 */
466	if (is_64) {
467		mh64->ncmds -= segment_count;
468		mh64->sizeofcmds -= segment_count * segment_command_sz;
469	} else {
470		mh->ncmds -= segment_count;
471		mh->sizeofcmds -= segment_count * segment_command_sz;
472	}
473
474	tir1.header = header;
475	tir1.hoffset = hoffset;
476	tir1.flavors = flavors;
477	tir1.tstate_size = tstate_size;
478	task_act_iterate_wth_args(task, collectth_state,&tir1);
479
480	/*
481	 *	Write out the Mach header at the beginning of the
482	 *	file.  OK to use a 32 bit write for this.
483	 */
484	error = vn_rdwr(UIO_WRITE, vp, (caddr_t)header, header_size, (off_t)0,
485			UIO_SYSSPACE, IO_NOCACHE|IO_NODELOCKED|IO_UNIT, cred, (int *) 0, core_proc);
486	kmem_free(kernel_map, header, header_size);
487out:
488	error1 = vnode_close(vp, FWRITE, ctx);
489out2:
490#if CONFIG_AUDIT
491	audit_proc_coredump(core_proc, name, error);
492#endif
493	if (alloced_name != NULL)
494		FREE(alloced_name, M_TEMP);
495	if (error == 0)
496		error = error1;
497
498	return (error);
499}
500