xref: /freebsd/sys/compat/linux/linux_mmap.c (revision e5d258c9e599d2b2fe642e678091cac5da8a10d1)
1 /*-
2  * Copyright (c) 2004 Tim J. Robbins
3  * Copyright (c) 2002 Doug Rabson
4  * Copyright (c) 2000 Marcel Moolenaar
5  * Copyright (c) 1994-1995 Søren Schmidt
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer
13  *    in this position and unchanged.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. The name of the author may not be used to endorse or promote products
18  *    derived from this software without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
21  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
22  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
23  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
24  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
25  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
29  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30  */
31 
32 #include <sys/cdefs.h>
33 __FBSDID("$FreeBSD$");
34 
35 #include <sys/fcntl.h>
36 #include <sys/file.h>
37 #include <sys/ktr.h>
38 #include <sys/lock.h>
39 #include <sys/mman.h>
40 #include <sys/proc.h>
41 #include <sys/resourcevar.h>
42 #include <sys/rwlock.h>
43 #include <sys/syscallsubr.h>
44 #include <sys/sysent.h>
45 #include <sys/sysproto.h>
46 
47 #include <vm/pmap.h>
48 #include <vm/vm_extern.h>
49 #include <vm/vm_map.h>
50 #include <vm/vm_object.h>
51 
52 #include <compat/linux/linux_emul.h>
53 #include <compat/linux/linux_mmap.h>
54 #include <compat/linux/linux_persona.h>
55 #include <compat/linux/linux_util.h>
56 
57 #define STACK_SIZE  (2 * 1024 * 1024)
58 #define GUARD_SIZE  (4 * PAGE_SIZE)
59 
60 #if defined(__amd64__)
61 static void linux_fixup_prot(struct thread *td, int *prot);
62 #endif
63 
64 static int
65 linux_mmap_check_fp(struct file *fp, int flags, int prot, int maxprot)
66 {
67 
68 	/* Linux mmap() just fails for O_WRONLY files */
69 	if ((fp->f_flag & FREAD) == 0)
70 		return (EACCES);
71 
72 	return (0);
73 }
74 
75 int
76 linux_mmap_common(struct thread *td, uintptr_t addr, size_t len, int prot,
77     int flags, int fd, off_t pos)
78 {
79 	struct mmap_req mr, mr_fixed;
80 	struct proc *p = td->td_proc;
81 	struct vmspace *vms = td->td_proc->p_vmspace;
82 	int bsd_flags, error;
83 
84 	LINUX_CTR6(mmap2, "0x%lx, %ld, %ld, 0x%08lx, %ld, 0x%lx",
85 	    addr, len, prot, flags, fd, pos);
86 
87 	error = 0;
88 	bsd_flags = 0;
89 
90 	/*
91 	 * Linux mmap(2):
92 	 * You must specify exactly one of MAP_SHARED and MAP_PRIVATE
93 	 */
94 	if (!((flags & LINUX_MAP_SHARED) ^ (flags & LINUX_MAP_PRIVATE)))
95 		return (EINVAL);
96 
97 	if (flags & LINUX_MAP_SHARED)
98 		bsd_flags |= MAP_SHARED;
99 	if (flags & LINUX_MAP_PRIVATE)
100 		bsd_flags |= MAP_PRIVATE;
101 	if (flags & LINUX_MAP_FIXED)
102 		bsd_flags |= MAP_FIXED;
103 	if (flags & LINUX_MAP_ANON) {
104 		/* Enforce pos to be on page boundary, then ignore. */
105 		if ((pos & PAGE_MASK) != 0)
106 			return (EINVAL);
107 		pos = 0;
108 		bsd_flags |= MAP_ANON;
109 	} else
110 		bsd_flags |= MAP_NOSYNC;
111 	if (flags & LINUX_MAP_GROWSDOWN)
112 		bsd_flags |= MAP_STACK;
113 
114 #if defined(__amd64__)
115 	/*
116 	 * According to the Linux mmap(2) man page, "MAP_32BIT flag
117 	 * is ignored when MAP_FIXED is set."
118 	 */
119 	if ((flags & LINUX_MAP_32BIT) && (flags & LINUX_MAP_FIXED) == 0)
120 		bsd_flags |= MAP_32BIT;
121 
122 	/*
123 	 * PROT_READ, PROT_WRITE, or PROT_EXEC implies PROT_READ and PROT_EXEC
124 	 * on Linux/i386 if the binary requires executable stack.
125 	 * We do this only for IA32 emulation as on native i386 this is does not
126 	 * make sense without PAE.
127 	 *
128 	 * XXX. Linux checks that the file system is not mounted with noexec.
129 	 */
130 	linux_fixup_prot(td, &prot);
131 #endif
132 
133 	/* Linux does not check file descriptor when MAP_ANONYMOUS is set. */
134 	fd = (bsd_flags & MAP_ANON) ? -1 : fd;
135 	if (flags & LINUX_MAP_GROWSDOWN) {
136 		/*
137 		 * The Linux MAP_GROWSDOWN option does not limit auto
138 		 * growth of the region.  Linux mmap with this option
139 		 * takes as addr the initial BOS, and as len, the initial
140 		 * region size.  It can then grow down from addr without
141 		 * limit.  However, Linux threads has an implicit internal
142 		 * limit to stack size of STACK_SIZE.  Its just not
143 		 * enforced explicitly in Linux.  But, here we impose
144 		 * a limit of (STACK_SIZE - GUARD_SIZE) on the stack
145 		 * region, since we can do this with our mmap.
146 		 *
147 		 * Our mmap with MAP_STACK takes addr as the maximum
148 		 * downsize limit on BOS, and as len the max size of
149 		 * the region.  It then maps the top SGROWSIZ bytes,
150 		 * and auto grows the region down, up to the limit
151 		 * in addr.
152 		 *
153 		 * If we don't use the MAP_STACK option, the effect
154 		 * of this code is to allocate a stack region of a
155 		 * fixed size of (STACK_SIZE - GUARD_SIZE).
156 		 */
157 
158 		if ((caddr_t)addr + len > vms->vm_maxsaddr) {
159 			/*
160 			 * Some Linux apps will attempt to mmap
161 			 * thread stacks near the top of their
162 			 * address space.  If their TOS is greater
163 			 * than vm_maxsaddr, vm_map_growstack()
164 			 * will confuse the thread stack with the
165 			 * process stack and deliver a SEGV if they
166 			 * attempt to grow the thread stack past their
167 			 * current stacksize rlimit.  To avoid this,
168 			 * adjust vm_maxsaddr upwards to reflect
169 			 * the current stacksize rlimit rather
170 			 * than the maximum possible stacksize.
171 			 * It would be better to adjust the
172 			 * mmap'ed region, but some apps do not check
173 			 * mmap's return value.
174 			 */
175 			PROC_LOCK(p);
176 			vms->vm_maxsaddr = (char *)round_page(vms->vm_stacktop) -
177 			    lim_cur_proc(p, RLIMIT_STACK);
178 			PROC_UNLOCK(p);
179 		}
180 
181 		/*
182 		 * This gives us our maximum stack size and a new BOS.
183 		 * If we're using VM_STACK, then mmap will just map
184 		 * the top SGROWSIZ bytes, and let the stack grow down
185 		 * to the limit at BOS.  If we're not using VM_STACK
186 		 * we map the full stack, since we don't have a way
187 		 * to autogrow it.
188 		 */
189 		if (len <= STACK_SIZE - GUARD_SIZE) {
190 			addr = addr - (STACK_SIZE - GUARD_SIZE - len);
191 			len = STACK_SIZE - GUARD_SIZE;
192 		}
193 	}
194 
195 	/*
196 	 * FreeBSD is free to ignore the address hint if MAP_FIXED wasn't
197 	 * passed.  However, some Linux applications, like the ART runtime,
198 	 * depend on the hint.  If the MAP_FIXED wasn't passed, but the
199 	 * address is not zero, try with MAP_FIXED and MAP_EXCL first,
200 	 * and fall back to the normal behaviour if that fails.
201 	 */
202 	mr = (struct mmap_req) {
203 		.mr_hint = addr,
204 		.mr_len = len,
205 		.mr_prot = prot,
206 		.mr_flags = bsd_flags,
207 		.mr_fd = fd,
208 		.mr_pos = pos,
209 		.mr_check_fp_fn = linux_mmap_check_fp,
210 	};
211 	if (addr != 0 && (bsd_flags & MAP_FIXED) == 0 &&
212 	    (bsd_flags & MAP_EXCL) == 0) {
213 		mr_fixed = mr;
214 		mr_fixed.mr_flags |= MAP_FIXED | MAP_EXCL;
215 		error = kern_mmap(td, &mr_fixed);
216 		if (error == 0)
217 			goto out;
218 	}
219 
220 	error = kern_mmap(td, &mr);
221 out:
222 	LINUX_CTR2(mmap2, "return: %d (%p)", error, td->td_retval[0]);
223 
224 	return (error);
225 }
226 
227 int
228 linux_mprotect_common(struct thread *td, uintptr_t addr, size_t len, int prot)
229 {
230 	int flags = 0;
231 
232 	/* XXX Ignore PROT_GROWSUP for now. */
233 	prot &= ~LINUX_PROT_GROWSUP;
234 	if ((prot & ~(LINUX_PROT_GROWSDOWN | PROT_READ | PROT_WRITE |
235 	    PROT_EXEC)) != 0)
236 		return (EINVAL);
237 	if ((prot & LINUX_PROT_GROWSDOWN) != 0) {
238 		prot &= ~LINUX_PROT_GROWSDOWN;
239 		flags |= VM_MAP_PROTECT_GROWSDOWN;
240 	}
241 
242 #if defined(__amd64__)
243 	linux_fixup_prot(td, &prot);
244 #endif
245 	return (kern_mprotect(td, addr, len, prot, flags));
246 }
247 
248 /*
249  * Implement Linux madvise(MADV_DONTNEED), which has unusual semantics: for
250  * anonymous memory, pages in the range are immediately discarded.
251  */
252 static int
253 linux_madvise_dontneed(struct thread *td, vm_offset_t start, vm_offset_t end)
254 {
255 	vm_map_t map;
256 	vm_map_entry_t entry;
257 	vm_object_t backing_object, object;
258 	vm_offset_t estart, eend;
259 	vm_pindex_t pstart, pend;
260 	int error;
261 
262 	map = &td->td_proc->p_vmspace->vm_map;
263 
264 	if (!vm_map_range_valid(map, start, end))
265 		return (EINVAL);
266 	start = trunc_page(start);
267 	end = round_page(end);
268 
269 	error = 0;
270 	vm_map_lock_read(map);
271 	if (!vm_map_lookup_entry(map, start, &entry))
272 		entry = vm_map_entry_succ(entry);
273 	for (; entry->start < end; entry = vm_map_entry_succ(entry)) {
274 		if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) != 0)
275 			continue;
276 
277 		if (entry->wired_count != 0) {
278 			error = EINVAL;
279 			break;
280 		}
281 
282 		object = entry->object.vm_object;
283 		if (object == NULL)
284 			continue;
285 		if ((object->flags & (OBJ_UNMANAGED | OBJ_FICTITIOUS)) != 0)
286 			continue;
287 
288 		pstart = OFF_TO_IDX(entry->offset);
289 		if (start > entry->start) {
290 			pstart += atop(start - entry->start);
291 			estart = start;
292 		} else {
293 			estart = entry->start;
294 		}
295 		pend = OFF_TO_IDX(entry->offset) +
296 		    atop(entry->end - entry->start);
297 		if (entry->end > end) {
298 			pend -= atop(entry->end - end);
299 			eend = end;
300 		} else {
301 			eend = entry->end;
302 		}
303 
304 		if ((object->flags & (OBJ_ANON | OBJ_ONEMAPPING)) ==
305 		    (OBJ_ANON | OBJ_ONEMAPPING)) {
306 			/*
307 			 * Singly-mapped anonymous memory is discarded.  This
308 			 * does not match Linux's semantics when the object
309 			 * belongs to a shadow chain of length > 1, since
310 			 * subsequent faults may retrieve pages from an
311 			 * intermediate anonymous object.  However, handling
312 			 * this case correctly introduces a fair bit of
313 			 * complexity.
314 			 */
315 			VM_OBJECT_WLOCK(object);
316 			if ((object->flags & OBJ_ONEMAPPING) != 0) {
317 				vm_object_collapse(object);
318 				vm_object_page_remove(object, pstart, pend, 0);
319 				backing_object = object->backing_object;
320 				if (backing_object != NULL &&
321 				    (backing_object->flags & OBJ_ANON) != 0)
322 					linux_msg(td,
323 					    "possibly incorrect MADV_DONTNEED");
324 				VM_OBJECT_WUNLOCK(object);
325 				continue;
326 			}
327 			VM_OBJECT_WUNLOCK(object);
328 		}
329 
330 		/*
331 		 * Handle shared mappings.  Remove them outright instead of
332 		 * calling pmap_advise(), for consistency with Linux.
333 		 */
334 		pmap_remove(map->pmap, estart, eend);
335 		vm_object_madvise(object, pstart, pend, MADV_DONTNEED);
336 	}
337 	vm_map_unlock_read(map);
338 
339 	return (error);
340 }
341 
342 int
343 linux_madvise_common(struct thread *td, uintptr_t addr, size_t len, int behav)
344 {
345 
346 	switch (behav) {
347 	case LINUX_MADV_NORMAL:
348 		return (kern_madvise(td, addr, len, MADV_NORMAL));
349 	case LINUX_MADV_RANDOM:
350 		return (kern_madvise(td, addr, len, MADV_RANDOM));
351 	case LINUX_MADV_SEQUENTIAL:
352 		return (kern_madvise(td, addr, len, MADV_SEQUENTIAL));
353 	case LINUX_MADV_WILLNEED:
354 		return (kern_madvise(td, addr, len, MADV_WILLNEED));
355 	case LINUX_MADV_DONTNEED:
356 		return (linux_madvise_dontneed(td, addr, addr + len));
357 	case LINUX_MADV_FREE:
358 		return (kern_madvise(td, addr, len, MADV_FREE));
359 	case LINUX_MADV_REMOVE:
360 		linux_msg(curthread, "unsupported madvise MADV_REMOVE");
361 		return (EINVAL);
362 	case LINUX_MADV_DONTFORK:
363 		return (kern_minherit(td, addr, len, INHERIT_NONE));
364 	case LINUX_MADV_DOFORK:
365 		return (kern_minherit(td, addr, len, INHERIT_COPY));
366 	case LINUX_MADV_MERGEABLE:
367 		linux_msg(curthread, "unsupported madvise MADV_MERGEABLE");
368 		return (EINVAL);
369 	case LINUX_MADV_UNMERGEABLE:
370 		/* We don't merge anyway. */
371 		return (0);
372 	case LINUX_MADV_HUGEPAGE:
373 		/* Ignored; on FreeBSD huge pages are always on. */
374 		return (0);
375 	case LINUX_MADV_NOHUGEPAGE:
376 #if 0
377 		/*
378 		 * Don't warn - Firefox uses it a lot, and in real Linux it's
379 		 * an optional feature.
380 		 */
381 		linux_msg(curthread, "unsupported madvise MADV_NOHUGEPAGE");
382 #endif
383 		return (EINVAL);
384 	case LINUX_MADV_DONTDUMP:
385 		return (kern_madvise(td, addr, len, MADV_NOCORE));
386 	case LINUX_MADV_DODUMP:
387 		return (kern_madvise(td, addr, len, MADV_CORE));
388 	case LINUX_MADV_WIPEONFORK:
389 		return (kern_minherit(td, addr, len, INHERIT_ZERO));
390 	case LINUX_MADV_KEEPONFORK:
391 		return (kern_minherit(td, addr, len, INHERIT_COPY));
392 	case LINUX_MADV_HWPOISON:
393 		linux_msg(curthread, "unsupported madvise MADV_HWPOISON");
394 		return (EINVAL);
395 	case LINUX_MADV_SOFT_OFFLINE:
396 		linux_msg(curthread, "unsupported madvise MADV_SOFT_OFFLINE");
397 		return (EINVAL);
398 	case -1:
399 		/*
400 		 * -1 is sometimes used as a dummy value to detect simplistic
401 		 * madvise(2) stub implementations.  This safeguard is used by
402 		 * BoringSSL, for example, before assuming MADV_WIPEONFORK is
403 		 * safe to use.  Don't produce an "unsupported" error message
404 		 * for this special dummy value, which is unlikely to be used
405 		 * by any new advisory behavior feature.
406 		 */
407 		return (EINVAL);
408 	default:
409 		linux_msg(curthread, "unsupported madvise behav %d", behav);
410 		return (EINVAL);
411 	}
412 }
413 
414 #if defined(__amd64__)
415 static void
416 linux_fixup_prot(struct thread *td, int *prot)
417 {
418 	struct linux_pemuldata *pem;
419 
420 	if (SV_PROC_FLAG(td->td_proc, SV_ILP32) && *prot & PROT_READ) {
421 		pem = pem_find(td->td_proc);
422 		if (pem->persona & LINUX_READ_IMPLIES_EXEC)
423 			*prot |= PROT_EXEC;
424 	}
425 
426 }
427 #endif
428