Import unmodified NetBSD libc in trunk

This patch imports the unmodified current version of NetBSD libc.
The NetBSD includes are in /nbsd_include, while the libc code itself is 
split between lib/nbsd_libc and common/lib/libc.
This commit is contained in:
Gianluca Guida
2011-02-14 19:36:03 +00:00
parent 43d1edf88c
commit b6cbf7203b
3215 changed files with 401041 additions and 0 deletions

View File

@@ -0,0 +1,16 @@
/* $NetBSD: Lint_abs.c,v 1.2 2000/06/14 06:49:07 cgd Exp $ */
/*
* This file placed in the public domain.
* Chris Demetriou, November 5, 1997.
*/
#include <stdlib.h>
/*ARGSUSED*/
int
abs(j)
int j;
{
return (0);
}

View File

@@ -0,0 +1,17 @@
/* $NetBSD: Lint_div.c,v 1.2 2000/06/14 06:49:07 cgd Exp $ */
/*
* This file placed in the public domain.
* Chris Demetriou, November 5, 1997.
*/
#include <stdlib.h>
/*ARGSUSED*/
div_t
div(num, denom)
int num, denom;
{
div_t rv = { 0 };
return (rv);
}

View File

@@ -0,0 +1,15 @@
/* $NetBSD: Lint_imaxabs.c,v 1.1 2008/08/04 21:29:27 matt Exp $ */
/*
* This file placed in the public domain.
* Matt Thomas, August 4, 2008.
*/
#include <inttypes.h>
/* ARGSUSED */
intmax_t
imaxabs(intmax_t j)
{
return (0);
}

View File

@@ -0,0 +1,16 @@
/* $NetBSD: Lint_labs.c,v 1.2 2000/06/14 06:49:07 cgd Exp $ */
/*
* This file placed in the public domain.
* Chris Demetriou, November 5, 1997.
*/
#include <stdlib.h>
/*ARGSUSED*/
long
labs(j)
long j;
{
return (0);
}

View File

@@ -0,0 +1,17 @@
/* $NetBSD: Lint_ldiv.c,v 1.2 2000/06/14 06:49:07 cgd Exp $ */
/*
* This file placed in the public domain.
* Chris Demetriou, November 5, 1997.
*/
#include <stdlib.h>
/*ARGSUSED*/
ldiv_t
ldiv(num, denom)
long num, denom;
{
ldiv_t rv = { 0 };
return (rv);
}

View File

@@ -0,0 +1,16 @@
/* $NetBSD: Lint_llabs.c,v 1.2 2000/03/07 20:02:00 kleink Exp $ */
/*
* This file placed in the public domain.
* Klaus Klein, March 6, 2000.
*/
#include <stdlib.h>
/* ARGSUSED */ /* LONGLONG */
long long int
llabs(j)
long long int j;
{
return (0);
}

View File

@@ -0,0 +1,81 @@
# $NetBSD: Makefile.inc,v 1.75 2010/11/14 18:11:43 tron Exp $
# from: @(#)Makefile.inc 8.3 (Berkeley) 2/4/95
# stdlib sources
.PATH: ${ARCHDIR}/stdlib ${.CURDIR}/stdlib
SRCS+= _env.c _rand48.c \
a64l.c abort.c atexit.c atof.c atoi.c atol.c atoll.c \
bsearch.c drand48.c exit.c \
getenv.c getopt.c getopt_long.c getsubopt.c \
hcreate.c heapsort.c imaxdiv.c insque.c jrand48.c l64a.c lldiv.c \
lcong48.c lrand48.c lsearch.c merge.c mi_vector_hash.c mrand48.c \
nrand48.c putenv.c qabs.c qdiv.c qsort.c posix_openpt.c pty.c \
radixsort.c rand.c rand_r.c random.c remque.c \
seed48.c setenv.c srand48.c strsuftoll.c \
strtoimax.c strtol.c strtoll.c strtoq.c strtoul.c strtoull.c \
strtoumax.c strtouq.c system.c tdelete.c tfind.c tsearch.c twalk.c \
unsetenv.c strfmon.c
# These are often replaced by MD .S versions
SRCS+= abs.c labs.c llabs.c imaxabs.c
SRCS+= div.c ldiv.c imaxdiv.c
# This might be replaced by erand48.c
SRCS+= erand48_ieee754.c
.if (${USE_JEMALLOC} != "no")
SRCS+= jemalloc.c
.else
SRCS+= malloc.c
.endif
CPPFLAGS.strtoimax.c+= -I${LIBCDIR}/../../common/lib/libc/stdlib
CPPFLAGS.strtol.c+= -I${LIBCDIR}/../../common/lib/libc/stdlib
CPPFLAGS.strtoq.c+= -I${LIBCDIR}/../../common/lib/libc/stdlib
CPPFLAGS.strtouq.c+= -I${LIBCDIR}/../../common/lib/libc/stdlib
.include "${ARCHDIR}/stdlib/Makefile.inc"
MAN+= a64l.3 abort.3 abs.3 alloca.3 atexit.3 atof.3 atoi.3 atol.3 atoll.3 \
bsearch.3 \
div.3 \
exit.3 \
getenv.3 getopt.3 getopt_long.3 getsubopt.3 grantpt.3 \
hcreate.3 \
imaxabs.3 imaxdiv.3 insque.3 \
jemalloc.3 \
labs.3 ldiv.3 llabs.3 lldiv.3 lsearch.3 \
malloc.3 memory.3 mi_vector_hash.3 \
posix_memalign.3 posix_openpt.3 ptsname.3 \
qabs.3 qdiv.3 qsort.3 \
radixsort.3 rand48.3 rand.3 random.3 \
strfmon.3 strsuftoll.3 strtod.3 strtol.3 strtoul.3 system.3 \
tsearch.3 \
unlockpt.3
MLINKS+=a64l.3 l64a.3
MLINKS+=a64l.3 l64a_r.3
MLINKS+=getenv.3 setenv.3 getenv.3 unsetenv.3 getenv.3 putenv.3
MLINKS+=getenv.3 getenv_r.3
MLINKS+=hcreate.3 hdestroy.3 hcreate.3 hsearch.3
MLINKS+=insque.3 remque.3
MLINKS+=lsearch.3 lfind.3
MLINKS+=malloc.3 calloc.3 malloc.3 realloc.3 malloc.3 free.3
MLINKS+=qsort.3 heapsort.3 qsort.3 mergesort.3
MLINKS+=rand.3 rand_r.3
MLINKS+=rand.3 srand.3
MLINKS+=rand48.3 drand48.3 rand48.3 erand48.3 rand48.3 lrand48.3
MLINKS+=rand48.3 mrand48.3 rand48.3 nrand48.3 rand48.3 jrand48.3
MLINKS+=rand48.3 srand48.3 rand48.3 seed48.3 rand48.3 lcong48.3
MLINKS+=random.3 initstate.3 random.3 setstate.3 random.3 srandom.3
MLINKS+=radixsort.3 sradixsort.3
MLINKS+=strsuftoll.3 strsuftollx.3
MLINKS+=strtod.3 strtof.3 strtod.3 strtold.3
MLINKS+=strtol.3 strtoimax.3
MLINKS+=strtol.3 strtoll.3
MLINKS+=strtol.3 strtoq.3
MLINKS+=strtoul.3 strtoull.3
MLINKS+=strtoul.3 strtoumax.3
MLINKS+=strtoul.3 strtouq.3
MLINKS+=tsearch.3 tfind.3 tsearch.3 twalk.3 tsearch.3 tdelete.3

405
lib/nbsd_libc/stdlib/_env.c Normal file
View File

@@ -0,0 +1,405 @@
/* $NetBSD: _env.c,v 1.5 2010/11/17 13:25:53 tron Exp $ */
/*-
* Copyright (c) 2010 The NetBSD Foundation, Inc.
* All rights reserved.
*
* This code is derived from software contributed to The NetBSD Foundation
* by Matthias Scheler.
*
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
*/
#include <sys/cdefs.h>
#if defined(LIBC_SCCS) && !defined(lint)
__RCSID("$NetBSD: _env.c,v 1.5 2010/11/17 13:25:53 tron Exp $");
#endif /* LIBC_SCCS and not lint */
#include "namespace.h"
#include <sys/rbtree.h>
#include <assert.h>
#include <errno.h>
#include <limits.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include "env.h"
#include "reentrant.h"
#include "local.h"
/*
* Red-Black tree node for tracking memory used by environment variables.
* The tree is sorted by the address of the nodes themselves.
*/
typedef struct {
rb_node_t rb_node;
size_t length;
uint8_t marker;
char data[];
} env_node_t;
/* Compare functions for above tree. */
static signed int env_tree_compare_nodes(void *, const void *, const void *);
static signed int env_tree_compare_key(void *, const void *, const void *);
/* Operations for above tree. */
static const rb_tree_ops_t env_tree_ops = {
.rbto_compare_nodes = env_tree_compare_nodes,
.rbto_compare_key = env_tree_compare_key,
.rbto_node_offset = offsetof(env_node_t, rb_node),
.rbto_context = NULL
};
/* The single instance of above tree. */
static rb_tree_t env_tree;
/* The allocated environment. */
static char **allocated_environ;
static size_t allocated_environ_size;
#define ENV_ARRAY_SIZE_MIN 16
/* The lock protecting access to the environment. */
#ifdef _REENTRANT
static rwlock_t env_lock = RWLOCK_INITIALIZER;
#endif
/* Compatibility function. */
char *__findenv(const char *name, int *offsetp);
__warn_references(__findenv,
"warning: __findenv is an internal obsolete function.")
/* Our initialization function. */
void __libc_env_init(void);
/*ARGSUSED*/
static signed int
env_tree_compare_nodes(void *ctx, const void *node_a, const void *node_b)
{
uintptr_t addr_a, addr_b;
addr_a = (uintptr_t)node_a;
addr_b = (uintptr_t)node_b;
if (addr_a < addr_b)
return -1;
if (addr_a > addr_b)
return 1;
return 0;
}
static signed int
env_tree_compare_key(void *ctx, const void *node, const void *key)
{
return env_tree_compare_nodes(ctx, node,
(const uint8_t *)key - offsetof(env_node_t, data));
}
/*
* Determine the of the name in an environment string. Return 0 if the
* name is not valid.
*/
size_t
__envvarnamelen(const char *str, bool withequal)
{
size_t l_name;
if (str == NULL)
return 0;
l_name = strcspn(str, "=");
if (l_name == 0)
return 0;
if (withequal) {
if (str[l_name] != '=')
return 0;
} else {
if (str[l_name] == '=')
return 0;
}
return l_name;
}
/*
* Free memory occupied by environment variable if possible. This function
* must be called with the environment write locked.
*/
void
__freeenvvar(char *envvar)
{
env_node_t *node;
_DIAGASSERT(envvar != NULL);
node = rb_tree_find_node(&env_tree, envvar);
if (node != NULL) {
rb_tree_remove_node(&env_tree, node);
free(node);
}
}
/*
* Allocate memory for an environment variable. This function must be called
* with the environment write locked.
*/
char *
__allocenvvar(size_t length)
{
env_node_t *node;
node = malloc(sizeof(*node) + length);
if (node != NULL) {
node->length = length;
node->marker = 0;
rb_tree_insert_node(&env_tree, node);
return node->data;
} else {
return NULL;
}
}
/*
* Check whether an environment variable is writable. This function must be
* called with the environment write locked as the caller will probably
* overwrite the environment variable afterwards.
*/
bool
__canoverwriteenvvar(char *envvar, size_t length)
{
env_node_t *node;
_DIAGASSERT(envvar != NULL);
node = rb_tree_find_node(&env_tree, envvar);
return (node != NULL && length <= node->length);
}
/* Free all allocated environment variables that are no longer used. */
static void
__scrubenv(void)
{
static uint8_t marker = 0;
size_t num_entries;
env_node_t *node, *next;
while (++marker == 0);
/* Mark all nodes which are currently used. */
for (num_entries = 0; environ[num_entries] != NULL; num_entries++) {
node = rb_tree_find_node(&env_tree, environ[num_entries]);
if (node != NULL)
node->marker = marker;
}
/* Free all nodes which are currently not used. */
for (node = RB_TREE_MIN(&env_tree); node != NULL; node = next) {
next = rb_tree_iterate(&env_tree, node, RB_DIR_RIGHT);
if (node->marker != marker) {
rb_tree_remove_node(&env_tree, node);
free(node);
}
}
/* Deal with the environment array itself. */
if (environ == allocated_environ) {
/* Clear out spurious entries in the environment. */
(void)memset(&environ[num_entries + 1], 0,
(allocated_environ_size - num_entries - 1) *
sizeof(*environ));
} else {
/*
* The environment array was not allocated by "libc".
* Free our array if we allocated one.
*/
free(allocated_environ);
allocated_environ = NULL;
allocated_environ_size = 0;
}
}
/*
* Get a (new) slot in the environment. This function must be called with
* the environment write locked.
*/
ssize_t
__getenvslot(const char *name, size_t l_name, bool allocate)
{
size_t new_size, num_entries, required_size;
char **new_environ;
/* Does the environ need scrubbing? */
if (environ != allocated_environ && allocated_environ != NULL)
__scrubenv();
/* Search for an existing environment variable of the given name. */
num_entries = 0;
while (environ[num_entries] != NULL) {
if (strncmp(environ[num_entries], name, l_name) == 0 &&
environ[num_entries][l_name] == '=') {
/* We found a match. */
return num_entries;
}
num_entries ++;
}
/* No match found, return if we don't want to allocate a new slot. */
if (!allocate)
return -1;
/* Create a new slot in the environment. */
required_size = num_entries + 1;
if (environ == allocated_environ &&
required_size < allocated_environ_size) {
/* Does the environment need scrubbing? */
if (required_size < allocated_environ_size &&
allocated_environ[required_size] != NULL) {
__scrubenv();
}
/* Return a free slot. */
return num_entries;
}
/* Determine size of a new environment array. */
new_size = ENV_ARRAY_SIZE_MIN;
while (new_size <= required_size)
new_size <<= 1;
/* Allocate a new environment array. */
if (environ == allocated_environ) {
new_environ = realloc(environ,
new_size * sizeof(*new_environ));
if (new_environ == NULL)
return -1;
} else {
free(allocated_environ);
allocated_environ = NULL;
allocated_environ_size = 0;
new_environ = malloc(new_size * sizeof(*new_environ));
if (new_environ == NULL)
return -1;
(void)memcpy(new_environ, environ,
num_entries * sizeof(*new_environ));
}
/* Clear remaining entries. */
(void)memset(&new_environ[num_entries], 0,
(new_size - num_entries) * sizeof(*new_environ));
/* Use the new environment array. */
environ = allocated_environ = new_environ;
allocated_environ_size = new_size;
/* Return a free slot. */
return num_entries;
}
/* Find a string in the environment. */
char *
__findenvvar(const char *name, size_t l_name)
{
ssize_t offset;
offset = __getenvslot(name, l_name, false);
return (offset != -1) ? environ[offset] + l_name + 1 : NULL;
}
/* Compatibility interface, do *not* call this function. */
char *
__findenv(const char *name, int *offsetp)
{
size_t l_name;
ssize_t offset;
l_name = __envvarnamelen(name, false);
if (l_name == 0)
return NULL;
offset = __getenvslot(name, l_name, false);
if (offset < 0 || offset > INT_MAX)
return NULL;
*offsetp = (int)offset;
return environ[offset] + l_name + 1;
}
#ifdef _REENTRANT
/* Lock the environment for read. */
bool
__readlockenv(void)
{
int error;
error = rwlock_rdlock(&env_lock);
if (error == 0)
return true;
errno = error;
return false;
}
/* Lock the environment for write. */
bool
__writelockenv(void)
{
int error;
error = rwlock_wrlock(&env_lock);
if (error == 0)
return true;
errno = error;
return false;
}
/* Unlock the environment for write. */
bool
__unlockenv(void)
{
int error;
error = rwlock_unlock(&env_lock);
if (error == 0)
return true;
errno = error;
return false;
}
#endif
/* Initialize environment memory RB tree. */
void
__libc_env_init(void)
{
rb_tree_init(&env_tree, &env_tree_ops);
}

View File

@@ -0,0 +1,57 @@
/* $NetBSD: _rand48.c,v 1.7 2005/06/12 05:21:27 lukem Exp $ */
/*
* Copyright (c) 1993 Martin Birgmeier
* All rights reserved.
*
* You may redistribute unmodified or modified versions of this source
* code provided that the above copyright notice and this and the
* following conditions are retained.
*
* This software is provided ``as is'', and comes with no warranties
* of any kind. I shall in no event be liable for anything that happens
* to anyone/anything when using this software.
*/
#include <sys/cdefs.h>
#if defined(LIBC_SCCS) && !defined(lint)
__RCSID("$NetBSD: _rand48.c,v 1.7 2005/06/12 05:21:27 lukem Exp $");
#endif /* LIBC_SCCS and not lint */
#include <assert.h>
#include "rand48.h"
unsigned short __rand48_seed[3] = {
RAND48_SEED_0,
RAND48_SEED_1,
RAND48_SEED_2
};
unsigned short __rand48_mult[3] = {
RAND48_MULT_0,
RAND48_MULT_1,
RAND48_MULT_2
};
unsigned short __rand48_add = RAND48_ADD;
void
__dorand48(unsigned short xseed[3])
{
unsigned long accu;
unsigned short temp[2];
_DIAGASSERT(xseed != NULL);
accu = (unsigned long) __rand48_mult[0] * (unsigned long) xseed[0] +
(unsigned long) __rand48_add;
temp[0] = (unsigned short) accu; /* lower 16 bits */
accu >>= sizeof(unsigned short) * 8;
accu += (unsigned long) __rand48_mult[0] * (unsigned long) xseed[1] +
(unsigned long) __rand48_mult[1] * (unsigned long) xseed[0];
temp[1] = (unsigned short) accu; /* middle 16 bits */
accu >>= sizeof(unsigned short) * 8;
accu += __rand48_mult[0] * xseed[2] + __rand48_mult[1] * xseed[1] + __rand48_mult[2] * xseed[0];
xseed[0] = temp[0];
xseed[1] = temp[1];
xseed[2] = (unsigned short) accu;
}

133
lib/nbsd_libc/stdlib/a64l.3 Normal file
View File

@@ -0,0 +1,133 @@
.\" $NetBSD: a64l.3,v 1.10 2010/05/06 18:55:34 jruoho Exp $
.\"
.\" Copyright (c) 1998, 1999 The NetBSD Foundation, Inc.
.\" All rights reserved.
.\"
.\" This code is derived from software contributed to The NetBSD Foundation
.\" by Klaus Klein.
.\"
.\" 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.
.\"
.\" THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
.\"
.Dd May 6, 2010
.Dt A64L 3
.Os
.Sh NAME
.Nm a64l ,
.Nm l64a ,
.Nm l64a_r
.Nd "convert between a long integer and a base-64 ASCII string"
.Sh LIBRARY
.Lb libc
.Sh SYNOPSIS
.In stdlib.h
.Ft long
.Fn a64l "const char *s"
.Ft char *
.Fn l64a "long int l"
.Ft int
.Fn l64a_r "long int l" "char *buffer" "int buflen"
.Sh DESCRIPTION
The
.Fn a64l
and
.Fn l64a
functions convert between a long integer and its base-64 ASCII string
representation.
.Pp
The characters used to represent ``digits'' are
`.' for 0,
`/' for 1,
`0' - `9' for 2 - 11,
`A' - `Z' for 12 - 37, and
`a' - `z' for 38 - 63.
.Pp
.Fn a64l
takes a pointer to a NUL-terminated base-64 ASCII string
representation,
.Fa s ,
and returns the corresponding long integer value.
.Pp
.Fn l64a
takes a long integer value,
.Fa l ,
and returns a pointer to the corresponding NUL-terminated base-64
ASCII string representation.
.Pp
.Fn l64a_r
performs a conversion identical to that of
.Fn l64a
and stores the resulting representation in the memory area pointed to by
.Fa buffer ,
consuming at most
.Fa buflen
characters including the terminating NUL character.
.Sh RETURN VALUES
On successful completion,
.Fn a64l
returns the long integer value corresponding to the input string.
If the string pointed to by
.Fa s
is an empty string,
.Fn a64l
returns a value of 0L.
.Pp
.Fn l64a
returns a pointer to the base-64 ASCII string representation corresponding to
the input value.
If
.Fa l
is 0L,
.Fn l64a
returns a pointer to an empty string.
.Pp
On successful completion,
.Fn l64a_r
returns 0; if
.Fa buffer
is of insufficient length, -1 is returned.
.Sh SEE ALSO
.Xr strtol 3
.Sh STANDARDS
The
.Fn a64l
and
.Fn l64a
functions conform to
.St -xpg4.2
and
.St -p1003.1-2004 .
The
.Fn l64a_r
function conforms to
.St -svid4 ,
Multithreading Extension.
.Sh BUGS
The
.Fn l64a
function is not reentrant.
The value returned by it points into a static buffer area;
subsequent calls to
.Fn la64a
may overwrite this buffer.
In multi-threaded applications,
.Fn l64a_r
should be used instead.

View File

@@ -0,0 +1,46 @@
/*
* Written by J.T. Conklin <jtc@NetBSD.org>.
* Public domain.
*/
#include <sys/cdefs.h>
#if defined(LIBC_SCCS) && !defined(lint)
__RCSID("$NetBSD: a64l.c,v 1.9 2003/07/26 19:24:53 salo Exp $");
#endif
#include "namespace.h"
#include <assert.h>
#include <stdlib.h>
#ifdef __weak_alias
__weak_alias(a64l,_a64l)
#endif
long
a64l(s)
const char *s;
{
long value, digit, shift;
int i;
_DIAGASSERT(s != NULL);
value = 0;
shift = 0;
for (i = 0; *s && i < 6; i++, s++) {
if (*s <= '/')
digit = *s - '.';
else if (*s <= '9')
digit = *s - '0' + 2;
else if (*s <= 'Z')
digit = *s - 'A' + 12;
else
digit = *s - 'a' + 38;
value |= digit << shift;
shift += 6;
}
return (long) value;
}

View File

@@ -0,0 +1,73 @@
.\" $NetBSD: abort.3,v 1.12 2003/08/07 16:43:37 agc Exp $
.\"
.\" Copyright (c) 1990, 1991, 1993
.\" The Regents of the University of California. All rights reserved.
.\"
.\" This code is derived from software contributed to Berkeley by
.\" the American National Standards Committee X3, on Information
.\" Processing Systems.
.\"
.\" 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. 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.
.\"
.\" from: @(#)abort.3 8.1 (Berkeley) 6/4/93
.\"
.Dd August 11, 2002
.Dt ABORT 3
.Os
.Sh NAME
.Nm abort
.Nd cause abnormal program termination
.Sh LIBRARY
.Lb libc
.Sh SYNOPSIS
.In stdlib.h
.Ft void
.Fn abort void
.Sh DESCRIPTION
The
.Fn abort
function causes abnormal program termination to occur, unless the
signal
.Dv SIGABRT
is being caught and the signal handler does not return.
.Pp
Calling the
.Fn abort
function results in temporary files being removed.
Any open streams are flushed and closed.
.Sh RETURN VALUES
The
.Nm abort
function
never returns.
.Sh SEE ALSO
.Xr sigaction 2 ,
.Xr exit 3
.Sh STANDARDS
The
.Fn abort
function
conforms to
.St -ansiC .

View File

@@ -0,0 +1,84 @@
/* $NetBSD: abort.c,v 1.13 2009/01/30 23:21:03 ad Exp $ */
/*
* Copyright (c) 1985, 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. 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.
*/
#include <sys/cdefs.h>
#if defined(LIBC_SCCS) && !defined(lint)
#if 0
static char sccsid[] = "@(#)abort.c 8.1 (Berkeley) 6/4/93";
#else
__RCSID("$NetBSD: abort.c,v 1.13 2009/01/30 23:21:03 ad Exp $");
#endif
#endif /* LIBC_SCCS and not lint */
#include "namespace.h"
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>
extern void (*__cleanup) __P((void));
static int aborting = 0;
void
abort()
{
sigset_t mask;
sigfillset(&mask);
/*
* don't block SIGABRT to give any handler a chance; we ignore
* any errors -- X311J doesn't allow abort to return anyway.
*/
sigdelset(&mask, SIGABRT);
(void)sigprocmask(SIG_SETMASK, &mask, (sigset_t *)NULL);
/*
* POSIX.1 requires that stdio buffers be flushed on abort.
* We ensure the cleanup routines are only called once in
* case the user calls abort() in a SIGABRT handler.
*/
if (!aborting) {
aborting = 1;
if (__cleanup)
(*__cleanup)();
}
(void)raise(SIGABRT);
/*
* if SIGABRT ignored, or caught and the handler returns, do
* it again, only harder.
*/
(void)signal(SIGABRT, SIG_DFL);
(void)sigprocmask(SIG_SETMASK, &mask, (sigset_t *)NULL);
(void)raise(SIGABRT);
_exit(1);
}

View File

@@ -0,0 +1,76 @@
.\" $NetBSD: abs.3,v 1.13 2008/08/04 21:29:27 matt Exp $
.\"
.\" Copyright (c) 1990, 1991, 1993
.\" The Regents of the University of California. All rights reserved.
.\"
.\" This code is derived from software contributed to Berkeley by
.\" the American National Standards Committee X3, on Information
.\" Processing Systems.
.\"
.\" 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. 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.
.\"
.\" from: @(#)abs.3 8.1 (Berkeley) 6/4/93
.\"
.Dd June 4, 1993
.Dt ABS 3
.Os
.Sh NAME
.Nm abs
.Nd integer absolute value function
.Sh LIBRARY
.Lb libc
.Sh SYNOPSIS
.In stdlib.h
.Ft int
.Fn abs "int j"
.Sh DESCRIPTION
The
.Fn abs
function
computes
the absolute value of the integer
.Ar j .
.Sh RETURN VALUES
The
.Fn abs
function
returns
the absolute value.
.Sh SEE ALSO
.Xr cabs 3 ,
.Xr fabs 3 ,
.Xr floor 3 ,
.Xr hypot 3 ,
.Xr imaxabs 3 ,
.Xr labs 3 ,
.Xr llabs 3 ,
.Xr math 3
.Sh STANDARDS
The
.Fn abs
function conforms to
.St -ansiC .
.Sh BUGS
The absolute value of the most negative integer remains negative.

View File

@@ -0,0 +1,48 @@
/* $NetBSD: abs.c,v 1.7 2003/08/07 16:43:37 agc Exp $ */
/*-
* 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. 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.
*/
#include <sys/cdefs.h>
#if defined(LIBC_SCCS) && !defined(lint)
#if 0
static char sccsid[] = "@(#)abs.c 8.1 (Berkeley) 6/4/93";
#else
__RCSID("$NetBSD: abs.c,v 1.7 2003/08/07 16:43:37 agc Exp $");
#endif
#endif /* LIBC_SCCS and not lint */
#include <stdlib.h>
int
abs(j)
int j;
{
return(j < 0 ? -j : j);
}

