]> git.ipfire.org Git - thirdparty/man-pages.git/blob - man2/mmap.2
clock_getres.2, fsync.2, mlock.2, mmap.2, msync.2, INFINITY.3, cexp2.3, clog2.3,...
[thirdparty/man-pages.git] / man2 / mmap.2
1 .\" Copyright (C) 1996 Andries Brouwer <aeb@cwi.nl>
2 .\" and Copyright (C) 2006, 2007 Michael Kerrisk <mtk.manpages@gmail.com>
3 .\"
4 .\" %%%LICENSE_START(VERBATIM)
5 .\" Permission is granted to make and distribute verbatim copies of this
6 .\" manual provided the copyright notice and this permission notice are
7 .\" preserved on all copies.
8 .\"
9 .\" Permission is granted to copy and distribute modified versions of this
10 .\" manual under the conditions for verbatim copying, provided that the
11 .\" entire resulting derived work is distributed under the terms of a
12 .\" permission notice identical to this one.
13 .\"
14 .\" Since the Linux kernel and libraries are constantly changing, this
15 .\" manual page may be incorrect or out-of-date. The author(s) assume no
16 .\" responsibility for errors or omissions, or for damages resulting from
17 .\" the use of the information contained herein. The author(s) may not
18 .\" have taken the same level of care in the production of this manual,
19 .\" which is licensed free of charge, as they might when working
20 .\" professionally.
21 .\"
22 .\" Formatted or processed versions of this manual, if unaccompanied by
23 .\" the source, must acknowledge the copyright and authors of this work.
24 .\" %%%LICENSE_END
25 .\"
26 .\" Modified 1997-01-31 by Eric S. Raymond <esr@thyrsus.com>
27 .\" Modified 2000-03-25 by Jim Van Zandt <jrv@vanzandt.mv.com>
28 .\" Modified 2001-10-04 by John Levon <moz@compsoc.man.ac.uk>
29 .\" Modified 2003-02-02 by Andi Kleen <ak@muc.de>
30 .\" Modified 2003-05-21 by Michael Kerrisk <mtk.manpages@gmail.com>
31 .\" MAP_LOCKED works from 2.5.37
32 .\" Modified 2004-06-17 by Michael Kerrisk <mtk.manpages@gmail.com>
33 .\" Modified 2004-09-11 by aeb
34 .\" Modified 2004-12-08, from Eric Estievenart <eric.estievenart@free.fr>
35 .\" Modified 2004-12-08, mtk, formatting tidy-ups
36 .\" Modified 2006-12-04, mtk, various parts rewritten
37 .\" 2007-07-10, mtk, Added an example program.
38 .\" 2008-11-18, mtk, document MAP_STACK
39 .\"
40 .TH MMAP 2 2020-04-11 "Linux" "Linux Programmer's Manual"
41 .SH NAME
42 mmap, munmap \- map or unmap files or devices into memory
43 .SH SYNOPSIS
44 .nf
45 .B #include <sys/mman.h>
46 .PP
47 .BI "void *mmap(void *" addr ", size_t " length \
48 ", int " prot ", int " flags ,
49 .BI " int " fd ", off_t " offset );
50 .BI "int munmap(void *" addr ", size_t " length );
51 .fi
52 .PP
53 See NOTES for information on feature test macro requirements.
54 .SH DESCRIPTION
55 .BR mmap ()
56 creates a new mapping in the virtual address space of
57 the calling process.
58 The starting address for the new mapping is specified in
59 .IR addr .
60 The
61 .I length
62 argument specifies the length of the mapping (which must be greater than 0).
63 .PP
64 If
65 .I addr
66 is NULL,
67 then the kernel chooses the (page-aligned) address
68 at which to create the mapping;
69 this is the most portable method of creating a new mapping.
70 If
71 .I addr
72 is not NULL,
73 then the kernel takes it as a hint about where to place the mapping;
74 on Linux, the kernel will pick a nearby page boundary (but always above
75 or equal to the value specified by
76 .IR /proc/sys/vm/mmap_min_addr )
77 and attempt to create the mapping there.
78 If another mapping already exists there, the kernel picks a new address that
79 may or may not depend on the hint.
80 .\" Before Linux 2.6.24, the address was rounded up to the next page
81 .\" boundary; since 2.6.24, it is rounded down!
82 The address of the new mapping is returned as the result of the call.
83 .PP
84 The contents of a file mapping (as opposed to an anonymous mapping; see
85 .B MAP_ANONYMOUS
86 below), are initialized using
87 .I length
88 bytes starting at offset
89 .I offset
90 in the file (or other object) referred to by the file descriptor
91 .IR fd .
92 .I offset
93 must be a multiple of the page size as returned by
94 .IR sysconf(_SC_PAGE_SIZE) .
95 .PP
96 After the
97 .BR mmap ()
98 call has returned, the file descriptor,
99 .IR fd ,
100 can be closed immediately without invalidating the mapping.
101 .PP
102 The
103 .I prot
104 argument describes the desired memory protection of the mapping
105 (and must not conflict with the open mode of the file).
106 It is either
107 .B PROT_NONE
108 or the bitwise OR of one or more of the following flags:
109 .TP 1.1i
110 .B PROT_EXEC
111 Pages may be executed.
112 .TP
113 .B PROT_READ
114 Pages may be read.
115 .TP
116 .B PROT_WRITE
117 Pages may be written.
118 .TP
119 .B PROT_NONE
120 Pages may not be accessed.
121 .\"
122 .SS The flags argument
123 The
124 .I flags
125 argument determines whether updates to the mapping
126 are visible to other processes mapping the same region,
127 and whether updates are carried through to the underlying file.
128 This behavior is determined by including exactly one
129 of the following values in
130 .IR flags :
131 .TP
132 .B MAP_SHARED
133 Share this mapping.
134 Updates to the mapping are visible to other processes mapping the same region,
135 and (in the case of file-backed mappings)
136 are carried through to the underlying file.
137 (To precisely control when updates are carried through
138 to the underlying file requires the use of
139 .BR msync (2).)
140 .TP
141 .BR MAP_SHARED_VALIDATE " (since Linux 4.15)"
142 This flag provides the same behavior as
143 .B MAP_SHARED
144 except that
145 .B MAP_SHARED
146 mappings ignore unknown flags in
147 .IR flags .
148 By contrast, when creating a mapping using
149 .BR MAP_SHARED_VALIDATE ,
150 the kernel verifies all passed flags are known and fails the
151 mapping with the error
152 .BR EOPNOTSUPP
153 for unknown flags.
154 This mapping type is also required to be able to use some mapping flags
155 (e.g.,
156 .BR MAP_SYNC ).
157 .TP
158 .B MAP_PRIVATE
159 Create a private copy-on-write mapping.
160 Updates to the mapping are not visible to other processes
161 mapping the same file, and are not carried through to
162 the underlying file.
163 It is unspecified whether changes made to the file after the
164 .BR mmap ()
165 call are visible in the mapped region.
166 .PP
167 Both
168 .B MAP_SHARED
169 and
170 .B MAP_PRIVATE
171 are described in POSIX.1-2001 and POSIX.1-2008.
172 .B MAP_SHARED_VALIDATE
173 is a Linux extension.
174 .PP
175 In addition, zero or more of the following values can be ORed in
176 .IR flags :
177 .TP
178 .BR MAP_32BIT " (since Linux 2.4.20, 2.6)"
179 Put the mapping into the first 2 Gigabytes of the process address space.
180 This flag is supported only on x86-64, for 64-bit programs.
181 It was added to allow thread stacks to be allocated somewhere
182 in the first 2\ GB of memory,
183 so as to improve context-switch performance on some early
184 64-bit processors.
185 .\" See http://lwn.net/Articles/294642 "Tangled up in threads", 19 Aug 08
186 Modern x86-64 processors no longer have this performance problem,
187 so use of this flag is not required on those systems.
188 The
189 .B MAP_32BIT
190 flag is ignored when
191 .B MAP_FIXED
192 is set.
193 .TP
194 .B MAP_ANON
195 Synonym for
196 .BR MAP_ANONYMOUS ;
197 provided for compatibility with other implementations.
198 .TP
199 .B MAP_ANONYMOUS
200 The mapping is not backed by any file;
201 its contents are initialized to zero.
202 The
203 .I fd
204 argument is ignored;
205 however, some implementations require
206 .I fd
207 to be \-1 if
208 .B MAP_ANONYMOUS
209 (or
210 .BR MAP_ANON )
211 is specified,
212 and portable applications should ensure this.
213 The
214 .I offset
215 argument should be zero.
216 .\" See the pgoff overflow check in do_mmap().
217 .\" See the offset check in sys_mmap in arch/x86/kernel/sys_x86_64.c.
218 The use of
219 .B MAP_ANONYMOUS
220 in conjunction with
221 .B MAP_SHARED
222 is supported on Linux only since kernel 2.4.
223 .TP
224 .B MAP_DENYWRITE
225 This flag is ignored.
226 .\" Introduced in 1.1.36, removed in 1.3.24.
227 (Long ago\(emLinux 2.0 and earlier\(emit signaled
228 that attempts to write to the underlying file should fail with
229 .BR ETXTBUSY .
230 But this was a source of denial-of-service attacks.)
231 .TP
232 .B MAP_EXECUTABLE
233 This flag is ignored.
234 .\" Introduced in 1.1.38, removed in 1.3.24. Flag tested in proc_follow_link.
235 .\" (Long ago, it signaled that the underlying file is an executable.
236 .\" However, that information was not really used anywhere.)
237 .\" Linus talked about DOS related to MAP_EXECUTABLE, but he was thinking of
238 .\" MAP_DENYWRITE?
239 .TP
240 .B MAP_FILE
241 Compatibility flag.
242 Ignored.
243 .\" On some systems, this was required as the opposite of
244 .\" MAP_ANONYMOUS -- mtk, 1 May 2007
245 .TP
246 .B MAP_FIXED
247 Don't interpret
248 .I addr
249 as a hint: place the mapping at exactly that address.
250 .I addr
251 must be suitably aligned: for most architectures a multiple of the page
252 size is sufficient; however, some architectures may impose additional
253 restrictions.
254 If the memory region specified by
255 .I addr
256 and
257 .I len
258 overlaps pages of any existing mapping(s), then the overlapped
259 part of the existing mapping(s) will be discarded.
260 If the specified address cannot be used,
261 .BR mmap ()
262 will fail.
263 .IP
264 Software that aspires to be portable should use the
265 .BR MAP_FIXED
266 flag with care,
267 keeping in mind that the exact layout of a process's memory mappings
268 is allowed to change significantly between kernel versions,
269 C library versions, and operating system releases.
270 .IR "Carefully read the discussion of this flag in NOTES!"
271 .TP
272 .BR MAP_FIXED_NOREPLACE " (since Linux 4.17)"
273 .\" commit a4ff8e8620d3f4f50ac4b41e8067b7d395056843
274 This flag provides behavior that is similar to
275 .B MAP_FIXED
276 with respect to the
277 .I addr
278 enforcement, but differs in that
279 .B MAP_FIXED_NOREPLACE
280 never clobbers a preexisting mapped range.
281 If the requested range would collide with an existing mapping,
282 then this call fails with the error
283 .B EEXIST.
284 This flag can therefore be used as a way to atomically
285 (with respect to other threads) attempt to map an address range:
286 one thread will succeed; all others will report failure.
287 .IP
288 Note that older kernels which do not recognize the
289 .BR MAP_FIXED_NOREPLACE
290 flag will typically (upon detecting a collision with a preexisting mapping)
291 fall back to a "non-\c
292 .B MAP_FIXED\c
293 " type of behavior:
294 they will return an address that is different from the requested address.
295 Therefore, backward-compatible software
296 should check the returned address against the requested address.
297 .TP
298 .B MAP_GROWSDOWN
299 This flag is used for stacks.
300 It indicates to the kernel virtual memory system that the mapping
301 should extend downward in memory.
302 The return address is one page lower than the memory area that is
303 actually created in the process's virtual address space.
304 Touching an address in the "guard" page below the mapping will cause
305 the mapping to grow by a page.
306 This growth can be repeated until the mapping grows to within a
307 page of the high end of the next lower mapping,
308 at which point touching the "guard" page will result in a
309 .B SIGSEGV
310 signal.
311 .TP
312 .BR MAP_HUGETLB " (since Linux 2.6.32)"
313 Allocate the mapping using "huge pages."
314 See the Linux kernel source file
315 .I Documentation/admin-guide/mm/hugetlbpage.rst
316 for further information, as well as NOTES, below.
317 .TP
318 .BR MAP_HUGE_2MB ", " MAP_HUGE_1GB " (since Linux 3.8)"
319 .\" See https://lwn.net/Articles/533499/
320 Used in conjunction with
321 .B MAP_HUGETLB
322 to select alternative hugetlb page sizes (respectively, 2\ MB and 1\ GB)
323 on systems that support multiple hugetlb page sizes.
324 .IP
325 More generally, the desired huge page size can be configured by encoding
326 the base-2 logarithm of the desired page size in the six bits at the offset
327 .BR MAP_HUGE_SHIFT .
328 (A value of zero in this bit field provides the default huge page size;
329 the default huge page size can be discovered via the
330 .I Hugepagesize
331 field exposed by
332 .IR /proc/meminfo .)
333 Thus, the above two constants are defined as:
334 .IP
335 .in +4n
336 .EX
337 #define MAP_HUGE_2MB (21 << MAP_HUGE_SHIFT)
338 #define MAP_HUGE_1GB (30 << MAP_HUGE_SHIFT)
339 .EE
340 .in
341 .IP
342 The range of huge page sizes that are supported by the system
343 can be discovered by listing the subdirectories in
344 .IR /sys/kernel/mm/hugepages .
345 .TP
346 .BR MAP_LOCKED " (since Linux 2.5.37)"
347 Mark the mapped region to be locked in the same way as
348 .BR mlock (2).
349 This implementation will try to populate (prefault) the whole range but the
350 .BR mmap ()
351 call doesn't fail with
352 .B ENOMEM
353 if this fails.
354 Therefore major faults might happen later on.
355 So the semantic is not as strong as
356 .BR mlock (2).
357 One should use
358 .BR mmap ()
359 plus
360 .BR mlock (2)
361 when major faults are not acceptable after the initialization of the mapping.
362 The
363 .BR MAP_LOCKED
364 flag is ignored in older kernels.
365 .\" If set, the mapped pages will not be swapped out.
366 .TP
367 .BR MAP_NONBLOCK " (since Linux 2.5.46)"
368 This flag is meaningful only in conjunction with
369 .BR MAP_POPULATE .
370 Don't perform read-ahead:
371 create page tables entries only for pages
372 that are already present in RAM.
373 Since Linux 2.6.23,
374 .\" commit 54cb8821de07f2ffcd28c380ce9b93d5784b40d7
375 this flag causes
376 .BR MAP_POPULATE
377 to do nothing.
378 One day, the combination of
379 .BR MAP_POPULATE
380 and
381 .BR MAP_NONBLOCK
382 may be reimplemented.
383 .TP
384 .B MAP_NORESERVE
385 Do not reserve swap space for this mapping.
386 When swap space is reserved, one has the guarantee
387 that it is possible to modify the mapping.
388 When swap space is not reserved one might get
389 .B SIGSEGV
390 upon a write
391 if no physical memory is available.
392 See also the discussion of the file
393 .I /proc/sys/vm/overcommit_memory
394 in
395 .BR proc (5).
396 In kernels before 2.6, this flag had effect only for
397 private writable mappings.
398 .TP
399 .BR MAP_POPULATE " (since Linux 2.5.46)"
400 Populate (prefault) page tables for a mapping.
401 For a file mapping, this causes read-ahead on the file.
402 This will help to reduce blocking on page faults later.
403 .BR MAP_POPULATE
404 is supported for private mappings only since Linux 2.6.23.
405 .TP
406 .BR MAP_STACK " (since Linux 2.6.27)"
407 Allocate the mapping at an address suitable for a process
408 or thread stack.
409 .IP
410 This flag is currently a no-op on Linux.
411 However, by employing this flag, applications can ensure that
412 they transparently obtain support if the flag
413 is implemented in the future.
414 Thus, it is used in the glibc threading implementation to allow for
415 the fact that some architectures may (later) require special treatment
416 for stack allocations.
417 .\" See http://lwn.net/Articles/294642 "Tangled up in threads", 19 Aug 08
418 .\" commit cd98a04a59e2f94fa64d5bf1e26498d27427d5e7
419 .\" http://thread.gmane.org/gmane.linux.kernel/720412
420 .\" "pthread_create() slow for many threads; also time to revisit 64b
421 .\" context switch optimization?"
422 A further reason to employ this flag is portability:
423 .BR MAP_STACK
424 exists (and has an effect) on some other systems (e.g., some of the BSDs).
425 .TP
426 .BR MAP_SYNC " (since Linux 4.15)"
427 This flag is available only with the
428 .B MAP_SHARED_VALIDATE
429 mapping type;
430 mappings of type
431 .B MAP_SHARED
432 will silently ignore this flag.
433 This flag is supported only for files supporting DAX
434 (direct mapping of persistent memory).
435 For other files, creating a mapping with this flag results in an
436 .B EOPNOTSUPP
437 error.
438 .IP
439 Shared file mappings with this flag provide the guarantee that while
440 some memory is writably mapped in the address space of the process,
441 it will be visible in the same file at the same offset even after
442 the system crashes or is rebooted.
443 In conjunction with the use of appropriate CPU instructions,
444 this provides users of such mappings with a more efficient way
445 of making data modifications persistent.
446 .TP
447 .BR MAP_UNINITIALIZED " (since Linux 2.6.33)"
448 Don't clear anonymous pages.
449 This flag is intended to improve performance on embedded devices.
450 This flag is honored only if the kernel was configured with the
451 .B CONFIG_MMAP_ALLOW_UNINITIALIZED
452 option.
453 Because of the security implications,
454 that option is normally enabled only on embedded devices
455 (i.e., devices where one has complete control of the contents of user memory).
456 .PP
457 Of the above flags, only
458 .B MAP_FIXED
459 is specified in POSIX.1-2001 and POSIX.1-2008.
460 However, most systems also support
461 .B MAP_ANONYMOUS
462 (or its synonym
463 .BR MAP_ANON ).
464 .\" FIXME . for later review when Issue 8 is one day released...
465 .\" POSIX may add MAP_ANON in the future
466 .\" http://austingroupbugs.net/tag_view_page.php?tag_id=8
467 .\" http://austingroupbugs.net/view.php?id=850
468 .SS munmap()
469 The
470 .BR munmap ()
471 system call deletes the mappings for the specified address range, and
472 causes further references to addresses within the range to generate
473 invalid memory references.
474 The region is also automatically unmapped
475 when the process is terminated.
476 On the other hand, closing the file
477 descriptor does not unmap the region.
478 .PP
479 The address
480 .I addr
481 must be a multiple of the page size (but
482 .I length
483 need not be).
484 All pages containing a part
485 of the indicated range are unmapped, and subsequent references
486 to these pages will generate
487 .BR SIGSEGV .
488 It is not an error if the
489 indicated range does not contain any mapped pages.
490 .SH RETURN VALUE
491 On success,
492 .BR mmap ()
493 returns a pointer to the mapped area.
494 On error, the value
495 .B MAP_FAILED
496 (that is,
497 .IR "(void\ *)\ \-1" )
498 is returned, and
499 .I errno
500 is set to indicate the cause of the error.
501 .PP
502 On success,
503 .BR munmap ()
504 returns 0.
505 On failure, it returns \-1, and
506 .I errno
507 is set to indicate the cause of the error (probably to
508 .BR EINVAL ).
509 .SH ERRORS
510 .TP
511 .B EACCES
512 A file descriptor refers to a non-regular file.
513 Or a file mapping was requested, but
514 .I fd
515 is not open for reading.
516 Or
517 .B MAP_SHARED
518 was requested and
519 .B PROT_WRITE
520 is set, but
521 .I fd
522 is not open in read/write
523 .RB ( O_RDWR )
524 mode.
525 Or
526 .B PROT_WRITE
527 is set, but the file is append-only.
528 .TP
529 .B EAGAIN
530 The file has been locked, or too much memory has been locked (see
531 .BR setrlimit (2)).
532 .TP
533 .B EBADF
534 .I fd
535 is not a valid file descriptor (and
536 .B MAP_ANONYMOUS
537 was not set).
538 .TP
539 .B EEXIST
540 .BR MAP_FIXED_NOREPLACE
541 was specified in
542 .IR flags ,
543 and the range covered by
544 .IR addr
545 and
546 .IR length
547 clashes with an existing mapping.
548 .TP
549 .B EINVAL
550 We don't like
551 .IR addr ,
552 .IR length ,
553 or
554 .I offset
555 (e.g., they are too large, or not aligned on a page boundary).
556 .TP
557 .B EINVAL
558 (since Linux 2.6.12)
559 .I length
560 was 0.
561 .TP
562 .B EINVAL
563 .I flags
564 contained none of
565 .BR MAP_PRIVATE ,
566 .B MAP_SHARED
567 or
568 .BR MAP_SHARED_VALIDATE .
569 .TP
570 .B ENFILE
571 .\" This is for shared anonymous segments
572 .\" [2.6.7] shmem_zero_setup()-->shmem_file_setup()-->get_empty_filp()
573 The system-wide limit on the total number of open files has been reached.
574 .\" .TP
575 .\" .B ENOEXEC
576 .\" A file could not be mapped for reading.
577 .TP
578 .B ENODEV
579 The underlying filesystem of the specified file does not support
580 memory mapping.
581 .TP
582 .B ENOMEM
583 No memory is available.
584 .TP
585 .B ENOMEM
586 The process's maximum number of mappings would have been exceeded.
587 This error can also occur for
588 .BR munmap (),
589 when unmapping a region in the middle of an existing mapping,
590 since this results in two smaller mappings on either side of
591 the region being unmapped.
592 .TP
593 .B ENOMEM
594 (since Linux 4.7)
595 The process's
596 .B RLIMIT_DATA
597 limit, described in
598 .BR getrlimit (2),
599 would have been exceeded.
600 .TP
601 .B EOVERFLOW
602 On 32-bit architecture together with the large file extension
603 (i.e., using 64-bit
604 .IR off_t ):
605 the number of pages used for
606 .I length
607 plus number of pages used for
608 .I offset
609 would overflow
610 .I "unsigned long"
611 (32 bits).
612 .TP
613 .B EPERM
614 The
615 .I prot
616 argument asks for
617 .B PROT_EXEC
618 but the mapped area belongs to a file on a filesystem that
619 was mounted no-exec.
620 .\" (Since 2.4.25 / 2.6.0.)
621 .TP
622 .B EPERM
623 The operation was prevented by a file seal; see
624 .BR fcntl (2).
625 .TP
626 .B ETXTBSY
627 .B MAP_DENYWRITE
628 was set but the object specified by
629 .I fd
630 is open for writing.
631 .PP
632 Use of a mapped region can result in these signals:
633 .TP
634 .B SIGSEGV
635 Attempted write into a region mapped as read-only.
636 .TP
637 .B SIGBUS
638 Attempted access to a portion of the buffer that does not correspond
639 to the file (for example, beyond the end of the file, including the
640 case where another process has truncated the file).
641 .SH ATTRIBUTES
642 For an explanation of the terms used in this section, see
643 .BR attributes (7).
644 .TS
645 allbox;
646 lbw18 lb lb
647 l l l.
648 Interface Attribute Value
649 T{
650 .BR mmap (),
651 .BR munmap ()
652 T} Thread safety MT-Safe
653 .TE
654 .SH CONFORMING TO
655 POSIX.1-2001, POSIX.1-2008, SVr4, 4.4BSD.
656 .\" SVr4 documents additional error codes ENXIO and ENODEV.
657 .\" SUSv2 documents additional error codes EMFILE and EOVERFLOW.
658 .PP
659 On POSIX systems on which
660 .BR mmap (),
661 .BR msync (2),
662 and
663 .BR munmap ()
664 are available,
665 .B _POSIX_MAPPED_FILES
666 is defined in \fI<unistd.h>\fP to a value greater than 0.
667 (See also
668 .BR sysconf (3).)
669 .\" POSIX.1-2001: It shall be defined to -1 or 0 or 200112L.
670 .\" -1: unavailable, 0: ask using sysconf().
671 .\" glibc defines it to 1.
672 .SH NOTES
673 .PP
674 Memory mapped by
675 .BR mmap ()
676 is preserved across
677 .BR fork (2),
678 with the same attributes.
679 .PP
680 A file is mapped in multiples of the page size.
681 For a file that is not
682 a multiple of the page size, the remaining memory is zeroed when mapped,
683 and writes to that region are not written out to the file.
684 The effect of
685 changing the size of the underlying file of a mapping on the pages that
686 correspond to added or removed regions of the file is unspecified.
687 .PP
688 On some hardware architectures (e.g., i386),
689 .B PROT_WRITE
690 implies
691 .BR PROT_READ .
692 It is architecture dependent whether
693 .B PROT_READ
694 implies
695 .B PROT_EXEC
696 or not.
697 Portable programs should always set
698 .B PROT_EXEC
699 if they intend to execute code in the new mapping.
700 .PP
701 The portable way to create a mapping is to specify
702 .I addr
703 as 0 (NULL), and omit
704 .B MAP_FIXED
705 from
706 .IR flags .
707 In this case, the system chooses the address for the mapping;
708 the address is chosen so as not to conflict with any existing mapping,
709 and will not be 0.
710 If the
711 .B MAP_FIXED
712 flag is specified, and
713 .I addr
714 is 0 (NULL), then the mapped address will be 0 (NULL).
715 .PP
716 Certain
717 .I flags
718 constants are defined only if suitable feature test macros are defined
719 (possibly by default):
720 .BR _DEFAULT_SOURCE
721 with glibc 2.19 or later;
722 or
723 .BR _BSD_SOURCE
724 or
725 .BR _SVID_SOURCE
726 in glibc 2.19 and earlier.
727 (Employing
728 .BR _GNU_SOURCE
729 also suffices,
730 and requiring that macro specifically would have been more logical,
731 since these flags are all Linux-specific.)
732 The relevant flags are:
733 .BR MAP_32BIT ,
734 .BR MAP_ANONYMOUS
735 (and the synonym
736 .BR MAP_ANON ),
737 .BR MAP_DENYWRITE ,
738 .BR MAP_EXECUTABLE ,
739 .BR MAP_FILE ,
740 .BR MAP_GROWSDOWN ,
741 .BR MAP_HUGETLB ,
742 .BR MAP_LOCKED ,
743 .BR MAP_NONBLOCK ,
744 .BR MAP_NORESERVE ,
745 .BR MAP_POPULATE ,
746 and
747 .BR MAP_STACK .
748 .PP
749 An application can determine which pages of a mapping are
750 currently resident in the buffer/page cache using
751 .BR mincore (2).
752 .\"
753 .SS Using MAP_FIXED safely
754 The only safe use for
755 .BR MAP_FIXED
756 is where the address range specified by
757 .IR addr
758 and
759 .I length
760 was previously reserved using another mapping;
761 otherwise, the use of
762 .BR MAP_FIXED
763 is hazardous because it forcibly removes preexisting mappings,
764 making it easy for a multithreaded process to corrupt its own address space.
765 .PP
766 For example, suppose that thread A looks through
767 .I /proc/<pid>/maps
768 and in order to locate an unused address range that it can map using
769 .BR MAP_FIXED ,
770 while thread B simultaneously acquires part or all of that same
771 address range.
772 When thread A subsequently employs
773 .BR mmap(MAP_FIXED) ,
774 it will effectively clobber the mapping that thread B created.
775 In this scenario,
776 thread B need not create a mapping directly; simply making a library call
777 that, internally, uses
778 .BR dlopen (3)
779 to load some other shared library, will suffice.
780 The
781 .BR dlopen (3)
782 call will map the library into the process's address space.
783 Furthermore, almost any library call may be implemented in a way that
784 adds memory mappings to the address space, either with this technique,
785 or by simply allocating memory.
786 Examples include
787 .BR brk (2),
788 .BR malloc (3),
789 .BR pthread_create (3),
790 and the PAM libraries
791 .UR http://www.linux-pam.org
792 .UE .
793 .PP
794 Since Linux 4.17, a multithreaded program can use the
795 .BR MAP_FIXED_NOREPLACE
796 flag to avoid the hazard described above
797 when attempting to create a mapping at a fixed address
798 that has not been reserved by a preexisting mapping.
799 .\"
800 .SS Timestamps changes for file-backed mappings
801 For file-backed mappings, the
802 .I st_atime
803 field for the mapped file may be updated at any time between the
804 .BR mmap ()
805 and the corresponding unmapping; the first reference to a mapped
806 page will update the field if it has not been already.
807 .PP
808 The
809 .I st_ctime
810 and
811 .I st_mtime
812 field for a file mapped with
813 .B PROT_WRITE
814 and
815 .B MAP_SHARED
816 will be updated after
817 a write to the mapped region, and before a subsequent
818 .BR msync (2)
819 with the
820 .B MS_SYNC
821 or
822 .B MS_ASYNC
823 flag, if one occurs.
824 .\"
825 .SS Huge page (Huge TLB) mappings
826 For mappings that employ huge pages, the requirements for the arguments of
827 .BR mmap ()
828 and
829 .BR munmap ()
830 differ somewhat from the requirements for mappings
831 that use the native system page size.
832 .PP
833 For
834 .BR mmap (),
835 .I offset
836 must be a multiple of the underlying huge page size.
837 The system automatically aligns
838 .I length
839 to be a multiple of the underlying huge page size.
840 .PP
841 For
842 .BR munmap (),
843 .I addr
844 and
845 .I length
846 must both be a multiple of the underlying huge page size.
847 .\"
848 .SS C library/kernel differences
849 This page describes the interface provided by the glibc
850 .BR mmap ()
851 wrapper function.
852 Originally, this function invoked a system call of the same name.
853 Since kernel 2.4, that system call has been superseded by
854 .BR mmap2 (2),
855 and nowadays
856 .\" Since around glibc 2.1/2.2, depending on the platform.
857 the glibc
858 .BR mmap ()
859 wrapper function invokes
860 .BR mmap2 (2)
861 with a suitably adjusted value for
862 .IR offset .
863 .SH BUGS
864 On Linux, there are no guarantees like those suggested above under
865 .BR MAP_NORESERVE .
866 By default, any process can be killed
867 at any moment when the system runs out of memory.
868 .PP
869 In kernels before 2.6.7, the
870 .B MAP_POPULATE
871 flag has effect only if
872 .I prot
873 is specified as
874 .BR PROT_NONE .
875 .PP
876 SUSv3 specifies that
877 .BR mmap ()
878 should fail if
879 .I length
880 is 0.
881 However, in kernels before 2.6.12,
882 .BR mmap ()
883 succeeded in this case: no mapping was created and the call returned
884 .IR addr .
885 Since kernel 2.6.12,
886 .BR mmap ()
887 fails with the error
888 .B EINVAL
889 for this case.
890 .PP
891 POSIX specifies that the system shall always
892 zero fill any partial page at the end
893 of the object and that system will never write any modification of the
894 object beyond its end.
895 On Linux, when you write data to such partial page after the end
896 of the object, the data stays in the page cache even after the file
897 is closed and unmapped
898 and even though the data is never written to the file itself,
899 subsequent mappings may see the modified content.
900 In some cases, this could be fixed by calling
901 .BR msync (2)
902 before the unmap takes place;
903 however, this doesn't work on
904 .BR tmpfs (5)
905 (for example, when using the POSIX shared memory interface documented in
906 .BR shm_overview (7)).
907 .SH EXAMPLES
908 .\" FIXME . Add an example here that uses an anonymous shared region for
909 .\" IPC between parent and child.
910 .PP
911 The following program prints part of the file specified in
912 its first command-line argument to standard output.
913 The range of bytes to be printed is specified via offset and length
914 values in the second and third command-line arguments.
915 The program creates a memory mapping of the required
916 pages of the file and then uses
917 .BR write (2)
918 to output the desired bytes.
919 .SS Program source
920 .EX
921 #include <sys/mman.h>
922 #include <sys/stat.h>
923 #include <fcntl.h>
924 #include <stdio.h>
925 #include <stdlib.h>
926 #include <unistd.h>
927
928 #define handle_error(msg) \e
929 do { perror(msg); exit(EXIT_FAILURE); } while (0)
930
931 int
932 main(int argc, char *argv[])
933 {
934 char *addr;
935 int fd;
936 struct stat sb;
937 off_t offset, pa_offset;
938 size_t length;
939 ssize_t s;
940
941 if (argc < 3 || argc > 4) {
942 fprintf(stderr, "%s file offset [length]\en", argv[0]);
943 exit(EXIT_FAILURE);
944 }
945
946 fd = open(argv[1], O_RDONLY);
947 if (fd == \-1)
948 handle_error("open");
949
950 if (fstat(fd, &sb) == \-1) /* To obtain file size */
951 handle_error("fstat");
952
953 offset = atoi(argv[2]);
954 pa_offset = offset & ~(sysconf(_SC_PAGE_SIZE) \- 1);
955 /* offset for mmap() must be page aligned */
956
957 if (offset >= sb.st_size) {
958 fprintf(stderr, "offset is past end of file\en");
959 exit(EXIT_FAILURE);
960 }
961
962 if (argc == 4) {
963 length = atoi(argv[3]);
964 if (offset + length > sb.st_size)
965 length = sb.st_size \- offset;
966 /* Can\(aqt display bytes past end of file */
967
968 } else { /* No length arg ==> display to end of file */
969 length = sb.st_size \- offset;
970 }
971
972 addr = mmap(NULL, length + offset \- pa_offset, PROT_READ,
973 MAP_PRIVATE, fd, pa_offset);
974 if (addr == MAP_FAILED)
975 handle_error("mmap");
976
977 s = write(STDOUT_FILENO, addr + offset \- pa_offset, length);
978 if (s != length) {
979 if (s == \-1)
980 handle_error("write");
981
982 fprintf(stderr, "partial write");
983 exit(EXIT_FAILURE);
984 }
985
986 munmap(addr, length + offset \- pa_offset);
987 close(fd);
988
989 exit(EXIT_SUCCESS);
990 }
991 .EE
992 .SH SEE ALSO
993 .BR ftruncate (2),
994 .BR getpagesize (2),
995 .BR memfd_create (2),
996 .BR mincore (2),
997 .BR mlock (2),
998 .BR mmap2 (2),
999 .BR mprotect (2),
1000 .BR mremap (2),
1001 .BR msync (2),
1002 .BR remap_file_pages (2),
1003 .BR setrlimit (2),
1004 .BR shmat (2),
1005 .BR userfaultfd (2),
1006 .BR shm_open (3),
1007 .BR shm_overview (7)
1008 .PP
1009 The descriptions of the following files in
1010 .BR proc (5):
1011 .IR /proc/[pid]/maps ,
1012 .IR /proc/[pid]/map_files ,
1013 and
1014 .IR /proc/[pid]/smaps .
1015 .PP
1016 B.O. Gallmeister, POSIX.4, O'Reilly, pp. 128\(en129 and 389\(en391.
1017 .\"
1018 .\" Repeat after me: private read-only mappings are 100% equivalent to
1019 .\" shared read-only mappings. No ifs, buts, or maybes. -- Linus