xref: /titanic_50/usr/src/cmd/sgs/libelf/common/output.c (revision d7ddd43c70ebe97a1118be9f663a54d0d1d89fe6)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 /*
28  *	Copyright (c) 1988 AT&T
29  *	  All Rights Reserved
30  */
31 
32 #include <sys/mman.h>
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <unistd.h>
36 #include <libelf.h>
37 #include <errno.h>
38 #include "decl.h"
39 #include "msg.h"
40 
41 /*
42  * File output
43  *	These functions write output files.
44  *	On SVR4 and newer systems use mmap(2).  On older systems (or on
45  *	file systems that don't support mmap), use write(2).
46  */
47 
48 
49 char *
50 _elf_outmap(int fd, size_t sz, unsigned int *pflag)
51 {
52 	char	*p;
53 
54 	/*
55 	 * Note: Some NFS implementations do not provide from enlarging a file
56 	 * via ftruncate(), thus this may fail with ENOSUP.  In this case the
57 	 * fall through to the calloc() mechanism will occur.
58 	 */
59 	if ((!*pflag) && (ftruncate(fd, (off_t)sz) == 0) &&
60 	    (p = mmap((char *)0, sz, PROT_READ+PROT_WRITE,
61 	    MAP_SHARED, fd, (off_t)0)) != (char *)-1) {
62 		*pflag = 1;
63 		return (p);
64 	}
65 
66 	*pflag = 0;
67 
68 	/*
69 	 * If mmap fails, try calloc.  Some file systems don't mmap.  Note, we
70 	 * use calloc rather than malloc, as ld(1) assumes that the backing
71 	 * storage it is working with is zero filled.
72 	 */
73 	if ((p = (char *)calloc(1, sz)) == 0)
74 		_elf_seterr(EMEM_OUT, errno);
75 	return (p);
76 }
77 
78 
79 size_t
80 _elf_outsync(int fd, char *p, size_t sz, unsigned int flag)
81 {
82 	if (flag != 0) {
83 		int	err;
84 
85 		if ((fd = msync(p, sz, MS_ASYNC)) == -1)
86 			err = errno;
87 		(void) munmap(p, sz);
88 		if (fd == 0)
89 			return (sz);
90 		_elf_seterr(EIO_SYNC, err);
91 		return (0);
92 	}
93 	if ((lseek(fd, 0L, SEEK_SET) == 0) &&
94 	    (write(fd, p, sz) == sz)) {
95 		(void) free(p);
96 		return (sz);
97 	}
98 	_elf_seterr(EIO_WRITE, errno);
99 	return (0);
100 }
101