View File

@@ -0,0 +1,102 @@
.\" $NetBSD: alloca.3,v 1.13 2010/05/03 06:11:38 jruoho Exp $
.\"
.\" 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. 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.
.\"
.\" from: @(#)alloca.3 8.1 (Berkeley) 6/4/93
.\"
.Dd May 3, 2010
.Dt ALLOCA 3
.Os
.Sh NAME
.Nm alloca
.Nd memory allocator
.Sh LIBRARY
.Lb libc
.Sh SYNOPSIS
.In stdlib.h
.Ft void *
.Fn alloca "size_t size"
.Sh DESCRIPTION
The
.Fn alloca
function
allocates
.Fa size
bytes of space in the stack frame of the caller.
This temporary space is automatically freed on
return.
.Sh RETURN VALUES
The
.Fn alloca
function returns a pointer to the beginning of the allocated space.
If the allocation failed, a
.Dv NULL
pointer is returned.
.Sh SEE ALSO
.Xr brk 2 ,
.Xr calloc 3 ,
.Xr getpagesize 3 ,
.Xr malloc 3 ,
.Xr realloc 3
.Sh CAVEATS
Few limitations can be mentioned:
.Bl -bullet
.It
The
.Fn alloca
function
is machine dependent; its use is discouraged.
.It
The
.Fn alloca
function is slightly unsafe because it cannot ensure that the pointer
returned points to a valid and usable block of memory.
The allocation made may exceed the bounds of the stack, or even go
further into other objects in memory, and
.Fn alloca
cannot determine such an error.
Avoid
.Fn alloca
with large unbounded allocations.
.It
Since
.Fn alloca
modifies the stack at runtime,
it causes problems to certain security features.
See
.Xr security 8
for a discussion.
.El
.\" .Sh HISTORY
.\" The
.\" .Fn alloca
.\" function appeared in
.\" .Bx ?? .
.\" The function appeared in 32v, pwb and pwb.2 and in 3bsd 4bsd
.\" The first man page (or link to a man page that I can find at the
.\" moment is 4.3...

View File

@@ -0,0 +1,77 @@
.\" $NetBSD: atexit.3,v 1.9 2003/08/07 16:43:38 agc Exp $
.\"
.\" Copyright (c) 1990, 1991, 1993
.\" The Regents of the University of California. All rights reserved.
.\"
.\" This code is derived from software contributed to Berkeley by
.\" Chris Torek and the American National Standards Committee X3,
.\" on Information Processing Systems.
.\"
.\" 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. 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.
.\"
.\" from: @(#)atexit.3 8.1 (Berkeley) 6/4/93
.\"
.Dd June 4, 1993
.Dt ATEXIT 3
.Os
.Sh NAME
.Nm atexit
.Nd register a function to be called on exit
.Sh LIBRARY
.Lb libc
.Sh SYNOPSIS
.In stdlib.h
.Ft int
.Fn atexit "void (*function)(void)"
.Sh DESCRIPTION
The
.Fn atexit
function
registers the given
.Ar function
to be called at program exit, whether via
.Xr exit 3
or via return from the program's
.Em main .
Functions so registered are called in reverse order;
no arguments are passed.
At least 32 functions can always be registered,
and more are allowed as long as sufficient memory can be allocated.
.Sh RETURN VALUES
.Rv -std atexit
.Sh ERRORS
.Bl -tag -width Er
.It Bq Er ENOMEM
No memory was available to add the function to the list.
The existing list of functions is unmodified.
.El
.Sh SEE ALSO
.Xr exit 3
.Sh STANDARDS
The
.Fn atexit
function
conforms to
.St -ansiC .

View File

@@ -0,0 +1,246 @@
/* $NetBSD: atexit.c,v 1.24 2009/10/08 16:33:45 pooka Exp $ */
/*-
* Copyright (c) 2003 The NetBSD Foundation, Inc.
* All rights reserved.
*
* This code is derived from software contributed to The NetBSD Foundation
* by Jason R. Thorpe.
*
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
*/
#include <sys/cdefs.h>
#if defined(LIBC_SCCS) && !defined(lint)
__RCSID("$NetBSD: atexit.c,v 1.24 2009/10/08 16:33:45 pooka Exp $");
#endif /* LIBC_SCCS and not lint */
#include "reentrant.h"
#include <assert.h>
#include <stdlib.h>
#include "atexit.h"
struct atexit_handler {
struct atexit_handler *ah_next;
union {
void (*fun_atexit)(void);
void (*fun_cxa_atexit)(void *);
} ah_fun;
#define ah_atexit ah_fun.fun_atexit
#define ah_cxa_atexit ah_fun.fun_cxa_atexit
void *ah_arg; /* argument for cxa_atexit handlers */
void *ah_dso; /* home DSO for cxa_atexit handlers */
};
/*
* There must be at least 32 to guarantee ANSI conformance, plus
* 3 additional ones for the benefit of the startup code, which
* may use them to register the dynamic loader's cleanup routine,
* the profiling cleanup routine, and the global destructor routine.
*/
#define NSTATIC_HANDLERS (32 + 3)
static struct atexit_handler atexit_handler0[NSTATIC_HANDLERS];
#define STATIC_HANDLER_P(ah) \
(ah >= &atexit_handler0[0] && ah < &atexit_handler0[NSTATIC_HANDLERS])
/*
* Stack of atexit handlers. Handlers must be called in the opposite
* order they were registered.
*/
static struct atexit_handler *atexit_handler_stack;
#ifdef _REENTRANT
/* ..and a mutex to protect it all. */
static mutex_t atexit_mutex;
#endif /* _REENTRANT */
void __libc_atexit_init(void) __attribute__ ((visibility("hidden")));
/*
* Allocate an atexit handler descriptor. If "dso" is NULL, it indicates
* a normal atexit handler, which must be allocated from the static pool,
* if possible. cxa_atexit handlers are never allocated from the static
* pool.
*
* atexit_mutex must be held.
*/
static struct atexit_handler *
atexit_handler_alloc(void *dso)
{
struct atexit_handler *ah;
int i;
if (dso == NULL) {
for (i = 0; i < NSTATIC_HANDLERS; i++) {
ah = &atexit_handler0[i];
if (ah->ah_atexit == NULL && ah->ah_next == NULL) {
/* Slot is free. */
return (ah);
}
}
}
/*
* Either no static slot was free, or this is a cxa_atexit
* handler. Allocate a new one. We keep the atexit_mutex
* held to prevent handlers from being run while we (potentially)
* block in malloc().
*/
ah = malloc(sizeof(*ah));
return (ah);
}
/*
* Initialize atexit_mutex with the PTHREAD_MUTEX_RECURSIVE attribute.
* Note that __cxa_finalize may generate calls to __cxa_atexit.
*/
void
__libc_atexit_init(void)
{
mutexattr_t atexit_mutex_attr;
mutexattr_init(&atexit_mutex_attr);
mutexattr_settype(&atexit_mutex_attr, PTHREAD_MUTEX_RECURSIVE);
mutex_init(&atexit_mutex, &atexit_mutex_attr);
}
/*
* Register an atexit routine. This is suitable either for a cxa_atexit
* or normal atexit type handler. The __cxa_atexit() name and arguments
* are specified by the C++ ABI. See:
*
* http://www.codesourcery.com/cxx-abi/abi.html#dso-dtor
*/
int
__cxa_atexit(void (*func)(void *), void *arg, void *dso)
{
struct atexit_handler *ah;
_DIAGASSERT(func != NULL);
mutex_lock(&atexit_mutex);
ah = atexit_handler_alloc(dso);
if (ah == NULL) {
mutex_unlock(&atexit_mutex);
return (-1);
}
ah->ah_cxa_atexit = func;
ah->ah_arg = arg;
ah->ah_dso = dso;
ah->ah_next = atexit_handler_stack;
atexit_handler_stack = ah;
mutex_unlock(&atexit_mutex);
return (0);
}
/*
* Run the list of atexit handlers. If dso is NULL, run all of them,
* otherwise run only those matching the specified dso.
*
* Note that we can be recursively invoked; rtld cleanup is via an
* atexit handler, and rtld cleanup invokes _fini() for DSOs, which
* in turn invokes __cxa_finalize() for the DSO.
*/
void
__cxa_finalize(void *dso)
{
static u_int call_depth;
struct atexit_handler *ah, *dead_handlers = NULL, **prevp;
void (*cxa_func)(void *);
void (*atexit_func)(void);
mutex_lock(&atexit_mutex);
call_depth++;
/*
* If we are at call depth 1 (which is usually the "do everything"
* call from exit(3)), we go ahead and remove elements from the
* list as we call them. This will prevent any nested calls from
* having to traverse elements we've already processed. If we are
* at call depth > 1, we simply mark elements we process as unused.
* When the depth 1 caller sees those, it will simply unlink them
* for us.
*/
again:
for (prevp = &atexit_handler_stack; (ah = (*prevp)) != NULL;) {
if (dso == NULL || dso == ah->ah_dso || ah->ah_atexit == NULL) {
if (ah->ah_atexit != NULL) {
void *p = atexit_handler_stack;
if (ah->ah_dso != NULL) {
cxa_func = ah->ah_cxa_atexit;
ah->ah_cxa_atexit = NULL;
(*cxa_func)(ah->ah_arg);
} else {
atexit_func = ah->ah_atexit;
ah->ah_atexit = NULL;
(*atexit_func)();
}
/* Restart if new atexit handler was added. */
if (p != atexit_handler_stack)
goto again;
}
if (call_depth == 1) {
*prevp = ah->ah_next;
if (STATIC_HANDLER_P(ah))
ah->ah_next = NULL;
else {
ah->ah_next = dead_handlers;
dead_handlers = ah;
}
} else
prevp = &ah->ah_next;
} else
prevp = &ah->ah_next;
}
call_depth--;
mutex_unlock(&atexit_mutex);
if (call_depth > 0)
return;
/*
* Now free any dead handlers. Do this even if we're about to
* exit, in case a leak-detecting malloc is being used.
*/
while ((ah = dead_handlers) != NULL) {
dead_handlers = ah->ah_next;
free(ah);
}
}
/*
* Register a function to be performed at exit.
*/
int
atexit(void (*func)(void))
{
return (__cxa_atexit((void (*)(void *))func, NULL, NULL));
}

View File

@@ -0,0 +1,33 @@
/* $NetBSD: atexit.h,v 1.11 2008/04/28 20:23:00 martin Exp $ */
/*-
* Copyright (c) 2003 The NetBSD Foundation, Inc.
* All rights reserved.
*
* This code is derived from software contributed to The NetBSD Foundation
* by Jason R. Thorpe.
*
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
*/
int __cxa_atexit(void (*)(void *), void *, void *);
void __cxa_finalize(void *);

View File

@@ -0,0 +1,73 @@
.\" $NetBSD: atof.3,v 1.9 2003/08/07 16:43:38 agc Exp $
.\"
.\" Copyright (c) 1991, 1993
.\" The Regents of the University of California. All rights reserved.
.\"
.\" This code is derived from software contributed to Berkeley by
.\" the American National Standards Committee X3, on Information
.\" Processing Systems.
.\"
.\" 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. 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.
.\"
.\" from: @(#)atof.3 8.1 (Berkeley) 6/4/93
.\"
.Dd June 4, 1993
.Dt ATOF 3
.Os
.Sh NAME
.Nm atof
.Nd convert
.Tn ASCII
string to double
.Sh LIBRARY
.Lb libc
.Sh SYNOPSIS
.In stdlib.h
.Ft double
.Fn atof "const char *nptr"
.Sh DESCRIPTION
The
.Fn atof
function converts the initial portion of the string pointed to by
.Ar nptr
to
.Ar double
representation.
.Pp
It is equivalent to:
.Bd -literal -offset indent
strtod(nptr, (char **)NULL);
.Ed
.Sh SEE ALSO
.Xr atoi 3 ,
.Xr atol 3 ,
.Xr strtod 3 ,
.Xr strtol 3 ,
.Xr strtoul 3
.Sh STANDARDS
The
.Fn atof
function conforms to
.St -ansiC .

View File

@@ -0,0 +1,51 @@
/* $NetBSD: atof.c,v 1.12 2003/08/07 16:43:38 agc Exp $ */
/*
* 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. 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.
*/
#include <sys/cdefs.h>
#if defined(LIBC_SCCS) && !defined(lint)
#if 0
static char sccsid[] = "@(#)atof.c 8.1 (Berkeley) 6/4/93";
#else
__RCSID("$NetBSD: atof.c,v 1.12 2003/08/07 16:43:38 agc Exp $");
#endif
#endif /* LIBC_SCCS and not lint */
#include <assert.h>
#include <stdlib.h>
double
atof(ascii)
const char *ascii;
{
_DIAGASSERT(ascii != NULL);
return (strtod(ascii, NULL));
}

View File

@@ -0,0 +1,85 @@
.\" $NetBSD: atoi.3,v 1.10 2003/08/07 16:43:38 agc Exp $
.\"
.\" Copyright (c) 1990, 1991, 1993
.\" The Regents of the University of California. All rights reserved.
.\"
.\" This code is derived from software contributed to Berkeley by
.\" the American National Standards Committee X3, on Information
.\" Processing Systems.
.\"
.\" 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. 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.
.\"
.\" from: @(#)atoi.3 8.1 (Berkeley) 6/4/93
.\"
.Dd June 4, 1993
.Dt ATOI 3
.Os
.Sh NAME
.Nm atoi
.Nd convert
.Tn ASCII
string to integer
.Sh LIBRARY
.Lb libc
.Sh SYNOPSIS
.In stdlib.h
.Ft int
.Fn atoi "const char *nptr"
.Sh DESCRIPTION
The
.Fn atoi
function converts the initial portion of the string pointed to by
.Em nptr
to
.Em integer
representation.
.Pp
It is equivalent to:
.Bd -literal -offset indent
(int)strtol(nptr, (char **)NULL, 10);
.Ed
.Sh SEE ALSO
.Xr atof 3 ,
.Xr atol 3 ,
.Xr strtod 3 ,
.Xr strtol 3 ,
.Xr strtoul 3
.Sh STANDARDS
The
.Fn atoi
function conforms to
.St -ansiC .
.Sh CAVEATS
.Nm
does no overflow checking, handles unsigned numbers poorly,
and handles strings containing trailing extra characters
(like
.Dq 123abc )
poorly.
Careful use of
.Xr strtol 3
and
.Xr strtoul 3
can alleviate these problems.

View File

@@ -0,0 +1,51 @@
/* $NetBSD: atoi.c,v 1.11 2003/08/07 16:43:38 agc Exp $ */
/*
* 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. 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.
*/
#include <sys/cdefs.h>
#if defined(LIBC_SCCS) && !defined(lint)
#if 0
static char sccsid[] = "@(#)atoi.c 8.1 (Berkeley) 6/4/93";
#else
__RCSID("$NetBSD: atoi.c,v 1.11 2003/08/07 16:43:38 agc Exp $");
#endif
#endif /* LIBC_SCCS and not lint */
#include <assert.h>
#include <stdlib.h>
int
atoi(str)
const char *str;
{
_DIAGASSERT(str != NULL);
return((int)strtol(str, (char **)NULL, 10));
}

View File

@@ -0,0 +1,74 @@
.\" $NetBSD: atol.3,v 1.8 2003/08/07 16:43:38 agc Exp $
.\"
.\" Copyright (c) 1990, 1991, 1993
.\" The Regents of the University of California. All rights reserved.
.\"
.\" This code is derived from software contributed to Berkeley by
.\" the American National Standards Committee X3, on Information
.\" Processing Systems.
.\"
.\" 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. 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.
.\"
.\" from: @(#)atol.3 8.1 (Berkeley) 6/4/93
.\"
.Dd June 4, 1993
.Dt ATOL 3
.Os
.Sh NAME
.Nm atol
.Nd convert
.Tn ASCII
string to long integer
.Sh LIBRARY
.Lb libc
.Sh SYNOPSIS
.In stdlib.h
.Ft long
.Fn atol "const char *nptr"
.Sh DESCRIPTION
The
.Fn atol
function converts the initial portion of the string pointed to by
.Ar nptr
to
.Em long integer
representation.
.Pp
It is equivalent to:
.Bd -literal -offset indent
strtol(nptr, (char **)NULL, 10);
.Ed
.Sh SEE ALSO
.Xr atof 3 ,
.Xr atoi 3 ,
.Xr strtod 3 ,
.Xr strtol 3 ,
.Xr strtoul 3
.Sh STANDARDS
The
.Fn atol
function
conforms to
.St -ansiC .

View File

@@ -0,0 +1,51 @@
/* $NetBSD: atol.c,v 1.10 2003/08/07 16:43:38 agc Exp $ */
/*
* 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. 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.
*/
#include <sys/cdefs.h>
#if defined(LIBC_SCCS) && !defined(lint)
#if 0
static char sccsid[] = "@(#)atol.c 8.1 (Berkeley) 6/4/93";
#else
__RCSID("$NetBSD: atol.c,v 1.10 2003/08/07 16:43:38 agc Exp $");
#endif
#endif /* LIBC_SCCS and not lint */
#include <assert.h>
#include <stdlib.h>
long
atol(str)
const char *str;
{
_DIAGASSERT(str != NULL);
return(strtol(str, (char **)NULL, 10));
}

View File

@@ -0,0 +1,77 @@
.\" $NetBSD: atoll.3,v 1.6 2003/09/08 17:54:33 wiz Exp $
.\"
.\" Copyright (c) 1990, 1991, 1993
.\" The Regents of the University of California. All rights reserved.
.\"
.\" This code is derived from software contributed to Berkeley by
.\" the American National Standards Committee X3, on Information
.\" Processing Systems.
.\"
.\" 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. 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.
.\"
.\" from: @(#)atol.3 8.1 (Berkeley) 6/4/93
.\"
.Dd March 6, 2000
.Dt ATOLL 3
.Os
.Sh NAME
.Nm atoll
.Nd convert
.Tn ASCII
string to long long integer
.Sh LIBRARY
.Lb libc
.Sh SYNOPSIS
.In stdlib.h
.Ft long long int
.Fn atoll "const char *nptr"
.Sh DESCRIPTION
The
.Fn atoll
function converts the initial portion of the string pointed to by
.Ar nptr
to
.Em long long integer
representation.
.Pp
It is equivalent to:
.Bd -literal -offset indent
strtoll(nptr, (char **)NULL, 10);
.Ed
.Sh SEE ALSO
.Xr atof 3 ,
.Xr atoi 3 ,
.Xr atol 3 ,
.Xr strtod 3 ,
.Xr strtol 3 ,
.Xr strtoll 3 ,
.Xr strtoul 3 ,
.Xr strtoull 3
.Sh STANDARDS
The
.Fn atoll
function
conforms to
.St -isoC-99 .

View File

@@ -0,0 +1,65 @@
/* $NetBSD: atoll.c,v 1.5 2003/10/27 00:12:42 lukem Exp $ */
/*
* 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. 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 HAVE_NBTOOL_CONFIG_H
#include "nbtool_config.h"
#endif
#include <sys/cdefs.h>
#if defined(LIBC_SCCS) && !defined(lint)
#if 0
static char sccsid[] = "from: @(#)atol.c 8.1 (Berkeley) 6/4/93";
#else
__RCSID("$NetBSD: atoll.c,v 1.5 2003/10/27 00:12:42 lukem Exp $");
#endif
#endif /* LIBC_SCCS and not lint */
#ifdef _LIBC
#include "namespace.h"
#endif
#include <stdlib.h>
#ifdef _LIBC
#ifdef __weak_alias
__weak_alias(atoll, _atoll)
#endif
#endif
#if !HAVE_ATOLL
/* LONGLONG */
long long int
atoll(str)
const char *str;
{
return (strtoll(str, (char **)NULL, 10));
}
#endif

View File

@@ -0,0 +1,90 @@
.\" $NetBSD: bsearch.3,v 1.10 2003/08/07 16:43:38 agc Exp $
.\"
.\" Copyright (c) 1990, 1991, 1993, 1994
.\" The Regents of the University of California. All rights reserved.
.\"
.\" This code is derived from software contributed to Berkeley by
.\" the American National Standards Committee X3, on Information
.\" Processing Systems.
.\"
.\" 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. 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.
.\"
.\" from: @(#)bsearch.3 8.3 (Berkeley) 4/19/94
.\"
.Dd April 19, 1994
.Dt BSEARCH 3
.Os
.Sh NAME
.Nm bsearch
.Nd binary search of a sorted table
.Sh LIBRARY
.Lb libc
.Sh SYNOPSIS
.In stdlib.h
.Ft void *
.Fn bsearch "const void *key" "const void *base" "size_t nmemb" "size_t size" "int (*compar) (const void *, const void *)"
.Sh DESCRIPTION
The
.Fn bsearch
function searches an array of
.Fa nmemb
objects, the initial member of which is
pointed to by
.Fa base ,
for a member that matches the object pointed to by
.Fa key .
The size of each member of the array is specified by
.Fa size .
.Pp
The contents of the array should be in ascending sorted order according
to the comparison function referenced by
.Fa compar .
The
.Fa compar
routine
is expected to have
two arguments which point to the
.Fa key
object and to an array member, in that order, and should return an integer
less than, equal to, or greater than zero if the
.Fa key
object is found, respectively, to be less than, to match, or be
greater than the array member.
.Sh RETURN VALUES
The
.Fn bsearch
function returns a pointer to a matching member of the array, or a null
pointer if no match is found.
If two members compare as equal, which member is matched is unspecified.
.Sh SEE ALSO
.Xr db 3 ,
.Xr lsearch 3 ,
.Xr qsort 3 ,
.Xr tsearch 3
.Sh STANDARDS
The
.Fn bsearch
function conforms to
.St -ansiC .

View File

@@ -0,0 +1,85 @@
/* $NetBSD: bsearch.c,v 1.14 2010/11/27 18:33:54 christos Exp $ */
/*
* 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. 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.
*/
#include <sys/cdefs.h>
#if defined(LIBC_SCCS) && !defined(lint)
#if 0
static char sccsid[] = "@(#)bsearch.c 8.1 (Berkeley) 6/4/93";
#else
__RCSID("$NetBSD: bsearch.c,v 1.14 2010/11/27 18:33:54 christos Exp $");
#endif
#endif /* LIBC_SCCS and not lint */
#include <assert.h>
#include <errno.h>
#include <stdlib.h>
/*
* Perform a binary search.
*
* The code below is a bit sneaky. After a comparison fails, we
* divide the work in half by moving either left or right. If lim
* is odd, moving left simply involves halving lim: e.g., when lim
* is 5 we look at item 2, so we change lim to 2 so that we will
* look at items 0 & 1. If lim is even, the same applies. If lim
* is odd, moving right again involes halving lim, this time moving
* the base up one item past p: e.g., when lim is 5 we change base
* to item 3 and make lim 2 so that we will look at items 3 and 4.
* If lim is even, however, we have to shrink it by one before
* halving: e.g., when lim is 4, we still looked at item 2, so we
* have to make lim 3, then halve, obtaining 1, so that we will only
* look at item 3.
*/
void *
bsearch(const void *key, const void *base0, size_t nmemb, size_t size,
int (*compar)(const void *, const void *))
{
const char *base = base0;
size_t lim;
int cmp;
const void *p;
_DIAGASSERT(key != NULL);
_DIAGASSERT(base0 != NULL);
_DIAGASSERT(compar != NULL);
for (lim = nmemb; lim != 0; lim >>= 1) {
p = base + (lim >> 1) * size;
cmp = (*compar)(key, p);
if (cmp == 0)
return __UNCONST(p);
if (cmp > 0) { /* key > p: move right */
base = (const char *)p + size;
lim--;
} /* else move left */
}
return (NULL);
}

View File

@@ -0,0 +1,71 @@
.\" $NetBSD: div.3,v 1.12 2008/08/04 21:29:27 matt Exp $
.\"
.\" Copyright (c) 1990, 1991, 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. 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.
.\"
.\" from: @(#)div.3 8.1 (Berkeley) 6/4/93
.\"
.Dd June 4, 1993
.Dt DIV 3
.Os
.Sh NAME
.Nm div
.Nd return quotient and remainder from division
.Sh LIBRARY
.Lb libc
.Sh SYNOPSIS
.In stdlib.h
.Ft div_t
.Fn div "int num" "int denom"
.Sh DESCRIPTION
The
.Fn div
function
computes the value
.Fa num/denom
and returns the quotient and remainder in a structure named
.Fa div_t
that contains two
.Em int
members named
.Fa quot
and
.Fa rem .
.Sh SEE ALSO
.Xr imaxdiv 3 ,
.Xr ldiv 3 ,
.Xr lldiv 3 ,
.Xr math 3 ,
.Xr qdiv 3
.Sh STANDARDS
The
.Fn div
function
conforms to
.St -ansiC .

View File

@@ -0,0 +1,82 @@
/* $NetBSD: div.c,v 1.7 2003/08/07 16:43:39 agc Exp $ */
/*
* 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. 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.
*/
#include <sys/cdefs.h>
#if defined(LIBC_SCCS) && !defined(lint)
#if 0
static char sccsid[] = "@(#)div.c 8.1 (Berkeley) 6/4/93";
#else
__RCSID("$NetBSD: div.c,v 1.7 2003/08/07 16:43:39 agc Exp $");
#endif
#endif /* LIBC_SCCS and not lint */
#include <stdlib.h> /* div_t */
div_t
div(num, denom)
int num, denom;
{
div_t r;
r.quot = num / denom;
r.rem = num % denom;
/*
* The ANSI standard says that |r.quot| <= |n/d|, where
* n/d is to be computed in infinite precision. In other
* words, we should always truncate the quotient towards
* 0, never -infinity.
*
* Machine division and remainer may work either way when
* one or both of n or d is negative. If only one is
* negative and r.quot has been truncated towards -inf,
* r.rem will have the same sign as denom and the opposite
* sign of num; if both are negative and r.quot has been
* truncated towards -inf, r.rem will be positive (will
* have the opposite sign of num). These are considered
* `wrong'.
*
* If both are num and denom are positive, r will always
* be positive.
*
* This all boils down to:
* if num >= 0, but r.rem < 0, we got the wrong answer.
* In that case, to get the right answer, add 1 to r.quot and
* subtract denom from r.rem.
*/
if (num >= 0 && r.rem < 0) {
r.quot++;
r.rem -= denom;
}
return (r);
}

View File

