Import CSRG 4.4BSD-Lite2 lib/libc onto vendor branch

This commit is contained in:
Peter Wemm 1997-03-11 11:29:42 +00:00
parent dee7a427ff
commit 662909a780
76 changed files with 12377 additions and 0 deletions

92
lib/libc/gen/Makefile.inc Normal file
View file

@ -0,0 +1,92 @@
# @(#)Makefile.inc 8.6 (Berkeley) 5/4/95
# machine-independent gen sources
.PATH: ${.CURDIR}/${MACHINE}/gen ${.CURDIR}/gen
SRCS+= alarm.c assert.c clock.c closedir.c confstr.c crypt.c ctermid.c \
ctime.c daemon.c devname.c difftime.c disklabel.c err.c errlst.c \
exec.c fnmatch.c frexp.c fstab.c fts.c getbsize.c getcap.c getcwd.c \
getgrent.c getgrouplist.c gethostname.c getloadavg.c getlogin.c \
getmntinfo.c getnetgrent.c getpagesize.c getpass.c getpwent.c \
getttyent.c getusershell.c getvfsbyname.c glob.c initgroups.c isatty.c \
nice.c nlist.c opendir.c pause.c popen.c psignal.c pwcache.c raise.c \
readdir.c rewinddir.c scandir.c seekdir.c sethostname.c setjmperr.c \
setmode.c siginterrupt.c siglist.c signal.c \
sigsetops.c sleep.c sysconf.c sysctl.c syslog.c telldir.c \
termios.c time.c times.c timezone.c ttyname.c ttyslot.c ualarm.c \
uname.c unvis.c usleep.c utime.c valloc.c vis.c wait.c wait3.c \
waitpid.c
# machine-dependent gen sources
.include "${.CURDIR}/${MACHINE}/gen/Makefile.inc"
.if (${MACHINE} == "tahoe" || ${MACHINE} == "vax")
errlst.o errlst.po:
${CC} -S ${CFLAGS} ${.IMPSRC}
ed - < ${.CURDIR}/${MACHINE}/:errfix errlst.s
${AS} -o ${.TARGET} errlst.s
rm -f errlst.s
.endif
MAN3+= alarm.0 clock.0 confstr.0 crypt.0 ctermid.0 ctime.0 daemon.0 \
devname.0 directory.0 err.0 exec.0 fnmatch.0 frexp.0 fts.0 \
getbsize.0 getcap.0 getcwd.0 getdiskbyname.0 getfsent.0 \
getgrent.0 getgrouplist.0 gethostname.0 getloadavg.0 \
getmntinfo.0 getnetgrent.0 getpagesize.0 getpass.0 getpwent.0 \
getttyent.0 getusershell.0 getvfsbyname.0 glob.0 initgroups.0 isinf.0 \
ldexp.0 modf.0 nice.0 nlist.0 pause.0 popen.0 psignal.0 pwcache.0 \
raise.0 realpath.0 scandir.0 setjmp.0 setmode.0 siginterrupt.0 \
signal.0 sigsetops.0 sleep.0 sysconf.0 sysctl.0 syslog.0 tcgetpgrp.0 \
tcsendbreak.0 tcsetattr.0 tcsetpgrp.0 time.0 times.0 timezone.0 \
ttyname.0 tzset.0 ualarm.0 uname.0 unvis.0 usleep.0 utime.0 \
valloc.0 vis.0
MLINKS+=crypt.3 encrypt.3 crypt.3 setkey.3
MLINKS+=ctime.3 asctime.3 ctime.3 difftime.3 ctime.3 gmtime.3 \
ctime.3 localtime.3 ctime.3 mktime.3
MLINKS+=directory.3 closedir.3 directory.3 dirfd.3 directory.3 opendir.3 \
directory.3 readdir.3 directory.3 rewinddir.3 directory.3 seekdir.3 \
directory.3 telldir.3
MLINKS+=exec.3 execl.3 exec.3 execle.3 exec.3 execlp.3 exec.3 execv.3 \
exec.3 execvp.3
MLINKS+=err.3 verr.3 err.3 errx.3 err.3 verrx.3 err.3 warn.3 err.3 vwarn.3 \
err.3 warnx.3 err.3 vwarnx.3
MLINKS+=isinf.3 isnan.3
MLINKS+=getcap.3 cgetcap.3 getcap.3 cgetclose.3 getcap.3 cgetent.3 \
getcap.3 cgetfirst.3 getcap.3 cgetmatch.3 getcap.3 cgetnext.3 \
getcap.3 cgetnum.3 getcap.3 cgetset.3 getcap.3 cgetstr.3 \
getcap.3 cgetustr.3
MLINKS+=getcwd.3 getwd.3
MLINKS+=getfsent.3 endfsent.3 getfsent.3 getfsfile.3 getfsent.3 getfsspec.3 \
getfsent.3 getfstype.3 getfsent.3 setfsent.3
MLINKS+=getgrent.3 endgrent.3 getgrent.3 setgroupent.3 getgrent.3 getgrgid.3 \
getgrent.3 getgrnam.3 getgrent.3 setgrent.3 getgrent.3 setgrfile.3
MLINKS+=gethostname.3 sethostname.3
MLINKS+=getnetgrent.3 endnetgrent.3 getnetgrent.3 setnetgrent.3 \
getnetgrent.3 innetgr.3
MLINKS+=getpwent.3 endpwent.3 getpwent.3 setpassent.3 getpwent.3 getpwnam.3 \
getpwent.3 getpwuid.3 getpwent.3 setpwent.3 getpwent.3 setpwfile.3
MLINKS+=getttyent.3 endttyent.3 getttyent.3 getttynam.3 getttyent.3 setttyent.3
MLINKS+=getusershell.3 endusershell.3 getusershell.3 setusershell.3
MLINKS+=glob.3 globfree.3
MLINKS+=popen.3 pclose.3
MLINKS+=psignal.3 sys_siglist.3
MLINKS+=pwcache.3 user_from_uid.3 pwcache.3 group_from_gid.3
MLINKS+=scandir.3 alphasort.3
MLINKS+=setjmp.3 _longjmp.3 setjmp.3 _setjmp.3 setjmp.3 longjmp.3 \
setjmp.3 longjmperr.3 setjmp.3 longjmperror.3 \
setjmp.3 sigsetjmp.3 setjmp.3 siglongjmp.3
MLINKS+=setmode.3 getmode.3
MLINKS+=sigsetops.3 sigemptyset.3 sigsetops.3 sigfillset.3 \
sigsetops.3 sigaddset.3 sigsetops.3 sigdelset.3 \
sigsetops.3 sigismember.3
MLINKS+=syslog.3 closelog.3 syslog.3 openlog.3 syslog.3 setlogmask.3 \
syslog.3 vsyslog.3
MLINKS+=tcsendbreak.3 tcdrain.3 tcsendbreak.3 tcflush.3 tcsendbreak.3 tcflow.3
MLINKS+=tcsetattr.3 tcgetattr.3 tcsetattr.3 cfsetospeed.3 \
tcsetattr.3 cfgetospeed.3 tcsetattr.3 cfgetispeed.3 \
tcsetattr.3 cfsetispeed.3 tcsetattr.3 cfsetspeed.3 \
tcsetattr.3 cfmakeraw.3
MLINKS+=ttyname.3 isatty.3 ttyname.3 ttyslot.3
MLINKS+=tzset.3 tzsetwall.3
MLINKS+=vis.3 strvis.3 vis.3 strvisx.3

277
lib/libc/gen/crypt.3 Normal file
View file

@ -0,0 +1,277 @@
.\" Copyright (c) 1989, 1991, 1993
.\" The Regents of the University of California. All rights reserved.
.\"
.\" Redistribution and use in source and binary forms, with or without
.\" modification, are permitted provided that the following conditions
.\" are met:
.\" 1. Redistributions of source code must retain the above copyright
.\" notice, this list of conditions and the following disclaimer.
.\" 2. Redistributions in binary form must reproduce the above copyright
.\" notice, this list of conditions and the following disclaimer in the
.\" documentation and/or other materials provided with the distribution.
.\" 3. All advertising materials mentioning features or use of this software
.\" must display the following acknowledgement:
.\" This product includes software developed by the University of
.\" California, Berkeley and its contributors.
.\" 4. Neither the name of the University nor the names of its contributors
.\" may be used to endorse or promote products derived from this software
.\" without specific prior written permission.
.\"
.\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
.\" ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
.\" SUCH DAMAGE.
.\"
.\" @(#)crypt.3 8.1.1.1 (Berkeley) 8/18/93
.\"
.Dd August 18, 1993
.Dt CRYPT 3
.Os
.Sh NAME
.Nm crypt ,
.Nm setkey ,
.Nm encrypt ,
.Nm des_setkey ,
.Nm des_cipher
.Nd DES encryption
.Sh SYNOPSIS
.Ft char
.Fn *crypt "const char *key" "const char *setting"
.Ft int
.Fn setkey "char *key"
.Ft int
.Fn encrypt "char *block" "int flag"
.Ft int
.Fn des_setkey "const char *key"
.Ft int
.Fn des_cipher "const char *in" "char *out" "long salt" "int count"
.Sh DESCRIPTION
The
.Xr crypt
function
performs password encryption.
It is derived from the
.Tn NBS
Data Encryption Standard.
Additional code has been added to deter
key search attempts.
The first argument to
.Nm crypt
is
a
.Dv NUL Ns -terminated
string (normally a password typed by a user).
The second is a character array, 9 bytes in length, consisting of an
underscore (``_'') followed by 4 bytes of iteration count and 4 bytes
of salt.
Both the iteration
.Fa count
and the
.Fa salt
are encoded with 6 bits per character, least significant bits first.
The values 0 to 63 are encoded by the characters ``./0-9A-Za-z'',
respectively.
.Pp
The
.Fa salt
is used to induce disorder in to the
.Tn DES
algorithm
in one of 16777216
possible ways
(specifically, if bit
.Em i
of the
.Ar salt
is set then bits
.Em i
and
.Em i+24
are swapped in the
.Tn DES
``E'' box output).
The
.Ar key
is divided into groups of 8 characters (a short final group is null-padded)
and the low-order 7 bits of each character (56 bits per group) are
used to form the DES key as follows: the first group of 56 bits becomes the
initial DES key.
For each additional group, the XOR of the group bits and the encryption of
the DES key with itself becomes the next DES key.
Then the final DES key is used to perform
.Ar count
cumulative encryptions of a 64-bit constant.
The value returned is a
.Dv NUL Ns -terminated
string, 20 bytes in length, consisting
of the
.Ar setting
followed by the encoded 64-bit encryption.
.Pp
For compatibility with historical versions of
.Xr crypt 3 ,
the
.Ar setting
may consist of 2 bytes of salt, encoded as above, in which case an
iteration
.Ar count
of 25 is used, fewer perturbations of
.Tn DES
are available, at most 8
characters of
.Ar key
are used, and the returned value is a
.Dv NUL Ns -terminated
string 13 bytes in length.
.Pp
The
functions,
.Fn encrypt ,
.Fn setkey ,
.Fn des_setkey
and
.Fn des_cipher
allow limited access to the
.Tn DES
algorithm itself.
The
.Ar key
argument to
.Fn setkey
is a 64 character array of
binary values (numeric 0 or 1).
A 56-bit key is derived from this array by dividing the array
into groups of 8 and ignoring the last bit in each group.
.Pp
The
.Fn encrypt
argument
.Fa block
is also a 64 character array of
binary values.
If the value of
.Fa flag
is 0,
the argument
.Fa block
is encrypted, otherwise it fails.
The encryption is returned in the original
array
.Fa block
after using the
key specified
by
.Fn setkey
to process it.
.Pp
The
.Fn des_setkey
and
.Fn des_cipher
functions are faster but less portable than
.Fn setkey
and
.Fn encrypt .
The argument to
.Fn des_setkey
is a character array of length 8.
The
.Em least
significant bit in each character is ignored and the next 7 bits of each
character are concatenated to yield a 56-bit key.
The function
.Fn des_cipher
encrypts the 64-bits stored in the 8 characters at
.Fa in
using
.Xr abs 3
of
.Fa count
iterations of
.Tn DES
and stores the 64-bit result in the 8 characters at
.Fa out .
The
.Fa salt
specifies perturbations to
.Tn DES
as described above.
.Pp
The function
.Fn crypt
returns a pointer to the encrypted value on success and NULL on failure.
The functions
.Fn setkey ,
.Fn encrypt ,
.Fn des_setkey ,
and
.Fn des_cipher
return 0 on success and 1 on failure.
Historically, the functions
.Fn setkey
and
.Fn encrypt
did not return any value.
They have been provided return values primarily to distinguish
implementations where hardware support is provided but not
available or where the DES encryption is not available due to the
usual political silliness.
.Sh SEE ALSO
.Xr login 1 ,
.Xr passwd 1 ,
.Xr getpass 3 ,
.Xr passwd 5
.sp
.Rs
.%T "Mathematical Cryptology for Computer Scientists and Mathematicians"
.%A Wayne Patterson
.%D 1987
.%N ISBN 0-8476-7438-X
.Re
.Rs
.%T "Password Security: A Case History"
.%A R. Morris
.%A Ken Thompson
.%J "Communications of the ACM"
.%V vol. 22
.%P pp. 594-597
.%D Nov. 1979
.Re
.Rs
.%T "DES will be Totally Insecure within Ten Years"
.%A M.E. Hellman
.%J "IEEE Spectrum"
.%V vol. 16
.%P pp. 32-39
.%D July 1979
.Re
.Sh HISTORY
A rotor-based
.Fn crypt
function appeared in
.At v6 .
The current style
.Fn crypt
first appeared in
.At v7 .
.Sh BUGS
Dropping the
.Em least
significant bit in each character of the argument to
.Fn des_setkey
is ridiculous.
.Pp
The
.Fn crypt
function leaves its result in an internal static object and returns
a pointer to that object.
Subsequent calls to
.Fn crypt
will modify the same object.

68
lib/libc/gen/devname.3 Normal file
View file

@ -0,0 +1,68 @@
.\" Copyright (c) 1993
.\" The Regents of the University of California. All rights reserved.
.\"
.\" Redistribution and use in source and binary forms, with or without
.\" modification, are permitted provided that the following conditions
.\" are met:
.\" 1. Redistributions of source code must retain the above copyright
.\" notice, this list of conditions and the following disclaimer.
.\" 2. Redistributions in binary form must reproduce the above copyright
.\" notice, this list of conditions and the following disclaimer in the
.\" documentation and/or other materials provided with the distribution.
.\" 3. All advertising materials mentioning features or use of this software
.\" must display the following acknowledgement:
.\" This product includes software developed by the University of
.\" California, Berkeley and its contributors.
.\" 4. Neither the name of the University nor the names of its contributors
.\" may be used to endorse or promote products derived from this software
.\" without specific prior written permission.
.\"
.\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
.\" ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
.\" SUCH DAMAGE.
.\"
.\" @(#)devname.3 8.2 (Berkeley) 4/29/95
.\"
.Dd April 29, 1995
.Dt DEVNAME 3
.Os BSD 4.4
.Sh NAME
.Nm devname
.Nd get device name
.Sh SYNOPSIS
.Fd #include <stdlib.h>
.Ft char *
.Fn devname "dev_t dev" "mode_t type"
.Sh DESCRIPTION
The
.Fn devname
function returns a pointer to the name of the block or character
device in
.Dq Pa /dev
with a device number of
.Fa dev ,
and a file type matching the one encoded in
.Fa type
which must be one of S_IFBLK or S_IFCHR.
If no device matches the specified values, or no information is
available, NULL is returned.
.Pp
The traditional display for applications when no device is
found is the string
.Dq ?? .
.Sh SEE ALSO
.Xr stat 2 ,
.Xr dev_mkdb 8
.Sh HISTORY
The
.Nm devname
function call appeared in
.Bx 4.4 .

80
lib/libc/gen/devname.c Normal file
View file

@ -0,0 +1,80 @@
/*
* Copyright (c) 1989, 1993
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#if defined(LIBC_SCCS) && !defined(lint)
static char sccsid[] = "@(#)devname.c 8.2 (Berkeley) 4/29/95";
#endif /* LIBC_SCCS and not lint */
#include <sys/types.h>
#include <db.h>
#include <err.h>
#include <errno.h>
#include <fcntl.h>
#include <paths.h>
#include <stdio.h>
#include <string.h>
char *
devname(dev, type)
dev_t dev;
mode_t type;
{
struct {
mode_t type;
dev_t dev;
} bkey;
static DB *db;
static int failure;
DBT data, key;
if (!db && !failure &&
!(db = dbopen(_PATH_DEVDB, O_RDONLY, 0, DB_HASH, NULL))) {
warn("warning: %s", _PATH_DEVDB);
failure = 1;
}
if (failure)
return (NULL);
/*
* Keys are a mode_t followed by a dev_t. The former is the type of
* the file (mode & S_IFMT), the latter is the st_rdev field. Be
* sure to clear any padding that may be found in bkey.
*/
memset(&bkey, 0, sizeof(bkey));
bkey.dev = dev;
bkey.type = type;
key.data = &bkey;
key.size = sizeof(bkey);
return ((db->get)(db, &key, &data, 0) ? NULL : (char *)data.data);
}

184
lib/libc/gen/disklabel.c Normal file
View file

@ -0,0 +1,184 @@
/*
* Copyright (c) 1983, 1987, 1993
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#ifndef lint
static char sccsid[] = "@(#)disklabel.c 8.2 (Berkeley) 5/3/95";
#endif /* not lint */
#include <sys/param.h>
#define DKTYPENAMES
#include <sys/disklabel.h>
#include <ufs/ufs/dinode.h>
#include <ufs/ffs/fs.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
static int error __P((int));
static int gettype __P((char *, char **));
struct disklabel *
getdiskbyname(name)
const char *name;
{
static struct disklabel disk;
register struct disklabel *dp = &disk;
register struct partition *pp;
char *buf;
char *db_array[2] = { _PATH_DISKTAB, 0 };
char *cp, *cq; /* can't be register */
char p, max, psize[3], pbsize[3],
pfsize[3], poffset[3], ptype[3];
u_int32_t *dx;
if (cgetent(&buf, db_array, (char *) name) < 0)
return NULL;
bzero((char *)&disk, sizeof(disk));
/*
* typename
*/
cq = dp->d_typename;
cp = buf;
while (cq < dp->d_typename + sizeof(dp->d_typename) - 1 &&
(*cq = *cp) && *cq != '|' && *cq != ':')
cq++, cp++;
*cq = '\0';
/*
* boot name (optional) xxboot, bootxx
*/
cgetstr(buf, "b0", &dp->d_boot0);
cgetstr(buf, "b1", &dp->d_boot1);
if (cgetstr(buf, "ty", &cq) > 0 && strcmp(cq, "removable") == 0)
dp->d_flags |= D_REMOVABLE;
else if (cq && strcmp(cq, "simulated") == 0)
dp->d_flags |= D_RAMDISK;
if (cgetcap(buf, "sf", ':') != NULL)
dp->d_flags |= D_BADSECT;
#define getnumdflt(field, dname, dflt) \
{ long f; (field) = (cgetnum(buf, dname, &f) == -1) ? (dflt) : f; }
getnumdflt(dp->d_secsize, "se", DEV_BSIZE);
cgetnum(buf, "nt",(long *) &dp->d_ntracks);
cgetnum(buf, "ns",(long *) &dp->d_nsectors);
cgetnum(buf, "nc",(long *) &dp->d_ncylinders);
if (cgetstr(buf, "dt", &cq) > 0)
dp->d_type = gettype(cq, dktypenames);
else
getnumdflt(dp->d_type, "dt", 0);
getnumdflt(dp->d_secpercyl, "sc", dp->d_nsectors * dp->d_ntracks);
getnumdflt(dp->d_secperunit, "su", dp->d_secpercyl * dp->d_ncylinders);
getnumdflt(dp->d_rpm, "rm", 3600);
getnumdflt(dp->d_interleave, "il", 1);
getnumdflt(dp->d_trackskew, "sk", 0);
getnumdflt(dp->d_cylskew, "cs", 0);
getnumdflt(dp->d_headswitch, "hs", 0);
getnumdflt(dp->d_trkseek, "ts", 0);
getnumdflt(dp->d_bbsize, "bs", BBSIZE);
getnumdflt(dp->d_sbsize, "sb", SBSIZE);
strcpy(psize, "px");
strcpy(pbsize, "bx");
strcpy(pfsize, "fx");
strcpy(poffset, "ox");
strcpy(ptype, "tx");
max = 'a' - 1;
pp = &dp->d_partitions[0];
for (p = 'a'; p < 'a' + MAXPARTITIONS; p++, pp++) {
psize[1] = pbsize[1] = pfsize[1] = poffset[1] = ptype[1] = p;
if (cgetnum(buf, psize,(long *) &pp->p_size) == -1)
pp->p_size = 0;
else {
cgetnum(buf, poffset, (long *) &pp->p_offset);
getnumdflt(pp->p_fsize, pfsize, 0);
if (pp->p_fsize) {
long bsize;
if (cgetnum(buf, pbsize, &bsize) == 0)
pp->p_frag = bsize / pp->p_fsize;
else
pp->p_frag = 8;
}
getnumdflt(pp->p_fstype, ptype, 0);
if (pp->p_fstype == 0 && cgetstr(buf, ptype, &cq) > 0)
pp->p_fstype = gettype(cq, fstypenames);
max = p;
}
}
dp->d_npartitions = max + 1 - 'a';
(void)strcpy(psize, "dx");
dx = dp->d_drivedata;
for (p = '0'; p < '0' + NDDATA; p++, dx++) {
psize[1] = p;
getnumdflt(*dx, psize, 0);
}
dp->d_magic = DISKMAGIC;
dp->d_magic2 = DISKMAGIC;
free(buf);
return (dp);
}
static int
gettype(t, names)
char *t;
char **names;
{
register char **nm;
for (nm = names; *nm; nm++)
if (strcasecmp(t, *nm) == 0)
return (nm - names);
if (isdigit(*t))
return (atoi(t));
return (0);
}
static int
error(err)
int err;
{
char *p;
(void)write(STDERR_FILENO, "disktab: ", 9);
(void)write(STDERR_FILENO, _PATH_DISKTAB, sizeof(_PATH_DISKTAB) - 1);
(void)write(STDERR_FILENO, ": ", 2);
p = strerror(err);
(void)write(STDERR_FILENO, p, strlen(p));
(void)write(STDERR_FILENO, "\n", 1);
}

126
lib/libc/gen/fnmatch.3 Normal file
View file

@ -0,0 +1,126 @@
.\" Copyright (c) 1989, 1991, 1993
.\" The Regents of the University of California. All rights reserved.
.\"
.\" This code is derived from software contributed to Berkeley by
.\" Guido van Rossum.
.\" Redistribution and use in source and binary forms, with or without
.\" modification, are permitted provided that the following conditions
.\" are met:
.\" 1. Redistributions of source code must retain the above copyright
.\" notice, this list of conditions and the following disclaimer.
.\" 2. Redistributions in binary form must reproduce the above copyright
.\" notice, this list of conditions and the following disclaimer in the
.\" documentation and/or other materials provided with the distribution.
.\" 3. All advertising materials mentioning features or use of this software
.\" must display the following acknowledgement:
.\" This product includes software developed by the University of
.\" California, Berkeley and its contributors.
.\" 4. Neither the name of the University nor the names of its contributors
.\" may be used to endorse or promote products derived from this software
.\" without specific prior written permission.
.\"
.\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
.\" ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
.\" SUCH DAMAGE.
.\"
.\" @(#)fnmatch.3 8.3 (Berkeley) 4/28/95
.\"
.Dd April 28, 1995
.Dt FNMATCH 3
.Os
.Sh NAME
.Nm fnmatch
.Nd match filename or pathname
.Sh SYNOPSIS
.Fd #include <fnmatch.h>
.Ft int
.Fn fnmatch "const char *pattern" "const char *string" "int flags"
.Sh DESCRIPTION
The
.Fn fnmatch
function
matches patterns according to the rules used by the shell.
It checks the string specified by the
.Fa string
argument to see if it matches the pattern specified by the
.Fa pattern
argument.
.Pp
The
.Fa flags
argument modifies the interpretation of
.Fa pattern
and
.Fa string .
The value of
.Fa flags
is the bitwise inclusive
.Tn OR
of any of the following
constants, which are defined in the include file
.Pa fnmatch.h .
.Bl -tag -width FNM_PATHNAME
.It Dv FNM_NOESCAPE
Normally, every occurrence of a backslash
.Pq Ql \e
followed by a character in
.Fa pattern
is replaced by that character.
This is done to negate any special meaning for the character.
If the
.Dv FNM_NOESCAPE
flag is set, a backslash character is treated as an ordinary character.
.It Dv FNM_PATHNAME
Slash characters in
.Fa string
must be explicitly matched by slashes in
.Fa pattern .
If this flag is not set, then slashes are treated as regular characters.
.It Dv FNM_PERIOD
Leading periods in strings match periods in patterns.
The definition of ``leading'' is related to the specification of
.Dv FNM_PATHNAME.
A period is always ``leading'' if it is the first character in
.Ar string .
Additionally, if
.Dv FNM_PATHNAME
is set,
a period is ``leading'' if it immediately follows a slash.
.El
.Sh RETURN VALUES
The
.Fn fnmatch
function returns zero if
.Fa string
matches the pattern specified by
.Fa pattern ,
otherwise, it returns the value
.Dv FNM_NOMATCH .
.Sh SEE ALSO
.Xr sh 1 ,
.Xr glob 3 ,
.Xr regex 3
.Sh STANDARDS
The
.Fn fnmatch
function conforms to
.St -p1003.2 .
.Sh HISTORY
The
.Fn fnmatch
function first appeared in
.Bx 4.4 .
.Sh BUGS
The pattern
.Ql *
matches the empty string, even if
.Dv FNM_PATHNAME
is specified.

995
lib/libc/gen/fts.c Normal file
View file

@ -0,0 +1,995 @@
/*-
* Copyright (c) 1990, 1993, 1994
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#if defined(LIBC_SCCS) && !defined(lint)
static char sccsid[] = "@(#)fts.c 8.6 (Berkeley) 8/14/94";
#endif /* LIBC_SCCS and not lint */
#include <sys/param.h>
#include <sys/stat.h>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <fts.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
static FTSENT *fts_alloc __P((FTS *, char *, int));
static FTSENT *fts_build __P((FTS *, int));
static void fts_lfree __P((FTSENT *));
static void fts_load __P((FTS *, FTSENT *));
static size_t fts_maxarglen __P((char * const *));
static void fts_padjust __P((FTS *, void *));
static int fts_palloc __P((FTS *, size_t));
static FTSENT *fts_sort __P((FTS *, FTSENT *, int));
static u_short fts_stat __P((FTS *, FTSENT *, int));
#define ISDOT(a) (a[0] == '.' && (!a[1] || a[1] == '.' && !a[2]))
#define ISSET(opt) (sp->fts_options & opt)
#define SET(opt) (sp->fts_options |= opt)
#define CHDIR(sp, path) (!ISSET(FTS_NOCHDIR) && chdir(path))
#define FCHDIR(sp, fd) (!ISSET(FTS_NOCHDIR) && fchdir(fd))
/* fts_build flags */
#define BCHILD 1 /* fts_children */
#define BNAMES 2 /* fts_children, names only */
#define BREAD 3 /* fts_read */
FTS *
fts_open(argv, options, compar)
char * const *argv;
register int options;
int (*compar)();
{
register FTS *sp;
register FTSENT *p, *root;
register int nitems;
FTSENT *parent, *tmp;
int len;
/* Options check. */
if (options & ~FTS_OPTIONMASK) {
errno = EINVAL;
return (NULL);
}
/* Allocate/initialize the stream */
if ((sp = malloc((u_int)sizeof(FTS))) == NULL)
return (NULL);
memset(sp, 0, sizeof(FTS));
sp->fts_compar = compar;
sp->fts_options = options;
/* Logical walks turn on NOCHDIR; symbolic links are too hard. */
if (ISSET(FTS_LOGICAL))
SET(FTS_NOCHDIR);
/*
* Start out with 1K of path space, and enough, in any case,
* to hold the user's paths.
*/
if (fts_palloc(sp, MAX(fts_maxarglen(argv), MAXPATHLEN)))
goto mem1;
/* Allocate/initialize root's parent. */
if ((parent = fts_alloc(sp, "", 0)) == NULL)
goto mem2;
parent->fts_level = FTS_ROOTPARENTLEVEL;
/* Allocate/initialize root(s). */
for (root = NULL, nitems = 0; *argv; ++argv, ++nitems) {
/* Don't allow zero-length paths. */
if ((len = strlen(*argv)) == 0) {
errno = ENOENT;
goto mem3;
}
p = fts_alloc(sp, *argv, len);
p->fts_level = FTS_ROOTLEVEL;
p->fts_parent = parent;
p->fts_accpath = p->fts_name;
p->fts_info = fts_stat(sp, p, ISSET(FTS_COMFOLLOW));
/* Command-line "." and ".." are real directories. */
if (p->fts_info == FTS_DOT)
p->fts_info = FTS_D;
/*
* If comparison routine supplied, traverse in sorted
* order; otherwise traverse in the order specified.
*/
if (compar) {
p->fts_link = root;
root = p;
} else {
p->fts_link = NULL;
if (root == NULL)
tmp = root = p;
else {
tmp->fts_link = p;
tmp = p;
}
}
}
if (compar && nitems > 1)
root = fts_sort(sp, root, nitems);
/*
* Allocate a dummy pointer and make fts_read think that we've just
* finished the node before the root(s); set p->fts_info to FTS_INIT
* so that everything about the "current" node is ignored.
*/
if ((sp->fts_cur = fts_alloc(sp, "", 0)) == NULL)
goto mem3;
sp->fts_cur->fts_link = root;
sp->fts_cur->fts_info = FTS_INIT;
/*
* If using chdir(2), grab a file descriptor pointing to dot to insure
* that we can get back here; this could be avoided for some paths,
* but almost certainly not worth the effort. Slashes, symbolic links,
* and ".." are all fairly nasty problems. Note, if we can't get the
* descriptor we run anyway, just more slowly.
*/
if (!ISSET(FTS_NOCHDIR) && (sp->fts_rfd = open(".", O_RDONLY, 0)) < 0)
SET(FTS_NOCHDIR);
return (sp);
mem3: fts_lfree(root);
free(parent);
mem2: free(sp->fts_path);
mem1: free(sp);
return (NULL);
}
static void
fts_load(sp, p)
FTS *sp;
register FTSENT *p;
{
register int len;
register char *cp;
/*
* Load the stream structure for the next traversal. Since we don't
* actually enter the directory until after the preorder visit, set
* the fts_accpath field specially so the chdir gets done to the right
* place and the user can access the first node. From fts_open it's
* known that the path will fit.
*/
len = p->fts_pathlen = p->fts_namelen;
memmove(sp->fts_path, p->fts_name, len + 1);
if ((cp = strrchr(p->fts_name, '/')) && (cp != p->fts_name || cp[1])) {
len = strlen(++cp);
memmove(p->fts_name, cp, len + 1);
p->fts_namelen = len;
}
p->fts_accpath = p->fts_path = sp->fts_path;
sp->fts_dev = p->fts_dev;
}
int
fts_close(sp)
FTS *sp;
{
register FTSENT *freep, *p;
int saved_errno;
/*
* This still works if we haven't read anything -- the dummy structure
* points to the root list, so we step through to the end of the root
* list which has a valid parent pointer.
*/
if (sp->fts_cur) {
for (p = sp->fts_cur; p->fts_level >= FTS_ROOTLEVEL;) {
freep = p;
p = p->fts_link ? p->fts_link : p->fts_parent;
free(freep);
}
free(p);
}
/* Free up child linked list, sort array, path buffer. */
if (sp->fts_child)
fts_lfree(sp->fts_child);
if (sp->fts_array)
free(sp->fts_array);
free(sp->fts_path);
/* Return to original directory, save errno if necessary. */
if (!ISSET(FTS_NOCHDIR)) {
saved_errno = fchdir(sp->fts_rfd) ? errno : 0;
(void)close(sp->fts_rfd);
}
/* Free up the stream pointer. */
free(sp);
/* Set errno and return. */
if (!ISSET(FTS_NOCHDIR) && saved_errno) {
errno = saved_errno;
return (-1);
}
return (0);
}
/*
* Special case a root of "/" so that slashes aren't appended which would
* cause paths to be written as "//foo".
*/
#define NAPPEND(p) \
(p->fts_level == FTS_ROOTLEVEL && p->fts_pathlen == 1 && \
p->fts_path[0] == '/' ? 0 : p->fts_pathlen)
FTSENT *
fts_read(sp)
register FTS *sp;
{
register FTSENT *p, *tmp;
register int instr;
register char *t;
int saved_errno;
/* If finished or unrecoverable error, return NULL. */
if (sp->fts_cur == NULL || ISSET(FTS_STOP))
return (NULL);
/* Set current node pointer. */
p = sp->fts_cur;
/* Save and zero out user instructions. */
instr = p->fts_instr;
p->fts_instr = FTS_NOINSTR;
/* Any type of file may be re-visited; re-stat and re-turn. */
if (instr == FTS_AGAIN) {
p->fts_info = fts_stat(sp, p, 0);
return (p);
}
/*
* Following a symlink -- SLNONE test allows application to see
* SLNONE and recover. If indirecting through a symlink, have
* keep a pointer to current location. If unable to get that
* pointer, follow fails.
*/
if (instr == FTS_FOLLOW &&
(p->fts_info == FTS_SL || p->fts_info == FTS_SLNONE)) {
p->fts_info = fts_stat(sp, p, 1);
if (p->fts_info == FTS_D && !ISSET(FTS_NOCHDIR))
if ((p->fts_symfd = open(".", O_RDONLY, 0)) < 0) {
p->fts_errno = errno;
p->fts_info = FTS_ERR;
} else
p->fts_flags |= FTS_SYMFOLLOW;
return (p);
}
/* Directory in pre-order. */
if (p->fts_info == FTS_D) {
/* If skipped or crossed mount point, do post-order visit. */
if (instr == FTS_SKIP ||
ISSET(FTS_XDEV) && p->fts_dev != sp->fts_dev) {
if (p->fts_flags & FTS_SYMFOLLOW)
(void)close(p->fts_symfd);
if (sp->fts_child) {
fts_lfree(sp->fts_child);
sp->fts_child = NULL;
}
p->fts_info = FTS_DP;
return (p);
}
/* Rebuild if only read the names and now traversing. */
if (sp->fts_child && sp->fts_options & FTS_NAMEONLY) {
sp->fts_options &= ~FTS_NAMEONLY;
fts_lfree(sp->fts_child);
sp->fts_child = NULL;
}
/*
* Cd to the subdirectory.
*
* If have already read and now fail to chdir, whack the list
* to make the names come out right, and set the parent errno
* so the application will eventually get an error condition.
* Set the FTS_DONTCHDIR flag so that when we logically change
* directories back to the parent we don't do a chdir.
*
* If haven't read do so. If the read fails, fts_build sets
* FTS_STOP or the fts_info field of the node.
*/
if (sp->fts_child) {
if (CHDIR(sp, p->fts_accpath)) {
p->fts_errno = errno;
p->fts_flags |= FTS_DONTCHDIR;
for (p = sp->fts_child; p; p = p->fts_link)
p->fts_accpath =
p->fts_parent->fts_accpath;
}
} else if ((sp->fts_child = fts_build(sp, BREAD)) == NULL) {
if (ISSET(FTS_STOP))
return (NULL);
return (p);
}
p = sp->fts_child;
sp->fts_child = NULL;
goto name;
}
/* Move to the next node on this level. */
next: tmp = p;
if (p = p->fts_link) {
free(tmp);
/*
* If reached the top, return to the original directory, and
* load the paths for the next root.
*/
if (p->fts_level == FTS_ROOTLEVEL) {
if (!ISSET(FTS_NOCHDIR) && FCHDIR(sp, sp->fts_rfd)) {
SET(FTS_STOP);
return (NULL);
}
fts_load(sp, p);
return (sp->fts_cur = p);
}
/*
* User may have called fts_set on the node. If skipped,
* ignore. If followed, get a file descriptor so we can
* get back if necessary.
*/
if (p->fts_instr == FTS_SKIP)
goto next;
if (p->fts_instr == FTS_FOLLOW) {
p->fts_info = fts_stat(sp, p, 1);
if (p->fts_info == FTS_D && !ISSET(FTS_NOCHDIR))
if ((p->fts_symfd =
open(".", O_RDONLY, 0)) < 0) {
p->fts_errno = errno;
p->fts_info = FTS_ERR;
} else
p->fts_flags |= FTS_SYMFOLLOW;
p->fts_instr = FTS_NOINSTR;
}
name: t = sp->fts_path + NAPPEND(p->fts_parent);
*t++ = '/';
memmove(t, p->fts_name, p->fts_namelen + 1);
return (sp->fts_cur = p);
}
/* Move up to the parent node. */
p = tmp->fts_parent;
free(tmp);
if (p->fts_level == FTS_ROOTPARENTLEVEL) {
/*
* Done; free everything up and set errno to 0 so the user
* can distinguish between error and EOF.
*/
free(p);
errno = 0;
return (sp->fts_cur = NULL);
}
/* Nul terminate the pathname. */
sp->fts_path[p->fts_pathlen] = '\0';
/*
* Return to the parent directory. If at a root node or came through
* a symlink, go back through the file descriptor. Otherwise, cd up
* one directory.
*/
if (p->fts_level == FTS_ROOTLEVEL) {
if (!ISSET(FTS_NOCHDIR) && FCHDIR(sp, sp->fts_rfd)) {
SET(FTS_STOP);
return (NULL);
}
} else if (p->fts_flags & FTS_SYMFOLLOW) {
if (FCHDIR(sp, p->fts_symfd)) {
saved_errno = errno;
(void)close(p->fts_symfd);
errno = saved_errno;
SET(FTS_STOP);
return (NULL);
}
(void)close(p->fts_symfd);
} else if (!(p->fts_flags & FTS_DONTCHDIR)) {
if (CHDIR(sp, "..")) {
SET(FTS_STOP);
return (NULL);
}
}
p->fts_info = p->fts_errno ? FTS_ERR : FTS_DP;
return (sp->fts_cur = p);
}
/*
* Fts_set takes the stream as an argument although it's not used in this
* implementation; it would be necessary if anyone wanted to add global
* semantics to fts using fts_set. An error return is allowed for similar
* reasons.
*/
/* ARGSUSED */
int
fts_set(sp, p, instr)
FTS *sp;
FTSENT *p;
int instr;
{
if (instr && instr != FTS_AGAIN && instr != FTS_FOLLOW &&
instr != FTS_NOINSTR && instr != FTS_SKIP) {
errno = EINVAL;
return (1);
}
p->fts_instr = instr;
return (0);
}
FTSENT *
fts_children(sp, instr)
register FTS *sp;
int instr;
{
register FTSENT *p;
int fd;
if (instr && instr != FTS_NAMEONLY) {
errno = EINVAL;
return (NULL);
}
/* Set current node pointer. */
p = sp->fts_cur;
/*
* Errno set to 0 so user can distinguish empty directory from
* an error.
*/
errno = 0;
/* Fatal errors stop here. */
if (ISSET(FTS_STOP))
return (NULL);
/* Return logical hierarchy of user's arguments. */
if (p->fts_info == FTS_INIT)
return (p->fts_link);
/*
* If not a directory being visited in pre-order, stop here. Could
* allow FTS_DNR, assuming the user has fixed the problem, but the
* same effect is available with FTS_AGAIN.
*/
if (p->fts_info != FTS_D /* && p->fts_info != FTS_DNR */)
return (NULL);
/* Free up any previous child list. */
if (sp->fts_child)
fts_lfree(sp->fts_child);
if (instr == FTS_NAMEONLY) {
sp->fts_options |= FTS_NAMEONLY;
instr = BNAMES;
} else
instr = BCHILD;
/*
* If using chdir on a relative path and called BEFORE fts_read does
* its chdir to the root of a traversal, we can lose -- we need to
* chdir into the subdirectory, and we don't know where the current
* directory is, so we can't get back so that the upcoming chdir by
* fts_read will work.
*/
if (p->fts_level != FTS_ROOTLEVEL || p->fts_accpath[0] == '/' ||
ISSET(FTS_NOCHDIR))
return (sp->fts_child = fts_build(sp, instr));
if ((fd = open(".", O_RDONLY, 0)) < 0)
return (NULL);
sp->fts_child = fts_build(sp, instr);
if (fchdir(fd))
return (NULL);
(void)close(fd);
return (sp->fts_child);
}
/*
* This is the tricky part -- do not casually change *anything* in here. The
* idea is to build the linked list of entries that are used by fts_children
* and fts_read. There are lots of special cases.
*
* The real slowdown in walking the tree is the stat calls. If FTS_NOSTAT is
* set and it's a physical walk (so that symbolic links can't be directories),
* we can do things quickly. First, if it's a 4.4BSD file system, the type
* of the file is in the directory entry. Otherwise, we assume that the number
* of subdirectories in a node is equal to the number of links to the parent.
* The former skips all stat calls. The latter skips stat calls in any leaf
* directories and for any files after the subdirectories in the directory have
* been found, cutting the stat calls by about 2/3.
*/
static FTSENT *
fts_build(sp, type)
register FTS *sp;
int type;
{
register struct dirent *dp;
register FTSENT *p, *head;
register int nitems;
FTSENT *cur, *tail;
DIR *dirp;
void *adjaddr;
int cderrno, descend, len, level, maxlen, nlinks, oflag, saved_errno;
char *cp;
/* Set current node pointer. */
cur = sp->fts_cur;
/*
* Open the directory for reading. If this fails, we're done.
* If being called from fts_read, set the fts_info field.
*/
#ifdef FTS_WHITEOUT
if (ISSET(FTS_WHITEOUT))
oflag = DTF_NODUP|DTF_REWIND;
else
oflag = DTF_HIDEW|DTF_NODUP|DTF_REWIND;
#else
#define __opendir2(path, flag) opendir(path)
#endif
if ((dirp = __opendir2(cur->fts_accpath, oflag)) == NULL) {
if (type == BREAD) {
cur->fts_info = FTS_DNR;
cur->fts_errno = errno;
}
return (NULL);
}
/*
* Nlinks is the number of possible entries of type directory in the
* directory if we're cheating on stat calls, 0 if we're not doing
* any stat calls at all, -1 if we're doing stats on everything.
*/
if (type == BNAMES)
nlinks = 0;
else if (ISSET(FTS_NOSTAT) && ISSET(FTS_PHYSICAL))
nlinks = cur->fts_nlink - (ISSET(FTS_SEEDOT) ? 0 : 2);
else
nlinks = -1;
#ifdef notdef
(void)printf("nlinks == %d (cur: %d)\n", nlinks, cur->fts_nlink);
(void)printf("NOSTAT %d PHYSICAL %d SEEDOT %d\n",
ISSET(FTS_NOSTAT), ISSET(FTS_PHYSICAL), ISSET(FTS_SEEDOT));
#endif
/*
* If we're going to need to stat anything or we want to descend
* and stay in the directory, chdir. If this fails we keep going,
* but set a flag so we don't chdir after the post-order visit.
* We won't be able to stat anything, but we can still return the
* names themselves. Note, that since fts_read won't be able to
* chdir into the directory, it will have to return different path
* names than before, i.e. "a/b" instead of "b". Since the node
* has already been visited in pre-order, have to wait until the
* post-order visit to return the error. There is a special case
* here, if there was nothing to stat then it's not an error to
* not be able to stat. This is all fairly nasty. If a program
* needed sorted entries or stat information, they had better be
* checking FTS_NS on the returned nodes.
*/
cderrno = 0;
if (nlinks || type == BREAD)
if (FCHDIR(sp, dirfd(dirp))) {
if (nlinks && type == BREAD)
cur->fts_errno = errno;
cur->fts_flags |= FTS_DONTCHDIR;
descend = 0;
cderrno = errno;
} else
descend = 1;
else
descend = 0;
/*
* Figure out the max file name length that can be stored in the
* current path -- the inner loop allocates more path as necessary.
* We really wouldn't have to do the maxlen calculations here, we
* could do them in fts_read before returning the path, but it's a
* lot easier here since the length is part of the dirent structure.
*
* If not changing directories set a pointer so that can just append
* each new name into the path.
*/
maxlen = sp->fts_pathlen - cur->fts_pathlen - 1;
len = NAPPEND(cur);
if (ISSET(FTS_NOCHDIR)) {
cp = sp->fts_path + len;
*cp++ = '/';
}
level = cur->fts_level + 1;
/* Read the directory, attaching each entry to the `link' pointer. */
adjaddr = NULL;
for (head = tail = NULL, nitems = 0; dp = readdir(dirp);) {
if (!ISSET(FTS_SEEDOT) && ISDOT(dp->d_name))
continue;
if ((p = fts_alloc(sp, dp->d_name, (int)dp->d_namlen)) == NULL)
goto mem1;
if (dp->d_namlen > maxlen) {
if (fts_palloc(sp, (size_t)dp->d_namlen)) {
/*
* No more memory for path or structures. Save
* errno, free up the current structure and the
* structures already allocated.
*/
mem1: saved_errno = errno;
if (p)
free(p);
fts_lfree(head);
(void)closedir(dirp);
errno = saved_errno;
cur->fts_info = FTS_ERR;
SET(FTS_STOP);
return (NULL);
}
adjaddr = sp->fts_path;
maxlen = sp->fts_pathlen - sp->fts_cur->fts_pathlen - 1;
}
p->fts_pathlen = len + dp->d_namlen + 1;
p->fts_parent = sp->fts_cur;
p->fts_level = level;
#ifdef FTS_WHITEOUT
if (dp->d_type == DT_WHT)
p->fts_flags |= FTS_ISW;
#endif
if (cderrno) {
if (nlinks) {
p->fts_info = FTS_NS;
p->fts_errno = cderrno;
} else
p->fts_info = FTS_NSOK;
p->fts_accpath = cur->fts_accpath;
} else if (nlinks == 0
#ifdef DT_DIR
|| nlinks > 0 &&
dp->d_type != DT_DIR && dp->d_type != DT_UNKNOWN
#endif
) {
p->fts_accpath =
ISSET(FTS_NOCHDIR) ? p->fts_path : p->fts_name;
p->fts_info = FTS_NSOK;
} else {
/* Build a file name for fts_stat to stat. */
if (ISSET(FTS_NOCHDIR)) {
p->fts_accpath = p->fts_path;
memmove(cp, p->fts_name, p->fts_namelen + 1);
} else
p->fts_accpath = p->fts_name;
/* Stat it. */
p->fts_info = fts_stat(sp, p, 0);
/* Decrement link count if applicable. */
if (nlinks > 0 && (p->fts_info == FTS_D ||
p->fts_info == FTS_DC || p->fts_info == FTS_DOT))
--nlinks;
}
/* We walk in directory order so "ls -f" doesn't get upset. */
p->fts_link = NULL;
if (head == NULL)
head = tail = p;
else {
tail->fts_link = p;
tail = p;
}
++nitems;
}
(void)closedir(dirp);
/*
* If had to realloc the path, adjust the addresses for the rest
* of the tree.
*/
if (adjaddr)
fts_padjust(sp, adjaddr);
/*
* If not changing directories, reset the path back to original
* state.
*/
if (ISSET(FTS_NOCHDIR)) {
if (cp - 1 > sp->fts_path)
--cp;
*cp = '\0';
}
/*
* If descended after called from fts_children or after called from
* fts_read and nothing found, get back. At the root level we use
* the saved fd; if one of fts_open()'s arguments is a relative path
* to an empty directory, we wind up here with no other way back. If
* can't get back, we're done.
*/
if (descend && (type == BCHILD || !nitems) &&
(cur->fts_level == FTS_ROOTLEVEL ?
FCHDIR(sp, sp->fts_rfd) : CHDIR(sp, ".."))) {
cur->fts_info = FTS_ERR;
SET(FTS_STOP);
return (NULL);
}
/* If didn't find anything, return NULL. */
if (!nitems) {
if (type == BREAD)
cur->fts_info = FTS_DP;
return (NULL);
}
/* Sort the entries. */
if (sp->fts_compar && nitems > 1)
head = fts_sort(sp, head, nitems);
return (head);
}
static u_short
fts_stat(sp, p, follow)
FTS *sp;
register FTSENT *p;
int follow;
{
register FTSENT *t;
register dev_t dev;
register ino_t ino;
struct stat *sbp, sb;
int saved_errno;
/* If user needs stat info, stat buffer already allocated. */
sbp = ISSET(FTS_NOSTAT) ? &sb : p->fts_statp;
#ifdef FTS_WHITEOUT
/* check for whiteout */
if (p->fts_flags & FTS_ISW) {
if (sbp != &sb) {
memset(sbp, '\0', sizeof (*sbp));
sbp->st_mode = S_IFWHT;
}
return (FTS_W);
}
#endif
/*
* If doing a logical walk, or application requested FTS_FOLLOW, do
* a stat(2). If that fails, check for a non-existent symlink. If
* fail, set the errno from the stat call.
*/
if (ISSET(FTS_LOGICAL) || follow) {
if (stat(p->fts_accpath, sbp)) {
saved_errno = errno;
if (!lstat(p->fts_accpath, sbp)) {
errno = 0;
return (FTS_SLNONE);
}
p->fts_errno = saved_errno;
goto err;
}
} else if (lstat(p->fts_accpath, sbp)) {
p->fts_errno = errno;
err: memset(sbp, 0, sizeof(struct stat));
return (FTS_NS);
}
if (S_ISDIR(sbp->st_mode)) {
/*
* Set the device/inode. Used to find cycles and check for
* crossing mount points. Also remember the link count, used
* in fts_build to limit the number of stat calls. It is
* understood that these fields are only referenced if fts_info
* is set to FTS_D.
*/
dev = p->fts_dev = sbp->st_dev;
ino = p->fts_ino = sbp->st_ino;
p->fts_nlink = sbp->st_nlink;
if (ISDOT(p->fts_name))
return (FTS_DOT);
/*
* Cycle detection is done by brute force when the directory
* is first encountered. If the tree gets deep enough or the
* number of symbolic links to directories is high enough,
* something faster might be worthwhile.
*/
for (t = p->fts_parent;
t->fts_level >= FTS_ROOTLEVEL; t = t->fts_parent)
if (ino == t->fts_ino && dev == t->fts_dev) {
p->fts_cycle = t;
return (FTS_DC);
}
return (FTS_D);
}
if (S_ISLNK(sbp->st_mode))
return (FTS_SL);
if (S_ISREG(sbp->st_mode))
return (FTS_F);
return (FTS_DEFAULT);
}
static FTSENT *
fts_sort(sp, head, nitems)
FTS *sp;
FTSENT *head;
register int nitems;
{
register FTSENT **ap, *p;
/*
* Construct an array of pointers to the structures and call qsort(3).
* Reassemble the array in the order returned by qsort. If unable to
* sort for memory reasons, return the directory entries in their
* current order. Allocate enough space for the current needs plus
* 40 so don't realloc one entry at a time.
*/
if (nitems > sp->fts_nitems) {
sp->fts_nitems = nitems + 40;
if ((sp->fts_array = realloc(sp->fts_array,
(size_t)(sp->fts_nitems * sizeof(FTSENT *)))) == NULL) {
sp->fts_nitems = 0;
return (head);
}
}
for (ap = sp->fts_array, p = head; p; p = p->fts_link)
*ap++ = p;
qsort((void *)sp->fts_array, nitems, sizeof(FTSENT *), sp->fts_compar);
for (head = *(ap = sp->fts_array); --nitems; ++ap)
ap[0]->fts_link = ap[1];
ap[0]->fts_link = NULL;
return (head);
}
static FTSENT *
fts_alloc(sp, name, namelen)
FTS *sp;
char *name;
register int namelen;
{
register FTSENT *p;
size_t len;
/*
* The file name is a variable length array and no stat structure is
* necessary if the user has set the nostat bit. Allocate the FTSENT
* structure, the file name and the stat structure in one chunk, but
* be careful that the stat structure is reasonably aligned. Since the
* fts_name field is declared to be of size 1, the fts_name pointer is
* namelen + 2 before the first possible address of the stat structure.
*/
len = sizeof(FTSENT) + namelen;
if (!ISSET(FTS_NOSTAT))
len += sizeof(struct stat) + ALIGNBYTES;
if ((p = malloc(len)) == NULL)
return (NULL);
/* Copy the name plus the trailing NULL. */
memmove(p->fts_name, name, namelen + 1);
if (!ISSET(FTS_NOSTAT))
p->fts_statp = (struct stat *)ALIGN(p->fts_name + namelen + 2);
p->fts_namelen = namelen;
p->fts_path = sp->fts_path;
p->fts_errno = 0;
p->fts_flags = 0;
p->fts_instr = FTS_NOINSTR;
p->fts_number = 0;
p->fts_pointer = NULL;
return (p);
}
static void
fts_lfree(head)
register FTSENT *head;
{
register FTSENT *p;
/* Free a linked list of structures. */
while (p = head) {
head = head->fts_link;
free(p);
}
}
/*
* Allow essentially unlimited paths; find, rm, ls should all work on any tree.
* Most systems will allow creation of paths much longer than MAXPATHLEN, even
* though the kernel won't resolve them. Add the size (not just what's needed)
* plus 256 bytes so don't realloc the path 2 bytes at a time.
*/
static int
fts_palloc(sp, more)
FTS *sp;
size_t more;
{
sp->fts_pathlen += more + 256;
sp->fts_path = realloc(sp->fts_path, (size_t)sp->fts_pathlen);
return (sp->fts_path == NULL);
}
/*
* When the path is realloc'd, have to fix all of the pointers in structures
* already returned.
*/
static void
fts_padjust(sp, addr)
FTS *sp;
void *addr;
{
FTSENT *p;
#define ADJUST(p) { \
(p)->fts_accpath = \
(char *)addr + ((p)->fts_accpath - (p)->fts_path); \
(p)->fts_path = addr; \
}
/* Adjust the current set of children. */
for (p = sp->fts_child; p; p = p->fts_link)
ADJUST(p);
/* Adjust the rest of the tree. */
for (p = sp->fts_cur; p->fts_level >= FTS_ROOTLEVEL;) {
ADJUST(p);
p = p->fts_link ? p->fts_link : p->fts_parent;
}
}
static size_t
fts_maxarglen(argv)
char * const *argv;
{
size_t len, max;
for (max = 0; *argv; ++argv)
if ((len = strlen(*argv)) > max)
max = len;
return (max);
}

511
lib/libc/gen/getcap.3 Normal file
View file

@ -0,0 +1,511 @@
.\" Copyright (c) 1992, 1993
.\" The Regents of the University of California. All rights reserved.
.\"
.\" This code is derived from software contributed to Berkeley by
.\" Casey Leedom of Lawrence Livermore National Laboratory.
.\"
.\" Redistribution and use in source and binary forms, with or without
.\" modification, are permitted provided that the following conditions
.\" are met:
.\" 1. Redistributions of source code must retain the above copyright
.\" notice, this list of conditions and the following disclaimer.
.\" 2. Redistributions in binary form must reproduce the above copyright
.\" notice, this list of conditions and the following disclaimer in the
.\" documentation and/or other materials provided with the distribution.
.\" 3. All advertising materials mentioning features or use of this software
.\" must display the following acknowledgement:
.\" This product includes software developed by the University of
.\" California, Berkeley and its contributors.
.\" 4. Neither the name of the University nor the names of its contributors
.\" may be used to endorse or promote products derived from this software
.\" without specific prior written permission.
.\"
.\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
.\" ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
.\" SUCH DAMAGE.
.\"
.\" @(#)getcap.3 8.4 (Berkeley) 5/13/94
.\"
.Dd "May 13, 1994"
.Dt GETCAP 3
.Os
.Sh NAME
.Nm cgetent ,
.Nm cgetset ,
.Nm cgetmatch ,
.Nm cgetcap ,
.Nm cgetnum ,
.Nm cgetstr ,
.Nm cgetustr ,
.Nm cgetfirst ,
.Nm cgetnext ,
.Nm cgetclose
.Nd capability database access routines
.Sh SYNOPSIS
.Fd #include <stdlib.h>
.Ft int
.Fn cgetent "char **buf" "char **db_array" "char *name"
.Ft int
.Fn cgetset "char *ent"
.Ft int
.Fn cgetmatch "char *buf" "char *name"
.Ft char *
.Fn cgetcap "char *buf" "char *cap" "char type"
.Ft int
.Fn cgetnum "char *buf" "char *cap" "long *num"
.Ft int
.Fn cgetstr "char *buf" "char *cap" "char **str"
.Ft int
.Fn cgetustr "char *buf" "char *cap" "char **str"
.Ft int
.Fn cgetfirst "char **buf" "char **db_array"
.Ft int
.Fn cgetnext "char **buf" "char **db_array"
.Ft int
.Fn cgetclose "void"
.Sh DESCRIPTION
.Fn Cgetent
extracts the capability
.Fa name
from the database specified by the
.Dv NULL
terminated file array
.Fa db_array
and returns a pointer to a
.Xr malloc Ns \&'d
copy of it in
.Fa buf .
.Nm Cgetent
will first look for files ending in
.Nm .db
(see
.Xr cap_mkdb 1)
before accessing the ASCII file.
.Fa Buf
must be retained through all subsequent calls to
.Fn cgetmatch ,
.Fn cgetcap ,
.Fn cgetnum ,
.Fn cgetstr ,
and
.Fn cgetustr ,
but may then be
.Xr free Ns \&'d.
On success 0 is returned, 1 if the returned
record contains an unresolved
.Nm tc
expansion,
\-1 if the requested record couldn't be found,
\-2 if a system error was encountered (couldn't open/read a file, etc.) also
setting
.Va errno ,
and \-3 if a potential reference loop is detected (see
.Ic tc=
comments below).
.Pp
.Nm Cgetset
enables the addition of a character buffer containing a single capability
record entry
to the capability database.
Conceptually, the entry is added as the first ``file'' in the database, and
is therefore searched first on the call to
.Nm cgetent .
The entry is passed in
.Fa ent .
If
.Fa ent
is
.Dv NULL ,
the current entry is removed from the database.
.Nm Cgetset
must precede the database traversal. It must be called before the
.Nm cgetent
call. If a sequential access is being performed (see below), it must be called
before the first sequential access call (
.Nm cgetfirst
or
.Nm cgetnext
), or be directly preceded by a
.Nm cgetclose
call.
On success 0 is returned and \-1 on failure.
.Pp
.Nm Cgetmatch
will return 0 if
.Fa name
is one of the names of the capability record
.Fa buf ,
\-1 if
not.
.Pp
.Nm Cgetcap
searches the capability record
.Fa buf
for the capability
.Fa cap
with type
.Fa type .
A
.Fa type
is specified using any single character. If a colon (`:') is used, an
untyped capability will be searched for (see below for explanation of
types). A pointer to the value of
.Fa cap
in
.Fa buf
is returned on success,
.Dv NULL
if the requested capability couldn't be
found. The end of the capability value is signaled by a `:' or
.Tn ASCII
.Dv NUL
(see below for capability database syntax).
.Pp
.Nm Cgetnum
retrieves the value of the numeric capability
.Fa cap
from the capability record pointed to by
.Fa buf .
The numeric value is returned in the
.Ft long
pointed to by
.Fa num .
0 is returned on success, \-1 if the requested numeric capability couldn't
be found.
.Pp
.Nm Cgetstr
retrieves the value of the string capability
.Fa cap
from the capability record pointed to by
.Fa buf .
A pointer to a decoded,
.Dv NUL
terminated,
.Xr malloc Ns \&'d
copy of the string is returned in the
.Ft char *
pointed to by
.Fa str .
The number of characters in the decoded string not including the trailing
.Dv NUL
is returned on success, \-1 if the requested string capability couldn't
be found, \-2 if a system error was encountered (storage allocation
failure).
.Pp
.Nm Cgetustr
is identical to
.Nm cgetstr
except that it does not expand special characters, but rather returns each
character of the capability string literally.
.Pp
.Nm Cgetfirst ,
.Nm cgetnext ,
comprise a function group that provides for sequential
access of the
.Dv NULL
pointer terminated array of file names,
.Fa db_array .
.Nm Cgetfirst
returns the first record in the database and resets the access
to the first record.
.Nm Cgetnext
returns the next record in the database with respect to the
record returned by the previous
.Nm cgetfirst
or
.Nm cgetnext
call. If there is no such previous call, the first record in the database is
returned.
Each record is returned in a
.Xr malloc Ns \&'d
copy pointed to by
.Fa buf .
.Ic Tc
expansion is done (see
.Ic tc=
comments below).
Upon completion of the database 0 is returned, 1 is returned upon successful
return of record with possibly more remaining (we haven't reached the end of
the database yet), 2 is returned if the record contains an unresolved
.Nm tc
expansion, \-1 is returned if an system error occurred, and \-2
is returned if a potential reference loop is detected (see
.Ic tc=
comments below).
Upon completion of database (0 return) the database is closed.
.Pp
.Nm Cgetclose
closes the sequential access and frees any memory and file descriptors
being used. Note that it does not erase the buffer pushed by a call to
.Nm cgetset .
.Sh CAPABILITY DATABASE SYNTAX
Capability databases are normally
.Tn ASCII
and may be edited with standard
text editors. Blank lines and lines beginning with a `#' are comments
and are ignored. Lines ending with a `\|\e' indicate that the next line
is a continuation of the current line; the `\|\e' and following newline
are ignored. Long lines are usually continued onto several physical
lines by ending each line except the last with a `\|\e'.
.Pp
Capability databases consist of a series of records, one per logical
line. Each record contains a variable number of `:'-separated fields
(capabilities). Empty fields consisting entirely of white space
characters (spaces and tabs) are ignored.
.Pp
The first capability of each record specifies its names, separated by `|'
characters. These names are used to reference records in the database.
By convention, the last name is usually a comment and is not intended as
a lookup tag. For example, the
.Em vt100
record from the
.Nm termcap
database begins:
.Pp
.Dl "d0\||\|vt100\||\|vt100-am\||\|vt100am\||\|dec vt100:"
.Pp
giving four names that can be used to access the record.
.Pp
The remaining non-empty capabilities describe a set of (name, value)
bindings, consisting of a names optionally followed by a typed values:
.Bl -column "nameTvalue"
.It name Ta "typeless [boolean] capability"
.Em name No "is present [true]"
.It name Ns Em \&T Ns value Ta capability
.Pq Em name , \&T
has value
.Em value
.It name@ Ta "no capability" Em name No exists
.It name Ns Em T Ns \&@ Ta capability
.Pq Em name , T
does not exist
.El
.Pp
Names consist of one or more characters. Names may contain any character
except `:', but it's usually best to restrict them to the printable
characters and avoid use of graphics like `#', `=', `%', `@', etc. Types
are single characters used to separate capability names from their
associated typed values. Types may be any character except a `:'.
Typically, graphics like `#', `=', `%', etc. are used. Values may be any
number of characters and may contain any character except `:'.
.Sh CAPABILITY DATABASE SEMANTICS
Capability records describe a set of (name, value) bindings. Names may
have multiple values bound to them. Different values for a name are
distinguished by their
.Fa types .
.Nm Cgetcap
will return a pointer to a value of a name given the capability name and
the type of the value.
.Pp
The types `#' and `=' are conventionally used to denote numeric and
string typed values, but no restriction on those types is enforced. The
functions
.Nm cgetnum
and
.Nm cgetstr
can be used to implement the traditional syntax and semantics of `#'
and `='.
Typeless capabilities are typically used to denote boolean objects with
presence or absence indicating truth and false values respectively.
This interpretation is conveniently represented by:
.Pp
.Dl "(getcap(buf, name, ':') != NULL)"
.Pp
A special capability,
.Ic tc= name ,
is used to indicate that the record specified by
.Fa name
should be substituted for the
.Ic tc
capability.
.Ic Tc
capabilities may interpolate records which also contain
.Ic tc
capabilities and more than one
.Ic tc
capability may be used in a record. A
.Ic tc
expansion scope (i.e., where the argument is searched for) contains the
file in which the
.Ic tc
is declared and all subsequent files in the file array.
.Pp
When a database is searched for a capability record, the first matching
record in the search is returned. When a record is scanned for a
capability, the first matching capability is returned; the capability
.Ic :nameT@:
will hide any following definition of a value of type
.Em T
for
.Fa name ;
and the capability
.Ic :name@:
will prevent any following values of
.Fa name
from being seen.
.Pp
These features combined with
.Ic tc
capabilities can be used to generate variations of other databases and
records by either adding new capabilities, overriding definitions with new
definitions, or hiding following definitions via `@' capabilities.
.Sh EXAMPLES
.Bd -unfilled -offset indent
example\||\|an example of binding multiple values to names:\e
:foo%bar:foo^blah:foo@:\e
:abc%xyz:abc^frap:abc$@:\e
:tc=more:
.Ed
.Pp
The capability foo has two values bound to it (bar of type `%' and blah of
type `^') and any other value bindings are hidden. The capability abc
also has two values bound but only a value of type `$' is prevented from
being defined in the capability record more.
.Pp
.Bd -unfilled -offset indent
file1:
new\||\|new_record\||\|a modification of "old":\e
:fript=bar:who-cares@:tc=old:blah:tc=extensions:
file2:
old\||\|old_record\||\|an old database record:\e
:fript=foo:who-cares:glork#200:
.Ed
.Pp
The records are extracted by calling
.Nm cgetent
with file1 preceding file2.
In the capability record new in file1, fript=bar overrides the definition
of fript=foo interpolated from the capability record old in file2,
who-cares@ prevents the definition of any who-cares definitions in old
from being seen, glork#200 is inherited from old, and blah and anything
defined by the record extensions is added to those definitions in old.
Note that the position of the fript=bar and who-cares@ definitions before
tc=old is important here. If they were after, the definitions in old
would take precedence.
.Sh CGETNUM AND CGETSTR SYNTAX AND SEMANTICS
Two types are predefined by
.Nm cgetnum
and
.Nm cgetstr :
.Bl -column "nameXnumber"
.Sm off
.It Em name No \&# Em number Ta numeric
capability
.Em name
has value
.Em number
.It Em name No = Em string Ta "string capability"
.Em name
has value
.Em string
.It Em name No \&#@ Ta "the numeric capability"
.Em name
does not exist
.It Em name No \&=@ Ta "the string capability"
.Em name
does not exist
.El
.Pp
Numeric capability values may be given in one of three numeric bases.
If the number starts with either
.Ql 0x
or
.Ql 0X
it is interpreted as a hexadecimal number (both upper and lower case a-f
may be used to denote the extended hexadecimal digits).
Otherwise, if the number starts with a
.Ql 0
it is interpreted as an octal number.
Otherwise the number is interpreted as a decimal number.
.Pp
String capability values may contain any character. Non-printable
.Dv ASCII
codes, new lines, and colons may be conveniently represented by the use
of escape sequences:
.Bl -column "\e\|X,X\e\|X" "(ASCII octal nnn)"
^X ('\fIX\fP' & 037) control-\fIX\fP
\e\|b, \e\|B (ASCII 010) backspace
\e\|t, \e\|T (ASCII 011) tab
\e\|n, \e\|N (ASCII 012) line feed (newline)
\e\|f, \e\|F (ASCII 014) form feed
\e\|r, \e\|R (ASCII 015) carriage return
\e\|e, \e\|E (ASCII 027) escape
\e\|c, \e\|C (:) colon
\e\|\e (\e\|) back slash
\e\|^ (^) caret
\e\|\fInnn\fP (ASCII octal \fInnn\fP)
.El
.Pp
A `\|\e' may be followed by up to three octal digits directly specifies
the numeric code for a character. The use of
.Tn ASCII
.Dv NUL Ns s ,
while easily
encoded, causes all sorts of problems and must be used with care since
.Dv NUL Ns s
are typically used to denote the end of strings; many applications
use `\e\|200' to represent a
.Dv NUL .
.Sh DIAGNOSTICS
.Nm Cgetent ,
.Nm cgetset ,
.Nm cgetmatch ,
.Nm cgetnum ,
.Nm cgetstr ,
.Nm cgetustr ,
.Nm cgetfirst ,
and
.Nm cgetnext
return a value greater than or equal to 0 on success and a value less
than 0 on failure.
.Nm Cgetcap
returns a character pointer on success and a
.Dv NULL
on failure.
.Pp
.Nm Cgetent ,
and
.Nm cgetseq
may fail and set
.Va errno
for any of the errors specified for the library functions:
.Xr fopen 2 ,
.Xr fclose 2 ,
.Xr open 2 ,
and
.Xr close 2 .
.Pp
.Nm Cgetent ,
.Nm cgetset ,
.Nm cgetstr ,
and
.Nm cgetustr
may fail and set
.Va errno
as follows:
.Bl -tag -width Er
.It Bq Er ENOMEM
No memory to allocate.
.El
.Sh SEE ALSO
.Xr cap_mkdb 1 ,
.Xr malloc 3
.Sh BUGS
Colons (`:') can't be used in names, types, or values.
.Pp
There are no checks for
.Ic tc= name
loops in
.Nm cgetent .
.Pp
The buffer added to the database by a call to
.Nm cgetset
is not unique to the database but is rather prepended to any database used.

384
lib/libc/gen/getcwd.c Normal file
View file

@ -0,0 +1,384 @@
/*
* Copyright (c) 1989, 1991, 1993, 1995
* The Regents of the University of California. All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* Jan-Simon Pendry.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#if defined(LIBC_SCCS) && !defined(lint)
static char sccsid[] = "@(#)getcwd.c 8.5 (Berkeley) 2/7/95";
#endif /* LIBC_SCCS and not lint */
#include <sys/param.h>
#include <sys/stat.h>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
static char *getcwd_physical __P((char *, size_t));
#define ISDOT(dp) \
(dp->d_name[0] == '.' && (dp->d_name[1] == '\0' || \
dp->d_name[1] == '.' && dp->d_name[2] == '\0'))
char *
getcwd(pt, size)
char *pt;
size_t size;
{
char *pwd;
size_t pwdlen;
dev_t dev;
ino_t ino;
struct stat s;
/* Check $PWD -- if it's right, it's fast. */
if ((pwd = getenv("PWD")) != NULL && pwd[0] == '/' && !stat(pwd, &s)) {
dev = s.st_dev;
ino = s.st_ino;
if (!stat(".", &s) && dev == s.st_dev && ino == s.st_ino) {
pwdlen = strlen(pwd);
if (size != 0) {
if (pwdlen + 1 > size) {
errno = ERANGE;
return (NULL);
}
} else if ((pt = malloc(pwdlen + 1)) == NULL)
return (NULL);
memmove(pt, pwd, pwdlen);
pt[pwdlen] = '\0';
return (pt);
}
}
return (getcwd_physical(pt, size));
}
/*
* char *realpath(const char *path, char resolved_path[MAXPATHLEN]);
*
* Find the real name of path, by removing all ".", ".." and symlink
* components. Returns (resolved) on success, or (NULL) on failure,
* in which case the path which caused trouble is left in (resolved).
*/
char *
realpath(path, resolved)
const char *path;
char *resolved;
{
struct stat sb;
int fd, n, rootd, serrno;
char *p, *q, wbuf[MAXPATHLEN];
/* Save the starting point. */
if ((fd = open(".", O_RDONLY)) < 0) {
(void)strcpy(resolved, ".");
return (NULL);
}
/*
* Find the dirname and basename from the path to be resolved.
* Change directory to the dirname component.
* lstat the basename part.
* if it is a symlink, read in the value and loop.
* if it is a directory, then change to that directory.
* get the current directory name and append the basename.
*/
(void)strncpy(resolved, path, MAXPATHLEN - 1);
resolved[MAXPATHLEN - 1] = '\0';
loop:
q = strrchr(resolved, '/');
if (q != NULL) {
p = q + 1;
if (q == resolved)
q = "/";
else {
do {
--q;
} while (q > resolved && *q == '/');
q[1] = '\0';
q = resolved;
}
if (chdir(q) < 0)
goto err1;
} else
p = resolved;
/* Deal with the last component. */
if (lstat(p, &sb) == 0) {
if (S_ISLNK(sb.st_mode)) {
n = readlink(p, resolved, MAXPATHLEN);
if (n < 0)
goto err1;
resolved[n] = '\0';
goto loop;
}
if (S_ISDIR(sb.st_mode)) {
if (chdir(p) < 0)
goto err1;
p = "";
}
}
/*
* Save the last component name and get the full pathname of
* the current directory.
*/
(void)strcpy(wbuf, p);
/*
* Call the inernal internal version of getcwd which
* does a physical search rather than using the $PWD short-cut
*/
if (getcwd_physical(resolved, MAXPATHLEN) == 0)
goto err1;
/*
* Join the two strings together, ensuring that the right thing
* happens if the last component is empty, or the dirname is root.
*/
if (resolved[0] == '/' && resolved[1] == '\0')
rootd = 1;
else
rootd = 0;
if (*wbuf) {
if (strlen(resolved) + strlen(wbuf) + rootd + 1 > MAXPATHLEN) {
errno = ENAMETOOLONG;
goto err1;
}
if (rootd == 0)
(void)strcat(resolved, "/");
(void)strcat(resolved, wbuf);
}
/* Go back to where we came from. */
if (fchdir(fd) < 0) {
serrno = errno;
goto err2;
}
/* It's okay if the close fails, what's an fd more or less? */
(void)close(fd);
return (resolved);
err1: serrno = errno;
(void)fchdir(fd);
err2: (void)close(fd);
errno = serrno;
return (NULL);
}
static char *
getcwd_physical(pt, size)
char *pt;
size_t size;
{
register struct dirent *dp;
register DIR *dir;
register dev_t dev;
register ino_t ino;
register int first;
register char *bpt, *bup;
struct stat s;
dev_t root_dev;
ino_t root_ino;
size_t ptsize, upsize;
int save_errno;
char *ept, *eup, *up;
/*
* If no buffer specified by the user, allocate one as necessary.
* If a buffer is specified, the size has to be non-zero. The path
* is built from the end of the buffer backwards.
*/
if (pt) {
ptsize = 0;
if (!size) {
errno = EINVAL;
return (NULL);
}
ept = pt + size;
} else {
if ((pt = malloc(ptsize = 1024 - 4)) == NULL)
return (NULL);
ept = pt + ptsize;
}
bpt = ept - 1;
*bpt = '\0';
/*
* Allocate bytes (1024 - malloc space) for the string of "../"'s.
* Should always be enough (it's 340 levels). If it's not, allocate
* as necessary. Special case the first stat, it's ".", not "..".
*/
if ((up = malloc(upsize = 1024 - 4)) == NULL)
goto err;
eup = up + MAXPATHLEN;
bup = up;
up[0] = '.';
up[1] = '\0';
/* Save root values, so know when to stop. */
if (stat("/", &s))
goto err;
root_dev = s.st_dev;
root_ino = s.st_ino;
errno = 0; /* XXX readdir has no error return. */
for (first = 1;; first = 0) {
/* Stat the current level. */
if (lstat(up, &s))
goto err;
/* Save current node values. */
ino = s.st_ino;
dev = s.st_dev;
/* Check for reaching root. */
if (root_dev == dev && root_ino == ino) {
*--bpt = '/';
/*
* It's unclear that it's a requirement to copy the
* path to the beginning of the buffer, but it's always
* been that way and stuff would probably break.
*/
(void)bcopy(bpt, pt, ept - bpt);
free(up);
return (pt);
}
/*
* Build pointer to the parent directory, allocating memory
* as necessary. Max length is 3 for "../", the largest
* possible component name, plus a trailing NULL.
*/
if (bup + 3 + MAXNAMLEN + 1 >= eup) {
if ((up = realloc(up, upsize *= 2)) == NULL)
goto err;
bup = up;
eup = up + upsize;
}
*bup++ = '.';
*bup++ = '.';
*bup = '\0';
/* Open and stat parent directory. */
if (!(dir = opendir(up)) || fstat(dirfd(dir), &s))
goto err;
/* Add trailing slash for next directory. */
*bup++ = '/';
/*
* If it's a mount point, have to stat each element because
* the inode number in the directory is for the entry in the
* parent directory, not the inode number of the mounted file.
*/
save_errno = 0;
if (s.st_dev == dev) {
for (;;) {
if (!(dp = readdir(dir)))
goto notfound;
if (dp->d_fileno == ino)
break;
}
} else
for (;;) {
if (!(dp = readdir(dir)))
goto notfound;
if (ISDOT(dp))
continue;
bcopy(dp->d_name, bup, dp->d_namlen + 1);
/* Save the first error for later. */
if (lstat(up, &s)) {
if (!save_errno)
save_errno = errno;
errno = 0;
continue;
}
if (s.st_dev == dev && s.st_ino == ino)
break;
}
/*
* Check for length of the current name, preceding slash,
* leading slash.
*/
if (bpt - pt <= dp->d_namlen + (first ? 1 : 2)) {
size_t len, off;
if (!ptsize) {
errno = ERANGE;
goto err;
}
off = bpt - pt;
len = ept - bpt;
if ((pt = realloc(pt, ptsize *= 2)) == NULL)
goto err;
bpt = pt + off;
ept = pt + ptsize;
(void)bcopy(bpt, ept - len, len);
bpt = ept - len;
}
if (!first)
*--bpt = '/';
bpt -= dp->d_namlen;
bcopy(dp->d_name, bpt, dp->d_namlen);
(void)closedir(dir);
/* Truncate any file name. */
*bup = '\0';
}
notfound:
/*
* If readdir set errno, use it, not any saved error; otherwise,
* didn't find the current directory in its parent directory, set
* errno to ENOENT.
*/
if (!errno)
errno = save_errno ? save_errno : ENOENT;
/* FALLTHROUGH */
err:
if (ptsize)
free(pt);
free(up);
return (NULL);
}

View file

@ -0,0 +1,89 @@
/*
* Copyright (c) 1991, 1993
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#if defined(LIBC_SCCS) && !defined(lint)
static char sccsid[] = "@(#)getgrouplist.c 8.2 (Berkeley) 12/8/94";
#endif /* LIBC_SCCS and not lint */
/*
* get credential
*/
#include <sys/types.h>
#include <string.h>
#include <grp.h>
int
getgrouplist(uname, agroup, groups, grpcnt)
const char *uname;
int agroup;
register int *groups;
int *grpcnt;
{
register struct group *grp;
register struct passwd *pw;
register int i, ngroups;
int ret, maxgroups;
ret = 0;
ngroups = 0;
maxgroups = *grpcnt;
/*
* When installing primary group, duplicate it;
* the first element of groups is the effective gid
* and will be overwritten when a setgid file is executed.
*/
groups[ngroups++] = agroup;
if (maxgroups > 1)
groups[ngroups++] = agroup;
/*
* Scan the group file to find additional groups.
*/
setgrent();
while (grp = getgrent()) {
if (grp->gr_gid == agroup)
continue;
for (i = 0; grp->gr_mem[i]; i++) {
if (!strcmp(grp->gr_mem[i], uname)) {
if (ngroups >= maxgroups) {
ret = -1;
break;
}
groups[ngroups++] = grp->gr_gid;
break;
}
}
}
endgrent();
*grpcnt = ngroups;
return (ret);
}

341
lib/libc/gen/getnetgrent.c Normal file
View file

@ -0,0 +1,341 @@
/*
* Copyright (c) 1992, 1993
* The Regents of the University of California. All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* Rick Macklem at The University of Guelph.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#if defined(LIBC_SCCS) && !defined(lint)
static char sccsid[] = "@(#)getnetgrent.c 8.2 (Berkeley) 4/27/95";
#endif /* LIBC_SCCS and not lint */
#include <stdio.h>
#include <strings.h>
#define _PATH_NETGROUP "/etc/netgroup"
/*
* Static Variables and functions used by setnetgrent(), getnetgrent() and
* endnetgrent().
* There are two linked lists:
* - linelist is just used by setnetgrent() to parse the net group file via.
* parse_netgrp()
* - netgrp is the list of entries for the current netgroup
*/
struct linelist {
struct linelist *l_next; /* Chain ptr. */
int l_parsed; /* Flag for cycles */
char *l_groupname; /* Name of netgroup */
char *l_line; /* Netgroup entrie(s) to be parsed */
};
struct netgrp {
struct netgrp *ng_next; /* Chain ptr */
char *ng_str[3]; /* Field pointers, see below */
};
#define NG_HOST 0 /* Host name */
#define NG_USER 1 /* User name */
#define NG_DOM 2 /* and Domain name */
static struct linelist *linehead = (struct linelist *)0;
static struct netgrp *nextgrp = (struct netgrp *)0;
static struct {
struct netgrp *gr;
char *grname;
} grouphead = {
(struct netgrp *)0,
(char *)0,
};
static FILE *netf = (FILE *)0;
static int parse_netgrp();
static struct linelist *read_for_group();
void setnetgrent(), endnetgrent();
int getnetgrent(), innetgr();
#define LINSIZ 1024 /* Length of netgroup file line */
/*
* setnetgrent()
* Parse the netgroup file looking for the netgroup and build the list
* of netgrp structures. Let parse_netgrp() and read_for_group() do
* most of the work.
*/
void
setnetgrent(group)
char *group;
{
if (grouphead.gr == (struct netgrp *)0 ||
strcmp(group, grouphead.grname)) {
endnetgrent();
if (netf = fopen(_PATH_NETGROUP, "r")) {
if (parse_netgrp(group))
endnetgrent();
else {
grouphead.grname = (char *)
malloc(strlen(group) + 1);
strcpy(grouphead.grname, group);
}
fclose(netf);
}
}
nextgrp = grouphead.gr;
}
/*
* Get the next netgroup off the list.
*/
int
getnetgrent(hostp, userp, domp)
char **hostp, **userp, **domp;
{
if (nextgrp) {
*hostp = nextgrp->ng_str[NG_HOST];
*userp = nextgrp->ng_str[NG_USER];
*domp = nextgrp->ng_str[NG_DOM];
nextgrp = nextgrp->ng_next;
return (1);
}
return (0);
}
/*
* endnetgrent() - cleanup
*/
void
endnetgrent()
{
register struct linelist *lp, *olp;
register struct netgrp *gp, *ogp;
lp = linehead;
while (lp) {
olp = lp;
lp = lp->l_next;
free(olp->l_groupname);
free(olp->l_line);
free((char *)olp);
}
linehead = (struct linelist *)0;
if (grouphead.grname) {
free(grouphead.grname);
grouphead.grname = (char *)0;
}
gp = grouphead.gr;
while (gp) {
ogp = gp;
gp = gp->ng_next;
if (ogp->ng_str[NG_HOST])
free(ogp->ng_str[NG_HOST]);
if (ogp->ng_str[NG_USER])
free(ogp->ng_str[NG_USER]);
if (ogp->ng_str[NG_DOM])
free(ogp->ng_str[NG_DOM]);
free((char *)ogp);
}
grouphead.gr = (struct netgrp *)0;
}
/*
* Search for a match in a netgroup.
*/
int
innetgr(group, host, user, dom)
char *group, *host, *user, *dom;
{
char *hst, *usr, *dm;
setnetgrent(group);
while (getnetgrent(&hst, &usr, &dm))
if ((host == (char *)0 || !strcmp(host, hst)) &&
(user == (char *)0 || !strcmp(user, usr)) &&
(dom == (char *)0 || !strcmp(dom, dm))) {
endnetgrent();
return (1);
}
endnetgrent();
return (0);
}
/*
* Parse the netgroup file setting up the linked lists.
*/
static int
parse_netgrp(group)
char *group;
{
register char *spos, *epos;
register int len, strpos;
char *pos, *gpos;
struct netgrp *grp;
struct linelist *lp = linehead;
/*
* First, see if the line has already been read in.
*/
while (lp) {
if (!strcmp(group, lp->l_groupname))
break;
lp = lp->l_next;
}
if (lp == (struct linelist *)0 &&
(lp = read_for_group(group)) == (struct linelist *)0)
return (1);
if (lp->l_parsed) {
fprintf(stderr, "Cycle in netgroup %s\n", lp->l_groupname);
return (1);
} else
lp->l_parsed = 1;
pos = lp->l_line;
while (*pos != '\0') {
if (*pos == '(') {
grp = (struct netgrp *)malloc(sizeof (struct netgrp));
bzero((char *)grp, sizeof (struct netgrp));
grp->ng_next = grouphead.gr;
grouphead.gr = grp;
pos++;
gpos = strsep(&pos, ")");
for (strpos = 0; strpos < 3; strpos++) {
if (spos = strsep(&gpos, ",")) {
while (*spos == ' ' || *spos == '\t')
spos++;
if (epos = strpbrk(spos, " \t")) {
*epos = '\0';
len = epos - spos;
} else
len = strlen(spos);
if (len > 0) {
grp->ng_str[strpos] = (char *)
malloc(len + 1);
bcopy(spos, grp->ng_str[strpos],
len + 1);
}
} else
goto errout;
}
} else {
spos = strsep(&pos, ", \t");
if (parse_netgrp(spos))
return (1);
}
if (pos == NULL)
break;
while (*pos == ' ' || *pos == ',' || *pos == '\t')
pos++;
}
return (0);
errout:
fprintf(stderr, "Bad netgroup %s at ..%s\n", lp->l_groupname,
spos);
return (1);
}
/*
* Read the netgroup file and save lines until the line for the netgroup
* is found. Return 1 if eof is encountered.
*/
static struct linelist *
read_for_group(group)
char *group;
{
register char *pos, *spos, *linep, *olinep;
register int len, olen;
int cont;
struct linelist *lp;
char line[LINSIZ + 1];
while (fgets(line, LINSIZ, netf) != NULL) {
pos = line;
if (*pos == '#')
continue;
while (*pos == ' ' || *pos == '\t')
pos++;
spos = pos;
while (*pos != ' ' && *pos != '\t' && *pos != '\n' &&
*pos != '\0')
pos++;
len = pos - spos;
while (*pos == ' ' || *pos == '\t')
pos++;
if (*pos != '\n' && *pos != '\0') {
lp = (struct linelist *)malloc(sizeof (*lp));
lp->l_parsed = 0;
lp->l_groupname = (char *)malloc(len + 1);
bcopy(spos, lp->l_groupname, len);
*(lp->l_groupname + len) = '\0';
len = strlen(pos);
olen = 0;
/*
* Loop around handling line continuations.
*/
do {
if (*(pos + len - 1) == '\n')
len--;
if (*(pos + len - 1) == '\\') {
len--;
cont = 1;
} else
cont = 0;
if (len > 0) {
linep = (char *)malloc(olen + len + 1);
if (olen > 0) {
bcopy(olinep, linep, olen);
free(olinep);
}
bcopy(pos, linep + olen, len);
olen += len;
*(linep + olen) = '\0';
olinep = linep;
}
if (cont) {
if (fgets(line, LINSIZ, netf)) {
pos = line;
len = strlen(pos);
} else
cont = 0;
}
} while (cont);
lp->l_line = linep;
lp->l_next = linehead;
linehead = lp;
/*
* If this is the one we wanted, we are done.
*/
if (!strcmp(lp->l_groupname, group))
return (lp);
}
}
return ((struct linelist *)0);
}

200
lib/libc/gen/getpwent.c Normal file
View file

@ -0,0 +1,200 @@
/*
* Copyright (c) 1988, 1993
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#if defined(LIBC_SCCS) && !defined(lint)
static char sccsid[] = "@(#)getpwent.c 8.2 (Berkeley) 4/27/95";
#endif /* LIBC_SCCS and not lint */
#include <sys/param.h>
#include <fcntl.h>
#include <db.h>
#include <syslog.h>
#include <pwd.h>
#include <utmp.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
/*
* The lookup techniques and data extraction code here must be kept
* in sync with that in `pwd_mkdb'.
*/
static struct passwd _pw_passwd; /* password structure */
static DB *_pw_db; /* password database */
static int _pw_keynum; /* key counter */
static int _pw_stayopen; /* keep fd's open */
static int __hashpw(), __initdb();
struct passwd *
getpwent()
{
DBT key;
char bf[sizeof(_pw_keynum) + 1];
if (!_pw_db && !__initdb())
return((struct passwd *)NULL);
++_pw_keynum;
bf[0] = _PW_KEYBYNUM;
bcopy((char *)&_pw_keynum, bf + 1, sizeof(_pw_keynum));
key.data = (u_char *)bf;
key.size = sizeof(_pw_keynum) + 1;
return(__hashpw(&key) ? &_pw_passwd : (struct passwd *)NULL);
}
struct passwd *
getpwnam(name)
const char *name;
{
DBT key;
int len, rval;
char bf[UT_NAMESIZE + 1];
if (!_pw_db && !__initdb())
return((struct passwd *)NULL);
bf[0] = _PW_KEYBYNAME;
len = strlen(name);
bcopy(name, bf + 1, MIN(len, UT_NAMESIZE));
key.data = (u_char *)bf;
key.size = len + 1;
rval = __hashpw(&key);
if (!_pw_stayopen) {
(void)(_pw_db->close)(_pw_db);
_pw_db = (DB *)NULL;
}
return(rval ? &_pw_passwd : (struct passwd *)NULL);
}
struct passwd *
getpwuid(uid)
uid_t uid;
{
DBT key;
int keyuid, rval;
char bf[sizeof(keyuid) + 1];
if (!_pw_db && !__initdb())
return((struct passwd *)NULL);
bf[0] = _PW_KEYBYUID;
keyuid = uid;
bcopy(&keyuid, bf + 1, sizeof(keyuid));
key.data = (u_char *)bf;
key.size = sizeof(keyuid) + 1;
rval = __hashpw(&key);
if (!_pw_stayopen) {
(void)(_pw_db->close)(_pw_db);
_pw_db = (DB *)NULL;
}
return(rval ? &_pw_passwd : (struct passwd *)NULL);
}
int
setpassent(stayopen)
int stayopen;
{
_pw_keynum = 0;
_pw_stayopen = stayopen;
return(1);
}
int
setpwent()
{
_pw_keynum = 0;
_pw_stayopen = 0;
return(1);
}
void
endpwent()
{
_pw_keynum = 0;
if (_pw_db) {
(void)(_pw_db->close)(_pw_db);
_pw_db = (DB *)NULL;
}
}
static
__initdb()
{
static int warned;
char *p;
p = (geteuid()) ? _PATH_MP_DB : _PATH_SMP_DB;
_pw_db = dbopen(p, O_RDONLY, 0, DB_HASH, NULL);
if (_pw_db)
return(1);
if (!warned)
syslog(LOG_ERR, "%s: %m", p);
return(0);
}
static
__hashpw(key)
DBT *key;
{
register char *p, *t;
static u_int max;
static char *line;
DBT data;
if ((_pw_db->get)(_pw_db, key, &data, 0))
return(0);
p = (char *)data.data;
if (data.size > max && !(line = realloc(line, max += 1024)))
return(0);
/* THIS CODE MUST MATCH THAT IN pwd_mkdb. */
t = line;
#define EXPAND(e) e = t; while (*t++ = *p++);
#define SCALAR(v) memmove(&(v), p, sizeof v); p += sizeof v
EXPAND(_pw_passwd.pw_name);
EXPAND(_pw_passwd.pw_passwd);
SCALAR(_pw_passwd.pw_uid);
SCALAR(_pw_passwd.pw_gid);
SCALAR(_pw_passwd.pw_change);
EXPAND(_pw_passwd.pw_class);
EXPAND(_pw_passwd.pw_gecos);
EXPAND(_pw_passwd.pw_dir);
EXPAND(_pw_passwd.pw_shell);
SCALAR(_pw_passwd.pw_expire);
return(1);
}

View file

@ -0,0 +1,98 @@
.\" Copyright (c) 1995
.\" The Regents of the University of California. All rights reserved.
.\"
.\" Redistribution and use in source and binary forms, with or without
.\" modification, are permitted provided that the following conditions
.\" are met:
.\" 1. Redistributions of source code must retain the above copyright
.\" notice, this list of conditions and the following disclaimer.
.\" 2. Redistributions in binary form must reproduce the above copyright
.\" notice, this list of conditions and the following disclaimer in the
.\" documentation and/or other materials provided with the distribution.
.\" 3. All advertising materials mentioning features or use of this software
.\" must display the following acknowledgement:
.\" This product includes software developed by the University of
.\" California, Berkeley and its contributors.
.\" 4. Neither the name of the University nor the names of its contributors
.\" may be used to endorse or promote products derived from this software
.\" without specific prior written permission.
.\"
.\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
.\" ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
.\" SUCH DAMAGE.
.\"
.\" @(#)kvm_getvfsbyname.3 8.3 (Berkeley) 5/4/95
.\"
.Dd May 4, 1995
.Dt GETVFSBYNAME 3
.Os
.Sh NAME
.Nm getvfsbyname
.Nd get information about a filesystem
.Sh SYNOPSIS
.Fd #include <sys/types.h>
.Fd #include <sys/mount.h>
.Fd #include <kvm.h>
.br
.Ft int
.Fn getvfsbyname "const char *name" "struct vfsconf *vfc"
.Sh DESCRIPTION
The
.Fn getvfsbyname
function provides access to information about a
filesystem module that is configured in the kernel.
If successful,
the requested filesystem
.Fa vfsconf
is returned in the location pointed to by
.Nm vfc .
The fields in a
.Dq Li struct vfsconf
are defined as follows:
.Pp
.Bl -tag -compact -width vfc_refcount
.It vfc_name
the name of the filesystem
.It vfc_typenum
the filesystem type number assigned by the kernel
.It vfc_refcount
the number of active mount points using the filesystem
.It vfc_flags
flag bits that are used to initialize a new mount point
using the filesystem
.El
.Sh RETURN VALUES
If the call to
.Nm getvfsbyname
is successful, 0 is returned.
Otherwise \-1 is returned and
.Va errno
is set appropriately.
.Sh ERRORS
The following errors may be reported:
.Bl -tag -width Er
.It Bq Er EFAULT
The
.Fa vfc
pointer contains an invalid address.
.It Bq Er ENOENT
The
.Fa name
specifies a filesystem that is unknown or not configured in the kernel.
.Sh SEE ALSO
.Xr sysctl 1 ,
.Xr mount 2 ,
.Xr sysctl 3 ,
.Xr mount 8
.Sh HISTORY
A variant of the
.Fn getvfsbyname
function first appeared in FreeBSD 2.0.

265
lib/libc/gen/opendir.c Normal file
View file

@ -0,0 +1,265 @@
/*
* Copyright (c) 1983, 1993
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#if defined(LIBC_SCCS) && !defined(lint)
static char sccsid[] = "@(#)opendir.c 8.8 (Berkeley) 5/1/95";
#endif /* LIBC_SCCS and not lint */
#include <sys/param.h>
#include <sys/mount.h>
#include <sys/stat.h>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
/*
* Open a directory.
*/
DIR *
opendir(name)
const char *name;
{
return (__opendir2(name, DTF_HIDEW|DTF_NODUP));
}
DIR *
__opendir2(name, flags)
const char *name;
int flags;
{
DIR *dirp;
int fd;
int incr;
int unionstack;
struct stat statb;
if ((fd = open(name, O_RDONLY)) == -1)
return (NULL);
if (fstat(fd, &statb) || !S_ISDIR(statb.st_mode)) {
errno = ENOTDIR;
close(fd);
return (NULL);
}
if (fcntl(fd, F_SETFD, FD_CLOEXEC) == -1 ||
(dirp = (DIR *)malloc(sizeof(DIR))) == NULL) {
close(fd);
return (NULL);
}
/*
* If CLBYTES is an exact multiple of DIRBLKSIZ, use a CLBYTES
* buffer that it cluster boundary aligned.
* Hopefully this can be a big win someday by allowing page
* trades to user space to be done by getdirentries()
*/
if ((CLBYTES % DIRBLKSIZ) == 0)
incr = CLBYTES;
else
incr = DIRBLKSIZ;
/*
* Determine whether this directory is the top of a union stack.
*/
if (flags & DTF_NODUP) {
struct statfs sfb;
if (fstatfs(fd, &sfb) < 0) {
free(dirp);
close(fd);
return (NULL);
}
unionstack = !strcmp(sfb.f_fstypename, "union");
} else {
unionstack = 0;
}
if (unionstack) {
int len = 0;
int space = 0;
char *buf = 0;
char *ddptr = 0;
char *ddeptr;
int n;
struct dirent **dpv;
/*
* The strategy here is to read all the directory
* entries into a buffer, sort the buffer, and
* remove duplicate entries by setting the inode
* number to zero.
*/
do {
/*
* Always make at least DIRBLKSIZ bytes
* available to getdirentries
*/
if (space < DIRBLKSIZ) {
space += incr;
len += incr;
buf = realloc(buf, len);
if (buf == NULL) {
free(dirp);
close(fd);
return (NULL);
}
ddptr = buf + (len - space);
}
n = getdirentries(fd, ddptr, space, &dirp->dd_seek);
if (n > 0) {
ddptr += n;
space -= n;
}
} while (n > 0);
ddeptr = ddptr;
flags |= __DTF_READALL;
/*
* Re-open the directory.
* This has the effect of rewinding back to the
* top of the union stack and is needed by
* programs which plan to fchdir to a descriptor
* which has also been read -- see fts.c.
*/
if (flags & DTF_REWIND) {
(void) close(fd);
if ((fd = open(name, O_RDONLY)) == -1) {
free(buf);
free(dirp);
return (NULL);
}
}
/*
* There is now a buffer full of (possibly) duplicate
* names.
*/
dirp->dd_buf = buf;
/*
* Go round this loop twice...
*
* Scan through the buffer, counting entries.
* On the second pass, save pointers to each one.
* Then sort the pointers and remove duplicate names.
*/
for (dpv = 0;;) {
n = 0;
ddptr = buf;
while (ddptr < ddeptr) {
struct dirent *dp;
dp = (struct dirent *) ddptr;
if ((int)dp & 03)
break;
if ((dp->d_reclen <= 0) ||
(dp->d_reclen > (ddeptr + 1 - ddptr)))
break;
ddptr += dp->d_reclen;
if (dp->d_fileno) {
if (dpv)
dpv[n] = dp;
n++;
}
}
if (dpv) {
struct dirent *xp;
/*
* This sort must be stable.
*/
mergesort(dpv, n, sizeof(*dpv), alphasort);
dpv[n] = NULL;
xp = NULL;
/*
* Scan through the buffer in sort order,
* zapping the inode number of any
* duplicate names.
*/
for (n = 0; dpv[n]; n++) {
struct dirent *dp = dpv[n];
if ((xp == NULL) ||
strcmp(dp->d_name, xp->d_name)) {
xp = dp;
} else {
dp->d_fileno = 0;
}
if (dp->d_type == DT_WHT &&
(flags & DTF_HIDEW))
dp->d_fileno = 0;
}
free(dpv);
break;
} else {
dpv = malloc((n+1) * sizeof(struct dirent *));
if (dpv == NULL)
break;
}
}
dirp->dd_len = len;
dirp->dd_size = ddptr - dirp->dd_buf;
} else {
dirp->dd_len = incr;
dirp->dd_buf = malloc(dirp->dd_len);
if (dirp->dd_buf == NULL) {
free(dirp);
close (fd);
return (NULL);
}
dirp->dd_seek = 0;
flags &= ~DTF_REWIND;
}
dirp->dd_loc = 0;
dirp->dd_fd = fd;
dirp->dd_flags = flags;
/*
* Set up seek point for rewinddir.
*/
dirp->dd_rewind = telldir(dirp);
return (dirp);
}

194
lib/libc/gen/popen.3 Normal file
View file

@ -0,0 +1,194 @@
.\" Copyright (c) 1991, 1993
.\" The Regents of the University of California. All rights reserved.
.\"
.\" Redistribution and use in source and binary forms, with or without
.\" modification, are permitted provided that the following conditions
.\" are met:
.\" 1. Redistributions of source code must retain the above copyright
.\" notice, this list of conditions and the following disclaimer.
.\" 2. Redistributions in binary form must reproduce the above copyright
.\" notice, this list of conditions and the following disclaimer in the
.\" documentation and/or other materials provided with the distribution.
.\" 3. All advertising materials mentioning features or use of this software
.\" must display the following acknowledgement:
.\" This product includes software developed by the University of
.\" California, Berkeley and its contributors.
.\" 4. Neither the name of the University nor the names of its contributors
.\" may be used to endorse or promote products derived from this software
.\" without specific prior written permission.
.\"
.\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
.\" ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
.\" SUCH DAMAGE.
.\"
.\" @(#)popen.3 8.2 (Berkeley) 5/3/95
.\"
.Dd May 3, 1995
.Dt POPEN 3
.Os
.Sh NAME
.Nm popen ,
.Nm pclose
.Nd process
.Tn I/O
.Sh SYNOPSIS
.Fd #include <stdio.h>
.Ft FILE *
.Fn popen "const char *command" "const char *type"
.Ft int
.Fn pclose "FILE *stream"
.Sh DESCRIPTION
The
.Fn popen
function
.Dq opens
a process by creating an IPC connection,
forking,
and invoking the shell.
Historically,
.Nm popen
was implemented with a unidirectional pipe;
hence many implementations of
.Nm popen
only allow the
.Fa type
argument to specify reading or writing, not both.
Since
.Nm popen
is now implemented using sockets, the
.Fa type
may request a bidirectional data flow.
The
.Fa type
argument is a pointer to a null-terminated string
which must be
.Ql r
for reading,
.Ql w
for writing, or
.Ql r+
for reading and writing.
.Pp
The
.Fa command
argument is a pointer to a null-terminated string
containing a shell command line.
This command is passed to
.Pa /bin/sh
using the
.Fl c
flag; interpretation, if any, is performed by the shell.
.Pp
The return value from
.Fn popen
is a normal standard
.Tn I/O
stream in all respects
save that it must be closed with
.Fn pclose
rather than
.Fn fclose .
Writing to such a stream
writes to the standard input of the command;
the command's standard output is the same as that of the process that called
.Fn popen ,
unless this is altered by the command itself.
Conversely, reading from a
.Dq popened
stream reads the command's standard output, and
the command's standard input is the same as that of the process that called
.Fn popen .
.Pp
Note that output
.Fn popen
streams are fully buffered by default.
.Pp
The
.Fn pclose
function waits for the associated process to terminate
and returns the exit status of the command
as returned by
.Fn wait4 .
.Sh RETURN VALUE
The
.Fn popen
function returns
.Dv NULL
if the
.Xr fork 2 ,
.Xr pipe 2 ,
or
.Xr socketpair 2
calls fail,
or if it cannot allocate memory.
.Pp
The
.Fn pclose
function
returns \-1 if
.Fa stream
is not associated with a
.Dq popened
command, if
.Fa stream
already
.Dq pclosed ,
or if
.Xr wait4
returns an error.
.Sh ERRORS
The
.Fn popen
function does not reliably set
.Va errno .
.Sh SEE ALSO
.Xr fork 2 ,
.Xr sh 1 ,
.Xr pipe 2 ,
.Xr socketpair 2 ,
.Xr wait4 2 ,
.Xr fflush 3 ,
.Xr fclose 3 ,
.Xr fopen 3 ,
.Xr stdio 3 ,
.Xr system 3
.Sh BUGS
Since the standard input of a command opened for reading
shares its seek offset with the process that called
.Fn popen ,
if the original process has done a buffered read,
the command's input position may not be as expected.
Similarly, the output from a command opened for writing
may become intermingled with that of the original process.
The latter can be avoided by calling
.Xr fflush 3
before
.Fn popen .
.Pp
Failure to execute the shell
is indistinguishable from the shell's failure to execute command,
or an immediate exit of the command.
The only hint is an exit status of 127.
.Pp
The
.Fn popen
argument
always calls
.Xr sh ,
never calls
.Xr csh .
.Sh HISTORY
A
.Fn popen
and a
.Fn pclose
function appeared in
.At v7 .

164
lib/libc/gen/popen.c Normal file
View file

@ -0,0 +1,164 @@
/*
* Copyright (c) 1988, 1993
* The Regents of the University of California. All rights reserved.
*
* This code is derived from software written by Ken Arnold and
* published in UNIX Review, Vol. 6, No. 8.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#if defined(LIBC_SCCS) && !defined(lint)
static char sccsid[] = "@(#)popen.c 8.3 (Berkeley) 5/3/95";
#endif /* LIBC_SCCS and not lint */
#include <sys/param.h>
#include <sys/wait.h>
#include <sys/socket.h>
#include <signal.h>
#include <errno.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <paths.h>
static struct pid {
struct pid *next;
FILE *fp;
pid_t pid;
} *pidlist;
FILE *
popen(command, type)
const char *command, *type;
{
struct pid *cur;
FILE *iop;
int pdes[2], pid, twoway;
if (strchr(type, '+')) {
twoway = 1;
type = "r+";
if (socketpair(AF_UNIX, SOCK_STREAM, 0, pdes) < 0)
return (NULL);
} else {
twoway = 0;
if (*type != 'r' && *type != 'w' || type[1] ||
(pipe(pdes) < 0))
return (NULL);
}
if ((cur = malloc(sizeof(struct pid))) == NULL)
return (NULL);
switch (pid = vfork()) {
case -1: /* Error. */
(void)close(pdes[0]);
(void)close(pdes[1]);
(void)free(cur);
return (NULL);
/* NOTREACHED */
case 0: /* Child. */
if (*type == 'r') {
if (pdes[1] != STDOUT_FILENO) {
(void)dup2(pdes[1], STDOUT_FILENO);
(void)close(pdes[1]);
pdes[1] = STDOUT_FILENO;
}
(void) close(pdes[0]);
if (twoway && (pdes[1] != STDIN_FILENO))
(void)dup2(pdes[1], STDIN_FILENO);
} else {
if (pdes[0] != STDIN_FILENO) {
(void)dup2(pdes[0], STDIN_FILENO);
(void)close(pdes[0]);
}
(void)close(pdes[1]);
}
execl(_PATH_BSHELL, "sh", "-c", command, NULL);
_exit(127);
/* NOTREACHED */
}
/* Parent; assume fdopen can't fail. */
if (*type == 'r') {
iop = fdopen(pdes[0], type);
(void)close(pdes[1]);
} else {
iop = fdopen(pdes[1], type);
(void)close(pdes[0]);
}
/* Link into list of file descriptors. */
cur->fp = iop;
cur->pid = pid;
cur->next = pidlist;
pidlist = cur;
return (iop);
}
/*
* pclose --
* Pclose returns -1 if stream is not associated with a `popened' command,
* if already `pclosed', or waitpid returns an error.
*/
int
pclose(iop)
FILE *iop;
{
register struct pid *cur, *last;
int omask;
int pstat;
pid_t pid;
/* Find the appropriate file pointer. */
for (last = NULL, cur = pidlist; cur; last = cur, cur = cur->next)
if (cur->fp == iop)
break;
if (cur == NULL)
return (-1);
(void)fclose(iop);
do {
pid = waitpid(cur->pid, &pstat, 0);
} while (pid == -1 && errno == EINTR);
/* Remove the entry from the linked list. */
if (last == NULL)
pidlist = cur->next;
else
last->next = cur->next;
free(cur);
return (pid == -1 ? -1 : pstat);
}

92
lib/libc/gen/psignal.3 Normal file
View file

@ -0,0 +1,92 @@
.\" Copyright (c) 1983, 1991, 1993
.\" The Regents of the University of California. All rights reserved.
.\"
.\" Redistribution and use in source and binary forms, with or without
.\" modification, are permitted provided that the following conditions
.\" are met:
.\" 1. Redistributions of source code must retain the above copyright
.\" notice, this list of conditions and the following disclaimer.
.\" 2. Redistributions in binary form must reproduce the above copyright
.\" notice, this list of conditions and the following disclaimer in the
.\" documentation and/or other materials provided with the distribution.
.\" 3. All advertising materials mentioning features or use of this software
.\" must display the following acknowledgement:
.\" This product includes software developed by the University of
.\" California, Berkeley and its contributors.
.\" 4. Neither the name of the University nor the names of its contributors
.\" may be used to endorse or promote products derived from this software
.\" without specific prior written permission.
.\"
.\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
.\" ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
.\" SUCH DAMAGE.
.\"
.\" @(#)psignal.3 8.2 (Berkeley) 2/27/95
.\"
.Dd February 27, 1995
.Dt PSIGNAL 3
.Os BSD 4.2
.Sh NAME
.Nm psignal ,
.Nm sys_siglist ,
.Nm sys_signame
.Nd system signal messages
.Sh SYNOPSIS
.Fd #include <sys/signal.h>
.Ft void
.Fn psignal "unsigned sig" "const char *s"
.Vt extern char *sys_siglist[];
.Vt extern char *sys_signame[];
.Sh DESCRIPTION
The
.Fn psignal
function locates the descriptive message
string for the given signal number
.Fa sig
and writes it to the standard error.
.Pp
If the argument
.Fa s
is
.Pf non- Dv NULL
it is written to the standard error file descriptor
prior to the message string,
immediately followed by a colon and a space.
If the signal number is not recognized
.Pq Xr sigaction 2 ,
the string
.Dq "Unknown signal
is produced.
.Pp
The message strings can be accessed directly
through the external array
.Va sys_siglist ,
indexed by recognized signal numbers.
The external array
.Va sys_signame
is used similarly and
contains short, lower-case abbreviations for signals
which are useful for recognizing signal names
in user input.
The defined variable
.Dv NSIG
contains a count of the strings in
.Va sys_siglist
and
.Va sys_signame .
.Sh SEE ALSO
.Xr sigaction 2 ,
.Xr perror 3
.Sh HISTORY
The
.Fn psignal
function appeared in
.Bx 4.2 .

75
lib/libc/gen/readdir.c Normal file
View file

@ -0,0 +1,75 @@
/*
* Copyright (c) 1983, 1993
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#if defined(LIBC_SCCS) && !defined(lint)
static char sccsid[] = "@(#)readdir.c 8.3 (Berkeley) 9/29/94";
#endif /* LIBC_SCCS and not lint */
#include <sys/param.h>
#include <dirent.h>
/*
* get next entry in a directory.
*/
struct dirent *
readdir(dirp)
register DIR *dirp;
{
register struct dirent *dp;
for (;;) {
if (dirp->dd_loc >= dirp->dd_size) {
if (dirp->dd_flags & __DTF_READALL)
return (NULL);
dirp->dd_loc = 0;
}
if (dirp->dd_loc == 0 && !(dirp->dd_flags & __DTF_READALL)) {
dirp->dd_size = getdirentries(dirp->dd_fd,
dirp->dd_buf, dirp->dd_len, &dirp->dd_seek);
if (dirp->dd_size <= 0)
return (NULL);
}
dp = (struct dirent *)(dirp->dd_buf + dirp->dd_loc);
if ((int)dp & 03) /* bogus pointer check */
return (NULL);
if (dp->d_reclen <= 0 ||
dp->d_reclen > dirp->dd_len + 1 - dirp->dd_loc)
return (NULL);
dirp->dd_loc += dp->d_reclen;
if (dp->d_ino == 0)
continue;
if (dp->d_type == DT_WHT && (dirp->dd_flags & DTF_HIDEW))
continue;
return (dp);
}
}

125
lib/libc/gen/realpath.3 Normal file
View file

@ -0,0 +1,125 @@
.\" Copyright (c) 1994
.\" The Regents of the University of California. All rights reserved.
.\"
.\" This code is derived from software contributed to Berkeley by
.\" Jan-Simon Pendry.
.\"
.\" Redistribution and use in source and binary forms, with or without
.\" modification, are permitted provided that the following conditions
.\" are met:
.\" 1. Redistributions of source code must retain the above copyright
.\" notice, this list of conditions and the following disclaimer.
.\" 2. Redistributions in binary form must reproduce the above copyright
.\" notice, this list of conditions and the following disclaimer in the
.\" documentation and/or other materials provided with the distribution.
.\" 3. All advertising materials mentioning features or use of this software
.\" must display the following acknowledgement:
.\" This product includes software developed by the University of
.\" California, Berkeley and its contributors.
.\" 4. Neither the name of the University nor the names of its contributors
.\" may be used to endorse or promote products derived from this software
.\" without specific prior written permission.
.\"
.\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
.\" ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
.\" SUCH DAMAGE.
.\"
.\" @(#)realpath.3 8.2 (Berkeley) 2/16/94
.\"
.Dd "February 16, 1994"
.Dt REALPATH 3
.Os
.Sh NAME
.Nm realpath
.Nd returns the canonicalized absolute pathname
.Sh SYNOPSIS
.Fd #include <sys/param.h>
.Fd #include <stdlib.h>
.Ft "char *"
.Fn realpath "const char *pathname" "char resolvedname[MAXPATHLEN]"
.Sh DESCRIPTION
The
.Fn realpath
function resolves all symbolic links, extra
.Dq /
characters and references to
.Pa /./
and
.Pa /../
in
.Fa pathname ,
and copies the resulting absolute pathname into
the memory referenced by
.Fa resolvedname .
The
.Fa resolvedname
argument
.Em must
refer to a buffer capable of storing at least
.Dv MAXPATHLEN
characters.
.Pp
The
.Fn realpath
function will resolve both absolute and relative paths
and return the absolute pathname corresponding to
.Fa pathname .
All but the last component of
.Fa pathname
must exist when
.Fn realpath
is called.
.Sh "RETURN VALUES"
The
.Fn realpath
function returns
.Fa resolved_name
on success.
If an error occurs,
.Fn realpath
returns
.Dv NULL ,
and
.Fa resolved_name
contains the pathname which caused the problem.
.Sh ERRORS
The function
.Fn realpath
may fail and set the external variable
.Va errno
for any of the errors specified for the library functions
.Xr chdir 2 ,
.Xr close 2 ,
.Xr fchdir 2 ,
.Xr lstat 2 ,
.Xr open 2 ,
.Xr readlink 2
and
.Xr getcwd 3 .
.Sh CAVEATS
This implementation of
.Fn realpath
differs slightly from the Solaris implementation.
The
.Bx 4.4
version always returns absolute pathnames,
whereas the Solaris implementation will,
under certain circumstances, return a relative
.Fa resolved_path
when given a relative
.Fa pathname .
.Sh "SEE ALSO"
.Xr getcwd 3
.Sh HISTORY
The
.Fn realpath
function call first appeared in
.Bx 4.4 .

104
lib/libc/gen/setmode.3 Normal file
View file

@ -0,0 +1,104 @@
.\" Copyright (c) 1989, 1991, 1993
.\" The Regents of the University of California. All rights reserved.
.\"
.\" Redistribution and use in source and binary forms, with or without
.\" modification, are permitted provided that the following conditions
.\" are met:
.\" 1. Redistributions of source code must retain the above copyright
.\" notice, this list of conditions and the following disclaimer.
.\" 2. Redistributions in binary form must reproduce the above copyright
.\" notice, this list of conditions and the following disclaimer in the
.\" documentation and/or other materials provided with the distribution.
.\" 3. All advertising materials mentioning features or use of this software
.\" must display the following acknowledgement:
.\" This product includes software developed by the University of
.\" California, Berkeley and its contributors.
.\" 4. Neither the name of the University nor the names of its contributors
.\" may be used to endorse or promote products derived from this software
.\" without specific prior written permission.
.\"
.\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
.\" ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
.\" SUCH DAMAGE.
.\"
.\" @(#)setmode.3 8.2 (Berkeley) 4/28/95
.\"
.Dd April 28, 1995
.Dt SETMODE 3
.Os
.Sh NAME
.Nm getmode ,
.Nm setmode
.Nd modify mode bits
.Sh SYNOPSIS
.Ft mode_t
.Fn getmode "const void *set" "mode_t mode"
.Ft void *
.Fn setmode "const char *mode_str"
.Sh DESCRIPTION
The
.Fn getmode
function
returns a copy of the file permission bits
.Fa mode
as altered by the values pointed to by
.Fa set .
While only the mode bits are altered, other parts of the file mode
may be examined.
.Pp
The
.Fn setmode
function
takes an absolute (octal) or symbolic value, as described in
.Xr chmod 1 ,
as an argument
and returns a pointer to mode values to be supplied to
.Fn getmode .
Because some of the symbolic values are relative to the file
creation mask,
.Fn setmode
may call
.Xr umask 2 .
If this occurs, the file creation mask will be restored before
.Fn setmode
returns.
If the calling program changes the value of its file creation mask
after calling
.Fn setmode ,
.Fn setmode
must be called again if
.Fn getmode
is to modify future file modes correctly.
.Pp
If the mode passed to
.Fn setmode
is invalid,
.Fn setmode
returns
.Dv NULL .
.Sh ERRORS
The
.Fn setmode
function
may fail and set errno for any of the errors specified for the library
routine
.Xr malloc 3 .
.Sh SEE ALSO
.Xr chmod 1 ,
.Xr stat 2 ,
.Xr umask 2 ,
.Xr malloc 3
.Sh HISTORY
The
.Fn getmode
and
.Fn setmode
functions first appeared in 4.4BSD.

670
lib/libc/gen/sysctl.3 Normal file
View file

@ -0,0 +1,670 @@
.\" Copyright (c) 1993
.\" The Regents of the University of California. All rights reserved.
.\"
.\" Redistribution and use in source and binary forms, with or without
.\" modification, are permitted provided that the following conditions
.\" are met:
.\" 1. Redistributions of source code must retain the above copyright
.\" notice, this list of conditions and the following disclaimer.
.\" 2. Redistributions in binary form must reproduce the above copyright
.\" notice, this list of conditions and the following disclaimer in the
.\" documentation and/or other materials provided with the distribution.
.\" 3. All advertising materials mentioning features or use of this software
.\" must display the following acknowledgement:
.\" This product includes software developed by the University of
.\" California, Berkeley and its contributors.
.\" 4. Neither the name of the University nor the names of its contributors
.\" may be used to endorse or promote products derived from this software
.\" without specific prior written permission.
.\"
.\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
.\" ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
.\" SUCH DAMAGE.
.\"
.\" @(#)sysctl.3 8.4 (Berkeley) 5/9/95
.\"
.Dd "May 9, 1995"
.Dt SYSCTL 3
.Os
.Sh NAME
.Nm sysctl
.Nd get or set system information
.Sh SYNOPSIS
.Fd #include <sys/sysctl.h>
.Ft int
.Fn sysctl "int *name" "u_int namelen" "void *oldp" "size_t *oldlenp" "void *newp" "size_t newlen"
.Sh DESCRIPTION
The
.Nm sysctl
function retrieves system information and allows processes with
appropriate privileges to set system information.
The information available from
.Nm sysctl
consists of integers, strings, and tables.
Information may be retrieved and set from the command interface
using the
.Xr sysctl 1
utility.
.Pp
Unless explicitly noted below,
.Nm sysctl
returns a consistent snapshot of the data requested.
Consistency is obtained by locking the destination
buffer into memory so that the data may be copied out without blocking.
Calls to
.Nm sysctl
are serialized to avoid deadlock.
.Pp
The state is described using a ``Management Information Base'' (MIB)
style name, listed in
.Fa name ,
which is a
.Fa namelen
length array of integers.
.Pp
The information is copied into the buffer specified by
.Fa oldp .
The size of the buffer is given by the location specified by
.Fa oldlenp
before the call,
and that location gives the amount of data copied after a successful call.
If the amount of data available is greater
than the size of the buffer supplied,
the call supplies as much data as fits in the buffer provided
and returns with the error code ENOMEM.
If the old value is not desired,
.Fa oldp
and
.Fa oldlenp
should be set to NULL.
.Pp
The size of the available data can be determined by calling
.Nm sysctl
with a NULL parameter for
.Fa oldp .
The size of the available data will be returned in the location pointed to by
.Fa oldlenp .
For some operations, the amount of space may change often.
For these operations,
the system attempts to round up so that the returned size is
large enough for a call to return the data shortly thereafter.
.Pp
To set a new value,
.Fa newp
is set to point to a buffer of length
.Fa newlen
from which the requested value is to be taken.
If a new value is not to be set,
.Fa newp
should be set to NULL and
.Fa newlen
set to 0.
.Pp
The top level names are defined with a CTL_ prefix in
.Pa <sys/sysctl.h> ,
and are as follows.
The next and subsequent levels down are found in the include files
listed here, and described in separate sections below.
.Pp
.Bl -column CTLXMACHDEPXXX "Next level namesXXXXXX" -offset indent
.It Sy Pa Name Next level names Description
.It CTL\_DEBUG sys/sysctl.h Debugging
.It CTL\_VFS sys/mount.h Filesystem
.It CTL\_HW sys/sysctl.h Generic CPU, I/O
.It CTL\_KERN sys/sysctl.h High kernel limits
.It CTL\_MACHDEP sys/sysctl.h Machine dependent
.It CTL\_NET sys/socket.h Networking
.It CTL\_USER sys/sysctl.h User-level
.It CTL\_VM vm/vm_param.h Virtual memory
.El
.Pp
For example, the following retrieves the maximum number of processes allowed
in the system:
.Bd -literal -offset indent -compact
int mib[2], maxproc;
size_t len;
.sp
mib[0] = CTL_KERN;
mib[1] = KERN_MAXPROC;
len = sizeof(maxproc);
sysctl(mib, 2, &maxproc, &len, NULL, 0);
.Ed
.sp
To retrieve the standard search path for the system utilities:
.Bd -literal -offset indent -compact
int mib[2];
size_t len;
char *p;
.sp
mib[0] = CTL_USER;
mib[1] = USER_CS_PATH;
sysctl(mib, 2, NULL, &len, NULL, 0);
p = malloc(len);
sysctl(mib, 2, p, &len, NULL, 0);
.Ed
.Sh CTL_DEBUG
The debugging variables vary from system to system.
A debugging variable may be added or deleted without need to recompile
.Nm sysctl
to know about it.
Each time it runs,
.Nm sysctl
gets the list of debugging variables from the kernel and
displays their current values.
The system defines twenty
.Ns ( Va struct ctldebug )
variables named
.Nm debug0
through
.Nm debug19 .
They are declared as separate variables so that they can be
individually initialized at the location of their associated variable.
The loader prevents multiple use of the same variable by issuing errors
if a variable is initialized in more than one place.
For example, to export the variable
.Nm dospecialcheck
as a debugging variable, the following declaration would be used:
.Bd -literal -offset indent -compact
int dospecialcheck = 1;
struct ctldebug debug5 = { "dospecialcheck", &dospecialcheck };
.Ed
.Sh CTL_VFS
A distinguished second level name, VFS_GENERIC,
is used to get general information about all filesystems.
One of its third level identifiers is VFS_MAXTYPENUM
that gives the highest valid filesystem type number.
Its other third level identifier is VFS_CONF that
returns configuration information about the filesystem
type given as a fourth level identifier (see
.Xr getvfsbyname 3
as an example of its use).
The remaining second level identifiers are the
filesystem type number returned by a
.Xr statfs 2
call or from VFS_CONF.
The third level identifiers available for each filesystem
are given in the header file that defines the mount
argument structure for that filesystem.
.Sh CTL_HW
The string and integer information available for the CTL_HW level
is detailed below.
The changeable column shows whether a process with appropriate
privilege may change the value.
.Bl -column "Second level nameXXXXXX" integerXXX -offset indent
.It Sy Pa Second level name Type Changeable
.It HW\_MACHINE string no
.It HW\_MODEL string no
.It HW\_NCPU integer no
.It HW\_BYTEORDER integer no
.It HW\_PHYSMEM integer no
.It HW\_USERMEM integer no
.It HW\_PAGESIZE integer no
.\".It HW\_DISKNAMES integer no
.\".It HW\_DISKSTATS integer no
.El
.Pp
.Bl -tag -width "123456"
.It Li HW_MACHINE
The machine class.
.It Li HW_MODEL
The machine model
.It Li HW_NCPU
The number of cpus.
.ne 1i
.It Li HW_BYTEORDER
The byteorder (4,321, or 1,234).
.It Li HW_PHYSMEM
The bytes of physical memory.
.It Li HW_USERMEM
The bytes of non-kernel memory.
.It Li HW_PAGESIZE
The software page size.
.\".It Fa HW_DISKNAMES
.\".It Fa HW_DISKSTATS
.El
.Sh CTL_KERN
The string and integer information available for the CTL_KERN level
is detailed below.
The changeable column shows whether a process with appropriate
privilege may change the value.
The types of data currently available are process information,
system vnodes, the open file entries, routing table entries,
virtual memory statistics, load average history, and clock rate
information.
.Bl -column "KERNXCHOWNXRESTRICTEDXXX" "struct clockrateXXX" -offset indent
.It Sy Pa Second level name Type Changeable
.It KERN\_ARGMAX integer no
.It KERN\_BOOTTIME struct timeval no
.It KERN\_CHOWN\_RESTRICTED integer no
.It KERN\_CLOCKRATE struct clockinfo no
.It KERN\_FILE struct file no
.It KERN\_HOSTID integer yes
.It KERN\_HOSTNAME string yes
.It KERN\_JOB\_CONTROL integer no
.It KERN\_LINK\_MAX integer no
.It KERN\_MAXFILES integer yes
.It KERN\_MAXPROC integer yes
.It KERN\_MAXVNODES integer yes
.It KERN\_MAX\_CANON integer no
.It KERN\_MAX\_INPUT integer no
.It KERN\_NAME\_MAX integer no
.It KERN\_NGROUPS integer no
.It KERN\_NO\_TRUNC integer no
.It KERN\_OSRELEASE string no
.It KERN\_OSREV integer no
.It KERN\_OSTYPE string no
.It KERN\_PATH\_MAX integer no
.It KERN\_PIPE\_BUF integer no
.It KERN\_POSIX1 integer no
.It KERN\_PROC struct proc no
.It KERN\_PROF node not applicable
.It KERN\_SAVED\_IDS integer no
.It KERN\_SECURELVL integer raise only
.It KERN\_VDISABLE integer no
.It KERN\_VERSION string no
.It KERN\_VNODE struct vnode no
.El
.ne 1i
.Pp
.Bl -tag -width "123456"
.It Li KERN_ARGMAX
The maximum bytes of argument to
.Xr exec 2 .
.It Li KERN_BOOTTIME
A
.Va struct timeval
structure is returned.
This structure contains the time that the system was booted.
.It Li KERN_CHOWN_RESTRICTED
Return 1 if appropriate privileges are required for the
.Xr chown 2
system call, otherwise 0.
.It Li KERN_CLOCKRATE
A
.Va struct clockinfo
structure is returned.
This structure contains the clock, statistics clock and profiling clock
frequencies, and the number of micro-seconds per hz tick.
.It Li KERN_FILE
Return the entire file table.
The returned data consists of a single
.Va struct filehead
followed by an array of
.Va struct file ,
whose size depends on the current number of such objects in the system.
.It Li KERN_HOSTID
Get or set the host id.
.It Li KERN_HOSTNAME
Get or set the hostname.
.It Li KERN_JOB_CONTROL
Return 1 if job control is available on this system, otherwise 0.
.It Li KERN_LINK_MAX
The maximum file link count.
.It Li KERN_MAXFILES
The maximum number of open files that may be open in the system.
.It Li KERN_MAXPROC
The maximum number of simultaneous processes the system will allow.
.It Li KERN_MAXVNODES
The maximum number of vnodes available on the system.
.It Li KERN_MAX_CANON
The maximum number of bytes in terminal canonical input line.
.It Li KERN_MAX_INPUT
The minimum maximum number of bytes for which space is available in
a terminal input queue.
.It Li KERN_NAME_MAX
The maximum number of bytes in a file name.
.It Li KERN_NGROUPS
The maximum number of supplemental groups.
.It Li KERN_NO_TRUNC
Return 1 if file names longer than KERN_NAME_MAX are truncated.
.It Li KERN_OSRELEASE
The system release string.
.It Li KERN_OSREV
The system revision string.
.It Li KERN_OSTYPE
The system type string.
.It Li KERN_PATH_MAX
The maximum number of bytes in a pathname.
.It Li KERN_PIPE_BUF
The maximum number of bytes which will be written atomically to a pipe.
.It Li KERN_POSIX1
The version of ISO/IEC 9945 (POSIX 1003.1) with which the system
attempts to comply.
.It Li KERN_PROC
Return the entire process table, or a subset of it.
An array of
.Va struct kinfo_proc
structures is returned,
whose size depends on the current number of such objects in the system.
The third and fourth level names are as follows:
.Bl -column "Third level nameXXXXXX" "Fourth level is:XXXXXX" -offset indent
.It Pa Third level name Fourth level is:
.It KERN\_PROC\_ALL None
.It KERN\_PROC\_PID A process ID
.It KERN\_PROC\_PGRP A process group
.It KERN\_PROC\_TTY A tty device
.It KERN\_PROC\_UID A user ID
.It KERN\_PROC\_RUID A real user ID
.El
.It Li KERN_PROF
Return profiling information about the kernel.
If the kernel is not compiled for profiling,
attempts to retrieve any of the KERN_PROF values will
fail with EOPNOTSUPP.
The third level names for the string and integer profiling information
is detailed below.
The changeable column shows whether a process with appropriate
privilege may change the value.
.Bl -column "GPROFXGMONPARAMXXX" "struct gmonparamXXX" -offset indent
.It Sy Pa Third level name Type Changeable
.It GPROF\_STATE integer yes
.It GPROF\_COUNT u_short[\|] yes
.It GPROF\_FROMS u_short[\|] yes
.It GPROF\_TOS struct tostruct yes
.It GPROF\_GMONPARAM struct gmonparam no
.El
.Pp
The variables are as follows:
.Bl -tag -width "123456"
.It Li GPROF_STATE
Returns GMON_PROF_ON or GMON_PROF_OFF to show that profiling
is running or stopped.
.It Li GPROF_COUNT
Array of statistical program counter counts.
.It Li GPROF_FROMS
Array indexed by program counter of call-from points.
.It Li GPROF_TOS
Array of
.Va struct tostruct
describing destination of calls and their counts.
.It Li GPROF_GMONPARAM
Structure giving the sizes of the above arrays.
.El
.ne 1i
.It Li KERN_SAVED_IDS
Returns 1 if saved set-group and saved set-user ID is available.
.It Li KERN_SECURELVL
The system security level.
This level may be raised by processes with appropriate privilege.
It may only be lowered by process 1.
.It Li KERN_VDISABLE
Returns the terminal character disabling value.
.It Li KERN_VERSION
The system version string.
.It Li KERN_VNODE
Return the entire vnode table.
Note, the vnode table is not necessarily a consistent snapshot of
the system.
The returned data consists of an array whose size depends on the
current number of such objects in the system.
Each element of the array contains the kernel address of a vnode
.Va struct vnode *
followed by the vnode itself
.Va struct vnode .
.El
.Sh CTL_MACHDEP
The set of variables defined is architecture dependent.
Most architectures define at least the following variables.
.Bl -column "CONSOLE_DEVICEXXX" "integerXXX" -offset indent
.It Sy Pa Second level name Type Changeable
.It Li CPU_CONSDEV dev_t no
.El
.Sh CTL_NET
The string and integer information available for the CTL_NET level
is detailed below.
The changeable column shows whether a process with appropriate
privilege may change the value.
.Bl -column "Second level nameXXXXXX" "routing messagesXXX" -offset indent
.It Sy Pa Second level name Type Changeable
.It PF\_ROUTE routing messages no
.It PF\_INET internet values yes
.El
.Pp
.Bl -tag -width "123456"
.It Li PF_ROUTE
Return the entire routing table or a subset of it.
The data is returned as a sequence of routing messages (see
.Xr route 4
for the header file, format and meaning).
The length of each message is contained in the message header.
.Pp
The third level name is a protocol number, which is currently always 0.
The fourth level name is an address family, which may be set to 0 to
select all address families.
The fifth and sixth level names are as follows:
.Bl -column "Fifth level nameXXXXXX" "Sixth level is:XXX" -offset indent
.It Pa Fifth level name Sixth level is:
.It NET\_RT\_FLAGS rtflags
.It NET\_RT\_DUMP None
.It NET\_RT\_IFLIST None
.El
.It Li PF_INET
Get or set various global information about the internet protocols.
The third level name is the protocol.
The fourth level name is the variable name.
The currently defined protocols and names are:
.ne 1i
.Bl -column "Protocol nameXXXXXX" "Variable nameXXX" "integerXXX" -offset indent
.It Pa Protocol name Variable name Type Changeable
.It ip forwarding integer yes
.It ip redirect integer yes
.It ip ttl integer yes
.It icmp maskrepl integer yes
.It udp checksum integer yes
.El
.Pp
The variables are as follows:
.Bl -tag -width "123456"
.It Li ip.forwarding
Returns 1 when IP forwarding is enabled for the host,
meaning that the host is acting as a router.
.It Li ip.redirect
Returns 1 when ICMP redirects may be sent by the host.
This option is ignored unless the host is routing IP packets,
and should normally be enabled on all systems.
.It Li ip.ttl
The maximum time-to-live (hop count) value for an IP packet sourced by
the system.
This value applies to normal transport protocols, not to ICMP.
.It Li icmp.maskrepl
Returns 1 if ICMP network mask requests are to be answered.
.It Li udp.checksum
Returns 1 when UDP checksums are being computed and checked.
Disabling UDP checksums is strongly discouraged.
.El
.Sh CTL_USER
The string and integer information available for the CTL_USER level
is detailed below.
The changeable column shows whether a process with appropriate
privilege may change the value.
.Bl -column "USER_COLL_WEIGHTS_MAXXXX" "integerXXX" -offset indent
.It Sy Pa Second level name Type Changeable
.It USER\_BC\_BASE\_MAX integer no
.It USER\_BC\_DIM\_MAX integer no
.It USER\_BC\_SCALE\_MAX integer no
.It USER\_BC\_STRING\_MAX integer no
.It USER\_COLL\_WEIGHTS\_MAX integer no
.It USER\_CS\_PATH string no
.It USER\_EXPR\_NEST\_MAX integer no
.It USER\_LINE\_MAX integer no
.It USER\_POSIX2\_CHAR\_TERM integer no
.It USER\_POSIX2\_C\_BIND integer no
.It USER\_POSIX2\_C\_DEV integer no
.It USER\_POSIX2\_FORT\_DEV integer no
.It USER\_POSIX2\_FORT\_RUN integer no
.It USER\_POSIX2\_LOCALEDEF integer no
.It USER\_POSIX2\_SW\_DEV integer no
.It USER\_POSIX2\_UPE integer no
.It USER\_POSIX2\_VERSION integer no
.It USER\_RE\_DUP\_MAX integer no
.It USER\_STREAM\_MAX integer no
.It USER\_TZNAME\_MAX integer no
.El
.Bl -tag -width "123456"
.Pp
.It Li USER_BC_BASE_MAX
The maximum ibase/obase values in the
.Xr bc 1
utility.
.It Li USER_BC_DIM_MAX
The maximum array size in the
.Xr bc 1
utility.
.It Li USER_BC_SCALE_MAX
The maximum scale value in the
.Xr bc 1
utility.
.It Li USER_BC_STRING_MAX
The maximum string length in the
.Xr bc 1
utility.
.It Li USER_COLL_WEIGHTS_MAX
The maximum number of weights that can be assigned to any entry of
the LC_COLLATE order keyword in the locale definition file.
.It Li USER_CS_PATH
Return a value for the
.Ev PATH
environment variable that finds all the standard utilities.
.It Li USER_EXPR_NEST_MAX
The maximum number of expressions that can be nested within
parenthesis by the
.Xr expr 1
utility.
.It Li USER_LINE_MAX
The maximum length in bytes of a text-processing utility's input
line.
.It Li USER_POSIX2_CHAR_TERM
Return 1 if the system supports at least one terminal type capable of
all operations described in POSIX 1003.2, otherwise 0.
.It Li USER_POSIX2_C_BIND
Return 1 if the system's C-language development facilities support the
C-Language Bindings Option, otherwise 0.
.It Li USER_POSIX2_C_DEV
Return 1 if the system supports the C-Language Development Utilities Option,
otherwise 0.
.It Li USER_POSIX2_FORT_DEV
Return 1 if the system supports the FORTRAN Development Utilities Option,
otherwise 0.
.It Li USER_POSIX2_FORT_RUN
Return 1 if the system supports the FORTRAN Runtime Utilities Option,
otherwise 0.
.It Li USER_POSIX2_LOCALEDEF
Return 1 if the system supports the creation of locales, otherwise 0.
.It Li USER_POSIX2_SW_DEV
Return 1 if the system supports the Software Development Utilities Option,
otherwise 0.
.It Li USER_POSIX2_UPE
Return 1 if the system supports the User Portability Utilities Option,
otherwise 0.
.It Li USER_POSIX2_VERSION
The version of POSIX 1003.2 with which the system attempts to comply.
.It Li USER_RE_DUP_MAX
The maximum number of repeated occurrences of a regular expression
permitted when using interval notation.
.ne 1i
.It Li USER_STREAM_MAX
The minimum maximum number of streams that a process may have open
at any one time.
.It Li USER_TZNAME_MAX
The minimum maximum number of types supported for the name of a
timezone.
.El
.Sh CTL_VM
The string and integer information available for the CTL_VM level
is detailed below.
The changeable column shows whether a process with appropriate
privilege may change the value.
.Bl -column "Second level nameXXXXXX" "struct loadavgXXX" -offset indent
.It Sy Pa Second level name Type Changeable
.It VM\_LOADAVG struct loadavg no
.It VM\_METER struct vmtotal no
.El
.Pp
.Bl -tag -width "123456"
.It Li VM_LOADAVG
Return the load average history.
The returned data consists of a
.Va struct loadavg .
.It Li VM_METER
Return the system wide virtual memory statistics.
The returned data consists of a
.Va struct vmtotal .
.El
.Sh RETURN VALUES
If the call to
.Nm sysctl
is successful, the number of bytes copied out is returned.
Otherwise \-1 is returned and
.Va errno
is set appropriately.
.Sh ERRORS
The following errors may be reported:
.Bl -tag -width Er
.It Bq Er EFAULT
The buffer
.Fa name ,
.Fa oldp ,
.Fa newp ,
or length pointer
.Fa oldlenp
contains an invalid address.
.It Bq Er EINVAL
The
.Fa name
array is less than two or greater than CTL_MAXNAME.
.It Bq Er EINVAL
A non-null
.Fa newp
is given and its specified length in
.Fa newlen
is too large or too small.
.It Bq Er ENOMEM
The length pointed to by
.Fa oldlenp
is too short to hold the requested value.
.It Bq Er ENOTDIR
The
.Fa name
array specifies an intermediate rather than terminal name.
.It Bq Er EOPNOTSUPP
The
.Fa name
array specifies a value that is unknown.
.It Bq Er EPERM
An attempt is made to set a read-only value.
.It Bq Er EPERM
A process without appropriate privilege attempts to set a value.
.El
.Sh FILES
.Bl -tag -width <netinet/icmpXvar.h> -compact
.It Pa <sys/sysctl.h>
definitions for top level identifiers, second level kernel and hardware
identifiers, and user level identifiers
.It Pa <sys/socket.h>
definitions for second level network identifiers
.It Pa <sys/gmon.h>
definitions for third level profiling identifiers
.It Pa <vm/vm_param.h>
definitions for second level virtual memory identifiers
.It Pa <netinet/in.h>
definitions for third level Internet identifiers and
fourth level IP identifiers
.It Pa <netinet/icmp_var.h>
definitions for fourth level ICMP identifiers
.It Pa <netinet/udp_var.h>
definitions for fourth level UDP identifiers
.El
.Sh SEE ALSO
.Xr sysctl 8
.Sh HISTORY
The
.Nm sysctl
function first appeared in 4.4BSD.

235
lib/libc/gen/syslog.c Normal file
View file

@ -0,0 +1,235 @@
/*
* Copyright (c) 1983, 1988, 1993
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#if defined(LIBC_SCCS) && !defined(lint)
static char sccsid[] = "@(#)syslog.c 8.5 (Berkeley) 4/29/95";
#endif /* LIBC_SCCS and not lint */
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/syslog.h>
#include <sys/uio.h>
#include <netdb.h>
#include <errno.h>
#include <fcntl.h>
#include <paths.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#if __STDC__
#include <stdarg.h>
#else
#include <varargs.h>
#endif
static int LogFile = -1; /* fd for log */
static int connected; /* have done connect */
static int LogStat = 0; /* status bits, set by openlog() */
static const char *LogTag = NULL; /* string to tag the entry with */
static int LogFacility = LOG_USER; /* default facility code */
static int LogMask = 0xff; /* mask of priorities to be logged */
extern char *__progname; /* Program name, from crt0. */
/*
* syslog, vsyslog --
* print message on log file; output is intended for syslogd(8).
*/
void
#if __STDC__
syslog(int pri, const char *fmt, ...)
#else
syslog(pri, fmt, va_alist)
int pri;
char *fmt;
va_dcl
#endif
{
va_list ap;
#if __STDC__
va_start(ap, fmt);
#else
va_start(ap);
#endif
vsyslog(pri, fmt, ap);
va_end(ap);
}
void
vsyslog(pri, fmt, ap)
int pri;
register const char *fmt;
va_list ap;
{
register int cnt;
register char ch, *p, *t;
time_t now;
int fd, saved_errno;
char *stdp, tbuf[2048], fmt_cpy[1024];
#define INTERNALLOG LOG_ERR|LOG_CONS|LOG_PERROR|LOG_PID
/* Check for invalid bits. */
if (pri & ~(LOG_PRIMASK|LOG_FACMASK)) {
syslog(INTERNALLOG,
"syslog: unknown facility/priority: %x", pri);
pri &= LOG_PRIMASK|LOG_FACMASK;
}
/* Check priority against setlogmask values. */
if (!(LOG_MASK(LOG_PRI(pri)) & LogMask))
return;
saved_errno = errno;
/* Set default facility if none specified. */
if ((pri & LOG_FACMASK) == 0)
pri |= LogFacility;
/* Build the message. */
(void)time(&now);
p = tbuf + sprintf(tbuf, "<%d>", pri);
p += strftime(p, sizeof (tbuf) - (p - tbuf), "%h %e %T ",
localtime(&now));
if (LogStat & LOG_PERROR)
stdp = p;
if (LogTag == NULL)
LogTag = __progname;
if (LogTag != NULL)
p += sprintf(p, "%s", LogTag);
if (LogStat & LOG_PID)
p += sprintf(p, "[%d]", getpid());
if (LogTag != NULL) {
*p++ = ':';
*p++ = ' ';
}
/* Substitute error message for %m. */
for (t = fmt_cpy; ch = *fmt; ++fmt)
if (ch == '%' && fmt[1] == 'm') {
++fmt;
t += sprintf(t, "%s", strerror(saved_errno));
} else
*t++ = ch;
*t = '\0';
p += vsprintf(p, fmt_cpy, ap);
cnt = p - tbuf;
/* Output to stderr if requested. */
if (LogStat & LOG_PERROR) {
struct iovec iov[2];
register struct iovec *v = iov;
v->iov_base = stdp;
v->iov_len = cnt - (stdp - tbuf);
++v;
v->iov_base = "\n";
v->iov_len = 1;
(void)writev(STDERR_FILENO, iov, 2);
}
/* Get connected, output the message to the local logger. */
if (!connected)
openlog(LogTag, LogStat | LOG_NDELAY, 0);
if (send(LogFile, tbuf, cnt, 0) >= 0)
return;
/*
* Output the message to the console; don't worry about blocking,
* if console blocks everything will. Make sure the error reported
* is the one from the syslogd failure.
*/
if (LogStat & LOG_CONS &&
(fd = open(_PATH_CONSOLE, O_WRONLY, 0)) >= 0) {
(void)strcat(tbuf, "\r\n");
cnt += 2;
p = index(tbuf, '>') + 1;
(void)write(fd, p, cnt - (p - tbuf));
(void)close(fd);
}
}
static struct sockaddr SyslogAddr; /* AF_UNIX address of local logger */
void
openlog(ident, logstat, logfac)
const char *ident;
int logstat, logfac;
{
if (ident != NULL)
LogTag = ident;
LogStat = logstat;
if (logfac != 0 && (logfac &~ LOG_FACMASK) == 0)
LogFacility = logfac;
if (LogFile == -1) {
SyslogAddr.sa_family = AF_UNIX;
(void)strncpy(SyslogAddr.sa_data, _PATH_LOG,
sizeof(SyslogAddr.sa_data));
if (LogStat & LOG_NDELAY) {
if ((LogFile = socket(AF_UNIX, SOCK_DGRAM, 0)) == -1)
return;
(void)fcntl(LogFile, F_SETFD, 1);
}
}
if (LogFile != -1 && !connected)
if (connect(LogFile, &SyslogAddr, sizeof(SyslogAddr)) == -1) {
(void)close(LogFile);
LogFile = -1;
} else
connected = 1;
}
void
closelog()
{
(void)close(LogFile);
LogFile = -1;
connected = 0;
}
/* setlogmask -- set the log mask level */
int
setlogmask(pmask)
int pmask;
{
int omask;
omask = LogMask;
if (pmask != 0)
LogMask = pmask;
return (omask);
}

View file

@ -0,0 +1,78 @@
/*-
* Copyright (c) 1990, 1993
* The Regents of the University of California. All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* William Jolitz.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#if defined(LIBC_SCCS) && !defined(lint)
.asciz "@(#)_setjmp.s 8.1 (Berkeley) 6/4/93"
#endif /* LIBC_SCCS and not lint */
/*
* C library -- _setjmp, _longjmp
*
* _longjmp(a,v)
* will generate a "return(v)" from the last call to
* _setjmp(a)
* by restoring registers from the stack.
* The previous signal state is NOT restored.
*/
#include "DEFS.h"
ENTRY(_setjmp)
movl 4(%esp),%eax
movl 0(%esp),%edx
movl %edx, 0(%eax) /* rta */
movl %ebx, 4(%eax)
movl %esp, 8(%eax)
movl %ebp,12(%eax)
movl %esi,16(%eax)
movl %edi,20(%eax)
movl $0,%eax
ret
ENTRY(_longjmp)
movl 4(%esp),%edx
movl 8(%esp),%eax
movl 0(%edx),%ecx
movl 4(%edx),%ebx
movl 8(%edx),%esp
movl 12(%edx),%ebp
movl 16(%edx),%esi
movl 20(%edx),%edi
cmpl $0,%eax
jne 1f
movl $1,%eax
1: movl %ecx,0(%esp)
ret

View file

@ -0,0 +1,57 @@
/*-
* Copyright (c) 1990, 1993
* The Regents of the University of California. All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* William Jolitz.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#if defined(LIBC_SCCS) && !defined(lint)
.asciz "@(#)alloca.s 8.1 (Berkeley) 6/4/93"
#endif /* LIBC_SCCS and not lint */
/* like alloc, but automatic automatic free in return */
#include "DEFS.h"
ENTRY(alloca)
popl %edx /* pop return addr */
popl %eax /* pop amount to allocate */
movl %esp,%ecx
addl $3,%eax /* round up to next word */
andl $0xfffffffc,%eax
subl %eax,%esp
movl %esp,%eax /* base of newly allocated space */
pushl 8(%ecx) /* copy possible saved registers */
pushl 4(%ecx)
pushl 0(%ecx)
pushl %eax /* dummy to pop at callsite */
jmp %edx /* "return" */

46
lib/libc/i386/gen/fabs.S Normal file
View file

@ -0,0 +1,46 @@
/*-
* Copyright (c) 1990, 1993
* The Regents of the University of California. All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* William Jolitz.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#if defined(LIBC_SCCS) && !defined(lint)
.asciz "@(#)fabs.s 8.1 (Berkeley) 6/4/93"
#endif /* LIBC_SCCS and not lint */
#include "DEFS.h"
ENTRY(fabs)
fldl 4(%esp)
fabs
ret

75
lib/libc/i386/gen/modf.S Normal file
View file

@ -0,0 +1,75 @@
/*-
* Copyright (c) 1990, 1993
* The Regents of the University of California. All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* Sean Eric Fagan.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#if defined(LIBC_SCCS) && !defined(lint)
.asciz "@(#)modf.s 8.1 (Berkeley) 6/4/93"
#endif /* LIBC_SCCS and not lint */
/*
* modf(value, iptr): return fractional part of value, and stores the
* integral part into iptr (a pointer to double).
*
* Written by Sean Eric Fagan (sef@kithrup.COM)
* Sun Mar 11 20:27:30 PST 1990
*/
/* With CHOP mode on, frndint behaves as TRUNC does. Useful. */
.text
.globl _modf
_modf:
pushl %ebp
movl %esp,%ebp
subl $16,%esp
fnstcw -12(%ebp)
movw -12(%ebp),%dx
orw $3072,%dx
movw %dx,-16(%ebp)
fldcw -16(%ebp)
fldl 8(%ebp)
frndint
fstpl -8(%ebp)
fldcw -12(%ebp)
movl 16(%ebp),%eax
movl -8(%ebp),%edx
movl -4(%ebp),%ecx
movl %edx,(%eax)
movl %ecx,4(%eax)
fldl 8(%ebp)
fsubl -8(%ebp)
jmp L1
L1:
leave
ret

View file

@ -0,0 +1,86 @@
/*-
* Copyright (c) 1990, 1993
* The Regents of the University of California. All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* William Jolitz.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#if defined(LIBC_SCCS) && !defined(lint)
.asciz "@(#)setjmp.s 8.1 (Berkeley) 6/4/93"
#endif /* LIBC_SCCS and not lint */
/*
* C library -- _setjmp, _longjmp
*
* longjmp(a,v)
* will generate a "return(v)" from the last call to
* setjmp(a)
* by restoring registers from the stack.
* The previous signal state is restored.
*/
#include "DEFS.h"
ENTRY(setjmp)
pushl $0
call _sigblock
popl %edx
movl 4(%esp),%ecx
movl 0(%esp),%edx
movl %edx, 0(%ecx)
movl %ebx, 4(%ecx)
movl %esp, 8(%ecx)
movl %ebp,12(%ecx)
movl %esi,16(%ecx)
movl %edi,20(%ecx)
movl %eax,24(%ecx)
movl $0,%eax
ret
ENTRY(longjmp)
movl 4(%esp),%edx
pushl 24(%edx)
call _sigsetmask
popl %eax
movl 4(%esp),%edx
movl 8(%esp),%eax
movl 0(%edx),%ecx
movl 4(%edx),%ebx
movl 8(%edx),%esp
movl 12(%edx),%ebp
movl 16(%edx),%esi
movl 20(%edx),%edi
cmpl $0,%eax
jne 1f
movl $1,%eax
1: movl %ecx,0(%esp)
ret

View file

@ -0,0 +1,48 @@
/*-
* Copyright (c) 1990, 1993
* The Regents of the University of California. All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* William Jolitz.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#if defined(LIBC_SCCS) && !defined(lint)
.asciz "@(#)abs.s 8.1 (Berkeley) 6/4/93"
#endif /* LIBC_SCCS and not lint */
#include "DEFS.h"
ENTRY(abs)
movl 4(%esp),%eax
cmpl $0,%eax
jge 1f
negl %eax
1: ret

View file

@ -0,0 +1,53 @@
/*-
* Copyright (c) 1990, 1993
* The Regents of the University of California. All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* William Jolitz.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#if defined(LIBC_SCCS) && !defined(lint)
.asciz "@(#)bzero.s 8.1 (Berkeley) 6/4/93"
#endif /* LIBC_SCCS and not lint */
/* bzero (base,cnt) */
.globl _bzero
_bzero:
pushl %edi
movl 8(%esp),%edi
movl 12(%esp),%ecx
movb $0x00,%al
cld
rep
stosb
popl %edi
ret

View file

@ -0,0 +1,70 @@
/*-
* Copyright (c) 1990, 1993
* The Regents of the University of California. All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* William Jolitz.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#if defined(SYSLIBC_SCCS) && !defined(lint)
.asciz "@(#)Ovfork.s 8.1 (Berkeley) 6/4/93"
#endif /* SYSLIBC_SCCS and not lint */
#include "SYS.h"
/*
* pid = vfork();
*
* %edx == 0 in parent process, %edx == 1 in child process.
* %eax == pid of child in parent, %eax == pid of parent in child.
*
*/
.set vfork,66
.globl _vfork
_vfork:
popl %ecx /* my rta into ecx */
movl $vfork, %eax
LCALL(7,0)
jb verror
vforkok:
cmpl $0,%edx /* child process? */
jne child /* yes */
jmp parent
.globl _errno
verror:
movl %eax,_errno
movl $-1,%eax
jmp %ecx
child:
movl $0,%eax
parent:
jmp %ecx

65
lib/libc/i386/sys/brk.S Normal file
View file

@ -0,0 +1,65 @@
/*-
* Copyright (c) 1990, 1993
* The Regents of the University of California. All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* William Jolitz.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#if defined(SYSLIBC_SCCS) && !defined(lint)
.asciz "@(#)brk.s 8.1 (Berkeley) 6/4/93"
#endif /* SYSLIBC_SCCS and not lint */
#include "SYS.h"
#define SYS_brk 17
.globl curbrk
.globl minbrk
ENTRY(_brk)
jmp ok
ENTRY(brk)
movl 4(%esp),%eax
cmpl %eax,minbrk
jl ok
movl minbrk,%eax
movl %eax,4(%esp)
ok:
lea SYS_brk,%eax
LCALL(7,0)
jb err
movl 4(%esp),%eax
movl %eax,curbrk
movl $0,%eax
ret
err:
jmp cerror

View file

@ -0,0 +1,47 @@
/*-
* Copyright (c) 1990, 1993
* The Regents of the University of California. All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* William Jolitz.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#if defined(SYSLIBC_SCCS) && !defined(lint)
.asciz "@(#)cerror.s 8.1 (Berkeley) 6/4/93"
#endif /* SYSLIBC_SCCS and not lint */
#include "SYS.h"
.globl _errno
cerror:
movl %eax,_errno
movl $-1,%eax
ret

52
lib/libc/i386/sys/exect.S Normal file
View file

@ -0,0 +1,52 @@
/*-
* Copyright (c) 1990, 1993
* The Regents of the University of California. All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* William Jolitz.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#if defined(SYSLIBC_SCCS) && !defined(lint)
.asciz "@(#)exect.s 8.1 (Berkeley) 6/4/93"
#endif /* SYSLIBC_SCCS and not lint */
#include "SYS.h"
#include <machine/psl.h>
ENTRY(exect)
lea SYS_execve,%eax
pushf
popl %edx
orl $ PSL_T,%edx
pushl %edx
popf
LCALL(7,0)
jmp cerror /* exect(file, argv, env); */

48
lib/libc/i386/sys/fork.S Normal file
View file

@ -0,0 +1,48 @@
/*-
* Copyright (c) 1990, 1993
* The Regents of the University of California. All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* William Jolitz.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#if defined(SYSLIBC_SCCS) && !defined(lint)
.asciz "@(#)fork.s 8.1 (Berkeley) 6/4/93"
#endif /* SYSLIBC_SCCS and not lint */
#include "SYS.h"
SYSCALL(fork)
cmpl $0,%edx /* parent, since %edx == 0 in parent, 1 in child */
je 1f
movl $0,%eax
1:
ret /* pid = fork(); */

45
lib/libc/i386/sys/mount.S Normal file
View file

@ -0,0 +1,45 @@
/*-
* Copyright (c) 1990, 1993
* The Regents of the University of California. All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* William Jolitz.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#if defined(SYSLIBC_SCCS) && !defined(lint)
.asciz "@(#)mount.s 8.1 (Berkeley) 6/4/93"
#endif /* SYSLIBC_SCCS and not lint */
#include "SYS.h"
SYSCALL(mount)
movl $0,%eax
ret

48
lib/libc/i386/sys/pipe.S Normal file
View file

@ -0,0 +1,48 @@
/*-
* Copyright (c) 1990, 1993
* The Regents of the University of California. All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* William Jolitz.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#if defined(SYSLIBC_SCCS) && !defined(lint)
.asciz "@(#)pipe.s 8.1 (Berkeley) 6/4/93"
#endif /* SYSLIBC_SCCS and not lint */
#include "SYS.h"
SYSCALL(pipe)
movl 4(%esp),%ecx
movl %eax,(%ecx)
movl %edx,4(%ecx)
movl $0,%eax
ret

View file

@ -0,0 +1,51 @@
/*-
* Copyright (c) 1990, 1993
* The Regents of the University of California. All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* William Jolitz.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#if defined(SYSLIBC_SCCS) && !defined(lint)
.asciz "@(#)ptrace.s 8.1 (Berkeley) 6/4/93"
#endif /* SYSLIBC_SCCS and not lint */
#include "SYS.h"
ENTRY(ptrace)
xorl %eax,%eax
movl %eax,_errno
lea SYS_ptrace,%eax
LCALL(7,0)
jb err
ret
err:
jmp cerror

View file

@ -0,0 +1,44 @@
/*-
* Copyright (c) 1990, 1993
* The Regents of the University of California. All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* William Jolitz.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#if defined(SYSLIBC_SCCS) && !defined(lint)
.asciz "@(#)reboot.s 8.1 (Berkeley) 6/4/93"
#endif /* SYSLIBC_SCCS and not lint */
#include "SYS.h"
SYSCALL(reboot)
iret

65
lib/libc/i386/sys/sbrk.S Normal file
View file

@ -0,0 +1,65 @@
/*-
* Copyright (c) 1990, 1993
* The Regents of the University of California. All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* William Jolitz.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#if defined(SYSLIBC_SCCS) && !defined(lint)
.asciz "@(#)sbrk.s 8.1 (Berkeley) 6/4/93"
#endif /* SYSLIBC_SCCS and not lint */
#include "SYS.h"
#define SYS_brk 17
.globl _end
.globl minbrk
.globl curbrk
.data
minbrk: .long _end
curbrk: .long _end
.text
ENTRY(sbrk)
movl 4(%esp),%ecx
movl curbrk,%eax
addl %eax,4(%esp)
lea SYS_brk,%eax
LCALL(7,0)
jb err
movl curbrk,%eax
addl %ecx,curbrk
ret
err:
jmp cerror

View file

@ -0,0 +1,47 @@
/*-
* Copyright (c) 1991, 1993
* The Regents of the University of California. All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* William Jolitz.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#if defined(LIBC_SCCS) && !defined(lint)
.asciz "@(#)setlogin.s 8.1 (Berkeley) 6/4/93"
#endif /* LIBC_SCCS and not lint */
#include "SYS.h"
.globl __logname_valid /* in getlogin() */
SYSCALL(setlogin)
movl $0,__logname_valid
ret /* setlogin(name) */

View file

@ -0,0 +1,47 @@
/*-
* Copyright (c) 1990, 1993
* The Regents of the University of California. All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* William Jolitz.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#if defined(SYSLIBC_SCCS) && !defined(lint)
.asciz "@(#)sigpending.s 8.1 (Berkeley) 6/4/93"
#endif /* SYSLIBC_SCCS and not lint */
#include "SYS.h"
SYSCALL(sigpending)
movl 4(%esp),%ecx # fetch pointer to...
movl %eax,(%ecx) # store old mask
xorl %eax,%eax
ret

View file

@ -0,0 +1,64 @@
/*-
* Copyright (c) 1990, 1993
* The Regents of the University of California. All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* William Jolitz.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#if defined(SYSLIBC_SCCS) && !defined(lint)
.asciz "@(#)sigprocmask.s 8.1 (Berkeley) 6/4/93"
#endif /* SYSLIBC_SCCS and not lint */
#include "SYS.h"
err:
jmp cerror
ENTRY(sigprocmask)
movl 8(%esp),%ecx # fetch new sigset pointer
cmpl $0,%ecx # check new sigset pointer
jne 1f # if not null, indirect
/* movl $0,8(%esp) # null mask pointer: block empty set */
movl $1,4(%esp) # SIG_BLOCK
jmp 2f
1: movl (%ecx),%ecx # fetch indirect ...
movl %ecx,8(%esp) # to new mask arg
2: movl $ SYS_sigprocmask , %eax
LCALL(0x7,0)
jb err
movl 12(%esp),%ecx # fetch old mask requested
cmpl $0,%ecx # test if old mask requested
je out
movl %eax,(%ecx) # store old mask
out:
xorl %eax,%eax
ret

View file

@ -0,0 +1,54 @@
/*-
* Copyright (c) 1990, 1993
* The Regents of the University of California. All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* William Jolitz.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#if defined(SYSLIBC_SCCS) && !defined(lint)
.asciz "@(#)sigreturn.s 8.1 (Berkeley) 6/4/93"
#endif /* SYSLIBC_SCCS and not lint */
#include "SYS.h"
/*
* We must preserve the state of the registers as the user has set them up.
*/
#ifdef PROF
#undef ENTRY
#define ENTRY(x) \
.globl _/**/x; .align 2; _/**/x: pusha ; \
.data; 1:; .long 0; .text; movl $1b,%eax; call mcount; popa ; nop
#endif /* PROF */
SYSCALL(sigreturn)
ret

View file

@ -0,0 +1,54 @@
/*-
* Copyright (c) 1990, 1993
* The Regents of the University of California. All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* William Jolitz.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#if defined(SYSLIBC_SCCS) && !defined(lint)
.asciz "@(#)sigsuspend.s 8.1 (Berkeley) 6/4/93"
#endif /* SYSLIBC_SCCS and not lint */
#include "SYS.h"
err:
jmp cerror
ENTRY(sigsuspend)
movl 4(%esp),%eax # fetch mask arg
movl (%eax),%eax # indirect to mask arg
movl %eax,4(%esp)
movl $ SYS_sigsuspend ,%eax
LCALL(0x7,0)
jb err
xorl %eax,%eax # shouldn t happen
ret

View file

@ -0,0 +1,51 @@
/*-
* Copyright (c) 1990, 1993
* The Regents of the University of California. All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* William Jolitz.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#if defined(SYSLIBC_SCCS) && !defined(lint)
.asciz "@(#)syscall.s 8.1 (Berkeley) 6/4/93"
#endif /* SYSLIBC_SCCS and not lint */
#include "SYS.h"
ENTRY(syscall)
pop %ecx /* rta */
pop %eax /* syscall number */
push %ecx
LCALL(7,0)
jb 1f
ret
1:
jmp cerror

88
lib/libc/stdio/ftell.c Normal file
View file

@ -0,0 +1,88 @@
/*-
* Copyright (c) 1990, 1993
* The Regents of the University of California. All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* Chris Torek.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#if defined(LIBC_SCCS) && !defined(lint)
static char sccsid[] = "@(#)ftell.c 8.2 (Berkeley) 5/4/95";
#endif /* LIBC_SCCS and not lint */
#include <stdio.h>
#include <errno.h>
#include "local.h"
/*
* ftell: return current offset.
*/
long
ftell(fp)
register FILE *fp;
{
register fpos_t pos;
if (fp->_seek == NULL) {
errno = ESPIPE; /* historic practice */
return (-1L);
}
/*
* Find offset of underlying I/O object, then
* adjust for buffered bytes.
*/
if (fp->_flags & __SOFF)
pos = fp->_offset;
else {
pos = (*fp->_seek)(fp->_cookie, (fpos_t)0, SEEK_CUR);
if (pos == -1L)
return (pos);
}
if (fp->_flags & __SRD) {
/*
* Reading. Any unread characters (including
* those from ungetc) cause the position to be
* smaller than that in the underlying object.
*/
pos -= fp->_r;
if (HASUB(fp))
pos -= fp->_ur;
} else if (fp->_flags & __SWR && fp->_p != NULL) {
/*
* Writing. Any buffered characters cause the
* position to be greater than that in the
* underlying object.
*/
pos += fp->_p - fp->_bf._base;
}
return (pos);
}

87
lib/libc/stdio/local.h Normal file
View file

@ -0,0 +1,87 @@
/*-
* Copyright (c) 1990, 1993
* The Regents of the University of California. All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* Chris Torek.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* @(#)local.h 8.3 (Berkeley) 7/3/94
*/
/*
* Information local to this implementation of stdio,
* in particular, macros and private variables.
*/
extern int __sflush __P((FILE *));
extern FILE *__sfp __P((void));
extern int __srefill __P((FILE *));
extern int __sread __P((void *, char *, int));
extern int __swrite __P((void *, char const *, int));
extern fpos_t __sseek __P((void *, fpos_t, int));
extern int __sclose __P((void *));
extern void __sinit __P((void));
extern void _cleanup __P((void));
extern void (*__cleanup) __P((void));
extern void __smakebuf __P((FILE *));
extern int __swhatbuf __P((FILE *, size_t *, int *));
extern int _fwalk __P((int (*)(FILE *)));
extern int __swsetup __P((FILE *));
extern int __sflags __P((const char *, int *));
extern int __sdidinit;
/*
* Return true iff the given FILE cannot be written now.
*/
#define cantwrite(fp) \
((((fp)->_flags & __SWR) == 0 || (fp)->_bf._base == NULL) && \
__swsetup(fp))
/*
* Test whether the given stdio file has an active ungetc buffer;
* release such a buffer, without restoring ordinary unread data.
*/
#define HASUB(fp) ((fp)->_ub._base != NULL)
#define FREEUB(fp) { \
if ((fp)->_ub._base != (fp)->_ubuf) \
free((char *)(fp)->_ub._base); \
(fp)->_ub._base = NULL; \
}
/*
* test for an fgetln() buffer.
*/
#define HASLB(fp) ((fp)->_lb._base != NULL)
#define FREELB(fp) { \
free((char *)(fp)->_lb._base); \
(fp)->_lb._base = NULL; \
}

View file

@ -0,0 +1,25 @@
# @(#)Makefile.inc 8.3 (Berkeley) 2/4/95
# machine-independent stdlib sources
.PATH: ${.CURDIR}/${MACHINE}/stdlib ${.CURDIR}/stdlib
SRCS+= abort.c atexit.c atof.c atoi.c atol.c bsearch.c calloc.c div.c \
exit.c getenv.c getopt.c getsubopt.c heapsort.c labs.c ldiv.c \
malloc.c merge.c putenv.c qsort.c radixsort.c rand.c random.c \
setenv.c strtod.c strtol.c strtoq.c strtoul.c \
strtouq.c system.c
# machine-dependent stdlib sources
.include "${.CURDIR}/${MACHINE}/stdlib/Makefile.inc"
MAN3+= abort.0 abs.0 alloca.0 atexit.0 atof.0 atoi.0 atol.0 bsearch.0 \
calloc.0 div.0 exit.0 free.0 getenv.0 getopt.0 getsubopt.0 labs.0 \
ldiv.0 malloc.0 memory.0 qsort.0 radixsort.0 rand.0 random.0 \
realloc.0 strtol.0 strtoul.0 system.0
MLINKS+=getenv.3 setenv.3 getenv.3 unsetenv.3 getenv.3 putenv.3
MLINKS+=qsort.3 heapsort.3 qsort.3 mergesort.3
MLINKS+=rand.3 srand.3
MLINKS+=random.3 initstate.3 random.3 setstate.3 random.3 srandom.3
MLINKS+=strtol.3 strtoq.3
MLINKS+=strtoul.3 strtouq.3

68
lib/libc/stdlib/atexit.c Normal file
View file

@ -0,0 +1,68 @@
/*-
* Copyright (c) 1990, 1993
* The Regents of the University of California. All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* Chris Torek.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#if defined(LIBC_SCCS) && !defined(lint)
static char sccsid[] = "@(#)atexit.c 8.2 (Berkeley) 7/3/94";
#endif /* LIBC_SCCS and not lint */
#include <stddef.h>
#include <stdlib.h>
#include "atexit.h"
struct atexit *__atexit; /* points to head of LIFO stack */
/*
* Register a function to be performed at exit.
*/
int
atexit(fn)
void (*fn)();
{
static struct atexit __atexit0; /* one guaranteed table */
register struct atexit *p;
if ((p = __atexit) == NULL)
__atexit = p = &__atexit0;
else if (p->ind >= ATEXIT_SIZE) {
if ((p = malloc(sizeof(*p))) == NULL)
return (-1);
p->ind = 0;
p->next = __atexit;
__atexit = p;
}
p->fns[p->ind++] = fn;
return (0);
}

45
lib/libc/stdlib/atexit.h Normal file
View file

@ -0,0 +1,45 @@
/*-
* Copyright (c) 1990, 1993
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* @(#)atexit.h 8.2 (Berkeley) 7/3/94
*/
/* must be at least 32 to guarantee ANSI conformance */
#define ATEXIT_SIZE 32
struct atexit {
struct atexit *next; /* next in list */
int ind; /* next index in this table */
void (*fns[ATEXIT_SIZE])(); /* the table itself */
};
extern struct atexit *__atexit; /* points to head of LIFO stack */

260
lib/libc/stdlib/getopt.3 Normal file
View file

@ -0,0 +1,260 @@
.\" Copyright (c) 1988, 1991, 1993
.\" The Regents of the University of California. All rights reserved.
.\"
.\" Redistribution and use in source and binary forms, with or without
.\" modification, are permitted provided that the following conditions
.\" are met:
.\" 1. Redistributions of source code must retain the above copyright
.\" notice, this list of conditions and the following disclaimer.
.\" 2. Redistributions in binary form must reproduce the above copyright
.\" notice, this list of conditions and the following disclaimer in the
.\" documentation and/or other materials provided with the distribution.
.\" 3. All advertising materials mentioning features or use of this software
.\" must display the following acknowledgement:
.\" This product includes software developed by the University of
.\" California, Berkeley and its contributors.
.\" 4. Neither the name of the University nor the names of its contributors
.\" may be used to endorse or promote products derived from this software
.\" without specific prior written permission.
.\"
.\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
.\" ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
.\" SUCH DAMAGE.
.\"
.\" @(#)getopt.3 8.5 (Berkeley) 4/27/95
.\"
.Dd April 27, 1995
.Dt GETOPT 3
.Os BSD 4.3
.Sh NAME
.Nm getopt
.Nd get option character from command line argument list
.Sh SYNOPSIS
.Fd #include <unistd.h>
.Vt extern char *optarg;
.Vt extern int optind;
.Vt extern int optopt;
.Vt extern int opterr;
.Vt extern int optreset;
.Ft int
.Fn getopt "int argc" "char * const *argv" "const char *optstring"
.Sh DESCRIPTION
The
.Fn getopt
function incrementally parses a command line argument list
.Fa argv
and returns the next
.Em known
option character.
An option character is
.Em known
if it has been specified in the string of accepted option characters,
.Fa optstring .
.Pp
The option string
.Fa optstring
may contain the following elements: individual characters, and
characters followed by a colon to indicate an option argument
is to follow.
For example, an option string
.Li "\&""x""
recognizes an option
.Dq Fl x ,
and an option string
.Li "\&""x:""
recognizes an option and argument
.Dq Fl x Ar argument .
It does not matter to
.Fn getopt
if a following argument has leading white space.
.Pp
On return from
.Fn getopt ,
.Va optarg
points to an option argument, if it is anticipated,
and the variable
.Va optind
contains the index to the next
.Fa argv
argument for a subsequent call
to
.Fn getopt .
The variable
.Va optopt
saves the last
.Em known
option character returned by
.Fn getopt .
.Pp
The variable
.Va opterr
and
.Va optind
are both initialized to 1.
The
.Va optind
variable may be set to another value before a set of calls to
.Fn getopt
in order to skip over more or less argv entries.
.Pp
In order to use
.Fn getopt
to evaluate multiple sets of arguments, or to evaluate a single set of
arguments multiple times,
the variable
.Va optreset
must be set to 1 before the second and each additional set of calls to
.Fn getopt ,
and the variable
.Va optind
must be reinitialized.
.Pp
The
.Fn getopt
function
returns \-1
when the argument list is exhausted, or a non-recognized
option is encountered.
The interpretation of options in the argument list may be cancelled
by the option
.Ql --
(double dash) which causes
.Fn getopt
to signal the end of argument processing and returns \-1.
When all options have been processed (i.e., up to the first non-option
argument),
.Fn getopt
returns \-1.
.Sh DIAGNOSTICS
If the
.Fn getopt
function encounters a character not found in the string
.Va optarg
or detects
a missing option argument it writes an error message and returns
.Ql ?
to the
.Em stderr .
Setting
.Va opterr
to a zero will disable these error messages.
If
.Va optstring
has a leading
.Ql \&:
then a missing option argument causes a
.Ql \&:
to be returned in addition to suppressing any error messages.
.Pp
Option arguments are allowed to begin with
.Dq Li \- ;
this is reasonable but
reduces the amount of error checking possible.
.Sh EXTENSIONS
The
.Va optreset
variable was added to make it possible to call the
.Fn getopt
function multiple times.
This is an extension to the
.St -p1003.2
specification.
.Sh EXAMPLE
.Bd -literal -compact
extern char *optarg;
extern int optind;
int bflag, ch, fd;
bflag = 0;
while ((ch = getopt(argc, argv, "bf:")) != -1)
switch(ch) {
case 'b':
bflag = 1;
break;
case 'f':
if ((fd = open(optarg, O_RDONLY, 0)) < 0) {
(void)fprintf(stderr,
"myname: %s: %s\en", optarg, strerror(errno));
exit(1);
}
break;
case '?':
default:
usage();
}
argc -= optind;
argv += optind;
.Ed
.Sh HISTORY
The
.Fn getopt
function appeared
.Bx 4.3 .
.Sh BUGS
The
.Fn getopt
function was once specified to return
.Dv EOF
instead of \-1.
This was changed by
.St -p1003.2-92
to decouple
.Fn getopt
from
.Pa <stdio.h> .
.Pp
A single dash
.Dq Li -
may be specified as an character in
.Fa optstring ,
however it should
.Em never
have an argument associated with it.
This allows
.Fn getopt
to be used with programs that expect
.Dq Li -
as an option flag.
This practice is wrong, and should not be used in any current development.
It is provided for backward compatibility
.Em only .
By default, a single dash causes
.Fn getopt
to return \-1.
This is, we believe, compatible with System V.
.Pp
It is also possible to handle digits as option letters.
This allows
.Fn getopt
to be used with programs that expect a number
.Pq Dq Li \&-\&3
as an option.
This practice is wrong, and should not be used in any current development.
It is provided for backward compatibility
.Em only .
The following code fragment works in most cases.
.Bd -literal -offset indent
int length;
char *p;
while ((c = getopt(argc, argv, "0123456789")) != -1)
switch (c) {
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
p = argv[optind - 1];
if (p[0] == '-' && p[1] == ch && !p[2])
length = atoi(++p);
else
length = atoi(argv[optind] + 1);
break;
}
}
.Ed

117
lib/libc/stdlib/getopt.c Normal file
View file

@ -0,0 +1,117 @@
/*
* Copyright (c) 1987, 1993, 1994
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#if defined(LIBC_SCCS) && !defined(lint)
static char sccsid[] = "@(#)getopt.c 8.3 (Berkeley) 4/27/95";
#endif /* LIBC_SCCS and not lint */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int opterr = 1, /* if error message should be printed */
optind = 1, /* index into parent argv vector */
optopt, /* character checked for validity */
optreset; /* reset getopt */
char *optarg; /* argument associated with option */
#define BADCH (int)'?'
#define BADARG (int)':'
#define EMSG ""
/*
* getopt --
* Parse argc/argv argument vector.
*/
int
getopt(nargc, nargv, ostr)
int nargc;
char * const *nargv;
const char *ostr;
{
extern char *__progname;
static char *place = EMSG; /* option letter processing */
char *oli; /* option letter list index */
if (optreset || !*place) { /* update scanning pointer */
optreset = 0;
if (optind >= nargc || *(place = nargv[optind]) != '-') {
place = EMSG;
return (-1);
}
if (place[1] && *++place == '-') { /* found "--" */
++optind;
place = EMSG;
return (-1);
}
} /* option letter okay? */
if ((optopt = (int)*place++) == (int)':' ||
!(oli = strchr(ostr, optopt))) {
/*
* if the user didn't specify '-' as an option,
* assume it means -1.
*/
if (optopt == (int)'-')
return (-1);
if (!*place)
++optind;
if (opterr && *ostr != ':')
(void)fprintf(stderr,
"%s: illegal option -- %c\n", __progname, optopt);
return (BADCH);
}
if (*++oli != ':') { /* don't need argument */
optarg = NULL;
if (!*place)
++optind;
}
else { /* need an argument */
if (*place) /* no white space */
optarg = place;
else if (nargc <= ++optind) { /* no arg */
place = EMSG;
if (*ostr == ':')
return (BADARG);
if (opterr)
(void)fprintf(stderr,
"%s: option requires an argument -- %c\n",
__progname, optopt);
return (BADCH);
}
else /* white space */
optarg = nargv[optind];
place = EMSG;
++optind;
}
return (optopt); /* dump back option letter */
}

318
lib/libc/stdlib/radixsort.c Normal file
View file

@ -0,0 +1,318 @@
/*-
* Copyright (c) 1990, 1993
* The Regents of the University of California. All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* Peter McIlroy and by Dan Bernstein at New York University,
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#if defined(LIBC_SCCS) && !defined(lint)
static char sccsid[] = "@(#)radixsort.c 8.2 (Berkeley) 4/28/95";
#endif /* LIBC_SCCS and not lint */
/*
* Radixsort routines.
*
* Program r_sort_a() is unstable but uses O(logN) extra memory for a stack.
* Use radixsort(a, n, trace, endchar) for this case.
*
* For stable sorting (using N extra pointers) use sradixsort(), which calls
* r_sort_b().
*
* For a description of this code, see D. McIlroy, P. McIlroy, K. Bostic,
* "Engineering Radix Sort".
*/
#include <sys/types.h>
#include <stdlib.h>
#include <stddef.h>
#include <errno.h>
typedef struct {
const u_char **sa;
int sn, si;
} stack;
static inline void simplesort
__P((const u_char **, int, int, const u_char *, u_int));
static void r_sort_a __P((const u_char **, int, int, const u_char *, u_int));
static void r_sort_b __P((const u_char **,
const u_char **, int, int, const u_char *, u_int));
#define THRESHOLD 20 /* Divert to simplesort(). */
#define SIZE 512 /* Default stack size. */
#define SETUP { \
if (tab == NULL) { \
tr = tr0; \
for (c = 0; c < endch; c++) \
tr0[c] = c + 1; \
tr0[c] = 0; \
for (c++; c < 256; c++) \
tr0[c] = c; \
endch = 0; \
} else { \
endch = tab[endch]; \
tr = tab; \
if (endch != 0 && endch != 255) { \
errno = EINVAL; \
return (-1); \
} \
} \
}
int
radixsort(a, n, tab, endch)
const u_char **a, *tab;
int n;
u_int endch;
{
const u_char *tr;
int c;
u_char tr0[256];
SETUP;
r_sort_a(a, n, 0, tr, endch);
return (0);
}
int
sradixsort(a, n, tab, endch)
const u_char **a, *tab;
int n;
u_int endch;
{
const u_char *tr, **ta;
int c;
u_char tr0[256];
SETUP;
if (n < THRESHOLD)
simplesort(a, n, 0, tr, endch);
else {
if ((ta = malloc(n * sizeof(a))) == NULL)
return (-1);
r_sort_b(a, ta, n, 0, tr, endch);
free(ta);
}
return (0);
}
#define empty(s) (s >= sp)
#define pop(a, n, i) a = (--sp)->sa, n = sp->sn, i = sp->si
#define push(a, n, i) sp->sa = a, sp->sn = n, (sp++)->si = i
#define swap(a, b, t) t = a, a = b, b = t
/* Unstable, in-place sort. */
static void
r_sort_a(a, n, i, tr, endch)
const u_char **a;
int n, i;
const u_char *tr;
u_int endch;
{
static int count[256], nc, bmin;
register int c;
register const u_char **ak, *r;
stack s[SIZE], *sp, *sp0, *sp1, temp;
int *cp, bigc;
const u_char **an, *t, **aj, **top[256];
/* Set up stack. */
sp = s;
push(a, n, i);
while (!empty(s)) {
pop(a, n, i);
if (n < THRESHOLD) {
simplesort(a, n, i, tr, endch);
continue;
}
an = a + n;
/* Make character histogram. */
if (nc == 0) {
bmin = 255; /* First occupied bin, excluding eos. */
for (ak = a; ak < an;) {
c = tr[(*ak++)[i]];
if (++count[c] == 1 && c != endch) {
if (c < bmin)
bmin = c;
nc++;
}
}
if (sp + nc > s + SIZE) { /* Get more stack. */
r_sort_a(a, n, i, tr, endch);
continue;
}
}
/*
* Set top[]; push incompletely sorted bins onto stack.
* top[] = pointers to last out-of-place element in bins.
* count[] = counts of elements in bins.
* Before permuting: top[c-1] + count[c] = top[c];
* during deal: top[c] counts down to top[c-1].
*/
sp0 = sp1 = sp; /* Stack position of biggest bin. */
bigc = 2; /* Size of biggest bin. */
if (endch == 0) /* Special case: set top[eos]. */
top[0] = ak = a + count[0];
else {
ak = a;
top[255] = an;
}
for (cp = count + bmin; nc > 0; cp++) {
while (*cp == 0) /* Find next non-empty pile. */
cp++;
if (*cp > 1) {
if (*cp > bigc) {
bigc = *cp;
sp1 = sp;
}
push(ak, *cp, i+1);
}
top[cp-count] = ak += *cp;
nc--;
}
swap(*sp0, *sp1, temp); /* Play it safe -- biggest bin last. */
/*
* Permute misplacements home. Already home: everything
* before aj, and in bin[c], items from top[c] on.
* Inner loop:
* r = next element to put in place;
* ak = top[r[i]] = location to put the next element.
* aj = bottom of 1st disordered bin.
* Outer loop:
* Once the 1st disordered bin is done, ie. aj >= ak,
* aj<-aj + count[c] connects the bins in a linked list;
* reset count[c].
*/
for (aj = a; aj < an; *aj = r, aj += count[c], count[c] = 0)
for (r = *aj; aj < (ak = --top[c = tr[r[i]]]);)
swap(*ak, r, t);
}
}
/* Stable sort, requiring additional memory. */
static void
r_sort_b(a, ta, n, i, tr, endch)
const u_char **a, **ta;
int n, i;
const u_char *tr;
u_int endch;
{
static int count[256], nc, bmin;
register int c;
register const u_char **ak, **ai;
stack s[512], *sp, *sp0, *sp1, temp;
const u_char **top[256];
int *cp, bigc;
sp = s;
push(a, n, i);
while (!empty(s)) {
pop(a, n, i);
if (n < THRESHOLD) {
simplesort(a, n, i, tr, endch);
continue;
}
if (nc == 0) {
bmin = 255;
for (ak = a + n; --ak >= a;) {
c = tr[(*ak)[i]];
if (++count[c] == 1 && c != endch) {
if (c < bmin)
bmin = c;
nc++;
}
}
if (sp + nc > s + SIZE) {
r_sort_b(a, ta, n, i, tr, endch);
continue;
}
}
sp0 = sp1 = sp;
bigc = 2;
if (endch == 0) {
top[0] = ak = a + count[0];
count[0] = 0;
} else {
ak = a;
top[255] = a + n;
count[255] = 0;
}
for (cp = count + bmin; nc > 0; cp++) {
while (*cp == 0)
cp++;
if ((c = *cp) > 1) {
if (c > bigc) {
bigc = c;
sp1 = sp;
}
push(ak, c, i+1);
}
top[cp-count] = ak += c;
*cp = 0; /* Reset count[]. */
nc--;
}
swap(*sp0, *sp1, temp);
for (ak = ta + n, ai = a+n; ak > ta;) /* Copy to temp. */
*--ak = *--ai;
for (ak = ta+n; --ak >= ta;) /* Deal to piles. */
*--top[tr[(*ak)[i]]] = *ak;
}
}
static inline void
simplesort(a, n, b, tr, endch) /* insertion sort */
register const u_char **a;
int n, b;
register const u_char *tr;
u_int endch;
{
register u_char ch;
const u_char **ak, **ai, *s, *t;
for (ak = a+1; --n >= 1; ak++)
for (ai = ak; ai > a; ai--) {
for (s = ai[0] + b, t = ai[-1] + b;
(ch = tr[*s]) != endch; s++, t++)
if (ch != tr[*t])
break;
if (ch >= tr[*t])
break;
swap(ai[0], ai[-1], s);
}
}

400
lib/libc/stdlib/random.c Normal file
View file

@ -0,0 +1,400 @@
/*
* Copyright (c) 1983, 1993
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#if defined(LIBC_SCCS) && !defined(lint)
static char sccsid[] = "@(#)random.c 8.2 (Berkeley) 5/19/95";
#endif /* LIBC_SCCS and not lint */
#include <stdio.h>
#include <stdlib.h>
/*
* random.c:
*
* An improved random number generation package. In addition to the standard
* rand()/srand() like interface, this package also has a special state info
* interface. The initstate() routine is called with a seed, an array of
* bytes, and a count of how many bytes are being passed in; this array is
* then initialized to contain information for random number generation with
* that much state information. Good sizes for the amount of state
* information are 32, 64, 128, and 256 bytes. The state can be switched by
* calling the setstate() routine with the same array as was initiallized
* with initstate(). By default, the package runs with 128 bytes of state
* information and generates far better random numbers than a linear
* congruential generator. If the amount of state information is less than
* 32 bytes, a simple linear congruential R.N.G. is used.
*
* Internally, the state information is treated as an array of longs; the
* zeroeth element of the array is the type of R.N.G. being used (small
* integer); the remainder of the array is the state information for the
* R.N.G. Thus, 32 bytes of state information will give 7 longs worth of
* state information, which will allow a degree seven polynomial. (Note:
* the zeroeth word of state information also has some other information
* stored in it -- see setstate() for details).
*
* The random number generation technique is a linear feedback shift register
* approach, employing trinomials (since there are fewer terms to sum up that
* way). In this approach, the least significant bit of all the numbers in
* the state table will act as a linear feedback shift register, and will
* have period 2^deg - 1 (where deg is the degree of the polynomial being
* used, assuming that the polynomial is irreducible and primitive). The
* higher order bits will have longer periods, since their values are also
* influenced by pseudo-random carries out of the lower bits. The total
* period of the generator is approximately deg*(2**deg - 1); thus doubling
* the amount of state information has a vast influence on the period of the
* generator. Note: the deg*(2**deg - 1) is an approximation only good for
* large deg, when the period of the shift register is the dominant factor.
* With deg equal to seven, the period is actually much longer than the
* 7*(2**7 - 1) predicted by this formula.
*
* Modified 28 December 1994 by Jacob S. Rosenberg.
* The following changes have been made:
* All references to the type u_int have been changed to unsigned long.
* All references to type int have been changed to type long. Other
* cleanups have been made as well. A warning for both initstate and
* setstate has been inserted to the effect that on Sparc platforms
* the 'arg_state' variable must be forced to begin on word boundaries.
* This can be easily done by casting a long integer array to char *.
* The overall logic has been left STRICTLY alone. This software was
* tested on both a VAX and Sun SpacsStation with exactly the same
* results. The new version and the original give IDENTICAL results.
* The new version is somewhat faster than the original. As the
* documentation says: "By default, the package runs with 128 bytes of
* state information and generates far better random numbers than a linear
* congruential generator. If the amount of state information is less than
* 32 bytes, a simple linear congruential R.N.G. is used." For a buffer of
* 128 bytes, this new version runs about 19 percent faster and for a 16
* byte buffer it is about 5 percent faster.
*/
/*
* For each of the currently supported random number generators, we have a
* break value on the amount of state information (you need at least this
* many bytes of state info to support this random number generator), a degree
* for the polynomial (actually a trinomial) that the R.N.G. is based on, and
* the separation between the two lower order coefficients of the trinomial.
*/
#define TYPE_0 0 /* linear congruential */
#define BREAK_0 8
#define DEG_0 0
#define SEP_0 0
#define TYPE_1 1 /* x**7 + x**3 + 1 */
#define BREAK_1 32
#define DEG_1 7
#define SEP_1 3
#define TYPE_2 2 /* x**15 + x + 1 */
#define BREAK_2 64
#define DEG_2 15
#define SEP_2 1
#define TYPE_3 3 /* x**31 + x**3 + 1 */
#define BREAK_3 128
#define DEG_3 31
#define SEP_3 3
#define TYPE_4 4 /* x**63 + x + 1 */
#define BREAK_4 256
#define DEG_4 63
#define SEP_4 1
/*
* Array versions of the above information to make code run faster --
* relies on fact that TYPE_i == i.
*/
#define MAX_TYPES 5 /* max number of types above */
static long degrees[MAX_TYPES] = { DEG_0, DEG_1, DEG_2, DEG_3, DEG_4 };
static long seps [MAX_TYPES] = { SEP_0, SEP_1, SEP_2, SEP_3, SEP_4 };
/*
* Initially, everything is set up as if from:
*
* initstate(1, &randtbl, 128);
*
* Note that this initialization takes advantage of the fact that srandom()
* advances the front and rear pointers 10*rand_deg times, and hence the
* rear pointer which starts at 0 will also end up at zero; thus the zeroeth
* element of the state information, which contains info about the current
* position of the rear pointer is just
*
* MAX_TYPES * (rptr - state) + TYPE_3 == TYPE_3.
*/
static long randtbl[DEG_3 + 1] = {
TYPE_3,
0x9a319039, 0x32d9c024, 0x9b663182, 0x5da1f342, 0xde3b81e0, 0xdf0a6fb5,
0xf103bc02, 0x48f340fb, 0x7449e56b, 0xbeb1dbb0, 0xab5c5918, 0x946554fd,
0x8c2e680f, 0xeb3d799f, 0xb11ee0b7, 0x2d436b86, 0xda672e2a, 0x1588ca88,
0xe369735d, 0x904f35f7, 0xd7158fd6, 0x6fa6f051, 0x616e6b96, 0xac94efdc,
0x36413f93, 0xc622c298, 0xf5a42ab8, 0x8a88d77b, 0xf5ad9d0e, 0x8999220b,
0x27fb47b9,
};
/*
* fptr and rptr are two pointers into the state info, a front and a rear
* pointer. These two pointers are always rand_sep places aparts, as they
* cycle cyclically through the state information. (Yes, this does mean we
* could get away with just one pointer, but the code for random() is more
* efficient this way). The pointers are left positioned as they would be
* from the call
*
* initstate(1, randtbl, 128);
*
* (The position of the rear pointer, rptr, is really 0 (as explained above
* in the initialization of randtbl) because the state table pointer is set
* to point to randtbl[1] (as explained below).
*/
static long *fptr = &randtbl[SEP_3 + 1];
static long *rptr = &randtbl[1];
/*
* The following things are the pointer to the state information table, the
* type of the current generator, the degree of the current polynomial being
* used, and the separation between the two pointers. Note that for efficiency
* of random(), we remember the first location of the state information, not
* the zeroeth. Hence it is valid to access state[-1], which is used to
* store the type of the R.N.G. Also, we remember the last location, since
* this is more efficient than indexing every time to find the address of
* the last element to see if the front and rear pointers have wrapped.
*/
static long *state = &randtbl[1];
static long rand_type = TYPE_3;
static long rand_deg = DEG_3;
static long rand_sep = SEP_3;
static long *end_ptr = &randtbl[DEG_3 + 1];
/*
* srandom:
*
* Initialize the random number generator based on the given seed. If the
* type is the trivial no-state-information type, just remember the seed.
* Otherwise, initializes state[] based on the given "seed" via a linear
* congruential generator. Then, the pointers are set to known locations
* that are exactly rand_sep places apart. Lastly, it cycles the state
* information a given number of times to get rid of any initial dependencies
* introduced by the L.C.R.N.G. Note that the initialization of randtbl[]
* for default usage relies on values produced by this routine.
*/
void
srandom(x)
unsigned long x;
{
register long i;
if (rand_type == TYPE_0)
state[0] = x;
else {
state[0] = x;
for (i = 1; i < rand_deg; i++)
state[i] = 1103515245 * state[i - 1] + 12345;
fptr = &state[rand_sep];
rptr = &state[0];
for (i = 0; i < 10 * rand_deg; i++)
(void)random();
}
}
/*
* initstate:
*
* Initialize the state information in the given array of n bytes for future
* random number generation. Based on the number of bytes we are given, and
* the break values for the different R.N.G.'s, we choose the best (largest)
* one we can and set things up for it. srandom() is then called to
* initialize the state information.
*
* Note that on return from srandom(), we set state[-1] to be the type
* multiplexed with the current value of the rear pointer; this is so
* successive calls to initstate() won't lose this information and will be
* able to restart with setstate().
*
* Note: the first thing we do is save the current state, if any, just like
* setstate() so that it doesn't matter when initstate is called.
*
* Returns a pointer to the old state.
*
* Note: The Sparc platform requires that arg_state begin on a long
* word boundary; otherwise a bus error will occur. Even so, lint will
* complain about mis-alignment, but you should disregard these messages.
*/
char *
initstate(seed, arg_state, n)
unsigned long seed; /* seed for R.N.G. */
char *arg_state; /* pointer to state array */
long n; /* # bytes of state info */
{
register char *ostate = (char *)(&state[-1]);
register long *long_arg_state = (long *) arg_state;
if (rand_type == TYPE_0)
state[-1] = rand_type;
else
state[-1] = MAX_TYPES * (rptr - state) + rand_type;
if (n < BREAK_0) {
(void)fprintf(stderr,
"random: not enough state (%ld bytes); ignored.\n", n);
return(0);
}
if (n < BREAK_1) {
rand_type = TYPE_0;
rand_deg = DEG_0;
rand_sep = SEP_0;
} else if (n < BREAK_2) {
rand_type = TYPE_1;
rand_deg = DEG_1;
rand_sep = SEP_1;
} else if (n < BREAK_3) {
rand_type = TYPE_2;
rand_deg = DEG_2;
rand_sep = SEP_2;
} else if (n < BREAK_4) {
rand_type = TYPE_3;
rand_deg = DEG_3;
rand_sep = SEP_3;
} else {
rand_type = TYPE_4;
rand_deg = DEG_4;
rand_sep = SEP_4;
}
state = (long *) (long_arg_state + 1); /* first location */
end_ptr = &state[rand_deg]; /* must set end_ptr before srandom */
srandom(seed);
if (rand_type == TYPE_0)
long_arg_state[0] = rand_type;
else
long_arg_state[0] = MAX_TYPES * (rptr - state) + rand_type;
return(ostate);
}
/*
* setstate:
*
* Restore the state from the given state array.
*
* Note: it is important that we also remember the locations of the pointers
* in the current state information, and restore the locations of the pointers
* from the old state information. This is done by multiplexing the pointer
* location into the zeroeth word of the state information.
*
* Note that due to the order in which things are done, it is OK to call
* setstate() with the same state as the current state.
*
* Returns a pointer to the old state information.
*
* Note: The Sparc platform requires that arg_state begin on a long
* word boundary; otherwise a bus error will occur. Even so, lint will
* complain about mis-alignment, but you should disregard these messages.
*/
char *
setstate(arg_state)
char *arg_state; /* pointer to state array */
{
register long *new_state = (long *) arg_state;
register long type = new_state[0] % MAX_TYPES;
register long rear = new_state[0] / MAX_TYPES;
char *ostate = (char *)(&state[-1]);
if (rand_type == TYPE_0)
state[-1] = rand_type;
else
state[-1] = MAX_TYPES * (rptr - state) + rand_type;
switch(type) {
case TYPE_0:
case TYPE_1:
case TYPE_2:
case TYPE_3:
case TYPE_4:
rand_type = type;
rand_deg = degrees[type];
rand_sep = seps[type];
break;
default:
(void)fprintf(stderr,
"random: state info corrupted; not changed.\n");
}
state = (long *) (new_state + 1);
if (rand_type != TYPE_0) {
rptr = &state[rear];
fptr = &state[(rear + rand_sep) % rand_deg];
}
end_ptr = &state[rand_deg]; /* set end_ptr too */
return(ostate);
}
/*
* random:
*
* If we are using the trivial TYPE_0 R.N.G., just do the old linear
* congruential bit. Otherwise, we do our fancy trinomial stuff, which is
* the same in all the other cases due to all the global variables that have
* been set up. The basic operation is to add the number at the rear pointer
* into the one at the front pointer. Then both pointers are advanced to
* the next location cyclically in the table. The value returned is the sum
* generated, reduced to 31 bits by throwing away the "least random" low bit.
*
* Note: the code takes advantage of the fact that both the front and
* rear pointers can't wrap on the same call by not testing the rear
* pointer if the front one has wrapped.
*
* Returns a 31-bit random number.
*/
long
random()
{
register long i;
register long *f, *r;
if (rand_type == TYPE_0) {
i = state[0];
state[0] = i = (i * 1103515245 + 12345) & 0x7fffffff;
} else {
/*
* Use local variables rather than static variables for speed.
*/
f = fptr; r = rptr;
*f += *r;
i = (*f >> 1) & 0x7fffffff; /* chucking least random bit */
if (++f >= end_ptr) {
f = state;
++r;
}
else if (++r >= end_ptr) {
r = state;
}
fptr = f; rptr = r;
}
return(i);
}

149
lib/libc/string/strmode.3 Normal file
View file

@ -0,0 +1,149 @@
.\" Copyright (c) 1990, 1991, 1993
.\" The Regents of the University of California. All rights reserved.
.\"
.\" Redistribution and use in source and binary forms, with or without
.\" modification, are permitted provided that the following conditions
.\" are met:
.\" 1. Redistributions of source code must retain the above copyright
.\" notice, this list of conditions and the following disclaimer.
.\" 2. Redistributions in binary form must reproduce the above copyright
.\" notice, this list of conditions and the following disclaimer in the
.\" documentation and/or other materials provided with the distribution.
.\" 3. All advertising materials mentioning features or use of this software
.\" must display the following acknowledgement:
.\" This product includes software developed by the University of
.\" California, Berkeley and its contributors.
.\" 4. Neither the name of the University nor the names of its contributors
.\" may be used to endorse or promote products derived from this software
.\" without specific prior written permission.
.\"
.\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
.\" ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
.\" SUCH DAMAGE.
.\"
.\" @(#)strmode.3 8.3 (Berkeley) 7/28/94
.\"
.Dd July 28, 1994
.Dt STRMODE 3
.Os
.Sh NAME
.Nm strmode
.Nd convert inode status information into a symbolic string
.Sh SYNOPSIS
.Fd #include <string.h>
.Ft void
.Fn strmode "mode_t mode" "char *bp"
.Sh DESCRIPTION
The
.Fn strmode
function
converts a file
.Fa mode
(the type and permission information associated with an inode, see
.Xr stat 2 )
into a symbolic string which is stored in the location referenced by
.Fa bp .
This stored string is eleven characters in length plus a trailing
.Dv NULL .
.Pp
The first character is the inode type, and will be one of the following:
.Pp
.Bl -tag -width flag -offset indent -compact
.It \-
regular file
.It b
block special
.It c
character special
.It d
directory
.It l
symbolic link
.It p
fifo
.It s
socket
.It w
whiteout
.It ?
unknown inode type
.El
.Pp
The next nine characters encode three sets of permissions, in three
characters each.
The first three characters are the permissions for the owner of the
file, the second three for the group the file belongs to, and the
third for the ``other'', or default, set of users.
.Pp
Permission checking is done as specifically as possible.
If read permission is denied to the owner of a file in the first set
of permissions, the owner of the file will not be able to read the file.
This is true even if the owner is in the file's group and the group
permissions allow reading or the ``other'' permissions allow reading.
.Pp
If the first character of the three character set is an ``r'', the file is
readable for that set of users; if a dash ``\-'', it is not readable.
.Pp
If the second character of the three character set is a ``w'', the file is
writable for that set of users; if a dash ``\-'', it is not writable.
.Pp
The third character is the first of the following characters that apply:
.Bl -tag -width xxxx
.It S
If the character is part of the owner permissions and the file is not
executable or the directory is not searchable by the owner, and the
set-user-id bit is set.
.It S
If the character is part of the group permissions and the file is not
executable or the directory is not searchable by the group, and the
set-group-id bit is set.
.It T
If the character is part of the other permissions and the file is not
executable or the directory is not searchable by others, and the ``sticky''
.Pq Dv S_ISVTX
bit is set.
.It s
If the character is part of the owner permissions and the file is
executable or the directory searchable by the owner, and the set-user-id
bit is set.
.It s
If the character is part of the group permissions and the file is
executable or the directory searchable by the group, and the set-group-id
bit is set.
.It t
If the character is part of the other permissions and the file is
executable or the directory searchable by others, and the ``sticky''
.Pq Dv S_ISVTX
bit is set.
.It x
The file is executable or the directory is searchable.
.It \-
None of the above apply.
.El
.Pp
The last character is a plus sign ``+'' if any there are any alternate
or additional access control methods associated with the inode, otherwise
it will be a space.
.Sh RETURN VALUES
The
.Fn strmode
function
always returns 0.
.Sh SEE ALSO
.Xr chmod 1 ,
.Xr find 1 ,
.Xr stat 2 ,
.Xr getmode 3 ,
.Xr setmode 3
.Sh HISTORY
The
.Fn strmode
function first appeared in 4.4BSD.

152
lib/libc/string/strmode.c Normal file
View file

@ -0,0 +1,152 @@
/*-
* Copyright (c) 1990, 1993
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#if defined(LIBC_SCCS) && !defined(lint)
static char sccsid[] = "@(#)strmode.c 8.3 (Berkeley) 8/15/94";
#endif /* LIBC_SCCS and not lint */
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
void
strmode(mode, p)
register mode_t mode;
register char *p;
{
/* print type */
switch (mode & S_IFMT) {
case S_IFDIR: /* directory */
*p++ = 'd';
break;
case S_IFCHR: /* character special */
*p++ = 'c';
break;
case S_IFBLK: /* block special */
*p++ = 'b';
break;
case S_IFREG: /* regular */
*p++ = '-';
break;
case S_IFLNK: /* symbolic link */
*p++ = 'l';
break;
case S_IFSOCK: /* socket */
*p++ = 's';
break;
#ifdef S_IFIFO
case S_IFIFO: /* fifo */
*p++ = 'p';
break;
#endif
#ifdef S_IFWHT
case S_IFWHT: /* whiteout */
*p++ = 'w';
break;
#endif
default: /* unknown */
*p++ = '?';
break;
}
/* usr */
if (mode & S_IRUSR)
*p++ = 'r';
else
*p++ = '-';
if (mode & S_IWUSR)
*p++ = 'w';
else
*p++ = '-';
switch (mode & (S_IXUSR | S_ISUID)) {
case 0:
*p++ = '-';
break;
case S_IXUSR:
*p++ = 'x';
break;
case S_ISUID:
*p++ = 'S';
break;
case S_IXUSR | S_ISUID:
*p++ = 's';
break;
}
/* group */
if (mode & S_IRGRP)
*p++ = 'r';
else
*p++ = '-';
if (mode & S_IWGRP)
*p++ = 'w';
else
*p++ = '-';
switch (mode & (S_IXGRP | S_ISGID)) {
case 0:
*p++ = '-';
break;
case S_IXGRP:
*p++ = 'x';
break;
case S_ISGID:
*p++ = 'S';
break;
case S_IXGRP | S_ISGID:
*p++ = 's';
break;
}
/* other */
if (mode & S_IROTH)
*p++ = 'r';
else
*p++ = '-';
if (mode & S_IWOTH)
*p++ = 'w';
else
*p++ = '-';
switch (mode & (S_IXOTH | S_ISVTX)) {
case 0:
*p++ = '-';
break;
case S_IXOTH:
*p++ = 'x';
break;
case S_ISVTX:
*p++ = 'T';
break;
case S_IXOTH | S_ISVTX:
*p++ = 't';
break;
}
*p++ = ' '; /* will be a '+' if ACL's implemented */
*p = '\0';
}

110
lib/libc/sys/Makefile.inc Normal file
View file

@ -0,0 +1,110 @@
# @(#)Makefile.inc 8.3 (Berkeley) 10/24/94
# sys sources
.PATH: ${.CURDIR}/${MACHINE}/sys ${.CURDIR}/sys
# modules with non-default implementations on at least one architecture:
SRCS+= Ovfork.s brk.s cerror.s exect.s fork.s pipe.s ptrace.s reboot.s \
sbrk.s setlogin.s sigpending.s sigprocmask.s sigreturn.s \
sigsuspend.s syscall.s
# glue to provide compatibility between GCC 1.X and 2.X
SRCS+= ftruncate.c lseek.c mmap.c truncate.c
# modules with default implementations on all architectures:
ASM= accept.o access.o acct.o adjtime.o bind.o chdir.o chflags.o chmod.o \
chown.o chroot.o close.o connect.o dup.o dup2.o execve.o fchdir.o \
fchflags.o fchmod.o fchown.o fcntl.o flock.o fpathconf.o fstat.o \
fstatfs.o fsync.o getdirentries.o getdtablesize.o getegid.o \
geteuid.o getfh.o getfsstat.o getgid.o getgroups.o getitimer.o \
getpeername.o getpgrp.o getpid.o getppid.o getpriority.o \
getrlimit.o getrusage.o getsockname.o getsockopt.o gettimeofday.o \
getuid.o ioctl.o kill.o ktrace.o lfs_bmapv.o lfs_markv.o \
lfs_segclean.o lfs_segwait.o link.o listen.o lstat.o \
madvise.o mincore.o mkdir.o mkfifo.o mknod.o mlock.o mount.o \
mprotect.o msync.o munlock.o munmap.o nfssvc.o open.o \
pathconf.o profil.o quotactl.o read.o \
readlink.o readv.o recvfrom.o recvmsg.o rename.o revoke.o rmdir.o \
select.o sendmsg.o sendto.o setegid.o seteuid.o setgid.o \
setgroups.o setitimer.o setpgid.o setpriority.o setrlimit.o \
setsid.o setsockopt.o settimeofday.o setuid.o shutdown.o \
sigaction.o sigaltstack.o socket.o socketpair.o stat.o statfs.o \
swapon.o symlink.o sync.o umask.o undelete.o unlink.o unmount.o \
utimes.o vadvise.o wait4.o write.o writev.o __syscall.o __sysctl.o
PSEUDO= _exit.o _getlogin.o
OBJS+= ${ASM} ${PSEUDO}
POBJS+= ${ASM:.o=.po} ${PSEUDO:.o=.po}
CLEANFILES+=${ASM} ${PSEUDO} ${POBJS}
${ASM}: ${.CURDIR}/${MACHINE}/SYS.h /usr/include/sys/syscall.h
@echo creating ${.PREFIX}.o ${.PREFIX}.po
@printf '#include "SYS.h"\nRSYSCALL(${.PREFIX})\n' | \
${CPP} ${CFLAGS:M-[ID]*} ${AINC} | ${AS} -o ${.PREFIX}.o
@${LD} -x -r ${.PREFIX}.o
@mv a.out ${.PREFIX}.o
@printf '#include "SYS.h"\nRSYSCALL(${.PREFIX})\n' | \
${CPP} -DPROF ${CFLAGS:M-[ID]*} ${AINC} | ${AS} -o ${.PREFIX}.po
@${LD} -x -r ${.PREFIX}.po
@mv a.out ${.PREFIX}.po
${PSEUDO}: ${.CURDIR}/${MACHINE}/SYS.h /usr/include/sys/syscall.h
@echo creating ${.PREFIX}.o ${.PREFIX}.po
@printf '#include "SYS.h"\nPSEUDO(${.PREFIX},${.PREFIX:S/_//})\n' | \
${CPP} ${CFLAGS:M-[ID]*} ${AINC} | ${AS} -o ${.PREFIX}.o
@${LD} -x -r ${.PREFIX}.o
@mv a.out ${.PREFIX}.o
@printf '#include "SYS.h"\nPSEUDO(${.PREFIX},${.PREFIX:S/_//})\n' | \
${CPP} -DPROF ${CFLAGS:M-[ID]*} ${AINC} | ${AS} -o ${.PREFIX}.po
@${LD} -x -r ${.PREFIX}.po
@mv a.out ${.PREFIX}.po
MAN2+= accept.0 access.0 acct.0 adjtime.0 bind.0 brk.0 chdir.0 chflags.0 \
chmod.0 chown.0 chroot.0 close.0 connect.0 dup.0 execve.0 _exit.0 \
fcntl.0 flock.0 fork.0 fsync.0 getdirentries.0 getdtablesize.0 \
getfh.0 getfsstat.0 getgid.0 getgroups.0 getitimer.0 getlogin.0 \
getpeername.0 getpgrp.0 getpid.0 getpriority.0 getrlimit.0 \
getrusage.0 getsockname.0 getsockopt.0 gettimeofday.0 getuid.0 \
intro.0 ioctl.0 kill.0 ktrace.0 link.0 listen.0 lseek.0 \
mkdir.0 mkfifo.0 mknod.0 madvise.0 mincore.0 mlock.0 mmap.0 \
mount.0 mprotect.0 msync.0 munmap.0 \
nfssvc.0 open.0 pathconf.0 pipe.0 profil.0 ptrace.0 quotactl.0 \
munmap.0 nfssvc.0 open.0 pipe.0 profil.0 ptrace.0 quotactl.0 \
read.0 readlink.0 reboot.0 recv.0 rename.0 revoke.0 rmdir.0 \
select.0 send.0 setgroups.0 setpgid.0 setsid.0 setuid.0 shutdown.0 \
sigaction.0 sigpending.0 sigprocmask.0 sigreturn.0 sigaltstack.0 \
sigstack.0 sigsuspend.0 socket.0 socketpair.0 stat.0 statfs.0 \
swapon.0 symlink.0 sync.0 syscall.0 truncate.0 umask.0 unlink.0 \
undelete.0 utimes.0 vfork.0 wait.0 write.0
MLINKS+=brk.2 sbrk.2
MLINKS+=dup.2 dup2.2
MLINKS+=chdir.2 fchdir.2
MLINKS+=chflags.2 fchflags.2
MLINKS+=chmod.2 fchmod.2
MLINKS+=chown.2 fchown.2
MLINKS+=getgid.2 getegid.2
MLINKS+=getitimer.2 setitimer.2
MLINKS+=getlogin.2 setlogin.2
MLINKS+=getpid.2 getppid.2
MLINKS+=getpriority.2 setpriority.2
MLINKS+=getrlimit.2 setrlimit.2
MLINKS+=getsockopt.2 setsockopt.2
MLINKS+=gettimeofday.2 settimeofday.2
MLINKS+=getuid.2 geteuid.2
MLINKS+=intro.2 errno.2
MLINKS+=lseek.2 seek.2
MLINKS+=mlock.2 munlock.2
MLINKS+=mount.2 unmount.2
MLINKS+=pathconf.2 fpathconf.2
MLINKS+=read.2 readv.2
MLINKS+=recv.2 recvfrom.2 recv.2 recvmsg.2
MLINKS+=send.2 sendmsg.2 send.2 sendto.2
MLINKS+=setuid.2 setegid.2 setuid.2 seteuid.2 setuid.2 setgid.2
MLINKS+=stat.2 fstat.2 stat.2 lstat.2
MLINKS+=statfs.2 fstatfs.2
MLINKS+=syscall.2 __syscall.2
MLINKS+=truncate.2 ftruncate.2
MLINKS+=wait.2 wait3.2 wait.2 wait4.2 wait.2 waitpid.2
MLINKS+=write.2 writev.2

147
lib/libc/sys/brk.2 Normal file
View file

@ -0,0 +1,147 @@
.\" Copyright (c) 1980, 1991, 1993
.\" The Regents of the University of California. All rights reserved.
.\"
.\" Redistribution and use in source and binary forms, with or without
.\" modification, are permitted provided that the following conditions
.\" are met:
.\" 1. Redistributions of source code must retain the above copyright
.\" notice, this list of conditions and the following disclaimer.
.\" 2. Redistributions in binary form must reproduce the above copyright
.\" notice, this list of conditions and the following disclaimer in the
.\" documentation and/or other materials provided with the distribution.
.\" 3. All advertising materials mentioning features or use of this software
.\" must display the following acknowledgement:
.\" This product includes software developed by the University of
.\" California, Berkeley and its contributors.
.\" 4. Neither the name of the University nor the names of its contributors
.\" may be used to endorse or promote products derived from this software
.\" without specific prior written permission.
.\"
.\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
.\" ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
.\" SUCH DAMAGE.
.\"
.\" @(#)brk.2 8.4 (Berkeley) 5/1/95
.\"
.Dd May 1, 1995
.Dt BRK 2
.Os BSD 4
.Sh NAME
.Nm brk ,
.Nm sbrk
.Nd change data segment size
.Sh SYNOPSIS
.Fd #include <sys/types.h>
.Ft char
.Fn *brk "const char *addr"
.Ft char *
.Fn *sbrk "int incr"
.Sh DESCRIPTION
.Bf -symbolic
The brk and sbrk functions are historical curiosities
left over from earlier days before the advent of virtual memory management.
.Ef
The
.Fn brk
function
sets the break or lowest address
of a process's data segment (uninitialized data) to
.Fa addr
(immediately above bss).
Data addressing is restricted between
.Fa addr
and the lowest stack pointer to the stack segment.
Memory is allocated by
.Fa brk
in page size pieces;
if
.Fa addr
is not evenly divisible by the system page size, it is
increased to the next page boundary.
.Pp
.\" The
.\" .Nm sbrk
.\" function
.\" allocates chunks of
.\" .Fa incr
.\" bytes
.\" to the process's data space
.\" and returns an address pointer.
.\" The
.\" .Xr malloc 3
.\" function utilizes
.\" .Nm sbrk .
.\" .Pp
The current value of the program break is reliably returned by
.Dq Li sbrk(0)
(see also
.Xr end 3 ) .
The
.Xr getrlimit 2
system call may be used to determine
the maximum permissible size of the
.Em data
segment;
it will not be possible to set the break
beyond the
.Em rlim_max
value returned from a call to
.Xr getrlimit ,
e.g.
.Dq etext + rlp\(->rlim_max.
(see
.Xr end 3
for the definition of
.Em etext ) .
.Sh RETURN VALUES
.Nm Brk
returns 0 if successful;
otherwise -1 with
.Va errno
set to indicate why the allocation failed.
.Nm Sbrk
returns a pointer to the base of the new storage if successful;
otherwise -1 with
.Va errno
set to indicate why the allocation failed.
.Sh ERRORS
.Xr Brk
or
.Xr sbrk
will fail and no additional memory will be allocated if
one of the following are true:
.Bl -tag -width [ENOMEM]
.It Bq Er ENOMEM
The limit, as set by
.Xr setrlimit 2 ,
was exceeded.
.It Bq Er ENOMEM
The maximum possible size of a data segment (compiled into the
system) was exceeded.
.It Bq Er ENOMEM
Insufficient space existed in the swap area
to support the expansion.
.El
.Sh SEE ALSO
.Xr execve 2 ,
.Xr getrlimit 2 ,
.Xr malloc 3 ,
.Xr end 3
.Sh BUGS
Setting the break may fail due to a temporary lack of
swap space. It is not possible to distinguish this
from a failure caused by exceeding the maximum size of
the data segment without consulting
.Xr getrlimit .
.Sh HISTORY
A
.Nm
function call appeared in Version 7 AT&T UNIX.

159
lib/libc/sys/chflags.2 Normal file
View file

@ -0,0 +1,159 @@
.\" Copyright (c) 1989, 1993
.\" The Regents of the University of California. All rights reserved.
.\"
.\" Redistribution and use in source and binary forms, with or without
.\" modification, are permitted provided that the following conditions
.\" are met:
.\" 1. Redistributions of source code must retain the above copyright
.\" notice, this list of conditions and the following disclaimer.
.\" 2. Redistributions in binary form must reproduce the above copyright
.\" notice, this list of conditions and the following disclaimer in the
.\" documentation and/or other materials provided with the distribution.
.\" 3. All advertising materials mentioning features or use of this software
.\" must display the following acknowledgement:
.\" This product includes software developed by the University of
.\" California, Berkeley and its contributors.
.\" 4. Neither the name of the University nor the names of its contributors
.\" may be used to endorse or promote products derived from this software
.\" without specific prior written permission.
.\"
.\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
.\" ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
.\" SUCH DAMAGE.
.\"
.\" @(#)chflags.2 8.3 (Berkeley) 5/2/95
.\"
.Dd May 2, 1995
.Dt CHFLAGS 2
.Os
.Sh NAME
.Nm chflags ,
.Nm fchflags
.Nd set file flags
.Sh SYNOPSIS
.Fd #include <sys/stat.h>
.Fd #include <unistd.h>
.Ft int
.Fn chflags "const char *path" "u_long flags"
.Ft int
.Fn fchflags "int fd" "u_long flags"
.Sh DESCRIPTION
The file whose name
is given by
.Fa path
or referenced by the descriptor
.Fa fd
has its flags changed to
.Fa flags .
.Pp
The flags specified are formed by
.Em or Ns 'ing
the following values
.Pp
.Bl -tag -width "SF_IMMUTABLE" -compact -offset indent
.It UF_NODUMP
Do not dump the file.
.It UF_IMMUTABLE
The file may not be changed.
.It UF_APPEND
The file may only be appended to.
.It UF_OPAQUE
The directory is opaque when viewed through a union stack.
.\".It ARCHIVED
.\"File is archived.
.It SF_IMMUTABLE
The file may not be changed.
.It SF_APPEND
The file may only be appended to.
.El
.Pp
The
.Dq UF_IMMUTABLE
and
.Dq UF_APPEND
flags may be set or unset by either the owner of a file or the super-user.
.Pp
The
.Dq SF_IMMUTABLE
and
.Dq SF_APPEND
flags may only be set or unset by the super-user.
Attempts by the non-super-user to set the super-user only flags
are silently ignored.
These flags may be set at any time, but normally may only be unset when
the system is in single-user mode.
(See
.Xr init 8
for details.)
.Sh RETURN VALUES
Upon successful completion, a value of 0 is returned.
Otherwise, -1 is returned and the global variable
.Va errno
is set to indicate the error.
.Sh ERRORS
.Fn Chflags
will fail it:
.Bl -tag -width Er
.It Bq Er ENOTDIR
A component of the path prefix is not a directory.
.It Bq Er EINVAL
The pathname contains a character with the high-order bit set.
.It Bq Er ENAMETOOLONG
A component of a pathname exceeded 255 characters,
or an entire path name exceeded 1023 characters.
.It Bq Er ENOENT
The named file does not exist.
.It Bq Er EACCES
Search permission is denied for a component of the path prefix.
.It Bq Er ELOOP
Too many symbolic links were encountered in translating the pathname.
.It Bq Er EPERM
The effective user ID does not match the owner of the file and
the effective user ID is not the super-user.
.It Bq Er EROFS
The named file resides on a read-only file system.
.It Bq Er EFAULT
.Fa Path
points outside the process's allocated address space.
.It Bq Er EIO
An
.Tn I/O
error occurred while reading from or writing to the file system.
.El
.Pp
.Fn Fchflags
will fail if:
.Bl -tag -width Er
.It Bq Er EBADF
The descriptor is not valid.
.It Bq Er EINVAL
.Fa Fd
refers to a socket, not to a file.
.It Bq Er EPERM
The effective user ID does not match the owner of the file and
the effective user ID is not the super-user.
.It Bq Er EROFS
The file resides on a read-only file system.
.It Bq Er EIO
An
.Tn I/O
error occurred while reading from or writing to the file system.
.El
.Sh SEE ALSO
.Xr chflags 1 ,
.Xr init 8 ,
.Xr mount_union 8
.Sh HISTORY
The
.Nm chflags
and
.Nm fchflags
functions first appeared in 4.4BSD.

268
lib/libc/sys/execve.2 Normal file
View file

@ -0,0 +1,268 @@
.\" Copyright (c) 1980, 1991, 1993
.\" The Regents of the University of California. All rights reserved.
.\"
.\" Redistribution and use in source and binary forms, with or without
.\" modification, are permitted provided that the following conditions
.\" are met:
.\" 1. Redistributions of source code must retain the above copyright
.\" notice, this list of conditions and the following disclaimer.
.\" 2. Redistributions in binary form must reproduce the above copyright
.\" notice, this list of conditions and the following disclaimer in the
.\" documentation and/or other materials provided with the distribution.
.\" 3. All advertising materials mentioning features or use of this software
.\" must display the following acknowledgement:
.\" This product includes software developed by the University of
.\" California, Berkeley and its contributors.
.\" 4. Neither the name of the University nor the names of its contributors
.\" may be used to endorse or promote products derived from this software
.\" without specific prior written permission.
.\"
.\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
.\" ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
.\" SUCH DAMAGE.
.\"
.\" @(#)execve.2 8.5 (Berkeley) 6/1/94
.\"
.Dd June 1, 1994
.Dt EXECVE 2
.Os BSD 4
.Sh NAME
.Nm execve
.Nd execute a file
.Sh SYNOPSIS
.Fd #include <unistd.h>
.Ft int
.Fn execve "const char *path" "char *const argv[]" "char *const envp[]"
.Sh DESCRIPTION
.Fn Execve
transforms the calling process into a new process.
The new process is constructed from an ordinary file,
whose name is pointed to by
.Fa path ,
called the
.Em new process file .
This file is either an executable object file,
or a file of data for an interpreter.
An executable object file consists of an identifying header,
followed by pages of data representing the initial program (text)
and initialized data pages. Additional pages may be specified
by the header to be initialized with zero data; see
.Xr a.out 5 .
.Pp
An interpreter file begins with a line of the form:
.Pp
.Bd -filled -offset indent -compact
.Sy \&#!
.Em interpreter
.Bq Em arg
.Ed
.Pp
When an interpreter file is
.\" was .Fn execve Ap d ,
\fBexecve\fP'd,
the system
.\" was .Fn execve Ap s
\fBexecve\fP's
runs the specified
.Em interpreter .
If the optional
.Em arg
is specified, it becomes the first argument to the
.Em interpreter ,
and the name of the originally
.\" was .Fn execve Ap d
\fBexecve\fP'd
file becomes the second argument;
otherwise, the name of the originally
.\" was .Fn execve Ap d
\fBexecve\fP'd
file becomes the first argument. The original arguments are shifted over to
become the subsequent arguments. The zeroth argument, normally the name of the
.\" was .Fn execve Ap d
\fBexecve\fP'd
file, is left unchanged.
.Pp
The argument
.Fa argv
is a pointer to a null-terminated array of
character pointers to null-terminated character strings.
These strings construct the argument list to be made available to the new
process. At least one argument must be present in
the array; by custom, the first element should be
the name of the executed program (for example, the last component of
.Fa path ) .
.Pp
The argument
.Fa envp
is also a pointer to a null-terminated array of
character pointers to null-terminated strings.
A pointer to this array is normally stored in the global variable
.Va environ.
These strings pass information to the
new process that is not directly an argument to the command (see
.Xr environ 7 ) .
.Pp
File descriptors open in the calling process image remain open in
the new process image, except for those for which the close-on-exec
flag is set (see
.Xr close 2
and
.Xr fcntl 2 ) .
Descriptors that remain open are unaffected by
.Fn execve .
.Pp
Signals set to be ignored in the calling process are set to be ignored in
the
new process. Signals which are set to be caught in the calling process image
are set to default action in the new process image.
Blocked signals remain blocked regardless of changes to the signal action.
The signal stack is reset to be undefined (see
.Xr sigaction 2
for more information).
.Pp
If the set-user-ID mode bit of the new process image file is set
(see
.Xr chmod 2 ) ,
the effective user ID of the new process image is set to the owner ID
of the new process image file.
If the set-group-ID mode bit of the new process image file is set,
the effective group ID of the new process image is set to the group ID
of the new process image file.
(The effective group ID is the first element of the group list.)
The real user ID, real group ID and
other group IDs of the new process image remain the same as the calling
process image.
After any set-user-ID and set-group-ID processing,
the effective user ID is recorded as the saved set-user-ID,
and the effective group ID is recorded as the saved set-group-ID.
These values may be used in changing the effective IDs later (see
.Xr setuid 2 ) .
.ne 1i
.Pp
The new process also inherits the following attributes from
the calling process:
.Pp
.Bl -column parent_process_ID -offset indent -compact
.It process ID Ta see Xr getpid 2
.It parent process ID Ta see Xr getppid 2
.It process group ID Ta see Xr getpgrp 2
.It access groups Ta see Xr getgroups 2
.It working directory Ta see Xr chdir 2
.It root directory Ta see Xr chroot 2
.It control terminal Ta see Xr termios 4
.It resource usages Ta see Xr getrusage 2
.It interval timers Ta see Xr getitimer 2
.It resource limits Ta see Xr getrlimit 2
.It file mode mask Ta see Xr umask 2
.It signal mask Ta see Xr sigvec 2 ,
.Xr sigsetmask 2
.El
.Pp
When a program is executed as a result of an
.Fn execve
call, it is entered as follows:
.Bd -literal -offset indent
main(argc, argv, envp)
int argc;
char **argv, **envp;
.Ed
.Pp
where
.Fa argc
is the number of elements in
.Fa argv
(the ``arg count'')
and
.Fa argv
points to the array of character pointers
to the arguments themselves.
.Sh RETURN VALUES
As the
.Fn execve
function overlays the current process image
with a new process image the successful call
has no process to return to.
If
.Fn execve
does return to the calling process an error has occurred; the
return value will be -1 and the global variable
.Va errno
is set to indicate the error.
.Sh ERRORS
.Fn Execve
will fail and return to the calling process if:
.Bl -tag -width [ENAMETOOLONG]
.It Bq Er ENOTDIR
A component of the path prefix is not a directory.
.It Bq Er EINVAL
The pathname contains a character with the high-order bit set.
.It Bq Er ENAMETOOLONG
A component of a pathname exceeded 255 characters,
or an entire path name exceeded 1023 characters.
.It Bq Er ENOENT
The new process file does not exist.
.It Bq Er ELOOP
Too many symbolic links were encountered in translating the pathname.
.It Bq Er EACCES
Search permission is denied for a component of the path prefix.
.It Bq Er EACCES
The new process file is not an ordinary file.
.It Bq Er EACCES
The new process file mode denies execute permission.
.It Bq Er ENOEXEC
The new process file has the appropriate access
permission, but has an invalid magic number in its header.
.It Bq Er ETXTBSY
The new process file is a pure procedure (shared text)
file that is currently open for writing or reading by some process.
.ne 1i
.It Bq Er ENOMEM
The new process requires more virtual memory than
is allowed by the imposed maximum
.Pq Xr getrlimit 2 .
.It Bq Er E2BIG
The number of bytes in the new process's argument list
is larger than the system-imposed limit.
The limit in the system as released is 20480 bytes
.Pf ( Dv NCARGS
in
.Ao Pa sys/param.h Ac .
.It Bq Er EFAULT
The new process file is not as long as indicated by
the size values in its header.
.It Bq Er EFAULT
.Fa Path ,
.Fa argv ,
or
.Fa envp
point
to an illegal address.
.It Bq Er EIO
An I/O error occurred while reading from the file system.
.El
.Sh CAVEAT
If a program is
.Em setuid
to a non-super-user, but is executed when
the real
.Em uid
is ``root'', then the program has some of the powers
of a super-user as well.
.Sh SEE ALSO
.Xr exit 2 ,
.Xr fork 2 ,
.Xr execl 3 ,
.Xr environ 7
.Sh HISTORY
The
.Nm
function call appeared in
.Bx 4.2 .

View file

@ -0,0 +1,158 @@
.\" Copyright (c) 1989, 1991, 1993
.\" The Regents of the University of California. All rights reserved.
.\"
.\" Redistribution and use in source and binary forms, with or without
.\" modification, are permitted provided that the following conditions
.\" are met:
.\" 1. Redistributions of source code must retain the above copyright
.\" notice, this list of conditions and the following disclaimer.
.\" 2. Redistributions in binary form must reproduce the above copyright
.\" notice, this list of conditions and the following disclaimer in the
.\" documentation and/or other materials provided with the distribution.
.\" 3. All advertising materials mentioning features or use of this software
.\" must display the following acknowledgement:
.\" This product includes software developed by the University of
.\" California, Berkeley and its contributors.
.\" 4. Neither the name of the University nor the names of its contributors
.\" may be used to endorse or promote products derived from this software
.\" without specific prior written permission.
.\"
.\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
.\" ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
.\" SUCH DAMAGE.
.\"
.\" @(#)getdirentries.2 8.2 (Berkeley) 5/3/95
.\"
.Dd May 3, 1995
.Dt GETDIRENTRIES 2
.Os
.Sh NAME
.Nm getdirentries
.Nd "get directory entries in a filesystem independent format"
.Sh SYNOPSIS
.Fd #include <sys/dirent.h>
.Ft int
.Fn getdirentries "int fd" "char *buf" "int nbytes" "long *basep"
.Sh DESCRIPTION
.Fn Getdirentries
reads directory entries from the directory
referenced by the file descriptor
.Fa fd
into the buffer pointed to by
.Fa buf ,
in a filesystem independent format.
Up to
.Fa nbytes
of data will be transferred.
.Fa Nbytes
must be greater than or equal to the
block size associated with the file,
see
.Xr stat 2 .
Some filesystems may not support
.Fn getdirentries
with buffers smaller than this size.
.Pp
The data in the buffer is a series of
.Em dirent
structures each containing the following entries:
.Bd -literal -offset indent
unsigned long d_fileno;
unsigned short d_reclen;
unsigned char d_type;
unsigned char d_namlen;
char d_name[MAXNAMELEN + 1]; /* see below */
.Ed
.Pp
The
.Fa d_fileno
entry is a number which is unique for each
distinct file in the filesystem.
Files that are linked by hard links (see
.Xr link 2 )
have the same
.Fa d_fileno .
The
.Fa d_reclen
entry is the length, in bytes, of the directory record.
The
.Fa d_type
entry is the type of the file pointed to by the directory record.
The file type values are defined in
.Fa <sys/dirent.h> .
The
.Fa d_name
entry contains a null terminated file name.
The
.Fa d_namlen
entry specifies the length of the file name excluding the null byte.
Thus the actual size of
.Fa d_name
may vary from 1 to
.Dv MAXNAMELEN
\&+ 1.
.Pp
Entries may be separated by extra space.
The
.Fa d_reclen
entry may be used as an offset from the start of a
.Fa dirent
structure to the next structure, if any.
.Pp
The actual number of bytes transferred is returned.
The current position pointer associated with
.Fa fd
is set to point to the next block of entries.
The pointer may not advance by the number of bytes returned by
.Fn getdirentries .
A value of zero is returned when
the end of the directory has been reached.
.Pp
.Fn Getdirentries
writes the position of the block read into the location pointed to by
.Fa basep .
Alternatively, the current position pointer may be set and retrieved by
.Xr lseek 2 .
The current position pointer should only be set to a value returned by
.Xr lseek 2 ,
a value returned in the location pointed to by
.Fa basep ,
or zero.
.Sh RETURN VALUES
If successful, the number of bytes actually transferred is returned.
Otherwise, -1 is returned and the global variable
.Va errno
is set to indicate the error.
.Sh ERRORS
.Fn Getdirentries
will fail if:
.Bl -tag -width [EFAULT]
.It EBADF
.Fa fd
is not a valid file descriptor open for reading.
.It EFAULT
Either
.Fa buf
or
.Fa basep
point outside the allocated address space.
.It EIO
An
.Tn I/O
error occurred while reading from or writing to the file system.
.El
.Sh SEE ALSO
.Xr open 2 ,
.Xr lseek 2
.Sh HISTORY
The
.Nm getdirentries
function first appeared in 4.4BSD.

165
lib/libc/sys/getfsstat.2 Normal file
View file

@ -0,0 +1,165 @@
.\" Copyright (c) 1989, 1991, 1993
.\" The Regents of the University of California. All rights reserved.
.\"
.\" Redistribution and use in source and binary forms, with or without
.\" modification, are permitted provided that the following conditions
.\" are met:
.\" 1. Redistributions of source code must retain the above copyright
.\" notice, this list of conditions and the following disclaimer.
.\" 2. Redistributions in binary form must reproduce the above copyright
.\" notice, this list of conditions and the following disclaimer in the
.\" documentation and/or other materials provided with the distribution.
.\" 3. All advertising materials mentioning features or use of this software
.\" must display the following acknowledgement:
.\" This product includes software developed by the University of
.\" California, Berkeley and its contributors.
.\" 4. Neither the name of the University nor the names of its contributors
.\" may be used to endorse or promote products derived from this software
.\" without specific prior written permission.
.\"
.\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
.\" ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
.\" SUCH DAMAGE.
.\"
.\" @(#)getfsstat.2 8.3 (Berkeley) 5/25/95
.\"
.Dd May 25, 1995
.Dt GETFSSTAT 2
.Os
.Sh NAME
.Nm getfsstat
.Nd get list of all mounted filesystems
.Sh SYNOPSIS
.Fd #include <sys/param.h>
.Fd #include <sys/ucred.h>
.Fd #include <sys/mount.h>
.Ft int
.Fn getfsstat "struct statfs *buf" "long bufsize" "int flags"
.Sh DESCRIPTION
.Fn Getfsstat
returns information about all mounted filesystems.
.Fa Buf
is a pointer to
.Xr statfs
structures defined as follows:
.Bd -literal
typedef quad fsid_t;
#define MFSNAMELEN 16 /* length of fs type name, including null */
#define MNAMELEN 90 /* length of buffer for returned name */
struct statfs {
short f_type; /* filesystem type number */
short f_flags; /* copy of mount flags */
long f_bsize; /* fundamental file system block size */
long f_iosize; /* optimal transfer block size */
long f_blocks; /* total data blocks in file system */
long f_bfree; /* free blocks in fs */
long f_bavail; /* free blocks avail to non-superuser */
long f_files; /* total file nodes in file system */
long f_ffree; /* free file nodes in fs */
fsid_t f_fsid; /* file system id */
uid_t f_owner; /* user that mounted the filesystem */
long f_spare[4]; /* spare for later */
char f_fstypename[MFSNAMELEN]; /* fs type name */
char f_mntonname[MNAMELEN]; /* directory on which mounted */
char f_mntfromname[MNAMELEN];/* mounted filesystem */
};
.Ed
.Pp
The flags that may be returned include:
.Bl -tag -width MNT_ASYNCHRONOUS
.It Dv MNT_RDONLY
The filesystem is mounted read-only;
Even the super-user may not write on it.
.It Dv MNT_NOEXEC
Files may not be executed from the filesystem.
.It Dv MNT_NOSUID
Setuid and setgid bits on files are not honored when they are executed.
.It Dv MNT_NODEV
Special files in the filesystem may not be opened.
.It Dv MNT_SYNCHRONOUS
All I/O to the filesystem is done synchronously.
.It Dv MNT_ASYNCHRONOUS
No filesystem I/O is done synchronously.
.It Dv MNT_LOCAL
The filesystem resides locally.
.It Dv MNT_QUOTA
The filesystem has quotas enabled on it.
.It Dv MNT_ROOTFS
Identifies the root filesystem.
.It Dv MNT_EXRDONLY
The filesystem is exported read-only.
.It Dv MNT_EXPORTED
The filesystem is exported for both reading and writing.
.It Dv MNT_DEFEXPORTED
The filesystem is exported for both reading and writing to any Internet host.
.It Dv MNT_EXPORTANON
The filesystem maps all remote accesses to the anonymous user.
.It Dv MNT_EXKERB
The filesystem is exported with Kerberos uid mapping.
.El
.Pp
Fields that are undefined for a particular filesystem are set to -1.
The buffer is filled with an array of
.Fa fsstat
structures, one for each mounted filesystem
up to the size specified by
.Fa bufsize .
.Pp
If
.Fa buf
is given as NULL,
.Fn getfsstat
returns just the number of mounted filesystems.
.Pp
Normally
.Fa flags
should be specified as
.Dv MNT_WAIT .
If
.Fa flags
is set to
.Dv MNT_NOWAIT ,
.Fn getfsstat
will return the information it has available without requesting
an update from each filesystem.
Thus, some of the information will be out of date, but
.Fn getfsstat
will not block waiting for information from a filesystem that is
unable to respond.
.Sh RETURN VALUES
Upon successful completion, the number of
.Fa fsstat
structures is returned.
Otherwise, -1 is returned and the global variable
.Va errno
is set to indicate the error.
.Sh ERRORS
.Fn Getfsstat
fails if one or more of the following are true:
.Bl -tag -width Er
.It EFAULT
.Fa Buf
points to an invalid address.
.It EIO
An
.Tn I/O
error occurred while reading from or writing to the filesystem.
.El
.Sh SEE ALSO
.Xr statfs 2 ,
.Xr fstab 5 ,
.Xr mount 8
.Sh HISTORY
The
.Nm getfsstat
function first appeared in 4.4BSD.

165
lib/libc/sys/getitimer.2 Normal file
View file

@ -0,0 +1,165 @@
.\" Copyright (c) 1983, 1991, 1993
.\" The Regents of the University of California. All rights reserved.
.\"
.\" Redistribution and use in source and binary forms, with or without
.\" modification, are permitted provided that the following conditions
.\" are met:
.\" 1. Redistributions of source code must retain the above copyright
.\" notice, this list of conditions and the following disclaimer.
.\" 2. Redistributions in binary form must reproduce the above copyright
.\" notice, this list of conditions and the following disclaimer in the
.\" documentation and/or other materials provided with the distribution.
.\" 3. All advertising materials mentioning features or use of this software
.\" must display the following acknowledgement:
.\" This product includes software developed by the University of
.\" California, Berkeley and its contributors.
.\" 4. Neither the name of the University nor the names of its contributors
.\" may be used to endorse or promote products derived from this software
.\" without specific prior written permission.
.\"
.\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
.\" ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
.\" SUCH DAMAGE.
.\"
.\" @(#)getitimer.2 8.3 (Berkeley) 5/16/95
.\"
.Dd May 16, 1995
.Dt GETITIMER 2
.Os BSD 4.2
.Sh NAME
.Nm getitimer ,
.Nm setitimer
.Nd get/set value of interval timer
.Sh SYNOPSIS
.Fd #include <sys/time.h>
.Fd #define ITIMER_REAL 0
.Fd #define ITIMER_VIRTUAL 1
.Fd #define ITIMER_PROF 2
.Ft int
.Fn getitimer "int which" "struct itimerval *value"
.Ft int
.Fn setitimer "int which" "struct itimerval *value" "struct itimerval *ovalue"
.Sh DESCRIPTION
The system provides each process with three interval timers,
defined in
.Ao Pa sys/time.h Ac .
The
.Fn getitimer
call returns the current value for the timer specified in
.Fa which
in the structure at
.Fa value .
The
.Fn setitimer
call sets a timer to the specified
.Fa value
(returning the previous value of the timer if
.Fa ovalue
is non-nil).
.Pp
A timer value is defined by the
.Fa itimerval
structure:
.Bd -literal -offset indent
struct itimerval {
struct timeval it_interval; /* timer interval */
struct timeval it_value; /* current value */
};
.Ed
.Pp
If
.Fa it_value
is non-zero, it indicates the time to the next timer expiration.
If
.Fa it_interval
is non-zero, it specifies a value to be used in reloading
.Fa it_value
when the timer expires.
Setting
.Fa it_value
to 0 disables a timer. Setting
.Fa it_interval
to 0 causes a timer to be disabled after its next expiration (assuming
.Fa it_value
is non-zero).
.Pp
Time values smaller than the resolution of the
system clock are rounded up to this resolution
(typically 10 milliseconds).
.Pp
The
.Dv ITIMER_REAL
timer decrements in real time. A
.Dv SIGALRM
signal is
delivered when this timer expires.
.Pp
The
.Dv ITIMER_VIRTUAL
timer decrements in process virtual time.
It runs only when the process is executing. A
.Dv SIGVTALRM
signal
is delivered when it expires.
.Pp
The
.Dv ITIMER_PROF
timer decrements both in process virtual time and
when the system is running on behalf of the process. It is designed
to be used by interpreters in statistically profiling the execution
of interpreted programs.
Each time the
.Dv ITIMER_PROF
timer expires, the
.Dv SIGPROF
signal is
delivered. Because this signal may interrupt in-progress
system calls, programs using this timer must be prepared to
restart interrupted system calls.
.Sh NOTES
Three macros for manipulating time values are defined in
.Ao Pa sys/time.h Ac .
.Fa Timerclear
sets a time value to zero,
.Fa timerisset
tests if a time value is non-zero, and
.Fa timercmp
compares two time values.
.Sh RETURN VALUES
If the calls succeed, a value of 0 is returned. If an error occurs,
the value -1 is returned, and a more precise error code is placed
in the global variable
.Va errno .
.Sh ERRORS
.Fn Getitimer
and
.Fn setitimer
will fail if:
.Bl -tag -width Er
.It Bq Er EFAULT
The
.Fa value
parameter specified a bad address.
.It Bq Er EINVAL
A
.Fa value
parameter specified a time that was too large
to be handled.
.El
.Sh SEE ALSO
.Xr select 2 ,
.Xr sigvec 2 ,
.Xr gettimeofday 2
.Sh HISTORY
The
.Nm
function call appeared in
.Bx 4.2 .

347
lib/libc/sys/getsockopt.2 Normal file
View file

@ -0,0 +1,347 @@
.\" Copyright (c) 1983, 1991, 1993
.\" The Regents of the University of California. All rights reserved.
.\"
.\" Redistribution and use in source and binary forms, with or without
.\" modification, are permitted provided that the following conditions
.\" are met:
.\" 1. Redistributions of source code must retain the above copyright
.\" notice, this list of conditions and the following disclaimer.
.\" 2. Redistributions in binary form must reproduce the above copyright
.\" notice, this list of conditions and the following disclaimer in the
.\" documentation and/or other materials provided with the distribution.
.\" 3. All advertising materials mentioning features or use of this software
.\" must display the following acknowledgement:
.\" This product includes software developed by the University of
.\" California, Berkeley and its contributors.
.\" 4. Neither the name of the University nor the names of its contributors
.\" may be used to endorse or promote products derived from this software
.\" without specific prior written permission.
.\"
.\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
.\" ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
.\" SUCH DAMAGE.
.\"
.\" @(#)getsockopt.2 8.4 (Berkeley) 5/2/95
.\"
.Dd May 2, 1995
.Dt GETSOCKOPT 2
.Os BSD 4.3r
.Sh NAME
.Nm getsockopt ,
.Nm setsockopt
.Nd get and set options on sockets
.Sh SYNOPSIS
.Fd #include <sys/types.h>
.Fd #include <sys/socket.h>
.Ft int
.Fn getsockopt "int s" "int level" "int optname" "void *optval" "int *optlen"
.Ft int
.Fn setsockopt "int s" "int level" "int optname" "const void *optval" "int optlen"
.Sh DESCRIPTION
.Fn Getsockopt
and
.Fn setsockopt
manipulate the
.Em options
associated with a socket. Options may exist at multiple
protocol levels; they are always present at the uppermost
.Dq socket
level.
.Pp
When manipulating socket options the level at which the
option resides and the name of the option must be specified.
To manipulate options at the socket level,
.Fa level
is specified as
.Dv SOL_SOCKET .
To manipulate options at any
other level the protocol number of the appropriate protocol
controlling the option is supplied. For example,
to indicate that an option is to be interpreted by the
.Tn TCP
protocol,
.Fa level
should be set to the protocol number of
.Tn TCP ;
see
.Xr getprotoent 3 .
.Pp
The parameters
.Fa optval
and
.Fa optlen
are used to access option values for
.Fn setsockopt .
For
.Fn getsockopt
they identify a buffer in which the value for the
requested option(s) are to be returned. For
.Fn getsockopt ,
.Fa optlen
is a value-result parameter, initially containing the
size of the buffer pointed to by
.Fa optval ,
and modified on return to indicate the actual size of
the value returned. If no option value is
to be supplied or returned,
.Fa optval
may be NULL.
.Pp
.Fa Optname
and any specified options are passed uninterpreted to the appropriate
protocol module for interpretation.
The include file
.Ao Pa sys/socket.h Ac
contains definitions for
socket level options, described below.
Options at other protocol levels vary in format and
name; consult the appropriate entries in
section
4 of the manual.
.Pp
Most socket-level options utilize an
.Fa int
parameter for
.Fa optval .
For
.Fn setsockopt ,
the parameter should be non-zero to enable a boolean option,
or zero if the option is to be disabled.
.Dv SO_LINGER
uses a
.Fa struct linger
parameter, defined in
.Ao Pa sys/socket.h Ac ,
which specifies the desired state of the option and the
linger interval (see below).
.Dv SO_SNDTIMEO
and
.Dv SO_RCVTIMEO
use a
.Fa struct timeval
parameter, defined in
.Ao Pa sys/time.h Ac .
.Pp
The following options are recognized at the socket level.
Except as noted, each may be examined with
.Fn getsockopt
and set with
.Fn setsockopt .
.Bl -column SO_OOBINLINE -offset indent
.It Dv SO_DEBUG Ta "enables recording of debugging information"
.It Dv SO_REUSEADDR Ta "enables local address reuse"
.It Dv SO_REUSEPORT Ta "enables duplicate address and port bindings"
.It Dv SO_KEEPALIVE Ta "enables keep connections alive"
.It Dv SO_DONTROUTE Ta "enables routing bypass for outgoing messages"
.It Dv SO_LINGER Ta "linger on close if data present"
.It Dv SO_BROADCAST Ta "enables permission to transmit broadcast messages"
.It Dv SO_OOBINLINE Ta "enables reception of out-of-band data in band"
.It Dv SO_SNDBUF Ta "set buffer size for output"
.It Dv SO_RCVBUF Ta "set buffer size for input"
.It Dv SO_SNDLOWAT Ta "set minimum count for output"
.It Dv SO_RCVLOWAT Ta "set minimum count for input"
.It Dv SO_SNDTIMEO Ta "set timeout value for output"
.It Dv SO_RCVTIMEO Ta "set timeout value for input"
.It Dv SO_TYPE Ta "get the type of the socket (get only)"
.It Dv SO_ERROR Ta "get and clear error on the socket (get only)"
.El
.Pp
.Dv SO_DEBUG
enables debugging in the underlying protocol modules.
.Dv SO_REUSEADDR
indicates that the rules used in validating addresses supplied
in a
.Xr bind 2
call should allow reuse of local addresses.
.Dv SO_REUSEPORT
allows completely duplicate bindings by multiple processes
if they all set
.Dv SO_REUSEPORT
before binding the port.
This option permits multiple instances of a program to each
receive UDP/IP multicast or broadcast datagrams destined for the bound port.
.Dv SO_KEEPALIVE
enables the
periodic transmission of messages on a connected socket. Should the
connected party fail to respond to these messages, the connection is
considered broken and processes using the socket are notified via a
.Dv SIGPIPE
signal when attempting to send data.
.Dv SO_DONTROUTE
indicates that outgoing messages should
bypass the standard routing facilities. Instead, messages are directed
to the appropriate network interface according to the network portion
of the destination address.
.Pp
.Dv SO_LINGER
controls the action taken when unsent messages
are queued on socket and a
.Xr close 2
is performed.
If the socket promises reliable delivery of data and
.Dv SO_LINGER is set,
the system will block the process on the
.Xr close
attempt until it is able to transmit the data or until it decides it
is unable to deliver the information (a timeout period, termed the
linger interval, is specified in seconds in the
.Fn setsockopt
call when
.Dv SO_LINGER
is requested).
If
.Dv SO_LINGER
is disabled and a
.Xr close
is issued, the system will process the close in a manner that allows
the process to continue as quickly as possible.
.Pp
The option
.Dv SO_BROADCAST
requests permission to send broadcast datagrams
on the socket.
Broadcast was a privileged operation in earlier versions of the system.
With protocols that support out-of-band data, the
.Dv SO_OOBINLINE
option
requests that out-of-band data be placed in the normal data input queue
as received; it will then be accessible with
.Xr recv
or
.Xr read
calls without the
.Dv MSG_OOB
flag.
Some protocols always behave as if this option is set.
.Dv SO_SNDBUF
and
.Dv SO_RCVBUF
are options to adjust the normal
buffer sizes allocated for output and input buffers, respectively.
The buffer size may be increased for high-volume connections,
or may be decreased to limit the possible backlog of incoming data.
The system places an absolute limit on these values.
.Pp
.Dv SO_SNDLOWAT
is an option to set the minimum count for output operations.
Most output operations process all of the data supplied
by the call, delivering data to the protocol for transmission
and blocking as necessary for flow control.
Nonblocking output operations will process as much data as permitted
subject to flow control without blocking, but will process no data
if flow control does not allow the smaller of the low water mark value
or the entire request to be processed.
A
.Xr select 2
operation testing the ability to write to a socket will return true
only if the low water mark amount could be processed.
The default value for
.Dv SO_SNDLOWAT
is set to a convenient size for network efficiency, often 1024.
.Dv SO_RCVLOWAT
is an option to set the minimum count for input operations.
In general, receive calls will block until any (non-zero) amount of data
is received, then return with the smaller of the amount available or the amount
requested.
The default value for
.Dv SO_RCVLOWAT
is 1.
If
.Dv SO_RCVLOWAT
is set to a larger value, blocking receive calls normally
wait until they have received the smaller of the low water mark value
or the requested amount.
Receive calls may still return less than the low water mark if an error
occurs, a signal is caught, or the type of data next in the receive queue
is different than that returned.
.Pp
.Dv SO_SNDTIMEO
is an option to set a timeout value for output operations.
It accepts a
.Fa struct timeval
parameter with the number of seconds and microseconds
used to limit waits for output operations to complete.
If a send operation has blocked for this much time,
it returns with a partial count
or with the error
.Er EWOULDBLOCK
if no data were sent.
In the current implementation, this timer is restarted each time additional
data are delivered to the protocol,
implying that the limit applies to output portions ranging in size
from the low water mark to the high water mark for output.
.Dv SO_RCVTIMEO
is an option to set a timeout value for input operations.
It accepts a
.Fa struct timeval
parameter with the number of seconds and microseconds
used to limit waits for input operations to complete.
In the current implementation, this timer is restarted each time additional
data are received by the protocol,
and thus the limit is in effect an inactivity timer.
If a receive operation has been blocked for this much time without
receiving additional data, it returns with a short count
or with the error
.Er EWOULDBLOCK
if no data were received.
.Pp
Finally,
.Dv SO_TYPE
and
.Dv SO_ERROR
are options used only with
.Fn getsockopt .
.Dv SO_TYPE
returns the type of the socket, such as
.Dv SOCK_STREAM ;
it is useful for servers that inherit sockets on startup.
.Dv SO_ERROR
returns any pending error on the socket and clears
the error status.
It may be used to check for asynchronous errors on connected
datagram sockets or for other asynchronous errors.
.Sh RETURN VALUES
A 0 is returned if the call succeeds, -1 if it fails.
.Sh ERRORS
The call succeeds unless:
.Bl -tag -width ENOPROTOOPTAA
.It Bq Er EBADF
The argument
.Fa s
is not a valid descriptor.
.It Bq Er ENOTSOCK
The argument
.Fa s
is a file, not a socket.
.It Bq Er ENOPROTOOPT
The option is unknown at the level indicated.
.It Bq Er EFAULT
The address pointed to by
.Fa optval
is not in a valid part of the process address space.
For
.Fn getsockopt ,
this error may also be returned if
.Fa optlen
is not in a valid part of the process address space.
.El
.Sh SEE ALSO
.Xr ioctl 2 ,
.Xr socket 2 ,
.Xr getprotoent 3
.Xr protocols 5
.Sh BUGS
Several of the socket options should be handled at lower levels of the system.
.Sh HISTORY
The
.Nm
system call appeared in
.Bx 4.2 .

127
lib/libc/sys/gettimeofday.2 Normal file
View file

@ -0,0 +1,127 @@
.\" Copyright (c) 1980, 1991, 1993
.\" The Regents of the University of California. All rights reserved.
.\"
.\" Redistribution and use in source and binary forms, with or without
.\" modification, are permitted provided that the following conditions
.\" are met:
.\" 1. Redistributions of source code must retain the above copyright
.\" notice, this list of conditions and the following disclaimer.
.\" 2. Redistributions in binary form must reproduce the above copyright
.\" notice, this list of conditions and the following disclaimer in the
.\" documentation and/or other materials provided with the distribution.
.\" 3. All advertising materials mentioning features or use of this software
.\" must display the following acknowledgement:
.\" This product includes software developed by the University of
.\" California, Berkeley and its contributors.
.\" 4. Neither the name of the University nor the names of its contributors
.\" may be used to endorse or promote products derived from this software
.\" without specific prior written permission.
.\"
.\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
.\" ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
.\" SUCH DAMAGE.
.\"
.\" @(#)gettimeofday.2 8.2 (Berkeley) 5/26/95
.\"
.Dd May 26, 1995
.Dt GETTIMEOFDAY 2
.Os BSD 4
.Sh NAME
.Nm gettimeofday ,
.Nm settimeofday
.Nd get/set date and time
.Sh SYNOPSIS
.Fd #include <sys/time.h>
.Ft int
.Fn gettimeofday "struct timeval *tp" "struct timezone *tzp"
.Ft int
.Fn settimeofday "struct timeval *tp" "struct timezone *tzp"
.Sh DESCRIPTION
.Bf -symbolic
Note: timezone is no longer used; this information is kept outside
the kernel.
.Ef
The system's notion of the current Greenwich time and the current time
zone is obtained with the
.Fn gettimeofday
call, and set with the
.Fn settimeofday
call. The time is expressed in seconds and microseconds
since midnight (0 hour), January 1, 1970. The resolution of the system
clock is hardware dependent, and the time may be updated continuously or
in ``ticks.'' If
.Fa tp
or
.Fa tzp
is NULL, the associated time
information will not be returned or set.
.Pp
The structures pointed to by
.Fa tp
and
.Fa tzp
are defined in
.Ao Pa sys/time.h Ac
as:
.Pp
.Bd -literal
struct timeval {
long tv_sec; /* seconds since Jan. 1, 1970 */
long tv_usec; /* and microseconds */
};
struct timezone {
int tz_minuteswest; /* of Greenwich */
int tz_dsttime; /* type of dst correction to apply */
};
.Ed
.Pp
The
.Fa timezone
structure indicates the local time zone
(measured in minutes of time westward from Greenwich),
and a flag that, if nonzero, indicates that
Daylight Saving time applies locally during
the appropriate part of the year.
.Pp
Only the super-user may set the time of day or time zone.
If the system is running in secure mode (see
.Xr init 8 ),
the time may only be advanced.
This limitation is imposed to prevent a malicious super-user
from setting arbitrary time stamps on files.
The system time can still be adjusted backwards using the
.Xr adjtime 2
system call even when the system is secure.
.Sh RETURN
A 0 return value indicates that the call succeeded.
A -1 return value indicates an error occurred, and in this
case an error code is stored into the global variable
.Va errno .
.Sh ERRORS
The following error codes may be set in
.Va errno :
.Bl -tag -width [EFAULT]
.It Bq Er EFAULT
An argument address referenced invalid memory.
.It Bq Er EPERM
A user other than the super-user attempted to set the time.
.El
.Sh SEE ALSO
.Xr date 1 ,
.Xr adjtime 2 ,
.Xr ctime 3 ,
.Xr timed 8
.Sh HISTORY
The
.Nm
function call appeared in
.Bx 4.2 .

674
lib/libc/sys/intro.2 Normal file
View file

@ -0,0 +1,674 @@
.\" Copyright (c) 1980, 1983, 1986, 1991, 1993
.\" The Regents of the University of California. All rights reserved.
.\"
.\" Redistribution and use in source and binary forms, with or without
.\" modification, are permitted provided that the following conditions
.\" are met:
.\" 1. Redistributions of source code must retain the above copyright
.\" notice, this list of conditions and the following disclaimer.
.\" 2. Redistributions in binary form must reproduce the above copyright
.\" notice, this list of conditions and the following disclaimer in the
.\" documentation and/or other materials provided with the distribution.
.\" 3. All advertising materials mentioning features or use of this software
.\" must display the following acknowledgement:
.\" This product includes software developed by the University of
.\" California, Berkeley and its contributors.
.\" 4. Neither the name of the University nor the names of its contributors
.\" may be used to endorse or promote products derived from this software
.\" without specific prior written permission.
.\"
.\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
.\" ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
.\" SUCH DAMAGE.
.\"
.\" @(#)intro.2 8.5 (Berkeley) 2/27/95
.\"
.Dd February 27, 1995
.Dt INTRO 2
.Os BSD 4
.Sh NAME
.Nm intro
.Nd introduction to system calls and error numbers
.Sh SYNOPSIS
.Fd #include <sys/errno.h>
.Sh DESCRIPTION
This section provides an overview of the system calls,
their error returns, and other common definitions and concepts.
.\".Pp
.\".Sy System call restart
.\".Pp
.\"<more later...>
.Sh DIAGNOSTICS
Nearly all of the system calls provide an error number in the external
variable
.Va errno ,
which is defined as:
.Pp
.Dl extern int errno
.Pp
When a system call detects an error,
it returns an integer value
indicating failure (usually -1)
and sets the variable
.Va errno
accordingly.
<This allows interpretation of the failure on receiving
a -1 and to take action accordingly.>
Successful calls never set
.Va errno ;
once set, it remains until another error occurs.
It should only be examined after an error.
Note that a number of system calls overload the meanings of these
error numbers, and that the meanings must be interpreted according
to the type and circumstances of the call.
.Pp
The following is a complete list of the errors and their
names as given in
.Aq Pa sys/errno.h .
.Bl -hang -width Ds
.It Er 0 Em "Error 0" .
Not used.
.It Er 1 EPERM Em "Operation not permitted" .
An attempt was made to perform an operation limited to processes
with appropriate privileges or to the owner of a file or other
resources.
.It Er 2 ENOENT Em "No such file or directory" .
A component of a specified pathname did not exist, or the
pathname was an empty string.
.It Er 3 ESRCH Em "No such process" .
No process could be found corresponding to that specified by the given
process ID.
.It Er 4 EINTR Em "Interrupted function call" .
An asynchronous signal (such as
.Dv SIGINT
or
.Dv SIGQUIT )
was caught by the process during the execution of an interruptible
function. If the signal handler performs a normal return, the
interrupted function call will seem to have returned the error condition.
.It Er 5 EIO Em "Input/output error" .
Some physical input or output error occurred.
This error will not be reported until a subsequent operation on the same file
descriptor and may be lost (over written) by any subsequent errors.
.It Er 6 ENXIO Em "\&No such device or address" .
Input or output on a special file referred to a device that did not
exist, or
made a request beyond the limits of the device.
This error may also occur when, for example,
a tape drive is not online or no disk pack is
loaded on a drive.
.It Er 7 E2BIG Em "Arg list too long" .
The number of bytes used for the argument and environment
list of the new process exceeded the current limit
of 20480 bytes
.Pf ( Dv NCARGS
in
.Aq Pa sys/param.h ) .
.It Er 8 ENOEXEC Em "Exec format error" .
A request was made to execute a file
that, although it has the appropriate permissions,
was not in the format required for an
executable file.
.It Er 9 EBADF Em "Bad file descriptor" .
A file descriptor argument was out of range, referred to no open file,
or a read (write) request was made to a file that was only open for
writing (reading).
.sp
.It Er 10 ECHILD Em "\&No child processes" .
A
.Xr wait
or
.Xr waitpid
function was executed by a process that had no existing or unwaited-for
child processes.
.It Er 11 EDEADLK Em "Resource deadlock avoided" .
An attempt was made to lock a system resource that
would have resulted in a deadlock situation.
.It Er 12 ENOMEM Em "Cannot allocate memory" .
The new process image required more memory than was allowed by the hardware
or by system-imposed memory management constraints.
A lack of swap space is normally temporary; however,
a lack of core is not.
Soft limits may be increased to their corresponding hard limits.
.It Er 13 EACCES Em "Permission denied" .
An attempt was made to access a file in a way forbidden
by its file access permissions.
.It Er 14 EFAULT Em "Bad address" .
The system detected an invalid address in attempting to
use an argument of a call.
.It Er 15 ENOTBLK Em "Not a block device" .
A block device operation was attempted on a non-block device or file.
.It Er 16 EBUSY Em "Resource busy" .
An attempt to use a system resource which was in use at the time
in a manner which would have conflicted with the request.
.It Er 17 EEXIST Em "File exists" .
An existing file was mentioned in an inappropriate context,
for instance, as the new link name in a
.Xr link
function.
.It Er 18 EXDEV Em "Improper link" .
A hard link to a file on another file system
was attempted.
.It Er 19 ENODEV Em "Operation not supported by device" .
An attempt was made to apply an inappropriate
function to a device,
for example,
trying to read a write-only device such as a printer.
.It Er 20 ENOTDIR Em "Not a directory" .
A component of the specified pathname existed, but it was
not a directory, when a directory was expected.
.It Er 21 EISDIR Em "Is a directory" .
An attempt was made to open a directory with write mode specified.
.It Er 22 EINVAL Em "Invalid argument" .
Some invalid argument was supplied. (For example,
specifying an undefined signal to a
.Xr signal
or
.Xr kill
function).
.It Er 23 ENFILE Em "Too many open files in system" .
Maximum number of file descriptors allowable on the system
has been reached and a requests for an open cannot be satisfied
until at least one has been closed.
.It Er 24 EMFILE Em "Too many open files" .
<As released, the limit on the number of
open files per process is 64.>
.Xr Getdtablesize 2
will obtain the current limit.
.It Er 25 ENOTTY Em "Inappropriate ioctl for device" .
A control function (see
.Xr ioctl 2 )
was attempted for a file or
special device for which the operation was inappropriate.
.It Er 26 ETXTBSY Em "Text file busy" .
The new process was a pure procedure (shared text) file
which was open for writing by another process, or
while the pure procedure file was being executed an
.Xr open
call requested write access.
.It Er 27 EFBIG Em "File too large" .
The size of a file exceeded the maximum (about
.if t 2\u\s-231\s+2\d
.if n 2.1E9
bytes).
.It Er 28 ENOSPC Em "Device out of space" .
A
.Xr write
to an ordinary file, the creation of a
directory or symbolic link, or the creation of a directory
entry failed because no more disk blocks were available
on the file system, or the allocation of an inode for a newly
created file failed because no more inodes were available
on the file system.
.It Er 29 ESPIPE Em "Illegal seek" .
An
.Xr lseek
function was issued on a socket, pipe or
.Tn FIFO .
.It Er 30 EROFS Em "Read-only file system" .
An attempt was made to modify a file or directory
was made
on a file system that was read-only at the time.
.It Er 31 EMLINK Em "Too many links" .
Maximum allowable hard links to a single file has been exceeded (limit
of 32767 hard links per file).
.It Er 32 EPIPE Em "Broken pipe" .
A write on a pipe, socket or
.Tn FIFO
for which there is no process
to read the data.
.It Er 33 EDOM Em "Numerical argument out of domain" .
A numerical input argument was outside the defined domain of the mathematical
function.
.It Er 34 ERANGE Em "Numerical result out of range" .
A numerical result of the function was too large to fit in the
available space (perhaps exceeded precision).
.It Er 35 EAGAIN Em "Resource temporarily unavailable" .
This is a temporary condition and later calls to the
same routine may complete normally.
.It Er 36 EINPROGRESS Em "Operation now in progress" .
An operation that takes a long time to complete (such as
a
.Xr connect 2 )
was attempted on a non-blocking object (see
.Xr fcntl 2 ) .
.It Er 37 EALREADY Em "Operation already in progress" .
An operation was attempted on a non-blocking object that already
had an operation in progress.
.It Er 38 ENOTSOCK Em "Socket operation on non-socket" .
Self-explanatory.
.It Er 39 EDESTADDRREQ Em "Destination address required" .
A required address was omitted from an operation on a socket.
.It Er 40 EMSGSIZE Em "Message too long" .
A message sent on a socket was larger than the internal message buffer
or some other network limit.
.It Er 41 EPROTOTYPE Em "Protocol wrong type for socket" .
A protocol was specified that does not support the semantics of the
socket type requested. For example, you cannot use the
.Tn ARPA
Internet
.Tn UDP
protocol with type
.Dv SOCK_STREAM .
.It Er 42 ENOPROTOOPT Em "Protocol not available" .
A bad option or level was specified in a
.Xr getsockopt 2
or
.Xr setsockopt 2
call.
.It Er 43 EPROTONOSUPPORT Em "Protocol not supported" .
The protocol has not been configured into the
system or no implementation for it exists.
.It Er 44 ESOCKTNOSUPPORT Em "Socket type not supported" .
The support for the socket type has not been configured into the
system or no implementation for it exists.
.It Er 45 EOPNOTSUPP Em "Operation not supported" .
The attempted operation is not supported for the type of object referenced.
Usually this occurs when a file descriptor refers to a file or socket
that cannot support this operation,
for example, trying to
.Em accept
a connection on a datagram socket.
.It Er 46 EPFNOSUPPORT Em "Protocol family not supported" .
The protocol family has not been configured into the
system or no implementation for it exists.
.It Er 47 EAFNOSUPPORT Em "Address family not supported by protocol family" .
An address incompatible with the requested protocol was used.
For example, you shouldn't necessarily expect to be able to use
.Tn NS
addresses with
.Tn ARPA
Internet protocols.
.It Er 48 EADDRINUSE Em "Address already in use" .
Only one usage of each address is normally permitted.
.sp
.It Er 49 EADDRNOTAVAIL Em "Cannot assign requested address" .
Normally results from an attempt to create a socket with an
address not on this machine.
.It Er 50 ENETDOWN Em "Network is down" .
A socket operation encountered a dead network.
.It Er 51 ENETUNREACH Em "Network is unreachable" .
A socket operation was attempted to an unreachable network.
.It Er 52 ENETRESET Em "Network dropped connection on reset" .
The host you were connected to crashed and rebooted.
.It Er 53 ECONNABORTED Em "Software caused connection abort" .
A connection abort was caused internal to your host machine.
.It Er 54 ECONNRESET Em "Connection reset by peer" .
A connection was forcibly closed by a peer. This normally
results from a loss of the connection on the remote socket
due to a timeout or a reboot.
.It Er 55 ENOBUFS Em "\&No buffer space available" .
An operation on a socket or pipe was not performed because
the system lacked sufficient buffer space or because a queue was full.
.It Er 56 EISCONN Em "Socket is already connected" .
A
.Xr connect
request was made on an already connected socket; or,
a
.Xr sendto
or
.Xr sendmsg
request on a connected socket specified a destination
when already connected.
.It Er 57 ENOTCONN Em "Socket is not connected" .
An request to send or receive data was disallowed because
the socket was not connected and (when sending on a datagram socket)
no address was supplied.
.It Er 58 ESHUTDOWN Em "Cannot send after socket shutdown" .
A request to send data was disallowed because the socket
had already been shut down with a previous
.Xr shutdown 2
call.
.It Er 60 ETIMEDOUT Em "Operation timed out" .
A
.Xr connect
or
.Xr send
request failed because the connected party did not
properly respond after a period of time. (The timeout
period is dependent on the communication protocol.)
.It Er 61 ECONNREFUSED Em "Connection refused" .
No connection could be made because the target machine actively
refused it. This usually results from trying to connect
to a service that is inactive on the foreign host.
.It Er 62 ELOOP Em "Too many levels of symbolic links" .
A path name lookup involved more than 8 symbolic links.
.It Er 63 ENAMETOOLONG Em "File name too long" .
A component of a path name exceeded 255
.Pq Dv MAXNAMELEN
characters, or an entire
path name exceeded 1023
.Pq Dv MAXPATHLEN Ns -1
characters.
.It Er 64 EHOSTDOWN Em "Host is down" .
A socket operation failed because the destination host was down.
.It Er 65 EHOSTUNREACH Em "No route to host" .
A socket operation was attempted to an unreachable host.
.It Er 66 ENOTEMPTY Em "Directory not empty" .
A directory with entries other than
.Ql \&.
and
.Ql \&..
was supplied to a remove directory or rename call.
.It Er 67 EPROCLIM Em "Too many processes" .
.It Er 68 EUSERS Em "Too many users" .
The quota system ran out of table entries.
.It Er 69 EDQUOT Em "Disc quota exceeded" .
A
.Xr write
to an ordinary file, the creation of a
directory or symbolic link, or the creation of a directory
entry failed because the user's quota of disk blocks was
exhausted, or the allocation of an inode for a newly
created file failed because the user's quota of inodes
was exhausted.
.ne 1i
.It Er 70 ESTALE Em "Stale NFS file handle" .
An attempt was made to access an open file (on an
.Tn NFS
filesystem)
which is now unavailable as referenced by the file descriptor.
This may indicate the file was deleted on the
.Tn NFS
server or some
other catastrophic event occurred.
.It Er 72 EBADRPC Em "RPC struct is bad" .
Exchange of
.Tn RPC
information was unsuccessful.
.It Er 73 ERPCMISMATCH Em "RPC version wrong" .
The version of
.Tn RPC
on the remote peer is not compatible with
the local version.
.It Er 74 EPROGUNAVAIL Em "RPC prog. not avail" .
The requested program is not registered on the remote host.
.It Er 75 EPROGMISMATCH Em "Program version wrong" .
The requested version of the program is not available
on the remote host
.Pq Tn RPC .
.It Er 76 EPROCUNAVAIL Em "Bad procedure for program" .
An
.Tn RPC
call was attempted for a procedure which doesn't exist
in the remote program.
.It Er 77 ENOLCK Em "No locks available" .
A system-imposed limit on the number of simultaneous file
locks was reached.
.It Er 78 ENOSYS Em "Function not implemented" .
Attempted a system call that is not available on this
system.
.Sh DEFINITIONS
.Bl -tag -width Ds
.It Process ID .
Each active process in the system is uniquely identified by a non-negative
integer called a process ID. The range of this ID is from 0 to 30000.
.It Parent process ID
A new process is created by a currently active process; (see
.Xr fork 2 ) .
The parent process ID of a process is initially the process ID of its creator.
If the creating process exits,
the parent process ID of each child is set to the ID of a system process,
.Xr init .
.It Process Group
Each active process is a member of a process group that is identified by
a non-negative integer called the process group ID. This is the process
ID of the group leader. This grouping permits the signaling of related
processes (see
.Xr termios 4 )
and the job control mechanisms of
.Xr csh 1 .
.It Session
A session is a set of one or more process groups.
A session is created by a successful call to
.Xr setsid 2 ,
which causes the caller to become the only member of the only process
group in the new session.
.It Session leader
A process that has created a new session by a successful call to
.Xr setsid 2 ,
is known as a session leader.
Only a session leader may acquire a terminal as its controlling terminal (see
.Xr termios 4 ) .
.It Controlling process
A session leader with a controlling terminal is a controlling process.
.It Controlling terminal
A terminal that is associated with a session is known as the controlling
terminal for that session and its members.
.ne 1i
.It "Terminal Process Group ID"
A terminal may be acquired by a session leader as its controlling terminal.
Once a terminal is associated with a session, any of the process groups
within the session may be placed into the foreground by setting
the terminal process group ID to the ID of the process group.
This facility is used
to arbitrate between multiple jobs contending for the same terminal;
(see
.Xr csh 1
and
.Xr tty 4 ) .
.It "Orphaned Process Group"
A process group is considered to be
.Em orphaned
if it is not under the control of a job control shell.
More precisely, a process group is orphaned
when none of its members has a parent process that is in the same session
as the group,
but is in a different process group.
Note that when a process exits, the parent process for its children
is changed to be
.Xr init ,
which is in a separate session.
Not all members of an orphaned process group are necessarily orphaned
processes (those whose creating process has exited).
The process group of a session leader is orphaned by definition.
.It "Real User ID and Real Group ID"
Each user on the system is identified by a positive integer
termed the real user ID.
.Pp
Each user is also a member of one or more groups.
One of these groups is distinguished from others and
used in implementing accounting facilities. The positive
integer corresponding to this distinguished group is termed
the real group ID.
.Pp
All processes have a real user ID and real group ID.
These are initialized from the equivalent attributes
of the process that created it.
.It "Effective User Id, Effective Group Id, and Group Access List"
Access to system resources is governed by two values:
the effective user ID, and the group access list.
The first member of the group access list is also known as the
effective group ID.
(In POSIX.1, the group access list is known as the set of supplementary
group IDs, and it is unspecified whether the effective group ID is
a member of the list.)
.Pp
The effective user ID and effective group ID are initially the
process's real user ID and real group ID respectively. Either
may be modified through execution of a set-user-ID or set-group-ID
file (possibly by one its ancestors) (see
.Xr execve 2 ) .
By convention, the effective group ID (the first member of the group access
list) is duplicated, so that the execution of a set-group-ID program
does not result in the loss of the original (real) group ID.
.Pp
The group access list is a set of group IDs
used only in determining resource accessibility. Access checks
are performed as described below in ``File Access Permissions''.
.It "Saved Set User ID and Saved Set Group ID"
When a process executes a new file, the effective user ID is set
to the owner of the file if the file is set-user-ID, and the effective
group ID (first element of the group access list) is set to the group
of the file if the file is set-group-ID.
The effective user ID of the process is then recorded as the saved set-user-ID,
and the effective group ID of the process is recorded as the saved set-group-ID.
These values may be used to regain those values as the effective user
or group ID after reverting to the real ID (see
.Xr setuid 2 ) .
(In POSIX.1, the saved set-user-ID and saved set-group-ID are optional,
and are used in setuid and setgid, but this does not work as desired
for the super-user.)
.It Super-user
A process is recognized as a
.Em super-user
process and is granted special privileges if its effective user ID is 0.
.ne 1i
.It Special Processes
The processes with process IDs of 0, 1, and 2 are special.
Process 0 is the scheduler. Process 1 is the initialization process
.Xr init ,
and is the ancestor of every other process in the system.
It is used to control the process structure.
Process 2 is the paging daemon.
.It Descriptor
An integer assigned by the system when a file is referenced
by
.Xr open 2
or
.Xr dup 2 ,
or when a socket is created by
.Xr pipe 2 ,
.Xr socket 2
or
.Xr socketpair 2 ,
which uniquely identifies an access path to that file or socket from
a given process or any of its children.
.It File Name
Names consisting of up to 255
.Pq Dv MAXNAMELEN
characters may be used to name
an ordinary file, special file, or directory.
.Pp
These characters may be selected from the set of all
.Tn ASCII
character
excluding 0 (NUL) and the
.Tn ASCII
code for
.Ql \&/
(slash). (The parity bit,
bit 7, must be 0.)
.Pp
Note that it is generally unwise to use
.Ql \&* ,
.Ql \&? ,
.Ql \&[
or
.Ql \&]
as part of
file names because of the special meaning attached to these characters
by the shell.
.It Path Name
A path name is a
.Tn NUL Ns -terminated
character string starting with an
optional slash
.Ql \&/ ,
followed by zero or more directory names separated
by slashes, optionally followed by a file name.
The total length of a path name must be less than 1024
.Pq Dv MAXPATHLEN
characters.
.Pp
If a path name begins with a slash, the path search begins at the
.Em root
directory.
Otherwise, the search begins from the current working directory.
A slash by itself names the root directory. An empty
pathname refers to the current directory.
.It Directory
A directory is a special type of file that contains entries
that are references to other files.
Directory entries are called links. By convention, a directory
contains at least two links,
.Ql \&.
and
.Ql \&.. ,
referred to as
.Em dot
and
.Em dot-dot
respectively. Dot refers to the directory itself and
dot-dot refers to its parent directory.
.It "Root Directory and Current Working Directory"
Each process has associated with it a concept of a root directory
and a current working directory for the purpose of resolving path
name searches. A process's root directory need not be the root
directory of the root file system.
.It File Access Permissions
Every file in the file system has a set of access permissions.
These permissions are used in determining whether a process
may perform a requested operation on the file (such as opening
a file for writing). Access permissions are established at the
time a file is created. They may be changed at some later time
through the
.Xr chmod 2
call.
.Pp
File access is broken down according to whether a file may be: read,
written, or executed. Directory files use the execute
permission to control if the directory may be searched.
.Pp
File access permissions are interpreted by the system as
they apply to three different classes of users: the owner
of the file, those users in the file's group, anyone else.
Every file has an independent set of access permissions for
each of these classes. When an access check is made, the system
decides if permission should be granted by checking the access
information applicable to the caller.
.Pp
Read, write, and execute/search permissions on
a file are granted to a process if:
.Pp
The process's effective user ID is that of the super-user. (Note:
even the super-user cannot execute a non-executable file.)
.Pp
The process's effective user ID matches the user ID of the owner
of the file and the owner permissions allow the access.
.Pp
The process's effective user ID does not match the user ID of the
owner of the file, and either the process's effective
group ID matches the group ID
of the file, or the group ID of the file is in
the process's group access list,
and the group permissions allow the access.
.Pp
Neither the effective user ID nor effective group ID
and group access list of the process
match the corresponding user ID and group ID of the file,
but the permissions for ``other users'' allow access.
.Pp
Otherwise, permission is denied.
.It Sockets and Address Families
.Pp
A socket is an endpoint for communication between processes.
Each socket has queues for sending and receiving data.
.Pp
Sockets are typed according to their communications properties.
These properties include whether messages sent and received
at a socket require the name of the partner, whether communication
is reliable, the format used in naming message recipients, etc.
.Pp
Each instance of the system supports some
collection of socket types; consult
.Xr socket 2
for more information about the types available and
their properties.
.Pp
Each instance of the system supports some number of sets of
communications protocols. Each protocol set supports addresses
of a certain format. An Address Family is the set of addresses
for a specific group of protocols. Each socket has an address
chosen from the address family in which the socket was created.
.Sh SEE ALSO
.Xr intro 3 ,
.Xr perror 3

214
lib/libc/sys/mmap.2 Normal file
View file

@ -0,0 +1,214 @@
.\" Copyright (c) 1991, 1993
.\" The Regents of the University of California. All rights reserved.
.\"
.\" Redistribution and use in source and binary forms, with or without
.\" modification, are permitted provided that the following conditions
.\" are met:
.\" 1. Redistributions of source code must retain the above copyright
.\" notice, this list of conditions and the following disclaimer.
.\" 2. Redistributions in binary form must reproduce the above copyright
.\" notice, this list of conditions and the following disclaimer in the
.\" documentation and/or other materials provided with the distribution.
.\" 3. All advertising materials mentioning features or use of this software
.\" must display the following acknowledgement:
.\" This product includes software developed by the University of
.\" California, Berkeley and its contributors.
.\" 4. Neither the name of the University nor the names of its contributors
.\" may be used to endorse or promote products derived from this software
.\" without specific prior written permission.
.\"
.\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
.\" ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
.\" SUCH DAMAGE.
.\"
.\" @(#)mmap.2 8.4 (Berkeley) 5/11/95
.\"
.Dd "May 11, 1995"
.Dt MMAP 2
.Os BSD 4
.Sh NAME
.Nm mmap
.Nd map files or devices into memory
.Sh SYNOPSIS
.Fd #include <sys/types.h>
.Fd #include <sys/mman.h>
.Ft caddr_t
.Fn mmap "caddr_t addr" "size_t len" "int prot" "int flags" "int fd" "off_t offset"
.Sh DESCRIPTION
The
.Nm mmap
function causes the pages starting at
.Fa addr
and continuing for at most
.Fa len
bytes to be mapped from the object described by
.Fa fd ,
starting at byte offset
.Fa offset .
If
.Fa len
is not a multiple of the pagesize, the mapped region may extend past the
specified range.
Any such extension beyond the end of the mapped object will be zero-filled.
.Pp
If
.Fa addr
is non-zero, it is used as a hint to the system.
(As a convenience to the system, the actual address of the region may differ
from the address supplied.)
If
.Fa addr
is zero, an address will be selected by the system.
The actual starting address of the region is returned.
A successful
.Fa mmap
deletes any previous mapping in the allocated address range.
.Pp
The protections (region accessibility) are specified in the
.Fa prot
argument by
.Em or Ns 'ing
the following values:
.Pp
.Bl -tag -width MAP_FIXEDX
.It Dv PROT_EXEC
Pages may be executed.
.It Dv PROT_READ
Pages may be read.
.It Dv PROT_WRITE
Pages may be written.
.El
.Pp
The
.Fa flags
parameter specifies the type of the mapped object, mapping options and
whether modifications made to the mapped copy of the page are private
to the process or are to be shared with other references.
Sharing, mapping type and options are specified in the
.Fa flags
argument by
.Em or Ns 'ing
the following values:
.Pp
.Bl -tag -width MAP_FIXEDX
.It Dv MAP_ANON
Map anonymous memory not associated with any specific file.
The file descriptor used for creating
.Dv MAP_ANON
must be \-1.
The
.Fa offset
parameter is ignored.
.\".It Dv MAP_FILE
.\"Mapped from a regular file or character-special device memory.
.It Dv MAP_FIXED
Do not permit the system to select a different address than the one
specified.
If the specified address cannot be used,
.Nm mmap
will fail.
If MAP_FIXED is specified,
.Fa addr
must be a multiple of the pagesize.
Use of this option is discouraged.
.It Dv MAP_HASSEMAPHORE
Notify the kernel that the region may contain semaphores and that special
handling may be necessary.
.It Dv MAP_INHERIT
Permit regions to be inherited across
.Xr exec 2
system calls.
.It Dv MAP_PRIVATE
Modifications are private.
.It Dv MAP_SHARED
Modifications are shared.
.El
.Pp
The
.Xr close 2
function does not unmap pages, see
.Xr munmap 2
for further information.
.Pp
The current design does not allow a process to specify the location of
swap space.
In the future we may define an additional mapping type,
.Dv MAP_SWAP ,
in which
the file descriptor argument specifies a file or device to which swapping
should be done.
.Sh RETURN VALUES
Upon successful completion,
.Nm mmap
returns a pointer to the mapped region.
Otherwise, a value of -1 is returned and
.Va errno
is set to indicate the error.
.Sh ERRORS
.Fn Mmap
will fail if:
.Bl -tag -width Er
.It Bq Er EACCES
The flag
.Dv PROT_READ
was specified as part of the
.Fa prot
parameter and
.Fa fd
was not open for reading.
The flags
.Dv MAP_SHARED
and
.Dv PROT_WRITE
were specified as part of the
.Fa flags
and
.Fa prot
parameters and
.Fa fd
was not open for writing.
.It Bq Er EBADF
.Fa Fd
is not a valid open file descriptor.
.It Bq Er EINVAL
.\"One of
.\".Dv MAP_ANON
.\"or
.\".Dv MAP_FILE
.\"was not specified as part of the
.\".Fa flags
.\"parameter.
.Dv MAP_FIXED
was specified and the
.Fa addr
parameter was not page aligned or was outside of the
valid address range for a process.
.Dv MAP_ANON was specified and
.Fa fd
was not \-1.
.Fa Fd
did not reference a regular or character special file.
.Fa Len
was less than zero.
.It Bq Er ENOMEM
.Dv MAP_FIXED
was specified and the
.Fa addr
parameter wasn't available.
.Dv MAP_ANON
was specified and insufficient memory was available.
.Sh "SEE ALSO"
.Xr getpagesize 2 ,
.Xr msync 2 ,
.Xr munmap 2 ,
.Xr mprotect 2 ,
.Xr madvise 2 ,
.Xr mincore 2

295
lib/libc/sys/mount.2 Normal file
View file

@ -0,0 +1,295 @@
.\" Copyright (c) 1980, 1989, 1993
.\" The Regents of the University of California. All rights reserved.
.\"
.\" Redistribution and use in source and binary forms, with or without
.\" modification, are permitted provided that the following conditions
.\" are met:
.\" 1. Redistributions of source code must retain the above copyright
.\" notice, this list of conditions and the following disclaimer.
.\" 2. Redistributions in binary form must reproduce the above copyright
.\" notice, this list of conditions and the following disclaimer in the
.\" documentation and/or other materials provided with the distribution.
.\" 3. All advertising materials mentioning features or use of this software
.\" must display the following acknowledgement:
.\" This product includes software developed by the University of
.\" California, Berkeley and its contributors.
.\" 4. Neither the name of the University nor the names of its contributors
.\" may be used to endorse or promote products derived from this software
.\" without specific prior written permission.
.\"
.\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
.\" ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
.\" SUCH DAMAGE.
.\"
.\" @(#)mount.2 8.3 (Berkeley) 5/24/95
.\"
.Dd May 24, 1995
.Dt MOUNT 2
.Os BSD 4
.Sh NAME
.Nm mount ,
.Nm unmount
.Nd mount or dismount a filesystem
.Sh SYNOPSIS
.Fd #include <sys/param.h>
.Fd #include <sys/mount.h>
.Ft int
.Fn mount "int type" "const char *dir" "int flags" "caddr_t data"
.Ft int
.Fn unmount "const char *dir" "int flags"
.Sh DESCRIPTION
The
.Fn mount
function grafts
a filesystem object onto the system file tree
at the point
.Ar dir .
The argument
.Ar data
describes the filesystem object to be mounted.
The argument
.Ar type
tells the kernel how to interpret
.Ar data
(See
.Ar type
below).
The contents of the filesystem
become available through the new mount point
.Ar dir .
Any files in
.Ar dir
at the time
of a successful mount are swept under the carpet so to speak, and
are unavailable until the filesystem is unmounted.
.Pp
The following
.Ar flags
may be specified to
suppress default semantics which affect filesystem access.
.Bl -tag -width MNT_SYNCHRONOUS
.It Dv MNT_RDONLY
The filesystem should be treated as read-only;
Even the super-user may not write on it.
.It Dv MNT_NOEXEC
Do not allow files to be executed from the filesystem.
.It Dv MNT_NOSUID
Do not honor setuid or setgid bits on files when executing them.
.It Dv MNT_NODEV
Do not interpret special files on the filesystem.
.It Dv MNT_SYNCHRONOUS
All I/O to the filesystem should be done synchronously.
.El
.Pp
The flag
.Dv MNT_UPDATE
indicates that the mount command is being applied
to an already mounted filesystem.
This allows the mount flags to be changed without requiring
that the filesystem be unmounted and remounted.
Some filesystems may not allow all flags to be changed.
For example,
most filesystems will not allow a change from read-write to read-only.
.Pp
The
.Fa type
argument names the filesystem.
The types of filesystems known to the system can be obtained with
.Xr sysctl 8
by using the command:
.Bd -literal -offset indent
sysctl vfs
.Ed
.Pp
.Fa Data
is a pointer to a structure that contains the type
specific arguments to mount.
The format for these argument structures is described in the
manual page for each filesystem.
By convention filesystem manual pages are named
by prefixing ``mount_'' to the name of the filesystem as returned by
.Xr sysctl 8 .
Thus the
.Nm NFS
filesystem is described by the
.Xr mount_nfs 8
manual page.
.Pp
The
.Fn umount
function call disassociates the filesystem from the specified
mount point
.Fa dir .
.Pp
The
.Fa flags
argument may specify
.Dv MNT_FORCE
to specify that the filesystem should be forcibly unmounted even if files are
still active.
Active special devices continue to work,
but any further accesses to any other active files result in errors
even if the filesystem is later remounted.
.Sh RETURN VALUES
The
.Fn mount
returns the value 0 if the mount was successful, otherwise -1 is returned
and the variable
.Va errno
is set to indicate the error.
.Pp
.Nm Umount
returns the value 0 if the umount succeeded; otherwise -1 is returned
and the variable
.Va errno
is set to indicate the error.
.Sh ERRORS
.Fn Mount
will fail when one of the following occurs:
.Bl -tag -width [ENOTBLK]
.It Bq Er EPERM
The caller is not the super-user.
.It Bq Er ENAMETOOLONG
A component of a pathname exceeded 255 characters,
or the entire length of a path name exceeded 1023 characters.
.It Bq Er ELOOP
Too many symbolic links were encountered in translating a pathname.
.It Bq Er ENOENT
A component of
.Fa dir
does not exist.
.It Bq Er ENOTDIR
A component of
.Ar name
is not a directory,
or a path prefix of
.Ar special
is not a directory.
.It Bq Er EINVAL
A pathname contains a character with the high-order bit set.
.It Bq Er EBUSY
Another process currently holds a reference to
.Fa dir .
.It Bq Er EFAULT
.Fa Dir
points outside the process's allocated address space.
.El
.Pp
The following errors can occur for a
.Em ufs
filesystem mount:
.Bl -tag -width [ENOTBLK]
.It Bq Er ENODEV
A component of ufs_args
.Ar fspec
does not exist.
.It Bq Er ENOTBLK
.Ar Fspec
is not a block device.
.It Bq Er ENXIO
The major device number of
.Ar fspec
is out of range (this indicates no device driver exists
for the associated hardware).
.It Bq Er EBUSY
.Ar Fspec
is already mounted.
.It Bq Er EMFILE
No space remains in the mount table.
.It Bq Er EINVAL
The super block for the filesystem had a bad magic
number or an out of range block size.
.It Bq Er ENOMEM
Not enough memory was available to read the cylinder
group information for the filesystem.
.It Bq Er EIO
An I/O error occurred while reading the super block or
cylinder group information.
.It Bq Er EFAULT
.Ar Fspec
points outside the process's allocated address space.
.El
.Pp
The following errors can occur for a
.Em nfs
filesystem mount:
.Bl -tag -width [ENOTBLK]
.It Bq Er ETIMEDOUT
.Em Nfs
timed out trying to contact the server.
.It Bq Er EFAULT
Some part of the information described by nfs_args
points outside the process's allocated address space.
.El
.Pp
The following errors can occur for a
.Em mfs
filesystem mount:
.Bl -tag -width [ENOTBLK]
.It Bq Er EMFILE
No space remains in the mount table.
.It Bq Er EINVAL
The super block for the filesystem had a bad magic
number or an out of range block size.
.It Bq Er ENOMEM
Not enough memory was available to read the cylinder
group information for the filesystem.
.It Bq Er EIO
A paging error occurred while reading the super block or
cylinder group information.
.It Bq Er EFAULT
.Em Name
points outside the process's allocated address space.
.El
.Pp
.Nm Umount
may fail with one of the following errors:
.Bl -tag -width [ENOTBLK]
.It Bq Er EPERM
The caller is not the super-user.
.It Bq Er ENOTDIR
A component of the path is not a directory.
.It Bq Er EINVAL
The pathname contains a character with the high-order bit set.
.It Bq Er ENAMETOOLONG
A component of a pathname exceeded 255 characters,
or an entire path name exceeded 1023 characters.
.It Bq Er ELOOP
Too many symbolic links were encountered in translating the pathname.
.It Bq Er EINVAL
The requested directory is not in the mount table.
.It Bq Er EBUSY
A process is holding a reference to a file located
on the filesystem.
.It Bq Er EIO
An I/O error occurred while writing cached filesystem information.
.It Bq Er EFAULT
.Fa Dir
points outside the process's allocated address space.
.El
.Pp
A
.Em ufs
or
.Em mfs
mount can also fail if the maximum number of filesystems are currently
mounted.
.Sh SEE ALSO
.Xr mount 8 ,
.Xr umount 8 ,
.Xr sysctl 8
.Sh BUGS
Some of the error codes need translation to more obvious messages.
.Sh HISTORY
.Fn Mount
and
.Fn umount
function calls appeared in Version 6 AT&T UNIX.

90
lib/libc/sys/msync.2 Normal file
View file

@ -0,0 +1,90 @@
.\" Copyright (c) 1991, 1993
.\" The Regents of the University of California. All rights reserved.
.\"
.\" Redistribution and use in source and binary forms, with or without
.\" modification, are permitted provided that the following conditions
.\" are met:
.\" 1. Redistributions of source code must retain the above copyright
.\" notice, this list of conditions and the following disclaimer.
.\" 2. Redistributions in binary form must reproduce the above copyright
.\" notice, this list of conditions and the following disclaimer in the
.\" documentation and/or other materials provided with the distribution.
.\" 3. All advertising materials mentioning features or use of this software
.\" must display the following acknowledgement:
.\" This product includes software developed by the University of
.\" California, Berkeley and its contributors.
.\" 4. Neither the name of the University nor the names of its contributors
.\" may be used to endorse or promote products derived from this software
.\" without specific prior written permission.
.\"
.\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
.\" ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
.\" SUCH DAMAGE.
.\"
.\" @(#)msync.2 8.2 (Berkeley) 6/21/94
.\"
.Dd June 21, 1994
.Dt MSYNC 2
.Os
.Sh NAME
.Nm msync
.Nd synchronize a mapped region
.Sh SYNOPSIS
.Fn msync "caddr_t addr" "int len"
.Sh DESCRIPTION
The
.Fn msync
system call
writes any modified pages back to the filesystem and updates
the file modification time.
If
.Fa len
is 0, all modified pages within the region containing
.Fa addr
will be flushed;
if
.Fa len
is non-zero, only the pages containing
.Fa addr
and
.Fa len
succeeding locations will be examined.
Any required synchronization of memory caches
will also take place at this time.
Filesystem operations on a file that is mapped for shared modifications
are unpredictable except after an
.Fn msync .
.Sh ERRORS
The following errors may be reported:
.Bl -tag -width Er
.It Bq Er EINVAL
The
.Fa addr
parameter was not page aligned.
.It Bq Er EINVAL
The
.Fa addr
parameter did not specify an address part of a mapped region.
.It Bq Er EINVAL
The
.Fa len
parameter was negative.
.It Bq Er EIO
An I/O error occured while writing to the file system.
.Sh SEE ALSO
.Xr madvise 2 ,
.Xr munmap 2 ,
.Xr mprotect 2 ,
.Xr mincore 2
.Sh HISTORY
The
.Fn msync
function first appeared in 4.4BSD.

78
lib/libc/sys/munmap.2 Normal file
View file

@ -0,0 +1,78 @@
.\" Copyright (c) 1991, 1993
.\" The Regents of the University of California. All rights reserved.
.\"
.\" Redistribution and use in source and binary forms, with or without
.\" modification, are permitted provided that the following conditions
.\" are met:
.\" 1. Redistributions of source code must retain the above copyright
.\" notice, this list of conditions and the following disclaimer.
.\" 2. Redistributions in binary form must reproduce the above copyright
.\" notice, this list of conditions and the following disclaimer in the
.\" documentation and/or other materials provided with the distribution.
.\" 3. All advertising materials mentioning features or use of this software
.\" must display the following acknowledgement:
.\" This product includes software developed by the University of
.\" California, Berkeley and its contributors.
.\" 4. Neither the name of the University nor the names of its contributors
.\" may be used to endorse or promote products derived from this software
.\" without specific prior written permission.
.\"
.\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
.\" ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
.\" SUCH DAMAGE.
.\"
.\" @(#)munmap.2 8.3 (Berkeley) 5/27/94
.\"
.Dd May 27, 1994
.Dt MUNMAP 2
.Os
.Sh NAME
.Nm munmap
.Nd remove a mapping
.Sh SYNOPSIS
.Fn munmap "caddr_t addr" "size_t len"
.Sh DESCRIPTION
The
.Fn munmap
system call
deletes the mappings for the specified address range,
and causes further references to addresses within the range
to generate invalid memory references.
.Sh RETURN VALUES
Upon successful completion,
.Nm munmap
returns zero.
Otherwise, a value of -1 is returned and
.Va errno
is set to indicate the error.
.Sh ERRORS
.Fn Munmap
will fail if:
.Bl -tag -width Er
.It Bq Er EINVAL
The
.Fa addr
parameter was not page aligned, the
.Fa len
parameter was negative, or
some part of the region being unmapped is outside the
valid address range for a process.
.Sh "SEE ALSO"
.Xr getpagesize 2 ,
.Xr msync 2 ,
.Xr munmap 2 ,
.Xr mprotect 2 ,
.Xr madvise 2 ,
.Xr mincore 2
.Sh HISTORY
The
.Fn munmap
function first appeared in 4.4BSD.

213
lib/libc/sys/quotactl.2 Normal file
View file

@ -0,0 +1,213 @@
.\" Copyright (c) 1983, 1990, 1991, 1993
.\" The Regents of the University of California. All rights reserved.
.\"
.\" This code is derived from software contributed to Berkeley by
.\" Robert Elz at The University of Melbourne.
.\"
.\" Redistribution and use in source and binary forms, with or without
.\" modification, are permitted provided that the following conditions
.\" are met:
.\" 1. Redistributions of source code must retain the above copyright
.\" notice, this list of conditions and the following disclaimer.
.\" 2. Redistributions in binary form must reproduce the above copyright
.\" notice, this list of conditions and the following disclaimer in the
.\" documentation and/or other materials provided with the distribution.
.\" 3. All advertising materials mentioning features or use of this software
.\" must display the following acknowledgement:
.\" This product includes software developed by the University of
.\" California, Berkeley and its contributors.
.\" 4. Neither the name of the University nor the names of its contributors
.\" may be used to endorse or promote products derived from this software
.\" without specific prior written permission.
.\"
.\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
.\" ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
.\" SUCH DAMAGE.
.\"
.\" @(#)quotactl.2 8.2 (Berkeley) 3/10/95
.\"
.Dd March 10, 1995
.Dt QUOTACTL 2
.Os
.Sh NAME
.Nm quotactl
.Nd manipulate filesystem quotas
.Sh SYNOPSIS
.Fd #include <ufs/quota.h> /* for ufs quotas */
.Ft int
.Fn quotactl "const char *path" "int cmd" "int id" "char *addr"
.Sh DESCRIPTION
The
.Fn quotactl
call enables, disables and
manipulates filesystem quotas.
A quota control command
given by
.Fa cmd
operates on the given filename
.Fa path
for the given user
.Fa id .
The address of an optional command specific data structure,
.Fa addr ,
may be given; its interpretation
is discussed below with each command.
.Pp
Currently quotas are supported only for the ``ufs'' filesystem.
For ``ufs'',
a command is composed of a primary command (see below)
and a command type used to interpret the
.Fa id .
Types are supported for interpretation of user identifiers
and group identifiers.
The ``ufs'' specific commands are:
.Bl -tag -width Q_QUOTAON
.It Dv Q_QUOTAON
Enable disk quotas for the filesystem specified by
.Fa path .
The command type specifies the type of the quotas being enabled.
The
.Fa addr
argument specifies a file from which to take the quotas.
The quota file must exist;
it is normally created with the
.Xr quotacheck 8
program.
The
.Fa id
argument is unused.
Only the super-user may turn quotas on.
.It Dv Q_QUOTAOFF
Disable disk quotas for the filesystem specified by
.Fa path .
The command type specifies the type of the quotas being disabled.
The
.Fa addr
and
.Fa id
arguments are unused.
Only the super-user may turn quotas off.
.It Dv Q_GETQUOTA
Get disk quota limits and current usage for the user or group
(as determined by the command type) with identifier
.Fa id .
.Fa Addr
is a pointer to a
.Fa struct dqblk
structure (defined in
.Ao Pa ufs/quota.h Ac ) .
.It Dv Q_SETQUOTA
Set disk quota limits for the user or group
(as determined by the command type) with identifier
.Fa id .
.Fa Addr
is a pointer to a
.Fa struct dqblk
structure (defined in
.Ao Pa ufs/quota.h Ac ) .
The usage fields of the
.Fa dqblk
structure are ignored.
This call is restricted to the super-user.
.It Dv Q_SETUSE
Set disk usage limits for the user or group
(as determined by the command type) with identifier
.Fa id .
.Fa Addr
is a pointer to a
.Fa struct dqblk
structure (defined in
.Ao Pa ufs/quota.h Ac ) .
Only the usage fields are used.
This call is restricted to the super-user.
.It Dv Q_SYNC
Update the on-disk copy of quota usages.
The command type specifies which type of quotas are to be updated.
The
.Fa id
and
.Fa addr
parameters are ignored.
.El
.Sh RETURN VALUES
A successful call returns 0,
otherwise the value -1 is returned and the global variable
.Va errno
indicates the reason for the failure.
.Sh ERRORS
A
.Fn quotactl
call will fail if:
.Bl -tag -width ENAMETOOLONGAA
.It Bq Er EOPNOTSUPP
The kernel has not been compiled with the
.Dv QUOTA
option.
.It Bq Er EUSERS
The quota table cannot be expanded.
.It Bq Er EINVAL
.Fa Cmd
or the command type is invalid.
.It Bq Er EINVAL
A pathname contains a character with the high-order bit set.
.It Bq Er EACCES
In
.Dv Q_QUOTAON ,
the quota file is not a plain file.
.It Bq Er EACCES
Search permission is denied for a component of a path prefix.
.It Bq Er ENOTDIR
A component of a path prefix was not a directory.
.It Bq Er ENAMETOOLONG
A component of either pathname exceeded 255 characters,
or the entire length of either path name exceeded 1023 characters.
.It Bq Er ENOENT
A filename does not exist.
.It Bq Er ELOOP
Too many symbolic links were encountered in translating a pathname.
.It Bq Er EROFS
In
.Dv Q_QUOTAON ,
the quota file resides on a read-only filesystem.
.It Bq Er EIO
An
.Tn I/O
error occurred while reading from or writing
to a file containing quotas.
.It Bq Er EFAULT
An invalid
.Fa addr
was supplied; the associated structure could not be copied in or out
of the kernel.
.It Bq Er EFAULT
.Fa Path
points outside the process's allocated address space.
.It Bq Er EPERM
The call was privileged and the caller was not the super-user.
.El
.Sh SEE ALSO
.Xr quota 1 ,
.Xr fstab 5 ,
.Xr edquota 8 ,
.Xr quotacheck 8 ,
.Xr quotaon 8 ,
.Xr repquota 8
.Sh BUGS
There should be some way to integrate this call with the resource
limit interface provided by
.Xr setrlimit 2
and
.Xr getrlimit 2 .
.Sh HISTORY
The
.Nm quotactl
function call appeared in
.Bx 4.3 Reno .

165
lib/libc/sys/sigaltstack.2 Normal file
View file

@ -0,0 +1,165 @@
.\" Copyright (c) 1983, 1991, 1992, 1993
.\" The Regents of the University of California. All rights reserved.
.\"
.\" Redistribution and use in source and binary forms, with or without
.\" modification, are permitted provided that the following conditions
.\" are met:
.\" 1. Redistributions of source code must retain the above copyright
.\" notice, this list of conditions and the following disclaimer.
.\" 2. Redistributions in binary form must reproduce the above copyright
.\" notice, this list of conditions and the following disclaimer in the
.\" documentation and/or other materials provided with the distribution.
.\" 3. All advertising materials mentioning features or use of this software
.\" must display the following acknowledgement:
.\" This product includes software developed by the University of
.\" California, Berkeley and its contributors.
.\" 4. Neither the name of the University nor the names of its contributors
.\" may be used to endorse or promote products derived from this software
.\" without specific prior written permission.
.\"
.\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
.\" ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
.\" SUCH DAMAGE.
.\"
.\" @(#)sigaltstack.2 8.2 (Berkeley) 5/1/95
.\"
.Dd May 1, 1995
.Dt SIGALTSTACK 2
.Os BSD 4.2
.Sh NAME
.Nm sigaltstack
.Nd set and/or get signal stack context
.Sh SYNOPSIS
.Fd #include <sys/types.h>
.Fd #include <signal.h>
.Bd -literal
struct sigaltstack {
caddr_t ss_base;
long ss_size;
int ss_flags;
};
.Ed
.Ft int
.Fn sigaltstack "const struct sigaltstack *ss" "struct sigaltstack *oss"
.Sh DESCRIPTION
.Fn Sigaltstack
allows users to define an alternate stack on which signals
are to be processed.
If
.Fa ss
is non-zero,
it specifies a pointer to and the size of a
.Em "signal stack"
on which to deliver signals,
and tells the system if the process is currently executing
on that stack.
When a signal's action indicates its handler
should execute on the signal stack (specified with a
.Xr sigaction 2
call), the system checks to see
if the process is currently executing on that stack.
If the process is not currently executing on the signal stack,
the system arranges a switch to the signal stack for the
duration of the signal handler's execution.
.Pp
If
.Dv SA_DISABLE
is set in
.Fa ss_flags ,
.Fa ss_base
and
.Fa ss_size
are ignored and the signal stack will be disabled.
Trying to disable an active stack will cause
.Nm
to return -1 with
.Va errno
set to
.Dv EINVAL .
A disabled stack will cause all signals to be
taken on the regular user stack.
If the stack is later re-enabled then all signals that were specified
to be processed on an alternate stack will resume doing so.
.Pp
If
.Fa oss
is non-zero, the current signal stack state is returned.
The
.Fa ss_flags
field will contain the value
.Dv SA_ONSTACK
if the process is currently on a signal stack and
.Dv SA_DISABLE
if the signal stack is currently disabled.
.Sh NOTES
The value
.Dv SIGSTKSZ
is defined to be the number of bytes/chars that would be used to cover
the usual case when allocating an alternate stack area.
The following code fragment is typically used to allocate an alternate stack.
.Bd -literal -offset indent
if ((sigstk.ss_base = malloc(SIGSTKSZ)) == NULL)
/* error return */
sigstk.ss_size = SIGSTKSZ;
sigstk.ss_flags = 0;
if (sigaltstack(&sigstk,0) < 0)
perror("sigaltstack");
.Ed
An alternative approach is provided for programs with signal handlers
that require a specific amount of stack space other than the default size.
The value
.Dv MINSIGSTKSZ
is defined to be the number of bytes/chars that is required by
the operating system to implement the alternate stack feature.
In computing an alternate stack size,
programs should add
.Dv MINSIGSTKSZ
to their stack requirements to allow for the operating system overhead.
.Pp
Signal stacks are automatically adjusted for the direction of stack
growth and alignment requirements.
Signal stacks may or may not be protected by the hardware and
are not ``grown'' automatically as is done for the normal stack.
If the stack overflows and this space is not protected
unpredictable results may occur.
.Sh RETURN VALUES
Upon successful completion, a value of 0 is returned.
Otherwise, a value of -1 is returned and
.Va errno
is set to indicate the error.
.Sh ERRORS
.Fn Sigstack
will fail and the signal stack context will remain unchanged
if one of the following occurs.
.Bl -tag -width [ENOMEM]
.It Bq Er EFAULT
Either
.Fa ss
or
.Fa oss
points to memory that is not a valid part of the process
address space.
.It Bq Er EINVAL
An attempt was made to disable an active stack.
.It Bq Er ENOMEM
Size of alternate stack area is less than or equal to
.Dv MINSIGSTKSZ .
.El
.Sh SEE ALSO
.Xr sigaction 2 ,
.Xr setjmp 3
.Sh HISTORY
The predecessor to
.Nm sigaltstack ,
the
.Fn sigstack
system call, appeared in
.Bx 4.2 .

80
lib/libc/sys/sigsuspend.2 Normal file
View file

@ -0,0 +1,80 @@
.\" Copyright (c) 1983, 1991, 1993
.\" The Regents of the University of California. All rights reserved.
.\"
.\" Redistribution and use in source and binary forms, with or without
.\" modification, are permitted provided that the following conditions
.\" are met:
.\" 1. Redistributions of source code must retain the above copyright
.\" notice, this list of conditions and the following disclaimer.
.\" 2. Redistributions in binary form must reproduce the above copyright
.\" notice, this list of conditions and the following disclaimer in the
.\" documentation and/or other materials provided with the distribution.
.\" 3. All advertising materials mentioning features or use of this software
.\" must display the following acknowledgement:
.\" This product includes software developed by the University of
.\" California, Berkeley and its contributors.
.\" 4. Neither the name of the University nor the names of its contributors
.\" may be used to endorse or promote products derived from this software
.\" without specific prior written permission.
.\"
.\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
.\" ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
.\" SUCH DAMAGE.
.\"
.\" @(#)sigsuspend.2 8.2 (Berkeley) 5/16/95
.\"
.Dd May 16, 1995
.Dt SIGSUSPEND 2
.Os
.Sh NAME
.Nm sigsuspend
.Nd atomically release blocked signals and wait for interrupt
.Sh SYNOPSIS
.Fd #include <signal.h>
.Ft int
.Fn sigsuspend "const sigset_t *sigmask"
.Sh DESCRIPTION
.Fn Sigsuspend
temporarily changes the blocked signal mask to the set to which
.Fa sigmask
points,
and then waits for a signal to arrive;
on return the previous set of masked signals is restored.
The signal mask set
is usually empty to indicate that all
signals are to be unblocked for the duration of the call.
.Pp
In normal usage, a signal is blocked using
.Xr sigprocmask 2
to begin a critical section, variables modified on the occurrence
of the signal are examined to determine that there is no work
to be done, and the process pauses awaiting work by using
.Fn sigsuspend
with the previous mask returned by
.Xr sigprocmask .
.Sh RETURN VALUES
The
.Fn sigsuspend
function
always terminates by being interrupted, returning -1 with
.Va errno
set to
.Dv EINTR .
.Sh SEE ALSO
.Xr sigprocmask 2 ,
.Xr sigaction 2 ,
.Xr sigsetops 3
.Sh STANDARDS
The
.Nm sigsuspend
function call
conforms to
.St -p1003.1-88 .

266
lib/libc/sys/stat.2 Normal file
View file

@ -0,0 +1,266 @@
.\" Copyright (c) 1980, 1991, 1993, 1994
.\" The Regents of the University of California. All rights reserved.
.\"
.\" Redistribution and use in source and binary forms, with or without
.\" modification, are permitted provided that the following conditions
.\" are met:
.\" 1. Redistributions of source code must retain the above copyright
.\" notice, this list of conditions and the following disclaimer.
.\" 2. Redistributions in binary form must reproduce the above copyright
.\" notice, this list of conditions and the following disclaimer in the
.\" documentation and/or other materials provided with the distribution.
.\" 3. All advertising materials mentioning features or use of this software
.\" must display the following acknowledgement:
.\" This product includes software developed by the University of
.\" California, Berkeley and its contributors.
.\" 4. Neither the name of the University nor the names of its contributors
.\" may be used to endorse or promote products derived from this software
.\" without specific prior written permission.
.\"
.\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
.\" ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
.\" SUCH DAMAGE.
.\"
.\" @(#)stat.2 8.4 (Berkeley) 5/1/95
.\"
.Dd May 1, 1995
.Dt STAT 2
.Os BSD 4
.Sh NAME
.Nm stat ,
.Nm lstat ,
.Nm fstat
.Nd get file status
.Sh SYNOPSIS
.Fd #include <sys/types.h>
.Fd #include <sys/stat.h>
.Ft int
.Fn stat "const char *path" "struct stat *sb"
.Ft int
.Fn lstat "const char *path" "struct stat *sb"
.Ft int
.Fn fstat "int fd" "struct stat *sb"
.Sh DESCRIPTION
The
.Fn stat
function obtains information about the file pointed to by
.Fa path .
Read, write or execute
permission of the named file is not required, but all directories
listed in the path name leading to the file must be searchable.
.Pp
.Fn Lstat
is like
.Fn stat
except in the case where the named file is a symbolic link,
in which case
.Fn lstat
returns information about the link,
while
.Fn stat
returns information about the file the link references.
Unlike other filesystem objects,
symbolic links do not have an owner, group, access mode, times, etc.
Instead, these attributes are taken from the directory that
contains the link.
The only attributes returned from an
.Fn lstat
that refer to the symbolic link itself are the file type (S_IFLNK),
size, blocks, and link count (always 1).
.Pp
The
.Fn fstat
obtains the same information about an open file
known by the file descriptor
.Fa fd .
.Pp
The
.Fa sb
argument is a pointer to a
.Fn stat
structure
as defined by
.Aq Pa sys/stat.h
(shown below)
and into which information is placed concerning the file.
.Bd -literal
struct stat {
dev_t st_dev; /* device inode resides on */
ino_t st_ino; /* inode's number */
mode_t st_mode; /* inode protection mode */
nlink_t st_nlink; /* number or hard links to the file */
uid_t st_uid; /* user-id of owner */
gid_t st_gid; /* group-id of owner */
dev_t st_rdev; /* device type, for special file inode */
struct timespec st_atimespec; /* time of last access */
struct timespec st_mtimespec; /* time of last data modification */
struct timespec st_ctimespec; /* time of last file status change */
off_t st_size; /* file size, in bytes */
quad_t st_blocks; /* blocks allocated for file */
u_long st_blksize;/* optimal file sys I/O ops blocksize */
u_long st_flags; /* user defined flags for file */
u_long st_gen; /* file generation number */
};
.Ed
.Pp
The time-related fields of
.Fa struct stat
are as follows:
.Bl -tag -width XXXst_mtime
.It st_atime
Time when file data last accessed.
Changed by the
.Xr mknod 2 ,
.Xr utimes 2
and
.Xr read 2
system calls.
.It st_mtime
Time when file data last modified.
Changed by the
.Xr mknod 2 ,
.Xr utimes 2
and
.Xr write 2
system calls.
.It st_ctime
Time when file status was last changed (inode data modification).
Changed by the
.Xr chmod 2 ,
.Xr chown 2 ,
.Xr link 2 ,
.Xr mknod 2 ,
.Xr rename 2 ,
.Xr unlink 2 ,
.Xr utimes 2
and
.Xr write 2
system calls.
.El
.Pp
The size-related fields of the
.Fa struct stat
are as follows:
.Bl -tag -width XXXst_blksize
.It st_blksize
The optimal I/O block size for the file.
.It st_blocks
The actual number of blocks allocated for the file in 512-byte units.
As short symbolic links are stored in the inode, this number may
be zero.
.El
.Pp
The status information word
.Fa st_mode
has the following bits:
.Bd -literal
#define S_IFMT 0170000 /* type of file */
#define S_IFIFO 0010000 /* named pipe (fifo) */
#define S_IFCHR 0020000 /* character special */
#define S_IFDIR 0040000 /* directory */
#define S_IFBLK 0060000 /* block special */
#define S_IFREG 0100000 /* regular */
#define S_IFLNK 0120000 /* symbolic link */
#define S_IFSOCK 0140000 /* socket */
#define S_ISUID 0004000 /* set user id on execution */
#define S_ISGID 0002000 /* set group id on execution */
#define S_ISVTX 0001000 /* save swapped text even after use */
#define S_IRUSR 0000400 /* read permission, owner */
#define S_IWUSR 0000200 /* write permission, owner */
#define S_IXUSR 0000100 /* execute/search permission, owner */
.Ed
.Pp
For a list of access modes, see
.Aq Pa sys/stat.h ,
.Xr access 2
and
.Xr chmod 2 .
.Sh RETURN VALUES
Upon successful completion a value of 0 is returned.
Otherwise, a value of -1 is returned and
.Va errno
is set to indicate the error.
.Sh COMPATIBILITY
Previous versions of the system used different types for the
.Li st_dev ,
.Li st_uid ,
.Li st_gid ,
.Li st_rdev ,
.Li st_size ,
.Li st_blksize
and
.Li st_blocks
fields.
.Sh ERRORS
.Fn Stat
and
.Fn lstat
will fail if:
.Bl -tag -width ENAMETOOLONGAA
.It Bq Er ENOTDIR
A component of the path prefix is not a directory.
.It Bq Er EINVAL
The pathname contains a character with the high-order bit set.
.It Bq Er ENAMETOOLONG
A component of a pathname exceeded 255 characters,
or an entire path name exceeded 1023 characters.
.It Bq Er ENOENT
The named file does not exist.
.It Bq Er EACCES
Search permission is denied for a component of the path prefix.
.It Bq Er ELOOP
Too many symbolic links were encountered in translating the pathname.
.It Bq Er EFAULT
.Fa Sb
or
.Em name
points to an invalid address.
.It Bq Er EIO
An I/O error occurred while reading from or writing to the file system.
.El
.Pp
.Bl -tag -width [EFAULT]
.Fn Fstat
will fail if:
.It Bq Er EBADF
.Fa fd
is not a valid open file descriptor.
.It Bq Er EFAULT
.Fa Sb
points to an invalid address.
.It Bq Er EIO
An I/O error occurred while reading from or writing to the file system.
.El
.Sh SEE ALSO
.Xr chmod 2 ,
.Xr chown 2 ,
.Xr utimes 2
.Xr symlink 7
.Sh BUGS
Applying
.Xr fstat
to a socket (and thus to a pipe)
returns a zero'd buffer,
except for the blocksize field,
and a unique device and inode number.
.Sh STANDARDS
The
.Fn stat
and
.Fn fstat
function calls are expected to
conform to IEEE Std 1003.1-1988
.Pq Dq Tn POSIX .
.Sh HISTORY
A
.Nm lstat
function call appeared in
.Bx 4.2 .

178
lib/libc/sys/statfs.2 Normal file
View file

@ -0,0 +1,178 @@
.\" Copyright (c) 1989, 1991, 1993
.\" The Regents of the University of California. All rights reserved.
.\"
.\" Redistribution and use in source and binary forms, with or without
.\" modification, are permitted provided that the following conditions
.\" are met:
.\" 1. Redistributions of source code must retain the above copyright
.\" notice, this list of conditions and the following disclaimer.
.\" 2. Redistributions in binary form must reproduce the above copyright
.\" notice, this list of conditions and the following disclaimer in the
.\" documentation and/or other materials provided with the distribution.
.\" 3. All advertising materials mentioning features or use of this software
.\" must display the following acknowledgement:
.\" This product includes software developed by the University of
.\" California, Berkeley and its contributors.
.\" 4. Neither the name of the University nor the names of its contributors
.\" may be used to endorse or promote products derived from this software
.\" without specific prior written permission.
.\"
.\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
.\" ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
.\" SUCH DAMAGE.
.\"
.\" @(#)statfs.2 8.5 (Berkeley) 5/24/95
.\"
.Dd May 24, 1995
.Dt STATFS 2
.Os
.Sh NAME
.Nm statfs
.Nd get file system statistics
.Sh SYNOPSIS
.Fd #include <sys/param.h>
.Fd #include <sys/mount.h>
.Ft int
.Fn statfs "const char *path" "struct statfs *buf"
.Ft int
.Fn fstatfs "int fd" "struct statfs *buf"
.Sh DESCRIPTION
.Fn Statfs
returns information about a mounted file system.
.Fa Path
is the path name of any file within the mounted filesystem.
.Fa Buf
is a pointer to a
.Fn statfs
structure defined as follows:
.Bd -literal
typedef quad fsid_t;
#define MFSNAMELEN 16 /* length of fs type name, including null */
#define MNAMELEN 90 /* length of buffer for returned name */
struct statfs {
short f_type; /* filesystem type number */
short f_flags; /* copy of mount flags */
long f_bsize; /* fundamental file system block size */
long f_iosize; /* optimal transfer block size */
long f_blocks; /* total data blocks in file system */
long f_bfree; /* free blocks in fs */
long f_bavail; /* free blocks avail to non-superuser */
long f_files; /* total file nodes in file system */
long f_ffree; /* free file nodes in fs */
fsid_t f_fsid; /* file system id */
uid_t f_owner; /* user that mounted the filesystem */
long f_spare[4]; /* spare for later */
char f_fstypename[MFSNAMELEN]; /* fs type name */
char f_mntonname[MNAMELEN]; /* directory on which mounted */
char f_mntfromname[MNAMELEN];/* mounted filesystem */
};
.Ed
The flags that may be returned include:
.Bl -tag -width MNT_ASYNCHRONOUS
.It Dv MNT_RDONLY
The filesystem is mounted read-only;
Even the super-user may not write on it.
.It Dv MNT_NOEXEC
Files may not be executed from the filesystem.
.It Dv MNT_NOSUID
Setuid and setgid bits on files are not honored when they are executed.
.It Dv MNT_NODEV
Special files in the filesystem may not be opened.
.It Dv MNT_SYNCHRONOUS
All I/O to the filesystem is done synchronously.
.It Dv MNT_ASYNCHRONOUS
No filesystem I/O is done synchronously.
.It Dv MNT_LOCAL
The filesystem resides locally.
.It Dv MNT_QUOTA
The filesystem has quotas enabled on it.
.It Dv MNT_ROOTFS
Identifies the root filesystem.
.It Dv MNT_EXRDONLY
The filesystem is exported read-only.
.It Dv MNT_EXPORTED
The filesystem is exported for both reading and writing.
.It Dv MNT_DEFEXPORTED
The filesystem is exported for both reading and writing to any Internet host.
.It Dv MNT_EXPORTANON
The filesystem maps all remote accesses to the anonymous user.
.It Dv MNT_EXKERB
The filesystem is exported with Kerberos uid mapping.
.El
.Pp
Fields that are undefined for a particular file system are set to -1.
.Fn Fstatfs
returns the same information about an open file referenced by descriptor
.Fa fd .
.Sh RETURN VALUES
Upon successful completion, a value of 0 is returned.
Otherwise, -1 is returned and the global variable
.Va errno
is set to indicate the error.
.Sh ERRORS
.Fn Statfs
fails if one or more of the following are true:
.Bl -tag -width ENAMETOOLONGA
.It Bq Er ENOTDIR
A component of the path prefix of
.Fa Path
is not a directory.
.It Bq Er EINVAL
.Fa path
contains a character with the high-order bit set.
.It Bq Er ENAMETOOLONG
The length of a component of
.Fa path
exceeds 255 characters,
or the length of
.Fa path
exceeds 1023 characters.
.It Bq Er ENOENT
The file referred to by
.Fa path
does not exist.
.It Bq Er EACCES
Search permission is denied for a component of the path prefix of
.Fa path .
.It Bq Er ELOOP
Too many symbolic links were encountered in translating
.Fa path .
.It Bq Er EFAULT
.Fa Buf
or
.Fa path
points to an invalid address.
.It Bq Er EIO
An
.Tn I/O
error occurred while reading from or writing to the file system.
.El
.Pp
.Fn Fstatfs
fails if one or more of the following are true:
.Bl -tag -width ENAMETOOLONGA
.It Bq Er EBADF
.Fa Fd
is not a valid open file descriptor.
.It Bq Er EFAULT
.Fa Buf
points to an invalid address.
.It Bq Er EIO
An
.Tn I/O
error occurred while reading from or writing to the file system.
.El
.Sh HISTORY
The
.Nm statfs
function first appeared in 4.4BSD.

105
lib/libc/sys/undelete.2 Normal file
View file

@ -0,0 +1,105 @@
.\" Copyright (c) 1994
.\" Jan-Simon Pendry
.\" The Regents of the University of California. All rights reserved.
.\"
.\" Redistribution and use in source and binary forms, with or without
.\" modification, are permitted provided that the following conditions
.\" are met:
.\" 1. Redistributions of source code must retain the above copyright
.\" notice, this list of conditions and the following disclaimer.
.\" 2. Redistributions in binary form must reproduce the above copyright
.\" notice, this list of conditions and the following disclaimer in the
.\" documentation and/or other materials provided with the distribution.
.\" 3. All advertising materials mentioning features or use of this software
.\" must display the following acknowledgement:
.\" This product includes software developed by the University of
.\" California, Berkeley and its contributors.
.\" 4. Neither the name of the University nor the names of its contributors
.\" may be used to endorse or promote products derived from this software
.\" without specific prior written permission.
.\"
.\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
.\" ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
.\" SUCH DAMAGE.
.\"
.\" @(#)undelete.2 8.4 (Berkeley) 10/18/94
.\"
.Dd October 18, 1994
.Dt UNDELETE 2
.Os BSD 4
.Sh NAME
.Nm undelete
.Nd attempt to recover a deleted file
.Sh SYNOPSIS
.Fd #include <unistd.h>
.Ft int
.Fn undelete "const char *path"
.Sh DESCRIPTION
The
.Fn undelete
function attempts to recover the deleted file named by
.Fa path .
Currently, this works only when the named object
is a whiteout in a union filesystem.
The system call removes the whiteout causing
any objects in a lower layer of the
union stack to become visible once more.
.Pp
Eventually, the
.Nm undelete
functionality may be expanded to other filesystems able to recover
deleted files such as the log-structured filesystem.
.Sh RETURN VALUES
Upon successful completion, a value of 0 is returned.
Otherwise, a value of -1 is returned and
.Va errno
is set to indicate the error.
.Sh ERRORS
The
.Fn undelete
succeeds unless:
.Bl -tag -width ENAMETOOLONGAA
.It Bq Er ENOTDIR
A component of the path prefix is not a directory.
.It Bq Er EINVAL
The pathname contains a character with the high-order bit set.
.It Bq Er ENAMETOOLONG
A component of a pathname exceeded 255 characters,
or an entire path name exceeded 1023 characters.
.It Bq Er EEXIST
The path does not reference a whiteout.
.It Bq Er ENOENT
The named whiteout does not exist.
.It Bq Er EACCES
Search permission is denied for a component of the path prefix.
.It Bq Er EACCES
Write permission is denied on the directory containing the name
to be undeleted.
.It Bq Er ELOOP
Too many symbolic links were encountered in translating the pathname.
.It Bq Er EPERM
The directory containing the name is marked sticky,
and the containing directory is not owned by the effective user ID.
.It Bq Er EIO
An I/O error occurred while updating the directory entry.
.It Bq Er EROFS
The name resides on a read-only file system.
.It Bq Er EFAULT
.Fa Path
points outside the process's allocated address space.
.El
.Sh SEE ALSO
.Xr unlink 2 ,
.Xr mount_union 8
.Sh HISTORY
An
.Nm undelete
function call first appeared in 4.4BSD-Lite.