@@ -0,0 +1,32 @@
/* $NetBSD: drand48.c,v 1.6 2005/06/12 05:21:28 lukem Exp $ */
/*
* Copyright (c) 1993 Martin Birgmeier
* All rights reserved.
*
* You may redistribute unmodified or modified versions of this source
* code provided that the above copyright notice and this and the
* following conditions are retained.
*
* This software is provided ``as is'', and comes with no warranties
* of any kind. I shall in no event be liable for anything that happens
* to anyone/anything when using this software.
*/
#include <sys/cdefs.h>
#if defined(LIBC_SCCS) && !defined(lint)
__RCSID("$NetBSD: drand48.c,v 1.6 2005/06/12 05:21:28 lukem Exp $");
#endif /* LIBC_SCCS and not lint */
#include "namespace.h"
#include "rand48.h"
#ifdef __weak_alias
__weak_alias(drand48,_drand48)
#endif
double
drand48(void)
{
return erand48(__rand48_seed);
}

View File

@@ -0,0 +1,42 @@
/* $NetBSD: erand48.c,v 1.9 2006/03/22 20:52:16 drochner Exp $ */
/*
* Copyright (c) 1993 Martin Birgmeier
* All rights reserved.
*
* You may redistribute unmodified or modified versions of this source
* code provided that the above copyright notice and this and the
* following conditions are retained.
*
* This software is provided ``as is'', and comes with no warranties
* of any kind. I shall in no event be liable for anything that happens
* to anyone/anything when using this software.
*/
#include <sys/cdefs.h>
#if defined(LIBC_SCCS) && !defined(lint)
__RCSID("$NetBSD: erand48.c,v 1.9 2006/03/22 20:52:16 drochner Exp $");
#endif /* LIBC_SCCS and not lint */
#include "namespace.h"
#include <assert.h>
#include <math.h>
#include "rand48.h"
#ifdef __weak_alias
__weak_alias(erand48,_erand48)
#endif
double
erand48(unsigned short xseed[3])
{
_DIAGASSERT(xseed != NULL);
__dorand48(xseed);
return ldexp((double) xseed[0], -48) +
ldexp((double) xseed[1], -32) +
ldexp((double) xseed[2], -16);
}

View File

@@ -0,0 +1,47 @@
/* $NetBSD: erand48_ieee754.c,v 1.2 2006/03/31 11:42:31 drochner Exp $ */
/*
* Copyright (c) 1993 Martin Birgmeier
* All rights reserved.
*
* You may redistribute unmodified or modified versions of this source
* code provided that the above copyright notice and this and the
* following conditions are retained.
*
* This software is provided ``as is'', and comes with no warranties
* of any kind. I shall in no event be liable for anything that happens
* to anyone/anything when using this software.
*/
#include <sys/cdefs.h>
#if defined(LIBC_SCCS) && !defined(lint)
__RCSID("$NetBSD: erand48_ieee754.c,v 1.2 2006/03/31 11:42:31 drochner Exp $");
#endif /* LIBC_SCCS and not lint */
#include "namespace.h"
#include <assert.h>
#include <machine/ieee.h>
#include "rand48.h"
#ifdef __weak_alias
__weak_alias(erand48,_erand48)
#endif
double
erand48(unsigned short xseed[3])
{
union ieee_double_u u;
_DIAGASSERT(xseed != NULL);
__dorand48(xseed);
u.dblu_dbl.dbl_sign = 0;
u.dblu_dbl.dbl_exp = DBL_EXP_BIAS; /* so we get [1,2) */
u.dblu_dbl.dbl_frach = ((unsigned int)xseed[2] << 4)
| ((unsigned int)xseed[1] >> 12);
u.dblu_dbl.dbl_fracl = (((unsigned int)xseed[1] & 0x0fff) << 20)
| ((unsigned int)xseed[0] << 4);
return (u.dblu_d - 1);
}

101
lib/nbsd_libc/stdlib/exit.3 Normal file
View File

@@ -0,0 +1,101 @@
.\" $NetBSD: exit.3,v 1.14 2003/08/07 16:43:39 agc Exp $
.\"
.\" Copyright (c) 1990, 1991, 1993
.\" The Regents of the University of California. All rights reserved.
.\"
.\" This code is derived from software contributed to Berkeley by
.\" the American National Standards Committee X3, on Information
.\" Processing Systems.
.\"
.\" 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. 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.
.\"
.\" from: @(#)exit.3 8.1 (Berkeley) 6/4/93
.\"
.Dd August 11, 2002
.Dt EXIT 3
.Os
.Sh NAME
.Nm exit
.Nd perform normal program termination
.Sh LIBRARY
.Lb libc
.Sh SYNOPSIS
.In stdlib.h
.Ft void
.Fn exit "int status"
.Sh DESCRIPTION
.Fn exit
terminates a process.
The
.Fa status
values
.Dv EXIT_SUCCESS
and
.Dv EXIT_FAILURE
can be used to indicate successful and unsuccessful
termination, respectively.
.Pp
Before termination it performs the following functions in the
order listed:
.Bl -enum -offset indent
.It
Call the functions registered with the
.Xr atexit 3
function, in the reverse order of their registration.
.It
Flush all open output streams.
.It
Close all open streams.
.It
Unlink all files created with the
.Xr tmpfile 3
function.
.El
.Pp
Following this,
.Fn exit
calls
.Xr _exit 2 .
Note that typically
.Xr _exit 2
only passes the lower 8 bits of
.Fa status
on to the parent, thus negative values have less meaning.
.Sh RETURN VALUES
The
.Fn exit
function
never returns.
.Sh SEE ALSO
.Xr _exit 2 ,
.Xr atexit 3 ,
.Xr intro 3 ,
.Xr tmpfile 3
.Sh STANDARDS
The
.Fn exit
function
conforms to
.St -ansiC .

View File

@@ -0,0 +1,70 @@
/* $NetBSD: exit.c,v 1.13 2010/09/09 10:19:31 skrll Exp $ */
/*-
* 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. 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.
*/
#include <sys/cdefs.h>
#if defined(LIBC_SCCS) && !defined(lint)
#if 0
static char sccsid[] = "@(#)exit.c 8.1 (Berkeley) 6/4/93";
#else
__RCSID("$NetBSD: exit.c,v 1.13 2010/09/09 10:19:31 skrll Exp $");
#endif
#endif /* LIBC_SCCS and not lint */
#include <stdlib.h>
#include <unistd.h>
#ifdef _LIBC
#include "reentrant.h"
#include "atexit.h"
#endif
#ifdef _LIBC
extern void __libc_init(void);
#ifndef __lint
static void (*force_ref)(void) __used = __libc_init;
#endif
#endif
void (*__cleanup) __P((void));
/*
* Exit, flushing stdio buffers if necessary.
*/
void
exit(int status)
{
#ifdef _LIBC
__cxa_finalize(NULL);
#endif
if (__cleanup)
(*__cleanup)();
_exit(status);
}

View File

@@ -0,0 +1,227 @@
.\" $NetBSD: getenv.3,v 1.25 2010/10/26 22:34:33 wiz Exp $
.\"
.\" Copyright (c) 1988, 1991, 1993
.\" The Regents of the University of California. All rights reserved.
.\"
.\" This code is derived from software contributed to Berkeley by
.\" the American National Standards Committee X3, on Information
.\" Processing Systems.
.\"
.\" 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. 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.
.\"
.\" from: @(#)getenv.3 8.2 (Berkeley) 12/11/93
.\"
.Dd October 25, 2010
.Dt GETENV 3
.Os
.Sh NAME
.Nm getenv ,
.Nm getenv_r ,
.Nm putenv ,
.Nm setenv ,
.Nm unsetenv
.Nd environment variable functions
.Sh LIBRARY
.Lb libc
.Sh SYNOPSIS
.In stdlib.h
.Ft char *
.Fn getenv "const char *name"
.Ft int
.Fn getenv_r "const char *name" "char *buf" "size_t len"
.Ft int
.Fn setenv "const char *name" "const char *value" "int overwrite"
.Ft int
.Fn putenv "char *string"
.Ft int
.Fn unsetenv "const char *name"
.Sh DESCRIPTION
These functions set, unset and fetch environment variables from the
host
.Em environment list .
For compatibility with differing environment conventions,
the
.Fn getenv
or
.Fn getenv_r
given argument
.Ar name
may be appended with an equal sign
.Dq Li \&= .
.Pp
The
.Fn getenv
function obtains the current value of the environment variable
.Ar name .
If the variable
.Ar name
is not in the current environment, a
.Dv NULL
pointer is returned.
.Pp
The
.Fn getenv_r
function obtains the current value of the environment variable
.Fa name
and copies it to
.Fa buf .
If
.Fa name
is not in the current environment, or the string length of the value of
.Fa name
is longer than
.Fa len
characters, then \-1 is returned and
.Va errno
is set to indicate the error.
.Pp
The
.Fn setenv
function inserts or resets the environment variable
.Ar name
in the current environment list.
If the variable
.Ar name
does not exist in the list,
it is inserted with the given
.Ar value .
If the variable does exist, the argument
.Ar overwrite
is tested; if
.Ar overwrite is
zero, the
variable is not reset, otherwise it is reset
to the given
.Ar value .
.Pp
The
.Fn putenv
function takes an argument of the form
.Dq name=value
and it will set the environment variable
.Dq name
equal to
.Dq value
by altering an existing entry, or creating a new one if an existing
one does not exist.
The actual string argument passed to
.Fn putenv
will become part of the environment.
If one changes the string, the environment will also change.
.Pp
The
.Fn unsetenv
function
deletes all instances of the variable name pointed to by
.Fa name
from the list.
.Sh RETURN VALUES
The functions
.Fn getenv_r ,
.Fn setenv ,
.Fn putenv ,
and
.Fn unsetenv
return zero if successful; otherwise the global variable
.Va errno
is set to indicate the error and a
\-1 is returned.
.Pp
If
.Fn getenv
is successful, the string returned should be considered read-only.
.Sh ERRORS
.Bl -tag -width Er
.It Bq Er EINVAL
The
.Fa name
argument to
.Fn setenv
or
.Fn unsetenv
is a null pointer, points to an empty string, or points to a string
containing an
.Dq Li \&=
character.
The
.Fa value
argument to
.Fn setenv
is a null pointer.
The
.Fa string
argument to
.Fn putenv
is a null pointer, or points to a string that either starts with a
.Dq Li \&=
character or does not contain one at all.
.It Bq Er ENOMEM
The function
.Fn setenv
or
.Fn putenv
failed because they were unable to allocate memory for the environment.
.El
.Pp
The function
.Fn getenv_r
can return the following errors:
.Bl -tag -width Er
.It Bq Er ENOENT
The variable
.Fa name
was not found in the environment.
.It Bq Er ERANGE
The value of the named variable is too long to fit in the supplied buffer.
.El
.Sh SEE ALSO
.Xr csh 1 ,
.Xr sh 1 ,
.Xr execve 2 ,
.Xr environ 7
.Sh STANDARDS
The
.Fn getenv
function conforms to
.St -ansiC .
The
.Fn putenv
function conforms to
.St -xpg4 .
The
.Fn unsetenv
function conforms to
.St -p1003.1-2001 .
.Sh HISTORY
The functions
.Fn setenv
and
.Fn unsetenv
appeared in
.At v7 .
The
.Fn putenv
function appeared in
.Bx 4.3 Reno .

View File

@@ -0,0 +1,113 @@
/* $NetBSD: getenv.c,v 1.35 2010/11/14 22:04:36 tron Exp $ */
/*
* Copyright (c) 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. 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.
*/
#include <sys/cdefs.h>
#if defined(LIBC_SCCS) && !defined(lint)
#if 0
static char sccsid[] = "@(#)getenv.c 8.1 (Berkeley) 6/4/93";
#else
__RCSID("$NetBSD: getenv.c,v 1.35 2010/11/14 22:04:36 tron Exp $");
#endif
#endif /* LIBC_SCCS and not lint */
#include "namespace.h"
#include <assert.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include "env.h"
#include "reentrant.h"
#include "local.h"
__weak_alias(getenv_r, _getenv_r)
/*
* getenv --
* Returns ptr to value associated with name, if any, else NULL.
* XXX: we cannot use getenv_r to implement this, because getenv()
* cannot use a shared buffer, because if it did, subsequent calls
* to getenv would trash previous results.
*/
char *
getenv(const char *name)
{
size_t l_name;
char *result;
_DIAGASSERT(name != NULL);
l_name = __envvarnamelen(name, false);
if (l_name == 0)
return NULL;
result = NULL;
if (__readlockenv()) {
result = __findenvvar(name, l_name);
(void)__unlockenv();
}
return result;
}
int
getenv_r(const char *name, char *buf, size_t len)
{
size_t l_name;
int rv;
_DIAGASSERT(name != NULL);
l_name = __envvarnamelen(name, false);
if (l_name == 0) {
errno = ENOENT;
return -1;
}
rv = -1;
if (__readlockenv()) {
const char *value;
value = __findenvvar(name, l_name);
if (value != NULL) {
if (strlcpy(buf, value, len) < len) {
rv = 0;
} else {
errno = ERANGE;
}
} else {
errno = ENOENT;
}
(void)__unlockenv();
}
return rv;
}

View File

@@ -0,0 +1,299 @@
.\" $NetBSD: getopt.3,v 1.32 2010/03/22 19:30:54 joerg Exp $
.\"
.\" 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. 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 September 10, 2003
.Dt GETOPT 3
.Os
.Sh NAME
.Nm getopt
.Nd get option character from command line argument list
.Sh LIBRARY
.Lb libc
.Sh SYNOPSIS
.In 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
.Qq x
recognizes an option
.Dq Fl x ,
and an option string
.Qq x:
recognizes an option and argument
.Dq Fl x Ar argument .
It does not matter to
.Fn getopt
if a following argument has leading whitespace.
.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 variables
.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.
The interpretation of options in the argument list may be cancelled
by the option
.Dq --
(double dash) which causes
.Fn getopt
to signal the end of argument processing and return \-1.
When all options have been processed (i.e., up to the first non-option
argument),
.Fn getopt
returns \-1.
.Sh RETURN VALUES
The
.Fn getopt
function returns the next known option character in
.Fa optstring .
If
.Fn getopt
encounters a character not found in
.Fa optstring
or if it detects a missing option argument,
it returns
.Sq \&?
(question mark).
If
.Fa optstring
has a leading
.Sq \&:
then a missing option argument causes
.Sq \&:
to be returned instead of
.Sq \&? .
In either case, the variable
.Va optopt
is set to the character that caused the error.
The
.Fn getopt
function returns \-1 when the argument list is exhausted.
.Sh EXAMPLES
.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)) \*[Lt] 0) {
(void)fprintf(stderr,
"myname: %s: %s\en", optarg, strerror(errno));
exit(1);
}
break;
case '?':
default:
usage();
}
}
argc -= optind;
argv += optind;
.Ed
.Sh DIAGNOSTICS
If the
.Fn getopt
function encounters a character not found in the string
.Fa optstring
or detects
a missing option argument it writes an error message to
.Em stderr
and returns
.Sq \&? .
Setting
.Va opterr
to a zero will disable these error messages.
If
.Fa optstring
has a leading
.Sq \&:
then a missing option argument causes a
.Sq \&:
to be returned in addition to suppressing any error messages.
.Pp
Option arguments are allowed to begin with
.Sq - ;
this is reasonable but reduces the amount of error checking possible.
.Sh SEE ALSO
.Xr getopt 1 ,
.Xr getopt_long 3 ,
.Xr getsubopt 3
.Sh STANDARDS
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 HISTORY
The
.Fn getopt
function appeared in
.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
.In stdio.h .
.Pp
A single dash
.Pq Sq -
may be specified as a 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
.Sq -
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 .
Care should be taken not to use
.Sq -
as the first character in
.Fa optstring
to avoid a semantic conflict with
.Tn GNU
.Fn getopt ,
which assigns different meaning to an
.Fa optstring
that begins with a
.Sq - .
By default, a single dash causes
.Fn getopt
to return \-1.
.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 ch;
long length;
char *p;
while ((ch = getopt(argc, argv, "0123456789")) != -1) {
switch (ch) {
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] == '-' \*[Am]\*[Am] p[1] == ch \*[Am]\*[Am] !p[2])
length = ch - '0';
else
length = strtol(argv[optind] + 1, NULL, 10);
break;
}
}
.Ed

View File

@@ -0,0 +1,136 @@
/* $NetBSD: getopt.c,v 1.28 2009/03/20 13:56:57 joerg Exp $ */
/*
* 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. 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.
*/
#include <sys/cdefs.h>
__RCSID("$NetBSD: getopt.c,v 1.28 2009/03/20 13:56:57 joerg Exp $");
#include "namespace.h"
#include <assert.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#ifdef __weak_alias
__weak_alias(getopt,_getopt)
#endif
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(int nargc, char * const nargv[], const char *ostr)
{
static const char *place = EMSG; /* option letter processing */
char *oli; /* option letter list index */
_DIAGASSERT(nargv != NULL);
_DIAGASSERT(ostr != NULL);
if (optreset || *place == 0) { /* update scanning pointer */
optreset = 0;
place = nargv[optind];
if (optind >= nargc || *place++ != '-') {
/* Argument is absent or is not an option */
place = EMSG;
return (-1);
}
optopt = *place++;
if (optopt == '-' && *place == 0) {
/* "--" => end of options */
++optind;
place = EMSG;
return (-1);
}
if (optopt == 0) {
/* Solitary '-', treat as a '-' option
if the program (eg su) is looking for it. */
place = EMSG;
if (strchr(ostr, '-') == NULL)
return -1;
optopt = '-';
}
} else
optopt = *place++;
/* See if option letter is one the caller wanted... */
if (optopt == ':' || (oli = strchr(ostr, optopt)) == NULL) {
if (*place == 0)
++optind;
if (opterr && *ostr != ':')
(void)fprintf(stderr,
"%s: unknown option -- %c\n", getprogname(),
optopt);
return (BADCH);
}
/* Does this option need an argument? */
if (oli[1] != ':') {
/* don't need argument */
optarg = NULL;
if (*place == 0)
++optind;
} else {
/* Option-argument is either the rest of this argument or the
entire next argument. */
if (*place)
optarg = __UNCONST(place);
else if (nargc > ++optind)
optarg = nargv[optind];
else {
/* option-argument absent */
place = EMSG;
if (*ostr == ':')
return (BADARG);
if (opterr)
(void)fprintf(stderr,
"%s: option requires an argument -- %c\n",
getprogname(), optopt);
return (BADCH);
}
place = EMSG;
++optind;
}
return (optopt); /* return option letter */
}

View File

@@ -0,0 +1,310 @@
.\" $NetBSD: getopt_long.3,v 1.18 2007/07/02 17:56:17 ginsbach Exp $
.\"
.\" 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. 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 July 2, 2007
.Dt GETOPT_LONG 3
.Os
.Sh NAME
.Nm getopt_long
.Nd get long options from command line argument list
.Sh LIBRARY
.Lb libc
.Sh SYNOPSIS
.In getopt.h
.Ft int
.Fn getopt_long "int argc" "char * const *argv" "const char *optstring" "struct option *long_options" "int *index"
.Sh DESCRIPTION
The
.Fn getopt_long
function is similar to
.Xr getopt 3
but it accepts options in two forms: words and characters.
The
.Fn getopt_long
function provides a superset of the functionality of
.Xr getopt 3 .
.Fn getopt_long
can be used in two ways.
In the first way, every long option understood by the program has a
corresponding short option, and the option structure is only used to
translate from long options to short options.
When used in this fashion,
.Fn getopt_long
behaves identically to
.Xr getopt 3 .
This is a good way to add long option processing to an existing program
with the minimum of rewriting.
.Pp
In the second mechanism, a long option sets a flag in the
.Fa option
structure passed, or will store a pointer to the command line argument
in the
.Fa option
structure passed to it for options that take arguments.
Additionally, the long option's argument may be specified as a single
argument with an equal sign, e.g.
.Bd -literal
myprogram --myoption=somevalue
.Ed
.Pp
When a long option is processed the call to
.Fn getopt_long
will return 0.
For this reason, long option processing without
shortcuts is not backwards compatible with
.Xr getopt 3 .
.Pp
It is possible to combine these methods, providing for long options
processing with short option equivalents for some options.
Less frequently used options would be processed as long options only.
.Pp
Abbreviated long option names are accepted when
.Fn getopt_long
processes long options if the abbreviation is unique.
An exact match is always preferred for a defined long option.
.Pp
The
.Fn getopt_long
call requires a structure to be initialized describing the long options.
The structure is:
.Bd -literal
struct option {
char *name;
int has_arg;
int *flag;
int val;
};
.Ed
.Pp
The
.Fa name
field should contain the option name without the leading double dash.
.Pp
The
.Fa has_arg
field should be one of:
.Bl -tag -width "optional_argument"
.It Li no_argument
no argument to the option is expect.
.It Li required_argument
an argument to the option is required.
.It Li optional_argument
an argument to the option may be presented.
.El
.Pp
If
.Fa flag
is not
.Dv NULL ,
then the integer pointed to by it will be set to the value in the
.Fa val
field.
If the
.Fa flag
field is
.Dv NULL ,
then the
.Fa val
field will be returned.
Setting
.Fa flag
to
.Dv NULL
and setting
.Fa val
to the corresponding short option will make this function act just
like
.Xr getopt 3 .
.Pp
If the
.Fa index
field is not
.Dv NULL ,
the integer it points to will be set to the index of the long option
in the
.Fa long_options
array.
.Pp
The last element of the
.Fa long_options
array has to be filled with zeroes (see
.Sx EXAMPLES
section).
.Sh EXAMPLES
.Bd -literal -compact
extern char *optarg;
extern int optind;
int bflag, ch, fd;
int daggerset;
/* options descriptor */
static struct option longopts[] = {
{ "buffy", no_argument, 0, 'b' },
{ "fluoride", required_argument, 0, 'f' },
{ "daggerset", no_argument, \*[Am]daggerset, 1 },
{ NULL, 0, NULL, 0 }
};
bflag = 0;
while ((ch = getopt_long(argc, argv, "bf:", longopts, NULL)) != -1)
switch (ch) {
case 'b':
bflag = 1;
break;
case 'f':
if ((fd = open(optarg, O_RDONLY, 0)) \*[Lt] 0) {
(void)fprintf(stderr,
"myname: %s: %s\en", optarg, strerror(errno));
exit(1);
}
break;
case 0:
if(daggerset) {
fprintf(stderr,"Buffy will use her dagger to "
"apply fluoride to dracula's teeth\en");
}
break;
case '?':
default:
usage();
}
argc -= optind;
argv += optind;
.Ed
.Sh IMPLEMENTATION DIFFERENCES
This section describes differences to the GNU implementation
found in glibc-2.1.3:
.Bl -tag -width "xxx"
.It Li o
handling of - as first char of option string in presence of
environment variable POSIXLY_CORRECT:
.Bl -tag -width "NetBSD"
.It Li GNU
ignores POSIXLY_CORRECT and returns non-options as
arguments to option '\e1'.
.It Li NetBSD
honors POSIXLY_CORRECT and stops at the first non-option.
.El
.It Li o
handling of :: in options string in presence of POSIXLY_CORRECT:
.Bl -tag -width "NetBSD"
.It Li Both
GNU and NetBSD ignore POSIXLY_CORRECT here and take :: to
mean the preceding option takes an optional argument.
.El
.It Li o
return value in case of missing argument if first character
(after + or -) in option string is not ':':
.Bl -tag -width "NetBSD"
.It Li GNU
returns '?'
.It NetBSD
returns ':' (since NetBSD's getopt does).
.El
.It Li o
handling of --a in getopt:
.Bl -tag -width "NetBSD"
.It Li GNU
parses this as option '-', option 'a'.
.It Li NetBSD
parses this as '--', and returns \-1 (ignoring the a).
(Because the original getopt does.)
.El
.It Li o
setting of optopt for long options with flag !=
.Dv NULL :
.Bl -tag -width "NetBSD"
.It Li GNU
sets optopt to val.
.It Li NetBSD
sets optopt to 0 (since val would never be returned).
.El
.It Li o
handling of -W with W; in option string in getopt (not getopt_long):
.Bl -tag -width "NetBSD"
.It Li GNU
causes a segfault.
.It Li NetBSD
returns \-1, with optind pointing past the argument of -W
(as if `-W arg' were `--arg', and thus '--' had been found).
.\" How should we treat W; in the option string when called via
.\" getopt? Ignore the ';' or treat it as a ':'? Issue a warning?
.El
.It Li o
setting of optarg for long options without an argument that are
invoked via -W (W; in option string):
.Bl -tag -width "NetBSD"
.It Li GNU
sets optarg to the option name (the argument of -W).
.It Li NetBSD
sets optarg to
.Dv NULL
(the argument of the long option).
.El
.It Li o
handling of -W with an argument that is not (a prefix to) a known
long option (W; in option string):
.Bl -tag -width "NetBSD"
.It Li GNU
returns -W with optarg set to the unknown option.
.It Li NetBSD
treats this as an error (unknown option) and returns '?' with
optopt set to 0 and optarg set to
.Dv NULL
(as GNU's man page documents).
.El
.It Li o
The error messages are different.
.It Li o
NetBSD does not permute the argument vector at the same points in
the calling sequence as GNU does.
The aspects normally used by the caller
(ordering after \-1 is returned, value of optind relative
to current positions) are the same, though.
(We do fewer variable swaps.)
.El
.Sh SEE ALSO
.Xr getopt 3
.Sh HISTORY
The
.Fn getopt_long
function first appeared in GNU libiberty.
The first
.Nx
implementation appeared in 1.5.
.Sh BUGS
The implementation can completely replace
.Xr getopt 3 ,
but right now we are using separate code.
.Pp
The
.Fa argv
argument is not really const.

View File

@@ -0,0 +1,482 @@
/* $NetBSD: getopt_long.c,v 1.25 2009/03/20 14:05:54 joerg Exp $ */
/*-
* Copyright (c) 2000 The NetBSD Foundation, Inc.
* All rights reserved.
*
* This code is derived from software contributed to The NetBSD Foundation
* by Dieter Baron and Thomas Klausner.
*
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. 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 FOUNDATION 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 HAVE_NBTOOL_CONFIG_H
#include "nbtool_config.h"
#endif
#include <sys/cdefs.h>
__RCSID("$NetBSD: getopt_long.c,v 1.25 2009/03/20 14:05:54 joerg Exp $");
#include "namespace.h"
#include <assert.h>
#include <err.h>
#include <errno.h>
#if HAVE_NBTOOL_CONFIG_H
#include "compat_getopt.h"
#else
#include <getopt.h>
#endif
#include <stdlib.h>
#include <string.h>
#if HAVE_NBTOOL_CONFIG_H && !HAVE_GETOPT_LONG && !HAVE_DECL_OPTIND
#define REPLACE_GETOPT
#endif
#ifdef REPLACE_GETOPT
#ifdef __weak_alias
__weak_alias(getopt,_getopt)
#endif
int opterr = 1; /* if error message should be printed */
int optind = 1; /* index into parent argv vector */
int optopt = '?'; /* character checked for validity */
int optreset; /* reset getopt */
char *optarg; /* argument associated with option */
#elif HAVE_NBTOOL_CONFIG_H && !HAVE_DECL_OPTRESET
static int optreset;
#endif
#ifdef __weak_alias
__weak_alias(getopt_long,_getopt_long)
#endif
#define IGNORE_FIRST (*options == '-' || *options == '+')
#define PRINT_ERROR ((opterr) && ((*options != ':') \
|| (IGNORE_FIRST && options[1] != ':')))
#define IS_POSIXLY_CORRECT (getenv("POSIXLY_CORRECT") != NULL)
#define PERMUTE (!IS_POSIXLY_CORRECT && !IGNORE_FIRST)
/* XXX: GNU ignores PC if *options == '-' */
#define IN_ORDER (!IS_POSIXLY_CORRECT && *options == '-')
/* return values */
#define BADCH (int)'?'
#define BADARG ((IGNORE_FIRST && options[1] == ':') \
|| (*options == ':') ? (int)':' : (int)'?')
#define INORDER (int)1
#define EMSG ""
static int getopt_internal(int, char **, const char *);
static int gcd(int, int);
static void permute_args(int, int, int, char **);
static const char *place = EMSG; /* option letter processing */
/* XXX: set optreset to 1 rather than these two */
static int nonopt_start = -1; /* first non option argument (for permute) */
static int nonopt_end = -1; /* first option after non options (for permute) */
/* Error messages */
static const char recargchar[] = "option requires an argument -- %c";
static const char recargstring[] = "option requires an argument -- %s";
static const char ambig[] = "ambiguous option -- %.*s";
static const char noarg[] = "option doesn't take an argument -- %.*s";
static const char illoptchar[] = "unknown option -- %c";
static const char illoptstring[] = "unknown option -- %s";
/*
* Compute the greatest common divisor of a and b.
*/
static int
gcd(int a, int b)
{
int c;
c = a % b;
while (c != 0) {
a = b;
b = c;
c = a % b;
}
return b;
}
/*
* Exchange the block from nonopt_start to nonopt_end with the block
* from nonopt_end to opt_end (keeping the same order of arguments
* in each block).
*/
static void
permute_args(int panonopt_start, int panonopt_end, int opt_end, char **nargv)
{
int cstart, cyclelen, i, j, ncycle, nnonopts, nopts, pos;
char *swap;
_DIAGASSERT(nargv != NULL);
/*
* compute lengths of blocks and number and size of cycles
*/
nnonopts = panonopt_end - panonopt_start;
nopts = opt_end - panonopt_end;
ncycle = gcd(nnonopts, nopts);
cyclelen = (opt_end - panonopt_start) / ncycle;
for (i = 0; i < ncycle; i++) {
cstart = panonopt_end+i;
pos = cstart;
for (j = 0; j < cyclelen; j++) {
if (pos >= panonopt_end)
pos -= nnonopts;
else
pos += nopts;
swap = nargv[pos];
nargv[pos] = nargv[cstart];
nargv[cstart] = swap;
}
}
}
/*
* getopt_internal --
* Parse argc/argv argument vector. Called by user level routines.
* Returns -2 if -- is found (can be long option or end of options marker).
*/
static int
getopt_internal(int nargc, char **nargv, const char *options)
{
char *oli; /* option letter list index */
int optchar;
_DIAGASSERT(nargv != NULL);
_DIAGASSERT(options != NULL);
optarg = NULL;
/*
* XXX Some programs (like rsyncd) expect to be able to
* XXX re-initialize optind to 0 and have getopt_long(3)
* XXX properly function again. Work around this braindamage.
*/
if (optind == 0)
optind = 1;
if (optreset)
nonopt_start = nonopt_end = -1;
start:
if (optreset || !*place) { /* update scanning pointer */
optreset = 0;
if (optind >= nargc) { /* end of argument vector */
place = EMSG;
if (nonopt_end != -1) {
/* do permutation, if we have to */
permute_args(nonopt_start, nonopt_end,
optind, nargv);
optind -= nonopt_end - nonopt_start;
}
else if (nonopt_start != -1) {
/*
* If we skipped non-options, set optind
* to the first of them.
*/
optind = nonopt_start;
}
nonopt_start = nonopt_end = -1;
return -1;
}
if ((*(place = nargv[optind]) != '-')
|| (place[1] == '\0')) { /* found non-option */
place = EMSG;
if (IN_ORDER) {
/*
* GNU extension:
* return non-option as argument to option 1
*/
optarg = nargv[optind++];
return INORDER;
}
if (!PERMUTE) {
/*
* if no permutation wanted, stop parsing
* at first non-option
*/
return -1;
}
/* do permutation */
if (nonopt_start == -1)
nonopt_start = optind;
else if (nonopt_end != -1) {
permute_args(nonopt_start, nonopt_end,
optind, nargv);
nonopt_start = optind -
(nonopt_end - nonopt_start);
nonopt_end = -1;
}
optind++;
/* process next argument */
goto start;
}
if (nonopt_start != -1 && nonopt_end == -1)
nonopt_end = optind;
if (place[1] && *++place == '-') { /* found "--" */
place++;
return -2;
}
}
if ((optchar = (int)*place++) == (int)':' ||
(oli = strchr(options + (IGNORE_FIRST ? 1 : 0), optchar)) == NULL) {
/* option letter unknown or ':' */
if (!*place)
++optind;
if (PRINT_ERROR)
warnx(illoptchar, optchar);
optopt = optchar;
return BADCH;
}
if (optchar == 'W' && oli[1] == ';') { /* -W long-option */
/* XXX: what if no long options provided (called by getopt)? */
if (*place)
return -2;
if (++optind >= nargc) { /* no arg */
place = EMSG;
if (PRINT_ERROR)
warnx(recargchar, optchar);
optopt = optchar;
return BADARG;
} else /* white space */
place = nargv[optind];
/*
* Handle -W arg the same as --arg (which causes getopt to
* stop parsing).
*/
return -2;
}
if (*++oli != ':') { /* doesn't take argument */
if (!*place)
++optind;
} else { /* takes (optional) argument */
optarg = NULL;
if (*place) /* no white space */
optarg = __UNCONST(place);
/* XXX: disable test for :: if PC? (GNU doesn't) */
else if (oli[1] != ':') { /* arg not optional */
if (++optind >= nargc) { /* no arg */
place = EMSG;
if (PRINT_ERROR)
warnx(recargchar, optchar);
optopt = optchar;
return BADARG;
} else
optarg = nargv[optind];
}
place = EMSG;
++optind;
}
/* dump back option letter */
return optchar;
}
#ifdef REPLACE_GETOPT
/*
* getopt --
* Parse argc/argv argument vector.
*
* [eventually this will replace the real getopt]
*/
int
getopt(nargc, nargv, options)
int nargc;
char * const *nargv;
const char *options;
{
int retval;
_DIAGASSERT(nargv != NULL);
_DIAGASSERT(options != NULL);
retval = getopt_internal(nargc, __UNCONST(nargv), options);
if (retval == -2) {
++optind;
/*
* We found an option (--), so if we skipped non-options,
* we have to permute.
*/
if (nonopt_end != -1) {
permute_args(nonopt_start, nonopt_end, optind,
nargv);
optind -= nonopt_end - nonopt_start;
}
nonopt_start = nonopt_end = -1;
retval = -1;
}
return retval;
}
#endif
/*
* getopt_long --
* Parse argc/argv argument vector.
*/
int
getopt_long(int nargc, char * const *nargv, const char *options,
const struct option *long_options, int *idx)
{
int retval;
#define IDENTICAL_INTERPRETATION(_x, _y) \
(long_options[(_x)].has_arg == long_options[(_y)].has_arg && \
long_options[(_x)].flag == long_options[(_y)].flag && \
long_options[(_x)].val == long_options[(_y)].val)
_DIAGASSERT(nargv != NULL);
_DIAGASSERT(options != NULL);
_DIAGASSERT(long_options != NULL);
/* idx may be NULL */
retval = getopt_internal(nargc, __UNCONST(nargv), options);
if (retval == -2) {
char *current_argv, *has_equal;
size_t current_argv_len;
int i, ambiguous, match;
current_argv = __UNCONST(place);
match = -1;
ambiguous = 0;
optind++;
place = EMSG;
if (*current_argv == '\0') { /* found "--" */
/*
* We found an option (--), so if we skipped
* non-options, we have to permute.
*/
if (nonopt_end != -1) {
permute_args(nonopt_start, nonopt_end,
optind, __UNCONST(nargv));
optind -= nonopt_end - nonopt_start;
}
nonopt_start = nonopt_end = -1;
return -1;
}
if ((has_equal = strchr(current_argv, '=')) != NULL) {
/* argument found (--option=arg) */
current_argv_len = has_equal - current_argv;
has_equal++;
} else
current_argv_len = strlen(current_argv);
for (i = 0; long_options[i].name; i++) {
/* find matching long option */
if (strncmp(current_argv, long_options[i].name,
current_argv_len))
continue;
if (strlen(long_options[i].name) ==
(unsigned)current_argv_len) {
/* exact match */
match = i;
ambiguous = 0;
break;
}
if (match == -1) /* partial match */
match = i;
else if (!IDENTICAL_INTERPRETATION(i, match))
ambiguous = 1;
}
if (ambiguous) {
/* ambiguous abbreviation */
if (PRINT_ERROR)
warnx(ambig, (int)current_argv_len,
current_argv);
optopt = 0;
return BADCH;
}
if (match != -1) { /* option found */
if (long_options[match].has_arg == no_argument
&& has_equal) {
if (PRINT_ERROR)
warnx(noarg, (int)current_argv_len,
current_argv);
/*
* XXX: GNU sets optopt to val regardless of
* flag
*/
if (long_options[match].flag == NULL)
optopt = long_options[match].val;
else
optopt = 0;
return BADARG;
}
if (long_options[match].has_arg == required_argument ||
long_options[match].has_arg == optional_argument) {
if (has_equal)
optarg = has_equal;
else if (long_options[match].has_arg ==
required_argument) {
/*
* optional argument doesn't use
* next nargv
*/
optarg = nargv[optind++];
}
}
if ((long_options[match].has_arg == required_argument)
&& (optarg == NULL)) {
/*
* Missing argument; leading ':'
* indicates no error should be generated
*/
if (PRINT_ERROR)
warnx(recargstring, current_argv);
/*
* XXX: GNU sets optopt to val regardless
* of flag
*/
if (long_options[match].flag == NULL)
optopt = long_options[match].val;
else
optopt = 0;
--optind;
return BADARG;
}
} else { /* unknown option */
if (PRINT_ERROR)
warnx(illoptstring, current_argv);
optopt = 0;
return BADCH;
}
if (long_options[match].flag) {
*long_options[match].flag = long_options[match].val;
retval = 0;
} else
retval = long_options[match].val;
if (idx)
*idx = match;
}
return retval;
#undef IDENTICAL_INTERPRETATION
}

View File

@@ -0,0 +1,148 @@
.\" $NetBSD: getsubopt.3,v 1.14 2009/11/17 15:02:08 wiz Exp $
.\"
.\" 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. 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.
.\"
.\" @(#)getsubopt.3 8.1 (Berkeley) 6/9/93
.\"
.Dd November 17, 2009
.Dt GETSUBOPT 3
.Os
.Sh NAME
.Nm getsubopt
.Nd get sub options from an argument
.Sh LIBRARY
.Lb libc
.Sh SYNOPSIS
.In unistd.h
.Vt extern char *suboptarg
.Ft int
.Fn getsubopt "char **optionp" "char * const *tokens" "char **valuep"
.Sh DESCRIPTION
The
.Fn getsubopt
function
parses a string containing tokens delimited by one or more tab, space or
comma
.Pq Ql \&,
characters.
It is intended for use in parsing groups of option arguments provided
as part of a utility command line.
.Pp
The argument
.Fa optionp
is a pointer to a pointer to the string.
The argument
.Fa tokens
is a pointer to a
.Dv NULL Ns -terminated
array of pointers to strings.
.Pp
The
.Fn getsubopt
function
returns the zero-based offset of the pointer in the
.Fa tokens
array referencing a string which matches the first token
in the string, or \-1 if the string contains no tokens or
.Fa tokens
does not contain a matching string.
.Pp
If the token is of the form ``name=value'', the location referenced by
.Fa valuep
will be set to point to the start of the ``value'' portion of the token.
.Pp
On return from
.Fn getsubopt ,
.Fa optionp
will be set to point to the start of the next token in the string,
or the null at the end of the string if no more tokens are present.
The external variable
.Fa suboptarg
will be set to point to the start of the current token, or
.Dv NULL
if no
tokens were present.
The argument
.Fa valuep
will be set to point to the ``value'' portion of the token, or
.Dv NULL
if no ``value'' portion was present.
.Sh EXAMPLES
.Bd -literal -compact
char *tokens[] = {
#define ONE 0
"one",
#define TWO 1
"two",
NULL
};
\&...
extern char *optarg, *suboptarg;
char *options, *value;
while ((ch = getopt(argc, argv, "ab:")) != \-1) {
switch(ch) {
case 'a':
/* process ``a'' option */
break;
case 'b':
options = optarg;
while (*options) {
switch(getsubopt(\*[Am]options, tokens, \*[Am]value)) {
case ONE:
/* process ``one'' sub option */
break;
case TWO:
/* process ``two'' sub option */
if (!value)
error("no value for two");
i = atoi(value);
break;
case \-1:
if (suboptarg)
error("unknown sub option %s",
suboptarg);
else
error("missing sub option");
break;
}
break;
}
.Ed
.Sh SEE ALSO
.Xr getopt 3 ,
.Xr strsep 3
.Sh HISTORY
The
.Fn getsubopt
function first appeared in
.Bx 4.4 ,
and is included in
.St -p1003.1-2008 .

View File

@@ -0,0 +1,114 @@
/* $NetBSD: getsubopt.c,v 1.8 2004/05/09 19:34:11 kleink Exp $ */
/*-
* 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. 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.
*/
#include <sys/cdefs.h>
#if defined(LIBC_SCCS) && !defined(lint)
#if 0
static char sccsid[] = "@(#)getsubopt.c 8.1 (Berkeley) 6/4/93";
#else
__RCSID("$NetBSD: getsubopt.c,v 1.8 2004/05/09 19:34:11 kleink Exp $");
#endif
#endif /* LIBC_SCCS and not lint */
#include "namespace.h"
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#ifdef __weak_alias
__weak_alias(getsubopt,_getsubopt)
#endif
/*
* The SVID interface to getsubopt provides no way of figuring out which
* part of the suboptions list wasn't matched. This makes error messages
* tricky... The extern variable suboptarg is a pointer to the token
* which didn't match.
*/
char *suboptarg;
int
getsubopt(optionp, tokens, valuep)
char **optionp, **valuep;
char * const *tokens;
{
int cnt;
char *p;
_DIAGASSERT(tokens != NULL);
_DIAGASSERT(valuep != NULL);
/* optionp is tested below */
suboptarg = *valuep = NULL;
if (!optionp || !*optionp)
return(-1);
/* skip leading white-space, commas */
for (p = *optionp; *p && (*p == ',' || *p == ' ' || *p == '\t'); ++p);
if (!*p) {
*optionp = p;
return(-1);
}
/* save the start of the token, and skip the rest of the token. */
for (suboptarg = p;
*++p && *p != ',' && *p != '=' && *p != ' ' && *p != '\t';);
if (*p) {
/*
* If there's an equals sign, set the value pointer, and
* skip over the value part of the token. Terminate the
* token.
*/
if (*p == '=') {
*p = '\0';
for (*valuep = ++p;
*p && *p != ',' && *p != ' ' && *p != '\t'; ++p);
if (*p)
*p++ = '\0';
} else
*p++ = '\0';
/* Skip any whitespace or commas after this token. */
for (; *p && (*p == ',' || *p == ' ' || *p == '\t'); ++p);
}
/* set optionp for next round. */
*optionp = p;
for (cnt = 0; *tokens; ++tokens, ++cnt)
if (!strcmp(suboptarg, *tokens))
return(cnt);
return(-1);
}

View File

@@ -0,0 +1,97 @@
.\" $NetBSD: grantpt.3,v 1.4 2008/04/30 13:10:51 martin Exp $
.\"
.\" Copyright (c) 2004 The NetBSD Foundation, Inc.
.\" All rights reserved.
.\"
.\" This code is derived from software contributed to The NetBSD Foundation
.\" by Christos Zoulas.
.\"
.\" 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.
.\"
.\" THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
.\"
.Dd May 25, 2004
.Dt GRANTPT 3
.Os
.Sh NAME
.Nm grantpt
.Nd grant access to a slave pseudo-terminal device
.Sh LIBRARY
.Lb libc
.Sh SYNOPSIS
.In stdlib.h
.Ft int
.Fn grantpt "int fildes"
.Sh DESCRIPTION
The
.Fn grantpt
function changes the mode and ownership of the slave pseudo-terminal device
that corresponds to the master pseudo-terminal device associated with
.Fa fildes
to be owned by the real user id of the calling process, group id of
.Dv tty .
The permissions are set to readable and writable by owner, and writable by
group.
If the slave pseudo-terminal device was being accessed by other file
descriptors at the time, all such access will be revoked.
.Sh RETURN VALUES
If successful,
.Fn grantpt
returns 0; otherwise a value of \-1 is returned and
.Va errno
is set to indicate the error.
.Sh ERRORS
The
.Fn grantpt
function will fail if:
.Bl -tag -width Er
.It Bq Er EACCESS
the corresponding pseudo-terminal device could not be accessed.
.It Bq Er EBADF
.Fa fildes
is not a valid descriptor.
.It Bq Er EINVAL
.Fa fildes
is not associated with a master pseudo-terminal device.
.El
.Sh NOTES
Setting the group to
.Dv tty
and revoking accesses by other file descriptors are
.Nx
extensions.
Calling
.Fn grantpt
is equivalent to:
.Bd -literal
ioctl(fildes, TIOCGRANTPT, 0);
.Ed
.Sh SEE ALSO
.Xr ioctl 2 ,
.Xr posix_openpt 3 ,
.Xr ptsname 3 ,
.Xr unlockpt 3
.Sh STANDARDS
The
.Fn grantpt
function conforms to
.St -p1003.1-2001 .
Its first release was in
.St -xpg4.2 .

View File

@@ -0,0 +1,240 @@
.\" $NetBSD: hcreate.3,v 1.8 2010/05/01 06:18:03 jruoho Exp $
.\"
.\" Copyright (c) 1999 The NetBSD Foundation, Inc.
.\" All rights reserved.
.\"
.\" This code is derived from software contributed to The NetBSD Foundation
.\" by Klaus Klein.
.\"
.\" 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.
.\"
.\" THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
.\"
.Dd May 1, 2010
.Dt HCREATE 3
.Os
.Sh NAME
.Nm hcreate ,
.Nm hdestroy ,
.Nm hsearch
.Nd manage hash search table
.Sh LIBRARY
.Lb libc
.Sh SYNOPSIS
.In search.h
.Ft int
.Fn hcreate "size_t nel"
.Ft void
.Fn hdestroy "void"
.Ft ENTRY *
.Fn hsearch "ENTRY item" "ACTION action"
.Sh DESCRIPTION
The
.Fn hcreate ,
.Fn hdestroy
and
.Fn hsearch
functions manage hash search tables.
.Pp
The
.Fn hcreate
function allocates and initializes the table.
The
.Fa nel
argument specifies an estimate of the maximum number of entries to be held
by the table.
Unless further memory allocation fails, supplying an insufficient
.Fa nel
value will not result in functional harm, although a performance degradation
may occur.
Initialization using the
.Fn hcreate
function is mandatory prior to any access operations using
.Fn hsearch .
.Pp
The
.Fn hdestroy
function destroys a table previously created using
.Fn hcreate .
After a call to
.Fn hdestroy ,
the data can no longer be accessed.
.Pp
The
.Fn hsearch
function is used to search to the hash table.
It returns a pointer into the
hash table indicating the address of an item.
The
.Fa item
argument is of type
.Vt ENTRY ,
defined in the
.In search.h
header.
This is a structure type that contains two pointers:
.Pp
.Bl -tag -compact -offset indent -width "void *data "
.It Fa char *key
comparison key
.It Fa void *data
pointer to data associated with
.Fa key
.El
.Pp
The key comparison function used by
.Fn hsearch
is
.Xr strcmp 3 .
.Pp
The
.Fa action
argument is of type
.Vt ACTION ,
an enumeration type which defines the following values:
.Bl -tag -offset indent -width ENTERXX
.It Dv ENTER
Insert
.Fa item
into the hash table.
If an existing item with the same key is found, it is not replaced.
Note that the
.Fa key
and
.Fa data
elements of
.Fa item
are used directly by the new table entry.
The storage for the
key must not be modified during the lifetime of the hash table.
.It Dv FIND
Search the hash table without inserting
.Fa item .
.El
.Pp
Note that the comparison
.Fa key
must be allocated using
.Xr malloc 3
or
.Xr calloc 3
if action is
.Dv ENTER
and
.Fn hdestroy
will be called.
This is because
.Fn hdestroy
will call
.Xr free 3
for each comparison
.Fa key
(but not
.Fa data ) .
Typically the comparison
.Fa key
is allocated by using
.Xr strdup 3 .
.Sh RETURN VALUES
If successful, the
.Fn hcreate
function returns a non-zero value.
Otherwise, a value of 0 is returned and
.Va errno
is set to indicate the error.
.Pp
The
.Fn hdestroy
functions
returns no value.
.Pp
If successful, the
.Fn hsearch
function returns a pointer to hash table entry matching
the provided key.
If the action is
.Dv FIND
and the item was not found, or if the action is
.Dv ENTER
and the insertion failed,
.Dv NULL
is returned and
.Va errno
is set to indicate the error.
If the action is
.Dv ENTER
and an entry already existed in the table matching the given
key, the existing entry is returned and is not replaced.
.Sh ERRORS
The
.Fn hcreate
and
.Fn hsearch
functions will fail if:
.Bl -tag -width Er
.It Bq Er ENOMEM
Insufficient memory is available.
.El
.Sh SEE ALSO
.Xr bsearch 3 ,
.Xr lsearch 3 ,
.Xr malloc 3 ,
.Xr strcmp 3
.Sh STANDARDS
The
.Fn hcreate ,
.Fn hdestroy
and
.Fn hsearch
functions conform to
.St -xpg4.2 .
.Sh HISTORY
The
.Fn hcreate ,
.Fn hdestroy
and
.Fn hsearch
functions first appeared in
.At V .
.Sh CAVEATS
At least the following limitations can be mentioned:
.Bl -bullet
.It
The interface permits the use of only one hash table at a time.
.It
Individual hash table entries can be added, but not deleted.
.It
The standard is indecipherable about the
internal memory usage of the functions,
mentioning only that
.Do
.Fn hcreate
and
.Fn hsearch
functions may use
.Fn malloc
to allocate space
.Dc .
This limits the portability of the functions,
given that other implementations may not
.Xr free 3
the buffer pointed by
.Fa key .
.El

View File

@@ -0,0 +1,196 @@
/* $NetBSD: hcreate.c,v 1.6 2008/07/21 12:05:43 lukem Exp $ */
/*
* Copyright (c) 2001 Christopher G. Demetriou
* 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 for the
* NetBSD Project. See http://www.NetBSD.org/ for
* information about NetBSD.
* 4. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
*
* <<Id: LICENSE,v 1.2 2000/06/14 15:57:33 cgd Exp>>
*/
/*
* hcreate() / hsearch() / hdestroy()
*
* SysV/XPG4 hash table functions.
*
* Implementation done based on NetBSD manual page and Solaris manual page,
* plus my own personal experience about how they're supposed to work.
*
* I tried to look at Knuth (as cited by the Solaris manual page), but
* nobody had a copy in the office, so...
*/
#include <sys/cdefs.h>
#if defined(LIBC_SCCS) && !defined(lint)
__RCSID("$NetBSD: hcreate.c,v 1.6 2008/07/21 12:05:43 lukem Exp $");
#endif /* LIBC_SCCS and not lint */
#if !defined(lint)
__COPYRIGHT("@(#) Copyright (c) 2001\
Christopher G. Demetriou. All rights reserved.");
#endif /* not lint */
#include "namespace.h"
#include <assert.h>
#include <errno.h>
#include <inttypes.h>
#include <search.h>
#include <stdlib.h>
#include <string.h>
#include <sys/queue.h>
/*
* DO NOT MAKE THIS STRUCTURE LARGER THAN 32 BYTES (4 ptrs on 64-bit
* ptr machine) without adjusting MAX_BUCKETS_LG2 below.
*/
struct internal_entry {
SLIST_ENTRY(internal_entry) link;
ENTRY ent;
};
SLIST_HEAD(internal_head, internal_entry);
#define MIN_BUCKETS_LG2 4
#define MIN_BUCKETS (1 << MIN_BUCKETS_LG2)
/*
* max * sizeof internal_entry must fit into size_t.
* assumes internal_entry is <= 32 (2^5) bytes.
*/
#define MAX_BUCKETS_LG2 (sizeof (size_t) * 8 - 1 - 5)
#define MAX_BUCKETS ((size_t)1 << MAX_BUCKETS_LG2)
/* Default hash function, from db/hash/hash_func.c */
extern u_int32_t (*__default_hash)(const void *, size_t);
static struct internal_head *htable;
static size_t htablesize;
int
hcreate(size_t nel)
{
size_t idx;
unsigned int p2;
/* Make sure this isn't called when a table already exists. */
_DIAGASSERT(htable == NULL);
if (htable != NULL) {
errno = EINVAL;
return 0;
}
/* If nel is too small, make it min sized. */
if (nel < MIN_BUCKETS)
nel = MIN_BUCKETS;
/* If it's too large, cap it. */
if (nel > MAX_BUCKETS)
nel = MAX_BUCKETS;
/* If it's is not a power of two in size, round up. */
if ((nel & (nel - 1)) != 0) {
for (p2 = 0; nel != 0; p2++)
nel >>= 1;
_DIAGASSERT(p2 <= MAX_BUCKETS_LG2);
nel = 1 << p2;
}
/* Allocate the table. */
htablesize = nel;
htable = malloc(htablesize * sizeof htable[0]);
if (htable == NULL) {
errno = ENOMEM;
return 0;
}
/* Initialize it. */
for (idx = 0; idx < htablesize; idx++)
SLIST_INIT(&htable[idx]);
return 1;
}
void
hdestroy(void)
{
struct internal_entry *ie;
size_t idx;
_DIAGASSERT(htable != NULL);
if (htable == NULL)
return;
for (idx = 0; idx < htablesize; idx++) {
while (!SLIST_EMPTY(&htable[idx])) {
ie = SLIST_FIRST(&htable[idx]);
SLIST_REMOVE_HEAD(&htable[idx], link);
free(ie->ent.key);
free(ie);
}
}
free(htable);
htable = NULL;
}
ENTRY *
hsearch(ENTRY item, ACTION action)
{
struct internal_head *head;
struct internal_entry *ie;
uint32_t hashval;
size_t len;
_DIAGASSERT(htable != NULL);
_DIAGASSERT(item.key != NULL);
_DIAGASSERT(action == ENTER || action == FIND);
len = strlen(item.key);
hashval = (*__default_hash)(item.key, len);
head = &htable[hashval & (htablesize - 1)];
ie = SLIST_FIRST(head);
while (ie != NULL) {
if (strcmp(ie->ent.key, item.key) == 0)
break;
ie = SLIST_NEXT(ie, link);
}
if (ie != NULL)
return &ie->ent;
else if (action == FIND)
return NULL;
ie = malloc(sizeof *ie);
if (ie == NULL)
return NULL;
ie->ent.key = item.key;
ie->ent.data = item.data;
SLIST_INSERT_HEAD(head, ie, link);
return &ie->ent;
}

View File

@@ -0,0 +1,70 @@
.\" $NetBSD: imaxabs.3,v 1.2 2010/03/21 13:39:51 jruoho Exp $
.\"
.\" Copyright (c) 1990, 1991, 1993
.\" The Regents of the University of California. All rights reserved.
.\"
.\" This code is derived from software contributed to Berkeley by
.\" the American National Standards Committee X3, on Information
.\" Processing Systems.
.\"
.\" 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. 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.
.\"
.\" from: @(#)labs.3 8.1 (Berkeley) 6/4/93
.\"
.Dd March 6, 2000
.Dt IMAXABS 3
.Os
.Sh NAME
.Nm imaxabs
.Nd return the absolute value of a imaxint_t
.Sh LIBRARY
.Lb libc
.Sh SYNOPSIS
.In inttypes.h
.Ft intmax_t
.Fn imaxabs "intmax_t i"
.Sh DESCRIPTION
The
.Fn imaxabs
function
returns the absolute value of the
.Vt imaxint_t
integer
.Ar j .
.Sh SEE ALSO
.Xr abs 3 ,
.Xr cabs 3 ,
.Xr floor 3 ,
.Xr labs 3 ,
.Xr llabs 3 ,
.Xr math 3
.Sh STANDARDS
The
.Fn imaxabs
function
conforms to
.St -isoC-99 .
.Sh BUGS
The absolute value of the most negative integer remains negative.

View File

@@ -0,0 +1,49 @@
/* $NetBSD: imaxabs.c,v 1.1 2008/08/04 21:29:27 matt Exp $ */
/*-
* Copyright (c) 2008 The NetBSD Foundation, Inc.
* All rights reserved.
*
* This code is derived from software contributed to The NetBSD Foundation
* by Matt Thomas <matt@3am-software.com>
*
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
*/
#include <sys/cdefs.h>
#if !defined(lint)
__RCSID("$NetBSD: imaxabs.c,v 1.1 2008/08/04 21:29:27 matt Exp $");
#endif
#include "namespace.h"
#include <inttypes.h>
#ifdef __weak_alias
__weak_alias(imaxabs, _imaxabs)
#endif
intmax_t
imaxabs(intmax_t i)
{
return i < 0 ? -i : i;
}

View File

@@ -0,0 +1,75 @@
.\" $NetBSD: imaxdiv.3,v 1.1 2008/08/04 21:29:27 matt Exp $
.\"
.\" Copyright (c) 1990, 1991, 1993
.\" The Regents of the University of California. All rights reserved.
.\"
.\" This code is derived from software contributed to Berkeley by
.\" Chris Torek and the American National Standards Committee X3,
.\" on Information Processing Systems.
.\"
.\" 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. 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.
.\"
.\" from: @(#)ldiv.3 8.1 (Berkeley) 6/4/93
.\"
.Dd March 6, 2000
.Dt IMAXDIV 3
.Os
.Sh NAME
.Nm imaxdiv
.Nd return quotient and remainder from division
.Sh LIBRARY
.Lb libc
.Sh SYNOPSIS
.In inttypes.h
.Ft imaxdiv_t
.Fn imaxdiv "intmax_t num" "intmax_t denom"
.Sh DESCRIPTION
The
.Fn imaxdiv
function
divides
.Ar num
by
.Ar denom
and returns the resulting quotient and remainder in a structure named
.Ar imaxdiv_t
that contains two
.Em imaxint_t
members named
.Ar quot
and
.Ar rem .
.Sh SEE ALSO
.Xr div 3 ,
.Xr ldiv 3 ,
.Xr lldiv 3 ,
.Xr math 3 ,
.Xr qdiv 3
.Sh STANDARDS
The
.Fn imaxdiv
function
conforms to
.St -isoC-99 .

View File

@@ -0,0 +1,66 @@
/* $NetBSD: imaxdiv.c,v 1.1 2008/08/04 21:29:27 matt Exp $ */
/*
* Copyright (c) 1990, 1993
* The Regents of the University of California. Aimax 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 foimaxowing conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the foimaxowing disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the foimaxowing disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. 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.
*/
#include <sys/cdefs.h>
#if defined(LIBC_SCCS) && !defined(lint)
#if 0
static char sccsid[] = "from: @(#)ldiv.c 8.1 (Berkeley) 6/4/93";
#else
__RCSID("$NetBSD: imaxdiv.c,v 1.1 2008/08/04 21:29:27 matt Exp $");
#endif
#endif /* LIBC_SCCS and not lint */
#include "namespace.h"
#include <inttypes.h> /* imaxdiv_t */
#ifdef __weak_alias
__weak_alias(imaxdiv, _imaxdiv)
#endif
/* LONGLONG */
imaxdiv_t
imaxdiv(intmax_t num, intmax_t denom)
{
imaxdiv_t r;
/* see div.c for comments */
r.quot = num / denom;
r.rem = num % denom;
if (num >= 0 && r.rem < 0) {
r.quot++;
r.rem -= denom;
}
return (r);
}

View File

@@ -0,0 +1,80 @@
.\" Copyright (c) 1993 John Brezak
.\" 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. The name of the author may be used to endorse or promote products
.\" derived from this software without specific prior written permission.
.\"
.\" THIS SOFTWARE IS PROVIDED BY THE AUTHOR `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 AUTHOR 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.
.\"
.\" $NetBSD: insque.3,v 1.5 2010/04/30 10:24:02 jruoho Exp $
.\"
.Dd April 30, 2010
.Dt INSQUE 3
.Os
.Sh NAME
.Nm insque ,
.Nm remque
.Nd insert/remove element from a queue
.Sh LIBRARY
.Lb libc
.Sh SYNOPSIS
.In search.h
.Ft void
.Fn insque "void *elem" "void *pred"
.Ft void
.Fn remque "void *elem"
.Sh DESCRIPTION
.Fn insque
and
.Fn remque
manipulate queues built from doubly linked lists.
The queue can be either circular or linear.
The functions expect their
arguments to point to a structure whose first and second members are
pointers to the next and previous element, respectively.
The
.Fn insque
function also allows the
.Fa pred
argument to be a
.Dv NULL
pointer for the initialization of a new linear list's
head element.
.Sh STANDARDS
The
.Fn insque
and
.Fn remque
functions conform to
.St -p1003.1-2001 .
.Sh HISTORY
The
.Fn insque
and
.Fn remque
are derived from the
.Sq insque
and
.Sq remque
instructions on the
.Tn VAX .
They first appeared in
.Bx 4.2 .

View File

@@ -0,0 +1,60 @@
/*
* Copyright (c) 1993 John Brezak
* 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. The name of the author may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR `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 AUTHOR 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.
*/
#include <sys/cdefs.h>
#if defined(LIBC_SCCS) && !defined(lint)
__RCSID("$NetBSD: insque.c,v 1.2 2005/07/06 17:17:15 drochner Exp $");
#endif /* LIBC_SCCS and not lint */
#include <assert.h>
#include <search.h>
struct qelem {
struct qelem *q_forw;
struct qelem *q_back;
};
void
insque(entry, pred)
void *entry;
void *pred;
{
struct qelem *e = (struct qelem *) entry;
struct qelem *p = (struct qelem *) pred;
_DIAGASSERT(e != 0);
e->q_back = p;
if (p) {
e->q_forw = p->q_forw;
if (p->q_forw)
p->q_forw->q_back = e;
p->q_forw = e;
} else
e->q_forw = 0;
}

View File

@@ -0,0 +1,385 @@
.\" $NetBSD $
.\"
.\" Copyright (c) 1980, 1991, 1993
.\" The Regents of the University of California. All rights reserved.
.\"
.\" This code is derived from software contributed to Berkeley by
.\" the American National Standards Committee X3, on Information
.\" Processing Systems.
.\"
.\" 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. 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.
.\"
.\" @(#)malloc.3 8.1 (Berkeley) 6/4/93
.\" $FreeBSD: src/lib/libc/stdlib/malloc.3,v 1.73 2007/06/15 22:32:33 jasone Exp $
.\"
.Dd May 14, 2010
.Os
.Dt JEMALLOC 3
.Sh NAME
.Nm jemalloc
.Nd the default system allocator
.Sh LIBRARY
.Lb libc
.Sh SYNOPSIS
.Ft const char *
.Va _malloc_options ;
.Sh DESCRIPTION
The
.Nm
is a general-purpose concurrent
.Xr malloc 3
implementation specifically designed to be scalable
on modern multi-processor systems.
It is the default user space system allocator in
.Nx .
.Pp
When the first call is made to one of the memory allocation
routines such as
.Fn malloc
or
.Fn realloc ,
various flags that affect the workings of the allocator are set or reset.
These are described below.
.Pp
The
.Dq name
of the file referenced by the symbolic link named
.Pa /etc/malloc.conf ,
the value of the environment variable
.Ev MALLOC_OPTIONS ,
and the string pointed to by the global variable
.Va _malloc_options
will be interpreted, in that order, character by character as flags.
.Pp
Most flags are single letters.
Uppercase letters indicate that the behavior is set, or on,
and lowercase letters mean that the behavior is not set, or off.
The following options are available.
.Bl -tag -width "A " -offset 3n
.It Em A
All warnings (except for the warning about unknown
flags being set) become fatal.
The process will call
.Xr abort 3
in these cases.
.It Em H
Use
.Xr madvise 2
when pages within a chunk are no longer in use, but the chunk as a whole cannot
yet be deallocated.
This is primarily of use when swapping is a real possibility, due to the high
overhead of the
.Fn madvise
system call.
.It Em J
Each byte of new memory allocated by
.Fn malloc ,
.Fn realloc
will be initialized to 0xa5.
All memory returned by
.Fn free ,
.Fn realloc
will be initialized to 0x5a.
This is intended for debugging and will impact performance negatively.
.It Em K
Increase/decrease the virtual memory chunk size by a factor of two.
The default chunk size is 1 MB.
This option can be specified multiple times.
.It Em N
Increase/decrease the number of arenas by a factor of two.
The default number of arenas is four times the number of CPUs, or one if there
is a single CPU.
This option can be specified multiple times.
.It Em P
Various statistics are printed at program exit via an
.Xr atexit 3
function.
This has the potential to cause deadlock for a multi-threaded process that exits
while one or more threads are executing in the memory allocation functions.
Therefore, this option should only be used with care; it is primarily intended
as a performance tuning aid during application development.
.It Em Q
Increase/decrease the size of the allocation quantum by a factor of two.
The default quantum is the minimum allowed by the architecture (typically 8 or
16 bytes).
This option can be specified multiple times.
.It Em S
Increase/decrease the size of the maximum size class that is a multiple of the
quantum by a factor of two.
Above this size, power-of-two spacing is used for size classes.
The default value is 512 bytes.
This option can be specified multiple times.
.It Em U
Generate
.Dq utrace
entries for
.Xr ktrace 1 ,
for all operations.
Consult the source for details on this option.
.It Em V
Attempting to allocate zero bytes will return a
.Dv NULL
pointer instead of a valid pointer.
(The default behavior is to make a minimal allocation and return a
pointer to it.)
This option is provided for System V compatibility.
This option is incompatible with the
.Em X
option.
.It Em X
Rather than return failure for any allocation function,
display a diagnostic message on
.Dv stderr
and cause the program to drop
core (using
.Xr abort 3 ) .
This option should be set at compile time by including the following in
the source code:
.Bd -literal -offset indent
_malloc_options = "X";
.Ed
.Pp
.It Em Z
Each byte of new memory allocated by
.Fn malloc ,
.Fn realloc
will be initialized to 0.
Note that this initialization only happens once for each byte, so
.Fn realloc
does not zero memory that was previously allocated.
This is intended for debugging and will impact performance negatively.
.El
.Pp
The
.Em J
and
.Em Z
options are intended for testing and debugging.
An application which changes its behavior when these options are used
is flawed.
.Sh IMPLEMENTATION NOTES
The
.Nm
allocator uses multiple arenas in order to reduce lock
contention for threaded programs on multi-processor systems.
This works well with regard to threading scalability, but incurs some costs.
There is a small fixed per-arena overhead, and additionally, arenas manage
memory completely independently of each other, which means a small fixed
increase in overall memory fragmentation.
These overheads are not generally an issue,
given the number of arenas normally used.
Note that using substantially more arenas than the default is not likely to
improve performance, mainly due to reduced cache performance.
However, it may make sense to reduce the number of arenas if an application
does not make much use of the allocation functions.
.Pp
Memory is conceptually broken into equal-sized chunks,
where the chunk size is a power of two that is greater than the page size.
Chunks are always aligned to multiples of the chunk size.
This alignment makes it possible to find
metadata for user objects very quickly.
.Pp
User objects are broken into three categories according to size:
.Bl -enum -offset 3n
.It
Small objects are smaller than one page.
.It
Large objects are smaller than the chunk size.
.It
Huge objects are a multiple of the chunk size.
.El
.Pp
Small and large objects are managed by arenas; huge objects are managed
separately in a single data structure that is shared by all threads.
Huge objects are used by applications infrequently enough that this single
data structure is not a scalability issue.
.Pp
Each chunk that is managed by an arena tracks its contents in a page map as
runs of contiguous pages (unused, backing a set of small objects, or backing
one large object).
The combination of chunk alignment and chunk page maps makes it possible to
determine all metadata regarding small and large allocations in constant time.
.Pp
Small objects are managed in groups by page runs.
Each run maintains a bitmap that tracks which regions are in use.
Allocation requests can be grouped as follows.
.Pp
.Bl -bullet -offset 3n
.It
Allocation requests that are no more than half the quantum (see the
.Em Q
option) are rounded up to the nearest power of two (typically 2, 4, or 8).
.It
Allocation requests that are more than half the quantum, but no more than the
maximum quantum-multiple size class (see the
.Em S
option) are rounded up to the nearest multiple of the quantum.
.It
Allocation requests that are larger than the maximum quantum-multiple size
class, but no larger than one half of a page, are rounded up to the nearest
power of two.
.It
Allocation requests that are larger than half of a page, but small enough to
fit in an arena-managed chunk (see the
.Em K
option), are rounded up to the nearest run size.
.It
Allocation requests that are too large to fit in an arena-managed chunk are
rounded up to the nearest multiple of the chunk size.
.El
.Pp
Allocations are packed tightly together, which can be an issue for
multi-threaded applications.
If you need to assure that allocations do not suffer from cache line sharing,
round your allocation requests up to the nearest multiple of the cache line
size.
.Sh DEBUGGING
The first thing to do is to set the
.Em A
option.
This option forces a coredump (if possible) at the first sign of trouble,
rather than the normal policy of trying to continue if at all possible.
.Pp
It is probably also a good idea to recompile the program with suitable
options and symbols for debugger support.
.Pp
If the program starts to give unusual results, coredump or generally behave
differently without emitting any of the messages mentioned in the next
section, it is likely because it depends on the storage being filled with
zero bytes.
Try running it with the
.Em Z
option set;
if that improves the situation, this diagnosis has been confirmed.
If the program still misbehaves,
the likely problem is accessing memory outside the allocated area.
.Pp
Alternatively, if the symptoms are not easy to reproduce, setting the
.Em J
option may help provoke the problem.
In truly difficult cases, the
.Em U
option, if supported by the kernel, can provide a detailed trace of
all calls made to these functions.
.Pp
Unfortunately,
.Nm
does not provide much detail about the problems it detects;
the performance impact for storing such information would be prohibitive.
There are a number of allocator implementations available on the Internet
which focus on detecting and pinpointing problems by trading performance for
extra sanity checks and detailed diagnostics.
.Sh DIAGNOSTICS
If any of the memory allocation/deallocation functions detect an error or
warning condition, a message will be printed to file descriptor
.Dv STDERR_FILENO .
Errors will result in the process dumping core.
If the
.Em A
option is set, all warnings are treated as errors.
.Pp
.\"
.\" XXX: The _malloc_message should be documented
.\" better in order to be worth mentioning.
.\"
The
.Va _malloc_message
variable allows the programmer to override the function which emits
the text strings forming the errors and warnings if for some reason
the
.Dv stderr
file descriptor is not suitable for this.
Please note that doing anything which tries to allocate memory in
this function is likely to result in a crash or deadlock.
.Pp
All messages are prefixed by
.Dq Ao Ar progname Ac Ns Li \&: Pq malloc .
.Sh ENVIRONMENT
The following environment variables affect the execution of the allocation
functions:
.Bl -tag -width ".Ev MALLOC_OPTIONS"
.It Ev MALLOC_OPTIONS
If the environment variable
.Ev MALLOC_OPTIONS
is set, the characters it contains will be interpreted as flags to the
allocation functions.
.El
.Sh EXAMPLES
To dump core whenever a problem occurs:
.Pp
.Bd -literal -offset indent
ln -s 'A' /etc/malloc.conf
.Ed
.Pp
To specify in the source that a program does no return value checking
on calls to these functions:
.Bd -literal -offset indent
_malloc_options = "X";
.Ed
.Sh SEE ALSO
.Xr emalloc 3 ,
.Xr malloc 3 ,
.Xr memory 3 ,
.Xr memoryallocators 9
.\"
.\" XXX: Add more references that could be worth reading.
.\"
.Rs
.%A Jason Evans
.%T "A Scalable Concurrent malloc(3) Implementation for FreeBSD"
.%D April 16, 2006
.%O BSDCan 2006
.%U http://people.freebsd.org/~jasone/jemalloc/bsdcan2006/jemalloc.pdf
.Re
.Rs
.%A Poul-Henning Kamp
.%T "Malloc(3) revisited"
.%I USENIX Association
.%B Proceedings of the FREENIX Track: 1998 USENIX Annual Technical Conference
.%D June 15-19, 1998
.%U http://www.usenix.org/publications/library/proceedings/usenix98/freenix/kamp.pdf
.Re
.Rs
.%A Paul R. Wilson
.%A Mark S. Johnstone
.%A Michael Neely
.%A David Boles
.%T "Dynamic Storage Allocation: A Survey and Critical Review"
.%D 1995
.%I University of Texas at Austin
.%U ftp://ftp.cs.utexas.edu/pub/garbage/allocsrv.ps
.Re
.Sh HISTORY
The
.Nm
allocator became the default system allocator first in
.Fx 7.0
and then in
.Nx 5.0 .
In both systems it replaced the older so-called
.Dq phkmalloc
implementation.
.Sh AUTHORS
.An Jason Evans Aq jasone@canonware.com

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,39 @@
/* $NetBSD: jrand48.c,v 1.8 2005/06/12 05:21:28 lukem Exp $ */
/*
* Copyright (c) 1993 Martin Birgmeier
* All rights reserved.
*
* You may redistribute unmodified or modified versions of this source
* code provided that the above copyright notice and this and the
* following conditions are retained.
*
* This software is provided ``as is'', and comes with no warranties
* of any kind. I shall in no event be liable for anything that happens
* to anyone/anything when using this software.
*/
#include <sys/cdefs.h>
#if defined(LIBC_SCCS) && !defined(lint)
__RCSID("$NetBSD: jrand48.c,v 1.8 2005/06/12 05:21:28 lukem Exp $");
#endif /* LIBC_SCCS and not lint */
#include "namespace.h"
#include <assert.h>
#include "rand48.h"
#ifdef __weak_alias
__weak_alias(jrand48,_jrand48)
#endif
long
jrand48(unsigned short xseed[3])
{
_DIAGASSERT(xseed != NULL);
__dorand48(xseed);
return ((long) xseed[2] << 16) + (long) xseed[1];
}

View File

@@ -0,0 +1,67 @@
/* $NetBSD: l64a.c,v 1.13 2003/07/26 19:24:54 salo Exp $ */
/*
* Written by J.T. Conklin <jtc@NetBSD.org>.
* Public domain.
*/
#include <sys/cdefs.h>
#if defined(LIBC_SCCS) && !defined(lint)
__RCSID("$NetBSD: l64a.c,v 1.13 2003/07/26 19:24:54 salo Exp $");
#endif
#include "namespace.h"
#include <assert.h>
#include <errno.h>
#include <stdlib.h>
#ifdef __weak_alias
__weak_alias(l64a,_l64a)
__weak_alias(l64a_r,_l64a_r)
#endif
char *
l64a (value)
long value;
{
static char buf[8];
(void)l64a_r(value, buf, sizeof (buf));
return buf;
}
int
l64a_r (value, buffer, buflen)
long value;
char *buffer;
int buflen;
{
char *s = buffer;
int digit;
unsigned long v = value;
_DIAGASSERT(buffer != NULL);
if (value == 0UL)
goto out;
for (; v != 0 && buflen > 1; s++, buflen--) {
digit = (int)(v & 0x3f);
if (digit < 2)
*s = digit + '.';
else if (digit < 12)
*s = digit + '0' - 2;
else if (digit < 38)
*s = digit + 'A' - 12;
else
*s = digit + 'a' - 38;
v >>= 6;
}
out:
*s = '\0';
return (v == 0UL ? 0 : -1);
}

View File

@@ -0,0 +1,68 @@
.\" $NetBSD: labs.3,v 1.11 2008/08/04 21:29:27 matt Exp $
.\"
.\" Copyright (c) 1990, 1991, 1993
.\" The Regents of the University of California. All rights reserved.
.\"
.\" This code is derived from software contributed to Berkeley by
.\" the American National Standards Committee X3, on Information
.\" Processing Systems.
.\"
.\" 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. 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.
.\"
.\" from: @(#)labs.3 8.1 (Berkeley) 6/4/93
.\"
.Dd June 4, 1993
.Dt LABS 3
.Os
.Sh NAME
.Nm labs
.Nd return the absolute value of a long integer
.Sh LIBRARY
.Lb libc
.Sh SYNOPSIS
.In stdlib.h
.Ft long int
.Fn labs "long int j"
.Sh DESCRIPTION
The
.Fn labs
function
returns the absolute value of the long integer
.Ar j .
.Sh SEE ALSO
.Xr abs 3 ,
.Xr cabs 3 ,
.Xr floor 3 ,
.Xr imaxabs 3 ,
.Xr llabs 3 ,
.Xr math 3
.Sh STANDARDS
The
.Fn labs
function
conforms to
.St -ansiC .
.Sh BUGS
The absolute value of the most negative integer remains negative.

View File

@@ -0,0 +1,48 @@
/* $NetBSD: labs.c,v 1.7 2003/08/07 16:43:41 agc Exp $ */
/*-
* 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. 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.
*/
#include <sys/cdefs.h>
#if defined(LIBC_SCCS) && !defined(lint)
#if 0
static char sccsid[] = "@(#)labs.c 8.1 (Berkeley) 6/4/93";
#else
__RCSID("$NetBSD: labs.c,v 1.7 2003/08/07 16:43:41 agc Exp $");
#endif
#endif /* LIBC_SCCS and not lint */
#include <stdlib.h>
long
labs(j)
long j;
{
return(j < 0 ? -j : j);
}

View File

@@ -0,0 +1,43 @@
/* $NetBSD: lcong48.c,v 1.8 2005/06/12 05:21:28 lukem Exp $ */
/*
* Copyright (c) 1993 Martin Birgmeier
* All rights reserved.
*
* You may redistribute unmodified or modified versions of this source
* code provided that the above copyright notice and this and the
* following conditions are retained.
*
* This software is provided ``as is'', and comes with no warranties
* of any kind. I shall in no event be liable for anything that happens
* to anyone/anything when using this software.
*/
#include <sys/cdefs.h>
#if defined(LIBC_SCCS) && !defined(lint)
__RCSID("$NetBSD: lcong48.c,v 1.8 2005/06/12 05:21:28 lukem Exp $");
#endif /* LIBC_SCCS and not lint */
#include "namespace.h"
#include <assert.h>
#include "rand48.h"
#ifdef __weak_alias
__weak_alias(lcong48,_lcong48)
#endif
void
lcong48(unsigned short p[7])
{
_DIAGASSERT(p != NULL);
__rand48_seed[0] = p[0];
__rand48_seed[1] = p[1];
__rand48_seed[2] = p[2];
__rand48_mult[0] = p[3];
__rand48_mult[1] = p[4];
__rand48_mult[2] = p[5];
__rand48_add = p[6];
}

View File

@@ -0,0 +1,73 @@
.\" $NetBSD: ldiv.3,v 1.13 2008/08/04 21:29:27 matt Exp $
.\"
.\" Copyright (c) 1990, 1991, 1993
.\" The Regents of the University of California. All rights reserved.
.\"
.\" This code is derived from software contributed to Berkeley by
.\" Chris Torek and the American National Standards Committee X3,
.\" on Information Processing Systems.
.\"
.\" 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. 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.
.\"
.\" from: @(#)ldiv.3 8.1 (Berkeley) 6/4/93
.\"
.Dd June 4, 1993
.Dt LDIV 3
.Os
.Sh NAME
.Nm ldiv
.Nd return quotient and remainder from division
.Sh LIBRARY
.Lb libc
.Sh SYNOPSIS
.In stdlib.h
.Ft ldiv_t
.Fn ldiv "long int num" "long int denom"
.Sh DESCRIPTION
The
.Fn ldiv
function
computes the value
.Ar num/denom
and returns the quotient and remainder in a structure named
.Ar ldiv_t
that contains two
.Em long integer
members named
.Ar quot
and
.Ar rem .
.Sh SEE ALSO
.Xr div 3 ,
.Xr imaxdiv 3 ,
.Xr lldiv 3 ,
.Xr math 3 ,
.Xr qdiv 3
.Sh STANDARDS
The
.Fn ldiv
function
conforms to
.St -ansiC .

View File

@@ -0,0 +1,61 @@
/* $NetBSD: ldiv.c,v 1.7 2003/08/07 16:43:41 agc Exp $ */
/*
* 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. 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.
*/
#include <sys/cdefs.h>
#if defined(LIBC_SCCS) && !defined(lint)
#if 0
static char sccsid[] = "@(#)ldiv.c 8.1 (Berkeley) 6/4/93";
#else
__RCSID("$NetBSD: ldiv.c,v 1.7 2003/08/07 16:43:41 agc Exp $");
#endif
#endif /* LIBC_SCCS and not lint */
#include <stdlib.h> /* ldiv_t */
ldiv_t
ldiv(num, denom)
long num, denom;
{
ldiv_t r;
/* see div.c for comments */
r.quot = num / denom;
r.rem = num % denom;
if (num >= 0 && r.rem < 0) {
r.quot++;
r.rem -= denom;
}
return (r);
}

View File

@@ -0,0 +1,68 @@
.\" $NetBSD: llabs.3,v 1.7 2008/08/04 21:29:27 matt Exp $
.\"
.\" Copyright (c) 1990, 1991, 1993
.\" The Regents of the University of California. All rights reserved.
.\"
.\" This code is derived from software contributed to Berkeley by
.\" the American National Standards Committee X3, on Information
.\" Processing Systems.
.\"
.\" 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. 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.
.\"
.\" from: @(#)labs.3 8.1 (Berkeley) 6/4/93
.\"
.Dd March 6, 2000
.Dt LLABS 3
.Os
.Sh NAME
.Nm llabs
.Nd return the absolute value of a long long integer
.Sh LIBRARY
.Lb libc
.Sh SYNOPSIS
.In stdlib.h
.Ft long long int
.Fn llabs "long long int j"
.Sh DESCRIPTION
The
.Fn llabs
function
returns the absolute value of the long long integer
.Ar j .
.Sh SEE ALSO
.Xr abs 3 ,
.Xr cabs 3 ,
.Xr floor 3 ,
.Xr imaxabs 3 ,
.Xr labs 3 ,
.Xr math 3
.Sh STANDARDS
The
.Fn llabs
function
conforms to
.St -isoC-99 .
.Sh BUGS
The absolute value of the most negative integer remains negative.

View File

@@ -0,0 +1,54 @@
/* $NetBSD: llabs.c,v 1.3 2003/08/07 16:43:41 agc Exp $ */
/*-
* 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. 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.
*/
#include <sys/cdefs.h>
#if defined(LIBC_SCCS) && !defined(lint)
#if 0
static char sccsid[] = "from: @(#)labs.c 8.1 (Berkeley) 6/4/93";
#else
__RCSID("$NetBSD: llabs.c,v 1.3 2003/08/07 16:43:41 agc Exp $");
#endif
#endif /* LIBC_SCCS and not lint */
#include "namespace.h"
#include <stdlib.h>
#ifdef __weak_alias
__weak_alias(llabs, _llabs)
#endif
/* LONGLONG */
long long int
llabs(j)
long long int j;
{
return (j < 0 ? -j : j);
}

View File

@@ -0,0 +1,73 @@
.\" $NetBSD: lldiv.3,v 1.7 2008/08/04 21:29:27 matt Exp $
.\"
.\" Copyright (c) 1990, 1991, 1993
.\" The Regents of the University of California. All rights reserved.
.\"
.\" This code is derived from software contributed to Berkeley by
.\" Chris Torek and the American National Standards Committee X3,
.\" on Information Processing Systems.
.\"
.\" 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. 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.
.\"
.\" from: @(#)ldiv.3 8.1 (Berkeley) 6/4/93
.\"
.Dd March 6, 2000
.Dt LLDIV 3
.Os
.Sh NAME
.Nm lldiv
.Nd return quotient and remainder from division
.Sh LIBRARY
.Lb libc
.Sh SYNOPSIS
.In stdlib.h
.Ft lldiv_t
.Fn lldiv "long long int num" "long long int denom"
.Sh DESCRIPTION
The
.Fn lldiv
function
computes the value
.Ar num/denom
and returns the quotient and remainder in a structure named
.Ar lldiv_t
that contains two
.Em long long integer
members named
.Ar quot
and
.Ar rem .
.Sh SEE ALSO
.Xr div 3 ,
.Xr imaxdiv 3 ,
.Xr ldiv 3 ,
.Xr math 3 ,
.Xr qdiv 3
.Sh STANDARDS
The
.Fn lldiv
function
conforms to
.St -isoC-99 .

View File

@@ -0,0 +1,67 @@
/* $NetBSD: lldiv.c,v 1.3 2003/08/07 16:43:41 agc Exp $ */
/*
* 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. 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.
*/
#include <sys/cdefs.h>
#if defined(LIBC_SCCS) && !defined(lint)
#if 0
static char sccsid[] = "from: @(#)ldiv.c 8.1 (Berkeley) 6/4/93";
#else
__RCSID("$NetBSD: lldiv.c,v 1.3 2003/08/07 16:43:41 agc Exp $");
#endif
#endif /* LIBC_SCCS and not lint */
#include "namespace.h"
#include <stdlib.h> /* lldiv_t */
#ifdef __weak_alias
__weak_alias(lldiv, _lldiv)
#endif
/* LONGLONG */
lldiv_t
lldiv(num, denom)
long long int num, denom;
{
lldiv_t r;
/* see div.c for comments */
r.quot = num / denom;
r.rem = num % denom;
if (num >= 0 && r.rem < 0) {
r.quot++;
r.rem -= denom;
}
return (r);
}

View File

@@ -0,0 +1,36 @@
/* $NetBSD: local.h,v 1.6 2010/11/14 18:11:43 tron Exp $ */
/*
* Copyright (c) 1997 Christos Zoulas. 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.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
*/
/* Environment handling. */
#include <sys/types.h>
#include <stdbool.h>
extern size_t __envvarnamelen(const char *str, bool withequal);
extern void __freeenvvar(char *envvar);
extern char *__allocenvvar(size_t length);
extern bool __canoverwriteenvvar(char *envvar, size_t length);

View File

@@ -0,0 +1,34 @@
/* $NetBSD: lrand48.c,v 1.8 2005/06/12 05:21:28 lukem Exp $ */
/*
* Copyright (c) 1993 Martin Birgmeier
* All rights reserved.
*
* You may redistribute unmodified or modified versions of this source
* code provided that the above copyright notice and this and the
* following conditions are retained.
*
* This software is provided ``as is'', and comes with no warranties
* of any kind. I shall in no event be liable for anything that happens
* to anyone/anything when using this software.
*/
#include <sys/cdefs.h>
#if defined(LIBC_SCCS) && !defined(lint)
__RCSID("$NetBSD: lrand48.c,v 1.8 2005/06/12 05:21:28 lukem Exp $");
#endif /* LIBC_SCCS and not lint */
#include "namespace.h"
#include "rand48.h"
#ifdef __weak_alias
__weak_alias(lrand48,_lrand48)
#endif
long
lrand48(void)
{
__dorand48(__rand48_seed);
return (long)((unsigned long) __rand48_seed[2] << 15) +
((unsigned long) __rand48_seed[1] >> 1);
}

View File

@@ -0,0 +1,97 @@
.\" 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. 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.
.\"
.\" from: @(#)lsearch.3 8.1 (Berkeley) 6/4/93
.\" $NetBSD: lsearch.3,v 1.3 2005/07/12 08:28:42 wiz Exp $
.\"
.Dd July 6, 2005
.Dt LSEARCH 3
.Os
.Sh NAME
.Nm lsearch ,
.Nm lfind
.Nd linear searching routines
.Sh LIBRARY
.Lb libc
.Sh SYNOPSIS
.In search.h
.Ft void *
.Fn lsearch "const void *key" "void *base" "size_t *nelp" "size_t width" "int (*compar)(const void *, const void *)"
.Ft void *
.Fn lfind "const void *key" "const void *base" "size_t *nelp" "size_t width" "int (*compar)(const void *, const void *)"
.Sh DESCRIPTION
The functions
.Fn lsearch ,
and
.Fn lfind
provide basic linear searching functionality.
.Pp
.Fa base
is the pointer to the beginning of an array.
The argument
.Fa nelp
is the current number of elements in the array, where each element
is
.Fa width
bytes long.
The
.Fa compar
argument points to a function which compares its two arguments and returns
zero if they are matching, and non-zero otherwise.
.Pp
The
.Fn lsearch
and
.Fn lfind
functions
return a pointer into the array referenced by
.Fa base
where
.Fa key
is located.
If
.Fa key
does not exist,
.Fn lfind
will return a null pointer and
.Fn lsearch
will add it to the array.
When an element is added to the array by
.Fn lsearch
the location referenced by the argument
.Fa nelp
is incremented by one.
.Sh SEE ALSO
.Xr bsearch 3 ,
.Xr db 3
.Sh STANDARDS
The
.Fn lsearch
and
.Fn lfind
functions conform to
.St -p1003.1-2001 .

View File

@@ -0,0 +1,116 @@
/*
* Copyright (c) 1989, 1993
* The Regents of the University of California. All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* Roger L. Snyder.
*
* 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. 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.
*/
#include <sys/cdefs.h>
#if defined(LIBC_SCCS) && !defined(lint)
#if 0
static char sccsid[] = "@(#)lsearch.c 8.1 (Berkeley) 6/4/93";
#else
__RCSID("$NetBSD: lsearch.c,v 1.4 2005/07/16 17:32:09 christos Exp $");
#endif
#endif /* LIBC_SCCS and not lint */
#include <sys/types.h>
#include <assert.h>
#include <errno.h>
#include <string.h>
#include <search.h>
typedef int (*cmp_fn_t) __P((const void *, const void *));
static void *linear_base __P((const void *, void *, size_t *, size_t,
cmp_fn_t, int));
void *
lsearch(key, base, nelp, width, compar)
const void *key;
void *base;
size_t *nelp, width;
cmp_fn_t compar;
{
_DIAGASSERT(key != NULL);
_DIAGASSERT(base != NULL);
_DIAGASSERT(compar != NULL);
return(linear_base(key, base, nelp, width, compar, 1));
}
void *
lfind(key, base, nelp, width, compar)
const void *key, *base;
size_t *nelp, width;
cmp_fn_t compar;
{
_DIAGASSERT(key != NULL);
_DIAGASSERT(base != NULL);
_DIAGASSERT(compar != NULL);
return(linear_base(key, __UNCONST(base), nelp, width, compar, 0));
}
static void *
linear_base(key, base, nelp, width, compar, add_flag)
const void *key;
void *base;
size_t *nelp, width;
cmp_fn_t compar;
int add_flag;
{
char *element, *end;
_DIAGASSERT(key != NULL);
_DIAGASSERT(base != NULL);
_DIAGASSERT(compar != NULL);
end = (char *)base + *nelp * width;
for (element = (char *)base; element < end; element += width)
if (!compar(element, key)) /* key found */
return element;
if (!add_flag) /* key not found */
return(NULL);
/*
* The UNIX System User's Manual, 1986 edition claims that
* a NULL pointer is returned by lsearch with errno set
* appropriately, if there is not enough room in the table
* to add a new item. This can't be done as none of these
* routines have any method of determining the size of the
* table. This comment isn't in the 1986-87 System V
* manual.
*/
++*nelp;
memcpy(end, key, width);
return end;
}

View File

@@ -0,0 +1,229 @@
.\" $NetBSD: malloc.3,v 1.38 2010/05/03 08:23:20 jruoho Exp $
.\"
.\" Copyright (c) 1980, 1991, 1993
.\" The Regents of the University of California. All rights reserved.
.\"
.\" This code is derived from software contributed to Berkeley by
.\" the American National Standards Committee X3, on Information
.\" Processing Systems.
.\"
.\" 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. 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.
.\"
.\" @(#)malloc.3 8.1 (Berkeley) 6/4/93
.\" $FreeBSD: src/lib/libc/stdlib/malloc.3,v 1.73 2007/06/15 22:32:33 jasone Exp $
.\"
.Dd May 3, 2010
.Dt MALLOC 3
.Os
.Sh NAME
.Nm malloc , calloc , realloc , free
.Nd general purpose memory allocation functions
.Sh LIBRARY
.Lb libc
.Sh SYNOPSIS
.In stdlib.h
.Ft void *
.Fn malloc "size_t size"
.Ft void *
.Fn calloc "size_t number" "size_t size"
.Ft void *
.Fn realloc "void *ptr" "size_t size"
.Ft void
.Fn free "void *ptr"
.Sh DESCRIPTION
The
.Fn malloc
function allocates
.Fa size
bytes of uninitialized memory.
The allocated space is suitably aligned (after possible pointer coercion)
for storage of any type of object.
.Pp
The
.Fn calloc
function allocates space for
.Fa number
objects,
each
.Fa size
bytes in length.
The result is identical to calling
.Fn malloc
with an argument of
.Dq "number * size" ,
with the exception that the allocated memory is explicitly initialized
to zero bytes.
.Pp
The
.Fn realloc
function changes the size of the previously allocated memory referenced by
.Fa ptr
to
.Fa size
bytes.
The contents of the memory are unchanged up to the lesser of the new and
old sizes.
If the new size is larger,
the value of the newly allocated portion of the memory is undefined.
Upon success, the memory referenced by
.Fa ptr
is freed and a pointer to the newly allocated memory is returned.
Note that
.Fn realloc
may move the memory allocation, resulting in a different return value than
.Fa ptr .
If
.Fa ptr
is
.Dv NULL ,
the
.Fn realloc
function behaves identically to
.Fn malloc
for the specified size.
.Pp
The
.Fn free
function causes the allocated memory referenced by
.Fa ptr
to be made available for future allocations.
If
.Fa ptr
is
.Dv NULL ,
no action occurs.
.Sh RETURN VALUES
The
.Fn malloc
and
.Fn calloc
functions return a pointer to the allocated memory if successful; otherwise
a
.Dv NULL
pointer is returned and
.Va errno
is set to
.Er ENOMEM .
.Pp
The
.Fn realloc
function returns a pointer, possibly identical to
.Fa ptr ,
to the allocated memory
if successful; otherwise a
.Dv NULL
pointer is returned, and
.Va errno
is set to
.Er ENOMEM
if the error was the result of an allocation failure.
The
.Fn realloc
function always leaves the original buffer intact
when an error occurs.
.Pp
The
.Fn free
function returns no value.
.Sh EXAMPLES
When using
.Fn malloc ,
be careful to avoid the following idiom:
.Bd -literal -offset indent
if ((p = malloc(number * size)) == NULL)
err(EXIT_FAILURE, "malloc");
.Ed
.Pp
The multiplication may lead to an integer overflow.
To avoid this,
.Fn calloc
is recommended.
.Pp
If
.Fn malloc
must be used, be sure to test for overflow:
.Bd -literal -offset indent
if (size && number > SIZE_MAX / size) {
errno = EOVERFLOW;
err(EXIT_FAILURE, "allocation");
}
.Ed
.Pp
When using
.Fn realloc ,
one must be careful to avoid the following idiom:
.Pp
.Bd -literal -offset indent
nsize += 50;
if ((p = realloc(p, nsize)) == NULL)
return NULL;
.Ed
.Pp
Do not adjust the variable describing how much memory has been allocated
until it is known that the allocation has been successful.
This can cause aberrant program behavior if the incorrect size value is used.
In most cases, the above example will also leak memory.
As stated earlier, a return value of
.Dv NULL
indicates that the old object still remains allocated.
Better code looks like this:
.Bd -literal -offset indent
newsize = size + 50;
if ((p2 = realloc(p, newsize)) == NULL) {
if (p != NULL)
free(p);
p = NULL;
return NULL;
}
p = p2;
size = newsize;
.Ed
.Sh SEE ALSO
.\" .Xr limits 1 ,
.Xr madvise 2 ,
.Xr mmap 2 ,
.Xr sbrk 2 ,
.Xr alloca 3 ,
.Xr atexit 3 ,
.Xr getpagesize 3 ,
.Xr memory 3 ,
.Xr posix_memalign 3
.Pp
For the implementation details, see
.Xr jemalloc 3 .
.Sh STANDARDS
The
.Fn malloc ,
.Fn calloc ,
.Fn realloc
and
.Fn free
functions conform to
.St -isoC .

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,70 @@
.\" $NetBSD: memory.3,v 1.10 2003/08/07 16:43:42 agc Exp $
.\"
.\" 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. 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.
.\"
.\" from: @(#)memory.3 8.1 (Berkeley) 6/4/93
.\"
.Dd June 4, 1993
.Dt MEMORY 3
.Os
.Sh NAME
.Nm malloc ,
.Nm free ,
.Nm realloc ,
.Nm calloc ,
.Nm alloca
.Nd general memory allocation operations
.Sh LIBRARY
.Lb libc
.Sh SYNOPSIS
.In stdlib.h
.Ft void *
.Fn malloc "size_t size"
.Ft void
.Fn free "void *ptr"
.Ft void *
.Fn realloc "void *ptr" "size_t size"
.Ft void *
.Fn calloc "size_t nelem" "size_t elsize"
.Ft void *
.Fn alloca "size_t size"
.Sh DESCRIPTION
These functions allocate and free memory for the calling process.
They are described in the
individual manual pages.
.Sh SEE ALSO
.Xr alloca 3 ,
.Xr calloc 3 ,
.Xr free 3 ,
.Xr malloc 3 ,
.Xr realloc 3
.Sh STANDARDS
These functions, with the exception of
.Fn alloca
conform to
.St -ansiC .

View File

@@ -0,0 +1,380 @@
/* $NetBSD: merge.c,v 1.12 2009/02/12 03:12:36 lukem Exp $ */
/*-
* Copyright (c) 1992, 1993
* The Regents of the University of California. All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* Peter McIlroy.
*
* 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. 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.
*/
#include <sys/cdefs.h>
#if defined(LIBC_SCCS) && !defined(lint)
#if 0
static char sccsid[] = "from: @(#)merge.c 8.2 (Berkeley) 2/14/94";
#else
__RCSID("$NetBSD: merge.c,v 1.12 2009/02/12 03:12:36 lukem Exp $");
#endif
#endif /* LIBC_SCCS and not lint */
/*
* Hybrid exponential search/linear search merge sort with hybrid
* natural/pairwise first pass. Requires about .3% more comparisons
* for random data than LSMS with pairwise first pass alone.
* It works for objects as small as two bytes.
*/
#define NATURAL
#define THRESHOLD 16 /* Best choice for natural merge cut-off. */
/* #define NATURAL to get hybrid natural merge.
* (The default is pairwise merging.)
*/
#include "namespace.h"
#include <sys/types.h>
#include <assert.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#ifdef __weak_alias
__weak_alias(mergesort,_mergesort)
#endif
static void setup __P((u_char *, u_char *, size_t, size_t,
int (*)(const void *, const void *)));
static void insertionsort __P((u_char *, size_t, size_t,
int (*)(const void *, const void *)));
#define ISIZE sizeof(int)
#define PSIZE sizeof(u_char *)
#define ICOPY_LIST(src, dst, last) \
do \
*(int*)(void *)dst = *(int*)(void *)src, \
src += ISIZE, dst += ISIZE; \
while(src < last)
#define ICOPY_ELT(src, dst, i) \
do \
*(int*)(void *)dst = *(int*)(void *)src, \
src += ISIZE, dst += ISIZE; \
while (i -= ISIZE)
#define CCOPY_LIST(src, dst, last) \
do \
*dst++ = *src++; \
while (src < last)
#define CCOPY_ELT(src, dst, i) \
do \
*dst++ = *src++; \
while (i -= 1)
/*
* Find the next possible pointer head. (Trickery for forcing an array
* to do double duty as a linked list when objects do not align with word
* boundaries.
*/
/* Assumption: PSIZE is a power of 2. */
#define EVAL(p) ((u_char **)(void *) \
((u_char *)0 + \
(((u_char *)(void *)(p) + PSIZE - 1 - (u_char *) 0) & ~(PSIZE - 1))))
/*
* Arguments are as for qsort.
*/
int
mergesort(base, nmemb, size, cmp)
void *base;
size_t nmemb;
size_t size;
int (*cmp) __P((const void *, const void *));
{
size_t i;
int sense;
int big, iflag;
u_char *f1, *f2, *t, *b, *tp2, *q, *l1, *l2;
u_char *list2, *list1, *p2, *p, *last, **p1;
_DIAGASSERT(base != NULL);
_DIAGASSERT(cmp != NULL);
if (size < PSIZE / 2) { /* Pointers must fit into 2 * size. */
errno = EINVAL;
return (-1);
}
/*
* XXX
* Stupid subtraction for the Cray.
*/
iflag = 0;
if (!(size % ISIZE) && !(((char *)base - (char *)0) % ISIZE))
iflag = 1;
if ((list2 = malloc(nmemb * size + PSIZE)) == NULL)
return (-1);
list1 = base;
setup(list1, list2, nmemb, size, cmp);
last = list2 + nmemb * size;
i = big = 0;
while (*EVAL(list2) != last) {
l2 = list1;
p1 = EVAL(list1);
for (tp2 = p2 = list2; p2 != last; p1 = EVAL(l2)) {
p2 = *EVAL(p2);
f1 = l2;
f2 = l1 = list1 + (p2 - list2);
if (p2 != last)
p2 = *EVAL(p2);
l2 = list1 + (p2 - list2);
while (f1 < l1 && f2 < l2) {
if ((*cmp)(f1, f2) <= 0) {
q = f2;
b = f1, t = l1;
sense = -1;
} else {
q = f1;
b = f2, t = l2;
sense = 0;
}
if (!big) { /* here i = 0 */
#if 0
LINEAR:
#endif
while ((b += size) < t && cmp(q, b) >sense)
if (++i == 6) {
big = 1;
goto EXPONENTIAL;
}
} else {
EXPONENTIAL: for (i = size; ; i <<= 1)
if ((p = (b + i)) >= t) {
if ((p = t - size) > b &&
(*cmp)(q, p) <= sense)
t = p;
else
b = p;
break;
} else if ((*cmp)(q, p) <= sense) {
t = p;
if (i == size)
big = 0;
goto FASTCASE;
} else
b = p;
#if 0
SLOWCASE:
#endif
while (t > b+size) {
i = (((t - b) / size) >> 1) * size;
if ((*cmp)(q, p = b + i) <= sense)
t = p;
else
b = p;
}
goto COPY;
FASTCASE: while (i > size)
if ((*cmp)(q,
p = b +
(i = (unsigned int) i >> 1)) <= sense)
t = p;
else
b = p;
COPY: b = t;
}
i = size;
if (q == f1) {
if (iflag) {
ICOPY_LIST(f2, tp2, b);
ICOPY_ELT(f1, tp2, i);
} else {
CCOPY_LIST(f2, tp2, b);
CCOPY_ELT(f1, tp2, i);
}
} else {
if (iflag) {
ICOPY_LIST(f1, tp2, b);
ICOPY_ELT(f2, tp2, i);
} else {
CCOPY_LIST(f1, tp2, b);
CCOPY_ELT(f2, tp2, i);
}
}
}
if (f2 < l2) {
if (iflag)
ICOPY_LIST(f2, tp2, l2);
else
CCOPY_LIST(f2, tp2, l2);
} else if (f1 < l1) {
if (iflag)
ICOPY_LIST(f1, tp2, l1);
else
CCOPY_LIST(f1, tp2, l1);
}
*p1 = l2;
}
tp2 = list1; /* swap list1, list2 */
list1 = list2;
list2 = tp2;
last = list2 + nmemb*size;
}
if (base == list2) {
memmove(list2, list1, nmemb*size);
list2 = list1;
}
free(list2);
return (0);
}
#define swap(a, b) { \
s = b; \
i = size; \
do { \
tmp = *a; *a++ = *s; *s++ = tmp; \
} while (--i); \
a -= size; \
}
#define reverse(bot, top) { \
s = top; \
do { \
i = size; \
do { \
tmp = *bot; *bot++ = *s; *s++ = tmp; \
} while (--i); \
s -= size2; \
} while(bot < s); \
}
/*
* Optional hybrid natural/pairwise first pass. Eats up list1 in runs of
* increasing order, list2 in a corresponding linked list. Checks for runs
* when THRESHOLD/2 pairs compare with same sense. (Only used when NATURAL
* is defined. Otherwise simple pairwise merging is used.)
*/
/* XXX: shouldn't this function be static? - lukem 990810 */
void
setup(list1, list2, n, size, cmp)
size_t n, size;
int (*cmp) __P((const void *, const void *));
u_char *list1, *list2;
{
int i, length, size2, tmp, sense;
u_char *f1, *f2, *s, *l2, *last, *p2;
_DIAGASSERT(cmp != NULL);
_DIAGASSERT(list1 != NULL);
_DIAGASSERT(list2 != NULL);
size2 = size*2;
if (n <= 5) {
insertionsort(list1, n, size, cmp);
*EVAL(list2) = list2 + n*size;
return;
}
/*
* Avoid running pointers out of bounds; limit n to evens
* for simplicity.
*/
i = 4 + (n & 1);
insertionsort(list1 + (n - i) * size, (size_t)i, size, cmp);
last = list1 + size * (n - i);
*EVAL(list2 + (last - list1)) = list2 + n * size;
#ifdef NATURAL
p2 = list2;
f1 = list1;
sense = (cmp(f1, f1 + size) > 0);
for (; f1 < last; sense = !sense) {
length = 2;
/* Find pairs with same sense. */
for (f2 = f1 + size2; f2 < last; f2 += size2) {
if ((cmp(f2, f2+ size) > 0) != sense)
break;
length += 2;
}
if (length < THRESHOLD) { /* Pairwise merge */
do {
p2 = *EVAL(p2) = f1 + size2 - list1 + list2;
if (sense > 0)
swap (f1, f1 + size);
} while ((f1 += size2) < f2);
} else { /* Natural merge */
l2 = f2;
for (f2 = f1 + size2; f2 < l2; f2 += size2) {
if ((cmp(f2-size, f2) > 0) != sense) {
p2 = *EVAL(p2) = f2 - list1 + list2;
if (sense > 0)
reverse(f1, f2-size);
f1 = f2;
}
}
if (sense > 0)
reverse (f1, f2-size);
f1 = f2;
if (f2 < last || cmp(f2 - size, f2) > 0)
p2 = *EVAL(p2) = f2 - list1 + list2;
else
p2 = *EVAL(p2) = list2 + n*size;
}
}
#else /* pairwise merge only. */
for (f1 = list1, p2 = list2; f1 < last; f1 += size2) {
p2 = *EVAL(p2) = p2 + size2;
if (cmp (f1, f1 + size) > 0)
swap(f1, f1 + size);
}
#endif /* NATURAL */
}
/*
* This is to avoid out-of-bounds addresses in sorting the
* last 4 elements.
*/
static void
insertionsort(a, n, size, cmp)
u_char *a;
size_t n, size;
int (*cmp) __P((const void *, const void *));
{
u_char *ai, *s, *t, *u, tmp;
int i;
_DIAGASSERT(a != NULL);
_DIAGASSERT(cmp != NULL);
for (ai = a+size; --n >= 1; ai += size)
for (t = ai; t > a; t -= size) {
u = t - size;
if (cmp(u, t) <= 0)
break;
swap(u, t);
}
}

View File

@@ -0,0 +1,65 @@
.\" $NetBSD: mi_vector_hash.3,v 1.2 2009/07/21 12:40:52 joerg Exp $
.\"
.\" Copyright (c) 2009 The NetBSD Foundation, Inc.
.\" All rights reserved.
.\"
.\" This code is derived from software contributed to The NetBSD Foundation
.\" by Joerg Sonnenberger.
.\"
.\" 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.
.\"
.\" THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
.\"
.Dd July 13, 2009
.Dt MI_VECTOR_HASH 3
.Os
.Sh NAME
.Nm mi_vector_hash
.Nd fast 32bit hash functions
.Sh LIBRARY
.Lb libc
.Sh SYNOPSIS
.In stdlib.h
.Ft void
.Fn mi_vector_hash "const void * restrict key" "size_t len" \
"uint32_t seed" "uint32_t hashes[3]"
.Sh DESCRIPTION
The
.Nm
function computes three 32-bit hash values of the memory area starting at
.Fa key
with length
.Fa len .
.Pp
The output is identical on all architectures and only depends on
.Fa key
and
.Fa seed .
.Sh IMPLEMENTATION NOTES
An optimised code path is used if
.Fa key
is aligned on a 32-bit boundary.
.Sh HISTORY
The
.Nm
function appeared in
.Nx 6.0 .
.Sh AUTHORS
The hash function has been created by Bob Jenkins.

View File

@@ -0,0 +1,171 @@
/* $NetBSD: mi_vector_hash.c,v 1.3 2010/03/19 18:11:30 joerg Exp $ */
/*-
* Copyright (c) 2009 The NetBSD Foundation, Inc.
* All rights reserved.
*
* This code is derived from software contributed to The NetBSD Foundation
* by Joerg Sonnenberger.
*
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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
* COPYRIGHT HOLDERS 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.
*/
/*
* See http://burtleburtle.net/bob/hash/doobs.html for the full description
* and the original version of the code. This version differs by exposing
* the full internal state and avoiding byte operations in the inner loop
* if the key is aligned correctly.
*/
#if HAVE_NBTOOL_CONFIG_H
#include "nbtool_config.h"
#endif
#include <sys/cdefs.h>
__RCSID("$NetBSD: mi_vector_hash.c,v 1.3 2010/03/19 18:11:30 joerg Exp $");
#include "namespace.h"
#include <sys/endian.h>
#include <stdint.h>
#include <stdlib.h>
#define mix(a, b, c) do { \
a -= b; a -= c; a ^= (c >> 13); \
b -= c; b -= a; b ^= (a << 8); \
c -= a; c -= b; c ^= (b >> 13); \
a -= b; a -= c; a ^= (c >> 12); \
b -= c; b -= a; b ^= (a << 16); \
c -= a; c -= b; c ^= (b >> 5); \
a -= b; a -= c; a ^= (c >> 3); \
b -= c; b -= a; b ^= (a << 10); \
c -= a; c -= b; c ^= (b >> 15); \
} while (/* CONSTCOND */0)
#define FIXED_SEED 0x9e3779b9 /* Golden ratio, arbitrary constant */
#ifdef __weak_alias
__weak_alias(mi_vector_hash, _mi_vector_hash)
#endif
void
mi_vector_hash(const void * __restrict key, size_t len, uint32_t seed,
uint32_t hashes[3])
{
static const uint32_t mask[4] = {
0x000000ff, 0x0000ffff, 0x00ffffff, 0xffffffff
};
uint32_t orig_len, a, b, c;
const uint8_t *k;
orig_len = (uint32_t)len;
a = b = FIXED_SEED;
c = seed;
if ((uintptr_t)key & 3) {
k = key;
while (len >= 12) {
a += le32dec(k);
b += le32dec(k + 4);
c += le32dec(k + 8);
mix(a, b, c);
k += 12;
len -= 12;
}
c += orig_len;
if (len > 8) {
switch (len) {
case 11:
c += (uint32_t)k[10] << 24;
/* FALLTHROUGH */
case 10:
c += (uint32_t)k[9] << 16;
/* FALLTHROUGH */
case 9:
c += (uint32_t)k[8] << 8;
/* FALLTHROUGH */
}
b += le32dec(k + 4);
a += le32dec(k);
} else if (len > 4) {
switch (len) {
case 8:
b += (uint32_t)k[7] << 24;
/* FALLTHROUGH */
case 7:
b += (uint32_t)k[6] << 16;
/* FALLTHROUGH */
case 6:
b += (uint32_t)k[5] << 8;
/* FALLTHROUGH */
case 5:
b += k[4];
/* FALLTHROUGH */
}
a += le32dec(k);
} else if (len) {
switch (len) {
case 4:
a += (uint32_t)k[3] << 24;
/* FALLTHROUGH */
case 3:
a += (uint32_t)k[2] << 16;
/* FALLTHROUGH */
case 2:
a += (uint32_t)k[1] << 8;
/* FALLTHROUGH */
case 1:
a += k[0];
/* FALLTHROUGH */
}
}
} else {
const uint32_t *key32 = key;
while (len >= 12) {
a += le32toh(key32[0]);
b += le32toh(key32[1]);
c += le32toh(key32[2]);
mix(a, b, c);
key32 += 3;
len -= 12;
}
c += orig_len;
if (len > 8) {
c += (le32toh(key32[2]) & mask[len - 9]) << 8;
b += le32toh(key32[1]);
a += le32toh(key32[0]);
} else if (len > 4) {
b += le32toh(key32[1]) & mask[len - 5];
a += le32toh(key32[0]);
} else if (len)
a += le32toh(key32[0]) & mask[len - 1];
}
mix(a, b, c);
hashes[0] = a;
hashes[1] = b;
hashes[2] = c;
}

View File

@@ -0,0 +1,33 @@
/* $NetBSD: mrand48.c,v 1.7 2005/06/12 05:21:28 lukem Exp $ */
/*
* Copyright (c) 1993 Martin Birgmeier
* All rights reserved.
*
* You may redistribute unmodified or modified versions of this source
* code provided that the above copyright notice and this and the
* following conditions are retained.
*
* This software is provided ``as is'', and comes with no warranties
* of any kind. I shall in no event be liable for anything that happens
* to anyone/anything when using this software.
*/
#include <sys/cdefs.h>
#if defined(LIBC_SCCS) && !defined(lint)
__RCSID("$NetBSD: mrand48.c,v 1.7 2005/06/12 05:21:28 lukem Exp $");
#endif /* LIBC_SCCS and not lint */
#include "namespace.h"
#include "rand48.h"
#ifdef __weak_alias
__weak_alias(mrand48,_mrand48)
#endif
long
mrand48(void)
{
__dorand48(__rand48_seed);
return ((long) __rand48_seed[2] << 16) + (long) __rand48_seed[1];
}

View File

@@ -0,0 +1,39 @@
/* $NetBSD: nrand48.c,v 1.9 2005/06/12 05:21:28 lukem Exp $ */
/*
* Copyright (c) 1993 Martin Birgmeier
* All rights reserved.
*
* You may redistribute unmodified or modified versions of this source
* code provided that the above copyright notice and this and the
* following conditions are retained.
*
* This software is provided ``as is'', and comes with no warranties
* of any kind. I shall in no event be liable for anything that happens
* to anyone/anything when using this software.
*/
#include <sys/cdefs.h>
#if defined(LIBC_SCCS) && !defined(lint)
__RCSID("$NetBSD: nrand48.c,v 1.9 2005/06/12 05:21:28 lukem Exp $");
#endif /* LIBC_SCCS and not lint */
#include "namespace.h"
#include <assert.h>
#include "rand48.h"
#ifdef __weak_alias
__weak_alias(nrand48,_nrand48)
#endif
long
nrand48(unsigned short xseed[3])
{
_DIAGASSERT(xseed != NULL);
__dorand48(xseed);
return (long)((unsigned long) xseed[2] << 15) +
((unsigned long) xseed[1] >> 1);
}

View File

@@ -0,0 +1,91 @@
.\" $NetBSD: posix_memalign.3,v 1.1 2007/11/19 14:48:43 ad Exp $
.\"
.\" Copyright (C) 2006 Jason Evans <jasone@FreeBSD.org>.
.\" 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(s), this list of conditions and the following disclaimer as
.\" the first lines of this file unmodified other than the possible
.\" addition of one or more copyright notices.
.\" 2. Redistributions in binary form must reproduce the above copyright
.\" notice(s), this list of conditions and the following disclaimer in
.\" the documentation and/or other materials provided with the
.\" distribution.
.\"
.\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) ``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 COPYRIGHT HOLDER(S) 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.
.\"
.\" FreeBSD: src/lib/libc/stdlib/posix_memalign.3,v 1.3 2007/03/28 04:32:51 jasone Exp
.\"
.Dd November 19, 2007
.Dt POSIX_MEMALIGN 3
.Os
.Sh NAME
.Nm posix_memalign
.Nd aligned memory allocation
.Sh LIBRARY
.Lb libc
.Sh SYNOPSIS
.In stdlib.h
.Ft int
.Fn posix_memalign "void **ptr" "size_t alignment" "size_t size"
.Sh DESCRIPTION
The
.Fn posix_memalign
function allocates
.Fa size
bytes of memory such that the allocation's base address is an even multiple of
.Fa alignment ,
and returns the allocation in the value pointed to by
.Fa ptr .
.Pp
The requested
.Fa alignment
must be a power of 2 at least as large as
.Fn sizeof "void *" .
.Pp
Memory that is allocated via
.Fn posix_memalign
can be used as an argument in subsequent calls to
.Xr realloc 3
and
.Xr free 3 .
.Sh RETURN VALUES
The
.Fn posix_memalign
function returns the value 0 if successful; otherwise it returns an error value.
.Sh ERRORS
The
.Fn posix_memalign
function will fail if:
.Bl -tag -width Er
.It Bq Er EINVAL
The
.Fa alignment
parameter is not a power of 2 at least as large as
.Fn sizeof "void *" .
.It Bq Er ENOMEM
Memory allocation error.
.El
.Sh SEE ALSO
.Xr free 3 ,
.Xr malloc 3 ,
.Xr realloc 3 ,
.Xr valloc 3
.Sh STANDARDS
The
.Fn posix_memalign
function conforms to
.St -p1003.1-2001 .

View File

@@ -0,0 +1,80 @@
.\" $NetBSD: posix_openpt.3,v 1.4 2008/04/30 13:10:51 martin Exp $
.\"
.\" Copyright (c) 2004 The NetBSD Foundation, Inc.
.\" All rights reserved.
.\"
.\" This code is derived from software contributed to The NetBSD Foundation
.\" by Christos Zoulas.
.\"
.\" 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.
.\"
.\" THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
.\"
.Dd May 25, 2004
.Dt POSIX_OPENPT 3
.Os
.Sh NAME
.Nm posix_openpt
.Nd open a pseudo-terminal device
.Sh LIBRARY
.Lb libc
.Sh SYNOPSIS
.In stdlib.h
.In fcntl.h
.Ft int
.Fn posix_openpt "int oflag"
.Sh DESCRIPTION
.Fn posix_openpt
Searches for an unused master pseudo-terminal device, opens it, and returns
a file descriptor associated the now used pseudo-terminal device.
The
.Fa oflag
argument has the same meaning as in the
.Xr open 2
call.
.Sh RETURN VALUES
If successful,
.Fn posix_openpt
returns a non-negative integer, which corresponds to a file descriptor
pointing to the master pseudo-terminal device.
Otherwise, a value of \-1 is returned and
.Va errno
is set to indicate the error.
.Sh SEE ALSO
.Xr ioctl 2 ,
.Xr open 2 ,
.Xr grantpt 3 ,
.Xr ptsname 3 ,
.Xr unlockpt 3
.Sh RATIONALE
The standards committee did not want to directly expose the cloning device,
thus decided to wrap the functionality in this function.
The equivalent code would be:
.Bd -literal
int
posix_openpt(int oflag) {
return open("/dev/ptmx", oflag);
}
.Ed
.Sh STANDARDS
The
.Fn posix_openpt
function conforms to
.St -p1003.1-2001 .

View File

@@ -0,0 +1,46 @@
/* $NetBSD: posix_openpt.c,v 1.2 2008/04/28 20:23:00 martin Exp $ */
/*-
* Copyright (c) 2004 The NetBSD Foundation, Inc.
* All rights reserved.
*
* This code is derived from software contributed to The NetBSD Foundation
* by Christos Zoulas.
*
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
*/
#include <sys/cdefs.h>
#if defined(LIBC_SCCS) && !defined(lint)
__RCSID("$NetBSD: posix_openpt.c,v 1.2 2008/04/28 20:23:00 martin Exp $");
#endif /* LIBC_SCCS and not lint */
#include "namespace.h"
#include <fcntl.h>
#include <stdlib.h>
int
posix_openpt(int oflag)
{
return open("/dev/ptmx", oflag);
}

View File

@@ -0,0 +1,101 @@
.\" $NetBSD: ptsname.3,v 1.5 2008/04/30 13:10:51 martin Exp $
.\"
.\" Copyright (c) 2004 The NetBSD Foundation, Inc.
.\" All rights reserved.
.\"
.\" This code is derived from software contributed to The NetBSD Foundation
.\" by Christos Zoulas.
.\"
.\" 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.
.\"
.\" THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
.\"
.Dd May 25, 2004
.Dt PTSNAME 3
.Os
.Sh NAME
.Nm ptsname
.Nd get the pathname of the slave pseudo-terminal device
.Sh LIBRARY
.Lb libc
.Sh SYNOPSIS
.In stdlib.h
.Ft char *
.Fn ptsname "int masterfd"
.Sh DESCRIPTION
The
.Fn ptsname
function returns the pathname of the slave pseudo-terminal device
that corresponds to the master pseudo-terminal device associated with
.Fa masterfd .
The
.Fn ptsname
function is not reentrant or thread-safe.
.Sh RETURN VALUES
If successful,
.Fn ptsname
returns a pointer to a nul-terminated string containing the pathname
of the slave pseudo-terminal device.
If an error occurs
.Fn ptsname
will return
.Dv NULL
and
.Va errno
is set to indicate the error.
.Sh ERRORS
The
.Fn ptsname
function will fail if:
.Bl -tag -width Er
.It Bq Er EACCESS
the corresponding pseudo-terminal device could not be accessed.
.It Bq Er EBADF
.Fa masterfd
is not a valid descriptor.
.It Bq Er EINVAL
.Fa masterfd
is not associated with a master pseudo-terminal device.
.El
.Sh NOTES
The error returns of
.Fn ptsname
are a
.Nx
extension.
The
.Fn ptsname
function is equivalent to:
.Bd -literal
struct ptmget pm;
return ioctl(masterfd, TIOCPTSNAME, \*[Am]pm) == -1 ? NULL : pm.ps;
.Ed
.Sh SEE ALSO
.Xr ioctl 2 ,
.Xr grantpt 3 ,
.Xr posix_openpt 3 ,
.Xr unlockpt 3
.Sh STANDARDS
The
.Fn ptsname
function conforms to
.St -p1003.1-2001 .
Its first release was in
.St -xpg4.2 .

View File

@@ -0,0 +1,66 @@
/* $NetBSD: pty.c,v 1.2 2008/04/28 20:23:00 martin Exp $ */
/*-
* Copyright (c) 2004 The NetBSD Foundation, Inc.
* All rights reserved.
*
* This code is derived from software contributed to The NetBSD Foundation
* by Christos Zoulas.
*
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
*/
#include <sys/cdefs.h>
#if defined(LIBC_SCCS) && !defined(lint)
__RCSID("$NetBSD: pty.c,v 1.2 2008/04/28 20:23:00 martin Exp $");
#endif /* LIBC_SCCS and not lint */
#include "namespace.h"
#include <fcntl.h>
#include <stdlib.h>
#include <sys/ioctl.h>
int
grantpt(int fildes)
{
return ioctl(fildes, TIOCGRANTPT, 0);
}
int
/*ARGSUSED*/
unlockpt(int fildes)
{
return 0;
}
char *
ptsname(int fildes)
{
static struct ptmget pm;
if (ioctl(fildes, TIOCPTSNAME, &pm) == -1)
return NULL;
return pm.sn;
}

View File

@@ -0,0 +1,87 @@
/* $NetBSD: putenv.c,v 1.19 2010/11/14 18:11:43 tron Exp $ */
/*-
* 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. 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.
*/
#include <sys/cdefs.h>
#if defined(LIBC_SCCS) && !defined(lint)
#if 0
static char sccsid[] = "@(#)putenv.c 8.2 (Berkeley) 3/27/94";
#else
__RCSID("$NetBSD: putenv.c,v 1.19 2010/11/14 18:11:43 tron Exp $");
#endif
#endif /* LIBC_SCCS and not lint */
#include "namespace.h"
#include <assert.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include "env.h"
#include "reentrant.h"
#include "local.h"
#ifdef __weak_alias
__weak_alias(putenv,_putenv)
#endif
int
putenv(char *str)
{
size_t l_name;
int rv;
_DIAGASSERT(str != NULL);
l_name = __envvarnamelen(str, true);
if (l_name == 0) {
errno = EINVAL;
return -1;
}
rv = -1;
if (__writelockenv()) {
ssize_t offset;
offset = __getenvslot(str, l_name, true);
if (offset != -1) {
if (environ[offset] != NULL)
__freeenvvar(environ[offset]);
environ[offset] = str;
rv = 0;
}
(void)__unlockenv();
}
return rv;
}

View File

@@ -0,0 +1,63 @@
.\" $NetBSD: qabs.3,v 1.9 2008/08/04 21:29:27 matt Exp $
.\"
.\" Copyright (c) 1990, 1991 The Regents of the University of California.
.\" All rights reserved.
.\"
.\" This code is derived from software contributed to Berkeley by
.\" the American National Standards Committee X3, on Information
.\" Processing Systems.
.\"
.\" 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. 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.
.\"
.\" from: @(#)labs.3 5.3 (Berkeley) 6/29/91
.\"
.Dd June 29, 1991
.Dt QABS 3
.Os
.Sh NAME
.Nm qabs
.Nd return the absolute value of a quad integer
.Sh LIBRARY
.Lb libc
.Sh SYNOPSIS
.In stdlib.h
.Ft quad_t
.Fn qabs "quad_t j"
.Sh DESCRIPTION
The
.Fn qabs
function
returns the absolute value of the quad integer
.Ar j .
.Sh SEE ALSO
.Xr abs 3 ,
.Xr cabs 3 ,
.Xr floor 3 ,
.Xr imaxabs 3 ,
.Xr labs 3 ,
.Xr llabs 3 ,
.Xr math 3
.Sh BUGS
The absolute value of the most negative integer remains negative.

View File

@@ -0,0 +1,53 @@
/* $NetBSD: qabs.c,v 1.6 2003/08/07 16:43:42 agc Exp $ */
/*-
* Copyright (c) 1990 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. 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.
*/
#include <sys/cdefs.h>
#if defined(LIBC_SCCS) && !defined(lint)
#if 0
static char *sccsid = "from: @(#)labs.c 5.2 (Berkeley) 5/17/90";
#else
__RCSID("$NetBSD: qabs.c,v 1.6 2003/08/07 16:43:42 agc Exp $");
#endif
#endif /* LIBC_SCCS and not lint */
#include "namespace.h"
#include <stdlib.h>
#ifdef __weak_alias
__weak_alias(qabs,_qabs)
#endif
quad_t
qabs(j)
quad_t j;
{
return(j < 0 ? -j : j);
}

View File

@@ -0,0 +1,67 @@
.\" $NetBSD: qdiv.3,v 1.9 2008/08/04 21:29:27 matt Exp $
.\"
.\" Copyright (c) 1990, 1991 The Regents of the University of California.
.\" All rights reserved.
.\"
.\" This code is derived from software contributed to Berkeley by
.\" Chris Torek and the American National Standards Committee X3,
.\" on Information Processing Systems.
.\"
.\" 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. 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.
.\"
.\" from: @(#)qdiv.3 5.3 (Berkeley) 6/29/91
.\"
.Dd June 29, 1991
.Dt QDIV 3
.Os
.Sh NAME
.Nm qdiv
.Nd return quotient and remainder from division
.Sh LIBRARY
.Lb libc
.Sh SYNOPSIS
.In stdlib.h
.Ft qdiv_t
.Fn qdiv "quad_t num" "quad_t denom"
.Sh DESCRIPTION
The
.Fn qdiv
function
computes the value
.Ar num/denom
and returns the quotient and remainder in a structure named
.Ar qdiv_t
that contains two
.Em quad integer
members named
.Ar quot
and
.Ar rem .
.Sh SEE ALSO
.Xr div 3 ,
.Xr imaxdiv 3 ,
.Xr ldiv 3 ,
.Xr lldiv 3 ,
.Xr math 3

View File

@@ -0,0 +1,66 @@
/* $NetBSD: qdiv.c,v 1.6 2003/08/07 16:43:42 agc Exp $ */
/*
* Copyright (c) 1990 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. 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.
*/
#include <sys/cdefs.h>
#if defined(LIBC_SCCS) && !defined(lint)
#if 0
static char *sccsid = "from: @(#)ldiv.c 5.2 (Berkeley) 4/16/91";
#else
__RCSID("$NetBSD: qdiv.c,v 1.6 2003/08/07 16:43:42 agc Exp $");
#endif
#endif /* LIBC_SCCS and not lint */
#include "namespace.h"
#include <stdlib.h> /* qdiv_t */
#ifdef __weak_alias
__weak_alias(qdiv,_qdiv)
#endif
qdiv_t
qdiv(num, denom)
quad_t num, denom;
{
qdiv_t r;
/* see div.c for comments */
r.quot = num / denom;
r.rem = num % denom;
if (num >= 0 && r.rem < 0) {
r.quot++;
r.rem -= denom;
}
return (r);
}

View File

@@ -0,0 +1,238 @@
.\" $NetBSD: qsort.3,v 1.13 2003/08/07 16:43:42 agc Exp $
.\"
.\" Copyright (c) 1990, 1991, 1993
.\" The Regents of the University of California. All rights reserved.
.\"
.\" This code is derived from software contributed to Berkeley by
.\" the American National Standards Committee X3, on Information
.\" Processing Systems.
.\"
.\" 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. 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.
.\"
.\" from: @(#)qsort.3 8.1 (Berkeley) 6/4/93
.\"
.Dd June 4, 1993
.Dt QSORT 3
.Os
.Sh NAME
.Nm qsort ,
.Nm heapsort ,
.Nm mergesort
.Nd sort functions
.Sh LIBRARY
.Lb libc
.Sh SYNOPSIS
.In stdlib.h
.Ft void
.Fn qsort "void *base" "size_t nmemb" "size_t size" "int (*compar)(const void *, const void *)"
.Ft int
.Fn heapsort "void *base" "size_t nmemb" "size_t size" "int (*compar)(const void *, const void *)"
.Ft int
.Fn mergesort "void *base" "size_t nmemb" "size_t size" "int (*compar)(const void *, const void *)"
.Sh DESCRIPTION
The
.Fn qsort
function is a modified partition-exchange sort, or quicksort.
The
.Fn heapsort
function is a modified selection sort.
The
.Fn mergesort
function is a modified merge sort with exponential search
intended for sorting data with pre-existing order.
.Pp
The
.Fn qsort
and
.Fn heapsort
functions sort an array of
.Fa nmemb
objects, the initial member of which is pointed to by
.Fa base .
The size of each object is specified by
.Fa size .
.Fn mergesort
behaves similarly, but
.Em requires
that
.Fa size
be greater than
.Dq "sizeof(void *) / 2" .
.Pp
The contents of the array
.Fa base
are sorted in ascending order according to
a comparison function pointed to by
.Fa compar ,
which requires two arguments pointing to the objects being
compared.
.Pp
The comparison function must return an integer less than, equal to, or
greater than zero if the first argument is considered to be respectively
less than, equal to, or greater than the second.
.Pp
The functions
.Fn qsort
and
.Fn heapsort
are
.Em not
stable, that is, if two members compare as equal, their order in
the sorted array is undefined.
The function
.Fn mergesort
is stable.
.Pp
The
.Fn qsort
function is an implementation of C.A.R. Hoare's ``quicksort'' algorithm,
a variant of partition-exchange sorting; in particular, see D.E. Knuth's
Algorithm Q.
.Fn qsort
takes O N lg N average time.
This implementation uses median selection to avoid its
O N**2 worst-case behavior.
.Pp
The
.Fn heapsort
function is an implementation of J.W.J. William's ``heapsort'' algorithm,
a variant of selection sorting; in particular, see D.E. Knuth's Algorithm H.
.Fn heapsort
takes O N lg N worst-case time.
Its
.Em only
advantage over
.Fn qsort
is that it uses almost no additional memory; while
.Fn qsort
does not allocate memory, it is implemented using recursion.
.Pp
The function
.Fn mergesort
requires additional memory of size
.Fa nmemb *
.Fa size
bytes; it should be used only when space is not at a premium.
.Fn mergesort
is optimized for data with pre-existing order; its worst case
time is O N lg N; its best case is O N.
.Pp
Normally,
.Fn qsort
is faster than
.Fn mergesort
is faster than
.Fn heapsort .
Memory availability and pre-existing order in the data can make this
untrue.
.Sh RETURN VALUES
The
.Fn qsort
function
returns no value.
.Pp
Upon successful completion,
.Fn heapsort
and
.Fn mergesort
return 0.
Otherwise, they return \-1 and the global variable
.Va errno
is set to indicate the error.
.Sh ERRORS
The
.Fn heapsort
function succeeds unless:
.Bl -tag -width Er
.It Bq Er EINVAL
The
.Fa size
argument is zero, or,
the
.Fa size
argument to
.Fn mergesort
is less than
.Dq "sizeof(void *) / 2" .
.It Bq Er ENOMEM
.Fn heapsort
or
.Fn mergesort
were unable to allocate memory.
.El
.Sh COMPATIBILITY
Previous versions of
.Fn qsort
did not permit the comparison routine itself to call
.Fn qsort .
This is no longer true.
.Sh SEE ALSO
.Xr sort 1 ,
.Xr radixsort 3
.Rs
.%A Hoare, C.A.R.
.%D 1962
.%T "Quicksort"
.%J "The Computer Journal"
.%V 5:1
.%P pp. 10-15
.Re
.Rs
.%A Williams, J.W.J
.%D 1964
.%T "Heapsort"
.%J "Communications of the ACM"
.%V 7:1
.%P pp. 347-348
.Re
.Rs
.%A Knuth, D.E.
.%D 1968
.%B "The Art of Computer Programming"
.%V Vol. 3
.%T "Sorting and Searching"
.%P pp. 114-123, 145-149
.Re
.Rs
.%A McIlroy, P.M.
.%D 1993
.%T "Optimistic Sorting and Information Theoretic Complexity"
.%J "Proceedings of the Fourth Annual ACM-SIAM Symposium on Discrete Algorithms"
.%P pp. 467-474
.Re
.Rs
.%A Bentley, J.L. and McIlroy, M.D.
.%D 1993
.%T "Engineering a Sort Function"
.%J "Software-Practice and Experience"
.%V Vol. 23
.%P pp. 1249-1265
.Re
.Sh STANDARDS
The
.Fn qsort
function
conforms to
.St -ansiC .

View File

@@ -0,0 +1,171 @@
/* $NetBSD: qsort.c,v 1.20 2009/06/01 06:37:40 yamt Exp $ */
/*-
* Copyright (c) 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. 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.
*/
#include <sys/cdefs.h>
#if defined(LIBC_SCCS) && !defined(lint)
#if 0
static char sccsid[] = "@(#)qsort.c 8.1 (Berkeley) 6/4/93";
#else
__RCSID("$NetBSD: qsort.c,v 1.20 2009/06/01 06:37:40 yamt Exp $");
#endif
#endif /* LIBC_SCCS and not lint */
#include <sys/types.h>
#include <assert.h>
#include <errno.h>
#include <stdlib.h>
static inline char *med3 __P((char *, char *, char *,
int (*)(const void *, const void *)));
static inline void swapfunc __P((char *, char *, size_t, int));
#define min(a, b) (a) < (b) ? a : b
/*
* Qsort routine from Bentley & McIlroy's "Engineering a Sort Function".
*/
#define swapcode(TYPE, parmi, parmj, n) { \
size_t i = (n) / sizeof (TYPE); \
TYPE *pi = (TYPE *)(void *)(parmi); \
TYPE *pj = (TYPE *)(void *)(parmj); \
do { \
TYPE t = *pi; \
*pi++ = *pj; \
*pj++ = t; \
} while (--i > 0); \
}
#define SWAPINIT(a, es) swaptype = ((char *)a - (char *)0) % sizeof(long) || \
es % sizeof(long) ? 2 : es == sizeof(long)? 0 : 1;
static inline void
swapfunc(char *a, char *b, size_t n, int swaptype)
{
if (swaptype <= 1)
swapcode(long, a, b, n)
else
swapcode(char, a, b, n)
}
#define swap(a, b) \
if (swaptype == 0) { \
long t = *(long *)(void *)(a); \
*(long *)(void *)(a) = *(long *)(void *)(b); \
*(long *)(void *)(b) = t; \
} else \
swapfunc(a, b, es, swaptype)
#define vecswap(a, b, n) if ((n) > 0) swapfunc((a), (b), (size_t)(n), swaptype)
static inline char *
med3(char *a, char *b, char *c,
int (*cmp) __P((const void *, const void *)))
{
return cmp(a, b) < 0 ?
(cmp(b, c) < 0 ? b : (cmp(a, c) < 0 ? c : a ))
:(cmp(b, c) > 0 ? b : (cmp(a, c) < 0 ? a : c ));
}
void
qsort(void *a, size_t n, size_t es,
int (*cmp) __P((const void *, const void *)))
{
char *pa, *pb, *pc, *pd, *pl, *pm, *pn;
size_t d, r;
int swaptype, cmp_result;
_DIAGASSERT(a != NULL);
_DIAGASSERT(cmp != NULL);
loop: SWAPINIT(a, es);
if (n < 7) {
for (pm = (char *) a + es; pm < (char *) a + n * es; pm += es)
for (pl = pm; pl > (char *) a && cmp(pl - es, pl) > 0;
pl -= es)
swap(pl, pl - es);
return;
}
pm = (char *) a + (n / 2) * es;
if (n > 7) {
pl = (char *) a;
pn = (char *) a + (n - 1) * es;
if (n > 40) {
d = (n / 8) * es;
pl = med3(pl, pl + d, pl + 2 * d, cmp);
pm = med3(pm - d, pm, pm + d, cmp);
pn = med3(pn - 2 * d, pn - d, pn, cmp);
}
pm = med3(pl, pm, pn, cmp);
}
swap(a, pm);
pa = pb = (char *) a + es;
pc = pd = (char *) a + (n - 1) * es;
for (;;) {
while (pb <= pc && (cmp_result = cmp(pb, a)) <= 0) {
if (cmp_result == 0) {
swap(pa, pb);
pa += es;
}
pb += es;
}
while (pb <= pc && (cmp_result = cmp(pc, a)) >= 0) {
if (cmp_result == 0) {
swap(pc, pd);
pd -= es;
}
pc -= es;
}
if (pb > pc)
break;
swap(pb, pc);
pb += es;
pc -= es;
}
pn = (char *) a + n * es;
r = min(pa - (char *) a, pb - pa);
vecswap(a, pb - r, r);
r = min((size_t)(pd - pc), pn - pd - es);
vecswap(pb, pn - r, r);
if ((r = pb - pa) > es)
qsort(a, r / es, es, cmp);
if ((r = pd - pc) > es) {
/* Iterate rather than recurse to save stack space */
a = pn - r;
n = r / es;
goto loop;
}
/* qsort(pn - r, r / es, es, cmp);*/
}

View File

@@ -0,0 +1,167 @@
.\" $NetBSD: radixsort.3,v 1.13 2003/08/07 16:43:43 agc Exp $
.\"
.\" 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. 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.
.\"
.\" from: @(#)radixsort.3 8.2 (Berkeley) 1/27/94
.\"
.Dd January 27, 1994
.Dt RADIXSORT 3
.Os
.Sh NAME
.Nm radixsort ,
.Nm sradixsort
.Nd radix sort
.Sh LIBRARY
.Lb libc
.Sh SYNOPSIS
.In limits.h
.In stdlib.h
.Ft int
.Fn radixsort "const u_char **base" "int nmemb" "u_char *table" "u_int endbyte"
.Ft int
.Fn sradixsort "const u_char **base" "int nmemb" "u_char *table" "u_int endbyte"
.Sh DESCRIPTION
The
.Fn radixsort
and
.Fn sradixsort
functions
are implementations of radix sort.
.Pp
These functions sort an
.Fa nmemb
element array of pointers to byte strings, with
the initial member of which is referenced by
.Fa base .
The byte strings may contain any values.
End of strings is denoted
by character which has same weight as user specified value
.Fa endbyte .
.Fa endbyte
has to be between 0 and 255.
.Pp
Applications may specify a sort order by providing the
.Fa table
argument.
If
.Pf non- Dv NULL ,
.Fa table
must reference an array of
.Dv UCHAR_MAX
+ 1 bytes which contains the sort
weight of each possible byte value.
The end-of-string byte must have a sort weight of 0 or 255
(for sorting in reverse order).
More than one byte may have the same sort weight.
The
.Fa table
argument
is useful for applications which wish to sort different characters
equally, for example, providing a table with the same weights
for A-Z as for a-z will result in a case-insensitive sort.
If
.Fa table
is NULL, the contents of the array are sorted in ascending order
according to the
.Tn ASCII
order of the byte strings they reference and
.Fa endbyte
has a sorting weight of 0.
.Pp
The
.Fn sradixsort
function is stable, that is, if two elements compare as equal, their
order in the sorted array is unchanged.
The
.Fn sradixsort
function uses additional memory sufficient to hold
.Fa nmemb
pointers.
.Pp
The
.Fn radixsort
function is not stable, but uses no additional memory.
.Pp
These functions are variants of most-significant-byte radix sorting; in
particular, see D.E. Knuth's Algorithm R and section 5.2.5, exercise 10.
They take linear time relative to the number of bytes in the strings.
.Sh RETURN VALUES
Upon successful completion 0 is returned.
Otherwise, \-1 is returned and the global variable
.Va errno
is set to indicate the error.
.Sh ERRORS
.Bl -tag -width Er
.It Bq Er EINVAL
The value of the
.Fa endbyte
element of
.Fa table
is not 0 or 255.
.El
.Pp
Additionally, the
.Fn sradixsort
function
may fail and set
.Va errno
for any of the errors specified for the library routine
.Xr malloc 3 .
.Sh SEE ALSO
.Xr sort 1 ,
.Xr qsort 3
.Pp
.Rs
.%A Knuth, D.E.
.%D 1968
.%B "The Art of Computer Programming"
.%T "Sorting and Searching"
.%V Vol. 3
.%P pp. 170-178
.Re
.Rs
.%A Paige, R.
.%D 1987
.%T "Three Partition Refinement Algorithms"
.%J "SIAM J. Comput."
.%V Vol. 16
.%N No. 6
.Re
.Rs
.%A McIlroy, P.
.%D 1993
.%B "Engineering Radix Sort"
.%T "Computing Systems"
.%V Vol. 6:1
.%P pp. 5-27
.Re
.Sh HISTORY
The
.Fn radixsort
function first appeared in
.Bx 4.4 .

View File

@@ -0,0 +1,329 @@
/* $NetBSD: radixsort.c,v 1.19 2009/09/05 08:53:06 dsl Exp $ */
/*-
* 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. 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.
*/
#include <sys/cdefs.h>
#if defined(LIBC_SCCS) && !defined(lint)
#if 0
static char sccsid[] = "@(#)radixsort.c 8.2 (Berkeley) 4/28/95";
#else
__RCSID("$NetBSD: radixsort.c,v 1.19 2009/09/05 08:53:06 dsl Exp $");
#endif
#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 "namespace.h"
#include <sys/types.h>
#include <assert.h>
#include <errno.h>
#include <stdlib.h>
#ifdef __weak_alias
__weak_alias(radixsort,_radixsort)
__weak_alias(sradixsort,_sradixsort)
#endif
typedef struct {
const u_char **sa;
int sn, si;
} stack;
static inline void simplesort(const u_char **, int, int, const u_char *, u_int);
static void r_sort_a(const u_char **, int, int, const u_char *, u_int);
static void r_sort_b(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(const u_char **a, int n, const u_char *tab, u_int endch)
{
const u_char *tr;
u_int c;
u_char tr0[256];
_DIAGASSERT(a != NULL);
SETUP;
r_sort_a(a, n, 0, tr, endch);
return (0);
}
int
sradixsort(const u_char **a, int n, const u_char *tab, u_int endch)
{
const u_char *tr, **ta;
u_int c;
u_char tr0[256];
_DIAGASSERT(a != NULL);
if (a == NULL) {
errno = EFAULT;
return (-1);
}
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(const u_char **a, int n, int i, const u_char *tr, u_int endch)
{
static u_int count[256], nc, bmin;
u_int c;
const u_char **ak, *r;
stack s[SIZE], *sp, *sp0, *sp1, temp;
u_int *cp, bigc;
const u_char **an, *t, **aj, **top[256];
_DIAGASSERT(a != NULL);
_DIAGASSERT(tr != NULL);
/* 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(const u_char **a, const u_char **ta, int n, int i, const u_char *tr,
u_int endch)
{
static u_int count[256], nc, bmin;
u_int c;
const u_char **ak, **ai;
stack s[512], *sp, *sp0, *sp1, temp;
const u_char **top[256];
u_int *cp, bigc;
_DIAGASSERT(a != NULL);
_DIAGASSERT(ta != NULL);
_DIAGASSERT(tr != NULL);
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;
}
}
/* insertion sort */
static inline void
simplesort(const u_char **a, int n, int b, const u_char *tr, u_int endch)
{
u_char ch;
const u_char **ak, **ai, *s, *t;
_DIAGASSERT(a != NULL);
_DIAGASSERT(tr != NULL);
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);
}
}

100
lib/nbsd_libc/stdlib/rand.3 Normal file
View File

@@ -0,0 +1,100 @@
.\" $NetBSD: rand.3,v 1.12 2010/03/22 19:30:54 joerg Exp $
.\"
.\" Copyright (c) 1990, 1991, 1993
.\" The Regents of the University of California. All rights reserved.
.\"
.\" This code is derived from software contributed to Berkeley by
.\" the American National Standards Committee X3, on Information
.\" Processing Systems.
.\"
.\" 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. 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.
.\"
.\" from: @(#)rand.3 8.1 (Berkeley) 6/4/93
.\"
.Dd June 4, 1993
.Dt RAND 3
.Os
.Sh NAME
.Nm rand ,
.Nm srand ,
.Nm rand_r
.Nd bad random number generator
.Sh LIBRARY
.Lb libc
.Sh SYNOPSIS
.In stdlib.h
.Ft void
.Fn srand "unsigned int seed"
.Ft int
.Fn rand void
.Ft int
.Fn rand_r "unsigned int *seed"
.Sh DESCRIPTION
.Bf -symbolic
These interfaces are obsoleted by
.Xr random 3 .
.Ef
.Pp
The
.Fn rand
function computes a sequence of pseudo-random integers in the range
of 0 to
.Dv RAND_MAX
(as defined by the header file
.In stdlib.h ) .
.Pp
The
.Fn srand
function sets its argument as the seed for a new sequence of
pseudo-random numbers to be returned by
.Fn rand .
These sequences are repeatable by calling
.Fn srand
with the same seed value.
.Pp
If no seed value is provided, the
.Fn rand
function is automatically seeded with a value of 1.
.Pp
The
.Fn rand_r
function is a reentrant interface to
.Fn rand ;
the seed has to be supplied and is maintained by the caller.
.Sh SEE ALSO
.Xr random 3 ,
.Xr rnd 4
.Sh STANDARDS
The
.Fn rand
and
.Fn srand
functions
conform to
.St -ansiC .
The
.Fn rand_r
function conforms to
.St -p1003.1c-95 .

View File

@@ -0,0 +1,58 @@
/* $NetBSD: rand.c,v 1.10 2003/08/07 16:43:43 agc Exp $ */
/*-
* 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. 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.
*/
#include <sys/cdefs.h>
#if defined(LIBC_SCCS) && !defined(lint)
#if 0
static char sccsid[] = "@(#)rand.c 8.1 (Berkeley) 6/14/93";
#else
__RCSID("$NetBSD: rand.c,v 1.10 2003/08/07 16:43:43 agc Exp $");
#endif
#endif /* LIBC_SCCS and not lint */
#include <sys/types.h>
#include <stdlib.h>
static u_long next = 1;
int
rand()
{
/* LINTED integer overflow */
return (int)((next = next * 1103515245 + 12345) % ((u_long)RAND_MAX + 1));
}
void
srand(seed)
u_int seed;
{
next = seed;
}

View File

@@ -0,0 +1,163 @@
.\" $NetBSD: rand48.3,v 1.11 2006/03/31 11:43:54 drochner Exp $
.\"
.\" Copyright (c) 1993 Martin Birgmeier
.\" All rights reserved.
.\"
.\" You may redistribute unmodified or modified versions of this source
.\" code provided that the above copyright notice and this and the
.\" following conditions are retained.
.\"
.\" This software is provided ``as is'', and comes with no warranties
.\" of any kind. I shall in no event be liable for anything that happens
.\" to anyone/anything when using this software.
.\"
.Dd October 8, 1993
.Dt RAND48 3
.Os
.Sh NAME
.Nm drand48 ,
.Nm erand48 ,
.Nm lrand48 ,
.Nm nrand48 ,
.Nm mrand48 ,
.Nm jrand48 ,
.Nm srand48 ,
.Nm seed48 ,
.Nm lcong48
.Nd pseudo-random number generators and initialization routines
.Sh LIBRARY
.Lb libc
.Sh SYNOPSIS
.In stdlib.h
.Ft double
.Fn drand48 void
.Ft double
.Fn erand48 "unsigned short xseed[3]"
.Ft long
.Fn lrand48 void
.Ft long
.Fn nrand48 "unsigned short xseed[3]"
.Ft long
.Fn mrand48 void
.Ft long
.Fn jrand48 "unsigned short xseed[3]"
.Ft void
.Fn srand48 "long seed"
.Ft "unsigned short *"
.Fn seed48 "unsigned short xseed[3]"
.Ft void
.Fn lcong48 "unsigned short p[7]"
.Sh DESCRIPTION
The
.Fn rand48
family of functions generates pseudo-random numbers using a linear
congruential algorithm working on integers 48 bits in size.
The particular formula employed is
r(n+1) = (a * r(n) + c) mod m
where the default values are
for the multiplicand a = 0x5deece66d = 25214903917 and
the addend c = 0xb = 11.
The modulus is always fixed at m = 2 ** 48.
r(n) is called the seed of the random number generator.
.Pp
For all the six generator routines described next, the first
computational step is to perform a single iteration of the algorithm.
.Pp
.Fn drand48
and
.Fn erand48
return values of type double.
The full 48 bits of r(n+1) are loaded into the mantissa of the
returned value, with the exponent set such that the values produced
lie in the interval [0.0, 1.0).
.Pp
.Fn lrand48
and
.Fn nrand48
return values of type long in the range [0, 2**31-1].
The high-order (31) bits of r(n+1) are loaded into the lower bits
of the returned value, with the topmost (sign) bit set to zero.
.Pp
.Fn mrand48
and
.Fn jrand48
return values of type long in the range [-2**31, 2**31-1].
The high-order (32) bits of r(n+1) are loaded into the returned value.
.Pp
.Fn drand48 ,
.Fn lrand48 ,
and
.Fn mrand48
use an internal buffer to store r(n).
For these functions
the initial value of r(0) = 0x1234abcd330e = 20017429951246.
.Pp
On the other hand,
.Fn erand48 ,
.Fn nrand48 ,
and
.Fn jrand48
use a user-supplied buffer to store the seed r(n), which consists
of an array of 3 shorts, where the zeroth member holds the least
significant bits.
.Pp
All functions share the same multiplicand and addend.
.Pp
.Fn srand48
is used to initialize the internal buffer r(n) of
.Fn drand48 ,
.Fn lrand48 ,
and
.Fn mrand48
such that the 32 bits of the seed value are copied into the upper 32 bits
of r(n), with the lower 16 bits of r(n) arbitrarily being set to 0x330e.
Additionally, the constant multiplicand and addend of the algorithm are
reset to the default values given above.
.Pp
.Fn seed48
also initializes the internal buffer r(n) of
.Fn drand48 ,
.Fn lrand48 ,
and
.Fn mrand48 ,
but here all 48 bits of the seed can be specified in an array of 3 shorts,
where the zeroth member specifies the lowest bits.
Again, the constant multiplicand and addend of the algorithm are
reset to the default values given above.
.Fn seed48
returns a pointer to an array of 3 shorts which contains the old seed.
This array is statically allocated, thus its contents are lost after
each new call to
.Fn seed48 .
.Pp
Finally,
.Fn lcong48
allows full control over the multiplicand and addend used in
.Fn drand48 ,
.Fn erand48 ,
.Fn lrand48 ,
.Fn nrand48 ,
.Fn mrand48 ,
and
.Fn jrand48 ,
and the seed used in
.Fn drand48 ,
.Fn lrand48 ,
and
.Fn mrand48 .
An array of 7 shorts is passed as parameter; the first three shorts are
used to initialize the seed; the second three are used to initialize the
multiplicand; and the last short is used to initialize the addend.
It is thus not possible to use values greater than 0xffff as the addend.
.Pp
Note that all three methods of seeding the random number generator
always also set the multiplicand and addend for any of the six
generator calls.
.Pp
For a more powerful random number generator, see
.Xr random 3 .
.Sh SEE ALSO
.Xr rand 3 ,
.Xr random 3
.Sh AUTHORS
Martin Birgmeier

View File

@@ -0,0 +1,34 @@
/* $NetBSD: rand48.h,v 1.5 2006/03/22 20:52:16 drochner Exp $ */
/*
* Copyright (c) 1993 Martin Birgmeier
* All rights reserved.
*
* You may redistribute unmodified or modified versions of this source
* code provided that the above copyright notice and this and the
* following conditions are retained.
*
* This software is provided ``as is'', and comes with no warranties
* of any kind. I shall in no event be liable for anything that happens
* to anyone/anything when using this software.
*/
#ifndef _RAND48_H_
#define _RAND48_H_
#include <stdlib.h>
extern void __dorand48 __P((unsigned short[3]));
extern unsigned short __rand48_seed[3];
extern unsigned short __rand48_mult[3];
extern unsigned short __rand48_add;
#define RAND48_SEED_0 (0x330e)
#define RAND48_SEED_1 (0xabcd)
#define RAND48_SEED_2 (0x1234)
#define RAND48_MULT_0 (0xe66d)
#define RAND48_MULT_1 (0xdeec)
#define RAND48_MULT_2 (0x0005)
#define RAND48_ADD (0x000b)
#endif /* _RAND48_H_ */

View File

@@ -0,0 +1,52 @@
/* $NetBSD: rand_r.c,v 1.5 2003/08/07 16:43:43 agc Exp $ */
/*-
* Copyright (c) 1990 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. 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.
*/
#include <sys/cdefs.h>
#if defined(LIBC_SCCS) && !defined(lint)
#if 0
static char *sccsid = "from: @(#)rand.c 5.6 (Berkeley) 6/24/91";
#else
__RCSID("$NetBSD: rand_r.c,v 1.5 2003/08/07 16:43:43 agc Exp $");
#endif
#endif /* LIBC_SCCS and not lint */
#include <assert.h>
#include <errno.h>
#include <stdlib.h>
int
rand_r(seed)
unsigned int *seed;
{
_DIAGASSERT(seed != NULL);
return ((*seed = *seed * 1103515245 + 12345) & RAND_MAX);
}

View File

@@ -0,0 +1,182 @@
.\" $NetBSD: random.3,v 1.19 2008/02/28 16:16:35 christos Exp $
.\"
.\" 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. 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.
.\"
.\" from: @(#)random.3 8.1 (Berkeley) 6/4/93
.\"
.Dd February 28, 2008
.Dt RANDOM 3
.Os
.Sh NAME
.Nm random ,
.Nm srandom ,
.Nm initstate ,
.Nm setstate
.Nd better random number generator; routines for changing generators
.Sh LIBRARY
.Lb libc
.Sh SYNOPSIS
.In stdlib.h
.Ft long
.Fn random void
.Ft void
.Fn srandom "unsigned long seed"
.Ft char *
.Fn initstate "unsigned long seed" "char *state" "size_t n"
.Ft char *
.Fn setstate "char *state"
.Sh DESCRIPTION
The
.Fn random
function
uses a non-linear additive feedback random number generator employing a
default table of size 31 long integers to return successive pseudo-random
numbers in the range from 0 to
.if t 2\u\s731\s10\d\(mi1.
.if n (2**31)\(mi1.
The period of this random number generator is very large, approximately
.if t 16\(mu(2\u\s731\s10\d\(mi1).
.if n 16*((2**31)\(mi1).
The maximum value
.Dv RANDOM_MAX
is defined in
.In stdlib.h .
.Pp
The
.Fn random
and
.Fn srandom
have (almost) the same calling sequence and initialization properties as
.Xr rand 3
and
.Xr srand 3 .
The difference is that
.Xr rand 3
produces a much less random sequence \(em in fact, the low dozen bits
generated by
.Xr rand 3
go through a cyclic pattern.
All the bits generated by
.Fn random
are usable.
For example,
.Sq Li random()\*[Am]01
will produce a random binary value.
.Pp
Like
.Xr rand 3 ,
.Fn random
will by default produce a sequence of numbers that can be duplicated
by calling
.Fn srandom
with
.Ql 1
as the seed.
.Pp
The
.Fn initstate
routine allows a state array, passed in as an argument, to be initialized
for future use.
The size of the state array (in bytes) is used by
.Fn initstate
to decide how sophisticated a random number generator it should use \(em the
more state, the better the random numbers will be.
(Current "optimal" values for the amount of state information are
8, 32, 64, 128, and 256 bytes; other amounts will be rounded down to
the nearest known amount.
Using less than 8 bytes will cause an error).
The seed for the initialization (which specifies a starting point for
the random number sequence, and provides for restarting at the same
point) is also an argument.
The state array passed to
.Fn initstate
must be aligned to a 32-bit boundary.
This can be achieved by using
a suitably-sized array of ints, and casting the array to char * when
passing it to
.Fn initstate .
The
.Fn initstate
function
returns a pointer to the previous state information array.
.Pp
Once a state has been initialized, the
.Fn setstate
routine provides for rapid switching between states.
The
.Fn setstate
function
returns a pointer to the previous state array; its
argument state array is used for further random number generation
until the next call to
.Fn initstate
or
.Fn setstate .
.Pp
Once a state array has been initialized, it may be restarted at a
different point either by calling
.Fn initstate
(with the desired seed, the state array, and its size) or by calling
both
.Fn setstate
(with the state array) and
.Fn srandom
(with the desired seed).
The advantage of calling both
.Fn setstate
and
.Fn srandom
is that the size of the state array does not have to be remembered after
it is initialized.
.Pp
With 256 bytes of state information, the period of the random number
generator is greater than
.if t 2\u\s769\s10\d,
.if n 2**69
which should be sufficient for most purposes.
.Sh DIAGNOSTICS
If
.Fn initstate
is called with less than 8 bytes of state information, or if
.Fn setstate
detects that the state information has been garbled, error
messages are printed on the standard error output.
.Sh SEE ALSO
.Xr rand 3 ,
.Xr srand 3 ,
.Xr rnd 4 ,
.Xr rnd 9
.Sh HISTORY
These
functions appeared in
.Bx 4.2 .
.Sh AUTHORS
.An Earl T. Cohen
.Sh BUGS
About 2/3 the speed of
.Xr rand 3 .

View File

@@ -0,0 +1,54 @@
/*
* Copyright (c) 1993 John Brezak
* 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. The name of the author may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR `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 AUTHOR 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.
*/
#include <sys/cdefs.h>
#if defined(LIBC_SCCS) && !defined(lint)
__RCSID("$NetBSD: remque.c,v 1.2 2005/07/06 17:17:15 drochner Exp $");
#endif /* LIBC_SCCS and not lint */
#include <assert.h>
#include <search.h>
struct qelem {
struct qelem *q_forw;
struct qelem *q_back;
};
void
remque(element)
void *element;
{
struct qelem *e = (struct qelem *) element;
_DIAGASSERT(e != 0);
if (e->q_forw)
e->q_forw->q_back = e->q_back;
if (e->q_back)
e->q_back->q_forw = e->q_forw;
}

View File

@@ -0,0 +1,49 @@
/* $NetBSD: seed48.c,v 1.8 2005/06/12 05:21:28 lukem Exp $ */
/*
* Copyright (c) 1993 Martin Birgmeier
* All rights reserved.
*
* You may redistribute unmodified or modified versions of this source
* code provided that the above copyright notice and this and the
* following conditions are retained.
*
* This software is provided ``as is'', and comes with no warranties
* of any kind. I shall in no event be liable for anything that happens
* to anyone/anything when using this software.
*/
#include <sys/cdefs.h>
#if defined(LIBC_SCCS) && !defined(lint)
__RCSID("$NetBSD: seed48.c,v 1.8 2005/06/12 05:21:28 lukem Exp $");
#endif /* LIBC_SCCS and not lint */
#include "namespace.h"
#include <assert.h>
#include "rand48.h"
#ifdef __weak_alias
__weak_alias(seed48,_seed48)
#endif
unsigned short *
seed48(unsigned short xseed[3])
{
static unsigned short sseed[3];
_DIAGASSERT(xseed != NULL);
sseed[0] = __rand48_seed[0];
sseed[1] = __rand48_seed[1];
sseed[2] = __rand48_seed[2];
__rand48_seed[0] = xseed[0];
__rand48_seed[1] = xseed[1];
__rand48_seed[2] = xseed[2];
__rand48_mult[0] = RAND48_MULT_0;
__rand48_mult[1] = RAND48_MULT_1;
__rand48_mult[2] = RAND48_MULT_2;
__rand48_add = RAND48_ADD;
return sseed;
}

Some files were not shown because too many files have changed in this diff Show More