diff --git a/.gitignore b/.gitignore index 3b37c71..c9ffe48 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ /Default/ t t.c +*.o diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..cc37119 --- /dev/null +++ b/Makefile @@ -0,0 +1,19 @@ +# The System Makefile (C) 2002, 2017 The UbixOS Project + +.if ${.MAKEFLAGS:M${.CURDIR}/share/mk} == "" +.MAKEFLAGS: -m ${.CURDIR}/share/mk +.endif + +.include + +_SUBDIR=lib bin sys + +.for dir in ${_SUBDIR} +.if (${BUILD_${dir}:Uyes} != "no" && exists(${dir}/Makefile)) +SUBDIR+= ${dir} +.endif +.endfor + +.include +.include +.include diff --git a/Makefile.incl b/Makefile.incl new file mode 100644 index 0000000..f0a9e86 --- /dev/null +++ b/Makefile.incl @@ -0,0 +1,19 @@ +# $Id: Makefile.inc 89 2016-01-12 00:20:40Z reddawg $ +# Global 'Source' Options + +# allow you to change your default compiler without affecting your other work +#MrOlsen (2016-01-10) NOTE: I pass all this now +#CFLAGS = -m32 +#CC = cc +#CXX = c++ +#LD = ld +#AR = ar + +#Glogal Override And Defs +_ARCH?=${MACHINE_ARCH} + +_ARCH=i386 + +REMOVE = rm -rf + +#FD_DEVICE = /dev/md0 diff --git a/bin/Makefile.incl b/bin/Makefile.incl new file mode 100644 index 0000000..2d0ca5d --- /dev/null +++ b/bin/Makefile.incl @@ -0,0 +1,11 @@ +# 'bin' options + +CFLAGS = -m32 -nostdlib -nostdinc -fno-builtin + +INCLUDES = -I../../include + +#LIBRARIES = ../../lib/libc_old/math/*.o ../../lib/libc_old/quad/*.o ../../lib/libc_old/stdio/*.o ../../lib/libc_old/stdlib/*.o ../../lib/libc_old/sys/*.o ../../lib/libc_old/string/*.o ../../lib/libc_old/locale/*.o ../../lib/libc_old/gen/*.o ../../lib/libc_old/generic/*.o ../../lib/libc_old/*/*.o + +LIBRARIES = ../../lib/libc_old/*/*.o + +STARTUP = ../../lib/ubix/*.o diff --git a/bin/Makefile.old b/bin/Makefile.old new file mode 100644 index 0000000..a123b29 --- /dev/null +++ b/bin/Makefile.old @@ -0,0 +1,95 @@ +# $Id: Makefile 121 2016-01-14 03:18:20Z reddawg $ +# The System Makefile (C) 2002 The UbixOS Project + +all: init-bin login-bin shell-bin clock-bin cp-bin fdisk-bin format-bin disklabel-bin ubistry-bin ld-bin ttyd-bin stat-bin ls-bin #rtld-elf-bin +# MrOlsen (2016-01-11) ERROR: weird it didnt like -elf rtld-elf-bin +# MrOlsen (2016-01-11) NOTE: edit-bin cat-bin +# test-bin pwd-bin cat-bin de-bin ls-bin goofball-bin mount-bin + +init-bin: init + (cd init;make) + +login-bin: login + (cd login;make) + +shell-bin: shell + (cd shell;make) + +test-bin: test + (cd test;make) + +ls-bin: ls + (cd ls;make) + +pwd-bin: pwd + (cd pwd;make) + +cat-bin: cat + (cd cat;make) + +ld-bin: ld + (cd ld;make) + +de-bin: de + (cd de;make) + +muffin-bin: muffin + (cd muffin;make) + +goofball-bin: goofball + (cd goofball;make) + +clock-bin: clock + (cd clock;make) + +fdisk-bin: fdisk + (cd fdisk;make) + +cp-bin: cp + (cd cp;make) + +format-bin: format + (cd format;make) + +disklabel-bin: disklabel + (cd disklabel;make) + +launcher-bin: launcher + (cd launcher;make) + +ubistry-bin: ubistry + (cd ubistry;make) + +edit-bin: edit + (cd edit;make) + +ttyd-bin: ttyd + (cd ttyd;make) + +stat-bin: stat + (cd stat;make) + +mount-bin: mount + (cd mount;make) + +rtld-elf-bin: rtld-elf + (cd rtld-elf;make) + +clean: + (cd cp;make clean) + (cd fdisk;make clean) + (cd init;make clean) + (cd shell;make clean) + (cd ls;make clean) + (cd login;make clean) + (cd clock;make clean) + (cd muffin;make clean) + (cd format;make clean) + (cd disklabel;make clean) + (cd ubistry;make clean) + (cd ld;make clean) + (cd edit;make clean) + (cd ttyd;make clean) + (cd stat;make clean) + (cd mount;make clean) + (cd rtld-elf;make clean) diff --git a/bin/clock/Makefile b/bin/clock/Makefile new file mode 100644 index 0000000..3f7b34d --- /dev/null +++ b/bin/clock/Makefile @@ -0,0 +1,48 @@ +# $Id: Makefile 129 2016-01-14 14:16:33Z reddawg $ +# Application Makefile (C) 2002-2004 The UbixOS Project + +# Include Global 'Source' Options +include ../../Makefile.incl +include ../Makefile.incl + +#Linker +LD = ld + +#Binary File Name +BINARY = clock + +#Delete Program +REMOVE = rm -f + +#Objects +OBJS = main.o + +LIBRARIES = ../../build/lib/libc_old.so + +# Link The Binary +$(BINARY) : $(OBJS) + $(CC) $(CFLAGS) -o $(BUILD_DIR)/bin/$@ $(STARTUP) $(LIBRARIES) $(OBJS) +# strip $(BINARY) + +# Compile the source files +.cpp.o: + $(CXX) -Wall -O $(CFLAGS) $(INCLUDES) -c -o $@ $< + +.cc.o: + $(CXX) -Wall -O $(CFLAGS) $(INCLUDES) -c -o $@ $< + +.cc.s: + $(CXX) -Wall -O $(CFLAGS) $(INCLUDES) -S -o $@ $< + +.c.o: + $(CC) -Wall -O $(CFLAGS) $(INCLUDES) -c -o $@ $< + +.c.s: + $(CC) -Wall -O $(CFLAGS) $(INCLUDES) -S -o $@ $< + +.S.o: + $(CC) -Wall $(CLFAGS) $(INCLUDES) -c -o $@ $< + +# Clean Up The junk +clean: + $(REMOVE) $(OBJS) $(BUILD_DIR)/bin/$(BINARY) diff --git a/bin/clock/main.c b/bin/clock/main.c new file mode 100644 index 0000000..397c3a4 --- /dev/null +++ b/bin/clock/main.c @@ -0,0 +1,101 @@ +/***************************************************************************************** + Copyright (c) 2002-2004 The UbixOS Project + All rights reserved. + + Redistribution and use in source and binary forms, with or without modification, are + permitted provided that the following conditions are met: + + Redistributions of source code must retain the above copyright notice, this list of + conditions, the following disclaimer and the list of authors. Redistributions in binary + form must reproduce the above copyright notice, this list of conditions, the following + disclaimer and the list of authors in the documentation and/or other materials provided + with the distribution. Neither the name of the UbixOS Project 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 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 OWNER 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. + + $Id: main.c 89 2016-01-12 00:20:40Z reddawg $ + +*****************************************************************************************/ + +#include +#include +#include +#include + +void print2(char *string,int,int); + +#define MINUTE 60 +#define HOUR (60*MINUTE) +#define DAY (24*HOUR) +#define YEAR (365*DAY) +extern const char *__progname; + + +static int monthSecs[12] = { + 0, + DAY*(31), + DAY*(31+29), + DAY*(31+29+31), + DAY*(31+29+31+30), + DAY*(31+29+31+30+31), + DAY*(31+29+31+30+31+30), + DAY*(31+29+31+30+31+30+31), + DAY*(31+29+31+30+31+30+31+31), + DAY*(31+29+31+30+31+30+31+31+30), + DAY*(31+29+31+30+31+30+31+31+30+31), + DAY*(31+29+31+30+31+30+31+31+30+31+30) +}; + +int main(int argc,char **argv) { + int sysTime = 0x0; + int i = 0x0; + + int year = 0x0; + int month = 0x0; + int day = 0x0; + int hour = 0x0; + int min = 0x0; + int sec = 0x0; + + sysTime = gettime(); + + year = (sysTime/YEAR) + 1970; + sysTime -= (YEAR * (year-1970)); + sysTime -= DAY*(((year-1970)+1)/4); + for (i = 11;i >= 0;i--) { + if ((sysTime - monthSecs[i]) > 0) { + month = i; + break; + } + } + sysTime -= monthSecs[i]; + if (((month > 1) && (((year-1970)+2)%4)) == 0x0) { + sysTime += DAY; + } + + day = (sysTime/DAY); + sysTime -= (day*DAY); + hour = (sysTime/HOUR); + sysTime -= (hour*HOUR); + min = (sysTime/MINUTE); + sysTime -= (min*MINUTE); + sec = sysTime; + + printf("[%s][%02d/%02d/%i, %02d:%02d.%02d]\n",argv[0],month,day,year,hour,min,sec); + return(0); + } + +/*** + END + ***/ + diff --git a/bin/cp/Makefile b/bin/cp/Makefile new file mode 100644 index 0000000..e1d1ea1 --- /dev/null +++ b/bin/cp/Makefile @@ -0,0 +1,45 @@ +# $Id: Makefile 129 2016-01-14 14:16:33Z reddawg $ +# Application Makefile (C) 2002-2004 The UbixOS Project + +# Include Global 'Source' Options +include ../../Makefile.incl +include ../Makefile.incl + +#Linker +LD = ld + +#Binary File Name +BINARY = cp + +#Delete Program +REMOVE = rm -f + +#Objects +OBJS = main.o + +LIBRARIES = ../../build/lib/libc_old.so + +# Link The Binary +$(BINARY) : $(OBJS) + $(CC) $(CFLAGS) -o $(BUILD_DIR)/bin/$@ $(STARTUP) $(LIBRARIES) $(OBJS) + strip ${BUILD_DIR}/bin/$(BINARY) + +# Compile the source files +.cc.o: + $(CXX) -Wall -O $(CFLAGS) $(INCLUDES) -c -o $@ $< + +.cc.s: + $(CXX) -Wall -O $(CFLAGS) $(INCLUDES) -S -o $@ $< + +.c.o: + $(CC) -Wall -O $(CFLAGS) $(INCLUDES) -c -o $@ $< + +.c.s: + $(CC) -Wall -O $(CFLAGS) $(INCLUDES) -S -o $@ $< + +.S.o: + $(CC) -Wall $(CLFAGS) $(INCLUDES) -c -o $@ $< + +# Clean Up The junk +clean: + $(REMOVE) $(OBJS) $(BUILD_DIR)/bin/$(BINARY) diff --git a/bin/cp/main.c b/bin/cp/main.c new file mode 100644 index 0000000..e45c71c --- /dev/null +++ b/bin/cp/main.c @@ -0,0 +1,68 @@ +/***************************************************************************************** + Copyright (c) 2002-2004 The UbixOS Project + All rights reserved. + + Redistribution and use in source and binary forms, with or without modification, are + permitted provided that the following conditions are met: + + Redistributions of source code must retain the above copyright notice, this list of + conditions, the following disclaimer and the list of authors. Redistributions in binary + form must reproduce the above copyright notice, this list of conditions, the following + disclaimer and the list of authors in the documentation and/or other materials provided + with the distribution. Neither the name of the UbixOS Project 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 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 OWNER 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. + + $Id: main.c 89 2016-01-12 00:20:40Z reddawg $ + +*****************************************************************************************/ + +#include +#include + +int main(int argc,char **argv) { + int i = 0x0; + char *buffer = (char *)malloc(0x2000); + FILE *in = 0x0; + FILE *out = 0x0; + in = fopen(argv[1],"rb"); + out = fopen(argv[2],"wb"); + /* + while (!feof(in)) { + */ + for (i=0;i<21;i++) { + fread(buffer,0x1000,1,in); + fwrite(buffer,0x1000,1,out); + } + fclose(in); + fclose(out); + return(0x0); + } + +/*** + $Log: main.c,v $ + Revision 1.1.1.1 2006/06/01 12:46:09 reddawg + ubix2 + + Revision 1.2 2005/10/12 00:13:28 reddawg + Removed + + Revision 1.1.1.1 2005/09/26 17:13:57 reddawg + no message + + Revision 1.3 2004/05/24 13:40:35 reddawg + Clean Up + + + END + ***/ diff --git a/bin/disklabel/Makefile b/bin/disklabel/Makefile new file mode 100644 index 0000000..26003be --- /dev/null +++ b/bin/disklabel/Makefile @@ -0,0 +1,45 @@ +# $Id: Makefile 129 2016-01-14 14:16:33Z reddawg $ +# Application Makefile (C) 2002-2004 The UbixOS Project + +# Include Global 'Source' Options +include ../../Makefile.incl +include ../Makefile.incl + +#Linker +LD = ld + +#Binary File Name +BINARY = disklabel + +#Delete Program +REMOVE = rm -f + +#Objects +OBJS = main.o + +LIBRARIES = ../../build/lib/libc_old.so + +# Link The Binary +$(BINARY) : $(OBJS) + $(CC) $(CFLAGS) -o $(BUILD_DIR)/bin/$@ $(STARTUP) $(LIBRARIES) $(OBJS) + strip ${BUILD_DIR}/bin/$(BINARY) + +# Compile the source files +.cc.o: + $(CXX) -Wall -O $(CFLAGS) $(INCLUDES) -c -o $@ $< + +.cc.s: + $(CXX) -Wall -O $(CFLAGS) $(INCLUDES) -S -o $@ $< + +.c.o: + $(CC) -Wall -O $(CFLAGS) $(INCLUDES) -c -o $@ $< + +.c.s: + $(CC) -Wall -O $(CFLAGS) $(INCLUDES) -S -o $@ $< + +.S.o: + $(CC) -Wall $(CLFAGS) $(INCLUDES) -c -o $@ $< + +# Clean Up The junk +clean: + $(REMOVE) $(OBJS) $(BUILD_DIR)/bin/$(BINARY) diff --git a/bin/disklabel/main.c b/bin/disklabel/main.c new file mode 100644 index 0000000..bdbf664 --- /dev/null +++ b/bin/disklabel/main.c @@ -0,0 +1,120 @@ +/***************************************************************************************** + Copyright (c) 2002-2004 The UbixOS Project + All rights reserved. + + Redistribution and use in source and binary forms, with or without modification, are + permitted provided that the following conditions are met: + + Redistributions of source code must retain the above copyright notice, this list of + conditions, the following disclaimer and the list of authors. Redistributions in binary + form must reproduce the above copyright notice, this list of conditions, the following + disclaimer and the list of authors in the documentation and/or other materials provided + with the distribution. Neither the name of the UbixOS Project 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 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 OWNER 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. + + $Id: main.c 89 2016-01-12 00:20:40Z reddawg $ + +*****************************************************************************************/ + +#include +#include +#include +#include +#include + +#include "ubixfs.h" + + +int main(int argc,char **argv) { + FILE *fd; + struct ubixDiskLabel *d = (struct ubixDiskLabel *)malloc(512); + int i = 0x0; + char buf[256]; + + printf("Ubix Disk Label Editor Version 1.0\n"); + printf("(c) 2004 Ubix Corp \n\n"); + + if (argc >= 2) { + printf("Drive Info (%s):\n",argv[1]); + fd = fopen(argv[1],"rb"); + } + else { + printf("Drive Info (hd0):\n"); + fd = fopen("hd0@devfs","rb"); + } + fseek(fd,512,0); + fread(d,512,1,fd); + + if (argc >= 3) { + i = atoi(argv[2]); + printf("d->partitions[%i].p_size = %i, ",i,d->partitions[i].p_size); + printf("New Value: "); + gets((char *)&buf); + d->partitions[i].p_size = atoi(buf); + printf("d->partitions[%i].p_offset = %i, ",i,d->partitions[i].p_offset); + printf("New Value: "); + gets((char *)&buf); + d->partitions[i].p_offset = atoi(buf); + printf("d->partitions[%i].p_fstype = %i, ",i,d->partitions[i].p_fstype); + printf("New Value: "); + gets((char *)&buf); + d->partitions[i].p_fstype = atoi(buf); + printf("d->partitions[%i].p_bsize = %i, ",i,d->partitions[i].p_bsize); + printf("New Value: "); + gets((char *)&buf); + d->partitions[i].p_bsize = atoi(buf); + printf("\n"); + printf("d->partitions[%i].p_size = %i\n",i,d->partitions[i].p_size); + printf("d->partitions[%i].p_offset = %i\n",i,d->partitions[i].p_offset); + printf("d->partitions[%i].p_fstype = %i\n",i,d->partitions[i].p_fstype); + printf("d->partitions[%i].p_bsize = %i\n",i,d->partitions[i].p_bsize); + fseek(fd,512,0); + fwrite(d,512,1,fd); + } + else { + for (i=0;i<4;i++) { + if (d->partitions[i].p_fstype != 0x0) { + printf("d->partitions[%i].p_size = %i\n",i,d->partitions[i].p_size); + printf("d->partitions[%i].p_offset = %i\n",i,d->partitions[i].p_offset); + printf("d->partitions[%i].p_fstype = 0x%X\n",i,d->partitions[i].p_fstype); + printf("d->partitions[%i].p_bsize = 0x%X\n",i,d->partitions[i].p_bsize); + } + } + } + + fclose(fd); + + return(0); + } + +/*** + $Log: main.c,v $ + Revision 1.1.1.1 2006/06/01 12:46:09 reddawg + ubix2 + + Revision 1.2 2005/10/12 00:13:28 reddawg + Removed + + Revision 1.1.1.1 2005/09/26 17:13:58 reddawg + no message + + Revision 1.3 2004/06/01 01:30:43 reddawg + No more warnings and organized make files + + Revision 1.2 2004/05/24 13:42:29 reddawg + Clean Up + + + END + ***/ diff --git a/bin/disklabel/ubixfs.h b/bin/disklabel/ubixfs.h new file mode 100644 index 0000000..42662cf --- /dev/null +++ b/bin/disklabel/ubixfs.h @@ -0,0 +1,92 @@ +/***************************************************************************************** + Copyright (c) 2002-2004 The UbixOS Project + All rights reserved. + + Redistribution and use in source and binary forms, with or without modification, are + permitted provided that the following conditions are met: + + Redistributions of source code must retain the above copyright notice, this list of + conditions, the following disclaimer and the list of authors. Redistributions in binary + form must reproduce the above copyright notice, this list of conditions, the following + disclaimer and the list of authors in the documentation and/or other materials provided + with the distribution. Neither the name of the UbixOS Project 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 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 OWNER 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. + + $Id: ubixfs.h 89 2016-01-12 00:20:40Z reddawg $ + +*****************************************************************************************/ + +#include + +#define DOSPTYP_UBX 0x2A /* UbixFS partition type */ +#define UBIXDISKMAGIC ((uInt32)0x45) /* The disk magic number */ +#define MAXUBIXPARTITIONS 16 +#define UBIXFSMAGIC ((uInt32)0x69) /* The File System Magic Number */ + +struct ubixDiskLabel { + uInt32 magicNum; + uInt32 magicNum2; + uInt16 driveType; + uInt16 numPartitions; + struct ubixPartitions { /* the partition table */ + uInt32 p_size; /* number of sectors in partition */ + uInt32 p_offset; /* starting sector */ + uInt32 p_fsize; /* filesystem basic fragment size */ + uInt32 p_bsize; /* BAT size */ + uInt8 p_fstype; /* filesystem type, see below */ + uInt8 p_frag; /* filesystem fragments per block */ + } partitions[MAXUBIXPARTITIONS]; + }; + +//Block Allocation Table Entry +struct blockAllocationTableEntry { + long attributes; //Block Attributes + long realSector; //Real Sector + long nextBlock; //Sector Of Next Block + long reserved; //Reserved + }; + + +struct directoryEntry { + uInt32 startCluster; //Starting Cluster Of File + uInt32 size; //Size Of File + uInt32 creationDate; //Date Created + uInt32 lastModified; //Date Last Modified + uInt32 uid; //UID Of Owner + uInt32 gid; //GID Of Owner + uInt16 attributes; //Files Attributes + uInt16 permissions; //Files Permissions + char fileName[256]; //File Name + }; + +/*** + $Log: ubixfs.h,v $ + Revision 1.2 2006/10/26 23:52:26 reddawg + Fixens + + Revision 1.1.1.1 2006/06/01 12:46:09 reddawg + ubix2 + + Revision 1.2 2005/10/12 00:13:28 reddawg + Removed + + Revision 1.1.1.1 2005/09/26 17:13:59 reddawg + no message + + Revision 1.2 2004/05/24 13:54:52 reddawg + Clean Up + + + END + ***/ diff --git a/bin/edit/Makefile b/bin/edit/Makefile new file mode 100644 index 0000000..44505b1 --- /dev/null +++ b/bin/edit/Makefile @@ -0,0 +1,49 @@ +# $Id: Makefile 115 2016-01-14 02:55:19Z reddawg $ +# Application Makefile (C) 2002-2004 The UbixOS Project + +# Include Global 'Source' Options +include ../../Makefile.incl +include ../Makefile.incl + +#Linker +LD = ld + +#Binary File Name +BINARY = edit + +#Delete Program +REMOVE = rm -f + +#Objects +OBJS = main.o + +INCLUDES = -I../../include.new + +LIBRARIES = ../../lib/libc/libc.so + +STARTUP = ../../lib/csu/*.o + +# Link The Binary +$(BINARY) : $(OBJS) + $(CC) $(CFLAGS) -o $(BUILD_DIR)/bin/$@ $(STARTUP) $(LIBRARIES) $(OBJS) + #strip $(BINARY) + +# Compile the source files +.cc.o: + $(CXX) -Wall -O $(CFLAGS) $(INCLUDES) -c -o $@ $< + +.cc.s: + $(CXX) -Wall -O $(CFLAGS) $(INCLUDES) -S -o $@ $< + +.c.o: + $(CC) -Wall -O $(CFLAGS) $(INCLUDES) -c -o $@ $< + +.c.s: + $(CC) -Wall -O $(CFLAGS) $(INCLUDES) -S -o $@ $< + +.S.o: + $(CC) -Wall $(CLFAGS) $(INCLUDES) -c -o $@ $< + +# Clean Up The junk +clean: + $(REMOVE) $(OBJS) $(BUILD_DIR)/bin/$(BINARY) diff --git a/bin/edit/main.c b/bin/edit/main.c new file mode 100644 index 0000000..558afa2 --- /dev/null +++ b/bin/edit/main.c @@ -0,0 +1,60 @@ +/***************************************************************************************** + Copyright (c) 2002-2004 The UbixOS Project + All rights reserved. + + Redistribution and use in source and binary forms, with or without modification, are + permitted provided that the following conditions are met: + + Redistributions of source code must retain the above copyright notice, this list of + conditions, the following disclaimer and the list of authors. Redistributions in binary + form must reproduce the above copyright notice, this list of conditions, the following + disclaimer and the list of authors in the documentation and/or other materials provided + with the distribution. Neither the name of the UbixOS Project 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 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 OWNER 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. + + $Id: main.c 89 2016-01-12 00:20:40Z reddawg $ + +*****************************************************************************************/ + +#include +#include + +int main(int argc,char **argv) { + extern char *environ; + char in[1024]; + FILE *out; + size_t count = 0x0; + printf("UbixOS Text Editor\n"); + printf("V1.0\n"); + printf("ARGC: [%i]\n",argc); + printf("ARGV[0]: [%s]\n",argv[0]); + + out = fopen("/test.txt","r"); + + while (!feof(out)) { + printf("%c",fgetc(out)); + } + + //printf("[%S]",getenv("TEST")); + printf("\nENV TEST: [0x%X]\n",environ); + setenv("BLAH","WOOT",1); + printf("[%s]",getenv("BLAH")); + + return(0); + } + +/*** + END + ***/ + diff --git a/bin/fdisk/Makefile b/bin/fdisk/Makefile new file mode 100644 index 0000000..b125aae --- /dev/null +++ b/bin/fdisk/Makefile @@ -0,0 +1,45 @@ +# $Id: Makefile 129 2016-01-14 14:16:33Z reddawg $ +# Application Makefile (C) 2002-2004 The UbixOS Project + +# Include Global 'Source' Options +include ../../Makefile.incl +include ../Makefile.incl + +#Linker +LD = ld + +#Binary File Name +BINARY = fdisk + +#Delete Program +REMOVE = rm -f + +#Objects +OBJS = main.o + +LIBRARIES = ../../build/lib/libc_old.so + +# Link The Binary +$(BINARY) : $(OBJS) + $(CC) $(CFLAGS) -o $(BUILD_DIR)/bin/$@ $(STARTUP) $(LIBRARIES) $(OBJS) + strip ${BUILD_DIR}/bin/$(BINARY) + +# Compile the source files +.cc.o: + $(CXX) -Wall -O $(CFLAGS) $(INCLUDES) -c -o $@ $< + +.cc.s: + $(CXX) -Wall -O $(CFLAGS) $(INCLUDES) -S -o $@ $< + +.c.o: + $(CC) -Wall -O $(CFLAGS) $(INCLUDES) -c -o $@ $< + +.c.s: + $(CC) -Wall -O $(CFLAGS) $(INCLUDES) -S -o $@ $< + +.S.o: + $(CC) -Wall $(CLFAGS) $(INCLUDES) -c -o $@ $< + +# Clean Up The junk +clean: + $(REMOVE) $(OBJS) $(BUILD_DIR)/bin/$(BINARY) diff --git a/bin/fdisk/main.c b/bin/fdisk/main.c new file mode 100644 index 0000000..1648d30 --- /dev/null +++ b/bin/fdisk/main.c @@ -0,0 +1,151 @@ +/***************************************************************************************** + Copyright (c) 2002-2004 The UbixOS Project + All rights reserved. + + Redistribution and use in source and binary forms, with or without modification, are + permitted provided that the following conditions are met: + + Redistributions of source code must retain the above copyright notice, this list of + conditions, the following disclaimer and the list of authors. Redistributions in binary + form must reproduce the above copyright notice, this list of conditions, the following + disclaimer and the list of authors in the documentation and/or other materials provided + with the distribution. Neither the name of the UbixOS Project 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 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 OWNER 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. + + $Id: main.c 89 2016-01-12 00:20:40Z reddawg $ + +*****************************************************************************************/ + +#include +#include +#include +#include +#include + +#include "ubixfs.h" + +struct dos_partition { + unsigned char dp_flag; /* bootstrap flags */ + unsigned char dp_shd; /* starting head */ + unsigned char dp_ssect; /* starting sector */ + unsigned char dp_scyl; /* starting cylinder */ + unsigned char dp_type; /* partition type */ + unsigned char dp_ehd; /* end head */ + unsigned char dp_esect; /* end sector */ + unsigned char dp_ecyl; /* end cylinder */ + uInt32 dp_start; /* absolute starting sector number */ + uInt32 dp_size; /* partition size in sectors */ +}; + + +int main(int argc,char **argv) { + FILE *fd; + FILE *mbr; + struct dos_partition *d = 0x0; + char *data = (char *)malloc(512); + int i = 0x0; + char buf[256]; + + d = (struct dos_partition *)(data + 0x1BE); + + printf("Ubix Disk Editor Version 1.0\n"); + printf("(c) 2004 Ubix Corp \n\n"); + + if (argc >= 2) { + printf("Drive Info (%s):\n",argv[1]); + fd = fopen(argv[1],"rb"); + } + else { + printf("Drive Info (ad0):\n"); + fd = fopen("devfs:ad0","rb"); + } + if (fd->size == 0x0) { + printf("Invalid Device\n"); + exit(0x1); + } + + fseek(fd,0,0); + fread(data,512,1,fd); + + if (argc >= 3) { + i = atoi(argv[2]); + if (i == 0) { + mbr = fopen("sys:mrb","rb"); + fseek(mbr,0,0); + fread(data,512,1,mbr); + printf("Installing Ubix MBR\n"); + } + else { + i--; + printf("d[%i].dp_type = %i, ",i,d[i].dp_type); + printf("New Value: "); + gets((char *)&buf); + d[i].dp_type = atoi(buf); + printf("d[%i].dp_start: %i, ",i,d[i].dp_start); + printf("New Value: "); + gets((char *)&buf); + d[i].dp_start = atoi(buf); + printf("d[%i].dp_size: %i, ",i,d[i].dp_size); + printf("New Value: "); + gets((char *)&buf); + d[i].dp_size = atoi(buf); + printf("d[%i].dp_type: 0x%X\n",i,d[i].dp_type); + printf("d[%i].dp_start: %i\n",i,d[i].dp_start); + printf("d[%i].dp_size: %i\n",i,d[i].dp_size); + } + fseek(fd,0,0); + fwrite(data,512,1,fd); + } + else { + printf("Partition Table:\n"); + for (i=0;i<4;i++) { + if (d[i].dp_type != 0x0) { + printf("d[%i].dp_type: 0x%X\n",i,d[i].dp_type); + printf("d[%i].dp_start: %i\n",i,d[i].dp_start); + printf("d[%i].dp_size: %i\n",i,d[i].dp_size); + } + } + } + + fclose(fd); + + return(0); + } + +/*** + $Log: main.c,v $ + Revision 1.2 2006/10/12 15:00:26 reddawg + More changes + + Revision 1.1.1.1 2006/06/01 12:46:09 reddawg + ubix2 + + Revision 1.2 2005/10/12 00:13:28 reddawg + Removed + + Revision 1.1.1.1 2005/09/26 17:13:58 reddawg + no message + + Revision 1.9 2004/08/15 00:33:02 reddawg + Wow the ide driver works again + + Revision 1.8 2004/06/01 01:30:43 reddawg + No more warnings and organized make files + + Revision 1.7 2004/05/24 13:54:52 reddawg + Clean Up + + + END + ***/ diff --git a/bin/fdisk/ubixfs.h b/bin/fdisk/ubixfs.h new file mode 100644 index 0000000..42662cf --- /dev/null +++ b/bin/fdisk/ubixfs.h @@ -0,0 +1,92 @@ +/***************************************************************************************** + Copyright (c) 2002-2004 The UbixOS Project + All rights reserved. + + Redistribution and use in source and binary forms, with or without modification, are + permitted provided that the following conditions are met: + + Redistributions of source code must retain the above copyright notice, this list of + conditions, the following disclaimer and the list of authors. Redistributions in binary + form must reproduce the above copyright notice, this list of conditions, the following + disclaimer and the list of authors in the documentation and/or other materials provided + with the distribution. Neither the name of the UbixOS Project 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 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 OWNER 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. + + $Id: ubixfs.h 89 2016-01-12 00:20:40Z reddawg $ + +*****************************************************************************************/ + +#include + +#define DOSPTYP_UBX 0x2A /* UbixFS partition type */ +#define UBIXDISKMAGIC ((uInt32)0x45) /* The disk magic number */ +#define MAXUBIXPARTITIONS 16 +#define UBIXFSMAGIC ((uInt32)0x69) /* The File System Magic Number */ + +struct ubixDiskLabel { + uInt32 magicNum; + uInt32 magicNum2; + uInt16 driveType; + uInt16 numPartitions; + struct ubixPartitions { /* the partition table */ + uInt32 p_size; /* number of sectors in partition */ + uInt32 p_offset; /* starting sector */ + uInt32 p_fsize; /* filesystem basic fragment size */ + uInt32 p_bsize; /* BAT size */ + uInt8 p_fstype; /* filesystem type, see below */ + uInt8 p_frag; /* filesystem fragments per block */ + } partitions[MAXUBIXPARTITIONS]; + }; + +//Block Allocation Table Entry +struct blockAllocationTableEntry { + long attributes; //Block Attributes + long realSector; //Real Sector + long nextBlock; //Sector Of Next Block + long reserved; //Reserved + }; + + +struct directoryEntry { + uInt32 startCluster; //Starting Cluster Of File + uInt32 size; //Size Of File + uInt32 creationDate; //Date Created + uInt32 lastModified; //Date Last Modified + uInt32 uid; //UID Of Owner + uInt32 gid; //GID Of Owner + uInt16 attributes; //Files Attributes + uInt16 permissions; //Files Permissions + char fileName[256]; //File Name + }; + +/*** + $Log: ubixfs.h,v $ + Revision 1.2 2006/10/26 23:52:26 reddawg + Fixens + + Revision 1.1.1.1 2006/06/01 12:46:09 reddawg + ubix2 + + Revision 1.2 2005/10/12 00:13:28 reddawg + Removed + + Revision 1.1.1.1 2005/09/26 17:13:59 reddawg + no message + + Revision 1.2 2004/05/24 13:54:52 reddawg + Clean Up + + + END + ***/ diff --git a/bin/format/Makefile b/bin/format/Makefile new file mode 100644 index 0000000..418f569 --- /dev/null +++ b/bin/format/Makefile @@ -0,0 +1,45 @@ +# $Id: Makefile 121 2016-01-14 03:18:20Z reddawg $ +# Application Makefile (C) 2002-2004 The UbixOS Project + +# Include Global 'Source' Options +include ../../Makefile.incl +include ../Makefile.incl + +#Linker +LD = ld + +#Binary File Name +BINARY = format + +#Delete Program +REMOVE = rm -f + +#Objects +OBJS = main.o + +LIBRARIIES = ../../lib/libc/libc.so + +# Link The Binary +$(BINARY) : $(OBJS) + $(CC) $(CFLAGS) -o ${BUILD_DIR}/bin/$@ $(STARTUP) $(LIBRARIES) $(OBJS) + strip ${BUILD_DIR}/bin/$(BINARY) + +# Compile the source files +.cc.o: + $(CXX) -Wall -O $(CFLAGS) $(INCLUDES) -c -o $@ $< + +.cc.s: + $(CXX) -Wall -O $(CFLAGS) $(INCLUDES) -S -o $@ $< + +.c.o: + $(CC) -Wall -O $(CFLAGS) $(INCLUDES) -c -o $@ $< + +.c.s: + $(CC) -Wall -O $(CFLAGS) $(INCLUDES) -S -o $@ $< + +.S.o: + $(CC) -Wall $(CLFAGS) $(INCLUDES) -c -o $@ $< + +# Clean Up The junk +clean: + $(REMOVE) $(OBJS) ${BUILD_DIR}/bin/$(BINARY) diff --git a/bin/format/main.c b/bin/format/main.c new file mode 100644 index 0000000..5872c27 --- /dev/null +++ b/bin/format/main.c @@ -0,0 +1,61 @@ +/***************************************************************************************** + Copyright (c) 2002-2004 The UbixOS Project + All rights reserved. + + Redistribution and use in source and binary forms, with or without modification, are + permitted provided that the following conditions are met: + + Redistributions of source code must retain the above copyright notice, this list of + conditions, the following disclaimer and the list of authors. Redistributions in binary + form must reproduce the above copyright notice, this list of conditions, the following + disclaimer and the list of authors in the documentation and/or other materials provided + with the distribution. Neither the name of the UbixOS Project 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 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 OWNER 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. + + $Id: main.c 89 2016-01-12 00:20:40Z reddawg $ + +*****************************************************************************************/ + +#include +#include +#include +#include +#include + + +int main(int argc,char **argv) { + printf("UbixOS Format V1.0\n"); + return(0); + } + +/*** + $Log: main.c,v $ + Revision 1.1.1.1 2006/06/01 12:46:08 reddawg + ubix2 + + Revision 1.2 2005/10/12 00:13:28 reddawg + Removed + + Revision 1.1.1.1 2005/09/26 17:13:59 reddawg + no message + + Revision 1.4 2004/06/01 01:30:43 reddawg + No more warnings and organized make files + + Revision 1.3 2004/05/24 14:09:20 reddawg + Clean Up + + + END + ***/ diff --git a/bin/init/Makefile b/bin/init/Makefile new file mode 100644 index 0000000..e429432 --- /dev/null +++ b/bin/init/Makefile @@ -0,0 +1,2 @@ +PROG=cat +.include diff --git a/bin/init/main.c b/bin/init/main.c new file mode 100644 index 0000000..076da7a --- /dev/null +++ b/bin/init/main.c @@ -0,0 +1,124 @@ +/***************************************************************************************** + Copyright (c) 2002-2004 The UbixOS Project + All rights reserved. + + Redistribution and use in source and binary forms, with or without modification, are + permitted provided that the following conditions are met: + + Redistributions of source code must retain the above copyright notice, this list of + conditions, the following disclaimer and the list of authors. Redistributions in binary + form must reproduce the above copyright notice, this list of conditions, the following + disclaimer and the list of authors in the documentation and/or other materials provided + with the distribution. Neither the name of the UbixOS Project 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 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 OWNER 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. + + $Id: main.c 158 2016-01-19 02:08:13Z reddawg $ + +*****************************************************************************************/ + +#include +#include +#include +#include +#include +#include + +int main(int argc,char **argv) { + int i=0x0; + mpi_message_t myMsg; + + + + /* Create a mailbox for this task */ + /* + if (mpi_createMbox("init") != 0x0) { + printf("Error: Failed to creating mail box: init\n"); + exit(0x1); + } + */ + + /* Make sure we have superuser permissions if not exit */ + if ((getuid() != 0x0) || (getgid() != 0x0)) { + printf("Error: This program must be run by root.\n"); + exit(0x1); + } + + printf("Initializing UbixOS\n"); + + + /* Start TTYD */ +/* + i = fork(); + + + if (0x0 == i) { + printf("Error: Could not start TTYD\n"); + execve("sys:/bin/ttyd",0x0,0x0); + printf("Error: Could not start TTYD\n"); + exit(0x0); + } +*/ + + +/* + i = fork(); + if (0x0 == i) { + printf("Starting Ubix Registry (ubistry)\n"); + exec("sys:/ubistry",0x0); + printf("Error: Error Starting ubistry\n"); + exit(0x0); + } + + while (pidStatus(i) > 0x0) { + sched_yield(); + } +*/ + startup: + i = fork(); + + if (0 == i) { + printf("Starting Login Daemon.\n"); + execve("sys:/bin/login",0x0,0x0); + printf("Error Starting System\n"); + exit(0x0); + } + + while (pidStatus(i) > 0x0) { + /* + fetchAgain: + if (mpi_fetchMessage("init",&myMsg) == 0x0) { + switch (myMsg.header) { + case 10: + printf("Exec: (%s)\n",myMsg.data); + break; + default: + printf("MailBox: init Received Message %i:%s\n",myMsg.header,myMsg.data); + break; + } + goto fetchAgain; + } + */ + sched_yield(); + } + printf("login exited?"); + + goto startup; + + return(0x0); + } + +/*** + END + ***/ + diff --git a/bin/launcher/Makefile b/bin/launcher/Makefile new file mode 100644 index 0000000..21974b0 --- /dev/null +++ b/bin/launcher/Makefile @@ -0,0 +1,50 @@ +# $Id: Makefile 115 2016-01-14 02:55:19Z reddawg $ +# Application Makefile (C) 2002-2004 The UbixOS Project + +# Include Global 'Source' Options +Makefile.incl +Makefile.incl + +INCLUDES += -I./include -I../../lib/views/sunlight/include -I../../lib/libcpp/include -I../../lib/objgfx40/objgfx40 +CFLAGS = -nostdlib -fno-exceptions -frtti +LIBRARIES += ../../lib/libstdc++/*.o + +#Linker +LD = ld + +#Binary File Name +BINARY = launcher + +#Delete Program +REMOVE = rm -f + +#Objects +OBJS = launcher.o ubixButton.o ubixDesktop.o + +# Link The Binary +$(BINARY) : $(OBJS) + $(CC) $(CFLAGS) -o ../build/$@ $(STARTUP) $(LIBRARIES) $(OBJS) + strip $(BINARY) + +# Compile the source files +.cpp.o: + $(CXX) -Wall -O -DNOBOOL $(CFLAGS) $(INCLUDES) -c -o $@ $< + +.cc.o: + $(CXX) -Wall -O -DNOBOOL $(CFLAGS) $(INCLUDES) -c -o $@ $< + +.cc.s: + $(CXX) -Wall -O $(CFLAGS) $(INCLUDES) -S -o $@ $< + +.c.o: + $(CC) -Wall -O $(CFLAGS) $(INCLUDES) -c -o $@ $< + +.c.s: + $(CC) -Wall -O $(CFLAGS) $(INCLUDES) -S -o $@ $< + +.S.o: + $(CC) -Wall $(CLFAGS) $(INCLUDES) -c -o $@ $< + +# Clean Up The junk +clean: + $(REMOVE) $(OBJS) $(BINARY) diff --git a/bin/launcher/include/ubixButton.h b/bin/launcher/include/ubixButton.h new file mode 100644 index 0000000..34ee379 --- /dev/null +++ b/bin/launcher/include/ubixButton.h @@ -0,0 +1,13 @@ +#ifndef UBIXBUTTON_H +#define UBIXBUTTON_H + +#include + +class ubixButton : public vButton { + public: + ubixButton(vContext *); +// virtual bool vCreate(void); + virtual void vDraw(void); + virtual ~ubixButton(void); +}; // ubixButton +#endif diff --git a/bin/launcher/include/ubixDesktop.h b/bin/launcher/include/ubixDesktop.h new file mode 100644 index 0000000..61a1a38 --- /dev/null +++ b/bin/launcher/include/ubixDesktop.h @@ -0,0 +1,14 @@ +#ifndef UBIXDESKTOP_H +#define UBIXDESKTOP_H + +#include + +class ubixDesktop : public vContext { + protected: + public: + ubixDesktop(vContext *); + virtual bool vCreate(void); + virtual void vDraw(void); + virtual ~ubixDesktop(void); +}; // ubixDesktop +#endif diff --git a/bin/launcher/launcher.cpp b/bin/launcher/launcher.cpp new file mode 100644 index 0000000..db6cd82 --- /dev/null +++ b/bin/launcher/launcher.cpp @@ -0,0 +1,16 @@ +#include +#include +#include +#include + +int +main(void) { + ubixDesktop * desktop = new ubixDesktop(NULL); + ubixButton * daButton = new ubixButton(desktop); + desktop->vCreate(); + daButton->vCreate(); + delete daButton; + delete desktop; + + return 0; +} diff --git a/bin/launcher/ubixButton.cpp b/bin/launcher/ubixButton.cpp new file mode 100644 index 0000000..f74f65c --- /dev/null +++ b/bin/launcher/ubixButton.cpp @@ -0,0 +1,20 @@ +#include +#include +#include +#include + +ubixButton::ubixButton(vContext * parent) : vButton(parent) { + vSetSize(48, 48); + vSetPos(0, 600-vGetHeight()); + vSetStyle("default.button.border.size", new sSize(0)); + return; +} // ubixButton::ubixButton() + +void +ubixButton::vDraw(void) { + return; +} // ubixButton::vDraw() + +ubixButton::~ubixButton(void) { + return; +} // ubixButton::~ubixButton() diff --git a/bin/launcher/ubixDesktop.cpp b/bin/launcher/ubixDesktop.cpp new file mode 100644 index 0000000..c9afad0 --- /dev/null +++ b/bin/launcher/ubixDesktop.cpp @@ -0,0 +1,30 @@ +#include +#include +#include +#include + +ubixDesktop::ubixDesktop(vContext * parent) : vContext(parent) { + vSetStyle("default.button.border.size", new sSize(2)); + vSetStyle("default.font.filename", new sString("ROM8X14.DPF")); + vSetStyle("default.font.color.foreground", + new sRGBA8Color(255, 255, 255, 255)); + vSetStyle("default.font.color.background", + new sRGBA8Color(0, 0, 0, 255)); + vSetStyle("default.desktop.pixelformat", + new sPixelFormat(16, 11,5,0,0, 5,6,5,0)); + return; +} // ubixDesktop::ubixDesktop + +bool +ubixDesktop::vCreate(void) { + return true; +} // ubixDesktop::vCreate + +void +ubixDesktop::vDraw(void) { + return; +} // ubixDesktop::vDraw + +ubixDesktop::~ubixDesktop(void) { + return; +} diff --git a/bin/ld/Makefile b/bin/ld/Makefile new file mode 100644 index 0000000..db85020 --- /dev/null +++ b/bin/ld/Makefile @@ -0,0 +1,46 @@ +# $Id: Makefile 119 2016-01-14 03:06:36Z reddawg $ +# Application Makefile (C) 2002-2004 The UbixOS Project + +# Include Global 'Source' Options +include ../../Makefile.incl +include ../Makefile.incl + +#Linker +LD = ld + +#Binary File Name +OUTPUT = ld.so + +#Delete Program +REMOVE = rm -f + +#Objects +OBJS = main.o findlibrary.o findfunc.o addlibrary.o entry.o + +# Link The Binary +$(OUTPUT) : $(OBJS) + $(CC) -m32 -nostdlib -shared -Wl,-soname,$(OUTPUT) -Wl,-m,elf_i386_fbsd -e _ld -o ../../build/libexec/$(OUTPUT) $(OBJS) $(LIBRARIES) $(SUBS) +# strip $(OUTPUT) + +# Compile the source files +.cpp.o: + $(CXX) -Wall -O $(CFLAGS) $(INCLUDES) -c -o $@ $< + +.cc.o: + $(CXX) -Wall -O $(CFLAGS) $(INCLUDES) -c -o $@ $< + +.cc.s: + $(CXX) -Wall -O $(CFLAGS) $(INCLUDES) -S -o $@ $< + +.c.o: + $(CC) -Wall -O $(CFLAGS) $(INCLUDES) -c -o $@ $< + +.c.s: + $(CC) -Wall -O $(CFLAGS) $(INCLUDES) -S -o $@ $< + +.S.o: + $(CC) -Wall $(CFLAGS) $(INCLUDES) -c -o $@ $< + +# Clean Up The junk +clean: + $(REMOVE) $(OBJS) ../../build/bin/$(OUTPUT) diff --git a/bin/ld/addlibrary.c b/bin/ld/addlibrary.c new file mode 100644 index 0000000..e527520 --- /dev/null +++ b/bin/ld/addlibrary.c @@ -0,0 +1,161 @@ +#include +#include +#include "ld.h" + +ldLibrary *ldAddLibrary(const char *lib) { + int i = 0x0; + int x = 0x0; + int rel = 0x0; + uInt32 *reMap = 0x0; + char *newLoc = 0x0; + FILE *linkerFd = 0x0; + char tmpFile[1024]; + ldLibrary *tmpLib = 0x0; + + if ((tmpLib = (ldLibrary *)malloc(sizeof(ldLibrary))) == 0x0) { + printf("malloc failed: tmpLib\n"); + exit(0x1); + } + if (tmpLib->output == 0x0) { + /* Hack because we have no ld path set */ + sprintf(tmpFile,"sys:/lib/%s",lib); + linkerFd = fopen(tmpFile,"rb"); + if (linkerFd->fd == 0x0) { + printf("Could not open library: %s\n",lib); + exit(-1); + } + //if ((tmpLib->output = (char *)malloc((linkerFd->size+0x4000))) == 0x0) { + //if ((tmpLib->output = (char *)malloc(0x111000)) == 0x0) { + if ((tmpLib->output = (char *)getPage((0x111000/0x1000),2)) == 0x0) { + printf("malloc failed: tmpLib->output\n"); + exit(0x1); + } + sprintf(tmpLib->name,lib); + } + printf("Base: {0x%X}\n",tmpLib->output); + if (tmpLib->linkerHeader == 0x0) { + fseek(linkerFd,0x0,0x0); + if ((tmpLib->linkerHeader = (elfHeader *)malloc(sizeof(elfHeader))) == 0x0) { + printf("malloc failed: tmpLib->linkerHeader\n"); + exit(0x1); + } + fread(tmpLib->linkerHeader,sizeof(elfHeader),1,linkerFd); + } + if (tmpLib->linkerProgramHeader == 0x0) { + if ((tmpLib->linkerProgramHeader = (elfProgramHeader *)malloc(sizeof(elfProgramHeader)*tmpLib->linkerHeader->ePhnum)) == 0x0) { + printf("malloc failed: tmpLib->linkerProgramHeader\n"); + exit(0x1); + } + fseek(linkerFd,tmpLib->linkerHeader->ePhoff,0); + fread(tmpLib->linkerProgramHeader,sizeof(elfProgramHeader),tmpLib->linkerHeader->ePhnum,linkerFd); + + for (i=0;ilinkerHeader->ePhnum;i++) { + switch (tmpLib->linkerProgramHeader[i].phType) { + case PT_LOAD: + case PT_DYNAMIC: + newLoc = (char *)tmpLib->linkerProgramHeader[i].phVaddr + (uInt32)tmpLib->output; + fseek(linkerFd,tmpLib->linkerProgramHeader[i].phOffset,0); + fread(newLoc,tmpLib->linkerProgramHeader[i].phFilesz,1,linkerFd); + break; + case PT_GNU_STACK: + /* Tells us if the stack should be executable. Failsafe to + executable until we add checking */ + printf("NOT DEF1\n"); + break; + case PT_PAX_FLAGS: + /* Not sure... */ + printf("NOT DEF2\n"); + break; + default: + printf("Unhandled Header (ld.so) : %08x\n", tmpLib->linkerProgramHeader[i].phType); + break; + } + } + } + + if (tmpLib->linkerSectionHeader == 0x0) { + if ((tmpLib->linkerSectionHeader = (elfSectionHeader *)malloc(sizeof(elfSectionHeader)*tmpLib->linkerHeader->eShnum)) == 0x0) { + printf("malloc failed: tmpLib->linkerSectionHeader\n"); + exit(0x1); + } + fseek(linkerFd,tmpLib->linkerHeader->eShoff,0); + fread(tmpLib->linkerSectionHeader,sizeof(elfSectionHeader),tmpLib->linkerHeader->eShnum,linkerFd); + + if (tmpLib->linkerShStr == 0x0) { + tmpLib->linkerShStr = (char *)malloc(tmpLib->linkerSectionHeader[tmpLib->linkerHeader->eShstrndx].shSize); + fseek(linkerFd,tmpLib->linkerSectionHeader[tmpLib->linkerHeader->eShstrndx].shOffset,0); + fread(tmpLib->linkerShStr,tmpLib->linkerSectionHeader[tmpLib->linkerHeader->eShstrndx].shSize,1,linkerFd); + } + + for (i = 0x0;i < tmpLib->linkerHeader->eShnum;i++) { + switch (tmpLib->linkerSectionHeader[i].shType) { + case 3: + if (!strcmp((tmpLib->linkerShStr + tmpLib->linkerSectionHeader[i].shName),".dynstr")) { + if (tmpLib->linkerDynStr == 0x0) { + if ((tmpLib->linkerDynStr = (char *)malloc(tmpLib->linkerSectionHeader[i].shSize)) == 0x0) { + printf("malloc failed: tmpLib->linkerDynStr\n"); + exit(0x1); + } + fseek(linkerFd,tmpLib->linkerSectionHeader[i].shOffset,0); + fread(tmpLib->linkerDynStr,tmpLib->linkerSectionHeader[i].shSize,1,linkerFd); + } + } + break; + case 9: + if ((tmpLib->linkerElfRel = (elfPltInfo *)malloc(tmpLib->linkerSectionHeader[i].shSize)) == 0x0) { + printf("malloc failed: tmpLib->linkerElfRel\n"); + exit(0x1); + } + fseek(linkerFd,tmpLib->linkerSectionHeader[i].shOffset,0x0); + fread(tmpLib->linkerElfRel,tmpLib->linkerSectionHeader[i].shSize,1,linkerFd); + + for (x=0x0;xlinkerSectionHeader[i].shSize/sizeof(elfPltInfo);x++) { + rel = ELF32_R_SYM(tmpLib->linkerElfRel[x].pltInfo); + reMap = (uInt32 *)((uInt32)tmpLib->output + tmpLib->linkerElfRel[x].pltOffset); + switch (ELF32_R_TYPE(tmpLib->linkerElfRel[x].pltInfo)) { + case R_386_32: + *reMap += ((uInt32)tmpLib->output + tmpLib->linkerRelSymTab[rel].dynValue); + //printf("[0x%X]",*reMap); + break; + case R_386_PC32: + *reMap += ((uInt32)tmpLib->output + tmpLib->linkerRelSymTab[rel].dynValue) - (uInt32)reMap; + break; + case R_386_RELATIVE: + *reMap += (uInt32)tmpLib->output; + break; + case R_386_JMP_SLOT: + *reMap += (uInt32)tmpLib->output; + break; + case R_386_GLOB_DAT: + *reMap = ((uInt32)tmpLib->output + tmpLib->linkerRelSymTab[rel].dynValue); + break; + default: + printf("Unhandled sym: [0x%X]\n", ELF32_R_TYPE(tmpLib->linkerElfRel[x].pltInfo)); + while (1); + break; + } + } + free(tmpLib->linkerElfRel); + break; + case 11: + if (tmpLib->linkerRelSymTab == 0x0) { + tmpLib->linkerRelSymTab = (elfDynSym *)malloc(tmpLib->linkerSectionHeader[i].shSize); + fseek(linkerFd,tmpLib->linkerSectionHeader[i].shOffset,0); + fread(tmpLib->linkerRelSymTab,tmpLib->linkerSectionHeader[i].shSize,1,linkerFd); + tmpLib->sym = i; + } + break; + } + } + } + if (libs != 0x0) + libs->prev = tmpLib; + tmpLib->prev = 0x0; + tmpLib->next = libs; + libs = tmpLib; + + if (linkerFd) { + fclose(linkerFd); + } + return(tmpLib); + } diff --git a/bin/ld/elf.h b/bin/ld/elf.h new file mode 100644 index 0000000..d344299 --- /dev/null +++ b/bin/ld/elf.h @@ -0,0 +1,186 @@ +/************************************************************************************** + Copyright (c) 2002 The UbixOS Project + All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +Redistributions of source code must retain the above copyright notice, this list of conditions, the following disclaimer and the list of authors. +Redistributions in binary form must reproduce the above copyright notice, this list of conditions, the following disclaimer and the list of authors +in the documentation and/or other materials provided with the distribution. Neither the name of the UbixOS Project 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 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 OWNER 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. + + $Id: elf.h 89 2016-01-12 00:20:40Z reddawg $ + +**************************************************************************************/ + +#ifndef _ELF_H +#define _ELF_H + +#include + +#define elfExecutable 0x002 +#define elfLibrary 0x003 + +#define R_386_NONE 0 /* none none */ +#define R_386_32 1 /* word32 S + A */ +#define R_386_PC32 2 /* word32 S + A - P */ +#define R_386_GOT32 3 /* word32 G + A - P */ +#define R_386_PLT32 4 /* word32 L + A - P */ +#define R_386_COPY 5 /* none none */ +#define R_386_GLOB_DAT 6 /* word32 S */ +#define R_386_JMP_SLOT 7 /* word32 S */ +#define R_386_RELATIVE 8 /* word32 B + A */ +#define R_386_GOTOFF 9 /* word32 S + A - GOT */ +#define R_386_GOTPC 10 /* word32 GOT + A - P */ + + +/* Elf Types */ +#define ET_NONE 0 // No file type +#define ET_REL 1 // Relocatable file +#define ET_EXEC 2 // Executable file +#define ET_DYN 3 // Shared object file +#define ET_CORE 4 // Core file +#define ET_LOPROC 0xff00 // Processor-specific +#define ET_HIPROC 0xffff +/* End Elf Types */ + +/* Elf Machine Types */ +#define EM_NONE 0 // No machine +#define EM_M32 1 // AT&T WE 32100 +#define EM_SPARC 2 // SPARC +#define EM_386 3 // Intel 80386 +#define EM_68K 4 // Motorola 68000 +#define EM_88K 5 // Motorola 88000 +#define EM_860 7 // Intel 80860 +#define EM_MIPS 8 // MIPS RS3000 +/* End Elf Machines Types */ + +/* Elf Version */ +#define EV_NONE 0 // Invalid version +#define EV_CURRENT 1 // Current version +/* End Elf Version */ + +/* Elf Program Header Types */ +#define PT_NULL 0 +#define PT_LOAD 1 +#define PT_DYNAMIC 2 +#define PT_INTERP 3 +#define PT_NOTE 4 +#define PT_SHLIB 5 +#define PT_PHDR 6 +#define PT_LOOS 0x60000000 +#define PT_HIOS 0x6fffffff +#define PT_LOPROC 0x70000000 +#define PT_HIPROC 0x7fffffff +#define PT_GNU_EH_FRAME 0x6474e550 +#define PT_GNU_STACK (PT_LOOS + 0x474e551) +#define PT_GNU_RELRO (PT_LOOS + 0x474e552) +#define PT_PAX_FLAGS (PT_LOOS + 0x5041580) +/* End Elf Program Header Types */ + +typedef struct { + uInt8 eIdent[16]; /* File identification. */ + uInt16 eType; /* File type. */ + uInt16 eMachine; /* Machine architecture. */ + uInt32 eVersion; /* ELF format version. */ + uInt32 eEntry; /* Entry point. */ + uInt32 ePhoff; /* Program Header file offset. */ + uInt32 eShoff; /* Section header file offset. */ + uInt32 eFlags; /* Architecture-specific flags. */ + uInt16 eEhsize; /* Size of ELF header in bytes. */ + uInt16 ePhentsize; /* Size of program header entry. */ + uInt16 ePhnum; /* Number of program header entries. */ + uInt16 eShentsize; /* Size of section header entry. */ + uInt16 eShnum; /* Number of section header entries. */ + uInt16 eShstrndx; /* Section name strings section. */ + } elfHeader; + +typedef struct { + uInt32 phType; /* Entry type. */ + uInt32 phOffset; /* File offset of contents. */ + uInt32 phVaddr; /* Virtual address in memory image. */ + uInt32 phPaddr; /* Physical address (not used). */ + uInt32 phFilesz; /* Size of contents in file. */ + uInt32 phMemsz; /* Size of contents in memory. */ + uInt32 phFlags; /* Access permission flags. */ + uInt32 phAlign; /* Alignment in memory and file. */ + } elfProgramHeader; + +typedef struct { + uInt32 shName; /* Section name (index into the section header string table). */ + uInt32 shType; /* Section type. */ + uInt32 shFlags; /* Section flags. */ + uInt32 shAddr; /* Address in memory image. */ + uInt32 shOffset; /* Offset in file. */ + uInt32 shSize; /* Size in bytes. */ + uInt32 shLink; /* Index of a related section. */ + uInt32 shInfo; /* Depends on section type. */ + uInt32 shAddralign; /* Alignment in bytes. */ + uInt32 shEntsize; /* Size of each entry in section. */ + } elfSectionHeader; + +typedef struct { + uInt32 pltOffset; + uInt32 pltInfo; + } elfPltInfo; + +typedef struct { + uInt32 dynName; + uInt32 dynValue; + uInt32 dynSize; + uInt8 dynInfo; + uInt8 dynOther; + uInt16 dynShndx; + } elfDynSym; + +typedef struct { + uInt32 dynVal; + uInt32 dynPtr; + } elfDynamic; + + +char *elfGetShType(int); +char *elfGetPhType(int); +char *elfGetRelType(int); + +#define ELF32_R_SYM(i) ((i)>>8) +#define ELF32_R_TYPE(i) ((unsigned char)(i)) +#define ELF32_R_INFO(s, t) ((s)<<8+(unsigned char)(t)) + +/* New Stuff */ +#define SHT_NULL 0 +#define SHT_PROGBITS 1 +#define SHT_SYMTAB 2 +#define SHT_STRTAB 3 +#define SHT_RELA 4 +#define SHT_HASH 5 +#define SHT_DYNAMIC 6 +#define SHT_NOTE 7 +#define SHT_NOBITS 8 +#define SHT_REL 9 +#define SHT_SHLIB 10 +#define SHT_DYNSYM 11 +#define SHT_LOPROC 0x70000000 +#define SHT_HIPROC 0x7fffffff +#define SHT_LOUSER 0x80000000 +#define SHT_HIUSER 0xffffffff + +typedef struct { + long d_tag; + union { + uInt32 d_val; + uInt32 d_ptr; + } d_un; + } Elf32_Dyn; + + +#endif + diff --git a/bin/ld/entry.S b/bin/ld/entry.S new file mode 100644 index 0000000..5b7ba32 --- /dev/null +++ b/bin/ld/entry.S @@ -0,0 +1,57 @@ +/***************************************************************************************** + Copyright (c) 2002-2004 The UbixOS Project + All rights reserved. + + Redistribution and use in source and binary forms, with or without modification, are + permitted provided that the following conditions are met: + + Redistributions of source code must retain the above copyright notice, this list of + conditions, the following disclaimer and the list of authors. Redistributions in binary + form must reproduce the above copyright notice, this list of conditions, the following + disclaimer and the list of authors in the documentation and/or other materials provided + with the distribution. Neither the name of the UbixOS Project 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 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 OWNER 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. + + $Id: entry.S 89 2016-01-12 00:20:40Z reddawg $ + +*****************************************************************************************/ + +.globl _ld +.text +.code32 + +_ld: + call ld + add $8,%esp + push %eax + ret + +/*** + $Log: entry.S,v $ + Revision 1.1.1.1 2006/06/01 12:46:09 reddawg + ubix2 + + Revision 1.2 2005/10/12 00:13:28 reddawg + Removed + + Revision 1.1.1.1 2005/09/26 17:14:00 reddawg + no message + + Revision 1.1 2004/06/17 11:58:10 reddawg + ld.so: Made a few changes to the way it functions hopefully it will + improve some of its performance. + + END + ***/ + diff --git a/bin/ld/findfunc.c b/bin/ld/findfunc.c new file mode 100644 index 0000000..527000c --- /dev/null +++ b/bin/ld/findfunc.c @@ -0,0 +1,32 @@ +#include +#include +#include "ld.h" + +uInt32 ldFindFunc(const char *func,const char *lib) { + int i = 0x0; + int x = 0x0; + uInt32 *funcPtr = 0x0; + ldLibrary *libPtr = 0x0; + + for (x = 0; x < lib_c;x++) { + libPtr = ldFindLibrary(lib + lib_s[x]); + if (libPtr == 0x0) { + libPtr = ldAddLibrary(lib + lib_s[x]); + } + + for (i=0x0;ilinkerSectionHeader[libPtr->sym].shSize/sizeof(elfDynSym);i++) { + if (!strcmp(func,(libPtr->linkerDynStr + libPtr->linkerRelSymTab[i].dynName))) { + funcPtr = (uInt32 *)((uInt32)(libPtr->linkerRelSymTab[i].dynValue) + (uInt32)libPtr->output); + if (funcPtr == 0x0) { + printf("[%s:0x%X]\n",func,funcPtr); + } + return((uInt32)funcPtr); + break; + } + } + } + + printf("ERROR COULDN'T FIND FUNCTION: %s:%s\n",func,lib); + return(0x0); + } + diff --git a/bin/ld/findlibrary.c b/bin/ld/findlibrary.c new file mode 100644 index 0000000..f071e7d --- /dev/null +++ b/bin/ld/findlibrary.c @@ -0,0 +1,13 @@ +#include +#include "ld.h" + +ldLibrary *ldFindLibrary(const char *lib) { + ldLibrary *tmpLibs = 0x0; + + for (tmpLibs = libs;tmpLibs != 0x0;tmpLibs = tmpLibs->next) { + if (!strcmp(tmpLibs->name,lib)) { + return(tmpLibs); + } + } + return(0x0); + } diff --git a/bin/ld/ld.h b/bin/ld/ld.h new file mode 100644 index 0000000..0255e4d --- /dev/null +++ b/bin/ld/ld.h @@ -0,0 +1,31 @@ +#include +#include +#include "elf.h" + +typedef struct ldLibrary_s { + struct ldLibrary_s *next; + struct ldLibrary_s *prev; + char name[256]; + elfHeader *linkerHeader; + elfSectionHeader *linkerSectionHeader; + elfProgramHeader *linkerProgramHeader; + elfDynSym *linkerRelSymTab; + elfPltInfo *linkerElfRel; + char *linkerShStr; + char *linkerDynStr; + char *output; + int sym; + } ldLibrary; + +extern ldLibrary *libs; +extern int lib_c; +extern int lib_s[10]; + +uInt32 ldFindFunc(const char *,const char *); +ldLibrary *ldFindLibrary(const char *); +ldLibrary *ldAddLibrary(const char *); + +/*** + END + ***/ + diff --git a/bin/ld/main.c b/bin/ld/main.c new file mode 100644 index 0000000..ee9f78b --- /dev/null +++ b/bin/ld/main.c @@ -0,0 +1,159 @@ +/***************************************************************************************** + Copyright (c) 2002-2004 The UbixOS Project + All rights reserved. + + Redistribution and use in source and binary forms, with or without modification, are + permitted provided that the following conditions are met: + + Redistributions of source code must retain the above copyright notice, this list of + conditions, the following disclaimer and the list of authors. Redistributions in binary + form must reproduce the above copyright notice, this list of conditions, the following + disclaimer and the list of authors in the documentation and/or other materials provided + with the distribution. Neither the name of the UbixOS Project 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 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 OWNER 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. + + $Id: main.c 122 2016-01-14 03:45:52Z reddawg $ + + *****************************************************************************************/ + +#include +#include +#include +#include "ld.h" + +ldLibrary *libs = 0x0; +int lib_c = 0x0; +int lib_s[10]; + +static elfHeader *binaryHeader = 0x0; +static elfSectionHeader *binarySectionHeader = 0x0; +static char *binaryShStr = 0x0; +static char *binaryDynStr = 0x0; +static elfDynSym *binaryRelSymTab = 0x0; +static Elf32_Dyn *binaryElf32_Dyn = 0x0; +static elfPltInfo *binaryElfRelDyn = 0x0; +static elfPltInfo *binaryElfRel = 0x0; + +uInt32 ld( uInt32 got2, uInt32 entry ) { + int i = 0x0; + int x = 0x0; + int y = 0x0; + int rel = 0x0; + int relDyn = 0x0; + uInt32 *reMap = 0x0; + FILE *binaryFd = 0x0; + + if ( binaryHeader == 0x0 ) { + binaryFd = malloc( sizeof(FILE) ); + binaryFd->fd = (uInt32) got2; + fseek( binaryFd, 0x0, 0x0 ); + binaryHeader = (elfHeader *) malloc( sizeof(elfHeader) ); + fread( binaryHeader, sizeof(elfHeader), 1, binaryFd ); + } + + if ( binarySectionHeader == 0x0 ) { + binarySectionHeader = (elfSectionHeader *) malloc( sizeof(elfSectionHeader) * binaryHeader->eShnum ); + fseek( binaryFd, binaryHeader->eShoff, 0 ); + fread( binarySectionHeader, sizeof(elfSectionHeader), binaryHeader->eShnum, binaryFd ); + + if ( binaryShStr == 0x0 ) { + binaryShStr = (char *) malloc( binarySectionHeader[binaryHeader->eShstrndx].shSize ); + fseek( binaryFd, binarySectionHeader[binaryHeader->eShstrndx].shOffset, 0 ); + fread( binaryShStr, binarySectionHeader[binaryHeader->eShstrndx].shSize, 1, binaryFd ); + } + + for ( i = 0x0; i < binaryHeader->eShnum ; i++ ) { + switch ( binarySectionHeader[i].shType ) { + case 3: + if ( !strcmp( ( binaryShStr + binarySectionHeader[i].shName ), ".dynstr" ) ) { + if ( binaryDynStr == 0x0 ) { + binaryDynStr = (char *) malloc( binarySectionHeader[i].shSize ); + fseek( binaryFd, binarySectionHeader[i].shOffset, 0 ); + fread( binaryDynStr, binarySectionHeader[i].shSize, 1, binaryFd ); + } + } + break; + case SHT_DYNAMIC: + binaryElf32_Dyn = (Elf32_Dyn *) malloc( binarySectionHeader[i].shSize ); + fseek( binaryFd, binarySectionHeader[i].shOffset, 0 ); + fread( binaryElf32_Dyn, binarySectionHeader[i].shSize, 1, binaryFd ); + for ( x = 0; x < binarySectionHeader[i].shSize / sizeof(Elf32_Dyn) ; x++ ) { + if ( binaryElf32_Dyn[x].d_tag == 1 ) { + lib_s[lib_c] = binaryElf32_Dyn[x].d_un.d_ptr; + lib_c++; + } + } + break; + case SHT_REL: + // if (!strcmp(binaryShStr + binarySectionHeader[i].shName,".rel.dyn")) + // relDyn = i; + // else + rel = i; + break; + case 11: + if ( binaryRelSymTab == 0x0 ) { + binaryRelSymTab = (elfDynSym *) malloc( binarySectionHeader[i].shSize ); + fseek( binaryFd, binarySectionHeader[i].shOffset, 0 ); + fread( binaryRelSymTab, binarySectionHeader[i].shSize, 1, binaryFd ); + } + break; + } + } + } + + /* + if ((binaryElfRelDyn == 0x0) && (relDyn != 0)) { + binaryElfRelDyn = (elfPltInfo *)malloc(binarySectionHeader[i].shSize); + fseek(binaryFd,binarySectionHeader[relDyn].shOffset,0x0); + fread(binaryElfRelDyn,binarySectionHeader[relDyn].shSize,1,binaryFd); + + for (x = 0;x < binarySectionHeader[relDyn].shSize / sizeof(elfPltInfo);x++) { + switch (ELF32_R_TYPE(binaryElfRelDyn[x].pltInfo)) { + case R_386_COPY: + printf("COPY"); + reMap = (uInt32 *)binaryElfRelDyn[x].pltOffset; + *reMap = 0x1; + break; + default: + //printf("UNHANDLED THING"); + break; + } + printf("y: [%i:0x%X]",y,binaryElfRelDyn[x].pltOffset); + } + } + */ + + if ( binaryElfRel == 0x0 ) { + binaryElfRel = (elfPltInfo *) malloc( binarySectionHeader[rel].shSize ); + fseek( binaryFd, binarySectionHeader[rel].shOffset, 0x0 ); + fread( binaryElfRel, binarySectionHeader[rel].shSize, 1, binaryFd ); + } + + i = ( entry / sizeof(elfPltInfo) ); + x = ELF32_R_SYM( binaryElfRel[i].pltInfo ); + reMap = (uInt32 *) binaryElfRel[i].pltOffset; + *reMap = ldFindFunc( binaryDynStr + binaryRelSymTab[x].dynName, binaryDynStr ); + printf( "\nld(%s)", binaryDynStr + binaryRelSymTab[x].dynName ); + //*reMap = ldFindFunc(binaryDynStr + binaryRelSymTab[x].dynName,(char *)(binaryDynStr + 1)); + + if ( binaryFd ) { + fclose( binaryFd ); + } + + return ( *reMap ); +} + +/*** + END + ***/ diff --git a/bin/login/Makefile b/bin/login/Makefile new file mode 100644 index 0000000..01e2f78 --- /dev/null +++ b/bin/login/Makefile @@ -0,0 +1,48 @@ +# $Id: Makefile 115 2016-01-14 02:55:19Z reddawg $ +# Application Makefile (C) 2002-2004 The UbixOS Project + +# Include Global 'Source' Options +include ../../Makefile.incl +include ../Makefile.incl + +#Linker +LD = ld + +#Binary File Name +BINARY = login + +#Delete Program +REMOVE = rm -f + +#Objects +OBJS = main.o + +#LIBRARIES = ../../lib/libc/libc.so + +# Link The Binary +$(BINARY) : $(OBJS) + $(CC) $(CFLAGS) -o $(BUILD_DIR)/bin/$@ $(STARTUP) $(LIBRARIES) $(OBJS) +# strip $(BINARY) + +# Compile the source files +.cpp.o: + $(CXX) -Wall -O $(CFLAGS) $(INCLUDES) -c -o $@ $< + +.cc.o: + $(CXX) -Wall -O $(CFLAGS) $(INCLUDES) -c -o $@ $< + +.cc.s: + $(CXX) -Wall -O $(CFLAGS) $(INCLUDES) -S -o $@ $< + +.c.o: + $(CC) -Wall -O $(CFLAGS) $(INCLUDES) -c -o $@ $< + +.c.s: + $(CC) -Wall -O $(CFLAGS) $(INCLUDES) -S -o $@ $< + +.S.o: + $(CC) -Wall $(CLFAGS) $(INCLUDES) -c -o $@ $< + +# Clean Up The junk +clean: + $(REMOVE) $(OBJS) $(BUILD_DIR)/bin/$(BINARY) diff --git a/bin/login/main.c b/bin/login/main.c new file mode 100644 index 0000000..f620c5e --- /dev/null +++ b/bin/login/main.c @@ -0,0 +1,153 @@ +/************************************************************************************** + Copyright (c) 2002 The UbixOS Project + All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +Redistributions of source code must retain the above copyright notice, this list of conditions, the following disclaimer and the list of authors. +Redistributions in binary form must reproduce the above copyright notice, this list of conditions, the following disclaimer and the list of authors +in the documentation and/or other materials provided with the distribution. Neither the name of the UbixOS Project 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 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 OWNER 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. + + $Id: main.c 159 2016-01-19 03:07:04Z reddawg $ + +**************************************************************************************/ + +#include +#include +#include +#include +#include +#include + +struct passwd { + char username[32]; + char password[32]; + int uid; + int gid; + char shell[128]; + char realname[256]; + char path[256]; + }; + +static char *pgets(char *string) { + int count=0,ch=0; + while (1) { + ch = fgetc(stdin); + if(ch == 10) { + printf("\n"); + break; + } + else if(ch == 8 && count > 0) count-=2; + else if(ch == 0) count--; + else string[count] = ch; + if (ch != 8) printf("*"); + count++; + } + string[count] = '\0'; + return(string); + } + +int main() { + FILE *fd; + int shellPid = 0,i = 0x0; + char userName[32]; + char passWord[32]; + char *data2 = 0x0; + struct passwd *data = 0x0; + + + if ((getuid() != 0x0) && (getgid() != 0x0)) { + printf("This Application Must Be Run As Root.\n"); + exit(-1); + } + + if ((data = (struct passwd *)malloc(0x1000)) == 0x0) { + printf("Malloc Failed\n"); + exit(0x1); + } + + fd = fopen("sys:/etc/userdb","r"); + if (fd->fd == 0x0) { + printf("Missing User Database.\n"); + exit(0x1); + } + + fread(data,0x1000,0x1,fd); + + fclose(fd); + + if ((data2 = (char *)malloc(384)) == 0x0) { + printf("Malloc Failed\n"); + exit(0x1); + } + +/* we need to move this into the libc for getpwent(), etc */ +/* + foo = auth("root", "user"); + if(foo != -1) + printf("yay\n"); + else + printf("damn\n"); +*/ + + login: + printf("\nUbixOS/IA-32 (devel.ubixos.com) (console)"); + printf("\n\nLogin: "); + gets((char *)&userName); + printf("Password: "); + pgets((char *)&passWord); + + for (i=0x0;i<(4096/sizeof(struct passwd));i++) { + if (0x0 == strcmp(userName,data[i].username)) { + if (0x0 == strcmp(passWord,data[i].password)) { + shellPid = fork(); + if (shellPid == 0x0) { + if (setuid(data[i].uid) != 0x0) { + printf("Set UID Failed\n"); + } + + if (setgid(data[i].gid) != 0x0) { + printf("Set GID Failed\n"); + } + + fd = 0x0; + fd = fopen("sys:/etc/motd","r"); + + //if ((fd = fopen("sys:/motd","r")) == 0x0) { + if (fd == 0x0) { + printf("No MOTD"); + } + else { + fread(data2,384,1,fd); + printf("%s\n",data2); + } + fclose(fd); + //chdir(data[i].path); + chdir("sys:/bin/"); + execve(data[i].shell,0x0,0x0); + printf("Error: Problem Starting Shell\n"); + exit(-1); + } + else { + while (pidStatus(shellPid) > 0) { + sched_yield(); + } + goto login; + } + } + } + } + printf("Login Incorrect!\n"); + goto login; + return(0x0); + } + diff --git a/bin/ls/Makefile b/bin/ls/Makefile new file mode 100644 index 0000000..55ec9fd --- /dev/null +++ b/bin/ls/Makefile @@ -0,0 +1,48 @@ +# $Id: Makefile 115 2016-01-14 02:55:19Z reddawg $ +# Application Makefile (C) 2002-2004 The UbixOS Project + +# Include Global 'Source' Options +include ../../Makefile.incl +include ../Makefile.incl + +#Linker +LD = ld + +#Binary File Name +BINARY = ls + +#Delete Program +REMOVE = rm -f + +#Objects +OBJS = main.o + +LIBRARIES = ../../build/lib/libc_old.so + +# Link The Binary +$(BINARY) : $(OBJS) + $(CC) $(CFLAGS) -o ../../build/bin/$@ $(STARTUP) $(LIBRARIES) $(OBJS) + #strip $(BINARY) + +# Compile the source files +.cpp.o: + $(CXX) -Wall -O $(CFLAGS) $(INCLUDES) -c -o $@ $< + +.cc.o: + $(CXX) -Wall -O $(CFLAGS) $(INCLUDES) -c -o $@ $< + +.cc.s: + $(CXX) -Wall -O $(CFLAGS) $(INCLUDES) -S -o $@ $< + +.c.o: + $(CC) -Wall -O $(CFLAGS) $(INCLUDES) -c -o $@ $< + +.c.s: + $(CC) -Wall -O $(CFLAGS) $(INCLUDES) -S -o $@ $< + +.S.o: + $(CC) -Wall $(CLFAGS) $(INCLUDES) -c -o $@ $< + +# Clean Up The junk +clean: + $(REMOVE) $(OBJS) ../../build/bin/$(BINARY) diff --git a/bin/ls/main.c b/bin/ls/main.c new file mode 100644 index 0000000..1574b9f --- /dev/null +++ b/bin/ls/main.c @@ -0,0 +1,138 @@ +/************************************************************************************** + Copyright (c) 2002 The UbixOS Project + All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +Redistributions of source code must retain the above copyright notice, this list of conditions, the following disclaimer and the list of authors. +Redistributions in binary form must reproduce the above copyright notice, this list of conditions, the following disclaimer and the list of authors +in the documentation and/or other materials provided with the distribution. Neither the name of the UbixOS Project 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 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 OWNER 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. + + $Id: main.c 89 2016-01-12 00:20:40Z reddawg $ + +**************************************************************************************/ + +#include +#include +#include +#include + + +#define permRead 0x8 +#define permWrite 0x4 +#define permExecute 0x2 +#define permHidden 0x1 + + +//UbixFS Directory Entry +struct directoryEntry { + uint32_t startCluster; //Starting Cluster Of File + uint32_t size; //Size Of File + uint32_t creationDate; //Date Created + uint32_t lastModified; //Date Last Modified + uint32_t uid; //UID Of Owner + uint32_t gid; //GID Of Owner + uint16_t attributes; //Files Attributes + uint16_t permissions; //Files Permissions + char fileName[256]; //File Name + }; + +#define typeFile 1 +#define typeContainer 2 +#define typeDirectory 4 +#define typeDeleted 8 + +int main(int argc,char **argv) { + int i = 0x0,x = 0x0,tmpPerms = 0x0; + char *pwd = 0x0; + char *permsData = 0x0; + FILE *fd; + struct directoryEntry *dirEntry = 0x0; + + pwd = (char *)malloc(256); + permsData = (char *)malloc(13); + + if (argv == 0x0) { + getcwd(pwd,256); +printf("PWD1: %s\n", pwd); + if ((fd = fopen(pwd,"rb")) == 0x0) { + printf("Error: Reading Directory\n"); + exit(1); + } + } + else if (argv[1] == 0x0) { + getcwd(pwd,256); +printf("PWD2: %s\n", pwd); + if ((fd = fopen(pwd,"rb")) == 0x0) { + printf("Error: Reading Directory\n"); + exit(1); + } + } + else { + getcwd(pwd,256); +printf("PWD3: %s\n", pwd); + fd = fopen(argv[1],"rb"); + if (fd->fd == 0x0) { + printf("Error: Reading Directory\n"); + exit(1); + } + } + dirEntry = (struct directoryEntry *)malloc(fd->size); + fread(dirEntry,fd->size,1,fd); + pwd[0] = '/'; + for (i=0;i<(fd->size/sizeof(struct directoryEntry));i++) { +printf("[fN: %s]", dirEntry[i].fileName); + if ((dirEntry[i].fileName[0] > 0) && (dirEntry[i].fileName[0] != '/')) { + for (x=0;x<12;x++) { + permsData[x] = '-'; + } + if ((dirEntry[i].attributes & typeDeleted) == typeDeleted) { + permsData[0] = 'd'; + goto next; + } + else if ((dirEntry[i].attributes & typeFile) == typeFile) { + permsData[0] = 'F'; + } + else if ((dirEntry[i].attributes & typeDirectory) == typeDirectory) { + permsData[0] = 'D'; + } + else if ((dirEntry[i].attributes & typeContainer) == typeContainer) { + permsData[0] = '@'; + } + else { + permsData[0] = 'U'; + } + tmpPerms = ((dirEntry[i].permissions & 0xF00) >> 8); + if ((tmpPerms & permRead) == permRead) permsData[1] = 'R'; + if ((tmpPerms & permWrite) == permWrite) permsData[2] = 'W'; + if ((tmpPerms & permExecute) == permExecute) permsData[3] = 'E'; + if ((tmpPerms & permHidden) == permHidden) permsData[4] = 'H'; + tmpPerms = ((dirEntry[i].permissions & 0x0F0) >> 4); + if ((tmpPerms & permRead) == permRead) permsData[5] = 'R'; + if ((tmpPerms & permWrite) == permWrite) permsData[6] = 'W'; + if ((tmpPerms & permExecute) == permExecute) permsData[7] = 'E'; + if ((tmpPerms & permHidden) == permHidden) permsData[8] = 'H'; + tmpPerms = ((dirEntry[i].permissions & 0x00F) >> 0); + if ((tmpPerms & permRead) == permRead) permsData[9] = 'R'; + if ((tmpPerms & permWrite) == permWrite) permsData[10] = 'W'; + if ((tmpPerms & permExecute) == permExecute) permsData[11] = 'E'; + if ((tmpPerms & permHidden) == permHidden) permsData[12] = 'H'; + printf("%s %i %i %i %s\n",permsData,(int)dirEntry[i].uid,(int)dirEntry[i].gid,(int)dirEntry[i].size,dirEntry[i].fileName); + next: + asm("nop"); + } + } + if (fclose(fd) != 0x0) { + printf("Error Closing Directory\n"); + } + return(0); + } diff --git a/bin/mount/Makefile b/bin/mount/Makefile new file mode 100644 index 0000000..a860e2d --- /dev/null +++ b/bin/mount/Makefile @@ -0,0 +1,45 @@ +# $Id: Makefile 115 2016-01-14 02:55:19Z reddawg $ +# Application Makefile (C) 2002-2004 The UbixOS Project + +# Include Global 'Source' Options +include ../../Makefile.incl +include ../Makefile.incl + +#Linker +LD = ld + +#Binary File Name +BINARY = mount + +#Delete Program +REMOVE = rm -f + +#Objects +OBJS = main.o + +LIBRARIES = ../../lib/libc_old/libc_old.so + +# Link The Binary +$(BINARY) : $(OBJS) + $(CC) $(CFLAGS) -o ../../build/bin/$@ $(STARTUP) $(LIBRARIES) $(OBJS) + strip $(BINARY) + +# Compile the source files +.cc.o: + $(CXX) -Wall -O $(CFLAGS) $(INCLUDES) -c -o $@ $< + +.cc.s: + $(CXX) -Wall -O $(CFLAGS) $(INCLUDES) -S -o $@ $< + +.c.o: + $(CC) -Wall -O $(CFLAGS) $(INCLUDES) -c -o $@ $< + +.c.s: + $(CC) -Wall -O $(CFLAGS) $(INCLUDES) -S -o $@ $< + +.S.o: + $(CC) -Wall $(CLFAGS) $(INCLUDES) -c -o $@ $< + +# Clean Up The junk +clean: + $(REMOVE) $(OBJS) ../../build/bin/$(BINARY) diff --git a/bin/mount/main.c b/bin/mount/main.c new file mode 100644 index 0000000..75a03f1 --- /dev/null +++ b/bin/mount/main.c @@ -0,0 +1,28 @@ +#include +#include + +void usage(); + +int main(int argc,char * const argv[]) { + int ch = 0x0; + while ((ch = getopt(argc, argv, "adlF:fo:prwt:uv")) != -1) { + printf("[%i]\n",ch); + switch (ch) { + default: + usage(); + } + argc -= optind; + argv += optind; + } + return(0x0); + } + +void usage() { + + (void)printf("%s\n%s\n%s\n", +"usage: mount [-adflpruvw] [-F fstab] [-o options] [-t ufs | external_type]", +" mount [-dfpruvw] special | node", +" mount [-dfpruvw] [-o options] [-t ufs | external_type] special node"); + exit(1); +} + diff --git a/bin/muffin/Makefile b/bin/muffin/Makefile new file mode 100644 index 0000000..7d52000 --- /dev/null +++ b/bin/muffin/Makefile @@ -0,0 +1,52 @@ +# $Id: Makefile 119 2016-01-14 03:06:36Z reddawg $ +# Application Makefile (C) 2002 The UbixOS Project + +# Include Global 'Source' Options +include ../../Makefile.incl +include ../Makefile.incl + +#Compiler Flags +CFLAGS = -DNOBOOL -fno-builtin -fno-exceptions -nostdlib -nostdinc + +#Linker +LD = ld + +#Binary File Name +BINARY = muffin + +#Delete Program +REMOVE = rm -f + +#Objects +OBJS = main.o + +#Libraries +LIBRARIES2 = ../../lib/objgfx40/*.o ../../lib/libcpp/*.o + +#Include +INCLUDE = -I../../lib/libc/include -I../../lib/libcpp/include -I../../lib/objgfx40 + +# Link The Binary +$(BINARY) : $(OBJS) + $(CC) $(CFLAGS) -o ../../build/bin/$@ $(STARTUP) $(LIBRARIES) $(LIBRARIES2) $(OBJS) + strip $(BINARY) + +# Compile the source files +.cc.o: + $(CXX) -Wall -fomit-frame-pointer -O $(CFLAGS) $(INCLUDE) -c -o $@ $< + +.cc.s: + $(CXX) -Wall -fomit-frame-pointer -O $(CFLAGS) $(INCLUDE) -S -o $@ $< + +.c.o: + $(CC) -Wall -O $(CFLAGS) $(INCLUDE) -c -o $@ $< + +.c.s: + $(CC) -Wall -fomit-frame-pointer -O $(CFLAGS) $(INCLUDE) -S -o $@ $< + +.S.o: + $(CC) -Wall -fomit-frame-pointer $(INCLUDE) -c -o $@ $< + +# Clean Up The junk +clean: + $(REMOVE) $(OBJS) ../../build/bin/$(BINARY) diff --git a/bin/muffin/main.cc b/bin/muffin/main.cc new file mode 100644 index 0000000..30868da --- /dev/null +++ b/bin/muffin/main.cc @@ -0,0 +1,35 @@ +#include +extern "C" { + #include + #include + #include + } + +int main() { + vWindow *window = new vWindow(); + uInt16 i = 0x0; + uInt16 ii = 0x0; + uInt16 iii = 0x0; + if (fork() == 0x0) { + window->vCreate(); + window->vSDECommand(1); + while (1) { + for (i=0x2;i<0xFF;i += 16) { + for (ii=0x0;ii<0xFF;ii+= 16) { + for (iii= 0x0;iii< 0xFF;iii+= 16) { + window->Clear(window->Pack(i,ii,iii)); + window->FillRect(50, 50, 100, 100, window->Pack(255, 0, 0)); + window->FillRect(50, 50, 100, 100, window->Pack(255, 0, 0)); + window->FillRect(100, 50, 150, 100, window->Pack(0, 255, 0)); + window->FillRect(150, 50, 200, 100, window->Pack(0, 0, 255)); + window->FillRect(200, 50, 250, 100, window->Pack(0, 0, 0)); + window->FillRect(250, 50, 300, 100, window->Pack(255, 255, 255)); + window->vSDECommand(3); + } + } + } + } + window->vSDECommand(4); + } + return(0); + } diff --git a/bin/rtld-elf/Makefile b/bin/rtld-elf/Makefile new file mode 100644 index 0000000..734c27d --- /dev/null +++ b/bin/rtld-elf/Makefile @@ -0,0 +1,59 @@ +# $Id: Makefile 115 2016-01-14 02:55:19Z reddawg $ +# Application Makefile (C) 2002-2004 The UbixOS Project + +# Include Global 'Source' Options +include ../../Makefile.incl +include ../Makefile.incl + +INCLUDES = -I../../include.new -I./ + +CFLAGS+= -Wall -DFREEBSD_ELF -DIN_RTLD -DPIC +CFLAGS = -O2 -fno-strict-aliasing -pipe -Wall -DFREEBSD_ELF -DIN_RTLD -I./ -fpic -DPIC -std=gnu99 -Wformat=2 -Wno-format-extra-args -Werror -DDEBUG +#MrOlsen 2016-01-13 CFLAGS = -O2 -fno-strict-aliasing -pipe -Wall -DFREEBSD_ELF -DIN_RTLD -I./ -fpic -elf -DPIC -std=gnu99 -Wformat=2 -Wno-format-extra-args -Werror -DDEBUG + + +#Linker +LD = ld + +#Binary File Name +OUTPUT = ld-elf.so.1 + +#Delete Program +REMOVE = rm -f + +#Objects +OBJS = rtld_start.o reloc.o rtld.o rtld_lock.o map_object.o malloc.o xmalloc.o debug.o libmap.o + +LIBRARIES = #../../lib/libc/libc.so + + +# Link The Binary +$(OUTPUT) : $(OBJS) +# $(CC) -fpic -nostdlib -shared -Wl,-soname,$(OUTPUT) -e .rtld_start -o $(OUTPUT) $(OBJS) $(LIBRARIES) $(SUBS) +# $(CC) $(CFLAGS) -nostdlib -e .rtld_start -elf -shared -Wl,-Bsymbolic -o $(OUTPUT) $(OBJS) -lc_pic +# $(CC) $(CFLAGS) -nostdlib -e .rtld_start -elf -shared -Wl,-Bsymbolic -o $(OUTPUT) $(OBJS) ./libc_pic.a #-lc_pic + $(CC) $(CFLAGS) -nostdlib -e .rtld_start -elf -shared -Wl,-Bsymbolic -o ../../build/libexec/$(OUTPUT) $(OBJS) ../../lib/libc/pic.a #-lc_pic +# strip $(OUTPUT) + +# Compile the source files +.cpp.o: + $(CXX) -Wall -O $(CFLAGS) $(INCLUDES) -c -o $@ $< + +.cc.o: + $(CXX) -Wall -O $(CFLAGS) $(INCLUDES) -c -o $@ $< + +.cc.s: + $(CXX) -Wall -O $(CFLAGS) $(INCLUDES) -S -o $@ $< + +.c.o: + $(CC) -Wall -O $(CFLAGS) $(INCLUDES) -c -o $@ $< + +.c.s: + $(CC) -Wall -O $(CFLAGS) $(INCLUDES) -S -o $@ $< + +.S.o: + $(CC) -Wall $(CLFAGS) $(INCLUDES) -c -o $@ $< + +# Clean Up The junk +clean: + $(REMOVE) $(OBJS) $(OUTPUT) diff --git a/bin/rtld-elf/debug.c b/bin/rtld-elf/debug.c new file mode 100644 index 0000000..3a83b66 --- /dev/null +++ b/bin/rtld-elf/debug.c @@ -0,0 +1,143 @@ +/*- + * Copyright 1996-1998 John D. Polstra. + * 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. + * + * $FreeBSD: src/libexec/rtld-elf/debug.c,v 1.4 2003/06/19 16:09:18 mdodd Exp $ + */ + +/* + * Support for printing debugging messages. + */ + +#include +#include + +#include "debug.h" +#include "rtld.h" + +static const char rel_header[] = + " symbol name r_info r_offset st_value st_size address value\n" + " ------------------------------------------------------------------------------\n"; +static const char rel_format[] = " %-25s %6lx %08lx %08lx %7d %10p %08lx\n"; + +int debug = 0; + +void +debug_printf(const char *format, ...) +{ + if (debug) { + va_list ap; + va_start(ap, format); + + fflush(stdout); + vfprintf(stderr, format, ap); + putc('\n', stderr); + + va_end(ap); + } +} + +void +dump_relocations (Obj_Entry *obj0) +{ + Obj_Entry *obj; + + for (obj = obj0; obj != NULL; obj = obj->next) { + dump_obj_relocations(obj); + } +} + +void +dump_obj_relocations (Obj_Entry *obj) +{ + + printf("Object \"%s\", relocbase %p\n", obj->path, obj->relocbase); + + if (obj->relsize) { + printf("Non-PLT Relocations: %ld\n", + (obj->relsize / sizeof(Elf_Rel))); + dump_Elf_Rel(obj, obj->rel, obj->relsize); + } + + if (obj->relasize) { + printf("Non-PLT Relocations with Addend: %ld\n", + (obj->relasize / sizeof(Elf_Rela))); + dump_Elf_Rela(obj, obj->rela, obj->relasize); + } + + if (obj->pltrelsize) { + printf("PLT Relocations: %ld\n", + (obj->pltrelsize / sizeof(Elf_Rel))); + dump_Elf_Rel(obj, obj->pltrel, obj->pltrelsize); + } + + if (obj->pltrelasize) { + printf("PLT Relocations with Addend: %ld\n", + (obj->pltrelasize / sizeof(Elf_Rela))); + dump_Elf_Rela(obj, obj->pltrela, obj->pltrelasize); + } +} + +void +dump_Elf_Rel (Obj_Entry *obj, const Elf_Rel *rel0, u_long relsize) +{ + const Elf_Rel *rel; + const Elf_Rel *rellim; + const Elf_Sym *sym; + Elf_Addr *dstaddr; + + printf("%s", rel_header); + rellim = (const Elf_Rel *)((const char *)rel0 + relsize); + for (rel = rel0; rel < rellim; rel++) { + dstaddr = (Elf_Addr *)(obj->relocbase + rel->r_offset); + sym = obj->symtab + ELF_R_SYM(rel->r_info); + printf(rel_format, + obj->strtab + sym->st_name, + (u_long)rel->r_info, (u_long)rel->r_offset, + (u_long)sym->st_value, (int)sym->st_size, + dstaddr, (u_long)*dstaddr); + } + return; +} + +void +dump_Elf_Rela (Obj_Entry *obj, const Elf_Rela *rela0, u_long relasize) +{ + const Elf_Rela *rela; + const Elf_Rela *relalim; + const Elf_Sym *sym; + Elf_Addr *dstaddr; + + printf("%s", rel_header); + relalim = (const Elf_Rela *)((const char *)rela0 + relasize); + for (rela = rela0; rela < relalim; rela++) { + dstaddr = (Elf_Addr *)(obj->relocbase + rela->r_offset); + sym = obj->symtab + ELF_R_SYM(rela->r_info); + printf(rel_format, + obj->strtab + sym->st_name, + (u_long)rela->r_info, (u_long)rela->r_offset, + (u_long)sym->st_value, (int)sym->st_size, + dstaddr, (u_long)*dstaddr); + } + return; +} diff --git a/bin/rtld-elf/debug.h b/bin/rtld-elf/debug.h new file mode 100644 index 0000000..68faa0a --- /dev/null +++ b/bin/rtld-elf/debug.h @@ -0,0 +1,66 @@ +/*- + * Copyright 1996-1998 John D. Polstra. + * 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. + * + * $FreeBSD: src/libexec/rtld-elf/debug.h,v 1.6 2004/03/21 01:21:26 peter Exp $ + */ + +/* + * Support for printing debugging messages. + */ + +#ifndef DEBUG_H +#define DEBUG_H 1 + +#ifndef __GNUC__ +#error "This file must be compiled with GCC" +#endif + +#include + +#include +#include + +extern void debug_printf(const char *, ...) __printflike(1, 2); +extern int debug; + +#ifdef DEBUG +#define dbg(format, args...) debug_printf(format , ## args) +#else +#define dbg(format, args...) ((void) 0) +#endif + +#ifndef COMPAT_32BIT +#define _MYNAME "ld-elf.so.1" +#else +#define _MYNAME "ld-elf32.so.1" +#endif + +#define assert(cond) ((cond) ? (void) 0 : \ + (msg(_MYNAME ": assert failed: " __FILE__ ":" \ + __XSTRING(__LINE__) "\n"), abort())) +#define msg(s) write(STDOUT_FILENO, s, strlen(s)) +#define trace() msg(_MYNAME ": " __XSTRING(__LINE__) "\n") + + +#endif /* DEBUG_H */ diff --git a/bin/rtld-elf/libmap.c b/bin/rtld-elf/libmap.c new file mode 100644 index 0000000..b78fe4c --- /dev/null +++ b/bin/rtld-elf/libmap.c @@ -0,0 +1,371 @@ +/* + * $FreeBSD: src/libexec/rtld-elf/libmap.c,v 1.14 2005/02/04 02:46:41 mdodd Exp $ + */ + +#include +#include +#include +#include +#include +#include + +#include "debug.h" +#include "rtld.h" +#include "libmap.h" + +#ifndef _PATH_LIBMAP_CONF +#define _PATH_LIBMAP_CONF "/etc/libmap.conf" +#endif + +#ifdef COMPAT_32BIT +#undef _PATH_LIBMAP_CONF +#define _PATH_LIBMAP_CONF "/etc/libmap32.conf" +#endif + +TAILQ_HEAD(lm_list, lm); +struct lm { + char *f; + char *t; + + TAILQ_ENTRY(lm) lm_link; +}; + +TAILQ_HEAD(lmp_list, lmp) lmp_head = TAILQ_HEAD_INITIALIZER(lmp_head); +struct lmp { + char *p; + enum { T_EXACT=0, T_BASENAME, T_DIRECTORY } type; + struct lm_list lml; + TAILQ_ENTRY(lmp) lmp_link; +}; + +static int lm_count; + +static void lmc_parse (FILE *); +static void lm_add (const char *, const char *, const char *); +static void lm_free (struct lm_list *); +static char * lml_find (struct lm_list *, const char *); +static struct lm_list * lmp_find (const char *); +static struct lm_list * lmp_init (char *); +static const char * quickbasename (const char *); +static int readstrfn (void * cookie, char *buf, int len); +static int closestrfn (void * cookie); + +#define iseol(c) (((c) == '#') || ((c) == '\0') || \ + ((c) == '\n') || ((c) == '\r')) + +int +lm_init (char *libmap_override) +{ + FILE *fp; + + dbg("%s(\"%s\")", __func__, libmap_override); + + TAILQ_INIT(&lmp_head); + + fp = fopen(_PATH_LIBMAP_CONF, "r"); + if (fp) { + lmc_parse(fp); + fclose(fp); + } + + if (libmap_override) { + char *p; + /* do some character replacement to make $LIBMAP look like a + text file, then "open" it with funopen */ + libmap_override = xstrdup(libmap_override); + + for (p = libmap_override; *p; p++) { + switch (*p) { + case '=': + *p = ' '; break; + case ',': + *p = '\n'; break; + } + } + fp = funopen(libmap_override, readstrfn, NULL, NULL, closestrfn); + if (fp) { + lmc_parse(fp); + fclose(fp); + } + } + + return (lm_count == 0); +} + +static void +lmc_parse (FILE *fp) +{ + char *cp; + char *f, *t, *c, *p; + char prog[MAXPATHLEN]; + char line[MAXPATHLEN + 2]; + + dbg("%s(%p)", __func__, fp); + + p = NULL; + while ((cp = fgets(line, MAXPATHLEN + 1, fp)) != NULL) { + t = f = c = NULL; + + /* Skip over leading space */ + while (isspace(*cp)) cp++; + + /* Found a comment or EOL */ + if (iseol(*cp)) continue; + + /* Found a constraint selector */ + if (*cp == '[') { + cp++; + + /* Skip leading space */ + while (isspace(*cp)) cp++; + + /* Found comment, EOL or end of selector */ + if (iseol(*cp) || *cp == ']') + continue; + + c = cp++; + /* Skip to end of word */ + while (!isspace(*cp) && !iseol(*cp) && *cp != ']') + cp++; + + /* Skip and zero out trailing space */ + while (isspace(*cp)) *cp++ = '\0'; + + /* Check if there is a closing brace */ + if (*cp != ']') continue; + + /* Terminate string if there was no trailing space */ + *cp++ = '\0'; + + /* + * There should be nothing except whitespace or comment + from this point to the end of the line. + */ + while(isspace(*cp)) cp++; + if (!iseol(*cp)) continue; + + strcpy(prog, c); + p = prog; + continue; + } + + /* Parse the 'from' candidate. */ + f = cp++; + while (!isspace(*cp) && !iseol(*cp)) cp++; + + /* Skip and zero out the trailing whitespace */ + while (isspace(*cp)) *cp++ = '\0'; + + /* Found a comment or EOL */ + if (iseol(*cp)) continue; + + /* Parse 'to' mapping */ + t = cp++; + while (!isspace(*cp) && !iseol(*cp)) cp++; + + /* Skip and zero out the trailing whitespace */ + while (isspace(*cp)) *cp++ = '\0'; + + /* Should be no extra tokens at this point */ + if (!iseol(*cp)) continue; + + *cp = '\0'; + lm_add(p, f, t); + } +} + +static void +lm_free (struct lm_list *lml) +{ + struct lm *lm; + + dbg("%s(%p)", __func__, lml); + + while (!TAILQ_EMPTY(lml)) { + lm = TAILQ_FIRST(lml); + TAILQ_REMOVE(lml, lm, lm_link); + free(lm->f); + free(lm->t); + free(lm); + } + return; +} + +void +lm_fini (void) +{ + struct lmp *lmp; + + dbg("%s()", __func__); + + while (!TAILQ_EMPTY(&lmp_head)) { + lmp = TAILQ_FIRST(&lmp_head); + TAILQ_REMOVE(&lmp_head, lmp, lmp_link); + free(lmp->p); + lm_free(&lmp->lml); + free(lmp); + } + return; +} + +static void +lm_add (const char *p, const char *f, const char *t) +{ + struct lm_list *lml; + struct lm *lm; + + if (p == NULL) + p = "$DEFAULT$"; + + dbg("%s(\"%s\", \"%s\", \"%s\")", __func__, p, f, t); + + if ((lml = lmp_find(p)) == NULL) + lml = lmp_init(xstrdup(p)); + + lm = xmalloc(sizeof(struct lm)); + lm->f = xstrdup(f); + lm->t = xstrdup(t); + TAILQ_INSERT_HEAD(lml, lm, lm_link); + lm_count++; +} + +char * +lm_find (const char *p, const char *f) +{ + struct lm_list *lml; + char *t; + + dbg("%s(\"%s\", \"%s\")", __func__, p, f); + + if (p != NULL && (lml = lmp_find(p)) != NULL) { + t = lml_find(lml, f); + if (t != NULL) { + /* + * Add a global mapping if we have + * a successful constrained match. + */ + lm_add(NULL, f, t); + return (t); + } + } + lml = lmp_find("$DEFAULT$"); + if (lml != NULL) + return (lml_find(lml, f)); + else + return (NULL); +} + +/* Given a libmap translation list and a library name, return the + replacement library, or NULL */ +#ifdef COMPAT_32BIT +char * +lm_findn (const char *p, const char *f, const int n) +{ + char pathbuf[64], *s, *t; + + if (n < sizeof(pathbuf) - 1) { + memcpy(pathbuf, f, n); + pathbuf[n] = '\0'; + s = pathbuf; + } else { + s = xmalloc(n + 1); + strcpy(s, f); + } + t = lm_find(p, s); + if (s != pathbuf) + free(s); + return (t); +} +#endif + +static char * +lml_find (struct lm_list *lmh, const char *f) +{ + struct lm *lm; + + dbg("%s(%p, \"%s\")", __func__, lmh, f); + + TAILQ_FOREACH(lm, lmh, lm_link) + if (strcmp(f, lm->f) == 0) + return (lm->t); + return (NULL); +} + +/* Given an executable name, return a pointer to the translation list or + NULL if no matches */ +static struct lm_list * +lmp_find (const char *n) +{ + struct lmp *lmp; + + dbg("%s(\"%s\")", __func__, n); + + TAILQ_FOREACH(lmp, &lmp_head, lmp_link) + if ((lmp->type == T_EXACT && strcmp(n, lmp->p) == 0) || + (lmp->type == T_DIRECTORY && strncmp(n, lmp->p, strlen(lmp->p)) == 0) || + (lmp->type == T_BASENAME && strcmp(quickbasename(n), lmp->p) == 0)) + return (&lmp->lml); + return (NULL); +} + +static struct lm_list * +lmp_init (char *n) +{ + struct lmp *lmp; + + dbg("%s(\"%s\")", __func__, n); + + lmp = xmalloc(sizeof(struct lmp)); + lmp->p = n; + if (n[strlen(n)-1] == '/') + lmp->type = T_DIRECTORY; + else if (strchr(n,'/') == NULL) + lmp->type = T_BASENAME; + else + lmp->type = T_EXACT; + TAILQ_INIT(&lmp->lml); + TAILQ_INSERT_HEAD(&lmp_head, lmp, lmp_link); + + return (&lmp->lml); +} + +/* libc basename is overkill. Return a pointer to the character after the + last /, or the original string if there are no slashes. */ +static const char * +quickbasename (const char *path) +{ + const char *p = path; + for (; *path; path++) { + if (*path == '/') + p = path+1; + } + return (p); +} + +static int +readstrfn(void * cookie, char *buf, int len) +{ + static char *current; + static int left; + int copied; + + copied = 0; + if (!current) { + current = cookie; + left = strlen(cookie); + } + while (*current && left && len) { + *buf++ = *current++; + left--; + len--; + copied++; + } + return copied; +} + +static int +closestrfn(void * cookie) +{ + free(cookie); + return 0; +} diff --git a/bin/rtld-elf/libmap.h b/bin/rtld-elf/libmap.h new file mode 100644 index 0000000..6b0991d --- /dev/null +++ b/bin/rtld-elf/libmap.h @@ -0,0 +1,10 @@ +/* + * $FreeBSD: src/libexec/rtld-elf/libmap.h,v 1.4 2005/02/04 02:46:41 mdodd Exp $ + */ + +int lm_init (char *); +void lm_fini (void); +char * lm_find (const char *, const char *); +#ifdef COMPAT_32BIT +char * lm_findn (const char *, const char *, const int); +#endif diff --git a/bin/rtld-elf/malloc.c b/bin/rtld-elf/malloc.c new file mode 100644 index 0000000..3c43e5f --- /dev/null +++ b/bin/rtld-elf/malloc.c @@ -0,0 +1,491 @@ +/*- + * Copyright (c) 1983 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 defined(LIBC_SCCS) && !defined(lint) +/*static char *sccsid = "from: @(#)malloc.c 5.11 (Berkeley) 2/23/91";*/ +static char *rcsid = "$FreeBSD: releng/10.2/libexec/rtld-elf/malloc.c 281452 2015-04-12 06:43:13Z kib $"; +#endif /* LIBC_SCCS and not lint */ + +/* + * malloc.c (Caltech) 2/21/82 + * Chris Kingsley, kingsley@cit-20. + * + * This is a very fast storage allocator. It allocates blocks of a small + * number of different sizes, and keeps free lists of each size. Blocks that + * don't exactly fit are passed up to the next larger size. In this + * implementation, the available sizes are 2^n-4 (or 2^n-10) bytes long. + * This is designed for use in a virtual memory environment. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "rtld_printf.h" + +static void morecore(); +static int findbucket(); + +/* + * Pre-allocate mmap'ed pages + */ +#define NPOOLPAGES (32*1024/pagesz) +static caddr_t pagepool_start, pagepool_end; +static int morepages(); + +/* + * The overhead on a block is at least 4 bytes. When free, this space + * contains a pointer to the next free block, and the bottom two bits must + * be zero. When in use, the first byte is set to MAGIC, and the second + * byte is the size index. The remaining bytes are for alignment. + * If range checking is enabled then a second word holds the size of the + * requested block, less 1, rounded up to a multiple of sizeof(RMAGIC). + * The order of elements is critical: ov_magic must overlay the low order + * bits of ov_next, and ov_magic can not be a valid ov_next bit pattern. + */ +union overhead { + union overhead *ov_next; /* when free */ + struct { + u_char ovu_magic; /* magic number */ + u_char ovu_index; /* bucket # */ +#ifdef RCHECK + u_short ovu_rmagic; /* range magic number */ + u_int ovu_size; /* actual block size */ +#endif + } ovu; +#define ov_magic ovu.ovu_magic +#define ov_index ovu.ovu_index +#define ov_rmagic ovu.ovu_rmagic +#define ov_size ovu.ovu_size +}; + +#define MAGIC 0xef /* magic # on accounting info */ +#define RMAGIC 0x5555 /* magic # on range info */ + +#ifdef RCHECK +#define RSLOP sizeof (u_short) +#else +#define RSLOP 0 +#endif + +/* + * nextf[i] is the pointer to the next free block of size 2^(i+3). The + * smallest allocatable block is 8 bytes. The overhead information + * precedes the data area returned to the user. + */ +#define NBUCKETS 30 +static union overhead *nextf[NBUCKETS]; + +static int pagesz; /* page size */ +static int pagebucket; /* page size bucket */ + +#ifdef MSTATS +/* + * nmalloc[i] is the difference between the number of mallocs and frees + * for a given block size. + */ +static u_int nmalloc[NBUCKETS]; +#include +#endif + +#if defined(MALLOC_DEBUG) || defined(RCHECK) +#define ASSERT(p) if (!(p)) botch("p") +#include +static void +botch(s) + char *s; +{ + fprintf(stderr, "\r\nassertion botched: %s\r\n", s); + (void) fflush(stderr); /* just in case user buffered it */ + abort(); +} +#else +#define ASSERT(p) +#endif + +/* Debugging stuff */ +#define TRACE() rtld_printf("TRACE %s:%d\n", __FILE__, __LINE__) + +/* + * The array of supported page sizes is provided by the user, i.e., the + * program that calls this storage allocator. That program must initialize + * the array before making its first call to allocate storage. The array + * must contain at least one page size. The page sizes must be stored in + * increasing order. + */ +extern size_t *pagesizes; + +void * +malloc(nbytes) + size_t nbytes; +{ + register union overhead *op; + register int bucket; + register long n; + register unsigned amt; + + /* + * First time malloc is called, setup page size and + * align break pointer so all data will be page aligned. + */ + if (pagesz == 0) { + pagesz = n = pagesizes[0]; + if (morepages(NPOOLPAGES) == 0) + return NULL; + op = (union overhead *)(pagepool_start); + n = n - sizeof (*op) - ((long)op & (n - 1)); + if (n < 0) + n += pagesz; + if (n) { + pagepool_start += n; + } + bucket = 0; + amt = 8; + while ((unsigned)pagesz > amt) { + amt <<= 1; + bucket++; + } + pagebucket = bucket; + } + /* + * Convert amount of memory requested into closest block size + * stored in hash buckets which satisfies request. + * Account for space used per block for accounting. + */ + if (nbytes <= (unsigned long)(n = pagesz - sizeof (*op) - RSLOP)) { +#ifndef RCHECK + amt = 8; /* size of first bucket */ + bucket = 0; +#else + amt = 16; /* size of first bucket */ + bucket = 1; +#endif + n = -(sizeof (*op) + RSLOP); + } else { + amt = pagesz; + bucket = pagebucket; + } + while (nbytes > amt + n) { + amt <<= 1; + if (amt == 0) + return (NULL); + bucket++; + } + /* + * If nothing in hash bucket right now, + * request more memory from the system. + */ + if ((op = nextf[bucket]) == NULL) { + morecore(bucket); + if ((op = nextf[bucket]) == NULL) + return (NULL); + } + /* remove from linked list */ + nextf[bucket] = op->ov_next; + op->ov_magic = MAGIC; + op->ov_index = bucket; +#ifdef MSTATS + nmalloc[bucket]++; +#endif +#ifdef RCHECK + /* + * Record allocated size of block and + * bound space with magic numbers. + */ + op->ov_size = (nbytes + RSLOP - 1) & ~(RSLOP - 1); + op->ov_rmagic = RMAGIC; + *(u_short *)((caddr_t)(op + 1) + op->ov_size) = RMAGIC; +#endif + return ((char *)(op + 1)); +} + +void * +calloc(size_t num, size_t size) +{ + void *ret; + + if (size != 0 && (num * size) / size != num) { + /* size_t overflow. */ + return (NULL); + } + + if ((ret = malloc(num * size)) != NULL) + memset(ret, 0, num * size); + + return (ret); +} + +/* + * Allocate more memory to the indicated bucket. + */ +static void +morecore(bucket) + int bucket; +{ + register union overhead *op; + register int sz; /* size of desired block */ + int amt; /* amount to allocate */ + int nblks; /* how many blocks we get */ + + /* + * sbrk_size <= 0 only for big, FLUFFY, requests (about + * 2^30 bytes on a VAX, I think) or for a negative arg. + */ + sz = 1 << (bucket + 3); +#ifdef MALLOC_DEBUG + ASSERT(sz > 0); +#else + if (sz <= 0) + return; +#endif + if (sz < pagesz) { + amt = pagesz; + nblks = amt / sz; + } else { + amt = sz + pagesz; + nblks = 1; + } + if (amt > pagepool_end - pagepool_start) + if (morepages(amt/pagesz + NPOOLPAGES) == 0) + return; + op = (union overhead *)pagepool_start; + pagepool_start += amt; + + /* + * Add new memory allocated to that on + * free list for this hash bucket. + */ + nextf[bucket] = op; + while (--nblks > 0) { + op->ov_next = (union overhead *)((caddr_t)op + sz); + op = (union overhead *)((caddr_t)op + sz); + } +} + +void +free(cp) + void *cp; +{ + register int size; + register union overhead *op; + + if (cp == NULL) + return; + op = (union overhead *)((caddr_t)cp - sizeof (union overhead)); +#ifdef MALLOC_DEBUG + ASSERT(op->ov_magic == MAGIC); /* make sure it was in use */ +#else + if (op->ov_magic != MAGIC) + return; /* sanity */ +#endif +#ifdef RCHECK + ASSERT(op->ov_rmagic == RMAGIC); + ASSERT(*(u_short *)((caddr_t)(op + 1) + op->ov_size) == RMAGIC); +#endif + size = op->ov_index; + ASSERT(size < NBUCKETS); + op->ov_next = nextf[size]; /* also clobbers ov_magic */ + nextf[size] = op; +#ifdef MSTATS + nmalloc[size]--; +#endif +} + +/* + * When a program attempts "storage compaction" as mentioned in the + * old malloc man page, it realloc's an already freed block. Usually + * this is the last block it freed; occasionally it might be farther + * back. We have to search all the free lists for the block in order + * to determine its bucket: 1st we make one pass thru the lists + * checking only the first block in each; if that fails we search + * ``realloc_srchlen'' blocks in each list for a match (the variable + * is extern so the caller can modify it). If that fails we just copy + * however many bytes was given to realloc() and hope it's not huge. + */ +int realloc_srchlen = 4; /* 4 should be plenty, -1 =>'s whole list */ + +void * +realloc(cp, nbytes) + void *cp; + size_t nbytes; +{ + register u_int onb; + register int i; + union overhead *op; + char *res; + int was_alloced = 0; + + if (cp == NULL) + return (malloc(nbytes)); + op = (union overhead *)((caddr_t)cp - sizeof (union overhead)); + if (op->ov_magic == MAGIC) { + was_alloced++; + i = op->ov_index; + } else { + /* + * Already free, doing "compaction". + * + * Search for the old block of memory on the + * free list. First, check the most common + * case (last element free'd), then (this failing) + * the last ``realloc_srchlen'' items free'd. + * If all lookups fail, then assume the size of + * the memory block being realloc'd is the + * largest possible (so that all "nbytes" of new + * memory are copied into). Note that this could cause + * a memory fault if the old area was tiny, and the moon + * is gibbous. However, that is very unlikely. + */ + if ((i = findbucket(op, 1)) < 0 && + (i = findbucket(op, realloc_srchlen)) < 0) + i = NBUCKETS; + } + onb = 1 << (i + 3); + if (onb < (u_int)pagesz) + onb -= sizeof (*op) + RSLOP; + else + onb += pagesz - sizeof (*op) - RSLOP; + /* avoid the copy if same size block */ + if (was_alloced) { + if (i) { + i = 1 << (i + 2); + if (i < pagesz) + i -= sizeof (*op) + RSLOP; + else + i += pagesz - sizeof (*op) - RSLOP; + } + if (nbytes <= onb && nbytes > (size_t)i) { +#ifdef RCHECK + op->ov_size = (nbytes + RSLOP - 1) & ~(RSLOP - 1); + *(u_short *)((caddr_t)(op + 1) + op->ov_size) = RMAGIC; +#endif + return(cp); + } else + free(cp); + } + if ((res = malloc(nbytes)) == NULL) + return (NULL); + if (cp != res) /* common optimization if "compacting" */ + bcopy(cp, res, (nbytes < onb) ? nbytes : onb); + return (res); +} + +/* + * Search ``srchlen'' elements of each free list for a block whose + * header starts at ``freep''. If srchlen is -1 search the whole list. + * Return bucket number, or -1 if not found. + */ +static int +findbucket(freep, srchlen) + union overhead *freep; + int srchlen; +{ + register union overhead *p; + register int i, j; + + for (i = 0; i < NBUCKETS; i++) { + j = 0; + for (p = nextf[i]; p && j != srchlen; p = p->ov_next) { + if (p == freep) + return (i); + j++; + } + } + return (-1); +} + +#ifdef MSTATS +/* + * mstats - print out statistics about malloc + * + * Prints two lines of numbers, one showing the length of the free list + * for each size category, the second showing the number of mallocs - + * frees for each size category. + */ +mstats(s) + char *s; +{ + register int i, j; + register union overhead *p; + int totfree = 0, + totused = 0; + + fprintf(stderr, "Memory allocation statistics %s\nfree:\t", s); + for (i = 0; i < NBUCKETS; i++) { + for (j = 0, p = nextf[i]; p; p = p->ov_next, j++) + ; + fprintf(stderr, " %d", j); + totfree += j * (1 << (i + 3)); + } + fprintf(stderr, "\nused:\t"); + for (i = 0; i < NBUCKETS; i++) { + fprintf(stderr, " %d", nmalloc[i]); + totused += nmalloc[i] * (1 << (i + 3)); + } + fprintf(stderr, "\n\tTotal in use: %d, total free: %d\n", + totused, totfree); +} +#endif + + +static int +morepages(n) +int n; +{ + int fd = -1; + int offset; + + if (pagepool_end - pagepool_start > pagesz) { + caddr_t addr = (caddr_t) + (((long)pagepool_start + pagesz - 1) & ~(pagesz - 1)); + if (munmap(addr, pagepool_end - addr) != 0) + rtld_fdprintf(STDERR_FILENO, "morepages: munmap %p", + addr); + } + + offset = (long)pagepool_start - ((long)pagepool_start & ~(pagesz - 1)); + + if ((pagepool_start = mmap(0, n * pagesz, + PROT_READ|PROT_WRITE, + MAP_ANON|MAP_COPY, fd, 0)) == (caddr_t)-1) { + rtld_printf("Cannot map anonymous memory\n"); + return 0; + } + pagepool_end = pagepool_start + n * pagesz; + pagepool_start += offset; + + return n; +} diff --git a/bin/rtld-elf/map_object.c b/bin/rtld-elf/map_object.c new file mode 100644 index 0000000..8d5f24a --- /dev/null +++ b/bin/rtld-elf/map_object.c @@ -0,0 +1,372 @@ +/*- + * Copyright 1996-1998 John D. Polstra. + * 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. + * + * $FreeBSD: src/libexec/rtld-elf/map_object.c,v 1.16 2005/02/27 12:55:40 dfr Exp $ + */ + +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "debug.h" +#include "rtld.h" + +static Elf_Ehdr *get_elf_header (int, const char *); +static int convert_prot(int); /* Elf flags -> mmap protection */ +static int convert_flags(int); /* Elf flags -> mmap flags */ + +/* + * Map a shared object into memory. The "fd" argument is a file descriptor, + * which must be open on the object and positioned at its beginning. + * The "path" argument is a pathname that is used only for error messages. + * + * The return value is a pointer to a newly-allocated Obj_Entry structure + * for the shared object. Returns NULL on failure. + */ +Obj_Entry * +map_object(int fd, const char *path, const struct stat *sb) +{ + Obj_Entry *obj; + Elf_Ehdr *hdr; + int i; + Elf_Phdr *phdr; + Elf_Phdr *phlimit; + Elf_Phdr **segs; + int nsegs; + Elf_Phdr *phdyn; + Elf_Phdr *phphdr; + Elf_Phdr *phinterp; + Elf_Phdr *phtls; + caddr_t mapbase; + size_t mapsize; + Elf_Off base_offset; + Elf_Addr base_vaddr; + Elf_Addr base_vlimit; + caddr_t base_addr; + Elf_Off data_offset; + Elf_Addr data_vaddr; + Elf_Addr data_vlimit; + caddr_t data_addr; + int data_prot; + int data_flags; + Elf_Addr clear_vaddr; + caddr_t clear_addr; + caddr_t clear_page; + size_t nclear; + Elf_Addr bss_vaddr; + Elf_Addr bss_vlimit; + caddr_t bss_addr; + + hdr = get_elf_header(fd, path); + if (hdr == NULL) + return (NULL); + + /* + * Scan the program header entries, and save key information. + * + * We rely on there being exactly two load segments, text and data, + * in that order. + */ + phdr = (Elf_Phdr *) ((char *)hdr + hdr->e_phoff); + phlimit = phdr + hdr->e_phnum; + nsegs = -1; + phdyn = phphdr = phinterp = phtls = NULL; + segs = alloca(sizeof(segs[0]) * hdr->e_phnum); + while (phdr < phlimit) { + switch (phdr->p_type) { + + case PT_INTERP: + phinterp = phdr; + break; + + case PT_LOAD: + segs[++nsegs] = phdr; + if (segs[nsegs]->p_align < PAGE_SIZE) { + _rtld_error("%s: PT_LOAD segment %d not page-aligned", + path, nsegs); + return NULL; + } + break; + + case PT_PHDR: + phphdr = phdr; + break; + + case PT_DYNAMIC: + phdyn = phdr; + break; + + case PT_TLS: + phtls = phdr; + break; + } + + ++phdr; + } + if (phdyn == NULL) { + _rtld_error("%s: object is not dynamically-linked", path); + return NULL; + } + + if (nsegs < 0) { + _rtld_error("%s: too few PT_LOAD segments", path); + return NULL; + } + + /* + * Map the entire address space of the object, to stake out our + * contiguous region, and to establish the base address for relocation. + */ + base_offset = trunc_page(segs[0]->p_offset); + base_vaddr = trunc_page(segs[0]->p_vaddr); + base_vlimit = round_page(segs[nsegs]->p_vaddr + segs[nsegs]->p_memsz); + mapsize = base_vlimit - base_vaddr; + base_addr = hdr->e_type == ET_EXEC ? (caddr_t) base_vaddr : NULL; + + mapbase = mmap(base_addr, mapsize, convert_prot(segs[0]->p_flags), + convert_flags(segs[0]->p_flags), fd, base_offset); + if (mapbase == (caddr_t) -1) { + _rtld_error("%s: mmap of entire address space failed: %s", + path, strerror(errno)); + return NULL; + } + if (base_addr != NULL && mapbase != base_addr) { + _rtld_error("%s: mmap returned wrong address: wanted %p, got %p", + path, base_addr, mapbase); + munmap(mapbase, mapsize); + return NULL; + } + + for (i = 0; i <= nsegs; i++) { + /* Overlay the segment onto the proper region. */ + data_offset = trunc_page(segs[i]->p_offset); + data_vaddr = trunc_page(segs[i]->p_vaddr); + data_vlimit = round_page(segs[i]->p_vaddr + segs[i]->p_filesz); + data_addr = mapbase + (data_vaddr - base_vaddr); + data_prot = convert_prot(segs[i]->p_flags); + data_flags = convert_flags(segs[i]->p_flags) | MAP_FIXED; + /* Do not call mmap on the first segment - this is redundant */ + if (i && mmap(data_addr, data_vlimit - data_vaddr, data_prot, + data_flags, fd, data_offset) == (caddr_t) -1) { + _rtld_error("%s: mmap of data failed: %s", path, strerror(errno)); + return NULL; + } + + /* Clear any BSS in the last page of the segment. */ + clear_vaddr = segs[i]->p_vaddr + segs[i]->p_filesz; + clear_addr = mapbase + (clear_vaddr - base_vaddr); + clear_page = mapbase + (trunc_page(clear_vaddr) - base_vaddr); + if ((nclear = data_vlimit - clear_vaddr) > 0) { + /* Make sure the end of the segment is writable */ + if ((data_prot & PROT_WRITE) == 0 && + -1 == mprotect(clear_page, PAGE_SIZE, data_prot|PROT_WRITE)) { + _rtld_error("%s: mprotect failed: %s", path, + strerror(errno)); + return NULL; + } + + memset(clear_addr, 0, nclear); + + /* Reset the data protection back */ + if ((data_prot & PROT_WRITE) == 0) + mprotect(clear_page, PAGE_SIZE, data_prot); + } + + /* Overlay the BSS segment onto the proper region. */ + bss_vaddr = data_vlimit; + bss_vlimit = round_page(segs[i]->p_vaddr + segs[i]->p_memsz); + bss_addr = mapbase + (bss_vaddr - base_vaddr); + if (bss_vlimit > bss_vaddr) { /* There is something to do */ + if (mmap(bss_addr, bss_vlimit - bss_vaddr, data_prot, + MAP_PRIVATE|MAP_FIXED|MAP_ANON, -1, 0) == (caddr_t) -1) { + _rtld_error("%s: mmap of bss failed: %s", path, + strerror(errno)); + return NULL; + } + } + } + + obj = obj_new(); + if (sb != NULL) { + obj->dev = sb->st_dev; + obj->ino = sb->st_ino; + } + obj->mapbase = mapbase; + obj->mapsize = mapsize; + obj->textsize = round_page(segs[0]->p_vaddr + segs[0]->p_memsz) - + base_vaddr; + obj->vaddrbase = base_vaddr; + obj->relocbase = mapbase - base_vaddr; + obj->dynamic = (const Elf_Dyn *) (obj->relocbase + phdyn->p_vaddr); + if (hdr->e_entry != 0) + obj->entry = (caddr_t) (obj->relocbase + hdr->e_entry); + if (phphdr != NULL) { + obj->phdr = (const Elf_Phdr *) (obj->relocbase + phphdr->p_vaddr); + obj->phsize = phphdr->p_memsz; + } + if (phinterp != NULL) + obj->interp = (const char *) (obj->relocbase + phinterp->p_vaddr); + if (phtls != NULL) { + tls_dtv_generation++; + obj->tlsindex = ++tls_max_index; + obj->tlssize = phtls->p_memsz; + obj->tlsalign = phtls->p_align; + obj->tlsinitsize = phtls->p_filesz; + obj->tlsinit = mapbase + phtls->p_vaddr; + } + return obj; +} + +static Elf_Ehdr * +get_elf_header (int fd, const char *path) +{ + static union { + Elf_Ehdr hdr; + char buf[PAGE_SIZE]; + } u; + ssize_t nbytes; + + if ((nbytes = read(fd, u.buf, PAGE_SIZE)) == -1) { + _rtld_error("%s: read error: %s", path, strerror(errno)); + return NULL; + } + + /* Make sure the file is valid */ + if (nbytes < (ssize_t)sizeof(Elf_Ehdr) || !IS_ELF(u.hdr)) { + _rtld_error("%s: invalid file format", path); + return NULL; + } + if (u.hdr.e_ident[EI_CLASS] != ELF_TARG_CLASS + || u.hdr.e_ident[EI_DATA] != ELF_TARG_DATA) { + _rtld_error("%s: unsupported file layout", path); + return NULL; + } + if (u.hdr.e_ident[EI_VERSION] != EV_CURRENT + || u.hdr.e_version != EV_CURRENT) { + _rtld_error("%s: unsupported file version", path); + return NULL; + } + if (u.hdr.e_type != ET_EXEC && u.hdr.e_type != ET_DYN) { + _rtld_error("%s: unsupported file type", path); + return NULL; + } + if (u.hdr.e_machine != ELF_TARG_MACH) { + _rtld_error("%s: unsupported machine", path); + return NULL; + } + + /* + * We rely on the program header being in the first page. This is + * not strictly required by the ABI specification, but it seems to + * always true in practice. And, it simplifies things considerably. + */ + if (u.hdr.e_phentsize != sizeof(Elf_Phdr)) { + _rtld_error( + "%s: invalid shared object: e_phentsize != sizeof(Elf_Phdr)", path); + return NULL; + } + if (u.hdr.e_phoff + u.hdr.e_phnum * sizeof(Elf_Phdr) > (size_t)nbytes) { + _rtld_error("%s: program header too large", path); + return NULL; + } + + return (&u.hdr); +} + +void +obj_free(Obj_Entry *obj) +{ + Objlist_Entry *elm; + + if (obj->tls_done) { + free_tls_offset(obj); + } + free(obj->path); + while (obj->needed != NULL) { + Needed_Entry *needed = obj->needed; + obj->needed = needed->next; + free(needed); + } + while (!STAILQ_EMPTY(&obj->dldags)) { + elm = STAILQ_FIRST(&obj->dldags); + STAILQ_REMOVE_HEAD(&obj->dldags, link); + free(elm); + } + while (!STAILQ_EMPTY(&obj->dagmembers)) { + elm = STAILQ_FIRST(&obj->dagmembers); + STAILQ_REMOVE_HEAD(&obj->dagmembers, link); + free(elm); + } + free(obj->origin_path); + free(obj->priv); + free(obj); +} + +Obj_Entry * +obj_new(void) +{ + Obj_Entry *obj; + + obj = CNEW(Obj_Entry); + STAILQ_INIT(&obj->dldags); + STAILQ_INIT(&obj->dagmembers); + return obj; +} + +/* + * Given a set of ELF protection flags, return the corresponding protection + * flags for MMAP. + */ +static int +convert_prot(int elfflags) +{ + int prot = 0; + if (elfflags & PF_R) + prot |= PROT_READ; + if (elfflags & PF_W) + prot |= PROT_WRITE; + if (elfflags & PF_X) + prot |= PROT_EXEC; + return prot; +} + +static int +convert_flags(int elfflags) +{ + int flags = MAP_PRIVATE; /* All mappings are private */ + + /* + * Readonly mappings are marked "MAP_NOCORE", because they can be + * reconstructed by a debugger. + */ + if (!(elfflags & PF_W)) + flags |= MAP_NOCORE; + return flags; +} diff --git a/bin/rtld-elf/reloc.c b/bin/rtld-elf/reloc.c new file mode 100644 index 0000000..ba9be47 --- /dev/null +++ b/bin/rtld-elf/reloc.c @@ -0,0 +1,367 @@ +/*- + * Copyright 1996, 1997, 1998, 1999 John D. Polstra. + * 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. + * + * $FreeBSD: src/libexec/rtld-elf/i386/reloc.c,v 1.18 2005/06/29 23:15:36 peter Exp $ + */ + +/* + * Dynamic linker for ELF. + * + * John Polstra . + */ + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "debug.h" +#include "rtld.h" + +/* + * Process the special R_386_COPY relocations in the main program. These + * copy data from a shared object into a region in the main program's BSS + * segment. + * + * Returns 0 on success, -1 on failure. + */ +int +do_copy_relocations(Obj_Entry *dstobj) +{ + const Elf_Rel *rellim; + const Elf_Rel *rel; + + assert(dstobj->mainprog); /* COPY relocations are invalid elsewhere */ + + rellim = (const Elf_Rel *) ((caddr_t) dstobj->rel + dstobj->relsize); + for (rel = dstobj->rel; rel < rellim; rel++) { + if (ELF_R_TYPE(rel->r_info) == R_386_COPY) { + void *dstaddr; + const Elf_Sym *dstsym; + const char *name; + unsigned long hash; + size_t size; + const void *srcaddr; + const Elf_Sym *srcsym; + Obj_Entry *srcobj; + + dstaddr = (void *) (dstobj->relocbase + rel->r_offset); + dstsym = dstobj->symtab + ELF_R_SYM(rel->r_info); + name = dstobj->strtab + dstsym->st_name; + hash = elf_hash(name); + size = dstsym->st_size; + + for (srcobj = dstobj->next; srcobj != NULL; srcobj = srcobj->next) + if ((srcsym = symlook_obj(name, hash, srcobj, false)) != NULL) + break; + + if (srcobj == NULL) { + _rtld_error("Undefined symbol \"%s\" referenced from COPY" + " relocation in %s", name, dstobj->path); + return -1; + } + + srcaddr = (const void *) (srcobj->relocbase + srcsym->st_value); + memcpy(dstaddr, srcaddr, size); + } + } + + return 0; +} + +/* Initialize the special GOT entries. */ +void +init_pltgot(Obj_Entry *obj) +{ + if (obj->pltgot != NULL) { + obj->pltgot[1] = (Elf_Addr) obj; + obj->pltgot[2] = (Elf_Addr) &_rtld_bind_start; + } +} + +/* Process the non-PLT relocations. */ +int +reloc_non_plt(Obj_Entry *obj, Obj_Entry *obj_rtld) +{ + const Elf_Rel *rellim; + const Elf_Rel *rel; + SymCache *cache; + int bytes = obj->nchains * sizeof(SymCache); + int r = -1; + + /* + * The dynamic loader may be called from a thread, we have + * limited amounts of stack available so we cannot use alloca(). + */ + cache = mmap(NULL, bytes, PROT_READ|PROT_WRITE, MAP_ANON, -1, 0); + if (cache == MAP_FAILED) + cache = NULL; + + rellim = (const Elf_Rel *) ((caddr_t) obj->rel + obj->relsize); + for (rel = obj->rel; rel < rellim; rel++) { + Elf_Addr *where = (Elf_Addr *) (obj->relocbase + rel->r_offset); + + switch (ELF_R_TYPE(rel->r_info)) { + + case R_386_NONE: + break; + + case R_386_32: + { + const Elf_Sym *def; + const Obj_Entry *defobj; + + def = find_symdef(ELF_R_SYM(rel->r_info), obj, &defobj, + false, cache); + + if (def == NULL) + goto done; + *where += (Elf_Addr) (defobj->relocbase + def->st_value); + } + break; + + case R_386_PC32: + /* + * I don't think the dynamic linker should ever see this + * type of relocation. But the binutils-2.6 tools sometimes + * generate it. + */ + { + const Elf_Sym *def; + const Obj_Entry *defobj; +//dbg("A.1"); + def = find_symdef(ELF_R_SYM(rel->r_info), obj, &defobj, + false, cache); +//dbg("A.2"); + if (def == NULL) + goto done; + + *where += + (Elf_Addr) (defobj->relocbase + def->st_value) - + (Elf_Addr) where; + } + break; + + case R_386_COPY: + /* + * These are deferred until all other relocations have + * been done. All we do here is make sure that the COPY + * relocation is not in a shared library. They are allowed + * only in executable files. + */ +//dbg("386_COPY"); + if (!obj->mainprog) { + _rtld_error("%s: Unexpected R_386_COPY relocation" + " in shared library", obj->path); + goto done; + } + break; + + case R_386_GLOB_DAT: + { +//dbg("386_GD"); + const Elf_Sym *def; + const Obj_Entry *defobj; + + def = find_symdef(ELF_R_SYM(rel->r_info), obj, &defobj, + false, cache); + if (def == NULL) + goto done; + + *where = (Elf_Addr) (defobj->relocbase + def->st_value); + } + break; + + case R_386_RELATIVE: + *where += (Elf_Addr) obj->relocbase; + break; + + case R_386_TLS_TPOFF: + { + const Elf_Sym *def; + const Obj_Entry *defobj; + + def = find_symdef(ELF_R_SYM(rel->r_info), obj, &defobj, + false, cache); + if (def == NULL) + goto done; + + /* + * We lazily allocate offsets for static TLS as we + * see the first relocation that references the + * TLS block. This allows us to support (small + * amounts of) static TLS in dynamically loaded + * modules. If we run out of space, we generate an + * error. + */ + if (!defobj->tls_done) { + if (!allocate_tls_offset((Obj_Entry*) defobj)) { + _rtld_error("%s: No space available for static " + "Thread Local Storage", obj->path); + goto done; + } + } + + *where += (Elf_Addr) (def->st_value - defobj->tlsoffset); + } + break; + + case R_386_TLS_DTPMOD32: + { + const Elf_Sym *def; + const Obj_Entry *defobj; + + def = find_symdef(ELF_R_SYM(rel->r_info), obj, &defobj, + false, cache); + if (def == NULL) + goto done; + + *where += (Elf_Addr) defobj->tlsindex; + } + break; + + case R_386_TLS_DTPOFF32: + { + const Elf_Sym *def; + const Obj_Entry *defobj; + + def = find_symdef(ELF_R_SYM(rel->r_info), obj, &defobj, + false, cache); + if (def == NULL) + goto done; + + *where += (Elf_Addr) def->st_value; + } + break; + + default: + _rtld_error("%s: Unsupported relocation type %d" + " in non-PLT relocations\n", obj->path, + ELF_R_TYPE(rel->r_info)); + goto done; + } + } + r = 0; +done: + if (cache) + munmap(cache, bytes); + return(r); +} + +/* Process the PLT relocations. */ +int +reloc_plt(Obj_Entry *obj) +{ + const Elf_Rel *rellim; + const Elf_Rel *rel; + + rellim = (const Elf_Rel *)((char *)obj->pltrel + obj->pltrelsize); + for (rel = obj->pltrel; rel < rellim; rel++) { + Elf_Addr *where; + + assert(ELF_R_TYPE(rel->r_info) == R_386_JMP_SLOT); + + /* Relocate the GOT slot pointing into the PLT. */ + where = (Elf_Addr *)(obj->relocbase + rel->r_offset); + *where += (Elf_Addr)obj->relocbase; + } + return 0; +} + +/* Relocate the jump slots in an object. */ +int +reloc_jmpslots(Obj_Entry *obj) +{ + const Elf_Rel *rellim; + const Elf_Rel *rel; + + if (obj->jmpslots_done) + return 0; + rellim = (const Elf_Rel *)((char *)obj->pltrel + obj->pltrelsize); + for (rel = obj->pltrel; rel < rellim; rel++) { + Elf_Addr *where, target; + const Elf_Sym *def; + const Obj_Entry *defobj; + + assert(ELF_R_TYPE(rel->r_info) == R_386_JMP_SLOT); + where = (Elf_Addr *)(obj->relocbase + rel->r_offset); + def = find_symdef(ELF_R_SYM(rel->r_info), obj, &defobj, true, NULL); + if (def == NULL) + return -1; + target = (Elf_Addr)(defobj->relocbase + def->st_value); + reloc_jmpslot(where, target, defobj, obj, rel); + } + obj->jmpslots_done = true; + return 0; +} + +void +allocate_initial_tls(Obj_Entry *objs) +{ + void* tls; + + /* + * Fix the size of the static TLS block by using the maximum + * offset allocated so far and adding a bit for dynamic modules to + * use. + */ + tls_static_space = tls_last_offset + RTLD_STATIC_TLS_EXTRA; + tls = allocate_tls(objs, NULL, 2*sizeof(Elf_Addr), sizeof(Elf_Addr)); + i386_set_gsbase(tls); +} + +/* GNU ABI */ +__attribute__((__regparm__(1))) +void *___tls_get_addr(tls_index *ti) +{ + Elf_Addr** segbase; + Elf_Addr* dtv; + + __asm __volatile("movl %%gs:0, %0" : "=r" (segbase)); + dtv = segbase[1]; + + return tls_get_addr_common(&segbase[1], ti->ti_module, ti->ti_offset); +} + +/* Sun ABI */ +void *__tls_get_addr(tls_index *ti) +{ + Elf_Addr** segbase; + Elf_Addr* dtv; + + __asm __volatile("movl %%gs:0, %0" : "=r" (segbase)); + dtv = segbase[1]; + + return tls_get_addr_common(&segbase[1], ti->ti_module, ti->ti_offset); +} diff --git a/bin/rtld-elf/rtld.c b/bin/rtld-elf/rtld.c new file mode 100644 index 0000000..789071b --- /dev/null +++ b/bin/rtld-elf/rtld.c @@ -0,0 +1,2840 @@ +/*- + * Copyright 1996, 1997, 1998, 1999, 2000 John D. Polstra. + * Copyright 2003 Alexander Kabaev . + * 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. + * + * $Id: rtld.c 114 2016-01-14 02:30:09Z reddawg $ + */ + +/* + * Dynamic linker for ELF. + * + * John Polstra . + */ + +#ifndef __GNUC__ +#error "GCC is needed to compile this file" +#endif + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "debug.h" +#include "rtld.h" +#include "libmap.h" +#include "rtld_tls.h" + +#ifndef COMPAT_32BIT +#define PATH_RTLD "/libexec/ld-elf.so.1" +#else +#define PATH_RTLD "/libexec/ld-elf32.so.1" +#endif + +/* Types. */ +typedef void (*func_ptr_type)(); +typedef void * (*path_enum_proc) (const char *path, size_t len, void *arg); + +/* + * This structure provides a reentrant way to keep a list of objects and + * check which ones have already been processed in some way. + */ +typedef struct Struct_DoneList { + const Obj_Entry **objs; /* Array of object pointers */ + unsigned int num_alloc; /* Allocated size of the array */ + unsigned int num_used; /* Number of array slots used */ +} DoneList; + +/* + * Function declarations. + */ +static const char *basename(const char *); +static void die(void); +static void digest_dynamic(Obj_Entry *, int); +static Obj_Entry *digest_phdr(const Elf_Phdr *, int, caddr_t, const char *); +static Obj_Entry *dlcheck(void *); +static int do_search_info(const Obj_Entry *obj, int, struct dl_serinfo *); +static bool donelist_check(DoneList *, const Obj_Entry *); +static void errmsg_restore(char *); +static char *errmsg_save(void); +static void *fill_search_info(const char *, size_t, void *); +static char *find_library(const char *, const Obj_Entry *); +static const char *gethints(void); +static void init_dag(Obj_Entry *); +static void init_dag1(Obj_Entry *root, Obj_Entry *obj, DoneList *); +static void init_rtld(caddr_t); +static void initlist_add_neededs(Needed_Entry *needed, Objlist *list); +static void initlist_add_objects(Obj_Entry *obj, Obj_Entry **tail, + Objlist *list); +static bool is_exported(const Elf_Sym *); +static void linkmap_add(Obj_Entry *); +static void linkmap_delete(Obj_Entry *); +static int load_needed_objects(Obj_Entry *); +static int load_preload_objects(void); +static Obj_Entry *load_object(char *); +static Obj_Entry *obj_from_addr(const void *); +static void objlist_call_fini(Objlist *); +static void objlist_call_init(Objlist *); +static void objlist_clear(Objlist *); +static Objlist_Entry *objlist_find(Objlist *, const Obj_Entry *); +static void objlist_init(Objlist *); +static void objlist_push_head(Objlist *, Obj_Entry *); +static void objlist_push_tail(Objlist *, Obj_Entry *); +static void objlist_remove(Objlist *, Obj_Entry *); +static void objlist_remove_unref(Objlist *); +static void *path_enumerate(const char *, path_enum_proc, void *); +static int relocate_objects(Obj_Entry *, bool, Obj_Entry *); +static int rtld_dirname(const char *, char *); +static void rtld_exit(void); +static char *search_library_path(const char *, const char *); +static const void **get_program_var_addr(const char *name); +static void set_program_var(const char *, const void *); +static const Elf_Sym *symlook_default(const char *, unsigned long hash, + const Obj_Entry *refobj, const Obj_Entry **defobj_out, bool in_plt); +static const Elf_Sym *symlook_list(const char *, unsigned long, + Objlist *, const Obj_Entry **, bool in_plt, DoneList *); +static void trace_loaded_objects(Obj_Entry *obj); +static void unlink_object(Obj_Entry *); +static void unload_object(Obj_Entry *); +static void unref_dag(Obj_Entry *); +static void ref_dag(Obj_Entry *); + +void r_debug_state(struct r_debug*, struct link_map*); + +/* + * Data declarations. + */ +static char *error_message; /* Message for dlerror(), or NULL */ +struct r_debug r_debug; /* for GDB; */ +static bool libmap_disable; /* Disable libmap */ +static char *libmap_override; /* Maps to use in addition to libmap.conf */ +static bool trust; /* False for setuid and setgid programs */ +static bool dangerous_ld_env; /* True if environment variables have been + used to affect the libraries loaded */ +static char *ld_bind_now; /* Environment variable for immediate binding */ +static char *ld_debug; /* Environment variable for debugging */ +static char *ld_library_path; /* Environment variable for search path */ +static char *ld_preload; /* Environment variable for libraries to + load first */ +static char *ld_tracing; /* Called from ldd to print libs */ +static Obj_Entry *obj_list; /* Head of linked list of shared objects */ +static Obj_Entry **obj_tail; /* Link field of last object in list */ +static Obj_Entry *obj_main; /* The main program shared object */ +static Obj_Entry obj_rtld; /* The dynamic linker shared object */ +static unsigned int obj_count; /* Number of objects in obj_list */ + +static Objlist list_global = /* Objects dlopened with RTLD_GLOBAL */ + STAILQ_HEAD_INITIALIZER(list_global); +static Objlist list_main = /* Objects loaded at program startup */ + STAILQ_HEAD_INITIALIZER(list_main); +static Objlist list_fini = /* Objects needing fini() calls */ + STAILQ_HEAD_INITIALIZER(list_fini); + +static Elf_Sym sym_zero; /* For resolving undefined weak refs. */ + +#define GDB_STATE(s,m) r_debug.r_state = s; r_debug_state(&r_debug,m); + +extern Elf_Dyn _DYNAMIC; +#pragma weak _DYNAMIC +#ifndef RTLD_IS_DYNAMIC +#define RTLD_IS_DYNAMIC() (&_DYNAMIC != NULL) +#endif + +/* + * These are the functions the dynamic linker exports to application + * programs. They are the only symbols the dynamic linker is willing + * to export from itself. + */ +static func_ptr_type exports[] = { + (func_ptr_type) &_rtld_error, + (func_ptr_type) &dlclose, + (func_ptr_type) &dlerror, + (func_ptr_type) &dlopen, + (func_ptr_type) &dlsym, + (func_ptr_type) &dladdr, + (func_ptr_type) &dllockinit, + (func_ptr_type) &dlinfo, + (func_ptr_type) &_rtld_thread_init, +#ifdef __i386__ + (func_ptr_type) &___tls_get_addr, +#endif + (func_ptr_type) &__tls_get_addr, + (func_ptr_type) &_rtld_allocate_tls, + (func_ptr_type) &_rtld_free_tls, + NULL +}; + +/* + * Global declarations normally provided by crt1. The dynamic linker is + * not built with crt1, so we have to provide them ourselves. + */ +char *__progname; +char **environ; + +/* + * Globals to control TLS allocation. + */ +size_t tls_last_offset; /* Static TLS offset of last module */ +size_t tls_last_size; /* Static TLS size of last module */ +size_t tls_static_space; /* Static TLS space allocated */ +int tls_dtv_generation = 1; /* Used to detect when dtv size changes */ +int tls_max_index = 1; /* Largest module index allocated */ + +/* + * Fill in a DoneList with an allocation large enough to hold all of + * the currently-loaded objects. Keep this as a macro since it calls + * alloca and we want that to occur within the scope of the caller. + */ +#define donelist_init(dlp) \ + ((dlp)->objs = alloca(obj_count * sizeof (dlp)->objs[0]), \ + assert((dlp)->objs != NULL), \ + (dlp)->num_alloc = obj_count, \ + (dlp)->num_used = 0) + +/* + * Main entry point for dynamic linking. The first argument is the + * stack pointer. The stack is expected to be laid out as described + * in the SVR4 ABI specification, Intel 386 Processor Supplement. + * Specifically, the stack pointer points to a word containing + * ARGC. Following that in the stack is a null-terminated sequence + * of pointers to argument strings. Then comes a null-terminated + * sequence of pointers to environment strings. Finally, there is a + * sequence of "auxiliary vector" entries. + * + * The second argument points to a place to store the dynamic linker's + * exit procedure pointer and the third to a place to store the main + * program's object. + * + * The return value is the main program's entry point. + */ +func_ptr_type +_rtld(Elf_Addr *sp, func_ptr_type *exit_proc, Obj_Entry **objp) +{ + Elf_Auxinfo *aux_info[AT_COUNT]; + int i; + int argc; + char **argv; + char **env; + Elf_Auxinfo *aux; + Elf_Auxinfo *auxp; + const char *argv0; + Objlist_Entry *entry; + Obj_Entry *obj; + Obj_Entry **preload_tail; + Objlist initlist; + int lockstate; + + /* + * On entry, the dynamic linker itself has not been relocated yet. + * Be very careful not to reference any global data until after + * init_rtld has returned. It is OK to reference file-scope statics + * and string constants, and to call static and global functions. + */ + + /* Find the auxiliary vector on the stack. */ + argc = *sp++; + argv = (char **) sp; + + sp += argc + 1; /* Skip over arguments and NULL terminator */ + env = (char **) sp; + + while (*sp++ != 0); /* Skip over environment, and NULL terminator */ + + aux = (Elf_Auxinfo *) sp; + + + /* Digest the auxiliary vector. */ + for (i = 0; i < AT_COUNT; i++) + aux_info[i] = NULL; + + for (auxp = aux; auxp->a_type != AT_NULL; auxp++) { + if (auxp->a_type < AT_COUNT) { + aux_info[auxp->a_type] = auxp; + } + } + + /* Initialize and relocate ourselves. */ + assert(aux_info[AT_BASE] != NULL); + + init_rtld((caddr_t) aux_info[AT_BASE]->a_un.a_ptr); + + __progname = obj_rtld.path; + argv0 = argv[0] != NULL ? argv[0] : "(null)"; + environ = env; + + trust = !issetugid(); + + ld_bind_now = getenv(LD_ "BIND_NOW"); + if (trust) { + ld_debug = getenv(LD_ "DEBUG"); + libmap_disable = getenv(LD_ "LIBMAP_DISABLE") != NULL; + libmap_override = getenv(LD_ "LIBMAP"); + ld_library_path = "/lib";//getenv(LD_ "LIBRARY_PATH"); + ld_preload = getenv(LD_ "PRELOAD"); + dangerous_ld_env = libmap_disable || (libmap_override != NULL) || + (ld_library_path != NULL) || (ld_preload != NULL); + } else + dangerous_ld_env = 0; + ld_tracing = getenv(LD_ "TRACE_LOADED_OBJECTS"); + + + if (ld_debug != NULL && *ld_debug != '\0') + debug = 1; + + dbg("%s is initialized, base address = %p", __progname, + (caddr_t) aux_info[AT_BASE]->a_un.a_ptr); + dbg("RTLD dynamic = %p", obj_rtld.dynamic); + dbg("RTLD pltgot = %p", obj_rtld.pltgot); + + /* + * Load the main program, or process its program header if it is + * already loaded. + */ + if (aux_info[AT_EXECFD] != NULL) { /* Load the main program. */ + int fd = aux_info[AT_EXECFD]->a_un.a_val; + dbg("loading main program"); + obj_main = map_object(fd, argv0, NULL); + close(fd); + if (obj_main == NULL) + die(); + } else { /* Main program already loaded. */ + const Elf_Phdr *phdr; + int phnum; + caddr_t entry; + + dbg("processing main program's program header"); + assert(aux_info[AT_PHDR] != NULL); + phdr = (const Elf_Phdr *) aux_info[AT_PHDR]->a_un.a_ptr; + assert(aux_info[AT_PHNUM] != NULL); + phnum = aux_info[AT_PHNUM]->a_un.a_val; + assert(aux_info[AT_PHENT] != NULL); + assert(aux_info[AT_PHENT]->a_un.a_val == sizeof(Elf_Phdr)); + assert(aux_info[AT_ENTRY] != NULL); + entry = (caddr_t) aux_info[AT_ENTRY]->a_un.a_ptr; + if ((obj_main = digest_phdr(phdr, phnum, entry, argv0)) == NULL) + die(); + } + + obj_main->path = xstrdup(argv0); + obj_main->mainprog = true; + + /* + * Get the actual dynamic linker pathname from the executable if + * possible. (It should always be possible.) That ensures that + * gdb will find the right dynamic linker even if a non-standard + * one is being used. + */ + if (obj_main->interp != NULL && + strcmp(obj_main->interp, obj_rtld.path) != 0) { + free(obj_rtld.path); + obj_rtld.path = xstrdup(obj_main->interp); + __progname = obj_rtld.path; + } + + + digest_dynamic(obj_main, 0); + + linkmap_add(obj_main); + linkmap_add(&obj_rtld); + + /* Link the main program into the list of objects. */ + *obj_tail = obj_main; + obj_tail = &obj_main->next; + obj_count++; + /* Make sure we don't call the main program's init and fini functions. */ + obj_main->init = obj_main->fini = (Elf_Addr)NULL; + + /* Initialize a fake symbol for resolving undefined weak references. */ + sym_zero.st_info = ELF_ST_INFO(STB_GLOBAL, STT_NOTYPE); + sym_zero.st_shndx = SHN_UNDEF; + + if (!libmap_disable) + libmap_disable = (bool)lm_init(libmap_override); + + dbg("loading LD_PRELOAD libraries"); + if (load_preload_objects() == -1) + die(); + preload_tail = obj_tail; + + dbg("loading needed objects"); + if (load_needed_objects(obj_main) == -1) + die(); + + /* Make a list of all objects loaded at startup. */ + for (obj = obj_list; obj != NULL; obj = obj->next) { + objlist_push_tail(&list_main, obj); + obj->refcount++; + } + + if (ld_tracing) { /* We're done */ + trace_loaded_objects(obj_main); + exit(0); + } + + if (getenv(LD_ "DUMP_REL_PRE") != NULL) { + dump_relocations(obj_main); + exit (0); + } + + /* setup TLS for main thread */ + dbg("initializing initial thread local storage"); + STAILQ_FOREACH(entry, &list_main, link) { + /* + * Allocate all the initial objects out of the static TLS + * block even if they didn't ask for it. + */ + allocate_tls_offset(entry->obj); + } + + allocate_initial_tls(obj_list); + +debug = 1; + if (relocate_objects(obj_main, + ld_bind_now != NULL && *ld_bind_now != '\0', &obj_rtld) == -1) + die(); + + dbg("doing copy relocations"); + if (do_copy_relocations(obj_main) == -1) + die(); + + if (getenv(LD_ "DUMP_REL_POST") != NULL) { + dump_relocations(obj_main); + exit (0); + } + + dbg("initializing key program variables"); + set_program_var("__progname", argv[0] != NULL ? basename(argv[0]) : ""); + set_program_var("environ", env); + + dbg("initializing thread locks"); + lockdflt_init(); + + /* Make a list of init functions to call. */ + objlist_init(&initlist); + initlist_add_objects(obj_list, preload_tail, &initlist); + + r_debug_state(NULL, &obj_main->linkmap); /* say hello to gdb! */ + + objlist_call_init(&initlist); + lockstate = wlock_acquire(rtld_bind_lock); + objlist_clear(&initlist); + wlock_release(rtld_bind_lock, lockstate); + + dbg("transferring control to program entry point = %p", obj_main->entry); + + /* Return the exit procedure and the program entry point. */ + *exit_proc = rtld_exit; + *objp = obj_main; + return (func_ptr_type) obj_main->entry; +} + +Elf_Addr +_rtld_bind(Obj_Entry *obj, Elf_Size reloff) +{ + const Elf_Rel *rel; + const Elf_Sym *def; + const Obj_Entry *defobj; + Elf_Addr *where; + Elf_Addr target; + int lockstate; + + lockstate = rlock_acquire(rtld_bind_lock); + if (obj->pltrel) + rel = (const Elf_Rel *) ((caddr_t) obj->pltrel + reloff); + else + rel = (const Elf_Rel *) ((caddr_t) obj->pltrela + reloff); + + where = (Elf_Addr *) (obj->relocbase + rel->r_offset); + def = find_symdef(ELF_R_SYM(rel->r_info), obj, &defobj, true, NULL); + if (def == NULL) + die(); + + target = (Elf_Addr)(defobj->relocbase + def->st_value); + + dbg("\"%s\" in \"%s\" ==> %p in \"%s\"", + defobj->strtab + def->st_name, basename(obj->path), + (void *)target, basename(defobj->path)); + + /* + * Write the new contents for the jmpslot. Note that depending on + * architecture, the value which we need to return back to the + * lazy binding trampoline may or may not be the target + * address. The value returned from reloc_jmpslot() is the value + * that the trampoline needs. + */ + target = reloc_jmpslot(where, target, defobj, obj, rel); + rlock_release(rtld_bind_lock, lockstate); + return target; +} + +/* + * Error reporting function. Use it like printf. If formats the message + * into a buffer, and sets things up so that the next call to dlerror() + * will return the message. + */ +void +_rtld_error(const char *fmt, ...) +{ + static char buf[512]; + va_list ap; + + va_start(ap, fmt); + vsnprintf(buf, sizeof buf, fmt, ap); + error_message = buf; + va_end(ap); +} + +/* + * Return a dynamically-allocated copy of the current error message, if any. + */ +static char * +errmsg_save(void) +{ + return error_message == NULL ? NULL : xstrdup(error_message); +} + +/* + * Restore the current error message from a copy which was previously saved + * by errmsg_save(). The copy is freed. + */ +static void +errmsg_restore(char *saved_msg) +{ + if (saved_msg == NULL) + error_message = NULL; + else { + _rtld_error("%s", saved_msg); + free(saved_msg); + } +} + +static const char * +basename(const char *name) +{ + const char *p = strrchr(name, '/'); + return p != NULL ? p + 1 : name; +} + +static void +die(void) +{ + const char *msg = dlerror(); + + if (msg == NULL) + msg = "Fatal error"; + errx(1, "%s", msg); +} + +/* + * Process a shared object's DYNAMIC section, and save the important + * information in its Obj_Entry structure. + */ +static void +digest_dynamic(Obj_Entry *obj, int early) +{ + const Elf_Dyn *dynp; + Needed_Entry **needed_tail = &obj->needed; + const Elf_Dyn *dyn_rpath = NULL; + int plttype = DT_REL; + + obj->bind_now = false; + for (dynp = obj->dynamic; dynp->d_tag != DT_NULL; dynp++) { + switch (dynp->d_tag) { + + case DT_REL: + obj->rel = (const Elf_Rel *) (obj->relocbase + dynp->d_un.d_ptr); + break; + + case DT_RELSZ: + obj->relsize = dynp->d_un.d_val; + break; + + case DT_RELENT: + assert(dynp->d_un.d_val == sizeof(Elf_Rel)); + break; + + case DT_JMPREL: + obj->pltrel = (const Elf_Rel *) + (obj->relocbase + dynp->d_un.d_ptr); + break; + + case DT_PLTRELSZ: + obj->pltrelsize = dynp->d_un.d_val; + break; + + case DT_RELA: + obj->rela = (const Elf_Rela *) (obj->relocbase + dynp->d_un.d_ptr); + break; + + case DT_RELASZ: + obj->relasize = dynp->d_un.d_val; + break; + + case DT_RELAENT: + assert(dynp->d_un.d_val == sizeof(Elf_Rela)); + break; + + case DT_PLTREL: + plttype = dynp->d_un.d_val; + assert(dynp->d_un.d_val == DT_REL || plttype == DT_RELA); + break; + + case DT_SYMTAB: + obj->symtab = (const Elf_Sym *) + (obj->relocbase + dynp->d_un.d_ptr); + break; + + case DT_SYMENT: + assert(dynp->d_un.d_val == sizeof(Elf_Sym)); + break; + + case DT_STRTAB: + obj->strtab = (const char *) (obj->relocbase + dynp->d_un.d_ptr); + break; + + case DT_STRSZ: + obj->strsize = dynp->d_un.d_val; + break; + + case DT_HASH: + { + const Elf_Hashelt *hashtab = (const Elf_Hashelt *) + (obj->relocbase + dynp->d_un.d_ptr); + obj->nbuckets = hashtab[0]; + obj->nchains = hashtab[1]; + obj->buckets = hashtab + 2; + obj->chains = obj->buckets + obj->nbuckets; + } + break; + + case DT_NEEDED: + if (!obj->rtld) { + Needed_Entry *nep = NEW(Needed_Entry); + nep->name = dynp->d_un.d_val; + nep->obj = NULL; + nep->next = NULL; + + *needed_tail = nep; + needed_tail = &nep->next; + } + break; + + case DT_PLTGOT: + obj->pltgot = (Elf_Addr *) (obj->relocbase + dynp->d_un.d_ptr); + break; + + case DT_TEXTREL: + obj->textrel = true; + break; + + case DT_SYMBOLIC: + obj->symbolic = true; + break; + + case DT_RPATH: + case DT_RUNPATH: /* XXX: process separately */ + /* + * We have to wait until later to process this, because we + * might not have gotten the address of the string table yet. + */ + dyn_rpath = dynp; + break; + + case DT_SONAME: + /* Not used by the dynamic linker. */ + break; + + case DT_INIT: + obj->init = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr); + break; + + case DT_FINI: + obj->fini = (Elf_Addr) (obj->relocbase + dynp->d_un.d_ptr); + break; + + case DT_DEBUG: + /* XXX - not implemented yet */ + if (!early) + dbg("Filling in DT_DEBUG entry"); + ((Elf_Dyn*)dynp)->d_un.d_ptr = (Elf_Addr) &r_debug; + break; + + case DT_FLAGS: + if (dynp->d_un.d_val & DF_ORIGIN) { + obj->origin_path = xmalloc(PATH_MAX); + if (rtld_dirname(obj->path, obj->origin_path) == -1) + die(); + } + if (dynp->d_un.d_val & DF_SYMBOLIC) + obj->symbolic = true; + if (dynp->d_un.d_val & DF_TEXTREL) + obj->textrel = true; + if (dynp->d_un.d_val & DF_BIND_NOW) + obj->bind_now = true; + if (dynp->d_un.d_val & DF_STATIC_TLS) + ; + break; + + default: + if (!early) { + dbg("Ignoring d_tag %ld = %#lx", (long)dynp->d_tag, + (long)dynp->d_tag); + } + break; + } + } + + obj->traced = false; + + if (plttype == DT_RELA) { + obj->pltrela = (const Elf_Rela *) obj->pltrel; + obj->pltrel = NULL; + obj->pltrelasize = obj->pltrelsize; + obj->pltrelsize = 0; + } + + if (dyn_rpath != NULL) + obj->rpath = obj->strtab + dyn_rpath->d_un.d_val; +} + +/* + * Process a shared object's program header. This is used only for the + * main program, when the kernel has already loaded the main program + * into memory before calling the dynamic linker. It creates and + * returns an Obj_Entry structure. + */ +static Obj_Entry * +digest_phdr(const Elf_Phdr *phdr, int phnum, caddr_t entry, const char *path) +{ + Obj_Entry *obj; + const Elf_Phdr *phlimit = phdr + phnum; + const Elf_Phdr *ph; + int nsegs = 0; + + obj = obj_new(); + for (ph = phdr; ph < phlimit; ph++) { + switch (ph->p_type) { + + case PT_PHDR: + if ((const Elf_Phdr *)ph->p_vaddr != phdr) { + _rtld_error("%s: invalid PT_PHDR", path); + return NULL; + } + obj->phdr = (const Elf_Phdr *) ph->p_vaddr; + obj->phsize = ph->p_memsz; + break; + + case PT_INTERP: + obj->interp = (const char *) ph->p_vaddr; + break; + + case PT_LOAD: + if (nsegs == 0) { /* First load segment */ + obj->vaddrbase = trunc_page(ph->p_vaddr); + obj->mapbase = (caddr_t) obj->vaddrbase; + obj->relocbase = obj->mapbase - obj->vaddrbase; + obj->textsize = round_page(ph->p_vaddr + ph->p_memsz) - + obj->vaddrbase; + } else { /* Last load segment */ + obj->mapsize = round_page(ph->p_vaddr + ph->p_memsz) - + obj->vaddrbase; + } + nsegs++; + break; + + case PT_DYNAMIC: + obj->dynamic = (const Elf_Dyn *) ph->p_vaddr; + break; + + case PT_TLS: + obj->tlsindex = 1; + obj->tlssize = ph->p_memsz; + obj->tlsalign = ph->p_align; + obj->tlsinitsize = ph->p_filesz; + obj->tlsinit = (void*) ph->p_vaddr; + break; + } + } + if (nsegs < 1) { + _rtld_error("%s: too few PT_LOAD segments", path); + return NULL; + } + + obj->entry = entry; + return obj; +} + +static Obj_Entry * +dlcheck(void *handle) +{ + Obj_Entry *obj; + + for (obj = obj_list; obj != NULL; obj = obj->next) + if (obj == (Obj_Entry *) handle) + break; + + if (obj == NULL || obj->refcount == 0 || obj->dl_refcount == 0) { + _rtld_error("Invalid shared object handle %p", handle); + return NULL; + } + return obj; +} + +/* + * If the given object is already in the donelist, return true. Otherwise + * add the object to the list and return false. + */ +static bool +donelist_check(DoneList *dlp, const Obj_Entry *obj) +{ + unsigned int i; + + for (i = 0; i < dlp->num_used; i++) + if (dlp->objs[i] == obj) + return true; + /* + * Our donelist allocation should always be sufficient. But if + * our threads locking isn't working properly, more shared objects + * could have been loaded since we allocated the list. That should + * never happen, but we'll handle it properly just in case it does. + */ + if (dlp->num_used < dlp->num_alloc) + dlp->objs[dlp->num_used++] = obj; + return false; +} + +/* + * Hash function for symbol table lookup. Don't even think about changing + * this. It is specified by the System V ABI. + */ +unsigned long +elf_hash(const char *name) +{ + const unsigned char *p = (const unsigned char *) name; + unsigned long h = 0; + unsigned long g; + + while (*p != '\0') { + h = (h << 4) + *p++; + if ((g = h & 0xf0000000) != 0) + h ^= g >> 24; + h &= ~g; + } + return h; +} + +/* + * Find the library with the given name, and return its full pathname. + * The returned string is dynamically allocated. Generates an error + * message and returns NULL if the library cannot be found. + * + * If the second argument is non-NULL, then it refers to an already- + * loaded shared object, whose library search path will be searched. + * + * The search order is: + * LD_LIBRARY_PATH + * rpath in the referencing file + * ldconfig hints + * /lib:/usr/lib + */ +static char * +find_library(const char *xname, const Obj_Entry *refobj) +{ + char *pathname; + char *name; + + if (strchr(xname, '/') != NULL) { /* Hard coded pathname */ + if (xname[0] != '/' && !trust) { + _rtld_error("Absolute pathname required for shared object \"%s\"", + xname); + return NULL; + } + return xstrdup(xname); + } + + if (libmap_disable || (refobj == NULL) || + (name = lm_find(refobj->path, xname)) == NULL) + name = (char *)xname; + + dbg(" Searching for \"%s\"", name); + if ((pathname = search_library_path(name, ld_library_path)) != NULL || + (refobj != NULL && + (pathname = search_library_path(name, refobj->rpath)) != NULL) || + (pathname = search_library_path(name, gethints())) != NULL || + (pathname = search_library_path(name, STANDARD_LIBRARY_PATH)) != NULL) + return pathname; + + if(refobj != NULL && refobj->path != NULL) { + _rtld_error("Shared object \"%s\" not found, required by \"%s\"", + name, basename(refobj->path)); + } else { + _rtld_error("Shared object \"%s\" not found", name); + } + return NULL; +} + +/* + * Given a symbol number in a referencing object, find the corresponding + * definition of the symbol. Returns a pointer to the symbol, or NULL if + * no definition was found. Returns a pointer to the Obj_Entry of the + * defining object via the reference parameter DEFOBJ_OUT. + */ +const Elf_Sym * +find_symdef(unsigned long symnum, const Obj_Entry *refobj, + const Obj_Entry **defobj_out, bool in_plt, SymCache *cache) +{ + const Elf_Sym *ref; + const Elf_Sym *def; + const Obj_Entry *defobj; + const char *name; + unsigned long hash; + + /* + * If we have already found this symbol, get the information from + * the cache. + */ + if (symnum >= refobj->nchains) + return NULL; /* Bad object */ + + if (cache != NULL && cache[symnum].sym != NULL) { + *defobj_out = cache[symnum].obj; + return cache[symnum].sym; + } + + ref = refobj->symtab + symnum; + name = refobj->strtab + ref->st_name; + defobj = NULL; + + /* + * We don't have to do a full scale lookup if the symbol is local. + * We know it will bind to the instance in this load module; to + * which we already have a pointer (ie ref). By not doing a lookup, + * we not only improve performance, but it also avoids unresolvable + * symbols when local symbols are not in the hash table. This has + * been seen with the ia64 toolchain. + */ + if (ELF_ST_BIND(ref->st_info) != STB_LOCAL) { + if (ELF_ST_TYPE(ref->st_info) == STT_SECTION) { + _rtld_error("%s: Bogus symbol table entry %lu", refobj->path, + symnum); + } + hash = elf_hash(name); + def = symlook_default(name, hash, refobj, &defobj, in_plt); + } else { + def = ref; + defobj = refobj; + } + + /* + * If we found no definition and the reference is weak, treat the + * symbol as having the value zero. + */ + if (def == NULL && ELF_ST_BIND(ref->st_info) == STB_WEAK) { + def = &sym_zero; + defobj = obj_main; + } + + if (def != NULL) { + *defobj_out = defobj; + /* Record the information in the cache to avoid subsequent lookups. */ + if (cache != NULL) { + cache[symnum].sym = def; + cache[symnum].obj = defobj; + } + } else { + if (refobj != &obj_rtld) + _rtld_error("%s: Undefined symbol \"%s\"", refobj->path, name); + } + return def; +} + +/* + * Return the search path from the ldconfig hints file, reading it if + * necessary. Returns NULL if there are problems with the hints file, + * or if the search path there is empty. + */ +static const char * +gethints(void) +{ + static char *hints; + + if (hints == NULL) { + int fd; + struct elfhints_hdr hdr; + char *p; + + /* Keep from trying again in case the hints file is bad. */ + hints = ""; + + if ((fd = open(_PATH_ELF_HINTS, O_RDONLY)) == -1) + return NULL; + if (read(fd, &hdr, sizeof hdr) != sizeof hdr || + hdr.magic != ELFHINTS_MAGIC || + hdr.version != 1) { + close(fd); + return NULL; + } + p = xmalloc(hdr.dirlistlen + 1); + if (lseek(fd, hdr.strtab + hdr.dirlist, SEEK_SET) == -1 || + read(fd, p, hdr.dirlistlen + 1) != (ssize_t)hdr.dirlistlen + 1) { + free(p); + close(fd); + return NULL; + } + hints = p; + close(fd); + } + return hints[0] != '\0' ? hints : NULL; +} + +static void +init_dag(Obj_Entry *root) +{ + DoneList donelist; + + donelist_init(&donelist); + init_dag1(root, root, &donelist); +} + +static void +init_dag1(Obj_Entry *root, Obj_Entry *obj, DoneList *dlp) +{ + const Needed_Entry *needed; + + if (donelist_check(dlp, obj)) + return; + + obj->refcount++; + objlist_push_tail(&obj->dldags, root); + objlist_push_tail(&root->dagmembers, obj); + for (needed = obj->needed; needed != NULL; needed = needed->next) + if (needed->obj != NULL) + init_dag1(root, needed->obj, dlp); +} + +/* + * Initialize the dynamic linker. The argument is the address at which + * the dynamic linker has been mapped into memory. The primary task of + * this function is to relocate the dynamic linker. + */ +static void +init_rtld(caddr_t mapbase) +{ + Obj_Entry objtmp; /* Temporary rtld object */ + + /* + * Conjure up an Obj_Entry structure for the dynamic linker. + * + * The "path" member can't be initialized yet because string constatns + * cannot yet be acessed. Below we will set it correctly. + */ + memset(&objtmp, 0, sizeof(objtmp)); + objtmp.path = NULL; + objtmp.rtld = true; + objtmp.mapbase = mapbase; +#ifdef PIC + objtmp.relocbase = mapbase; +#endif + if (RTLD_IS_DYNAMIC()) { + objtmp.dynamic = rtld_dynamic(&objtmp); + digest_dynamic(&objtmp, 1); + assert(objtmp.needed == NULL); + assert(!objtmp.textrel); + + /* + * Temporarily put the dynamic linker entry into the object list, so + * that symbols can be found. + */ + + relocate_objects(&objtmp, true, &objtmp); + } + + /* Initialize the object list. */ + obj_tail = &obj_list; + + /* Now that non-local variables can be accesses, copy out obj_rtld. */ + memcpy(&obj_rtld, &objtmp, sizeof(obj_rtld)); + + /* Replace the path with a dynamically allocated copy. */ + obj_rtld.path = xstrdup(PATH_RTLD); + + r_debug.r_brk = r_debug_state; + r_debug.r_state = RT_CONSISTENT; +} + +/* + * Add the init functions from a needed object list (and its recursive + * needed objects) to "list". This is not used directly; it is a helper + * function for initlist_add_objects(). The write lock must be held + * when this function is called. + */ +static void +initlist_add_neededs(Needed_Entry *needed, Objlist *list) +{ + /* Recursively process the successor needed objects. */ + if (needed->next != NULL) + initlist_add_neededs(needed->next, list); + + /* Process the current needed object. */ + if (needed->obj != NULL) + initlist_add_objects(needed->obj, &needed->obj->next, list); +} + +/* + * Scan all of the DAGs rooted in the range of objects from "obj" to + * "tail" and add their init functions to "list". This recurses over + * the DAGs and ensure the proper init ordering such that each object's + * needed libraries are initialized before the object itself. At the + * same time, this function adds the objects to the global finalization + * list "list_fini" in the opposite order. The write lock must be + * held when this function is called. + */ +static void +initlist_add_objects(Obj_Entry *obj, Obj_Entry **tail, Objlist *list) +{ + if (obj->init_done) + return; + obj->init_done = true; + + /* Recursively process the successor objects. */ + if (&obj->next != tail) + initlist_add_objects(obj->next, tail, list); + + /* Recursively process the needed objects. */ + if (obj->needed != NULL) + initlist_add_neededs(obj->needed, list); + + /* Add the object to the init list. */ + if (obj->init != (Elf_Addr)NULL) + objlist_push_tail(list, obj); + + /* Add the object to the global fini list in the reverse order. */ + if (obj->fini != (Elf_Addr)NULL) + objlist_push_head(&list_fini, obj); +} + +#ifndef FPTR_TARGET +#define FPTR_TARGET(f) ((Elf_Addr) (f)) +#endif + +static bool +is_exported(const Elf_Sym *def) +{ + Elf_Addr value; + const func_ptr_type *p; + + value = (Elf_Addr)(obj_rtld.relocbase + def->st_value); + for (p = exports; *p != NULL; p++) + if (FPTR_TARGET(*p) == value) + return true; + return false; +} + +/* + * Given a shared object, traverse its list of needed objects, and load + * each of them. Returns 0 on success. Generates an error message and + * returns -1 on failure. + */ +static int +load_needed_objects(Obj_Entry *first) +{ + Obj_Entry *obj; + + for (obj = first; obj != NULL; obj = obj->next) { + Needed_Entry *needed; + + for (needed = obj->needed; needed != NULL; needed = needed->next) { + const char *name = obj->strtab + needed->name; + char *path = find_library(name, obj); + + needed->obj = NULL; + if (path == NULL && !ld_tracing) + return -1; +printf("\n\nPATH: [%s]\n",path); + if (path) { + needed->obj = load_object(path); + if (needed->obj == NULL && !ld_tracing) + return -1; /* XXX - cleanup */ + } + } + } + + return 0; +} + +static int +load_preload_objects(void) +{ + char *p = ld_preload; + static const char delim[] = " \t:;"; + + if (p == NULL) + return 0; + + p += strspn(p, delim); + while (*p != '\0') { + size_t len = strcspn(p, delim); + char *path; + char savech; + + savech = p[len]; + p[len] = '\0'; + if ((path = find_library(p, NULL)) == NULL) + return -1; + if (load_object(path) == NULL) + return -1; /* XXX - cleanup */ + p[len] = savech; + p += len; + p += strspn(p, delim); + } + return 0; +} + +/* + * Load a shared object into memory, if it is not already loaded. The + * argument must be a string allocated on the heap. This function assumes + * responsibility for freeing it when necessary. + * + * Returns a pointer to the Obj_Entry for the object. Returns NULL + * on failure. + */ +static Obj_Entry * +load_object(char *path) +{ + Obj_Entry *obj; + int fd = -1; + struct stat sb; + struct statfs fs; + + for (obj = obj_list->next; obj != NULL; obj = obj->next) + if (strcmp(obj->path, path) == 0) + break; + + /* + * If we didn't find a match by pathname, open the file and check + * again by device and inode. This avoids false mismatches caused + * by multiple links or ".." in pathnames. + * + * To avoid a race, we open the file and use fstat() rather than + * using stat(). + */ + if (obj == NULL) { + if ((fd = open(path, O_RDONLY)) == -1) { + _rtld_error("Cannot open \"%s\"", path); + return NULL; + } + if (fstat(fd, &sb) == -1) { + _rtld_error("Cannot fstat \"%s\"", path); + close(fd); + return NULL; + } + for (obj = obj_list->next; obj != NULL; obj = obj->next) { + if (obj->ino == sb.st_ino && obj->dev == sb.st_dev) { + close(fd); + break; + } + } + } + + if (obj == NULL) { /* First use of this object, so we must map it in */ + /* + * but first, make sure that environment variables haven't been + * used to circumvent the noexec flag on a filesystem. + */ + if (dangerous_ld_env) { + if (fstatfs(fd, &fs) != 0) { + _rtld_error("Cannot fstatfs \"%s\"", path); + close(fd); + return NULL; + } + if (fs.f_flags & MNT_NOEXEC) { + _rtld_error("Cannot execute objects on %s\n", fs.f_mntonname); + close(fd); + return NULL; + } + } + dbg("loading \"%s\"", path); + printf("\n\n loading \"%s\"\n", path); + obj = map_object(fd, path, &sb); + printf("\nmapped object\n"); + close(fd); + if (obj == NULL) { + free(path); + return NULL; + } + + obj->path = path; + digest_dynamic(obj, 0); + + *obj_tail = obj; + obj_tail = &obj->next; + obj_count++; + linkmap_add(obj); /* for GDB & dlinfo() */ + + dbg(" %p .. %p: %s", obj->mapbase, + obj->mapbase + obj->mapsize - 1, obj->path); + if (obj->textrel) + dbg(" WARNING: %s has impure text", obj->path); + } else + free(path); + + return obj; +} + +static Obj_Entry * +obj_from_addr(const void *addr) +{ + Obj_Entry *obj; + + for (obj = obj_list; obj != NULL; obj = obj->next) { + if (addr < (void *) obj->mapbase) + continue; + if (addr < (void *) (obj->mapbase + obj->mapsize)) + return obj; + } + return NULL; +} + +/* + * Call the finalization functions for each of the objects in "list" + * which are unreferenced. All of the objects are expected to have + * non-NULL fini functions. + */ +static void +objlist_call_fini(Objlist *list) +{ + Objlist_Entry *elm; + char *saved_msg; + + /* + * Preserve the current error message since a fini function might + * call into the dynamic linker and overwrite it. + */ + saved_msg = errmsg_save(); + STAILQ_FOREACH(elm, list, link) { + if (elm->obj->refcount == 0) { + dbg("calling fini function for %s at %p", elm->obj->path, + (void *)elm->obj->fini); + call_initfini_pointer(elm->obj, elm->obj->fini); + } + } + errmsg_restore(saved_msg); +} + +/* + * Call the initialization functions for each of the objects in + * "list". All of the objects are expected to have non-NULL init + * functions. + */ +static void +objlist_call_init(Objlist *list) +{ + Objlist_Entry *elm; + char *saved_msg; + + /* + * Preserve the current error message since an init function might + * call into the dynamic linker and overwrite it. + */ + saved_msg = errmsg_save(); + STAILQ_FOREACH(elm, list, link) { + dbg("calling init function for %s at %p", elm->obj->path, + (void *)elm->obj->init); + call_initfini_pointer(elm->obj, elm->obj->init); + } + errmsg_restore(saved_msg); +} + +static void +objlist_clear(Objlist *list) +{ + Objlist_Entry *elm; + + while (!STAILQ_EMPTY(list)) { + elm = STAILQ_FIRST(list); + STAILQ_REMOVE_HEAD(list, link); + free(elm); + } +} + +static Objlist_Entry * +objlist_find(Objlist *list, const Obj_Entry *obj) +{ + Objlist_Entry *elm; + + STAILQ_FOREACH(elm, list, link) + if (elm->obj == obj) + return elm; + return NULL; +} + +static void +objlist_init(Objlist *list) +{ + STAILQ_INIT(list); +} + +static void +objlist_push_head(Objlist *list, Obj_Entry *obj) +{ + Objlist_Entry *elm; + + elm = NEW(Objlist_Entry); + elm->obj = obj; + STAILQ_INSERT_HEAD(list, elm, link); +} + +static void +objlist_push_tail(Objlist *list, Obj_Entry *obj) +{ + Objlist_Entry *elm; + + elm = NEW(Objlist_Entry); + elm->obj = obj; + STAILQ_INSERT_TAIL(list, elm, link); +} + +static void +objlist_remove(Objlist *list, Obj_Entry *obj) +{ + Objlist_Entry *elm; + + if ((elm = objlist_find(list, obj)) != NULL) { + STAILQ_REMOVE(list, elm, Struct_Objlist_Entry, link); + free(elm); + } +} + +/* + * Remove all of the unreferenced objects from "list". + */ +static void +objlist_remove_unref(Objlist *list) +{ + Objlist newlist; + Objlist_Entry *elm; + + STAILQ_INIT(&newlist); + while (!STAILQ_EMPTY(list)) { + elm = STAILQ_FIRST(list); + STAILQ_REMOVE_HEAD(list, link); + if (elm->obj->refcount == 0) + free(elm); + else + STAILQ_INSERT_TAIL(&newlist, elm, link); + } + *list = newlist; +} + +/* + * Relocate newly-loaded shared objects. The argument is a pointer to + * the Obj_Entry for the first such object. All objects from the first + * to the end of the list of objects are relocated. Returns 0 on success, + * or -1 on failure. + */ +static int +relocate_objects(Obj_Entry *first, bool bind_now, Obj_Entry *rtldobj) +{ + Obj_Entry *obj; + + for (obj = first; obj != NULL; obj = obj->next) { + if (obj != rtldobj) + dbg("relocating \"%s\"", obj->path); + if (obj->nbuckets == 0 || obj->nchains == 0 || obj->buckets == NULL || + obj->symtab == NULL || obj->strtab == NULL) { + _rtld_error("%s: Shared object has no run-time symbol table", + obj->path); + return -1; + } + + if (obj->textrel) { + /* There are relocations to the write-protected text segment. */ + if (mprotect(obj->mapbase, obj->textsize, + PROT_READ|PROT_WRITE|PROT_EXEC) == -1) { + _rtld_error("%s: Cannot write-enable text segment: %s", + obj->path, strerror(errno)); + return -1; + } + } + + /* Process the non-PLT relocations. */ + if (reloc_non_plt(obj, rtldobj)) + return -1; + + if (obj->textrel) { /* Re-protected the text segment. */ + if (mprotect(obj->mapbase, obj->textsize, + PROT_READ|PROT_EXEC) == -1) { + _rtld_error("%s: Cannot write-protect text segment: %s", + obj->path, strerror(errno)); + return -1; + } + } + + /* Process the PLT relocations. */ + if (reloc_plt(obj) == -1) + return -1; + /* Relocate the jump slots if we are doing immediate binding. */ + if (obj->bind_now || bind_now) + if (reloc_jmpslots(obj) == -1) + return -1; + + /* + * Set up the magic number and version in the Obj_Entry. These + * were checked in the crt1.o from the original ElfKit, so we + * set them for backward compatibility. + */ + obj->magic = RTLD_MAGIC; + obj->version = RTLD_VERSION; + + /* Set the special PLT or GOT entries. */ + init_pltgot(obj); + } + + return 0; +} + +/* + * Cleanup procedure. It will be called (by the atexit mechanism) just + * before the process exits. + */ +static void +rtld_exit(void) +{ + Obj_Entry *obj; + + dbg("rtld_exit()"); + /* Clear all the reference counts so the fini functions will be called. */ + for (obj = obj_list; obj != NULL; obj = obj->next) + obj->refcount = 0; + objlist_call_fini(&list_fini); + /* No need to remove the items from the list, since we are exiting. */ + if (!libmap_disable) + lm_fini(); +} + +static void * +path_enumerate(const char *path, path_enum_proc callback, void *arg) +{ +#ifdef COMPAT_32BIT + const char *trans; +#endif + if (path == NULL) + return (NULL); + + path += strspn(path, ":;"); + while (*path != '\0') { + size_t len; + char *res; + + len = strcspn(path, ":;"); +#ifdef COMPAT_32BIT + trans = lm_findn(NULL, path, len); + if (trans) + res = callback(trans, strlen(trans), arg); + else +#endif + res = callback(path, len, arg); + + if (res != NULL) + return (res); + + path += len; + path += strspn(path, ":;"); + } + + return (NULL); +} + +struct try_library_args { + const char *name; + size_t namelen; + char *buffer; + size_t buflen; +}; + +static void * +try_library_path(const char *dir, size_t dirlen, void *param) +{ + struct try_library_args *arg; + + arg = param; + if (*dir == '/' || trust) { + char *pathname; + + if (dirlen + 1 + arg->namelen + 1 > arg->buflen) + return (NULL); + + pathname = arg->buffer; + strncpy(pathname, dir, dirlen); + pathname[dirlen] = '/'; + strcpy(pathname + dirlen + 1, arg->name); + + dbg(" Trying \"%s\"", pathname); + if (access(pathname, F_OK) == 0) { /* We found it */ + pathname = xmalloc(dirlen + 1 + arg->namelen + 1); + strcpy(pathname, arg->buffer); + return (pathname); + } + } + return (NULL); +} + +static char * +search_library_path(const char *name, const char *path) +{ + char *p; + struct try_library_args arg; + + if (path == NULL) + return NULL; +printf("name: [%s]\n",name); + arg.name = name; + arg.namelen = strlen(name); + arg.buffer = xmalloc(PATH_MAX); + arg.buflen = PATH_MAX; + + p = path_enumerate(path, try_library_path, &arg); + + free(arg.buffer); + + return (p); +} + +int +dlclose(void *handle) +{ + Obj_Entry *root; + int lockstate; + + lockstate = wlock_acquire(rtld_bind_lock); + root = dlcheck(handle); + if (root == NULL) { + wlock_release(rtld_bind_lock, lockstate); + return -1; + } + + /* Unreference the object and its dependencies. */ + root->dl_refcount--; + + unref_dag(root); + + if (root->refcount == 0) { + /* + * The object is no longer referenced, so we must unload it. + * First, call the fini functions with no locks held. + */ + wlock_release(rtld_bind_lock, lockstate); + objlist_call_fini(&list_fini); + lockstate = wlock_acquire(rtld_bind_lock); + objlist_remove_unref(&list_fini); + + /* Finish cleaning up the newly-unreferenced objects. */ + GDB_STATE(RT_DELETE,&root->linkmap); + unload_object(root); + GDB_STATE(RT_CONSISTENT,NULL); + } + wlock_release(rtld_bind_lock, lockstate); + return 0; +} + +char * +dlerror(void) +{ + char *msg = error_message; + error_message = NULL; + return msg; +} + +/* + * This function is deprecated and has no effect. + */ +void +dllockinit(void *context, + void *(*lock_create)(void *context), + void (*rlock_acquire)(void *lock), + void (*wlock_acquire)(void *lock), + void (*lock_release)(void *lock), + void (*lock_destroy)(void *lock), + void (*context_destroy)(void *context)) +{ + static void *cur_context; + static void (*cur_context_destroy)(void *); + + /* Just destroy the context from the previous call, if necessary. */ + if (cur_context_destroy != NULL) + cur_context_destroy(cur_context); + cur_context = context; + cur_context_destroy = context_destroy; +} + +void * +dlopen(const char *name, int mode) +{ + Obj_Entry **old_obj_tail; + Obj_Entry *obj; + Objlist initlist; + int result, lockstate; + + ld_tracing = (mode & RTLD_TRACE) == 0 ? NULL : "1"; + if (ld_tracing != NULL) + environ = (char **)*get_program_var_addr("environ"); + + objlist_init(&initlist); + + lockstate = wlock_acquire(rtld_bind_lock); + GDB_STATE(RT_ADD,NULL); + + old_obj_tail = obj_tail; + obj = NULL; + if (name == NULL) { + obj = obj_main; + obj->refcount++; + } else { + char *path = find_library(name, obj_main); + if (path != NULL) + obj = load_object(path); + } + + if (obj) { + obj->dl_refcount++; + if (mode & RTLD_GLOBAL && objlist_find(&list_global, obj) == NULL) + objlist_push_tail(&list_global, obj); + mode &= RTLD_MODEMASK; + if (*old_obj_tail != NULL) { /* We loaded something new. */ + assert(*old_obj_tail == obj); + + result = load_needed_objects(obj); + if (result != -1 && ld_tracing) + goto trace; + + if (result == -1 || + (init_dag(obj), relocate_objects(obj, mode == RTLD_NOW, + &obj_rtld)) == -1) { + obj->dl_refcount--; + unref_dag(obj); + if (obj->refcount == 0) + unload_object(obj); + obj = NULL; + } else { + /* Make list of init functions to call. */ + initlist_add_objects(obj, &obj->next, &initlist); + } + } else { + + /* Bump the reference counts for objects on this DAG. */ + ref_dag(obj); + + if (ld_tracing) + goto trace; + } + } + + GDB_STATE(RT_CONSISTENT,obj ? &obj->linkmap : NULL); + + /* Call the init functions with no locks held. */ + wlock_release(rtld_bind_lock, lockstate); + objlist_call_init(&initlist); + lockstate = wlock_acquire(rtld_bind_lock); + objlist_clear(&initlist); + wlock_release(rtld_bind_lock, lockstate); + return obj; +trace: + trace_loaded_objects(obj); + wlock_release(rtld_bind_lock, lockstate); + exit(0); +} + +void * +dlsym(void *handle, const char *name) +{ + const Obj_Entry *obj; + unsigned long hash; + const Elf_Sym *def; + const Obj_Entry *defobj; + int lockstate; + + hash = elf_hash(name); + def = NULL; + defobj = NULL; + + lockstate = rlock_acquire(rtld_bind_lock); + if (handle == NULL || handle == RTLD_NEXT || + handle == RTLD_DEFAULT || handle == RTLD_SELF) { + void *retaddr; + + retaddr = __builtin_return_address(0); /* __GNUC__ only */ + if ((obj = obj_from_addr(retaddr)) == NULL) { + _rtld_error("Cannot determine caller's shared object"); + rlock_release(rtld_bind_lock, lockstate); + return NULL; + } + if (handle == NULL) { /* Just the caller's shared object. */ + def = symlook_obj(name, hash, obj, true); + defobj = obj; + } else if (handle == RTLD_NEXT || /* Objects after caller's */ + handle == RTLD_SELF) { /* ... caller included */ + if (handle == RTLD_NEXT) + obj = obj->next; + for (; obj != NULL; obj = obj->next) { + if ((def = symlook_obj(name, hash, obj, true)) != NULL) { + defobj = obj; + break; + } + } + } else { + assert(handle == RTLD_DEFAULT); + def = symlook_default(name, hash, obj, &defobj, true); + } + } else { + if ((obj = dlcheck(handle)) == NULL) { + rlock_release(rtld_bind_lock, lockstate); + return NULL; + } + + if (obj->mainprog) { + DoneList donelist; + + /* Search main program and all libraries loaded by it. */ + donelist_init(&donelist); + def = symlook_list(name, hash, &list_main, &defobj, true, + &donelist); + } else { + /* + * XXX - This isn't correct. The search should include the whole + * DAG rooted at the given object. + */ + def = symlook_obj(name, hash, obj, true); + defobj = obj; + } + } + + if (def != NULL) { + rlock_release(rtld_bind_lock, lockstate); + + /* + * The value required by the caller is derived from the value + * of the symbol. For the ia64 architecture, we need to + * construct a function descriptor which the caller can use to + * call the function with the right 'gp' value. For other + * architectures and for non-functions, the value is simply + * the relocated value of the symbol. + */ + if (ELF_ST_TYPE(def->st_info) == STT_FUNC) + return make_function_pointer(def, defobj); + else + return defobj->relocbase + def->st_value; + } + + _rtld_error("Undefined symbol \"%s\"", name); + rlock_release(rtld_bind_lock, lockstate); + return NULL; +} + +int +dladdr(const void *addr, Dl_info *info) +{ + const Obj_Entry *obj; + const Elf_Sym *def; + void *symbol_addr; + unsigned long symoffset; + int lockstate; + + lockstate = rlock_acquire(rtld_bind_lock); + obj = obj_from_addr(addr); + if (obj == NULL) { + _rtld_error("No shared object contains address"); + rlock_release(rtld_bind_lock, lockstate); + return 0; + } + info->dli_fname = obj->path; + info->dli_fbase = obj->mapbase; + info->dli_saddr = (void *)0; + info->dli_sname = NULL; + + /* + * Walk the symbol list looking for the symbol whose address is + * closest to the address sent in. + */ + for (symoffset = 0; symoffset < obj->nchains; symoffset++) { + def = obj->symtab + symoffset; + + /* + * For skip the symbol if st_shndx is either SHN_UNDEF or + * SHN_COMMON. + */ + if (def->st_shndx == SHN_UNDEF || def->st_shndx == SHN_COMMON) + continue; + + /* + * If the symbol is greater than the specified address, or if it + * is further away from addr than the current nearest symbol, + * then reject it. + */ + symbol_addr = obj->relocbase + def->st_value; + if (symbol_addr > addr || symbol_addr < info->dli_saddr) + continue; + + /* Update our idea of the nearest symbol. */ + info->dli_sname = obj->strtab + def->st_name; + info->dli_saddr = symbol_addr; + + /* Exact match? */ + if (info->dli_saddr == addr) + break; + } + rlock_release(rtld_bind_lock, lockstate); + return 1; +} + +int +dlinfo(void *handle, int request, void *p) +{ + const Obj_Entry *obj; + int error, lockstate; + + lockstate = rlock_acquire(rtld_bind_lock); + + if (handle == NULL || handle == RTLD_SELF) { + void *retaddr; + + retaddr = __builtin_return_address(0); /* __GNUC__ only */ + if ((obj = obj_from_addr(retaddr)) == NULL) + _rtld_error("Cannot determine caller's shared object"); + } else + obj = dlcheck(handle); + + if (obj == NULL) { + rlock_release(rtld_bind_lock, lockstate); + return (-1); + } + + error = 0; + switch (request) { + case RTLD_DI_LINKMAP: + *((struct link_map const **)p) = &obj->linkmap; + break; + case RTLD_DI_ORIGIN: + error = rtld_dirname(obj->path, p); + break; + + case RTLD_DI_SERINFOSIZE: + case RTLD_DI_SERINFO: + error = do_search_info(obj, request, (struct dl_serinfo *)p); + break; + + default: + _rtld_error("Invalid request %d passed to dlinfo()", request); + error = -1; + } + + rlock_release(rtld_bind_lock, lockstate); + + return (error); +} + +struct fill_search_info_args { + int request; + unsigned int flags; + Dl_serinfo *serinfo; + Dl_serpath *serpath; + char *strspace; +}; + +static void * +fill_search_info(const char *dir, size_t dirlen, void *param) +{ + struct fill_search_info_args *arg; + + arg = param; + + if (arg->request == RTLD_DI_SERINFOSIZE) { + arg->serinfo->dls_cnt ++; + arg->serinfo->dls_size += sizeof(Dl_serpath) + dirlen + 1; + } else { + struct dl_serpath *s_entry; + + s_entry = arg->serpath; + s_entry->dls_name = arg->strspace; + s_entry->dls_flags = arg->flags; + + strncpy(arg->strspace, dir, dirlen); + arg->strspace[dirlen] = '\0'; + + arg->strspace += dirlen + 1; + arg->serpath++; + } + + return (NULL); +} + +static int +do_search_info(const Obj_Entry *obj, int request, struct dl_serinfo *info) +{ + struct dl_serinfo _info; + struct fill_search_info_args args; + + args.request = RTLD_DI_SERINFOSIZE; + args.serinfo = &_info; + + _info.dls_size = __offsetof(struct dl_serinfo, dls_serpath); + _info.dls_cnt = 0; + + path_enumerate(ld_library_path, fill_search_info, &args); + path_enumerate(obj->rpath, fill_search_info, &args); + path_enumerate(gethints(), fill_search_info, &args); + path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args); + + + if (request == RTLD_DI_SERINFOSIZE) { + info->dls_size = _info.dls_size; + info->dls_cnt = _info.dls_cnt; + return (0); + } + + if (info->dls_cnt != _info.dls_cnt || info->dls_size != _info.dls_size) { + _rtld_error("Uninitialized Dl_serinfo struct passed to dlinfo()"); + return (-1); + } + + args.request = RTLD_DI_SERINFO; + args.serinfo = info; + args.serpath = &info->dls_serpath[0]; + args.strspace = (char *)&info->dls_serpath[_info.dls_cnt]; + + args.flags = LA_SER_LIBPATH; + if (path_enumerate(ld_library_path, fill_search_info, &args) != NULL) + return (-1); + + args.flags = LA_SER_RUNPATH; + if (path_enumerate(obj->rpath, fill_search_info, &args) != NULL) + return (-1); + + args.flags = LA_SER_CONFIG; + if (path_enumerate(gethints(), fill_search_info, &args) != NULL) + return (-1); + + args.flags = LA_SER_DEFAULT; + if (path_enumerate(STANDARD_LIBRARY_PATH, fill_search_info, &args) != NULL) + return (-1); + return (0); +} + +static int +rtld_dirname(const char *path, char *bname) +{ + const char *endp; + + /* Empty or NULL string gets treated as "." */ + if (path == NULL || *path == '\0') { + bname[0] = '.'; + bname[1] = '\0'; + return (0); + } + + /* Strip trailing slashes */ + endp = path + strlen(path) - 1; + while (endp > path && *endp == '/') + endp--; + + /* Find the start of the dir */ + while (endp > path && *endp != '/') + endp--; + + /* Either the dir is "/" or there are no slashes */ + if (endp == path) { + bname[0] = *endp == '/' ? '/' : '.'; + bname[1] = '\0'; + return (0); + } else { + do { + endp--; + } while (endp > path && *endp == '/'); + } + + if (endp - path + 2 > PATH_MAX) + { + _rtld_error("Filename is too long: %s", path); + return(-1); + } + + strncpy(bname, path, endp - path + 1); + bname[endp - path + 1] = '\0'; + return (0); +} + +static void +linkmap_add(Obj_Entry *obj) +{ + struct link_map *l = &obj->linkmap; + struct link_map *prev; + + obj->linkmap.l_name = obj->path; + obj->linkmap.l_addr = obj->mapbase; + obj->linkmap.l_ld = obj->dynamic; +#ifdef __mips__ + /* GDB needs load offset on MIPS to use the symbols */ + obj->linkmap.l_offs = obj->relocbase; +#endif + + if (r_debug.r_map == NULL) { + r_debug.r_map = l; + return; + } + + /* + * Scan to the end of the list, but not past the entry for the + * dynamic linker, which we want to keep at the very end. + */ + for (prev = r_debug.r_map; + prev->l_next != NULL && prev->l_next != &obj_rtld.linkmap; + prev = prev->l_next) + ; + + /* Link in the new entry. */ + l->l_prev = prev; + l->l_next = prev->l_next; + if (l->l_next != NULL) + l->l_next->l_prev = l; + prev->l_next = l; +} + +static void +linkmap_delete(Obj_Entry *obj) +{ + struct link_map *l = &obj->linkmap; + + if (l->l_prev == NULL) { + if ((r_debug.r_map = l->l_next) != NULL) + l->l_next->l_prev = NULL; + return; + } + + if ((l->l_prev->l_next = l->l_next) != NULL) + l->l_next->l_prev = l->l_prev; +} + +/* + * Function for the debugger to set a breakpoint on to gain control. + * + * The two parameters allow the debugger to easily find and determine + * what the runtime loader is doing and to whom it is doing it. + * + * When the loadhook trap is hit (r_debug_state, set at program + * initialization), the arguments can be found on the stack: + * + * +8 struct link_map *m + * +4 struct r_debug *rd + * +0 RetAddr + */ +void +r_debug_state(struct r_debug* rd, struct link_map *m) +{ +} + +/* + * Get address of the pointer variable in the main program. + */ +static const void ** +get_program_var_addr(const char *name) +{ + const Obj_Entry *obj; + unsigned long hash; + + hash = elf_hash(name); + for (obj = obj_main; obj != NULL; obj = obj->next) { + const Elf_Sym *def; + + if ((def = symlook_obj(name, hash, obj, false)) != NULL) { + const void **addr; + + addr = (const void **)(obj->relocbase + def->st_value); + return addr; + } + } + return NULL; +} + +/* + * Set a pointer variable in the main program to the given value. This + * is used to set key variables such as "environ" before any of the + * init functions are called. + */ +static void +set_program_var(const char *name, const void *value) +{ + const void **addr; + + if ((addr = get_program_var_addr(name)) != NULL) { + dbg("\"%s\": *%p <-- %p", name, addr, value); + *addr = value; + } +} + +/* + * Given a symbol name in a referencing object, find the corresponding + * definition of the symbol. Returns a pointer to the symbol, or NULL if + * no definition was found. Returns a pointer to the Obj_Entry of the + * defining object via the reference parameter DEFOBJ_OUT. + */ +static const Elf_Sym * +symlook_default(const char *name, unsigned long hash, + const Obj_Entry *refobj, const Obj_Entry **defobj_out, bool in_plt) +{ + DoneList donelist; + const Elf_Sym *def; + const Elf_Sym *symp; + const Obj_Entry *obj; + const Obj_Entry *defobj; + const Objlist_Entry *elm; + def = NULL; + defobj = NULL; + donelist_init(&donelist); + + /* Look first in the referencing object if linked symbolically. */ + if (refobj->symbolic && !donelist_check(&donelist, refobj)) { + symp = symlook_obj(name, hash, refobj, in_plt); + if (symp != NULL) { + def = symp; + defobj = refobj; + } + } + + /* Search all objects loaded at program start up. */ + if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) { + symp = symlook_list(name, hash, &list_main, &obj, in_plt, &donelist); + if (symp != NULL && + (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) { + def = symp; + defobj = obj; + } + } + + /* Search all DAGs whose roots are RTLD_GLOBAL objects. */ + STAILQ_FOREACH(elm, &list_global, link) { + if (def != NULL && ELF_ST_BIND(def->st_info) != STB_WEAK) + break; + symp = symlook_list(name, hash, &elm->obj->dagmembers, &obj, in_plt, + &donelist); + if (symp != NULL && + (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) { + def = symp; + defobj = obj; + } + } + + /* Search all dlopened DAGs containing the referencing object. */ + STAILQ_FOREACH(elm, &refobj->dldags, link) { + if (def != NULL && ELF_ST_BIND(def->st_info) != STB_WEAK) + break; + symp = symlook_list(name, hash, &elm->obj->dagmembers, &obj, in_plt, + &donelist); + if (symp != NULL && + (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK)) { + def = symp; + defobj = obj; + } + } + + /* + * Search the dynamic linker itself, and possibly resolve the + * symbol from there. This is how the application links to + * dynamic linker services such as dlopen. Only the values listed + * in the "exports" array can be resolved from the dynamic linker. + */ + if (def == NULL || ELF_ST_BIND(def->st_info) == STB_WEAK) { + symp = symlook_obj(name, hash, &obj_rtld, in_plt); + if (symp != NULL && is_exported(symp)) { + def = symp; + defobj = &obj_rtld; + } + } + + if (def != NULL) + *defobj_out = defobj; + return def; +} + +static const Elf_Sym * +symlook_list(const char *name, unsigned long hash, Objlist *objlist, + const Obj_Entry **defobj_out, bool in_plt, DoneList *dlp) +{ + const Elf_Sym *symp; + const Elf_Sym *def; + const Obj_Entry *defobj; + const Objlist_Entry *elm; + + def = NULL; + defobj = NULL; + STAILQ_FOREACH(elm, objlist, link) { + if (donelist_check(dlp, elm->obj)) + continue; + if ((symp = symlook_obj(name, hash, elm->obj, in_plt)) != NULL) { + if (def == NULL || ELF_ST_BIND(symp->st_info) != STB_WEAK) { + def = symp; + defobj = elm->obj; + if (ELF_ST_BIND(def->st_info) != STB_WEAK) + break; + } + } + } + if (def != NULL) + *defobj_out = defobj; + return def; +} + +/* + * Search the symbol table of a single shared object for a symbol of + * the given name. Returns a pointer to the symbol, or NULL if no + * definition was found. + * + * The symbol's hash value is passed in for efficiency reasons; that + * eliminates many recomputations of the hash value. + */ +const Elf_Sym * +symlook_obj(const char *name, unsigned long hash, const Obj_Entry *obj, + bool in_plt) +{ + if (obj->buckets != NULL) { + unsigned long symnum = obj->buckets[hash % obj->nbuckets]; + + while (symnum != STN_UNDEF) { + const Elf_Sym *symp; + const char *strp; + + if (symnum >= obj->nchains) + return NULL; /* Bad object */ + symp = obj->symtab + symnum; + strp = obj->strtab + symp->st_name; + + if (name[0] == strp[0] && strcmp(name, strp) == 0) + return symp->st_shndx != SHN_UNDEF || + (!in_plt && symp->st_value != 0 && + ELF_ST_TYPE(symp->st_info) == STT_FUNC) ? symp : NULL; + + symnum = obj->chains[symnum]; + } + } + return NULL; +} + +static void +trace_loaded_objects(Obj_Entry *obj) +{ + char *fmt1, *fmt2, *fmt, *main_local, *list_containers; + int c; + + if ((main_local = getenv(LD_ "TRACE_LOADED_OBJECTS_PROGNAME")) == NULL) + main_local = ""; + + if ((fmt1 = getenv(LD_ "TRACE_LOADED_OBJECTS_FMT1")) == NULL) + fmt1 = "\t%o => %p (%x)\n"; + + if ((fmt2 = getenv(LD_ "TRACE_LOADED_OBJECTS_FMT2")) == NULL) + fmt2 = "\t%o (%x)\n"; + + list_containers = getenv(LD_ "TRACE_LOADED_OBJECTS_ALL"); + + for (; obj; obj = obj->next) { + Needed_Entry *needed; + char *name, *path; + bool is_lib; + + if (list_containers && obj->needed != NULL) + printf("%s:\n", obj->path); + for (needed = obj->needed; needed; needed = needed->next) { + if (needed->obj != NULL) { + if (needed->obj->traced && !list_containers) + continue; + needed->obj->traced = true; + path = needed->obj->path; + } else + path = "not found"; + + name = (char *)obj->strtab + needed->name; + is_lib = strncmp(name, "lib", 3) == 0; /* XXX - bogus */ + + fmt = is_lib ? fmt1 : fmt2; + while ((c = *fmt++) != '\0') { + switch (c) { + default: + putchar(c); + continue; + case '\\': + switch (c = *fmt) { + case '\0': + continue; + case 'n': + putchar('\n'); + break; + case 't': + putchar('\t'); + break; + } + break; + case '%': + switch (c = *fmt) { + case '\0': + continue; + case '%': + default: + putchar(c); + break; + case 'A': + printf("%s", main_local); + break; + case 'a': + printf("%s", obj_main->path); + break; + case 'o': + printf("%s", name); + break; +#if 0 + case 'm': + printf("%d", sodp->sod_major); + break; + case 'n': + printf("%d", sodp->sod_minor); + break; +#endif + case 'p': + printf("%s", path); + break; + case 'x': + printf("%p", needed->obj ? needed->obj->mapbase : 0); + break; + } + break; + } + ++fmt; + } + } + } +} + +/* + * Unload a dlopened object and its dependencies from memory and from + * our data structures. It is assumed that the DAG rooted in the + * object has already been unreferenced, and that the object has a + * reference count of 0. + */ +static void +unload_object(Obj_Entry *root) +{ + Obj_Entry *obj; + Obj_Entry **linkp; + + assert(root->refcount == 0); + + /* + * Pass over the DAG removing unreferenced objects from + * appropriate lists. + */ + unlink_object(root); + + /* Unmap all objects that are no longer referenced. */ + linkp = &obj_list->next; + while ((obj = *linkp) != NULL) { + if (obj->refcount == 0) { + dbg("unloading \"%s\"", obj->path); + munmap(obj->mapbase, obj->mapsize); + linkmap_delete(obj); + *linkp = obj->next; + obj_count--; + obj_free(obj); + } else + linkp = &obj->next; + } + obj_tail = linkp; +} + +static void +unlink_object(Obj_Entry *root) +{ + Objlist_Entry *elm; + + if (root->refcount == 0) { + /* Remove the object from the RTLD_GLOBAL list. */ + objlist_remove(&list_global, root); + + /* Remove the object from all objects' DAG lists. */ + STAILQ_FOREACH(elm, &root->dagmembers , link) { + objlist_remove(&elm->obj->dldags, root); + if (elm->obj != root) + unlink_object(elm->obj); + } + } +} + +static void +ref_dag(Obj_Entry *root) +{ + Objlist_Entry *elm; + + STAILQ_FOREACH(elm, &root->dagmembers , link) + elm->obj->refcount++; +} + +static void +unref_dag(Obj_Entry *root) +{ + Objlist_Entry *elm; + + STAILQ_FOREACH(elm, &root->dagmembers , link) + elm->obj->refcount--; +} + +/* + * Common code for MD __tls_get_addr(). + */ +void * +tls_get_addr_common(Elf_Addr** dtvp, int index, size_t offset) +{ + Elf_Addr* dtv = *dtvp; + int lockstate; + + /* Check dtv generation in case new modules have arrived */ + if (dtv[0] != tls_dtv_generation) { + Elf_Addr* newdtv; + int to_copy; + + lockstate = wlock_acquire(rtld_bind_lock); + newdtv = calloc(1, (tls_max_index + 2) * sizeof(Elf_Addr)); + to_copy = dtv[1]; + if (to_copy > tls_max_index) + to_copy = tls_max_index; + memcpy(&newdtv[2], &dtv[2], to_copy * sizeof(Elf_Addr)); + newdtv[0] = tls_dtv_generation; + newdtv[1] = tls_max_index; + free(dtv); + wlock_release(rtld_bind_lock, lockstate); + *dtvp = newdtv; + } + + /* Dynamically allocate module TLS if necessary */ + if (!dtv[index + 1]) { + /* Signal safe, wlock will block out signals. */ + lockstate = wlock_acquire(rtld_bind_lock); + if (!dtv[index + 1]) + dtv[index + 1] = (Elf_Addr)allocate_module_tls(index); + wlock_release(rtld_bind_lock, lockstate); + } + return (void*) (dtv[index + 1] + offset); +} + +/* XXX not sure what variants to use for arm. */ + +#if defined(__ia64__) || defined(__alpha__) || defined(__powerpc__) + +/* + * Allocate Static TLS using the Variant I method. + */ +void * +allocate_tls(Obj_Entry *objs, void *oldtcb, size_t tcbsize, size_t tcbalign) +{ + Obj_Entry *obj; + char *tcb; + Elf_Addr **tls; + Elf_Addr *dtv; + Elf_Addr addr; + int i; + + if (oldtcb != NULL && tcbsize == TLS_TCB_SIZE) + return (oldtcb); + + assert(tcbsize >= TLS_TCB_SIZE); + tcb = calloc(1, tls_static_space - TLS_TCB_SIZE + tcbsize); + tls = (Elf_Addr **)(tcb + tcbsize - TLS_TCB_SIZE); + + if (oldtcb != NULL) { + memcpy(tls, oldtcb, tls_static_space); + free(oldtcb); + + /* Adjust the DTV. */ + dtv = tls[0]; + for (i = 0; i < dtv[1]; i++) { + if (dtv[i+2] >= (Elf_Addr)oldtcb && + dtv[i+2] < (Elf_Addr)oldtcb + tls_static_space) { + dtv[i+2] = dtv[i+2] - (Elf_Addr)oldtcb + (Elf_Addr)tls; + } + } + } else { + dtv = calloc(tls_max_index + 2, sizeof(Elf_Addr)); + tls[0] = dtv; + dtv[0] = tls_dtv_generation; + dtv[1] = tls_max_index; + + for (obj = objs; obj; obj = obj->next) { + if (obj->tlsoffset) { + addr = (Elf_Addr)tls + obj->tlsoffset; + memset((void*) (addr + obj->tlsinitsize), + 0, obj->tlssize - obj->tlsinitsize); + if (obj->tlsinit) + memcpy((void*) addr, obj->tlsinit, + obj->tlsinitsize); + dtv[obj->tlsindex + 1] = addr; + } + } + } + + return (tcb); +} + +void +free_tls(void *tcb, size_t tcbsize, size_t tcbalign) +{ + Elf_Addr *dtv; + Elf_Addr tlsstart, tlsend; + int dtvsize, i; + + assert(tcbsize >= TLS_TCB_SIZE); + + tlsstart = (Elf_Addr)tcb + tcbsize - TLS_TCB_SIZE; + tlsend = tlsstart + tls_static_space; + + dtv = *(Elf_Addr **)tlsstart; + dtvsize = dtv[1]; + for (i = 0; i < dtvsize; i++) { + if (dtv[i+2] && (dtv[i+2] < tlsstart || dtv[i+2] >= tlsend)) { + free((void*)dtv[i+2]); + } + } + free(dtv); + free(tcb); +} + +#endif + +#if defined(__i386__) || defined(__amd64__) || defined(__sparc64__) || \ + defined(__arm__) + +/* + * Allocate Static TLS using the Variant II method. + */ +void * +allocate_tls(Obj_Entry *objs, void *oldtls, size_t tcbsize, size_t tcbalign) +{ + Obj_Entry *obj; + size_t size; + char *tls; + Elf_Addr *dtv, *olddtv; + Elf_Addr segbase, oldsegbase, addr; + int i; + + size = round(tls_static_space, tcbalign); + + assert(tcbsize >= 2*sizeof(Elf_Addr)); + tls = malloc(size + tcbsize); + dtv = calloc(1, (tls_max_index + 2) * sizeof(Elf_Addr)); + + segbase = (Elf_Addr)(tls + size); + ((Elf_Addr*)segbase)[0] = segbase; + ((Elf_Addr*)segbase)[1] = (Elf_Addr) dtv; + + dtv[0] = tls_dtv_generation; + dtv[1] = tls_max_index; + + if (oldtls) { + /* + * Copy the static TLS block over whole. + */ + oldsegbase = (Elf_Addr) oldtls; + memcpy((void *)(segbase - tls_static_space), + (const void *)(oldsegbase - tls_static_space), + tls_static_space); + + /* + * If any dynamic TLS blocks have been created tls_get_addr(), + * move them over. + */ + olddtv = ((Elf_Addr**)oldsegbase)[1]; + for (i = 0; i < olddtv[1]; i++) { + if (olddtv[i+2] < oldsegbase - size || olddtv[i+2] > oldsegbase) { + dtv[i+2] = olddtv[i+2]; + olddtv[i+2] = 0; + } + } + + /* + * We assume that this block was the one we created with + * allocate_initial_tls(). + */ + free_tls(oldtls, 2*sizeof(Elf_Addr), sizeof(Elf_Addr)); + } else { + for (obj = objs; obj; obj = obj->next) { + if (obj->tlsoffset) { + addr = segbase - obj->tlsoffset; + memset((void*) (addr + obj->tlsinitsize), + 0, obj->tlssize - obj->tlsinitsize); + if (obj->tlsinit) + memcpy((void*) addr, obj->tlsinit, obj->tlsinitsize); + dtv[obj->tlsindex + 1] = addr; + } + } + } + + return (void*) segbase; +} + +void +free_tls(void *tls, size_t tcbsize, size_t tcbalign) +{ + size_t size; + Elf_Addr* dtv; + int dtvsize, i; + Elf_Addr tlsstart, tlsend; + + /* + * Figure out the size of the initial TLS block so that we can + * find stuff which ___tls_get_addr() allocated dynamically. + */ + size = round(tls_static_space, tcbalign); + + dtv = ((Elf_Addr**)tls)[1]; + dtvsize = dtv[1]; + tlsend = (Elf_Addr) tls; + tlsstart = tlsend - size; + for (i = 0; i < dtvsize; i++) { + if (dtv[i+2] && (dtv[i+2] < tlsstart || dtv[i+2] > tlsend)) { + free((void*) dtv[i+2]); + } + } + + free((void*) tlsstart); +} + +#endif + +/* + * Allocate TLS block for module with given index. + */ +void * +allocate_module_tls(int index) +{ + Obj_Entry* obj; + char* p; + + for (obj = obj_list; obj; obj = obj->next) { + if (obj->tlsindex == index) + break; + } + if (!obj) { + _rtld_error("Can't find module with TLS index %d", index); + die(); + } + + p = malloc(obj->tlssize); + memcpy(p, obj->tlsinit, obj->tlsinitsize); + memset(p + obj->tlsinitsize, 0, obj->tlssize - obj->tlsinitsize); + + return p; +} + +bool +allocate_tls_offset(Obj_Entry *obj) +{ + size_t off; + + if (obj->tls_done) + return true; + + if (obj->tlssize == 0) { + obj->tls_done = true; + return true; + } + + if (obj->tlsindex == 1) + off = calculate_first_tls_offset(obj->tlssize, obj->tlsalign); + else + off = calculate_tls_offset(tls_last_offset, tls_last_size, + obj->tlssize, obj->tlsalign); + + /* + * If we have already fixed the size of the static TLS block, we + * must stay within that size. When allocating the static TLS, we + * leave a small amount of space spare to be used for dynamically + * loading modules which use static TLS. + */ + if (tls_static_space) { + if (calculate_tls_end(off, obj->tlssize) > tls_static_space) + return false; + } + + tls_last_offset = obj->tlsoffset = off; + tls_last_size = obj->tlssize; + obj->tls_done = true; + + return true; +} + +void +free_tls_offset(Obj_Entry *obj) +{ +#if defined(__i386__) || defined(__amd64__) || defined(__sparc64__) || \ + defined(__arm__) + /* + * If we were the last thing to allocate out of the static TLS + * block, we give our space back to the 'allocator'. This is a + * simplistic workaround to allow libGL.so.1 to be loaded and + * unloaded multiple times. We only handle the Variant II + * mechanism for now - this really needs a proper allocator. + */ + if (calculate_tls_end(obj->tlsoffset, obj->tlssize) + == calculate_tls_end(tls_last_offset, tls_last_size)) { + tls_last_offset -= obj->tlssize; + tls_last_size = 0; + } +#endif +} + +void * +_rtld_allocate_tls(void *oldtls, size_t tcbsize, size_t tcbalign) +{ + void *ret; + int lockstate; + + lockstate = wlock_acquire(rtld_bind_lock); + ret = allocate_tls(obj_list, oldtls, tcbsize, tcbalign); + wlock_release(rtld_bind_lock, lockstate); + return (ret); +} + +void +_rtld_free_tls(void *tcb, size_t tcbsize, size_t tcbalign) +{ + int lockstate; + + lockstate = wlock_acquire(rtld_bind_lock); + free_tls(tcb, tcbsize, tcbalign); + wlock_release(rtld_bind_lock, lockstate); +} diff --git a/bin/rtld-elf/rtld.h b/bin/rtld-elf/rtld.h new file mode 100644 index 0000000..890c5e5 --- /dev/null +++ b/bin/rtld-elf/rtld.h @@ -0,0 +1,409 @@ +/*- + * Copyright 1996, 1997, 1998, 1999, 2000 John D. Polstra. + * 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. + * + * $FreeBSD: releng/10.2/libexec/rtld-elf/rtld.h 282118 2015-04-28 01:15:17Z emaste $ + */ + +#ifndef RTLD_H /* { */ +#define RTLD_H 1 + +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "rtld_lock.h" +#include "rtld_machdep.h" + +#ifdef COMPAT_32BIT +#undef STANDARD_LIBRARY_PATH +#undef _PATH_ELF_HINTS +#define _PATH_ELF_HINTS "/var/run/ld-elf32.so.hints" +/* For running 32 bit binaries */ +#define STANDARD_LIBRARY_PATH "/lib32:/usr/lib32" +#define LD_ "LD_32_" +#endif + +#ifndef STANDARD_LIBRARY_PATH +#define STANDARD_LIBRARY_PATH "/lib:/usr/lib" +#endif +#ifndef LD_ +#define LD_ "LD_" +#endif + +#define NEW(type) ((type *) xmalloc(sizeof(type))) +#define CNEW(type) ((type *) xcalloc(1, sizeof(type))) + +/* We might as well do booleans like C++. */ +typedef unsigned char bool; +#define false 0 +#define true 1 + +extern size_t tls_last_offset; +extern size_t tls_last_size; +extern size_t tls_static_space; +extern int tls_dtv_generation; +extern int tls_max_index; + +extern int npagesizes; +extern size_t *pagesizes; + +extern int main_argc; +extern char **main_argv; +extern char **environ; + +struct stat; +struct Struct_Obj_Entry; + +/* Lists of shared objects */ +typedef struct Struct_Objlist_Entry { + STAILQ_ENTRY(Struct_Objlist_Entry) link; + struct Struct_Obj_Entry *obj; +} Objlist_Entry; + +typedef STAILQ_HEAD(Struct_Objlist, Struct_Objlist_Entry) Objlist; + +/* Types of init and fini functions */ +typedef void (*InitFunc)(void); +typedef void (*InitArrFunc)(int, char **, char **); + +/* Lists of shared object dependencies */ +typedef struct Struct_Needed_Entry { + struct Struct_Needed_Entry *next; + struct Struct_Obj_Entry *obj; + unsigned long name; /* Offset of name in string table */ +} Needed_Entry; + +typedef struct Struct_Name_Entry { + STAILQ_ENTRY(Struct_Name_Entry) link; + char name[1]; +} Name_Entry; + +/* Lock object */ +typedef struct Struct_LockInfo { + void *context; /* Client context for creating locks */ + void *thelock; /* The one big lock */ + /* Debugging aids. */ + volatile int rcount; /* Number of readers holding lock */ + volatile int wcount; /* Number of writers holding lock */ + /* Methods */ + void *(*lock_create)(void *context); + void (*rlock_acquire)(void *lock); + void (*wlock_acquire)(void *lock); + void (*rlock_release)(void *lock); + void (*wlock_release)(void *lock); + void (*lock_destroy)(void *lock); + void (*context_destroy)(void *context); +} LockInfo; + +typedef struct Struct_Ver_Entry { + Elf_Word hash; + unsigned int flags; + const char *name; + const char *file; +} Ver_Entry; + +typedef struct Struct_Sym_Match_Result { + const Elf_Sym *sym_out; + const Elf_Sym *vsymp; + int vcount; +} Sym_Match_Result; + +#define VER_INFO_HIDDEN 0x01 + +/* + * Shared object descriptor. + * + * Items marked with "(%)" are dynamically allocated, and must be freed + * when the structure is destroyed. + * + * CAUTION: It appears that the JDK port peeks into these structures. + * It looks at "next" and "mapbase" at least. Don't add new members + * near the front, until this can be straightened out. + */ +typedef struct Struct_Obj_Entry { + /* + * These two items have to be set right for compatibility with the + * original ElfKit crt1.o. + */ + Elf_Size magic; /* Magic number (sanity check) */ + Elf_Size version; /* Version number of struct format */ + + struct Struct_Obj_Entry *next; + char *path; /* Pathname of underlying file (%) */ + char *origin_path; /* Directory path of origin file */ + int refcount; + int dl_refcount; /* Number of times loaded by dlopen */ + + /* These items are computed by map_object() or by digest_phdr(). */ + caddr_t mapbase; /* Base address of mapped region */ + size_t mapsize; /* Size of mapped region in bytes */ + size_t textsize; /* Size of text segment in bytes */ + Elf_Addr vaddrbase; /* Base address in shared object file */ + caddr_t relocbase; /* Relocation constant = mapbase - vaddrbase */ + const Elf_Dyn *dynamic; /* Dynamic section */ + caddr_t entry; /* Entry point */ + const Elf_Phdr *phdr; /* Program header if it is mapped, else NULL */ + size_t phsize; /* Size of program header in bytes */ + const char *interp; /* Pathname of the interpreter, if any */ + Elf_Word stack_flags; + + /* TLS information */ + int tlsindex; /* Index in DTV for this module */ + void *tlsinit; /* Base address of TLS init block */ + size_t tlsinitsize; /* Size of TLS init block for this module */ + size_t tlssize; /* Size of TLS block for this module */ + size_t tlsoffset; /* Offset of static TLS block for this module */ + size_t tlsalign; /* Alignment of static TLS block */ + + caddr_t relro_page; + size_t relro_size; + + /* Items from the dynamic section. */ + Elf_Addr *pltgot; /* PLT or GOT, depending on architecture */ + const Elf_Rel *rel; /* Relocation entries */ + unsigned long relsize; /* Size in bytes of relocation info */ + const Elf_Rela *rela; /* Relocation entries with addend */ + unsigned long relasize; /* Size in bytes of addend relocation info */ + const Elf_Rel *pltrel; /* PLT relocation entries */ + unsigned long pltrelsize; /* Size in bytes of PLT relocation info */ + const Elf_Rela *pltrela; /* PLT relocation entries with addend */ + unsigned long pltrelasize; /* Size in bytes of PLT addend reloc info */ + const Elf_Sym *symtab; /* Symbol table */ + const char *strtab; /* String table */ + unsigned long strsize; /* Size in bytes of string table */ +#ifdef __mips__ + Elf_Word local_gotno; /* Number of local GOT entries */ + Elf_Word symtabno; /* Number of dynamic symbols */ + Elf_Word gotsym; /* First dynamic symbol in GOT */ +#endif + + const Elf_Verneed *verneed; /* Required versions. */ + Elf_Word verneednum; /* Number of entries in verneed table */ + const Elf_Verdef *verdef; /* Provided versions. */ + Elf_Word verdefnum; /* Number of entries in verdef table */ + const Elf_Versym *versyms; /* Symbol versions table */ + + const Elf_Hashelt *buckets; /* Hash table buckets array */ + unsigned long nbuckets; /* Number of buckets */ + const Elf_Hashelt *chains; /* Hash table chain array */ + unsigned long nchains; /* Number of entries in chain array */ + + Elf32_Word nbuckets_gnu; /* Number of GNU hash buckets*/ + Elf32_Word symndx_gnu; /* 1st accessible symbol on dynsym table */ + Elf32_Word maskwords_bm_gnu; /* Bloom filter words - 1 (bitmask) */ + Elf32_Word shift2_gnu; /* Bloom filter shift count */ + Elf32_Word dynsymcount; /* Total entries in dynsym table */ + Elf_Addr *bloom_gnu; /* Bloom filter used by GNU hash func */ + const Elf_Hashelt *buckets_gnu; /* GNU hash table bucket array */ + const Elf_Hashelt *chain_zero_gnu; /* GNU hash table value array (Zeroed) */ + + char *rpath; /* Search path specified in object */ + char *runpath; /* Search path with different priority */ + Needed_Entry *needed; /* Shared objects needed by this one (%) */ + Needed_Entry *needed_filtees; + Needed_Entry *needed_aux_filtees; + + STAILQ_HEAD(, Struct_Name_Entry) names; /* List of names for this object we + know about. */ + Ver_Entry *vertab; /* Versions required /defined by this object */ + int vernum; /* Number of entries in vertab */ + + Elf_Addr init; /* Initialization function to call */ + Elf_Addr fini; /* Termination function to call */ + Elf_Addr preinit_array; /* Pre-initialization array of functions */ + Elf_Addr init_array; /* Initialization array of functions */ + Elf_Addr fini_array; /* Termination array of functions */ + int preinit_array_num; /* Number of entries in preinit_array */ + int init_array_num; /* Number of entries in init_array */ + int fini_array_num; /* Number of entries in fini_array */ + + int32_t osrel; /* OSREL note value */ + + bool mainprog : 1; /* True if this is the main program */ + bool rtld : 1; /* True if this is the dynamic linker */ + bool relocated : 1; /* True if processed by relocate_objects() */ + bool ver_checked : 1; /* True if processed by rtld_verify_object_versions */ + bool textrel : 1; /* True if there are relocations to text seg */ + bool symbolic : 1; /* True if generated with "-Bsymbolic" */ + bool bind_now : 1; /* True if all relocations should be made first */ + bool traced : 1; /* Already printed in ldd trace output */ + bool jmpslots_done : 1; /* Already have relocated the jump slots */ + bool init_done : 1; /* Already have added object to init list */ + bool tls_done : 1; /* Already allocated offset for static TLS */ + bool phdr_alloc : 1; /* Phdr is allocated and needs to be freed. */ + bool z_origin : 1; /* Process rpath and soname tokens */ + bool z_nodelete : 1; /* Do not unload the object and dependencies */ + bool z_noopen : 1; /* Do not load on dlopen */ + bool z_loadfltr : 1; /* Immediately load filtees */ + bool z_interpose : 1; /* Interpose all objects but main */ + bool z_nodeflib : 1; /* Don't search default library path */ + bool z_global : 1; /* Make the object global */ + bool ref_nodel : 1; /* Refcount increased to prevent dlclose */ + bool init_scanned: 1; /* Object is already on init list. */ + bool on_fini_list: 1; /* Object is already on fini list. */ + bool dag_inited : 1; /* Object has its DAG initialized. */ + bool filtees_loaded : 1; /* Filtees loaded */ + bool irelative : 1; /* Object has R_MACHDEP_IRELATIVE relocs */ + bool gnu_ifunc : 1; /* Object has references to STT_GNU_IFUNC */ + bool non_plt_gnu_ifunc : 1; /* Object has non-plt IFUNC references */ + bool crt_no_init : 1; /* Object' crt does not call _init/_fini */ + bool valid_hash_sysv : 1; /* A valid System V hash hash tag is available */ + bool valid_hash_gnu : 1; /* A valid GNU hash tag is available */ + bool dlopened : 1; /* dlopen()-ed (vs. load statically) */ + + struct link_map linkmap; /* For GDB and dlinfo() */ + Objlist dldags; /* Object belongs to these dlopened DAGs (%) */ + Objlist dagmembers; /* DAG has these members (%) */ + dev_t dev; /* Object's filesystem's device */ + ino_t ino; /* Object's inode number */ + void *priv; /* Platform-dependent */ +} Obj_Entry; + +#define RTLD_MAGIC 0xd550b87a +#define RTLD_VERSION 1 + +#define RTLD_STATIC_TLS_EXTRA 128 + +/* Flags to be passed into symlook_ family of functions. */ +#define SYMLOOK_IN_PLT 0x01 /* Lookup for PLT symbol */ +#define SYMLOOK_DLSYM 0x02 /* Return newest versioned symbol. Used by + dlsym. */ +#define SYMLOOK_EARLY 0x04 /* Symlook is done during initialization. */ +#define SYMLOOK_IFUNC 0x08 /* Allow IFUNC processing in + reloc_non_plt(). */ + +/* Flags for load_object(). */ +#define RTLD_LO_NOLOAD 0x01 /* dlopen() specified RTLD_NOLOAD. */ +#define RTLD_LO_DLOPEN 0x02 /* Load_object() called from dlopen(). */ +#define RTLD_LO_TRACE 0x04 /* Only tracing. */ +#define RTLD_LO_NODELETE 0x08 /* Loaded object cannot be closed. */ +#define RTLD_LO_FILTEES 0x10 /* Loading filtee. */ +#define RTLD_LO_EARLY 0x20 /* Do not call ctors, postpone it to the + initialization during the image start. */ + +/* + * Symbol cache entry used during relocation to avoid multiple lookups + * of the same symbol. + */ +typedef struct Struct_SymCache { + const Elf_Sym *sym; /* Symbol table entry */ + const Obj_Entry *obj; /* Shared object which defines it */ +} SymCache; + +/* + * This structure provides a reentrant way to keep a list of objects and + * check which ones have already been processed in some way. + */ +typedef struct Struct_DoneList { + const Obj_Entry **objs; /* Array of object pointers */ + unsigned int num_alloc; /* Allocated size of the array */ + unsigned int num_used; /* Number of array slots used */ +} DoneList; + +struct Struct_RtldLockState { + int lockstate; + sigjmp_buf env; +}; + +struct fill_search_info_args { + int request; + unsigned int flags; + struct dl_serinfo *serinfo; + struct dl_serpath *serpath; + char *strspace; +}; + +/* + * The pack of arguments and results for the symbol lookup functions. + */ +typedef struct Struct_SymLook { + const char *name; + unsigned long hash; + uint32_t hash_gnu; + const Ver_Entry *ventry; + int flags; + const Obj_Entry *defobj_out; + const Elf_Sym *sym_out; + struct Struct_RtldLockState *lockstate; +} SymLook; + +void _rtld_error(const char *, ...) __printflike(1, 2) __exported; +void rtld_die(void) __dead2; +const char *rtld_strerror(int); +Obj_Entry *map_object(int, const char *, const struct stat *); +void *xcalloc(size_t, size_t); +void *xmalloc(size_t); +char *xstrdup(const char *); +void *malloc_aligned(size_t size, size_t align); +void free_aligned(void *ptr); +extern Elf_Addr _GLOBAL_OFFSET_TABLE_[]; +extern Elf_Sym sym_zero; /* For resolving undefined weak refs. */ + +void dump_relocations(Obj_Entry *); +void dump_obj_relocations(Obj_Entry *); +void dump_Elf_Rel(Obj_Entry *, const Elf_Rel *, u_long); +void dump_Elf_Rela(Obj_Entry *, const Elf_Rela *, u_long); + +/* + * Function declarations. + */ +unsigned long elf_hash(const char *); +const Elf_Sym *find_symdef(unsigned long, const Obj_Entry *, + const Obj_Entry **, int, SymCache *, struct Struct_RtldLockState *); +void init_pltgot(Obj_Entry *); +void lockdflt_init(void); +void digest_notes(Obj_Entry *, Elf_Addr, Elf_Addr); +void obj_free(Obj_Entry *); +Obj_Entry *obj_new(void); +void _rtld_bind_start(void); +void *rtld_resolve_ifunc(const Obj_Entry *obj, const Elf_Sym *def); +void symlook_init(SymLook *, const char *); +int symlook_obj(SymLook *, const Obj_Entry *); +void *tls_get_addr_common(Elf_Addr** dtvp, int index, size_t offset); +void *allocate_tls(Obj_Entry *, void *, size_t, size_t); +void free_tls(void *, size_t, size_t); +void *allocate_module_tls(int index); +bool allocate_tls_offset(Obj_Entry *obj); +void free_tls_offset(Obj_Entry *obj); +const Ver_Entry *fetch_ventry(const Obj_Entry *obj, unsigned long); + +/* + * MD function declarations. + */ +int do_copy_relocations(Obj_Entry *); +int reloc_non_plt(Obj_Entry *, Obj_Entry *, int flags, + struct Struct_RtldLockState *); +int reloc_plt(Obj_Entry *); +int reloc_jmpslots(Obj_Entry *, int flags, struct Struct_RtldLockState *); +int reloc_iresolve(Obj_Entry *, struct Struct_RtldLockState *); +int reloc_gnu_ifunc(Obj_Entry *, int flags, struct Struct_RtldLockState *); +void allocate_initial_tls(Obj_Entry *); + +#endif /* } */ diff --git a/bin/rtld-elf/rtld_lock.c b/bin/rtld-elf/rtld_lock.c new file mode 100644 index 0000000..0e4babf --- /dev/null +++ b/bin/rtld-elf/rtld_lock.c @@ -0,0 +1,404 @@ +/*- + * Copyright 1999, 2000 John D. Polstra. + * 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. + * + * from: FreeBSD: src/libexec/rtld-elf/sparc64/lockdflt.c,v 1.3 2002/10/09 + * $FreeBSD: releng/10.2/libexec/rtld-elf/rtld_lock.c 281453 2015-04-12 06:45:40Z kib $ + */ + +/* + * Thread locking implementation for the dynamic linker. + * + * We use the "simple, non-scalable reader-preference lock" from: + * + * J. M. Mellor-Crummey and M. L. Scott. "Scalable Reader-Writer + * Synchronization for Shared-Memory Multiprocessors." 3rd ACM Symp. on + * Principles and Practice of Parallel Programming, April 1991. + * + * In this algorithm the lock is a single word. Its low-order bit is + * set when a writer holds the lock. The remaining high-order bits + * contain a count of readers desiring the lock. The algorithm requires + * atomic "compare_and_store" and "add" operations, which we implement + * using assembly language sequences in "rtld_start.S". + */ + +#include +#include +#include +#include + +#include "debug.h" +#include "rtld.h" +#include "rtld_machdep.h" + +void _rtld_thread_init(struct RtldLockInfo *) __exported; +void _rtld_atfork_pre(int *) __exported; +void _rtld_atfork_post(int *) __exported; + +#define WAFLAG 0x1 /* A writer holds the lock */ +#define RC_INCR 0x2 /* Adjusts count of readers desiring lock */ + +typedef struct Struct_Lock { + volatile u_int lock; + void *base; +} Lock; + +static sigset_t fullsigmask, oldsigmask; +static int thread_flag; + +static void * +def_lock_create() +{ + void *base; + char *p; + uintptr_t r; + Lock *l; + + /* + * Arrange for the lock to occupy its own cache line. First, we + * optimistically allocate just a cache line, hoping that malloc + * will give us a well-aligned block of memory. If that doesn't + * work, we allocate a larger block and take a well-aligned cache + * line from it. + */ + base = xmalloc(CACHE_LINE_SIZE); + p = (char *)base; + if ((uintptr_t)p % CACHE_LINE_SIZE != 0) { + free(base); + base = xmalloc(2 * CACHE_LINE_SIZE); + p = (char *)base; + if ((r = (uintptr_t)p % CACHE_LINE_SIZE) != 0) + p += CACHE_LINE_SIZE - r; + } + l = (Lock *)p; + l->base = base; + l->lock = 0; + return l; +} + +static void +def_lock_destroy(void *lock) +{ + Lock *l = (Lock *)lock; + + free(l->base); +} + +static void +def_rlock_acquire(void *lock) +{ + Lock *l = (Lock *)lock; + + atomic_add_acq_int(&l->lock, RC_INCR); + while (l->lock & WAFLAG) + ; /* Spin */ +} + +static void +def_wlock_acquire(void *lock) +{ + Lock *l = (Lock *)lock; + sigset_t tmp_oldsigmask; + + for ( ; ; ) { + sigprocmask(SIG_BLOCK, &fullsigmask, &tmp_oldsigmask); + if (atomic_cmpset_acq_int(&l->lock, 0, WAFLAG)) + break; + sigprocmask(SIG_SETMASK, &tmp_oldsigmask, NULL); + } + oldsigmask = tmp_oldsigmask; +} + +static void +def_lock_release(void *lock) +{ + Lock *l = (Lock *)lock; + + if ((l->lock & WAFLAG) == 0) + atomic_add_rel_int(&l->lock, -RC_INCR); + else { + atomic_add_rel_int(&l->lock, -WAFLAG); + sigprocmask(SIG_SETMASK, &oldsigmask, NULL); + } +} + +static int +def_thread_set_flag(int mask) +{ + int old_val = thread_flag; + thread_flag |= mask; + return (old_val); +} + +static int +def_thread_clr_flag(int mask) +{ + int old_val = thread_flag; + thread_flag &= ~mask; + return (old_val); +} + +/* + * Public interface exposed to the rest of the dynamic linker. + */ +static struct RtldLockInfo lockinfo; +static struct RtldLockInfo deflockinfo; + +static __inline int +thread_mask_set(int mask) +{ + return lockinfo.thread_set_flag(mask); +} + +static __inline void +thread_mask_clear(int mask) +{ + lockinfo.thread_clr_flag(mask); +} + +#define RTLD_LOCK_CNT 3 +struct rtld_lock { + void *handle; + int mask; +} rtld_locks[RTLD_LOCK_CNT]; + +rtld_lock_t rtld_bind_lock = &rtld_locks[0]; +rtld_lock_t rtld_libc_lock = &rtld_locks[1]; +rtld_lock_t rtld_phdr_lock = &rtld_locks[2]; + +void +rlock_acquire(rtld_lock_t lock, RtldLockState *lockstate) +{ + + if (lockstate == NULL) + return; + + if (thread_mask_set(lock->mask) & lock->mask) { + dbg("rlock_acquire: recursed"); + lockstate->lockstate = RTLD_LOCK_UNLOCKED; + return; + } + lockinfo.rlock_acquire(lock->handle); + lockstate->lockstate = RTLD_LOCK_RLOCKED; +} + +void +wlock_acquire(rtld_lock_t lock, RtldLockState *lockstate) +{ + + if (lockstate == NULL) + return; + + if (thread_mask_set(lock->mask) & lock->mask) { + dbg("wlock_acquire: recursed"); + lockstate->lockstate = RTLD_LOCK_UNLOCKED; + return; + } + lockinfo.wlock_acquire(lock->handle); + lockstate->lockstate = RTLD_LOCK_WLOCKED; +} + +void +lock_release(rtld_lock_t lock, RtldLockState *lockstate) +{ + + if (lockstate == NULL) + return; + + switch (lockstate->lockstate) { + case RTLD_LOCK_UNLOCKED: + break; + case RTLD_LOCK_RLOCKED: + case RTLD_LOCK_WLOCKED: + thread_mask_clear(lock->mask); + lockinfo.lock_release(lock->handle); + break; + default: + assert(0); + } +} + +void +lock_upgrade(rtld_lock_t lock, RtldLockState *lockstate) +{ + + if (lockstate == NULL) + return; + + lock_release(lock, lockstate); + wlock_acquire(lock, lockstate); +} + +void +lock_restart_for_upgrade(RtldLockState *lockstate) +{ + + if (lockstate == NULL) + return; + + switch (lockstate->lockstate) { + case RTLD_LOCK_UNLOCKED: + case RTLD_LOCK_WLOCKED: + break; + case RTLD_LOCK_RLOCKED: + siglongjmp(lockstate->env, 1); + break; + default: + assert(0); + } +} + +void +lockdflt_init() +{ + int i; + + deflockinfo.rtli_version = RTLI_VERSION; + deflockinfo.lock_create = def_lock_create; + deflockinfo.lock_destroy = def_lock_destroy; + deflockinfo.rlock_acquire = def_rlock_acquire; + deflockinfo.wlock_acquire = def_wlock_acquire; + deflockinfo.lock_release = def_lock_release; + deflockinfo.thread_set_flag = def_thread_set_flag; + deflockinfo.thread_clr_flag = def_thread_clr_flag; + deflockinfo.at_fork = NULL; + + for (i = 0; i < RTLD_LOCK_CNT; i++) { + rtld_locks[i].mask = (1 << i); + rtld_locks[i].handle = NULL; + } + + memcpy(&lockinfo, &deflockinfo, sizeof(lockinfo)); + _rtld_thread_init(NULL); + /* + * Construct a mask to block all signals except traps which might + * conceivably be generated within the dynamic linker itself. + */ + sigfillset(&fullsigmask); + sigdelset(&fullsigmask, SIGILL); + sigdelset(&fullsigmask, SIGTRAP); + sigdelset(&fullsigmask, SIGABRT); + sigdelset(&fullsigmask, SIGEMT); + sigdelset(&fullsigmask, SIGFPE); + sigdelset(&fullsigmask, SIGBUS); + sigdelset(&fullsigmask, SIGSEGV); + sigdelset(&fullsigmask, SIGSYS); +} + +/* + * Callback function to allow threads implementation to + * register their own locking primitives if the default + * one is not suitable. + * The current context should be the only context + * executing at the invocation time. + */ +void +_rtld_thread_init(struct RtldLockInfo *pli) +{ + int flags, i; + void *locks[RTLD_LOCK_CNT]; + + /* disable all locking while this function is running */ + flags = thread_mask_set(~0); + + if (pli == NULL) + pli = &deflockinfo; + + + for (i = 0; i < RTLD_LOCK_CNT; i++) + if ((locks[i] = pli->lock_create()) == NULL) + break; + + if (i < RTLD_LOCK_CNT) { + while (--i >= 0) + pli->lock_destroy(locks[i]); + abort(); + } + + for (i = 0; i < RTLD_LOCK_CNT; i++) { + if (rtld_locks[i].handle == NULL) + continue; + if (flags & rtld_locks[i].mask) + lockinfo.lock_release(rtld_locks[i].handle); + lockinfo.lock_destroy(rtld_locks[i].handle); + } + + for (i = 0; i < RTLD_LOCK_CNT; i++) { + rtld_locks[i].handle = locks[i]; + if (flags & rtld_locks[i].mask) + pli->wlock_acquire(rtld_locks[i].handle); + } + + lockinfo.lock_create = pli->lock_create; + lockinfo.lock_destroy = pli->lock_destroy; + lockinfo.rlock_acquire = pli->rlock_acquire; + lockinfo.wlock_acquire = pli->wlock_acquire; + lockinfo.lock_release = pli->lock_release; + lockinfo.thread_set_flag = pli->thread_set_flag; + lockinfo.thread_clr_flag = pli->thread_clr_flag; + lockinfo.at_fork = pli->at_fork; + + /* restore thread locking state, this time with new locks */ + thread_mask_clear(~0); + thread_mask_set(flags); + dbg("_rtld_thread_init: done"); +} + +void +_rtld_atfork_pre(int *locks) +{ + RtldLockState ls[2]; + + if (locks == NULL) + return; + + /* + * Warning: this does not work with the rtld compat locks + * above, since the thread signal mask is corrupted (set to + * all signals blocked) if two locks are taken in write mode. + * The caller of the _rtld_atfork_pre() must provide the + * working implementation of the locks, and libthr locks are + * fine. + */ + wlock_acquire(rtld_phdr_lock, &ls[0]); + wlock_acquire(rtld_bind_lock, &ls[1]); + + /* XXXKIB: I am really sorry for this. */ + locks[0] = ls[1].lockstate; + locks[2] = ls[0].lockstate; +} + +void +_rtld_atfork_post(int *locks) +{ + RtldLockState ls[2]; + + if (locks == NULL) + return; + + bzero(ls, sizeof(ls)); + ls[0].lockstate = locks[2]; + ls[1].lockstate = locks[0]; + lock_release(rtld_bind_lock, &ls[1]); + lock_release(rtld_phdr_lock, &ls[0]); +} diff --git a/bin/rtld-elf/rtld_lock.h b/bin/rtld-elf/rtld_lock.h new file mode 100644 index 0000000..f30c63f --- /dev/null +++ b/bin/rtld-elf/rtld_lock.h @@ -0,0 +1,75 @@ +/*- + * Copyright 2003 Alexander Kabaev. + * 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. + * + * $FreeBSD: releng/10.2/libexec/rtld-elf/rtld_lock.h 281453 2015-04-12 06:45:40Z kib $ + */ + +#ifndef _RTLD_LOCK_H_ +#define _RTLD_LOCK_H_ + +#define RTLI_VERSION 0x01 +#define MAX_RTLD_LOCKS 8 + +struct RtldLockInfo +{ + unsigned int rtli_version; + void *(*lock_create)(void); + void (*lock_destroy)(void *); + void (*rlock_acquire)(void *); + void (*wlock_acquire)(void *); + void (*lock_release)(void *); + int (*thread_set_flag)(int); + int (*thread_clr_flag)(int); + void (*at_fork)(void); +}; + +extern void _rtld_thread_init(struct RtldLockInfo *) __exported; +extern void _rtld_atfork_pre(int *) __exported; +extern void _rtld_atfork_post(int *) __exported; + +#ifdef IN_RTLD + +struct rtld_lock; +typedef struct rtld_lock *rtld_lock_t; + +extern rtld_lock_t rtld_bind_lock; +extern rtld_lock_t rtld_libc_lock; +extern rtld_lock_t rtld_phdr_lock; + +#define RTLD_LOCK_UNLOCKED 0 +#define RTLD_LOCK_RLOCKED 1 +#define RTLD_LOCK_WLOCKED 2 + +struct Struct_RtldLockState; +typedef struct Struct_RtldLockState RtldLockState; + +void rlock_acquire(rtld_lock_t, RtldLockState *); +void wlock_acquire(rtld_lock_t, RtldLockState *); +void lock_release(rtld_lock_t, RtldLockState *); +void lock_upgrade(rtld_lock_t, RtldLockState *); +void lock_restart_for_upgrade(RtldLockState *); + +#endif /* IN_RTLD */ + +#endif diff --git a/bin/rtld-elf/rtld_machdep.h b/bin/rtld-elf/rtld_machdep.h new file mode 100644 index 0000000..3b2ccb9 --- /dev/null +++ b/bin/rtld-elf/rtld_machdep.h @@ -0,0 +1,83 @@ +/*- + * Copyright (c) 1999, 2000 John D. Polstra. + * 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 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 AUTHOR 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. + * + * $FreeBSD: releng/10.2/libexec/rtld-elf/i386/rtld_machdep.h 281453 2015-04-12 06:45:40Z kib $ + */ + +#ifndef RTLD_MACHDEP_H +#define RTLD_MACHDEP_H 1 + +#include +#include + +struct Struct_Obj_Entry; + +/* Return the address of the .dynamic section in the dynamic linker. */ +#define rtld_dynamic(obj) \ + ((const Elf_Dyn *)((obj)->relocbase + (Elf_Addr)&_DYNAMIC)) + +/* Fixup the jump slot at "where" to transfer control to "target". */ +static inline Elf_Addr +reloc_jmpslot(Elf_Addr *where, Elf_Addr target, + const struct Struct_Obj_Entry *obj, + const struct Struct_Obj_Entry *refobj, const Elf_Rel *rel) +{ +#ifdef dbg + dbg("reloc_jmpslot: *%p = %p", (void *)(where), + (void *)(target)); +#endif + (*(Elf_Addr *)(where) = (Elf_Addr)(target)); + return target; +} + +#define make_function_pointer(def, defobj) \ + ((defobj)->relocbase + (def)->st_value) + +#define call_initfini_pointer(obj, target) \ + (((InitFunc)(target))()) + +#define call_init_pointer(obj, target) \ + (((InitArrFunc)(target))(main_argc, main_argv, environ)) + +#define round(size, align) \ + (((size) + (align) - 1) & ~((align) - 1)) +#define calculate_first_tls_offset(size, align) \ + round(size, align) +#define calculate_tls_offset(prev_offset, prev_size, size, align) \ + round((prev_offset) + (size), align) +#define calculate_tls_end(off, size) (off) + +typedef struct { + unsigned long ti_module; + unsigned long ti_offset; +} tls_index; + +void *___tls_get_addr(tls_index *ti) __attribute__((__regparm__(1))) __exported; +void *__tls_get_addr(tls_index *ti) __exported; + +#define RTLD_DEFAULT_STACK_PF_EXEC PF_X +#define RTLD_DEFAULT_STACK_EXEC PROT_EXEC + +#endif diff --git a/bin/rtld-elf/rtld_printf.h b/bin/rtld-elf/rtld_printf.h new file mode 100644 index 0000000..b37bee6 --- /dev/null +++ b/bin/rtld-elf/rtld_printf.h @@ -0,0 +1,44 @@ +/*- + * Copyright 2011 Konstantin Belousov . + * 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. + * + * $FreeBSD: releng/10.2/libexec/rtld-elf/rtld_printf.h 225152 2011-08-24 20:05:13Z kib $ + */ + +#ifndef RTLD_PRINTF_H +#define RTLD_PRINTF_H 1 + +#include +#include + +int rtld_vsnprintf(char *buf, size_t bufsize, const char *fmt, va_list ap); +int rtld_vfdprintf(int fd, const char *fmt, va_list ap); +int rtld_fdprintf(int fd, const char *fmt, ...) __printflike(2, 3); +void rtld_fdputstr(int fd, const char *str); +void rtld_fdputchar(int fd, int c); + +#define rtld_printf(...) rtld_fdprintf(STDOUT_FILENO, __VA_ARGS__) +#define rtld_putstr(str) rtld_fdputstr(STDOUT_FILENO, (str)) +#define rtld_putchar(c) rtld_fdputchar(STDOUT_FILENO, (c)) + +#endif diff --git a/bin/rtld-elf/rtld_start.S b/bin/rtld-elf/rtld_start.S new file mode 100644 index 0000000..65d900d --- /dev/null +++ b/bin/rtld-elf/rtld_start.S @@ -0,0 +1,91 @@ +/*- + * Copyright 1996-1998 John D. Polstra. + * 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. + * + * $FreeBSD: src/libexec/rtld-elf/i386/rtld_start.S,v 1.4 2005/05/19 07:32:42 dfr Exp $ + */ + + .text + .align 4 + .globl .rtld_start + .type .rtld_start,@function +.rtld_start: + xorl %ebp,%ebp # Clear frame pointer for good form + movl %esp,%eax # Save initial stack pointer + movl %esp,%esi # Save initial stack pointer + andl $0xfffffff0,%esp # Align stack pointer + subl $16,%esp # A place to store exit procedure addr + movl %esp,%ebx # save address of exit proc + movl %esp,%ecx # construct address of obj_main + addl $4,%ecx + subl $4,%esp # Keep stack aligned + pushl %ecx # Pass address of obj_main + pushl %ebx # Pass address of exit proc + pushl %eax # Pass initial stack pointer to rtld + call _rtld@PLT # Call rtld(sp); returns entry point + addl $16,%esp # Remove arguments from stack + popl %edx # Get exit procedure address + movl %esi,%esp # Ignore obj_main +/* + * At this point, %eax contains the entry point of the main program, and + * %edx contains a pointer to a termination function that should be + * registered with atexit(). (crt1.o registers it.) + */ +.globl .rtld_goto_main +.rtld_goto_main: # This symbol exists just to make debugging easier. + jmp *%eax # Enter main program + + +/* + * Binder entry point. Control is transferred to here by code in the PLT. + * On entry, there are two arguments on the stack. In ascending address + * order, they are (1) "obj", a pointer to the calling object's Obj_Entry, + * and (2) "reloff", the byte offset of the appropriate relocation entry + * in the PLT relocation table. + * + * We are careful to preserve all registers, even the the caller-save + * registers. That is because this code may be invoked by low-level + * assembly-language code that is not ABI-compliant. + */ + .align 4 + .globl _rtld_bind_start + .type _rtld_bind_start,@function +_rtld_bind_start: + pushf # Save eflags + pushl %eax # Save %eax + pushl %edx # Save %edx + pushl %ecx # Save %ecx + pushl 20(%esp) # Copy reloff argument + pushl 20(%esp) # Copy obj argument + + call _rtld_bind@PLT # Transfer control to the binder + /* Now %eax contains the entry point of the function being called. */ + + addl $8,%esp # Discard binder arguments + movl %eax,20(%esp) # Store target over obj argument + popl %ecx # Restore %ecx + popl %edx # Restore %edx + popl %eax # Restore %eax + popf # Restore eflags + leal 4(%esp),%esp # Discard reloff, do not change eflags + ret # "Return" to target address diff --git a/bin/rtld-elf/rtld_tls.h b/bin/rtld-elf/rtld_tls.h new file mode 100644 index 0000000..4e17934 --- /dev/null +++ b/bin/rtld-elf/rtld_tls.h @@ -0,0 +1,69 @@ +/*- + * Copyright (c) 2004 Doug Rabson + * 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 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 AUTHOR 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. + * + * $FreeBSD: src/libexec/rtld-elf/rtld_tls.h,v 1.1 2004/08/03 08:50:58 dfr Exp $ + */ + +/* + * Semi-public interface from thread libraries to rtld for managing + * TLS. + */ + +#ifndef _RTLD_TLS_H_ +#define _RTLD_TLS_H_ + +/* + * Allocate a TLS block for a new thread. The memory allocated will + * include 'tcbsize' bytes aligned to a 'tcbalign' boundary (in bytes) + * for the thread library's private purposes. The location of the TCB + * block is returned by this function. For architectures using + * 'Variant I' TLS, the thread local storage follows the TCB, and for + * 'Variant II', the thread local storage precedes it. For + * architectures using the 'Variant II' model (e.g. i386, amd64, + * sparc64), the TCB must begin with two pointer fields which are used + * by rtld for its TLS implementation. For the 'Variant I' model, the + * TCB must begin with a single pointer field for rtld's + * implementation. + * + * If the value of 'oldtls' is non-NULL, the new TLS block will be + * initialised using the values contained in 'oldtls' and 'oldtls' + * will be freed. This is typically used when initialising a thread + * library to migrate from using the initial bootstrap TLS block + * created by rtld to one which contains suitable thread library + * private data. + * + * The value returned from this function is suitable for installing + * directly into the thread pointer register. + */ +extern void *_rtld_allocate_tls(void* oldtls, size_t tcbsize, size_t tcbalign); + +/* + * Free a TLS block allocated using _rtld_allocate_tls(). The tcbsize + * and tcbalign parameters must be the same as those used to allocate + * the block. + */ +extern void _rtld_free_tls(void *tcb, size_t tcbsize, size_t tcbalign); + +#endif diff --git a/bin/rtld-elf/xmalloc.c b/bin/rtld-elf/xmalloc.c new file mode 100644 index 0000000..785e162 --- /dev/null +++ b/bin/rtld-elf/xmalloc.c @@ -0,0 +1,59 @@ +/*- + * Copyright 1996-1998 John D. Polstra. + * 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. + * + * $FreeBSD: src/libexec/rtld-elf/xmalloc.c,v 1.3 2003/06/19 05:28:26 mdodd Exp $ + */ + +#include +#include +#include +#include + +void *xcalloc(size_t); +void *xmalloc(size_t); +char *xstrdup(const char *); + +void * +xcalloc(size_t size) +{ + return memset(xmalloc(size), 0, size); +} + +void * +xmalloc(size_t size) +{ + void *p = malloc(size); + if (p == NULL) + err(1, "Out of memory"); + return p; +} + +char * +xstrdup(const char *s) +{ + char *p = strdup(s); + if (p == NULL) + err(1, "Out of memory"); + return p; +} diff --git a/bin/sh/Makefile b/bin/sh/Makefile new file mode 100644 index 0000000..47eeb1d --- /dev/null +++ b/bin/sh/Makefile @@ -0,0 +1,49 @@ +# $Id: Makefile 115 2016-01-14 02:55:19Z reddawg $ +# Application Makefile (C) 2002-2004 The UbixOS Project + +# Include Global 'Source' Options +Makefile.incl +Makefile.incl + +#Linker +LD = ld + +#Binary File Name +BINARY = sh + +#Delete Program +REMOVE = rm -f + +#Objects +OBJS = sh1.o + +INCLUDES = -I../../include.new + +LIBRARIES = ../../lib/libc/libc.so + +STARTUP = ../../lib/csu/*.o + +# Link The Binary +$(BINARY) : $(OBJS) + $(CC) $(CFLAGS) -o ../../build/bin/$@ $(STARTUP) $(LIBRARIES) $(OBJS) + #strip $(BINARY) + +# Compile the source files +.cc.o: + $(CXX) -Wall -O $(CFLAGS) $(INCLUDES) -c -o $@ $< + +.cc.s: + $(CXX) -Wall -O $(CFLAGS) $(INCLUDES) -S -o $@ $< + +.c.o: + $(CC) -Wall -O $(CFLAGS) $(INCLUDES) -c -o $@ $< + +.c.s: + $(CC) -Wall -O $(CFLAGS) $(INCLUDES) -S -o $@ $< + +.S.o: + $(CC) -Wall $(CLFAGS) $(INCLUDES) -c -o $@ $< + +# Clean Up The junk +clean: + $(REMOVE) $(OBJS) ../../build/bin/$(BINARY) diff --git a/bin/shell/Makefile b/bin/shell/Makefile new file mode 100644 index 0000000..dbf897e --- /dev/null +++ b/bin/shell/Makefile @@ -0,0 +1,48 @@ +# $Id: Makefile 129 2016-01-14 14:16:33Z reddawg $ +# Application Makefile (C) 2002-2004 The UbixOS Project + +# Include Global 'Source' Options +include ../../Makefile.incl +include ../Makefile.incl + +#Linker +LD = ld + +#Binary File Name +BINARY = shell + +#Delete Program +REMOVE = rm -f + +#Objects +OBJS = main.o error.o commands.o exec.o input.o + +LIBRARIES = ../../build/lib/libc_old.so ../../build/lib/ubix_api.so + +# Link The Binary +$(BINARY) : $(OBJS) + $(CC) $(CFLAGS) -o $(BUILD_DIR)/bin/$@ $(STARTUP) $(LIBRARIES) $(OBJS) + strip ${BUILD_DIR}/bin/$(BINARY) + +# Compile the source files +.cpp.o: + $(CXX) -Wall -O $(CFLAGS) $(INCLUDES) -c -o $@ $< + +.cc.o: + $(CXX) -Wall -O $(CFLAGS) $(INCLUDES) -c -o $@ $< + +.cc.s: + $(CXX) -Wall -O $(CFLAGS) $(INCLUDES) -S -o $@ $< + +.c.o: + $(CC) -Wall -O $(CFLAGS) $(INCLUDES) -c -o $@ $< + +.c.s: + $(CC) -Wall -O $(CFLAGS) $(INCLUDES) -S -o $@ $< + +.S.o: + $(CC) -Wall $(CLFAGS) $(INCLUDES) -c -o $@ $< + +# Clean Up The junk +clean: + $(REMOVE) $(OBJS) $(BUILD_DIR)/bin/$(BINARY) diff --git a/bin/shell/commands.c b/bin/shell/commands.c new file mode 100644 index 0000000..e6f22d3 --- /dev/null +++ b/bin/shell/commands.c @@ -0,0 +1,157 @@ +/***************************************************************************************** + Copyright (c) 2002-2004 The UbixOS Project + All rights reserved. + + Redistribution and use in source and binary forms, with or without modification, are + permitted provided that the following conditions are met: + + Redistributions of source code must retain the above copyright notice, this list of + conditions, the following disclaimer and the list of authors. Redistributions in binary + form must reproduce the above copyright notice, this list of conditions, the following + disclaimer and the list of authors in the documentation and/or other materials provided + with the distribution. Neither the name of the UbixOS Project 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 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 OWNER 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. + + $Id: commands.c 158 2016-01-19 02:08:13Z reddawg $ + +*****************************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "shell.h" + +int commands(inputBuffer *data) { + int cPid = 0x0,i = 0x0,x = 0x0; + char **argv = &data->argv; + + mpi_message_t cmdMsg; + + if (data == NULL) return 1; + if (data->args->arg == NULL) return 1; + if (*data->args->arg == '\0') return 1; + + if (0 == memcmp(data->args->arg, "uname", 5)) { + printf("UbixOS v0.87 " __DATE__" " __TIME__ " \n"); + return(1); + } + else if (0 == memcmp(data->args->arg, "exit", 4)) { + exit(1); + } + else if (0 == memcmp(data->args->arg, "mypid", 5)) { + printf("My Pid: [%i]\n",getpid()); + return(1); + } + else if (memcmp(data->args->arg,"stress", 6) == 0) { + //for (i=0x0;i<100;i++) { + while (1) { + /* printf("Starting Clock\n"); */ + cPid = fork(); + if (cPid == 0x0) { + execve("clock",0x0,0x0); + exit(0x1); + } else { + printf("Childs Pid: [%i]\n",cPid); + while (pidStatus(cPid) > 0) + sched_yield(); + } + cPid = fork(); + if (cPid == 0x0) { + execve("ls", 0x0, 0x0); + exit(0x1); + } else { + printf("Childs Pid: [%i]\n",cPid); + while (pidStatus(cPid) > 0) + sched_yield(); + } + } + } + else if (memcmp(data->args->arg,"test2", 5) == 0) { + for (i=0x0;i<500;i++) { + cPid = fork(); + if (cPid == 0x0) { + printf("Pid: [%i:%i]\n",cPid,i); + execve("clock",0x0,0x0); + exit(0x1); + } + else { + printf("Childs Pid: [%i]\n",cPid); + } + } + } + else if (memcmp(data->args->arg,"test3", 5) == 0) { + for (i=0x0;i<50;i++) { + cPid = fork(); + if (cPid == 0x0) { + printf("Pid: [%i:%i]\n",cPid,i); + for (x=0x0;x<100;x++) sched_yield(); + printf("Exiting!!!\n"); + exit(0x1); + } + else { + printf("Childs Pid: [%i]\n",cPid); + } + } + } + else if (memcmp(data->args->arg,"echo",4) == 0) { + for (i=1;iargc;i++) { + printf("%s ",argv[i]); + } + printf("\n"); + } + else if (memcmp(data->args->arg,"about",5) == 0) { + printf("UbixOS Shell v0.99 (C) 2002\n"); + printf("Base Command Line Interface\n"); + } + else if (memcmp(data->args->arg,"cd",2) == 0) { + if (argv[1]) { + chdir(argv[1]); + getcwd(cwd,1024); + } + } + else if (memcmp(data->args->arg,"unlink",6) == 0) { + if (argv[1]) { + unlink(argv[1]); + } + } + else if (memcmp(data->args->arg,"msg",3) == 0x0) { + printf("Posting Message\n"); + cmdMsg.header = atoi(argv[2]); + sprintf(cmdMsg.data,argv[3]); + mpi_postMessage(argv[1],0x1,&cmdMsg); + } + else if (memcmp(data->args->arg,"mkdir",5) == 0x0) { + if (argv[1]) { + mkdir(argv[1],0xEAA); + } + } + else if (memcmp(data->args->arg,"id",2) == 0x0) { + printf("UID: %i, GID: %i\n",getuid(),getgid()); + } + else if (!strcmp(argv[1],"reboot")) { + cmdMsg.header = 1000; + cmdMsg.data[0] = '\0'; + mpi_postMessage("system",0x1,&cmdMsg); + } + else { + return(0); + } + return(1); + } diff --git a/bin/shell/error.c b/bin/shell/error.c new file mode 100644 index 0000000..3bba1a3 --- /dev/null +++ b/bin/shell/error.c @@ -0,0 +1,30 @@ +/************************************************************************************** + Copyright (c) 2002 The UbixOS Project + All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +Redistributions of source code must retain the above copyright notice, this list of conditions, the following disclaimer and the list of authors. +Redistributions in binary form must reproduce the above copyright notice, this list of conditions, the following disclaimer and the list of authors +in the documentation and/or other materials provided with the distribution. Neither the name of the UbixOS Project 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 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 OWNER 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. + + $Id: error.c 89 2016-01-12 00:20:40Z reddawg $ + +**************************************************************************************/ + +#include +#include + +void error(int errorCode,const char *errorMsg) { + printf("ERROR: #%i Message: %s\n", errorCode, errorMsg); + exit(errorCode); + } diff --git a/bin/shell/exec.c b/bin/shell/exec.c new file mode 100644 index 0000000..6a2ee04 --- /dev/null +++ b/bin/shell/exec.c @@ -0,0 +1,62 @@ +/************************************************************************************** + Copyright (c) 2002 The UbixOS Project + All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +Redistributions of source code must retain the above copyright notice, this list of conditions, the following disclaimer and the list of authors. +Redistributions in binary form must reproduce the above copyright notice, this list of conditions, the following disclaimer and the list of authors +in the documentation and/or other materials provided with the distribution. Neither the name of the UbixOS Project 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 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 OWNER 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. + + $Id: exec.c 158 2016-01-19 02:08:13Z reddawg $ + +**************************************************************************************/ + +#include +#include +#include +#include +#include +#include "shell.h" + + int boo = 0x0; + +void execProgram(inputBuffer *data) { + char file[1024]; + int cPid = 0x0; + + //printf("Executing App\n"); + + cPid = fork(); +printf("Forked: [%i]\n", cPid); + + if (!cPid) { + sprintf(file, "%s%s", cwd, data->argv[1]); + // if (boo == 0) + //execve(file,data->argv, 0x0); + execve(file,0x0, 0x0); + /* + else + execn(file,&data->argv); +*/ + printf("%s: Command Not Found.\n",data->argv[1]); + exit(-1); + } + else { + if (data->bg == 0x0) { + while (pidStatus(cPid) > 0) + sched_yield(); + } + if (cPid > 4) + boo = 1; + } + } diff --git a/bin/shell/input.c b/bin/shell/input.c new file mode 100644 index 0000000..11f8fe6 --- /dev/null +++ b/bin/shell/input.c @@ -0,0 +1,97 @@ +/************************************************************************************** + Copyright (c) 2002 The UbixOS Project + All rights reserved. + + Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + Redistributions of source code must retain the above copyright notice, this list of conditions, the following disclaimer and the list of authors. + Redistributions in binary form must reproduce the above copyright notice, this list of conditions, the following disclaimer and the list of authors + in the documentation and/or other materials provided with the distribution. Neither the name of the UbixOS Project 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 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 OWNER 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. + + $Id: input.c 128 2016-01-14 14:06:43Z reddawg $ + + **************************************************************************************/ + +#include +#include +#include +#include "shell.h" + +void parseInput( inputBuffer *buffer, char *data ) { + int i = 0x0; + char *arg = 0x0; + // char **argv = 0x0; + struct argsStruct *tmpArgs = 0x0; + + while ( data[0] == ' ' ) { + data++; + } + + if ( *data == '\0' ) + return; + + buffer->args = (struct argsStruct *) malloc( sizeof(struct argsStruct) ); + + tmpArgs = buffer->args; + + while ( data != 0x0 ) { + + arg = strtok( data, " " ); + data = strtok( NULL, "\n" ); + +/* +if (data != 0x0) + printf( "sh[%s:%s]", arg, data ); +else + printf( "sh[%s]", arg ); +*/ + + if ( arg[0] == '&' ) { + buffer->bg = 0x1; + } + else { + buffer->argc++; + tmpArgs->arg = arg; + if ( data != 0x0 ) { + tmpArgs->next = (struct argsStruct *) malloc( sizeof(struct argsStruct) ); + } + tmpArgs = tmpArgs->next; + } + } + + /* Alloc memory for argv[] */ + buffer->argv = (char **) malloc( sizeof(char *) * ( buffer->argc + 1 ) ); + //buffer->envp = (char **)malloc(sizeof(char)); + + //buffer->envp[0] = 0x1; + + tmpArgs = buffer->args; + //argv = buffer->argv; + + //printf( "argc: [%i]\n", buffer->argc ); + //printf( "arg-1: [%i:%s]\n", buffer->args->arg, buffer->args->arg ); + + for ( i = 0x1; i <= buffer->argc ; i++ ) { + buffer->argv[i] = tmpArgs->arg; + //printf( "argv[%i]: %s\n", i, argv[i] ); + tmpArgs = tmpArgs->next; + } + buffer->argv[0] = (char *)buffer->argc; + //argv[buffer->argc+1] = buffer->envp; + //printf( "arg-1: [%i:%i:%s]\n", argv[0], buffer->args->arg, buffer->args->arg ); + +} + +void freeArgs( inputBuffer *ptr ) { + free( ptr->args ); + //free(tmpArgs->argv); +} diff --git a/bin/shell/main.c b/bin/shell/main.c new file mode 100644 index 0000000..36d564e --- /dev/null +++ b/bin/shell/main.c @@ -0,0 +1,76 @@ +/************************************************************************************** + Copyright (c) 2002 The UbixOS Project + All rights reserved. + + Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + Redistributions of source code must retain the above copyright notice, this list of conditions, the following disclaimer and the list of authors. + Redistributions in binary form must reproduce the above copyright notice, this list of conditions, the following disclaimer and the list of authors + in the documentation and/or other materials provided with the distribution. Neither the name of the UbixOS Project 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 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 OWNER 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. + + $Id: main.c 160 2016-01-19 04:01:03Z reddawg $ + + **************************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include "shell.h" + +char *machine = 0x0; +char *cwd = 0x0; +char *cwc = 0x0; + +int main() { + + char *buffer = (char *) malloc( 512 ); + inputBuffer *inBuf = (inputBuffer *) malloc( sizeof(inputBuffer) ); + + machine = (char *) malloc( 32 ); + cwd = (char *) malloc( 1024 ); + + sprintf( machine, "uBixCube" ); + getcwd( cwd, 1024 ); + +printf("Is this My ERROR?"); + + //MrOlsen 2017-11-17 printf( "[0x%X]\n", ubix_test() ); + + while ( 1 ) { + aGain: printf( "%s@%s# ", machine, cwd ); + gets( (char *) buffer ); + + if ( buffer[0] == 0x0 ) + goto aGain; + + inBuf->argc = 0x0; + inBuf->args = 0x0; + inBuf->bg = 0x0; + + parseInput( inBuf, buffer ); + +printf( "m-arg: [%i]\n", inBuf->args->arg ); + + if ( inBuf->args->arg != 0x0 ) { + +// execProgram( inBuf ); + if (!commands(inBuf)) + execProgram(inBuf); + } + + freeArgs( inBuf ); + } + return ( 0x0 ); +} diff --git a/bin/shell/shell.h b/bin/shell/shell.h new file mode 100644 index 0000000..e140799 --- /dev/null +++ b/bin/shell/shell.h @@ -0,0 +1,22 @@ +#include + +extern char *cwd; + +struct argsStruct { + struct argsStruct *next; + char *arg; + }; + +typedef struct { + int argc; + char **argv; + char **envp; + uInt8 bg; + struct argsStruct *args; + } inputBuffer; + +void parseInput(inputBuffer *,char *); +int commands(inputBuffer *); +void execProgram(inputBuffer *); +void freeArgs(inputBuffer *ptr); +void error(int errorCode,const char *errorMsg); diff --git a/bin/stat/Makefile b/bin/stat/Makefile new file mode 100644 index 0000000..7730ee1 --- /dev/null +++ b/bin/stat/Makefile @@ -0,0 +1,48 @@ +# $Id: Makefile 170 2016-01-20 02:28:45Z reddawg $ +# Application Makefile (C) 2002-2004 The UbixOS Project + +# Include Global 'Source' Options +include ../../Makefile.incl +include ../Makefile.incl + +#Linker +LD = ld + +#Binary File Name +BINARY = stat + +#Delete Program +REMOVE = rm -f + +#Objects +OBJS = main.o + +#MrOlsen (2016-01-19) TEMP: This is just to make it static LIBRARIES = ../../build/lib/libc_old.so + +# Link The Binary +$(BINARY) : $(OBJS) + $(CC) $(CFLAGS) -o $(BUILD_DIR)/bin/$@ $(STARTUP) $(LIBRARIES) $(OBJS) +# strip $(BINARY) + +# Compile the source files +.cpp.o: + $(CXX) -Wall -O $(CFLAGS) $(INCLUDES) -c -o $@ $< + +.cc.o: + $(CXX) -Wall -O $(CFLAGS) $(INCLUDES) -c -o $@ $< + +.cc.s: + $(CXX) -Wall -O $(CFLAGS) $(INCLUDES) -S -o $@ $< + +.c.o: + $(CC) -Wall -O $(CFLAGS) $(INCLUDES) -c -o $@ $< + +.c.s: + $(CC) -Wall -O $(CFLAGS) $(INCLUDES) -S -o $@ $< + +.S.o: + $(CC) -Wall $(CLFAGS) $(INCLUDES) -c -o $@ $< + +# Clean Up The junk +clean: + $(REMOVE) $(OBJS) $(BUILD_DIR)/bin/$(BINARY) diff --git a/bin/stat/main.c b/bin/stat/main.c new file mode 100644 index 0000000..b422f22 --- /dev/null +++ b/bin/stat/main.c @@ -0,0 +1,125 @@ +/***************************************************************************************** + Copyright (c) 2002-2004 The UbixOS Project + All rights reserved. + + Redistribution and use in source and binary forms, with or without modification, are + permitted provided that the following conditions are met: + + Redistributions of source code must retain the above copyright notice, this list of + conditions, the following disclaimer and the list of authors. Redistributions in binary + form must reproduce the above copyright notice, this list of conditions, the following + disclaimer and the list of authors in the documentation and/or other materials provided + with the distribution. Neither the name of the UbixOS Project 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 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 OWNER 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. + + $Id: main.c 163 2016-01-19 15:34:38Z reddawg $ + +*****************************************************************************************/ + +#include +#include +#include +#include + +void print2(char *string,int,int); + +#define MINUTE 60 +#define HOUR (60*MINUTE) +#define DAY (24*HOUR) +#define YEAR (365*DAY) + + +static int monthSecs[12] = { + 0, + DAY*(31), + DAY*(31+29), + DAY*(31+29+31), + DAY*(31+29+31+30), + DAY*(31+29+31+30+31), + DAY*(31+29+31+30+31+30), + DAY*(31+29+31+30+31+30+31), + DAY*(31+29+31+30+31+30+31+31), + DAY*(31+29+31+30+31+30+31+31+30), + DAY*(31+29+31+30+31+30+31+31+30+31), + DAY*(31+29+31+30+31+30+31+31+30+31+30) +}; + +int main(int argc,char **argv) { + int sysTime = 0x0; + int i = 0x0; + + int year = 0x0; + int month = 0x0; + int day = 0x0; + int hour = 0x0; + int min = 0x0; + int sec = 0x0; + + int x = 0x0; + + asm( + "movl %%gs,%%eax\n" + "movl %%eax, %0\n" + : "=g" (x) + : + : "eax" + ); + + printf("GS: [0x%X]\n", x); + asm( + "movl %%fs,%%eax\n" + "movl %%eax, %0\n" + : "=g" (x) + : + : "eax" + ); + printf("FS: [0x%X]\n", x); + exit(0); + + + + //start: + sysTime = gettime(); + + year = (sysTime/YEAR) + 1970; + sysTime -= (YEAR * (year-1970)); + sysTime -= DAY*(((year-1970)+1)/4); + for (i = 11;i >= 0;i--) { + if ((sysTime - monthSecs[i]) > 0) { + month = i; + break; + } + } + sysTime -= monthSecs[i]; + if (((month > 1) && (((year-1970)+2)%4)) == 0x0) { + sysTime += DAY; + } + + day = (sysTime/DAY); + sysTime -= (day*DAY); + hour = (sysTime/HOUR); + sysTime -= (hour*HOUR); + min = (sysTime/MINUTE); + sysTime -= (min*MINUTE); + sec = sysTime; + + printf("[%02d/%02d/%i, %02d:%02d.%02d]\n",month,day,year,hour,min,sec); +// goto start; + return(0); + } + +/*** + END + ***/ + diff --git a/bin/ttyd/Makefile b/bin/ttyd/Makefile new file mode 100644 index 0000000..60ee069 --- /dev/null +++ b/bin/ttyd/Makefile @@ -0,0 +1,45 @@ +# $Id: Makefile 129 2016-01-14 14:16:33Z reddawg $ +# Application Makefile (C) 2002-2004 The UbixOS Project + +# Include Global 'Source' Options +include ../../Makefile.incl +include ../Makefile.incl + +#Linker +LD = ld + +#Binary File Name +BINARY = ttyd + +#Delete Program +REMOVE = rm -f + +#Objects +OBJS = main.o + +LIBRARIES = ../../build/lib/libc_old.so + +# Link The Binary +$(BINARY) : $(OBJS) + $(CC) $(CFLAGS) -o $(BUILD_DIR)/bin/$@ $(STARTUP) $(LIBRARIES) $(OBJS) + strip ${BUILD_DIR}/bin/$(BINARY) + +# Compile the source files +.cc.o: + $(CXX) -Wall -O $(CFLAGS) $(INCLUDES) -c -o $@ $< + +.cc.s: + $(CXX) -Wall -O $(CFLAGS) $(INCLUDES) -S -o $@ $< + +.c.o: + $(CC) -Wall -O $(CFLAGS) $(INCLUDES) -c -o $@ $< + +.c.s: + $(CC) -Wall -O $(CFLAGS) $(INCLUDES) -S -o $@ $< + +.S.o: + $(CC) -Wall $(CLFAGS) $(INCLUDES) -c -o $@ $< + +# Clean Up The junk +clean: + $(REMOVE) $(OBJS) $(BUILD_DIR)/bin/$(BINARY) diff --git a/bin/ttyd/main.c b/bin/ttyd/main.c new file mode 100644 index 0000000..8cf8479 --- /dev/null +++ b/bin/ttyd/main.c @@ -0,0 +1,58 @@ +/***************************************************************************************** + Copyright (c) 2002-2004 The UbixOS Project + All rights reserved. + + Redistribution and use in source and binary forms, with or without modification, are + permitted provided that the following conditions are met: + + Redistributions of source code must retain the above copyright notice, this list of + conditions, the following disclaimer and the list of authors. Redistributions in binary + form must reproduce the above copyright notice, this list of conditions, the following + disclaimer and the list of authors in the documentation and/or other materials provided + with the distribution. Neither the name of the UbixOS Project 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 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 OWNER 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. + + $Id: main.c 89 2016-01-12 00:20:40Z reddawg $ + +*****************************************************************************************/ + +#include +#include + +int main(int argc,char **argv) { + mpi_message_t myMsg; + + printf("Initializing TTYD\n"); + printf("mpi_post: [%i]\n",mpi_postMessage("system",0x1,&myMsg)); + + return(0x0); + } + +/*** + $Log: main.c,v $ + Revision 1.1.1.1 2006/06/01 12:46:09 reddawg + ubix2 + + Revision 1.2 2005/10/12 00:13:28 reddawg + Removed + + Revision 1.1.1.1 2005/09/26 17:14:03 reddawg + no message + + Revision 1.1 2004/08/14 11:28:59 reddawg + ttyd + + END + ***/ + diff --git a/bin/ubistry/Makefile b/bin/ubistry/Makefile new file mode 100644 index 0000000..cdb7a53 --- /dev/null +++ b/bin/ubistry/Makefile @@ -0,0 +1,48 @@ +# $Id: Makefile 129 2016-01-14 14:16:33Z reddawg $ +# Application Makefile (C) 2002-2004 The UbixOS Project + +# Include Global 'Source' Options +include ../../Makefile.incl +include ../Makefile.incl + +#Linker +LD = ld + +#Binary File Name +BINARY = ubistry + +#Delete Program +REMOVE = rm -f + +#Objects +OBJS = db.o message.o main.o + +LIBRARIES = ../../build/lib/libc_old.so + +# Link The Binary +$(BINARY) : $(OBJS) + $(CC) $(CFLAGS) -o ${BUILD_DIR}/bin/$@ $(STARTUP) $(LIBRARIES) $(OBJS) + strip ${BUILD_DIR}/bin/$(BINARY) + +# Compile the source files +.cpp.o: + $(CXX) -Wall -O $(CFLAGS) $(INCLUDES) -c -o $@ $< + +.cc.o: + $(CXX) -Wall -O $(CFLAGS) $(INCLUDES) -c -o $@ $< + +.cc.s: + $(CXX) -Wall -O $(CFLAGS) $(INCLUDES) -S -o $@ $< + +.c.o: + $(CC) -Wall -O $(CFLAGS) $(INCLUDES) -c -o $@ $< + +.c.s: + $(CC) -Wall -O $(CFLAGS) $(INCLUDES) -S -o $@ $< + +.S.o: + $(CC) -Wall $(CLFAGS) $(INCLUDES) -c -o $@ $< + +# Clean Up The junk +clean: + $(REMOVE) $(OBJS) ${BUILD_DIR}/bin/$(BINARY) diff --git a/bin/ubistry/db.c b/bin/ubistry/db.c new file mode 100644 index 0000000..633d666 --- /dev/null +++ b/bin/ubistry/db.c @@ -0,0 +1,89 @@ +/***************************************************************************************** + Copyright (c) 2002-2004 The UbixOS Project + All rights reserved. + + Redistribution and use in source and binary forms, with or without modification, are + permitted provided that the following conditions are met: + + Redistributions of source code must retain the above copyright notice, this list of + conditions, the following disclaimer and the list of authors. Redistributions in binary + form must reproduce the above copyright notice, this list of conditions, the following + disclaimer and the list of authors in the documentation and/or other materials provided + with the distribution. Neither the name of the UbixOS Project 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 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 OWNER 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. + + $Id: db.c 89 2016-01-12 00:20:40Z reddawg $ + +*****************************************************************************************/ + +#include +#include +#include +#include "./include/ubistry.h" + +static struct ubistryKey *keys = 0x0; + + +struct ubistryKey * ubistryFindKey(char *name) { + struct ubistryKey *tmpKey = keys; + + for (;tmpKey;tmpKey=tmpKey->next) { + if (!strcmp(name,tmpKey->name)) { + return(tmpKey); + } + } + return(0x0); + } + +int ubistryAddKey(char *name,char *value) { + struct ubistryKey *tmpKey = (struct ubistryKey *)malloc(sizeof(struct ubistryKey)); + + sprintf(tmpKey->name,name); + sprintf(tmpKey->value,value); + + if (keys == 0x0) { + keys = tmpKey; + keys->prev = 0x0; + keys->next = 0x0; + } + else { + tmpKey->next = keys; + tmpKey->prev = 0x0; + keys->prev = tmpKey; + keys = tmpKey; + } + + return(0x0); + } + +/*** + $Log: db.c,v $ + Revision 1.1.1.1 2006/06/01 12:46:08 reddawg + ubix2 + + Revision 1.2 2005/10/12 00:13:28 reddawg + Removed + + Revision 1.1.1.1 2005/09/26 17:14:04 reddawg + no message + + Revision 1.2 2004/06/17 15:10:55 reddawg + Fixed Some Global Variables + + Revision 1.1 2004/05/26 15:41:20 reddawg + ubistry: added command 666 which will restart the registry server also added + command 51 to add a key format key,value + + END + ***/ diff --git a/bin/ubistry/include/ubistry.h b/bin/ubistry/include/ubistry.h new file mode 100644 index 0000000..231acea --- /dev/null +++ b/bin/ubistry/include/ubistry.h @@ -0,0 +1,15 @@ +#include + +#define MBOX_NAME "ubistry" + +struct ubistryKey { + struct ubistryKey *prev; + struct ubistryKey *next; + char name[128]; + char value[512]; + }; + +struct ubistryKey * ubistryFindKey(char *); +int ubistryAddKey(char *,char *); +int ubistryInitMbox(char *); +void ubistryProcessMessages(); diff --git a/bin/ubistry/main.c b/bin/ubistry/main.c new file mode 100644 index 0000000..c12c9f4 --- /dev/null +++ b/bin/ubistry/main.c @@ -0,0 +1,106 @@ +/***************************************************************************************** + Copyright (c) 2002-2004 The UbixOS Project + All rights reserved. + + Redistribution and use in source and binary forms, with or without modification, are + permitted provided that the following conditions are met: + + Redistributions of source code must retain the above copyright notice, this list of + conditions, the following disclaimer and the list of authors. Redistributions in binary + form must reproduce the above copyright notice, this list of conditions, the following + disclaimer and the list of authors in the documentation and/or other materials provided + with the distribution. Neither the name of the UbixOS Project 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 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 OWNER 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. + + $Id: main.c 89 2016-01-12 00:20:40Z reddawg $ + +*****************************************************************************************/ + +#include +#include +#include +#include +#include +#include "./include/ubistry.h" + +int main(int argc,char **argv) { + //FILE *pidFile; + + if (fork() != 0x0) { + exit(0x0); + } + + ubistryInitMbox(MBOX_NAME); + + ubistryAddKey("Ubu","Creator Of UbixOS"); + ubistryAddKey("TCA","The GUI GUY!!!"); + + while (1) { + ubistryProcessMessages(); + sched_yield(); + } + + exit(0x0); + } + +/*** + $Log: main.c,v $ + Revision 1.1.1.1 2006/06/01 12:46:09 reddawg + ubix2 + + Revision 1.2 2005/10/12 00:13:28 reddawg + Removed + + Revision 1.1.1.1 2005/09/26 17:14:04 reddawg + no message + + Revision 1.10 2004/09/08 23:19:58 reddawg + hmm + + Revision 1.9 2004/08/02 18:50:13 reddawg + Updates to make some variable volatile to make work with gcc 3.3. However there are still some issues but we have not caused new issues with gcc 2.95 + + Revision 1.8 2004/07/17 16:43:10 reddawg + shell: fixed stress testing + ubistry: fixed some segfaults + spinlock: added assert() + + Revision 1.7 2004/06/17 15:10:55 reddawg + Fixed Some Global Variables + + Revision 1.6 2004/06/10 13:08:00 reddawg + Minor Bug Fixes + + Revision 1.5 2004/06/01 01:30:43 reddawg + No more warnings and organized make files + + Revision 1.4 2004/05/26 15:41:20 reddawg + ubistry: added command 666 which will restart the registry server also added + command 51 to add a key format key,value + + Revision 1.3 2004/05/26 13:10:39 reddawg + ubistry: added two functions + ubistryFindKey(char *name) <- Will find key with specified name + ubistryAddKey(char *name,char *value) <-> Will add key with specified + name and value + + Revision 1.2 2004/05/26 12:16:02 reddawg + ubistry: now runs as a deamon + + Revision 1.1 2004/05/26 12:09:12 reddawg + ubistry: this is the frame work for the ubix registry system more to come + over the next few days + + END + ***/ diff --git a/bin/ubistry/message.c b/bin/ubistry/message.c new file mode 100644 index 0000000..75523ab --- /dev/null +++ b/bin/ubistry/message.c @@ -0,0 +1,110 @@ +/***************************************************************************************** + Copyright (c) 2002-2004 The UbixOS Project + All rights reserved. + + Redistribution and use in source and binary forms, with or without modification, are + permitted provided that the following conditions are met: + + Redistributions of source code must retain the above copyright notice, this list of + conditions, the following disclaimer and the list of authors. Redistributions in binary + form must reproduce the above copyright notice, this list of conditions, the following + disclaimer and the list of authors in the documentation and/or other materials provided + with the distribution. Neither the name of the UbixOS Project 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 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 OWNER 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. + + $Id: message.c 158 2016-01-19 02:08:13Z reddawg $ + +*****************************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include "./include/ubistry.h" + +int ubistryInitMbox(char *name) { + + if (mpi_createMbox(name) != 0x0) { + printf("Error: Error Creating Mail Box: [%s]\n",name); + return(-1); + } + + return(0x0); + } + +void ubistryProcessMessages() { + mpi_message_t msg; + struct ubistryKey *tmpKey = 0x0; + char *key,*value; + + mfmStart: + if (mpi_fetchMessage("ubistry",&msg) == 0x0) { + switch (msg.header) { + case 50: + tmpKey = ubistryFindKey(msg.data); + if (tmpKey == 0x0) + printf("ubistry: Key (%s) Not Found\n",msg.data); + else + printf("ubistry: Key (%s) Found Has Value (%s)\n",tmpKey->name,tmpKey->value); + break; + case 51: + key = strtok(msg.data,","); + value = strtok(NULL,"\n"); + printf("ubistry: Adding key (%s) with value (%s)\n",key,value); + ubistryAddKey(key,value); + break; + case 666: + mpi_destroyMbox("ubistry"); + if (fork() == 0x0) { + printf("ubistry: Restarting\n"); + execve("ubistry@sys",0x0,0x0); + } + else { + exit(0x0); + } + break; + default: + printf("ubistry: Command (%i) With Data (%s) Not Valid\n",msg.header,msg.data); + break; + } + goto mfmStart; + } + return; + } + +/*** + $Log: message.c,v $ + Revision 1.2 2006/12/12 14:09:17 reddawg + Changes + + Revision 1.1.1.1 2006/06/01 12:46:09 reddawg + ubix2 + + Revision 1.2 2005/10/12 00:13:28 reddawg + Removed + + Revision 1.1.1.1 2005/09/26 17:14:04 reddawg + no message + + Revision 1.2 2004/08/14 11:23:02 reddawg + Changes + + Revision 1.1 2004/05/26 15:41:20 reddawg + ubistry: added command 666 which will restart the registry server also added + command 51 to add a key format key,value + + END + ***/ diff --git a/bin/views/Makefile b/bin/views/Makefile new file mode 100644 index 0000000..1de7a94 --- /dev/null +++ b/bin/views/Makefile @@ -0,0 +1,49 @@ +# $Id: Makefile 115 2016-01-14 02:55:19Z reddawg $ +# Application Makefile (C) 2002 The UbixOS Project + +# Include Global 'Source' Options +Makefile.incl + +#Compiler Flags +CFLAGS = -I../../lib/libc/include -fno-builtin -nostdlib -nostdinc + +#Linker +LD = ld + +#Binary File Name +BINARY = views + +#Delete Program +REMOVE = rm -f + +#Objects +OBJS = main.o + +#Libraries +#LIBRARIES = ../../lib/libc/libc.so +LIBRARIES = ../../lib/libc/locale/*.o ../../lib/libc/stdio/*.o ../../lib/libc/stdlib/*.o ../../lib/libc/sys/*.o ../../lib/libc/string/*.o + +# Link The Binary +$(BINARY) : $(OBJS) + $(CC) $(CFLAGS) -o ../build/$@ $(STARTUP) $(LIBRARIES) $(OBJS) + strip $(BINARY) + +# Compile the source files +.cc.o: + $(CXX) -Wall -fomit-frame-pointer -O $(CFLAGS) -c -o $@ $< + +.cc.s: + $(CXX) -Wall -fomit-frame-pointer -O $(CFLAGS) -S -o $@ $< + +.c.o: + $(CC) -Wall -O $(CFLAGS) -c -o $@ $< + +.c.s: + $(CC) -Wall -fomit-frame-pointer -O $(CFLAGS) -S -o $@ $< + +.S.o: + $(CC) -Wall -fomit-frame-pointer -c -o $@ $< + +# Clean Up The junk +clean: + $(REMOVE) $(OBJS) ../build/$(BINARY) diff --git a/bin/views/main.c b/bin/views/main.c new file mode 100644 index 0000000..dcf041e --- /dev/null +++ b/bin/views/main.c @@ -0,0 +1,34 @@ +/************************************************************************************** + Copyright (c) 2002 The UbixOS Project + All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +Redistributions of source code must retain the above copyright notice, this list of conditions, the following disclaimer and the list of authors. +Redistributions in binary form must reproduce the above copyright notice, this list of conditions, the following disclaimer and the list of authors +in the documentation and/or other materials provided with the distribution. Neither the name of the UbixOS Project 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 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 OWNER 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. + + $Id: main.c 89 2016-01-12 00:20:40Z reddawg $ + +**************************************************************************************/ + +#include +#include + +int main(int argc,char **argv) { + return(0); + } + +/*** + END + ***/ + diff --git a/lib/Makefile b/lib/Makefile new file mode 100644 index 0000000..1d10476 --- /dev/null +++ b/lib/Makefile @@ -0,0 +1,50 @@ +# $Id: Makefile 121 2016-01-14 03:18:20Z reddawg $ +# The System Makefile (C) 2002 The UbixOS Project + +all: csu-code ubix_api-code libc_old-code ubix-code #libc-code# libcpp-code +# bin tools +# depend kernel tools + +csu-code: csu + (cd csu;make) + +ubix_api-code: ubix_api + (cd ubix_api;make) + +libc_old-code: libc_old + (cd libc_old;make) + +libc-code: libc + (cd libc;make) + +objgfx40: src + (cd objgfx40;make) + +views: src + (cd src/lib/views/sunlight;make) + +ubix-code: ubix + (cd ubix;make) + +libcpp-code: libcpp + (cd libcpp;make) + +bin: src + (cd src/bin;make) + +libstdc++: src + (cd src/lib/libstdc++;make) + +tools: src + (cd src/tools;make) + +install: + (cd src/sys;make install) + +clean: + #(cd src/sys;make clean) + (cd csu;make clean) + (cd ubix_api;make clean) + (cd libc_old;make clean) + (cd libc;make clean) + (cd ubix;make clean) diff --git a/lib/Makefile.incl b/lib/Makefile.incl new file mode 100644 index 0000000..c2b1de8 --- /dev/null +++ b/lib/Makefile.incl @@ -0,0 +1,11 @@ +# $Id: Makefile.inc 103 2016-01-12 05:32:24Z reddawg $ +# 'lib' options + +LDFLAGS = -Bshareable +#CFLAGS = -fpic -DPIC -O2 -fno-strict-aliasing -pipe -D__DBINTERFACE_PRIVATE -DPOSIX_MISTAKE -DBROKEN_DES -DPORTMAP -DDES_BUILTIN -DYP -DHESIOD -Wsystem-headers -Wall -Wno-format-y2k -Wno-uninitialized +CFLAGS = -m32 -fno-builtin -Wno-uninitialized -O2 -fno-strict-aliasing -pipe + +INCLUDES = -I../include -I../../../include -I../i386 -I../include + +INCLUDES = -I${INCLUDE} +CFLAGS = -m32 ${WFLAGS} -Wall -nostdlib -nostdinc -fno-builtin -fno-exceptions -O diff --git a/lib/csu/Makefile b/lib/csu/Makefile new file mode 100644 index 0000000..7d1f627 --- /dev/null +++ b/lib/csu/Makefile @@ -0,0 +1,19 @@ +.include + +CSU_MACHINE_ARCH?= ${MACHINE_ARCH} +CSU_MACHINE_CPU?= ${MACHINE_CPU} + +.if !empty(CSU_MACHINE_ARCH:Mearm*) +ARCHDIR:= ${.CURDIR}/arch/earm +.elif exists(${.CURDIR}/arch/${CSU_MACHINE_ARCH}/Makefile.incl) +ARCHDIR:= ${.CURDIR}/arch/${CSU_MACHINE_ARCH} +.elif exists(${.CURDIR}/arch/${CSU_MACHINE_CPU}/Makefile.incl) +ARCHDIR:= ${.CURDIR}/arch/${CSU_MACHINE_CPU} +.else +.error Architecture (${CSU_MACHINE_ARCH} or ${CSU_MACHINE_CPU}) unsupported +.endif + + +.PATH: ${ARCHDIR} +.include "${ARCHDIR}/Makefile.incl" +.include "${.CURDIR}/common/Makefile.incl" diff --git a/lib/csu/crt1.c b/lib/csu/crt1.c new file mode 100644 index 0000000..6cdb2a8 --- /dev/null +++ b/lib/csu/crt1.c @@ -0,0 +1,119 @@ +/* LINTLIBRARY */ +/*- + * Copyright 1996-1998 John D. Polstra. + * 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. + */ + +#ifndef lint +#ifndef __GNUC__ +#error "GCC is needed to compile this file" +#endif +#endif /* lint */ + +#include + +#include "libc_private.h" +#include "crtbrand.c" + +extern int _DYNAMIC; +#pragma weak _DYNAMIC + +typedef void (*fptr)(void); + +extern void _fini(void); +extern void _init(void); +extern int main(int, char **, char **); +extern void _start(char *, ...); + +#ifdef GCRT +extern void _mcleanup(void); +extern void monstartup(void *, void *); +extern int eprol; +extern int etext; +#endif + +char **environ; +const char *__progname = ""; + +static __inline fptr +get_rtld_cleanup(void) +{ + fptr retval; + +#ifdef __GNUC__ + __asm__("movl %%edx,%0" : "=rm"(retval)); +#else + retval = (fptr)0; /* XXXX Fix this for other compilers */ +#endif + return(retval); +} + +/* The entry function. */ +void +_start(char *ap, ...) +{ + fptr cleanup; + int argc; + char **argv; + char **env; + const char *s; + +#ifdef __GNUC__ + __asm__("and $0xfffffff0,%esp"); +#endif + cleanup = get_rtld_cleanup(); + argv = ≈ + argc = *(long *)(void *)(argv - 1); + env = argv + argc + 1; + environ = env; + + if (argc > 0 && argv[0] != NULL) { + __progname = argv[0]; + for (s = __progname; *s != '\0'; s++) + if (*s == '/') + __progname = s + 1; + } + + if (&_DYNAMIC != NULL) + atexit(cleanup); + else + _init_tls(); + +#ifdef GCRT + atexit(_mcleanup); +#endif + atexit(_fini); +#ifdef GCRT + monstartup(&eprol, &etext); +#endif + _init(); + exit( main(argc, argv, env) ); +} + +#ifdef GCRT +__asm__(".text"); +__asm__("eprol:"); +__asm__(".previous"); +#endif + +__asm__(".ident\t\"$FreeBSD: src/lib/csu/i386-elf/crt1.c,v 1.14 2005/05/19 07:36:07 dfr Exp $\""); diff --git a/lib/csu/crtbrand.c b/lib/csu/crtbrand.c new file mode 100644 index 0000000..f17a450 --- /dev/null +++ b/lib/csu/crtbrand.c @@ -0,0 +1,51 @@ +/*- + * Copyright 2000 David E. O'Brien, John D. Polstra. + * 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. + */ + +#include + +#include + +#define ABI_VENDOR "UbixOS" +#define ABI_SECTION ".note.ABI-tag" +#define ABI_NOTETYPE 1 + +/* + * Special ".note" entry specifying the ABI version. See + * http://www.netbsd.org/Documentation/kernel/elf-notes.html + * for more information. + */ +static const struct { + int32_t namesz; + int32_t descsz; + int32_t type; + char name[sizeof ABI_VENDOR]; + int32_t desc; +} abitag __attribute__ ((section (ABI_SECTION), aligned(4))) __unused = { + sizeof ABI_VENDOR, + sizeof(int32_t), + ABI_NOTETYPE, + ABI_VENDOR, + __UbixOS_version +}; diff --git a/lib/csu/crti.S b/lib/csu/crti.S new file mode 100644 index 0000000..ff895cb --- /dev/null +++ b/lib/csu/crti.S @@ -0,0 +1,41 @@ +/*- + * Copyright 1996, 1997, 1998, 2000 John D. Polstra. + * 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. + */ + + .section .init,"ax",@progbits + .align 4 + .globl _init + .type _init,@function +_init: + sub $12,%esp /* re-align stack pointer */ + + .section .fini,"ax",@progbits + .align 4 + .globl _fini + .type _fini,@function +_fini: + sub $12,%esp /* re-align stack pointer */ + + .section .rodata +.ascii "$FreeBSD: src/lib/csu/i386-elf/crti.S,v 1.7 2005/05/19 07:31:06 dfr Exp $\0" diff --git a/lib/csu/crtn.S b/lib/csu/crtn.S new file mode 100644 index 0000000..8e820e3 --- /dev/null +++ b/lib/csu/crtn.S @@ -0,0 +1,35 @@ +/*- + * Copyright 1996, 1997, 1998, 2000 John D. Polstra. + * 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. + */ + + .section .init,"ax",@progbits + add $12,%esp + ret + + .section .fini,"ax",@progbits + add $12,%esp + ret + + .section .rodata +.ascii "$FreeBSD: src/lib/csu/i386-elf/crtn.S,v 1.6 2005/05/19 07:31:06 dfr Exp $\0" diff --git a/lib/libc/Makefile b/lib/libc/Makefile new file mode 100644 index 0000000..adc2be8 --- /dev/null +++ b/lib/libc/Makefile @@ -0,0 +1,98 @@ +# $Id: Makefile 89 2016-01-12 00:20:40Z reddawg $ +# The System Makefile (C) 2002 The UbixOS Project + +# Include Global 'Source' Options +include ../../Makefile.incl +include ../Makefile.incl + +#Objects +OBJS = + +AR = ar + +LPIC = pic.a + +#Sub Sections +SUBS = ./*/*.o ./db/*/*.o ./i386/*/*.o + +#Output +OUTPUT = libc.so + +lib.so: $(OBJS) + (cd yp;make) + (cd xdr;make) + (cd uuid;make) + (cd uthread;make) + (cd sys;make) + (cd string;make) + (cd stdtime;make) + (cd stdlib;make) + (cd stdio;make) + (cd rpc;make) + (cd resolv;make) + (cd regex;make) + (cd quad;make) + (cd posix1e;make) + (cd nls;make) + (cd net;make) + (cd nameser;make) + (cd locale;make) + (cd isc;make) + (cd inet;make) + (cd i386;make) + (cd gmon;make) + (cd gen;make) + (cd gdtoa;make) + (cd db;make) + (cd compat-43;make) + $(CC) -nostdlib -shared -Wl,-soname,libc.so -o $(OUTPUT) $(OBJS) $(SUBS) + +pic.a: $(OBJS) + $(AR) cq $(LPIC) $(OBJS) $(SUBS) + ranlib $(LPIC) + +# Compile the source files +.cc.o: + $(CXX) -Wall -nostdinc -O -I./include -c -o $@ $< + +.cc.s: + $(CXX) -Wall -nostdinc -O -I./include -S -o $@ $< + +.c.o: + $(CC) -Wall -nostdinc -O -I./include -c $< + +.c.s: + $(CC) -Wall -nostdinc -O -I./include -S -o $@ $< + +.S.o: + $(CC) -Wall -nostdinc -c -o $@ $< + +# Clean up the junk +clean: + $(REMOVE) $(OBJS) $(OUTPUT) + (cd yp;make clean) + (cd xdr;make clean) + (cd uuid;make clean) + (cd uthread;make clean) + (cd sys;make clean) + (cd string;make clean) + (cd stdtime;make clean) + (cd stdlib;make clean) + (cd stdio;make clean) + (cd rpc;make clean) + (cd resolv;make clean) + (cd regex;make clean) + (cd quad;make clean) + (cd posix1e;make clean) + (cd nls;make clean) + (cd net;make clean) + (cd nameser;make clean) + (cd locale;make clean) + (cd isc;make clean) + (cd inet;make clean) + (cd i386;make clean) + (cd gmon;make clean) + (cd gen;make clean) + (cd gdtoa;make clean) + (cd db;make clean) + (cd compat-43;make clean) diff --git a/lib/libc/Makefile.incl b/lib/libc/Makefile.incl new file mode 100644 index 0000000..f26452b --- /dev/null +++ b/lib/libc/Makefile.incl @@ -0,0 +1,4 @@ +#MrOlsen (2016-01-11) NOTE Temp Disable INCLUDES = -I../include -I../../../include.new +INCLUDES+=-I../include -I../locale +CFLAGS = -fpic -DPIC -O2 -fno-strict-aliasing -pipe -D__DBINTERFACE_PRIVATE -DPOSIX_MISTAKE -DBROKEN_DES -DPORTMAP -DDES_BUILTIN -DYP -DHESIOD -Wsystem-headers -Wall -Wno-format-y2k -Wno-uninitialized +CFLAGS += -DPORTMAP -D__DBINTERFACE_PRIVATE -nostdinc #-DPIC diff --git a/lib/libc/compat-43/Makefile b/lib/libc/compat-43/Makefile new file mode 100644 index 0000000..c869a28 --- /dev/null +++ b/lib/libc/compat-43/Makefile @@ -0,0 +1,35 @@ +# $Id: Makefile 89 2016-01-12 00:20:40Z reddawg $ +# The System Makefile (C) 2002 The UbixOS Project + +# Include Global 'Source' Options +include ../../../Makefile.incl +include ../../Makefile.incl +include ../Makefile.incl + +INCLUDES += -I../locale/ + +#Objects +OBJS = creat.o gethostid.o getwd.o killpg.o sethostid.o setpgrp.o setrgid.o setruid.o sigcompat.o + +all: $(OBJS) + +# Compile the source files +.cc.o: + $(CXX) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -c -o $@ $< + +.cc.s: + $(CXX) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -S -o $@ $< + +.c.o: + $(CC) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -c $< + +.c.s: + $(CC) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -S -o $@ $< + +.S.o: + $(CC) $(CFLAGS) -Wall -nostdlib -c -o $@ $< + +# Clean up the junk +clean: + $(REMOVE) $(OBJS) + diff --git a/lib/libc/compat-43/creat.c b/lib/libc/compat-43/creat.c new file mode 100644 index 0000000..7af5b25 --- /dev/null +++ b/lib/libc/compat-43/creat.c @@ -0,0 +1,50 @@ +/* + * Copyright (c) 1989, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)creat.c 8.1 (Berkeley) 6/2/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/compat-43/creat.c,v 1.7 2002/03/22 21:51:56 obrien Exp $"); + +#include "namespace.h" +#include +#include "un-namespace.h" + +int +__creat(const char *path, mode_t mode) +{ + return(_open(path, O_WRONLY|O_CREAT|O_TRUNC, mode)); +} +__weak_reference(__creat, creat); +__weak_reference(__creat, _creat); diff --git a/lib/libc/compat-43/gethostid.c b/lib/libc/compat-43/gethostid.c new file mode 100644 index 0000000..0f08fad --- /dev/null +++ b/lib/libc/compat-43/gethostid.c @@ -0,0 +1,56 @@ +/* + * Copyright (c) 1989, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)gethostid.c 8.1 (Berkeley) 6/2/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/compat-43/gethostid.c,v 1.3 2002/05/28 16:56:57 alfred Exp $"); + +#include +#include + +long +gethostid(void) +{ + int mib[2]; + size_t size; + long value; + + mib[0] = CTL_KERN; + mib[1] = KERN_HOSTID; + size = sizeof value; + if (sysctl(mib, 2, &value, &size, NULL, 0) == -1) + return (-1); + return (value); +} diff --git a/lib/libc/compat-43/getwd.c b/lib/libc/compat-43/getwd.c new file mode 100644 index 0000000..9d52a4a --- /dev/null +++ b/lib/libc/compat-43/getwd.c @@ -0,0 +1,55 @@ +/*- + * Copyright (c) 1990, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)getwd.c 8.1 (Berkeley) 6/2/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/compat-43/getwd.c,v 1.5 2005/02/27 18:39:02 phantom Exp $"); + +#include +#include +#include +#include +#include + +char * +getwd(char *buf) +{ + char *p; + + if ( (p = getcwd(buf, MAXPATHLEN)) ) + return(p); + (void)strerror_r(errno, buf, MAXPATHLEN); + return((char *)NULL); +} diff --git a/lib/libc/compat-43/killpg.c b/lib/libc/compat-43/killpg.c new file mode 100644 index 0000000..a6220f7 --- /dev/null +++ b/lib/libc/compat-43/killpg.c @@ -0,0 +1,55 @@ +/* + * Copyright (c) 1989, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)killpg.c 8.1 (Berkeley) 6/2/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/compat-43/killpg.c,v 1.4 2002/05/28 16:56:57 alfred Exp $"); + +#include +#include +#include + +/* + * Backwards-compatible killpg(). + */ +int +killpg(pid_t pgid, int sig) +{ + if (pgid == 1) { + errno = ESRCH; + return (-1); + } + return (kill(-pgid, sig)); +} diff --git a/lib/libc/compat-43/sethostid.c b/lib/libc/compat-43/sethostid.c new file mode 100644 index 0000000..a23ec8e --- /dev/null +++ b/lib/libc/compat-43/sethostid.c @@ -0,0 +1,53 @@ +/* + * Copyright (c) 1989, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)sethostid.c 8.1 (Berkeley) 6/2/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/compat-43/sethostid.c,v 1.3 2002/05/28 16:56:57 alfred Exp $"); + +#include +#include + +long +sethostid(long hostid) +{ + int mib[2]; + + mib[0] = CTL_KERN; + mib[1] = KERN_HOSTID; + if (sysctl(mib, 2, NULL, NULL, &hostid, sizeof hostid) == -1) + return (-1); + return (0); +} diff --git a/lib/libc/compat-43/setpgrp.c b/lib/libc/compat-43/setpgrp.c new file mode 100644 index 0000000..0c07ce8 --- /dev/null +++ b/lib/libc/compat-43/setpgrp.c @@ -0,0 +1,47 @@ +/*- + * Copyright (c) 1990, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)setpgrp.c 8.1 (Berkeley) 6/2/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/compat-43/setpgrp.c,v 1.4 2002/05/28 16:56:57 alfred Exp $"); + +#include +#include + +int +setpgrp(pid_t pid, pid_t pgid) +{ + return(setpgid(pid, pgid)); +} diff --git a/lib/libc/compat-43/setrgid.c b/lib/libc/compat-43/setrgid.c new file mode 100644 index 0000000..360e562 --- /dev/null +++ b/lib/libc/compat-43/setrgid.c @@ -0,0 +1,47 @@ +/* + * Copyright (c) 1983, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)setrgid.c 8.1 (Berkeley) 6/2/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/compat-43/setrgid.c,v 1.3 2002/05/28 16:56:57 alfred Exp $"); + +#include + +int +setrgid(gid_t rgid) +{ + + return (setregid(rgid, -1)); +} diff --git a/lib/libc/compat-43/setruid.c b/lib/libc/compat-43/setruid.c new file mode 100644 index 0000000..5fb6d60 --- /dev/null +++ b/lib/libc/compat-43/setruid.c @@ -0,0 +1,47 @@ +/* + * Copyright (c) 1983, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)setruid.c 8.1 (Berkeley) 6/2/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/compat-43/setruid.c,v 1.3 2002/05/28 16:56:57 alfred Exp $"); + +#include + +int +setruid(uid_t ruid) +{ + + return (setreuid(ruid, -1)); +} diff --git a/lib/libc/compat-43/sigcompat.c b/lib/libc/compat-43/sigcompat.c new file mode 100644 index 0000000..37ba978 --- /dev/null +++ b/lib/libc/compat-43/sigcompat.c @@ -0,0 +1,112 @@ +/* + * Copyright (c) 1989, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)sigcompat.c 8.1 (Berkeley) 6/2/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/compat-43/sigcompat.c,v 1.10 2002/03/22 21:51:56 obrien Exp $"); + +#include "namespace.h" +#include +#include +#include "un-namespace.h" +#include "libc_private.h" + +int +sigvec(signo, sv, osv) + int signo; + struct sigvec *sv, *osv; +{ + struct sigaction sa, osa; + struct sigaction *sap, *osap; + int ret; + + if (sv != NULL) { + sa.sa_handler = sv->sv_handler; + sa.sa_flags = sv->sv_flags ^ SV_INTERRUPT; + sigemptyset(&sa.sa_mask); + sa.sa_mask.__bits[0] = sv->sv_mask; + sap = &sa; + } else + sap = NULL; + osap = osv != NULL ? &osa : NULL; + ret = _sigaction(signo, sap, osap); + if (ret == 0 && osv != NULL) { + osv->sv_handler = osa.sa_handler; + osv->sv_flags = osa.sa_flags ^ SV_INTERRUPT; + osv->sv_mask = osa.sa_mask.__bits[0]; + } + return (ret); +} + +int +sigsetmask(mask) + int mask; +{ + sigset_t set, oset; + int n; + + sigemptyset(&set); + set.__bits[0] = mask; + n = _sigprocmask(SIG_SETMASK, &set, &oset); + if (n) + return (n); + return (oset.__bits[0]); +} + +int +sigblock(mask) + int mask; +{ + sigset_t set, oset; + int n; + + sigemptyset(&set); + set.__bits[0] = mask; + n = _sigprocmask(SIG_BLOCK, &set, &oset); + if (n) + return (n); + return (oset.__bits[0]); +} + +int +sigpause(mask) + int mask; +{ + sigset_t set; + + sigemptyset(&set); + set.__bits[0] = mask; + return (_sigsuspend(&set)); +} diff --git a/lib/libc/db/Makefile b/lib/libc/db/Makefile new file mode 100755 index 0000000..e61803a --- /dev/null +++ b/lib/libc/db/Makefile @@ -0,0 +1,17 @@ +# $Id: Makefile 89 2016-01-12 00:20:40Z reddawg $ +# The System Makefile (C) 2002 The UbixOS Project + +all: + (cd btree;make) + (cd db;make) + (cd hash;make) + (cd mpool;make) + (cd recno;make) + +# Clean up the junk +clean: + (cd btree;make clean) + (cd db;make clean) + (cd hash;make clean) + (cd mpool;make clean) + (cd recno;make clean) diff --git a/lib/libc/db/Makefile.incl b/lib/libc/db/Makefile.incl new file mode 100755 index 0000000..55ed355 --- /dev/null +++ b/lib/libc/db/Makefile.incl @@ -0,0 +1,2 @@ +INCLUDES = -I../../include -I../../../../include.new +CFLAGS += -DPORTMAP -D__DBINTERFACE_PRIVATE -nostdinc diff --git a/lib/libc/db/README b/lib/libc/db/README new file mode 100644 index 0000000..bed2c92 --- /dev/null +++ b/lib/libc/db/README @@ -0,0 +1,40 @@ +# @(#)README 8.27 (Berkeley) 9/1/94 + +This is version 1.85 of the Berkeley DB code. + +For information on compiling and installing this software, see the file +PORT/README. + +Newer versions of this software will periodically be made available by +anonymous ftp from ftp.cs.berkeley.edu. An archive in compressed format +is in ucb/4bsd/db.tar.Z, or in gzip format in ucb/4bsd/db.tar.gz. If +you'd like to receive announcements of future releases of this software, +send email to the contact address below. + +Email questions may be addressed to Keith Bostic at bostic@cs.berkeley.edu. + +============================================ +Distribution contents: + +Makefile.inc Ignore this, it's the 4.4BSD subsystem Makefile. +PORT The per OS/architecture directories to use to build + libdb.a, if you're not running 4.4BSD. See the file + PORT/README for more information. +README This file. +btree The B+tree routines. +changelog List of changes, per version. +db The dbopen(3) interface routine. +docs Various USENIX papers, and the formatted manual pages. +hash The extended linear hashing routines. +man The unformatted manual pages. +mpool The memory pool routines. +recno The fixed/variable length record routines. +test Test package. + +============================================ +Debugging: + +If you're running a memory checker (e.g. Purify) on DB, make sure that +you recompile it with "-DPURIFY" in the CFLAGS, first. By default, +allocated pages are not initialized by the DB code, and they will show +up as reads of uninitialized memory in the buffer write routines. diff --git a/lib/libc/db/btree/Makefile b/lib/libc/db/btree/Makefile new file mode 100644 index 0000000..b5e17cc --- /dev/null +++ b/lib/libc/db/btree/Makefile @@ -0,0 +1,35 @@ +# $Id: Makefile 89 2016-01-12 00:20:40Z reddawg $ +# The System Makefile (C) 2002 The UbixOS Project + +# Include Global 'Source' Options +include ../../../../Makefile.incl +include ../../../Makefile.incl +include ../Makefile.incl + +INCLUDES += -I../ -I../../include + +#Objects +OBJS = bt_close.o bt_conv.o bt_debug.o bt_delete.o bt_get.o bt_open.o bt_overflow.o bt_page.o bt_put.o bt_search.o bt_seq.o bt_split.o bt_utils.o + +all: $(OBJS) + +# Compile the source files +.cc.o: + $(CXX) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -c -o $@ $< + +.cc.s: + $(CXX) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -S -o $@ $< + +.c.o: + $(CC) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -c $< + +.c.s: + $(CC) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -S -o $@ $< + +.S.o: + $(CC) $(CFLAGS) -Wall -nostdlib $(INCLUDES) -c -o $@ $< + +# Clean up the junk +clean: + $(REMOVE) $(OBJS) + diff --git a/lib/libc/db/btree/bt_close.c b/lib/libc/db/btree/bt_close.c new file mode 100644 index 0000000..c211d5b --- /dev/null +++ b/lib/libc/db/btree/bt_close.c @@ -0,0 +1,186 @@ +/*- + * Copyright (c) 1990, 1993, 1994 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * Mike Olson. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)bt_close.c 8.7 (Berkeley) 8/17/94"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/db/btree/bt_close.c,v 1.8 2002/03/22 21:52:00 obrien Exp $"); + +#include "namespace.h" +#include + +#include +#include +#include +#include +#include +#include "un-namespace.h" + +#include +#include "btree.h" + +static int bt_meta(BTREE *); + +/* + * BT_CLOSE -- Close a btree. + * + * Parameters: + * dbp: pointer to access method + * + * Returns: + * RET_ERROR, RET_SUCCESS + */ +int +__bt_close(dbp) + DB *dbp; +{ + BTREE *t; + int fd; + + t = dbp->internal; + + /* Toss any page pinned across calls. */ + if (t->bt_pinned != NULL) { + mpool_put(t->bt_mp, t->bt_pinned, 0); + t->bt_pinned = NULL; + } + + /* Sync the tree. */ + if (__bt_sync(dbp, 0) == RET_ERROR) + return (RET_ERROR); + + /* Close the memory pool. */ + if (mpool_close(t->bt_mp) == RET_ERROR) + return (RET_ERROR); + + /* Free random memory. */ + if (t->bt_cursor.key.data != NULL) { + free(t->bt_cursor.key.data); + t->bt_cursor.key.size = 0; + t->bt_cursor.key.data = NULL; + } + if (t->bt_rkey.data) { + free(t->bt_rkey.data); + t->bt_rkey.size = 0; + t->bt_rkey.data = NULL; + } + if (t->bt_rdata.data) { + free(t->bt_rdata.data); + t->bt_rdata.size = 0; + t->bt_rdata.data = NULL; + } + + fd = t->bt_fd; + free(t); + free(dbp); + return (_close(fd) ? RET_ERROR : RET_SUCCESS); +} + +/* + * BT_SYNC -- sync the btree to disk. + * + * Parameters: + * dbp: pointer to access method + * + * Returns: + * RET_SUCCESS, RET_ERROR. + */ +int +__bt_sync(dbp, flags) + const DB *dbp; + u_int flags; +{ + BTREE *t; + int status; + + t = dbp->internal; + + /* Toss any page pinned across calls. */ + if (t->bt_pinned != NULL) { + mpool_put(t->bt_mp, t->bt_pinned, 0); + t->bt_pinned = NULL; + } + + /* Sync doesn't currently take any flags. */ + if (flags != 0) { + errno = EINVAL; + return (RET_ERROR); + } + + if (F_ISSET(t, B_INMEM | B_RDONLY) || !F_ISSET(t, B_MODIFIED)) + return (RET_SUCCESS); + + if (F_ISSET(t, B_METADIRTY) && bt_meta(t) == RET_ERROR) + return (RET_ERROR); + + if ((status = mpool_sync(t->bt_mp)) == RET_SUCCESS) + F_CLR(t, B_MODIFIED); + + return (status); +} + +/* + * BT_META -- write the tree meta data to disk. + * + * Parameters: + * t: tree + * + * Returns: + * RET_ERROR, RET_SUCCESS + */ +static int +bt_meta(t) + BTREE *t; +{ + BTMETA m; + void *p; + + if ((p = mpool_get(t->bt_mp, P_META, 0)) == NULL) + return (RET_ERROR); + + /* Fill in metadata. */ + m.magic = BTREEMAGIC; + m.version = BTREEVERSION; + m.psize = t->bt_psize; + m.free = t->bt_free; + m.nrecs = t->bt_nrecs; + m.flags = F_ISSET(t, SAVEMETA); + + memmove(p, &m, sizeof(BTMETA)); + mpool_put(t->bt_mp, p, MPOOL_DIRTY); + return (RET_SUCCESS); +} diff --git a/lib/libc/db/btree/bt_conv.c b/lib/libc/db/btree/bt_conv.c new file mode 100644 index 0000000..86d6b2c --- /dev/null +++ b/lib/libc/db/btree/bt_conv.c @@ -0,0 +1,223 @@ +/*- + * Copyright (c) 1990, 1993, 1994 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * Mike Olson. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)bt_conv.c 8.5 (Berkeley) 8/17/94"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/db/btree/bt_conv.c,v 1.2 2002/03/21 22:46:25 obrien Exp $"); + +#include + +#include + +#include +#include "btree.h" + +static void mswap(PAGE *); + +/* + * __BT_BPGIN, __BT_BPGOUT -- + * Convert host-specific number layout to/from the host-independent + * format stored on disk. + * + * Parameters: + * t: tree + * pg: page number + * h: page to convert + */ +void +__bt_pgin(t, pg, pp) + void *t; + pgno_t pg; + void *pp; +{ + PAGE *h; + indx_t i, top; + u_char flags; + char *p; + + if (!F_ISSET(((BTREE *)t), B_NEEDSWAP)) + return; + if (pg == P_META) { + mswap(pp); + return; + } + + h = pp; + M_32_SWAP(h->pgno); + M_32_SWAP(h->prevpg); + M_32_SWAP(h->nextpg); + M_32_SWAP(h->flags); + M_16_SWAP(h->lower); + M_16_SWAP(h->upper); + + top = NEXTINDEX(h); + if ((h->flags & P_TYPE) == P_BINTERNAL) + for (i = 0; i < top; i++) { + M_16_SWAP(h->linp[i]); + p = (char *)GETBINTERNAL(h, i); + P_32_SWAP(p); + p += sizeof(uint32_t); + P_32_SWAP(p); + p += sizeof(pgno_t); + if (*(u_char *)p & P_BIGKEY) { + p += sizeof(u_char); + P_32_SWAP(p); + p += sizeof(pgno_t); + P_32_SWAP(p); + } + } + else if ((h->flags & P_TYPE) == P_BLEAF) + for (i = 0; i < top; i++) { + M_16_SWAP(h->linp[i]); + p = (char *)GETBLEAF(h, i); + P_32_SWAP(p); + p += sizeof(uint32_t); + P_32_SWAP(p); + p += sizeof(uint32_t); + flags = *(u_char *)p; + if (flags & (P_BIGKEY | P_BIGDATA)) { + p += sizeof(u_char); + if (flags & P_BIGKEY) { + P_32_SWAP(p); + p += sizeof(pgno_t); + P_32_SWAP(p); + } + if (flags & P_BIGDATA) { + p += sizeof(uint32_t); + P_32_SWAP(p); + p += sizeof(pgno_t); + P_32_SWAP(p); + } + } + } +} + +void +__bt_pgout(t, pg, pp) + void *t; + pgno_t pg; + void *pp; +{ + PAGE *h; + indx_t i, top; + u_char flags; + char *p; + + if (!F_ISSET(((BTREE *)t), B_NEEDSWAP)) + return; + if (pg == P_META) { + mswap(pp); + return; + } + + h = pp; + top = NEXTINDEX(h); + if ((h->flags & P_TYPE) == P_BINTERNAL) + for (i = 0; i < top; i++) { + p = (char *)GETBINTERNAL(h, i); + P_32_SWAP(p); + p += sizeof(uint32_t); + P_32_SWAP(p); + p += sizeof(pgno_t); + if (*(u_char *)p & P_BIGKEY) { + p += sizeof(u_char); + P_32_SWAP(p); + p += sizeof(pgno_t); + P_32_SWAP(p); + } + M_16_SWAP(h->linp[i]); + } + else if ((h->flags & P_TYPE) == P_BLEAF) + for (i = 0; i < top; i++) { + p = (char *)GETBLEAF(h, i); + P_32_SWAP(p); + p += sizeof(uint32_t); + P_32_SWAP(p); + p += sizeof(uint32_t); + flags = *(u_char *)p; + if (flags & (P_BIGKEY | P_BIGDATA)) { + p += sizeof(u_char); + if (flags & P_BIGKEY) { + P_32_SWAP(p); + p += sizeof(pgno_t); + P_32_SWAP(p); + } + if (flags & P_BIGDATA) { + p += sizeof(uint32_t); + P_32_SWAP(p); + p += sizeof(pgno_t); + P_32_SWAP(p); + } + } + M_16_SWAP(h->linp[i]); + } + + M_32_SWAP(h->pgno); + M_32_SWAP(h->prevpg); + M_32_SWAP(h->nextpg); + M_32_SWAP(h->flags); + M_16_SWAP(h->lower); + M_16_SWAP(h->upper); +} + +/* + * MSWAP -- Actually swap the bytes on the meta page. + * + * Parameters: + * p: page to convert + */ +static void +mswap(pg) + PAGE *pg; +{ + char *p; + + p = (char *)pg; + P_32_SWAP(p); /* magic */ + p += sizeof(uint32_t); + P_32_SWAP(p); /* version */ + p += sizeof(uint32_t); + P_32_SWAP(p); /* psize */ + p += sizeof(uint32_t); + P_32_SWAP(p); /* free */ + p += sizeof(uint32_t); + P_32_SWAP(p); /* nrecs */ + p += sizeof(uint32_t); + P_32_SWAP(p); /* flags */ + p += sizeof(uint32_t); +} diff --git a/lib/libc/db/btree/bt_debug.c b/lib/libc/db/btree/bt_debug.c new file mode 100644 index 0000000..ffda6d9 --- /dev/null +++ b/lib/libc/db/btree/bt_debug.c @@ -0,0 +1,332 @@ +/*- + * Copyright (c) 1990, 1993, 1994 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * Mike Olson. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)bt_debug.c 8.5 (Berkeley) 8/17/94"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/db/btree/bt_debug.c,v 1.3 2004/09/10 05:41:41 kuriyama Exp $"); + +#include + +#include +#include +#include + +#include +#include "btree.h" + +#ifdef DEBUG +/* + * BT_DUMP -- Dump the tree + * + * Parameters: + * dbp: pointer to the DB + */ +void +__bt_dump(dbp) + DB *dbp; +{ + BTREE *t; + PAGE *h; + pgno_t i; + char *sep; + + t = dbp->internal; + (void)fprintf(stderr, "%s: pgsz %d", + F_ISSET(t, B_INMEM) ? "memory" : "disk", t->bt_psize); + if (F_ISSET(t, R_RECNO)) + (void)fprintf(stderr, " keys %u", t->bt_nrecs); +#undef X +#define X(flag, name) \ + if (F_ISSET(t, flag)) { \ + (void)fprintf(stderr, "%s%s", sep, name); \ + sep = ", "; \ + } + if (t->flags != 0) { + sep = " flags ("; + X(R_FIXLEN, "FIXLEN"); + X(B_INMEM, "INMEM"); + X(B_NODUPS, "NODUPS"); + X(B_RDONLY, "RDONLY"); + X(R_RECNO, "RECNO"); + X(B_METADIRTY,"METADIRTY"); + (void)fprintf(stderr, ")\n"); + } +#undef X + + for (i = P_ROOT; (h = mpool_get(t->bt_mp, i, 0)) != NULL; ++i) { + __bt_dpage(h); + (void)mpool_put(t->bt_mp, h, 0); + } +} + +/* + * BT_DMPAGE -- Dump the meta page + * + * Parameters: + * h: pointer to the PAGE + */ +void +__bt_dmpage(h) + PAGE *h; +{ + BTMETA *m; + char *sep; + + m = (BTMETA *)h; + (void)fprintf(stderr, "magic %x\n", m->magic); + (void)fprintf(stderr, "version %u\n", m->version); + (void)fprintf(stderr, "psize %u\n", m->psize); + (void)fprintf(stderr, "free %u\n", m->free); + (void)fprintf(stderr, "nrecs %u\n", m->nrecs); + (void)fprintf(stderr, "flags %u", m->flags); +#undef X +#define X(flag, name) \ + if (m->flags & flag) { \ + (void)fprintf(stderr, "%s%s", sep, name); \ + sep = ", "; \ + } + if (m->flags) { + sep = " ("; + X(B_NODUPS, "NODUPS"); + X(R_RECNO, "RECNO"); + (void)fprintf(stderr, ")"); + } +} + +/* + * BT_DNPAGE -- Dump the page + * + * Parameters: + * n: page number to dump. + */ +void +__bt_dnpage(dbp, pgno) + DB *dbp; + pgno_t pgno; +{ + BTREE *t; + PAGE *h; + + t = dbp->internal; + if ((h = mpool_get(t->bt_mp, pgno, 0)) != NULL) { + __bt_dpage(h); + (void)mpool_put(t->bt_mp, h, 0); + } +} + +/* + * BT_DPAGE -- Dump the page + * + * Parameters: + * h: pointer to the PAGE + */ +void +__bt_dpage(h) + PAGE *h; +{ + BINTERNAL *bi; + BLEAF *bl; + RINTERNAL *ri; + RLEAF *rl; + indx_t cur, top; + char *sep; + + (void)fprintf(stderr, " page %d: (", h->pgno); +#undef X +#define X(flag, name) \ + if (h->flags & flag) { \ + (void)fprintf(stderr, "%s%s", sep, name); \ + sep = ", "; \ + } + sep = ""; + X(P_BINTERNAL, "BINTERNAL") /* types */ + X(P_BLEAF, "BLEAF") + X(P_RINTERNAL, "RINTERNAL") /* types */ + X(P_RLEAF, "RLEAF") + X(P_OVERFLOW, "OVERFLOW") + X(P_PRESERVE, "PRESERVE"); + (void)fprintf(stderr, ")\n"); +#undef X + + (void)fprintf(stderr, "\tprev %2d next %2d", h->prevpg, h->nextpg); + if (h->flags & P_OVERFLOW) + return; + + top = NEXTINDEX(h); + (void)fprintf(stderr, " lower %3d upper %3d nextind %d\n", + h->lower, h->upper, top); + for (cur = 0; cur < top; cur++) { + (void)fprintf(stderr, "\t[%03d] %4d ", cur, h->linp[cur]); + switch (h->flags & P_TYPE) { + case P_BINTERNAL: + bi = GETBINTERNAL(h, cur); + (void)fprintf(stderr, + "size %03d pgno %03d", bi->ksize, bi->pgno); + if (bi->flags & P_BIGKEY) + (void)fprintf(stderr, " (indirect)"); + else if (bi->ksize) + (void)fprintf(stderr, + " {%.*s}", (int)bi->ksize, bi->bytes); + break; + case P_RINTERNAL: + ri = GETRINTERNAL(h, cur); + (void)fprintf(stderr, "entries %03d pgno %03d", + ri->nrecs, ri->pgno); + break; + case P_BLEAF: + bl = GETBLEAF(h, cur); + if (bl->flags & P_BIGKEY) + (void)fprintf(stderr, + "big key page %u size %u/", + *(pgno_t *)bl->bytes, + *(uint32_t *)(bl->bytes + sizeof(pgno_t))); + else if (bl->ksize) + (void)fprintf(stderr, "%.*s/", + bl->ksize, bl->bytes); + if (bl->flags & P_BIGDATA) + (void)fprintf(stderr, + "big data page %u size %u", + *(pgno_t *)(bl->bytes + bl->ksize), + *(uint32_t *)(bl->bytes + bl->ksize + + sizeof(pgno_t))); + else if (bl->dsize) + (void)fprintf(stderr, "%.*s", + (int)bl->dsize, bl->bytes + bl->ksize); + break; + case P_RLEAF: + rl = GETRLEAF(h, cur); + if (rl->flags & P_BIGDATA) + (void)fprintf(stderr, + "big data page %u size %u", + *(pgno_t *)rl->bytes, + *(uint32_t *)(rl->bytes + sizeof(pgno_t))); + else if (rl->dsize) + (void)fprintf(stderr, + "%.*s", (int)rl->dsize, rl->bytes); + break; + } + (void)fprintf(stderr, "\n"); + } +} +#endif + +#ifdef STATISTICS +/* + * BT_STAT -- Gather/print the tree statistics + * + * Parameters: + * dbp: pointer to the DB + */ +void +__bt_stat(dbp) + DB *dbp; +{ + extern u_long bt_cache_hit, bt_cache_miss, bt_pfxsaved, bt_rootsplit; + extern u_long bt_sortsplit, bt_split; + BTREE *t; + PAGE *h; + pgno_t i, pcont, pinternal, pleaf; + u_long ifree, lfree, nkeys; + int levels; + + t = dbp->internal; + pcont = pinternal = pleaf = 0; + nkeys = ifree = lfree = 0; + for (i = P_ROOT; (h = mpool_get(t->bt_mp, i, 0)) != NULL; ++i) { + switch (h->flags & P_TYPE) { + case P_BINTERNAL: + case P_RINTERNAL: + ++pinternal; + ifree += h->upper - h->lower; + break; + case P_BLEAF: + case P_RLEAF: + ++pleaf; + lfree += h->upper - h->lower; + nkeys += NEXTINDEX(h); + break; + case P_OVERFLOW: + ++pcont; + break; + } + (void)mpool_put(t->bt_mp, h, 0); + } + + /* Count the levels of the tree. */ + for (i = P_ROOT, levels = 0 ;; ++levels) { + h = mpool_get(t->bt_mp, i, 0); + if (h->flags & (P_BLEAF|P_RLEAF)) { + if (levels == 0) + levels = 1; + (void)mpool_put(t->bt_mp, h, 0); + break; + } + i = F_ISSET(t, R_RECNO) ? + GETRINTERNAL(h, 0)->pgno : + GETBINTERNAL(h, 0)->pgno; + (void)mpool_put(t->bt_mp, h, 0); + } + + (void)fprintf(stderr, "%d level%s with %ld keys", + levels, levels == 1 ? "" : "s", nkeys); + if (F_ISSET(t, R_RECNO)) + (void)fprintf(stderr, " (%d header count)", t->bt_nrecs); + (void)fprintf(stderr, + "\n%u pages (leaf %d, internal %d, overflow %d)\n", + pinternal + pleaf + pcont, pleaf, pinternal, pcont); + (void)fprintf(stderr, "%ld cache hits, %ld cache misses\n", + bt_cache_hit, bt_cache_miss); + (void)fprintf(stderr, "%lu splits (%lu root splits, %lu sort splits)\n", + bt_split, bt_rootsplit, bt_sortsplit); + pleaf *= t->bt_psize - BTDATAOFF; + if (pleaf) + (void)fprintf(stderr, + "%.0f%% leaf fill (%ld bytes used, %ld bytes free)\n", + ((double)(pleaf - lfree) / pleaf) * 100, + pleaf - lfree, lfree); + pinternal *= t->bt_psize - BTDATAOFF; + if (pinternal) + (void)fprintf(stderr, + "%.0f%% internal fill (%ld bytes used, %ld bytes free\n", + ((double)(pinternal - ifree) / pinternal) * 100, + pinternal - ifree, ifree); + if (bt_pfxsaved) + (void)fprintf(stderr, "prefix checking removed %lu bytes.\n", + bt_pfxsaved); +} +#endif diff --git a/lib/libc/db/btree/bt_delete.c b/lib/libc/db/btree/bt_delete.c new file mode 100644 index 0000000..08d0d86 --- /dev/null +++ b/lib/libc/db/btree/bt_delete.c @@ -0,0 +1,659 @@ +/*- + * Copyright (c) 1990, 1993, 1994 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * Mike Olson. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)bt_delete.c 8.13 (Berkeley) 7/28/94"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/db/btree/bt_delete.c,v 1.2 2002/03/21 22:46:25 obrien Exp $"); + +#include + +#include +#include +#include + +#include +#include "btree.h" + +static int __bt_bdelete(BTREE *, const DBT *); +static int __bt_curdel(BTREE *, const DBT *, PAGE *, u_int); +static int __bt_pdelete(BTREE *, PAGE *); +static int __bt_relink(BTREE *, PAGE *); +static int __bt_stkacq(BTREE *, PAGE **, CURSOR *); + +/* + * __bt_delete + * Delete the item(s) referenced by a key. + * + * Return RET_SPECIAL if the key is not found. + */ +int +__bt_delete(dbp, key, flags) + const DB *dbp; + const DBT *key; + u_int flags; +{ + BTREE *t; + CURSOR *c; + PAGE *h; + int status; + + t = dbp->internal; + + /* Toss any page pinned across calls. */ + if (t->bt_pinned != NULL) { + mpool_put(t->bt_mp, t->bt_pinned, 0); + t->bt_pinned = NULL; + } + + /* Check for change to a read-only tree. */ + if (F_ISSET(t, B_RDONLY)) { + errno = EPERM; + return (RET_ERROR); + } + + switch (flags) { + case 0: + status = __bt_bdelete(t, key); + break; + case R_CURSOR: + /* + * If flags is R_CURSOR, delete the cursor. Must already + * have started a scan and not have already deleted it. + */ + c = &t->bt_cursor; + if (F_ISSET(c, CURS_INIT)) { + if (F_ISSET(c, CURS_ACQUIRE | CURS_AFTER | CURS_BEFORE)) + return (RET_SPECIAL); + if ((h = mpool_get(t->bt_mp, c->pg.pgno, 0)) == NULL) + return (RET_ERROR); + + /* + * If the page is about to be emptied, we'll need to + * delete it, which means we have to acquire a stack. + */ + if (NEXTINDEX(h) == 1) + if (__bt_stkacq(t, &h, &t->bt_cursor)) + return (RET_ERROR); + + status = __bt_dleaf(t, NULL, h, c->pg.index); + + if (NEXTINDEX(h) == 0 && status == RET_SUCCESS) { + if (__bt_pdelete(t, h)) + return (RET_ERROR); + } else + mpool_put(t->bt_mp, + h, status == RET_SUCCESS ? MPOOL_DIRTY : 0); + break; + } + /* FALLTHROUGH */ + default: + errno = EINVAL; + return (RET_ERROR); + } + if (status == RET_SUCCESS) + F_SET(t, B_MODIFIED); + return (status); +} + +/* + * __bt_stkacq -- + * Acquire a stack so we can delete a cursor entry. + * + * Parameters: + * t: tree + * hp: pointer to current, pinned PAGE pointer + * c: pointer to the cursor + * + * Returns: + * 0 on success, 1 on failure + */ +static int +__bt_stkacq(t, hp, c) + BTREE *t; + PAGE **hp; + CURSOR *c; +{ + BINTERNAL *bi; + EPG *e; + EPGNO *parent; + PAGE *h; + indx_t index; + pgno_t pgno; + recno_t nextpg, prevpg; + int exact, level; + + /* + * Find the first occurrence of the key in the tree. Toss the + * currently locked page so we don't hit an already-locked page. + */ + h = *hp; + mpool_put(t->bt_mp, h, 0); + if ((e = __bt_search(t, &c->key, &exact)) == NULL) + return (1); + h = e->page; + + /* See if we got it in one shot. */ + if (h->pgno == c->pg.pgno) + goto ret; + + /* + * Move right, looking for the page. At each move we have to move + * up the stack until we don't have to move to the next page. If + * we have to change pages at an internal level, we have to fix the + * stack back up. + */ + while (h->pgno != c->pg.pgno) { + if ((nextpg = h->nextpg) == P_INVALID) + break; + mpool_put(t->bt_mp, h, 0); + + /* Move up the stack. */ + for (level = 0; (parent = BT_POP(t)) != NULL; ++level) { + /* Get the parent page. */ + if ((h = mpool_get(t->bt_mp, parent->pgno, 0)) == NULL) + return (1); + + /* Move to the next index. */ + if (parent->index != NEXTINDEX(h) - 1) { + index = parent->index + 1; + BT_PUSH(t, h->pgno, index); + break; + } + mpool_put(t->bt_mp, h, 0); + } + + /* Restore the stack. */ + while (level--) { + /* Push the next level down onto the stack. */ + bi = GETBINTERNAL(h, index); + pgno = bi->pgno; + BT_PUSH(t, pgno, 0); + + /* Lose the currently pinned page. */ + mpool_put(t->bt_mp, h, 0); + + /* Get the next level down. */ + if ((h = mpool_get(t->bt_mp, pgno, 0)) == NULL) + return (1); + index = 0; + } + mpool_put(t->bt_mp, h, 0); + if ((h = mpool_get(t->bt_mp, nextpg, 0)) == NULL) + return (1); + } + + if (h->pgno == c->pg.pgno) + goto ret; + + /* Reacquire the original stack. */ + mpool_put(t->bt_mp, h, 0); + if ((e = __bt_search(t, &c->key, &exact)) == NULL) + return (1); + h = e->page; + + /* + * Move left, looking for the page. At each move we have to move + * up the stack until we don't have to change pages to move to the + * next page. If we have to change pages at an internal level, we + * have to fix the stack back up. + */ + while (h->pgno != c->pg.pgno) { + if ((prevpg = h->prevpg) == P_INVALID) + break; + mpool_put(t->bt_mp, h, 0); + + /* Move up the stack. */ + for (level = 0; (parent = BT_POP(t)) != NULL; ++level) { + /* Get the parent page. */ + if ((h = mpool_get(t->bt_mp, parent->pgno, 0)) == NULL) + return (1); + + /* Move to the next index. */ + if (parent->index != 0) { + index = parent->index - 1; + BT_PUSH(t, h->pgno, index); + break; + } + mpool_put(t->bt_mp, h, 0); + } + + /* Restore the stack. */ + while (level--) { + /* Push the next level down onto the stack. */ + bi = GETBINTERNAL(h, index); + pgno = bi->pgno; + + /* Lose the currently pinned page. */ + mpool_put(t->bt_mp, h, 0); + + /* Get the next level down. */ + if ((h = mpool_get(t->bt_mp, pgno, 0)) == NULL) + return (1); + + index = NEXTINDEX(h) - 1; + BT_PUSH(t, pgno, index); + } + mpool_put(t->bt_mp, h, 0); + if ((h = mpool_get(t->bt_mp, prevpg, 0)) == NULL) + return (1); + } + + +ret: mpool_put(t->bt_mp, h, 0); + return ((*hp = mpool_get(t->bt_mp, c->pg.pgno, 0)) == NULL); +} + +/* + * __bt_bdelete -- + * Delete all key/data pairs matching the specified key. + * + * Parameters: + * t: tree + * key: key to delete + * + * Returns: + * RET_ERROR, RET_SUCCESS and RET_SPECIAL if the key not found. + */ +static int +__bt_bdelete(t, key) + BTREE *t; + const DBT *key; +{ + EPG *e; + PAGE *h; + int deleted, exact, redo; + + deleted = 0; + + /* Find any matching record; __bt_search pins the page. */ +loop: if ((e = __bt_search(t, key, &exact)) == NULL) + return (deleted ? RET_SUCCESS : RET_ERROR); + if (!exact) { + mpool_put(t->bt_mp, e->page, 0); + return (deleted ? RET_SUCCESS : RET_SPECIAL); + } + + /* + * Delete forward, then delete backward, from the found key. If + * there are duplicates and we reach either side of the page, do + * the key search again, so that we get them all. + */ + redo = 0; + h = e->page; + do { + if (__bt_dleaf(t, key, h, e->index)) { + mpool_put(t->bt_mp, h, 0); + return (RET_ERROR); + } + if (F_ISSET(t, B_NODUPS)) { + if (NEXTINDEX(h) == 0) { + if (__bt_pdelete(t, h)) + return (RET_ERROR); + } else + mpool_put(t->bt_mp, h, MPOOL_DIRTY); + return (RET_SUCCESS); + } + deleted = 1; + } while (e->index < NEXTINDEX(h) && __bt_cmp(t, key, e) == 0); + + /* Check for right-hand edge of the page. */ + if (e->index == NEXTINDEX(h)) + redo = 1; + + /* Delete from the key to the beginning of the page. */ + while (e->index-- > 0) { + if (__bt_cmp(t, key, e) != 0) + break; + if (__bt_dleaf(t, key, h, e->index) == RET_ERROR) { + mpool_put(t->bt_mp, h, 0); + return (RET_ERROR); + } + if (e->index == 0) + redo = 1; + } + + /* Check for an empty page. */ + if (NEXTINDEX(h) == 0) { + if (__bt_pdelete(t, h)) + return (RET_ERROR); + goto loop; + } + + /* Put the page. */ + mpool_put(t->bt_mp, h, MPOOL_DIRTY); + + if (redo) + goto loop; + return (RET_SUCCESS); +} + +/* + * __bt_pdelete -- + * Delete a single page from the tree. + * + * Parameters: + * t: tree + * h: leaf page + * + * Returns: + * RET_SUCCESS, RET_ERROR. + * + * Side-effects: + * mpool_put's the page + */ +static int +__bt_pdelete(t, h) + BTREE *t; + PAGE *h; +{ + BINTERNAL *bi; + PAGE *pg; + EPGNO *parent; + indx_t cnt, index, *ip, offset; + uint32_t nksize; + char *from; + + /* + * Walk the parent page stack -- a LIFO stack of the pages that were + * traversed when we searched for the page where the delete occurred. + * Each stack entry is a page number and a page index offset. The + * offset is for the page traversed on the search. We've just deleted + * a page, so we have to delete the key from the parent page. + * + * If the delete from the parent page makes it empty, this process may + * continue all the way up the tree. We stop if we reach the root page + * (which is never deleted, it's just not worth the effort) or if the + * delete does not empty the page. + */ + while ((parent = BT_POP(t)) != NULL) { + /* Get the parent page. */ + if ((pg = mpool_get(t->bt_mp, parent->pgno, 0)) == NULL) + return (RET_ERROR); + + index = parent->index; + bi = GETBINTERNAL(pg, index); + + /* Free any overflow pages. */ + if (bi->flags & P_BIGKEY && + __ovfl_delete(t, bi->bytes) == RET_ERROR) { + mpool_put(t->bt_mp, pg, 0); + return (RET_ERROR); + } + + /* + * Free the parent if it has only the one key and it's not the + * root page. If it's the rootpage, turn it back into an empty + * leaf page. + */ + if (NEXTINDEX(pg) == 1) + if (pg->pgno == P_ROOT) { + pg->lower = BTDATAOFF; + pg->upper = t->bt_psize; + pg->flags = P_BLEAF; + } else { + if (__bt_relink(t, pg) || __bt_free(t, pg)) + return (RET_ERROR); + continue; + } + else { + /* Pack remaining key items at the end of the page. */ + nksize = NBINTERNAL(bi->ksize); + from = (char *)pg + pg->upper; + memmove(from + nksize, from, (char *)bi - from); + pg->upper += nksize; + + /* Adjust indices' offsets, shift the indices down. */ + offset = pg->linp[index]; + for (cnt = index, ip = &pg->linp[0]; cnt--; ++ip) + if (ip[0] < offset) + ip[0] += nksize; + for (cnt = NEXTINDEX(pg) - index; --cnt; ++ip) + ip[0] = ip[1] < offset ? ip[1] + nksize : ip[1]; + pg->lower -= sizeof(indx_t); + } + + mpool_put(t->bt_mp, pg, MPOOL_DIRTY); + break; + } + + /* Free the leaf page, as long as it wasn't the root. */ + if (h->pgno == P_ROOT) { + mpool_put(t->bt_mp, h, MPOOL_DIRTY); + return (RET_SUCCESS); + } + return (__bt_relink(t, h) || __bt_free(t, h)); +} + +/* + * __bt_dleaf -- + * Delete a single record from a leaf page. + * + * Parameters: + * t: tree + * key: referenced key + * h: page + * index: index on page to delete + * + * Returns: + * RET_SUCCESS, RET_ERROR. + */ +int +__bt_dleaf(t, key, h, index) + BTREE *t; + const DBT *key; + PAGE *h; + u_int index; +{ + BLEAF *bl; + indx_t cnt, *ip, offset; + uint32_t nbytes; + void *to; + char *from; + + /* If this record is referenced by the cursor, delete the cursor. */ + if (F_ISSET(&t->bt_cursor, CURS_INIT) && + !F_ISSET(&t->bt_cursor, CURS_ACQUIRE) && + t->bt_cursor.pg.pgno == h->pgno && t->bt_cursor.pg.index == index && + __bt_curdel(t, key, h, index)) + return (RET_ERROR); + + /* If the entry uses overflow pages, make them available for reuse. */ + to = bl = GETBLEAF(h, index); + if (bl->flags & P_BIGKEY && __ovfl_delete(t, bl->bytes) == RET_ERROR) + return (RET_ERROR); + if (bl->flags & P_BIGDATA && + __ovfl_delete(t, bl->bytes + bl->ksize) == RET_ERROR) + return (RET_ERROR); + + /* Pack the remaining key/data items at the end of the page. */ + nbytes = NBLEAF(bl); + from = (char *)h + h->upper; + memmove(from + nbytes, from, (char *)to - from); + h->upper += nbytes; + + /* Adjust the indices' offsets, shift the indices down. */ + offset = h->linp[index]; + for (cnt = index, ip = &h->linp[0]; cnt--; ++ip) + if (ip[0] < offset) + ip[0] += nbytes; + for (cnt = NEXTINDEX(h) - index; --cnt; ++ip) + ip[0] = ip[1] < offset ? ip[1] + nbytes : ip[1]; + h->lower -= sizeof(indx_t); + + /* If the cursor is on this page, adjust it as necessary. */ + if (F_ISSET(&t->bt_cursor, CURS_INIT) && + !F_ISSET(&t->bt_cursor, CURS_ACQUIRE) && + t->bt_cursor.pg.pgno == h->pgno && t->bt_cursor.pg.index > index) + --t->bt_cursor.pg.index; + + return (RET_SUCCESS); +} + +/* + * __bt_curdel -- + * Delete the cursor. + * + * Parameters: + * t: tree + * key: referenced key (or NULL) + * h: page + * index: index on page to delete + * + * Returns: + * RET_SUCCESS, RET_ERROR. + */ +static int +__bt_curdel(t, key, h, index) + BTREE *t; + const DBT *key; + PAGE *h; + u_int index; +{ + CURSOR *c; + EPG e; + PAGE *pg; + int curcopy, status; + + /* + * If there are duplicates, move forward or backward to one. + * Otherwise, copy the key into the cursor area. + */ + c = &t->bt_cursor; + F_CLR(c, CURS_AFTER | CURS_BEFORE | CURS_ACQUIRE); + + curcopy = 0; + if (!F_ISSET(t, B_NODUPS)) { + /* + * We're going to have to do comparisons. If we weren't + * provided a copy of the key, i.e. the user is deleting + * the current cursor position, get one. + */ + if (key == NULL) { + e.page = h; + e.index = index; + if ((status = __bt_ret(t, &e, + &c->key, &c->key, NULL, NULL, 1)) != RET_SUCCESS) + return (status); + curcopy = 1; + key = &c->key; + } + /* Check previous key, if not at the beginning of the page. */ + if (index > 0) { + e.page = h; + e.index = index - 1; + if (__bt_cmp(t, key, &e) == 0) { + F_SET(c, CURS_BEFORE); + goto dup2; + } + } + /* Check next key, if not at the end of the page. */ + if (index < NEXTINDEX(h) - 1) { + e.page = h; + e.index = index + 1; + if (__bt_cmp(t, key, &e) == 0) { + F_SET(c, CURS_AFTER); + goto dup2; + } + } + /* Check previous key if at the beginning of the page. */ + if (index == 0 && h->prevpg != P_INVALID) { + if ((pg = mpool_get(t->bt_mp, h->prevpg, 0)) == NULL) + return (RET_ERROR); + e.page = pg; + e.index = NEXTINDEX(pg) - 1; + if (__bt_cmp(t, key, &e) == 0) { + F_SET(c, CURS_BEFORE); + goto dup1; + } + mpool_put(t->bt_mp, pg, 0); + } + /* Check next key if at the end of the page. */ + if (index == NEXTINDEX(h) - 1 && h->nextpg != P_INVALID) { + if ((pg = mpool_get(t->bt_mp, h->nextpg, 0)) == NULL) + return (RET_ERROR); + e.page = pg; + e.index = 0; + if (__bt_cmp(t, key, &e) == 0) { + F_SET(c, CURS_AFTER); +dup1: mpool_put(t->bt_mp, pg, 0); +dup2: c->pg.pgno = e.page->pgno; + c->pg.index = e.index; + return (RET_SUCCESS); + } + mpool_put(t->bt_mp, pg, 0); + } + } + e.page = h; + e.index = index; + if (curcopy || (status = + __bt_ret(t, &e, &c->key, &c->key, NULL, NULL, 1)) == RET_SUCCESS) { + F_SET(c, CURS_ACQUIRE); + return (RET_SUCCESS); + } + return (status); +} + +/* + * __bt_relink -- + * Link around a deleted page. + * + * Parameters: + * t: tree + * h: page to be deleted + */ +static int +__bt_relink(t, h) + BTREE *t; + PAGE *h; +{ + PAGE *pg; + + if (h->nextpg != P_INVALID) { + if ((pg = mpool_get(t->bt_mp, h->nextpg, 0)) == NULL) + return (RET_ERROR); + pg->prevpg = h->prevpg; + mpool_put(t->bt_mp, pg, MPOOL_DIRTY); + } + if (h->prevpg != P_INVALID) { + if ((pg = mpool_get(t->bt_mp, h->prevpg, 0)) == NULL) + return (RET_ERROR); + pg->nextpg = h->nextpg; + mpool_put(t->bt_mp, pg, MPOOL_DIRTY); + } + return (0); +} diff --git a/lib/libc/db/btree/bt_get.c b/lib/libc/db/btree/bt_get.c new file mode 100644 index 0000000..0d91ae4 --- /dev/null +++ b/lib/libc/db/btree/bt_get.c @@ -0,0 +1,107 @@ +/*- + * Copyright (c) 1990, 1993, 1994 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * Mike Olson. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)bt_get.c 8.6 (Berkeley) 7/20/94"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/db/btree/bt_get.c,v 1.2 2002/03/22 21:52:01 obrien Exp $"); + +#include + +#include +#include +#include + +#include +#include "btree.h" + +/* + * __BT_GET -- Get a record from the btree. + * + * Parameters: + * dbp: pointer to access method + * key: key to find + * data: data to return + * flag: currently unused + * + * Returns: + * RET_ERROR, RET_SUCCESS and RET_SPECIAL if the key not found. + */ +int +__bt_get(dbp, key, data, flags) + const DB *dbp; + const DBT *key; + DBT *data; + u_int flags; +{ + BTREE *t; + EPG *e; + int exact, status; + + t = dbp->internal; + + /* Toss any page pinned across calls. */ + if (t->bt_pinned != NULL) { + mpool_put(t->bt_mp, t->bt_pinned, 0); + t->bt_pinned = NULL; + } + + /* Get currently doesn't take any flags. */ + if (flags) { + errno = EINVAL; + return (RET_ERROR); + } + + if ((e = __bt_search(t, key, &exact)) == NULL) + return (RET_ERROR); + if (!exact) { + mpool_put(t->bt_mp, e->page, 0); + return (RET_SPECIAL); + } + + status = __bt_ret(t, e, NULL, NULL, data, &t->bt_rdata, 0); + + /* + * If the user is doing concurrent access, we copied the + * key/data, toss the page. + */ + if (F_ISSET(t, B_DB_LOCK)) + mpool_put(t->bt_mp, e->page, 0); + else + t->bt_pinned = e->page; + return (status); +} diff --git a/lib/libc/db/btree/bt_open.c b/lib/libc/db/btree/bt_open.c new file mode 100644 index 0000000..385be9e --- /dev/null +++ b/lib/libc/db/btree/bt_open.c @@ -0,0 +1,449 @@ +/*- + * Copyright (c) 1990, 1993, 1994 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * Mike Olson. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)bt_open.c 8.10 (Berkeley) 8/17/94"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/db/btree/bt_open.c,v 1.11 2002/03/22 21:52:01 obrien Exp $"); + +/* + * Implementation of btree access method for 4.4BSD. + * + * The design here was originally based on that of the btree access method + * used in the Postgres database system at UC Berkeley. This implementation + * is wholly independent of the Postgres code. + */ + +#include "namespace.h" +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include "un-namespace.h" + +#include +#include "btree.h" + +#ifdef DEBUG +#undef MINPSIZE +#define MINPSIZE 128 +#endif + +static int byteorder(void); +static int nroot(BTREE *); +static int tmp(void); + +/* + * __BT_OPEN -- Open a btree. + * + * Creates and fills a DB struct, and calls the routine that actually + * opens the btree. + * + * Parameters: + * fname: filename (NULL for in-memory trees) + * flags: open flag bits + * mode: open permission bits + * b: BTREEINFO pointer + * + * Returns: + * NULL on failure, pointer to DB on success. + * + */ +DB * +__bt_open(fname, flags, mode, openinfo, dflags) + const char *fname; + int flags, mode, dflags; + const BTREEINFO *openinfo; +{ + struct stat sb; + BTMETA m; + BTREE *t; + BTREEINFO b; + DB *dbp; + pgno_t ncache; + ssize_t nr; + int machine_lorder; + + t = NULL; + + /* + * Intention is to make sure all of the user's selections are okay + * here and then use them without checking. Can't be complete, since + * we don't know the right page size, lorder or flags until the backing + * file is opened. Also, the file's page size can cause the cachesize + * to change. + */ + machine_lorder = byteorder(); + if (openinfo) { + b = *openinfo; + + /* Flags: R_DUP. */ + if (b.flags & ~(R_DUP)) + goto einval; + + /* + * Page size must be indx_t aligned and >= MINPSIZE. Default + * page size is set farther on, based on the underlying file + * transfer size. + */ + if (b.psize && + (b.psize < MINPSIZE || b.psize > MAX_PAGE_OFFSET + 1 || + b.psize & (sizeof(indx_t) - 1) )) + goto einval; + + /* Minimum number of keys per page; absolute minimum is 2. */ + if (b.minkeypage) { + if (b.minkeypage < 2) + goto einval; + } else + b.minkeypage = DEFMINKEYPAGE; + + /* If no comparison, use default comparison and prefix. */ + if (b.compare == NULL) { + b.compare = __bt_defcmp; + if (b.prefix == NULL) + b.prefix = __bt_defpfx; + } + + if (b.lorder == 0) + b.lorder = machine_lorder; + } else { + b.compare = __bt_defcmp; + b.cachesize = 0; + b.flags = 0; + b.lorder = machine_lorder; + b.minkeypage = DEFMINKEYPAGE; + b.prefix = __bt_defpfx; + b.psize = 0; + } + + /* Check for the ubiquitous PDP-11. */ + if (b.lorder != BIG_ENDIAN && b.lorder != LITTLE_ENDIAN) + goto einval; + + /* Allocate and initialize DB and BTREE structures. */ + if ((t = (BTREE *)malloc(sizeof(BTREE))) == NULL) + goto err; + memset(t, 0, sizeof(BTREE)); + t->bt_fd = -1; /* Don't close unopened fd on error. */ + t->bt_lorder = b.lorder; + t->bt_order = NOT; + t->bt_cmp = b.compare; + t->bt_pfx = b.prefix; + t->bt_rfd = -1; + + if ((t->bt_dbp = dbp = (DB *)malloc(sizeof(DB))) == NULL) + goto err; + memset(t->bt_dbp, 0, sizeof(DB)); + if (t->bt_lorder != machine_lorder) + F_SET(t, B_NEEDSWAP); + + dbp->type = DB_BTREE; + dbp->internal = t; + dbp->close = __bt_close; + dbp->del = __bt_delete; + dbp->fd = __bt_fd; + dbp->get = __bt_get; + dbp->put = __bt_put; + dbp->seq = __bt_seq; + dbp->sync = __bt_sync; + + /* + * If no file name was supplied, this is an in-memory btree and we + * open a backing temporary file. Otherwise, it's a disk-based tree. + */ + if (fname) { + switch (flags & O_ACCMODE) { + case O_RDONLY: + F_SET(t, B_RDONLY); + break; + case O_RDWR: + break; + case O_WRONLY: + default: + goto einval; + } + + if ((t->bt_fd = _open(fname, flags, mode)) < 0) + goto err; + + } else { + if ((flags & O_ACCMODE) != O_RDWR) + goto einval; + if ((t->bt_fd = tmp()) == -1) + goto err; + F_SET(t, B_INMEM); + } + + if (_fcntl(t->bt_fd, F_SETFD, 1) == -1) + goto err; + + if (_fstat(t->bt_fd, &sb)) + goto err; + if (sb.st_size) { + if ((nr = _read(t->bt_fd, &m, sizeof(BTMETA))) < 0) + goto err; + if (nr != sizeof(BTMETA)) + goto eftype; + + /* + * Read in the meta-data. This can change the notion of what + * the lorder, page size and flags are, and, when the page size + * changes, the cachesize value can change too. If the user + * specified the wrong byte order for an existing database, we + * don't bother to return an error, we just clear the NEEDSWAP + * bit. + */ + if (m.magic == BTREEMAGIC) + F_CLR(t, B_NEEDSWAP); + else { + F_SET(t, B_NEEDSWAP); + M_32_SWAP(m.magic); + M_32_SWAP(m.version); + M_32_SWAP(m.psize); + M_32_SWAP(m.free); + M_32_SWAP(m.nrecs); + M_32_SWAP(m.flags); + } + if (m.magic != BTREEMAGIC || m.version != BTREEVERSION) + goto eftype; + if (m.psize < MINPSIZE || m.psize > MAX_PAGE_OFFSET + 1 || + m.psize & (sizeof(indx_t) - 1) ) + goto eftype; + if (m.flags & ~SAVEMETA) + goto eftype; + b.psize = m.psize; + F_SET(t, m.flags); + t->bt_free = m.free; + t->bt_nrecs = m.nrecs; + } else { + /* + * Set the page size to the best value for I/O to this file. + * Don't overflow the page offset type. + */ + if (b.psize == 0) { + b.psize = sb.st_blksize; + if (b.psize < MINPSIZE) + b.psize = MINPSIZE; + if (b.psize > MAX_PAGE_OFFSET + 1) + b.psize = MAX_PAGE_OFFSET + 1; + } + + /* Set flag if duplicates permitted. */ + if (!(b.flags & R_DUP)) + F_SET(t, B_NODUPS); + + t->bt_free = P_INVALID; + t->bt_nrecs = 0; + F_SET(t, B_METADIRTY); + } + + t->bt_psize = b.psize; + + /* Set the cache size; must be a multiple of the page size. */ + if (b.cachesize && b.cachesize & (b.psize - 1) ) + b.cachesize += (~b.cachesize & (b.psize - 1) ) + 1; + if (b.cachesize < b.psize * MINCACHE) + b.cachesize = b.psize * MINCACHE; + + /* Calculate number of pages to cache. */ + ncache = (b.cachesize + t->bt_psize - 1) / t->bt_psize; + + /* + * The btree data structure requires that at least two keys can fit on + * a page, but other than that there's no fixed requirement. The user + * specified a minimum number per page, and we translated that into the + * number of bytes a key/data pair can use before being placed on an + * overflow page. This calculation includes the page header, the size + * of the index referencing the leaf item and the size of the leaf item + * structure. Also, don't let the user specify a minkeypage such that + * a key/data pair won't fit even if both key and data are on overflow + * pages. + */ + t->bt_ovflsize = (t->bt_psize - BTDATAOFF) / b.minkeypage - + (sizeof(indx_t) + NBLEAFDBT(0, 0)); + if (t->bt_ovflsize < NBLEAFDBT(NOVFLSIZE, NOVFLSIZE) + sizeof(indx_t)) + t->bt_ovflsize = + NBLEAFDBT(NOVFLSIZE, NOVFLSIZE) + sizeof(indx_t); + + /* Initialize the buffer pool. */ + if ((t->bt_mp = + mpool_open(NULL, t->bt_fd, t->bt_psize, ncache)) == NULL) + goto err; + if (!F_ISSET(t, B_INMEM)) + mpool_filter(t->bt_mp, __bt_pgin, __bt_pgout, t); + + /* Create a root page if new tree. */ + if (nroot(t) == RET_ERROR) + goto err; + + /* Global flags. */ + if (dflags & DB_LOCK) + F_SET(t, B_DB_LOCK); + if (dflags & DB_SHMEM) + F_SET(t, B_DB_SHMEM); + if (dflags & DB_TXN) + F_SET(t, B_DB_TXN); + + return (dbp); + +einval: errno = EINVAL; + goto err; + +eftype: errno = EFTYPE; + goto err; + +err: if (t) { + if (t->bt_dbp) + free(t->bt_dbp); + if (t->bt_fd != -1) + (void)_close(t->bt_fd); + free(t); + } + return (NULL); +} + +/* + * NROOT -- Create the root of a new tree. + * + * Parameters: + * t: tree + * + * Returns: + * RET_ERROR, RET_SUCCESS + */ +static int +nroot(t) + BTREE *t; +{ + PAGE *meta, *root; + pgno_t npg; + + if ((meta = mpool_get(t->bt_mp, 0, 0)) != NULL) { + mpool_put(t->bt_mp, meta, 0); + return (RET_SUCCESS); + } + if (errno != EINVAL) /* It's OK to not exist. */ + return (RET_ERROR); + errno = 0; + + if ((meta = mpool_new(t->bt_mp, &npg)) == NULL) + return (RET_ERROR); + + if ((root = mpool_new(t->bt_mp, &npg)) == NULL) + return (RET_ERROR); + + if (npg != P_ROOT) + return (RET_ERROR); + root->pgno = npg; + root->prevpg = root->nextpg = P_INVALID; + root->lower = BTDATAOFF; + root->upper = t->bt_psize; + root->flags = P_BLEAF; + memset(meta, 0, t->bt_psize); + mpool_put(t->bt_mp, meta, MPOOL_DIRTY); + mpool_put(t->bt_mp, root, MPOOL_DIRTY); + return (RET_SUCCESS); +} + +static int +tmp() +{ + sigset_t set, oset; + int fd; + char *envtmp = NULL; + char path[MAXPATHLEN]; + + if (issetugid() == 0) + envtmp = getenv("TMPDIR"); + (void)snprintf(path, + sizeof(path), "%s/bt.XXXXXXXXXX", envtmp ? envtmp : "/tmp"); + + (void)sigfillset(&set); + (void)_sigprocmask(SIG_BLOCK, &set, &oset); + if ((fd = mkstemp(path)) != -1) + (void)unlink(path); + (void)_sigprocmask(SIG_SETMASK, &oset, NULL); + return(fd); +} + +static int +byteorder() +{ + uint32_t x; + u_char *p; + + x = 0x01020304; + p = (u_char *)&x; + switch (*p) { + case 1: + return (BIG_ENDIAN); + case 4: + return (LITTLE_ENDIAN); + default: + return (0); + } +} + +int +__bt_fd(dbp) + const DB *dbp; +{ + BTREE *t; + + t = dbp->internal; + + /* Toss any page pinned across calls. */ + if (t->bt_pinned != NULL) { + mpool_put(t->bt_mp, t->bt_pinned, 0); + t->bt_pinned = NULL; + } + + /* In-memory database can't have a file descriptor. */ + if (F_ISSET(t, B_INMEM)) { + errno = ENOENT; + return (-1); + } + return (t->bt_fd); +} diff --git a/lib/libc/db/btree/bt_overflow.c b/lib/libc/db/btree/bt_overflow.c new file mode 100644 index 0000000..71abaa2 --- /dev/null +++ b/lib/libc/db/btree/bt_overflow.c @@ -0,0 +1,230 @@ +/*- + * Copyright (c) 1990, 1993, 1994 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * Mike Olson. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)bt_overflow.c 8.5 (Berkeley) 7/16/94"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/db/btree/bt_overflow.c,v 1.3 2002/03/22 21:52:01 obrien Exp $"); + +#include + +#include +#include +#include + +#include +#include "btree.h" + +/* + * Big key/data code. + * + * Big key and data entries are stored on linked lists of pages. The initial + * reference is byte string stored with the key or data and is the page number + * and size. The actual record is stored in a chain of pages linked by the + * nextpg field of the PAGE header. + * + * The first page of the chain has a special property. If the record is used + * by an internal page, it cannot be deleted and the P_PRESERVE bit will be set + * in the header. + * + * XXX + * A single DBT is written to each chain, so a lot of space on the last page + * is wasted. This is a fairly major bug for some data sets. + */ + +/* + * __OVFL_GET -- Get an overflow key/data item. + * + * Parameters: + * t: tree + * p: pointer to { pgno_t, uint32_t } + * buf: storage address + * bufsz: storage size + * + * Returns: + * RET_ERROR, RET_SUCCESS + */ +int +__ovfl_get(t, p, ssz, buf, bufsz) + BTREE *t; + void *p; + size_t *ssz; + void **buf; + size_t *bufsz; +{ + PAGE *h; + pgno_t pg; + size_t nb, plen; + uint32_t sz; + + memmove(&pg, p, sizeof(pgno_t)); + memmove(&sz, (char *)p + sizeof(pgno_t), sizeof(uint32_t)); + *ssz = sz; + +#ifdef DEBUG + if (pg == P_INVALID || sz == 0) + abort(); +#endif + /* Make the buffer bigger as necessary. */ + if (*bufsz < sz) { + *buf = (char *)(*buf == NULL ? malloc(sz) : reallocf(*buf, sz)); + if (*buf == NULL) + return (RET_ERROR); + *bufsz = sz; + } + + /* + * Step through the linked list of pages, copying the data on each one + * into the buffer. Never copy more than the data's length. + */ + plen = t->bt_psize - BTDATAOFF; + for (p = *buf;; p = (char *)p + nb, pg = h->nextpg) { + if ((h = mpool_get(t->bt_mp, pg, 0)) == NULL) + return (RET_ERROR); + + nb = MIN(sz, plen); + memmove(p, (char *)h + BTDATAOFF, nb); + mpool_put(t->bt_mp, h, 0); + + if ((sz -= nb) == 0) + break; + } + return (RET_SUCCESS); +} + +/* + * __OVFL_PUT -- Store an overflow key/data item. + * + * Parameters: + * t: tree + * data: DBT to store + * pgno: storage page number + * + * Returns: + * RET_ERROR, RET_SUCCESS + */ +int +__ovfl_put(t, dbt, pg) + BTREE *t; + const DBT *dbt; + pgno_t *pg; +{ + PAGE *h, *last; + void *p; + pgno_t npg; + size_t nb, plen; + uint32_t sz; + + /* + * Allocate pages and copy the key/data record into them. Store the + * number of the first page in the chain. + */ + plen = t->bt_psize - BTDATAOFF; + for (last = NULL, p = dbt->data, sz = dbt->size;; + p = (char *)p + plen, last = h) { + if ((h = __bt_new(t, &npg)) == NULL) + return (RET_ERROR); + + h->pgno = npg; + h->nextpg = h->prevpg = P_INVALID; + h->flags = P_OVERFLOW; + h->lower = h->upper = 0; + + nb = MIN(sz, plen); + memmove((char *)h + BTDATAOFF, p, nb); + + if (last) { + last->nextpg = h->pgno; + mpool_put(t->bt_mp, last, MPOOL_DIRTY); + } else + *pg = h->pgno; + + if ((sz -= nb) == 0) { + mpool_put(t->bt_mp, h, MPOOL_DIRTY); + break; + } + } + return (RET_SUCCESS); +} + +/* + * __OVFL_DELETE -- Delete an overflow chain. + * + * Parameters: + * t: tree + * p: pointer to { pgno_t, uint32_t } + * + * Returns: + * RET_ERROR, RET_SUCCESS + */ +int +__ovfl_delete(t, p) + BTREE *t; + void *p; +{ + PAGE *h; + pgno_t pg; + size_t plen; + uint32_t sz; + + memmove(&pg, p, sizeof(pgno_t)); + memmove(&sz, (char *)p + sizeof(pgno_t), sizeof(uint32_t)); + +#ifdef DEBUG + if (pg == P_INVALID || sz == 0) + abort(); +#endif + if ((h = mpool_get(t->bt_mp, pg, 0)) == NULL) + return (RET_ERROR); + + /* Don't delete chains used by internal pages. */ + if (h->flags & P_PRESERVE) { + mpool_put(t->bt_mp, h, 0); + return (RET_SUCCESS); + } + + /* Step through the chain, calling the free routine for each page. */ + for (plen = t->bt_psize - BTDATAOFF;; sz -= plen) { + pg = h->nextpg; + __bt_free(t, h); + if (sz <= plen) + break; + if ((h = mpool_get(t->bt_mp, pg, 0)) == NULL) + return (RET_ERROR); + } + return (RET_SUCCESS); +} diff --git a/lib/libc/db/btree/bt_page.c b/lib/libc/db/btree/bt_page.c new file mode 100644 index 0000000..3392709 --- /dev/null +++ b/lib/libc/db/btree/bt_page.c @@ -0,0 +1,102 @@ +/*- + * Copyright (c) 1990, 1993, 1994 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)bt_page.c 8.3 (Berkeley) 7/14/94"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/db/btree/bt_page.c,v 1.3 2002/03/22 21:52:01 obrien Exp $"); + +#include + +#include + +#include +#include "btree.h" + +/* + * __bt_free -- + * Put a page on the freelist. + * + * Parameters: + * t: tree + * h: page to free + * + * Returns: + * RET_ERROR, RET_SUCCESS + * + * Side-effect: + * mpool_put's the page. + */ +int +__bt_free(t, h) + BTREE *t; + PAGE *h; +{ + /* Insert the page at the head of the free list. */ + h->prevpg = P_INVALID; + h->nextpg = t->bt_free; + t->bt_free = h->pgno; + F_SET(t, B_METADIRTY); + + /* Make sure the page gets written back. */ + return (mpool_put(t->bt_mp, h, MPOOL_DIRTY)); +} + +/* + * __bt_new -- + * Get a new page, preferably from the freelist. + * + * Parameters: + * t: tree + * npg: storage for page number. + * + * Returns: + * Pointer to a page, NULL on error. + */ +PAGE * +__bt_new(t, npg) + BTREE *t; + pgno_t *npg; +{ + PAGE *h; + + if (t->bt_free != P_INVALID && + (h = mpool_get(t->bt_mp, t->bt_free, 0)) != NULL) { + *npg = t->bt_free; + t->bt_free = h->nextpg; + F_SET(t, B_METADIRTY); + return (h); + } + return (mpool_new(t->bt_mp, npg)); +} diff --git a/lib/libc/db/btree/bt_put.c b/lib/libc/db/btree/bt_put.c new file mode 100644 index 0000000..a2b0b16 --- /dev/null +++ b/lib/libc/db/btree/bt_put.c @@ -0,0 +1,325 @@ +/*- + * Copyright (c) 1990, 1993, 1994 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * Mike Olson. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)bt_put.c 8.8 (Berkeley) 7/26/94"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/db/btree/bt_put.c,v 1.4 2003/05/30 11:05:08 tmm Exp $"); + +#include + +#include +#include +#include +#include + +#include +#include "btree.h" + +static EPG *bt_fast(BTREE *, const DBT *, const DBT *, int *); + +/* + * __BT_PUT -- Add a btree item to the tree. + * + * Parameters: + * dbp: pointer to access method + * key: key + * data: data + * flag: R_NOOVERWRITE + * + * Returns: + * RET_ERROR, RET_SUCCESS and RET_SPECIAL if the key is already in the + * tree and R_NOOVERWRITE specified. + */ +int +__bt_put(dbp, key, data, flags) + const DB *dbp; + DBT *key; + const DBT *data; + u_int flags; +{ + BTREE *t; + DBT tkey, tdata; + EPG *e; + PAGE *h; + indx_t index, nxtindex; + pgno_t pg; + uint32_t nbytes, tmp; + int dflags, exact, status; + char *dest, db[NOVFLSIZE], kb[NOVFLSIZE]; + + t = dbp->internal; + + /* Toss any page pinned across calls. */ + if (t->bt_pinned != NULL) { + mpool_put(t->bt_mp, t->bt_pinned, 0); + t->bt_pinned = NULL; + } + + /* Check for change to a read-only tree. */ + if (F_ISSET(t, B_RDONLY)) { + errno = EPERM; + return (RET_ERROR); + } + + switch (flags) { + case 0: + case R_NOOVERWRITE: + break; + case R_CURSOR: + /* + * If flags is R_CURSOR, put the cursor. Must already + * have started a scan and not have already deleted it. + */ + if (F_ISSET(&t->bt_cursor, CURS_INIT) && + !F_ISSET(&t->bt_cursor, + CURS_ACQUIRE | CURS_AFTER | CURS_BEFORE)) + break; + /* FALLTHROUGH */ + default: + errno = EINVAL; + return (RET_ERROR); + } + + /* + * If the key/data pair won't fit on a page, store it on overflow + * pages. Only put the key on the overflow page if the pair are + * still too big after moving the data to an overflow page. + * + * XXX + * If the insert fails later on, the overflow pages aren't recovered. + */ + dflags = 0; + if (key->size + data->size > t->bt_ovflsize) { + if (key->size > t->bt_ovflsize) { +storekey: if (__ovfl_put(t, key, &pg) == RET_ERROR) + return (RET_ERROR); + tkey.data = kb; + tkey.size = NOVFLSIZE; + memmove(kb, &pg, sizeof(pgno_t)); + tmp = key->size; + memmove(kb + sizeof(pgno_t), + &tmp, sizeof(uint32_t)); + dflags |= P_BIGKEY; + key = &tkey; + } + if (key->size + data->size > t->bt_ovflsize) { + if (__ovfl_put(t, data, &pg) == RET_ERROR) + return (RET_ERROR); + tdata.data = db; + tdata.size = NOVFLSIZE; + memmove(db, &pg, sizeof(pgno_t)); + tmp = data->size; + memmove(db + sizeof(pgno_t), + &tmp, sizeof(uint32_t)); + dflags |= P_BIGDATA; + data = &tdata; + } + if (key->size + data->size > t->bt_ovflsize) + goto storekey; + } + + /* Replace the cursor. */ + if (flags == R_CURSOR) { + if ((h = mpool_get(t->bt_mp, t->bt_cursor.pg.pgno, 0)) == NULL) + return (RET_ERROR); + index = t->bt_cursor.pg.index; + goto delete; + } + + /* + * Find the key to delete, or, the location at which to insert. + * Bt_fast and __bt_search both pin the returned page. + */ + if (t->bt_order == NOT || (e = bt_fast(t, key, data, &exact)) == NULL) + if ((e = __bt_search(t, key, &exact)) == NULL) + return (RET_ERROR); + h = e->page; + index = e->index; + + /* + * Add the key/data pair to the tree. If an identical key is already + * in the tree, and R_NOOVERWRITE is set, an error is returned. If + * R_NOOVERWRITE is not set, the key is either added (if duplicates are + * permitted) or an error is returned. + */ + switch (flags) { + case R_NOOVERWRITE: + if (!exact) + break; + mpool_put(t->bt_mp, h, 0); + return (RET_SPECIAL); + default: + if (!exact || !F_ISSET(t, B_NODUPS)) + break; + /* + * !!! + * Note, the delete may empty the page, so we need to put a + * new entry into the page immediately. + */ +delete: if (__bt_dleaf(t, key, h, index) == RET_ERROR) { + mpool_put(t->bt_mp, h, 0); + return (RET_ERROR); + } + break; + } + + /* + * If not enough room, or the user has put a ceiling on the number of + * keys permitted in the page, split the page. The split code will + * insert the key and data and unpin the current page. If inserting + * into the offset array, shift the pointers up. + */ + nbytes = NBLEAFDBT(key->size, data->size); + if (h->upper - h->lower < nbytes + sizeof(indx_t)) { + if ((status = __bt_split(t, h, key, + data, dflags, nbytes, index)) != RET_SUCCESS) + return (status); + goto success; + } + + if (index < (nxtindex = NEXTINDEX(h))) + memmove(h->linp + index + 1, h->linp + index, + (nxtindex - index) * sizeof(indx_t)); + h->lower += sizeof(indx_t); + + h->linp[index] = h->upper -= nbytes; + dest = (char *)h + h->upper; + WR_BLEAF(dest, key, data, dflags); + + /* If the cursor is on this page, adjust it as necessary. */ + if (F_ISSET(&t->bt_cursor, CURS_INIT) && + !F_ISSET(&t->bt_cursor, CURS_ACQUIRE) && + t->bt_cursor.pg.pgno == h->pgno && t->bt_cursor.pg.index >= index) + ++t->bt_cursor.pg.index; + + if (t->bt_order == NOT) { + if (h->nextpg == P_INVALID) { + if (index == NEXTINDEX(h) - 1) { + t->bt_order = FORWARD; + t->bt_last.index = index; + t->bt_last.pgno = h->pgno; + } + } else if (h->prevpg == P_INVALID) { + if (index == 0) { + t->bt_order = BACK; + t->bt_last.index = 0; + t->bt_last.pgno = h->pgno; + } + } + } + + mpool_put(t->bt_mp, h, MPOOL_DIRTY); + +success: + if (flags == R_SETCURSOR) + __bt_setcur(t, e->page->pgno, e->index); + + F_SET(t, B_MODIFIED); + return (RET_SUCCESS); +} + +#ifdef STATISTICS +u_long bt_cache_hit, bt_cache_miss; +#endif + +/* + * BT_FAST -- Do a quick check for sorted data. + * + * Parameters: + * t: tree + * key: key to insert + * + * Returns: + * EPG for new record or NULL if not found. + */ +static EPG * +bt_fast(t, key, data, exactp) + BTREE *t; + const DBT *key, *data; + int *exactp; +{ + PAGE *h; + uint32_t nbytes; + int cmp; + + if ((h = mpool_get(t->bt_mp, t->bt_last.pgno, 0)) == NULL) { + t->bt_order = NOT; + return (NULL); + } + t->bt_cur.page = h; + t->bt_cur.index = t->bt_last.index; + + /* + * If won't fit in this page or have too many keys in this page, + * have to search to get split stack. + */ + nbytes = NBLEAFDBT(key->size, data->size); + if (h->upper - h->lower < nbytes + sizeof(indx_t)) + goto miss; + + if (t->bt_order == FORWARD) { + if (t->bt_cur.page->nextpg != P_INVALID) + goto miss; + if (t->bt_cur.index != NEXTINDEX(h) - 1) + goto miss; + if ((cmp = __bt_cmp(t, key, &t->bt_cur)) < 0) + goto miss; + t->bt_last.index = cmp ? ++t->bt_cur.index : t->bt_cur.index; + } else { + if (t->bt_cur.page->prevpg != P_INVALID) + goto miss; + if (t->bt_cur.index != 0) + goto miss; + if ((cmp = __bt_cmp(t, key, &t->bt_cur)) > 0) + goto miss; + t->bt_last.index = 0; + } + *exactp = cmp == 0; +#ifdef STATISTICS + ++bt_cache_hit; +#endif + return (&t->bt_cur); + +miss: +#ifdef STATISTICS + ++bt_cache_miss; +#endif + t->bt_order = NOT; + mpool_put(t->bt_mp, h, 0); + return (NULL); +} diff --git a/lib/libc/db/btree/bt_search.c b/lib/libc/db/btree/bt_search.c new file mode 100644 index 0000000..cee177d --- /dev/null +++ b/lib/libc/db/btree/bt_search.c @@ -0,0 +1,215 @@ +/*- + * Copyright (c) 1990, 1993, 1994 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * Mike Olson. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)bt_search.c 8.8 (Berkeley) 7/31/94"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/db/btree/bt_search.c,v 1.2 2002/03/21 22:46:25 obrien Exp $"); + +#include + +#include + +#include +#include "btree.h" + +static int __bt_snext(BTREE *, PAGE *, const DBT *, int *); +static int __bt_sprev(BTREE *, PAGE *, const DBT *, int *); + +/* + * __bt_search -- + * Search a btree for a key. + * + * Parameters: + * t: tree to search + * key: key to find + * exactp: pointer to exact match flag + * + * Returns: + * The EPG for matching record, if any, or the EPG for the location + * of the key, if it were inserted into the tree, is entered into + * the bt_cur field of the tree. A pointer to the field is returned. + */ +EPG * +__bt_search(t, key, exactp) + BTREE *t; + const DBT *key; + int *exactp; +{ + PAGE *h; + indx_t base, index, lim; + pgno_t pg; + int cmp; + + BT_CLR(t); + for (pg = P_ROOT;;) { + if ((h = mpool_get(t->bt_mp, pg, 0)) == NULL) + return (NULL); + + /* Do a binary search on the current page. */ + t->bt_cur.page = h; + for (base = 0, lim = NEXTINDEX(h); lim; lim >>= 1) { + t->bt_cur.index = index = base + (lim >> 1); + if ((cmp = __bt_cmp(t, key, &t->bt_cur)) == 0) { + if (h->flags & P_BLEAF) { + *exactp = 1; + return (&t->bt_cur); + } + goto next; + } + if (cmp > 0) { + base = index + 1; + --lim; + } + } + + /* + * If it's a leaf page, we're almost done. If no duplicates + * are allowed, or we have an exact match, we're done. Else, + * it's possible that there were matching keys on this page, + * which later deleted, and we're on a page with no matches + * while there are matches on other pages. If at the start or + * end of a page, check the adjacent page. + */ + if (h->flags & P_BLEAF) { + if (!F_ISSET(t, B_NODUPS)) { + if (base == 0 && + h->prevpg != P_INVALID && + __bt_sprev(t, h, key, exactp)) + return (&t->bt_cur); + if (base == NEXTINDEX(h) && + h->nextpg != P_INVALID && + __bt_snext(t, h, key, exactp)) + return (&t->bt_cur); + } + *exactp = 0; + t->bt_cur.index = base; + return (&t->bt_cur); + } + + /* + * No match found. Base is the smallest index greater than + * key and may be zero or a last + 1 index. If it's non-zero, + * decrement by one, and record the internal page which should + * be a parent page for the key. If a split later occurs, the + * inserted page will be to the right of the saved page. + */ + index = base ? base - 1 : base; + +next: BT_PUSH(t, h->pgno, index); + pg = GETBINTERNAL(h, index)->pgno; + mpool_put(t->bt_mp, h, 0); + } +} + +/* + * __bt_snext -- + * Check for an exact match after the key. + * + * Parameters: + * t: tree + * h: current page + * key: key + * exactp: pointer to exact match flag + * + * Returns: + * If an exact match found. + */ +static int +__bt_snext(t, h, key, exactp) + BTREE *t; + PAGE *h; + const DBT *key; + int *exactp; +{ + EPG e; + + /* + * Get the next page. The key is either an exact + * match, or not as good as the one we already have. + */ + if ((e.page = mpool_get(t->bt_mp, h->nextpg, 0)) == NULL) + return (0); + e.index = 0; + if (__bt_cmp(t, key, &e) == 0) { + mpool_put(t->bt_mp, h, 0); + t->bt_cur = e; + *exactp = 1; + return (1); + } + mpool_put(t->bt_mp, e.page, 0); + return (0); +} + +/* + * __bt_sprev -- + * Check for an exact match before the key. + * + * Parameters: + * t: tree + * h: current page + * key: key + * exactp: pointer to exact match flag + * + * Returns: + * If an exact match found. + */ +static int +__bt_sprev(t, h, key, exactp) + BTREE *t; + PAGE *h; + const DBT *key; + int *exactp; +{ + EPG e; + + /* + * Get the previous page. The key is either an exact + * match, or not as good as the one we already have. + */ + if ((e.page = mpool_get(t->bt_mp, h->prevpg, 0)) == NULL) + return (0); + e.index = NEXTINDEX(e.page) - 1; + if (__bt_cmp(t, key, &e) == 0) { + mpool_put(t->bt_mp, h, 0); + t->bt_cur = e; + *exactp = 1; + return (1); + } + mpool_put(t->bt_mp, e.page, 0); + return (0); +} diff --git a/lib/libc/db/btree/bt_seq.c b/lib/libc/db/btree/bt_seq.c new file mode 100644 index 0000000..662e195 --- /dev/null +++ b/lib/libc/db/btree/bt_seq.c @@ -0,0 +1,462 @@ +/*- + * Copyright (c) 1990, 1993, 1994 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * Mike Olson. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)bt_seq.c 8.7 (Berkeley) 7/20/94"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/db/btree/bt_seq.c,v 1.3 2002/03/21 22:46:25 obrien Exp $"); + +#include + +#include +#include +#include +#include + +#include +#include "btree.h" + +static int __bt_first(BTREE *, const DBT *, EPG *, int *); +static int __bt_seqadv(BTREE *, EPG *, int); +static int __bt_seqset(BTREE *, EPG *, DBT *, int); + +/* + * Sequential scan support. + * + * The tree can be scanned sequentially, starting from either end of the + * tree or from any specific key. A scan request before any scanning is + * done is initialized as starting from the least node. + */ + +/* + * __bt_seq -- + * Btree sequential scan interface. + * + * Parameters: + * dbp: pointer to access method + * key: key for positioning and return value + * data: data return value + * flags: R_CURSOR, R_FIRST, R_LAST, R_NEXT, R_PREV. + * + * Returns: + * RET_ERROR, RET_SUCCESS or RET_SPECIAL if there's no next key. + */ +int +__bt_seq(dbp, key, data, flags) + const DB *dbp; + DBT *key, *data; + u_int flags; +{ + BTREE *t; + EPG e; + int status; + + t = dbp->internal; + + /* Toss any page pinned across calls. */ + if (t->bt_pinned != NULL) { + mpool_put(t->bt_mp, t->bt_pinned, 0); + t->bt_pinned = NULL; + } + + /* + * If scan unitialized as yet, or starting at a specific record, set + * the scan to a specific key. Both __bt_seqset and __bt_seqadv pin + * the page the cursor references if they're successful. + */ + switch (flags) { + case R_NEXT: + case R_PREV: + if (F_ISSET(&t->bt_cursor, CURS_INIT)) { + status = __bt_seqadv(t, &e, flags); + break; + } + /* FALLTHROUGH */ + case R_FIRST: + case R_LAST: + case R_CURSOR: + status = __bt_seqset(t, &e, key, flags); + break; + default: + errno = EINVAL; + return (RET_ERROR); + } + + if (status == RET_SUCCESS) { + __bt_setcur(t, e.page->pgno, e.index); + + status = + __bt_ret(t, &e, key, &t->bt_rkey, data, &t->bt_rdata, 0); + + /* + * If the user is doing concurrent access, we copied the + * key/data, toss the page. + */ + if (F_ISSET(t, B_DB_LOCK)) + mpool_put(t->bt_mp, e.page, 0); + else + t->bt_pinned = e.page; + } + return (status); +} + +/* + * __bt_seqset -- + * Set the sequential scan to a specific key. + * + * Parameters: + * t: tree + * ep: storage for returned key + * key: key for initial scan position + * flags: R_CURSOR, R_FIRST, R_LAST, R_NEXT, R_PREV + * + * Side effects: + * Pins the page the cursor references. + * + * Returns: + * RET_ERROR, RET_SUCCESS or RET_SPECIAL if there's no next key. + */ +static int +__bt_seqset(t, ep, key, flags) + BTREE *t; + EPG *ep; + DBT *key; + int flags; +{ + PAGE *h; + pgno_t pg; + int exact; + + /* + * Find the first, last or specific key in the tree and point the + * cursor at it. The cursor may not be moved until a new key has + * been found. + */ + switch (flags) { + case R_CURSOR: /* Keyed scan. */ + /* + * Find the first instance of the key or the smallest key + * which is greater than or equal to the specified key. + */ + if (key->data == NULL || key->size == 0) { + errno = EINVAL; + return (RET_ERROR); + } + return (__bt_first(t, key, ep, &exact)); + case R_FIRST: /* First record. */ + case R_NEXT: + /* Walk down the left-hand side of the tree. */ + for (pg = P_ROOT;;) { + if ((h = mpool_get(t->bt_mp, pg, 0)) == NULL) + return (RET_ERROR); + + /* Check for an empty tree. */ + if (NEXTINDEX(h) == 0) { + mpool_put(t->bt_mp, h, 0); + return (RET_SPECIAL); + } + + if (h->flags & (P_BLEAF | P_RLEAF)) + break; + pg = GETBINTERNAL(h, 0)->pgno; + mpool_put(t->bt_mp, h, 0); + } + ep->page = h; + ep->index = 0; + break; + case R_LAST: /* Last record. */ + case R_PREV: + /* Walk down the right-hand side of the tree. */ + for (pg = P_ROOT;;) { + if ((h = mpool_get(t->bt_mp, pg, 0)) == NULL) + return (RET_ERROR); + + /* Check for an empty tree. */ + if (NEXTINDEX(h) == 0) { + mpool_put(t->bt_mp, h, 0); + return (RET_SPECIAL); + } + + if (h->flags & (P_BLEAF | P_RLEAF)) + break; + pg = GETBINTERNAL(h, NEXTINDEX(h) - 1)->pgno; + mpool_put(t->bt_mp, h, 0); + } + + ep->page = h; + ep->index = NEXTINDEX(h) - 1; + break; + } + return (RET_SUCCESS); +} + +/* + * __bt_seqadvance -- + * Advance the sequential scan. + * + * Parameters: + * t: tree + * flags: R_NEXT, R_PREV + * + * Side effects: + * Pins the page the new key/data record is on. + * + * Returns: + * RET_ERROR, RET_SUCCESS or RET_SPECIAL if there's no next key. + */ +static int +__bt_seqadv(t, ep, flags) + BTREE *t; + EPG *ep; + int flags; +{ + CURSOR *c; + PAGE *h; + indx_t index; + pgno_t pg; + int exact; + + /* + * There are a couple of states that we can be in. The cursor has + * been initialized by the time we get here, but that's all we know. + */ + c = &t->bt_cursor; + + /* + * The cursor was deleted where there weren't any duplicate records, + * so the key was saved. Find out where that key would go in the + * current tree. It doesn't matter if the returned key is an exact + * match or not -- if it's an exact match, the record was added after + * the delete so we can just return it. If not, as long as there's + * a record there, return it. + */ + if (F_ISSET(c, CURS_ACQUIRE)) + return (__bt_first(t, &c->key, ep, &exact)); + + /* Get the page referenced by the cursor. */ + if ((h = mpool_get(t->bt_mp, c->pg.pgno, 0)) == NULL) + return (RET_ERROR); + + /* + * Find the next/previous record in the tree and point the cursor at + * it. The cursor may not be moved until a new key has been found. + */ + switch (flags) { + case R_NEXT: /* Next record. */ + /* + * The cursor was deleted in duplicate records, and moved + * forward to a record that has yet to be returned. Clear + * that flag, and return the record. + */ + if (F_ISSET(c, CURS_AFTER)) + goto usecurrent; + index = c->pg.index; + if (++index == NEXTINDEX(h)) { + pg = h->nextpg; + mpool_put(t->bt_mp, h, 0); + if (pg == P_INVALID) + return (RET_SPECIAL); + if ((h = mpool_get(t->bt_mp, pg, 0)) == NULL) + return (RET_ERROR); + index = 0; + } + break; + case R_PREV: /* Previous record. */ + /* + * The cursor was deleted in duplicate records, and moved + * backward to a record that has yet to be returned. Clear + * that flag, and return the record. + */ + if (F_ISSET(c, CURS_BEFORE)) { +usecurrent: F_CLR(c, CURS_AFTER | CURS_BEFORE); + ep->page = h; + ep->index = c->pg.index; + return (RET_SUCCESS); + } + index = c->pg.index; + if (index == 0) { + pg = h->prevpg; + mpool_put(t->bt_mp, h, 0); + if (pg == P_INVALID) + return (RET_SPECIAL); + if ((h = mpool_get(t->bt_mp, pg, 0)) == NULL) + return (RET_ERROR); + index = NEXTINDEX(h) - 1; + } else + --index; + break; + } + + ep->page = h; + ep->index = index; + return (RET_SUCCESS); +} + +/* + * __bt_first -- + * Find the first entry. + * + * Parameters: + * t: the tree + * key: the key + * erval: return EPG + * exactp: pointer to exact match flag + * + * Returns: + * The first entry in the tree greater than or equal to key, + * or RET_SPECIAL if no such key exists. + */ +static int +__bt_first(t, key, erval, exactp) + BTREE *t; + const DBT *key; + EPG *erval; + int *exactp; +{ + PAGE *h; + EPG *ep, save; + pgno_t pg; + + /* + * Find any matching record; __bt_search pins the page. + * + * If it's an exact match and duplicates are possible, walk backwards + * in the tree until we find the first one. Otherwise, make sure it's + * a valid key (__bt_search may return an index just past the end of a + * page) and return it. + */ + if ((ep = __bt_search(t, key, exactp)) == NULL) + return (0); + if (*exactp) { + if (F_ISSET(t, B_NODUPS)) { + *erval = *ep; + return (RET_SUCCESS); + } + + /* + * Walk backwards, as long as the entry matches and there are + * keys left in the tree. Save a copy of each match in case + * we go too far. + */ + save = *ep; + h = ep->page; + do { + if (save.page->pgno != ep->page->pgno) { + mpool_put(t->bt_mp, save.page, 0); + save = *ep; + } else + save.index = ep->index; + + /* + * Don't unpin the page the last (or original) match + * was on, but make sure it's unpinned if an error + * occurs. + */ + if (ep->index == 0) { + if (h->prevpg == P_INVALID) + break; + if (h->pgno != save.page->pgno) + mpool_put(t->bt_mp, h, 0); + if ((h = mpool_get(t->bt_mp, + h->prevpg, 0)) == NULL) { + if (h->pgno == save.page->pgno) + mpool_put(t->bt_mp, + save.page, 0); + return (RET_ERROR); + } + ep->page = h; + ep->index = NEXTINDEX(h); + } + --ep->index; + } while (__bt_cmp(t, key, ep) == 0); + + /* + * Reach here with the last page that was looked at pinned, + * which may or may not be the same as the last (or original) + * match page. If it's not useful, release it. + */ + if (h->pgno != save.page->pgno) + mpool_put(t->bt_mp, h, 0); + + *erval = save; + return (RET_SUCCESS); + } + + /* If at the end of a page, find the next entry. */ + if (ep->index == NEXTINDEX(ep->page)) { + h = ep->page; + pg = h->nextpg; + mpool_put(t->bt_mp, h, 0); + if (pg == P_INVALID) + return (RET_SPECIAL); + if ((h = mpool_get(t->bt_mp, pg, 0)) == NULL) + return (RET_ERROR); + ep->index = 0; + ep->page = h; + } + *erval = *ep; + return (RET_SUCCESS); +} + +/* + * __bt_setcur -- + * Set the cursor to an entry in the tree. + * + * Parameters: + * t: the tree + * pgno: page number + * index: page index + */ +void +__bt_setcur(t, pgno, index) + BTREE *t; + pgno_t pgno; + u_int index; +{ + /* Lose any already deleted key. */ + if (t->bt_cursor.key.data != NULL) { + free(t->bt_cursor.key.data); + t->bt_cursor.key.size = 0; + t->bt_cursor.key.data = NULL; + } + F_CLR(&t->bt_cursor, CURS_ACQUIRE | CURS_AFTER | CURS_BEFORE); + + /* Update the cursor. */ + t->bt_cursor.pg.pgno = pgno; + t->bt_cursor.pg.index = index; + F_SET(&t->bt_cursor, CURS_INIT); +} diff --git a/lib/libc/db/btree/bt_split.c b/lib/libc/db/btree/bt_split.c new file mode 100644 index 0000000..6c767ee --- /dev/null +++ b/lib/libc/db/btree/bt_split.c @@ -0,0 +1,827 @@ +/*- + * Copyright (c) 1990, 1993, 1994 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * Mike Olson. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)bt_split.c 8.9 (Berkeley) 7/26/94"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/db/btree/bt_split.c,v 1.7 2004/09/13 22:07:24 kuriyama Exp $"); + +#include + +#include +#include +#include +#include + +#include +#include "btree.h" + +static int bt_broot(BTREE *, PAGE *, PAGE *, PAGE *); +static PAGE *bt_page (BTREE *, PAGE *, PAGE **, PAGE **, indx_t *, size_t); +static int bt_preserve(BTREE *, pgno_t); +static PAGE *bt_psplit (BTREE *, PAGE *, PAGE *, PAGE *, indx_t *, size_t); +static PAGE *bt_root (BTREE *, PAGE *, PAGE **, PAGE **, indx_t *, size_t); +static int bt_rroot(BTREE *, PAGE *, PAGE *, PAGE *); +static recno_t rec_total(PAGE *); + +#ifdef STATISTICS +u_long bt_rootsplit, bt_split, bt_sortsplit, bt_pfxsaved; +#endif + +/* + * __BT_SPLIT -- Split the tree. + * + * Parameters: + * t: tree + * sp: page to split + * key: key to insert + * data: data to insert + * flags: BIGKEY/BIGDATA flags + * ilen: insert length + * skip: index to leave open + * + * Returns: + * RET_ERROR, RET_SUCCESS + */ +int +__bt_split(t, sp, key, data, flags, ilen, argskip) + BTREE *t; + PAGE *sp; + const DBT *key, *data; + int flags; + size_t ilen; + uint32_t argskip; +{ + BINTERNAL *bi; + BLEAF *bl, *tbl; + DBT a, b; + EPGNO *parent; + PAGE *h, *l, *r, *lchild, *rchild; + indx_t nxtindex; + u_int16_t skip; + uint32_t n, nbytes, nksize; + int parentsplit; + char *dest; + + /* + * Split the page into two pages, l and r. The split routines return + * a pointer to the page into which the key should be inserted and with + * skip set to the offset which should be used. Additionally, l and r + * are pinned. + */ + skip = argskip; + h = sp->pgno == P_ROOT ? + bt_root(t, sp, &l, &r, &skip, ilen) : + bt_page(t, sp, &l, &r, &skip, ilen); + if (h == NULL) + return (RET_ERROR); + + /* + * Insert the new key/data pair into the leaf page. (Key inserts + * always cause a leaf page to split first.) + */ + h->linp[skip] = h->upper -= ilen; + dest = (char *)h + h->upper; + if (F_ISSET(t, R_RECNO)) + WR_RLEAF(dest, data, flags) + else + WR_BLEAF(dest, key, data, flags) + + /* If the root page was split, make it look right. */ + if (sp->pgno == P_ROOT && + (F_ISSET(t, R_RECNO) ? + bt_rroot(t, sp, l, r) : bt_broot(t, sp, l, r)) == RET_ERROR) + goto err2; + + /* + * Now we walk the parent page stack -- a LIFO stack of the pages that + * were traversed when we searched for the page that split. Each stack + * entry is a page number and a page index offset. The offset is for + * the page traversed on the search. We've just split a page, so we + * have to insert a new key into the parent page. + * + * If the insert into the parent page causes it to split, may have to + * continue splitting all the way up the tree. We stop if the root + * splits or the page inserted into didn't have to split to hold the + * new key. Some algorithms replace the key for the old page as well + * as the new page. We don't, as there's no reason to believe that the + * first key on the old page is any better than the key we have, and, + * in the case of a key being placed at index 0 causing the split, the + * key is unavailable. + * + * There are a maximum of 5 pages pinned at any time. We keep the left + * and right pages pinned while working on the parent. The 5 are the + * two children, left parent and right parent (when the parent splits) + * and the root page or the overflow key page when calling bt_preserve. + * This code must make sure that all pins are released other than the + * root page or overflow page which is unlocked elsewhere. + */ + while ((parent = BT_POP(t)) != NULL) { + lchild = l; + rchild = r; + + /* Get the parent page. */ + if ((h = mpool_get(t->bt_mp, parent->pgno, 0)) == NULL) + goto err2; + + /* + * The new key goes ONE AFTER the index, because the split + * was to the right. + */ + skip = parent->index + 1; + + /* + * Calculate the space needed on the parent page. + * + * Prefix trees: space hack when inserting into BINTERNAL + * pages. Retain only what's needed to distinguish between + * the new entry and the LAST entry on the page to its left. + * If the keys compare equal, retain the entire key. Note, + * we don't touch overflow keys, and the entire key must be + * retained for the next-to-left most key on the leftmost + * page of each level, or the search will fail. Applicable + * ONLY to internal pages that have leaf pages as children. + * Further reduction of the key between pairs of internal + * pages loses too much information. + */ + switch (rchild->flags & P_TYPE) { + case P_BINTERNAL: + bi = GETBINTERNAL(rchild, 0); + nbytes = NBINTERNAL(bi->ksize); + break; + case P_BLEAF: + bl = GETBLEAF(rchild, 0); + nbytes = NBINTERNAL(bl->ksize); + if (t->bt_pfx && !(bl->flags & P_BIGKEY) && + (h->prevpg != P_INVALID || skip > 1)) { + tbl = GETBLEAF(lchild, NEXTINDEX(lchild) - 1); + a.size = tbl->ksize; + a.data = tbl->bytes; + b.size = bl->ksize; + b.data = bl->bytes; + nksize = t->bt_pfx(&a, &b); + n = NBINTERNAL(nksize); + if (n < nbytes) { +#ifdef STATISTICS + bt_pfxsaved += nbytes - n; +#endif + nbytes = n; + } else + nksize = 0; + } else + nksize = 0; + break; + case P_RINTERNAL: + case P_RLEAF: + nbytes = NRINTERNAL; + break; + default: + abort(); + } + + /* Split the parent page if necessary or shift the indices. */ + if (h->upper - h->lower < nbytes + sizeof(indx_t)) { + sp = h; + h = h->pgno == P_ROOT ? + bt_root(t, h, &l, &r, &skip, nbytes) : + bt_page(t, h, &l, &r, &skip, nbytes); + if (h == NULL) + goto err1; + parentsplit = 1; + } else { + if (skip < (nxtindex = NEXTINDEX(h))) + memmove(h->linp + skip + 1, h->linp + skip, + (nxtindex - skip) * sizeof(indx_t)); + h->lower += sizeof(indx_t); + parentsplit = 0; + } + + /* Insert the key into the parent page. */ + switch (rchild->flags & P_TYPE) { + case P_BINTERNAL: + h->linp[skip] = h->upper -= nbytes; + dest = (char *)h + h->linp[skip]; + memmove(dest, bi, nbytes); + ((BINTERNAL *)dest)->pgno = rchild->pgno; + break; + case P_BLEAF: + h->linp[skip] = h->upper -= nbytes; + dest = (char *)h + h->linp[skip]; + WR_BINTERNAL(dest, nksize ? nksize : bl->ksize, + rchild->pgno, bl->flags & P_BIGKEY); + memmove(dest, bl->bytes, nksize ? nksize : bl->ksize); + if (bl->flags & P_BIGKEY && + bt_preserve(t, *(pgno_t *)bl->bytes) == RET_ERROR) + goto err1; + break; + case P_RINTERNAL: + /* + * Update the left page count. If split + * added at index 0, fix the correct page. + */ + if (skip > 0) + dest = (char *)h + h->linp[skip - 1]; + else + dest = (char *)l + l->linp[NEXTINDEX(l) - 1]; + ((RINTERNAL *)dest)->nrecs = rec_total(lchild); + ((RINTERNAL *)dest)->pgno = lchild->pgno; + + /* Update the right page count. */ + h->linp[skip] = h->upper -= nbytes; + dest = (char *)h + h->linp[skip]; + ((RINTERNAL *)dest)->nrecs = rec_total(rchild); + ((RINTERNAL *)dest)->pgno = rchild->pgno; + break; + case P_RLEAF: + /* + * Update the left page count. If split + * added at index 0, fix the correct page. + */ + if (skip > 0) + dest = (char *)h + h->linp[skip - 1]; + else + dest = (char *)l + l->linp[NEXTINDEX(l) - 1]; + ((RINTERNAL *)dest)->nrecs = NEXTINDEX(lchild); + ((RINTERNAL *)dest)->pgno = lchild->pgno; + + /* Update the right page count. */ + h->linp[skip] = h->upper -= nbytes; + dest = (char *)h + h->linp[skip]; + ((RINTERNAL *)dest)->nrecs = NEXTINDEX(rchild); + ((RINTERNAL *)dest)->pgno = rchild->pgno; + break; + default: + abort(); + } + + /* Unpin the held pages. */ + if (!parentsplit) { + mpool_put(t->bt_mp, h, MPOOL_DIRTY); + break; + } + + /* If the root page was split, make it look right. */ + if (sp->pgno == P_ROOT && + (F_ISSET(t, R_RECNO) ? + bt_rroot(t, sp, l, r) : bt_broot(t, sp, l, r)) == RET_ERROR) + goto err1; + + mpool_put(t->bt_mp, lchild, MPOOL_DIRTY); + mpool_put(t->bt_mp, rchild, MPOOL_DIRTY); + } + + /* Unpin the held pages. */ + mpool_put(t->bt_mp, l, MPOOL_DIRTY); + mpool_put(t->bt_mp, r, MPOOL_DIRTY); + + /* Clear any pages left on the stack. */ + return (RET_SUCCESS); + + /* + * If something fails in the above loop we were already walking back + * up the tree and the tree is now inconsistent. Nothing much we can + * do about it but release any memory we're holding. + */ +err1: mpool_put(t->bt_mp, lchild, MPOOL_DIRTY); + mpool_put(t->bt_mp, rchild, MPOOL_DIRTY); + +err2: mpool_put(t->bt_mp, l, 0); + mpool_put(t->bt_mp, r, 0); + __dbpanic(t->bt_dbp); + return (RET_ERROR); +} + +/* + * BT_PAGE -- Split a non-root page of a btree. + * + * Parameters: + * t: tree + * h: root page + * lp: pointer to left page pointer + * rp: pointer to right page pointer + * skip: pointer to index to leave open + * ilen: insert length + * + * Returns: + * Pointer to page in which to insert or NULL on error. + */ +static PAGE * +bt_page(t, h, lp, rp, skip, ilen) + BTREE *t; + PAGE *h, **lp, **rp; + indx_t *skip; + size_t ilen; +{ + PAGE *l, *r, *tp; + pgno_t npg; + +#ifdef STATISTICS + ++bt_split; +#endif + /* Put the new right page for the split into place. */ + if ((r = __bt_new(t, &npg)) == NULL) + return (NULL); + r->pgno = npg; + r->lower = BTDATAOFF; + r->upper = t->bt_psize; + r->nextpg = h->nextpg; + r->prevpg = h->pgno; + r->flags = h->flags & P_TYPE; + + /* + * If we're splitting the last page on a level because we're appending + * a key to it (skip is NEXTINDEX()), it's likely that the data is + * sorted. Adding an empty page on the side of the level is less work + * and can push the fill factor much higher than normal. If we're + * wrong it's no big deal, we'll just do the split the right way next + * time. It may look like it's equally easy to do a similar hack for + * reverse sorted data, that is, split the tree left, but it's not. + * Don't even try. + */ + if (h->nextpg == P_INVALID && *skip == NEXTINDEX(h)) { +#ifdef STATISTICS + ++bt_sortsplit; +#endif + h->nextpg = r->pgno; + r->lower = BTDATAOFF + sizeof(indx_t); + *skip = 0; + *lp = h; + *rp = r; + return (r); + } + + /* Put the new left page for the split into place. */ + if ((l = (PAGE *)malloc(t->bt_psize)) == NULL) { + mpool_put(t->bt_mp, r, 0); + return (NULL); + } +#ifdef PURIFY + memset(l, 0xff, t->bt_psize); +#endif + l->pgno = h->pgno; + l->nextpg = r->pgno; + l->prevpg = h->prevpg; + l->lower = BTDATAOFF; + l->upper = t->bt_psize; + l->flags = h->flags & P_TYPE; + + /* Fix up the previous pointer of the page after the split page. */ + if (h->nextpg != P_INVALID) { + if ((tp = mpool_get(t->bt_mp, h->nextpg, 0)) == NULL) { + free(l); + /* XXX mpool_free(t->bt_mp, r->pgno); */ + return (NULL); + } + tp->prevpg = r->pgno; + mpool_put(t->bt_mp, tp, MPOOL_DIRTY); + } + + /* + * Split right. The key/data pairs aren't sorted in the btree page so + * it's simpler to copy the data from the split page onto two new pages + * instead of copying half the data to the right page and compacting + * the left page in place. Since the left page can't change, we have + * to swap the original and the allocated left page after the split. + */ + tp = bt_psplit(t, h, l, r, skip, ilen); + + /* Move the new left page onto the old left page. */ + memmove(h, l, t->bt_psize); + if (tp == l) + tp = h; + free(l); + + *lp = h; + *rp = r; + return (tp); +} + +/* + * BT_ROOT -- Split the root page of a btree. + * + * Parameters: + * t: tree + * h: root page + * lp: pointer to left page pointer + * rp: pointer to right page pointer + * skip: pointer to index to leave open + * ilen: insert length + * + * Returns: + * Pointer to page in which to insert or NULL on error. + */ +static PAGE * +bt_root(t, h, lp, rp, skip, ilen) + BTREE *t; + PAGE *h, **lp, **rp; + indx_t *skip; + size_t ilen; +{ + PAGE *l, *r, *tp; + pgno_t lnpg, rnpg; + +#ifdef STATISTICS + ++bt_split; + ++bt_rootsplit; +#endif + /* Put the new left and right pages for the split into place. */ + if ((l = __bt_new(t, &lnpg)) == NULL || + (r = __bt_new(t, &rnpg)) == NULL) + return (NULL); + l->pgno = lnpg; + r->pgno = rnpg; + l->nextpg = r->pgno; + r->prevpg = l->pgno; + l->prevpg = r->nextpg = P_INVALID; + l->lower = r->lower = BTDATAOFF; + l->upper = r->upper = t->bt_psize; + l->flags = r->flags = h->flags & P_TYPE; + + /* Split the root page. */ + tp = bt_psplit(t, h, l, r, skip, ilen); + + *lp = l; + *rp = r; + return (tp); +} + +/* + * BT_RROOT -- Fix up the recno root page after it has been split. + * + * Parameters: + * t: tree + * h: root page + * l: left page + * r: right page + * + * Returns: + * RET_ERROR, RET_SUCCESS + */ +static int +bt_rroot(t, h, l, r) + BTREE *t; + PAGE *h, *l, *r; +{ + char *dest; + + /* Insert the left and right keys, set the header information. */ + h->linp[0] = h->upper = t->bt_psize - NRINTERNAL; + dest = (char *)h + h->upper; + WR_RINTERNAL(dest, + l->flags & P_RLEAF ? NEXTINDEX(l) : rec_total(l), l->pgno); + + h->linp[1] = h->upper -= NRINTERNAL; + dest = (char *)h + h->upper; + WR_RINTERNAL(dest, + r->flags & P_RLEAF ? NEXTINDEX(r) : rec_total(r), r->pgno); + + h->lower = BTDATAOFF + 2 * sizeof(indx_t); + + /* Unpin the root page, set to recno internal page. */ + h->flags &= ~P_TYPE; + h->flags |= P_RINTERNAL; + mpool_put(t->bt_mp, h, MPOOL_DIRTY); + + return (RET_SUCCESS); +} + +/* + * BT_BROOT -- Fix up the btree root page after it has been split. + * + * Parameters: + * t: tree + * h: root page + * l: left page + * r: right page + * + * Returns: + * RET_ERROR, RET_SUCCESS + */ +static int +bt_broot(t, h, l, r) + BTREE *t; + PAGE *h, *l, *r; +{ + BINTERNAL *bi; + BLEAF *bl; + uint32_t nbytes; + char *dest; + + /* + * If the root page was a leaf page, change it into an internal page. + * We copy the key we split on (but not the key's data, in the case of + * a leaf page) to the new root page. + * + * The btree comparison code guarantees that the left-most key on any + * level of the tree is never used, so it doesn't need to be filled in. + */ + nbytes = NBINTERNAL(0); + h->linp[0] = h->upper = t->bt_psize - nbytes; + dest = (char *)h + h->upper; + WR_BINTERNAL(dest, 0, l->pgno, 0); + + switch (h->flags & P_TYPE) { + case P_BLEAF: + bl = GETBLEAF(r, 0); + nbytes = NBINTERNAL(bl->ksize); + h->linp[1] = h->upper -= nbytes; + dest = (char *)h + h->upper; + WR_BINTERNAL(dest, bl->ksize, r->pgno, 0); + memmove(dest, bl->bytes, bl->ksize); + + /* + * If the key is on an overflow page, mark the overflow chain + * so it isn't deleted when the leaf copy of the key is deleted. + */ + if (bl->flags & P_BIGKEY && + bt_preserve(t, *(pgno_t *)bl->bytes) == RET_ERROR) + return (RET_ERROR); + break; + case P_BINTERNAL: + bi = GETBINTERNAL(r, 0); + nbytes = NBINTERNAL(bi->ksize); + h->linp[1] = h->upper -= nbytes; + dest = (char *)h + h->upper; + memmove(dest, bi, nbytes); + ((BINTERNAL *)dest)->pgno = r->pgno; + break; + default: + abort(); + } + + /* There are two keys on the page. */ + h->lower = BTDATAOFF + 2 * sizeof(indx_t); + + /* Unpin the root page, set to btree internal page. */ + h->flags &= ~P_TYPE; + h->flags |= P_BINTERNAL; + mpool_put(t->bt_mp, h, MPOOL_DIRTY); + + return (RET_SUCCESS); +} + +/* + * BT_PSPLIT -- Do the real work of splitting the page. + * + * Parameters: + * t: tree + * h: page to be split + * l: page to put lower half of data + * r: page to put upper half of data + * pskip: pointer to index to leave open + * ilen: insert length + * + * Returns: + * Pointer to page in which to insert. + */ +static PAGE * +bt_psplit(t, h, l, r, pskip, ilen) + BTREE *t; + PAGE *h, *l, *r; + indx_t *pskip; + size_t ilen; +{ + BINTERNAL *bi; + BLEAF *bl; + CURSOR *c; + RLEAF *rl; + PAGE *rval; + void *src; + indx_t full, half, nxt, off, skip, top, used; + uint32_t nbytes; + int bigkeycnt, isbigkey; + + /* + * Split the data to the left and right pages. Leave the skip index + * open. Additionally, make some effort not to split on an overflow + * key. This makes internal page processing faster and can save + * space as overflow keys used by internal pages are never deleted. + */ + bigkeycnt = 0; + skip = *pskip; + full = t->bt_psize - BTDATAOFF; + half = full / 2; + used = 0; + for (nxt = off = 0, top = NEXTINDEX(h); nxt < top; ++off) { + if (skip == off) { + nbytes = ilen; + isbigkey = 0; /* XXX: not really known. */ + } else + switch (h->flags & P_TYPE) { + case P_BINTERNAL: + src = bi = GETBINTERNAL(h, nxt); + nbytes = NBINTERNAL(bi->ksize); + isbigkey = bi->flags & P_BIGKEY; + break; + case P_BLEAF: + src = bl = GETBLEAF(h, nxt); + nbytes = NBLEAF(bl); + isbigkey = bl->flags & P_BIGKEY; + break; + case P_RINTERNAL: + src = GETRINTERNAL(h, nxt); + nbytes = NRINTERNAL; + isbigkey = 0; + break; + case P_RLEAF: + src = rl = GETRLEAF(h, nxt); + nbytes = NRLEAF(rl); + isbigkey = 0; + break; + default: + abort(); + } + + /* + * If the key/data pairs are substantial fractions of the max + * possible size for the page, it's possible to get situations + * where we decide to try and copy too much onto the left page. + * Make sure that doesn't happen. + */ + if ((skip <= off && used + nbytes + sizeof(indx_t) >= full) + || nxt == top - 1) { + --off; + break; + } + + /* Copy the key/data pair, if not the skipped index. */ + if (skip != off) { + ++nxt; + + l->linp[off] = l->upper -= nbytes; + memmove((char *)l + l->upper, src, nbytes); + } + + used += nbytes + sizeof(indx_t); + if (used >= half) { + if (!isbigkey || bigkeycnt == 3) + break; + else + ++bigkeycnt; + } + } + + /* + * Off is the last offset that's valid for the left page. + * Nxt is the first offset to be placed on the right page. + */ + l->lower += (off + 1) * sizeof(indx_t); + + /* + * If splitting the page that the cursor was on, the cursor has to be + * adjusted to point to the same record as before the split. If the + * cursor is at or past the skipped slot, the cursor is incremented by + * one. If the cursor is on the right page, it is decremented by the + * number of records split to the left page. + */ + c = &t->bt_cursor; + if (F_ISSET(c, CURS_INIT) && c->pg.pgno == h->pgno) { + if (c->pg.index >= skip) + ++c->pg.index; + if (c->pg.index < nxt) /* Left page. */ + c->pg.pgno = l->pgno; + else { /* Right page. */ + c->pg.pgno = r->pgno; + c->pg.index -= nxt; + } + } + + /* + * If the skipped index was on the left page, just return that page. + * Otherwise, adjust the skip index to reflect the new position on + * the right page. + */ + if (skip <= off) { + skip = MAX_PAGE_OFFSET; + rval = l; + } else { + rval = r; + *pskip -= nxt; + } + + for (off = 0; nxt < top; ++off) { + if (skip == nxt) { + ++off; + skip = MAX_PAGE_OFFSET; + } + switch (h->flags & P_TYPE) { + case P_BINTERNAL: + src = bi = GETBINTERNAL(h, nxt); + nbytes = NBINTERNAL(bi->ksize); + break; + case P_BLEAF: + src = bl = GETBLEAF(h, nxt); + nbytes = NBLEAF(bl); + break; + case P_RINTERNAL: + src = GETRINTERNAL(h, nxt); + nbytes = NRINTERNAL; + break; + case P_RLEAF: + src = rl = GETRLEAF(h, nxt); + nbytes = NRLEAF(rl); + break; + default: + abort(); + } + ++nxt; + r->linp[off] = r->upper -= nbytes; + memmove((char *)r + r->upper, src, nbytes); + } + r->lower += off * sizeof(indx_t); + + /* If the key is being appended to the page, adjust the index. */ + if (skip == top) + r->lower += sizeof(indx_t); + + return (rval); +} + +/* + * BT_PRESERVE -- Mark a chain of pages as used by an internal node. + * + * Chains of indirect blocks pointed to by leaf nodes get reclaimed when the + * record that references them gets deleted. Chains pointed to by internal + * pages never get deleted. This routine marks a chain as pointed to by an + * internal page. + * + * Parameters: + * t: tree + * pg: page number of first page in the chain. + * + * Returns: + * RET_SUCCESS, RET_ERROR. + */ +static int +bt_preserve(t, pg) + BTREE *t; + pgno_t pg; +{ + PAGE *h; + + if ((h = mpool_get(t->bt_mp, pg, 0)) == NULL) + return (RET_ERROR); + h->flags |= P_PRESERVE; + mpool_put(t->bt_mp, h, MPOOL_DIRTY); + return (RET_SUCCESS); +} + +/* + * REC_TOTAL -- Return the number of recno entries below a page. + * + * Parameters: + * h: page + * + * Returns: + * The number of recno entries below a page. + * + * XXX + * These values could be set by the bt_psplit routine. The problem is that the + * entry has to be popped off of the stack etc. or the values have to be passed + * all the way back to bt_split/bt_rroot and it's not very clean. + */ +static recno_t +rec_total(h) + PAGE *h; +{ + recno_t recs; + indx_t nxt, top; + + for (recs = 0, nxt = 0, top = NEXTINDEX(h); nxt < top; ++nxt) + recs += GETRINTERNAL(h, nxt)->nrecs; + return (recs); +} diff --git a/lib/libc/db/btree/bt_utils.c b/lib/libc/db/btree/bt_utils.c new file mode 100644 index 0000000..e9acfb7 --- /dev/null +++ b/lib/libc/db/btree/bt_utils.c @@ -0,0 +1,262 @@ +/*- + * Copyright (c) 1990, 1993, 1994 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * Mike Olson. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)bt_utils.c 8.8 (Berkeley) 7/20/94"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/db/btree/bt_utils.c,v 1.3 2003/01/01 18:48:42 schweikh Exp $"); + +#include + +#include +#include +#include + +#include +#include "btree.h" + +/* + * __bt_ret -- + * Build return key/data pair. + * + * Parameters: + * t: tree + * e: key/data pair to be returned + * key: user's key structure (NULL if not to be filled in) + * rkey: memory area to hold key + * data: user's data structure (NULL if not to be filled in) + * rdata: memory area to hold data + * copy: always copy the key/data item + * + * Returns: + * RET_SUCCESS, RET_ERROR. + */ +int +__bt_ret(t, e, key, rkey, data, rdata, copy) + BTREE *t; + EPG *e; + DBT *key, *rkey, *data, *rdata; + int copy; +{ + BLEAF *bl; + void *p; + + bl = GETBLEAF(e->page, e->index); + + /* + * We must copy big keys/data to make them contigous. Otherwise, + * leave the page pinned and don't copy unless the user specified + * concurrent access. + */ + if (key == NULL) + goto dataonly; + + if (bl->flags & P_BIGKEY) { + if (__ovfl_get(t, bl->bytes, + &key->size, &rkey->data, &rkey->size)) + return (RET_ERROR); + key->data = rkey->data; + } else if (copy || F_ISSET(t, B_DB_LOCK)) { + if (bl->ksize > rkey->size) { + p = (void *)(rkey->data == NULL ? + malloc(bl->ksize) : realloc(rkey->data, bl->ksize)); + if (p == NULL) + return (RET_ERROR); + rkey->data = p; + rkey->size = bl->ksize; + } + memmove(rkey->data, bl->bytes, bl->ksize); + key->size = bl->ksize; + key->data = rkey->data; + } else { + key->size = bl->ksize; + key->data = bl->bytes; + } + +dataonly: + if (data == NULL) + return (RET_SUCCESS); + + if (bl->flags & P_BIGDATA) { + if (__ovfl_get(t, bl->bytes + bl->ksize, + &data->size, &rdata->data, &rdata->size)) + return (RET_ERROR); + data->data = rdata->data; + } else if (copy || F_ISSET(t, B_DB_LOCK)) { + /* Use +1 in case the first record retrieved is 0 length. */ + if (bl->dsize + 1 > rdata->size) { + p = (void *)(rdata->data == NULL ? + malloc(bl->dsize + 1) : + realloc(rdata->data, bl->dsize + 1)); + if (p == NULL) + return (RET_ERROR); + rdata->data = p; + rdata->size = bl->dsize + 1; + } + memmove(rdata->data, bl->bytes + bl->ksize, bl->dsize); + data->size = bl->dsize; + data->data = rdata->data; + } else { + data->size = bl->dsize; + data->data = bl->bytes + bl->ksize; + } + + return (RET_SUCCESS); +} + +/* + * __BT_CMP -- Compare a key to a given record. + * + * Parameters: + * t: tree + * k1: DBT pointer of first arg to comparison + * e: pointer to EPG for comparison + * + * Returns: + * < 0 if k1 is < record + * = 0 if k1 is = record + * > 0 if k1 is > record + */ +int +__bt_cmp(t, k1, e) + BTREE *t; + const DBT *k1; + EPG *e; +{ + BINTERNAL *bi; + BLEAF *bl; + DBT k2; + PAGE *h; + void *bigkey; + + /* + * The left-most key on internal pages, at any level of the tree, is + * guaranteed by the following code to be less than any user key. + * This saves us from having to update the leftmost key on an internal + * page when the user inserts a new key in the tree smaller than + * anything we've yet seen. + */ + h = e->page; + if (e->index == 0 && h->prevpg == P_INVALID && !(h->flags & P_BLEAF)) + return (1); + + bigkey = NULL; + if (h->flags & P_BLEAF) { + bl = GETBLEAF(h, e->index); + if (bl->flags & P_BIGKEY) + bigkey = bl->bytes; + else { + k2.data = bl->bytes; + k2.size = bl->ksize; + } + } else { + bi = GETBINTERNAL(h, e->index); + if (bi->flags & P_BIGKEY) + bigkey = bi->bytes; + else { + k2.data = bi->bytes; + k2.size = bi->ksize; + } + } + + if (bigkey) { + if (__ovfl_get(t, bigkey, + &k2.size, &t->bt_rdata.data, &t->bt_rdata.size)) + return (RET_ERROR); + k2.data = t->bt_rdata.data; + } + return ((*t->bt_cmp)(k1, &k2)); +} + +/* + * __BT_DEFCMP -- Default comparison routine. + * + * Parameters: + * a: DBT #1 + * b: DBT #2 + * + * Returns: + * < 0 if a is < b + * = 0 if a is = b + * > 0 if a is > b + */ +int +__bt_defcmp(a, b) + const DBT *a, *b; +{ + size_t len; + u_char *p1, *p2; + + /* + * XXX + * If a size_t doesn't fit in an int, this routine can lose. + * What we need is an integral type which is guaranteed to be + * larger than a size_t, and there is no such thing. + */ + len = MIN(a->size, b->size); + for (p1 = a->data, p2 = b->data; len--; ++p1, ++p2) + if (*p1 != *p2) + return ((int)*p1 - (int)*p2); + return ((int)a->size - (int)b->size); +} + +/* + * __BT_DEFPFX -- Default prefix routine. + * + * Parameters: + * a: DBT #1 + * b: DBT #2 + * + * Returns: + * Number of bytes needed to distinguish b from a. + */ +size_t +__bt_defpfx(a, b) + const DBT *a, *b; +{ + u_char *p1, *p2; + size_t cnt, len; + + cnt = 1; + len = MIN(a->size, b->size); + for (p1 = a->data, p2 = b->data; len--; ++p1, ++p2, ++cnt) + if (*p1 != *p2) + return (cnt); + + /* a->size must be <= b->size, or they wouldn't be in this order. */ + return (a->size < b->size ? a->size + 1 : a->size); +} diff --git a/lib/libc/db/btree/btree.h b/lib/libc/db/btree/btree.h new file mode 100644 index 0000000..1891842 --- /dev/null +++ b/lib/libc/db/btree/btree.h @@ -0,0 +1,384 @@ +/*- + * Copyright (c) 1991, 1993, 1994 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * Mike Olson. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * @(#)btree.h 8.11 (Berkeley) 8/17/94 + * $FreeBSD: src/lib/libc/db/btree/btree.h,v 1.3 2002/03/22 23:41:40 obrien Exp $ + */ + +/* Macros to set/clear/test flags. */ +#define F_SET(p, f) (p)->flags |= (f) +#define F_CLR(p, f) (p)->flags &= ~(f) +#define F_ISSET(p, f) ((p)->flags & (f)) + +#include + +#define DEFMINKEYPAGE (2) /* Minimum keys per page */ +#define MINCACHE (5) /* Minimum cached pages */ +#define MINPSIZE (512) /* Minimum page size */ + +/* + * Page 0 of a btree file contains a copy of the meta-data. This page is also + * used as an out-of-band page, i.e. page pointers that point to nowhere point + * to page 0. Page 1 is the root of the btree. + */ +#define P_INVALID 0 /* Invalid tree page number. */ +#define P_META 0 /* Tree metadata page number. */ +#define P_ROOT 1 /* Tree root page number. */ + +/* + * There are five page layouts in the btree: btree internal pages (BINTERNAL), + * btree leaf pages (BLEAF), recno internal pages (RINTERNAL), recno leaf pages + * (RLEAF) and overflow pages. All five page types have a page header (PAGE). + * This implementation requires that values within structures NOT be padded. + * (ANSI C permits random padding.) If your compiler pads randomly you'll have + * to do some work to get this package to run. + */ +typedef struct _page { + pgno_t pgno; /* this page's page number */ + pgno_t prevpg; /* left sibling */ + pgno_t nextpg; /* right sibling */ + +#define P_BINTERNAL 0x01 /* btree internal page */ +#define P_BLEAF 0x02 /* leaf page */ +#define P_OVERFLOW 0x04 /* overflow page */ +#define P_RINTERNAL 0x08 /* recno internal page */ +#define P_RLEAF 0x10 /* leaf page */ +#define P_TYPE 0x1f /* type mask */ +#define P_PRESERVE 0x20 /* never delete this chain of pages */ + uint32_t flags; + + indx_t lower; /* lower bound of free space on page */ + indx_t upper; /* upper bound of free space on page */ + indx_t linp[1]; /* indx_t-aligned VAR. LENGTH DATA */ +} PAGE; + +/* First and next index. */ +#define BTDATAOFF \ + (sizeof(pgno_t) + sizeof(pgno_t) + sizeof(pgno_t) + \ + sizeof(uint32_t) + sizeof(indx_t) + sizeof(indx_t)) +#define NEXTINDEX(p) (((p)->lower - BTDATAOFF) / sizeof(indx_t)) + +/* + * For pages other than overflow pages, there is an array of offsets into the + * rest of the page immediately following the page header. Each offset is to + * an item which is unique to the type of page. The h_lower offset is just + * past the last filled-in index. The h_upper offset is the first item on the + * page. Offsets are from the beginning of the page. + * + * If an item is too big to store on a single page, a flag is set and the item + * is a { page, size } pair such that the page is the first page of an overflow + * chain with size bytes of item. Overflow pages are simply bytes without any + * external structure. + * + * The page number and size fields in the items are pgno_t-aligned so they can + * be manipulated without copying. (This presumes that 32 bit items can be + * manipulated on this system.) + */ +#define LALIGN(n) (((n) + sizeof(pgno_t) - 1) & ~(sizeof(pgno_t) - 1)) +#define NOVFLSIZE (sizeof(pgno_t) + sizeof(uint32_t)) + +/* + * For the btree internal pages, the item is a key. BINTERNALs are {key, pgno} + * pairs, such that the key compares less than or equal to all of the records + * on that page. For a tree without duplicate keys, an internal page with two + * consecutive keys, a and b, will have all records greater than or equal to a + * and less than b stored on the page associated with a. Duplicate keys are + * somewhat special and can cause duplicate internal and leaf page records and + * some minor modifications of the above rule. + */ +typedef struct _binternal { + uint32_t ksize; /* key size */ + pgno_t pgno; /* page number stored on */ +#define P_BIGDATA 0x01 /* overflow data */ +#define P_BIGKEY 0x02 /* overflow key */ + u_char flags; + char bytes[1]; /* data */ +} BINTERNAL; + +/* Get the page's BINTERNAL structure at index indx. */ +#define GETBINTERNAL(pg, indx) \ + ((BINTERNAL *)((char *)(pg) + (pg)->linp[indx])) + +/* Get the number of bytes in the entry. */ +#define NBINTERNAL(len) \ + LALIGN(sizeof(uint32_t) + sizeof(pgno_t) + sizeof(u_char) + (len)) + +/* Copy a BINTERNAL entry to the page. */ +#define WR_BINTERNAL(p, size, pgno, flags) { \ + *(uint32_t *)p = size; \ + p += sizeof(uint32_t); \ + *(pgno_t *)p = pgno; \ + p += sizeof(pgno_t); \ + *(u_char *)p = flags; \ + p += sizeof(u_char); \ +} + +/* + * For the recno internal pages, the item is a page number with the number of + * keys found on that page and below. + */ +typedef struct _rinternal { + recno_t nrecs; /* number of records */ + pgno_t pgno; /* page number stored below */ +} RINTERNAL; + +/* Get the page's RINTERNAL structure at index indx. */ +#define GETRINTERNAL(pg, indx) \ + ((RINTERNAL *)((char *)(pg) + (pg)->linp[indx])) + +/* Get the number of bytes in the entry. */ +#define NRINTERNAL \ + LALIGN(sizeof(recno_t) + sizeof(pgno_t)) + +/* Copy a RINTERAL entry to the page. */ +#define WR_RINTERNAL(p, nrecs, pgno) { \ + *(recno_t *)p = nrecs; \ + p += sizeof(recno_t); \ + *(pgno_t *)p = pgno; \ +} + +/* For the btree leaf pages, the item is a key and data pair. */ +typedef struct _bleaf { + uint32_t ksize; /* size of key */ + uint32_t dsize; /* size of data */ + u_char flags; /* P_BIGDATA, P_BIGKEY */ + char bytes[1]; /* data */ +} BLEAF; + +/* Get the page's BLEAF structure at index indx. */ +#define GETBLEAF(pg, indx) \ + ((BLEAF *)((char *)(pg) + (pg)->linp[indx])) + +/* Get the number of bytes in the entry. */ +#define NBLEAF(p) NBLEAFDBT((p)->ksize, (p)->dsize) + +/* Get the number of bytes in the user's key/data pair. */ +#define NBLEAFDBT(ksize, dsize) \ + LALIGN(sizeof(uint32_t) + sizeof(uint32_t) + sizeof(u_char) + \ + (ksize) + (dsize)) + +/* Copy a BLEAF entry to the page. */ +#define WR_BLEAF(p, key, data, flags) { \ + *(uint32_t *)p = key->size; \ + p += sizeof(uint32_t); \ + *(uint32_t *)p = data->size; \ + p += sizeof(uint32_t); \ + *(u_char *)p = flags; \ + p += sizeof(u_char); \ + memmove(p, key->data, key->size); \ + p += key->size; \ + memmove(p, data->data, data->size); \ +} + +/* For the recno leaf pages, the item is a data entry. */ +typedef struct _rleaf { + uint32_t dsize; /* size of data */ + u_char flags; /* P_BIGDATA */ + char bytes[1]; +} RLEAF; + +/* Get the page's RLEAF structure at index indx. */ +#define GETRLEAF(pg, indx) \ + ((RLEAF *)((char *)(pg) + (pg)->linp[indx])) + +/* Get the number of bytes in the entry. */ +#define NRLEAF(p) NRLEAFDBT((p)->dsize) + +/* Get the number of bytes from the user's data. */ +#define NRLEAFDBT(dsize) \ + LALIGN(sizeof(uint32_t) + sizeof(u_char) + (dsize)) + +/* Copy a RLEAF entry to the page. */ +#define WR_RLEAF(p, data, flags) { \ + *(uint32_t *)p = data->size; \ + p += sizeof(uint32_t); \ + *(u_char *)p = flags; \ + p += sizeof(u_char); \ + memmove(p, data->data, data->size); \ +} + +/* + * A record in the tree is either a pointer to a page and an index in the page + * or a page number and an index. These structures are used as a cursor, stack + * entry and search returns as well as to pass records to other routines. + * + * One comment about searches. Internal page searches must find the largest + * record less than key in the tree so that descents work. Leaf page searches + * must find the smallest record greater than key so that the returned index + * is the record's correct position for insertion. + */ +typedef struct _epgno { + pgno_t pgno; /* the page number */ + indx_t index; /* the index on the page */ +} EPGNO; + +typedef struct _epg { + PAGE *page; /* the (pinned) page */ + indx_t index; /* the index on the page */ +} EPG; + +/* + * About cursors. The cursor (and the page that contained the key/data pair + * that it referenced) can be deleted, which makes things a bit tricky. If + * there are no duplicates of the cursor key in the tree (i.e. B_NODUPS is set + * or there simply aren't any duplicates of the key) we copy the key that it + * referenced when it's deleted, and reacquire a new cursor key if the cursor + * is used again. If there are duplicates keys, we move to the next/previous + * key, and set a flag so that we know what happened. NOTE: if duplicate (to + * the cursor) keys are added to the tree during this process, it is undefined + * if they will be returned or not in a cursor scan. + * + * The flags determine the possible states of the cursor: + * + * CURS_INIT The cursor references *something*. + * CURS_ACQUIRE The cursor was deleted, and a key has been saved so that + * we can reacquire the right position in the tree. + * CURS_AFTER, CURS_BEFORE + * The cursor was deleted, and now references a key/data pair + * that has not yet been returned, either before or after the + * deleted key/data pair. + * XXX + * This structure is broken out so that we can eventually offer multiple + * cursors as part of the DB interface. + */ +typedef struct _cursor { + EPGNO pg; /* B: Saved tree reference. */ + DBT key; /* B: Saved key, or key.data == NULL. */ + recno_t rcursor; /* R: recno cursor (1-based) */ + +#define CURS_ACQUIRE 0x01 /* B: Cursor needs to be reacquired. */ +#define CURS_AFTER 0x02 /* B: Unreturned cursor after key. */ +#define CURS_BEFORE 0x04 /* B: Unreturned cursor before key. */ +#define CURS_INIT 0x08 /* RB: Cursor initialized. */ + u_int8_t flags; +} CURSOR; + +/* + * The metadata of the tree. The nrecs field is used only by the RECNO code. + * This is because the btree doesn't really need it and it requires that every + * put or delete call modify the metadata. + */ +typedef struct _btmeta { + uint32_t magic; /* magic number */ + uint32_t version; /* version */ + uint32_t psize; /* page size */ + uint32_t free; /* page number of first free page */ + uint32_t nrecs; /* R: number of records */ + +#define SAVEMETA (B_NODUPS | R_RECNO) + uint32_t flags; /* bt_flags & SAVEMETA */ +} BTMETA; + +/* The in-memory btree/recno data structure. */ +typedef struct _btree { + MPOOL *bt_mp; /* memory pool cookie */ + + DB *bt_dbp; /* pointer to enclosing DB */ + + EPG bt_cur; /* current (pinned) page */ + PAGE *bt_pinned; /* page pinned across calls */ + + CURSOR bt_cursor; /* cursor */ + +#define BT_PUSH(t, p, i) { \ + t->bt_sp->pgno = p; \ + t->bt_sp->index = i; \ + ++t->bt_sp; \ +} +#define BT_POP(t) (t->bt_sp == t->bt_stack ? NULL : --t->bt_sp) +#define BT_CLR(t) (t->bt_sp = t->bt_stack) + EPGNO bt_stack[50]; /* stack of parent pages */ + EPGNO *bt_sp; /* current stack pointer */ + + DBT bt_rkey; /* returned key */ + DBT bt_rdata; /* returned data */ + + int bt_fd; /* tree file descriptor */ + + pgno_t bt_free; /* next free page */ + uint32_t bt_psize; /* page size */ + indx_t bt_ovflsize; /* cut-off for key/data overflow */ + int bt_lorder; /* byte order */ + /* sorted order */ + enum { NOT, BACK, FORWARD } bt_order; + EPGNO bt_last; /* last insert */ + + /* B: key comparison function */ + int (*bt_cmp)(const DBT *, const DBT *); + /* B: prefix comparison function */ + size_t (*bt_pfx)(const DBT *, const DBT *); + /* R: recno input function */ + int (*bt_irec)(struct _btree *, recno_t); + + FILE *bt_rfp; /* R: record FILE pointer */ + int bt_rfd; /* R: record file descriptor */ + + caddr_t bt_cmap; /* R: current point in mapped space */ + caddr_t bt_smap; /* R: start of mapped space */ + caddr_t bt_emap; /* R: end of mapped space */ + size_t bt_msize; /* R: size of mapped region. */ + + recno_t bt_nrecs; /* R: number of records */ + size_t bt_reclen; /* R: fixed record length */ + u_char bt_bval; /* R: delimiting byte/pad character */ + +/* + * NB: + * B_NODUPS and R_RECNO are stored on disk, and may not be changed. + */ +#define B_INMEM 0x00001 /* in-memory tree */ +#define B_METADIRTY 0x00002 /* need to write metadata */ +#define B_MODIFIED 0x00004 /* tree modified */ +#define B_NEEDSWAP 0x00008 /* if byte order requires swapping */ +#define B_RDONLY 0x00010 /* read-only tree */ + +#define B_NODUPS 0x00020 /* no duplicate keys permitted */ +#define R_RECNO 0x00080 /* record oriented tree */ + +#define R_CLOSEFP 0x00040 /* opened a file pointer */ +#define R_EOF 0x00100 /* end of input file reached. */ +#define R_FIXLEN 0x00200 /* fixed length records */ +#define R_MEMMAPPED 0x00400 /* memory mapped file. */ +#define R_INMEM 0x00800 /* in-memory file */ +#define R_MODIFIED 0x01000 /* modified file */ +#define R_RDONLY 0x02000 /* read-only file */ + +#define B_DB_LOCK 0x04000 /* DB_LOCK specified. */ +#define B_DB_SHMEM 0x08000 /* DB_SHMEM specified. */ +#define B_DB_TXN 0x10000 /* DB_TXN specified. */ + uint32_t flags; +} BTREE; + +#include "extern.h" diff --git a/lib/libc/db/btree/extern.h b/lib/libc/db/btree/extern.h new file mode 100644 index 0000000..e356440 --- /dev/null +++ b/lib/libc/db/btree/extern.h @@ -0,0 +1,71 @@ +/*- + * Copyright (c) 1991, 1993, 1994 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * @(#)extern.h 8.10 (Berkeley) 7/20/94 + * $FreeBSD: src/lib/libc/db/btree/extern.h,v 1.3 2002/03/22 09:18:22 obrien Exp $ + */ + +int __bt_close(DB *); +int __bt_cmp(BTREE *, const DBT *, EPG *); +int __bt_crsrdel(BTREE *, EPGNO *); +int __bt_defcmp(const DBT *, const DBT *); +size_t __bt_defpfx(const DBT *, const DBT *); +int __bt_delete(const DB *, const DBT *, u_int); +int __bt_dleaf(BTREE *, const DBT *, PAGE *, u_int); +int __bt_fd(const DB *); +int __bt_free(BTREE *, PAGE *); +int __bt_get(const DB *, const DBT *, DBT *, u_int); +PAGE *__bt_new(BTREE *, pgno_t *); +void __bt_pgin(void *, pgno_t, void *); +void __bt_pgout(void *, pgno_t, void *); +int __bt_push(BTREE *, pgno_t, int); +int __bt_put(const DB *dbp, DBT *, const DBT *, u_int); +int __bt_ret(BTREE *, EPG *, DBT *, DBT *, DBT *, DBT *, int); +EPG *__bt_search(BTREE *, const DBT *, int *); +int __bt_seq(const DB *, DBT *, DBT *, u_int); +void __bt_setcur(BTREE *, pgno_t, u_int); +int __bt_split(BTREE *, PAGE *, + const DBT *, const DBT *, int, size_t, uint32_t); +int __bt_sync(const DB *, u_int); + +int __ovfl_delete(BTREE *, void *); +int __ovfl_get(BTREE *, void *, size_t *, void **, size_t *); +int __ovfl_put(BTREE *, const DBT *, pgno_t *); + +#ifdef DEBUG +void __bt_dnpage(DB *, pgno_t); +void __bt_dpage(PAGE *); +void __bt_dump(DB *); +#endif +#ifdef STATISTICS +void __bt_stat(DB *); +#endif diff --git a/lib/libc/db/db/Makefile b/lib/libc/db/db/Makefile new file mode 100644 index 0000000..750cf27 --- /dev/null +++ b/lib/libc/db/db/Makefile @@ -0,0 +1,35 @@ +# $Id: Makefile 89 2016-01-12 00:20:40Z reddawg $ +# The System Makefile (C) 2002 The UbixOS Project + +# Include Global 'Source' Options +include ../../../../Makefile.incl +include ../../../Makefile.incl +include ../Makefile.incl + +INCLUDES += -I../ + +#Objects +OBJS = db.o + +all: $(OBJS) + +# Compile the source files +.cc.o: + $(CXX) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -c -o $@ $< + +.cc.s: + $(CXX) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -S -o $@ $< + +.c.o: + $(CC) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -c $< + +.c.s: + $(CC) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -S -o $@ $< + +.S.o: + $(CC) $(CFLAGS) -Wall -nostdlib $(INCLUDES) -c -o $@ $< + +# Clean up the junk +clean: + $(REMOVE) $(OBJS) + diff --git a/lib/libc/db/db/db.c b/lib/libc/db/db/db.c new file mode 100644 index 0000000..9c65e55 --- /dev/null +++ b/lib/libc/db/db/db.c @@ -0,0 +1,101 @@ +/*- + * Copyright (c) 1991, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)db.c 8.4 (Berkeley) 2/21/94"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/db/db/db.c,v 1.2 2002/03/22 21:52:01 obrien Exp $"); + +#include + +#include +#include +#include +#include + +#include + +DB * +dbopen(fname, flags, mode, type, openinfo) + const char *fname; + int flags, mode; + DBTYPE type; + const void *openinfo; +{ + +#define DB_FLAGS (DB_LOCK | DB_SHMEM | DB_TXN) +#define USE_OPEN_FLAGS \ + (O_CREAT | O_EXCL | O_EXLOCK | O_NONBLOCK | O_RDONLY | \ + O_RDWR | O_SHLOCK | O_TRUNC) + + if ((flags & ~(USE_OPEN_FLAGS | DB_FLAGS)) == 0) + switch (type) { + case DB_BTREE: + return (__bt_open(fname, flags & USE_OPEN_FLAGS, + mode, openinfo, flags & DB_FLAGS)); + case DB_HASH: + return (__hash_open(fname, flags & USE_OPEN_FLAGS, + mode, openinfo, flags & DB_FLAGS)); + case DB_RECNO: + return (__rec_open(fname, flags & USE_OPEN_FLAGS, + mode, openinfo, flags & DB_FLAGS)); + } + errno = EINVAL; + return (NULL); +} + +static int +__dberr() +{ + return (RET_ERROR); +} + +/* + * __DBPANIC -- Stop. + * + * Parameters: + * dbp: pointer to the DB structure. + */ +void +__dbpanic(dbp) + DB *dbp; +{ + /* The only thing that can succeed is a close. */ + dbp->del = (int (*)())__dberr; + dbp->fd = (int (*)())__dberr; + dbp->get = (int (*)())__dberr; + dbp->put = (int (*)())__dberr; + dbp->seq = (int (*)())__dberr; + dbp->sync = (int (*)())__dberr; +} diff --git a/lib/libc/db/hash/Makefile b/lib/libc/db/hash/Makefile new file mode 100644 index 0000000..b0b99a9 --- /dev/null +++ b/lib/libc/db/hash/Makefile @@ -0,0 +1,35 @@ +# $Id: Makefile 89 2016-01-12 00:20:40Z reddawg $ +# The System Makefile (C) 2002 The UbixOS Project + +# Include Global 'Source' Options +include ../../../../Makefile.incl +include ../../../Makefile.incl +include ../Makefile.incl + +INCLUDES += -I../ -I../../include + +#Objects +OBJS = hash.o hash_bigkey.o hash_buf.o hash_func.o hash_log2.o hash_page.o ndbm.o + +all: $(OBJS) + +# Compile the source files +.cc.o: + $(CXX) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -c -o $@ $< + +.cc.s: + $(CXX) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -S -o $@ $< + +.c.o: + $(CC) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -c $< + +.c.s: + $(CC) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -S -o $@ $< + +.S.o: + $(CC) $(CFLAGS) -Wall -nostdlib $(INCLUDES) -c -o $@ $< + +# Clean up the junk +clean: + $(REMOVE) $(OBJS) + diff --git a/lib/libc/db/hash/README b/lib/libc/db/hash/README new file mode 100644 index 0000000..f29ccf7 --- /dev/null +++ b/lib/libc/db/hash/README @@ -0,0 +1,72 @@ +# @(#)README 8.1 (Berkeley) 6/4/93 + +This package implements a superset of the hsearch and dbm/ndbm libraries. + +Test Programs: + All test programs which need key/data pairs expect them entered + with key and data on separate lines + + tcreat3.c + Takes + bucketsize (bsize), + fill factor (ffactor), and + initial number of elements (nelem). + Creates a hash table named hashtest containing the + keys/data pairs entered from standard in. + thash4.c + Takes + bucketsize (bsize), + fill factor (ffactor), + initial number of elements (nelem) + bytes of cache (ncached), and + file from which to read data (fname) + Creates a table from the key/data pairs on standard in and + then does a read of each key/data in fname + tdel.c + Takes + bucketsize (bsize), and + fill factor (ffactor). + file from which to read data (fname) + Reads each key/data pair from fname and deletes the + key from the hash table hashtest + tseq.c + Reads the key/data pairs in the file hashtest and writes them + to standard out. + tread2.c + Takes + butes of cache (ncached). + Reads key/data pairs from standard in and looks them up + in the file hashtest. + tverify.c + Reads key/data pairs from standard in, looks them up + in the file hashtest, and verifies that the data is + correct. + +NOTES: + +The file search.h is provided for using the hsearch compatible interface +on BSD systems. On System V derived systems, search.h should appear in +/usr/include. + +The man page ../man/db.3 explains the interface to the hashing system. +The file hash.ps is a postscript copy of a paper explaining +the history, implementation, and performance of the hash package. + +"bugs" or idiosyncracies + +If you have a lot of overflows, it is possible to run out of overflow +pages. Currently, this will cause a message to be printed on stderr. +Eventually, this will be indicated by a return error code. + +If you are using the ndbm interface and exit without flushing or closing the +file, you may lose updates since the package buffers all writes. Also, +the db interface only creates a single database file. To avoid overwriting +the user's original file, the suffix ".db" is appended to the file name +passed to dbm_open. Additionally, if your code "knows" about the historic +.dir and .pag files, it will break. + +There is a fundamental difference between this package and the old hsearch. +Hsearch requires the user to maintain the keys and data in the application's +allocated memory while hash takes care of all storage management. The down +side is that the byte strings passed in the ENTRY structure must be null +terminated (both the keys and the data). diff --git a/lib/libc/db/hash/extern.h b/lib/libc/db/hash/extern.h new file mode 100644 index 0000000..2c23e09 --- /dev/null +++ b/lib/libc/db/hash/extern.h @@ -0,0 +1,66 @@ +/*- + * Copyright (c) 1991, 1993, 1994 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * @(#)extern.h 8.4 (Berkeley) 6/16/94 + * $FreeBSD: src/lib/libc/db/hash/extern.h,v 1.3 2002/03/22 09:18:22 obrien Exp $ + */ + +BUFHEAD *__add_ovflpage(HTAB *, BUFHEAD *); +int __addel(HTAB *, BUFHEAD *, const DBT *, const DBT *); +int __big_delete(HTAB *, BUFHEAD *); +int __big_insert(HTAB *, BUFHEAD *, const DBT *, const DBT *); +int __big_keydata(HTAB *, BUFHEAD *, DBT *, DBT *, int); +int __big_return(HTAB *, BUFHEAD *, int, DBT *, int); +int __big_split(HTAB *, BUFHEAD *, BUFHEAD *, BUFHEAD *, + int, uint32_t, SPLIT_RETURN *); +int __buf_free(HTAB *, int, int); +void __buf_init(HTAB *, int); +uint32_t __call_hash(HTAB *, char *, int); +int __delpair(HTAB *, BUFHEAD *, int); +int __expand_table(HTAB *); +int __find_bigpair(HTAB *, BUFHEAD *, int, char *, int); +u_int16_t __find_last_page(HTAB *, BUFHEAD **); +void __free_ovflpage(HTAB *, BUFHEAD *); +BUFHEAD *__get_buf(HTAB *, uint32_t, BUFHEAD *, int); +int __get_page(HTAB *, char *, uint32_t, int, int, int); +int __ibitmap(HTAB *, int, int, int); +uint32_t __log2(uint32_t); +int __put_page(HTAB *, char *, uint32_t, int, int); +void __reclaim_buf(HTAB *, BUFHEAD *); +int __split_page(HTAB *, uint32_t, uint32_t); + +/* Default hash routine. */ +extern uint32_t (*__default_hash)(const void *, size_t); + +#ifdef HASH_STATISTICS +extern int hash_accesses, hash_collisions, hash_expansions, hash_overflows; +#endif diff --git a/lib/libc/db/hash/hash.c b/lib/libc/db/hash/hash.c new file mode 100644 index 0000000..fd00d4f --- /dev/null +++ b/lib/libc/db/hash/hash.c @@ -0,0 +1,1006 @@ +/*- + * Copyright (c) 1990, 1993, 1994 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * Margo Seltzer. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)hash.c 8.9 (Berkeley) 6/16/94"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/db/hash/hash.c,v 1.12 2004/09/10 05:41:41 kuriyama Exp $"); + +#include "namespace.h" +#include +#include + +#include +#include +#include +#include +#include +#include +#ifdef DEBUG +#include +#endif +#include "un-namespace.h" + +#include +#include "hash.h" +#include "page.h" +#include "extern.h" + +static int alloc_segs(HTAB *, int); +static int flush_meta(HTAB *); +static int hash_access(HTAB *, ACTION, DBT *, DBT *); +static int hash_close(DB *); +static int hash_delete(const DB *, const DBT *, uint32_t); +static int hash_fd(const DB *); +static int hash_get(const DB *, const DBT *, DBT *, uint32_t); +static int hash_put(const DB *, DBT *, const DBT *, uint32_t); +static void *hash_realloc(SEGMENT **, int, int); +static int hash_seq(const DB *, DBT *, DBT *, uint32_t); +static int hash_sync(const DB *, uint32_t); +static int hdestroy(HTAB *); +static HTAB *init_hash(HTAB *, const char *, HASHINFO *); +static int init_htab(HTAB *, int); +#if BYTE_ORDER == LITTLE_ENDIAN +static void swap_header(HTAB *); +static void swap_header_copy(HASHHDR *, HASHHDR *); +#endif + +/* Fast arithmetic, relying on powers of 2, */ +#define MOD(x, y) ((x) & ((y) - 1)) + +#define RETURN_ERROR(ERR, LOC) { save_errno = ERR; goto LOC; } + +/* Return values */ +#define SUCCESS (0) +#define ERROR (-1) +#define ABNORMAL (1) + +#ifdef HASH_STATISTICS +int hash_accesses, hash_collisions, hash_expansions, hash_overflows; +#endif + +/************************** INTERFACE ROUTINES ***************************/ +/* OPEN/CLOSE */ + +extern DB * +__hash_open(file, flags, mode, info, dflags) + const char *file; + int flags, mode, dflags; + const HASHINFO *info; /* Special directives for create */ +{ + HTAB *hashp; + struct stat statbuf; + DB *dbp; + int bpages, hdrsize, new_table, nsegs, save_errno; + + if ((flags & O_ACCMODE) == O_WRONLY) { + errno = EINVAL; + return (NULL); + } + + if (!(hashp = (HTAB *)calloc(1, sizeof(HTAB)))) + return (NULL); + hashp->fp = -1; + + /* + * Even if user wants write only, we need to be able to read + * the actual file, so we need to open it read/write. But, the + * field in the hashp structure needs to be accurate so that + * we can check accesses. + */ + hashp->flags = flags; + + new_table = 0; + if (!file || (flags & O_TRUNC) || + (stat(file, &statbuf) && (errno == ENOENT))) { + if (errno == ENOENT) + errno = 0; /* Just in case someone looks at errno */ + new_table = 1; + } + if (file) { + if ((hashp->fp = _open(file, flags, mode)) == -1) + RETURN_ERROR(errno, error0); + + /* if the .db file is empty, and we had permission to create + a new .db file, then reinitialize the database */ + if ((flags & O_CREAT) && + _fstat(hashp->fp, &statbuf) == 0 && statbuf.st_size == 0) + new_table = 1; + + (void)_fcntl(hashp->fp, F_SETFD, 1); + } + if (new_table) { + if (!(hashp = init_hash(hashp, file, (HASHINFO *)info))) + RETURN_ERROR(errno, error1); + } else { + /* Table already exists */ + if (info && info->hash) + hashp->hash = info->hash; + else + hashp->hash = __default_hash; + + hdrsize = _read(hashp->fp, &hashp->hdr, sizeof(HASHHDR)); +#if BYTE_ORDER == LITTLE_ENDIAN + swap_header(hashp); +#endif + if (hdrsize == -1) + RETURN_ERROR(errno, error1); + if (hdrsize != sizeof(HASHHDR)) + RETURN_ERROR(EFTYPE, error1); + /* Verify file type, versions and hash function */ + if (hashp->MAGIC != HASHMAGIC) + RETURN_ERROR(EFTYPE, error1); +#define OLDHASHVERSION 1 + if (hashp->VERSION != HASHVERSION && + hashp->VERSION != OLDHASHVERSION) + RETURN_ERROR(EFTYPE, error1); + if (hashp->hash(CHARKEY, sizeof(CHARKEY)) != hashp->H_CHARKEY) + RETURN_ERROR(EFTYPE, error1); + /* + * Figure out how many segments we need. Max_Bucket is the + * maximum bucket number, so the number of buckets is + * max_bucket + 1. + */ + nsegs = (hashp->MAX_BUCKET + 1 + hashp->SGSIZE - 1) / + hashp->SGSIZE; + hashp->nsegs = 0; + if (alloc_segs(hashp, nsegs)) + /* + * If alloc_segs fails, table will have been destroyed + * and errno will have been set. + */ + return (NULL); + /* Read in bitmaps */ + bpages = (hashp->SPARES[hashp->OVFL_POINT] + + (hashp->BSIZE << BYTE_SHIFT) - 1) >> + (hashp->BSHIFT + BYTE_SHIFT); + + hashp->nmaps = bpages; + (void)memset(&hashp->mapp[0], 0, bpages * sizeof(uint32_t *)); + } + + /* Initialize Buffer Manager */ + if (info && info->cachesize) + __buf_init(hashp, info->cachesize); + else + __buf_init(hashp, DEF_BUFSIZE); + + hashp->new_file = new_table; + hashp->save_file = file && (hashp->flags & O_RDWR); + hashp->cbucket = -1; + if (!(dbp = (DB *)malloc(sizeof(DB)))) { + save_errno = errno; + hdestroy(hashp); + errno = save_errno; + return (NULL); + } + dbp->internal = hashp; + dbp->close = hash_close; + dbp->del = hash_delete; + dbp->fd = hash_fd; + dbp->get = hash_get; + dbp->put = hash_put; + dbp->seq = hash_seq; + dbp->sync = hash_sync; + dbp->type = DB_HASH; + +#ifdef DEBUG + (void)fprintf(stderr, +"%s\n%s%p\n%s%d\n%s%d\n%s%d\n%s%d\n%s%d\n%s%d\n%s%d\n%s%d\n%s%d\n%s%x\n%s%x\n%s%d\n%s%d\n", + "init_htab:", + "TABLE POINTER ", hashp, + "BUCKET SIZE ", hashp->BSIZE, + "BUCKET SHIFT ", hashp->BSHIFT, + "DIRECTORY SIZE ", hashp->DSIZE, + "SEGMENT SIZE ", hashp->SGSIZE, + "SEGMENT SHIFT ", hashp->SSHIFT, + "FILL FACTOR ", hashp->FFACTOR, + "MAX BUCKET ", hashp->MAX_BUCKET, + "OVFL POINT ", hashp->OVFL_POINT, + "LAST FREED ", hashp->LAST_FREED, + "HIGH MASK ", hashp->HIGH_MASK, + "LOW MASK ", hashp->LOW_MASK, + "NSEGS ", hashp->nsegs, + "NKEYS ", hashp->NKEYS); +#endif +#ifdef HASH_STATISTICS + hash_overflows = hash_accesses = hash_collisions = hash_expansions = 0; +#endif + return (dbp); + +error1: + if (hashp != NULL) + (void)_close(hashp->fp); + +error0: + free(hashp); + errno = save_errno; + return (NULL); +} + +static int +hash_close(dbp) + DB *dbp; +{ + HTAB *hashp; + int retval; + + if (!dbp) + return (ERROR); + + hashp = (HTAB *)dbp->internal; + retval = hdestroy(hashp); + free(dbp); + return (retval); +} + +static int +hash_fd(dbp) + const DB *dbp; +{ + HTAB *hashp; + + if (!dbp) + return (ERROR); + + hashp = (HTAB *)dbp->internal; + if (hashp->fp == -1) { + errno = ENOENT; + return (-1); + } + return (hashp->fp); +} + +/************************** LOCAL CREATION ROUTINES **********************/ +static HTAB * +init_hash(hashp, file, info) + HTAB *hashp; + const char *file; + HASHINFO *info; +{ + struct stat statbuf; + int nelem; + + nelem = 1; + hashp->NKEYS = 0; + hashp->LORDER = BYTE_ORDER; + hashp->BSIZE = DEF_BUCKET_SIZE; + hashp->BSHIFT = DEF_BUCKET_SHIFT; + hashp->SGSIZE = DEF_SEGSIZE; + hashp->SSHIFT = DEF_SEGSIZE_SHIFT; + hashp->DSIZE = DEF_DIRSIZE; + hashp->FFACTOR = DEF_FFACTOR; + hashp->hash = __default_hash; + memset(hashp->SPARES, 0, sizeof(hashp->SPARES)); + memset(hashp->BITMAPS, 0, sizeof (hashp->BITMAPS)); + + /* Fix bucket size to be optimal for file system */ + if (file != NULL) { + if (stat(file, &statbuf)) + return (NULL); + hashp->BSIZE = statbuf.st_blksize; + hashp->BSHIFT = __log2(hashp->BSIZE); + } + + if (info) { + if (info->bsize) { + /* Round pagesize up to power of 2 */ + hashp->BSHIFT = __log2(info->bsize); + hashp->BSIZE = 1 << hashp->BSHIFT; + if (hashp->BSIZE > MAX_BSIZE) { + errno = EINVAL; + return (NULL); + } + } + if (info->ffactor) + hashp->FFACTOR = info->ffactor; + if (info->hash) + hashp->hash = info->hash; + if (info->nelem) + nelem = info->nelem; + if (info->lorder) { + if (info->lorder != BIG_ENDIAN && + info->lorder != LITTLE_ENDIAN) { + errno = EINVAL; + return (NULL); + } + hashp->LORDER = info->lorder; + } + } + /* init_htab should destroy the table and set errno if it fails */ + if (init_htab(hashp, nelem)) + return (NULL); + else + return (hashp); +} +/* + * This calls alloc_segs which may run out of memory. Alloc_segs will destroy + * the table and set errno, so we just pass the error information along. + * + * Returns 0 on No Error + */ +static int +init_htab(hashp, nelem) + HTAB *hashp; + int nelem; +{ + int nbuckets, nsegs; + int l2; + + /* + * Divide number of elements by the fill factor and determine a + * desired number of buckets. Allocate space for the next greater + * power of two number of buckets. + */ + nelem = (nelem - 1) / hashp->FFACTOR + 1; + + l2 = __log2(MAX(nelem, 2)); + nbuckets = 1 << l2; + + hashp->SPARES[l2] = l2 + 1; + hashp->SPARES[l2 + 1] = l2 + 1; + hashp->OVFL_POINT = l2; + hashp->LAST_FREED = 2; + + /* First bitmap page is at: splitpoint l2 page offset 1 */ + if (__ibitmap(hashp, OADDR_OF(l2, 1), l2 + 1, 0)) + return (-1); + + hashp->MAX_BUCKET = hashp->LOW_MASK = nbuckets - 1; + hashp->HIGH_MASK = (nbuckets << 1) - 1; + hashp->HDRPAGES = ((MAX(sizeof(HASHHDR), MINHDRSIZE) - 1) >> + hashp->BSHIFT) + 1; + + nsegs = (nbuckets - 1) / hashp->SGSIZE + 1; + nsegs = 1 << __log2(nsegs); + + if (nsegs > hashp->DSIZE) + hashp->DSIZE = nsegs; + return (alloc_segs(hashp, nsegs)); +} + +/********************** DESTROY/CLOSE ROUTINES ************************/ + +/* + * Flushes any changes to the file if necessary and destroys the hashp + * structure, freeing all allocated space. + */ +static int +hdestroy(hashp) + HTAB *hashp; +{ + int i, save_errno; + + save_errno = 0; + +#ifdef HASH_STATISTICS + (void)fprintf(stderr, "hdestroy: accesses %ld collisions %ld\n", + hash_accesses, hash_collisions); + (void)fprintf(stderr, "hdestroy: expansions %ld\n", + hash_expansions); + (void)fprintf(stderr, "hdestroy: overflows %ld\n", + hash_overflows); + (void)fprintf(stderr, "keys %ld maxp %d segmentcount %d\n", + hashp->NKEYS, hashp->MAX_BUCKET, hashp->nsegs); + + for (i = 0; i < NCACHED; i++) + (void)fprintf(stderr, + "spares[%d] = %d\n", i, hashp->SPARES[i]); +#endif + /* + * Call on buffer manager to free buffers, and if required, + * write them to disk. + */ + if (__buf_free(hashp, 1, hashp->save_file)) + save_errno = errno; + if (hashp->dir) { + free(*hashp->dir); /* Free initial segments */ + /* Free extra segments */ + while (hashp->exsegs--) + free(hashp->dir[--hashp->nsegs]); + free(hashp->dir); + } + if (flush_meta(hashp) && !save_errno) + save_errno = errno; + /* Free Bigmaps */ + for (i = 0; i < hashp->nmaps; i++) + if (hashp->mapp[i]) + free(hashp->mapp[i]); + + if (hashp->fp != -1) + (void)_close(hashp->fp); + + free(hashp); + + if (save_errno) { + errno = save_errno; + return (ERROR); + } + return (SUCCESS); +} +/* + * Write modified pages to disk + * + * Returns: + * 0 == OK + * -1 ERROR + */ +static int +hash_sync(dbp, flags) + const DB *dbp; + uint32_t flags; +{ + HTAB *hashp; + + if (flags != 0) { + errno = EINVAL; + return (ERROR); + } + + if (!dbp) + return (ERROR); + + hashp = (HTAB *)dbp->internal; + if (!hashp->save_file) + return (0); + if (__buf_free(hashp, 0, 1) || flush_meta(hashp)) + return (ERROR); + hashp->new_file = 0; + return (0); +} + +/* + * Returns: + * 0 == OK + * -1 indicates that errno should be set + */ +static int +flush_meta(hashp) + HTAB *hashp; +{ + HASHHDR *whdrp; +#if BYTE_ORDER == LITTLE_ENDIAN + HASHHDR whdr; +#endif + int fp, i, wsize; + + if (!hashp->save_file) + return (0); + hashp->MAGIC = HASHMAGIC; + hashp->VERSION = HASHVERSION; + hashp->H_CHARKEY = hashp->hash(CHARKEY, sizeof(CHARKEY)); + + fp = hashp->fp; + whdrp = &hashp->hdr; +#if BYTE_ORDER == LITTLE_ENDIAN + whdrp = &whdr; + swap_header_copy(&hashp->hdr, whdrp); +#endif + if ((lseek(fp, (off_t)0, SEEK_SET) == -1) || + ((wsize = _write(fp, whdrp, sizeof(HASHHDR))) == -1)) + return (-1); + else + if (wsize != sizeof(HASHHDR)) { + errno = EFTYPE; + hashp->error = errno; + return (-1); + } + for (i = 0; i < NCACHED; i++) + if (hashp->mapp[i]) + if (__put_page(hashp, (char *)hashp->mapp[i], + hashp->BITMAPS[i], 0, 1)) + return (-1); + return (0); +} + +/*******************************SEARCH ROUTINES *****************************/ +/* + * All the access routines return + * + * Returns: + * 0 on SUCCESS + * 1 to indicate an external ERROR (i.e. key not found, etc) + * -1 to indicate an internal ERROR (i.e. out of memory, etc) + */ +static int +hash_get(dbp, key, data, flag) + const DB *dbp; + const DBT *key; + DBT *data; + uint32_t flag; +{ + HTAB *hashp; + + hashp = (HTAB *)dbp->internal; + if (flag) { + hashp->error = errno = EINVAL; + return (ERROR); + } + return (hash_access(hashp, HASH_GET, (DBT *)key, data)); +} + +static int +hash_put(dbp, key, data, flag) + const DB *dbp; + DBT *key; + const DBT *data; + uint32_t flag; +{ + HTAB *hashp; + + hashp = (HTAB *)dbp->internal; + if (flag && flag != R_NOOVERWRITE) { + hashp->error = EINVAL; + errno = EINVAL; + return (ERROR); + } + if ((hashp->flags & O_ACCMODE) == O_RDONLY) { + hashp->error = errno = EPERM; + return (ERROR); + } + return (hash_access(hashp, flag == R_NOOVERWRITE ? + HASH_PUTNEW : HASH_PUT, (DBT *)key, (DBT *)data)); +} + +static int +hash_delete(dbp, key, flag) + const DB *dbp; + const DBT *key; + uint32_t flag; /* Ignored */ +{ + HTAB *hashp; + + hashp = (HTAB *)dbp->internal; + if (flag && flag != R_CURSOR) { + hashp->error = errno = EINVAL; + return (ERROR); + } + if ((hashp->flags & O_ACCMODE) == O_RDONLY) { + hashp->error = errno = EPERM; + return (ERROR); + } + return (hash_access(hashp, HASH_DELETE, (DBT *)key, NULL)); +} + +/* + * Assume that hashp has been set in wrapper routine. + */ +static int +hash_access(hashp, action, key, val) + HTAB *hashp; + ACTION action; + DBT *key, *val; +{ + BUFHEAD *rbufp; + BUFHEAD *bufp, *save_bufp; + u_int16_t *bp; + int n, ndx, off, size; + char *kp; + u_int16_t pageno; + +#ifdef HASH_STATISTICS + hash_accesses++; +#endif + + off = hashp->BSIZE; + size = key->size; + kp = (char *)key->data; + rbufp = __get_buf(hashp, __call_hash(hashp, kp, size), NULL, 0); + if (!rbufp) + return (ERROR); + save_bufp = rbufp; + + /* Pin the bucket chain */ + rbufp->flags |= BUF_PIN; + for (bp = (u_int16_t *)rbufp->page, n = *bp++, ndx = 1; ndx < n;) + if (bp[1] >= REAL_KEY) { + /* Real key/data pair */ + if (size == off - *bp && + memcmp(kp, rbufp->page + *bp, size) == 0) + goto found; + off = bp[1]; +#ifdef HASH_STATISTICS + hash_collisions++; +#endif + bp += 2; + ndx += 2; + } else if (bp[1] == OVFLPAGE) { + rbufp = __get_buf(hashp, *bp, rbufp, 0); + if (!rbufp) { + save_bufp->flags &= ~BUF_PIN; + return (ERROR); + } + /* FOR LOOP INIT */ + bp = (u_int16_t *)rbufp->page; + n = *bp++; + ndx = 1; + off = hashp->BSIZE; + } else if (bp[1] < REAL_KEY) { + if ((ndx = + __find_bigpair(hashp, rbufp, ndx, kp, size)) > 0) + goto found; + if (ndx == -2) { + bufp = rbufp; + if (!(pageno = + __find_last_page(hashp, &bufp))) { + ndx = 0; + rbufp = bufp; + break; /* FOR */ + } + rbufp = __get_buf(hashp, pageno, bufp, 0); + if (!rbufp) { + save_bufp->flags &= ~BUF_PIN; + return (ERROR); + } + /* FOR LOOP INIT */ + bp = (u_int16_t *)rbufp->page; + n = *bp++; + ndx = 1; + off = hashp->BSIZE; + } else { + save_bufp->flags &= ~BUF_PIN; + return (ERROR); + } + } + + /* Not found */ + switch (action) { + case HASH_PUT: + case HASH_PUTNEW: + if (__addel(hashp, rbufp, key, val)) { + save_bufp->flags &= ~BUF_PIN; + return (ERROR); + } else { + save_bufp->flags &= ~BUF_PIN; + return (SUCCESS); + } + case HASH_GET: + case HASH_DELETE: + default: + save_bufp->flags &= ~BUF_PIN; + return (ABNORMAL); + } + +found: + switch (action) { + case HASH_PUTNEW: + save_bufp->flags &= ~BUF_PIN; + return (ABNORMAL); + case HASH_GET: + bp = (u_int16_t *)rbufp->page; + if (bp[ndx + 1] < REAL_KEY) { + if (__big_return(hashp, rbufp, ndx, val, 0)) + return (ERROR); + } else { + val->data = (u_char *)rbufp->page + (int)bp[ndx + 1]; + val->size = bp[ndx] - bp[ndx + 1]; + } + break; + case HASH_PUT: + if ((__delpair(hashp, rbufp, ndx)) || + (__addel(hashp, rbufp, key, val))) { + save_bufp->flags &= ~BUF_PIN; + return (ERROR); + } + break; + case HASH_DELETE: + if (__delpair(hashp, rbufp, ndx)) + return (ERROR); + break; + default: + abort(); + } + save_bufp->flags &= ~BUF_PIN; + return (SUCCESS); +} + +static int +hash_seq(dbp, key, data, flag) + const DB *dbp; + DBT *key, *data; + uint32_t flag; +{ + uint32_t bucket; + BUFHEAD *bufp; + HTAB *hashp; + u_int16_t *bp, ndx; + + hashp = (HTAB *)dbp->internal; + if (flag && flag != R_FIRST && flag != R_NEXT) { + hashp->error = errno = EINVAL; + return (ERROR); + } +#ifdef HASH_STATISTICS + hash_accesses++; +#endif + if ((hashp->cbucket < 0) || (flag == R_FIRST)) { + hashp->cbucket = 0; + hashp->cndx = 1; + hashp->cpage = NULL; + } + + for (bp = NULL; !bp || !bp[0]; ) { + if (!(bufp = hashp->cpage)) { + for (bucket = hashp->cbucket; + bucket <= hashp->MAX_BUCKET; + bucket++, hashp->cndx = 1) { + bufp = __get_buf(hashp, bucket, NULL, 0); + if (!bufp) + return (ERROR); + hashp->cpage = bufp; + bp = (u_int16_t *)bufp->page; + if (bp[0]) + break; + } + hashp->cbucket = bucket; + if (hashp->cbucket > hashp->MAX_BUCKET) { + hashp->cbucket = -1; + return (ABNORMAL); + } + } else + bp = (u_int16_t *)hashp->cpage->page; + +#ifdef DEBUG + assert(bp); + assert(bufp); +#endif + while (bp[hashp->cndx + 1] == OVFLPAGE) { + bufp = hashp->cpage = + __get_buf(hashp, bp[hashp->cndx], bufp, 0); + if (!bufp) + return (ERROR); + bp = (u_int16_t *)(bufp->page); + hashp->cndx = 1; + } + if (!bp[0]) { + hashp->cpage = NULL; + ++hashp->cbucket; + } + } + ndx = hashp->cndx; + if (bp[ndx + 1] < REAL_KEY) { + if (__big_keydata(hashp, bufp, key, data, 1)) + return (ERROR); + } else { + key->data = (u_char *)hashp->cpage->page + bp[ndx]; + key->size = (ndx > 1 ? bp[ndx - 1] : hashp->BSIZE) - bp[ndx]; + data->data = (u_char *)hashp->cpage->page + bp[ndx + 1]; + data->size = bp[ndx] - bp[ndx + 1]; + ndx += 2; + if (ndx > bp[0]) { + hashp->cpage = NULL; + hashp->cbucket++; + hashp->cndx = 1; + } else + hashp->cndx = ndx; + } + return (SUCCESS); +} + +/********************************* UTILITIES ************************/ + +/* + * Returns: + * 0 ==> OK + * -1 ==> Error + */ +extern int +__expand_table(hashp) + HTAB *hashp; +{ + uint32_t old_bucket, new_bucket; + int dirsize, new_segnum, spare_ndx; + +#ifdef HASH_STATISTICS + hash_expansions++; +#endif + new_bucket = ++hashp->MAX_BUCKET; + old_bucket = (hashp->MAX_BUCKET & hashp->LOW_MASK); + + new_segnum = new_bucket >> hashp->SSHIFT; + + /* Check if we need a new segment */ + if (new_segnum >= hashp->nsegs) { + /* Check if we need to expand directory */ + if (new_segnum >= hashp->DSIZE) { + /* Reallocate directory */ + dirsize = hashp->DSIZE * sizeof(SEGMENT *); + if (!hash_realloc(&hashp->dir, dirsize, dirsize << 1)) + return (-1); + hashp->DSIZE = dirsize << 1; + } + if ((hashp->dir[new_segnum] = + (SEGMENT)calloc(hashp->SGSIZE, sizeof(SEGMENT))) == NULL) + return (-1); + hashp->exsegs++; + hashp->nsegs++; + } + /* + * If the split point is increasing (MAX_BUCKET's log base 2 + * * increases), we need to copy the current contents of the spare + * split bucket to the next bucket. + */ + spare_ndx = __log2(hashp->MAX_BUCKET + 1); + if (spare_ndx > hashp->OVFL_POINT) { + hashp->SPARES[spare_ndx] = hashp->SPARES[hashp->OVFL_POINT]; + hashp->OVFL_POINT = spare_ndx; + } + + if (new_bucket > hashp->HIGH_MASK) { + /* Starting a new doubling */ + hashp->LOW_MASK = hashp->HIGH_MASK; + hashp->HIGH_MASK = new_bucket | hashp->LOW_MASK; + } + /* Relocate records to the new bucket */ + return (__split_page(hashp, old_bucket, new_bucket)); +} + +/* + * If realloc guarantees that the pointer is not destroyed if the realloc + * fails, then this routine can go away. + */ +static void * +hash_realloc(p_ptr, oldsize, newsize) + SEGMENT **p_ptr; + int oldsize, newsize; +{ + void *p; + + if ( (p = malloc(newsize)) ) { + memmove(p, *p_ptr, oldsize); + memset((char *)p + oldsize, 0, newsize - oldsize); + free(*p_ptr); + *p_ptr = p; + } + return (p); +} + +extern uint32_t +__call_hash(hashp, k, len) + HTAB *hashp; + char *k; + int len; +{ + int n, bucket; + + n = hashp->hash(k, len); + bucket = n & hashp->HIGH_MASK; + if (bucket > hashp->MAX_BUCKET) + bucket = bucket & hashp->LOW_MASK; + return (bucket); +} + +/* + * Allocate segment table. On error, destroy the table and set errno. + * + * Returns 0 on success + */ +static int +alloc_segs(hashp, nsegs) + HTAB *hashp; + int nsegs; +{ + int i; + SEGMENT store; + + int save_errno; + + if ((hashp->dir = + (SEGMENT *)calloc(hashp->DSIZE, sizeof(SEGMENT *))) == NULL) { + save_errno = errno; + (void)hdestroy(hashp); + errno = save_errno; + return (-1); + } + /* Allocate segments */ + if ((store = + (SEGMENT)calloc(nsegs << hashp->SSHIFT, sizeof(SEGMENT))) == NULL) { + save_errno = errno; + (void)hdestroy(hashp); + errno = save_errno; + return (-1); + } + for (i = 0; i < nsegs; i++, hashp->nsegs++) + hashp->dir[i] = &store[i << hashp->SSHIFT]; + return (0); +} + +#if BYTE_ORDER == LITTLE_ENDIAN +/* + * Hashp->hdr needs to be byteswapped. + */ +static void +swap_header_copy(srcp, destp) + HASHHDR *srcp, *destp; +{ + int i; + + P_32_COPY(srcp->magic, destp->magic); + P_32_COPY(srcp->version, destp->version); + P_32_COPY(srcp->lorder, destp->lorder); + P_32_COPY(srcp->bsize, destp->bsize); + P_32_COPY(srcp->bshift, destp->bshift); + P_32_COPY(srcp->dsize, destp->dsize); + P_32_COPY(srcp->ssize, destp->ssize); + P_32_COPY(srcp->sshift, destp->sshift); + P_32_COPY(srcp->ovfl_point, destp->ovfl_point); + P_32_COPY(srcp->last_freed, destp->last_freed); + P_32_COPY(srcp->max_bucket, destp->max_bucket); + P_32_COPY(srcp->high_mask, destp->high_mask); + P_32_COPY(srcp->low_mask, destp->low_mask); + P_32_COPY(srcp->ffactor, destp->ffactor); + P_32_COPY(srcp->nkeys, destp->nkeys); + P_32_COPY(srcp->hdrpages, destp->hdrpages); + P_32_COPY(srcp->h_charkey, destp->h_charkey); + for (i = 0; i < NCACHED; i++) { + P_32_COPY(srcp->spares[i], destp->spares[i]); + P_16_COPY(srcp->bitmaps[i], destp->bitmaps[i]); + } +} + +static void +swap_header(hashp) + HTAB *hashp; +{ + HASHHDR *hdrp; + int i; + + hdrp = &hashp->hdr; + + M_32_SWAP(hdrp->magic); + M_32_SWAP(hdrp->version); + M_32_SWAP(hdrp->lorder); + M_32_SWAP(hdrp->bsize); + M_32_SWAP(hdrp->bshift); + M_32_SWAP(hdrp->dsize); + M_32_SWAP(hdrp->ssize); + M_32_SWAP(hdrp->sshift); + M_32_SWAP(hdrp->ovfl_point); + M_32_SWAP(hdrp->last_freed); + M_32_SWAP(hdrp->max_bucket); + M_32_SWAP(hdrp->high_mask); + M_32_SWAP(hdrp->low_mask); + M_32_SWAP(hdrp->ffactor); + M_32_SWAP(hdrp->nkeys); + M_32_SWAP(hdrp->hdrpages); + M_32_SWAP(hdrp->h_charkey); + for (i = 0; i < NCACHED; i++) { + M_32_SWAP(hdrp->spares[i]); + M_16_SWAP(hdrp->bitmaps[i]); + } +} +#endif diff --git a/lib/libc/db/hash/hash.h b/lib/libc/db/hash/hash.h new file mode 100644 index 0000000..76237f3 --- /dev/null +++ b/lib/libc/db/hash/hash.h @@ -0,0 +1,294 @@ +/*- + * Copyright (c) 1990, 1993, 1994 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * Margo Seltzer. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * @(#)hash.h 8.3 (Berkeley) 5/31/94 + * $FreeBSD: src/lib/libc/db/hash/hash.h,v 1.6 2002/03/21 22:46:26 obrien Exp $ + */ + +/* Operations */ +typedef enum { + HASH_GET, HASH_PUT, HASH_PUTNEW, HASH_DELETE, HASH_FIRST, HASH_NEXT +} ACTION; + +/* Buffer Management structures */ +typedef struct _bufhead BUFHEAD; + +struct _bufhead { + BUFHEAD *prev; /* LRU links */ + BUFHEAD *next; /* LRU links */ + BUFHEAD *ovfl; /* Overflow page buffer header */ + uint32_t addr; /* Address of this page */ + char *page; /* Actual page data */ + char flags; +#define BUF_MOD 0x0001 +#define BUF_DISK 0x0002 +#define BUF_BUCKET 0x0004 +#define BUF_PIN 0x0008 +}; + +#define IS_BUCKET(X) ((X) & BUF_BUCKET) + +typedef BUFHEAD **SEGMENT; + +/* Hash Table Information */ +typedef struct hashhdr { /* Disk resident portion */ + int magic; /* Magic NO for hash tables */ + int version; /* Version ID */ + uint32_t lorder; /* Byte Order */ + int bsize; /* Bucket/Page Size */ + int bshift; /* Bucket shift */ + int dsize; /* Directory Size */ + int ssize; /* Segment Size */ + int sshift; /* Segment shift */ + int ovfl_point; /* Where overflow pages are being + * allocated */ + int last_freed; /* Last overflow page freed */ + int max_bucket; /* ID of Maximum bucket in use */ + int high_mask; /* Mask to modulo into entire table */ + int low_mask; /* Mask to modulo into lower half of + * table */ + int ffactor; /* Fill factor */ + int nkeys; /* Number of keys in hash table */ + int hdrpages; /* Size of table header */ + int h_charkey; /* value of hash(CHARKEY) */ +#define NCACHED 32 /* number of bit maps and spare + * points */ + int spares[NCACHED];/* spare pages for overflow */ + u_int16_t bitmaps[NCACHED]; /* address of overflow page + * bitmaps */ +} HASHHDR; + +typedef struct htab { /* Memory resident data structure */ + HASHHDR hdr; /* Header */ + int nsegs; /* Number of allocated segments */ + int exsegs; /* Number of extra allocated + * segments */ + uint32_t /* Hash function */ + (*hash)(const void *, size_t); + int flags; /* Flag values */ + int fp; /* File pointer */ + char *tmp_buf; /* Temporary Buffer for BIG data */ + char *tmp_key; /* Temporary Buffer for BIG keys */ + BUFHEAD *cpage; /* Current page */ + int cbucket; /* Current bucket */ + int cndx; /* Index of next item on cpage */ + int error; /* Error Number -- for DBM + * compatibility */ + int new_file; /* Indicates if fd is backing store + * or no */ + int save_file; /* Indicates whether we need to flush + * file at + * exit */ + uint32_t *mapp[NCACHED]; /* Pointers to page maps */ + int nmaps; /* Initial number of bitmaps */ + int nbufs; /* Number of buffers left to + * allocate */ + BUFHEAD bufhead; /* Header of buffer lru list */ + SEGMENT *dir; /* Hash Bucket directory */ +} HTAB; + +/* + * Constants + */ +#define MAX_BSIZE 65536 /* 2^16 */ +#define MIN_BUFFERS 6 +#define MINHDRSIZE 512 +#define DEF_BUFSIZE 65536 /* 64 K */ +#define DEF_BUCKET_SIZE 4096 +#define DEF_BUCKET_SHIFT 12 /* log2(BUCKET) */ +#define DEF_SEGSIZE 256 +#define DEF_SEGSIZE_SHIFT 8 /* log2(SEGSIZE) */ +#define DEF_DIRSIZE 256 +#define DEF_FFACTOR 65536 +#define MIN_FFACTOR 4 +#define SPLTMAX 8 +#define CHARKEY "%$sniglet^&" +#define NUMKEY 1038583 +#define BYTE_SHIFT 3 +#define INT_TO_BYTE 2 +#define INT_BYTE_SHIFT 5 +#define ALL_SET ((uint32_t)0xFFFFFFFF) +#define ALL_CLEAR 0 + +#define PTROF(X) ((BUFHEAD *)((ptrdiff_t)(X)&~0x3)) +#define ISMOD(X) ((uint32_t)(ptrdiff_t)(X)&0x1) +#define DOMOD(X) ((X) = (char *)((ptrdiff_t)(X)|0x1)) +#define ISDISK(X) ((uint32_t)(ptrdiff_t)(X)&0x2) +#define DODISK(X) ((X) = (char *)((ptrdiff_t)(X)|0x2)) + +#define BITS_PER_MAP 32 + +/* Given the address of the beginning of a big map, clear/set the nth bit */ +#define CLRBIT(A, N) ((A)[(N)/BITS_PER_MAP] &= ~(1<<((N)%BITS_PER_MAP))) +#define SETBIT(A, N) ((A)[(N)/BITS_PER_MAP] |= (1<<((N)%BITS_PER_MAP))) +#define ISSET(A, N) ((A)[(N)/BITS_PER_MAP] & (1<<((N)%BITS_PER_MAP))) + +/* Overflow management */ +/* + * Overflow page numbers are allocated per split point. At each doubling of + * the table, we can allocate extra pages. So, an overflow page number has + * the top 5 bits indicate which split point and the lower 11 bits indicate + * which page at that split point is indicated (pages within split points are + * numberered starting with 1). + */ + +#define SPLITSHIFT 11 +#define SPLITMASK 0x7FF +#define SPLITNUM(N) (((uint32_t)(N)) >> SPLITSHIFT) +#define OPAGENUM(N) ((N) & SPLITMASK) +#define OADDR_OF(S,O) ((uint32_t)((uint32_t)(S) << SPLITSHIFT) + (O)) + +#define BUCKET_TO_PAGE(B) \ + (B) + hashp->HDRPAGES + ((B) ? hashp->SPARES[__log2((B)+1)-1] : 0) +#define OADDR_TO_PAGE(B) \ + BUCKET_TO_PAGE ( (1 << SPLITNUM((B))) -1 ) + OPAGENUM((B)); + +/* + * page.h contains a detailed description of the page format. + * + * Normally, keys and data are accessed from offset tables in the top of + * each page which point to the beginning of the key and data. There are + * four flag values which may be stored in these offset tables which indicate + * the following: + * + * + * OVFLPAGE Rather than a key data pair, this pair contains + * the address of an overflow page. The format of + * the pair is: + * OVERFLOW_PAGE_NUMBER OVFLPAGE + * + * PARTIAL_KEY This must be the first key/data pair on a page + * and implies that page contains only a partial key. + * That is, the key is too big to fit on a single page + * so it starts on this page and continues on the next. + * The format of the page is: + * KEY_OFF PARTIAL_KEY OVFL_PAGENO OVFLPAGE + * + * KEY_OFF -- offset of the beginning of the key + * PARTIAL_KEY -- 1 + * OVFL_PAGENO - page number of the next overflow page + * OVFLPAGE -- 0 + * + * FULL_KEY This must be the first key/data pair on the page. It + * is used in two cases. + * + * Case 1: + * There is a complete key on the page but no data + * (because it wouldn't fit). The next page contains + * the data. + * + * Page format it: + * KEY_OFF FULL_KEY OVFL_PAGENO OVFL_PAGE + * + * KEY_OFF -- offset of the beginning of the key + * FULL_KEY -- 2 + * OVFL_PAGENO - page number of the next overflow page + * OVFLPAGE -- 0 + * + * Case 2: + * This page contains no key, but part of a large + * data field, which is continued on the next page. + * + * Page format it: + * DATA_OFF FULL_KEY OVFL_PAGENO OVFL_PAGE + * + * KEY_OFF -- offset of the beginning of the data on + * this page + * FULL_KEY -- 2 + * OVFL_PAGENO - page number of the next overflow page + * OVFLPAGE -- 0 + * + * FULL_KEY_DATA + * This must be the first key/data pair on the page. + * There are two cases: + * + * Case 1: + * This page contains a key and the beginning of the + * data field, but the data field is continued on the + * next page. + * + * Page format is: + * KEY_OFF FULL_KEY_DATA OVFL_PAGENO DATA_OFF + * + * KEY_OFF -- offset of the beginning of the key + * FULL_KEY_DATA -- 3 + * OVFL_PAGENO - page number of the next overflow page + * DATA_OFF -- offset of the beginning of the data + * + * Case 2: + * This page contains the last page of a big data pair. + * There is no key, only the tail end of the data + * on this page. + * + * Page format is: + * DATA_OFF FULL_KEY_DATA + * + * DATA_OFF -- offset of the beginning of the data on + * this page + * FULL_KEY_DATA -- 3 + * OVFL_PAGENO - page number of the next overflow page + * OVFLPAGE -- 0 + * + * OVFL_PAGENO and OVFLPAGE are optional (they are + * not present if there is no next page). + */ + +#define OVFLPAGE 0 +#define PARTIAL_KEY 1 +#define FULL_KEY 2 +#define FULL_KEY_DATA 3 +#define REAL_KEY 4 + +/* Short hands for accessing structure */ +#define BSIZE hdr.bsize +#define BSHIFT hdr.bshift +#define DSIZE hdr.dsize +#define SGSIZE hdr.ssize +#define SSHIFT hdr.sshift +#define LORDER hdr.lorder +#define OVFL_POINT hdr.ovfl_point +#define LAST_FREED hdr.last_freed +#define MAX_BUCKET hdr.max_bucket +#define FFACTOR hdr.ffactor +#define HIGH_MASK hdr.high_mask +#define LOW_MASK hdr.low_mask +#define NKEYS hdr.nkeys +#define HDRPAGES hdr.hdrpages +#define SPARES hdr.spares +#define BITMAPS hdr.bitmaps +#define VERSION hdr.version +#define MAGIC hdr.magic +#define NEXT_FREE hdr.next_free +#define H_CHARKEY hdr.h_charkey diff --git a/lib/libc/db/hash/hash_bigkey.c b/lib/libc/db/hash/hash_bigkey.c new file mode 100644 index 0000000..64b3e33 --- /dev/null +++ b/lib/libc/db/hash/hash_bigkey.c @@ -0,0 +1,670 @@ +/*- + * Copyright (c) 1990, 1993, 1994 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * Margo Seltzer. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)hash_bigkey.c 8.3 (Berkeley) 5/31/94"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/db/hash/hash_bigkey.c,v 1.5 2003/02/16 17:29:09 nectar Exp $"); + +/* + * PACKAGE: hash + * DESCRIPTION: + * Big key/data handling for the hashing package. + * + * ROUTINES: + * External + * __big_keydata + * __big_split + * __big_insert + * __big_return + * __big_delete + * __find_last_page + * Internal + * collect_key + * collect_data + */ + +#include + +#include +#include +#include +#include + +#ifdef DEBUG +#include +#endif + +#include +#include "hash.h" +#include "page.h" +#include "extern.h" + +static int collect_key(HTAB *, BUFHEAD *, int, DBT *, int); +static int collect_data(HTAB *, BUFHEAD *, int, int); + +/* + * Big_insert + * + * You need to do an insert and the key/data pair is too big + * + * Returns: + * 0 ==> OK + *-1 ==> ERROR + */ +extern int +__big_insert(hashp, bufp, key, val) + HTAB *hashp; + BUFHEAD *bufp; + const DBT *key, *val; +{ + u_int16_t *p; + int key_size, n, val_size; + u_int16_t space, move_bytes, off; + char *cp, *key_data, *val_data; + + cp = bufp->page; /* Character pointer of p. */ + p = (u_int16_t *)cp; + + key_data = (char *)key->data; + key_size = key->size; + val_data = (char *)val->data; + val_size = val->size; + + /* First move the Key */ + for (space = FREESPACE(p) - BIGOVERHEAD; key_size; + space = FREESPACE(p) - BIGOVERHEAD) { + move_bytes = MIN(space, key_size); + off = OFFSET(p) - move_bytes; + memmove(cp + off, key_data, move_bytes); + key_size -= move_bytes; + key_data += move_bytes; + n = p[0]; + p[++n] = off; + p[0] = ++n; + FREESPACE(p) = off - PAGE_META(n); + OFFSET(p) = off; + p[n] = PARTIAL_KEY; + bufp = __add_ovflpage(hashp, bufp); + if (!bufp) + return (-1); + n = p[0]; + if (!key_size) { + if (FREESPACE(p)) { + move_bytes = MIN(FREESPACE(p), val_size); + off = OFFSET(p) - move_bytes; + p[n] = off; + memmove(cp + off, val_data, move_bytes); + val_data += move_bytes; + val_size -= move_bytes; + p[n - 2] = FULL_KEY_DATA; + FREESPACE(p) = FREESPACE(p) - move_bytes; + OFFSET(p) = off; + } else + p[n - 2] = FULL_KEY; + } + p = (u_int16_t *)bufp->page; + cp = bufp->page; + bufp->flags |= BUF_MOD; + } + + /* Now move the data */ + for (space = FREESPACE(p) - BIGOVERHEAD; val_size; + space = FREESPACE(p) - BIGOVERHEAD) { + move_bytes = MIN(space, val_size); + /* + * Here's the hack to make sure that if the data ends on the + * same page as the key ends, FREESPACE is at least one. + */ + if (space == val_size && val_size == val->size) + move_bytes--; + off = OFFSET(p) - move_bytes; + memmove(cp + off, val_data, move_bytes); + val_size -= move_bytes; + val_data += move_bytes; + n = p[0]; + p[++n] = off; + p[0] = ++n; + FREESPACE(p) = off - PAGE_META(n); + OFFSET(p) = off; + if (val_size) { + p[n] = FULL_KEY; + bufp = __add_ovflpage(hashp, bufp); + if (!bufp) + return (-1); + cp = bufp->page; + p = (u_int16_t *)cp; + } else + p[n] = FULL_KEY_DATA; + bufp->flags |= BUF_MOD; + } + return (0); +} + +/* + * Called when bufp's page contains a partial key (index should be 1) + * + * All pages in the big key/data pair except bufp are freed. We cannot + * free bufp because the page pointing to it is lost and we can't get rid + * of its pointer. + * + * Returns: + * 0 => OK + *-1 => ERROR + */ +extern int +__big_delete(hashp, bufp) + HTAB *hashp; + BUFHEAD *bufp; +{ + BUFHEAD *last_bfp, *rbufp; + u_int16_t *bp, pageno; + int key_done, n; + + rbufp = bufp; + last_bfp = NULL; + bp = (u_int16_t *)bufp->page; + pageno = 0; + key_done = 0; + + while (!key_done || (bp[2] != FULL_KEY_DATA)) { + if (bp[2] == FULL_KEY || bp[2] == FULL_KEY_DATA) + key_done = 1; + + /* + * If there is freespace left on a FULL_KEY_DATA page, then + * the data is short and fits entirely on this page, and this + * is the last page. + */ + if (bp[2] == FULL_KEY_DATA && FREESPACE(bp)) + break; + pageno = bp[bp[0] - 1]; + rbufp->flags |= BUF_MOD; + rbufp = __get_buf(hashp, pageno, rbufp, 0); + if (last_bfp) + __free_ovflpage(hashp, last_bfp); + last_bfp = rbufp; + if (!rbufp) + return (-1); /* Error. */ + bp = (u_int16_t *)rbufp->page; + } + + /* + * If we get here then rbufp points to the last page of the big + * key/data pair. Bufp points to the first one -- it should now be + * empty pointing to the next page after this pair. Can't free it + * because we don't have the page pointing to it. + */ + + /* This is information from the last page of the pair. */ + n = bp[0]; + pageno = bp[n - 1]; + + /* Now, bp is the first page of the pair. */ + bp = (u_int16_t *)bufp->page; + if (n > 2) { + /* There is an overflow page. */ + bp[1] = pageno; + bp[2] = OVFLPAGE; + bufp->ovfl = rbufp->ovfl; + } else + /* This is the last page. */ + bufp->ovfl = NULL; + n -= 2; + bp[0] = n; + FREESPACE(bp) = hashp->BSIZE - PAGE_META(n); + OFFSET(bp) = hashp->BSIZE - 1; + + bufp->flags |= BUF_MOD; + if (rbufp) + __free_ovflpage(hashp, rbufp); + if (last_bfp != rbufp) + __free_ovflpage(hashp, last_bfp); + + hashp->NKEYS--; + return (0); +} +/* + * Returns: + * 0 = key not found + * -1 = get next overflow page + * -2 means key not found and this is big key/data + * -3 error + */ +extern int +__find_bigpair(hashp, bufp, ndx, key, size) + HTAB *hashp; + BUFHEAD *bufp; + int ndx; + char *key; + int size; +{ + u_int16_t *bp; + char *p; + int ksize; + u_int16_t bytes; + char *kkey; + + bp = (u_int16_t *)bufp->page; + p = bufp->page; + ksize = size; + kkey = key; + + for (bytes = hashp->BSIZE - bp[ndx]; + bytes <= size && bp[ndx + 1] == PARTIAL_KEY; + bytes = hashp->BSIZE - bp[ndx]) { + if (memcmp(p + bp[ndx], kkey, bytes)) + return (-2); + kkey += bytes; + ksize -= bytes; + bufp = __get_buf(hashp, bp[ndx + 2], bufp, 0); + if (!bufp) + return (-3); + p = bufp->page; + bp = (u_int16_t *)p; + ndx = 1; + } + + if (bytes != ksize || memcmp(p + bp[ndx], kkey, bytes)) { +#ifdef HASH_STATISTICS + ++hash_collisions; +#endif + return (-2); + } else + return (ndx); +} + +/* + * Given the buffer pointer of the first overflow page of a big pair, + * find the end of the big pair + * + * This will set bpp to the buffer header of the last page of the big pair. + * It will return the pageno of the overflow page following the last page + * of the pair; 0 if there isn't any (i.e. big pair is the last key in the + * bucket) + */ +extern u_int16_t +__find_last_page(hashp, bpp) + HTAB *hashp; + BUFHEAD **bpp; +{ + BUFHEAD *bufp; + u_int16_t *bp, pageno; + int n; + + bufp = *bpp; + bp = (u_int16_t *)bufp->page; + for (;;) { + n = bp[0]; + + /* + * This is the last page if: the tag is FULL_KEY_DATA and + * either only 2 entries OVFLPAGE marker is explicit there + * is freespace on the page. + */ + if (bp[2] == FULL_KEY_DATA && + ((n == 2) || (bp[n] == OVFLPAGE) || (FREESPACE(bp)))) + break; + + pageno = bp[n - 1]; + bufp = __get_buf(hashp, pageno, bufp, 0); + if (!bufp) + return (0); /* Need to indicate an error! */ + bp = (u_int16_t *)bufp->page; + } + + *bpp = bufp; + if (bp[0] > 2) + return (bp[3]); + else + return (0); +} + +/* + * Return the data for the key/data pair that begins on this page at this + * index (index should always be 1). + */ +extern int +__big_return(hashp, bufp, ndx, val, set_current) + HTAB *hashp; + BUFHEAD *bufp; + int ndx; + DBT *val; + int set_current; +{ + BUFHEAD *save_p; + u_int16_t *bp, len, off, save_addr; + char *tp; + + bp = (u_int16_t *)bufp->page; + while (bp[ndx + 1] == PARTIAL_KEY) { + bufp = __get_buf(hashp, bp[bp[0] - 1], bufp, 0); + if (!bufp) + return (-1); + bp = (u_int16_t *)bufp->page; + ndx = 1; + } + + if (bp[ndx + 1] == FULL_KEY) { + bufp = __get_buf(hashp, bp[bp[0] - 1], bufp, 0); + if (!bufp) + return (-1); + bp = (u_int16_t *)bufp->page; + save_p = bufp; + save_addr = save_p->addr; + off = bp[1]; + len = 0; + } else + if (!FREESPACE(bp)) { + /* + * This is a hack. We can't distinguish between + * FULL_KEY_DATA that contains complete data or + * incomplete data, so we require that if the data + * is complete, there is at least 1 byte of free + * space left. + */ + off = bp[bp[0]]; + len = bp[1] - off; + save_p = bufp; + save_addr = bufp->addr; + bufp = __get_buf(hashp, bp[bp[0] - 1], bufp, 0); + if (!bufp) + return (-1); + bp = (u_int16_t *)bufp->page; + } else { + /* The data is all on one page. */ + tp = (char *)bp; + off = bp[bp[0]]; + val->data = (u_char *)tp + off; + val->size = bp[1] - off; + if (set_current) { + if (bp[0] == 2) { /* No more buckets in + * chain */ + hashp->cpage = NULL; + hashp->cbucket++; + hashp->cndx = 1; + } else { + hashp->cpage = __get_buf(hashp, + bp[bp[0] - 1], bufp, 0); + if (!hashp->cpage) + return (-1); + hashp->cndx = 1; + if (!((u_int16_t *) + hashp->cpage->page)[0]) { + hashp->cbucket++; + hashp->cpage = NULL; + } + } + } + return (0); + } + + val->size = collect_data(hashp, bufp, (int)len, set_current); + if (val->size == -1) + return (-1); + if (save_p->addr != save_addr) { + /* We are pretty short on buffers. */ + errno = EINVAL; /* OUT OF BUFFERS */ + return (-1); + } + memmove(hashp->tmp_buf, (save_p->page) + off, len); + val->data = (u_char *)hashp->tmp_buf; + return (0); +} +/* + * Count how big the total datasize is by recursing through the pages. Then + * allocate a buffer and copy the data as you recurse up. + */ +static int +collect_data(hashp, bufp, len, set) + HTAB *hashp; + BUFHEAD *bufp; + int len, set; +{ + u_int16_t *bp; + char *p; + BUFHEAD *xbp; + u_int16_t save_addr; + int mylen, totlen; + + p = bufp->page; + bp = (u_int16_t *)p; + mylen = hashp->BSIZE - bp[1]; + save_addr = bufp->addr; + + if (bp[2] == FULL_KEY_DATA) { /* End of Data */ + totlen = len + mylen; + if (hashp->tmp_buf) + free(hashp->tmp_buf); + if ((hashp->tmp_buf = (char *)malloc(totlen)) == NULL) + return (-1); + if (set) { + hashp->cndx = 1; + if (bp[0] == 2) { /* No more buckets in chain */ + hashp->cpage = NULL; + hashp->cbucket++; + } else { + hashp->cpage = + __get_buf(hashp, bp[bp[0] - 1], bufp, 0); + if (!hashp->cpage) + return (-1); + else if (!((u_int16_t *)hashp->cpage->page)[0]) { + hashp->cbucket++; + hashp->cpage = NULL; + } + } + } + } else { + xbp = __get_buf(hashp, bp[bp[0] - 1], bufp, 0); + if (!xbp || ((totlen = + collect_data(hashp, xbp, len + mylen, set)) < 1)) + return (-1); + } + if (bufp->addr != save_addr) { + errno = EINVAL; /* Out of buffers. */ + return (-1); + } + memmove(&hashp->tmp_buf[len], (bufp->page) + bp[1], mylen); + return (totlen); +} + +/* + * Fill in the key and data for this big pair. + */ +extern int +__big_keydata(hashp, bufp, key, val, set) + HTAB *hashp; + BUFHEAD *bufp; + DBT *key, *val; + int set; +{ + key->size = collect_key(hashp, bufp, 0, val, set); + if (key->size == -1) + return (-1); + key->data = (u_char *)hashp->tmp_key; + return (0); +} + +/* + * Count how big the total key size is by recursing through the pages. Then + * collect the data, allocate a buffer and copy the key as you recurse up. + */ +static int +collect_key(hashp, bufp, len, val, set) + HTAB *hashp; + BUFHEAD *bufp; + int len; + DBT *val; + int set; +{ + BUFHEAD *xbp; + char *p; + int mylen, totlen; + u_int16_t *bp, save_addr; + + p = bufp->page; + bp = (u_int16_t *)p; + mylen = hashp->BSIZE - bp[1]; + + save_addr = bufp->addr; + totlen = len + mylen; + if (bp[2] == FULL_KEY || bp[2] == FULL_KEY_DATA) { /* End of Key. */ + if (hashp->tmp_key != NULL) + free(hashp->tmp_key); + if ((hashp->tmp_key = (char *)malloc(totlen)) == NULL) + return (-1); + if (__big_return(hashp, bufp, 1, val, set)) + return (-1); + } else { + xbp = __get_buf(hashp, bp[bp[0] - 1], bufp, 0); + if (!xbp || ((totlen = + collect_key(hashp, xbp, totlen, val, set)) < 1)) + return (-1); + } + if (bufp->addr != save_addr) { + errno = EINVAL; /* MIS -- OUT OF BUFFERS */ + return (-1); + } + memmove(&hashp->tmp_key[len], (bufp->page) + bp[1], mylen); + return (totlen); +} + +/* + * Returns: + * 0 => OK + * -1 => error + */ +extern int +__big_split(hashp, op, np, big_keyp, addr, obucket, ret) + HTAB *hashp; + BUFHEAD *op; /* Pointer to where to put keys that go in old bucket */ + BUFHEAD *np; /* Pointer to new bucket page */ + /* Pointer to first page containing the big key/data */ + BUFHEAD *big_keyp; + int addr; /* Address of big_keyp */ + uint32_t obucket;/* Old Bucket */ + SPLIT_RETURN *ret; +{ + BUFHEAD *tmpp; + u_int16_t *tp; + BUFHEAD *bp; + DBT key, val; + uint32_t change; + u_int16_t free_space, n, off; + + bp = big_keyp; + + /* Now figure out where the big key/data goes */ + if (__big_keydata(hashp, big_keyp, &key, &val, 0)) + return (-1); + change = (__call_hash(hashp, key.data, key.size) != obucket); + + if ( (ret->next_addr = __find_last_page(hashp, &big_keyp)) ) { + if (!(ret->nextp = + __get_buf(hashp, ret->next_addr, big_keyp, 0))) + return (-1);; + } else + ret->nextp = NULL; + + /* Now make one of np/op point to the big key/data pair */ +#ifdef DEBUG + assert(np->ovfl == NULL); +#endif + if (change) + tmpp = np; + else + tmpp = op; + + tmpp->flags |= BUF_MOD; +#ifdef DEBUG1 + (void)fprintf(stderr, + "BIG_SPLIT: %d->ovfl was %d is now %d\n", tmpp->addr, + (tmpp->ovfl ? tmpp->ovfl->addr : 0), (bp ? bp->addr : 0)); +#endif + tmpp->ovfl = bp; /* one of op/np point to big_keyp */ + tp = (u_int16_t *)tmpp->page; +#ifdef DEBUG + assert(FREESPACE(tp) >= OVFLSIZE); +#endif + n = tp[0]; + off = OFFSET(tp); + free_space = FREESPACE(tp); + tp[++n] = (u_int16_t)addr; + tp[++n] = OVFLPAGE; + tp[0] = n; + OFFSET(tp) = off; + FREESPACE(tp) = free_space - OVFLSIZE; + + /* + * Finally, set the new and old return values. BIG_KEYP contains a + * pointer to the last page of the big key_data pair. Make sure that + * big_keyp has no following page (2 elements) or create an empty + * following page. + */ + + ret->newp = np; + ret->oldp = op; + + tp = (u_int16_t *)big_keyp->page; + big_keyp->flags |= BUF_MOD; + if (tp[0] > 2) { + /* + * There may be either one or two offsets on this page. If + * there is one, then the overflow page is linked on normally + * and tp[4] is OVFLPAGE. If there are two, tp[4] contains + * the second offset and needs to get stuffed in after the + * next overflow page is added. + */ + n = tp[4]; + free_space = FREESPACE(tp); + off = OFFSET(tp); + tp[0] -= 2; + FREESPACE(tp) = free_space + OVFLSIZE; + OFFSET(tp) = off; + tmpp = __add_ovflpage(hashp, big_keyp); + if (!tmpp) + return (-1); + tp[4] = n; + } else + tmpp = big_keyp; + + if (change) + ret->newp = tmpp; + else + ret->oldp = tmpp; + return (0); +} diff --git a/lib/libc/db/hash/hash_buf.c b/lib/libc/db/hash/hash_buf.c new file mode 100644 index 0000000..5908723 --- /dev/null +++ b/lib/libc/db/hash/hash_buf.c @@ -0,0 +1,356 @@ +/*- + * Copyright (c) 1990, 1993, 1994 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * Margo Seltzer. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)hash_buf.c 8.5 (Berkeley) 7/15/94"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/db/hash/hash_buf.c,v 1.7 2002/03/21 22:46:26 obrien Exp $"); + +/* + * PACKAGE: hash + * + * DESCRIPTION: + * Contains buffer management + * + * ROUTINES: + * External + * __buf_init + * __get_buf + * __buf_free + * __reclaim_buf + * Internal + * newbuf + */ + +#include + +#include +#include +#include + +#ifdef DEBUG +#include +#endif + +#include +#include "hash.h" +#include "page.h" +#include "extern.h" + +static BUFHEAD *newbuf(HTAB *, uint32_t, BUFHEAD *); + +/* Unlink B from its place in the lru */ +#define BUF_REMOVE(B) { \ + (B)->prev->next = (B)->next; \ + (B)->next->prev = (B)->prev; \ +} + +/* Insert B after P */ +#define BUF_INSERT(B, P) { \ + (B)->next = (P)->next; \ + (B)->prev = (P); \ + (P)->next = (B); \ + (B)->next->prev = (B); \ +} + +#define MRU hashp->bufhead.next +#define LRU hashp->bufhead.prev + +#define MRU_INSERT(B) BUF_INSERT((B), &hashp->bufhead) +#define LRU_INSERT(B) BUF_INSERT((B), LRU) + +/* + * We are looking for a buffer with address "addr". If prev_bp is NULL, then + * address is a bucket index. If prev_bp is not NULL, then it points to the + * page previous to an overflow page that we are trying to find. + * + * CAVEAT: The buffer header accessed via prev_bp's ovfl field may no longer + * be valid. Therefore, you must always verify that its address matches the + * address you are seeking. + */ +extern BUFHEAD * +__get_buf(hashp, addr, prev_bp, newpage) + HTAB *hashp; + uint32_t addr; + BUFHEAD *prev_bp; + int newpage; /* If prev_bp set, indicates a new overflow page. */ +{ + BUFHEAD *bp; + uint32_t is_disk_mask; + int is_disk, segment_ndx; + SEGMENT segp; + + is_disk = 0; + is_disk_mask = 0; + if (prev_bp) { + bp = prev_bp->ovfl; + if (!bp || (bp->addr != addr)) + bp = NULL; + if (!newpage) + is_disk = BUF_DISK; + } else { + /* Grab buffer out of directory */ + segment_ndx = addr & (hashp->SGSIZE - 1); + + /* valid segment ensured by __call_hash() */ + segp = hashp->dir[addr >> hashp->SSHIFT]; +#ifdef DEBUG + assert(segp != NULL); +#endif + bp = PTROF(segp[segment_ndx]); + is_disk_mask = ISDISK(segp[segment_ndx]); + is_disk = is_disk_mask || !hashp->new_file; + } + + if (!bp) { + bp = newbuf(hashp, addr, prev_bp); + if (!bp || + __get_page(hashp, bp->page, addr, !prev_bp, is_disk, 0)) + return (NULL); + if (!prev_bp) + segp[segment_ndx] = + (BUFHEAD *)((ptrdiff_t)bp | is_disk_mask); + } else { + BUF_REMOVE(bp); + MRU_INSERT(bp); + } + return (bp); +} + +/* + * We need a buffer for this page. Either allocate one, or evict a resident + * one (if we have as many buffers as we're allowed) and put this one in. + * + * If newbuf finds an error (returning NULL), it also sets errno. + */ +static BUFHEAD * +newbuf(hashp, addr, prev_bp) + HTAB *hashp; + uint32_t addr; + BUFHEAD *prev_bp; +{ + BUFHEAD *bp; /* The buffer we're going to use */ + BUFHEAD *xbp; /* Temp pointer */ + BUFHEAD *next_xbp; + SEGMENT segp; + int segment_ndx; + u_int16_t oaddr, *shortp; + + oaddr = 0; + bp = LRU; + /* + * If LRU buffer is pinned, the buffer pool is too small. We need to + * allocate more buffers. + */ + if (hashp->nbufs || (bp->flags & BUF_PIN)) { + /* Allocate a new one */ + if ((bp = (BUFHEAD *)malloc(sizeof(BUFHEAD))) == NULL) + return (NULL); +#ifdef PURIFY + memset(bp, 0xff, sizeof(BUFHEAD)); +#endif + if ((bp->page = (char *)malloc(hashp->BSIZE)) == NULL) { + free(bp); + return (NULL); + } +#ifdef PURIFY + memset(bp->page, 0xff, hashp->BSIZE); +#endif + if (hashp->nbufs) + hashp->nbufs--; + } else { + /* Kick someone out */ + BUF_REMOVE(bp); + /* + * If this is an overflow page with addr 0, it's already been + * flushed back in an overflow chain and initialized. + */ + if ((bp->addr != 0) || (bp->flags & BUF_BUCKET)) { + /* + * Set oaddr before __put_page so that you get it + * before bytes are swapped. + */ + shortp = (u_int16_t *)bp->page; + if (shortp[0]) + oaddr = shortp[shortp[0] - 1]; + if ((bp->flags & BUF_MOD) && __put_page(hashp, bp->page, + bp->addr, (int)IS_BUCKET(bp->flags), 0)) + return (NULL); + /* + * Update the pointer to this page (i.e. invalidate it). + * + * If this is a new file (i.e. we created it at open + * time), make sure that we mark pages which have been + * written to disk so we retrieve them from disk later, + * rather than allocating new pages. + */ + if (IS_BUCKET(bp->flags)) { + segment_ndx = bp->addr & (hashp->SGSIZE - 1); + segp = hashp->dir[bp->addr >> hashp->SSHIFT]; +#ifdef DEBUG + assert(segp != NULL); +#endif + + if (hashp->new_file && + ((bp->flags & BUF_MOD) || + ISDISK(segp[segment_ndx]))) + segp[segment_ndx] = (BUFHEAD *)BUF_DISK; + else + segp[segment_ndx] = NULL; + } + /* + * Since overflow pages can only be access by means of + * their bucket, free overflow pages associated with + * this bucket. + */ + for (xbp = bp; xbp->ovfl;) { + next_xbp = xbp->ovfl; + xbp->ovfl = 0; + xbp = next_xbp; + + /* Check that ovfl pointer is up date. */ + if (IS_BUCKET(xbp->flags) || + (oaddr != xbp->addr)) + break; + + shortp = (u_int16_t *)xbp->page; + if (shortp[0]) + /* set before __put_page */ + oaddr = shortp[shortp[0] - 1]; + if ((xbp->flags & BUF_MOD) && __put_page(hashp, + xbp->page, xbp->addr, 0, 0)) + return (NULL); + xbp->addr = 0; + xbp->flags = 0; + BUF_REMOVE(xbp); + LRU_INSERT(xbp); + } + } + } + + /* Now assign this buffer */ + bp->addr = addr; +#ifdef DEBUG1 + (void)fprintf(stderr, "NEWBUF1: %d->ovfl was %d is now %d\n", + bp->addr, (bp->ovfl ? bp->ovfl->addr : 0), 0); +#endif + bp->ovfl = NULL; + if (prev_bp) { + /* + * If prev_bp is set, this is an overflow page, hook it in to + * the buffer overflow links. + */ +#ifdef DEBUG1 + (void)fprintf(stderr, "NEWBUF2: %d->ovfl was %d is now %d\n", + prev_bp->addr, (prev_bp->ovfl ? bp->ovfl->addr : 0), + (bp ? bp->addr : 0)); +#endif + prev_bp->ovfl = bp; + bp->flags = 0; + } else + bp->flags = BUF_BUCKET; + MRU_INSERT(bp); + return (bp); +} + +extern void +__buf_init(hashp, nbytes) + HTAB *hashp; + int nbytes; +{ + BUFHEAD *bfp; + int npages; + + bfp = &(hashp->bufhead); + npages = (nbytes + hashp->BSIZE - 1) >> hashp->BSHIFT; + npages = MAX(npages, MIN_BUFFERS); + + hashp->nbufs = npages; + bfp->next = bfp; + bfp->prev = bfp; + /* + * This space is calloc'd so these are already null. + * + * bfp->ovfl = NULL; + * bfp->flags = 0; + * bfp->page = NULL; + * bfp->addr = 0; + */ +} + +extern int +__buf_free(hashp, do_free, to_disk) + HTAB *hashp; + int do_free, to_disk; +{ + BUFHEAD *bp; + + /* Need to make sure that buffer manager has been initialized */ + if (!LRU) + return (0); + for (bp = LRU; bp != &hashp->bufhead;) { + /* Check that the buffer is valid */ + if (bp->addr || IS_BUCKET(bp->flags)) { + if (to_disk && (bp->flags & BUF_MOD) && + __put_page(hashp, bp->page, + bp->addr, IS_BUCKET(bp->flags), 0)) + return (-1); + } + /* Check if we are freeing stuff */ + if (do_free) { + if (bp->page) + free(bp->page); + BUF_REMOVE(bp); + free(bp); + bp = LRU; + } else + bp = bp->prev; + } + return (0); +} + +extern void +__reclaim_buf(hashp, bp) + HTAB *hashp; + BUFHEAD *bp; +{ + bp->ovfl = 0; + bp->addr = 0; + bp->flags = 0; + BUF_REMOVE(bp); + LRU_INSERT(bp); +} diff --git a/lib/libc/db/hash/hash_func.c b/lib/libc/db/hash/hash_func.c new file mode 100644 index 0000000..afa66a0 --- /dev/null +++ b/lib/libc/db/hash/hash_func.c @@ -0,0 +1,214 @@ +/*- + * Copyright (c) 1990, 1993 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * Margo Seltzer. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)hash_func.c 8.2 (Berkeley) 2/21/94"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/db/hash/hash_func.c,v 1.5 2003/02/16 17:29:09 nectar Exp $"); + +#include + +#include +#include "hash.h" +#include "page.h" +#include "extern.h" + +static uint32_t hash1(const void *, size_t) __unused; +static uint32_t hash2(const void *, size_t) __unused; +static uint32_t hash3(const void *, size_t) __unused; +static uint32_t hash4(const void *, size_t); + +/* Global default hash function */ +uint32_t (*__default_hash)(const void *, size_t) = hash4; + +/* + * HASH FUNCTIONS + * + * Assume that we've already split the bucket to which this key hashes, + * calculate that bucket, and check that in fact we did already split it. + * + * This came from ejb's hsearch. + */ + +#define PRIME1 37 +#define PRIME2 1048583 + +static uint32_t +hash1(keyarg, len) + const void *keyarg; + size_t len; +{ + const u_char *key; + uint32_t h; + + /* Convert string to integer */ + for (key = keyarg, h = 0; len--;) + h = h * PRIME1 ^ (*key++ - ' '); + h %= PRIME2; + return (h); +} + +/* + * Phong's linear congruential hash + */ +#define dcharhash(h, c) ((h) = 0x63c63cd9*(h) + 0x9c39c33d + (c)) + +static uint32_t +hash2(keyarg, len) + const void *keyarg; + size_t len; +{ + const u_char *e, *key; + uint32_t h; + u_char c; + + key = keyarg; + e = key + len; + for (h = 0; key != e;) { + c = *key++; + if (!c && key > e) + break; + dcharhash(h, c); + } + return (h); +} + +/* + * This is INCREDIBLY ugly, but fast. We break the string up into 8 byte + * units. On the first time through the loop we get the "leftover bytes" + * (strlen % 8). On every other iteration, we perform 8 HASHC's so we handle + * all 8 bytes. Essentially, this saves us 7 cmp & branch instructions. If + * this routine is heavily used enough, it's worth the ugly coding. + * + * OZ's original sdbm hash + */ +static uint32_t +hash3(keyarg, len) + const void *keyarg; + size_t len; +{ + const u_char *key; + size_t loop; + uint32_t h; + +#define HASHC h = *key++ + 65599 * h + + h = 0; + key = keyarg; + if (len > 0) { + loop = (len + 8 - 1) >> 3; + + switch (len & (8 - 1)) { + case 0: + do { + HASHC; + /* FALLTHROUGH */ + case 7: + HASHC; + /* FALLTHROUGH */ + case 6: + HASHC; + /* FALLTHROUGH */ + case 5: + HASHC; + /* FALLTHROUGH */ + case 4: + HASHC; + /* FALLTHROUGH */ + case 3: + HASHC; + /* FALLTHROUGH */ + case 2: + HASHC; + /* FALLTHROUGH */ + case 1: + HASHC; + } while (--loop); + } + } + return (h); +} + +/* Hash function from Chris Torek. */ +static uint32_t +hash4(keyarg, len) + const void *keyarg; + size_t len; +{ + const u_char *key; + size_t loop; + uint32_t h; + +#define HASH4a h = (h << 5) - h + *key++; +#define HASH4b h = (h << 5) + h + *key++; +#define HASH4 HASH4b + + h = 0; + key = keyarg; + if (len > 0) { + loop = (len + 8 - 1) >> 3; + + switch (len & (8 - 1)) { + case 0: + do { + HASH4; + /* FALLTHROUGH */ + case 7: + HASH4; + /* FALLTHROUGH */ + case 6: + HASH4; + /* FALLTHROUGH */ + case 5: + HASH4; + /* FALLTHROUGH */ + case 4: + HASH4; + /* FALLTHROUGH */ + case 3: + HASH4; + /* FALLTHROUGH */ + case 2: + HASH4; + /* FALLTHROUGH */ + case 1: + HASH4; + } while (--loop); + } + } + return (h); +} diff --git a/lib/libc/db/hash/hash_log2.c b/lib/libc/db/hash/hash_log2.c new file mode 100644 index 0000000..88f307e --- /dev/null +++ b/lib/libc/db/hash/hash_log2.c @@ -0,0 +1,56 @@ +/*- + * Copyright (c) 1990, 1993, 1994 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * Margo Seltzer. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)hash_log2.c 8.2 (Berkeley) 5/31/94"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/db/hash/hash_log2.c,v 1.2 2002/03/21 18:47:38 obrien Exp $"); + +#include + +#include + +uint32_t +__log2(num) + uint32_t num; +{ + uint32_t i, limit; + + limit = 1; + for (i = 0; limit < num; limit = limit << 1, i++); + return (i); +} diff --git a/lib/libc/db/hash/hash_page.c b/lib/libc/db/hash/hash_page.c new file mode 100644 index 0000000..c98d82a --- /dev/null +++ b/lib/libc/db/hash/hash_page.c @@ -0,0 +1,948 @@ +/*- + * Copyright (c) 1990, 1993, 1994 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * Margo Seltzer. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)hash_page.c 8.7 (Berkeley) 8/16/94"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/db/hash/hash_page.c,v 1.8 2002/03/21 22:46:26 obrien Exp $"); + +/* + * PACKAGE: hashing + * + * DESCRIPTION: + * Page manipulation for hashing package. + * + * ROUTINES: + * + * External + * __get_page + * __add_ovflpage + * Internal + * overflow_page + * open_temp + */ + +#include "namespace.h" +#include + +#include +#include +#include +#include +#include +#include +#include +#ifdef DEBUG +#include +#endif +#include "un-namespace.h" + +#include +#include "hash.h" +#include "page.h" +#include "extern.h" + +static uint32_t *fetch_bitmap(HTAB *, int); +static uint32_t first_free(uint32_t); +static int open_temp(HTAB *); +static u_int16_t overflow_page(HTAB *); +static void putpair(char *, const DBT *, const DBT *); +static void squeeze_key(u_int16_t *, const DBT *, const DBT *); +static int ugly_split +(HTAB *, uint32_t, BUFHEAD *, BUFHEAD *, int, int); + +#define PAGE_INIT(P) { \ + ((u_int16_t *)(P))[0] = 0; \ + ((u_int16_t *)(P))[1] = hashp->BSIZE - 3 * sizeof(u_int16_t); \ + ((u_int16_t *)(P))[2] = hashp->BSIZE; \ +} + +/* + * This is called AFTER we have verified that there is room on the page for + * the pair (PAIRFITS has returned true) so we go right ahead and start moving + * stuff on. + */ +static void +putpair(p, key, val) + char *p; + const DBT *key, *val; +{ + u_int16_t *bp, n, off; + + bp = (u_int16_t *)p; + + /* Enter the key first. */ + n = bp[0]; + + off = OFFSET(bp) - key->size; + memmove(p + off, key->data, key->size); + bp[++n] = off; + + /* Now the data. */ + off -= val->size; + memmove(p + off, val->data, val->size); + bp[++n] = off; + + /* Adjust page info. */ + bp[0] = n; + bp[n + 1] = off - ((n + 3) * sizeof(u_int16_t)); + bp[n + 2] = off; +} + +/* + * Returns: + * 0 OK + * -1 error + */ +extern int +__delpair(hashp, bufp, ndx) + HTAB *hashp; + BUFHEAD *bufp; + int ndx; +{ + u_int16_t *bp, newoff; + int n; + u_int16_t pairlen; + + bp = (u_int16_t *)bufp->page; + n = bp[0]; + + if (bp[ndx + 1] < REAL_KEY) + return (__big_delete(hashp, bufp)); + if (ndx != 1) + newoff = bp[ndx - 1]; + else + newoff = hashp->BSIZE; + pairlen = newoff - bp[ndx + 1]; + + if (ndx != (n - 1)) { + /* Hard Case -- need to shuffle keys */ + int i; + char *src = bufp->page + (int)OFFSET(bp); + char *dst = src + (int)pairlen; + memmove(dst, src, bp[ndx + 1] - OFFSET(bp)); + + /* Now adjust the pointers */ + for (i = ndx + 2; i <= n; i += 2) { + if (bp[i + 1] == OVFLPAGE) { + bp[i - 2] = bp[i]; + bp[i - 1] = bp[i + 1]; + } else { + bp[i - 2] = bp[i] + pairlen; + bp[i - 1] = bp[i + 1] + pairlen; + } + } + } + /* Finally adjust the page data */ + bp[n] = OFFSET(bp) + pairlen; + bp[n - 1] = bp[n + 1] + pairlen + 2 * sizeof(u_int16_t); + bp[0] = n - 2; + hashp->NKEYS--; + + bufp->flags |= BUF_MOD; + return (0); +} +/* + * Returns: + * 0 ==> OK + * -1 ==> Error + */ +extern int +__split_page(hashp, obucket, nbucket) + HTAB *hashp; + uint32_t obucket, nbucket; +{ + BUFHEAD *new_bufp, *old_bufp; + u_int16_t *ino; + char *np; + DBT key, val; + int n, ndx, retval; + u_int16_t copyto, diff, off, moved; + char *op; + + copyto = (u_int16_t)hashp->BSIZE; + off = (u_int16_t)hashp->BSIZE; + old_bufp = __get_buf(hashp, obucket, NULL, 0); + if (old_bufp == NULL) + return (-1); + new_bufp = __get_buf(hashp, nbucket, NULL, 0); + if (new_bufp == NULL) + return (-1); + + old_bufp->flags |= (BUF_MOD | BUF_PIN); + new_bufp->flags |= (BUF_MOD | BUF_PIN); + + ino = (u_int16_t *)(op = old_bufp->page); + np = new_bufp->page; + + moved = 0; + + for (n = 1, ndx = 1; n < ino[0]; n += 2) { + if (ino[n + 1] < REAL_KEY) { + retval = ugly_split(hashp, obucket, old_bufp, new_bufp, + (int)copyto, (int)moved); + old_bufp->flags &= ~BUF_PIN; + new_bufp->flags &= ~BUF_PIN; + return (retval); + + } + key.data = (u_char *)op + ino[n]; + key.size = off - ino[n]; + + if (__call_hash(hashp, key.data, key.size) == obucket) { + /* Don't switch page */ + diff = copyto - off; + if (diff) { + copyto = ino[n + 1] + diff; + memmove(op + copyto, op + ino[n + 1], + off - ino[n + 1]); + ino[ndx] = copyto + ino[n] - ino[n + 1]; + ino[ndx + 1] = copyto; + } else + copyto = ino[n + 1]; + ndx += 2; + } else { + /* Switch page */ + val.data = (u_char *)op + ino[n + 1]; + val.size = ino[n] - ino[n + 1]; + putpair(np, &key, &val); + moved += 2; + } + + off = ino[n + 1]; + } + + /* Now clean up the page */ + ino[0] -= moved; + FREESPACE(ino) = copyto - sizeof(u_int16_t) * (ino[0] + 3); + OFFSET(ino) = copyto; + +#ifdef DEBUG3 + (void)fprintf(stderr, "split %d/%d\n", + ((u_int16_t *)np)[0] / 2, + ((u_int16_t *)op)[0] / 2); +#endif + /* unpin both pages */ + old_bufp->flags &= ~BUF_PIN; + new_bufp->flags &= ~BUF_PIN; + return (0); +} + +/* + * Called when we encounter an overflow or big key/data page during split + * handling. This is special cased since we have to begin checking whether + * the key/data pairs fit on their respective pages and because we may need + * overflow pages for both the old and new pages. + * + * The first page might be a page with regular key/data pairs in which case + * we have a regular overflow condition and just need to go on to the next + * page or it might be a big key/data pair in which case we need to fix the + * big key/data pair. + * + * Returns: + * 0 ==> success + * -1 ==> failure + */ +static int +ugly_split(hashp, obucket, old_bufp, new_bufp, copyto, moved) + HTAB *hashp; + uint32_t obucket; /* Same as __split_page. */ + BUFHEAD *old_bufp, *new_bufp; + int copyto; /* First byte on page which contains key/data values. */ + int moved; /* Number of pairs moved to new page. */ +{ + BUFHEAD *bufp; /* Buffer header for ino */ + u_int16_t *ino; /* Page keys come off of */ + u_int16_t *np; /* New page */ + u_int16_t *op; /* Page keys go on to if they aren't moving */ + + BUFHEAD *last_bfp; /* Last buf header OVFL needing to be freed */ + DBT key, val; + SPLIT_RETURN ret; + u_int16_t n, off, ov_addr, scopyto; + char *cino; /* Character value of ino */ + + bufp = old_bufp; + ino = (u_int16_t *)old_bufp->page; + np = (u_int16_t *)new_bufp->page; + op = (u_int16_t *)old_bufp->page; + last_bfp = NULL; + scopyto = (u_int16_t)copyto; /* ANSI */ + + n = ino[0] - 1; + while (n < ino[0]) { + if (ino[2] < REAL_KEY && ino[2] != OVFLPAGE) { + if (__big_split(hashp, old_bufp, + new_bufp, bufp, bufp->addr, obucket, &ret)) + return (-1); + old_bufp = ret.oldp; + if (!old_bufp) + return (-1); + op = (u_int16_t *)old_bufp->page; + new_bufp = ret.newp; + if (!new_bufp) + return (-1); + np = (u_int16_t *)new_bufp->page; + bufp = ret.nextp; + if (!bufp) + return (0); + cino = (char *)bufp->page; + ino = (u_int16_t *)cino; + last_bfp = ret.nextp; + } else if (ino[n + 1] == OVFLPAGE) { + ov_addr = ino[n]; + /* + * Fix up the old page -- the extra 2 are the fields + * which contained the overflow information. + */ + ino[0] -= (moved + 2); + FREESPACE(ino) = + scopyto - sizeof(u_int16_t) * (ino[0] + 3); + OFFSET(ino) = scopyto; + + bufp = __get_buf(hashp, ov_addr, bufp, 0); + if (!bufp) + return (-1); + + ino = (u_int16_t *)bufp->page; + n = 1; + scopyto = hashp->BSIZE; + moved = 0; + + if (last_bfp) + __free_ovflpage(hashp, last_bfp); + last_bfp = bufp; + } + /* Move regular sized pairs of there are any */ + off = hashp->BSIZE; + for (n = 1; (n < ino[0]) && (ino[n + 1] >= REAL_KEY); n += 2) { + cino = (char *)ino; + key.data = (u_char *)cino + ino[n]; + key.size = off - ino[n]; + val.data = (u_char *)cino + ino[n + 1]; + val.size = ino[n] - ino[n + 1]; + off = ino[n + 1]; + + if (__call_hash(hashp, key.data, key.size) == obucket) { + /* Keep on old page */ + if (PAIRFITS(op, (&key), (&val))) + putpair((char *)op, &key, &val); + else { + old_bufp = + __add_ovflpage(hashp, old_bufp); + if (!old_bufp) + return (-1); + op = (u_int16_t *)old_bufp->page; + putpair((char *)op, &key, &val); + } + old_bufp->flags |= BUF_MOD; + } else { + /* Move to new page */ + if (PAIRFITS(np, (&key), (&val))) + putpair((char *)np, &key, &val); + else { + new_bufp = + __add_ovflpage(hashp, new_bufp); + if (!new_bufp) + return (-1); + np = (u_int16_t *)new_bufp->page; + putpair((char *)np, &key, &val); + } + new_bufp->flags |= BUF_MOD; + } + } + } + if (last_bfp) + __free_ovflpage(hashp, last_bfp); + return (0); +} + +/* + * Add the given pair to the page + * + * Returns: + * 0 ==> OK + * 1 ==> failure + */ +extern int +__addel(hashp, bufp, key, val) + HTAB *hashp; + BUFHEAD *bufp; + const DBT *key, *val; +{ + u_int16_t *bp, *sop; + int do_expand; + + bp = (u_int16_t *)bufp->page; + do_expand = 0; + while (bp[0] && (bp[2] < REAL_KEY || bp[bp[0]] < REAL_KEY)) + /* Exception case */ + if (bp[2] == FULL_KEY_DATA && bp[0] == 2) + /* This is the last page of a big key/data pair + and we need to add another page */ + break; + else if (bp[2] < REAL_KEY && bp[bp[0]] != OVFLPAGE) { + bufp = __get_buf(hashp, bp[bp[0] - 1], bufp, 0); + if (!bufp) + return (-1); + bp = (u_int16_t *)bufp->page; + } else + /* Try to squeeze key on this page */ + if (FREESPACE(bp) > PAIRSIZE(key, val)) { + squeeze_key(bp, key, val); + return (0); + } else { + bufp = __get_buf(hashp, bp[bp[0] - 1], bufp, 0); + if (!bufp) + return (-1); + bp = (u_int16_t *)bufp->page; + } + + if (PAIRFITS(bp, key, val)) + putpair(bufp->page, key, val); + else { + do_expand = 1; + bufp = __add_ovflpage(hashp, bufp); + if (!bufp) + return (-1); + sop = (u_int16_t *)bufp->page; + + if (PAIRFITS(sop, key, val)) + putpair((char *)sop, key, val); + else + if (__big_insert(hashp, bufp, key, val)) + return (-1); + } + bufp->flags |= BUF_MOD; + /* + * If the average number of keys per bucket exceeds the fill factor, + * expand the table. + */ + hashp->NKEYS++; + if (do_expand || + (hashp->NKEYS / (hashp->MAX_BUCKET + 1) > hashp->FFACTOR)) + return (__expand_table(hashp)); + return (0); +} + +/* + * + * Returns: + * pointer on success + * NULL on error + */ +extern BUFHEAD * +__add_ovflpage(hashp, bufp) + HTAB *hashp; + BUFHEAD *bufp; +{ + u_int16_t *sp; + u_int16_t ndx, ovfl_num; +#ifdef DEBUG1 + int tmp1, tmp2; +#endif + sp = (u_int16_t *)bufp->page; + + /* Check if we are dynamically determining the fill factor */ + if (hashp->FFACTOR == DEF_FFACTOR) { + hashp->FFACTOR = sp[0] >> 1; + if (hashp->FFACTOR < MIN_FFACTOR) + hashp->FFACTOR = MIN_FFACTOR; + } + bufp->flags |= BUF_MOD; + ovfl_num = overflow_page(hashp); +#ifdef DEBUG1 + tmp1 = bufp->addr; + tmp2 = bufp->ovfl ? bufp->ovfl->addr : 0; +#endif + if (!ovfl_num || !(bufp->ovfl = __get_buf(hashp, ovfl_num, bufp, 1))) + return (NULL); + bufp->ovfl->flags |= BUF_MOD; +#ifdef DEBUG1 + (void)fprintf(stderr, "ADDOVFLPAGE: %d->ovfl was %d is now %d\n", + tmp1, tmp2, bufp->ovfl->addr); +#endif + ndx = sp[0]; + /* + * Since a pair is allocated on a page only if there's room to add + * an overflow page, we know that the OVFL information will fit on + * the page. + */ + sp[ndx + 4] = OFFSET(sp); + sp[ndx + 3] = FREESPACE(sp) - OVFLSIZE; + sp[ndx + 1] = ovfl_num; + sp[ndx + 2] = OVFLPAGE; + sp[0] = ndx + 2; +#ifdef HASH_STATISTICS + hash_overflows++; +#endif + return (bufp->ovfl); +} + +/* + * Returns: + * 0 indicates SUCCESS + * -1 indicates FAILURE + */ +extern int +__get_page(hashp, p, bucket, is_bucket, is_disk, is_bitmap) + HTAB *hashp; + char *p; + uint32_t bucket; + int is_bucket, is_disk, is_bitmap; +{ + int fd, page, size; + int rsize; + u_int16_t *bp; + + fd = hashp->fp; + size = hashp->BSIZE; + + if ((fd == -1) || !is_disk) { + PAGE_INIT(p); + return (0); + } + if (is_bucket) + page = BUCKET_TO_PAGE(bucket); + else + page = OADDR_TO_PAGE(bucket); + if ((lseek(fd, (off_t)page << hashp->BSHIFT, SEEK_SET) == -1) || + ((rsize = _read(fd, p, size)) == -1)) + return (-1); + bp = (u_int16_t *)p; + if (!rsize) + bp[0] = 0; /* We hit the EOF, so initialize a new page */ + else + if (rsize != size) { + errno = EFTYPE; + return (-1); + } + if (!is_bitmap && !bp[0]) { + PAGE_INIT(p); + } else + if (hashp->LORDER != BYTE_ORDER) { + int i, max; + + if (is_bitmap) { + max = hashp->BSIZE >> 2; /* divide by 4 */ + for (i = 0; i < max; i++) + M_32_SWAP(((int *)p)[i]); + } else { + M_16_SWAP(bp[0]); + max = bp[0] + 2; + for (i = 1; i <= max; i++) + M_16_SWAP(bp[i]); + } + } + return (0); +} + +/* + * Write page p to disk + * + * Returns: + * 0 ==> OK + * -1 ==>failure + */ +extern int +__put_page(hashp, p, bucket, is_bucket, is_bitmap) + HTAB *hashp; + char *p; + uint32_t bucket; + int is_bucket, is_bitmap; +{ + int fd, page, size; + int wsize; + + size = hashp->BSIZE; + if ((hashp->fp == -1) && open_temp(hashp)) + return (-1); + fd = hashp->fp; + + if (hashp->LORDER != BYTE_ORDER) { + int i; + int max; + + if (is_bitmap) { + max = hashp->BSIZE >> 2; /* divide by 4 */ + for (i = 0; i < max; i++) + M_32_SWAP(((int *)p)[i]); + } else { + max = ((u_int16_t *)p)[0] + 2; + for (i = 0; i <= max; i++) + M_16_SWAP(((u_int16_t *)p)[i]); + } + } + if (is_bucket) + page = BUCKET_TO_PAGE(bucket); + else + page = OADDR_TO_PAGE(bucket); + if ((lseek(fd, (off_t)page << hashp->BSHIFT, SEEK_SET) == -1) || + ((wsize = _write(fd, p, size)) == -1)) + /* Errno is set */ + return (-1); + if (wsize != size) { + errno = EFTYPE; + return (-1); + } + return (0); +} + +#define BYTE_MASK ((1 << INT_BYTE_SHIFT) -1) +/* + * Initialize a new bitmap page. Bitmap pages are left in memory + * once they are read in. + */ +extern int +__ibitmap(hashp, pnum, nbits, ndx) + HTAB *hashp; + int pnum, nbits, ndx; +{ + uint32_t *ip; + int clearbytes, clearints; + + if ((ip = (uint32_t *)malloc(hashp->BSIZE)) == NULL) + return (1); + hashp->nmaps++; + clearints = ((nbits - 1) >> INT_BYTE_SHIFT) + 1; + clearbytes = clearints << INT_TO_BYTE; + (void)memset((char *)ip, 0, clearbytes); + (void)memset(((char *)ip) + clearbytes, 0xFF, + hashp->BSIZE - clearbytes); + ip[clearints - 1] = ALL_SET << (nbits & BYTE_MASK); + SETBIT(ip, 0); + hashp->BITMAPS[ndx] = (u_int16_t)pnum; + hashp->mapp[ndx] = ip; + return (0); +} + +static uint32_t +first_free(map) + uint32_t map; +{ + uint32_t i, mask; + + mask = 0x1; + for (i = 0; i < BITS_PER_MAP; i++) { + if (!(mask & map)) + return (i); + mask = mask << 1; + } + return (i); +} + +static u_int16_t +overflow_page(hashp) + HTAB *hashp; +{ + uint32_t *freep; + int max_free, offset, splitnum; + u_int16_t addr; + int bit, first_page, free_bit, free_page, i, in_use_bits, j; +#ifdef DEBUG2 + int tmp1, tmp2; +#endif + splitnum = hashp->OVFL_POINT; + max_free = hashp->SPARES[splitnum]; + + free_page = (max_free - 1) >> (hashp->BSHIFT + BYTE_SHIFT); + free_bit = (max_free - 1) & ((hashp->BSIZE << BYTE_SHIFT) - 1); + + /* Look through all the free maps to find the first free block */ + first_page = hashp->LAST_FREED >>(hashp->BSHIFT + BYTE_SHIFT); + for ( i = first_page; i <= free_page; i++ ) { + if (!(freep = (uint32_t *)hashp->mapp[i]) && + !(freep = fetch_bitmap(hashp, i))) + return (0); + if (i == free_page) + in_use_bits = free_bit; + else + in_use_bits = (hashp->BSIZE << BYTE_SHIFT) - 1; + + if (i == first_page) { + bit = hashp->LAST_FREED & + ((hashp->BSIZE << BYTE_SHIFT) - 1); + j = bit / BITS_PER_MAP; + bit = bit & ~(BITS_PER_MAP - 1); + } else { + bit = 0; + j = 0; + } + for (; bit <= in_use_bits; j++, bit += BITS_PER_MAP) + if (freep[j] != ALL_SET) + goto found; + } + + /* No Free Page Found */ + hashp->LAST_FREED = hashp->SPARES[splitnum]; + hashp->SPARES[splitnum]++; + offset = hashp->SPARES[splitnum] - + (splitnum ? hashp->SPARES[splitnum - 1] : 0); + +#define OVMSG "HASH: Out of overflow pages. Increase page size\n" + if (offset > SPLITMASK) { + if (++splitnum >= NCACHED) { + (void)_write(STDERR_FILENO, OVMSG, sizeof(OVMSG) - 1); + return (0); + } + hashp->OVFL_POINT = splitnum; + hashp->SPARES[splitnum] = hashp->SPARES[splitnum-1]; + hashp->SPARES[splitnum-1]--; + offset = 1; + } + + /* Check if we need to allocate a new bitmap page */ + if (free_bit == (hashp->BSIZE << BYTE_SHIFT) - 1) { + free_page++; + if (free_page >= NCACHED) { + (void)_write(STDERR_FILENO, OVMSG, sizeof(OVMSG) - 1); + return (0); + } + /* + * This is tricky. The 1 indicates that you want the new page + * allocated with 1 clear bit. Actually, you are going to + * allocate 2 pages from this map. The first is going to be + * the map page, the second is the overflow page we were + * looking for. The init_bitmap routine automatically, sets + * the first bit of itself to indicate that the bitmap itself + * is in use. We would explicitly set the second bit, but + * don't have to if we tell init_bitmap not to leave it clear + * in the first place. + */ + if (__ibitmap(hashp, + (int)OADDR_OF(splitnum, offset), 1, free_page)) + return (0); + hashp->SPARES[splitnum]++; +#ifdef DEBUG2 + free_bit = 2; +#endif + offset++; + if (offset > SPLITMASK) { + if (++splitnum >= NCACHED) { + (void)_write(STDERR_FILENO, OVMSG, + sizeof(OVMSG) - 1); + return (0); + } + hashp->OVFL_POINT = splitnum; + hashp->SPARES[splitnum] = hashp->SPARES[splitnum-1]; + hashp->SPARES[splitnum-1]--; + offset = 0; + } + } else { + /* + * Free_bit addresses the last used bit. Bump it to address + * the first available bit. + */ + free_bit++; + SETBIT(freep, free_bit); + } + + /* Calculate address of the new overflow page */ + addr = OADDR_OF(splitnum, offset); +#ifdef DEBUG2 + (void)fprintf(stderr, "OVERFLOW_PAGE: ADDR: %d BIT: %d PAGE %d\n", + addr, free_bit, free_page); +#endif + return (addr); + +found: + bit = bit + first_free(freep[j]); + SETBIT(freep, bit); +#ifdef DEBUG2 + tmp1 = bit; + tmp2 = i; +#endif + /* + * Bits are addressed starting with 0, but overflow pages are addressed + * beginning at 1. Bit is a bit addressnumber, so we need to increment + * it to convert it to a page number. + */ + bit = 1 + bit + (i * (hashp->BSIZE << BYTE_SHIFT)); + if (bit >= hashp->LAST_FREED) + hashp->LAST_FREED = bit - 1; + + /* Calculate the split number for this page */ + for (i = 0; (i < splitnum) && (bit > hashp->SPARES[i]); i++); + offset = (i ? bit - hashp->SPARES[i - 1] : bit); + if (offset >= SPLITMASK) + return (0); /* Out of overflow pages */ + addr = OADDR_OF(i, offset); +#ifdef DEBUG2 + (void)fprintf(stderr, "OVERFLOW_PAGE: ADDR: %d BIT: %d PAGE %d\n", + addr, tmp1, tmp2); +#endif + + /* Allocate and return the overflow page */ + return (addr); +} + +/* + * Mark this overflow page as free. + */ +extern void +__free_ovflpage(hashp, obufp) + HTAB *hashp; + BUFHEAD *obufp; +{ + u_int16_t addr; + uint32_t *freep; + int bit_address, free_page, free_bit; + u_int16_t ndx; + + addr = obufp->addr; +#ifdef DEBUG1 + (void)fprintf(stderr, "Freeing %d\n", addr); +#endif + ndx = (((u_int16_t)addr) >> SPLITSHIFT); + bit_address = + (ndx ? hashp->SPARES[ndx - 1] : 0) + (addr & SPLITMASK) - 1; + if (bit_address < hashp->LAST_FREED) + hashp->LAST_FREED = bit_address; + free_page = (bit_address >> (hashp->BSHIFT + BYTE_SHIFT)); + free_bit = bit_address & ((hashp->BSIZE << BYTE_SHIFT) - 1); + + if (!(freep = hashp->mapp[free_page])) + freep = fetch_bitmap(hashp, free_page); +#ifdef DEBUG + /* + * This had better never happen. It means we tried to read a bitmap + * that has already had overflow pages allocated off it, and we + * failed to read it from the file. + */ + if (!freep) + assert(0); +#endif + CLRBIT(freep, free_bit); +#ifdef DEBUG2 + (void)fprintf(stderr, "FREE_OVFLPAGE: ADDR: %d BIT: %d PAGE %d\n", + obufp->addr, free_bit, free_page); +#endif + __reclaim_buf(hashp, obufp); +} + +/* + * Returns: + * 0 success + * -1 failure + */ +static int +open_temp(hashp) + HTAB *hashp; +{ + sigset_t set, oset; + static char namestr[] = "_hashXXXXXX"; + + /* Block signals; make sure file goes away at process exit. */ + (void)sigfillset(&set); + (void)_sigprocmask(SIG_BLOCK, &set, &oset); + if ((hashp->fp = mkstemp(namestr)) != -1) { + (void)unlink(namestr); + (void)_fcntl(hashp->fp, F_SETFD, 1); + } + (void)_sigprocmask(SIG_SETMASK, &oset, (sigset_t *)NULL); + return (hashp->fp != -1 ? 0 : -1); +} + +/* + * We have to know that the key will fit, but the last entry on the page is + * an overflow pair, so we need to shift things. + */ +static void +squeeze_key(sp, key, val) + u_int16_t *sp; + const DBT *key, *val; +{ + char *p; + u_int16_t free_space, n, off, pageno; + + p = (char *)sp; + n = sp[0]; + free_space = FREESPACE(sp); + off = OFFSET(sp); + + pageno = sp[n - 1]; + off -= key->size; + sp[n - 1] = off; + memmove(p + off, key->data, key->size); + off -= val->size; + sp[n] = off; + memmove(p + off, val->data, val->size); + sp[0] = n + 2; + sp[n + 1] = pageno; + sp[n + 2] = OVFLPAGE; + FREESPACE(sp) = free_space - PAIRSIZE(key, val); + OFFSET(sp) = off; +} + +static uint32_t * +fetch_bitmap(hashp, ndx) + HTAB *hashp; + int ndx; +{ + if (ndx >= hashp->nmaps) + return (NULL); + if ((hashp->mapp[ndx] = (uint32_t *)malloc(hashp->BSIZE)) == NULL) + return (NULL); + if (__get_page(hashp, + (char *)hashp->mapp[ndx], hashp->BITMAPS[ndx], 0, 1, 1)) { + free(hashp->mapp[ndx]); + return (NULL); + } + return (hashp->mapp[ndx]); +} + +#ifdef DEBUG4 +int +print_chain(addr) + int addr; +{ + BUFHEAD *bufp; + short *bp, oaddr; + + (void)fprintf(stderr, "%d ", addr); + bufp = __get_buf(hashp, addr, NULL, 0); + bp = (short *)bufp->page; + while (bp[0] && ((bp[bp[0]] == OVFLPAGE) || + ((bp[0] > 2) && bp[2] < REAL_KEY))) { + oaddr = bp[bp[0] - 1]; + (void)fprintf(stderr, "%d ", (int)oaddr); + bufp = __get_buf(hashp, (int)oaddr, bufp, 0); + bp = (short *)bufp->page; + } + (void)fprintf(stderr, "\n"); +} +#endif diff --git a/lib/libc/db/hash/ndbm.c b/lib/libc/db/hash/ndbm.c new file mode 100644 index 0000000..8561c8c --- /dev/null +++ b/lib/libc/db/hash/ndbm.c @@ -0,0 +1,231 @@ +/*- + * Copyright (c) 1990, 1993 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * Margo Seltzer. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)ndbm.c 8.4 (Berkeley) 7/21/94"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/db/hash/ndbm.c,v 1.6 2002/03/22 21:52:01 obrien Exp $"); + +/* + * This package provides a dbm compatible interface to the new hashing + * package described in db(3). + */ + +#include + +#include +#include +#include + +#include +#include "hash.h" + +/* + * Returns: + * *DBM on success + * NULL on failure + */ +extern DBM * +dbm_open(file, flags, mode) + const char *file; + int flags, mode; +{ + HASHINFO info; + char path[MAXPATHLEN]; + + info.bsize = 4096; + info.ffactor = 40; + info.nelem = 1; + info.cachesize = 0; + info.hash = NULL; + info.lorder = 0; + + if( strlen(file) >= sizeof(path) - strlen(DBM_SUFFIX)) { + errno = ENAMETOOLONG; + return(NULL); + } + (void)strcpy(path, file); + (void)strcat(path, DBM_SUFFIX); + return ((DBM *)__hash_open(path, flags, mode, &info, 0)); +} + +extern void +dbm_close(db) + DBM *db; +{ + (void)(db->close)(db); +} + +/* + * Returns: + * DATUM on success + * NULL on failure + */ +extern datum +dbm_fetch(db, key) + DBM *db; + datum key; +{ + datum retdata; + int status; + DBT dbtkey, dbtretdata; + + dbtkey.data = key.dptr; + dbtkey.size = key.dsize; + status = (db->get)(db, &dbtkey, &dbtretdata, 0); + if (status) { + dbtretdata.data = NULL; + dbtretdata.size = 0; + } + retdata.dptr = dbtretdata.data; + retdata.dsize = dbtretdata.size; + return (retdata); +} + +/* + * Returns: + * DATUM on success + * NULL on failure + */ +extern datum +dbm_firstkey(db) + DBM *db; +{ + int status; + datum retkey; + DBT dbtretkey, dbtretdata; + + status = (db->seq)(db, &dbtretkey, &dbtretdata, R_FIRST); + if (status) + dbtretkey.data = NULL; + retkey.dptr = dbtretkey.data; + retkey.dsize = dbtretkey.size; + return (retkey); +} + +/* + * Returns: + * DATUM on success + * NULL on failure + */ +extern datum +dbm_nextkey(db) + DBM *db; +{ + int status; + datum retkey; + DBT dbtretkey, dbtretdata; + + status = (db->seq)(db, &dbtretkey, &dbtretdata, R_NEXT); + if (status) + dbtretkey.data = NULL; + retkey.dptr = dbtretkey.data; + retkey.dsize = dbtretkey.size; + return (retkey); +} + +/* + * Returns: + * 0 on success + * <0 failure + */ +extern int +dbm_delete(db, key) + DBM *db; + datum key; +{ + int status; + DBT dbtkey; + + dbtkey.data = key.dptr; + dbtkey.size = key.dsize; + status = (db->del)(db, &dbtkey, 0); + if (status) + return (-1); + else + return (0); +} + +/* + * Returns: + * 0 on success + * <0 failure + * 1 if DBM_INSERT and entry exists + */ +extern int +dbm_store(db, key, data, flags) + DBM *db; + datum key, data; + int flags; +{ + DBT dbtkey, dbtdata; + + dbtkey.data = key.dptr; + dbtkey.size = key.dsize; + dbtdata.data = data.dptr; + dbtdata.size = data.dsize; + return ((db->put)(db, &dbtkey, &dbtdata, + (flags == DBM_INSERT) ? R_NOOVERWRITE : 0)); +} + +extern int +dbm_error(db) + DBM *db; +{ + HTAB *hp; + + hp = (HTAB *)db->internal; + return (hp->error); +} + +extern int +dbm_clearerr(db) + DBM *db; +{ + HTAB *hp; + + hp = (HTAB *)db->internal; + hp->error = 0; + return (0); +} + +extern int +dbm_dirfno(db) + DBM *db; +{ + return(((HTAB *)db->internal)->fp); +} diff --git a/lib/libc/db/hash/page.h b/lib/libc/db/hash/page.h new file mode 100644 index 0000000..2cf7460 --- /dev/null +++ b/lib/libc/db/hash/page.h @@ -0,0 +1,93 @@ +/*- + * Copyright (c) 1990, 1993, 1994 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * Margo Seltzer. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * @(#)page.h 8.2 (Berkeley) 5/31/94 + * $FreeBSD: src/lib/libc/db/hash/page.h,v 1.2 2002/03/22 23:41:40 obrien Exp $ + */ + +/* + * Definitions for hashing page file format. + */ + +/* + * routines dealing with a data page + * + * page format: + * +------------------------------+ + * p | n | keyoff | datoff | keyoff | + * +------------+--------+--------+ + * | datoff | free | ptr | --> | + * +--------+---------------------+ + * | F R E E A R E A | + * +--------------+---------------+ + * | <---- - - - | data | + * +--------+-----+----+----------+ + * | key | data | key | + * +--------+----------+----------+ + * + * Pointer to the free space is always: p[p[0] + 2] + * Amount of free space on the page is: p[p[0] + 1] + */ + +/* + * How many bytes required for this pair? + * 2 shorts in the table at the top of the page + room for the + * key and room for the data + * + * We prohibit entering a pair on a page unless there is also room to append + * an overflow page. The reason for this it that you can get in a situation + * where a single key/data pair fits on a page, but you can't append an + * overflow page and later you'd have to split the key/data and handle like + * a big pair. + * You might as well do this up front. + */ + +#define PAIRSIZE(K,D) (2*sizeof(u_int16_t) + (K)->size + (D)->size) +#define BIGOVERHEAD (4*sizeof(u_int16_t)) +#define KEYSIZE(K) (4*sizeof(u_int16_t) + (K)->size); +#define OVFLSIZE (2*sizeof(u_int16_t)) +#define FREESPACE(P) ((P)[(P)[0]+1]) +#define OFFSET(P) ((P)[(P)[0]+2]) +#define PAIRFITS(P,K,D) \ + (((P)[2] >= REAL_KEY) && \ + (PAIRSIZE((K),(D)) + OVFLSIZE) <= FREESPACE((P))) +#define PAGE_META(N) (((N)+3) * sizeof(u_int16_t)) + +typedef struct { + BUFHEAD *newp; + BUFHEAD *oldp; + BUFHEAD *nextp; + u_int16_t next_addr; +} SPLIT_RETURN; diff --git a/lib/libc/db/mpool/Makefile b/lib/libc/db/mpool/Makefile new file mode 100644 index 0000000..618fce5 --- /dev/null +++ b/lib/libc/db/mpool/Makefile @@ -0,0 +1,35 @@ +# $Id: Makefile 89 2016-01-12 00:20:40Z reddawg $ +# The System Makefile (C) 2002 The UbixOS Project + +# Include Global 'Source' Options +include ../../../../Makefile.incl +include ../../../Makefile.incl +include ../Makefile.incl + +INCLUDES += -I../ -I../../include + +#Objects +OBJS = mpool.o + +all: $(OBJS) + +# Compile the source files +.cc.o: + $(CXX) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -c -o $@ $< + +.cc.s: + $(CXX) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -S -o $@ $< + +.c.o: + $(CC) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -c $< + +.c.s: + $(CC) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -S -o $@ $< + +.S.o: + $(CC) $(CFLAGS) -Wall -nostdlib $(INCLUDES) -c -o $@ $< + +# Clean up the junk +clean: + $(REMOVE) $(OBJS) + diff --git a/lib/libc/db/mpool/README b/lib/libc/db/mpool/README new file mode 100644 index 0000000..0f01fbc --- /dev/null +++ b/lib/libc/db/mpool/README @@ -0,0 +1,7 @@ +# @(#)README 8.1 (Berkeley) 6/4/93 + +These are the current memory pool routines. +They aren't ready for prime time, yet, and +the interface is expected to change. + +--keith diff --git a/lib/libc/db/mpool/mpool.c b/lib/libc/db/mpool/mpool.c new file mode 100644 index 0000000..3a1c29d --- /dev/null +++ b/lib/libc/db/mpool/mpool.c @@ -0,0 +1,462 @@ +/*- + * Copyright (c) 1990, 1993, 1994 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)mpool.c 8.5 (Berkeley) 7/26/94"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/db/mpool/mpool.c,v 1.12 2004/09/10 05:41:41 kuriyama Exp $"); + +#include "namespace.h" +#include +#include +#include + +#include +#include +#include +#include +#include +#include "un-namespace.h" + +#include + +#define __MPOOLINTERFACE_PRIVATE +#include + +static BKT *mpool_bkt(MPOOL *); +static BKT *mpool_look(MPOOL *, pgno_t); +static int mpool_write(MPOOL *, BKT *); + +/* + * mpool_open -- + * Initialize a memory pool. + */ +MPOOL * +mpool_open(key, fd, pagesize, maxcache) + void *key; + int fd; + pgno_t pagesize, maxcache; +{ + struct stat sb; + MPOOL *mp; + int entry; + + /* + * Get information about the file. + * + * XXX + * We don't currently handle pipes, although we should. + */ + if (_fstat(fd, &sb)) + return (NULL); + if (!S_ISREG(sb.st_mode)) { + errno = ESPIPE; + return (NULL); + } + + /* Allocate and initialize the MPOOL cookie. */ + if ((mp = (MPOOL *)calloc(1, sizeof(MPOOL))) == NULL) + return (NULL); + TAILQ_INIT(&mp->lqh); + for (entry = 0; entry < HASHSIZE; ++entry) + TAILQ_INIT(&mp->hqh[entry]); + mp->maxcache = maxcache; + mp->npages = sb.st_size / pagesize; + mp->pagesize = pagesize; + mp->fd = fd; + return (mp); +} + +/* + * mpool_filter -- + * Initialize input/output filters. + */ +void +mpool_filter(mp, pgin, pgout, pgcookie) + MPOOL *mp; + void (*pgin)(void *, pgno_t, void *); + void (*pgout)(void *, pgno_t, void *); + void *pgcookie; +{ + mp->pgin = pgin; + mp->pgout = pgout; + mp->pgcookie = pgcookie; +} + +/* + * mpool_new -- + * Get a new page of memory. + */ +void * +mpool_new(mp, pgnoaddr) + MPOOL *mp; + pgno_t *pgnoaddr; +{ + struct _hqh *head; + BKT *bp; + + if (mp->npages == MAX_PAGE_NUMBER) { + (void)fprintf(stderr, "mpool_new: page allocation overflow.\n"); + abort(); + } +#ifdef STATISTICS + ++mp->pagenew; +#endif + /* + * Get a BKT from the cache. Assign a new page number, attach + * it to the head of the hash chain, the tail of the lru chain, + * and return. + */ + if ((bp = mpool_bkt(mp)) == NULL) + return (NULL); + *pgnoaddr = bp->pgno = mp->npages++; + bp->flags = MPOOL_PINNED; + + head = &mp->hqh[HASHKEY(bp->pgno)]; + TAILQ_INSERT_HEAD(head, bp, hq); + TAILQ_INSERT_TAIL(&mp->lqh, bp, q); + return (bp->page); +} + +/* + * mpool_get + * Get a page. + */ +void * +mpool_get(mp, pgno, flags) + MPOOL *mp; + pgno_t pgno; + u_int flags; /* XXX not used? */ +{ + struct _hqh *head; + BKT *bp; + off_t off; + int nr; + + /* Check for attempt to retrieve a non-existent page. */ + if (pgno >= mp->npages) { + errno = EINVAL; + return (NULL); + } + +#ifdef STATISTICS + ++mp->pageget; +#endif + + /* Check for a page that is cached. */ + if ((bp = mpool_look(mp, pgno)) != NULL) { +#ifdef DEBUG + if (bp->flags & MPOOL_PINNED) { + (void)fprintf(stderr, + "mpool_get: page %d already pinned\n", bp->pgno); + abort(); + } +#endif + /* + * Move the page to the head of the hash chain and the tail + * of the lru chain. + */ + head = &mp->hqh[HASHKEY(bp->pgno)]; + TAILQ_REMOVE(head, bp, hq); + TAILQ_INSERT_HEAD(head, bp, hq); + TAILQ_REMOVE(&mp->lqh, bp, q); + TAILQ_INSERT_TAIL(&mp->lqh, bp, q); + + /* Return a pinned page. */ + bp->flags |= MPOOL_PINNED; + return (bp->page); + } + + /* Get a page from the cache. */ + if ((bp = mpool_bkt(mp)) == NULL) + return (NULL); + + /* Read in the contents. */ +#ifdef STATISTICS + ++mp->pageread; +#endif + off = mp->pagesize * pgno; + nr = pread(mp->fd, bp->page, mp->pagesize, off); + if (nr != mp->pagesize) { + if (nr >= 0) + errno = EFTYPE; + return (NULL); + } + + /* Set the page number, pin the page. */ + bp->pgno = pgno; + bp->flags = MPOOL_PINNED; + + /* + * Add the page to the head of the hash chain and the tail + * of the lru chain. + */ + head = &mp->hqh[HASHKEY(bp->pgno)]; + TAILQ_INSERT_HEAD(head, bp, hq); + TAILQ_INSERT_TAIL(&mp->lqh, bp, q); + + /* Run through the user's filter. */ + if (mp->pgin != NULL) + (mp->pgin)(mp->pgcookie, bp->pgno, bp->page); + + return (bp->page); +} + +/* + * mpool_put + * Return a page. + */ +int +mpool_put(mp, page, flags) + MPOOL *mp; + void *page; + u_int flags; +{ + BKT *bp; + +#ifdef STATISTICS + ++mp->pageput; +#endif + bp = (BKT *)((char *)page - sizeof(BKT)); +#ifdef DEBUG + if (!(bp->flags & MPOOL_PINNED)) { + (void)fprintf(stderr, + "mpool_put: page %d not pinned\n", bp->pgno); + abort(); + } +#endif + bp->flags &= ~MPOOL_PINNED; + bp->flags |= flags & MPOOL_DIRTY; + return (RET_SUCCESS); +} + +/* + * mpool_close + * Close the buffer pool. + */ +int +mpool_close(mp) + MPOOL *mp; +{ + BKT *bp; + + /* Free up any space allocated to the lru pages. */ + while (!TAILQ_EMPTY(&mp->lqh)) { + bp = TAILQ_FIRST(&mp->lqh); + TAILQ_REMOVE(&mp->lqh, bp, q); + free(bp); + } + + /* Free the MPOOL cookie. */ + free(mp); + return (RET_SUCCESS); +} + +/* + * mpool_sync + * Sync the pool to disk. + */ +int +mpool_sync(mp) + MPOOL *mp; +{ + BKT *bp; + + /* Walk the lru chain, flushing any dirty pages to disk. */ + TAILQ_FOREACH(bp, &mp->lqh, q) + if (bp->flags & MPOOL_DIRTY && + mpool_write(mp, bp) == RET_ERROR) + return (RET_ERROR); + + /* Sync the file descriptor. */ + return (_fsync(mp->fd) ? RET_ERROR : RET_SUCCESS); +} + +/* + * mpool_bkt + * Get a page from the cache (or create one). + */ +static BKT * +mpool_bkt(mp) + MPOOL *mp; +{ + struct _hqh *head; + BKT *bp; + + /* If under the max cached, always create a new page. */ + if (mp->curcache < mp->maxcache) + goto new; + + /* + * If the cache is max'd out, walk the lru list for a buffer we + * can flush. If we find one, write it (if necessary) and take it + * off any lists. If we don't find anything we grow the cache anyway. + * The cache never shrinks. + */ + TAILQ_FOREACH(bp, &mp->lqh, q) + if (!(bp->flags & MPOOL_PINNED)) { + /* Flush if dirty. */ + if (bp->flags & MPOOL_DIRTY && + mpool_write(mp, bp) == RET_ERROR) + return (NULL); +#ifdef STATISTICS + ++mp->pageflush; +#endif + /* Remove from the hash and lru queues. */ + head = &mp->hqh[HASHKEY(bp->pgno)]; + TAILQ_REMOVE(head, bp, hq); + TAILQ_REMOVE(&mp->lqh, bp, q); +#ifdef DEBUG + { void *spage; + spage = bp->page; + memset(bp, 0xff, sizeof(BKT) + mp->pagesize); + bp->page = spage; + } +#endif + return (bp); + } + +new: if ((bp = (BKT *)malloc(sizeof(BKT) + mp->pagesize)) == NULL) + return (NULL); +#ifdef STATISTICS + ++mp->pagealloc; +#endif +#if defined(DEBUG) || defined(PURIFY) + memset(bp, 0xff, sizeof(BKT) + mp->pagesize); +#endif + bp->page = (char *)bp + sizeof(BKT); + ++mp->curcache; + return (bp); +} + +/* + * mpool_write + * Write a page to disk. + */ +static int +mpool_write(mp, bp) + MPOOL *mp; + BKT *bp; +{ + off_t off; + +#ifdef STATISTICS + ++mp->pagewrite; +#endif + + /* Run through the user's filter. */ + if (mp->pgout) + (mp->pgout)(mp->pgcookie, bp->pgno, bp->page); + + off = mp->pagesize * bp->pgno; + if (pwrite(mp->fd, bp->page, mp->pagesize, off) != mp->pagesize) + return (RET_ERROR); + + bp->flags &= ~MPOOL_DIRTY; + return (RET_SUCCESS); +} + +/* + * mpool_look + * Lookup a page in the cache. + */ +static BKT * +mpool_look(mp, pgno) + MPOOL *mp; + pgno_t pgno; +{ + struct _hqh *head; + BKT *bp; + + head = &mp->hqh[HASHKEY(pgno)]; + TAILQ_FOREACH(bp, head, hq) + if (bp->pgno == pgno) { +#ifdef STATISTICS + ++mp->cachehit; +#endif + return (bp); + } +#ifdef STATISTICS + ++mp->cachemiss; +#endif + return (NULL); +} + +#ifdef STATISTICS +/* + * mpool_stat + * Print out cache statistics. + */ +void +mpool_stat(mp) + MPOOL *mp; +{ + BKT *bp; + int cnt; + char *sep; + + (void)fprintf(stderr, "%u pages in the file\n", mp->npages); + (void)fprintf(stderr, + "page size %lu, cacheing %u pages of %u page max cache\n", + mp->pagesize, mp->curcache, mp->maxcache); + (void)fprintf(stderr, "%lu page puts, %lu page gets, %lu page new\n", + mp->pageput, mp->pageget, mp->pagenew); + (void)fprintf(stderr, "%lu page allocs, %lu page flushes\n", + mp->pagealloc, mp->pageflush); + if (mp->cachehit + mp->cachemiss) + (void)fprintf(stderr, + "%.0f%% cache hit rate (%lu hits, %lu misses)\n", + ((double)mp->cachehit / (mp->cachehit + mp->cachemiss)) + * 100, mp->cachehit, mp->cachemiss); + (void)fprintf(stderr, "%lu page reads, %lu page writes\n", + mp->pageread, mp->pagewrite); + + sep = ""; + cnt = 0; + TAILQ_FOREACH(bp, &mp->lqh, q) { + (void)fprintf(stderr, "%s%d", sep, bp->pgno); + if (bp->flags & MPOOL_DIRTY) + (void)fprintf(stderr, "d"); + if (bp->flags & MPOOL_PINNED) + (void)fprintf(stderr, "P"); + if (++cnt == 10) { + sep = "\n"; + cnt = 0; + } else + sep = ", "; + + } + (void)fprintf(stderr, "\n"); +} +#endif diff --git a/lib/libc/db/mpool/mpool.libtp b/lib/libc/db/mpool/mpool.libtp new file mode 100644 index 0000000..0d82368 --- /dev/null +++ b/lib/libc/db/mpool/mpool.libtp @@ -0,0 +1,746 @@ +/****************************************************************************** + +VERSION $FreeBSD: src/lib/libc/db/mpool/mpool.libtp,v 1.4 1999/08/27 23:58:23 peter Exp $ +PACKAGE: User Level Shared Memory Manager + +DESCRIPTION: + This package provides a buffer pool interface implemented as + a collection of file pages mapped into shared memory. + + Based on Mark's buffer manager + +ROUTINES: + External + buf_alloc + buf_flags + buf_get + buf_init + buf_last + buf_open + buf_pin + buf_sync + buf_unpin + Internal + bf_assign_buf + bf_fid_to_fd + bf_newbuf + bf_put_page + + +******************************************************************************/ +#include +#include +#include +#include +#include +#include +#include "list.h" +#include "user.h" +#include "txn_sys.h" +#include "buf.h" +#include "semkeys.h" +#include "error.h" + +/* + we need to translate between some type of file id that the user + process passes and a file descriptor. For now, it's a nop. +*/ +#define GET_MASTER get_sem ( buf_spinlock ) +#define RELEASE_MASTER release_sem ( buf_spinlock ) + +#define LRUID *buf_lru +#define LRUP (bufhdr_table+*buf_lru) +#define MRU bufhdr_table[*buf_lru].lru.prev + +/* Global indicator that you have started reusing buffers */ +int do_statistics = 0; +/* + Process Statics (pointers into shared memory) +*/ +static BUF_T *buf_table = 0; +static BUFHDR_T *bufhdr_table; +static int *buf_hash_table; +static int *buf_lru; /* LRU is the free list */ +static int buf_spinlock; +static FINFO_T *buf_fids; +static int *buf_sp; /* Pointer to string free space */ +static char *buf_strings; + +/* Process Local FID->FD table */ +static int fds[NUM_FILE_ENTRIES]; + +/* Static routines */ +static BUFHDR_T *bf_assign_buf(); +static int bf_fid_to_fd(); +static BUFHDR_T *bf_newbuf(); +static int bf_put_page(); + +/* + Return 0 on success + 1 on failure +*/ +extern int +buf_init ( ) +{ + ADDR_T buf_region; + BUFHDR_T *bhp; + int i; + int ref_count; + int *spinlockp; + + /* + Initialize Process local structures + */ + for ( i = 0; i < NUM_FILE_ENTRIES; i++ ) { + fds[i] = -1; + } + + buf_region = attach_region ( BUF_REGION_NAME, BUF_REGION_NUM, + BUF_REGION_SIZE, &ref_count ); + if ( !buf_region ) { + return (1); + } + error_log3 ( "Buf Region: ADDR: %d ID: %d SIZE: %d\n", buf_region, + BUF_REGION_NUM, BUF_REGION_SIZE ); + + buf_table = (BUF_T *)buf_region; + bufhdr_table = (BUFHDR_T *)(buf_table + NUM_BUFS); + buf_hash_table = (int *)(bufhdr_table + NUM_BUFS); + buf_lru = buf_hash_table + NUMTABLE_ENTRIES; + spinlockp = buf_lru + 1; + buf_fids = (FINFO_T *)(spinlockp+1); + buf_sp = (int *)(buf_fids + NUM_FILE_ENTRIES); + buf_strings = (char *)(buf_sp + 1); + + /* Create locking spinlock (gets creating holding the lock) */ + buf_spinlock = create_sem ( BUF_SPIN_NAME, BUF_SPIN_NUM, ref_count <= 1 ); + if ( buf_spinlock < 0 ) { + return(1); + } + if ( ref_count <= 1 ) { + *spinlockp = buf_spinlock; + + /* Now initialize the buffer manager */ + + /* 1. Free list */ + *buf_lru = 0; + + /* 2. Buffer headers */ + for ( i = 0, bhp = bufhdr_table; i < NUM_BUFS; bhp++, i++ ) { + bhp->lru.next = i+1; + bhp->lru.prev = i-1; + bhp->flags = 0; /* All Flags off */ + bhp->refcount = 0; + bhp->wait_proc = -1; /* No sleepers */ + LISTPE_INIT ( hash, bhp, i ); /* Hash chains */ + } + bufhdr_table[0].lru.prev = NUM_BUFS-1; + bufhdr_table[NUM_BUFS-1].lru.next = 0; + + /* 3. Hash Table */ + for ( i = 0; i < NUMTABLE_ENTRIES; i++ ) { + buf_hash_table[i] = NUM_BUFS; + } + + /* 4. File ID Table */ + for ( i = 0; i < NUM_FILE_ENTRIES; i++ ) { + buf_fids[i].offset = -1; + buf_fids[i].npages = -1; + buf_fids[i].refcount = 0; + } + + /* 5. Free String Pointer */ + *buf_sp = (FILE_NAME_LEN*NUM_FILE_ENTRIES); + if (RELEASE_MASTER) { + return(1); + } + error_log0 ( "Initialized buffer region\n" ); + } + return (0); +} + +extern void +buf_exit() +{ + int ref; + int i; + + /* Flush Buffer Pool on Exit */ + for ( i = 0; i < NUM_FILE_ENTRIES; i++ ) { + if ( fds[i] != -1 ) { + close ( fds[i] ); + } + } + if ( buf_table ) { + detach_region ( buf_table, BUF_REGION_NUM, BUF_REGION_SIZE, &ref ); + } + return; +} + +/* + We need an empty buffer. Find the LRU unpinned NON-Dirty page. +*/ +static BUFHDR_T * +bf_newbuf() +{ + int fd; + int lruid; + int nbytes; + int ndx; + BUFHDR_T *bhp; + + lruid = LRUID; + for ( bhp = LRUP; + bhp->flags & (BUF_PINNED|BUF_IO_IN_PROGRESS); + bhp = LISTP_NEXTP (bufhdr_table, lru, bhp ) ) { + + if ( bhp->lru.next == lruid ) { + /* OUT OF BUFFERS */ + error_log1 ( "All buffers are pinned. %s\n", + "Unable to grant buffer request" ); + return(NULL); + } + } + /* BHP can be used */ + if ( bhp->flags & BUF_DIRTY ) { + do_statistics = 1; + /* + MIS Check for log flushed appropriately + */ + fd = bf_fid_to_fd(bhp->id.file_id); + if ( fd == -1 ) { + error_log1 ("Invalid fid %d\n", bhp->id.file_id); + return(NULL); + } + if ( bf_put_page(fd, bhp) < 0 ) { + return(NULL); + } + } + /* Update Hash Pointers */ + ndx = BUF_HASH ( bhp->id.file_id, bhp->id.obj_id ); + LISTP_REMOVE(bufhdr_table, hash, bhp); + if ( buf_hash_table[ndx] == (bhp-bufhdr_table) ) { + if ( bhp->hash.next != (bhp-bufhdr_table) ) { + buf_hash_table[ndx] = bhp->hash.next; + } else { + buf_hash_table[ndx] = NUM_BUFS; + } + } + INIT_BUF(bhp); + + return(bhp); +} +/* + buf_alloc + + Add a page to a file and return a buffer for it. + +*/ +ADDR_T +buf_alloc ( fid, new_pageno ) +int fid; +int *new_pageno; +{ + BUFHDR_T *bhp; + int fd; + int len; + int ndx; + OBJ_T fobj; + + if (GET_MASTER) { + return(NULL); + } + if ( buf_fids[fid].npages == -1 ) { + /* initialize npages field */ + fd = bf_fid_to_fd ( fid ); + } + assert (fid < NUM_FILE_ENTRIES); + + *new_pageno = buf_fids[fid].npages; + if ( *new_pageno == -1 ) { + RELEASE_MASTER; + return ( NULL ); + } + buf_fids[fid].npages++; + ndx = BUF_HASH ( fid, *new_pageno ); + fobj.file_id = fid; + fobj.obj_id = *new_pageno; + bhp = bf_assign_buf ( ndx, &fobj, BF_PIN|BF_DIRTY|BF_EMPTY, &len ); + if ( RELEASE_MASTER ) { + /* Memory leak */ + return(NULL); + } + if ( bhp ) { + return ((ADDR_T)(buf_table+(bhp-bufhdr_table))); + } else { + return ( NULL ); + } +} + + +/* + Buffer Flags + BF_DIRTY Mark page as dirty + BF_EMPTY Don't initialize page, just get buffer + BF_PIN Retrieve with pin + +MIS +Might want to add a flag that sets an LSN for this buffer is the +DIRTY flag is set + +Eventually, you may want a flag that indicates the I/O and lock +request should be shipped off together, but not for now. +*/ +extern ADDR_T +buf_get ( file_id, page_id, flags, len ) +int file_id; +int page_id; +u_long flags; +int *len; /* Number of bytes read into buffer */ +{ + BUFHDR_T *bhp; + int bufid; + int fd; + int ndx; + int next_bufid; + int stat; + OBJ_T fobj; + + ndx = BUF_HASH ( file_id, page_id ); + fobj.file_id = (long) file_id; + fobj.obj_id = (long) page_id; + if ( GET_MASTER ) { + return(NULL); + } + /* + This could be a for loop, but we lose speed + by making all the cases general purpose so we + optimize for the no-collision case. + */ + bufid = buf_hash_table[ndx]; + if ( bufid < NUM_BUFS ) { + for ( bhp = bufhdr_table+bufid; + !OBJ_EQ (bhp->id, fobj) || !(bhp->flags & BUF_VALID); + bhp = LISTP_NEXTP ( bufhdr_table, hash, bhp ) ) { + + if ( bhp->hash.next == bufid ) { + goto not_found; + } + } +/* found */ + if ( flags & BF_PIN ) { + bhp->flags |= BUF_PINNED; + bhp->refcount++; +#ifdef PIN_DEBUG + fprintf(stderr, "buf_get: %X PINNED (%d)\n", + buf_table + (bhp-bufhdr_table), bhp->refcount); +#endif + } + if ( flags & BF_DIRTY ) { + bhp->flags |= BUF_DIRTY; + } + + while ( bhp->flags & BUF_IO_IN_PROGRESS ) { + /* MIS -- eventually err check here */ +#ifdef DEBUG + printf("About to sleep on %d (me: %d\n)\n", bhp->wait_proc, + my_txnp - txn_table); +#endif +#ifdef WAIT_STATS + buf_waits++; +#endif + stat = proc_sleep_on ( &(bhp->wait_proc), buf_spinlock ); + if ( stat ) { + /* Memory leak */ + return(NULL); + } + if (!( bhp->flags & BUF_IO_IN_PROGRESS) && + (!OBJ_EQ (bhp->id, fobj) || !(bhp->flags & BUF_VALID))) { + if (RELEASE_MASTER) + return(NULL); + return(buf_get ( file_id, page_id, flags, len )); + } + } + MAKE_MRU( bhp ); + *len = BUFSIZE; + } else { +not_found: + /* If you get here, the page isn't in the hash table */ + bhp = bf_assign_buf ( ndx, &fobj, flags, len ); + } + /* Common code between found and not found */ + + if ( bhp && bhp->flags & BUF_NEWPAGE ) { + *len = 0; + } + if (RELEASE_MASTER){ + /* Memory leak */ + return(NULL); + } + if ( bhp ) { + return ((ADDR_T)(buf_table+(bhp-bufhdr_table))); + } else { + return ( NULL ); + } +} + +/* + MIS - do I want to add file links to buffer pool? +*/ +extern int +buf_sync ( fid, close ) +int fid; +int close; /* should we dec refcount and possibly + invalidate all the buffers */ +{ + int i; + int fd; + int invalidate; + BUFHDR_T *bhp; + + if ( (fd = bf_fid_to_fd ( fid )) < 0 ) { + return(1); + } + if (GET_MASTER) { + return(1); + } + invalidate = (buf_fids[fid].refcount == 1 && close); + if ( invalidate ) + for ( bhp = bufhdr_table, i = 0; i < NUM_BUFS; bhp++, i++ ) { + if (bhp->id.file_id == fid) { + if ((bhp->flags & BF_DIRTY) && (bf_put_page( fd, bhp ) < 0)) { + return(1); + } + bhp->id.file_id = -1; + } + } + if (invalidate || close) + buf_fids[fid].refcount--; + + if (RELEASE_MASTER) { + return(1); + } + return(0); + + +} + +extern int +buf_flags ( addr, set_flags, unset_flags ) +ADDR_T addr; +u_long set_flags; +u_long unset_flags; +{ + int bufid; + BUFHDR_T *bhp; + +#ifdef PIN_DEBUG + fprintf(stderr, "buf_flags: %X setting %s%s%s%s%s releasing %s%s%s%s%s\n", + addr, + set_flags&BUF_DIRTY ? "DIRTY " : "", + set_flags&BUF_VALID ? "VALID " : "", + set_flags&BUF_PINNED ? "PINNED " : "", + set_flags&BUF_IO_ERROR ? "IO_ERROR " : "", + set_flags&BUF_IO_IN_PROGRESS ? "IO_IN_PROG " : "", + set_flags&BUF_NEWPAGE ? "NEWPAGE " : "", + unset_flags&BUF_DIRTY ? "DIRTY " : "", + unset_flags&BUF_VALID ? "VALID " : "", + unset_flags&BUF_PINNED ? "PINNED " : "", + unset_flags&BUF_IO_ERROR ? "IO_ERROR " : "", + unset_flags&BUF_IO_IN_PROGRESS ? "IO_IN_PROG " : "", + unset_flags&BUF_NEWPAGE ? "NEWPAGE " : "" ); +#endif + if (!ADDR_OK(addr)) { + error_log1 ( "buf_pin: Invalid Buffer Address %x\n", addr ); + return(1); + } + bufid = ((BUF_T *)addr) - buf_table; + assert ( bufid < NUM_BUFS); + bhp = &bufhdr_table[bufid]; + if (GET_MASTER) { + return(1); + } + bhp->flags |= set_flags; + if ( set_flags & BUF_PINNED ) { + bhp->refcount++; + } + if ( set_flags & BUF_DIRTY ) { + unset_flags |= BUF_NEWPAGE; + } + + if ( unset_flags & BUF_PINNED ) { + bhp->refcount--; + if ( bhp->refcount ) { + /* Turn off pin bit so it doesn't get unset */ + unset_flags &= ~BUF_PINNED; + } + } + bhp->flags &= ~unset_flags; + MAKE_MRU(bhp); + if (RELEASE_MASTER) { + return(1); + } + return(0); +} + +/* + Take a string name and produce an fid. + + returns -1 on error + + MIS -- this is a potential problem -- you keep actual names + here -- what if people run from different directories? +*/ +extern int +buf_name_lookup ( fname ) +char *fname; +{ + int i; + int fid; + int ndx; + + fid = -1; + if (GET_MASTER) { + return(-1); + } + for ( i = 0; i < NUM_FILE_ENTRIES; i++ ) { + if ( buf_fids[i].offset == -1 ) { + fid = i; + } else { + if (!strcmp (fname, buf_strings+buf_fids[i].offset)) { + if (RELEASE_MASTER) { + return(-1); + } + buf_fids[i].refcount++; + return(i); + } + } + } + if ( fid == -1 ) { + error_log0 ( "No more file ID's\n" ); + } else { + ndx = *buf_sp - strlen(fname) - 1; + if ( ndx < 0 ) { + error_log0 ( "Out of string space\n" ); + fid = -1; + } else { + *buf_sp = ndx; + strcpy ( buf_strings+ndx, fname ); + buf_fids[fid].offset = ndx; + } + buf_fids[fid].refcount = 1; + } + if (RELEASE_MASTER) { + return(-1); + } + return(fid); +} + +static int +bf_fid_to_fd ( fid ) +int fid; +{ + struct stat sbuf; + + assert ( (fid < NUM_FILE_ENTRIES) && (buf_fids[fid].offset != -1) ); + if ( fds[fid] != -1 ) { + return(fds[fid]); + + } + fds[fid] = open ( buf_strings+buf_fids[fid].offset, O_RDWR|O_CREAT, + 0666 ); + if ( fds[fid] < 0 ) { + error_log3 ( "Error Opening File %s FID: %d FD: %d. Errno = %d\n", + buf_strings+buf_fids[fid].offset, fid, fds[fid], + errno ); + return(-1); + } + error_log3 ( "Opening File %s FID: %d FD: %d\n", + buf_strings+buf_fids[fid].offset, fid, fds[fid] ); + if ( buf_fids[fid].npages == -1 ) { + /* Initialize the npages field */ + if ( fstat ( fds[fid], &sbuf ) ) { + error_log3 ( "Error Fstating %s FID: %d. Errno = %d\n", + buf_strings+buf_fids[fid].offset, fid, errno ); + } else { + buf_fids[fid].npages = ( sbuf.st_size / BUFSIZE ); + } + } + + return ( fds[fid] ); +} + +static int +bf_put_page ( fd, bhp ) +int fd; +BUFHDR_T *bhp; +{ + int nbytes; + + assert ( (bhp-bufhdr_table) < NUM_BUFS ); + if ( lseek ( fd, bhp->id.obj_id << BUFSHIFT, L_SET ) < 0 ) { + return(-1); + } + bhp->flags |= BUF_IO_IN_PROGRESS; + if (RELEASE_MASTER) { + return(-1); + } + nbytes = write(fd, buf_table[bhp-bufhdr_table], BUFSIZE); + if (GET_MASTER) { + return(-2); + } + if ( nbytes < 0 ) { + error_log1 ("Write failed with error code %d\n", errno); + return(-1); + } else if ( nbytes != BUFSIZE ) { + error_log1 ("Short write: %d bytes of %d\n", nbytes, BUFSIZE ); + } + bhp->flags &= ~(BUF_DIRTY|BUF_IO_IN_PROGRESS); + return (0); +} + +static BUFHDR_T * +bf_assign_buf ( ndx, obj, flags, len ) +int ndx; +OBJ_T *obj; +u_long flags; +int *len; /* Number of bytes read */ +{ + BUFHDR_T *bhp; + int fd; + + assert ( obj->file_id < NUM_FILE_ENTRIES ); + bhp = bf_newbuf(); + if ( !bhp ) { + return(NULL); + } + OBJ_ASSIGN ( (*obj), bhp->id ); + if ( buf_hash_table[ndx] >= NUM_BUFS ) { + buf_hash_table[ndx] = bhp-bufhdr_table; + } else { + LISTPE_INSERT ( bufhdr_table, hash, bhp, buf_hash_table[ndx] ); + } + + bhp->flags |= BUF_VALID; + if ( flags & BF_PIN ) { + bhp->flags |= BUF_PINNED; + bhp->refcount++; +#ifdef PIN_DEBUG + fprintf(stderr, "bf_assign_buf: %X PINNED (%d)\n", + buf_table + (bhp-bufhdr_table), bhp->refcount); +#endif + } + fd = bf_fid_to_fd(obj->file_id); + if ( fd == -1 ) { + error_log1 ("Invalid fid %d\n", obj->file_id); + bhp->flags |= ~BUF_IO_ERROR; + return(NULL); + } + if ( obj->obj_id >= buf_fids[obj->file_id].npages) { + buf_fids[obj->file_id].npages = obj->obj_id+1; + *len = 0; + } else if ( flags & BF_EMPTY ) { + *len = 0; + } else { + bhp->flags |= BUF_IO_IN_PROGRESS; + if (RELEASE_MASTER) { + return(NULL); + } + if ( lseek ( fd, obj->obj_id << BUFSHIFT, L_SET ) < -1 ) { + error_log2 ("Unable to perform seek on file: %d to page %d", + obj->file_id, obj->obj_id ); + bhp->flags &= ~BUF_IO_IN_PROGRESS; + bhp->flags |= ~BUF_IO_ERROR; + return(NULL); + } + *len = read(fd, buf_table[bhp-bufhdr_table], BUFSIZE); + if ( *len < 0 ) { + error_log2 ("Unable to perform read on file: %d to page %d", + obj->file_id, obj->obj_id ); + bhp->flags &= ~BUF_IO_IN_PROGRESS; + bhp->flags |= ~BUF_IO_ERROR; + return(NULL); + } + if (GET_MASTER) { + return(NULL); + } + bhp->flags &= ~BUF_IO_IN_PROGRESS; + if ( bhp->wait_proc != -1 ) { + /* wake up waiter and anyone waiting on it */ +#ifdef DEBUG + printf("Waking transaction %d due to completed I/O\n", + bhp->wait_proc); +#endif + proc_wake_id ( bhp->wait_proc ); + bhp->wait_proc = -1; + } + MAKE_MRU(bhp); + } + + if ( flags & BF_DIRTY ) { + bhp->flags |= BUF_DIRTY; + } else if ( *len < BUFSIZE ) { + bhp->flags |= BUF_NEWPAGE; + } + return ( bhp ); +} + +int +buf_last ( fid ) +int fid; +{ + int val; + + if (GET_MASTER) { + return(-1); + } + assert ( fid < NUM_FILE_ENTRIES ); + if ( buf_fids[fid].npages == -1 ) { + /* initialize npages field */ + (void) bf_fid_to_fd ( fid ); + } + val = buf_fids[fid].npages; + if ( val ) { + val--; /* Convert to page number */ + } + if (RELEASE_MASTER) { + return(-1); + } + return(val); +} + +#ifdef DEBUG +extern void +buf_dump ( id, all ) +int id; +int all; +{ + int i; + BUFHDR_T *bhp; + + printf ( "LRU + %d\n", *buf_lru ); + if ( all ) { + printf("ID\tFID\tPID\tLNEXT\tLPREV\tHNEXT\tHPREV\tSLEEP\tFLAG\tREFS\n"); + for ( bhp = bufhdr_table, i = 0; i < NUM_BUFS; bhp++, i++ ) { + printf ( "%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%x\t%d\n", i, + bhp->id.file_id, bhp->id.obj_id, + bhp->lru.next, bhp->lru.prev, + bhp->hash.next, bhp->hash.prev, + bhp->wait_proc, bhp->flags, bhp->refcount ); + } + } else { + if ( id >= NUM_BUFS ) { + printf ( "Buffer ID (%d) too high\n", id ); + return; + } + bhp = bufhdr_table+id; + printf ( "%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%x\t%d\n", i, + bhp->id.file_id, bhp->id.obj_id, + bhp->lru.next, bhp->lru.prev, + bhp->hash.next, bhp->hash.prev, + bhp->wait_proc, bhp->flags, bhp->refcount ); + } + return; +} +#endif + diff --git a/lib/libc/db/recno/Makefile b/lib/libc/db/recno/Makefile new file mode 100644 index 0000000..86e1207 --- /dev/null +++ b/lib/libc/db/recno/Makefile @@ -0,0 +1,35 @@ +# $Id: Makefile 89 2016-01-12 00:20:40Z reddawg $ +# The System Makefile (C) 2002 The UbixOS Project + +# Include Global 'Source' Options +include ../../../../Makefile.incl +include ../../../Makefile.incl +include ../Makefile.incl + +INCLUDES += -I../ -I../../include + +#Objects +OBJS = rec_close.o rec_delete.o rec_get.o rec_open.o rec_put.o rec_search.o rec_seq.o rec_utils.o + +all: $(OBJS) + +# Compile the source files +.cc.o: + $(CXX) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -c -o $@ $< + +.cc.s: + $(CXX) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -S -o $@ $< + +.c.o: + $(CC) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -c $< + +.c.s: + $(CC) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -S -o $@ $< + +.S.o: + $(CC) $(CFLAGS) -Wall -nostdlib $(INCLUDES) -c -o $@ $< + +# Clean up the junk +clean: + $(REMOVE) $(OBJS) + diff --git a/lib/libc/db/recno/extern.h b/lib/libc/db/recno/extern.h new file mode 100644 index 0000000..7cacd95 --- /dev/null +++ b/lib/libc/db/recno/extern.h @@ -0,0 +1,55 @@ +/*- + * Copyright (c) 1991, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * @(#)extern.h 8.3 (Berkeley) 6/4/94 + * $FreeBSD: src/lib/libc/db/recno/extern.h,v 1.2 2002/03/21 22:46:28 obrien Exp $ + */ + +#include "../btree/extern.h" + +int __rec_close(DB *); +int __rec_delete(const DB *, const DBT *, u_int); +int __rec_dleaf(BTREE *, PAGE *, uint32_t); +int __rec_fd(const DB *); +int __rec_fmap(BTREE *, recno_t); +int __rec_fout(BTREE *); +int __rec_fpipe(BTREE *, recno_t); +int __rec_get(const DB *, const DBT *, DBT *, u_int); +int __rec_iput(BTREE *, recno_t, const DBT *, u_int); +int __rec_put(const DB *dbp, DBT *, const DBT *, u_int); +int __rec_ret(BTREE *, EPG *, recno_t, DBT *, DBT *); +EPG *__rec_search(BTREE *, recno_t, enum SRCHOP); +int __rec_seq(const DB *, DBT *, DBT *, u_int); +int __rec_sync(const DB *, u_int); +int __rec_vmap(BTREE *, recno_t); +int __rec_vout(BTREE *); +int __rec_vpipe(BTREE *, recno_t); diff --git a/lib/libc/db/recno/rec_close.c b/lib/libc/db/recno/rec_close.c new file mode 100644 index 0000000..fea96ae --- /dev/null +++ b/lib/libc/db/recno/rec_close.c @@ -0,0 +1,188 @@ +/*- + * Copyright (c) 1990, 1993, 1994 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)rec_close.c 8.6 (Berkeley) 8/18/94"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/db/recno/rec_close.c,v 1.7 2003/02/16 17:29:09 nectar Exp $"); + +#include "namespace.h" +#include +#include +#include + +#include +#include +#include +#include +#include "un-namespace.h" + +#include +#include "recno.h" + +/* + * __REC_CLOSE -- Close a recno tree. + * + * Parameters: + * dbp: pointer to access method + * + * Returns: + * RET_ERROR, RET_SUCCESS + */ +int +__rec_close(dbp) + DB *dbp; +{ + BTREE *t; + int status; + + t = dbp->internal; + + /* Toss any page pinned across calls. */ + if (t->bt_pinned != NULL) { + mpool_put(t->bt_mp, t->bt_pinned, 0); + t->bt_pinned = NULL; + } + + if (__rec_sync(dbp, 0) == RET_ERROR) + return (RET_ERROR); + + /* Committed to closing. */ + status = RET_SUCCESS; + if (F_ISSET(t, R_MEMMAPPED) && munmap(t->bt_smap, t->bt_msize)) + status = RET_ERROR; + + if (!F_ISSET(t, R_INMEM)) { + if (F_ISSET(t, R_CLOSEFP)) { + if (fclose(t->bt_rfp)) + status = RET_ERROR; + } else + if (_close(t->bt_rfd)) + status = RET_ERROR; + } + + if (__bt_close(dbp) == RET_ERROR) + status = RET_ERROR; + + return (status); +} + +/* + * __REC_SYNC -- sync the recno tree to disk. + * + * Parameters: + * dbp: pointer to access method + * + * Returns: + * RET_SUCCESS, RET_ERROR. + */ +int +__rec_sync(dbp, flags) + const DB *dbp; + u_int flags; +{ + struct iovec iov[2]; + BTREE *t; + DBT data, key; + off_t off; + recno_t scursor, trec; + int status; + + t = dbp->internal; + + /* Toss any page pinned across calls. */ + if (t->bt_pinned != NULL) { + mpool_put(t->bt_mp, t->bt_pinned, 0); + t->bt_pinned = NULL; + } + + if (flags == R_RECNOSYNC) + return (__bt_sync(dbp, 0)); + + if (F_ISSET(t, R_RDONLY | R_INMEM) || !F_ISSET(t, R_MODIFIED)) + return (RET_SUCCESS); + + /* Read any remaining records into the tree. */ + if (!F_ISSET(t, R_EOF) && t->bt_irec(t, MAX_REC_NUMBER) == RET_ERROR) + return (RET_ERROR); + + /* Rewind the file descriptor. */ + if (lseek(t->bt_rfd, (off_t)0, SEEK_SET) != 0) + return (RET_ERROR); + + /* Save the cursor. */ + scursor = t->bt_cursor.rcursor; + + key.size = sizeof(recno_t); + key.data = &trec; + + if (F_ISSET(t, R_FIXLEN)) { + /* + * We assume that fixed length records are all fixed length. + * Any that aren't are either EINVAL'd or corrected by the + * record put code. + */ + status = (dbp->seq)(dbp, &key, &data, R_FIRST); + while (status == RET_SUCCESS) { + if (_write(t->bt_rfd, data.data, data.size) != + data.size) + return (RET_ERROR); + status = (dbp->seq)(dbp, &key, &data, R_NEXT); + } + } else { + iov[1].iov_base = (char *)&t->bt_bval; + iov[1].iov_len = 1; + + status = (dbp->seq)(dbp, &key, &data, R_FIRST); + while (status == RET_SUCCESS) { + iov[0].iov_base = data.data; + iov[0].iov_len = data.size; + if (_writev(t->bt_rfd, iov, 2) != data.size + 1) + return (RET_ERROR); + status = (dbp->seq)(dbp, &key, &data, R_NEXT); + } + } + + /* Restore the cursor. */ + t->bt_cursor.rcursor = scursor; + + if (status == RET_ERROR) + return (RET_ERROR); + if ((off = lseek(t->bt_rfd, (off_t)0, SEEK_CUR)) == -1) + return (RET_ERROR); + if (ftruncate(t->bt_rfd, off)) + return (RET_ERROR); + F_CLR(t, R_MODIFIED); + return (RET_SUCCESS); +} diff --git a/lib/libc/db/recno/rec_delete.c b/lib/libc/db/recno/rec_delete.c new file mode 100644 index 0000000..82c436b --- /dev/null +++ b/lib/libc/db/recno/rec_delete.c @@ -0,0 +1,199 @@ +/*- + * Copyright (c) 1990, 1993, 1994 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * Mike Olson. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)rec_delete.c 8.7 (Berkeley) 7/14/94"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/db/recno/rec_delete.c,v 1.2 2002/03/21 22:46:28 obrien Exp $"); + +#include + +#include +#include +#include + +#include +#include "recno.h" + +static int rec_rdelete(BTREE *, recno_t); + +/* + * __REC_DELETE -- Delete the item(s) referenced by a key. + * + * Parameters: + * dbp: pointer to access method + * key: key to delete + * flags: R_CURSOR if deleting what the cursor references + * + * Returns: + * RET_ERROR, RET_SUCCESS and RET_SPECIAL if the key not found. + */ +int +__rec_delete(dbp, key, flags) + const DB *dbp; + const DBT *key; + u_int flags; +{ + BTREE *t; + recno_t nrec; + int status; + + t = dbp->internal; + + /* Toss any page pinned across calls. */ + if (t->bt_pinned != NULL) { + mpool_put(t->bt_mp, t->bt_pinned, 0); + t->bt_pinned = NULL; + } + + switch(flags) { + case 0: + if ((nrec = *(recno_t *)key->data) == 0) + goto einval; + if (nrec > t->bt_nrecs) + return (RET_SPECIAL); + --nrec; + status = rec_rdelete(t, nrec); + break; + case R_CURSOR: + if (!F_ISSET(&t->bt_cursor, CURS_INIT)) + goto einval; + if (t->bt_nrecs == 0) + return (RET_SPECIAL); + status = rec_rdelete(t, t->bt_cursor.rcursor - 1); + if (status == RET_SUCCESS) + --t->bt_cursor.rcursor; + break; + default: +einval: errno = EINVAL; + return (RET_ERROR); + } + + if (status == RET_SUCCESS) + F_SET(t, B_MODIFIED | R_MODIFIED); + return (status); +} + +/* + * REC_RDELETE -- Delete the data matching the specified key. + * + * Parameters: + * tree: tree + * nrec: record to delete + * + * Returns: + * RET_ERROR, RET_SUCCESS and RET_SPECIAL if the key not found. + */ +static int +rec_rdelete(t, nrec) + BTREE *t; + recno_t nrec; +{ + EPG *e; + PAGE *h; + int status; + + /* Find the record; __rec_search pins the page. */ + if ((e = __rec_search(t, nrec, SDELETE)) == NULL) + return (RET_ERROR); + + /* Delete the record. */ + h = e->page; + status = __rec_dleaf(t, h, e->index); + if (status != RET_SUCCESS) { + mpool_put(t->bt_mp, h, 0); + return (status); + } + mpool_put(t->bt_mp, h, MPOOL_DIRTY); + return (RET_SUCCESS); +} + +/* + * __REC_DLEAF -- Delete a single record from a recno leaf page. + * + * Parameters: + * t: tree + * index: index on current page to delete + * + * Returns: + * RET_SUCCESS, RET_ERROR. + */ +int +__rec_dleaf(t, h, index) + BTREE *t; + PAGE *h; + uint32_t index; +{ + RLEAF *rl; + indx_t *ip, cnt, offset; + uint32_t nbytes; + char *from; + void *to; + + /* + * Delete a record from a recno leaf page. Internal records are never + * deleted from internal pages, regardless of the records that caused + * them to be added being deleted. Pages made empty by deletion are + * not reclaimed. They are, however, made available for reuse. + * + * Pack the remaining entries at the end of the page, shift the indices + * down, overwriting the deleted record and its index. If the record + * uses overflow pages, make them available for reuse. + */ + to = rl = GETRLEAF(h, index); + if (rl->flags & P_BIGDATA && __ovfl_delete(t, rl->bytes) == RET_ERROR) + return (RET_ERROR); + nbytes = NRLEAF(rl); + + /* + * Compress the key/data pairs. Compress and adjust the [BR]LEAF + * offsets. Reset the headers. + */ + from = (char *)h + h->upper; + memmove(from + nbytes, from, (char *)to - from); + h->upper += nbytes; + + offset = h->linp[index]; + for (cnt = &h->linp[index] - (ip = &h->linp[0]); cnt--; ++ip) + if (ip[0] < offset) + ip[0] += nbytes; + for (cnt = &h->linp[NEXTINDEX(h)] - ip; --cnt; ++ip) + ip[0] = ip[1] < offset ? ip[1] + nbytes : ip[1]; + h->lower -= sizeof(indx_t); + --t->bt_nrecs; + return (RET_SUCCESS); +} diff --git a/lib/libc/db/recno/rec_get.c b/lib/libc/db/recno/rec_get.c new file mode 100644 index 0000000..d9da658 --- /dev/null +++ b/lib/libc/db/recno/rec_get.c @@ -0,0 +1,313 @@ +/*- + * Copyright (c) 1990, 1993, 1994 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)rec_get.c 8.9 (Berkeley) 8/18/94"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/db/recno/rec_get.c,v 1.5 2002/03/22 21:52:02 obrien Exp $"); + +#include + +#include +#include +#include +#include +#include +#include + +#include +#include "recno.h" + +/* + * __REC_GET -- Get a record from the btree. + * + * Parameters: + * dbp: pointer to access method + * key: key to find + * data: data to return + * flag: currently unused + * + * Returns: + * RET_ERROR, RET_SUCCESS and RET_SPECIAL if the key not found. + */ +int +__rec_get(dbp, key, data, flags) + const DB *dbp; + const DBT *key; + DBT *data; + u_int flags; +{ + BTREE *t; + EPG *e; + recno_t nrec; + int status; + + t = dbp->internal; + + /* Toss any page pinned across calls. */ + if (t->bt_pinned != NULL) { + mpool_put(t->bt_mp, t->bt_pinned, 0); + t->bt_pinned = NULL; + } + + /* Get currently doesn't take any flags, and keys of 0 are illegal. */ + if (flags || (nrec = *(recno_t *)key->data) == 0) { + errno = EINVAL; + return (RET_ERROR); + } + + /* + * If we haven't seen this record yet, try to find it in the + * original file. + */ + if (nrec > t->bt_nrecs) { + if (F_ISSET(t, R_EOF | R_INMEM)) + return (RET_SPECIAL); + if ((status = t->bt_irec(t, nrec)) != RET_SUCCESS) + return (status); + } + + --nrec; + if ((e = __rec_search(t, nrec, SEARCH)) == NULL) + return (RET_ERROR); + + status = __rec_ret(t, e, 0, NULL, data); + if (F_ISSET(t, B_DB_LOCK)) + mpool_put(t->bt_mp, e->page, 0); + else + t->bt_pinned = e->page; + return (status); +} + +/* + * __REC_FPIPE -- Get fixed length records from a pipe. + * + * Parameters: + * t: tree + * cnt: records to read + * + * Returns: + * RET_ERROR, RET_SUCCESS + */ +int +__rec_fpipe(t, top) + BTREE *t; + recno_t top; +{ + DBT data; + recno_t nrec; + size_t len; + int ch; + u_char *p; + + if (t->bt_rdata.size < t->bt_reclen) { + t->bt_rdata.data = t->bt_rdata.data == NULL ? + malloc(t->bt_reclen) : + reallocf(t->bt_rdata.data, t->bt_reclen); + if (t->bt_rdata.data == NULL) + return (RET_ERROR); + t->bt_rdata.size = t->bt_reclen; + } + data.data = t->bt_rdata.data; + data.size = t->bt_reclen; + + for (nrec = t->bt_nrecs; nrec < top;) { + len = t->bt_reclen; + for (p = t->bt_rdata.data;; *p++ = ch) + if ((ch = getc(t->bt_rfp)) == EOF || !--len) { + if (ch != EOF) + *p = ch; + if (len != 0) + memset(p, t->bt_bval, len); + if (__rec_iput(t, + nrec, &data, 0) != RET_SUCCESS) + return (RET_ERROR); + ++nrec; + break; + } + if (ch == EOF) + break; + } + if (nrec < top) { + F_SET(t, R_EOF); + return (RET_SPECIAL); + } + return (RET_SUCCESS); +} + +/* + * __REC_VPIPE -- Get variable length records from a pipe. + * + * Parameters: + * t: tree + * cnt: records to read + * + * Returns: + * RET_ERROR, RET_SUCCESS + */ +int +__rec_vpipe(t, top) + BTREE *t; + recno_t top; +{ + DBT data; + recno_t nrec; + size_t len; + size_t sz; + int bval, ch; + u_char *p; + + bval = t->bt_bval; + for (nrec = t->bt_nrecs; nrec < top; ++nrec) { + for (p = t->bt_rdata.data, + sz = t->bt_rdata.size;; *p++ = ch, --sz) { + if ((ch = getc(t->bt_rfp)) == EOF || ch == bval) { + data.data = t->bt_rdata.data; + data.size = p - (u_char *)t->bt_rdata.data; + if (ch == EOF && data.size == 0) + break; + if (__rec_iput(t, nrec, &data, 0) + != RET_SUCCESS) + return (RET_ERROR); + break; + } + if (sz == 0) { + len = p - (u_char *)t->bt_rdata.data; + t->bt_rdata.size += (sz = 256); + t->bt_rdata.data = t->bt_rdata.data == NULL ? + malloc(t->bt_rdata.size) : + reallocf(t->bt_rdata.data, t->bt_rdata.size); + if (t->bt_rdata.data == NULL) + return (RET_ERROR); + p = (u_char *)t->bt_rdata.data + len; + } + } + if (ch == EOF) + break; + } + if (nrec < top) { + F_SET(t, R_EOF); + return (RET_SPECIAL); + } + return (RET_SUCCESS); +} + +/* + * __REC_FMAP -- Get fixed length records from a file. + * + * Parameters: + * t: tree + * cnt: records to read + * + * Returns: + * RET_ERROR, RET_SUCCESS + */ +int +__rec_fmap(t, top) + BTREE *t; + recno_t top; +{ + DBT data; + recno_t nrec; + u_char *sp, *ep, *p; + size_t len; + + if (t->bt_rdata.size < t->bt_reclen) { + t->bt_rdata.data = t->bt_rdata.data == NULL ? + malloc(t->bt_reclen) : + reallocf(t->bt_rdata.data, t->bt_reclen); + if (t->bt_rdata.data == NULL) + return (RET_ERROR); + t->bt_rdata.size = t->bt_reclen; + } + data.data = t->bt_rdata.data; + data.size = t->bt_reclen; + + sp = (u_char *)t->bt_cmap; + ep = (u_char *)t->bt_emap; + for (nrec = t->bt_nrecs; nrec < top; ++nrec) { + if (sp >= ep) { + F_SET(t, R_EOF); + return (RET_SPECIAL); + } + len = t->bt_reclen; + for (p = t->bt_rdata.data; + sp < ep && len > 0; *p++ = *sp++, --len); + if (len != 0) + memset(p, t->bt_bval, len); + if (__rec_iput(t, nrec, &data, 0) != RET_SUCCESS) + return (RET_ERROR); + } + t->bt_cmap = (caddr_t)sp; + return (RET_SUCCESS); +} + +/* + * __REC_VMAP -- Get variable length records from a file. + * + * Parameters: + * t: tree + * cnt: records to read + * + * Returns: + * RET_ERROR, RET_SUCCESS + */ +int +__rec_vmap(t, top) + BTREE *t; + recno_t top; +{ + DBT data; + u_char *sp, *ep; + recno_t nrec; + int bval; + + sp = (u_char *)t->bt_cmap; + ep = (u_char *)t->bt_emap; + bval = t->bt_bval; + + for (nrec = t->bt_nrecs; nrec < top; ++nrec) { + if (sp >= ep) { + F_SET(t, R_EOF); + return (RET_SPECIAL); + } + for (data.data = sp; sp < ep && *sp != bval; ++sp); + data.size = sp - (u_char *)data.data; + if (__rec_iput(t, nrec, &data, 0) != RET_SUCCESS) + return (RET_ERROR); + ++sp; + } + t->bt_cmap = (caddr_t)sp; + return (RET_SUCCESS); +} diff --git a/lib/libc/db/recno/rec_open.c b/lib/libc/db/recno/rec_open.c new file mode 100644 index 0000000..a431f6f --- /dev/null +++ b/lib/libc/db/recno/rec_open.c @@ -0,0 +1,245 @@ +/*- + * Copyright (c) 1990, 1993, 1994 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * Mike Olson. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)rec_open.c 8.10 (Berkeley) 9/1/94"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/db/recno/rec_open.c,v 1.6 2002/03/22 21:52:02 obrien Exp $"); + +#include "namespace.h" +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include "un-namespace.h" + +#include +#include "recno.h" + +DB * +__rec_open(fname, flags, mode, openinfo, dflags) + const char *fname; + int flags, mode, dflags; + const RECNOINFO *openinfo; +{ + BTREE *t; + BTREEINFO btopeninfo; + DB *dbp; + PAGE *h; + struct stat sb; + int rfd, sverrno; + + /* Open the user's file -- if this fails, we're done. */ + if (fname != NULL && (rfd = _open(fname, flags, mode)) < 0) + return (NULL); + + /* Create a btree in memory (backed by disk). */ + dbp = NULL; + if (openinfo) { + if (openinfo->flags & ~(R_FIXEDLEN | R_NOKEY | R_SNAPSHOT)) + goto einval; + btopeninfo.flags = 0; + btopeninfo.cachesize = openinfo->cachesize; + btopeninfo.maxkeypage = 0; + btopeninfo.minkeypage = 0; + btopeninfo.psize = openinfo->psize; + btopeninfo.compare = NULL; + btopeninfo.prefix = NULL; + btopeninfo.lorder = openinfo->lorder; + dbp = __bt_open(openinfo->bfname, + O_RDWR, S_IRUSR | S_IWUSR, &btopeninfo, dflags); + } else + dbp = __bt_open(NULL, O_RDWR, S_IRUSR | S_IWUSR, NULL, dflags); + if (dbp == NULL) + goto err; + + /* + * Some fields in the tree structure are recno specific. Fill them + * in and make the btree structure look like a recno structure. We + * don't change the bt_ovflsize value, it's close enough and slightly + * bigger. + */ + t = dbp->internal; + if (openinfo) { + if (openinfo->flags & R_FIXEDLEN) { + F_SET(t, R_FIXLEN); + t->bt_reclen = openinfo->reclen; + if (t->bt_reclen == 0) + goto einval; + } + t->bt_bval = openinfo->bval; + } else + t->bt_bval = '\n'; + + F_SET(t, R_RECNO); + if (fname == NULL) + F_SET(t, R_EOF | R_INMEM); + else + t->bt_rfd = rfd; + + if (fname != NULL) { + /* + * In 4.4BSD, stat(2) returns true for ISSOCK on pipes. + * Unfortunately, that's not portable, so we use lseek + * and check the errno values. + */ + errno = 0; + if (lseek(rfd, (off_t)0, SEEK_CUR) == -1 && errno == ESPIPE) { + switch (flags & O_ACCMODE) { + case O_RDONLY: + F_SET(t, R_RDONLY); + break; + default: + goto einval; + } +slow: if ((t->bt_rfp = fdopen(rfd, "r")) == NULL) + goto err; + F_SET(t, R_CLOSEFP); + t->bt_irec = + F_ISSET(t, R_FIXLEN) ? __rec_fpipe : __rec_vpipe; + } else { + switch (flags & O_ACCMODE) { + case O_RDONLY: + F_SET(t, R_RDONLY); + break; + case O_RDWR: + break; + default: + goto einval; + } + + if (_fstat(rfd, &sb)) + goto err; + /* + * Kluge -- we'd like to test to see if the file is too + * big to mmap. Since, we don't know what size or type + * off_t's or size_t's are, what the largest unsigned + * integral type is, or what random insanity the local + * C compiler will perpetrate, doing the comparison in + * a portable way is flatly impossible. Hope that mmap + * fails if the file is too large. + */ + if (sb.st_size == 0) + F_SET(t, R_EOF); + else { +#ifdef MMAP_NOT_AVAILABLE + /* + * XXX + * Mmap doesn't work correctly on many current + * systems. In particular, it can fail subtly, + * with cache coherency problems. Don't use it + * for now. + */ + t->bt_msize = sb.st_size; + if ((t->bt_smap = mmap(NULL, t->bt_msize, + PROT_READ, MAP_PRIVATE, rfd, + (off_t)0)) == MAP_FAILED) + goto slow; + t->bt_cmap = t->bt_smap; + t->bt_emap = t->bt_smap + sb.st_size; + t->bt_irec = F_ISSET(t, R_FIXLEN) ? + __rec_fmap : __rec_vmap; + F_SET(t, R_MEMMAPPED); +#else + goto slow; +#endif + } + } + } + + /* Use the recno routines. */ + dbp->close = __rec_close; + dbp->del = __rec_delete; + dbp->fd = __rec_fd; + dbp->get = __rec_get; + dbp->put = __rec_put; + dbp->seq = __rec_seq; + dbp->sync = __rec_sync; + + /* If the root page was created, reset the flags. */ + if ((h = mpool_get(t->bt_mp, P_ROOT, 0)) == NULL) + goto err; + if ((h->flags & P_TYPE) == P_BLEAF) { + F_CLR(h, P_TYPE); + F_SET(h, P_RLEAF); + mpool_put(t->bt_mp, h, MPOOL_DIRTY); + } else + mpool_put(t->bt_mp, h, 0); + + if (openinfo && openinfo->flags & R_SNAPSHOT && + !F_ISSET(t, R_EOF | R_INMEM) && + t->bt_irec(t, MAX_REC_NUMBER) == RET_ERROR) + goto err; + return (dbp); + +einval: errno = EINVAL; +err: sverrno = errno; + if (dbp != NULL) + (void)__bt_close(dbp); + if (fname != NULL) + (void)_close(rfd); + errno = sverrno; + return (NULL); +} + +int +__rec_fd(dbp) + const DB *dbp; +{ + BTREE *t; + + t = dbp->internal; + + /* Toss any page pinned across calls. */ + if (t->bt_pinned != NULL) { + mpool_put(t->bt_mp, t->bt_pinned, 0); + t->bt_pinned = NULL; + } + + /* In-memory database can't have a file descriptor. */ + if (F_ISSET(t, R_INMEM)) { + errno = ENOENT; + return (-1); + } + return (t->bt_rfd); +} diff --git a/lib/libc/db/recno/rec_put.c b/lib/libc/db/recno/rec_put.c new file mode 100644 index 0000000..064aaa6 --- /dev/null +++ b/lib/libc/db/recno/rec_put.c @@ -0,0 +1,287 @@ +/*- + * Copyright (c) 1990, 1993, 1994 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)rec_put.c 8.7 (Berkeley) 8/18/94"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/db/recno/rec_put.c,v 1.6 2002/03/22 21:52:02 obrien Exp $"); + +#include + +#include +#include +#include +#include + +#include +#include "recno.h" + +/* + * __REC_PUT -- Add a recno item to the tree. + * + * Parameters: + * dbp: pointer to access method + * key: key + * data: data + * flag: R_CURSOR, R_IAFTER, R_IBEFORE, R_NOOVERWRITE + * + * Returns: + * RET_ERROR, RET_SUCCESS and RET_SPECIAL if the key is + * already in the tree and R_NOOVERWRITE specified. + */ +int +__rec_put(dbp, key, data, flags) + const DB *dbp; + DBT *key; + const DBT *data; + u_int flags; +{ + BTREE *t; + DBT fdata, tdata; + recno_t nrec; + int status; + + t = dbp->internal; + + /* Toss any page pinned across calls. */ + if (t->bt_pinned != NULL) { + mpool_put(t->bt_mp, t->bt_pinned, 0); + t->bt_pinned = NULL; + } + + /* + * If using fixed-length records, and the record is long, return + * EINVAL. If it's short, pad it out. Use the record data return + * memory, it's only short-term. + */ + if (F_ISSET(t, R_FIXLEN) && data->size != t->bt_reclen) { + if (data->size > t->bt_reclen) + goto einval; + + if (t->bt_rdata.size < t->bt_reclen) { + t->bt_rdata.data = + reallocf(t->bt_rdata.data, t->bt_reclen); + if (t->bt_rdata.data == NULL) + return (RET_ERROR); + t->bt_rdata.size = t->bt_reclen; + } + memmove(t->bt_rdata.data, data->data, data->size); + memset((char *)t->bt_rdata.data + data->size, + t->bt_bval, t->bt_reclen - data->size); + fdata.data = t->bt_rdata.data; + fdata.size = t->bt_reclen; + } else { + fdata.data = data->data; + fdata.size = data->size; + } + + switch (flags) { + case R_CURSOR: + if (!F_ISSET(&t->bt_cursor, CURS_INIT)) + goto einval; + nrec = t->bt_cursor.rcursor; + break; + case R_SETCURSOR: + if ((nrec = *(recno_t *)key->data) == 0) + goto einval; + break; + case R_IAFTER: + if ((nrec = *(recno_t *)key->data) == 0) { + nrec = 1; + flags = R_IBEFORE; + } + break; + case 0: + case R_IBEFORE: + if ((nrec = *(recno_t *)key->data) == 0) + goto einval; + break; + case R_NOOVERWRITE: + if ((nrec = *(recno_t *)key->data) == 0) + goto einval; + if (nrec <= t->bt_nrecs) + return (RET_SPECIAL); + break; + default: +einval: errno = EINVAL; + return (RET_ERROR); + } + + /* + * Make sure that records up to and including the put record are + * already in the database. If skipping records, create empty ones. + */ + if (nrec > t->bt_nrecs) { + if (!F_ISSET(t, R_EOF | R_INMEM) && + t->bt_irec(t, nrec) == RET_ERROR) + return (RET_ERROR); + if (nrec > t->bt_nrecs + 1) { + if (F_ISSET(t, R_FIXLEN)) { + if ((tdata.data = + (void *)malloc(t->bt_reclen)) == NULL) + return (RET_ERROR); + tdata.size = t->bt_reclen; + memset(tdata.data, t->bt_bval, tdata.size); + } else { + tdata.data = NULL; + tdata.size = 0; + } + while (nrec > t->bt_nrecs + 1) + if (__rec_iput(t, + t->bt_nrecs, &tdata, 0) != RET_SUCCESS) + return (RET_ERROR); + if (F_ISSET(t, R_FIXLEN)) + free(tdata.data); + } + } + + if ((status = __rec_iput(t, nrec - 1, &fdata, flags)) != RET_SUCCESS) + return (status); + + switch (flags) { + case R_IAFTER: + nrec++; + break; + case R_SETCURSOR: + t->bt_cursor.rcursor = nrec; + break; + } + + F_SET(t, R_MODIFIED); + return (__rec_ret(t, NULL, nrec, key, NULL)); +} + +/* + * __REC_IPUT -- Add a recno item to the tree. + * + * Parameters: + * t: tree + * nrec: record number + * data: data + * + * Returns: + * RET_ERROR, RET_SUCCESS + */ +int +__rec_iput(t, nrec, data, flags) + BTREE *t; + recno_t nrec; + const DBT *data; + u_int flags; +{ + DBT tdata; + EPG *e; + PAGE *h; + indx_t index, nxtindex; + pgno_t pg; + uint32_t nbytes; + int dflags, status; + char *dest, db[NOVFLSIZE]; + + /* + * If the data won't fit on a page, store it on indirect pages. + * + * XXX + * If the insert fails later on, these pages aren't recovered. + */ + if (data->size > t->bt_ovflsize) { + if (__ovfl_put(t, data, &pg) == RET_ERROR) + return (RET_ERROR); + tdata.data = db; + tdata.size = NOVFLSIZE; + *(pgno_t *)db = pg; + *(uint32_t *)(db + sizeof(pgno_t)) = data->size; + dflags = P_BIGDATA; + data = &tdata; + } else + dflags = 0; + + /* __rec_search pins the returned page. */ + if ((e = __rec_search(t, nrec, + nrec > t->bt_nrecs || flags == R_IAFTER || flags == R_IBEFORE ? + SINSERT : SEARCH)) == NULL) + return (RET_ERROR); + + h = e->page; + index = e->index; + + /* + * Add the specified key/data pair to the tree. The R_IAFTER and + * R_IBEFORE flags insert the key after/before the specified key. + * + * Pages are split as required. + */ + switch (flags) { + case R_IAFTER: + ++index; + break; + case R_IBEFORE: + break; + default: + if (nrec < t->bt_nrecs && + __rec_dleaf(t, h, index) == RET_ERROR) { + mpool_put(t->bt_mp, h, 0); + return (RET_ERROR); + } + break; + } + + /* + * If not enough room, split the page. The split code will insert + * the key and data and unpin the current page. If inserting into + * the offset array, shift the pointers up. + */ + nbytes = NRLEAFDBT(data->size); + if (h->upper - h->lower < nbytes + sizeof(indx_t)) { + status = __bt_split(t, h, NULL, data, dflags, nbytes, index); + if (status == RET_SUCCESS) + ++t->bt_nrecs; + return (status); + } + + if (index < (nxtindex = NEXTINDEX(h))) + memmove(h->linp + index + 1, h->linp + index, + (nxtindex - index) * sizeof(indx_t)); + h->lower += sizeof(indx_t); + + h->linp[index] = h->upper -= nbytes; + dest = (char *)h + h->upper; + WR_RLEAF(dest, data, dflags); + + ++t->bt_nrecs; + F_SET(t, B_MODIFIED); + mpool_put(t->bt_mp, h, MPOOL_DIRTY); + + return (RET_SUCCESS); +} diff --git a/lib/libc/db/recno/rec_search.c b/lib/libc/db/recno/rec_search.c new file mode 100644 index 0000000..3353bfb --- /dev/null +++ b/lib/libc/db/recno/rec_search.c @@ -0,0 +1,128 @@ +/*- + * Copyright (c) 1990, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)rec_search.c 8.4 (Berkeley) 7/14/94"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/db/recno/rec_search.c,v 1.4 2002/03/21 18:47:38 obrien Exp $"); + +#include + +#include +#include + +#include +#include "recno.h" + +/* + * __REC_SEARCH -- Search a btree for a key. + * + * Parameters: + * t: tree to search + * recno: key to find + * op: search operation + * + * Returns: + * EPG for matching record, if any, or the EPG for the location of the + * key, if it were inserted into the tree. + * + * Returns: + * The EPG for matching record, if any, or the EPG for the location + * of the key, if it were inserted into the tree, is entered into + * the bt_cur field of the tree. A pointer to the field is returned. + */ +EPG * +__rec_search(t, recno, op) + BTREE *t; + recno_t recno; + enum SRCHOP op; +{ + indx_t index; + PAGE *h; + EPGNO *parent; + RINTERNAL *r; + pgno_t pg; + indx_t top; + recno_t total; + int sverrno; + + BT_CLR(t); + for (pg = P_ROOT, total = 0;;) { + if ((h = mpool_get(t->bt_mp, pg, 0)) == NULL) + goto err; + if (h->flags & P_RLEAF) { + t->bt_cur.page = h; + t->bt_cur.index = recno - total; + return (&t->bt_cur); + } + for (index = 0, top = NEXTINDEX(h);;) { + r = GETRINTERNAL(h, index); + if (++index == top || total + r->nrecs > recno) + break; + total += r->nrecs; + } + + BT_PUSH(t, pg, index - 1); + + pg = r->pgno; + switch (op) { + case SDELETE: + --GETRINTERNAL(h, (index - 1))->nrecs; + mpool_put(t->bt_mp, h, MPOOL_DIRTY); + break; + case SINSERT: + ++GETRINTERNAL(h, (index - 1))->nrecs; + mpool_put(t->bt_mp, h, MPOOL_DIRTY); + break; + case SEARCH: + mpool_put(t->bt_mp, h, 0); + break; + } + + } + /* Try and recover the tree. */ +err: sverrno = errno; + if (op != SEARCH) + while ((parent = BT_POP(t)) != NULL) { + if ((h = mpool_get(t->bt_mp, parent->pgno, 0)) == NULL) + break; + if (op == SINSERT) + --GETRINTERNAL(h, parent->index)->nrecs; + else + ++GETRINTERNAL(h, parent->index)->nrecs; + mpool_put(t->bt_mp, h, MPOOL_DIRTY); + } + errno = sverrno; + return (NULL); +} diff --git a/lib/libc/db/recno/rec_seq.c b/lib/libc/db/recno/rec_seq.c new file mode 100644 index 0000000..6ed3384 --- /dev/null +++ b/lib/libc/db/recno/rec_seq.c @@ -0,0 +1,134 @@ +/*- + * Copyright (c) 1991, 1993, 1994 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#include +#ifndef lint +/* XXX use __SCCSID */ +static char sccsid[] __unused = "@(#)rec_seq.c 8.3 (Berkeley) 7/14/94"; +#endif /* not lint */ +__FBSDID("$FreeBSD: src/lib/libc/db/recno/rec_seq.c,v 1.5 2003/02/16 17:29:09 nectar Exp $"); + +#include + +#include +#include +#include +#include + +#include +#include "recno.h" + +/* + * __REC_SEQ -- Recno sequential scan interface. + * + * Parameters: + * dbp: pointer to access method + * key: key for positioning and return value + * data: data return value + * flags: R_CURSOR, R_FIRST, R_LAST, R_NEXT, R_PREV. + * + * Returns: + * RET_ERROR, RET_SUCCESS or RET_SPECIAL if there's no next key. + */ +int +__rec_seq(dbp, key, data, flags) + const DB *dbp; + DBT *key, *data; + u_int flags; +{ + BTREE *t; + EPG *e; + recno_t nrec; + int status; + + t = dbp->internal; + + /* Toss any page pinned across calls. */ + if (t->bt_pinned != NULL) { + mpool_put(t->bt_mp, t->bt_pinned, 0); + t->bt_pinned = NULL; + } + + switch(flags) { + case R_CURSOR: + if ((nrec = *(recno_t *)key->data) == 0) + goto einval; + break; + case R_NEXT: + if (F_ISSET(&t->bt_cursor, CURS_INIT)) { + nrec = t->bt_cursor.rcursor + 1; + break; + } + /* FALLTHROUGH */ + case R_FIRST: + nrec = 1; + break; + case R_PREV: + if (F_ISSET(&t->bt_cursor, CURS_INIT)) { + if ((nrec = t->bt_cursor.rcursor - 1) == 0) + return (RET_SPECIAL); + break; + } + /* FALLTHROUGH */ + case R_LAST: + if (!F_ISSET(t, R_EOF | R_INMEM) && + t->bt_irec(t, MAX_REC_NUMBER) == RET_ERROR) + return (RET_ERROR); + nrec = t->bt_nrecs; + break; + default: +einval: errno = EINVAL; + return (RET_ERROR); + } + + if (t->bt_nrecs == 0 || nrec > t->bt_nrecs) { + if (!F_ISSET(t, R_EOF | R_INMEM) && + (status = t->bt_irec(t, nrec)) != RET_SUCCESS) + return (status); + if (t->bt_nrecs == 0 || nrec > t->bt_nrecs) + return (RET_SPECIAL); + } + + if ((e = __rec_search(t, nrec - 1, SEARCH)) == NULL) + return (RET_ERROR); + + F_SET(&t->bt_cursor, CURS_INIT); + t->bt_cursor.rcursor = nrec; + + status = __rec_ret(t, e, nrec, key, data); + if (F_ISSET(t, B_DB_LOCK)) + mpool_put(t->bt_mp, e->page, 0); + else + t->bt_pinned = e->page; + return (status); +} diff --git a/lib/libc/db/recno/rec_utils.c b/lib/libc/db/recno/rec_utils.c new file mode 100644 index 0000000..81fa1d6 --- /dev/null +++ b/lib/libc/db/recno/rec_utils.c @@ -0,0 +1,124 @@ +/*- + * Copyright (c) 1990, 1993, 1994 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)rec_utils.c 8.6 (Berkeley) 7/16/94"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/db/recno/rec_utils.c,v 1.2 2002/03/22 21:52:02 obrien Exp $"); + +#include + +#include +#include +#include + +#include +#include "recno.h" + +/* + * __rec_ret -- + * Build return data. + * + * Parameters: + * t: tree + * e: key/data pair to be returned + * nrec: record number + * key: user's key structure + * data: user's data structure + * + * Returns: + * RET_SUCCESS, RET_ERROR. + */ +int +__rec_ret(t, e, nrec, key, data) + BTREE *t; + EPG *e; + recno_t nrec; + DBT *key, *data; +{ + RLEAF *rl; + void *p; + + if (key == NULL) + goto dataonly; + + /* We have to copy the key, it's not on the page. */ + if (sizeof(recno_t) > t->bt_rkey.size) { + p = (void *)(t->bt_rkey.data == NULL ? + malloc(sizeof(recno_t)) : + realloc(t->bt_rkey.data, sizeof(recno_t))); + if (p == NULL) + return (RET_ERROR); + t->bt_rkey.data = p; + t->bt_rkey.size = sizeof(recno_t); + } + memmove(t->bt_rkey.data, &nrec, sizeof(recno_t)); + key->size = sizeof(recno_t); + key->data = t->bt_rkey.data; + +dataonly: + if (data == NULL) + return (RET_SUCCESS); + + /* + * We must copy big keys/data to make them contigous. Otherwise, + * leave the page pinned and don't copy unless the user specified + * concurrent access. + */ + rl = GETRLEAF(e->page, e->index); + if (rl->flags & P_BIGDATA) { + if (__ovfl_get(t, rl->bytes, + &data->size, &t->bt_rdata.data, &t->bt_rdata.size)) + return (RET_ERROR); + data->data = t->bt_rdata.data; + } else if (F_ISSET(t, B_DB_LOCK)) { + /* Use +1 in case the first record retrieved is 0 length. */ + if (rl->dsize + 1 > t->bt_rdata.size) { + p = (void *)(t->bt_rdata.data == NULL ? + malloc(rl->dsize + 1) : + realloc(t->bt_rdata.data, rl->dsize + 1)); + if (p == NULL) + return (RET_ERROR); + t->bt_rdata.data = p; + t->bt_rdata.size = rl->dsize + 1; + } + memmove(t->bt_rdata.data, rl->bytes, rl->dsize); + data->size = rl->dsize; + data->data = t->bt_rdata.data; + } else { + data->size = rl->dsize; + data->data = rl->bytes; + } + return (RET_SUCCESS); +} diff --git a/lib/libc/db/recno/recno.h b/lib/libc/db/recno/recno.h new file mode 100644 index 0000000..b0c0af7 --- /dev/null +++ b/lib/libc/db/recno/recno.h @@ -0,0 +1,40 @@ +/*- + * Copyright (c) 1991, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * @(#)recno.h 8.1 (Berkeley) 6/4/93 + * $FreeBSD: src/lib/libc/db/recno/recno.h,v 1.2 2002/03/22 23:41:40 obrien Exp $ + */ + +enum SRCHOP { SDELETE, SINSERT, SEARCH}; /* Rec_search operation. */ + +#include "../btree/btree.h" +#include "extern.h" diff --git a/lib/libc/gdtoa/Makefile b/lib/libc/gdtoa/Makefile new file mode 100644 index 0000000..d135e56 --- /dev/null +++ b/lib/libc/gdtoa/Makefile @@ -0,0 +1,35 @@ +# $Id: Makefile 89 2016-01-12 00:20:40Z reddawg $ +# The System Makefile (C) 2002 The UbixOS Project + +# Include Global 'Source' Options +include ../../../Makefile.incl +include ../../Makefile.incl +include ../Makefile.incl + +INCLUDES += -I../locale/ -I../../../contrib/gdtoa -I../i386 + +#Objects +OBJS = _hdtoa.o _ldtoa.o arithchk.o dmisc.o dtoa.o g_Qfmt.o g__fmt.o g_ddfmt.o g_dfmt.o g_ffmt.o g_xLfmt.o g_xfmt.o gdtoa.o gethex.o glue.o gmisc.o hd_init.o hexnan.o machdep_ldisx.o misc.o smisc.o strtoIQ.o strtoId.o strtoIdd.o strtoIf.o strtoIg.o strtoIx.o strtoIxL.o strtod.o strtodI.o strtodg.o strtof.o strtopQ.o strtopd.o strtopdd.o strtopf.o strtopx.o strtopxL.o strtorQ.o strtord.o strtordd.o strtorf.o strtorx.o strtorxL.o sum.o ulp.o + +all: $(OBJS) + +# Compile the source files +.cc.o: + $(CXX) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -c -o $@ $< + +.cc.s: + $(CXX) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -S -o $@ $< + +.c.o: + $(CC) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -c $< + +.c.s: + $(CC) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -S -o $@ $< + +.S.o: + $(CC) $(CFLAGS) -Wall -nostdlib -c -o $@ $< + +# Clean up the junk +clean: + $(REMOVE) $(OBJS) + diff --git a/lib/libc/gdtoa/_hdtoa.c b/lib/libc/gdtoa/_hdtoa.c new file mode 100644 index 0000000..77e99ac --- /dev/null +++ b/lib/libc/gdtoa/_hdtoa.c @@ -0,0 +1,319 @@ +/*- + * Copyright (c) 2004, 2005 David Schultz + * 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 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 AUTHOR 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 +__FBSDID("$FreeBSD: src/lib/libc/gdtoa/_hdtoa.c,v 1.3 2005/01/18 18:44:07 das Exp $"); + +#include +#include +#include +#include "fpmath.h" +#include "gdtoaimp.h" + +/* Strings values used by dtoa() */ +#define INFSTR "Infinity" +#define NANSTR "NaN" + +#define DBL_ADJ (DBL_MAX_EXP - 2 + ((DBL_MANT_DIG - 1) % 4)) +#define LDBL_ADJ (LDBL_MAX_EXP - 2 + ((LDBL_MANT_DIG - 1) % 4)) + +/* + * Round up the given digit string. If the digit string is fff...f, + * this procedure sets it to 100...0 and returns 1 to indicate that + * the exponent needs to be bumped. Otherwise, 0 is returned. + */ +static int +roundup(char *s0, int ndigits) +{ + char *s; + + for (s = s0 + ndigits - 1; *s == 0xf; s--) { + if (s == s0) { + *s = 1; + return (1); + } + ++*s; + } + ++*s; + return (0); +} + +/* + * Round the given digit string to ndigits digits according to the + * current rounding mode. Note that this could produce a string whose + * value is not representable in the corresponding floating-point + * type. The exponent pointed to by decpt is adjusted if necessary. + */ +static void +dorounding(char *s0, int ndigits, int sign, int *decpt) +{ + int adjust = 0; /* do we need to adjust the exponent? */ + + switch (FLT_ROUNDS) { + case 0: /* toward zero */ + default: /* implementation-defined */ + break; + case 1: /* to nearest, halfway rounds to even */ + if ((s0[ndigits] > 8) || + (s0[ndigits] == 8 && s0[ndigits - 1] & 1)) + adjust = roundup(s0, ndigits); + break; + case 2: /* toward +inf */ + if (sign == 0) + adjust = roundup(s0, ndigits); + break; + case 3: /* toward -inf */ + if (sign != 0) + adjust = roundup(s0, ndigits); + break; + } + + if (adjust) + *decpt += 4; +} + +/* + * This procedure converts a double-precision number in IEEE format + * into a string of hexadecimal digits and an exponent of 2. Its + * behavior is bug-for-bug compatible with dtoa() in mode 2, with the + * following exceptions: + * + * - An ndigits < 0 causes it to use as many digits as necessary to + * represent the number exactly. + * - The additional xdigs argument should point to either the string + * "0123456789ABCDEF" or the string "0123456789abcdef", depending on + * which case is desired. + * - This routine does not repeat dtoa's mistake of setting decpt + * to 9999 in the case of an infinity or NaN. INT_MAX is used + * for this purpose instead. + * + * Note that the C99 standard does not specify what the leading digit + * should be for non-zero numbers. For instance, 0x1.3p3 is the same + * as 0x2.6p2 is the same as 0x4.cp3. This implementation chooses the + * first digit so that subsequent digits are aligned on nibble + * boundaries (before rounding). + * + * Inputs: d, xdigs, ndigits + * Outputs: decpt, sign, rve + */ +char * +__hdtoa(double d, const char *xdigs, int ndigits, int *decpt, int *sign, + char **rve) +{ + static const int sigfigs = (DBL_MANT_DIG + 3) / 4; + union IEEEd2bits u; + char *s, *s0; + int bufsize; + + u.d = d; + *sign = u.bits.sign; + + switch (fpclassify(d)) { + case FP_NORMAL: + *decpt = u.bits.exp - DBL_ADJ; + break; + case FP_ZERO: + *decpt = 1; + return (nrv_alloc("0", rve, 1)); + case FP_SUBNORMAL: + u.d *= 0x1p514; + *decpt = u.bits.exp - (514 + DBL_ADJ); + break; + case FP_INFINITE: + *decpt = INT_MAX; + return (nrv_alloc(INFSTR, rve, sizeof(INFSTR) - 1)); + case FP_NAN: + *decpt = INT_MAX; + return (nrv_alloc(NANSTR, rve, sizeof(NANSTR) - 1)); + default: + abort(); + } + + /* FP_NORMAL or FP_SUBNORMAL */ + + if (ndigits == 0) /* dtoa() compatibility */ + ndigits = 1; + + /* + * For simplicity, we generate all the digits even if the + * caller has requested fewer. + */ + bufsize = (sigfigs > ndigits) ? sigfigs : ndigits; + s0 = rv_alloc(bufsize); + + /* + * We work from right to left, first adding any requested zero + * padding, then the least significant portion of the + * mantissa, followed by the most significant. The buffer is + * filled with the byte values 0x0 through 0xf, which are + * converted to xdigs[0x0] through xdigs[0xf] after the + * rounding phase. + */ + for (s = s0 + bufsize - 1; s > s0 + sigfigs - 1; s--) + *s = 0; + for (; s > s0 + sigfigs - (DBL_MANL_SIZE / 4) - 1 && s > s0; s--) { + *s = u.bits.manl & 0xf; + u.bits.manl >>= 4; + } + for (; s > s0; s--) { + *s = u.bits.manh & 0xf; + u.bits.manh >>= 4; + } + + /* + * At this point, we have snarfed all the bits in the + * mantissa, with the possible exception of the highest-order + * (partial) nibble, which is dealt with by the next + * statement. We also tack on the implicit normalization bit. + */ + *s = u.bits.manh | (1U << ((DBL_MANT_DIG - 1) % 4)); + + /* If ndigits < 0, we are expected to auto-size the precision. */ + if (ndigits < 0) { + for (ndigits = sigfigs; s0[ndigits - 1] == 0; ndigits--) + ; + } + + if (sigfigs > ndigits && s0[ndigits] != 0) + dorounding(s0, ndigits, u.bits.sign, decpt); + + s = s0 + ndigits; + if (rve != NULL) + *rve = s; + *s-- = '\0'; + for (; s >= s0; s--) + *s = xdigs[(unsigned int)*s]; + + return (s0); +} + +#if (LDBL_MANT_DIG > DBL_MANT_DIG) + +/* + * This is the long double version of __hdtoa(). + */ +char * +__hldtoa(long double e, const char *xdigs, int ndigits, int *decpt, int *sign, + char **rve) +{ + static const int sigfigs = (LDBL_MANT_DIG + 3) / 4; + union IEEEl2bits u; + char *s, *s0; + int bufsize; + + u.e = e; + *sign = u.bits.sign; + + switch (fpclassify(e)) { + case FP_NORMAL: + *decpt = u.bits.exp - LDBL_ADJ; + break; + case FP_ZERO: + *decpt = 1; + return (nrv_alloc("0", rve, 1)); + case FP_SUBNORMAL: + u.e *= 0x1p514L; + *decpt = u.bits.exp - (514 + LDBL_ADJ); + break; + case FP_INFINITE: + *decpt = INT_MAX; + return (nrv_alloc(INFSTR, rve, sizeof(INFSTR) - 1)); + case FP_NAN: + *decpt = INT_MAX; + return (nrv_alloc(NANSTR, rve, sizeof(NANSTR) - 1)); + default: + abort(); + } + + /* FP_NORMAL or FP_SUBNORMAL */ + + if (ndigits == 0) /* dtoa() compatibility */ + ndigits = 1; + + /* + * For simplicity, we generate all the digits even if the + * caller has requested fewer. + */ + bufsize = (sigfigs > ndigits) ? sigfigs : ndigits; + s0 = rv_alloc(bufsize); + + /* + * We work from right to left, first adding any requested zero + * padding, then the least significant portion of the + * mantissa, followed by the most significant. The buffer is + * filled with the byte values 0x0 through 0xf, which are + * converted to xdigs[0x0] through xdigs[0xf] after the + * rounding phase. + */ + for (s = s0 + bufsize - 1; s > s0 + sigfigs - 1; s--) + *s = 0; + for (; s > s0 + sigfigs - (LDBL_MANL_SIZE / 4) - 1 && s > s0; s--) { + *s = u.bits.manl & 0xf; + u.bits.manl >>= 4; + } + for (; s > s0; s--) { + *s = u.bits.manh & 0xf; + u.bits.manh >>= 4; + } + + /* + * At this point, we have snarfed all the bits in the + * mantissa, with the possible exception of the highest-order + * (partial) nibble, which is dealt with by the next + * statement. We also tack on the implicit normalization bit. + */ + *s = u.bits.manh | (1U << ((LDBL_MANT_DIG - 1) % 4)); + + /* If ndigits < 0, we are expected to auto-size the precision. */ + if (ndigits < 0) { + for (ndigits = sigfigs; s0[ndigits - 1] == 0; ndigits--) + ; + } + + if (sigfigs > ndigits && s0[ndigits] != 0) + dorounding(s0, ndigits, u.bits.sign, decpt); + + s = s0 + ndigits; + if (rve != NULL) + *rve = s; + *s-- = '\0'; + for (; s >= s0; s--) + *s = xdigs[(unsigned int)*s]; + + return (s0); +} + +#else /* (LDBL_MANT_DIG == DBL_MANT_DIG) */ + +char * +__hldtoa(long double e, const char *xdigs, int ndigits, int *decpt, int *sign, + char **rve) +{ + + return (__hdtoa((double)e, xdigs, ndigits, decpt, sign, rve)); +} + +#endif /* (LDBL_MANT_DIG == DBL_MANT_DIG) */ diff --git a/lib/libc/gdtoa/_ldtoa.c b/lib/libc/gdtoa/_ldtoa.c new file mode 100644 index 0000000..ededc68 --- /dev/null +++ b/lib/libc/gdtoa/_ldtoa.c @@ -0,0 +1,100 @@ +/*- + * Copyright (c) 2003 David Schultz + * 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 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 AUTHOR 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 +__FBSDID("$FreeBSD: src/lib/libc/gdtoa/_ldtoa.c,v 1.2 2004/01/18 07:53:49 das Exp $"); + +#include +#include +#include +#include +#include +#include "fpmath.h" +#include "gdtoaimp.h" + +/* + * ldtoa() is a wrapper for gdtoa() that makes it smell like dtoa(), + * except that the floating point argument is passed by reference. + * When dtoa() is passed a NaN or infinity, it sets expt to 9999. + * However, a long double could have a valid exponent of 9999, so we + * use INT_MAX in ldtoa() instead. + */ +char * +__ldtoa(long double *ld, int mode, int ndigits, int *decpt, int *sign, + char **rve) +{ + static FPI fpi = { + LDBL_MANT_DIG, /* nbits */ + LDBL_MIN_EXP - LDBL_MANT_DIG, /* emin */ + LDBL_MAX_EXP - LDBL_MANT_DIG, /* emax */ + FPI_Round_near, /* rounding */ +#ifdef Sudden_Underflow /* unused, but correct anyway */ + 1 +#else + 0 +#endif + }; + int be, kind; + char *ret; + union IEEEl2bits u; + uint32_t bits[(LDBL_MANT_DIG + 31) / 32]; + + u.e = *ld; + *sign = u.bits.sign; + be = u.bits.exp - (LDBL_MAX_EXP - 1) - (LDBL_MANT_DIG - 1); + LDBL_TO_ARRAY32(u, bits); + + switch (fpclassify(u.e)) { + case FP_NORMAL: + kind = STRTOG_Normal; +#ifdef LDBL_IMPLICIT_NBIT + bits[LDBL_MANT_DIG / 32] |= 1 << ((LDBL_MANT_DIG - 1) % 32); +#endif /* LDBL_IMPLICIT_NBIT */ + break; + case FP_ZERO: + kind = STRTOG_Zero; + break; + case FP_SUBNORMAL: + kind = STRTOG_Denormal; +#ifdef LDBL_IMPLICIT_NBIT + be++; +#endif + break; + case FP_INFINITE: + kind = STRTOG_Infinite; + break; + case FP_NAN: + kind = STRTOG_NaN; + break; + default: + abort(); + } + + ret = gdtoa(&fpi, be, (ULong *)bits, &kind, mode, ndigits, decpt, rve); + if (*decpt == -32768) + *decpt = INT_MAX; + return ret; +} diff --git a/lib/libc/gdtoa/arithchk.c b/lib/libc/gdtoa/arithchk.c new file mode 100644 index 0000000..59eaad7 --- /dev/null +++ b/lib/libc/gdtoa/arithchk.c @@ -0,0 +1,182 @@ +/**************************************************************** +Copyright (C) 1997, 1998 Lucent Technologies +All Rights Reserved + +Permission to use, copy, modify, and distribute this software and +its documentation for any purpose and without fee is hereby +granted, provided that the above copyright notice appear in all +copies and that both that the copyright notice and this +permission notice and warranty disclaimer appear in supporting +documentation, and that the name of Lucent or any of its entities +not be used in advertising or publicity pertaining to +distribution of the software without specific, written prior +permission. + +LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, +INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. +IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY +SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER +IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. +****************************************************************/ + +/* Try to deduce arith.h from arithmetic properties. */ + +#include + + static int dalign; + typedef struct +Akind { + char *name; + int kind; + } Akind; + + static Akind +IEEE_8087 = { "IEEE_8087", 1 }, +IEEE_MC68k = { "IEEE_MC68k", 2 }, +IBM = { "IBM", 3 }, +VAX = { "VAX", 4 }, +CRAY = { "CRAY", 5}; + + static Akind * +Lcheck() +{ + union { + double d; + long L[2]; + } u; + struct { + double d; + long L; + } x[2]; + + if (sizeof(x) > 2*(sizeof(double) + sizeof(long))) + dalign = 1; + u.L[0] = u.L[1] = 0; + u.d = 1e13; + if (u.L[0] == 1117925532 && u.L[1] == -448790528) + return &IEEE_MC68k; + if (u.L[1] == 1117925532 && u.L[0] == -448790528) + return &IEEE_8087; + if (u.L[0] == -2065213935 && u.L[1] == 10752) + return &VAX; + if (u.L[0] == 1267827943 && u.L[1] == 704643072) + return &IBM; + return 0; + } + + static Akind * +icheck() +{ + union { + double d; + int L[2]; + } u; + struct { + double d; + int L; + } x[2]; + + if (sizeof(x) > 2*(sizeof(double) + sizeof(int))) + dalign = 1; + u.L[0] = u.L[1] = 0; + u.d = 1e13; + if (u.L[0] == 1117925532 && u.L[1] == -448790528) + return &IEEE_MC68k; + if (u.L[1] == 1117925532 && u.L[0] == -448790528) + return &IEEE_8087; + if (u.L[0] == -2065213935 && u.L[1] == 10752) + return &VAX; + if (u.L[0] == 1267827943 && u.L[1] == 704643072) + return &IBM; + return 0; + } + +char *emptyfmt = ""; /* avoid possible warning message with printf("") */ + + static Akind * +ccheck() +{ + union { + double d; + long L; + } u; + long Cray1; + + /* Cray1 = 4617762693716115456 -- without overflow on non-Crays */ + Cray1 = printf(emptyfmt) < 0 ? 0 : 4617762; + if (printf(emptyfmt, Cray1) >= 0) + Cray1 = 1000000*Cray1 + 693716; + if (printf(emptyfmt, Cray1) >= 0) + Cray1 = 1000000*Cray1 + 115456; + u.d = 1e13; + if (u.L == Cray1) + return &CRAY; + return 0; + } + + static int +fzcheck() +{ + double a, b; + int i; + + a = 1.; + b = .1; + for(i = 155;; b *= b, i >>= 1) { + if (i & 1) { + a *= b; + if (i == 1) + break; + } + } + b = a * a; + return b == 0.; + } + +main() +{ + Akind *a = 0; + int Ldef = 0; + FILE *f; + +#ifdef WRITE_ARITH_H /* for Symantec's buggy "make" */ + f = fopen("arith.h", "w"); + if (!f) { + printf("Cannot open arith.h\n"); + return 1; + } +#else + f = stdout; +#endif + + if (sizeof(double) == 2*sizeof(long)) + a = Lcheck(); + else if (sizeof(double) == 2*sizeof(int)) { + Ldef = 1; + a = icheck(); + } + else if (sizeof(double) == sizeof(long)) + a = ccheck(); + if (a) { + fprintf(f, "#define %s\n#define Arith_Kind_ASL %d\n", + a->name, a->kind); + if (Ldef) + fprintf(f, "#define Long int\n#define Intcast (int)(long)\n"); + if (dalign) + fprintf(f, "#define Double_Align\n"); + if (sizeof(char*) == 8) + fprintf(f, "#define X64_bit_pointers\n"); +#ifndef NO_LONG_LONG + if (sizeof(long long) < 8) +#endif + fprintf(f, "#define NO_LONG_LONG\n"); + if (a->kind <= 2 && fzcheck()) + fprintf(f, "#define Sudden_Underflow\n"); + return 0; + } + fprintf(f, "/* Unknown arithmetic */\n"); + return 1; + } diff --git a/lib/libc/gdtoa/dmisc.c b/lib/libc/gdtoa/dmisc.c new file mode 100644 index 0000000..14b5d7e --- /dev/null +++ b/lib/libc/gdtoa/dmisc.c @@ -0,0 +1,222 @@ +/**************************************************************** + +The author of this software is David M. Gay. + +Copyright (C) 1998 by Lucent Technologies +All Rights Reserved + +Permission to use, copy, modify, and distribute this software and +its documentation for any purpose and without fee is hereby +granted, provided that the above copyright notice appear in all +copies and that both that the copyright notice and this +permission notice and warranty disclaimer appear in supporting +documentation, and that the name of Lucent or any of its entities +not be used in advertising or publicity pertaining to +distribution of the software without specific, written prior +permission. + +LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, +INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. +IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY +SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER +IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. + +****************************************************************/ + +/* Please send bug reports to + David M. Gay + Bell Laboratories, Room 2C-463 + 600 Mountain Avenue + Murray Hill, NJ 07974-0636 + U.S.A. + dmg@bell-labs.com + */ + +#include "gdtoaimp.h" + +#ifndef MULTIPLE_THREADS + char *dtoa_result; +#endif + + char * +#ifdef KR_headers +rv_alloc(i) int i; +#else +rv_alloc(int i) +#endif +{ + int j, k, *r; + + j = sizeof(ULong); + for(k = 0; + sizeof(Bigint) - sizeof(ULong) - sizeof(int) + j <= i; + j <<= 1) + k++; + r = (int*)Balloc(k); + *r = k; + return +#ifndef MULTIPLE_THREADS + dtoa_result = +#endif + (char *)(r+1); + } + + char * +#ifdef KR_headers +nrv_alloc(s, rve, n) char *s, **rve; int n; +#else +nrv_alloc(char *s, char **rve, int n) +#endif +{ + char *rv, *t; + + t = rv = rv_alloc(n); + while((*t = *s++) !=0) + t++; + if (rve) + *rve = t; + return rv; + } + +/* freedtoa(s) must be used to free values s returned by dtoa + * when MULTIPLE_THREADS is #defined. It should be used in all cases, + * but for consistency with earlier versions of dtoa, it is optional + * when MULTIPLE_THREADS is not defined. + */ + + void +#ifdef KR_headers +freedtoa(s) char *s; +#else +freedtoa(char *s) +#endif +{ + Bigint *b = (Bigint *)((int *)s - 1); + b->maxwds = 1 << (b->k = *(int*)b); + Bfree(b); +#ifndef MULTIPLE_THREADS + if (s == dtoa_result) + dtoa_result = 0; +#endif + } + + int +quorem +#ifdef KR_headers + (b, S) Bigint *b, *S; +#else + (Bigint *b, Bigint *S) +#endif +{ + int n; + ULong *bx, *bxe, q, *sx, *sxe; +#ifdef ULLong + ULLong borrow, carry, y, ys; +#else + ULong borrow, carry, y, ys; +#ifdef Pack_32 + ULong si, z, zs; +#endif +#endif + + n = S->wds; +#ifdef DEBUG + /*debug*/ if (b->wds > n) + /*debug*/ Bug("oversize b in quorem"); +#endif + if (b->wds < n) + return 0; + sx = S->x; + sxe = sx + --n; + bx = b->x; + bxe = bx + n; + q = *bxe / (*sxe + 1); /* ensure q <= true quotient */ +#ifdef DEBUG + /*debug*/ if (q > 9) + /*debug*/ Bug("oversized quotient in quorem"); +#endif + if (q) { + borrow = 0; + carry = 0; + do { +#ifdef ULLong + ys = *sx++ * (ULLong)q + carry; + carry = ys >> 32; + y = *bx - (ys & 0xffffffffUL) - borrow; + borrow = y >> 32 & 1UL; + *bx++ = y & 0xffffffffUL; +#else +#ifdef Pack_32 + si = *sx++; + ys = (si & 0xffff) * q + carry; + zs = (si >> 16) * q + (ys >> 16); + carry = zs >> 16; + y = (*bx & 0xffff) - (ys & 0xffff) - borrow; + borrow = (y & 0x10000) >> 16; + z = (*bx >> 16) - (zs & 0xffff) - borrow; + borrow = (z & 0x10000) >> 16; + Storeinc(bx, z, y); +#else + ys = *sx++ * q + carry; + carry = ys >> 16; + y = *bx - (ys & 0xffff) - borrow; + borrow = (y & 0x10000) >> 16; + *bx++ = y & 0xffff; +#endif +#endif + } + while(sx <= sxe); + if (!*bxe) { + bx = b->x; + while(--bxe > bx && !*bxe) + --n; + b->wds = n; + } + } + if (cmp(b, S) >= 0) { + q++; + borrow = 0; + carry = 0; + bx = b->x; + sx = S->x; + do { +#ifdef ULLong + ys = *sx++ + carry; + carry = ys >> 32; + y = *bx - (ys & 0xffffffffUL) - borrow; + borrow = y >> 32 & 1UL; + *bx++ = y & 0xffffffffUL; +#else +#ifdef Pack_32 + si = *sx++; + ys = (si & 0xffff) + carry; + zs = (si >> 16) + (ys >> 16); + carry = zs >> 16; + y = (*bx & 0xffff) - (ys & 0xffff) - borrow; + borrow = (y & 0x10000) >> 16; + z = (*bx >> 16) - (zs & 0xffff) - borrow; + borrow = (z & 0x10000) >> 16; + Storeinc(bx, z, y); +#else + ys = *sx++ + carry; + carry = ys >> 16; + y = *bx - (ys & 0xffff) - borrow; + borrow = (y & 0x10000) >> 16; + *bx++ = y & 0xffff; +#endif +#endif + } + while(sx <= sxe); + bx = b->x; + bxe = bx + n; + if (!*bxe) { + while(--bxe > bx && !*bxe) + --n; + b->wds = n; + } + } + return q; + } diff --git a/lib/libc/gdtoa/dtoa.c b/lib/libc/gdtoa/dtoa.c new file mode 100644 index 0000000..20e2405 --- /dev/null +++ b/lib/libc/gdtoa/dtoa.c @@ -0,0 +1,759 @@ +/**************************************************************** + +The author of this software is David M. Gay. + +Copyright (C) 1998, 1999 by Lucent Technologies +All Rights Reserved + +Permission to use, copy, modify, and distribute this software and +its documentation for any purpose and without fee is hereby +granted, provided that the above copyright notice appear in all +copies and that both that the copyright notice and this +permission notice and warranty disclaimer appear in supporting +documentation, and that the name of Lucent or any of its entities +not be used in advertising or publicity pertaining to +distribution of the software without specific, written prior +permission. + +LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, +INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. +IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY +SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER +IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. + +****************************************************************/ + +/* Please send bug reports to + David M. Gay + Bell Laboratories, Room 2C-463 + 600 Mountain Avenue + Murray Hill, NJ 07974-0636 + U.S.A. + dmg@bell-labs.com + */ + +#include "gdtoaimp.h" + +/* dtoa for IEEE arithmetic (dmg): convert double to ASCII string. + * + * Inspired by "How to Print Floating-Point Numbers Accurately" by + * Guy L. Steele, Jr. and Jon L. White [Proc. ACM SIGPLAN '90, pp. 92-101]. + * + * Modifications: + * 1. Rather than iterating, we use a simple numeric overestimate + * to determine k = floor(log10(d)). We scale relevant + * quantities using O(log2(k)) rather than O(k) multiplications. + * 2. For some modes > 2 (corresponding to ecvt and fcvt), we don't + * try to generate digits strictly left to right. Instead, we + * compute with fewer bits and propagate the carry if necessary + * when rounding the final digit up. This is often faster. + * 3. Under the assumption that input will be rounded nearest, + * mode 0 renders 1e23 as 1e23 rather than 9.999999999999999e22. + * That is, we allow equality in stopping tests when the + * round-nearest rule will give the same floating-point value + * as would satisfaction of the stopping test with strict + * inequality. + * 4. We remove common factors of powers of 2 from relevant + * quantities. + * 5. When converting floating-point integers less than 1e16, + * we use floating-point arithmetic rather than resorting + * to multiple-precision integers. + * 6. When asked to produce fewer than 15 digits, we first try + * to get by with floating-point arithmetic; we resort to + * multiple-precision integer arithmetic only if we cannot + * guarantee that the floating-point calculation has given + * the correctly rounded result. For k requested digits and + * "uniformly" distributed input, the probability is + * something like 10^(k-15) that we must resort to the Long + * calculation. + */ + +#ifdef Honor_FLT_ROUNDS +#define Rounding rounding +#undef Check_FLT_ROUNDS +#define Check_FLT_ROUNDS +#else +#define Rounding Flt_Rounds +#endif + + char * +dtoa +#ifdef KR_headers + (d, mode, ndigits, decpt, sign, rve) + double d; int mode, ndigits, *decpt, *sign; char **rve; +#else + (double d, int mode, int ndigits, int *decpt, int *sign, char **rve) +#endif +{ + /* Arguments ndigits, decpt, sign are similar to those + of ecvt and fcvt; trailing zeros are suppressed from + the returned string. If not null, *rve is set to point + to the end of the return value. If d is +-Infinity or NaN, + then *decpt is set to 9999. + + mode: + 0 ==> shortest string that yields d when read in + and rounded to nearest. + 1 ==> like 0, but with Steele & White stopping rule; + e.g. with IEEE P754 arithmetic , mode 0 gives + 1e23 whereas mode 1 gives 9.999999999999999e22. + 2 ==> max(1,ndigits) significant digits. This gives a + return value similar to that of ecvt, except + that trailing zeros are suppressed. + 3 ==> through ndigits past the decimal point. This + gives a return value similar to that from fcvt, + except that trailing zeros are suppressed, and + ndigits can be negative. + 4,5 ==> similar to 2 and 3, respectively, but (in + round-nearest mode) with the tests of mode 0 to + possibly return a shorter string that rounds to d. + With IEEE arithmetic and compilation with + -DHonor_FLT_ROUNDS, modes 4 and 5 behave the same + as modes 2 and 3 when FLT_ROUNDS != 1. + 6-9 ==> Debugging modes similar to mode - 4: don't try + fast floating-point estimate (if applicable). + + Values of mode other than 0-9 are treated as mode 0. + + Sufficient space is allocated to the return value + to hold the suppressed trailing zeros. + */ + + int bbits, b2, b5, be, dig, i, ieps, ilim, ilim0, ilim1, + j, j1, k, k0, k_check, leftright, m2, m5, s2, s5, + spec_case, try_quick; + Long L; +#ifndef Sudden_Underflow + int denorm; + ULong x; +#endif + Bigint *b, *b1, *delta, *mlo, *mhi, *S; + double d2, ds, eps; + char *s, *s0; +#ifdef Honor_FLT_ROUNDS + int rounding; +#endif +#ifdef SET_INEXACT + int inexact, oldinexact; +#endif + +#ifndef MULTIPLE_THREADS + if (dtoa_result) { + freedtoa(dtoa_result); + dtoa_result = 0; + } +#endif + + if (word0(d) & Sign_bit) { + /* set sign for everything, including 0's and NaNs */ + *sign = 1; + word0(d) &= ~Sign_bit; /* clear sign bit */ + } + else + *sign = 0; + +#if defined(IEEE_Arith) + defined(VAX) +#ifdef IEEE_Arith + if ((word0(d) & Exp_mask) == Exp_mask) +#else + if (word0(d) == 0x8000) +#endif + { + /* Infinity or NaN */ + *decpt = 9999; +#ifdef IEEE_Arith + if (!word1(d) && !(word0(d) & 0xfffff)) + return nrv_alloc("Infinity", rve, 8); +#endif + return nrv_alloc("NaN", rve, 3); + } +#endif +#ifdef IBM + dval(d) += 0; /* normalize */ +#endif + if (!dval(d)) { + *decpt = 1; + return nrv_alloc("0", rve, 1); + } + +#ifdef SET_INEXACT + try_quick = oldinexact = get_inexact(); + inexact = 1; +#endif +#ifdef Honor_FLT_ROUNDS + if ((rounding = Flt_Rounds) >= 2) { + if (*sign) + rounding = rounding == 2 ? 0 : 2; + else + if (rounding != 2) + rounding = 0; + } +#endif + + b = d2b(dval(d), &be, &bbits); +#ifdef Sudden_Underflow + i = (int)(word0(d) >> Exp_shift1 & (Exp_mask>>Exp_shift1)); +#else + if (( i = (int)(word0(d) >> Exp_shift1 & (Exp_mask>>Exp_shift1)) )!=0) { +#endif + dval(d2) = dval(d); + word0(d2) &= Frac_mask1; + word0(d2) |= Exp_11; +#ifdef IBM + if (( j = 11 - hi0bits(word0(d2) & Frac_mask) )!=0) + dval(d2) /= 1 << j; +#endif + + /* log(x) ~=~ log(1.5) + (x-1.5)/1.5 + * log10(x) = log(x) / log(10) + * ~=~ log(1.5)/log(10) + (x-1.5)/(1.5*log(10)) + * log10(d) = (i-Bias)*log(2)/log(10) + log10(d2) + * + * This suggests computing an approximation k to log10(d) by + * + * k = (i - Bias)*0.301029995663981 + * + ( (d2-1.5)*0.289529654602168 + 0.176091259055681 ); + * + * We want k to be too large rather than too small. + * The error in the first-order Taylor series approximation + * is in our favor, so we just round up the constant enough + * to compensate for any error in the multiplication of + * (i - Bias) by 0.301029995663981; since |i - Bias| <= 1077, + * and 1077 * 0.30103 * 2^-52 ~=~ 7.2e-14, + * adding 1e-13 to the constant term more than suffices. + * Hence we adjust the constant term to 0.1760912590558. + * (We could get a more accurate k by invoking log10, + * but this is probably not worthwhile.) + */ + + i -= Bias; +#ifdef IBM + i <<= 2; + i += j; +#endif +#ifndef Sudden_Underflow + denorm = 0; + } + else { + /* d is denormalized */ + + i = bbits + be + (Bias + (P-1) - 1); + x = i > 32 ? word0(d) << 64 - i | word1(d) >> i - 32 + : word1(d) << 32 - i; + dval(d2) = x; + word0(d2) -= 31*Exp_msk1; /* adjust exponent */ + i -= (Bias + (P-1) - 1) + 1; + denorm = 1; + } +#endif + ds = (dval(d2)-1.5)*0.289529654602168 + 0.1760912590558 + i*0.301029995663981; + k = (int)ds; + if (ds < 0. && ds != k) + k--; /* want k = floor(ds) */ + k_check = 1; + if (k >= 0 && k <= Ten_pmax) { + if (dval(d) < tens[k]) + k--; + k_check = 0; + } + j = bbits - i - 1; + if (j >= 0) { + b2 = 0; + s2 = j; + } + else { + b2 = -j; + s2 = 0; + } + if (k >= 0) { + b5 = 0; + s5 = k; + s2 += k; + } + else { + b2 -= k; + b5 = -k; + s5 = 0; + } + if (mode < 0 || mode > 9) + mode = 0; + +#ifndef SET_INEXACT +#ifdef Check_FLT_ROUNDS + try_quick = Rounding == 1; +#else + try_quick = 1; +#endif +#endif /*SET_INEXACT*/ + + if (mode > 5) { + mode -= 4; + try_quick = 0; + } + leftright = 1; + switch(mode) { + case 0: + case 1: + ilim = ilim1 = -1; + i = 18; + ndigits = 0; + break; + case 2: + leftright = 0; + /* no break */ + case 4: + if (ndigits <= 0) + ndigits = 1; + ilim = ilim1 = i = ndigits; + break; + case 3: + leftright = 0; + /* no break */ + case 5: + i = ndigits + k + 1; + ilim = i; + ilim1 = i - 1; + if (i <= 0) + i = 1; + } + s = s0 = rv_alloc(i); + +#ifdef Honor_FLT_ROUNDS + if (mode > 1 && rounding != 1) + leftright = 0; +#endif + + if (ilim >= 0 && ilim <= Quick_max && try_quick) { + + /* Try to get by with floating-point arithmetic. */ + + i = 0; + dval(d2) = dval(d); + k0 = k; + ilim0 = ilim; + ieps = 2; /* conservative */ + if (k > 0) { + ds = tens[k&0xf]; + j = k >> 4; + if (j & Bletch) { + /* prevent overflows */ + j &= Bletch - 1; + dval(d) /= bigtens[n_bigtens-1]; + ieps++; + } + for(; j; j >>= 1, i++) + if (j & 1) { + ieps++; + ds *= bigtens[i]; + } + dval(d) /= ds; + } + else if (( j1 = -k )!=0) { + dval(d) *= tens[j1 & 0xf]; + for(j = j1 >> 4; j; j >>= 1, i++) + if (j & 1) { + ieps++; + dval(d) *= bigtens[i]; + } + } + if (k_check && dval(d) < 1. && ilim > 0) { + if (ilim1 <= 0) + goto fast_failed; + ilim = ilim1; + k--; + dval(d) *= 10.; + ieps++; + } + dval(eps) = ieps*dval(d) + 7.; + word0(eps) -= (P-1)*Exp_msk1; + if (ilim == 0) { + S = mhi = 0; + dval(d) -= 5.; + if (dval(d) > dval(eps)) + goto one_digit; + if (dval(d) < -dval(eps)) + goto no_digits; + goto fast_failed; + } +#ifndef No_leftright + if (leftright) { + /* Use Steele & White method of only + * generating digits needed. + */ + dval(eps) = 0.5/tens[ilim-1] - dval(eps); + for(i = 0;;) { + L = dval(d); + dval(d) -= L; + *s++ = '0' + (int)L; + if (dval(d) < dval(eps)) + goto ret1; + if (1. - dval(d) < dval(eps)) + goto bump_up; + if (++i >= ilim) + break; + dval(eps) *= 10.; + dval(d) *= 10.; + } + } + else { +#endif + /* Generate ilim digits, then fix them up. */ + dval(eps) *= tens[ilim-1]; + for(i = 1;; i++, dval(d) *= 10.) { + L = (Long)(dval(d)); + if (!(dval(d) -= L)) + ilim = i; + *s++ = '0' + (int)L; + if (i == ilim) { + if (dval(d) > 0.5 + dval(eps)) + goto bump_up; + else if (dval(d) < 0.5 - dval(eps)) { + while(*--s == '0'); + s++; + goto ret1; + } + break; + } + } +#ifndef No_leftright + } +#endif + fast_failed: + s = s0; + dval(d) = dval(d2); + k = k0; + ilim = ilim0; + } + + /* Do we have a "small" integer? */ + + if (be >= 0 && k <= Int_max) { + /* Yes. */ + ds = tens[k]; + if (ndigits < 0 && ilim <= 0) { + S = mhi = 0; + if (ilim < 0 || dval(d) <= 5*ds) + goto no_digits; + goto one_digit; + } + for(i = 1;; i++, dval(d) *= 10.) { + L = (Long)(dval(d) / ds); + dval(d) -= L*ds; +#ifdef Check_FLT_ROUNDS + /* If FLT_ROUNDS == 2, L will usually be high by 1 */ + if (dval(d) < 0) { + L--; + dval(d) += ds; + } +#endif + *s++ = '0' + (int)L; + if (!dval(d)) { +#ifdef SET_INEXACT + inexact = 0; +#endif + break; + } + if (i == ilim) { +#ifdef Honor_FLT_ROUNDS + if (mode > 1) + switch(rounding) { + case 0: goto ret1; + case 2: goto bump_up; + } +#endif + dval(d) += dval(d); + if (dval(d) > ds || dval(d) == ds && L & 1) { + bump_up: + while(*--s == '9') + if (s == s0) { + k++; + *s = '0'; + break; + } + ++*s++; + } + break; + } + } + goto ret1; + } + + m2 = b2; + m5 = b5; + mhi = mlo = 0; + if (leftright) { + i = +#ifndef Sudden_Underflow + denorm ? be + (Bias + (P-1) - 1 + 1) : +#endif +#ifdef IBM + 1 + 4*P - 3 - bbits + ((bbits + be - 1) & 3); +#else + 1 + P - bbits; +#endif + b2 += i; + s2 += i; + mhi = i2b(1); + } + if (m2 > 0 && s2 > 0) { + i = m2 < s2 ? m2 : s2; + b2 -= i; + m2 -= i; + s2 -= i; + } + if (b5 > 0) { + if (leftright) { + if (m5 > 0) { + mhi = pow5mult(mhi, m5); + b1 = mult(mhi, b); + Bfree(b); + b = b1; + } + if (( j = b5 - m5 )!=0) + b = pow5mult(b, j); + } + else + b = pow5mult(b, b5); + } + S = i2b(1); + if (s5 > 0) + S = pow5mult(S, s5); + + /* Check for special case that d is a normalized power of 2. */ + + spec_case = 0; + if ((mode < 2 || leftright) +#ifdef Honor_FLT_ROUNDS + && rounding == 1 +#endif + ) { + if (!word1(d) && !(word0(d) & Bndry_mask) +#ifndef Sudden_Underflow + && word0(d) & (Exp_mask & ~Exp_msk1) +#endif + ) { + /* The special case */ + b2 += Log2P; + s2 += Log2P; + spec_case = 1; + } + } + + /* Arrange for convenient computation of quotients: + * shift left if necessary so divisor has 4 leading 0 bits. + * + * Perhaps we should just compute leading 28 bits of S once + * and for all and pass them and a shift to quorem, so it + * can do shifts and ors to compute the numerator for q. + */ +#ifdef Pack_32 + if (( i = ((s5 ? 32 - hi0bits(S->x[S->wds-1]) : 1) + s2) & 0x1f )!=0) + i = 32 - i; +#else + if (( i = ((s5 ? 32 - hi0bits(S->x[S->wds-1]) : 1) + s2) & 0xf )!=0) + i = 16 - i; +#endif + if (i > 4) { + i -= 4; + b2 += i; + m2 += i; + s2 += i; + } + else if (i < 4) { + i += 28; + b2 += i; + m2 += i; + s2 += i; + } + if (b2 > 0) + b = lshift(b, b2); + if (s2 > 0) + S = lshift(S, s2); + if (k_check) { + if (cmp(b,S) < 0) { + k--; + b = multadd(b, 10, 0); /* we botched the k estimate */ + if (leftright) + mhi = multadd(mhi, 10, 0); + ilim = ilim1; + } + } + if (ilim <= 0 && (mode == 3 || mode == 5)) { + if (ilim < 0 || cmp(b,S = multadd(S,5,0)) <= 0) { + /* no digits, fcvt style */ + no_digits: + k = -1 - ndigits; + goto ret; + } + one_digit: + *s++ = '1'; + k++; + goto ret; + } + if (leftright) { + if (m2 > 0) + mhi = lshift(mhi, m2); + + /* Compute mlo -- check for special case + * that d is a normalized power of 2. + */ + + mlo = mhi; + if (spec_case) { + mhi = Balloc(mhi->k); + Bcopy(mhi, mlo); + mhi = lshift(mhi, Log2P); + } + + for(i = 1;;i++) { + dig = quorem(b,S) + '0'; + /* Do we yet have the shortest decimal string + * that will round to d? + */ + j = cmp(b, mlo); + delta = diff(S, mhi); + j1 = delta->sign ? 1 : cmp(b, delta); + Bfree(delta); +#ifndef ROUND_BIASED + if (j1 == 0 && mode != 1 && !(word1(d) & 1) +#ifdef Honor_FLT_ROUNDS + && rounding >= 1 +#endif + ) { + if (dig == '9') + goto round_9_up; + if (j > 0) + dig++; +#ifdef SET_INEXACT + else if (!b->x[0] && b->wds <= 1) + inexact = 0; +#endif + *s++ = dig; + goto ret; + } +#endif + if (j < 0 || j == 0 && mode != 1 +#ifndef ROUND_BIASED + && !(word1(d) & 1) +#endif + ) { + if (!b->x[0] && b->wds <= 1) { +#ifdef SET_INEXACT + inexact = 0; +#endif + goto accept_dig; + } +#ifdef Honor_FLT_ROUNDS + if (mode > 1) + switch(rounding) { + case 0: goto accept_dig; + case 2: goto keep_dig; + } +#endif /*Honor_FLT_ROUNDS*/ + if (j1 > 0) { + b = lshift(b, 1); + j1 = cmp(b, S); + if ((j1 > 0 || j1 == 0 && dig & 1) + && dig++ == '9') + goto round_9_up; + } + accept_dig: + *s++ = dig; + goto ret; + } + if (j1 > 0) { +#ifdef Honor_FLT_ROUNDS + if (!rounding) + goto accept_dig; +#endif + if (dig == '9') { /* possible if i == 1 */ + round_9_up: + *s++ = '9'; + goto roundoff; + } + *s++ = dig + 1; + goto ret; + } +#ifdef Honor_FLT_ROUNDS + keep_dig: +#endif + *s++ = dig; + if (i == ilim) + break; + b = multadd(b, 10, 0); + if (mlo == mhi) + mlo = mhi = multadd(mhi, 10, 0); + else { + mlo = multadd(mlo, 10, 0); + mhi = multadd(mhi, 10, 0); + } + } + } + else + for(i = 1;; i++) { + *s++ = dig = quorem(b,S) + '0'; + if (!b->x[0] && b->wds <= 1) { +#ifdef SET_INEXACT + inexact = 0; +#endif + goto ret; + } + if (i >= ilim) + break; + b = multadd(b, 10, 0); + } + + /* Round off last digit */ + +#ifdef Honor_FLT_ROUNDS + switch(rounding) { + case 0: goto trimzeros; + case 2: goto roundoff; + } +#endif + b = lshift(b, 1); + j = cmp(b, S); + if (j > 0 || j == 0 && dig & 1) { + roundoff: + while(*--s == '9') + if (s == s0) { + k++; + *s++ = '1'; + goto ret; + } + ++*s++; + } + else { + trimzeros: + while(*--s == '0'); + s++; + } + ret: + Bfree(S); + if (mhi) { + if (mlo && mlo != mhi) + Bfree(mlo); + Bfree(mhi); + } + ret1: +#ifdef SET_INEXACT + if (inexact) { + if (!oldinexact) { + word0(d) = Exp_1 + (70 << Exp_shift); + word1(d) = 0; + dval(d) += 1.; + } + } + else if (!oldinexact) + clear_inexact(); +#endif + Bfree(b); + *s = 0; + *decpt = k + 1; + if (rve) + *rve = s; + return s0; + } diff --git a/lib/libc/gdtoa/g_Qfmt.c b/lib/libc/gdtoa/g_Qfmt.c new file mode 100644 index 0000000..896b9d4 --- /dev/null +++ b/lib/libc/gdtoa/g_Qfmt.c @@ -0,0 +1,120 @@ +/**************************************************************** + +The author of this software is David M. Gay. + +Copyright (C) 1998, 2000 by Lucent Technologies +All Rights Reserved + +Permission to use, copy, modify, and distribute this software and +its documentation for any purpose and without fee is hereby +granted, provided that the above copyright notice appear in all +copies and that both that the copyright notice and this +permission notice and warranty disclaimer appear in supporting +documentation, and that the name of Lucent or any of its entities +not be used in advertising or publicity pertaining to +distribution of the software without specific, written prior +permission. + +LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, +INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. +IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY +SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER +IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. + +****************************************************************/ + +/* Please send bug reports to + David M. Gay + Bell Laboratories, Room 2C-463 + 600 Mountain Avenue + Murray Hill, NJ 07974-0636 + U.S.A. + dmg@bell-labs.com + */ + +#include "gdtoaimp.h" + +#undef _0 +#undef _1 + +/* one or the other of IEEE_MC68k or IEEE_8087 should be #defined */ + +#ifdef IEEE_MC68k +#define _0 0 +#define _1 1 +#define _2 2 +#define _3 3 +#endif +#ifdef IEEE_8087 +#define _0 3 +#define _1 2 +#define _2 1 +#define _3 0 +#endif + + char* +#ifdef KR_headers +g_Qfmt(buf, V, ndig, bufsize) char *buf; char *V; int ndig; unsigned bufsize; +#else +g_Qfmt(char *buf, void *V, int ndig, unsigned bufsize) +#endif +{ + static FPI fpi = { 113, 1-16383-113+1, 32766 - 16383 - 113 + 1, 1, 0 }; + char *b, *s, *se; + ULong bits[4], *L, sign; + int decpt, ex, i, mode; + + if (ndig < 0) + ndig = 0; + if (bufsize < ndig + 10) + return 0; + + L = (ULong*)V; + sign = L[_0] & 0x80000000L; + bits[3] = L[_0] & 0xffff; + bits[2] = L[_1]; + bits[1] = L[_2]; + bits[0] = L[_3]; + b = buf; + if ( (ex = (L[_0] & 0x7fff0000L) >> 16) !=0) { + if (ex == 0x7fff) { + /* Infinity or NaN */ + if (bits[0] | bits[1] | bits[2] | bits[3]) + b = strcpy(b, "NaN"); + else { + b = buf; + if (sign) + *b++ = '-'; + b = strcp(b, "Infinity"); + } + return b; + } + i = STRTOG_Normal; + bits[3] |= 0x10000; + } + else if (bits[0] | bits[1] | bits[2] | bits[3]) { + i = STRTOG_Denormal; + ex = 1; + } + else { +#ifndef IGNORE_ZERO_SIGN + if (sign) + *b++ = '-'; +#endif + *b++ = '0'; + *b = 0; + return b; + } + ex -= 0x3fff + 112; + mode = 2; + if (ndig <= 0) { + if (bufsize < 48) + return 0; + mode = 0; + } + s = gdtoa(&fpi, ex, bits, &i, mode, ndig, &decpt, &se); + return g__fmt(buf, s, se, decpt, sign); + } diff --git a/lib/libc/gdtoa/g__fmt.c b/lib/libc/gdtoa/g__fmt.c new file mode 100644 index 0000000..6274681 --- /dev/null +++ b/lib/libc/gdtoa/g__fmt.c @@ -0,0 +1,101 @@ +/**************************************************************** + +The author of this software is David M. Gay. + +Copyright (C) 1998 by Lucent Technologies +All Rights Reserved + +Permission to use, copy, modify, and distribute this software and +its documentation for any purpose and without fee is hereby +granted, provided that the above copyright notice appear in all +copies and that both that the copyright notice and this +permission notice and warranty disclaimer appear in supporting +documentation, and that the name of Lucent or any of its entities +not be used in advertising or publicity pertaining to +distribution of the software without specific, written prior +permission. + +LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, +INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. +IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY +SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER +IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. + +****************************************************************/ + +/* Please send bug reports to + David M. Gay + dmg@acm.org + */ + +#include "gdtoaimp.h" + +#ifdef USE_LOCALE +#include "locale.h" +#endif + + char * +#ifdef KR_headers +g__fmt(b, s, se, decpt, sign) char *b; char *s; char *se; int decpt; ULong sign; +#else +g__fmt(char *b, char *s, char *se, int decpt, ULong sign) +#endif +{ + int i, j, k; + char *s0 = s; +#ifdef USE_LOCALE + char decimalpoint = *localeconv()->decimal_point; +#else +#define decimalpoint '.' +#endif + if (sign) + *b++ = '-'; + if (decpt <= -4 || decpt > se - s + 5) { + *b++ = *s++; + if (*s) { + *b++ = decimalpoint; + while((*b = *s++) !=0) + b++; + } + *b++ = 'e'; + /* sprintf(b, "%+.2d", decpt - 1); */ + if (--decpt < 0) { + *b++ = '-'; + decpt = -decpt; + } + else + *b++ = '+'; + for(j = 2, k = 10; 10*k <= decpt; j++, k *= 10){} + for(;;) { + i = decpt / k; + *b++ = i + '0'; + if (--j <= 0) + break; + decpt -= i*k; + decpt *= 10; + } + *b = 0; + } + else if (decpt <= 0) { + *b++ = decimalpoint; + for(; decpt < 0; decpt++) + *b++ = '0'; + while((*b = *s++) !=0) + b++; + } + else { + while((*b = *s++) !=0) { + b++; + if (--decpt == 0 && *s) + *b++ = decimalpoint; + } + for(; decpt > 0; decpt--) + *b++ = '0'; + *b = 0; + } + freedtoa(s0); + return b; + } diff --git a/lib/libc/gdtoa/g_ddfmt.c b/lib/libc/gdtoa/g_ddfmt.c new file mode 100644 index 0000000..7d214ba --- /dev/null +++ b/lib/libc/gdtoa/g_ddfmt.c @@ -0,0 +1,161 @@ +/**************************************************************** + +The author of this software is David M. Gay. + +Copyright (C) 1998 by Lucent Technologies +All Rights Reserved + +Permission to use, copy, modify, and distribute this software and +its documentation for any purpose and without fee is hereby +granted, provided that the above copyright notice appear in all +copies and that both that the copyright notice and this +permission notice and warranty disclaimer appear in supporting +documentation, and that the name of Lucent or any of its entities +not be used in advertising or publicity pertaining to +distribution of the software without specific, written prior +permission. + +LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, +INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. +IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY +SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER +IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. + +****************************************************************/ + +/* Please send bug reports to + David M. Gay + Bell Laboratories, Room 2C-463 + 600 Mountain Avenue + Murray Hill, NJ 07974-0636 + U.S.A. + dmg@bell-labs.com + */ + +#include "gdtoaimp.h" +#include + + char * +#ifdef KR_headers +g_ddfmt(buf, dd, ndig, bufsize) char *buf; double *dd; int ndig; unsigned bufsize; +#else +g_ddfmt(char *buf, double *dd, int ndig, unsigned bufsize) +#endif +{ + FPI fpi; + char *b, *s, *se; + ULong *L, bits0[4], *bits, *zx; + int bx, by, decpt, ex, ey, i, j, mode; + Bigint *x, *y, *z; + double ddx[2]; + + if (bufsize < 10 || bufsize < ndig + 8) + return 0; + + L = (ULong*)dd; + if ((L[_0] & 0x7ff00000L) == 0x7ff00000L) { + /* Infinity or NaN */ + if (L[_0] & 0xfffff || L[_1]) { + nanret: + return strcp(buf, "NaN"); + } + if ((L[2+_0] & 0x7ff00000) == 0x7ff00000) { + if (L[2+_0] & 0xfffff || L[2+_1]) + goto nanret; + if ((L[_0] ^ L[2+_0]) & 0x80000000L) + goto nanret; /* Infinity - Infinity */ + } + infret: + b = buf; + if (L[_0] & 0x80000000L) + *b++ = '-'; + return strcp(b, "Infinity"); + } + if ((L[2+_0] & 0x7ff00000) == 0x7ff00000) { + L += 2; + if (L[_0] & 0xfffff || L[_1]) + goto nanret; + goto infret; + } + if (dd[0] + dd[1] == 0.) { + b = buf; +#ifndef IGNORE_ZERO_SIGN + if (L[_0] & L[2+_0] & 0x80000000L) + *b++ = '-'; +#endif + *b++ = '0'; + *b = 0; + return b; + } + if ((L[_0] & 0x7ff00000L) < (L[2+_0] & 0x7ff00000L)) { + ddx[1] = dd[0]; + ddx[0] = dd[1]; + dd = ddx; + L = (ULong*)dd; + } + z = d2b(dd[0], &ex, &bx); + if (dd[1] == 0.) + goto no_y; + x = z; + y = d2b(dd[1], &ey, &by); + if ( (i = ex - ey) !=0) { + if (i > 0) { + x = lshift(x, i); + ex = ey; + } + else + y = lshift(y, -i); + } + if ((L[_0] ^ L[2+_0]) & 0x80000000L) { + z = diff(x, y); + if (L[_0] & 0x80000000L) + z->sign = 1 - z->sign; + } + else { + z = sum(x, y); + if (L[_0] & 0x80000000L) + z->sign = 1; + } + Bfree(x); + Bfree(y); + no_y: + bits = zx = z->x; + for(i = 0; !*zx; zx++) + i += 32; + i += lo0bits(zx); + if (i) { + rshift(z, i); + ex += i; + } + fpi.nbits = z->wds * 32 - hi0bits(z->x[j = z->wds-1]); + if (fpi.nbits < 106) { + fpi.nbits = 106; + if (j < 3) { + for(i = 0; i <= j; i++) + bits0[i] = bits[i]; + while(i < 4) + bits0[i++] = 0; + bits = bits0; + } + } + mode = 2; + if (ndig <= 0) { + if (bufsize < (int)(fpi.nbits * .301029995664) + 10) { + Bfree(z); + return 0; + } + mode = 0; + } + fpi.emin = 1-1023-53+1; + fpi.emax = 2046-1023-106+1; + fpi.rounding = FPI_Round_near; + fpi.sudden_underflow = 0; + i = STRTOG_Normal; + s = gdtoa(&fpi, ex, bits, &i, mode, ndig, &decpt, &se); + b = g__fmt(buf, s, se, decpt, z->sign); + Bfree(z); + return b; + } diff --git a/lib/libc/gdtoa/g_dfmt.c b/lib/libc/gdtoa/g_dfmt.c new file mode 100644 index 0000000..1ade834 --- /dev/null +++ b/lib/libc/gdtoa/g_dfmt.c @@ -0,0 +1,95 @@ +/**************************************************************** + +The author of this software is David M. Gay. + +Copyright (C) 1998 by Lucent Technologies +All Rights Reserved + +Permission to use, copy, modify, and distribute this software and +its documentation for any purpose and without fee is hereby +granted, provided that the above copyright notice appear in all +copies and that both that the copyright notice and this +permission notice and warranty disclaimer appear in supporting +documentation, and that the name of Lucent or any of its entities +not be used in advertising or publicity pertaining to +distribution of the software without specific, written prior +permission. + +LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, +INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. +IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY +SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER +IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. + +****************************************************************/ + +/* Please send bug reports to + David M. Gay + Bell Laboratories, Room 2C-463 + 600 Mountain Avenue + Murray Hill, NJ 07974-0636 + U.S.A. + dmg@bell-labs.com + */ + +#include "gdtoaimp.h" + + char* +#ifdef KR_headers +g_dfmt(buf, d, ndig, bufsize) char *buf; double *d; int ndig; unsigned bufsize; +#else +g_dfmt(char *buf, double *d, int ndig, unsigned bufsize) +#endif +{ + static FPI fpi = { 53, 1-1023-53+1, 2046-1023-53+1, 1, 0 }; + char *b, *s, *se; + ULong bits[2], *L, sign; + int decpt, ex, i, mode; + + if (ndig < 0) + ndig = 0; + if (bufsize < ndig + 10) + return 0; + + L = (ULong*)d; + sign = L[_0] & 0x80000000L; + if ((L[_0] & 0x7ff00000) == 0x7ff00000) { + /* Infinity or NaN */ + if (L[_0] & 0xfffff || L[_1]) { + return strcp(buf, "NaN"); + } + b = buf; + if (sign) + *b++ = '-'; + return strcp(b, "Infinity"); + } + if (L[_1] == 0 && (L[_0] ^ sign) == 0 /*d == 0.*/) { + b = buf; +#ifndef IGNORE_ZERO_SIGN + if (L[_0] & 0x80000000L) + *b++ = '-'; +#endif + *b++ = '0'; + *b = 0; + return b; + } + bits[0] = L[_1]; + bits[1] = L[_0] & 0xfffff; + if ( (ex = (L[_0] >> 20) & 0x7ff) !=0) + bits[1] |= 0x100000; + else + ex = 1; + ex -= 0x3ff + 52; + mode = 2; + if (ndig <= 0) { + if (bufsize < 25) + return 0; + mode = 0; + } + i = STRTOG_Normal; + s = gdtoa(&fpi, ex, bits, &i, mode, ndig, &decpt, &se); + return g__fmt(buf, s, se, decpt, sign); + } diff --git a/lib/libc/gdtoa/g_ffmt.c b/lib/libc/gdtoa/g_ffmt.c new file mode 100644 index 0000000..851394a --- /dev/null +++ b/lib/libc/gdtoa/g_ffmt.c @@ -0,0 +1,94 @@ +/**************************************************************** + +The author of this software is David M. Gay. + +Copyright (C) 1998 by Lucent Technologies +All Rights Reserved + +Permission to use, copy, modify, and distribute this software and +its documentation for any purpose and without fee is hereby +granted, provided that the above copyright notice appear in all +copies and that both that the copyright notice and this +permission notice and warranty disclaimer appear in supporting +documentation, and that the name of Lucent or any of its entities +not be used in advertising or publicity pertaining to +distribution of the software without specific, written prior +permission. + +LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, +INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. +IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY +SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER +IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. + +****************************************************************/ + +/* Please send bug reports to + David M. Gay + Bell Laboratories, Room 2C-463 + 600 Mountain Avenue + Murray Hill, NJ 07974-0636 + U.S.A. + dmg@bell-labs.com + */ + +#include "gdtoaimp.h" + + char* +#ifdef KR_headers +g_ffmt(buf, f, ndig, bufsize) char *buf; float *f; int ndig; unsigned bufsize; +#else +g_ffmt(char *buf, float *f, int ndig, unsigned bufsize) +#endif +{ + static FPI fpi = { 24, 1-127-24+1, 254-127-24+1, 1, 0 }; + char *b, *s, *se; + ULong bits[1], *L, sign; + int decpt, ex, i, mode; + + if (ndig < 0) + ndig = 0; + if (bufsize < ndig + 10) + return 0; + + L = (ULong*)f; + sign = L[0] & 0x80000000L; + if ((L[0] & 0x7f800000) == 0x7f800000) { + /* Infinity or NaN */ + if (L[0] & 0x7fffff) { + return strcp(buf, "NaN"); + } + b = buf; + if (sign) + *b++ = '-'; + return strcp(b, "Infinity"); + } + if (*f == 0.) { + b = buf; +#ifndef IGNORE_ZERO_SIGN + if (L[0] & 0x80000000L) + *b++ = '-'; +#endif + *b++ = '0'; + *b = 0; + return b; + } + bits[0] = L[0] & 0x7fffff; + if ( (ex = (L[0] >> 23) & 0xff) !=0) + bits[0] |= 0x800000; + else + ex = 1; + ex -= 0x7f + 23; + mode = 2; + if (ndig <= 0) { + if (bufsize < 16) + return 0; + mode = 0; + } + i = STRTOG_Normal; + s = gdtoa(&fpi, ex, bits, &i, mode, ndig, &decpt, &se); + return g__fmt(buf, s, se, decpt, sign); + } diff --git a/lib/libc/gdtoa/g_xLfmt.c b/lib/libc/gdtoa/g_xLfmt.c new file mode 100644 index 0000000..fc17643 --- /dev/null +++ b/lib/libc/gdtoa/g_xLfmt.c @@ -0,0 +1,114 @@ +/**************************************************************** + +The author of this software is David M. Gay. + +Copyright (C) 1998 by Lucent Technologies +All Rights Reserved + +Permission to use, copy, modify, and distribute this software and +its documentation for any purpose and without fee is hereby +granted, provided that the above copyright notice appear in all +copies and that both that the copyright notice and this +permission notice and warranty disclaimer appear in supporting +documentation, and that the name of Lucent or any of its entities +not be used in advertising or publicity pertaining to +distribution of the software without specific, written prior +permission. + +LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, +INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. +IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY +SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER +IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. + +****************************************************************/ + +/* Please send bug reports to + David M. Gay + Bell Laboratories, Room 2C-463 + 600 Mountain Avenue + Murray Hill, NJ 07974-0636 + U.S.A. + dmg@bell-labs.com + */ + +#include "gdtoaimp.h" + +#undef _0 +#undef _1 + +/* one or the other of IEEE_MC68k or IEEE_8087 should be #defined */ + +#ifdef IEEE_MC68k +#define _0 0 +#define _1 1 +#define _2 2 +#endif +#ifdef IEEE_8087 +#define _0 2 +#define _1 1 +#define _2 0 +#endif + + char* +#ifdef KR_headers +g_xLfmt(buf, V, ndig, bufsize) char *buf; char *V; int ndig; unsigned bufsize; +#else +g_xLfmt(char *buf, void *V, int ndig, unsigned bufsize) +#endif +{ + static FPI fpi = { 64, 1-16383-64+1, 32766 - 16383 - 64 + 1, 1, 0 }; + char *b, *s, *se; + ULong bits[2], *L, sign; + int decpt, ex, i, mode; + + if (ndig < 0) + ndig = 0; + if (bufsize < ndig + 10) + return 0; + + L = (ULong*)V; + sign = L[_0] & 0x80000000L; + bits[1] = L[_1]; + bits[0] = L[_2]; + if ( (ex = (L[_0] >> 16) & 0x7fff) !=0) { + if (ex == 0x7fff) { + /* Infinity or NaN */ + if (bits[0] | bits[1]) + b = strcp(buf, "NaN"); + else { + b = buf; + if (sign) + *b++ = '-'; + b = strcp(b, "Infinity"); + } + return b; + } + i = STRTOG_Normal; + } + else if (bits[0] | bits[1]) { + i = STRTOG_Denormal; + } + else { + b = buf; +#ifndef IGNORE_ZERO_SIGN + if (sign) + *b++ = '-'; +#endif + *b++ = '0'; + *b = 0; + return b; + } + ex -= 0x3fff + 63; + mode = 2; + if (ndig <= 0) { + if (bufsize < 32) + return 0; + mode = 0; + } + s = gdtoa(&fpi, ex, bits, &i, mode, ndig, &decpt, &se); + return g__fmt(buf, s, se, decpt, sign); + } diff --git a/lib/libc/gdtoa/g_xfmt.c b/lib/libc/gdtoa/g_xfmt.c new file mode 100644 index 0000000..1e2a381 --- /dev/null +++ b/lib/libc/gdtoa/g_xfmt.c @@ -0,0 +1,119 @@ +/**************************************************************** + +The author of this software is David M. Gay. + +Copyright (C) 1998 by Lucent Technologies +All Rights Reserved + +Permission to use, copy, modify, and distribute this software and +its documentation for any purpose and without fee is hereby +granted, provided that the above copyright notice appear in all +copies and that both that the copyright notice and this +permission notice and warranty disclaimer appear in supporting +documentation, and that the name of Lucent or any of its entities +not be used in advertising or publicity pertaining to +distribution of the software without specific, written prior +permission. + +LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, +INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. +IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY +SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER +IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. + +****************************************************************/ + +/* Please send bug reports to + David M. Gay + Bell Laboratories, Room 2C-463 + 600 Mountain Avenue + Murray Hill, NJ 07974-0636 + U.S.A. + dmg@bell-labs.com + */ + +#include "gdtoaimp.h" + +#undef _0 +#undef _1 + +/* one or the other of IEEE_MC68k or IEEE_8087 should be #defined */ + +#ifdef IEEE_MC68k +#define _0 0 +#define _1 1 +#define _2 2 +#define _3 3 +#define _4 4 +#endif +#ifdef IEEE_8087 +#define _0 4 +#define _1 3 +#define _2 2 +#define _3 1 +#define _4 0 +#endif + + char* +#ifdef KR_headers +g_xfmt(buf, V, ndig, bufsize) char *buf; char *V; int ndig; unsigned bufsize; +#else +g_xfmt(char *buf, void *V, int ndig, unsigned bufsize) +#endif +{ + static FPI fpi = { 64, 1-16383-64+1, 32766 - 16383 - 64 + 1, 1, 0 }; + char *b, *s, *se; + ULong bits[2], sign; + UShort *L; + int decpt, ex, i, mode; + + if (ndig < 0) + ndig = 0; + if (bufsize < ndig + 10) + return 0; + + L = (UShort *)V; + sign = L[_0] & 0x8000; + bits[1] = (L[_1] << 16) | L[_2]; + bits[0] = (L[_3] << 16) | L[_4]; + if ( (ex = L[_0] & 0x7fff) !=0) { + if (ex == 0x7fff) { + /* Infinity or NaN */ + if (bits[0] | bits[1]) + b = strcp(buf, "NaN"); + else { + b = buf; + if (sign) + *b++ = '-'; + b = strcp(b, "Infinity"); + } + return b; + } + i = STRTOG_Normal; + } + else if (bits[0] | bits[1]) { + i = STRTOG_Denormal; + } + else { + b = buf; +#ifndef IGNORE_ZERO_SIGN + if (sign) + *b++ = '-'; +#endif + *b++ = '0'; + *b = 0; + return b; + } + ex -= 0x3fff + 63; + mode = 2; + if (ndig <= 0) { + if (bufsize < 32) + return 0; + mode = 0; + } + s = gdtoa(&fpi, ex, bits, &i, mode, ndig, &decpt, &se); + return g__fmt(buf, s, se, decpt, sign); + } diff --git a/lib/libc/gdtoa/gdtoa.c b/lib/libc/gdtoa/gdtoa.c new file mode 100644 index 0000000..706c055 --- /dev/null +++ b/lib/libc/gdtoa/gdtoa.c @@ -0,0 +1,764 @@ +/**************************************************************** + +The author of this software is David M. Gay. + +Copyright (C) 1998, 1999 by Lucent Technologies +All Rights Reserved + +Permission to use, copy, modify, and distribute this software and +its documentation for any purpose and without fee is hereby +granted, provided that the above copyright notice appear in all +copies and that both that the copyright notice and this +permission notice and warranty disclaimer appear in supporting +documentation, and that the name of Lucent or any of its entities +not be used in advertising or publicity pertaining to +distribution of the software without specific, written prior +permission. + +LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, +INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. +IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY +SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER +IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. + +****************************************************************/ + +/* Please send bug reports to + David M. Gay + Bell Laboratories, Room 2C-463 + 600 Mountain Avenue + Murray Hill, NJ 07974-0636 + U.S.A. + dmg@bell-labs.com + */ + +#include "gdtoaimp.h" + + static Bigint * +#ifdef KR_headers +bitstob(bits, nbits, bbits) ULong *bits; int nbits; int *bbits; +#else +bitstob(ULong *bits, int nbits, int *bbits) +#endif +{ + int i, k; + Bigint *b; + ULong *be, *x, *x0; + + i = ULbits; + k = 0; + while(i < nbits) { + i <<= 1; + k++; + } +#ifndef Pack_32 + if (!k) + k = 1; +#endif + b = Balloc(k); + be = bits + ((nbits - 1) >> kshift); + x = x0 = b->x; + do { + *x++ = *bits & ALL_ON; +#ifdef Pack_16 + *x++ = (*bits >> 16) & ALL_ON; +#endif + } while(++bits <= be); + i = x - x0; + while(!x0[--i]) + if (!i) { + b->wds = 0; + *bbits = 0; + goto ret; + } + b->wds = i + 1; + *bbits = i*ULbits + 32 - hi0bits(b->x[i]); + ret: + return b; + } + +/* dtoa for IEEE arithmetic (dmg): convert double to ASCII string. + * + * Inspired by "How to Print Floating-Point Numbers Accurately" by + * Guy L. Steele, Jr. and Jon L. White [Proc. ACM SIGPLAN '90, pp. 92-101]. + * + * Modifications: + * 1. Rather than iterating, we use a simple numeric overestimate + * to determine k = floor(log10(d)). We scale relevant + * quantities using O(log2(k)) rather than O(k) multiplications. + * 2. For some modes > 2 (corresponding to ecvt and fcvt), we don't + * try to generate digits strictly left to right. Instead, we + * compute with fewer bits and propagate the carry if necessary + * when rounding the final digit up. This is often faster. + * 3. Under the assumption that input will be rounded nearest, + * mode 0 renders 1e23 as 1e23 rather than 9.999999999999999e22. + * That is, we allow equality in stopping tests when the + * round-nearest rule will give the same floating-point value + * as would satisfaction of the stopping test with strict + * inequality. + * 4. We remove common factors of powers of 2 from relevant + * quantities. + * 5. When converting floating-point integers less than 1e16, + * we use floating-point arithmetic rather than resorting + * to multiple-precision integers. + * 6. When asked to produce fewer than 15 digits, we first try + * to get by with floating-point arithmetic; we resort to + * multiple-precision integer arithmetic only if we cannot + * guarantee that the floating-point calculation has given + * the correctly rounded result. For k requested digits and + * "uniformly" distributed input, the probability is + * something like 10^(k-15) that we must resort to the Long + * calculation. + */ + + char * +gdtoa +#ifdef KR_headers + (fpi, be, bits, kindp, mode, ndigits, decpt, rve) + FPI *fpi; int be; ULong *bits; + int *kindp, mode, ndigits, *decpt; char **rve; +#else + (FPI *fpi, int be, ULong *bits, int *kindp, int mode, int ndigits, int *decpt, char **rve) +#endif +{ + /* Arguments ndigits and decpt are similar to the second and third + arguments of ecvt and fcvt; trailing zeros are suppressed from + the returned string. If not null, *rve is set to point + to the end of the return value. If d is +-Infinity or NaN, + then *decpt is set to 9999. + + mode: + 0 ==> shortest string that yields d when read in + and rounded to nearest. + 1 ==> like 0, but with Steele & White stopping rule; + e.g. with IEEE P754 arithmetic , mode 0 gives + 1e23 whereas mode 1 gives 9.999999999999999e22. + 2 ==> max(1,ndigits) significant digits. This gives a + return value similar to that of ecvt, except + that trailing zeros are suppressed. + 3 ==> through ndigits past the decimal point. This + gives a return value similar to that from fcvt, + except that trailing zeros are suppressed, and + ndigits can be negative. + 4-9 should give the same return values as 2-3, i.e., + 4 <= mode <= 9 ==> same return as mode + 2 + (mode & 1). These modes are mainly for + debugging; often they run slower but sometimes + faster than modes 2-3. + 4,5,8,9 ==> left-to-right digit generation. + 6-9 ==> don't try fast floating-point estimate + (if applicable). + + Values of mode other than 0-9 are treated as mode 0. + + Sufficient space is allocated to the return value + to hold the suppressed trailing zeros. + */ + + int bbits, b2, b5, be0, dig, i, ieps, ilim, ilim0, ilim1, inex; + int j, j1, k, k0, k_check, kind, leftright, m2, m5, nbits; + int rdir, s2, s5, spec_case, try_quick; + Long L; + Bigint *b, *b1, *delta, *mlo, *mhi, *mhi1, *S; + double d, d2, ds, eps; + char *s, *s0; + +#ifndef MULTIPLE_THREADS + if (dtoa_result) { + freedtoa(dtoa_result); + dtoa_result = 0; + } +#endif + inex = 0; + kind = *kindp &= ~STRTOG_Inexact; + switch(kind & STRTOG_Retmask) { + case STRTOG_Zero: + goto ret_zero; + case STRTOG_Normal: + case STRTOG_Denormal: + break; + case STRTOG_Infinite: + *decpt = -32768; + return nrv_alloc("Infinity", rve, 8); + case STRTOG_NaN: + *decpt = -32768; + return nrv_alloc("NaN", rve, 3); + default: + return 0; + } + b = bitstob(bits, nbits = fpi->nbits, &bbits); + be0 = be; + if ( (i = trailz(b)) !=0) { + rshift(b, i); + be += i; + bbits -= i; + } + if (!b->wds) { + Bfree(b); + ret_zero: + *decpt = 1; + return nrv_alloc("0", rve, 1); + } + + dval(d) = b2d(b, &i); + i = be + bbits - 1; + word0(d) &= Frac_mask1; + word0(d) |= Exp_11; +#ifdef IBM + if ( (j = 11 - hi0bits(word0(d) & Frac_mask)) !=0) + dval(d) /= 1 << j; +#endif + + /* log(x) ~=~ log(1.5) + (x-1.5)/1.5 + * log10(x) = log(x) / log(10) + * ~=~ log(1.5)/log(10) + (x-1.5)/(1.5*log(10)) + * log10(d) = (i-Bias)*log(2)/log(10) + log10(d2) + * + * This suggests computing an approximation k to log10(d) by + * + * k = (i - Bias)*0.301029995663981 + * + ( (d2-1.5)*0.289529654602168 + 0.176091259055681 ); + * + * We want k to be too large rather than too small. + * The error in the first-order Taylor series approximation + * is in our favor, so we just round up the constant enough + * to compensate for any error in the multiplication of + * (i - Bias) by 0.301029995663981; since |i - Bias| <= 1077, + * and 1077 * 0.30103 * 2^-52 ~=~ 7.2e-14, + * adding 1e-13 to the constant term more than suffices. + * Hence we adjust the constant term to 0.1760912590558. + * (We could get a more accurate k by invoking log10, + * but this is probably not worthwhile.) + */ +#ifdef IBM + i <<= 2; + i += j; +#endif + ds = (dval(d)-1.5)*0.289529654602168 + 0.1760912590558 + i*0.301029995663981; + + /* correct assumption about exponent range */ + if ((j = i) < 0) + j = -j; + if ((j -= 1077) > 0) + ds += j * 7e-17; + + k = (int)ds; + if (ds < 0. && ds != k) + k--; /* want k = floor(ds) */ + k_check = 1; +#ifdef IBM + j = be + bbits - 1; + if ( (j1 = j & 3) !=0) + dval(d) *= 1 << j1; + word0(d) += j << Exp_shift - 2 & Exp_mask; +#else + word0(d) += (be + bbits - 1) << Exp_shift; +#endif + if (k >= 0 && k <= Ten_pmax) { + if (dval(d) < tens[k]) + k--; + k_check = 0; + } + j = bbits - i - 1; + if (j >= 0) { + b2 = 0; + s2 = j; + } + else { + b2 = -j; + s2 = 0; + } + if (k >= 0) { + b5 = 0; + s5 = k; + s2 += k; + } + else { + b2 -= k; + b5 = -k; + s5 = 0; + } + if (mode < 0 || mode > 9) + mode = 0; + try_quick = 1; + if (mode > 5) { + mode -= 4; + try_quick = 0; + } + leftright = 1; + switch(mode) { + case 0: + case 1: + ilim = ilim1 = -1; + i = (int)(nbits * .30103) + 3; + ndigits = 0; + break; + case 2: + leftright = 0; + /* no break */ + case 4: + if (ndigits <= 0) + ndigits = 1; + ilim = ilim1 = i = ndigits; + break; + case 3: + leftright = 0; + /* no break */ + case 5: + i = ndigits + k + 1; + ilim = i; + ilim1 = i - 1; + if (i <= 0) + i = 1; + } + s = s0 = rv_alloc(i); + + if ( (rdir = fpi->rounding - 1) !=0) { + if (rdir < 0) + rdir = 2; + if (kind & STRTOG_Neg) + rdir = 3 - rdir; + } + + /* Now rdir = 0 ==> round near, 1 ==> round up, 2 ==> round down. */ + + if (ilim >= 0 && ilim <= Quick_max && try_quick && !rdir +#ifndef IMPRECISE_INEXACT + && k == 0 +#endif + ) { + + /* Try to get by with floating-point arithmetic. */ + + i = 0; + d2 = dval(d); +#ifdef IBM + if ( (j = 11 - hi0bits(word0(d) & Frac_mask)) !=0) + dval(d) /= 1 << j; +#endif + k0 = k; + ilim0 = ilim; + ieps = 2; /* conservative */ + if (k > 0) { + ds = tens[k&0xf]; + j = k >> 4; + if (j & Bletch) { + /* prevent overflows */ + j &= Bletch - 1; + dval(d) /= bigtens[n_bigtens-1]; + ieps++; + } + for(; j; j >>= 1, i++) + if (j & 1) { + ieps++; + ds *= bigtens[i]; + } + } + else { + ds = 1.; + if ( (j1 = -k) !=0) { + dval(d) *= tens[j1 & 0xf]; + for(j = j1 >> 4; j; j >>= 1, i++) + if (j & 1) { + ieps++; + dval(d) *= bigtens[i]; + } + } + } + if (k_check && dval(d) < 1. && ilim > 0) { + if (ilim1 <= 0) + goto fast_failed; + ilim = ilim1; + k--; + dval(d) *= 10.; + ieps++; + } + dval(eps) = ieps*dval(d) + 7.; + word0(eps) -= (P-1)*Exp_msk1; + if (ilim == 0) { + S = mhi = 0; + dval(d) -= 5.; + if (dval(d) > dval(eps)) + goto one_digit; + if (dval(d) < -dval(eps)) + goto no_digits; + goto fast_failed; + } +#ifndef No_leftright + if (leftright) { + /* Use Steele & White method of only + * generating digits needed. + */ + dval(eps) = ds*0.5/tens[ilim-1] - dval(eps); + for(i = 0;;) { + L = (Long)(dval(d)/ds); + dval(d) -= L*ds; + *s++ = '0' + (int)L; + if (dval(d) < dval(eps)) { + if (dval(d)) + inex = STRTOG_Inexlo; + goto ret1; + } + if (ds - dval(d) < dval(eps)) + goto bump_up; + if (++i >= ilim) + break; + dval(eps) *= 10.; + dval(d) *= 10.; + } + } + else { +#endif + /* Generate ilim digits, then fix them up. */ + dval(eps) *= tens[ilim-1]; + for(i = 1;; i++, dval(d) *= 10.) { + if ( (L = (Long)(dval(d)/ds)) !=0) + dval(d) -= L*ds; + *s++ = '0' + (int)L; + if (i == ilim) { + ds *= 0.5; + if (dval(d) > ds + dval(eps)) + goto bump_up; + else if (dval(d) < ds - dval(eps)) { + while(*--s == '0'){} + s++; + if (dval(d)) + inex = STRTOG_Inexlo; + goto ret1; + } + break; + } + } +#ifndef No_leftright + } +#endif + fast_failed: + s = s0; + dval(d) = d2; + k = k0; + ilim = ilim0; + } + + /* Do we have a "small" integer? */ + + if (be >= 0 && k <= Int_max) { + /* Yes. */ + ds = tens[k]; + if (ndigits < 0 && ilim <= 0) { + S = mhi = 0; + if (ilim < 0 || dval(d) <= 5*ds) + goto no_digits; + goto one_digit; + } + for(i = 1;; i++, dval(d) *= 10.) { + L = dval(d) / ds; + dval(d) -= L*ds; +#ifdef Check_FLT_ROUNDS + /* If FLT_ROUNDS == 2, L will usually be high by 1 */ + if (dval(d) < 0) { + L--; + dval(d) += ds; + } +#endif + *s++ = '0' + (int)L; + if (dval(d) == 0.) + break; + if (i == ilim) { + if (rdir) { + if (rdir == 1) + goto bump_up; + inex = STRTOG_Inexlo; + goto ret1; + } + dval(d) += dval(d); + if (dval(d) > ds || dval(d) == ds && L & 1) { + bump_up: + inex = STRTOG_Inexhi; + while(*--s == '9') + if (s == s0) { + k++; + *s = '0'; + break; + } + ++*s++; + } + else + inex = STRTOG_Inexlo; + break; + } + } + goto ret1; + } + + m2 = b2; + m5 = b5; + mhi = mlo = 0; + if (leftright) { + if (mode < 2) { + i = nbits - bbits; + if (be - i++ < fpi->emin) + /* denormal */ + i = be - fpi->emin + 1; + } + else { + j = ilim - 1; + if (m5 >= j) + m5 -= j; + else { + s5 += j -= m5; + b5 += j; + m5 = 0; + } + if ((i = ilim) < 0) { + m2 -= i; + i = 0; + } + } + b2 += i; + s2 += i; + mhi = i2b(1); + } + if (m2 > 0 && s2 > 0) { + i = m2 < s2 ? m2 : s2; + b2 -= i; + m2 -= i; + s2 -= i; + } + if (b5 > 0) { + if (leftright) { + if (m5 > 0) { + mhi = pow5mult(mhi, m5); + b1 = mult(mhi, b); + Bfree(b); + b = b1; + } + if ( (j = b5 - m5) !=0) + b = pow5mult(b, j); + } + else + b = pow5mult(b, b5); + } + S = i2b(1); + if (s5 > 0) + S = pow5mult(S, s5); + + /* Check for special case that d is a normalized power of 2. */ + + spec_case = 0; + if (mode < 2) { + if (bbits == 1 && be0 > fpi->emin + 1) { + /* The special case */ + b2++; + s2++; + spec_case = 1; + } + } + + /* Arrange for convenient computation of quotients: + * shift left if necessary so divisor has 4 leading 0 bits. + * + * Perhaps we should just compute leading 28 bits of S once + * and for all and pass them and a shift to quorem, so it + * can do shifts and ors to compute the numerator for q. + */ +#ifdef Pack_32 + if ( (i = ((s5 ? 32 - hi0bits(S->x[S->wds-1]) : 1) + s2) & 0x1f) !=0) + i = 32 - i; +#else + if ( (i = ((s5 ? 32 - hi0bits(S->x[S->wds-1]) : 1) + s2) & 0xf) !=0) + i = 16 - i; +#endif + if (i > 4) { + i -= 4; + b2 += i; + m2 += i; + s2 += i; + } + else if (i < 4) { + i += 28; + b2 += i; + m2 += i; + s2 += i; + } + if (b2 > 0) + b = lshift(b, b2); + if (s2 > 0) + S = lshift(S, s2); + if (k_check) { + if (cmp(b,S) < 0) { + k--; + b = multadd(b, 10, 0); /* we botched the k estimate */ + if (leftright) + mhi = multadd(mhi, 10, 0); + ilim = ilim1; + } + } + if (ilim <= 0 && mode > 2) { + if (ilim < 0 || cmp(b,S = multadd(S,5,0)) <= 0) { + /* no digits, fcvt style */ + no_digits: + k = -1 - ndigits; + inex = STRTOG_Inexlo; + goto ret; + } + one_digit: + inex = STRTOG_Inexhi; + *s++ = '1'; + k++; + goto ret; + } + if (leftright) { + if (m2 > 0) + mhi = lshift(mhi, m2); + + /* Compute mlo -- check for special case + * that d is a normalized power of 2. + */ + + mlo = mhi; + if (spec_case) { + mhi = Balloc(mhi->k); + Bcopy(mhi, mlo); + mhi = lshift(mhi, 1); + } + + for(i = 1;;i++) { + dig = quorem(b,S) + '0'; + /* Do we yet have the shortest decimal string + * that will round to d? + */ + j = cmp(b, mlo); + delta = diff(S, mhi); + j1 = delta->sign ? 1 : cmp(b, delta); + Bfree(delta); +#ifndef ROUND_BIASED + if (j1 == 0 && !mode && !(bits[0] & 1) && !rdir) { + if (dig == '9') + goto round_9_up; + if (j <= 0) { + if (b->wds > 1 || b->x[0]) + inex = STRTOG_Inexlo; + } + else { + dig++; + inex = STRTOG_Inexhi; + } + *s++ = dig; + goto ret; + } +#endif + if (j < 0 || j == 0 && !mode +#ifndef ROUND_BIASED + && !(bits[0] & 1) +#endif + ) { + if (rdir && (b->wds > 1 || b->x[0])) { + if (rdir == 2) { + inex = STRTOG_Inexlo; + goto accept; + } + while (cmp(S,mhi) > 0) { + *s++ = dig; + mhi1 = multadd(mhi, 10, 0); + if (mlo == mhi) + mlo = mhi1; + mhi = mhi1; + b = multadd(b, 10, 0); + dig = quorem(b,S) + '0'; + } + if (dig++ == '9') + goto round_9_up; + inex = STRTOG_Inexhi; + goto accept; + } + if (j1 > 0) { + b = lshift(b, 1); + j1 = cmp(b, S); + if ((j1 > 0 || j1 == 0 && dig & 1) + && dig++ == '9') + goto round_9_up; + inex = STRTOG_Inexhi; + } + if (b->wds > 1 || b->x[0]) + inex = STRTOG_Inexlo; + accept: + *s++ = dig; + goto ret; + } + if (j1 > 0 && rdir != 2) { + if (dig == '9') { /* possible if i == 1 */ + round_9_up: + *s++ = '9'; + inex = STRTOG_Inexhi; + goto roundoff; + } + inex = STRTOG_Inexhi; + *s++ = dig + 1; + goto ret; + } + *s++ = dig; + if (i == ilim) + break; + b = multadd(b, 10, 0); + if (mlo == mhi) + mlo = mhi = multadd(mhi, 10, 0); + else { + mlo = multadd(mlo, 10, 0); + mhi = multadd(mhi, 10, 0); + } + } + } + else + for(i = 1;; i++) { + *s++ = dig = quorem(b,S) + '0'; + if (i >= ilim) + break; + b = multadd(b, 10, 0); + } + + /* Round off last digit */ + + if (rdir) { + if (rdir == 2 || b->wds <= 1 && !b->x[0]) + goto chopzeros; + goto roundoff; + } + b = lshift(b, 1); + j = cmp(b, S); + if (j > 0 || j == 0 && dig & 1) { + roundoff: + inex = STRTOG_Inexhi; + while(*--s == '9') + if (s == s0) { + k++; + *s++ = '1'; + goto ret; + } + ++*s++; + } + else { + chopzeros: + if (b->wds > 1 || b->x[0]) + inex = STRTOG_Inexlo; + while(*--s == '0'){} + s++; + } + ret: + Bfree(S); + if (mhi) { + if (mlo && mlo != mhi) + Bfree(mlo); + Bfree(mhi); + } + ret1: + Bfree(b); + *s = 0; + *decpt = k + 1; + if (rve) + *rve = s; + *kindp |= inex; + return s0; + } diff --git a/lib/libc/gdtoa/gethex.c b/lib/libc/gdtoa/gethex.c new file mode 100644 index 0000000..fadb5de --- /dev/null +++ b/lib/libc/gdtoa/gethex.c @@ -0,0 +1,249 @@ +/**************************************************************** + +The author of this software is David M. Gay. + +Copyright (C) 1998 by Lucent Technologies +All Rights Reserved + +Permission to use, copy, modify, and distribute this software and +its documentation for any purpose and without fee is hereby +granted, provided that the above copyright notice appear in all +copies and that both that the copyright notice and this +permission notice and warranty disclaimer appear in supporting +documentation, and that the name of Lucent or any of its entities +not be used in advertising or publicity pertaining to +distribution of the software without specific, written prior +permission. + +LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, +INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. +IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY +SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER +IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. + +****************************************************************/ + +/* Please send bug reports to + David M. Gay + dmg@acm.org + */ + +#include "gdtoaimp.h" + +#ifdef USE_LOCALE +#include "locale.h" +#endif + + int +#ifdef KR_headers +gethex(sp, fpi, exp, bp, sign) + CONST char **sp; FPI *fpi; Long *exp; Bigint **bp; int sign; +#else +gethex( CONST char **sp, FPI *fpi, Long *exp, Bigint **bp, int sign) +#endif +{ + Bigint *b; + CONST unsigned char *decpt, *s0, *s, *s1; + int esign, havedig, irv, k, n, nbits, up; + ULong L, lostbits, *x; + Long e, e1; +#ifdef USE_LOCALE + unsigned char decimalpoint = *localeconv()->decimal_point; +#else +#define decimalpoint '.' +#endif + + if (!hexdig['0']) + hexdig_init_D2A(); + havedig = 0; + s0 = *(CONST unsigned char **)sp + 2; + while(s0[havedig] == '0') + havedig++; + s0 += havedig; + s = s0; + decpt = 0; + if (!hexdig[*s]) { + if (*s == decimalpoint) { + decpt = ++s; + if (!hexdig[*s]) + goto ret0; + } + else { + ret0: + *sp = (char*)s; + return havedig ? STRTOG_Zero : STRTOG_NoNumber; + } + while(*s == '0') + s++; + havedig = 1; + if (!hexdig[*s]) + goto ret0; + s0 = s; + } + while(hexdig[*s]) + s++; + if (*s == decimalpoint && !decpt) { + decpt = ++s; + while(hexdig[*s]) + s++; + } + e = 0; + if (decpt) + e = -(((Long)(s-decpt)) << 2); + s1 = s; + switch(*s) { + case 'p': + case 'P': + esign = 0; + switch(*++s) { + case '-': + esign = 1; + /* no break */ + case '+': + s++; + } + if ((n = hexdig[*s]) == 0 || n > 0x19) { + s = s1; + break; + } + e1 = n - 0x10; + while((n = hexdig[*++s]) !=0 && n <= 0x19) + e1 = 10*e1 + n - 0x10; + if (esign) + e1 = -e1; + e += e1; + } + *sp = (char*)s; + n = s1 - s0 - 1; + for(k = 0; n > 7; n >>= 1) + k++; + b = Balloc(k); + x = b->x; + n = 0; + L = 0; + while(s1 > s0) { + if (*--s1 == decimalpoint) + continue; + if (n == 32) { + *x++ = L; + L = 0; + n = 0; + } + L |= (hexdig[*s1] & 0x0f) << n; + n += 4; + } + *x++ = L; + b->wds = n = x - b->x; + n = 32*n - hi0bits(L); + nbits = fpi->nbits; + lostbits = 0; + x = b->x; + if (n > nbits) { + n -= nbits; + if (any_on(b,n)) { + lostbits = 1; + k = n - 1; + if (x[k>>kshift] & 1 << (k & kmask)) { + lostbits = 2; + if (k > 1 && any_on(b,k-1)) + lostbits = 3; + } + } + rshift(b, n); + e += n; + } + else if (n < nbits) { + n = nbits - n; + b = lshift(b, n); + e -= n; + x = b->x; + } + if (e > fpi->emax) { + ovfl: + Bfree(b); + *bp = 0; + return STRTOG_Infinite | STRTOG_Overflow | STRTOG_Inexhi; + } + irv = STRTOG_Normal; + if (e < fpi->emin) { + irv = STRTOG_Denormal; + n = fpi->emin - e; + if (n >= nbits) { + switch (fpi->rounding) { + case FPI_Round_near: + if (n == nbits && (n < 2 || any_on(b,n-1))) + goto one_bit; + break; + case FPI_Round_up: + if (!sign) + goto one_bit; + break; + case FPI_Round_down: + if (sign) { + one_bit: + *exp = fpi->emin; + x[0] = b->wds = 1; + *bp = b; + return STRTOG_Denormal | STRTOG_Inexhi + | STRTOG_Underflow; + } + } + Bfree(b); + *bp = 0; + return STRTOG_Zero | STRTOG_Inexlo | STRTOG_Underflow; + } + k = n - 1; + if (lostbits) + lostbits = 1; + else if (k > 0) + lostbits = any_on(b,k); + if (x[k>>kshift] & 1 << (k & kmask)) + lostbits |= 2; + nbits -= n; + rshift(b,n); + e = fpi->emin; + } + if (lostbits) { + up = 0; + switch(fpi->rounding) { + case FPI_Round_zero: + break; + case FPI_Round_near: + if (lostbits & 2 + && (lostbits & 1) | x[0] & 1) + up = 1; + break; + case FPI_Round_up: + up = 1 - sign; + break; + case FPI_Round_down: + up = sign; + } + if (up) { + k = b->wds; + b = increment(b); + x = b->x; + if (irv == STRTOG_Denormal) { + if (nbits == fpi->nbits - 1 + && x[nbits >> kshift] & 1 << (nbits & kmask)) + irv = STRTOG_Normal; + } + else if (b->wds > k + || (n = nbits & kmask) !=0 + && hi0bits(x[k-1]) < 32-n) { + rshift(b,1); + if (++e > fpi->emax) + goto ovfl; + } + irv |= STRTOG_Inexhi; + } + else + irv |= STRTOG_Inexlo; + } + *bp = b; + *exp = e; + return irv; + } diff --git a/lib/libc/gdtoa/glue.c b/lib/libc/gdtoa/glue.c new file mode 100644 index 0000000..5178f59 --- /dev/null +++ b/lib/libc/gdtoa/glue.c @@ -0,0 +1,13 @@ +/* + * Machine-independent glue to integrate David Gay's gdtoa + * package into libc. + * + * $FreeBSD: src/lib/libc/gdtoa/glue.c,v 1.2 2003/06/21 08:20:14 das Exp $ + */ + +#include + +pthread_mutex_t __gdtoa_locks[] = { + PTHREAD_MUTEX_INITIALIZER, + PTHREAD_MUTEX_INITIALIZER +}; diff --git a/lib/libc/gdtoa/gmisc.c b/lib/libc/gdtoa/gmisc.c new file mode 100644 index 0000000..1607f4b --- /dev/null +++ b/lib/libc/gdtoa/gmisc.c @@ -0,0 +1,92 @@ +/**************************************************************** + +The author of this software is David M. Gay. + +Copyright (C) 1998 by Lucent Technologies +All Rights Reserved + +Permission to use, copy, modify, and distribute this software and +its documentation for any purpose and without fee is hereby +granted, provided that the above copyright notice appear in all +copies and that both that the copyright notice and this +permission notice and warranty disclaimer appear in supporting +documentation, and that the name of Lucent or any of its entities +not be used in advertising or publicity pertaining to +distribution of the software without specific, written prior +permission. + +LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, +INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. +IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY +SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER +IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. + +****************************************************************/ + +/* Please send bug reports to + David M. Gay + Bell Laboratories, Room 2C-463 + 600 Mountain Avenue + Murray Hill, NJ 07974-0636 + U.S.A. + dmg@bell-labs.com + */ + +#include "gdtoaimp.h" + + void +#ifdef KR_headers +rshift(b, k) Bigint *b; int k; +#else +rshift(Bigint *b, int k) +#endif +{ + ULong *x, *x1, *xe, y; + int n; + + x = x1 = b->x; + n = k >> kshift; + if (n < b->wds) { + xe = x + b->wds; + x += n; + if (k &= kmask) { + n = ULbits - k; + y = *x++ >> k; + while(x < xe) { + *x1++ = (y | (*x << n)) & ALL_ON; + y = *x++ >> k; + } + if ((*x1 = y) !=0) + x1++; + } + else + while(x < xe) + *x1++ = *x++; + } + if ((b->wds = x1 - b->x) == 0) + b->x[0] = 0; + } + + int +#ifdef KR_headers +trailz(b) Bigint *b; +#else +trailz(Bigint *b) +#endif +{ + ULong L, *x, *xe; + int n = 0; + + x = b->x; + xe = x + b->wds; + for(n = 0; x < xe && !*x; x++) + n += ULbits; + if (x < xe) { + L = *x; + n += lo0bits(&L); + } + return n; + } diff --git a/lib/libc/gdtoa/hd_init.c b/lib/libc/gdtoa/hd_init.c new file mode 100644 index 0000000..73afca1 --- /dev/null +++ b/lib/libc/gdtoa/hd_init.c @@ -0,0 +1,61 @@ +/**************************************************************** + +The author of this software is David M. Gay. + +Copyright (C) 2000 by Lucent Technologies +All Rights Reserved + +Permission to use, copy, modify, and distribute this software and +its documentation for any purpose and without fee is hereby +granted, provided that the above copyright notice appear in all +copies and that both that the copyright notice and this +permission notice and warranty disclaimer appear in supporting +documentation, and that the name of Lucent or any of its entities +not be used in advertising or publicity pertaining to +distribution of the software without specific, written prior +permission. + +LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, +INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. +IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY +SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER +IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. + +****************************************************************/ + +/* Please send bug reports to + David M. Gay + Bell Laboratories, Room 2C-463 + 600 Mountain Avenue + Murray Hill, NJ 07974-0636 + U.S.A. + dmg@bell-labs.com + */ + +#include "gdtoaimp.h" + + unsigned char hexdig[256]; + + static void +#ifdef KR_headers +htinit(h, s, inc) unsigned char *h; unsigned char *s; int inc; +#else +htinit(unsigned char *h, unsigned char *s, int inc) +#endif +{ + int i, j; + for(i = 0; (j = s[i]) !=0; i++) + h[j] = i + inc; + } + + void +hexdig_init_D2A(Void) +{ +#define USC (unsigned char *) + htinit(hexdig, USC "0123456789", 0x10); + htinit(hexdig, USC "abcdef", 0x10 + 10); + htinit(hexdig, USC "ABCDEF", 0x10 + 10); + } diff --git a/lib/libc/gdtoa/hexnan.c b/lib/libc/gdtoa/hexnan.c new file mode 100644 index 0000000..7a7e03a --- /dev/null +++ b/lib/libc/gdtoa/hexnan.c @@ -0,0 +1,137 @@ +/**************************************************************** + +The author of this software is David M. Gay. + +Copyright (C) 2000 by Lucent Technologies +All Rights Reserved + +Permission to use, copy, modify, and distribute this software and +its documentation for any purpose and without fee is hereby +granted, provided that the above copyright notice appear in all +copies and that both that the copyright notice and this +permission notice and warranty disclaimer appear in supporting +documentation, and that the name of Lucent or any of its entities +not be used in advertising or publicity pertaining to +distribution of the software without specific, written prior +permission. + +LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, +INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. +IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY +SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER +IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. + +****************************************************************/ + +/* Please send bug reports to + David M. Gay + Bell Laboratories, Room 2C-463 + 600 Mountain Avenue + Murray Hill, NJ 07974-0636 + U.S.A. + dmg@bell-labs.com + */ + +#include "gdtoaimp.h" + + static void +#ifdef KR_headers +L_shift(x, x1, i) ULong *x; ULong *x1; int i; +#else +L_shift(ULong *x, ULong *x1, int i) +#endif +{ + int j; + + i = 8 - i; + i <<= 2; + j = ULbits - i; + do { + *x |= x[1] << j; + x[1] >>= i; + } while(++x < x1); + } + + int +#ifdef KR_headers +hexnan(sp, fpi, x0) + CONST char **sp; FPI *fpi; ULong *x0; +#else +hexnan( CONST char **sp, FPI *fpi, ULong *x0) +#endif +{ + ULong c, h, *x, *x1, *xe; + CONST char *s; + int havedig, hd0, i, nbits; + + if (!hexdig['0']) + hexdig_init_D2A(); + nbits = fpi->nbits; + x = x0 + (nbits >> kshift); + if (nbits & kmask) + x++; + *--x = 0; + x1 = xe = x; + havedig = hd0 = i = 0; + s = *sp; + while(c = *(CONST unsigned char*)++s) { + if (!(h = hexdig[c])) { + if (c <= ' ') { + if (hd0 < havedig) { + if (x < x1 && i < 8) + L_shift(x, x1, i); + if (x <= x0) { + i = 8; + continue; + } + hd0 = havedig; + *--x = 0; + x1 = x; + i = 0; + } + continue; + } + if (/*(*/ c == ')' && havedig) { + *sp = s + 1; + break; + } + return STRTOG_NaN; + } + havedig++; + if (++i > 8) { + if (x <= x0) + continue; + i = 1; + *--x = 0; + } + *x = (*x << 4) | h & 0xf; + } + if (!havedig) + return STRTOG_NaN; + if (x < x1 && i < 8) + L_shift(x, x1, i); + if (x > x0) { + x1 = x0; + do *x1++ = *x++; + while(x <= xe); + do *x1++ = 0; + while(x1 <= xe); + } + else { + /* truncate high-order word if necessary */ + if ( (i = nbits & (ULbits-1)) !=0) + *xe &= ((ULong)0xffffffff) >> (ULbits - i); + } + for(x1 = xe;; --x1) { + if (*x1 != 0) + break; + if (x1 == x0) { + *x1 = 1; + break; + } + } + return STRTOG_NaNbits; + } diff --git a/lib/libc/gdtoa/machdep_ldisx.c b/lib/libc/gdtoa/machdep_ldisx.c new file mode 100644 index 0000000..0ceea1b --- /dev/null +++ b/lib/libc/gdtoa/machdep_ldisx.c @@ -0,0 +1,45 @@ +/*- + * Copyright (c) 2003 David Schultz + * 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 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 AUTHOR 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. + */ + +/* + * Machine-dependent glue to integrate David Gay's gdtoa + * package into libc for architectures where a long double + * is an IEEE extended precision number. + */ + +#include +__FBSDID("$FreeBSD: src/lib/libc/gdtoa/machdep_ldisx.c,v 1.2 2003/04/09 05:58:43 das Exp $"); + +#include "gdtoaimp.h" + +long double +strtold(const char * __restrict s, char ** __restrict sp) +{ + long double result; + + strtopx(s, sp, &result); + return result; +} diff --git a/lib/libc/gdtoa/misc.c b/lib/libc/gdtoa/misc.c new file mode 100644 index 0000000..5f5cbc2 --- /dev/null +++ b/lib/libc/gdtoa/misc.c @@ -0,0 +1,862 @@ +/**************************************************************** + +The author of this software is David M. Gay. + +Copyright (C) 1998, 1999 by Lucent Technologies +All Rights Reserved + +Permission to use, copy, modify, and distribute this software and +its documentation for any purpose and without fee is hereby +granted, provided that the above copyright notice appear in all +copies and that both that the copyright notice and this +permission notice and warranty disclaimer appear in supporting +documentation, and that the name of Lucent or any of its entities +not be used in advertising or publicity pertaining to +distribution of the software without specific, written prior +permission. + +LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, +INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. +IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY +SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER +IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. + +****************************************************************/ + +/* Please send bug reports to + David M. Gay + Bell Laboratories, Room 2C-463 + 600 Mountain Avenue + Murray Hill, NJ 07974-0636 + U.S.A. + dmg@bell-labs.com + */ + +#include "gdtoaimp.h" + + static Bigint *freelist[Kmax+1]; +#ifndef Omit_Private_Memory +#ifndef PRIVATE_MEM +#define PRIVATE_MEM 2304 +#endif +#define PRIVATE_mem ((PRIVATE_MEM+sizeof(double)-1)/sizeof(double)) +static double private_mem[PRIVATE_mem], *pmem_next = private_mem; +#endif + + Bigint * +Balloc +#ifdef KR_headers + (k) int k; +#else + (int k) +#endif +{ + int x; + Bigint *rv; +#ifndef Omit_Private_Memory + unsigned int len; +#endif + + ACQUIRE_DTOA_LOCK(0); + if ( (rv = freelist[k]) !=0) { + freelist[k] = rv->next; + } + else { + x = 1 << k; +#ifdef Omit_Private_Memory + rv = (Bigint *)MALLOC(sizeof(Bigint) + (x-1)*sizeof(ULong)); +#else + len = (sizeof(Bigint) + (x-1)*sizeof(ULong) + sizeof(double) - 1) + /sizeof(double); + if (pmem_next - private_mem + len <= PRIVATE_mem) { + rv = (Bigint*)pmem_next; + pmem_next += len; + } + else + rv = (Bigint*)MALLOC(len*sizeof(double)); +#endif + rv->k = k; + rv->maxwds = x; + } + FREE_DTOA_LOCK(0); + rv->sign = rv->wds = 0; + return rv; + } + + void +Bfree +#ifdef KR_headers + (v) Bigint *v; +#else + (Bigint *v) +#endif +{ + if (v) { + ACQUIRE_DTOA_LOCK(0); + v->next = freelist[v->k]; + freelist[v->k] = v; + FREE_DTOA_LOCK(0); + } + } + + int +lo0bits +#ifdef KR_headers + (y) ULong *y; +#else + (ULong *y) +#endif +{ + register int k; + register ULong x = *y; + + if (x & 7) { + if (x & 1) + return 0; + if (x & 2) { + *y = x >> 1; + return 1; + } + *y = x >> 2; + return 2; + } + k = 0; + if (!(x & 0xffff)) { + k = 16; + x >>= 16; + } + if (!(x & 0xff)) { + k += 8; + x >>= 8; + } + if (!(x & 0xf)) { + k += 4; + x >>= 4; + } + if (!(x & 0x3)) { + k += 2; + x >>= 2; + } + if (!(x & 1)) { + k++; + x >>= 1; + if (!x & 1) + return 32; + } + *y = x; + return k; + } + + Bigint * +multadd +#ifdef KR_headers + (b, m, a) Bigint *b; int m, a; +#else + (Bigint *b, int m, int a) /* multiply by m and add a */ +#endif +{ + int i, wds; +#ifdef ULLong + ULong *x; + ULLong carry, y; +#else + ULong carry, *x, y; +#ifdef Pack_32 + ULong xi, z; +#endif +#endif + Bigint *b1; + + wds = b->wds; + x = b->x; + i = 0; + carry = a; + do { +#ifdef ULLong + y = *x * (ULLong)m + carry; + carry = y >> 32; + *x++ = y & 0xffffffffUL; +#else +#ifdef Pack_32 + xi = *x; + y = (xi & 0xffff) * m + carry; + z = (xi >> 16) * m + (y >> 16); + carry = z >> 16; + *x++ = (z << 16) + (y & 0xffff); +#else + y = *x * m + carry; + carry = y >> 16; + *x++ = y & 0xffff; +#endif +#endif + } + while(++i < wds); + if (carry) { + if (wds >= b->maxwds) { + b1 = Balloc(b->k+1); + Bcopy(b1, b); + Bfree(b); + b = b1; + } + b->x[wds++] = carry; + b->wds = wds; + } + return b; + } + + int +hi0bits +#ifdef KR_headers + (x) register ULong x; +#else + (register ULong x) +#endif +{ + register int k = 0; + + if (!(x & 0xffff0000)) { + k = 16; + x <<= 16; + } + if (!(x & 0xff000000)) { + k += 8; + x <<= 8; + } + if (!(x & 0xf0000000)) { + k += 4; + x <<= 4; + } + if (!(x & 0xc0000000)) { + k += 2; + x <<= 2; + } + if (!(x & 0x80000000)) { + k++; + if (!(x & 0x40000000)) + return 32; + } + return k; + } + + Bigint * +i2b +#ifdef KR_headers + (i) int i; +#else + (int i) +#endif +{ + Bigint *b; + + b = Balloc(1); + b->x[0] = i; + b->wds = 1; + return b; + } + + Bigint * +mult +#ifdef KR_headers + (a, b) Bigint *a, *b; +#else + (Bigint *a, Bigint *b) +#endif +{ + Bigint *c; + int k, wa, wb, wc; + ULong *x, *xa, *xae, *xb, *xbe, *xc, *xc0; + ULong y; +#ifdef ULLong + ULLong carry, z; +#else + ULong carry, z; +#ifdef Pack_32 + ULong z2; +#endif +#endif + + if (a->wds < b->wds) { + c = a; + a = b; + b = c; + } + k = a->k; + wa = a->wds; + wb = b->wds; + wc = wa + wb; + if (wc > a->maxwds) + k++; + c = Balloc(k); + for(x = c->x, xa = x + wc; x < xa; x++) + *x = 0; + xa = a->x; + xae = xa + wa; + xb = b->x; + xbe = xb + wb; + xc0 = c->x; +#ifdef ULLong + for(; xb < xbe; xc0++) { + if ( (y = *xb++) !=0) { + x = xa; + xc = xc0; + carry = 0; + do { + z = *x++ * (ULLong)y + *xc + carry; + carry = z >> 32; + *xc++ = z & 0xffffffffUL; + } + while(x < xae); + *xc = carry; + } + } +#else +#ifdef Pack_32 + for(; xb < xbe; xb++, xc0++) { + if ( (y = *xb & 0xffff) !=0) { + x = xa; + xc = xc0; + carry = 0; + do { + z = (*x & 0xffff) * y + (*xc & 0xffff) + carry; + carry = z >> 16; + z2 = (*x++ >> 16) * y + (*xc >> 16) + carry; + carry = z2 >> 16; + Storeinc(xc, z2, z); + } + while(x < xae); + *xc = carry; + } + if ( (y = *xb >> 16) !=0) { + x = xa; + xc = xc0; + carry = 0; + z2 = *xc; + do { + z = (*x & 0xffff) * y + (*xc >> 16) + carry; + carry = z >> 16; + Storeinc(xc, z, z2); + z2 = (*x++ >> 16) * y + (*xc & 0xffff) + carry; + carry = z2 >> 16; + } + while(x < xae); + *xc = z2; + } + } +#else + for(; xb < xbe; xc0++) { + if ( (y = *xb++) !=0) { + x = xa; + xc = xc0; + carry = 0; + do { + z = *x++ * y + *xc + carry; + carry = z >> 16; + *xc++ = z & 0xffff; + } + while(x < xae); + *xc = carry; + } + } +#endif +#endif + for(xc0 = c->x, xc = xc0 + wc; wc > 0 && !*--xc; --wc) ; + c->wds = wc; + return c; + } + + static Bigint *p5s; + + Bigint * +pow5mult +#ifdef KR_headers + (b, k) Bigint *b; int k; +#else + (Bigint *b, int k) +#endif +{ + Bigint *b1, *p5, *p51; + int i; + static int p05[3] = { 5, 25, 125 }; + + if ( (i = k & 3) !=0) + b = multadd(b, p05[i-1], 0); + + if (!(k >>= 2)) + return b; + if ((p5 = p5s) == 0) { + /* first time */ +#ifdef MULTIPLE_THREADS + ACQUIRE_DTOA_LOCK(1); + if (!(p5 = p5s)) { + p5 = p5s = i2b(625); + p5->next = 0; + } + FREE_DTOA_LOCK(1); +#else + p5 = p5s = i2b(625); + p5->next = 0; +#endif + } + for(;;) { + if (k & 1) { + b1 = mult(b, p5); + Bfree(b); + b = b1; + } + if (!(k >>= 1)) + break; + if ((p51 = p5->next) == 0) { +#ifdef MULTIPLE_THREADS + ACQUIRE_DTOA_LOCK(1); + if (!(p51 = p5->next)) { + p51 = p5->next = mult(p5,p5); + p51->next = 0; + } + FREE_DTOA_LOCK(1); +#else + p51 = p5->next = mult(p5,p5); + p51->next = 0; +#endif + } + p5 = p51; + } + return b; + } + + Bigint * +lshift +#ifdef KR_headers + (b, k) Bigint *b; int k; +#else + (Bigint *b, int k) +#endif +{ + int i, k1, n, n1; + Bigint *b1; + ULong *x, *x1, *xe, z; + + n = k >> kshift; + k1 = b->k; + n1 = n + b->wds + 1; + for(i = b->maxwds; n1 > i; i <<= 1) + k1++; + b1 = Balloc(k1); + x1 = b1->x; + for(i = 0; i < n; i++) + *x1++ = 0; + x = b->x; + xe = x + b->wds; + if (k &= kmask) { +#ifdef Pack_32 + k1 = 32 - k; + z = 0; + do { + *x1++ = *x << k | z; + z = *x++ >> k1; + } + while(x < xe); + if ((*x1 = z) !=0) + ++n1; +#else + k1 = 16 - k; + z = 0; + do { + *x1++ = *x << k & 0xffff | z; + z = *x++ >> k1; + } + while(x < xe); + if (*x1 = z) + ++n1; +#endif + } + else do + *x1++ = *x++; + while(x < xe); + b1->wds = n1 - 1; + Bfree(b); + return b1; + } + + int +cmp +#ifdef KR_headers + (a, b) Bigint *a, *b; +#else + (Bigint *a, Bigint *b) +#endif +{ + ULong *xa, *xa0, *xb, *xb0; + int i, j; + + i = a->wds; + j = b->wds; +#ifdef DEBUG + if (i > 1 && !a->x[i-1]) + Bug("cmp called with a->x[a->wds-1] == 0"); + if (j > 1 && !b->x[j-1]) + Bug("cmp called with b->x[b->wds-1] == 0"); +#endif + if (i -= j) + return i; + xa0 = a->x; + xa = xa0 + j; + xb0 = b->x; + xb = xb0 + j; + for(;;) { + if (*--xa != *--xb) + return *xa < *xb ? -1 : 1; + if (xa <= xa0) + break; + } + return 0; + } + + Bigint * +diff +#ifdef KR_headers + (a, b) Bigint *a, *b; +#else + (Bigint *a, Bigint *b) +#endif +{ + Bigint *c; + int i, wa, wb; + ULong *xa, *xae, *xb, *xbe, *xc; +#ifdef ULLong + ULLong borrow, y; +#else + ULong borrow, y; +#ifdef Pack_32 + ULong z; +#endif +#endif + + i = cmp(a,b); + if (!i) { + c = Balloc(0); + c->wds = 1; + c->x[0] = 0; + return c; + } + if (i < 0) { + c = a; + a = b; + b = c; + i = 1; + } + else + i = 0; + c = Balloc(a->k); + c->sign = i; + wa = a->wds; + xa = a->x; + xae = xa + wa; + wb = b->wds; + xb = b->x; + xbe = xb + wb; + xc = c->x; + borrow = 0; +#ifdef ULLong + do { + y = (ULLong)*xa++ - *xb++ - borrow; + borrow = y >> 32 & 1UL; + *xc++ = y & 0xffffffffUL; + } + while(xb < xbe); + while(xa < xae) { + y = *xa++ - borrow; + borrow = y >> 32 & 1UL; + *xc++ = y & 0xffffffffUL; + } +#else +#ifdef Pack_32 + do { + y = (*xa & 0xffff) - (*xb & 0xffff) - borrow; + borrow = (y & 0x10000) >> 16; + z = (*xa++ >> 16) - (*xb++ >> 16) - borrow; + borrow = (z & 0x10000) >> 16; + Storeinc(xc, z, y); + } + while(xb < xbe); + while(xa < xae) { + y = (*xa & 0xffff) - borrow; + borrow = (y & 0x10000) >> 16; + z = (*xa++ >> 16) - borrow; + borrow = (z & 0x10000) >> 16; + Storeinc(xc, z, y); + } +#else + do { + y = *xa++ - *xb++ - borrow; + borrow = (y & 0x10000) >> 16; + *xc++ = y & 0xffff; + } + while(xb < xbe); + while(xa < xae) { + y = *xa++ - borrow; + borrow = (y & 0x10000) >> 16; + *xc++ = y & 0xffff; + } +#endif +#endif + while(!*--xc) + wa--; + c->wds = wa; + return c; + } + + double +b2d +#ifdef KR_headers + (a, e) Bigint *a; int *e; +#else + (Bigint *a, int *e) +#endif +{ + ULong *xa, *xa0, w, y, z; + int k; + double d; +#ifdef VAX + ULong d0, d1; +#else +#define d0 word0(d) +#define d1 word1(d) +#endif + + xa0 = a->x; + xa = xa0 + a->wds; + y = *--xa; +#ifdef DEBUG + if (!y) Bug("zero y in b2d"); +#endif + k = hi0bits(y); + *e = 32 - k; +#ifdef Pack_32 + if (k < Ebits) { + d0 = Exp_1 | y >> Ebits - k; + w = xa > xa0 ? *--xa : 0; + d1 = y << (32-Ebits) + k | w >> Ebits - k; + goto ret_d; + } + z = xa > xa0 ? *--xa : 0; + if (k -= Ebits) { + d0 = Exp_1 | y << k | z >> 32 - k; + y = xa > xa0 ? *--xa : 0; + d1 = z << k | y >> 32 - k; + } + else { + d0 = Exp_1 | y; + d1 = z; + } +#else + if (k < Ebits + 16) { + z = xa > xa0 ? *--xa : 0; + d0 = Exp_1 | y << k - Ebits | z >> Ebits + 16 - k; + w = xa > xa0 ? *--xa : 0; + y = xa > xa0 ? *--xa : 0; + d1 = z << k + 16 - Ebits | w << k - Ebits | y >> 16 + Ebits - k; + goto ret_d; + } + z = xa > xa0 ? *--xa : 0; + w = xa > xa0 ? *--xa : 0; + k -= Ebits + 16; + d0 = Exp_1 | y << k + 16 | z << k | w >> 16 - k; + y = xa > xa0 ? *--xa : 0; + d1 = w << k + 16 | y << k; +#endif + ret_d: +#ifdef VAX + word0(d) = d0 >> 16 | d0 << 16; + word1(d) = d1 >> 16 | d1 << 16; +#endif + return dval(d); + } +#undef d0 +#undef d1 + + Bigint * +d2b +#ifdef KR_headers + (d, e, bits) double d; int *e, *bits; +#else + (double d, int *e, int *bits) +#endif +{ + Bigint *b; + int de, i, k; + ULong *x, y, z; +#ifdef VAX + ULong d0, d1; + d0 = word0(d) >> 16 | word0(d) << 16; + d1 = word1(d) >> 16 | word1(d) << 16; +#else +#define d0 word0(d) +#define d1 word1(d) +#endif + +#ifdef Pack_32 + b = Balloc(1); +#else + b = Balloc(2); +#endif + x = b->x; + + z = d0 & Frac_mask; + d0 &= 0x7fffffff; /* clear sign bit, which we ignore */ +#ifdef Sudden_Underflow + de = (int)(d0 >> Exp_shift); +#ifndef IBM + z |= Exp_msk11; +#endif +#else + if ( (de = (int)(d0 >> Exp_shift)) !=0) + z |= Exp_msk1; +#endif +#ifdef Pack_32 + if ( (y = d1) !=0) { + if ( (k = lo0bits(&y)) !=0) { + x[0] = y | z << 32 - k; + z >>= k; + } + else + x[0] = y; + i = b->wds = (x[1] = z) !=0 ? 2 : 1; + } + else { +#ifdef DEBUG + if (!z) + Bug("Zero passed to d2b"); +#endif + k = lo0bits(&z); + x[0] = z; + i = b->wds = 1; + k += 32; + } +#else + if ( (y = d1) !=0) { + if ( (k = lo0bits(&y)) !=0) + if (k >= 16) { + x[0] = y | z << 32 - k & 0xffff; + x[1] = z >> k - 16 & 0xffff; + x[2] = z >> k; + i = 2; + } + else { + x[0] = y & 0xffff; + x[1] = y >> 16 | z << 16 - k & 0xffff; + x[2] = z >> k & 0xffff; + x[3] = z >> k+16; + i = 3; + } + else { + x[0] = y & 0xffff; + x[1] = y >> 16; + x[2] = z & 0xffff; + x[3] = z >> 16; + i = 3; + } + } + else { +#ifdef DEBUG + if (!z) + Bug("Zero passed to d2b"); +#endif + k = lo0bits(&z); + if (k >= 16) { + x[0] = z; + i = 0; + } + else { + x[0] = z & 0xffff; + x[1] = z >> 16; + i = 1; + } + k += 32; + } + while(!x[i]) + --i; + b->wds = i + 1; +#endif +#ifndef Sudden_Underflow + if (de) { +#endif +#ifdef IBM + *e = (de - Bias - (P-1) << 2) + k; + *bits = 4*P + 8 - k - hi0bits(word0(d) & Frac_mask); +#else + *e = de - Bias - (P-1) + k; + *bits = P - k; +#endif +#ifndef Sudden_Underflow + } + else { + *e = de - Bias - (P-1) + 1 + k; +#ifdef Pack_32 + *bits = 32*i - hi0bits(x[i-1]); +#else + *bits = (i+2)*16 - hi0bits(x[i]); +#endif + } +#endif + return b; + } +#undef d0 +#undef d1 + + CONST double +#ifdef IEEE_Arith +bigtens[] = { 1e16, 1e32, 1e64, 1e128, 1e256 }; +CONST double tinytens[] = { 1e-16, 1e-32, 1e-64, 1e-128, 1e-256 + }; +#else +#ifdef IBM +bigtens[] = { 1e16, 1e32, 1e64 }; +CONST double tinytens[] = { 1e-16, 1e-32, 1e-64 }; +#else +bigtens[] = { 1e16, 1e32 }; +CONST double tinytens[] = { 1e-16, 1e-32 }; +#endif +#endif + + CONST double +tens[] = { + 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, + 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19, + 1e20, 1e21, 1e22 +#ifdef VAX + , 1e23, 1e24 +#endif + }; + + char * +#ifdef KR_headers +strcp_D2A(a, b) char *a; char *b; +#else +strcp_D2A(char *a, CONST char *b) +#endif +{ + while(*a = *b++) + a++; + return a; + } + +#ifdef NO_STRING_H + + Char * +#ifdef KR_headers +memcpy_D2A(a, b, len) Char *a; Char *b; size_t len; +#else +memcpy_D2A(void *a1, void *b1, size_t len) +#endif +{ + register char *a = (char*)a1, *ae = a + len; + register char *b = (char*)b1, *a0 = a; + while(a < ae) + *a++ = *b++; + return a0; + } + +#endif /* NO_STRING_H */ diff --git a/lib/libc/gdtoa/smisc.c b/lib/libc/gdtoa/smisc.c new file mode 100644 index 0000000..e20e9da --- /dev/null +++ b/lib/libc/gdtoa/smisc.c @@ -0,0 +1,197 @@ +/**************************************************************** + +The author of this software is David M. Gay. + +Copyright (C) 1998, 1999 by Lucent Technologies +All Rights Reserved + +Permission to use, copy, modify, and distribute this software and +its documentation for any purpose and without fee is hereby +granted, provided that the above copyright notice appear in all +copies and that both that the copyright notice and this +permission notice and warranty disclaimer appear in supporting +documentation, and that the name of Lucent or any of its entities +not be used in advertising or publicity pertaining to +distribution of the software without specific, written prior +permission. + +LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, +INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. +IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY +SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER +IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. + +****************************************************************/ + +/* Please send bug reports to + David M. Gay + Bell Laboratories, Room 2C-463 + 600 Mountain Avenue + Murray Hill, NJ 07974-0636 + U.S.A. + dmg@bell-labs.com + */ + +#include "gdtoaimp.h" + + Bigint * +s2b +#ifdef KR_headers + (s, nd0, nd, y9) CONST char *s; int nd0, nd; ULong y9; +#else + (CONST char *s, int nd0, int nd, ULong y9) +#endif +{ + Bigint *b; + int i, k; + Long x, y; + + x = (nd + 8) / 9; + for(k = 0, y = 1; x > y; y <<= 1, k++) ; +#ifdef Pack_32 + b = Balloc(k); + b->x[0] = y9; + b->wds = 1; +#else + b = Balloc(k+1); + b->x[0] = y9 & 0xffff; + b->wds = (b->x[1] = y9 >> 16) ? 2 : 1; +#endif + + i = 9; + if (9 < nd0) { + s += 9; + do b = multadd(b, 10, *s++ - '0'); + while(++i < nd0); + s++; + } + else + s += 10; + for(; i < nd; i++) + b = multadd(b, 10, *s++ - '0'); + return b; + } + + double +ratio +#ifdef KR_headers + (a, b) Bigint *a, *b; +#else + (Bigint *a, Bigint *b) +#endif +{ + double da, db; + int k, ka, kb; + + dval(da) = b2d(a, &ka); + dval(db) = b2d(b, &kb); + k = ka - kb + ULbits*(a->wds - b->wds); +#ifdef IBM + if (k > 0) { + word0(da) += (k >> 2)*Exp_msk1; + if (k &= 3) + dval(da) *= 1 << k; + } + else { + k = -k; + word0(db) += (k >> 2)*Exp_msk1; + if (k &= 3) + dval(db) *= 1 << k; + } +#else + if (k > 0) + word0(da) += k*Exp_msk1; + else { + k = -k; + word0(db) += k*Exp_msk1; + } +#endif + return dval(da) / dval(db); + } + +#ifdef INFNAN_CHECK + + int +match +#ifdef KR_headers + (sp, t) char **sp, *t; +#else + (CONST char **sp, char *t) +#endif +{ + int c, d; + CONST char *s = *sp; + + while( (d = *t++) !=0) { + if ((c = *++s) >= 'A' && c <= 'Z') + c += 'a' - 'A'; + if (c != d) + return 0; + } + *sp = s + 1; + return 1; + } +#endif /* INFNAN_CHECK */ + + void +#ifdef KR_headers +copybits(c, n, b) ULong *c; int n; Bigint *b; +#else +copybits(ULong *c, int n, Bigint *b) +#endif +{ + ULong *ce, *x, *xe; +#ifdef Pack_16 + int nw, nw1; +#endif + + ce = c + ((n-1) >> kshift) + 1; + x = b->x; +#ifdef Pack_32 + xe = x + b->wds; + while(x < xe) + *c++ = *x++; +#else + nw = b->wds; + nw1 = nw & 1; + for(xe = x + (nw - nw1); x < xe; x += 2) + Storeinc(c, x[1], x[0]); + if (nw1) + *c++ = *x; +#endif + while(c < ce) + *c++ = 0; + } + + ULong +#ifdef KR_headers +any_on(b, k) Bigint *b; int k; +#else +any_on(Bigint *b, int k) +#endif +{ + int n, nwds; + ULong *x, *x0, x1, x2; + + x = b->x; + nwds = b->wds; + n = k >> kshift; + if (n > nwds) + n = nwds; + else if (n < nwds && (k &= kmask)) { + x1 = x2 = x[n]; + x1 >>= k; + x1 <<= k; + if (x1 != x2) + return 1; + } + x0 = x; + x += n; + while(x > x0) + if (*--x) + return 1; + return 0; + } diff --git a/lib/libc/gdtoa/strtoIQ.c b/lib/libc/gdtoa/strtoIQ.c new file mode 100644 index 0000000..0ce0420 --- /dev/null +++ b/lib/libc/gdtoa/strtoIQ.c @@ -0,0 +1,69 @@ +/**************************************************************** + +The author of this software is David M. Gay. + +Copyright (C) 1998 by Lucent Technologies +All Rights Reserved + +Permission to use, copy, modify, and distribute this software and +its documentation for any purpose and without fee is hereby +granted, provided that the above copyright notice appear in all +copies and that both that the copyright notice and this +permission notice and warranty disclaimer appear in supporting +documentation, and that the name of Lucent or any of its entities +not be used in advertising or publicity pertaining to +distribution of the software without specific, written prior +permission. + +LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, +INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. +IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY +SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER +IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. + +****************************************************************/ + +/* Please send bug reports to + David M. Gay + Bell Laboratories, Room 2C-463 + 600 Mountain Avenue + Murray Hill, NJ 07974-0636 + U.S.A. + dmg@bell-labs.com + */ + +#include "gdtoaimp.h" + + int +#ifdef KR_headers +strtoIQ(s, sp, a, b) CONST char *s; char **sp; void *a; void *b; +#else +strtoIQ(CONST char *s, char **sp, void *a, void *b) +#endif +{ + static FPI fpi = { 113, 1-16383-113+1, 32766-16383-113+1, 1, SI }; + Long exp[2]; + Bigint *B[2]; + int k, rv[2]; + ULong *L = (ULong *)a, *M = (ULong *)b; + + B[0] = Balloc(2); + B[0]->wds = 4; + k = strtoIg(s, sp, &fpi, exp, B, rv); + ULtoQ(L, B[0]->x, exp[0], rv[0]); + Bfree(B[0]); + if (B[1]) { + ULtoQ(M, B[1]->x, exp[1], rv[1]); + Bfree(B[1]); + } + else { + M[0] = L[0]; + M[1] = L[1]; + M[2] = L[2]; + M[3] = L[3]; + } + return k; + } diff --git a/lib/libc/gdtoa/strtoId.c b/lib/libc/gdtoa/strtoId.c new file mode 100644 index 0000000..f986e04 --- /dev/null +++ b/lib/libc/gdtoa/strtoId.c @@ -0,0 +1,66 @@ +/**************************************************************** + +The author of this software is David M. Gay. + +Copyright (C) 1998 by Lucent Technologies +All Rights Reserved + +Permission to use, copy, modify, and distribute this software and +its documentation for any purpose and without fee is hereby +granted, provided that the above copyright notice appear in all +copies and that both that the copyright notice and this +permission notice and warranty disclaimer appear in supporting +documentation, and that the name of Lucent or any of its entities +not be used in advertising or publicity pertaining to +distribution of the software without specific, written prior +permission. + +LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, +INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. +IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY +SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER +IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. + +****************************************************************/ + +/* Please send bug reports to + David M. Gay + Bell Laboratories, Room 2C-463 + 600 Mountain Avenue + Murray Hill, NJ 07974-0636 + U.S.A. + dmg@bell-labs.com + */ + +#include "gdtoaimp.h" + + int +#ifdef KR_headers +strtoId(s, sp, f0, f1) CONST char *s; char **sp; double *f0, *f1; +#else +strtoId(CONST char *s, char **sp, double *f0, double *f1) +#endif +{ + static FPI fpi = { 53, 1-1023-53+1, 2046-1023-53+1, 1, SI }; + Long exp[2]; + Bigint *B[2]; + int k, rv[2]; + + B[0] = Balloc(1); + B[0]->wds = 2; + k = strtoIg(s, sp, &fpi, exp, B, rv); + ULtod((ULong*)f0, B[0]->x, exp[0], rv[0]); + Bfree(B[0]); + if (B[1]) { + ULtod((ULong*)f1, B[1]->x, exp[1], rv[1]); + Bfree(B[1]); + } + else { + ((ULong*)f1)[0] = ((ULong*)f0)[0]; + ((ULong*)f1)[1] = ((ULong*)f0)[1]; + } + return k; + } diff --git a/lib/libc/gdtoa/strtoIdd.c b/lib/libc/gdtoa/strtoIdd.c new file mode 100644 index 0000000..9622c18 --- /dev/null +++ b/lib/libc/gdtoa/strtoIdd.c @@ -0,0 +1,72 @@ +/**************************************************************** + +The author of this software is David M. Gay. + +Copyright (C) 1998 by Lucent Technologies +All Rights Reserved + +Permission to use, copy, modify, and distribute this software and +its documentation for any purpose and without fee is hereby +granted, provided that the above copyright notice appear in all +copies and that both that the copyright notice and this +permission notice and warranty disclaimer appear in supporting +documentation, and that the name of Lucent or any of its entities +not be used in advertising or publicity pertaining to +distribution of the software without specific, written prior +permission. + +LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, +INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. +IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY +SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER +IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. + +****************************************************************/ + +/* Please send bug reports to + David M. Gay + Bell Laboratories, Room 2C-463 + 600 Mountain Avenue + Murray Hill, NJ 07974-0636 + U.S.A. + dmg@bell-labs.com + */ + +#include "gdtoaimp.h" + + int +#ifdef KR_headers +strtoIdd(s, sp, f0, f1) CONST char *s; char **sp; double *f0, *f1; +#else +strtoIdd(CONST char *s, char **sp, double *f0, double *f1) +#endif +{ +#ifdef Sudden_Underflow + static FPI fpi = { 106, 1-1023, 2046-1023-106+1, 1, 1 }; +#else + static FPI fpi = { 106, 1-1023-53+1, 2046-1023-106+1, 1, 0 }; +#endif + Long exp[2]; + Bigint *B[2]; + int k, rv[2]; + + B[0] = Balloc(2); + B[0]->wds = 4; + k = strtoIg(s, sp, &fpi, exp, B, rv); + ULtodd((ULong*)f0, B[0]->x, exp[0], rv[0]); + Bfree(B[0]); + if (B[1]) { + ULtodd((ULong*)f1, B[1]->x, exp[1], rv[1]); + Bfree(B[1]); + } + else { + ((ULong*)f1)[0] = ((ULong*)f0)[0]; + ((ULong*)f1)[1] = ((ULong*)f0)[1]; + ((ULong*)f1)[2] = ((ULong*)f0)[2]; + ((ULong*)f1)[3] = ((ULong*)f0)[3]; + } + return k; + } diff --git a/lib/libc/gdtoa/strtoIf.c b/lib/libc/gdtoa/strtoIf.c new file mode 100644 index 0000000..c439ff5 --- /dev/null +++ b/lib/libc/gdtoa/strtoIf.c @@ -0,0 +1,64 @@ +/**************************************************************** + +The author of this software is David M. Gay. + +Copyright (C) 1998 by Lucent Technologies +All Rights Reserved + +Permission to use, copy, modify, and distribute this software and +its documentation for any purpose and without fee is hereby +granted, provided that the above copyright notice appear in all +copies and that both that the copyright notice and this +permission notice and warranty disclaimer appear in supporting +documentation, and that the name of Lucent or any of its entities +not be used in advertising or publicity pertaining to +distribution of the software without specific, written prior +permission. + +LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, +INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. +IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY +SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER +IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. + +****************************************************************/ + +/* Please send bug reports to + David M. Gay + Bell Laboratories, Room 2C-463 + 600 Mountain Avenue + Murray Hill, NJ 07974-0636 + U.S.A. + dmg@bell-labs.com + */ + +#include "gdtoaimp.h" + + int +#ifdef KR_headers +strtoIf(s, sp, f0, f1) CONST char *s; char **sp; float *f0, *f1; +#else +strtoIf(CONST char *s, char **sp, float *f0, float *f1) +#endif +{ + static FPI fpi = { 24, 1-127-24+1, 254-127-24+1, 1, SI }; + Long exp[2]; + Bigint *B[2]; + int k, rv[2]; + + B[0] = Balloc(0); + B[0]->wds = 1; + k = strtoIg(s, sp, &fpi, exp, B, rv); + ULtof((ULong*)f0, B[0]->x, exp[0], rv[0]); + Bfree(B[0]); + if (B[1]) { + ULtof((ULong*)f1, B[1]->x, exp[1], rv[1]); + Bfree(B[1]); + } + else + *(ULong*)f1 = *(ULong*)f0; + return k; + } diff --git a/lib/libc/gdtoa/strtoIg.c b/lib/libc/gdtoa/strtoIg.c new file mode 100644 index 0000000..a766813 --- /dev/null +++ b/lib/libc/gdtoa/strtoIg.c @@ -0,0 +1,139 @@ +/**************************************************************** + +The author of this software is David M. Gay. + +Copyright (C) 1998 by Lucent Technologies +All Rights Reserved + +Permission to use, copy, modify, and distribute this software and +its documentation for any purpose and without fee is hereby +granted, provided that the above copyright notice appear in all +copies and that both that the copyright notice and this +permission notice and warranty disclaimer appear in supporting +documentation, and that the name of Lucent or any of its entities +not be used in advertising or publicity pertaining to +distribution of the software without specific, written prior +permission. + +LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, +INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. +IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY +SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER +IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. + +****************************************************************/ + +/* Please send bug reports to + David M. Gay + Bell Laboratories, Room 2C-463 + 600 Mountain Avenue + Murray Hill, NJ 07974-0636 + U.S.A. + dmg@bell-labs.com + */ + +#include "gdtoaimp.h" + + int +#ifdef KR_headers +strtoIg(s00, se, fpi, exp, B, rvp) CONST char *s00; char **se; FPI *fpi; Long *exp; Bigint **B; int *rvp; +#else +strtoIg(CONST char *s00, char **se, FPI *fpi, Long *exp, Bigint **B, int *rvp) +#endif +{ + Bigint *b, *b1; + int i, nb, nw, nw1, rv, rv1, swap; + unsigned int nb1, nb11; + Long e1; + + b = *B; + rv = strtodg(s00, se, fpi, exp, b->x); + if (!(rv & STRTOG_Inexact)) { + B[1] = 0; + return *rvp = rv; + } + e1 = exp[0]; + rv1 = rv ^ STRTOG_Inexact; + b1 = Balloc(b->k); + Bcopy(b1, b); + nb = fpi->nbits; + nb1 = nb & 31; + nb11 = (nb1 - 1) & 31; + nw = b->wds; + nw1 = nw - 1; + if (rv & STRTOG_Inexlo) { + swap = 0; + b1 = increment(b1); + if (fpi->sudden_underflow + && (rv & STRTOG_Retmask) == STRTOG_Zero) { + b1->x[0] = 0; + b1->x[nw1] = 1L << nb11; + rv1 += STRTOG_Normal - STRTOG_Zero; + rv1 &= ~STRTOG_Underflow; + goto swapcheck; + } + if (b1->wds > nw + || nb1 && b1->x[nw1] & 1L << nb1) { + if (++e1 > fpi->emax) + rv1 = STRTOG_Infinite | STRTOG_Inexhi; + rshift(b1, 1); + } + else if ((rv & STRTOG_Retmask) == STRTOG_Denormal) { + if (b1->x[nw1] & 1L << nb11) { + rv1 += STRTOG_Normal - STRTOG_Denormal; + rv1 &= ~STRTOG_Underflow; + } + } + } + else { + swap = STRTOG_Neg; + if ((rv & STRTOG_Retmask) == STRTOG_Infinite) { + b1 = set_ones(b1, nb); + e1 = fpi->emax; + rv1 = STRTOG_Normal | STRTOG_Inexlo; + goto swapcheck; + } + decrement(b1); + if ((rv & STRTOG_Retmask) == STRTOG_Denormal) { + for(i = nw1; !b1->x[i]; --i) + if (!i) { + rv1 = STRTOG_Zero | STRTOG_Inexlo; + break; + } + goto swapcheck; + } + if (!(b1->x[nw1] & 1L << nb11)) { + if (e1 == fpi->emin) { + if (fpi->sudden_underflow) + rv1 += STRTOG_Zero - STRTOG_Normal; + else + rv1 += STRTOG_Denormal - STRTOG_Normal; + rv1 |= STRTOG_Underflow; + } + else { + b1 = lshift(b1, 1); + b1->x[0] |= 1; + --e1; + } + } + } + swapcheck: + if (swap ^ (rv & STRTOG_Neg)) { + rvp[0] = rv1; + rvp[1] = rv; + B[0] = b1; + B[1] = b; + exp[1] = exp[0]; + exp[0] = e1; + } + else { + rvp[0] = rv; + rvp[1] = rv1; + B[1] = b1; + exp[1] = e1; + } + return rv; + } diff --git a/lib/libc/gdtoa/strtoIx.c b/lib/libc/gdtoa/strtoIx.c new file mode 100644 index 0000000..d699f04 --- /dev/null +++ b/lib/libc/gdtoa/strtoIx.c @@ -0,0 +1,70 @@ +/**************************************************************** + +The author of this software is David M. Gay. + +Copyright (C) 1998 by Lucent Technologies +All Rights Reserved + +Permission to use, copy, modify, and distribute this software and +its documentation for any purpose and without fee is hereby +granted, provided that the above copyright notice appear in all +copies and that both that the copyright notice and this +permission notice and warranty disclaimer appear in supporting +documentation, and that the name of Lucent or any of its entities +not be used in advertising or publicity pertaining to +distribution of the software without specific, written prior +permission. + +LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, +INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. +IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY +SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER +IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. + +****************************************************************/ + +/* Please send bug reports to + David M. Gay + Bell Laboratories, Room 2C-463 + 600 Mountain Avenue + Murray Hill, NJ 07974-0636 + U.S.A. + dmg@bell-labs.com + */ + +#include "gdtoaimp.h" + + int +#ifdef KR_headers +strtoIx(s, sp, a, b) CONST char *s; char **sp; void *a; void *b; +#else +strtoIx(CONST char *s, char **sp, void *a, void *b) +#endif +{ + static FPI fpi = { 64, 1-16383-64+1, 32766 - 16383 - 64 + 1, 1, SI }; + Long exp[2]; + Bigint *B[2]; + int k, rv[2]; + UShort *L = (UShort *)a, *M = (UShort *)b; + + B[0] = Balloc(1); + B[0]->wds = 2; + k = strtoIg(s, sp, &fpi, exp, B, rv); + ULtox(L, B[0]->x, exp[0], rv[0]); + Bfree(B[0]); + if (B[1]) { + ULtox(M, B[1]->x, exp[1], rv[1]); + Bfree(B[1]); + } + else { + M[0] = L[0]; + M[1] = L[1]; + M[2] = L[2]; + M[3] = L[3]; + M[4] = L[4]; + } + return k; + } diff --git a/lib/libc/gdtoa/strtoIxL.c b/lib/libc/gdtoa/strtoIxL.c new file mode 100644 index 0000000..c579589 --- /dev/null +++ b/lib/libc/gdtoa/strtoIxL.c @@ -0,0 +1,68 @@ +/**************************************************************** + +The author of this software is David M. Gay. + +Copyright (C) 1998 by Lucent Technologies +All Rights Reserved + +Permission to use, copy, modify, and distribute this software and +its documentation for any purpose and without fee is hereby +granted, provided that the above copyright notice appear in all +copies and that both that the copyright notice and this +permission notice and warranty disclaimer appear in supporting +documentation, and that the name of Lucent or any of its entities +not be used in advertising or publicity pertaining to +distribution of the software without specific, written prior +permission. + +LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, +INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. +IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY +SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER +IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. + +****************************************************************/ + +/* Please send bug reports to + David M. Gay + Bell Laboratories, Room 2C-463 + 600 Mountain Avenue + Murray Hill, NJ 07974-0636 + U.S.A. + dmg@bell-labs.com + */ + +#include "gdtoaimp.h" + + int +#ifdef KR_headers +strtoIxL(s, sp, a, b) CONST char *s; char **sp; void *a; void *b; +#else +strtoIxL(CONST char *s, char **sp, void *a, void *b) +#endif +{ + static FPI fpi = { 64, 1-16383-64+1, 32766 - 16383 - 64 + 1, 1, SI }; + Long exp[2]; + Bigint *B[2]; + int k, rv[2]; + ULong *L = (ULong *)a, *M = (ULong *)b; + + B[0] = Balloc(1); + B[0]->wds = 2; + k = strtoIg(s, sp, &fpi, exp, B, rv); + ULtoxL(L, B[0]->x, exp[0], rv[0]); + Bfree(B[0]); + if (B[1]) { + ULtoxL(M, B[1]->x, exp[1], rv[1]); + Bfree(B[1]); + } + else { + M[0] = L[0]; + M[1] = L[1]; + M[2] = L[2]; + } + return k; + } diff --git a/lib/libc/gdtoa/strtod.c b/lib/libc/gdtoa/strtod.c new file mode 100644 index 0000000..4913d50 --- /dev/null +++ b/lib/libc/gdtoa/strtod.c @@ -0,0 +1,966 @@ +/**************************************************************** + +The author of this software is David M. Gay. + +Copyright (C) 1998-2001 by Lucent Technologies +All Rights Reserved + +Permission to use, copy, modify, and distribute this software and +its documentation for any purpose and without fee is hereby +granted, provided that the above copyright notice appear in all +copies and that both that the copyright notice and this +permission notice and warranty disclaimer appear in supporting +documentation, and that the name of Lucent or any of its entities +not be used in advertising or publicity pertaining to +distribution of the software without specific, written prior +permission. + +LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, +INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. +IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY +SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER +IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. + +****************************************************************/ + +/* Please send bug reports to + David M. Gay + dmg@acm.org + */ + +#include "gdtoaimp.h" + +#ifdef USE_LOCALE +#include "locale.h" +#endif + +#ifdef IEEE_Arith +#ifndef NO_IEEE_Scale +#define Avoid_Underflow +#undef tinytens +/* The factor of 2^53 in tinytens[4] helps us avoid setting the underflow */ +/* flag unnecessarily. It leads to a song and dance at the end of strtod. */ +static CONST double tinytens[] = { 1e-16, 1e-32, 1e-64, 1e-128, + 9007199254740992.e-256 + }; +#endif +#endif + +#ifdef Honor_FLT_ROUNDS +#define Rounding rounding +#undef Check_FLT_ROUNDS +#define Check_FLT_ROUNDS +#else +#define Rounding Flt_Rounds +#endif + + double +strtod +#ifdef KR_headers + (s00, se) CONST char *s00; char **se; +#else + (CONST char *s00, char **se) +#endif +{ +#ifdef Avoid_Underflow + int scale; +#endif + int bb2, bb5, bbe, bd2, bd5, bbbits, bs2, c, dsign, + e, e1, esign, i, j, k, nd, nd0, nf, nz, nz0, sign; + CONST char *s, *s0, *s1; + double aadj, aadj1, adj, rv, rv0; + Long L; + ULong y, z; + Bigint *bb, *bb1, *bd, *bd0, *bs, *delta; +#ifdef SET_INEXACT + int inexact, oldinexact; +#endif +#ifdef Honor_FLT_ROUNDS + int rounding; +#endif + + sign = nz0 = nz = 0; + dval(rv) = 0.; + for(s = s00;;s++) switch(*s) { + case '-': + sign = 1; + /* no break */ + case '+': + if (*++s) + goto break2; + /* no break */ + case 0: + goto ret0; + case '\t': + case '\n': + case '\v': + case '\f': + case '\r': + case ' ': + continue; + default: + goto break2; + } + break2: + if (*s == '0') { +#ifndef NO_HEX_FP + { + static FPI fpi = { 53, 1-1023-53+1, 2046-1023-53+1, 1, SI }; + Long exp; + ULong bits[2]; + switch(s[1]) { + case 'x': + case 'X': + switch((i = gethex(&s, &fpi, &exp, &bb, sign)) & STRTOG_Retmask) { + case STRTOG_NoNumber: + s = s00; + sign = 0; + case STRTOG_Zero: + break; + default: + if (bb) { + copybits(bits, fpi.nbits, bb); + Bfree(bb); + } + ULtod(((U*)&rv)->L, bits, exp, i); + } + goto ret; + } + } +#endif + nz0 = 1; + while(*++s == '0') ; + if (!*s) + goto ret; + } + s0 = s; + y = z = 0; + for(nd = nf = 0; (c = *s) >= '0' && c <= '9'; nd++, s++) + if (nd < 9) + y = 10*y + c - '0'; + else if (nd < 16) + z = 10*z + c - '0'; + nd0 = nd; +#ifdef USE_LOCALE + if (c == *localeconv()->decimal_point) +#else + if (c == '.') +#endif + { + c = *++s; + if (!nd) { + for(; c == '0'; c = *++s) + nz++; + if (c > '0' && c <= '9') { + s0 = s; + nf += nz; + nz = 0; + goto have_dig; + } + goto dig_done; + } + for(; c >= '0' && c <= '9'; c = *++s) { + have_dig: + nz++; + if (c -= '0') { + nf += nz; + for(i = 1; i < nz; i++) + if (nd++ < 9) + y *= 10; + else if (nd <= DBL_DIG + 1) + z *= 10; + if (nd++ < 9) + y = 10*y + c; + else if (nd <= DBL_DIG + 1) + z = 10*z + c; + nz = 0; + } + } + } + dig_done: + e = 0; + if (c == 'e' || c == 'E') { + if (!nd && !nz && !nz0) { + goto ret0; + } + s00 = s; + esign = 0; + switch(c = *++s) { + case '-': + esign = 1; + case '+': + c = *++s; + } + if (c >= '0' && c <= '9') { + while(c == '0') + c = *++s; + if (c > '0' && c <= '9') { + L = c - '0'; + s1 = s; + while((c = *++s) >= '0' && c <= '9') + L = 10*L + c - '0'; + if (s - s1 > 8 || L > 19999) + /* Avoid confusion from exponents + * so large that e might overflow. + */ + e = 19999; /* safe for 16 bit ints */ + else + e = (int)L; + if (esign) + e = -e; + } + else + e = 0; + } + else + s = s00; + } + if (!nd) { + if (!nz && !nz0) { +#ifdef INFNAN_CHECK + /* Check for Nan and Infinity */ + ULong bits[2]; + static FPI fpinan = /* only 52 explicit bits */ + { 52, 1-1023-53+1, 2046-1023-53+1, 1, SI }; + switch(c) { + case 'i': + case 'I': + if (match(&s,"nf")) { + --s; + if (!match(&s,"inity")) + ++s; + word0(rv) = 0x7ff00000; + word1(rv) = 0; + goto ret; + } + break; + case 'n': + case 'N': + if (match(&s, "an")) { +#ifndef No_Hex_NaN + if (*s == '(' /*)*/ + && hexnan(&s, &fpinan, bits) + == STRTOG_NaNbits) { + word0(rv) = 0x7ff00000 | bits[1]; + word1(rv) = bits[0]; + } + else { + word0(rv) = NAN_WORD0; + word1(rv) = NAN_WORD1; + } +#endif + goto ret; + } + } +#endif /* INFNAN_CHECK */ + ret0: + s = s00; + sign = 0; + } + goto ret; + } + e1 = e -= nf; + + /* Now we have nd0 digits, starting at s0, followed by a + * decimal point, followed by nd-nd0 digits. The number we're + * after is the integer represented by those digits times + * 10**e */ + + if (!nd0) + nd0 = nd; + k = nd < DBL_DIG + 1 ? nd : DBL_DIG + 1; + dval(rv) = y; + if (k > 9) { +#ifdef SET_INEXACT + if (k > DBL_DIG) + oldinexact = get_inexact(); +#endif + dval(rv) = tens[k - 9] * dval(rv) + z; + } + bd0 = 0; + if (nd <= DBL_DIG +#ifndef RND_PRODQUOT +#ifndef Honor_FLT_ROUNDS + && Flt_Rounds == 1 +#endif +#endif + ) { + if (!e) + goto ret; + if (e > 0) { + if (e <= Ten_pmax) { +#ifdef VAX + goto vax_ovfl_check; +#else +#ifdef Honor_FLT_ROUNDS + /* round correctly FLT_ROUNDS = 2 or 3 */ + if (sign) { + rv = -rv; + sign = 0; + } +#endif + /* rv = */ rounded_product(dval(rv), tens[e]); + goto ret; +#endif + } + i = DBL_DIG - nd; + if (e <= Ten_pmax + i) { + /* A fancier test would sometimes let us do + * this for larger i values. + */ +#ifdef Honor_FLT_ROUNDS + /* round correctly FLT_ROUNDS = 2 or 3 */ + if (sign) { + rv = -rv; + sign = 0; + } +#endif + e -= i; + dval(rv) *= tens[i]; +#ifdef VAX + /* VAX exponent range is so narrow we must + * worry about overflow here... + */ + vax_ovfl_check: + word0(rv) -= P*Exp_msk1; + /* rv = */ rounded_product(dval(rv), tens[e]); + if ((word0(rv) & Exp_mask) + > Exp_msk1*(DBL_MAX_EXP+Bias-1-P)) + goto ovfl; + word0(rv) += P*Exp_msk1; +#else + /* rv = */ rounded_product(dval(rv), tens[e]); +#endif + goto ret; + } + } +#ifndef Inaccurate_Divide + else if (e >= -Ten_pmax) { +#ifdef Honor_FLT_ROUNDS + /* round correctly FLT_ROUNDS = 2 or 3 */ + if (sign) { + rv = -rv; + sign = 0; + } +#endif + /* rv = */ rounded_quotient(dval(rv), tens[-e]); + goto ret; + } +#endif + } + e1 += nd - k; + +#ifdef IEEE_Arith +#ifdef SET_INEXACT + inexact = 1; + if (k <= DBL_DIG) + oldinexact = get_inexact(); +#endif +#ifdef Avoid_Underflow + scale = 0; +#endif +#ifdef Honor_FLT_ROUNDS + if ((rounding = Flt_Rounds) >= 2) { + if (sign) + rounding = rounding == 2 ? 0 : 2; + else + if (rounding != 2) + rounding = 0; + } +#endif +#endif /*IEEE_Arith*/ + + /* Get starting approximation = rv * 10**e1 */ + + if (e1 > 0) { + if ( (i = e1 & 15) !=0) + dval(rv) *= tens[i]; + if (e1 &= ~15) { + if (e1 > DBL_MAX_10_EXP) { + ovfl: +#ifndef NO_ERRNO + errno = ERANGE; +#endif + /* Can't trust HUGE_VAL */ +#ifdef IEEE_Arith +#ifdef Honor_FLT_ROUNDS + switch(rounding) { + case 0: /* toward 0 */ + case 3: /* toward -infinity */ + word0(rv) = Big0; + word1(rv) = Big1; + break; + default: + word0(rv) = Exp_mask; + word1(rv) = 0; + } +#else /*Honor_FLT_ROUNDS*/ + word0(rv) = Exp_mask; + word1(rv) = 0; +#endif /*Honor_FLT_ROUNDS*/ +#ifdef SET_INEXACT + /* set overflow bit */ + dval(rv0) = 1e300; + dval(rv0) *= dval(rv0); +#endif +#else /*IEEE_Arith*/ + word0(rv) = Big0; + word1(rv) = Big1; +#endif /*IEEE_Arith*/ + if (bd0) + goto retfree; + goto ret; + } + e1 >>= 4; + for(j = 0; e1 > 1; j++, e1 >>= 1) + if (e1 & 1) + dval(rv) *= bigtens[j]; + /* The last multiplication could overflow. */ + word0(rv) -= P*Exp_msk1; + dval(rv) *= bigtens[j]; + if ((z = word0(rv) & Exp_mask) + > Exp_msk1*(DBL_MAX_EXP+Bias-P)) + goto ovfl; + if (z > Exp_msk1*(DBL_MAX_EXP+Bias-1-P)) { + /* set to largest number */ + /* (Can't trust DBL_MAX) */ + word0(rv) = Big0; + word1(rv) = Big1; + } + else + word0(rv) += P*Exp_msk1; + } + } + else if (e1 < 0) { + e1 = -e1; + if ( (i = e1 & 15) !=0) + dval(rv) /= tens[i]; + if (e1 >>= 4) { + if (e1 >= 1 << n_bigtens) + goto undfl; +#ifdef Avoid_Underflow + if (e1 & Scale_Bit) + scale = 2*P; + for(j = 0; e1 > 0; j++, e1 >>= 1) + if (e1 & 1) + dval(rv) *= tinytens[j]; + if (scale && (j = 2*P + 1 - ((word0(rv) & Exp_mask) + >> Exp_shift)) > 0) { + /* scaled rv is denormal; zap j low bits */ + if (j >= 32) { + word1(rv) = 0; + if (j >= 53) + word0(rv) = (P+2)*Exp_msk1; + else + word0(rv) &= 0xffffffff << j-32; + } + else + word1(rv) &= 0xffffffff << j; + } +#else + for(j = 0; e1 > 1; j++, e1 >>= 1) + if (e1 & 1) + dval(rv) *= tinytens[j]; + /* The last multiplication could underflow. */ + dval(rv0) = dval(rv); + dval(rv) *= tinytens[j]; + if (!dval(rv)) { + dval(rv) = 2.*dval(rv0); + dval(rv) *= tinytens[j]; +#endif + if (!dval(rv)) { + undfl: + dval(rv) = 0.; +#ifndef NO_ERRNO + errno = ERANGE; +#endif + if (bd0) + goto retfree; + goto ret; + } +#ifndef Avoid_Underflow + word0(rv) = Tiny0; + word1(rv) = Tiny1; + /* The refinement below will clean + * this approximation up. + */ + } +#endif + } + } + + /* Now the hard part -- adjusting rv to the correct value.*/ + + /* Put digits into bd: true value = bd * 10^e */ + + bd0 = s2b(s0, nd0, nd, y); + + for(;;) { + bd = Balloc(bd0->k); + Bcopy(bd, bd0); + bb = d2b(dval(rv), &bbe, &bbbits); /* rv = bb * 2^bbe */ + bs = i2b(1); + + if (e >= 0) { + bb2 = bb5 = 0; + bd2 = bd5 = e; + } + else { + bb2 = bb5 = -e; + bd2 = bd5 = 0; + } + if (bbe >= 0) + bb2 += bbe; + else + bd2 -= bbe; + bs2 = bb2; +#ifdef Honor_FLT_ROUNDS + if (rounding != 1) + bs2++; +#endif +#ifdef Avoid_Underflow + j = bbe - scale; + i = j + bbbits - 1; /* logb(rv) */ + if (i < Emin) /* denormal */ + j += P - Emin; + else + j = P + 1 - bbbits; +#else /*Avoid_Underflow*/ +#ifdef Sudden_Underflow +#ifdef IBM + j = 1 + 4*P - 3 - bbbits + ((bbe + bbbits - 1) & 3); +#else + j = P + 1 - bbbits; +#endif +#else /*Sudden_Underflow*/ + j = bbe; + i = j + bbbits - 1; /* logb(rv) */ + if (i < Emin) /* denormal */ + j += P - Emin; + else + j = P + 1 - bbbits; +#endif /*Sudden_Underflow*/ +#endif /*Avoid_Underflow*/ + bb2 += j; + bd2 += j; +#ifdef Avoid_Underflow + bd2 += scale; +#endif + i = bb2 < bd2 ? bb2 : bd2; + if (i > bs2) + i = bs2; + if (i > 0) { + bb2 -= i; + bd2 -= i; + bs2 -= i; + } + if (bb5 > 0) { + bs = pow5mult(bs, bb5); + bb1 = mult(bs, bb); + Bfree(bb); + bb = bb1; + } + if (bb2 > 0) + bb = lshift(bb, bb2); + if (bd5 > 0) + bd = pow5mult(bd, bd5); + if (bd2 > 0) + bd = lshift(bd, bd2); + if (bs2 > 0) + bs = lshift(bs, bs2); + delta = diff(bb, bd); + dsign = delta->sign; + delta->sign = 0; + i = cmp(delta, bs); +#ifdef Honor_FLT_ROUNDS + if (rounding != 1) { + if (i < 0) { + /* Error is less than an ulp */ + if (!delta->x[0] && delta->wds <= 1) { + /* exact */ +#ifdef SET_INEXACT + inexact = 0; +#endif + break; + } + if (rounding) { + if (dsign) { + adj = 1.; + goto apply_adj; + } + } + else if (!dsign) { + adj = -1.; + if (!word1(rv) + && !(word0(rv) & Frac_mask)) { + y = word0(rv) & Exp_mask; +#ifdef Avoid_Underflow + if (!scale || y > 2*P*Exp_msk1) +#else + if (y) +#endif + { + delta = lshift(delta,Log2P); + if (cmp(delta, bs) <= 0) + adj = -0.5; + } + } + apply_adj: +#ifdef Avoid_Underflow + if (scale && (y = word0(rv) & Exp_mask) + <= 2*P*Exp_msk1) + word0(adj) += (2*P+1)*Exp_msk1 - y; +#else +#ifdef Sudden_Underflow + if ((word0(rv) & Exp_mask) <= + P*Exp_msk1) { + word0(rv) += P*Exp_msk1; + dval(rv) += adj*ulp(dval(rv)); + word0(rv) -= P*Exp_msk1; + } + else +#endif /*Sudden_Underflow*/ +#endif /*Avoid_Underflow*/ + dval(rv) += adj*ulp(dval(rv)); + } + break; + } + adj = ratio(delta, bs); + if (adj < 1.) + adj = 1.; + if (adj <= 0x7ffffffe) { + /* adj = rounding ? ceil(adj) : floor(adj); */ + y = adj; + if (y != adj) { + if (!((rounding>>1) ^ dsign)) + y++; + adj = y; + } + } +#ifdef Avoid_Underflow + if (scale && (y = word0(rv) & Exp_mask) <= 2*P*Exp_msk1) + word0(adj) += (2*P+1)*Exp_msk1 - y; +#else +#ifdef Sudden_Underflow + if ((word0(rv) & Exp_mask) <= P*Exp_msk1) { + word0(rv) += P*Exp_msk1; + adj *= ulp(dval(rv)); + if (dsign) + dval(rv) += adj; + else + dval(rv) -= adj; + word0(rv) -= P*Exp_msk1; + goto cont; + } +#endif /*Sudden_Underflow*/ +#endif /*Avoid_Underflow*/ + adj *= ulp(dval(rv)); + if (dsign) + dval(rv) += adj; + else + dval(rv) -= adj; + goto cont; + } +#endif /*Honor_FLT_ROUNDS*/ + + if (i < 0) { + /* Error is less than half an ulp -- check for + * special case of mantissa a power of two. + */ + if (dsign || word1(rv) || word0(rv) & Bndry_mask +#ifdef IEEE_Arith +#ifdef Avoid_Underflow + || (word0(rv) & Exp_mask) <= (2*P+1)*Exp_msk1 +#else + || (word0(rv) & Exp_mask) <= Exp_msk1 +#endif +#endif + ) { +#ifdef SET_INEXACT + if (!delta->x[0] && delta->wds <= 1) + inexact = 0; +#endif + break; + } + if (!delta->x[0] && delta->wds <= 1) { + /* exact result */ +#ifdef SET_INEXACT + inexact = 0; +#endif + break; + } + delta = lshift(delta,Log2P); + if (cmp(delta, bs) > 0) + goto drop_down; + break; + } + if (i == 0) { + /* exactly half-way between */ + if (dsign) { + if ((word0(rv) & Bndry_mask1) == Bndry_mask1 + && word1(rv) == ( +#ifdef Avoid_Underflow + (scale && (y = word0(rv) & Exp_mask) <= 2*P*Exp_msk1) + ? (0xffffffff & (0xffffffff << (2*P+1-(y>>Exp_shift)))) : +#endif + 0xffffffff)) { + /*boundary case -- increment exponent*/ + word0(rv) = (word0(rv) & Exp_mask) + + Exp_msk1 +#ifdef IBM + | Exp_msk1 >> 4 +#endif + ; + word1(rv) = 0; +#ifdef Avoid_Underflow + dsign = 0; +#endif + break; + } + } + else if (!(word0(rv) & Bndry_mask) && !word1(rv)) { + drop_down: + /* boundary case -- decrement exponent */ +#ifdef Sudden_Underflow /*{{*/ + L = word0(rv) & Exp_mask; +#ifdef IBM + if (L < Exp_msk1) +#else +#ifdef Avoid_Underflow + if (L <= (scale ? (2*P+1)*Exp_msk1 : Exp_msk1)) +#else + if (L <= Exp_msk1) +#endif /*Avoid_Underflow*/ +#endif /*IBM*/ + goto undfl; + L -= Exp_msk1; +#else /*Sudden_Underflow}{*/ +#ifdef Avoid_Underflow + if (scale) { + L = word0(rv) & Exp_mask; + if (L <= (2*P+1)*Exp_msk1) { + if (L > (P+2)*Exp_msk1) + /* round even ==> */ + /* accept rv */ + break; + /* rv = smallest denormal */ + goto undfl; + } + } +#endif /*Avoid_Underflow*/ + L = (word0(rv) & Exp_mask) - Exp_msk1; +#endif /*Sudden_Underflow}*/ + word0(rv) = L | Bndry_mask1; + word1(rv) = 0xffffffff; +#ifdef IBM + goto cont; +#else + break; +#endif + } +#ifndef ROUND_BIASED + if (!(word1(rv) & LSB)) + break; +#endif + if (dsign) + dval(rv) += ulp(dval(rv)); +#ifndef ROUND_BIASED + else { + dval(rv) -= ulp(dval(rv)); +#ifndef Sudden_Underflow + if (!dval(rv)) + goto undfl; +#endif + } +#ifdef Avoid_Underflow + dsign = 1 - dsign; +#endif +#endif + break; + } + if ((aadj = ratio(delta, bs)) <= 2.) { + if (dsign) + aadj = aadj1 = 1.; + else if (word1(rv) || word0(rv) & Bndry_mask) { +#ifndef Sudden_Underflow + if (word1(rv) == Tiny1 && !word0(rv)) + goto undfl; +#endif + aadj = 1.; + aadj1 = -1.; + } + else { + /* special case -- power of FLT_RADIX to be */ + /* rounded down... */ + + if (aadj < 2./FLT_RADIX) + aadj = 1./FLT_RADIX; + else + aadj *= 0.5; + aadj1 = -aadj; + } + } + else { + aadj *= 0.5; + aadj1 = dsign ? aadj : -aadj; +#ifdef Check_FLT_ROUNDS + switch(Rounding) { + case 2: /* towards +infinity */ + aadj1 -= 0.5; + break; + case 0: /* towards 0 */ + case 3: /* towards -infinity */ + aadj1 += 0.5; + } +#else + if (Flt_Rounds == 0) + aadj1 += 0.5; +#endif /*Check_FLT_ROUNDS*/ + } + y = word0(rv) & Exp_mask; + + /* Check for overflow */ + + if (y == Exp_msk1*(DBL_MAX_EXP+Bias-1)) { + dval(rv0) = dval(rv); + word0(rv) -= P*Exp_msk1; + adj = aadj1 * ulp(dval(rv)); + dval(rv) += adj; + if ((word0(rv) & Exp_mask) >= + Exp_msk1*(DBL_MAX_EXP+Bias-P)) { + if (word0(rv0) == Big0 && word1(rv0) == Big1) + goto ovfl; + word0(rv) = Big0; + word1(rv) = Big1; + goto cont; + } + else + word0(rv) += P*Exp_msk1; + } + else { +#ifdef Avoid_Underflow + if (scale && y <= 2*P*Exp_msk1) { + if (aadj <= 0x7fffffff) { + if ((z = aadj) <= 0) + z = 1; + aadj = z; + aadj1 = dsign ? aadj : -aadj; + } + word0(aadj1) += (2*P+1)*Exp_msk1 - y; + } + adj = aadj1 * ulp(dval(rv)); + dval(rv) += adj; +#else +#ifdef Sudden_Underflow + if ((word0(rv) & Exp_mask) <= P*Exp_msk1) { + dval(rv0) = dval(rv); + word0(rv) += P*Exp_msk1; + adj = aadj1 * ulp(dval(rv)); + dval(rv) += adj; +#ifdef IBM + if ((word0(rv) & Exp_mask) < P*Exp_msk1) +#else + if ((word0(rv) & Exp_mask) <= P*Exp_msk1) +#endif + { + if (word0(rv0) == Tiny0 + && word1(rv0) == Tiny1) + goto undfl; + word0(rv) = Tiny0; + word1(rv) = Tiny1; + goto cont; + } + else + word0(rv) -= P*Exp_msk1; + } + else { + adj = aadj1 * ulp(dval(rv)); + dval(rv) += adj; + } +#else /*Sudden_Underflow*/ + /* Compute adj so that the IEEE rounding rules will + * correctly round rv + adj in some half-way cases. + * If rv * ulp(rv) is denormalized (i.e., + * y <= (P-1)*Exp_msk1), we must adjust aadj to avoid + * trouble from bits lost to denormalization; + * example: 1.2e-307 . + */ + if (y <= (P-1)*Exp_msk1 && aadj > 1.) { + aadj1 = (double)(int)(aadj + 0.5); + if (!dsign) + aadj1 = -aadj1; + } + adj = aadj1 * ulp(dval(rv)); + dval(rv) += adj; +#endif /*Sudden_Underflow*/ +#endif /*Avoid_Underflow*/ + } + z = word0(rv) & Exp_mask; +#ifndef SET_INEXACT +#ifdef Avoid_Underflow + if (!scale) +#endif + if (y == z) { + /* Can we stop now? */ + L = (Long)aadj; + aadj -= L; + /* The tolerances below are conservative. */ + if (dsign || word1(rv) || word0(rv) & Bndry_mask) { + if (aadj < .4999999 || aadj > .5000001) + break; + } + else if (aadj < .4999999/FLT_RADIX) + break; + } +#endif + cont: + Bfree(bb); + Bfree(bd); + Bfree(bs); + Bfree(delta); + } +#ifdef SET_INEXACT + if (inexact) { + if (!oldinexact) { + word0(rv0) = Exp_1 + (70 << Exp_shift); + word1(rv0) = 0; + dval(rv0) += 1.; + } + } + else if (!oldinexact) + clear_inexact(); +#endif +#ifdef Avoid_Underflow + if (scale) { + word0(rv0) = Exp_1 - 2*P*Exp_msk1; + word1(rv0) = 0; + dval(rv) *= dval(rv0); +#ifndef NO_ERRNO + /* try to avoid the bug of testing an 8087 register value */ + if (word0(rv) == 0 && word1(rv) == 0) + errno = ERANGE; +#endif + } +#endif /* Avoid_Underflow */ +#ifdef SET_INEXACT + if (inexact && !(word0(rv) & Exp_mask)) { + /* set underflow bit */ + dval(rv0) = 1e-300; + dval(rv0) *= dval(rv0); + } +#endif + retfree: + Bfree(bb); + Bfree(bd); + Bfree(bs); + Bfree(bd0); + Bfree(delta); + ret: + if (se) + *se = (char *)s; + return sign ? -dval(rv) : dval(rv); + } + diff --git a/lib/libc/gdtoa/strtodI.c b/lib/libc/gdtoa/strtodI.c new file mode 100644 index 0000000..163f363 --- /dev/null +++ b/lib/libc/gdtoa/strtodI.c @@ -0,0 +1,177 @@ +/**************************************************************** + +The author of this software is David M. Gay. + +Copyright (C) 1998, 2000 by Lucent Technologies +All Rights Reserved + +Permission to use, copy, modify, and distribute this software and +its documentation for any purpose and without fee is hereby +granted, provided that the above copyright notice appear in all +copies and that both that the copyright notice and this +permission notice and warranty disclaimer appear in supporting +documentation, and that the name of Lucent or any of its entities +not be used in advertising or publicity pertaining to +distribution of the software without specific, written prior +permission. + +LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, +INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. +IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY +SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER +IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. + +****************************************************************/ + +/* Please send bug reports to + David M. Gay + Bell Laboratories, Room 2C-463 + 600 Mountain Avenue + Murray Hill, NJ 07974-0636 + U.S.A. + dmg@bell-labs.com + */ + +#include "gdtoaimp.h" + + static double +#ifdef KR_headers +ulpdown(d) double *d; +#else +ulpdown(double *d) +#endif +{ + double u; + ULong *L = (ULong*)d; + + u = ulp(*d); + if (!(L[_1] | L[_0] & 0xfffff) + && (L[_0] & 0x7ff00000) > 0x00100000) + u *= 0.5; + return u; + } + + int +#ifdef KR_headers +strtodI(s, sp, dd) CONST char *s; char **sp; double *dd; +#else +strtodI(CONST char *s, char **sp, double *dd) +#endif +{ +#ifdef Sudden_Underflow + static FPI fpi = { 53, 1-1023-53+1, 2046-1023-53+1, 1, 1 }; +#else + static FPI fpi = { 53, 1-1023-53+1, 2046-1023-53+1, 1, 0 }; +#endif + ULong bits[2], sign; + Long exp; + int j, k; + typedef union { + double d[2]; + ULong L[4]; + } U; + U *u; + + k = strtodg(s, sp, &fpi, &exp, bits); + u = (U*)dd; + sign = k & STRTOG_Neg ? 0x80000000L : 0; + switch(k & STRTOG_Retmask) { + case STRTOG_NoNumber: + u->d[0] = u->d[1] = 0.; + break; + + case STRTOG_Zero: + u->d[0] = u->d[1] = 0.; +#ifdef Sudden_Underflow + if (k & STRTOG_Inexact) { + if (sign) + u->L[_0] = 0x80100000L; + else + u->L[2+_0] = 0x100000L; + } + break; +#else + goto contain; +#endif + + case STRTOG_Denormal: + u->L[_1] = bits[0]; + u->L[_0] = bits[1]; + goto contain; + + case STRTOG_Normal: + u->L[_1] = bits[0]; + u->L[_0] = (bits[1] & ~0x100000) | ((exp + 0x3ff + 52) << 20); + contain: + j = k & STRTOG_Inexact; + if (sign) { + u->L[_0] |= sign; + j = STRTOG_Inexact - j; + } + switch(j) { + case STRTOG_Inexlo: +#ifdef Sudden_Underflow + if ((u->L[_0] & 0x7ff00000) < 0x3500000) { + u->L[2+_0] = u->L[_0] + 0x3500000; + u->L[2+_1] = u->L[_1]; + u->d[1] += ulp(u->d[1]); + u->L[2+_0] -= 0x3500000; + if (!(u->L[2+_0] & 0x7ff00000)) { + u->L[2+_0] = sign; + u->L[2+_1] = 0; + } + } + else +#endif + u->d[1] = u->d[0] + ulp(u->d[0]); + break; + case STRTOG_Inexhi: + u->d[1] = u->d[0]; +#ifdef Sudden_Underflow + if ((u->L[_0] & 0x7ff00000) < 0x3500000) { + u->L[_0] += 0x3500000; + u->d[0] -= ulpdown(u->d); + u->L[_0] -= 0x3500000; + if (!(u->L[_0] & 0x7ff00000)) { + u->L[_0] = sign; + u->L[_1] = 0; + } + } + else +#endif + u->d[0] -= ulpdown(u->d); + break; + default: + u->d[1] = u->d[0]; + } + break; + + case STRTOG_Infinite: + u->L[_0] = u->L[2+_0] = sign | 0x7ff00000; + u->L[_1] = u->L[2+_1] = 0; + if (k & STRTOG_Inexact) { + if (sign) { + u->L[2+_0] = 0xffefffffL; + u->L[2+_1] = 0xffffffffL; + } + else { + u->L[_0] = 0x7fefffffL; + u->L[_1] = 0xffffffffL; + } + } + break; + + case STRTOG_NaN: + u->L[_0] = u->L[2+_0] = 0x7fffffff | sign; + u->L[_1] = u->L[2+_1] = (ULong)-1; + break; + + case STRTOG_NaNbits: + u->L[_0] = u->L[2+_0] = 0x7ff00000 | sign | bits[1]; + u->L[_1] = u->L[2+_1] = bits[0]; + } + return k; + } diff --git a/lib/libc/gdtoa/strtodg.c b/lib/libc/gdtoa/strtodg.c new file mode 100644 index 0000000..bf30e33 --- /dev/null +++ b/lib/libc/gdtoa/strtodg.c @@ -0,0 +1,1001 @@ +/**************************************************************** + +The author of this software is David M. Gay. + +Copyright (C) 1998-2001 by Lucent Technologies +All Rights Reserved + +Permission to use, copy, modify, and distribute this software and +its documentation for any purpose and without fee is hereby +granted, provided that the above copyright notice appear in all +copies and that both that the copyright notice and this +permission notice and warranty disclaimer appear in supporting +documentation, and that the name of Lucent or any of its entities +not be used in advertising or publicity pertaining to +distribution of the software without specific, written prior +permission. + +LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, +INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. +IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY +SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER +IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. + +****************************************************************/ + +/* Please send bug reports to + David M. Gay + dmg@acm.org + */ + +#include "gdtoaimp.h" + +#ifdef USE_LOCALE +#include "locale.h" +#endif + + static CONST int +fivesbits[] = { 0, 3, 5, 7, 10, 12, 14, 17, 19, 21, + 24, 26, 28, 31, 33, 35, 38, 40, 42, 45, + 47, 49, 52 +#ifdef VAX + , 54, 56 +#endif + }; + + Bigint * +#ifdef KR_headers +increment(b) Bigint *b; +#else +increment(Bigint *b) +#endif +{ + ULong *x, *xe; + Bigint *b1; +#ifdef Pack_16 + ULong carry = 1, y; +#endif + + x = b->x; + xe = x + b->wds; +#ifdef Pack_32 + do { + if (*x < (ULong)0xffffffffL) { + ++*x; + return b; + } + *x++ = 0; + } while(x < xe); +#else + do { + y = *x + carry; + carry = y >> 16; + *x++ = y & 0xffff; + if (!carry) + return b; + } while(x < xe); + if (carry) +#endif + { + if (b->wds >= b->maxwds) { + b1 = Balloc(b->k+1); + Bcopy(b1,b); + Bfree(b); + b = b1; + } + b->x[b->wds++] = 1; + } + return b; + } + + int +#ifdef KR_headers +decrement(b) Bigint *b; +#else +decrement(Bigint *b) +#endif +{ + ULong *x, *xe; +#ifdef Pack_16 + ULong borrow = 1, y; +#endif + + x = b->x; + xe = x + b->wds; +#ifdef Pack_32 + do { + if (*x) { + --*x; + break; + } + *x++ = 0xffffffffL; + } + while(x < xe); +#else + do { + y = *x - borrow; + borrow = (y & 0x10000) >> 16; + *x++ = y & 0xffff; + } while(borrow && x < xe); +#endif + return STRTOG_Inexlo; + } + + static int +#ifdef KR_headers +all_on(b, n) Bigint *b; int n; +#else +all_on(Bigint *b, int n) +#endif +{ + ULong *x, *xe; + + x = b->x; + xe = x + (n >> kshift); + while(x < xe) + if ((*x++ & ALL_ON) != ALL_ON) + return 0; + if (n &= kmask) + return ((*x | (ALL_ON << n)) & ALL_ON) == ALL_ON; + return 1; + } + + Bigint * +#ifdef KR_headers +set_ones(b, n) Bigint *b; int n; +#else +set_ones(Bigint *b, int n) +#endif +{ + int k; + ULong *x, *xe; + + k = (n + ((1 << kshift) - 1)) >> kshift; + if (b->k < k) { + Bfree(b); + b = Balloc(k); + } + k = n >> kshift; + if (n &= kmask) + k++; + b->wds = k; + x = b->x; + xe = x + k; + while(x < xe) + *x++ = ALL_ON; + if (n) + x[-1] >>= ULbits - n; + return b; + } + + static int +rvOK +#ifdef KR_headers + (d, fpi, exp, bits, exact, rd, irv) + double d; FPI *fpi; Long *exp; ULong *bits; int exact, rd, *irv; +#else + (double d, FPI *fpi, Long *exp, ULong *bits, int exact, int rd, int *irv) +#endif +{ + Bigint *b; + ULong carry, inex, lostbits; + int bdif, e, j, k, k1, nb, rv; + + carry = rv = 0; + b = d2b(d, &e, &bdif); + bdif -= nb = fpi->nbits; + e += bdif; + if (bdif <= 0) { + if (exact) + goto trunc; + goto ret; + } + if (P == nb) { + if ( +#ifndef IMPRECISE_INEXACT + exact && +#endif + fpi->rounding == +#ifdef RND_PRODQUOT + FPI_Round_near +#else + Flt_Rounds +#endif + ) goto trunc; + goto ret; + } + switch(rd) { + case 1: + goto trunc; + case 2: + break; + default: /* round near */ + k = bdif - 1; + if (k < 0) + goto trunc; + if (!k) { + if (!exact) + goto ret; + if (b->x[0] & 2) + break; + goto trunc; + } + if (b->x[k>>kshift] & ((ULong)1 << (k & kmask))) + break; + goto trunc; + } + /* "break" cases: round up 1 bit, then truncate; bdif > 0 */ + carry = 1; + trunc: + inex = lostbits = 0; + if (bdif > 0) { + if ( (lostbits = any_on(b, bdif)) !=0) + inex = STRTOG_Inexlo; + rshift(b, bdif); + if (carry) { + inex = STRTOG_Inexhi; + b = increment(b); + if ( (j = nb & kmask) !=0) + j = 32 - j; + if (hi0bits(b->x[b->wds - 1]) != j) { + if (!lostbits) + lostbits = b->x[0] & 1; + rshift(b, 1); + e++; + } + } + } + else if (bdif < 0) + b = lshift(b, -bdif); + if (e < fpi->emin) { + k = fpi->emin - e; + e = fpi->emin; + if (k > nb || fpi->sudden_underflow) { + b->wds = inex = 0; + *irv = STRTOG_Underflow | STRTOG_Inexlo; + } + else { + k1 = k - 1; + if (k1 > 0 && !lostbits) + lostbits = any_on(b, k1); + if (!lostbits && !exact) + goto ret; + lostbits |= + carry = b->x[k1>>kshift] & (1 << (k1 & kmask)); + rshift(b, k); + *irv = STRTOG_Denormal; + if (carry) { + b = increment(b); + inex = STRTOG_Inexhi | STRTOG_Underflow; + } + else if (lostbits) + inex = STRTOG_Inexlo | STRTOG_Underflow; + } + } + else if (e > fpi->emax) { + e = fpi->emax + 1; + *irv = STRTOG_Infinite | STRTOG_Overflow | STRTOG_Inexhi; +#ifndef NO_ERRNO + errno = ERANGE; +#endif + b->wds = inex = 0; + } + *exp = e; + copybits(bits, nb, b); + *irv |= inex; + rv = 1; + ret: + Bfree(b); + return rv; + } + + static int +#ifdef KR_headers +mantbits(d) double d; +#else +mantbits(double d) +#endif +{ + ULong L; +#ifdef VAX + L = word1(d) << 16 | word1(d) >> 16; + if (L) +#else + if ( (L = word1(d)) !=0) +#endif + return P - lo0bits(&L); +#ifdef VAX + L = word0(d) << 16 | word0(d) >> 16 | Exp_msk11; +#else + L = word0(d) | Exp_msk1; +#endif + return P - 32 - lo0bits(&L); + } + + int +strtodg +#ifdef KR_headers + (s00, se, fpi, exp, bits) + CONST char *s00; char **se; FPI *fpi; Long *exp; ULong *bits; +#else + (CONST char *s00, char **se, FPI *fpi, Long *exp, ULong *bits) +#endif +{ + int abe, abits, asub; + int bb0, bb2, bb5, bbe, bd2, bd5, bbbits, bs2; + int c, denorm, dsign, e, e1, e2, emin, esign, finished, i, inex, irv; + int j, k, nbits, nd, nd0, nf, nz, nz0, rd, rvbits, rve, rve1, sign; + int sudden_underflow; + CONST char *s, *s0, *s1; + double adj, adj0, rv, tol; + Long L; + ULong y, z; + Bigint *ab, *bb, *bb1, *bd, *bd0, *bs, *delta, *rvb, *rvb0; + + irv = STRTOG_Zero; + denorm = sign = nz0 = nz = 0; + dval(rv) = 0.; + rvb = 0; + nbits = fpi->nbits; + for(s = s00;;s++) switch(*s) { + case '-': + sign = 1; + /* no break */ + case '+': + if (*++s) + goto break2; + /* no break */ + case 0: + sign = 0; + irv = STRTOG_NoNumber; + s = s00; + goto ret; + case '\t': + case '\n': + case '\v': + case '\f': + case '\r': + case ' ': + continue; + default: + goto break2; + } + break2: + if (*s == '0') { +#ifndef NO_HEX_FP + switch(s[1]) { + case 'x': + case 'X': + irv = gethex(&s, fpi, exp, &rvb, sign); + if (irv == STRTOG_NoNumber) { + s = s00; + sign = 0; + } + goto ret; + } +#endif + nz0 = 1; + while(*++s == '0') ; + if (!*s) + goto ret; + } + sudden_underflow = fpi->sudden_underflow; + s0 = s; + y = z = 0; + for(nd = nf = 0; (c = *s) >= '0' && c <= '9'; nd++, s++) + if (nd < 9) + y = 10*y + c - '0'; + else if (nd < 16) + z = 10*z + c - '0'; + nd0 = nd; +#ifdef USE_LOCALE + if (c == *localeconv()->decimal_point) +#else + if (c == '.') +#endif + { + c = *++s; + if (!nd) { + for(; c == '0'; c = *++s) + nz++; + if (c > '0' && c <= '9') { + s0 = s; + nf += nz; + nz = 0; + goto have_dig; + } + goto dig_done; + } + for(; c >= '0' && c <= '9'; c = *++s) { + have_dig: + nz++; + if (c -= '0') { + nf += nz; + for(i = 1; i < nz; i++) + if (nd++ < 9) + y *= 10; + else if (nd <= DBL_DIG + 1) + z *= 10; + if (nd++ < 9) + y = 10*y + c; + else if (nd <= DBL_DIG + 1) + z = 10*z + c; + nz = 0; + } + } + } + dig_done: + e = 0; + if (c == 'e' || c == 'E') { + if (!nd && !nz && !nz0) { + irv = STRTOG_NoNumber; + s = s00; + goto ret; + } + s00 = s; + esign = 0; + switch(c = *++s) { + case '-': + esign = 1; + case '+': + c = *++s; + } + if (c >= '0' && c <= '9') { + while(c == '0') + c = *++s; + if (c > '0' && c <= '9') { + L = c - '0'; + s1 = s; + while((c = *++s) >= '0' && c <= '9') + L = 10*L + c - '0'; + if (s - s1 > 8 || L > 19999) + /* Avoid confusion from exponents + * so large that e might overflow. + */ + e = 19999; /* safe for 16 bit ints */ + else + e = (int)L; + if (esign) + e = -e; + } + else + e = 0; + } + else + s = s00; + } + if (!nd) { + if (!nz && !nz0) { +#ifdef INFNAN_CHECK + /* Check for Nan and Infinity */ + switch(c) { + case 'i': + case 'I': + if (match(&s,"nf")) { + --s; + if (!match(&s,"inity")) + ++s; + irv = STRTOG_Infinite; + goto infnanexp; + } + break; + case 'n': + case 'N': + if (match(&s, "an")) { + irv = STRTOG_NaN; + *exp = fpi->emax + 1; +#ifndef No_Hex_NaN + if (*s == '(') /*)*/ + irv = hexnan(&s, fpi, bits); +#endif + goto infnanexp; + } + } +#endif /* INFNAN_CHECK */ + irv = STRTOG_NoNumber; + s = s00; + } + goto ret; + } + + irv = STRTOG_Normal; + e1 = e -= nf; + rd = 0; + switch(fpi->rounding & 3) { + case FPI_Round_up: + rd = 2 - sign; + break; + case FPI_Round_zero: + rd = 1; + break; + case FPI_Round_down: + rd = 1 + sign; + } + + /* Now we have nd0 digits, starting at s0, followed by a + * decimal point, followed by nd-nd0 digits. The number we're + * after is the integer represented by those digits times + * 10**e */ + + if (!nd0) + nd0 = nd; + k = nd < DBL_DIG + 1 ? nd : DBL_DIG + 1; + dval(rv) = y; + if (k > 9) + dval(rv) = tens[k - 9] * dval(rv) + z; + bd0 = 0; + if (nbits <= P && nd <= DBL_DIG) { + if (!e) { + if (rvOK(dval(rv), fpi, exp, bits, 1, rd, &irv)) + goto ret; + } + else if (e > 0) { + if (e <= Ten_pmax) { +#ifdef VAX + goto vax_ovfl_check; +#else + i = fivesbits[e] + mantbits(dval(rv)) <= P; + /* rv = */ rounded_product(dval(rv), tens[e]); + if (rvOK(dval(rv), fpi, exp, bits, i, rd, &irv)) + goto ret; + e1 -= e; + goto rv_notOK; +#endif + } + i = DBL_DIG - nd; + if (e <= Ten_pmax + i) { + /* A fancier test would sometimes let us do + * this for larger i values. + */ + e2 = e - i; + e1 -= i; + dval(rv) *= tens[i]; +#ifdef VAX + /* VAX exponent range is so narrow we must + * worry about overflow here... + */ + vax_ovfl_check: + dval(adj) = dval(rv); + word0(adj) -= P*Exp_msk1; + /* adj = */ rounded_product(dval(adj), tens[e2]); + if ((word0(adj) & Exp_mask) + > Exp_msk1*(DBL_MAX_EXP+Bias-1-P)) + goto rv_notOK; + word0(adj) += P*Exp_msk1; + dval(rv) = dval(adj); +#else + /* rv = */ rounded_product(dval(rv), tens[e2]); +#endif + if (rvOK(dval(rv), fpi, exp, bits, 0, rd, &irv)) + goto ret; + e1 -= e2; + } + } +#ifndef Inaccurate_Divide + else if (e >= -Ten_pmax) { + /* rv = */ rounded_quotient(dval(rv), tens[-e]); + if (rvOK(dval(rv), fpi, exp, bits, 0, rd, &irv)) + goto ret; + e1 -= e; + } +#endif + } + rv_notOK: + e1 += nd - k; + + /* Get starting approximation = rv * 10**e1 */ + + e2 = 0; + if (e1 > 0) { + if ( (i = e1 & 15) !=0) + dval(rv) *= tens[i]; + if (e1 &= ~15) { + e1 >>= 4; + while(e1 >= (1 << n_bigtens-1)) { + e2 += ((word0(rv) & Exp_mask) + >> Exp_shift1) - Bias; + word0(rv) &= ~Exp_mask; + word0(rv) |= Bias << Exp_shift1; + dval(rv) *= bigtens[n_bigtens-1]; + e1 -= 1 << n_bigtens-1; + } + e2 += ((word0(rv) & Exp_mask) >> Exp_shift1) - Bias; + word0(rv) &= ~Exp_mask; + word0(rv) |= Bias << Exp_shift1; + for(j = 0; e1 > 0; j++, e1 >>= 1) + if (e1 & 1) + dval(rv) *= bigtens[j]; + } + } + else if (e1 < 0) { + e1 = -e1; + if ( (i = e1 & 15) !=0) + dval(rv) /= tens[i]; + if (e1 &= ~15) { + e1 >>= 4; + while(e1 >= (1 << n_bigtens-1)) { + e2 += ((word0(rv) & Exp_mask) + >> Exp_shift1) - Bias; + word0(rv) &= ~Exp_mask; + word0(rv) |= Bias << Exp_shift1; + dval(rv) *= tinytens[n_bigtens-1]; + e1 -= 1 << n_bigtens-1; + } + e2 += ((word0(rv) & Exp_mask) >> Exp_shift1) - Bias; + word0(rv) &= ~Exp_mask; + word0(rv) |= Bias << Exp_shift1; + for(j = 0; e1 > 0; j++, e1 >>= 1) + if (e1 & 1) + dval(rv) *= tinytens[j]; + } + } + + rvb = d2b(dval(rv), &rve, &rvbits); /* rv = rvb * 2^rve */ + rve += e2; + if ((j = rvbits - nbits) > 0) { + rshift(rvb, j); + rvbits = nbits; + rve += j; + } + bb0 = 0; /* trailing zero bits in rvb */ + e2 = rve + rvbits - nbits; + if (e2 > fpi->emax) { + rvb->wds = 0; + irv = STRTOG_Infinite | STRTOG_Overflow | STRTOG_Inexhi; +#ifndef NO_ERRNO + errno = ERANGE; +#endif + infnanexp: + *exp = fpi->emax + 1; + goto ret; + } + rve1 = rve + rvbits - nbits; + if (e2 < (emin = fpi->emin)) { + denorm = 1; + j = rve - emin; + if (j > 0) { + rvb = lshift(rvb, j); + rvbits += j; + } + else if (j < 0) { + rvbits += j; + if (rvbits <= 0) { + if (rvbits < -1) { + ufl: + rvb->wds = 0; + rvb->x[0] = 0; + *exp = emin; + irv = STRTOG_Underflow | STRTOG_Inexlo; + goto ret; + } + rvb->x[0] = rvb->wds = rvbits = 1; + } + else + rshift(rvb, -j); + } + rve = rve1 = emin; + if (sudden_underflow && e2 + 1 < emin) + goto ufl; + } + + /* Now the hard part -- adjusting rv to the correct value.*/ + + /* Put digits into bd: true value = bd * 10^e */ + + bd0 = s2b(s0, nd0, nd, y); + + for(;;) { + bd = Balloc(bd0->k); + Bcopy(bd, bd0); + bb = Balloc(rvb->k); + Bcopy(bb, rvb); + bbbits = rvbits - bb0; + bbe = rve + bb0; + bs = i2b(1); + + if (e >= 0) { + bb2 = bb5 = 0; + bd2 = bd5 = e; + } + else { + bb2 = bb5 = -e; + bd2 = bd5 = 0; + } + if (bbe >= 0) + bb2 += bbe; + else + bd2 -= bbe; + bs2 = bb2; + j = nbits + 1 - bbbits; + i = bbe + bbbits - nbits; + if (i < emin) /* denormal */ + j += i - emin; + bb2 += j; + bd2 += j; + i = bb2 < bd2 ? bb2 : bd2; + if (i > bs2) + i = bs2; + if (i > 0) { + bb2 -= i; + bd2 -= i; + bs2 -= i; + } + if (bb5 > 0) { + bs = pow5mult(bs, bb5); + bb1 = mult(bs, bb); + Bfree(bb); + bb = bb1; + } + bb2 -= bb0; + if (bb2 > 0) + bb = lshift(bb, bb2); + else if (bb2 < 0) + rshift(bb, -bb2); + if (bd5 > 0) + bd = pow5mult(bd, bd5); + if (bd2 > 0) + bd = lshift(bd, bd2); + if (bs2 > 0) + bs = lshift(bs, bs2); + asub = 1; + inex = STRTOG_Inexhi; + delta = diff(bb, bd); + if (delta->wds <= 1 && !delta->x[0]) + break; + dsign = delta->sign; + delta->sign = finished = 0; + L = 0; + i = cmp(delta, bs); + if (rd && i <= 0) { + irv = STRTOG_Normal; + if ( (finished = dsign ^ (rd&1)) !=0) { + if (dsign != 0) { + irv |= STRTOG_Inexhi; + goto adj1; + } + irv |= STRTOG_Inexlo; + if (rve1 == emin) + goto adj1; + for(i = 0, j = nbits; j >= ULbits; + i++, j -= ULbits) { + if (rvb->x[i] & ALL_ON) + goto adj1; + } + if (j > 1 && lo0bits(rvb->x + i) < j - 1) + goto adj1; + rve = rve1 - 1; + rvb = set_ones(rvb, rvbits = nbits); + break; + } + irv |= dsign ? STRTOG_Inexlo : STRTOG_Inexhi; + break; + } + if (i < 0) { + /* Error is less than half an ulp -- check for + * special case of mantissa a power of two. + */ + irv = dsign + ? STRTOG_Normal | STRTOG_Inexlo + : STRTOG_Normal | STRTOG_Inexhi; + if (dsign || bbbits > 1 || denorm || rve1 == emin) + break; + delta = lshift(delta,1); + if (cmp(delta, bs) > 0) { + irv = STRTOG_Normal | STRTOG_Inexlo; + goto drop_down; + } + break; + } + if (i == 0) { + /* exactly half-way between */ + if (dsign) { + if (denorm && all_on(rvb, rvbits)) { + /*boundary case -- increment exponent*/ + rvb->wds = 1; + rvb->x[0] = 1; + rve = emin + nbits - (rvbits = 1); + irv = STRTOG_Normal | STRTOG_Inexhi; + denorm = 0; + break; + } + irv = STRTOG_Normal | STRTOG_Inexlo; + } + else if (bbbits == 1) { + irv = STRTOG_Normal; + drop_down: + /* boundary case -- decrement exponent */ + if (rve1 == emin) { + irv = STRTOG_Normal | STRTOG_Inexhi; + if (rvb->wds == 1 && rvb->x[0] == 1) + sudden_underflow = 1; + break; + } + rve -= nbits; + rvb = set_ones(rvb, rvbits = nbits); + break; + } + else + irv = STRTOG_Normal | STRTOG_Inexhi; + if (bbbits < nbits && !denorm || !(rvb->x[0] & 1)) + break; + if (dsign) { + rvb = increment(rvb); + if ( (j = rvbits >> kshift) !=0) + j = 32 - j; + if (hi0bits(rvb->x[(rvb->wds - 1) >> kshift]) + != j) + rvbits++; + irv = STRTOG_Normal | STRTOG_Inexhi; + } + else { + if (bbbits == 1) + goto undfl; + decrement(rvb); + irv = STRTOG_Normal | STRTOG_Inexlo; + } + break; + } + if ((dval(adj) = ratio(delta, bs)) <= 2.) { + adj1: + inex = STRTOG_Inexlo; + if (dsign) { + asub = 0; + inex = STRTOG_Inexhi; + } + else if (denorm && bbbits <= 1) { + undfl: + rvb->wds = 0; + rve = emin; + irv = STRTOG_Underflow | STRTOG_Inexlo; + break; + } + adj0 = dval(adj) = 1.; + } + else { + adj0 = dval(adj) *= 0.5; + if (dsign) { + asub = 0; + inex = STRTOG_Inexlo; + } + if (dval(adj) < 2147483647.) { + L = adj0; + adj0 -= L; + switch(rd) { + case 0: + if (adj0 >= .5) + goto inc_L; + break; + case 1: + if (asub && adj0 > 0.) + goto inc_L; + break; + case 2: + if (!asub && adj0 > 0.) { + inc_L: + L++; + inex = STRTOG_Inexact - inex; + } + } + dval(adj) = L; + } + } + y = rve + rvbits; + + /* adj *= ulp(dval(rv)); */ + /* if (asub) rv -= adj; else rv += adj; */ + + if (!denorm && rvbits < nbits) { + rvb = lshift(rvb, j = nbits - rvbits); + rve -= j; + rvbits = nbits; + } + ab = d2b(dval(adj), &abe, &abits); + if (abe < 0) + rshift(ab, -abe); + else if (abe > 0) + ab = lshift(ab, abe); + rvb0 = rvb; + if (asub) { + /* rv -= adj; */ + j = hi0bits(rvb->x[rvb->wds-1]); + rvb = diff(rvb, ab); + k = rvb0->wds - 1; + if (denorm) + /* do nothing */; + else if (rvb->wds <= k + || hi0bits( rvb->x[k]) > + hi0bits(rvb0->x[k])) { + /* unlikely; can only have lost 1 high bit */ + if (rve1 == emin) { + --rvbits; + denorm = 1; + } + else { + rvb = lshift(rvb, 1); + --rve; + --rve1; + L = finished = 0; + } + } + } + else { + rvb = sum(rvb, ab); + k = rvb->wds - 1; + if (k >= rvb0->wds + || hi0bits(rvb->x[k]) < hi0bits(rvb0->x[k])) { + if (denorm) { + if (++rvbits == nbits) + denorm = 0; + } + else { + rshift(rvb, 1); + rve++; + rve1++; + L = 0; + } + } + } + Bfree(ab); + Bfree(rvb0); + if (finished) + break; + + z = rve + rvbits; + if (y == z && L) { + /* Can we stop now? */ + tol = dval(adj) * 5e-16; /* > max rel error */ + dval(adj) = adj0 - .5; + if (dval(adj) < -tol) { + if (adj0 > tol) { + irv |= inex; + break; + } + } + else if (dval(adj) > tol && adj0 < 1. - tol) { + irv |= inex; + break; + } + } + bb0 = denorm ? 0 : trailz(rvb); + Bfree(bb); + Bfree(bd); + Bfree(bs); + Bfree(delta); + } + if (!denorm && rvbits < nbits) { + j = nbits - rvbits; + rvb = lshift(rvb, j); + rve -= j; + } + *exp = rve; + Bfree(bb); + Bfree(bd); + Bfree(bs); + Bfree(bd0); + Bfree(delta); + ret: + if (denorm) { + if (sudden_underflow) { + rvb->wds = 0; + irv = STRTOG_Underflow | STRTOG_Inexlo; + } + else { + irv = (irv & ~STRTOG_Retmask) | + (rvb->wds > 0 ? STRTOG_Denormal : STRTOG_Zero); + if (irv & STRTOG_Inexact) + irv |= STRTOG_Underflow; + } + } + if (se) + *se = (char *)s; + if (sign) + irv |= STRTOG_Neg; + if (rvb) { + copybits(bits, nbits, rvb); + Bfree(rvb); + } + return irv; + } diff --git a/lib/libc/gdtoa/strtof.c b/lib/libc/gdtoa/strtof.c new file mode 100644 index 0000000..bb283ae --- /dev/null +++ b/lib/libc/gdtoa/strtof.c @@ -0,0 +1,83 @@ +/**************************************************************** + +The author of this software is David M. Gay. + +Copyright (C) 1998, 2000 by Lucent Technologies +All Rights Reserved + +Permission to use, copy, modify, and distribute this software and +its documentation for any purpose and without fee is hereby +granted, provided that the above copyright notice appear in all +copies and that both that the copyright notice and this +permission notice and warranty disclaimer appear in supporting +documentation, and that the name of Lucent or any of its entities +not be used in advertising or publicity pertaining to +distribution of the software without specific, written prior +permission. + +LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, +INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. +IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY +SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER +IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. + +****************************************************************/ + +/* Please send bug reports to + David M. Gay + Bell Laboratories, Room 2C-463 + 600 Mountain Avenue + Murray Hill, NJ 07974-0636 + U.S.A. + dmg@bell-labs.com + */ + +#include "gdtoaimp.h" + + float +#ifdef KR_headers +strtof(s, sp) CONST char *s; char **sp; +#else +strtof(CONST char *s, char **sp) +#endif +{ +#ifdef Sudden_Underflow + static FPI fpi = { 24, 1-127-24+1, 254-127-24+1, 1, 1 }; +#else + static FPI fpi = { 24, 1-127-24+1, 254-127-24+1, 1, 0 }; +#endif + ULong bits[1]; + Long exp; + int k; + union { ULong L[1]; float f; } u; + + k = strtodg(s, sp, &fpi, &exp, bits); + switch(k & STRTOG_Retmask) { + case STRTOG_NoNumber: + case STRTOG_Zero: + u.L[0] = 0; + break; + + case STRTOG_Normal: + case STRTOG_NaNbits: + u.L[0] = bits[0] & 0x7fffff | exp + 0x7f + 23 << 23; + break; + + case STRTOG_Denormal: + u.L[0] = bits[0]; + break; + + case STRTOG_Infinite: + u.L[0] = 0x7f800000; + break; + + case STRTOG_NaN: + u.L[0] = 0x7fffffff; + } + if (k & STRTOG_Neg) + u.L[0] |= 0x80000000L; + return u.f; + } diff --git a/lib/libc/gdtoa/strtopQ.c b/lib/libc/gdtoa/strtopQ.c new file mode 100644 index 0000000..4bcc581 --- /dev/null +++ b/lib/libc/gdtoa/strtopQ.c @@ -0,0 +1,109 @@ +/**************************************************************** + +The author of this software is David M. Gay. + +Copyright (C) 1998, 2000 by Lucent Technologies +All Rights Reserved + +Permission to use, copy, modify, and distribute this software and +its documentation for any purpose and without fee is hereby +granted, provided that the above copyright notice appear in all +copies and that both that the copyright notice and this +permission notice and warranty disclaimer appear in supporting +documentation, and that the name of Lucent or any of its entities +not be used in advertising or publicity pertaining to +distribution of the software without specific, written prior +permission. + +LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, +INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. +IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY +SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER +IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. + +****************************************************************/ + +/* Please send bug reports to + David M. Gay + Bell Laboratories, Room 2C-463 + 600 Mountain Avenue + Murray Hill, NJ 07974-0636 + U.S.A. + dmg@bell-labs.com + */ + +#include "gdtoaimp.h" + +#undef _0 +#undef _1 + +/* one or the other of IEEE_MC68k or IEEE_8087 should be #defined */ + +#ifdef IEEE_MC68k +#define _0 0 +#define _1 1 +#define _2 2 +#define _3 3 +#endif +#ifdef IEEE_8087 +#define _0 3 +#define _1 2 +#define _2 1 +#define _3 0 +#endif + + int +#ifdef KR_headers +strtopQ(s, sp, V) CONST char *s; char **sp; void *V; +#else +strtopQ(CONST char *s, char **sp, void *V) +#endif +{ +#ifdef Sudden_Underflow + static FPI fpi = { 113, 1-16383-113+1, 32766 - 16383 - 113 + 1, 1, 1 }; +#else + static FPI fpi = { 113, 1-16383-113+1, 32766 - 16383 - 113 + 1, 1, 0 }; +#endif + ULong bits[4]; + Long exp; + int k; + ULong *L = (ULong*)V; + + k = strtodg(s, sp, &fpi, &exp, bits); + switch(k & STRTOG_Retmask) { + case STRTOG_NoNumber: + case STRTOG_Zero: + L[0] = L[1] = L[2] = L[3] = 0; + break; + + case STRTOG_Normal: + case STRTOG_NaNbits: + L[_3] = bits[0]; + L[_2] = bits[1]; + L[_1] = bits[2]; + L[_0] = (bits[3] & ~0x10000) | ((exp + 0x3fff + 112) << 16); + break; + + case STRTOG_Denormal: + L[_3] = bits[0]; + L[_2] = bits[1]; + L[_1] = bits[2]; + L[_0] = bits[3]; + break; + + case STRTOG_Infinite: + L[_0] = 0x7fff0000; + L[_1] = L[_2] = L[_3] = 0; + break; + + case STRTOG_NaN: + L[_0] = 0x7fffffff; + L[_1] = L[_2] = L[_3] = (ULong)-1; + } + if (k & STRTOG_Neg) + L[_0] |= 0x80000000L; + return k; + } diff --git a/lib/libc/gdtoa/strtopd.c b/lib/libc/gdtoa/strtopd.c new file mode 100644 index 0000000..54e0838 --- /dev/null +++ b/lib/libc/gdtoa/strtopd.c @@ -0,0 +1,55 @@ +/**************************************************************** + +The author of this software is David M. Gay. + +Copyright (C) 1998 by Lucent Technologies +All Rights Reserved + +Permission to use, copy, modify, and distribute this software and +its documentation for any purpose and without fee is hereby +granted, provided that the above copyright notice appear in all +copies and that both that the copyright notice and this +permission notice and warranty disclaimer appear in supporting +documentation, and that the name of Lucent or any of its entities +not be used in advertising or publicity pertaining to +distribution of the software without specific, written prior +permission. + +LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, +INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. +IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY +SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER +IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. + +****************************************************************/ + +/* Please send bug reports to + David M. Gay + Bell Laboratories, Room 2C-463 + 600 Mountain Avenue + Murray Hill, NJ 07974-0636 + U.S.A. + dmg@bell-labs.com + */ + +#include "gdtoaimp.h" + + int +#ifdef KR_headers +strtopd(s, sp, d) char *s; char **sp; double *d; +#else +strtopd(CONST char *s, char **sp, double *d) +#endif +{ + static FPI fpi0 = { 53, 1-1023-53+1, 2046-1023-53+1, 1, SI }; + ULong bits[2]; + Long exp; + int k; + + k = strtodg(s, sp, &fpi0, &exp, bits); + ULtod((ULong*)d, bits, exp, k); + return k; + } diff --git a/lib/libc/gdtoa/strtopdd.c b/lib/libc/gdtoa/strtopdd.c new file mode 100644 index 0000000..f71bced --- /dev/null +++ b/lib/libc/gdtoa/strtopdd.c @@ -0,0 +1,184 @@ +/**************************************************************** + +The author of this software is David M. Gay. + +Copyright (C) 1998, 2000 by Lucent Technologies +All Rights Reserved + +Permission to use, copy, modify, and distribute this software and +its documentation for any purpose and without fee is hereby +granted, provided that the above copyright notice appear in all +copies and that both that the copyright notice and this +permission notice and warranty disclaimer appear in supporting +documentation, and that the name of Lucent or any of its entities +not be used in advertising or publicity pertaining to +distribution of the software without specific, written prior +permission. + +LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, +INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. +IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY +SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER +IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. + +****************************************************************/ + +/* Please send bug reports to + David M. Gay + Bell Laboratories, Room 2C-463 + 600 Mountain Avenue + Murray Hill, NJ 07974-0636 + U.S.A. + dmg@bell-labs.com + */ + +#include "gdtoaimp.h" + + int +#ifdef KR_headers +strtopdd(s, sp, dd) CONST char *s; char **sp; double *dd; +#else +strtopdd(CONST char *s, char **sp, double *dd) +#endif +{ +#ifdef Sudden_Underflow + static FPI fpi = { 106, 1-1023, 2046-1023-106+1, 1, 1 }; +#else + static FPI fpi = { 106, 1-1023-53+1, 2046-1023-106+1, 1, 0 }; +#endif + ULong bits[4]; + Long exp; + int i, j, rv; + typedef union { + double d[2]; + ULong L[4]; + } U; + U *u; + + rv = strtodg(s, sp, &fpi, &exp, bits); + u = (U*)dd; + switch(rv & STRTOG_Retmask) { + case STRTOG_NoNumber: + case STRTOG_Zero: + u->d[0] = u->d[1] = 0.; + break; + + case STRTOG_Normal: + u->L[_1] = (bits[1] >> 21 | bits[2] << 11) & 0xffffffffL; + u->L[_0] = bits[2] >> 21 | bits[3] << 11 & 0xfffff + | exp + 0x3ff + 105 << 20; + exp += 0x3ff + 52; + if (bits[1] &= 0x1fffff) { + i = hi0bits(bits[1]) - 11; + if (i >= exp) { + i = exp - 1; + exp = 0; + } + else + exp -= i; + if (i > 0) { + bits[1] = bits[1] << i | bits[0] >> 32-i; + bits[0] = bits[0] << i & 0xffffffffL; + } + } + else if (bits[0]) { + i = hi0bits(bits[0]) + 21; + if (i >= exp) { + i = exp - 1; + exp = 0; + } + else + exp -= i; + if (i < 32) { + bits[1] = bits[0] >> 32 - i; + bits[0] = bits[0] << i & 0xffffffffL; + } + else { + bits[1] = bits[0] << i - 32; + bits[0] = 0; + } + } + else { + u->L[2] = u->L[3] = 0; + break; + } + u->L[2+_1] = bits[0]; + u->L[2+_0] = bits[1] & 0xfffff | exp << 20; + break; + + case STRTOG_Denormal: + if (bits[3]) + goto nearly_normal; + if (bits[2]) + goto partly_normal; + if (bits[1] & 0xffe00000) + goto hardly_normal; + /* completely denormal */ + u->L[2] = u->L[3] = 0; + u->L[_1] = bits[0]; + u->L[_0] = bits[1]; + break; + + nearly_normal: + i = hi0bits(bits[3]) - 11; /* i >= 12 */ + j = 32 - i; + u->L[_0] = (bits[3] << i | bits[2] >> j) & 0xfffff + | 65 - i << 20; + u->L[_1] = (bits[2] << i | bits[1] >> j) & 0xffffffffL; + u->L[2+_0] = bits[1] & (1L << j) - 1; + u->L[2+_1] = bits[0]; + break; + + partly_normal: + i = hi0bits(bits[2]) - 11; + if (i < 0) { + j = -i; + i += 32; + u->L[_0] = bits[2] >> j & 0xfffff | (33 + j) << 20; + u->L[_1] = (bits[2] << i | bits[1] >> j) & 0xffffffffL; + u->L[2+_0] = bits[1] & (1L << j) - 1; + u->L[2+_1] = bits[0]; + break; + } + if (i == 0) { + u->L[_0] = bits[2] & 0xfffff | 33 << 20; + u->L[_1] = bits[1]; + u->L[2+_0] = 0; + u->L[2+_1] = bits[0]; + break; + } + j = 32 - i; + u->L[_0] = (bits[2] << i | bits[1] >> j) & 0xfffff + | j + 1 << 20; + u->L[_1] = (bits[1] << i | bits[0] >> j) & 0xffffffffL; + u->L[2+_0] = 0; + u->L[2+_1] = bits[0] & (1L << j) - 1; + break; + + hardly_normal: + j = 11 - hi0bits(bits[1]); + i = 32 - j; + u->L[_0] = bits[1] >> j & 0xfffff | j + 1 << 20; + u->L[_1] = (bits[1] << i | bits[0] >> j) & 0xffffffffL; + u->L[2+_0] = 0; + u->L[2+_1] = bits[0] & (1L << j) - 1; + break; + + case STRTOG_Infinite: + u->L[_0] = u->L[2+_0] = 0x7ff00000; + u->L[_1] = u->L[2+_1] = 0; + break; + + case STRTOG_NaN: + u->L[_0] = u->L[2+_0] = 0x7fffffff; + u->L[_1] = u->L[2+_1] = (ULong)-1; + } + if (rv & STRTOG_Neg) { + u->L[ _0] |= 0x80000000L; + u->L[2+_0] |= 0x80000000L; + } + return rv; + } diff --git a/lib/libc/gdtoa/strtopf.c b/lib/libc/gdtoa/strtopf.c new file mode 100644 index 0000000..c49fc96 --- /dev/null +++ b/lib/libc/gdtoa/strtopf.c @@ -0,0 +1,83 @@ +/**************************************************************** + +The author of this software is David M. Gay. + +Copyright (C) 1998, 2000 by Lucent Technologies +All Rights Reserved + +Permission to use, copy, modify, and distribute this software and +its documentation for any purpose and without fee is hereby +granted, provided that the above copyright notice appear in all +copies and that both that the copyright notice and this +permission notice and warranty disclaimer appear in supporting +documentation, and that the name of Lucent or any of its entities +not be used in advertising or publicity pertaining to +distribution of the software without specific, written prior +permission. + +LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, +INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. +IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY +SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER +IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. + +****************************************************************/ + +/* Please send bug reports to + David M. Gay + Bell Laboratories, Room 2C-463 + 600 Mountain Avenue + Murray Hill, NJ 07974-0636 + U.S.A. + dmg@bell-labs.com + */ + +#include "gdtoaimp.h" + + int +#ifdef KR_headers +strtopf(s, sp, f) CONST char *s; char **sp; float *f; +#else +strtopf(CONST char *s, char **sp, float *f) +#endif +{ +#ifdef Sudden_Underflow + static FPI fpi = { 24, 1-127-24+1, 254-127-24+1, 1, 1 }; +#else + static FPI fpi = { 24, 1-127-24+1, 254-127-24+1, 1, 0 }; +#endif + ULong bits[1], *L; + Long exp; + int k; + + k = strtodg(s, sp, &fpi, &exp, bits); + L = (ULong*)f; + switch(k & STRTOG_Retmask) { + case STRTOG_NoNumber: + case STRTOG_Zero: + L[0] = 0; + break; + + case STRTOG_Normal: + case STRTOG_NaNbits: + L[0] = bits[0] & 0x7fffff | exp + 0x7f + 23 << 23; + break; + + case STRTOG_Denormal: + L[0] = bits[0]; + break; + + case STRTOG_Infinite: + L[0] = 0x7f800000; + break; + + case STRTOG_NaN: + L[0] = 0x7fffffff; + } + if (k & STRTOG_Neg) + L[0] |= 0x80000000L; + return k; + } diff --git a/lib/libc/gdtoa/strtopx.c b/lib/libc/gdtoa/strtopx.c new file mode 100644 index 0000000..190b80f --- /dev/null +++ b/lib/libc/gdtoa/strtopx.c @@ -0,0 +1,106 @@ +/**************************************************************** + +The author of this software is David M. Gay. + +Copyright (C) 1998, 2000 by Lucent Technologies +All Rights Reserved + +Permission to use, copy, modify, and distribute this software and +its documentation for any purpose and without fee is hereby +granted, provided that the above copyright notice appear in all +copies and that both that the copyright notice and this +permission notice and warranty disclaimer appear in supporting +documentation, and that the name of Lucent or any of its entities +not be used in advertising or publicity pertaining to +distribution of the software without specific, written prior +permission. + +LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, +INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. +IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY +SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER +IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. + +****************************************************************/ + +/* Please send bug reports to + David M. Gay + Bell Laboratories, Room 2C-463 + 600 Mountain Avenue + Murray Hill, NJ 07974-0636 + U.S.A. + dmg@bell-labs.com + */ + +#include "gdtoaimp.h" + +#undef _0 +#undef _1 + +/* one or the other of IEEE_MC68k or IEEE_8087 should be #defined */ + +#ifdef IEEE_MC68k +#define _0 0 +#define _1 1 +#define _2 2 +#define _3 3 +#define _4 4 +#endif +#ifdef IEEE_8087 +#define _0 4 +#define _1 3 +#define _2 2 +#define _3 1 +#define _4 0 +#endif + + int +#ifdef KR_headers +strtopx(s, sp, V) CONST char *s; char **sp; void *V; +#else +strtopx(CONST char *s, char **sp, void *V) +#endif +{ +#ifdef Sudden_Underflow + static FPI fpi = { 64, 1-16383-64+1, 32766 - 16383 - 64 + 1, 1, 1 }; +#else + static FPI fpi = { 64, 1-16383-64+1, 32766 - 16383 - 64 + 1, 1, 0 }; +#endif + ULong bits[2]; + Long exp; + int k; + UShort *L = (UShort*)V; + + k = strtodg(s, sp, &fpi, &exp, bits); + switch(k & STRTOG_Retmask) { + case STRTOG_NoNumber: + case STRTOG_Zero: + L[0] = L[1] = L[2] = L[3] = L[4] = 0; + break; + + case STRTOG_Normal: + case STRTOG_Denormal: + case STRTOG_NaNbits: + L[_4] = (UShort)bits[0]; + L[_3] = (UShort)(bits[0] >> 16); + L[_2] = (UShort)bits[1]; + L[_1] = (UShort)(bits[1] >> 16); + L[_0] = exp + 0x3fff + 63; + break; + + case STRTOG_Infinite: + L[_0] = 0x7fff; + L[_1] = L[_2] = L[_3] = L[_4] = 0; + break; + + case STRTOG_NaN: + L[_0] = 0x7fff; + L[_1] = L[_2] = L[_3] = L[_4] = (UShort)-1; + } + if (k & STRTOG_Neg) + L[_0] |= 0x8000; + return k; + } diff --git a/lib/libc/gdtoa/strtopxL.c b/lib/libc/gdtoa/strtopxL.c new file mode 100644 index 0000000..95fd3d5 --- /dev/null +++ b/lib/libc/gdtoa/strtopxL.c @@ -0,0 +1,100 @@ +/**************************************************************** + +The author of this software is David M. Gay. + +Copyright (C) 1998, 2000 by Lucent Technologies +All Rights Reserved + +Permission to use, copy, modify, and distribute this software and +its documentation for any purpose and without fee is hereby +granted, provided that the above copyright notice appear in all +copies and that both that the copyright notice and this +permission notice and warranty disclaimer appear in supporting +documentation, and that the name of Lucent or any of its entities +not be used in advertising or publicity pertaining to +distribution of the software without specific, written prior +permission. + +LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, +INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. +IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY +SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER +IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. + +****************************************************************/ + +/* Please send bug reports to + David M. Gay + Bell Laboratories, Room 2C-463 + 600 Mountain Avenue + Murray Hill, NJ 07974-0636 + U.S.A. + dmg@bell-labs.com + */ + +#include "gdtoaimp.h" + +#undef _0 +#undef _1 + +/* one or the other of IEEE_MC68k or IEEE_8087 should be #defined */ + +#ifdef IEEE_MC68k +#define _0 0 +#define _1 1 +#define _2 2 +#endif +#ifdef IEEE_8087 +#define _0 2 +#define _1 1 +#define _2 0 +#endif + + int +#ifdef KR_headers +strtopxL(s, sp, V) CONST char *s; char **sp; void *V; +#else +strtopxL(CONST char *s, char **sp, void *V) +#endif +{ +#ifdef Sudden_Underflow + static FPI fpi = { 64, 1-16383-64+1, 32766 - 16383 - 64 + 1, 1, 1 }; +#else + static FPI fpi = { 64, 1-16383-64+1, 32766 - 16383 - 64 + 1, 1, 0 }; +#endif + ULong bits[2]; + Long exp; + int k; + ULong *L = (ULong*)V; + + k = strtodg(s, sp, &fpi, &exp, bits); + switch(k & STRTOG_Retmask) { + case STRTOG_NoNumber: + case STRTOG_Zero: + L[0] = L[1] = L[2] = 0; + break; + + case STRTOG_Normal: + case STRTOG_Denormal: + case STRTOG_NaNbits: + L[_2] = bits[0]; + L[_1] = bits[1]; + L[_0] = (exp + 0x3fff + 63) << 16; + break; + + case STRTOG_Infinite: + L[_0] = 0x7fff << 16; + L[_1] = L[_2] = 0; + break; + + case STRTOG_NaN: + L[_0] = 0x7fff << 16; + L[_1] = L[_2] = (ULong)-1; + } + if (k & STRTOG_Neg) + L[_0] |= 0x80000000L; + return k; + } diff --git a/lib/libc/gdtoa/strtorQ.c b/lib/libc/gdtoa/strtorQ.c new file mode 100644 index 0000000..63a7b6a --- /dev/null +++ b/lib/libc/gdtoa/strtorQ.c @@ -0,0 +1,121 @@ +/**************************************************************** + +The author of this software is David M. Gay. + +Copyright (C) 1998, 2000 by Lucent Technologies +All Rights Reserved + +Permission to use, copy, modify, and distribute this software and +its documentation for any purpose and without fee is hereby +granted, provided that the above copyright notice appear in all +copies and that both that the copyright notice and this +permission notice and warranty disclaimer appear in supporting +documentation, and that the name of Lucent or any of its entities +not be used in advertising or publicity pertaining to +distribution of the software without specific, written prior +permission. + +LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, +INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. +IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY +SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER +IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. + +****************************************************************/ + +/* Please send bug reports to + David M. Gay + Bell Laboratories, Room 2C-463 + 600 Mountain Avenue + Murray Hill, NJ 07974-0636 + U.S.A. + dmg@bell-labs.com + */ + +#include "gdtoaimp.h" + +#undef _0 +#undef _1 + +/* one or the other of IEEE_MC68k or IEEE_8087 should be #defined */ + +#ifdef IEEE_MC68k +#define _0 0 +#define _1 1 +#define _2 2 +#define _3 3 +#endif +#ifdef IEEE_8087 +#define _0 3 +#define _1 2 +#define _2 1 +#define _3 0 +#endif + + void +#ifdef KR_headers +ULtoQ(L, bits, exp, k) ULong *L; ULong *bits; Long exp; int k; +#else +ULtoQ(ULong *L, ULong *bits, Long exp, int k) +#endif +{ + switch(k & STRTOG_Retmask) { + case STRTOG_NoNumber: + case STRTOG_Zero: + L[0] = L[1] = L[2] = L[3] = 0; + break; + + case STRTOG_Normal: + case STRTOG_NaNbits: + L[_3] = bits[0]; + L[_2] = bits[1]; + L[_1] = bits[2]; + L[_0] = (bits[3] & ~0x10000) | ((exp + 0x3fff + 112) << 16); + break; + + case STRTOG_Denormal: + L[_3] = bits[0]; + L[_2] = bits[1]; + L[_1] = bits[2]; + L[_0] = bits[3]; + break; + + case STRTOG_Infinite: + L[_0] = 0x7fff0000; + L[_1] = L[_2] = L[_3] = 0; + break; + + case STRTOG_NaN: + L[_0] = 0x7fffffff; + L[_1] = L[_2] = L[_3] = (ULong)-1; + } + if (k & STRTOG_Neg) + L[_0] |= 0x80000000L; + } + + int +#ifdef KR_headers +strtorQ(s, sp, rounding, L) CONST char *s; char **sp; int rounding; void *L; +#else +strtorQ(CONST char *s, char **sp, int rounding, void *L) +#endif +{ + static FPI fpi0 = { 113, 1-16383-113+1, 32766-16383-113+1, 1, SI }; + FPI *fpi, fpi1; + ULong bits[4]; + Long exp; + int k; + + fpi = &fpi0; + if (rounding != FPI_Round_near) { + fpi1 = fpi0; + fpi1.rounding = rounding; + fpi = &fpi1; + } + k = strtodg(s, sp, fpi, &exp, bits); + ULtoQ((ULong*)L, bits, exp, k); + return k; + } diff --git a/lib/libc/gdtoa/strtord.c b/lib/libc/gdtoa/strtord.c new file mode 100644 index 0000000..12213f9 --- /dev/null +++ b/lib/libc/gdtoa/strtord.c @@ -0,0 +1,99 @@ +/**************************************************************** + +The author of this software is David M. Gay. + +Copyright (C) 1998, 2000 by Lucent Technologies +All Rights Reserved + +Permission to use, copy, modify, and distribute this software and +its documentation for any purpose and without fee is hereby +granted, provided that the above copyright notice appear in all +copies and that both that the copyright notice and this +permission notice and warranty disclaimer appear in supporting +documentation, and that the name of Lucent or any of its entities +not be used in advertising or publicity pertaining to +distribution of the software without specific, written prior +permission. + +LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, +INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. +IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY +SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER +IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. + +****************************************************************/ + +/* Please send bug reports to + David M. Gay + Bell Laboratories, Room 2C-463 + 600 Mountain Avenue + Murray Hill, NJ 07974-0636 + U.S.A. + dmg@bell-labs.com + */ + +#include "gdtoaimp.h" + + void +#ifdef KR_headers +ULtod(L, bits, exp, k) ULong *L; ULong *bits; Long exp; int k; +#else +ULtod(ULong *L, ULong *bits, Long exp, int k) +#endif +{ + switch(k & STRTOG_Retmask) { + case STRTOG_NoNumber: + case STRTOG_Zero: + L[0] = L[1] = 0; + break; + + case STRTOG_Denormal: + L[_1] = bits[0]; + L[_0] = bits[1]; + break; + + case STRTOG_Normal: + case STRTOG_NaNbits: + L[_1] = bits[0]; + L[_0] = (bits[1] & ~0x100000) | ((exp + 0x3ff + 52) << 20); + break; + + case STRTOG_Infinite: + L[_0] = 0x7ff00000; + L[_1] = 0; + break; + + case STRTOG_NaN: + L[_0] = 0x7fffffff; + L[_1] = (ULong)-1; + } + if (k & STRTOG_Neg) + L[_0] |= 0x80000000L; + } + + int +#ifdef KR_headers +strtord(s, sp, rounding, d) CONST char *s; char **sp; int rounding; double *d; +#else +strtord(CONST char *s, char **sp, int rounding, double *d) +#endif +{ + static FPI fpi0 = { 53, 1-1023-53+1, 2046-1023-53+1, 1, SI }; + FPI *fpi, fpi1; + ULong bits[2]; + Long exp; + int k; + + fpi = &fpi0; + if (rounding != FPI_Round_near) { + fpi1 = fpi0; + fpi1.rounding = rounding; + fpi = &fpi1; + } + k = strtodg(s, sp, fpi, &exp, bits); + ULtod((ULong*)d, bits, exp, k); + return k; + } diff --git a/lib/libc/gdtoa/strtordd.c b/lib/libc/gdtoa/strtordd.c new file mode 100644 index 0000000..626a4d3 --- /dev/null +++ b/lib/libc/gdtoa/strtordd.c @@ -0,0 +1,205 @@ +/**************************************************************** + +The author of this software is David M. Gay. + +Copyright (C) 1998, 2000 by Lucent Technologies +All Rights Reserved + +Permission to use, copy, modify, and distribute this software and +its documentation for any purpose and without fee is hereby +granted, provided that the above copyright notice appear in all +copies and that both that the copyright notice and this +permission notice and warranty disclaimer appear in supporting +documentation, and that the name of Lucent or any of its entities +not be used in advertising or publicity pertaining to +distribution of the software without specific, written prior +permission. + +LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, +INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. +IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY +SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER +IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. + +****************************************************************/ + +/* Please send bug reports to + David M. Gay + Bell Laboratories, Room 2C-463 + 600 Mountain Avenue + Murray Hill, NJ 07974-0636 + U.S.A. + dmg@bell-labs.com + */ + +#include "gdtoaimp.h" + + void +#ifdef KR_headers +ULtodd(L, bits, exp, k) ULong *L; ULong *bits; Long exp; int k; +#else +ULtodd(ULong *L, ULong *bits, Long exp, int k) +#endif +{ + int i, j; + + switch(k & STRTOG_Retmask) { + case STRTOG_NoNumber: + case STRTOG_Zero: + L[0] = L[1] = L[2] = L[3] = 0; + break; + + case STRTOG_Normal: + L[_1] = (bits[1] >> 21 | bits[2] << 11) & (ULong)0xffffffffL; + L[_0] = bits[2] >> 21 | bits[3] << 11 & 0xfffff + | exp + 0x3ff + 105 << 20; + exp += 0x3ff + 52; + if (bits[1] &= 0x1fffff) { + i = hi0bits(bits[1]) - 11; + if (i >= exp) { + i = exp - 1; + exp = 0; + } + else + exp -= i; + if (i > 0) { + bits[1] = bits[1] << i | bits[0] >> 32-i; + bits[0] = bits[0] << i & (ULong)0xffffffffL; + } + } + else if (bits[0]) { + i = hi0bits(bits[0]) + 21; + if (i >= exp) { + i = exp - 1; + exp = 0; + } + else + exp -= i; + if (i < 32) { + bits[1] = bits[0] >> 32 - i; + bits[0] = bits[0] << i & (ULong)0xffffffffL; + } + else { + bits[1] = bits[0] << i - 32; + bits[0] = 0; + } + } + else { + L[2] = L[3] = 0; + break; + } + L[2+_1] = bits[0]; + L[2+_0] = bits[1] & 0xfffff | exp << 20; + break; + + case STRTOG_Denormal: + if (bits[3]) + goto nearly_normal; + if (bits[2]) + goto partly_normal; + if (bits[1] & 0xffe00000) + goto hardly_normal; + /* completely denormal */ + L[2] = L[3] = 0; + L[_1] = bits[0]; + L[_0] = bits[1]; + break; + + nearly_normal: + i = hi0bits(bits[3]) - 11; /* i >= 12 */ + j = 32 - i; + L[_0] = (bits[3] << i | bits[2] >> j) & 0xfffff + | 65 - i << 20; + L[_1] = (bits[2] << i | bits[1] >> j) & 0xffffffffL; + L[2+_0] = bits[1] & ((ULong)1L << j) - 1; + L[2+_1] = bits[0]; + break; + + partly_normal: + i = hi0bits(bits[2]) - 11; + if (i < 0) { + j = -i; + i += 32; + L[_0] = bits[2] >> j & 0xfffff | (33 + j) << 20; + L[_1] = (bits[2] << i | bits[1] >> j) & 0xffffffffL; + L[2+_0] = bits[1] & ((ULong)1L << j) - 1; + L[2+_1] = bits[0]; + break; + } + if (i == 0) { + L[_0] = bits[2] & 0xfffff | 33 << 20; + L[_1] = bits[1]; + L[2+_0] = 0; + L[2+_1] = bits[0]; + break; + } + j = 32 - i; + L[_0] = (bits[2] << i | bits[1] >> j) & 0xfffff + | j + 1 << 20; + L[_1] = (bits[1] << i | bits[0] >> j) & 0xffffffffL; + L[2+_0] = 0; + L[2+_1] = bits[0] & (1L << j) - 1; + break; + + hardly_normal: + j = 11 - hi0bits(bits[1]); + i = 32 - j; + L[_0] = bits[1] >> j & 0xfffff | j + 1 << 20; + L[_1] = (bits[1] << i | bits[0] >> j) & 0xffffffffL; + L[2+_0] = 0; + L[2+_1] = bits[0] & ((ULong)1L << j) - 1; + break; + + case STRTOG_Infinite: + L[_0] = L[2+_0] = 0x7ff00000; + L[_1] = L[2+_1] = 0; + break; + + case STRTOG_NaN: + L[_0] = L[2+_0] = 0x7fffffff; + L[_1] = L[2+_1] = (ULong)-1; + break; + + case STRTOG_NaNbits: + L[_1] = (bits[1] >> 21 | bits[2] << 11) & (ULong)0xffffffffL; + L[_0] = bits[2] >> 21 | bits[3] << 11 + | (ULong)0x7ff00000L; + L[2+_1] = bits[0]; + L[2+_0] = bits[1] | (ULong)0x7ff00000L; + } + if (k & STRTOG_Neg) { + L[_0] |= 0x80000000L; + L[2+_0] |= 0x80000000L; + } + } + + int +#ifdef KR_headers +strtordd(s, sp, rounding, dd) CONST char *s; char **sp; int rounding; double *dd; +#else +strtordd(CONST char *s, char **sp, int rounding, double *dd) +#endif +{ +#ifdef Sudden_Underflow + static FPI fpi0 = { 106, 1-1023, 2046-1023-106+1, 1, 1 }; +#else + static FPI fpi0 = { 106, 1-1023-53+1, 2046-1023-106+1, 1, 0 }; +#endif + FPI *fpi, fpi1; + ULong bits[4]; + Long exp; + int k; + + fpi = &fpi0; + if (rounding != FPI_Round_near) { + fpi1 = fpi0; + fpi1.rounding = rounding; + fpi = &fpi1; + } + k = strtodg(s, sp, fpi, &exp, bits); + ULtodd((ULong*)dd, bits, exp, k); + return k; + } diff --git a/lib/libc/gdtoa/strtorf.c b/lib/libc/gdtoa/strtorf.c new file mode 100644 index 0000000..ecd1c0b --- /dev/null +++ b/lib/libc/gdtoa/strtorf.c @@ -0,0 +1,95 @@ +/**************************************************************** + +The author of this software is David M. Gay. + +Copyright (C) 1998, 2000 by Lucent Technologies +All Rights Reserved + +Permission to use, copy, modify, and distribute this software and +its documentation for any purpose and without fee is hereby +granted, provided that the above copyright notice appear in all +copies and that both that the copyright notice and this +permission notice and warranty disclaimer appear in supporting +documentation, and that the name of Lucent or any of its entities +not be used in advertising or publicity pertaining to +distribution of the software without specific, written prior +permission. + +LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, +INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. +IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY +SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER +IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. + +****************************************************************/ + +/* Please send bug reports to + David M. Gay + Bell Laboratories, Room 2C-463 + 600 Mountain Avenue + Murray Hill, NJ 07974-0636 + U.S.A. + dmg@bell-labs.com + */ + +#include "gdtoaimp.h" + + void +#ifdef KR_headers +ULtof(L, bits, exp, k) ULong *L; ULong *bits; Long exp; int k; +#else +ULtof(ULong *L, ULong *bits, Long exp, int k) +#endif +{ + switch(k & STRTOG_Retmask) { + case STRTOG_NoNumber: + case STRTOG_Zero: + *L = 0; + break; + + case STRTOG_Normal: + case STRTOG_NaNbits: + L[0] = bits[0] & 0x7fffff | exp + 0x7f + 23 << 23; + break; + + case STRTOG_Denormal: + L[0] = bits[0]; + break; + + case STRTOG_Infinite: + L[0] = 0x7f800000; + break; + + case STRTOG_NaN: + L[0] = 0x7fffffff; + } + if (k & STRTOG_Neg) + L[0] |= 0x80000000L; + } + + int +#ifdef KR_headers +strtorf(s, sp, rounding, f) CONST char *s; char **sp; int rounding; float *f; +#else +strtorf(CONST char *s, char **sp, int rounding, float *f) +#endif +{ + static FPI fpi0 = { 24, 1-127-24+1, 254-127-24+1, 1, SI }; + FPI *fpi, fpi1; + ULong bits[1]; + Long exp; + int k; + + fpi = &fpi0; + if (rounding != FPI_Round_near) { + fpi1 = fpi0; + fpi1.rounding = rounding; + fpi = &fpi1; + } + k = strtodg(s, sp, fpi, &exp, bits); + ULtof((ULong*)f, bits, exp, k); + return k; + } diff --git a/lib/libc/gdtoa/strtorx.c b/lib/libc/gdtoa/strtorx.c new file mode 100644 index 0000000..0a81e95 --- /dev/null +++ b/lib/libc/gdtoa/strtorx.c @@ -0,0 +1,118 @@ +/**************************************************************** + +The author of this software is David M. Gay. + +Copyright (C) 1998, 2000 by Lucent Technologies +All Rights Reserved + +Permission to use, copy, modify, and distribute this software and +its documentation for any purpose and without fee is hereby +granted, provided that the above copyright notice appear in all +copies and that both that the copyright notice and this +permission notice and warranty disclaimer appear in supporting +documentation, and that the name of Lucent or any of its entities +not be used in advertising or publicity pertaining to +distribution of the software without specific, written prior +permission. + +LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, +INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. +IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY +SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER +IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. + +****************************************************************/ + +/* Please send bug reports to + David M. Gay + Bell Laboratories, Room 2C-463 + 600 Mountain Avenue + Murray Hill, NJ 07974-0636 + U.S.A. + dmg@bell-labs.com + */ + +#include "gdtoaimp.h" + +#undef _0 +#undef _1 + +/* one or the other of IEEE_MC68k or IEEE_8087 should be #defined */ + +#ifdef IEEE_MC68k +#define _0 0 +#define _1 1 +#define _2 2 +#define _3 3 +#define _4 4 +#endif +#ifdef IEEE_8087 +#define _0 4 +#define _1 3 +#define _2 2 +#define _3 1 +#define _4 0 +#endif + + void +#ifdef KR_headers +ULtox(L, bits, exp, k) UShort *L; ULong *bits; Long exp; int k; +#else +ULtox(UShort *L, ULong *bits, Long exp, int k) +#endif +{ + switch(k & STRTOG_Retmask) { + case STRTOG_NoNumber: + case STRTOG_Zero: + L[0] = L[1] = L[2] = L[3] = L[4] = 0; + break; + + case STRTOG_Normal: + case STRTOG_Denormal: + case STRTOG_NaNbits: + L[_4] = (UShort)bits[0]; + L[_3] = (UShort)(bits[0] >> 16); + L[_2] = (UShort)bits[1]; + L[_1] = (UShort)(bits[1] >> 16); + L[_0] = exp + 0x3fff + 63; + break; + + case STRTOG_Infinite: + L[_0] = 0x7fff; + L[_1] = L[_2] = L[_3] = L[_4] = 0; + break; + + case STRTOG_NaN: + L[_0] = 0x7fff; + L[_1] = L[_2] = L[_3] = L[_4] = (UShort)-1; + } + if (k & STRTOG_Neg) + L[_0] |= 0x8000; + } + + int +#ifdef KR_headers +strtorx(s, sp, rounding, L) CONST char *s; char **sp; int rounding; void *L; +#else +strtorx(CONST char *s, char **sp, int rounding, void *L) +#endif +{ + static FPI fpi0 = { 64, 1-16383-64+1, 32766 - 16383 - 64 + 1, 1, SI }; + FPI *fpi, fpi1; + ULong bits[2]; + Long exp; + int k; + + fpi = &fpi0; + if (rounding != FPI_Round_near) { + fpi1 = fpi0; + fpi1.rounding = rounding; + fpi = &fpi1; + } + k = strtodg(s, sp, fpi, &exp, bits); + ULtox((UShort*)L, bits, exp, k); + return k; + } diff --git a/lib/libc/gdtoa/strtorxL.c b/lib/libc/gdtoa/strtorxL.c new file mode 100644 index 0000000..126cef8 --- /dev/null +++ b/lib/libc/gdtoa/strtorxL.c @@ -0,0 +1,112 @@ +/**************************************************************** + +The author of this software is David M. Gay. + +Copyright (C) 1998, 2000 by Lucent Technologies +All Rights Reserved + +Permission to use, copy, modify, and distribute this software and +its documentation for any purpose and without fee is hereby +granted, provided that the above copyright notice appear in all +copies and that both that the copyright notice and this +permission notice and warranty disclaimer appear in supporting +documentation, and that the name of Lucent or any of its entities +not be used in advertising or publicity pertaining to +distribution of the software without specific, written prior +permission. + +LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, +INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. +IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY +SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER +IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. + +****************************************************************/ + +/* Please send bug reports to + David M. Gay + Bell Laboratories, Room 2C-463 + 600 Mountain Avenue + Murray Hill, NJ 07974-0636 + U.S.A. + dmg@bell-labs.com + */ + +#include "gdtoaimp.h" + +#undef _0 +#undef _1 + +/* one or the other of IEEE_MC68k or IEEE_8087 should be #defined */ + +#ifdef IEEE_MC68k +#define _0 0 +#define _1 1 +#define _2 2 +#endif +#ifdef IEEE_8087 +#define _0 2 +#define _1 1 +#define _2 0 +#endif + + void +#ifdef KR_headers +ULtoxL(L, bits, exp, k) ULong *L; ULong *bits; Long exp; int k; +#else +ULtoxL(ULong *L, ULong *bits, Long exp, int k) +#endif +{ + switch(k & STRTOG_Retmask) { + case STRTOG_NoNumber: + case STRTOG_Zero: + L[0] = L[1] = L[2] = 0; + break; + + case STRTOG_Normal: + case STRTOG_Denormal: + case STRTOG_NaNbits: + L[_0] = (exp + 0x3fff + 63) << 16; + L[_1] = bits[1]; + L[_2] = bits[0]; + break; + + case STRTOG_Infinite: + L[_0] = 0x7fff << 16; + L[_1] = L[_2] = 0; + break; + + case STRTOG_NaN: + L[_0] = 0x7fff << 16; + L[_1] = L[_2] = (ULong)-1; + } + if (k & STRTOG_Neg) + L[_0] |= 0x80000000L; + } + + int +#ifdef KR_headers +strtorxL(s, sp, rounding, L) CONST char *s; char **sp; int rounding; void *L; +#else +strtorxL(CONST char *s, char **sp, int rounding, void *L) +#endif +{ + static FPI fpi0 = { 64, 1-16383-64+1, 32766 - 16383 - 64 + 1, 1, SI }; + FPI *fpi, fpi1; + ULong bits[2]; + Long exp; + int k; + + fpi = &fpi0; + if (rounding != FPI_Round_near) { + fpi1 = fpi0; + fpi1.rounding = rounding; + fpi = &fpi1; + } + k = strtodg(s, sp, fpi, &exp, bits); + ULtoxL((ULong*)L, bits, exp, k); + return k; + } diff --git a/lib/libc/gdtoa/sum.c b/lib/libc/gdtoa/sum.c new file mode 100644 index 0000000..1e1a4de --- /dev/null +++ b/lib/libc/gdtoa/sum.c @@ -0,0 +1,104 @@ +/**************************************************************** + +The author of this software is David M. Gay. + +Copyright (C) 1998 by Lucent Technologies +All Rights Reserved + +Permission to use, copy, modify, and distribute this software and +its documentation for any purpose and without fee is hereby +granted, provided that the above copyright notice appear in all +copies and that both that the copyright notice and this +permission notice and warranty disclaimer appear in supporting +documentation, and that the name of Lucent or any of its entities +not be used in advertising or publicity pertaining to +distribution of the software without specific, written prior +permission. + +LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, +INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. +IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY +SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER +IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. + +****************************************************************/ + +/* Please send bug reports to + David M. Gay + Bell Laboratories, Room 2C-463 + 600 Mountain Avenue + Murray Hill, NJ 07974-0636 + U.S.A. + dmg@bell-labs.com + */ + +#include "gdtoaimp.h" + + Bigint * +#ifdef KR_headers +sum(a, b) Bigint *a; Bigint *b; +#else +sum(Bigint *a, Bigint *b) +#endif +{ + Bigint *c; + ULong carry, *xc, *xa, *xb, *xe, y; +#ifdef Pack_32 + ULong z; +#endif + + if (a->wds < b->wds) { + c = b; b = a; a = c; + } + c = Balloc(a->k); + c->wds = a->wds; + carry = 0; + xa = a->x; + xb = b->x; + xc = c->x; + xe = xc + b->wds; +#ifdef Pack_32 + do { + y = (*xa & 0xffff) + (*xb & 0xffff) + carry; + carry = (y & 0x10000) >> 16; + z = (*xa++ >> 16) + (*xb++ >> 16) + carry; + carry = (z & 0x10000) >> 16; + Storeinc(xc, z, y); + } + while(xc < xe); + xe += a->wds - b->wds; + while(xc < xe) { + y = (*xa & 0xffff) + carry; + carry = (y & 0x10000) >> 16; + z = (*xa++ >> 16) + carry; + carry = (z & 0x10000) >> 16; + Storeinc(xc, z, y); + } +#else + do { + y = *xa++ + *xb++ + carry; + carry = (y & 0x10000) >> 16; + *xc++ = y & 0xffff; + } + while(xc < xe); + xe += a->wds - b->wds; + while(xc < xe) { + y = *xa++ + carry; + carry = (y & 0x10000) >> 16; + *xc++ = y & 0xffff; + } +#endif + if (carry) { + if (c->wds == c->maxwds) { + b = Balloc(c->k + 1); + Bcopy(b, c); + Bfree(c); + c = b; + } + c->x[c->wds++] = 1; + } + return c; + } diff --git a/lib/libc/gdtoa/ulp.c b/lib/libc/gdtoa/ulp.c new file mode 100644 index 0000000..536994a --- /dev/null +++ b/lib/libc/gdtoa/ulp.c @@ -0,0 +1,76 @@ +/**************************************************************** + +The author of this software is David M. Gay. + +Copyright (C) 1998, 1999 by Lucent Technologies +All Rights Reserved + +Permission to use, copy, modify, and distribute this software and +its documentation for any purpose and without fee is hereby +granted, provided that the above copyright notice appear in all +copies and that both that the copyright notice and this +permission notice and warranty disclaimer appear in supporting +documentation, and that the name of Lucent or any of its entities +not be used in advertising or publicity pertaining to +distribution of the software without specific, written prior +permission. + +LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, +INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. +IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY +SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER +IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. + +****************************************************************/ + +/* Please send bug reports to + David M. Gay + Bell Laboratories, Room 2C-463 + 600 Mountain Avenue + Murray Hill, NJ 07974-0636 + U.S.A. + dmg@bell-labs.com + */ + +#include "gdtoaimp.h" + + double +ulp +#ifdef KR_headers + (x) double x; +#else + (double x) +#endif +{ + Long L; + double a; + + L = (word0(x) & Exp_mask) - (P-1)*Exp_msk1; +#ifndef Sudden_Underflow + if (L > 0) { +#endif +#ifdef IBM + L |= Exp_msk1 >> 4; +#endif + word0(a) = L; + word1(a) = 0; +#ifndef Sudden_Underflow + } + else { + L = -L >> Exp_shift; + if (L < Exp_shift) { + word0(a) = 0x80000 >> L; + word1(a) = 0; + } + else { + word0(a) = 0; + L -= Exp_shift; + word1(a) = L >= 31 ? 1 : 1 << 31 - L; + } + } +#endif + return a; + } diff --git a/lib/libc/gen/Makefile b/lib/libc/gen/Makefile new file mode 100644 index 0000000..c1542b1 --- /dev/null +++ b/lib/libc/gen/Makefile @@ -0,0 +1,35 @@ +# $Id: Makefile 89 2016-01-12 00:20:40Z reddawg $ +# The System Makefile (C) 2002 The UbixOS Project + +# Include Global 'Source' Options +include ../../../Makefile.incl +include ../../Makefile.incl +include ../Makefile.incl + +INCLUDES += -I../locale/ -I../i386 + +#Objects ldexpo +OBJS = __xuname.o _pthread_stubs.o _rand48.o _spinlock_stub.o _thread_init.o alarm.o arc4random.o assert.o basename.o check_utility_compat.o clock.o closedir.o confstr.o crypt.o ctermid.o daemon.o devname.o dirname.o disklabel.o dlfcn.o dlfunc.o drand48.o erand48.o err.o errlst.o errno.o exec.o fmtcheck.o fmtmsg.o fnmatch.o fpclassify.o frexp.o fstab.o ftok.o fts.o ftw.o getbootfile.o getbsize.o getcap.o getcwd.o getdomainname.o getgrent.o getgrouplist.o gethostname.o getloadavg.o getlogin.o getmntinfo.o getnetgrent.o getobjformat.o getosreldate.o getpagesize.o getpeereid.o getprogname.o getpwent.o getttyent.o getusershell.o getvfsbyname.o glob.o initgroups.o isatty.o isinf.o isnan.o jrand48.o lcong48.o lockf.o lrand48.o mrand48.o nftw.o nice.o nlist.o nrand48.o opendir.o pause.o pmadvise.o popen.o posixshm.o pselect.o psignal.o pw_scan.o pwcache.o raise.o readdir.o readpassphrase.o rewinddir.o scandir.o seed48.o seekdir.o sem.o semctl.o setdomainname.o sethostname.o setjmperr.o setmode.o setproctitle.o setprogname.o siginterrupt.o siglist.o signal.o sigsetops.o sleep.o srand48.o statvfs.o stringlist.o strtofflags.o swapcontext.o sysconf.o sysctl.o sysctlbyname.o sysctlnametomib.o syslog.o telldir.o termios.o time.o times.o timezone.o tls.o ttyname.o ttyslot.o ualarm.o ulimit.o uname.o unvis.o usleep.o utime.o valloc.o vis.o wait.o wait3.o waitpid.o wordexp.o + +all: $(OBJS) + +# Compile the source files +.cc.o: + $(CXX) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -c -o $@ $< + +.cc.s: + $(CXX) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -S -o $@ $< + +.c.o: + $(CC) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -c $< + +.c.s: + $(CC) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -S -o $@ $< + +.S.o: + $(CC) $(CFLAGS) -Wall -nostdlib -c -o $@ $< + +# Clean up the junk +clean: + $(REMOVE) $(OBJS) + diff --git a/lib/libc/gen/__xuname.c b/lib/libc/gen/__xuname.c new file mode 100644 index 0000000..359f8ea --- /dev/null +++ b/lib/libc/gen/__xuname.c @@ -0,0 +1,132 @@ +/*- + * Copyright (c) 1994 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +/*static char sccsid[] = "From: @(#)uname.c 8.1 (Berkeley) 1/4/94";*/ +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/__xuname.c,v 1.9 2002/02/01 00:57:29 obrien Exp $"); + +#include +#include +#include +#include + +int +__xuname(int namesize, void *namebuf) +{ + int mib[2], rval; + size_t len; + char *p; + int oerrno; + struct xutsname { + char sysname[namesize]; /* Name of this OS. */ + char nodename[namesize]; /* Name of this network node. */ + char release[namesize]; /* Release level. */ + char version[namesize]; /* Version level. */ + char machine[namesize]; /* Hardware type. */ + } *name; + + name = (struct xutsname *)namebuf; + rval = 0; + + mib[0] = CTL_KERN; + mib[1] = KERN_OSTYPE; + len = sizeof(name->sysname); + oerrno = errno; + if (sysctl(mib, 2, &name->sysname, &len, NULL, 0) == -1) { + if(errno == ENOMEM) + errno = oerrno; + else + rval = -1; + } + name->sysname[sizeof(name->sysname) - 1] = '\0'; + + mib[0] = CTL_KERN; + mib[1] = KERN_HOSTNAME; + len = sizeof(name->nodename); + oerrno = errno; + if (sysctl(mib, 2, &name->nodename, &len, NULL, 0) == -1) { + if(errno == ENOMEM) + errno = oerrno; + else + rval = -1; + } + name->nodename[sizeof(name->nodename) - 1] = '\0'; + + mib[0] = CTL_KERN; + mib[1] = KERN_OSRELEASE; + len = sizeof(name->release); + oerrno = errno; + if (sysctl(mib, 2, &name->release, &len, NULL, 0) == -1) { + if(errno == ENOMEM) + errno = oerrno; + else + rval = -1; + } + name->release[sizeof(name->release) - 1] = '\0'; + + /* The version may have newlines in it, turn them into spaces. */ + mib[0] = CTL_KERN; + mib[1] = KERN_VERSION; + len = sizeof(name->version); + oerrno = errno; + if (sysctl(mib, 2, &name->version, &len, NULL, 0) == -1) { + if (errno == ENOMEM) + errno = oerrno; + else + rval = -1; + } + name->version[sizeof(name->version) - 1] = '\0'; + for (p = name->version; len--; ++p) { + if (*p == '\n' || *p == '\t') { + if (len > 1) + *p = ' '; + else + *p = '\0'; + } + } + + mib[0] = CTL_HW; + mib[1] = HW_MACHINE; + len = sizeof(name->machine); + oerrno = errno; + if (sysctl(mib, 2, &name->machine, &len, NULL, 0) == -1) { + if (errno == ENOMEM) + errno = oerrno; + else + rval = -1; + } + name->machine[sizeof(name->machine) - 1] = '\0'; + return (rval); +} diff --git a/lib/libc/gen/_pthread_stubs.c b/lib/libc/gen/_pthread_stubs.c new file mode 100644 index 0000000..f4178fa --- /dev/null +++ b/lib/libc/gen/_pthread_stubs.c @@ -0,0 +1,226 @@ +/* + * Copyright (c) 2001 Daniel Eischen . + * 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 DANIEL EISCHEN 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 AUTHOR 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 +__FBSDID("$FreeBSD: src/lib/libc/gen/_pthread_stubs.c,v 1.11.8.1 2006/08/11 18:34:19 thomas Exp $"); + +#include +#include + +#include "libc_private.h" + +/* + * Weak symbols: All libc internal usage of these functions should + * use the weak symbol versions (_pthread_XXX). If libpthread is + * linked, it will override these functions with (non-weak) routines. + * The _pthread_XXX functions are provided solely for internal libc + * usage to avoid unwanted cancellation points and to differentiate + * between application locks and libc locks (threads holding the + * latter can't be allowed to exit/terminate). + */ + +/* Define a null pthread structure just to satisfy _pthread_self. */ +struct pthread { +}; + +static struct pthread main_thread; + +static int stub_main(void); +static void *stub_null(void); +static struct pthread *stub_self(void); +static int stub_zero(void); + +#define PJT_DUAL_ENTRY(entry) \ + (pthread_func_t)entry, (pthread_func_t)entry + +pthread_func_entry_t __thr_jtable[PJT_MAX] = { + {PJT_DUAL_ENTRY(stub_zero)}, /* PJT_COND_BROADCAST */ + {PJT_DUAL_ENTRY(stub_zero)}, /* PJT_COND_DESTROY */ + {PJT_DUAL_ENTRY(stub_zero)}, /* PJT_COND_INIT */ + {PJT_DUAL_ENTRY(stub_zero)}, /* PJT_COND_SIGNAL */ + {PJT_DUAL_ENTRY(stub_zero)}, /* PJT_COND_WAIT */ + {PJT_DUAL_ENTRY(stub_null)}, /* PJT_GETSPECIFIC */ + {PJT_DUAL_ENTRY(stub_zero)}, /* PJT_KEY_CREATE */ + {PJT_DUAL_ENTRY(stub_zero)}, /* PJT_KEY_DELETE */ + {PJT_DUAL_ENTRY(stub_main)}, /* PJT_MAIN_NP */ + {PJT_DUAL_ENTRY(stub_zero)}, /* PJT_MUTEX_DESTROY */ + {PJT_DUAL_ENTRY(stub_zero)}, /* PJT_MUTEX_INIT */ + {PJT_DUAL_ENTRY(stub_zero)}, /* PJT_MUTEX_LOCK */ + {PJT_DUAL_ENTRY(stub_zero)}, /* PJT_MUTEX_TRYLOCK */ + {PJT_DUAL_ENTRY(stub_zero)}, /* PJT_MUTEX_UNLOCK */ + {PJT_DUAL_ENTRY(stub_zero)}, /* PJT_MUTEXATTR_DESTROY */ + {PJT_DUAL_ENTRY(stub_zero)}, /* PJT_MUTEXATTR_INIT */ + {PJT_DUAL_ENTRY(stub_zero)}, /* PJT_MUTEXATTR_SETTYPE */ + {PJT_DUAL_ENTRY(stub_zero)}, /* PJT_ONCE */ + {PJT_DUAL_ENTRY(stub_zero)}, /* PJT_RWLOCK_DESTROY */ + {PJT_DUAL_ENTRY(stub_zero)}, /* PJT_RWLOCK_INIT */ + {PJT_DUAL_ENTRY(stub_zero)}, /* PJT_RWLOCK_RDLOCK */ + {PJT_DUAL_ENTRY(stub_zero)}, /* PJT_RWLOCK_TRYRDLOCK */ + {PJT_DUAL_ENTRY(stub_zero)}, /* PJT_RWLOCK_TRYWRLOCK */ + {PJT_DUAL_ENTRY(stub_zero)}, /* PJT_RWLOCK_UNLOCK */ + {PJT_DUAL_ENTRY(stub_zero)}, /* PJT_RWLOCK_WRLOCK */ + {PJT_DUAL_ENTRY(stub_self)}, /* PJT_SELF */ + {PJT_DUAL_ENTRY(stub_zero)}, /* PJT_SETSPECIFIC */ + {PJT_DUAL_ENTRY(stub_zero)} /* PJT_SIGMASK */ +}; + +/* + * Weak aliases for exported (pthread_*) and internal (_pthread_*) routines. + */ +#define WEAK_REF(sym, alias) __weak_reference(sym, alias) + +#define FUNC_TYPE(name) __CONCAT(name, _func_t) +#define FUNC_INT(name) __CONCAT(name, _int) +#define FUNC_EXP(name) __CONCAT(name, _exp) + +#define STUB_FUNC(name, idx, ret) \ + static ret FUNC_EXP(name)(void) __used; \ + static ret FUNC_INT(name)(void) __used; \ + WEAK_REF(FUNC_EXP(name), name); \ + WEAK_REF(FUNC_INT(name), __CONCAT(_, name)); \ + typedef ret (*FUNC_TYPE(name))(void); \ + static ret FUNC_EXP(name)(void) \ + { \ + FUNC_TYPE(name) func; \ + func = (FUNC_TYPE(name))__thr_jtable[idx][0]; \ + return (func()); \ + } \ + static ret FUNC_INT(name)(void) \ + { \ + FUNC_TYPE(name) func; \ + func = (FUNC_TYPE(name))__thr_jtable[idx][1]; \ + return (func()); \ + } + +#define STUB_FUNC1(name, idx, ret, p0_type) \ + static ret FUNC_EXP(name)(p0_type) __used; \ + static ret FUNC_INT(name)(p0_type) __used; \ + WEAK_REF(FUNC_EXP(name), name); \ + WEAK_REF(FUNC_INT(name), __CONCAT(_, name)); \ + typedef ret (*FUNC_TYPE(name))(p0_type); \ + static ret FUNC_EXP(name)(p0_type p0) \ + { \ + FUNC_TYPE(name) func; \ + func = (FUNC_TYPE(name))__thr_jtable[idx][0]; \ + return (func(p0)); \ + } \ + static ret FUNC_INT(name)(p0_type p0) \ + { \ + FUNC_TYPE(name) func; \ + func = (FUNC_TYPE(name))__thr_jtable[idx][1]; \ + return (func(p0)); \ + } + +#define STUB_FUNC2(name, idx, ret, p0_type, p1_type) \ + static ret FUNC_EXP(name)(p0_type, p1_type) __used; \ + static ret FUNC_INT(name)(p0_type, p1_type) __used; \ + WEAK_REF(FUNC_EXP(name), name); \ + WEAK_REF(FUNC_INT(name), __CONCAT(_, name)); \ + typedef ret (*FUNC_TYPE(name))(p0_type, p1_type); \ + static ret FUNC_EXP(name)(p0_type p0, p1_type p1) \ + { \ + FUNC_TYPE(name) func; \ + func = (FUNC_TYPE(name))__thr_jtable[idx][0]; \ + return (func(p0, p1)); \ + } \ + static ret FUNC_INT(name)(p0_type p0, p1_type p1) \ + { \ + FUNC_TYPE(name) func; \ + func = (FUNC_TYPE(name))__thr_jtable[idx][1]; \ + return (func(p0, p1)); \ + } + +#define STUB_FUNC3(name, idx, ret, p0_type, p1_type, p2_type) \ + static ret FUNC_EXP(name)(p0_type, p1_type, p2_type) __used; \ + static ret FUNC_INT(name)(p0_type, p1_type, p2_type) __used; \ + WEAK_REF(FUNC_EXP(name), name); \ + WEAK_REF(FUNC_INT(name), __CONCAT(_, name)); \ + typedef ret (*FUNC_TYPE(name))(p0_type, p1_type, p2_type); \ + static ret FUNC_EXP(name)(p0_type p0, p1_type p1, p2_type p2) \ + { \ + FUNC_TYPE(name) func; \ + func = (FUNC_TYPE(name))__thr_jtable[idx][0]; \ + return (func(p0, p1, p2)); \ + } \ + static ret FUNC_INT(name)(p0_type p0, p1_type p1, p2_type p2) \ + { \ + FUNC_TYPE(name) func; \ + func = (FUNC_TYPE(name))__thr_jtable[idx][1]; \ + return (func(p0, p1, p2)); \ + } + +STUB_FUNC1(pthread_cond_broadcast, PJT_COND_BROADCAST, int, void *) +STUB_FUNC1(pthread_cond_destroy, PJT_COND_DESTROY, int, void *) +STUB_FUNC2(pthread_cond_init, PJT_COND_INIT, int, void *, void *) +STUB_FUNC1(pthread_cond_signal, PJT_COND_SIGNAL, int, void *) +STUB_FUNC2(pthread_cond_wait, PJT_COND_WAIT, int, void *, void *) +STUB_FUNC1(pthread_getspecific, PJT_GETSPECIFIC, void *, pthread_key_t) +STUB_FUNC2(pthread_key_create, PJT_KEY_CREATE, int, void *, void *) +STUB_FUNC1(pthread_key_delete, PJT_KEY_DELETE, int, pthread_key_t) +STUB_FUNC(pthread_main_np, PJT_MAIN_NP, int) +STUB_FUNC1(pthread_mutex_destroy, PJT_MUTEX_DESTROY, int, void *) +STUB_FUNC2(pthread_mutex_init, PJT_MUTEX_INIT, int, void *, void *) +STUB_FUNC1(pthread_mutex_lock, PJT_MUTEX_LOCK, int, void *) +STUB_FUNC1(pthread_mutex_trylock, PJT_MUTEX_TRYLOCK, int, void *) +STUB_FUNC1(pthread_mutex_unlock, PJT_MUTEX_UNLOCK, int, void *) +STUB_FUNC1(pthread_mutexattr_destroy, PJT_MUTEXATTR_DESTROY, int, void *) +STUB_FUNC1(pthread_mutexattr_init, PJT_MUTEXATTR_INIT, int, void *) +STUB_FUNC1(pthread_mutexattr_settype, PJT_MUTEXATTR_SETTYPE, int, void *) +STUB_FUNC2(pthread_once, PJT_ONCE, int, void *, void *) +STUB_FUNC1(pthread_rwlock_destroy, PJT_RWLOCK_DESTROY, int, void *) +STUB_FUNC2(pthread_rwlock_init, PJT_RWLOCK_INIT, int, void *, void *) +STUB_FUNC1(pthread_rwlock_rdlock, PJT_RWLOCK_RDLOCK, int, void *) +STUB_FUNC1(pthread_rwlock_tryrdlock, PJT_RWLOCK_TRYRDLOCK, int, void *) +STUB_FUNC1(pthread_rwlock_trywrlock, PJT_RWLOCK_TRYWRLOCK, int, void *) +STUB_FUNC1(pthread_rwlock_unlock, PJT_RWLOCK_UNLOCK, int, void *) +STUB_FUNC1(pthread_rwlock_wrlock, PJT_RWLOCK_WRLOCK, int, void *) +STUB_FUNC(pthread_self, PJT_SELF, pthread_t) +STUB_FUNC2(pthread_setspecific, PJT_SETSPECIFIC, int, pthread_key_t, void *) +STUB_FUNC3(pthread_sigmask, PJT_SIGMASK, int, int, void *, void *) + +static int +stub_zero(void) +{ + return (0); +} + +static void * +stub_null(void) +{ + return (NULL); +} + +static struct pthread * +stub_self(void) +{ + return (&main_thread); +} + +static int +stub_main(void) +{ + return (-1); +} diff --git a/lib/libc/gen/_rand48.c b/lib/libc/gen/_rand48.c new file mode 100644 index 0000000..4dbf0d7 --- /dev/null +++ b/lib/libc/gen/_rand48.c @@ -0,0 +1,49 @@ +/* + * 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 +__FBSDID("$FreeBSD: src/lib/libc/gen/_rand48.c,v 1.2 2002/03/22 21:52:05 obrien Exp $"); + +#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]; + + 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; +} diff --git a/lib/libc/gen/_spinlock_stub.c b/lib/libc/gen/_spinlock_stub.c new file mode 100644 index 0000000..78512b3 --- /dev/null +++ b/lib/libc/gen/_spinlock_stub.c @@ -0,0 +1,82 @@ +/* + * Copyright (c) 1998 John Birrell . + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by John Birrell. + * 4. Neither the name of the author nor the names of any co-contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY JOHN BIRRELL 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 +__FBSDID("$FreeBSD: src/lib/libc/gen/_spinlock_stub.c,v 1.8 2003/03/26 04:02:24 jeff Exp $"); + +#include + +#include "spinlock.h" + +/* + * Declare weak definitions in case the application is not linked + * with libpthread. + */ +__weak_reference(_atomic_lock_stub, _atomic_lock); +__weak_reference(_spinlock_stub, _spinlock); +__weak_reference(_spinlock_stub, _spinunlock); +__weak_reference(_spinlock_debug_stub, _spinlock_debug); + + +/* + * This function is a stub for the _atomic_lock function in libpthread. + */ +long +_atomic_lock_stub(volatile long *lck) +{ + return (0L); +} + + +/* + * This function is a stub for the spinlock function in libpthread. + */ +void +_spinlock_stub(spinlock_t *lck) +{ +} + +/* + * This function is a stub for the spinunlock function in libpthread. + */ +void +_spinunlock_stub(spinlock_t *lck) +{ +} + +/* + * This function is a stub for the debug spinlock function in libpthread. + */ +void +_spinlock_debug_stub(spinlock_t *lck, char *fname, int lineno) +{ +} diff --git a/lib/libc/gen/_thread_init.c b/lib/libc/gen/_thread_init.c new file mode 100644 index 0000000..afcd856 --- /dev/null +++ b/lib/libc/gen/_thread_init.c @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2001 Daniel Eischen + * 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. Neither the name of the author nor the names of any co-contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY DANIEL EISCHEN 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 AUTHOR 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 +__FBSDID("$FreeBSD: src/lib/libc/gen/_thread_init.c,v 1.5 2002/02/01 00:57:29 obrien Exp $"); + +#include + +__weak_reference(_thread_init_stub, _thread_init); +__weak_reference(_thread_autoinit_dummy_decl_stub, _thread_autoinit_dummy_decl); + +int _thread_autoinit_dummy_decl_stub = 0; + +void +_thread_init_stub(void) +{ + /* This is just a stub; there is nothing to do. */ +} diff --git a/lib/libc/gen/alarm.c b/lib/libc/gen/alarm.c new file mode 100644 index 0000000..58cce20 --- /dev/null +++ b/lib/libc/gen/alarm.c @@ -0,0 +1,61 @@ +/* + * Copyright (c) 1983, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)alarm.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/alarm.c,v 1.2 2002/02/01 01:08:47 obrien Exp $"); + +/* + * Backwards compatible alarm. + */ +#include +#include + +unsigned int +alarm(secs) + unsigned int secs; +{ + struct itimerval it, oitv; + struct itimerval *itp = ⁢ + + timerclear(&itp->it_interval); + itp->it_value.tv_sec = secs; + itp->it_value.tv_usec = 0; + if (setitimer(ITIMER_REAL, itp, &oitv) < 0) + return (-1); + if (oitv.it_value.tv_usec) + oitv.it_value.tv_sec++; + return (oitv.it_value.tv_sec); +} diff --git a/lib/libc/gen/arc4random.c b/lib/libc/gen/arc4random.c new file mode 100644 index 0000000..9e79fba --- /dev/null +++ b/lib/libc/gen/arc4random.c @@ -0,0 +1,235 @@ +/* + * Arc4 random number generator for OpenBSD. + * Copyright 1996 David Mazieres . + * + * Modification and redistribution in source and binary forms is + * permitted provided that due credit is given to the author and the + * OpenBSD project (for instance by leaving this copyright notice + * intact). + */ + +/* + * This code is derived from section 17.1 of Applied Cryptography, + * second edition, which describes a stream cipher allegedly + * compatible with RSA Labs "RC4" cipher (the actual description of + * which is a trade secret). The same algorithm is used as a stream + * cipher called "arcfour" in Tatu Ylonen's ssh package. + * + * Here the stream cipher has been modified always to include the time + * when initializing the state. That makes it impossible to + * regenerate the same random sequence twice, so this can't be used + * for encryption, but will generate good random numbers. + * + * RC4 is a registered trademark of RSA Laboratories. + */ + +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/arc4random.c,v 1.10 2004/03/24 14:44:57 green Exp $"); + +#include "namespace.h" +#include +#include +#include +#include +#include +#include + +#include "libc_private.h" +#include "un-namespace.h" + +struct arc4_stream { + u_int8_t i; + u_int8_t j; + u_int8_t s[256]; +}; + +static pthread_mutex_t arc4random_mtx = PTHREAD_MUTEX_INITIALIZER; + +#define RANDOMDEV "/dev/urandom" +#define THREAD_LOCK() \ + do { \ + if (__isthreaded) \ + _pthread_mutex_lock(&arc4random_mtx); \ + } while (0) + +#define THREAD_UNLOCK() \ + do { \ + if (__isthreaded) \ + _pthread_mutex_unlock(&arc4random_mtx); \ + } while (0) + +static struct arc4_stream rs; +static int rs_initialized; +static int rs_stired; + +static inline u_int8_t arc4_getbyte(struct arc4_stream *); +static void arc4_stir(struct arc4_stream *); + +static inline void +arc4_init(as) + struct arc4_stream *as; +{ + int n; + + for (n = 0; n < 256; n++) + as->s[n] = n; + as->i = 0; + as->j = 0; +} + +static inline void +arc4_addrandom(as, dat, datlen) + struct arc4_stream *as; + u_char *dat; + int datlen; +{ + int n; + u_int8_t si; + + as->i--; + for (n = 0; n < 256; n++) { + as->i = (as->i + 1); + si = as->s[as->i]; + as->j = (as->j + si + dat[n % datlen]); + as->s[as->i] = as->s[as->j]; + as->s[as->j] = si; + } +} + +static void +arc4_stir(as) + struct arc4_stream *as; +{ + int fd, n; + struct { + struct timeval tv; + pid_t pid; + u_int8_t rnd[128 - sizeof(struct timeval) - sizeof(pid_t)]; + } rdat; + + gettimeofday(&rdat.tv, NULL); + rdat.pid = getpid(); + fd = _open(RANDOMDEV, O_RDONLY, 0); + if (fd >= 0) { + (void) _read(fd, rdat.rnd, sizeof(rdat.rnd)); + _close(fd); + } + /* fd < 0? Ah, what the heck. We'll just take whatever was on the + * stack... */ + + arc4_addrandom(as, (void *) &rdat, sizeof(rdat)); + + /* + * Throw away the first N bytes of output, as suggested in the + * paper "Weaknesses in the Key Scheduling Algorithm of RC4" + * by Fluher, Mantin, and Shamir. N=1024 is based on + * suggestions in the paper "(Not So) Random Shuffles of RC4" + * by Ilya Mironov. + */ + for (n = 0; n < 1024; n++) + arc4_getbyte(as); +} + +static inline u_int8_t +arc4_getbyte(as) + struct arc4_stream *as; +{ + u_int8_t si, sj; + + as->i = (as->i + 1); + si = as->s[as->i]; + as->j = (as->j + si); + sj = as->s[as->j]; + as->s[as->i] = sj; + as->s[as->j] = si; + + return (as->s[(si + sj) & 0xff]); +} + +static inline uint32_t +arc4_getword(as) + struct arc4_stream *as; +{ + uint32_t val; + + val = arc4_getbyte(as) << 24; + val |= arc4_getbyte(as) << 16; + val |= arc4_getbyte(as) << 8; + val |= arc4_getbyte(as); + + return (val); +} + +static void +arc4_check_init(void) +{ + if (!rs_initialized) { + arc4_init(&rs); + rs_initialized = 1; + } +} + +static void +arc4_check_stir(void) +{ + if (!rs_stired) { + arc4_stir(&rs); + rs_stired = 1; + } +} + +void +arc4random_stir() +{ + THREAD_LOCK(); + arc4_check_init(); + arc4_stir(&rs); + THREAD_UNLOCK(); +} + +void +arc4random_addrandom(dat, datlen) + u_char *dat; + int datlen; +{ + THREAD_LOCK(); + arc4_check_init(); + arc4_check_stir(); + arc4_addrandom(&rs, dat, datlen); + THREAD_UNLOCK(); +} + +uint32_t +arc4random() +{ + uint32_t rnd; + + THREAD_LOCK(); + arc4_check_init(); + arc4_check_stir(); + rnd = arc4_getword(&rs); + THREAD_UNLOCK(); + + return (rnd); +} + +#if 0 +/*-------- Test code for i386 --------*/ +#include +#include +int +main(int argc, char **argv) +{ + const int iter = 1000000; + int i; + pctrval v; + + v = rdtsc(); + for (i = 0; i < iter; i++) + arc4random(); + v = rdtsc() - v; + v /= iter; + + printf("%qd cycles\n", v); +} +#endif diff --git a/lib/libc/gen/assert.c b/lib/libc/gen/assert.c new file mode 100644 index 0000000..f14e39c --- /dev/null +++ b/lib/libc/gen/assert.c @@ -0,0 +1,60 @@ +/*- + * 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. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)assert.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/assert.c,v 1.7 2002/02/01 00:57:29 obrien Exp $"); + +#include +#include +#include + +void +__assert(func, file, line, failedexpr) + const char *func, *file; + int line; + const char *failedexpr; +{ + if (func == NULL) + (void)fprintf(stderr, + "Assertion failed: (%s), file %s, line %d.\n", failedexpr, + file, line); + else + (void)fprintf(stderr, + "Assertion failed: (%s), function %s, file %s, line %d.\n", + failedexpr, func, file, line); + abort(); + /* NOTREACHED */ +} diff --git a/lib/libc/gen/basename.c b/lib/libc/gen/basename.c new file mode 100644 index 0000000..c5da463 --- /dev/null +++ b/lib/libc/gen/basename.c @@ -0,0 +1,84 @@ +/* + * Copyright (c) 1997 Todd C. Miller + * 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 not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED ``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. + */ + +#if 0 +#ifndef lint +static char rcsid[] = "$OpenBSD: basename.c,v 1.4 1999/05/30 17:10:30 espie Exp $"; +#endif /* not lint */ +#endif +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/basename.c,v 1.7 2002/12/30 01:41:14 marcel Exp $"); + +#include +#include +#include +#include +#include + +char * +basename(path) + const char *path; +{ + static char *bname = NULL; + const char *endp, *startp; + + if (bname == NULL) { + bname = (char *)malloc(MAXPATHLEN); + if (bname == NULL) + return(NULL); + } + + /* Empty or NULL string gets treated as "." */ + if (path == NULL || *path == '\0') { + (void)strcpy(bname, "."); + return(bname); + } + + /* Strip trailing slashes */ + endp = path + strlen(path) - 1; + while (endp > path && *endp == '/') + endp--; + + /* All slashes becomes "/" */ + if (endp == path && *endp == '/') { + (void)strcpy(bname, "/"); + return(bname); + } + + /* Find the start of the base */ + startp = endp; + while (startp > path && *(startp - 1) != '/') + startp--; + + if (endp - startp + 2 > MAXPATHLEN) { + errno = ENAMETOOLONG; + return(NULL); + } + (void)strncpy(bname, startp, endp - startp + 1); + bname[endp - startp + 1] = '\0'; + return(bname); +} diff --git a/lib/libc/gen/check_utility_compat.c b/lib/libc/gen/check_utility_compat.c new file mode 100644 index 0000000..716f5b2 --- /dev/null +++ b/lib/libc/gen/check_utility_compat.c @@ -0,0 +1,75 @@ +/* + * Copyright 2002 Massachusetts Institute of Technology + * + * Permission to use, copy, modify, and distribute this software and + * its documentation for any purpose and without fee is hereby + * granted, provided that both the above copyright notice and this + * permission notice appear in all copies, that both the above + * copyright notice and this permission notice appear in all + * supporting documentation, and that the name of M.I.T. not be used + * in advertising or publicity pertaining to distribution of the + * software without specific, written prior permission. M.I.T. makes + * no representations about the suitability of this software for any + * purpose. It is provided "as is" without express or implied + * warranty. + * + * THIS SOFTWARE IS PROVIDED BY M.I.T. ``AS IS''. M.I.T. DISCLAIMS + * ALL EXPRESS OR IMPLIED WARRANTIES WITH REGARD TO THIS SOFTWARE, + * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT + * SHALL M.I.T. 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 +__FBSDID("$FreeBSD: src/lib/libc/gen/check_utility_compat.c,v 1.3 2003/05/01 19:03:13 nectar Exp $"); + +/* + * I din't use "namespace.h" here because none of the relevant utilities + * are threaded, so I'm not concerned about cancellation points or other + * niceties. + */ +#include +#include +#include +#include + +#ifndef LINE_MAX +#define LINE_MAX _POSIX2_LINE_MAX +#endif + +#define _PATH_UTIL_COMPAT "/etc/compat-FreeBSD-4-util" +#define _ENV_UTIL_COMPAT "_COMPAT_FreeBSD_4" + +int +check_utility_compat(const char *utility) +{ + char buf[LINE_MAX]; + char *p, *bp; + int len; + + if ((p = getenv(_ENV_UTIL_COMPAT)) != NULL) { + strlcpy(buf, p, sizeof buf); + } else { + if ((len = readlink(_PATH_UTIL_COMPAT, buf, sizeof buf)) < 0) + return 0; + if (len > sizeof buf) + len = sizeof buf; + buf[len] = '\0'; + } + if (buf[0] == '\0') + return 1; + + bp = buf; + while ((p = strsep(&bp, ",")) != NULL) { + if (strcmp(p, utility) == 0) + return 1; + } + return 0; +} diff --git a/lib/libc/gen/clock.c b/lib/libc/gen/clock.c new file mode 100644 index 0000000..ddfccbe --- /dev/null +++ b/lib/libc/gen/clock.c @@ -0,0 +1,59 @@ +/* + * Copyright (c) 1989, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)clock.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/clock.c,v 1.3 2002/03/22 21:52:05 obrien Exp $"); + +#include +#include +#include + +/* + * Convert usec to clock ticks; could do (usec * CLOCKS_PER_SEC) / 1000000, + * but this would overflow if we switch to nanosec. + */ +#define CONVTCK(r) ((r).tv_sec * CLOCKS_PER_SEC \ + + (r).tv_usec / (1000000 / CLOCKS_PER_SEC)) + +clock_t +clock() +{ + struct rusage ru; + + if (getrusage(RUSAGE_SELF, &ru)) + return ((clock_t) -1); + return((clock_t)((CONVTCK(ru.ru_utime) + CONVTCK(ru.ru_stime)))); +} diff --git a/lib/libc/gen/closedir.c b/lib/libc/gen/closedir.c new file mode 100644 index 0000000..31dedc0 --- /dev/null +++ b/lib/libc/gen/closedir.c @@ -0,0 +1,74 @@ +/* + * Copyright (c) 1983, 1993 + * Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)closedir.c 8.1 (Berkeley) 6/10/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/closedir.c,v 1.10 2002/02/01 00:57:29 obrien Exp $"); + +#include "namespace.h" +#include +#include +#include +#include +#include +#include "un-namespace.h" + +#include "libc_private.h" +#include "telldir.h" + +/* + * close a directory. + */ +int +closedir(dirp) + DIR *dirp; +{ + int fd; + + if (__isthreaded) + _pthread_mutex_lock((pthread_mutex_t *)&dirp->dd_lock); + _seekdir(dirp, dirp->dd_rewind); /* free seekdir storage */ + fd = dirp->dd_fd; + dirp->dd_fd = -1; + dirp->dd_loc = 0; + free((void *)dirp->dd_buf); + _reclaim_telldir(dirp); + if (__isthreaded) { + _pthread_mutex_unlock((pthread_mutex_t *)&dirp->dd_lock); + _pthread_mutex_destroy((pthread_mutex_t *)&dirp->dd_lock); + } + free((void *)dirp); + return(_close(fd)); +} diff --git a/lib/libc/gen/confstr.c b/lib/libc/gen/confstr.c new file mode 100644 index 0000000..7c4699c --- /dev/null +++ b/lib/libc/gen/confstr.c @@ -0,0 +1,125 @@ +/*- + * Copyright (c) 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)confstr.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/confstr.c,v 1.9 2003/05/01 19:03:13 nectar Exp $"); + +#include + +#include +#include +#include +#include +#include + + +size_t +confstr(int name, char *buf, size_t len) +{ + const char *p; + const char UPE[] = "unsupported programming environment"; + + switch (name) { + case _CS_PATH: + p = _PATH_STDPATH; + goto docopy; + + /* + * POSIX/SUS ``Programming Environments'' stuff + * + * We don't support more than one programming environment + * on any platform (yet), so we just return the empty + * string for the environment we are compiled for, + * and the string "unsupported programming environment" + * for anything else. (The Standard says that if these + * values are used on a system which does not support + * this environment -- determined via sysconf() -- then + * the value we return is unspecified. So, we return + * something which will cause obvious breakage.) + */ + case _CS_POSIX_V6_ILP32_OFF32_CFLAGS: + case _CS_POSIX_V6_ILP32_OFF32_LDFLAGS: + case _CS_POSIX_V6_ILP32_OFF32_LIBS: + case _CS_POSIX_V6_LPBIG_OFFBIG_CFLAGS: + case _CS_POSIX_V6_LPBIG_OFFBIG_LDFLAGS: + case _CS_POSIX_V6_LPBIG_OFFBIG_LIBS: + /* + * These two environments are never supported. + */ + p = UPE; + goto docopy; + + case _CS_POSIX_V6_ILP32_OFFBIG_CFLAGS: + case _CS_POSIX_V6_ILP32_OFFBIG_LDFLAGS: + case _CS_POSIX_V6_ILP32_OFFBIG_LIBS: + if (sizeof(long) * CHAR_BIT == 32 && + sizeof(off_t) > sizeof(long)) + p = ""; + else + p = UPE; + goto docopy; + + case _CS_POSIX_V6_LP64_OFF64_CFLAGS: + case _CS_POSIX_V6_LP64_OFF64_LDFLAGS: + case _CS_POSIX_V6_LP64_OFF64_LIBS: + if (sizeof(long) * CHAR_BIT >= 64 && + sizeof(void *) * CHAR_BIT >= 64 && + sizeof(int) * CHAR_BIT >= 32 && + sizeof(off_t) >= sizeof(long)) + p = ""; + else + p = UPE; + goto docopy; + + case _CS_POSIX_V6_WIDTH_RESTRICTED_ENVS: + /* XXX - should have more complete coverage */ + if (sizeof(long) * CHAR_BIT >= 64) + p = "_POSIX_V6_LP64_OFF64"; + else + p = "_POSIX_V6_ILP32_OFFBIG"; + goto docopy; + +docopy: + if (len != 0 && buf != NULL) + strlcpy(buf, p, len); + return (strlen(p) + 1); + + default: + errno = EINVAL; + return (0); + } + /* NOTREACHED */ +} diff --git a/lib/libc/gen/crypt.c b/lib/libc/gen/crypt.c new file mode 100644 index 0000000..f846343 --- /dev/null +++ b/lib/libc/gen/crypt.c @@ -0,0 +1,98 @@ +/* + * Copyright (c) 1989 The Regents of the University of California. + * All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * Tom Truscott. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +/* from static char sccsid[] = "@(#)crypt.c 5.11 (Berkeley) 6/25/91"; */ +#endif /* LIBC_SCCS and not lint */ + +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/crypt.c,v 1.8 2002/10/18 16:24:20 markm Exp $"); + +#include +#include +#include + +/* + * UNIX password, and DES, encryption. + * + * since this is non-exportable, this is just a dummy. if you want real + * encryption, make sure you've got libcrypt.a around. + */ + +__warn_references(des_setkey, + "WARNING! des_setkey(3) not present in the system!"); + +/* ARGSUSED */ +int +des_setkey(const char *key __unused) +{ + fprintf(stderr, "WARNING! des_setkey(3) not present in the system!\n"); + return (0); +} + +__warn_references(des_cipher, + "WARNING! des_cipher(3) not present in the system!"); + +/* ARGSUSED */ +int +des_cipher(const char *in, char *out, long salt __unused, int num_iter __unused) +{ + fprintf(stderr, "WARNING! des_cipher(3) not present in the system!\n"); + bcopy(in, out, 8); + return (0); +} + +__warn_references(setkey, + "WARNING! setkey(3) not present in the system!"); + +/* ARGSUSED */ +int +setkey(const char *key __unused) +{ + fprintf(stderr, "WARNING! setkey(3) not present in the system!\n"); + return (0); +} + +__warn_references(encrypt, + "WARNING! encrypt(3) not present in the system!"); + +/* ARGSUSED */ +int +encrypt(char *block __unused, int flag __unused) +{ + fprintf(stderr, "WARNING! encrypt(3) not present in the system!\n"); + return (0); +} diff --git a/lib/libc/gen/ctermid.c b/lib/libc/gen/ctermid.c new file mode 100644 index 0000000..6b2c682 --- /dev/null +++ b/lib/libc/gen/ctermid.c @@ -0,0 +1,61 @@ +/*- + * Copyright (c) 1990, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)ctermid.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/ctermid.c,v 1.3 2002/03/22 21:52:05 obrien Exp $"); + +#include +#include +#include + +char * +ctermid(char *s) +{ + static char def[] = _PATH_TTY; + + if (s) { + bcopy(def, s, sizeof(_PATH_TTY)); + return(s); + } + return(def); +} + + +char * +ctermid_r(char *s) +{ + return (s) ? ctermid(s) : NULL; +} diff --git a/lib/libc/gen/daemon.c b/lib/libc/gen/daemon.c new file mode 100644 index 0000000..1b9b706 --- /dev/null +++ b/lib/libc/gen/daemon.c @@ -0,0 +1,94 @@ +/*- + * Copyright (c) 1990, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)daemon.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/daemon.c,v 1.6 2003/11/10 22:01:42 ghelmer Exp $"); + +#include "namespace.h" +#include +#include +#include +#include +#include +#include "un-namespace.h" + +int +daemon(nochdir, noclose) + int nochdir, noclose; +{ + struct sigaction osa, sa; + int fd; + pid_t newgrp; + int oerrno; + int osa_ok; + + /* A SIGHUP may be thrown when the parent exits below. */ + sigemptyset(&sa.sa_mask); + sa.sa_handler = SIG_IGN; + sa.sa_flags = 0; + osa_ok = _sigaction(SIGHUP, &sa, &osa); + + switch (fork()) { + case -1: + return (-1); + case 0: + break; + default: + _exit(0); + } + + newgrp = setsid(); + oerrno = errno; + if (osa_ok != -1) + _sigaction(SIGHUP, &osa, NULL); + + if (newgrp == -1) { + errno = oerrno; + return (-1); + } + + if (!nochdir) + (void)chdir("/"); + + if (!noclose && (fd = _open(_PATH_DEVNULL, O_RDWR, 0)) != -1) { + (void)_dup2(fd, STDIN_FILENO); + (void)_dup2(fd, STDOUT_FILENO); + (void)_dup2(fd, STDERR_FILENO); + if (fd > 2) + (void)_close(fd); + } + return (0); +} diff --git a/lib/libc/gen/devname.c b/lib/libc/gen/devname.c new file mode 100644 index 0000000..bf5af30 --- /dev/null +++ b/lib/libc/gen/devname.c @@ -0,0 +1,80 @@ +/* + * Copyright (c) 1989, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)devname.c 8.2 (Berkeley) 4/29/95"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/devname.c,v 1.9 2003/06/20 09:52:27 phk Exp $"); + +#include +#include + +#include +#include +#include +#include +#include +#include + +char * +devname_r(dev_t dev, mode_t type, char *buf, int len) +{ + int i; + size_t j; + char *r; + + if ((type & S_IFMT) == S_IFCHR) { + j = len; + i = sysctlbyname("kern.devname", buf, &j, &dev, sizeof (dev)); + if (i == 0) + return (buf); + } + + /* Finally just format it */ + if (dev == NODEV) + r = "#NODEV"; + else + r = "#%c:%d:0x%x"; + snprintf(buf, len, r, + (type & S_IFMT) == S_IFCHR ? 'C' : 'B', major(dev), minor(dev)); + return (buf); +} + +char * +devname(dev_t dev, mode_t type) +{ + static char buf[SPECNAMELEN + 1]; + + return(devname_r(dev, type, buf, sizeof(buf))); +} diff --git a/lib/libc/gen/dirname.c b/lib/libc/gen/dirname.c new file mode 100644 index 0000000..8a4e1c9 --- /dev/null +++ b/lib/libc/gen/dirname.c @@ -0,0 +1,87 @@ +/* + * Copyright (c) 1997 Todd C. Miller + * 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 not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED ``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. + */ + +#if 0 +#ifndef lint +static char rcsid[] = "$OpenBSD: dirname.c,v 1.4 1999/05/30 17:10:30 espie Exp $"; +#endif /* not lint */ +#endif +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/dirname.c,v 1.7 2002/12/30 01:41:14 marcel Exp $"); + +#include +#include +#include +#include +#include + +char * +dirname(path) + const char *path; +{ + static char *bname = NULL; + const char *endp; + + if (bname == NULL) { + bname = (char *)malloc(MAXPATHLEN); + if (bname == NULL) + return(NULL); + } + + /* Empty or NULL string gets treated as "." */ + if (path == NULL || *path == '\0') { + (void)strcpy(bname, "."); + return(bname); + } + + /* Strip trailing slashes */ + endp = path + strlen(path) - 1; + while (endp > path && *endp == '/') + endp--; + + /* Find the start of the dir */ + while (endp > path && *endp != '/') + endp--; + + /* Either the dir is "/" or there are no slashes */ + if (endp == path) { + (void)strcpy(bname, *endp == '/' ? "/" : "."); + return(bname); + } else { + do { + endp--; + } while (endp > path && *endp == '/'); + } + + if (endp - path + 2 > MAXPATHLEN) { + errno = ENAMETOOLONG; + return(NULL); + } + (void)strncpy(bname, path, endp - path + 1); + bname[endp - path + 1] = '\0'; + return(bname); +} diff --git a/lib/libc/gen/disklabel.c b/lib/libc/gen/disklabel.c new file mode 100644 index 0000000..e7e87cd --- /dev/null +++ b/lib/libc/gen/disklabel.c @@ -0,0 +1,163 @@ +/* + * Copyright (c) 1983, 1987, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)disklabel.c 8.2 (Berkeley) 5/3/95"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/disklabel.c,v 1.16 2002/08/16 15:33:20 bmilekic Exp $"); + +#include +#define DKTYPENAMES +#define FSTYPENAMES +#include + +#include +#include +#include +#include +#include +#include + +static int +gettype(char *t, const char **names) +{ + const char **nm; + + for (nm = names; *nm; nm++) + if (strcasecmp(t, *nm) == 0) + return (nm - names); + if (isdigit((unsigned char)*t)) + return (atoi(t)); + return (0); +} + +struct disklabel * +getdiskbyname(const char *name) +{ + static struct disklabel disk; + struct disklabel *dp = &disk; + struct partition *pp; + char *buf; + char *db_array[2] = { _PATH_DISKTAB, 0 }; + char *cp, *cq; /* can't be register */ + char p, max, psize[3], pbsize[3], + pfsize[3], poffset[3], ptype[3]; + uint32_t *dx; + + if (cgetent(&buf, db_array, (char *) name) < 0) + return NULL; + + bzero((char *)&disk, sizeof(disk)); + /* + * typename + */ + cq = dp->d_typename; + cp = buf; + while (cq < dp->d_typename + sizeof(dp->d_typename) - 1 && + (*cq = *cp) && *cq != '|' && *cq != ':') + cq++, cp++; + *cq = '\0'; + + if (cgetstr(buf, "ty", &cq) > 0 && strcmp(cq, "removable") == 0) + dp->d_flags |= D_REMOVABLE; + else if (cq && strcmp(cq, "simulated") == 0) + dp->d_flags |= D_RAMDISK; + if (cgetcap(buf, "sf", ':') != NULL) + dp->d_flags |= D_BADSECT; + +#define getnumdflt(field, dname, dflt) \ + { long f; (field) = (cgetnum(buf, dname, &f) == -1) ? (dflt) : f; } + + getnumdflt(dp->d_secsize, "se", DEV_BSIZE); + getnumdflt(dp->d_ntracks, "nt", 0); + getnumdflt(dp->d_nsectors, "ns", 0); + getnumdflt(dp->d_ncylinders, "nc", 0); + + if (cgetstr(buf, "dt", &cq) > 0) + dp->d_type = gettype(cq, dktypenames); + else + getnumdflt(dp->d_type, "dt", 0); + getnumdflt(dp->d_secpercyl, "sc", dp->d_nsectors * dp->d_ntracks); + getnumdflt(dp->d_secperunit, "su", dp->d_secpercyl * dp->d_ncylinders); + getnumdflt(dp->d_rpm, "rm", 3600); + getnumdflt(dp->d_interleave, "il", 1); + getnumdflt(dp->d_trackskew, "sk", 0); + getnumdflt(dp->d_cylskew, "cs", 0); + getnumdflt(dp->d_headswitch, "hs", 0); + getnumdflt(dp->d_trkseek, "ts", 0); + getnumdflt(dp->d_bbsize, "bs", BBSIZE); + getnumdflt(dp->d_sbsize, "sb", 0); + strcpy(psize, "px"); + strcpy(pbsize, "bx"); + strcpy(pfsize, "fx"); + strcpy(poffset, "ox"); + strcpy(ptype, "tx"); + max = 'a' - 1; + pp = &dp->d_partitions[0]; + for (p = 'a'; p < 'a' + MAXPARTITIONS; p++, pp++) { + long l; + psize[1] = pbsize[1] = pfsize[1] = poffset[1] = ptype[1] = p; + if (cgetnum(buf, psize, &l) == -1) + pp->p_size = 0; + else { + pp->p_size = l; + cgetnum(buf, poffset, &l); + pp->p_offset = l; + getnumdflt(pp->p_fsize, pfsize, 0); + if (pp->p_fsize) { + long bsize; + + if (cgetnum(buf, pbsize, &bsize) == 0) + pp->p_frag = bsize / pp->p_fsize; + else + pp->p_frag = 8; + } + getnumdflt(pp->p_fstype, ptype, 0); + if (pp->p_fstype == 0 && cgetstr(buf, ptype, &cq) > 0) + pp->p_fstype = gettype(cq, fstypenames); + max = p; + } + } + dp->d_npartitions = max + 1 - 'a'; + (void)strcpy(psize, "dx"); + dx = dp->d_drivedata; + for (p = '0'; p < '0' + NDDATA; p++, dx++) { + psize[1] = p; + getnumdflt(*dx, psize, 0); + } + dp->d_magic = DISKMAGIC; + dp->d_magic2 = DISKMAGIC; + free(buf); + return (dp); +} diff --git a/lib/libc/gen/dlfcn.c b/lib/libc/gen/dlfcn.c new file mode 100644 index 0000000..971b2dc --- /dev/null +++ b/lib/libc/gen/dlfcn.c @@ -0,0 +1,120 @@ +/*- + * Copyright (c) 1998 John D. Polstra + * 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 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 AUTHOR 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 +__FBSDID("$FreeBSD: src/lib/libc/gen/dlfcn.c,v 1.12 2004/03/05 08:10:17 markm Exp $"); + +/* + * Linkage to services provided by the dynamic linker. + */ +#include +#include + +static const char sorry[] = "Service unavailable"; + +/* + * For ELF, the dynamic linker directly resolves references to its + * services to functions inside the dynamic linker itself. These + * weak-symbol stubs are necessary so that "ld" won't complain about + * undefined symbols. The stubs are executed only when the program is + * linked statically, or when a given service isn't implemented in the + * dynamic linker. They must return an error if called, and they must + * be weak symbols so that the dynamic linker can override them. + */ + +#pragma weak _rtld_error +void +_rtld_error(const char *fmt, ...) +{ +} + +#pragma weak dladdr +int +dladdr(const void *addr, Dl_info *dlip) +{ + _rtld_error(sorry); + return 0; +} + +#pragma weak dlclose +int +dlclose(void *handle) +{ + _rtld_error(sorry); + return -1; +} + +#pragma weak dlerror +const char * +dlerror(void) +{ + return sorry; +} + +#pragma weak dllockinit +void +dllockinit(void *context, + void *(*lock_create)(void *context), + void (*rlock_acquire)(void *lock), + void (*wlock_acquire)(void *lock), + void (*lock_release)(void *lock), + void (*lock_destroy)(void *lock), + void (*context_destroy)(void *context)) +{ + if (context_destroy != NULL) + context_destroy(context); +} + +#pragma weak dlopen +void * +dlopen(const char *name, int mode) +{ + _rtld_error(sorry); + return NULL; +} + +#pragma weak dlsym +void * +dlsym(void * __restrict handle, const char * __restrict name) +{ + _rtld_error(sorry); + return NULL; +} + +#pragma weak dlinfo +int +dlinfo(void * __restrict handle, int request, void * __restrict p) +{ + _rtld_error(sorry); + return 0; +} + +#pragma weak _rtld_thread_init +void +_rtld_thread_init(void * li) +{ + _rtld_error(sorry); +} diff --git a/lib/libc/gen/dlfunc.c b/lib/libc/gen/dlfunc.c new file mode 100644 index 0000000..933ea19 --- /dev/null +++ b/lib/libc/gen/dlfunc.c @@ -0,0 +1,30 @@ +/* + * This source file is in the public domain. + * Garrett A. Wollman, 2002-05-28. + * + * $FreeBSD: src/lib/libc/gen/dlfunc.c,v 1.3 2002/09/11 05:05:48 mike Exp $ + */ + +#include + +/* + * Implement the dlfunc() interface, which behaves exactly the same as + * dlsym() except that it returns a function pointer instead of a data + * pointer. This can be used by applications to avoid compiler warnings + * about undefined behavior, and is intended as prior art for future + * POSIX standardization. This function requires that all pointer types + * have the same representation, which is true on all platforms FreeBSD + * runs on, but is not guaranteed by the C standard. + */ +dlfunc_t +dlfunc(void * __restrict handle, const char * __restrict symbol) +{ + union { + void *d; + dlfunc_t f; + } rv; + + rv.d = dlsym(handle, symbol); + return (rv.f); +} + diff --git a/lib/libc/gen/drand48.c b/lib/libc/gen/drand48.c new file mode 100644 index 0000000..92aeb80 --- /dev/null +++ b/lib/libc/gen/drand48.c @@ -0,0 +1,25 @@ +/* + * 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 +__FBSDID("$FreeBSD: src/lib/libc/gen/drand48.c,v 1.2 2002/03/22 21:52:05 obrien Exp $"); + +#include "rand48.h" + +extern unsigned short _rand48_seed[3]; + +double +drand48(void) +{ + return erand48(_rand48_seed); +} diff --git a/lib/libc/gen/erand48.c b/lib/libc/gen/erand48.c new file mode 100644 index 0000000..4b0c1df --- /dev/null +++ b/lib/libc/gen/erand48.c @@ -0,0 +1,26 @@ +/* + * 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 +__FBSDID("$FreeBSD: src/lib/libc/gen/erand48.c,v 1.2 2002/03/22 21:52:05 obrien Exp $"); + +#include "rand48.h" + +double +erand48(unsigned short xseed[3]) +{ + _dorand48(xseed); + return ldexp((double) xseed[0], -48) + + ldexp((double) xseed[1], -32) + + ldexp((double) xseed[2], -16); +} diff --git a/lib/libc/gen/err.c b/lib/libc/gen/err.c new file mode 100644 index 0000000..aa0d306 --- /dev/null +++ b/lib/libc/gen/err.c @@ -0,0 +1,213 @@ +/*- + * Copyright (c) 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)err.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/err.c,v 1.13 2002/03/29 22:43:41 markm Exp $"); + +#include "namespace.h" +#include +#include +#include +#include +#include +#include +#include "un-namespace.h" + +#include "libc_private.h" + +static FILE *err_file; /* file to use for error output */ +static void (*err_exit)(int); + +/* + * This is declared to take a `void *' so that the caller is not required + * to include first. However, it is really a `FILE *', and the + * manual page documents it as such. + */ +void +err_set_file(void *fp) +{ + if (fp) + err_file = fp; + else + err_file = stderr; +} + +void +err_set_exit(void (*ef)(int)) +{ + err_exit = ef; +} + +__weak_reference(_err, err); + +void +_err(int eval, const char *fmt, ...) +{ + va_list ap; + va_start(ap, fmt); + verrc(eval, errno, fmt, ap); + va_end(ap); +} + +void +verr(eval, fmt, ap) + int eval; + const char *fmt; + va_list ap; +{ + verrc(eval, errno, fmt, ap); +} + +void +errc(int eval, int code, const char *fmt, ...) +{ + va_list ap; + va_start(ap, fmt); + verrc(eval, code, fmt, ap); + va_end(ap); +} + +void +verrc(eval, code, fmt, ap) + int eval; + int code; + const char *fmt; + va_list ap; +{ + if (err_file == 0) + err_set_file((FILE *)0); + fprintf(err_file, "%s: ", _getprogname()); + if (fmt != NULL) { + vfprintf(err_file, fmt, ap); + fprintf(err_file, ": "); + } + fprintf(err_file, "%s\n", strerror(code)); + if (err_exit) + err_exit(eval); + exit(eval); +} + +void +errx(int eval, const char *fmt, ...) +{ + va_list ap; + va_start(ap, fmt); + verrx(eval, fmt, ap); + va_end(ap); +} + +void +verrx(eval, fmt, ap) + int eval; + const char *fmt; + va_list ap; +{ + if (err_file == 0) + err_set_file((FILE *)0); + fprintf(err_file, "%s: ", _getprogname()); + if (fmt != NULL) + vfprintf(err_file, fmt, ap); + fprintf(err_file, "\n"); + if (err_exit) + err_exit(eval); + exit(eval); +} + +__weak_reference(_warn, warn); + +void +_warn(const char *fmt, ...) +{ + va_list ap; + va_start(ap, fmt); + vwarnc(errno, fmt, ap); + va_end(ap); +} + +void +vwarn(fmt, ap) + const char *fmt; + va_list ap; +{ + vwarnc(errno, fmt, ap); +} + +void +warnc(int code, const char *fmt, ...) +{ + va_list ap; + va_start(ap, fmt); + vwarnc(code, fmt, ap); + va_end(ap); +} + +void +vwarnc(code, fmt, ap) + int code; + const char *fmt; + va_list ap; +{ + if (err_file == 0) + err_set_file((FILE *)0); + fprintf(err_file, "%s: ", _getprogname()); + if (fmt != NULL) { + vfprintf(err_file, fmt, ap); + fprintf(err_file, ": "); + } + fprintf(err_file, "%s\n", strerror(code)); +} + +void +warnx(const char *fmt, ...) +{ + va_list ap; + va_start(ap, fmt); + vwarnx(fmt, ap); + va_end(ap); +} + +void +vwarnx(fmt, ap) + const char *fmt; + va_list ap; +{ + if (err_file == 0) + err_set_file((FILE *)0); + fprintf(err_file, "%s: ", _getprogname()); + if (fmt != NULL) + vfprintf(err_file, fmt, ap); + fprintf(err_file, "\n"); +} diff --git a/lib/libc/gen/errlst.c b/lib/libc/gen/errlst.c new file mode 100644 index 0000000..28f99d8 --- /dev/null +++ b/lib/libc/gen/errlst.c @@ -0,0 +1,158 @@ +/* + * Copyright (c) 1982, 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. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)errlst.c 8.2 (Berkeley) 11/16/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/errlst.c,v 1.8 2005/04/02 12:33:28 das Exp $"); + +#include + +const char *const sys_errlist[] = { + "Undefined error: 0", /* 0 - ENOERROR */ + "Operation not permitted", /* 1 - EPERM */ + "No such file or directory", /* 2 - ENOENT */ + "No such process", /* 3 - ESRCH */ + "Interrupted system call", /* 4 - EINTR */ + "Input/output error", /* 5 - EIO */ + "Device not configured", /* 6 - ENXIO */ + "Argument list too long", /* 7 - E2BIG */ + "Exec format error", /* 8 - ENOEXEC */ + "Bad file descriptor", /* 9 - EBADF */ + "No child processes", /* 10 - ECHILD */ + "Resource deadlock avoided", /* 11 - EDEADLK */ + "Cannot allocate memory", /* 12 - ENOMEM */ + "Permission denied", /* 13 - EACCES */ + "Bad address", /* 14 - EFAULT */ + "Block device required", /* 15 - ENOTBLK */ + "Device busy", /* 16 - EBUSY */ + "File exists", /* 17 - EEXIST */ + "Cross-device link", /* 18 - EXDEV */ + "Operation not supported by device", /* 19 - ENODEV */ + "Not a directory", /* 20 - ENOTDIR */ + "Is a directory", /* 21 - EISDIR */ + "Invalid argument", /* 22 - EINVAL */ + "Too many open files in system", /* 23 - ENFILE */ + "Too many open files", /* 24 - EMFILE */ + "Inappropriate ioctl for device", /* 25 - ENOTTY */ + "Text file busy", /* 26 - ETXTBSY */ + "File too large", /* 27 - EFBIG */ + "No space left on device", /* 28 - ENOSPC */ + "Illegal seek", /* 29 - ESPIPE */ + "Read-only file system", /* 30 - EROFS */ + "Too many links", /* 31 - EMLINK */ + "Broken pipe", /* 32 - EPIPE */ + +/* math software */ + "Numerical argument out of domain", /* 33 - EDOM */ + "Result too large", /* 34 - ERANGE */ + +/* non-blocking and interrupt i/o */ + "Resource temporarily unavailable", /* 35 - EAGAIN */ + /* 35 - EWOULDBLOCK */ + "Operation now in progress", /* 36 - EINPROGRESS */ + "Operation already in progress", /* 37 - EALREADY */ + +/* ipc/network software -- argument errors */ + "Socket operation on non-socket", /* 38 - ENOTSOCK */ + "Destination address required", /* 39 - EDESTADDRREQ */ + "Message too long", /* 40 - EMSGSIZE */ + "Protocol wrong type for socket", /* 41 - EPROTOTYPE */ + "Protocol not available", /* 42 - ENOPROTOOPT */ + "Protocol not supported", /* 43 - EPROTONOSUPPORT */ + "Socket type not supported", /* 44 - ESOCKTNOSUPPORT */ + "Operation not supported", /* 45 - EOPNOTSUPP */ + "Protocol family not supported", /* 46 - EPFNOSUPPORT */ + /* 47 - EAFNOSUPPORT */ + "Address family not supported by protocol family", + "Address already in use", /* 48 - EADDRINUSE */ + "Can't assign requested address", /* 49 - EADDRNOTAVAIL */ + +/* ipc/network software -- operational errors */ + "Network is down", /* 50 - ENETDOWN */ + "Network is unreachable", /* 51 - ENETUNREACH */ + "Network dropped connection on reset", /* 52 - ENETRESET */ + "Software caused connection abort", /* 53 - ECONNABORTED */ + "Connection reset by peer", /* 54 - ECONNRESET */ + "No buffer space available", /* 55 - ENOBUFS */ + "Socket is already connected", /* 56 - EISCONN */ + "Socket is not connected", /* 57 - ENOTCONN */ + "Can't send after socket shutdown", /* 58 - ESHUTDOWN */ + "Too many references: can't splice", /* 59 - ETOOMANYREFS */ + "Operation timed out", /* 60 - ETIMEDOUT */ + "Connection refused", /* 61 - ECONNREFUSED */ + + "Too many levels of symbolic links", /* 62 - ELOOP */ + "File name too long", /* 63 - ENAMETOOLONG */ + +/* should be rearranged */ + "Host is down", /* 64 - EHOSTDOWN */ + "No route to host", /* 65 - EHOSTUNREACH */ + "Directory not empty", /* 66 - ENOTEMPTY */ + +/* quotas & mush */ + "Too many processes", /* 67 - EPROCLIM */ + "Too many users", /* 68 - EUSERS */ + "Disc quota exceeded", /* 69 - EDQUOT */ + +/* Network File System */ + "Stale NFS file handle", /* 70 - ESTALE */ + "Too many levels of remote in path", /* 71 - EREMOTE */ + "RPC struct is bad", /* 72 - EBADRPC */ + "RPC version wrong", /* 73 - ERPCMISMATCH */ + "RPC prog. not avail", /* 74 - EPROGUNAVAIL */ + "Program version wrong", /* 75 - EPROGMISMATCH */ + "Bad procedure for program", /* 76 - EPROCUNAVAIL */ + + "No locks available", /* 77 - ENOLCK */ + "Function not implemented", /* 78 - ENOSYS */ + "Inappropriate file type or format", /* 79 - EFTYPE */ + "Authentication error", /* 80 - EAUTH */ + "Need authenticator", /* 81 - ENEEDAUTH */ + "Identifier removed", /* 82 - EIDRM */ + "No message of desired type", /* 83 - ENOMSG */ + "Value too large to be stored in data type", /* 84 - EOVERFLOW */ + "Operation canceled", /* 85 - ECANCELED */ + "Illegal byte sequence", /* 86 - EILSEQ */ + "Attribute not found", /* 87 - ENOATTR */ + +/* General */ + "Programming error", /* 88 - EDOOFUS */ + + "Bad message", /* 89 - EBADMSG */ + "Multihop attempted", /* 90 - EMULTIHOP */ + "Link has been severed", /* 91 - ENOLINK */ + "Protocol error", /* 92 - EPROTO */ +}; +const int sys_nerr = sizeof(sys_errlist) / sizeof(sys_errlist[0]); diff --git a/lib/libc/gen/errno.c b/lib/libc/gen/errno.c new file mode 100644 index 0000000..7d98857 --- /dev/null +++ b/lib/libc/gen/errno.c @@ -0,0 +1,30 @@ +/*- + * Copyright (c) 2002 Peter Wemm + * 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 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 AUTHOR 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 +__FBSDID("$FreeBSD: src/lib/libc/gen/errno.c,v 1.1 2002/10/09 08:04:24 peter Exp $"); + +int errno; diff --git a/lib/libc/gen/exec.c b/lib/libc/gen/exec.c new file mode 100644 index 0000000..211eb78 --- /dev/null +++ b/lib/libc/gen/exec.c @@ -0,0 +1,275 @@ +/*- + * Copyright (c) 1991, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)exec.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/exec.c,v 1.22 2003/07/01 12:30:03 bde Exp $"); + +#include "namespace.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include "un-namespace.h" + +extern char **environ; + +int +execl(const char *name, const char *arg, ...) +{ + va_list ap; + char **argv; + int n; + + va_start(ap, arg); + n = 1; + while (va_arg(ap, char *) != NULL) + n++; + va_end(ap); + argv = alloca((n + 1) * sizeof(*argv)); + if (argv == NULL) { + errno = ENOMEM; + return (-1); + } + va_start(ap, arg); + n = 1; + argv[0] = (char *)arg; + while ((argv[n] = va_arg(ap, char *)) != NULL) + n++; + va_end(ap); + return (_execve(name, argv, environ)); +} + +int +execle(const char *name, const char *arg, ...) +{ + va_list ap; + char **argv, **envp; + int n; + + va_start(ap, arg); + n = 1; + while (va_arg(ap, char *) != NULL) + n++; + va_end(ap); + argv = alloca((n + 1) * sizeof(*argv)); + if (argv == NULL) { + errno = ENOMEM; + return (-1); + } + va_start(ap, arg); + n = 1; + argv[0] = (char *)arg; + while ((argv[n] = va_arg(ap, char *)) != NULL) + n++; + envp = va_arg(ap, char **); + va_end(ap); + return (_execve(name, argv, envp)); +} + +int +execlp(const char *name, const char *arg, ...) +{ + va_list ap; + char **argv; + int n; + + va_start(ap, arg); + n = 1; + while (va_arg(ap, char *) != NULL) + n++; + va_end(ap); + argv = alloca((n + 1) * sizeof(*argv)); + if (argv == NULL) { + errno = ENOMEM; + return (-1); + } + va_start(ap, arg); + n = 1; + argv[0] = (char *)arg; + while ((argv[n] = va_arg(ap, char *)) != NULL) + n++; + va_end(ap); + return (execvp(name, argv)); +} + +int +execv(name, argv) + const char *name; + char * const *argv; +{ + (void)_execve(name, argv, environ); + return (-1); +} + +int +execvp(const char *name, char * const *argv) +{ + const char *path; + + /* Get the path we're searching. */ + if ((path = getenv("PATH")) == NULL) + path = _PATH_DEFPATH; + + return (execvP(name, path, argv)); +} + +int +execvP(name, path, argv) + const char *name; + const char *path; + char * const *argv; +{ + char **memp; + int cnt, lp, ln; + char *p; + int eacces, save_errno; + char *bp, *cur, buf[MAXPATHLEN]; + struct stat sb; + + eacces = 0; + + /* If it's an absolute or relative path name, it's easy. */ + if (index(name, '/')) { + bp = (char *)name; + cur = NULL; + goto retry; + } + bp = buf; + + /* If it's an empty path name, fail in the usual POSIX way. */ + if (*name == '\0') { + errno = ENOENT; + return (-1); + } + + cur = alloca(strlen(path) + 1); + if (cur == NULL) { + errno = ENOMEM; + return (-1); + } + strcpy(cur, path); + while ((p = strsep(&cur, ":")) != NULL) { + /* + * It's a SHELL path -- double, leading and trailing colons + * mean the current directory. + */ + if (*p == '\0') { + p = "."; + lp = 1; + } else + lp = strlen(p); + ln = strlen(name); + + /* + * If the path is too long complain. This is a possible + * security issue; given a way to make the path too long + * the user may execute the wrong program. + */ + if (lp + ln + 2 > sizeof(buf)) { + (void)_write(STDERR_FILENO, "execvP: ", 8); + (void)_write(STDERR_FILENO, p, lp); + (void)_write(STDERR_FILENO, ": path too long\n", + 16); + continue; + } + bcopy(p, buf, lp); + buf[lp] = '/'; + bcopy(name, buf + lp + 1, ln); + buf[lp + ln + 1] = '\0'; + +retry: (void)_execve(bp, argv, environ); + switch (errno) { + case E2BIG: + goto done; + case ELOOP: + case ENAMETOOLONG: + case ENOENT: + break; + case ENOEXEC: + for (cnt = 0; argv[cnt]; ++cnt) + ; + memp = alloca((cnt + 2) * sizeof(char *)); + if (memp == NULL) { + /* errno = ENOMEM; XXX override ENOEXEC? */ + goto done; + } + memp[0] = "sh"; + memp[1] = bp; + bcopy(argv + 1, memp + 2, cnt * sizeof(char *)); + (void)_execve(_PATH_BSHELL, memp, environ); + goto done; + case ENOMEM: + goto done; + case ENOTDIR: + break; + case ETXTBSY: + /* + * We used to retry here, but sh(1) doesn't. + */ + goto done; + default: + /* + * EACCES may be for an inaccessible directory or + * a non-executable file. Call stat() to decide + * which. This also handles ambiguities for EFAULT + * and EIO, and undocumented errors like ESTALE. + * We hope that the race for a stat() is unimportant. + */ + save_errno = errno; + if (stat(bp, &sb) != 0) + break; + if (save_errno == EACCES) { + eacces = 1; + continue; + } + errno = save_errno; + goto done; + } + } + if (eacces) + errno = EACCES; + else + errno = ENOENT; +done: + return (-1); +} diff --git a/lib/libc/gen/fmtcheck.c b/lib/libc/gen/fmtcheck.c new file mode 100644 index 0000000..f6673aa --- /dev/null +++ b/lib/libc/gen/fmtcheck.c @@ -0,0 +1,267 @@ +/*- + * Copyright (c) 2000 The NetBSD Foundation, Inc. + * All rights reserved. + * + * This code was contributed to The NetBSD Foundation by Allen Briggs. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the NetBSD + * Foundation, Inc. and its contributors. + * 4. Neither the name of The NetBSD Foundation 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 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. + */ + +/* $NetBSD: fmtcheck.c,v 1.2 2000/11/01 01:17:20 briggs Exp $ */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/fmtcheck.c,v 1.8 2005/03/21 08:00:55 das Exp $"); + +#include +#include +#include + +__weak_reference(__fmtcheck, fmtcheck); + +enum __e_fmtcheck_types { + FMTCHECK_START, + FMTCHECK_SHORT, + FMTCHECK_INT, + FMTCHECK_LONG, + FMTCHECK_QUAD, + FMTCHECK_PTRDIFFT, + FMTCHECK_SIZET, + FMTCHECK_SHORTPOINTER, + FMTCHECK_INTPOINTER, + FMTCHECK_LONGPOINTER, + FMTCHECK_QUADPOINTER, + FMTCHECK_PTRDIFFTPOINTER, + FMTCHECK_SIZETPOINTER, +#ifndef NO_FLOATING_POINT + FMTCHECK_DOUBLE, + FMTCHECK_LONGDOUBLE, +#endif + FMTCHECK_STRING, + FMTCHECK_WIDTH, + FMTCHECK_PRECISION, + FMTCHECK_DONE, + FMTCHECK_UNKNOWN +}; +typedef enum __e_fmtcheck_types EFT; + +#define RETURN(pf,f,r) do { \ + *(pf) = (f); \ + return r; \ + } /*NOTREACHED*/ /*CONSTCOND*/ while (0) + +static EFT +get_next_format_from_precision(const char **pf) +{ + int sh, lg, quad, longdouble, ptrdifft, sizet; + const char *f; + + sh = lg = quad = longdouble = ptrdifft = sizet = 0; + + f = *pf; + switch (*f) { + case 'h': + f++; + sh = 1; + break; + case 'l': + f++; + if (!*f) RETURN(pf,f,FMTCHECK_UNKNOWN); + if (*f == 'l') { + f++; + quad = 1; + } else { + lg = 1; + } + break; + case 'q': + f++; + quad = 1; + break; + case 't': + f++; + ptrdifft = 1; + break; + case 'z': + f++; + sizet = 1; + break; + case 'L': + f++; + longdouble = 1; + break; + default: + break; + } + if (!*f) RETURN(pf,f,FMTCHECK_UNKNOWN); + if (strchr("diouxX", *f)) { + if (longdouble) + RETURN(pf,f,FMTCHECK_UNKNOWN); + if (lg) + RETURN(pf,f,FMTCHECK_LONG); + if (quad) + RETURN(pf,f,FMTCHECK_QUAD); + if (ptrdifft) + RETURN(pf,f,FMTCHECK_PTRDIFFT); + if (sizet) + RETURN(pf,f,FMTCHECK_SIZET); + RETURN(pf,f,FMTCHECK_INT); + } + if (*f == 'n') { + if (longdouble) + RETURN(pf,f,FMTCHECK_UNKNOWN); + if (sh) + RETURN(pf,f,FMTCHECK_SHORTPOINTER); + if (lg) + RETURN(pf,f,FMTCHECK_LONGPOINTER); + if (quad) + RETURN(pf,f,FMTCHECK_QUADPOINTER); + if (ptrdifft) + RETURN(pf,f,FMTCHECK_PTRDIFFTPOINTER); + if (sizet) + RETURN(pf,f,FMTCHECK_SIZETPOINTER); + RETURN(pf,f,FMTCHECK_INTPOINTER); + } + if (strchr("DOU", *f)) { + if (sh + lg + quad + longdouble + ptrdifft + sizet) + RETURN(pf,f,FMTCHECK_UNKNOWN); + RETURN(pf,f,FMTCHECK_LONG); + } +#ifndef NO_FLOATING_POINT + if (strchr("aAeEfFgG", *f)) { + if (longdouble) + RETURN(pf,f,FMTCHECK_LONGDOUBLE); + if (sh + lg + quad + ptrdifft + sizet) + RETURN(pf,f,FMTCHECK_UNKNOWN); + RETURN(pf,f,FMTCHECK_DOUBLE); + } +#endif + if (*f == 'c') { + if (sh + lg + quad + longdouble + ptrdifft + sizet) + RETURN(pf,f,FMTCHECK_UNKNOWN); + RETURN(pf,f,FMTCHECK_INT); + } + if (*f == 's') { + if (sh + lg + quad + longdouble + ptrdifft + sizet) + RETURN(pf,f,FMTCHECK_UNKNOWN); + RETURN(pf,f,FMTCHECK_STRING); + } + if (*f == 'p') { + if (sh + lg + quad + longdouble + ptrdifft + sizet) + RETURN(pf,f,FMTCHECK_UNKNOWN); + RETURN(pf,f,FMTCHECK_LONG); + } + RETURN(pf,f,FMTCHECK_UNKNOWN); + /*NOTREACHED*/ +} + +static EFT +get_next_format_from_width(const char **pf) +{ + const char *f; + + f = *pf; + if (*f == '.') { + f++; + if (*f == '*') { + RETURN(pf,f,FMTCHECK_PRECISION); + } + /* eat any precision (empty is allowed) */ + while (isdigit(*f)) f++; + if (!*f) RETURN(pf,f,FMTCHECK_UNKNOWN); + } + RETURN(pf,f,get_next_format_from_precision(pf)); + /*NOTREACHED*/ +} + +static EFT +get_next_format(const char **pf, EFT eft) +{ + int infmt; + const char *f; + + if (eft == FMTCHECK_WIDTH) { + (*pf)++; + return get_next_format_from_width(pf); + } else if (eft == FMTCHECK_PRECISION) { + (*pf)++; + return get_next_format_from_precision(pf); + } + + f = *pf; + infmt = 0; + while (!infmt) { + f = strchr(f, '%'); + if (f == NULL) + RETURN(pf,f,FMTCHECK_DONE); + f++; + if (!*f) + RETURN(pf,f,FMTCHECK_UNKNOWN); + if (*f != '%') + infmt = 1; + else + f++; + } + + /* Eat any of the flags */ + while (*f && (strchr("#'0- +", *f))) + f++; + + if (*f == '*') { + RETURN(pf,f,FMTCHECK_WIDTH); + } + /* eat any width */ + while (isdigit(*f)) f++; + if (!*f) { + RETURN(pf,f,FMTCHECK_UNKNOWN); + } + + RETURN(pf,f,get_next_format_from_width(pf)); + /*NOTREACHED*/ +} + +__const char * +__fmtcheck(const char *f1, const char *f2) +{ + const char *f1p, *f2p; + EFT f1t, f2t; + + if (!f1) return f2; + + f1p = f1; + f1t = FMTCHECK_START; + f2p = f2; + f2t = FMTCHECK_START; + while ((f1t = get_next_format(&f1p, f1t)) != FMTCHECK_DONE) { + if (f1t == FMTCHECK_UNKNOWN) + return f2; + f2t = get_next_format(&f2p, f2t); + if (f1t != f2t) + return f2; + } + return f1; +} diff --git a/lib/libc/gen/fmtmsg.c b/lib/libc/gen/fmtmsg.c new file mode 100644 index 0000000..4db35dc --- /dev/null +++ b/lib/libc/gen/fmtmsg.c @@ -0,0 +1,220 @@ +/*- + * Copyright (c) 2002 Mike Barcroft + * 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 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 AUTHOR 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 +__FBSDID("$FreeBSD: src/lib/libc/gen/fmtmsg.c,v 1.5 2003/05/01 19:03:13 nectar Exp $"); + +#include +#include +#include +#include + +/* Default value for MSGVERB. */ +#define DFLT_MSGVERB "label:severity:text:action:tag" + +/* Maximum valid size for a MSGVERB. */ +#define MAX_MSGVERB sizeof(DFLT_MSGVERB) + +static char *printfmt(char *, long, const char *, int, const char *, + const char *, const char *); +static char *nextcomp(const char *); +static const char + *sevinfo(int); +static int validmsgverb(const char *); + +static const char *validlist[] = { + "label", "severity", "text", "action", "tag", NULL +}; + +int +fmtmsg(long class, const char *label, int sev, const char *text, + const char *action, const char *tag) +{ + FILE *fp; + char *env, *msgverb, *output; + + if (class & MM_PRINT) { + if ((env = getenv("MSGVERB")) != NULL && *env != '\0' && + strlen(env) <= strlen(DFLT_MSGVERB)) { + if ((msgverb = strdup(env)) == NULL) + return (MM_NOTOK); + else if (validmsgverb(msgverb) == 0) { + free(msgverb); + goto def; + } + } else { +def: + if ((msgverb = strdup(DFLT_MSGVERB)) == NULL) + return (MM_NOTOK); + } + output = printfmt(msgverb, class, label, sev, text, action, + tag); + if (output == NULL) { + free(msgverb); + return (MM_NOTOK); + } + if (*output != '\0') + fprintf(stderr, "%s", output); + free(msgverb); + free(output); + } + if (class & MM_CONSOLE) { + output = printfmt(DFLT_MSGVERB, class, label, sev, text, + action, tag); + if (output == NULL) + return (MM_NOCON); + if (*output != '\0') { + if ((fp = fopen("/dev/console", "a")) == NULL) { + free(output); + return (MM_NOCON); + } + fprintf(fp, "%s", output); + fclose(fp); + } + free(output); + } + return (MM_OK); +} + +#define INSERT_COLON \ + if (*output != '\0') \ + strlcat(output, ": ", size) +#define INSERT_NEWLINE \ + if (*output != '\0') \ + strlcat(output, "\n", size) +#define INSERT_SPACE \ + if (*output != '\0') \ + strlcat(output, " ", size) + +/* + * Returns NULL on memory allocation failure, otherwise returns a pointer to + * a newly malloc()'d output buffer. + */ +static char * +printfmt(char *msgverb, long class, const char *label, int sev, + const char *text, const char *act, const char *tag) +{ + size_t size; + char *comp, *output; + const char *sevname; + + size = 32; + if (label != MM_NULLLBL) + size += strlen(label); + if ((sevname = sevinfo(sev)) != NULL) + size += strlen(sevname); + if (text != MM_NULLTXT) + size += strlen(text); + if (text != MM_NULLACT) + size += strlen(act); + if (tag != MM_NULLTAG) + size += strlen(tag); + + if ((output = malloc(size)) == NULL) + return (NULL); + *output = '\0'; + while ((comp = nextcomp(msgverb)) != NULL) { + if (strcmp(comp, "label") == 0 && label != MM_NULLLBL) { + INSERT_COLON; + strlcat(output, label, size); + } else if (strcmp(comp, "severity") == 0 && sevname != NULL) { + INSERT_COLON; + strlcat(output, sevinfo(sev), size); + } else if (strcmp(comp, "text") == 0 && text != MM_NULLTXT) { + INSERT_COLON; + strlcat(output, text, size); + } else if (strcmp(comp, "action") == 0 && act != MM_NULLACT) { + INSERT_NEWLINE; + strlcat(output, "TO FIX: ", size); + strlcat(output, act, size); + } else if (strcmp(comp, "tag") == 0 && tag != MM_NULLTAG) { + INSERT_SPACE; + strlcat(output, tag, size); + } + } + INSERT_NEWLINE; + return (output); +} + +/* + * Returns a component of a colon delimited string. NULL is returned to + * indicate that there are no remaining components. This function must be + * called until it returns NULL in order for the local state to be cleared. + */ +static char * +nextcomp(const char *msgverb) +{ + static char lmsgverb[MAX_MSGVERB], *state; + char *retval; + + if (*lmsgverb == '\0') { + strlcpy(lmsgverb, msgverb, sizeof(lmsgverb)); + retval = strtok_r(lmsgverb, ":", &state); + } else { + retval = strtok_r(NULL, ":", &state); + } + if (retval == NULL) + *lmsgverb = '\0'; + return (retval); +} + +static const char * +sevinfo(int sev) +{ + + switch (sev) { + case MM_HALT: + return ("HALT"); + case MM_ERROR: + return ("ERROR"); + case MM_WARNING: + return ("WARNING"); + case MM_INFO: + return ("INFO"); + default: + return (NULL); + } +} + +/* + * Returns 1 if the msgverb list is valid, otherwise 0. + */ +static int +validmsgverb(const char *msgverb) +{ + char *msgcomp; + int i, equality; + + equality = 0; + while ((msgcomp = nextcomp(msgverb)) != NULL) { + equality--; + for (i = 0; validlist[i] != NULL; i++) { + if (strcmp(msgcomp, validlist[i]) == 0) + equality++; + } + } + return (!equality); +} diff --git a/lib/libc/gen/fnmatch.c b/lib/libc/gen/fnmatch.c new file mode 100644 index 0000000..814bf22 --- /dev/null +++ b/lib/libc/gen/fnmatch.c @@ -0,0 +1,295 @@ +/* + * Copyright (c) 1989, 1993, 1994 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * Guido van Rossum. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)fnmatch.c 8.2 (Berkeley) 4/16/94"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/fnmatch.c,v 1.17 2005/04/08 21:24:23 stefanf Exp $"); + +/* + * Function fnmatch() as specified in POSIX 1003.2-1992, section B.6. + * Compares a filename or pathname to a pattern. + */ + +/* + * Some notes on multibyte character support: + * 1. Patterns with illegal byte sequences match nothing. + * 2. Illegal byte sequences in the "string" argument are handled by treating + * them as single-byte characters with a value of the first byte of the + * sequence cast to wchar_t. + * 3. Multibyte conversion state objects (mbstate_t) are passed around and + * used for most, but not all, conversions. Further work will be required + * to support state-dependent encodings. + */ + +#include +#include +#include +#include +#include + +#include "collate.h" + +#define EOS '\0' + +#define RANGE_MATCH 1 +#define RANGE_NOMATCH 0 +#define RANGE_ERROR (-1) + +static int rangematch(const char *, wchar_t, int, char **, mbstate_t *); +static int fnmatch1(const char *, const char *, int, mbstate_t, mbstate_t); + +int +fnmatch(pattern, string, flags) + const char *pattern, *string; + int flags; +{ + static const mbstate_t initial; + + return (fnmatch1(pattern, string, flags, initial, initial)); +} + +static int +fnmatch1(pattern, string, flags, patmbs, strmbs) + const char *pattern, *string; + int flags; + mbstate_t patmbs, strmbs; +{ + const char *stringstart; + char *newp; + char c; + wchar_t pc, sc; + size_t pclen, sclen; + + for (stringstart = string;;) { + pclen = mbrtowc(&pc, pattern, MB_LEN_MAX, &patmbs); + if (pclen == (size_t)-1 || pclen == (size_t)-2) + return (FNM_NOMATCH); + pattern += pclen; + sclen = mbrtowc(&sc, string, MB_LEN_MAX, &strmbs); + if (sclen == (size_t)-1 || sclen == (size_t)-2) { + sc = (unsigned char)*string; + sclen = 1; + memset(&strmbs, 0, sizeof(strmbs)); + } + switch (pc) { + case EOS: + if ((flags & FNM_LEADING_DIR) && sc == '/') + return (0); + return (sc == EOS ? 0 : FNM_NOMATCH); + case '?': + if (sc == EOS) + return (FNM_NOMATCH); + if (sc == '/' && (flags & FNM_PATHNAME)) + return (FNM_NOMATCH); + if (sc == '.' && (flags & FNM_PERIOD) && + (string == stringstart || + ((flags & FNM_PATHNAME) && *(string - 1) == '/'))) + return (FNM_NOMATCH); + string += sclen; + break; + case '*': + c = *pattern; + /* Collapse multiple stars. */ + while (c == '*') + c = *++pattern; + + if (sc == '.' && (flags & FNM_PERIOD) && + (string == stringstart || + ((flags & FNM_PATHNAME) && *(string - 1) == '/'))) + return (FNM_NOMATCH); + + /* Optimize for pattern with * at end or before /. */ + if (c == EOS) + if (flags & FNM_PATHNAME) + return ((flags & FNM_LEADING_DIR) || + strchr(string, '/') == NULL ? + 0 : FNM_NOMATCH); + else + return (0); + else if (c == '/' && flags & FNM_PATHNAME) { + if ((string = strchr(string, '/')) == NULL) + return (FNM_NOMATCH); + break; + } + + /* General case, use recursion. */ + while (sc != EOS) { + if (!fnmatch1(pattern, string, + flags & ~FNM_PERIOD, patmbs, strmbs)) + return (0); + sclen = mbrtowc(&sc, string, MB_LEN_MAX, + &strmbs); + if (sclen == (size_t)-1 || + sclen == (size_t)-2) { + sc = (unsigned char)*string; + sclen = 1; + memset(&strmbs, 0, sizeof(strmbs)); + } + if (sc == '/' && flags & FNM_PATHNAME) + break; + string += sclen; + } + return (FNM_NOMATCH); + case '[': + if (sc == EOS) + return (FNM_NOMATCH); + if (sc == '/' && (flags & FNM_PATHNAME)) + return (FNM_NOMATCH); + if (sc == '.' && (flags & FNM_PERIOD) && + (string == stringstart || + ((flags & FNM_PATHNAME) && *(string - 1) == '/'))) + return (FNM_NOMATCH); + + switch (rangematch(pattern, sc, flags, &newp, + &patmbs)) { + case RANGE_ERROR: + goto norm; + case RANGE_MATCH: + pattern = newp; + break; + case RANGE_NOMATCH: + return (FNM_NOMATCH); + } + string += sclen; + break; + case '\\': + if (!(flags & FNM_NOESCAPE)) { + pclen = mbrtowc(&pc, pattern, MB_LEN_MAX, + &patmbs); + if (pclen == (size_t)-1 || pclen == (size_t)-2) + return (FNM_NOMATCH); + if (pclen == 0) + pc = '\\'; + pattern += pclen; + } + /* FALLTHROUGH */ + default: + norm: + if (pc == sc) + ; + else if ((flags & FNM_CASEFOLD) && + (towlower(pc) == towlower(sc))) + ; + else + return (FNM_NOMATCH); + string += sclen; + break; + } + } + /* NOTREACHED */ +} + +static int +rangematch(pattern, test, flags, newp, patmbs) + const char *pattern; + wchar_t test; + int flags; + char **newp; + mbstate_t *patmbs; +{ + int negate, ok; + wchar_t c, c2; + size_t pclen; + const char *origpat; + + /* + * A bracket expression starting with an unquoted circumflex + * character produces unspecified results (IEEE 1003.2-1992, + * 3.13.2). This implementation treats it like '!', for + * consistency with the regular expression syntax. + * J.T. Conklin (conklin@ngai.kaleida.com) + */ + if ( (negate = (*pattern == '!' || *pattern == '^')) ) + ++pattern; + + if (flags & FNM_CASEFOLD) + test = towlower(test); + + /* + * A right bracket shall lose its special meaning and represent + * itself in a bracket expression if it occurs first in the list. + * -- POSIX.2 2.8.3.2 + */ + ok = 0; + origpat = pattern; + for (;;) { + if (*pattern == ']' && pattern > origpat) { + pattern++; + break; + } else if (*pattern == '\0') { + return (RANGE_ERROR); + } else if (*pattern == '/' && (flags & FNM_PATHNAME)) { + return (RANGE_NOMATCH); + } else if (*pattern == '\\' && !(flags & FNM_NOESCAPE)) + pattern++; + pclen = mbrtowc(&c, pattern, MB_LEN_MAX, patmbs); + if (pclen == (size_t)-1 || pclen == (size_t)-2) + return (RANGE_NOMATCH); + pattern += pclen; + + if (flags & FNM_CASEFOLD) + c = towlower(c); + + if (*pattern == '-' && *(pattern + 1) != EOS && + *(pattern + 1) != ']') { + if (*++pattern == '\\' && !(flags & FNM_NOESCAPE)) + if (*pattern != EOS) + pattern++; + pclen = mbrtowc(&c2, pattern, MB_LEN_MAX, patmbs); + if (pclen == (size_t)-1 || pclen == (size_t)-2) + return (RANGE_NOMATCH); + pattern += pclen; + if (c2 == EOS) + return (RANGE_ERROR); + + if (flags & FNM_CASEFOLD) + c2 = towlower(c2); + + if (__collate_load_error ? + c <= test && test <= c2 : + __collate_range_cmp(c, test) <= 0 + && __collate_range_cmp(test, c2) <= 0 + ) + ok = 1; + } else if (c == test) + ok = 1; + } + + *newp = (char *)pattern; + return (ok == negate ? RANGE_NOMATCH : RANGE_MATCH); +} diff --git a/lib/libc/gen/fpclassify.c b/lib/libc/gen/fpclassify.c new file mode 100644 index 0000000..1dafcfc --- /dev/null +++ b/lib/libc/gen/fpclassify.c @@ -0,0 +1,93 @@ +/*- + * Copyright (c) 2003 Mike Barcroft + * Copyright (c) 2002, 2003 David Schultz + * 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 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 AUTHOR 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. + * + * $FreeBSD: src/lib/libc/gen/fpclassify.c,v 1.2 2005/02/06 03:23:31 das Exp $ + */ + +#include + +#include +#include + +#include "fpmath.h" + +int +__fpclassifyf(float f) +{ + union IEEEf2bits u; + + u.f = f; + if (u.bits.exp == 0) { + if (u.bits.man == 0) + return (FP_ZERO); + return (FP_SUBNORMAL); + } + if (u.bits.exp == 255) { + if (u.bits.man == 0) + return (FP_INFINITE); + return (FP_NAN); + } + return (FP_NORMAL); +} + +int +__fpclassifyd(double d) +{ + union IEEEd2bits u; + + u.d = d; + if (u.bits.exp == 0) { + if ((u.bits.manl | u.bits.manh) == 0) + return (FP_ZERO); + return (FP_SUBNORMAL); + } + if (u.bits.exp == 2047) { + if ((u.bits.manl | u.bits.manh) == 0) + return (FP_INFINITE); + return (FP_NAN); + } + return (FP_NORMAL); +} + +int +__fpclassifyl(long double e) +{ + union IEEEl2bits u; + + u.e = e; + if (u.bits.exp == 0) { + if ((u.bits.manl | u.bits.manh) == 0) + return (FP_ZERO); + return (FP_SUBNORMAL); + } + mask_nbit_l(u); /* Mask normalization bit if applicable. */ + if (u.bits.exp == 32767) { + if ((u.bits.manl | u.bits.manh) == 0) + return (FP_INFINITE); + return (FP_NAN); + } + return (FP_NORMAL); +} diff --git a/lib/libc/gen/frexp.c b/lib/libc/gen/frexp.c new file mode 100644 index 0000000..24e1069 --- /dev/null +++ b/lib/libc/gen/frexp.c @@ -0,0 +1,57 @@ +/*- + * Copyright (c) 2004 David Schultz + * 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 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 AUTHOR 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. + * + * $FreeBSD: src/lib/libc/gen/frexp.c,v 1.1 2004/07/18 21:23:39 das Exp $ + */ + +#include + +#include "fpmath.h" + +double +frexp(double d, int *ex) +{ + union IEEEd2bits u; + + u.d = d; + switch (u.bits.exp) { + case 0: /* 0 or subnormal */ + if ((u.bits.manl | u.bits.manh) == 0) { + *ex = 0; + } else { + u.d *= 0x1.0p514; + *ex = u.bits.exp - 1536; + u.bits.exp = 1022; + } + break; + case 2047: /* infinity or NaN; value of *ex is unspecified */ + break; + default: /* normal */ + *ex = u.bits.exp - 1022; + u.bits.exp = 1022; + break; + } + return (u.d); +} diff --git a/lib/libc/gen/fstab.c b/lib/libc/gen/fstab.c new file mode 100644 index 0000000..33fc309 --- /dev/null +++ b/lib/libc/gen/fstab.c @@ -0,0 +1,298 @@ +/* + * Copyright (c) 1980, 1988, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)fstab.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/fstab.c,v 1.14 2003/04/07 12:55:00 mdodd Exp $"); + +#include "namespace.h" +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include "un-namespace.h" + +static FILE *_fs_fp; +static struct fstab _fs_fstab; +static int LineNo = 0; +static char *path_fstab; +static char fstab_path[PATH_MAX]; +static int fsp_set = 0; + +static void error(int); +static void fixfsfile(void); +static int fstabscan(void); + +void +setfstab(const char *file) +{ + + if (file == NULL) { + path_fstab = _PATH_FSTAB; + } else { + strncpy(fstab_path, file, PATH_MAX); + fstab_path[PATH_MAX - 1] = '\0'; + path_fstab = fstab_path; + } + fsp_set = 1; + + return; +} + +const char * +getfstab (void) +{ + + if (fsp_set) + return (path_fstab); + else + return (_PATH_FSTAB); +} + +static void +fixfsfile() +{ + static char buf[sizeof(_PATH_DEV) + MNAMELEN]; + struct stat sb; + struct statfs sf; + + if (strcmp(_fs_fstab.fs_file, "/") != 0) + return; + if (statfs("/", &sf) != 0) + return; + if (sf.f_mntfromname[0] == '/') + buf[0] = '\0'; + else + strcpy(buf, _PATH_DEV); + strcat(buf, sf.f_mntfromname); + if (stat(buf, &sb) != 0 || + (!S_ISBLK(sb.st_mode) && !S_ISCHR(sb.st_mode))) + return; + _fs_fstab.fs_spec = buf; +} + +static int +fstabscan() +{ + char *cp, *p; +#define MAXLINELENGTH 1024 + static char line[MAXLINELENGTH]; + char subline[MAXLINELENGTH]; + int typexx; + + for (;;) { + + if (!(p = fgets(line, sizeof(line), _fs_fp))) + return(0); +/* OLD_STYLE_FSTAB */ + ++LineNo; + if (*line == '#' || *line == '\n') + continue; + if (!strpbrk(p, " \t")) { + _fs_fstab.fs_spec = strsep(&p, ":\n"); + _fs_fstab.fs_file = strsep(&p, ":\n"); + fixfsfile(); + _fs_fstab.fs_type = strsep(&p, ":\n"); + if (_fs_fstab.fs_type) { + if (!strcmp(_fs_fstab.fs_type, FSTAB_XX)) + continue; + _fs_fstab.fs_mntops = _fs_fstab.fs_type; + _fs_fstab.fs_vfstype = + strcmp(_fs_fstab.fs_type, FSTAB_SW) ? + "ufs" : "swap"; + if ((cp = strsep(&p, ":\n")) != NULL) { + _fs_fstab.fs_freq = atoi(cp); + if ((cp = strsep(&p, ":\n")) != NULL) { + _fs_fstab.fs_passno = atoi(cp); + return(1); + } + } + } + goto bad; + } +/* OLD_STYLE_FSTAB */ + while ((cp = strsep(&p, " \t\n")) != NULL && *cp == '\0') + ; + _fs_fstab.fs_spec = cp; + if (!_fs_fstab.fs_spec || *_fs_fstab.fs_spec == '#') + continue; + while ((cp = strsep(&p, " \t\n")) != NULL && *cp == '\0') + ; + _fs_fstab.fs_file = cp; + fixfsfile(); + while ((cp = strsep(&p, " \t\n")) != NULL && *cp == '\0') + ; + _fs_fstab.fs_vfstype = cp; + while ((cp = strsep(&p, " \t\n")) != NULL && *cp == '\0') + ; + _fs_fstab.fs_mntops = cp; + if (_fs_fstab.fs_mntops == NULL) + goto bad; + _fs_fstab.fs_freq = 0; + _fs_fstab.fs_passno = 0; + while ((cp = strsep(&p, " \t\n")) != NULL && *cp == '\0') + ; + if (cp != NULL) { + _fs_fstab.fs_freq = atoi(cp); + while ((cp = strsep(&p, " \t\n")) != NULL && *cp == '\0') + ; + if (cp != NULL) + _fs_fstab.fs_passno = atoi(cp); + } + strcpy(subline, _fs_fstab.fs_mntops); + p = subline; + for (typexx = 0, cp = strsep(&p, ","); cp; + cp = strsep(&p, ",")) { + if (strlen(cp) != 2) + continue; + if (!strcmp(cp, FSTAB_RW)) { + _fs_fstab.fs_type = FSTAB_RW; + break; + } + if (!strcmp(cp, FSTAB_RQ)) { + _fs_fstab.fs_type = FSTAB_RQ; + break; + } + if (!strcmp(cp, FSTAB_RO)) { + _fs_fstab.fs_type = FSTAB_RO; + break; + } + if (!strcmp(cp, FSTAB_SW)) { + _fs_fstab.fs_type = FSTAB_SW; + break; + } + if (!strcmp(cp, FSTAB_XX)) { + _fs_fstab.fs_type = FSTAB_XX; + typexx++; + break; + } + } + if (typexx) + continue; + if (cp != NULL) + return(1); + +bad: /* no way to distinguish between EOF and syntax error */ + error(EFTYPE); + } + /* NOTREACHED */ +} + +struct fstab * +getfsent() +{ + if ((!_fs_fp && !setfsent()) || !fstabscan()) + return((struct fstab *)NULL); + return(&_fs_fstab); +} + +struct fstab * +getfsspec(name) + const char *name; +{ + if (setfsent()) + while (fstabscan()) + if (!strcmp(_fs_fstab.fs_spec, name)) + return(&_fs_fstab); + return((struct fstab *)NULL); +} + +struct fstab * +getfsfile(name) + const char *name; +{ + if (setfsent()) + while (fstabscan()) + if (!strcmp(_fs_fstab.fs_file, name)) + return(&_fs_fstab); + return((struct fstab *)NULL); +} + +int +setfsent() +{ + if (_fs_fp) { + rewind(_fs_fp); + LineNo = 0; + return(1); + } + if (fsp_set == 0) { + if (issetugid()) + setfstab(NULL); + else + setfstab(getenv("PATH_FSTAB")); + } + if ((_fs_fp = fopen(path_fstab, "r")) != NULL) { + LineNo = 0; + return(1); + } + error(errno); + return(0); +} + +void +endfsent() +{ + if (_fs_fp) { + (void)fclose(_fs_fp); + _fs_fp = NULL; + } + + fsp_set = 0; +} + +static void +error(err) + int err; +{ + char *p; + char num[30]; + + (void)_write(STDERR_FILENO, "fstab: ", 7); + (void)_write(STDERR_FILENO, path_fstab, strlen(path_fstab)); + (void)_write(STDERR_FILENO, ":", 1); + sprintf(num, "%d: ", LineNo); + (void)_write(STDERR_FILENO, num, strlen(num)); + p = strerror(err); + (void)_write(STDERR_FILENO, p, strlen(p)); + (void)_write(STDERR_FILENO, "\n", 1); +} diff --git a/lib/libc/gen/ftok.c b/lib/libc/gen/ftok.c new file mode 100644 index 0000000..6c7157a --- /dev/null +++ b/lib/libc/gen/ftok.c @@ -0,0 +1,46 @@ +/* + * Copyright (c) 1994 SigmaSoft, Th. Lockert + * 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 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. + */ + +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/ftok.c,v 1.7 2004/06/01 06:53:07 tjr Exp $"); + +#include +#include +#include + +key_t +ftok(path, id) + const char *path; + int id; +{ + struct stat st; + + if (stat(path, &st) < 0) + return (key_t)-1; + + return (key_t) (id << 24 | (st.st_dev & 0xff) << 16 | (st.st_ino & 0xffff)); +} diff --git a/lib/libc/gen/fts.c b/lib/libc/gen/fts.c new file mode 100644 index 0000000..28bf177 --- /dev/null +++ b/lib/libc/gen/fts.c @@ -0,0 +1,1226 @@ +/*- + * Copyright (c) 1990, 1993, 1994 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * $OpenBSD: fts.c,v 1.22 1999/10/03 19:22:22 millert Exp $ + */ + +#if 0 +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)fts.c 8.6 (Berkeley) 8/14/94"; +#endif /* LIBC_SCCS and not lint */ +#endif + +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/fts.c,v 1.27 2004/06/08 06:23:23 das Exp $"); + +#include "namespace.h" +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include "un-namespace.h" + +static FTSENT *fts_alloc(FTS *, char *, int); +static FTSENT *fts_build(FTS *, int); +static void fts_lfree(FTSENT *); +static void fts_load(FTS *, FTSENT *); +static size_t fts_maxarglen(char * const *); +static void fts_padjust(FTS *, FTSENT *); +static int fts_palloc(FTS *, size_t); +static FTSENT *fts_sort(FTS *, FTSENT *, int); +static u_short fts_stat(FTS *, FTSENT *, int); +static int fts_safe_changedir(FTS *, FTSENT *, int, char *); +static int fts_ufslinks(FTS *, const FTSENT *); + +#define ISDOT(a) (a[0] == '.' && (!a[1] || (a[1] == '.' && !a[2]))) + +#define CLR(opt) (sp->fts_options &= ~(opt)) +#define ISSET(opt) (sp->fts_options & (opt)) +#define SET(opt) (sp->fts_options |= (opt)) + +#define FCHDIR(sp, fd) (!ISSET(FTS_NOCHDIR) && fchdir(fd)) + +/* fts_build flags */ +#define BCHILD 1 /* fts_children */ +#define BNAMES 2 /* fts_children, names only */ +#define BREAD 3 /* fts_read */ + +/* + * Internal representation of an FTS, including extra implementation + * details. The FTS returned from fts_open points to this structure's + * ftsp_fts member (and can be cast to an _fts_private as required) + */ +struct _fts_private { + FTS ftsp_fts; + struct statfs ftsp_statfs; + dev_t ftsp_dev; + int ftsp_linksreliable; +}; + +/* + * The "FTS_NOSTAT" option can avoid a lot of calls to stat(2) if it + * knows that a directory could not possibly have subdirectories. This + * is decided by looking at the link count: a subdirectory would + * increment its parent's link count by virtue of its own ".." entry. + * This assumption only holds for UFS-like filesystems that implement + * links and directories this way, so we must punt for others. + */ + +static const char *ufslike_filesystems[] = { + "ufs", + "nfs", + "nfs4", + "ext2fs", + 0 +}; + +FTS * +fts_open(argv, options, compar) + char * const *argv; + int options; + int (*compar)(const FTSENT * const *, const FTSENT * const *); +{ + struct _fts_private *priv; + FTS *sp; + FTSENT *p, *root; + int nitems; + FTSENT *parent, *tmp; + int len; + + /* Options check. */ + if (options & ~FTS_OPTIONMASK) { + errno = EINVAL; + return (NULL); + } + + /* Allocate/initialize the stream. */ + if ((priv = malloc(sizeof(*priv))) == NULL) + return (NULL); + memset(priv, 0, sizeof(*priv)); + sp = &priv->ftsp_fts; + sp->fts_compar = compar; + sp->fts_options = options; + + /* Shush, GCC. */ + tmp = NULL; + + /* Logical walks turn on NOCHDIR; symbolic links are too hard. */ + if (ISSET(FTS_LOGICAL)) + SET(FTS_NOCHDIR); + + /* + * Start out with 1K of path space, and enough, in any case, + * to hold the user's paths. + */ + if (fts_palloc(sp, MAX(fts_maxarglen(argv), MAXPATHLEN))) + goto mem1; + + /* Allocate/initialize root's parent. */ + if ((parent = fts_alloc(sp, "", 0)) == NULL) + goto mem2; + parent->fts_level = FTS_ROOTPARENTLEVEL; + + /* Allocate/initialize root(s). */ + for (root = NULL, nitems = 0; *argv != NULL; ++argv, ++nitems) { + /* Don't allow zero-length paths. */ + if ((len = strlen(*argv)) == 0) { + errno = ENOENT; + goto mem3; + } + + p = fts_alloc(sp, *argv, len); + p->fts_level = FTS_ROOTLEVEL; + p->fts_parent = parent; + p->fts_accpath = p->fts_name; + p->fts_info = fts_stat(sp, p, ISSET(FTS_COMFOLLOW)); + + /* Command-line "." and ".." are real directories. */ + if (p->fts_info == FTS_DOT) + p->fts_info = FTS_D; + + /* + * If comparison routine supplied, traverse in sorted + * order; otherwise traverse in the order specified. + */ + if (compar) { + p->fts_link = root; + root = p; + } else { + p->fts_link = NULL; + if (root == NULL) + tmp = root = p; + else { + tmp->fts_link = p; + tmp = p; + } + } + } + if (compar && nitems > 1) + root = fts_sort(sp, root, nitems); + + /* + * Allocate a dummy pointer and make fts_read think that we've just + * finished the node before the root(s); set p->fts_info to FTS_INIT + * so that everything about the "current" node is ignored. + */ + if ((sp->fts_cur = fts_alloc(sp, "", 0)) == NULL) + goto mem3; + sp->fts_cur->fts_link = root; + sp->fts_cur->fts_info = FTS_INIT; + + /* + * If using chdir(2), grab a file descriptor pointing to dot to ensure + * that we can get back here; this could be avoided for some paths, + * but almost certainly not worth the effort. Slashes, symbolic links, + * and ".." are all fairly nasty problems. Note, if we can't get the + * descriptor we run anyway, just more slowly. + */ + if (!ISSET(FTS_NOCHDIR) && (sp->fts_rfd = _open(".", O_RDONLY, 0)) < 0) + SET(FTS_NOCHDIR); + + return (sp); + +mem3: fts_lfree(root); + free(parent); +mem2: free(sp->fts_path); +mem1: free(sp); + return (NULL); +} + +static void +fts_load(sp, p) + FTS *sp; + FTSENT *p; +{ + int len; + char *cp; + + /* + * Load the stream structure for the next traversal. Since we don't + * actually enter the directory until after the preorder visit, set + * the fts_accpath field specially so the chdir gets done to the right + * place and the user can access the first node. From fts_open it's + * known that the path will fit. + */ + len = p->fts_pathlen = p->fts_namelen; + memmove(sp->fts_path, p->fts_name, len + 1); + if ((cp = strrchr(p->fts_name, '/')) && (cp != p->fts_name || cp[1])) { + len = strlen(++cp); + memmove(p->fts_name, cp, len + 1); + p->fts_namelen = len; + } + p->fts_accpath = p->fts_path = sp->fts_path; + sp->fts_dev = p->fts_dev; +} + +int +fts_close(sp) + FTS *sp; +{ + FTSENT *freep, *p; + int saved_errno; + + /* + * This still works if we haven't read anything -- the dummy structure + * points to the root list, so we step through to the end of the root + * list which has a valid parent pointer. + */ + if (sp->fts_cur) { + for (p = sp->fts_cur; p->fts_level >= FTS_ROOTLEVEL;) { + freep = p; + p = p->fts_link != NULL ? p->fts_link : p->fts_parent; + free(freep); + } + free(p); + } + + /* Free up child linked list, sort array, path buffer. */ + if (sp->fts_child) + fts_lfree(sp->fts_child); + if (sp->fts_array) + free(sp->fts_array); + free(sp->fts_path); + + /* Return to original directory, save errno if necessary. */ + if (!ISSET(FTS_NOCHDIR)) { + saved_errno = fchdir(sp->fts_rfd) ? errno : 0; + (void)_close(sp->fts_rfd); + + /* Set errno and return. */ + if (saved_errno != 0) { + /* Free up the stream pointer. */ + free(sp); + errno = saved_errno; + return (-1); + } + } + + /* Free up the stream pointer. */ + free(sp); + return (0); +} + +/* + * Special case of "/" at the end of the path so that slashes aren't + * appended which would cause paths to be written as "....//foo". + */ +#define NAPPEND(p) \ + (p->fts_path[p->fts_pathlen - 1] == '/' \ + ? p->fts_pathlen - 1 : p->fts_pathlen) + +FTSENT * +fts_read(sp) + FTS *sp; +{ + FTSENT *p, *tmp; + int instr; + char *t; + int saved_errno; + + /* If finished or unrecoverable error, return NULL. */ + if (sp->fts_cur == NULL || ISSET(FTS_STOP)) + return (NULL); + + /* Set current node pointer. */ + p = sp->fts_cur; + + /* Save and zero out user instructions. */ + instr = p->fts_instr; + p->fts_instr = FTS_NOINSTR; + + /* Any type of file may be re-visited; re-stat and re-turn. */ + if (instr == FTS_AGAIN) { + p->fts_info = fts_stat(sp, p, 0); + return (p); + } + + /* + * Following a symlink -- SLNONE test allows application to see + * SLNONE and recover. If indirecting through a symlink, have + * keep a pointer to current location. If unable to get that + * pointer, follow fails. + */ + if (instr == FTS_FOLLOW && + (p->fts_info == FTS_SL || p->fts_info == FTS_SLNONE)) { + p->fts_info = fts_stat(sp, p, 1); + if (p->fts_info == FTS_D && !ISSET(FTS_NOCHDIR)) { + if ((p->fts_symfd = _open(".", O_RDONLY, 0)) < 0) { + p->fts_errno = errno; + p->fts_info = FTS_ERR; + } else + p->fts_flags |= FTS_SYMFOLLOW; + } + return (p); + } + + /* Directory in pre-order. */ + if (p->fts_info == FTS_D) { + /* If skipped or crossed mount point, do post-order visit. */ + if (instr == FTS_SKIP || + (ISSET(FTS_XDEV) && p->fts_dev != sp->fts_dev)) { + if (p->fts_flags & FTS_SYMFOLLOW) + (void)_close(p->fts_symfd); + if (sp->fts_child) { + fts_lfree(sp->fts_child); + sp->fts_child = NULL; + } + p->fts_info = FTS_DP; + return (p); + } + + /* Rebuild if only read the names and now traversing. */ + if (sp->fts_child != NULL && ISSET(FTS_NAMEONLY)) { + CLR(FTS_NAMEONLY); + fts_lfree(sp->fts_child); + sp->fts_child = NULL; + } + + /* + * Cd to the subdirectory. + * + * If have already read and now fail to chdir, whack the list + * to make the names come out right, and set the parent errno + * so the application will eventually get an error condition. + * Set the FTS_DONTCHDIR flag so that when we logically change + * directories back to the parent we don't do a chdir. + * + * If haven't read do so. If the read fails, fts_build sets + * FTS_STOP or the fts_info field of the node. + */ + if (sp->fts_child != NULL) { + if (fts_safe_changedir(sp, p, -1, p->fts_accpath)) { + p->fts_errno = errno; + p->fts_flags |= FTS_DONTCHDIR; + for (p = sp->fts_child; p != NULL; + p = p->fts_link) + p->fts_accpath = + p->fts_parent->fts_accpath; + } + } else if ((sp->fts_child = fts_build(sp, BREAD)) == NULL) { + if (ISSET(FTS_STOP)) + return (NULL); + return (p); + } + p = sp->fts_child; + sp->fts_child = NULL; + goto name; + } + + /* Move to the next node on this level. */ +next: tmp = p; + if ((p = p->fts_link) != NULL) { + free(tmp); + + /* + * If reached the top, return to the original directory (or + * the root of the tree), and load the paths for the next root. + */ + if (p->fts_level == FTS_ROOTLEVEL) { + if (FCHDIR(sp, sp->fts_rfd)) { + SET(FTS_STOP); + return (NULL); + } + fts_load(sp, p); + return (sp->fts_cur = p); + } + + /* + * User may have called fts_set on the node. If skipped, + * ignore. If followed, get a file descriptor so we can + * get back if necessary. + */ + if (p->fts_instr == FTS_SKIP) + goto next; + if (p->fts_instr == FTS_FOLLOW) { + p->fts_info = fts_stat(sp, p, 1); + if (p->fts_info == FTS_D && !ISSET(FTS_NOCHDIR)) { + if ((p->fts_symfd = + _open(".", O_RDONLY, 0)) < 0) { + p->fts_errno = errno; + p->fts_info = FTS_ERR; + } else + p->fts_flags |= FTS_SYMFOLLOW; + } + p->fts_instr = FTS_NOINSTR; + } + +name: t = sp->fts_path + NAPPEND(p->fts_parent); + *t++ = '/'; + memmove(t, p->fts_name, p->fts_namelen + 1); + return (sp->fts_cur = p); + } + + /* Move up to the parent node. */ + p = tmp->fts_parent; + free(tmp); + + if (p->fts_level == FTS_ROOTPARENTLEVEL) { + /* + * Done; free everything up and set errno to 0 so the user + * can distinguish between error and EOF. + */ + free(p); + errno = 0; + return (sp->fts_cur = NULL); + } + + /* NUL terminate the pathname. */ + sp->fts_path[p->fts_pathlen] = '\0'; + + /* + * Return to the parent directory. If at a root node or came through + * a symlink, go back through the file descriptor. Otherwise, cd up + * one directory. + */ + if (p->fts_level == FTS_ROOTLEVEL) { + if (FCHDIR(sp, sp->fts_rfd)) { + SET(FTS_STOP); + return (NULL); + } + } else if (p->fts_flags & FTS_SYMFOLLOW) { + if (FCHDIR(sp, p->fts_symfd)) { + saved_errno = errno; + (void)_close(p->fts_symfd); + errno = saved_errno; + SET(FTS_STOP); + return (NULL); + } + (void)_close(p->fts_symfd); + } else if (!(p->fts_flags & FTS_DONTCHDIR) && + fts_safe_changedir(sp, p->fts_parent, -1, "..")) { + SET(FTS_STOP); + return (NULL); + } + p->fts_info = p->fts_errno ? FTS_ERR : FTS_DP; + return (sp->fts_cur = p); +} + +/* + * Fts_set takes the stream as an argument although it's not used in this + * implementation; it would be necessary if anyone wanted to add global + * semantics to fts using fts_set. An error return is allowed for similar + * reasons. + */ +/* ARGSUSED */ +int +fts_set(sp, p, instr) + FTS *sp; + FTSENT *p; + int instr; +{ + if (instr != 0 && instr != FTS_AGAIN && instr != FTS_FOLLOW && + instr != FTS_NOINSTR && instr != FTS_SKIP) { + errno = EINVAL; + return (1); + } + p->fts_instr = instr; + return (0); +} + +FTSENT * +fts_children(sp, instr) + FTS *sp; + int instr; +{ + FTSENT *p; + int fd; + + if (instr != 0 && instr != FTS_NAMEONLY) { + errno = EINVAL; + return (NULL); + } + + /* Set current node pointer. */ + p = sp->fts_cur; + + /* + * Errno set to 0 so user can distinguish empty directory from + * an error. + */ + errno = 0; + + /* Fatal errors stop here. */ + if (ISSET(FTS_STOP)) + return (NULL); + + /* Return logical hierarchy of user's arguments. */ + if (p->fts_info == FTS_INIT) + return (p->fts_link); + + /* + * If not a directory being visited in pre-order, stop here. Could + * allow FTS_DNR, assuming the user has fixed the problem, but the + * same effect is available with FTS_AGAIN. + */ + if (p->fts_info != FTS_D /* && p->fts_info != FTS_DNR */) + return (NULL); + + /* Free up any previous child list. */ + if (sp->fts_child != NULL) + fts_lfree(sp->fts_child); + + if (instr == FTS_NAMEONLY) { + SET(FTS_NAMEONLY); + instr = BNAMES; + } else + instr = BCHILD; + + /* + * If using chdir on a relative path and called BEFORE fts_read does + * its chdir to the root of a traversal, we can lose -- we need to + * chdir into the subdirectory, and we don't know where the current + * directory is, so we can't get back so that the upcoming chdir by + * fts_read will work. + */ + if (p->fts_level != FTS_ROOTLEVEL || p->fts_accpath[0] == '/' || + ISSET(FTS_NOCHDIR)) + return (sp->fts_child = fts_build(sp, instr)); + + if ((fd = _open(".", O_RDONLY, 0)) < 0) + return (NULL); + sp->fts_child = fts_build(sp, instr); + if (fchdir(fd)) + return (NULL); + (void)_close(fd); + return (sp->fts_child); +} + +#ifndef fts_get_clientptr +#error "fts_get_clientptr not defined" +#endif + +void * +(fts_get_clientptr)(FTS *sp) +{ + + return (fts_get_clientptr(sp)); +} + +#ifndef fts_get_stream +#error "fts_get_stream not defined" +#endif + +FTS * +(fts_get_stream)(FTSENT *p) +{ + return (fts_get_stream(p)); +} + +void +fts_set_clientptr(FTS *sp, void *clientptr) +{ + + sp->fts_clientptr = clientptr; +} + +/* + * This is the tricky part -- do not casually change *anything* in here. The + * idea is to build the linked list of entries that are used by fts_children + * and fts_read. There are lots of special cases. + * + * The real slowdown in walking the tree is the stat calls. If FTS_NOSTAT is + * set and it's a physical walk (so that symbolic links can't be directories), + * we can do things quickly. First, if it's a 4.4BSD file system, the type + * of the file is in the directory entry. Otherwise, we assume that the number + * of subdirectories in a node is equal to the number of links to the parent. + * The former skips all stat calls. The latter skips stat calls in any leaf + * directories and for any files after the subdirectories in the directory have + * been found, cutting the stat calls by about 2/3. + */ +static FTSENT * +fts_build(sp, type) + FTS *sp; + int type; +{ + struct dirent *dp; + FTSENT *p, *head; + int nitems; + FTSENT *cur, *tail; + DIR *dirp; + void *oldaddr; + size_t dnamlen; + int cderrno, descend, len, level, maxlen, nlinks, oflag, saved_errno, + nostat, doadjust; + char *cp; + + /* Set current node pointer. */ + cur = sp->fts_cur; + + /* + * Open the directory for reading. If this fails, we're done. + * If being called from fts_read, set the fts_info field. + */ +#ifdef FTS_WHITEOUT + if (ISSET(FTS_WHITEOUT)) + oflag = DTF_NODUP | DTF_REWIND; + else + oflag = DTF_HIDEW | DTF_NODUP | DTF_REWIND; +#else +#define __opendir2(path, flag) opendir(path) +#endif + if ((dirp = __opendir2(cur->fts_accpath, oflag)) == NULL) { + if (type == BREAD) { + cur->fts_info = FTS_DNR; + cur->fts_errno = errno; + } + return (NULL); + } + + /* + * Nlinks is the number of possible entries of type directory in the + * directory if we're cheating on stat calls, 0 if we're not doing + * any stat calls at all, -1 if we're doing stats on everything. + */ + if (type == BNAMES) { + nlinks = 0; + /* Be quiet about nostat, GCC. */ + nostat = 0; + } else if (ISSET(FTS_NOSTAT) && ISSET(FTS_PHYSICAL)) { + if (fts_ufslinks(sp, cur)) + nlinks = cur->fts_nlink - (ISSET(FTS_SEEDOT) ? 0 : 2); + else + nlinks = -1; + nostat = 1; + } else { + nlinks = -1; + nostat = 0; + } + +#ifdef notdef + (void)printf("nlinks == %d (cur: %d)\n", nlinks, cur->fts_nlink); + (void)printf("NOSTAT %d PHYSICAL %d SEEDOT %d\n", + ISSET(FTS_NOSTAT), ISSET(FTS_PHYSICAL), ISSET(FTS_SEEDOT)); +#endif + /* + * If we're going to need to stat anything or we want to descend + * and stay in the directory, chdir. If this fails we keep going, + * but set a flag so we don't chdir after the post-order visit. + * We won't be able to stat anything, but we can still return the + * names themselves. Note, that since fts_read won't be able to + * chdir into the directory, it will have to return different path + * names than before, i.e. "a/b" instead of "b". Since the node + * has already been visited in pre-order, have to wait until the + * post-order visit to return the error. There is a special case + * here, if there was nothing to stat then it's not an error to + * not be able to stat. This is all fairly nasty. If a program + * needed sorted entries or stat information, they had better be + * checking FTS_NS on the returned nodes. + */ + cderrno = 0; + if (nlinks || type == BREAD) { + if (fts_safe_changedir(sp, cur, dirfd(dirp), NULL)) { + if (nlinks && type == BREAD) + cur->fts_errno = errno; + cur->fts_flags |= FTS_DONTCHDIR; + descend = 0; + cderrno = errno; + } else + descend = 1; + } else + descend = 0; + + /* + * Figure out the max file name length that can be stored in the + * current path -- the inner loop allocates more path as necessary. + * We really wouldn't have to do the maxlen calculations here, we + * could do them in fts_read before returning the path, but it's a + * lot easier here since the length is part of the dirent structure. + * + * If not changing directories set a pointer so that can just append + * each new name into the path. + */ + len = NAPPEND(cur); + if (ISSET(FTS_NOCHDIR)) { + cp = sp->fts_path + len; + *cp++ = '/'; + } else { + /* GCC, you're too verbose. */ + cp = NULL; + } + len++; + maxlen = sp->fts_pathlen - len; + + level = cur->fts_level + 1; + + /* Read the directory, attaching each entry to the `link' pointer. */ + doadjust = 0; + for (head = tail = NULL, nitems = 0; dirp && (dp = readdir(dirp));) { + dnamlen = dp->d_namlen; + if (!ISSET(FTS_SEEDOT) && ISDOT(dp->d_name)) + continue; + + if ((p = fts_alloc(sp, dp->d_name, (int)dnamlen)) == NULL) + goto mem1; + if (dnamlen >= maxlen) { /* include space for NUL */ + oldaddr = sp->fts_path; + if (fts_palloc(sp, dnamlen + len + 1)) { + /* + * No more memory for path or structures. Save + * errno, free up the current structure and the + * structures already allocated. + */ +mem1: saved_errno = errno; + if (p) + free(p); + fts_lfree(head); + (void)closedir(dirp); + cur->fts_info = FTS_ERR; + SET(FTS_STOP); + errno = saved_errno; + return (NULL); + } + /* Did realloc() change the pointer? */ + if (oldaddr != sp->fts_path) { + doadjust = 1; + if (ISSET(FTS_NOCHDIR)) + cp = sp->fts_path + len; + } + maxlen = sp->fts_pathlen - len; + } + + if (len + dnamlen >= USHRT_MAX) { + /* + * In an FTSENT, fts_pathlen is a u_short so it is + * possible to wraparound here. If we do, free up + * the current structure and the structures already + * allocated, then error out with ENAMETOOLONG. + */ + free(p); + fts_lfree(head); + (void)closedir(dirp); + cur->fts_info = FTS_ERR; + SET(FTS_STOP); + errno = ENAMETOOLONG; + return (NULL); + } + p->fts_level = level; + p->fts_parent = sp->fts_cur; + p->fts_pathlen = len + dnamlen; + +#ifdef FTS_WHITEOUT + if (dp->d_type == DT_WHT) + p->fts_flags |= FTS_ISW; +#endif + + if (cderrno) { + if (nlinks) { + p->fts_info = FTS_NS; + p->fts_errno = cderrno; + } else + p->fts_info = FTS_NSOK; + p->fts_accpath = cur->fts_accpath; + } else if (nlinks == 0 +#ifdef DT_DIR + || (nostat && + dp->d_type != DT_DIR && dp->d_type != DT_UNKNOWN) +#endif + ) { + p->fts_accpath = + ISSET(FTS_NOCHDIR) ? p->fts_path : p->fts_name; + p->fts_info = FTS_NSOK; + } else { + /* Build a file name for fts_stat to stat. */ + if (ISSET(FTS_NOCHDIR)) { + p->fts_accpath = p->fts_path; + memmove(cp, p->fts_name, p->fts_namelen + 1); + } else + p->fts_accpath = p->fts_name; + /* Stat it. */ + p->fts_info = fts_stat(sp, p, 0); + + /* Decrement link count if applicable. */ + if (nlinks > 0 && (p->fts_info == FTS_D || + p->fts_info == FTS_DC || p->fts_info == FTS_DOT)) + --nlinks; + } + + /* We walk in directory order so "ls -f" doesn't get upset. */ + p->fts_link = NULL; + if (head == NULL) + head = tail = p; + else { + tail->fts_link = p; + tail = p; + } + ++nitems; + } + if (dirp) + (void)closedir(dirp); + + /* + * If realloc() changed the address of the path, adjust the + * addresses for the rest of the tree and the dir list. + */ + if (doadjust) + fts_padjust(sp, head); + + /* + * If not changing directories, reset the path back to original + * state. + */ + if (ISSET(FTS_NOCHDIR)) { + if (len == sp->fts_pathlen || nitems == 0) + --cp; + *cp = '\0'; + } + + /* + * If descended after called from fts_children or after called from + * fts_read and nothing found, get back. At the root level we use + * the saved fd; if one of fts_open()'s arguments is a relative path + * to an empty directory, we wind up here with no other way back. If + * can't get back, we're done. + */ + if (descend && (type == BCHILD || !nitems) && + (cur->fts_level == FTS_ROOTLEVEL ? + FCHDIR(sp, sp->fts_rfd) : + fts_safe_changedir(sp, cur->fts_parent, -1, ".."))) { + cur->fts_info = FTS_ERR; + SET(FTS_STOP); + return (NULL); + } + + /* If didn't find anything, return NULL. */ + if (!nitems) { + if (type == BREAD) + cur->fts_info = FTS_DP; + return (NULL); + } + + /* Sort the entries. */ + if (sp->fts_compar && nitems > 1) + head = fts_sort(sp, head, nitems); + return (head); +} + +static u_short +fts_stat(sp, p, follow) + FTS *sp; + FTSENT *p; + int follow; +{ + FTSENT *t; + dev_t dev; + ino_t ino; + struct stat *sbp, sb; + int saved_errno; + + /* If user needs stat info, stat buffer already allocated. */ + sbp = ISSET(FTS_NOSTAT) ? &sb : p->fts_statp; + +#ifdef FTS_WHITEOUT + /* Check for whiteout. */ + if (p->fts_flags & FTS_ISW) { + if (sbp != &sb) { + memset(sbp, '\0', sizeof(*sbp)); + sbp->st_mode = S_IFWHT; + } + return (FTS_W); + } +#endif + + /* + * If doing a logical walk, or application requested FTS_FOLLOW, do + * a stat(2). If that fails, check for a non-existent symlink. If + * fail, set the errno from the stat call. + */ + if (ISSET(FTS_LOGICAL) || follow) { + if (stat(p->fts_accpath, sbp)) { + saved_errno = errno; + if (!lstat(p->fts_accpath, sbp)) { + errno = 0; + return (FTS_SLNONE); + } + p->fts_errno = saved_errno; + goto err; + } + } else if (lstat(p->fts_accpath, sbp)) { + p->fts_errno = errno; +err: memset(sbp, 0, sizeof(struct stat)); + return (FTS_NS); + } + + if (S_ISDIR(sbp->st_mode)) { + /* + * Set the device/inode. Used to find cycles and check for + * crossing mount points. Also remember the link count, used + * in fts_build to limit the number of stat calls. It is + * understood that these fields are only referenced if fts_info + * is set to FTS_D. + */ + dev = p->fts_dev = sbp->st_dev; + ino = p->fts_ino = sbp->st_ino; + p->fts_nlink = sbp->st_nlink; + + if (ISDOT(p->fts_name)) + return (FTS_DOT); + + /* + * Cycle detection is done by brute force when the directory + * is first encountered. If the tree gets deep enough or the + * number of symbolic links to directories is high enough, + * something faster might be worthwhile. + */ + for (t = p->fts_parent; + t->fts_level >= FTS_ROOTLEVEL; t = t->fts_parent) + if (ino == t->fts_ino && dev == t->fts_dev) { + p->fts_cycle = t; + return (FTS_DC); + } + return (FTS_D); + } + if (S_ISLNK(sbp->st_mode)) + return (FTS_SL); + if (S_ISREG(sbp->st_mode)) + return (FTS_F); + return (FTS_DEFAULT); +} + +/* + * The comparison function takes pointers to pointers to FTSENT structures. + * Qsort wants a comparison function that takes pointers to void. + * (Both with appropriate levels of const-poisoning, of course!) + * Use a trampoline function to deal with the difference. + */ +static int +fts_compar(const void *a, const void *b) +{ + FTS *parent; + + parent = (*(const FTSENT * const *)a)->fts_fts; + return (*parent->fts_compar)(a, b); +} + +static FTSENT * +fts_sort(sp, head, nitems) + FTS *sp; + FTSENT *head; + int nitems; +{ + FTSENT **ap, *p; + + /* + * Construct an array of pointers to the structures and call qsort(3). + * Reassemble the array in the order returned by qsort. If unable to + * sort for memory reasons, return the directory entries in their + * current order. Allocate enough space for the current needs plus + * 40 so don't realloc one entry at a time. + */ + if (nitems > sp->fts_nitems) { + sp->fts_nitems = nitems + 40; + if ((sp->fts_array = reallocf(sp->fts_array, + sp->fts_nitems * sizeof(FTSENT *))) == NULL) { + sp->fts_nitems = 0; + return (head); + } + } + for (ap = sp->fts_array, p = head; p; p = p->fts_link) + *ap++ = p; + qsort(sp->fts_array, nitems, sizeof(FTSENT *), fts_compar); + for (head = *(ap = sp->fts_array); --nitems; ++ap) + ap[0]->fts_link = ap[1]; + ap[0]->fts_link = NULL; + return (head); +} + +static FTSENT * +fts_alloc(sp, name, namelen) + FTS *sp; + char *name; + int namelen; +{ + FTSENT *p; + size_t len; + + struct ftsent_withstat { + FTSENT ent; + struct stat statbuf; + }; + + /* + * The file name is a variable length array and no stat structure is + * necessary if the user has set the nostat bit. Allocate the FTSENT + * structure, the file name and the stat structure in one chunk, but + * be careful that the stat structure is reasonably aligned. + */ + if (ISSET(FTS_NOSTAT)) + len = sizeof(FTSENT) + namelen + 1; + else + len = sizeof(struct ftsent_withstat) + namelen + 1; + + if ((p = malloc(len)) == NULL) + return (NULL); + + if (ISSET(FTS_NOSTAT)) { + p->fts_name = (char *)(p + 1); + p->fts_statp = NULL; + } else { + p->fts_name = (char *)((struct ftsent_withstat *)p + 1); + p->fts_statp = &((struct ftsent_withstat *)p)->statbuf; + } + + /* Copy the name and guarantee NUL termination. */ + memcpy(p->fts_name, name, namelen); + p->fts_name[namelen] = '\0'; + p->fts_namelen = namelen; + p->fts_path = sp->fts_path; + p->fts_errno = 0; + p->fts_flags = 0; + p->fts_instr = FTS_NOINSTR; + p->fts_number = 0; + p->fts_pointer = NULL; + p->fts_fts = sp; + return (p); +} + +static void +fts_lfree(head) + FTSENT *head; +{ + FTSENT *p; + + /* Free a linked list of structures. */ + while ((p = head)) { + head = head->fts_link; + free(p); + } +} + +/* + * Allow essentially unlimited paths; find, rm, ls should all work on any tree. + * Most systems will allow creation of paths much longer than MAXPATHLEN, even + * though the kernel won't resolve them. Add the size (not just what's needed) + * plus 256 bytes so don't realloc the path 2 bytes at a time. + */ +static int +fts_palloc(sp, more) + FTS *sp; + size_t more; +{ + + sp->fts_pathlen += more + 256; + /* + * Check for possible wraparound. In an FTS, fts_pathlen is + * a signed int but in an FTSENT it is an unsigned short. + * We limit fts_pathlen to USHRT_MAX to be safe in both cases. + */ + if (sp->fts_pathlen < 0 || sp->fts_pathlen >= USHRT_MAX) { + if (sp->fts_path) + free(sp->fts_path); + sp->fts_path = NULL; + errno = ENAMETOOLONG; + return (1); + } + sp->fts_path = reallocf(sp->fts_path, sp->fts_pathlen); + return (sp->fts_path == NULL); +} + +/* + * When the path is realloc'd, have to fix all of the pointers in structures + * already returned. + */ +static void +fts_padjust(sp, head) + FTS *sp; + FTSENT *head; +{ + FTSENT *p; + char *addr = sp->fts_path; + +#define ADJUST(p) do { \ + if ((p)->fts_accpath != (p)->fts_name) { \ + (p)->fts_accpath = \ + (char *)addr + ((p)->fts_accpath - (p)->fts_path); \ + } \ + (p)->fts_path = addr; \ +} while (0) + /* Adjust the current set of children. */ + for (p = sp->fts_child; p; p = p->fts_link) + ADJUST(p); + + /* Adjust the rest of the tree, including the current level. */ + for (p = head; p->fts_level >= FTS_ROOTLEVEL;) { + ADJUST(p); + p = p->fts_link ? p->fts_link : p->fts_parent; + } +} + +static size_t +fts_maxarglen(argv) + char * const *argv; +{ + size_t len, max; + + for (max = 0; *argv; ++argv) + if ((len = strlen(*argv)) > max) + max = len; + return (max + 1); +} + +/* + * Change to dir specified by fd or p->fts_accpath without getting + * tricked by someone changing the world out from underneath us. + * Assumes p->fts_dev and p->fts_ino are filled in. + */ +static int +fts_safe_changedir(sp, p, fd, path) + FTS *sp; + FTSENT *p; + int fd; + char *path; +{ + int ret, oerrno, newfd; + struct stat sb; + + newfd = fd; + if (ISSET(FTS_NOCHDIR)) + return (0); + if (fd < 0 && (newfd = _open(path, O_RDONLY, 0)) < 0) + return (-1); + if (_fstat(newfd, &sb)) { + ret = -1; + goto bail; + } + if (p->fts_dev != sb.st_dev || p->fts_ino != sb.st_ino) { + errno = ENOENT; /* disinformation */ + ret = -1; + goto bail; + } + ret = fchdir(newfd); +bail: + oerrno = errno; + if (fd < 0) + (void)_close(newfd); + errno = oerrno; + return (ret); +} + +/* + * Check if the filesystem for "ent" has UFS-style links. + */ +static int +fts_ufslinks(FTS *sp, const FTSENT *ent) +{ + struct _fts_private *priv; + const char **cpp; + + priv = (struct _fts_private *)sp; + /* + * If this node's device is different from the previous, grab + * the filesystem information, and decide on the reliability + * of the link information from this filesystem for stat(2) + * avoidance. + */ + if (priv->ftsp_dev != ent->fts_dev) { + if (statfs(ent->fts_path, &priv->ftsp_statfs) != -1) { + priv->ftsp_dev = ent->fts_dev; + priv->ftsp_linksreliable = 0; + for (cpp = ufslike_filesystems; *cpp; cpp++) { + if (strcmp(priv->ftsp_statfs.f_fstypename, + *cpp) == 0) { + priv->ftsp_linksreliable = 1; + break; + } + } + } else { + priv->ftsp_linksreliable = 0; + } + } + return (priv->ftsp_linksreliable); +} diff --git a/lib/libc/gen/ftw.c b/lib/libc/gen/ftw.c new file mode 100644 index 0000000..959c9cc --- /dev/null +++ b/lib/libc/gen/ftw.c @@ -0,0 +1,98 @@ +/* $OpenBSD: ftw.c,v 1.4 2004/07/07 16:05:23 millert Exp $ */ + +/* + * Copyright (c) 2003, 2004 Todd C. Miller + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * Sponsored in part by the Defense Advanced Research Projects + * Agency (DARPA) and Air Force Research Laboratory, Air Force + * Materiel Command, USAF, under agreement number F39502-99-1-0512. + */ + +#if 0 +#if defined(LIBC_SCCS) && !defined(lint) +static const char rcsid[] = "$OpenBSD: ftw.c,v 1.4 2004/07/07 16:05:23 millert Exp $"; +#endif /* LIBC_SCCS and not lint */ +#endif + +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/ftw.c,v 1.4 2004/08/24 13:00:55 tjr Exp $"); + +#include +#include +#include +#include +#include +#include + +int +ftw(const char *path, int (*fn)(const char *, const struct stat *, int), + int nfds) +{ + char * const paths[2] = { (char *)path, NULL }; + FTSENT *cur; + FTS *ftsp; + int error = 0, fnflag, sverrno; + + /* XXX - nfds is currently unused */ + if (nfds < 1 || nfds > OPEN_MAX) { + errno = EINVAL; + return (-1); + } + + ftsp = fts_open(paths, FTS_LOGICAL | FTS_COMFOLLOW | FTS_NOCHDIR, NULL); + if (ftsp == NULL) + return (-1); + while ((cur = fts_read(ftsp)) != NULL) { + switch (cur->fts_info) { + case FTS_D: + fnflag = FTW_D; + break; + case FTS_DNR: + fnflag = FTW_DNR; + break; + case FTS_DP: + /* we only visit in preorder */ + continue; + case FTS_F: + case FTS_DEFAULT: + fnflag = FTW_F; + break; + case FTS_NS: + case FTS_NSOK: + case FTS_SLNONE: + fnflag = FTW_NS; + break; + case FTS_SL: + fnflag = FTW_SL; + break; + case FTS_DC: + errno = ELOOP; + /* FALLTHROUGH */ + default: + error = -1; + goto done; + } + error = fn(cur->fts_path, cur->fts_statp, fnflag); + if (error != 0) + break; + } +done: + sverrno = errno; + if (fts_close(ftsp) != 0 && error == 0) + error = -1; + else + errno = sverrno; + return (error); +} diff --git a/lib/libc/gen/getbootfile.c b/lib/libc/gen/getbootfile.c new file mode 100644 index 0000000..9b2444d --- /dev/null +++ b/lib/libc/gen/getbootfile.c @@ -0,0 +1,57 @@ +/* + * Copyright (c) 1989, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "From: @(#)gethostname.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/getbootfile.c,v 1.8 2005/05/03 15:28:07 delphij Exp $"); + +#include +#include + +#include + +const char * +getbootfile(void) +{ + static char name[MAXPATHLEN]; + size_t size = sizeof name; + int mib[2]; + + mib[0] = CTL_KERN; + mib[1] = KERN_BOOTFILE; + if (sysctl(mib, 2, name, &size, NULL, 0) == -1) + return ("/boot/kernel/kernel"); + return (name); +} diff --git a/lib/libc/gen/getbsize.c b/lib/libc/gen/getbsize.c new file mode 100644 index 0000000..b922f1c --- /dev/null +++ b/lib/libc/gen/getbsize.c @@ -0,0 +1,109 @@ +/*- + * Copyright (c) 1991, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)getbsize.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/getbsize.c,v 1.7 2002/12/30 19:04:06 obrien Exp $"); + +#include +#include +#include +#include + +char * +getbsize(headerlenp, blocksizep) + int *headerlenp; + long *blocksizep; +{ + static char header[20]; + long n, max, mul, blocksize; + char *ep, *p; + const char *form; + +#define KB (1024L) +#define MB (1024L * 1024L) +#define GB (1024L * 1024L * 1024L) +#define MAXB GB /* No tera, peta, nor exa. */ + form = ""; + if ((p = getenv("BLOCKSIZE")) != NULL && *p != '\0') { + if ((n = strtol(p, &ep, 10)) < 0) + goto underflow; + if (n == 0) + n = 1; + if (*ep && ep[1]) + goto fmterr; + switch (*ep) { + case 'G': case 'g': + form = "G"; + max = MAXB / GB; + mul = GB; + break; + case 'K': case 'k': + form = "K"; + max = MAXB / KB; + mul = KB; + break; + case 'M': case 'm': + form = "M"; + max = MAXB / MB; + mul = MB; + break; + case '\0': + max = MAXB; + mul = 1; + break; + default: +fmterr: warnx("%s: unknown blocksize", p); + n = 512; + mul = 1; + break; + } + if (n > max) { + warnx("maximum blocksize is %ldG", MAXB / GB); + n = max; + } + if ((blocksize = n * mul) < 512) { +underflow: warnx("minimum blocksize is 512"); + form = ""; + blocksize = n = 512; + } + } else + blocksize = n = 512; + + (void)snprintf(header, sizeof(header), "%ld%s-blocks", n, form); + *headerlenp = strlen(header); + *blocksizep = blocksize; + return (header); +} diff --git a/lib/libc/gen/getcap.c b/lib/libc/gen/getcap.c new file mode 100644 index 0000000..3cf07fa --- /dev/null +++ b/lib/libc/gen/getcap.c @@ -0,0 +1,1058 @@ +/*- + * Copyright (c) 1992, 1993 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * Casey Leedom of Lawrence Livermore National Laboratory. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)getcap.c 8.3 (Berkeley) 3/25/94"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/getcap.c,v 1.19 2003/01/02 10:19:43 thomas Exp $"); + +#include "namespace.h" +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include "un-namespace.h" + +#include + +#define BFRAG 1024 +#define BSIZE 1024 +#define ESC ('[' & 037) /* ASCII ESC */ +#define MAX_RECURSION 32 /* maximum getent recursion */ +#define SFRAG 100 /* cgetstr mallocs in SFRAG chunks */ + +#define RECOK (char)0 +#define TCERR (char)1 +#define SHADOW (char)2 + +static size_t topreclen; /* toprec length */ +static char *toprec; /* Additional record specified by cgetset() */ +static int gottoprec; /* Flag indicating retrieval of toprecord */ + +static int cdbget(DB *, char **, const char *); +static int getent(char **, u_int *, char **, int, const char *, int, char *); +static int nfcmp(char *, char *); + +/* + * Cgetset() allows the addition of a user specified buffer to be added + * to the database array, in effect "pushing" the buffer on top of the + * virtual database. 0 is returned on success, -1 on failure. + */ +int +cgetset(const char *ent) +{ + if (ent == NULL) { + if (toprec) + free(toprec); + toprec = NULL; + topreclen = 0; + return (0); + } + topreclen = strlen(ent); + if ((toprec = malloc (topreclen + 1)) == NULL) { + errno = ENOMEM; + return (-1); + } + gottoprec = 0; + (void)strcpy(toprec, ent); + return (0); +} + +/* + * Cgetcap searches the capability record buf for the capability cap with + * type `type'. A pointer to the value of cap is returned on success, NULL + * if the requested capability couldn't be found. + * + * Specifying a type of ':' means that nothing should follow cap (:cap:). + * In this case a pointer to the terminating ':' or NUL will be returned if + * cap is found. + * + * If (cap, '@') or (cap, terminator, '@') is found before (cap, terminator) + * return NULL. + */ +char * +cgetcap(char *buf, const char *cap, int type) +{ + char *bp; + const char *cp; + + bp = buf; + for (;;) { + /* + * Skip past the current capability field - it's either the + * name field if this is the first time through the loop, or + * the remainder of a field whose name failed to match cap. + */ + for (;;) + if (*bp == '\0') + return (NULL); + else + if (*bp++ == ':') + break; + + /* + * Try to match (cap, type) in buf. + */ + for (cp = cap; *cp == *bp && *bp != '\0'; cp++, bp++) + continue; + if (*cp != '\0') + continue; + if (*bp == '@') + return (NULL); + if (type == ':') { + if (*bp != '\0' && *bp != ':') + continue; + return(bp); + } + if (*bp != type) + continue; + bp++; + return (*bp == '@' ? NULL : bp); + } + /* NOTREACHED */ +} + +/* + * Cgetent extracts the capability record name from the NULL terminated file + * array db_array and returns a pointer to a malloc'd copy of it in buf. + * Buf must be retained through all subsequent calls to cgetcap, cgetnum, + * cgetflag, and cgetstr, but may then be free'd. 0 is returned on success, + * -1 if the requested record couldn't be found, -2 if a system error was + * encountered (couldn't open/read a file, etc.), and -3 if a potential + * reference loop is detected. + */ +int +cgetent(char **buf, char **db_array, const char *name) +{ + u_int dummy; + + return (getent(buf, &dummy, db_array, -1, name, 0, NULL)); +} + +/* + * Getent implements the functions of cgetent. If fd is non-negative, + * *db_array has already been opened and fd is the open file descriptor. We + * do this to save time and avoid using up file descriptors for tc= + * recursions. + * + * Getent returns the same success/failure codes as cgetent. On success, a + * pointer to a malloc'ed capability record with all tc= capabilities fully + * expanded and its length (not including trailing ASCII NUL) are left in + * *cap and *len. + * + * Basic algorithm: + * + Allocate memory incrementally as needed in chunks of size BFRAG + * for capability buffer. + * + Recurse for each tc=name and interpolate result. Stop when all + * names interpolated, a name can't be found, or depth exceeds + * MAX_RECURSION. + */ +static int +getent(char **cap, u_int *len, char **db_array, int fd, const char *name, + int depth, char *nfield) +{ + DB *capdbp; + char *r_end, *rp, **db_p; + int myfd, eof, foundit, retval, clen; + char *record, *cbuf; + int tc_not_resolved; + char pbuf[_POSIX_PATH_MAX]; + + /* + * Return with ``loop detected'' error if we've recursed more than + * MAX_RECURSION times. + */ + if (depth > MAX_RECURSION) + return (-3); + + /* + * Check if we have a top record from cgetset(). + */ + if (depth == 0 && toprec != NULL && cgetmatch(toprec, name) == 0) { + if ((record = malloc (topreclen + BFRAG)) == NULL) { + errno = ENOMEM; + return (-2); + } + (void)strcpy(record, toprec); + myfd = 0; + db_p = db_array; + rp = record + topreclen + 1; + r_end = rp + BFRAG; + goto tc_exp; + } + /* + * Allocate first chunk of memory. + */ + if ((record = malloc(BFRAG)) == NULL) { + errno = ENOMEM; + return (-2); + } + r_end = record + BFRAG; + foundit = 0; + /* + * Loop through database array until finding the record. + */ + + for (db_p = db_array; *db_p != NULL; db_p++) { + eof = 0; + + /* + * Open database if not already open. + */ + + if (fd >= 0) { + (void)lseek(fd, (off_t)0, SEEK_SET); + myfd = 0; + } else { + (void)snprintf(pbuf, sizeof(pbuf), "%s.db", *db_p); + if ((capdbp = dbopen(pbuf, O_RDONLY, 0, DB_HASH, 0)) + != NULL) { + free(record); + retval = cdbget(capdbp, &record, name); + if (retval < 0) { + /* no record available */ + (void)capdbp->close(capdbp); + return (retval); + } + /* save the data; close frees it */ + clen = strlen(record); + cbuf = malloc(clen + 1); + memcpy(cbuf, record, clen + 1); + if (capdbp->close(capdbp) < 0) { + free(cbuf); + return (-2); + } + *len = clen; + *cap = cbuf; + return (retval); + } else { + fd = _open(*db_p, O_RDONLY, 0); + if (fd < 0) + continue; + myfd = 1; + } + } + /* + * Find the requested capability record ... + */ + { + char buf[BUFSIZ]; + char *b_end, *bp; + int c; + + /* + * Loop invariants: + * There is always room for one more character in record. + * R_end always points just past end of record. + * Rp always points just past last character in record. + * B_end always points just past last character in buf. + * Bp always points at next character in buf. + */ + b_end = buf; + bp = buf; + for (;;) { + + /* + * Read in a line implementing (\, newline) + * line continuation. + */ + rp = record; + for (;;) { + if (bp >= b_end) { + int n; + + n = _read(fd, buf, sizeof(buf)); + if (n <= 0) { + if (myfd) + (void)_close(fd); + if (n < 0) { + free(record); + return (-2); + } else { + fd = -1; + eof = 1; + break; + } + } + b_end = buf+n; + bp = buf; + } + + c = *bp++; + if (c == '\n') { + if (rp > record && *(rp-1) == '\\') { + rp--; + continue; + } else + break; + } + *rp++ = c; + + /* + * Enforce loop invariant: if no room + * left in record buffer, try to get + * some more. + */ + if (rp >= r_end) { + u_int pos; + size_t newsize; + + pos = rp - record; + newsize = r_end - record + BFRAG; + record = reallocf(record, newsize); + if (record == NULL) { + errno = ENOMEM; + if (myfd) + (void)_close(fd); + return (-2); + } + r_end = record + newsize; + rp = record + pos; + } + } + /* loop invariant let's us do this */ + *rp++ = '\0'; + + /* + * If encountered eof check next file. + */ + if (eof) + break; + + /* + * Toss blank lines and comments. + */ + if (*record == '\0' || *record == '#') + continue; + + /* + * See if this is the record we want ... + */ + if (cgetmatch(record, name) == 0) { + if (nfield == NULL || !nfcmp(nfield, record)) { + foundit = 1; + break; /* found it! */ + } + } + } + } + if (foundit) + break; + } + + if (!foundit) { + free(record); + return (-1); + } + + /* + * Got the capability record, but now we have to expand all tc=name + * references in it ... + */ +tc_exp: { + char *newicap, *s; + int newilen; + u_int ilen; + int diff, iret, tclen; + char *icap, *scan, *tc, *tcstart, *tcend; + + /* + * Loop invariants: + * There is room for one more character in record. + * R_end points just past end of record. + * Rp points just past last character in record. + * Scan points at remainder of record that needs to be + * scanned for tc=name constructs. + */ + scan = record; + tc_not_resolved = 0; + for (;;) { + if ((tc = cgetcap(scan, "tc", '=')) == NULL) + break; + + /* + * Find end of tc=name and stomp on the trailing `:' + * (if present) so we can use it to call ourselves. + */ + s = tc; + for (;;) + if (*s == '\0') + break; + else + if (*s++ == ':') { + *(s - 1) = '\0'; + break; + } + tcstart = tc - 3; + tclen = s - tcstart; + tcend = s; + + iret = getent(&icap, &ilen, db_p, fd, tc, depth+1, + NULL); + newicap = icap; /* Put into a register. */ + newilen = ilen; + if (iret != 0) { + /* an error */ + if (iret < -1) { + if (myfd) + (void)_close(fd); + free(record); + return (iret); + } + if (iret == 1) + tc_not_resolved = 1; + /* couldn't resolve tc */ + if (iret == -1) { + *(s - 1) = ':'; + scan = s - 1; + tc_not_resolved = 1; + continue; + + } + } + /* not interested in name field of tc'ed record */ + s = newicap; + for (;;) + if (*s == '\0') + break; + else + if (*s++ == ':') + break; + newilen -= s - newicap; + newicap = s; + + /* make sure interpolated record is `:'-terminated */ + s += newilen; + if (*(s-1) != ':') { + *s = ':'; /* overwrite NUL with : */ + newilen++; + } + + /* + * Make sure there's enough room to insert the + * new record. + */ + diff = newilen - tclen; + if (diff >= r_end - rp) { + u_int pos, tcpos, tcposend; + size_t newsize; + + pos = rp - record; + newsize = r_end - record + diff + BFRAG; + tcpos = tcstart - record; + tcposend = tcend - record; + record = reallocf(record, newsize); + if (record == NULL) { + errno = ENOMEM; + if (myfd) + (void)_close(fd); + free(icap); + return (-2); + } + r_end = record + newsize; + rp = record + pos; + tcstart = record + tcpos; + tcend = record + tcposend; + } + + /* + * Insert tc'ed record into our record. + */ + s = tcstart + newilen; + bcopy(tcend, s, rp - tcend); + bcopy(newicap, tcstart, newilen); + rp += diff; + free(icap); + + /* + * Start scan on `:' so next cgetcap works properly + * (cgetcap always skips first field). + */ + scan = s-1; + } + + } + /* + * Close file (if we opened it), give back any extra memory, and + * return capability, length and success. + */ + if (myfd) + (void)_close(fd); + *len = rp - record - 1; /* don't count NUL */ + if (r_end > rp) + if ((record = + reallocf(record, (size_t)(rp - record))) == NULL) { + errno = ENOMEM; + return (-2); + } + + *cap = record; + if (tc_not_resolved) + return (1); + return (0); +} + +static int +cdbget(DB *capdbp, char **bp, const char *name) +{ + DBT key, data; + char *namebuf; + + namebuf = strdup(name); + if (namebuf == NULL) + return (-2); + key.data = namebuf; + key.size = strlen(namebuf); + + for (;;) { + /* Get the reference. */ + switch(capdbp->get(capdbp, &key, &data, 0)) { + case -1: + free(namebuf); + return (-2); + case 1: + free(namebuf); + return (-1); + } + + /* If not an index to another record, leave. */ + if (((char *)data.data)[0] != SHADOW) + break; + + key.data = (char *)data.data + 1; + key.size = data.size - 1; + } + + *bp = (char *)data.data + 1; + free(namebuf); + return (((char *)(data.data))[0] == TCERR ? 1 : 0); +} + +/* + * Cgetmatch will return 0 if name is one of the names of the capability + * record buf, -1 if not. + */ +int +cgetmatch(const char *buf, const char *name) +{ + const char *np, *bp; + + if (name == NULL || *name == '\0') + return -1; + + /* + * Start search at beginning of record. + */ + bp = buf; + for (;;) { + /* + * Try to match a record name. + */ + np = name; + for (;;) + if (*np == '\0') + if (*bp == '|' || *bp == ':' || *bp == '\0') + return (0); + else + break; + else + if (*bp++ != *np++) + break; + + /* + * Match failed, skip to next name in record. + */ + bp--; /* a '|' or ':' may have stopped the match */ + for (;;) + if (*bp == '\0' || *bp == ':') + return (-1); /* match failed totally */ + else + if (*bp++ == '|') + break; /* found next name */ + } +} + + + + + +int +cgetfirst(char **buf, char **db_array) +{ + (void)cgetclose(); + return (cgetnext(buf, db_array)); +} + +static FILE *pfp; +static int slash; +static char **dbp; + +int +cgetclose(void) +{ + if (pfp != NULL) { + (void)fclose(pfp); + pfp = NULL; + } + dbp = NULL; + gottoprec = 0; + slash = 0; + return(0); +} + +/* + * Cgetnext() gets either the first or next entry in the logical database + * specified by db_array. It returns 0 upon completion of the database, 1 + * upon returning an entry with more remaining, and -1 if an error occurs. + */ +int +cgetnext(char **bp, char **db_array) +{ + size_t len; + int done, hadreaderr, i, savederrno, status; + char *cp, *line, *rp, *np, buf[BSIZE], nbuf[BSIZE]; + u_int dummy; + + if (dbp == NULL) + dbp = db_array; + + if (pfp == NULL && (pfp = fopen(*dbp, "r")) == NULL) { + (void)cgetclose(); + return (-1); + } + for(;;) { + if (toprec && !gottoprec) { + gottoprec = 1; + line = toprec; + } else { + line = fgetln(pfp, &len); + if (line == NULL && pfp) { + hadreaderr = ferror(pfp); + if (hadreaderr) + savederrno = errno; + fclose(pfp); + pfp = NULL; + if (hadreaderr) { + cgetclose(); + errno = savederrno; + return (-1); + } else { + if (*++dbp == NULL) { + (void)cgetclose(); + return (0); + } else if ((pfp = + fopen(*dbp, "r")) == NULL) { + (void)cgetclose(); + return (-1); + } else + continue; + } + } else + line[len - 1] = '\0'; + if (len == 1) { + slash = 0; + continue; + } + if (isspace((unsigned char)*line) || + *line == ':' || *line == '#' || slash) { + if (line[len - 2] == '\\') + slash = 1; + else + slash = 0; + continue; + } + if (line[len - 2] == '\\') + slash = 1; + else + slash = 0; + } + + + /* + * Line points to a name line. + */ + i = 0; + done = 0; + np = nbuf; + for (;;) { + for (cp = line; *cp != '\0'; cp++) { + if (*cp == ':') { + *np++ = ':'; + done = 1; + break; + } + if (*cp == '\\') + break; + *np++ = *cp; + } + if (done) { + *np = '\0'; + break; + } else { /* name field extends beyond the line */ + line = fgetln(pfp, &len); + if (line == NULL && pfp) { + /* Name extends beyond the EOF! */ + hadreaderr = ferror(pfp); + if (hadreaderr) + savederrno = errno; + fclose(pfp); + pfp = NULL; + if (hadreaderr) { + cgetclose(); + errno = savederrno; + return (-1); + } else { + cgetclose(); + return (-1); + } + } else + line[len - 1] = '\0'; + } + } + rp = buf; + for(cp = nbuf; *cp != '\0'; cp++) + if (*cp == '|' || *cp == ':') + break; + else + *rp++ = *cp; + + *rp = '\0'; + /* + * XXX + * Last argument of getent here should be nbuf if we want true + * sequential access in the case of duplicates. + * With NULL, getent will return the first entry found + * rather than the duplicate entry record. This is a + * matter of semantics that should be resolved. + */ + status = getent(bp, &dummy, db_array, -1, buf, 0, NULL); + if (status == -2 || status == -3) + (void)cgetclose(); + + return (status + 1); + } + /* NOTREACHED */ +} + +/* + * Cgetstr retrieves the value of the string capability cap from the + * capability record pointed to by buf. A pointer to a decoded, NUL + * terminated, malloc'd copy of the string is returned in the char * + * pointed to by str. The length of the string not including the trailing + * NUL is returned on success, -1 if the requested string capability + * couldn't be found, -2 if a system error was encountered (storage + * allocation failure). + */ +int +cgetstr(char *buf, const char *cap, char **str) +{ + u_int m_room; + char *bp, *mp; + int len; + char *mem; + + /* + * Find string capability cap + */ + bp = cgetcap(buf, cap, '='); + if (bp == NULL) + return (-1); + + /* + * Conversion / storage allocation loop ... Allocate memory in + * chunks SFRAG in size. + */ + if ((mem = malloc(SFRAG)) == NULL) { + errno = ENOMEM; + return (-2); /* couldn't even allocate the first fragment */ + } + m_room = SFRAG; + mp = mem; + + while (*bp != ':' && *bp != '\0') { + /* + * Loop invariants: + * There is always room for one more character in mem. + * Mp always points just past last character in mem. + * Bp always points at next character in buf. + */ + if (*bp == '^') { + bp++; + if (*bp == ':' || *bp == '\0') + break; /* drop unfinished escape */ + if (*bp == '?') { + *mp++ = '\177'; + bp++; + } else + *mp++ = *bp++ & 037; + } else if (*bp == '\\') { + bp++; + if (*bp == ':' || *bp == '\0') + break; /* drop unfinished escape */ + if ('0' <= *bp && *bp <= '7') { + int n, i; + + n = 0; + i = 3; /* maximum of three octal digits */ + do { + n = n * 8 + (*bp++ - '0'); + } while (--i && '0' <= *bp && *bp <= '7'); + *mp++ = n; + } + else switch (*bp++) { + case 'b': case 'B': + *mp++ = '\b'; + break; + case 't': case 'T': + *mp++ = '\t'; + break; + case 'n': case 'N': + *mp++ = '\n'; + break; + case 'f': case 'F': + *mp++ = '\f'; + break; + case 'r': case 'R': + *mp++ = '\r'; + break; + case 'e': case 'E': + *mp++ = ESC; + break; + case 'c': case 'C': + *mp++ = ':'; + break; + default: + /* + * Catches '\', '^', and + * everything else. + */ + *mp++ = *(bp-1); + break; + } + } else + *mp++ = *bp++; + m_room--; + + /* + * Enforce loop invariant: if no room left in current + * buffer, try to get some more. + */ + if (m_room == 0) { + size_t size = mp - mem; + + if ((mem = reallocf(mem, size + SFRAG)) == NULL) + return (-2); + m_room = SFRAG; + mp = mem + size; + } + } + *mp++ = '\0'; /* loop invariant let's us do this */ + m_room--; + len = mp - mem - 1; + + /* + * Give back any extra memory and return value and success. + */ + if (m_room != 0) + if ((mem = reallocf(mem, (size_t)(mp - mem))) == NULL) + return (-2); + *str = mem; + return (len); +} + +/* + * Cgetustr retrieves the value of the string capability cap from the + * capability record pointed to by buf. The difference between cgetustr() + * and cgetstr() is that cgetustr does not decode escapes but rather treats + * all characters literally. A pointer to a NUL terminated malloc'd + * copy of the string is returned in the char pointed to by str. The + * length of the string not including the trailing NUL is returned on success, + * -1 if the requested string capability couldn't be found, -2 if a system + * error was encountered (storage allocation failure). + */ +int +cgetustr(char *buf, const char *cap, char **str) +{ + u_int m_room; + char *bp, *mp; + int len; + char *mem; + + /* + * Find string capability cap + */ + if ((bp = cgetcap(buf, cap, '=')) == NULL) + return (-1); + + /* + * Conversion / storage allocation loop ... Allocate memory in + * chunks SFRAG in size. + */ + if ((mem = malloc(SFRAG)) == NULL) { + errno = ENOMEM; + return (-2); /* couldn't even allocate the first fragment */ + } + m_room = SFRAG; + mp = mem; + + while (*bp != ':' && *bp != '\0') { + /* + * Loop invariants: + * There is always room for one more character in mem. + * Mp always points just past last character in mem. + * Bp always points at next character in buf. + */ + *mp++ = *bp++; + m_room--; + + /* + * Enforce loop invariant: if no room left in current + * buffer, try to get some more. + */ + if (m_room == 0) { + size_t size = mp - mem; + + if ((mem = reallocf(mem, size + SFRAG)) == NULL) + return (-2); + m_room = SFRAG; + mp = mem + size; + } + } + *mp++ = '\0'; /* loop invariant let's us do this */ + m_room--; + len = mp - mem - 1; + + /* + * Give back any extra memory and return value and success. + */ + if (m_room != 0) + if ((mem = reallocf(mem, (size_t)(mp - mem))) == NULL) + return (-2); + *str = mem; + return (len); +} + +/* + * Cgetnum retrieves the value of the numeric capability cap from the + * capability record pointed to by buf. The numeric value is returned in + * the long pointed to by num. 0 is returned on success, -1 if the requested + * numeric capability couldn't be found. + */ +int +cgetnum(char *buf, const char *cap, long *num) +{ + long n; + int base, digit; + char *bp; + + /* + * Find numeric capability cap + */ + bp = cgetcap(buf, cap, '#'); + if (bp == NULL) + return (-1); + + /* + * Look at value and determine numeric base: + * 0x... or 0X... hexadecimal, + * else 0... octal, + * else decimal. + */ + if (*bp == '0') { + bp++; + if (*bp == 'x' || *bp == 'X') { + bp++; + base = 16; + } else + base = 8; + } else + base = 10; + + /* + * Conversion loop ... + */ + n = 0; + for (;;) { + if ('0' <= *bp && *bp <= '9') + digit = *bp - '0'; + else if ('a' <= *bp && *bp <= 'f') + digit = 10 + *bp - 'a'; + else if ('A' <= *bp && *bp <= 'F') + digit = 10 + *bp - 'A'; + else + break; + + if (digit >= base) + break; + + n = n * base + digit; + bp++; + } + + /* + * Return value and success. + */ + *num = n; + return (0); +} + + +/* + * Compare name field of record. + */ +static int +nfcmp(char *nf, char *rec) +{ + char *cp, tmp; + int ret; + + for (cp = rec; *cp != ':'; cp++) + ; + + tmp = *(cp + 1); + *(cp + 1) = '\0'; + ret = strcmp(nf, rec); + *(cp + 1) = tmp; + + return (ret); +} diff --git a/lib/libc/gen/getcwd.c b/lib/libc/gen/getcwd.c new file mode 100644 index 0000000..2e8c1b9 --- /dev/null +++ b/lib/libc/gen/getcwd.c @@ -0,0 +1,261 @@ +/* + * Copyright (c) 1989, 1991, 1993, 1995 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)getcwd.c 8.5 (Berkeley) 2/7/95"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/getcwd.c,v 1.25.10.1 2005/10/04 14:33:09 ache Exp $"); + +#include "namespace.h" +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include "un-namespace.h" + +#define ISDOT(dp) \ + (dp->d_name[0] == '.' && (dp->d_name[1] == '\0' || \ + (dp->d_name[1] == '.' && dp->d_name[2] == '\0'))) + +extern int __getcwd(char *, size_t); + +char * +getcwd(pt, size) + char *pt; + size_t size; +{ + struct dirent *dp; + DIR *dir = NULL; + dev_t dev; + ino_t ino; + int first; + char *bpt, *bup; + struct stat s; + dev_t root_dev; + ino_t root_ino; + size_t ptsize, upsize; + int save_errno; + char *ept, *eup, *up, c; + + /* + * If no buffer specified by the user, allocate one as necessary. + * If a buffer is specified, the size has to be non-zero. The path + * is built from the end of the buffer backwards. + */ + if (pt) { + ptsize = 0; + if (!size) { + errno = EINVAL; + return (NULL); + } + if (size == 1) { + errno = ERANGE; + return (NULL); + } + ept = pt + size; + } else { + if ((pt = malloc(ptsize = PATH_MAX)) == NULL) + return (NULL); + ept = pt + ptsize; + } + if (__getcwd(pt, ept - pt) == 0) { + if (*pt != '/') { + bpt = pt; + ept = pt + strlen(pt) - 1; + while (bpt < ept) { + c = *bpt; + *bpt++ = *ept; + *ept-- = c; + } + } + return (pt); + } + bpt = ept - 1; + *bpt = '\0'; + + /* + * Allocate 1024 bytes for the string of "../"'s. + * Should always be enough. If it's not, allocate + * as necessary. Special case the first stat, it's ".", not "..". + */ + if ((up = malloc(upsize = 1024)) == NULL) + goto err; + eup = up + upsize; + bup = up; + up[0] = '.'; + up[1] = '\0'; + + /* Save root values, so know when to stop. */ + if (stat("/", &s)) + goto err; + root_dev = s.st_dev; + root_ino = s.st_ino; + + errno = 0; /* XXX readdir has no error return. */ + + for (first = 1;; first = 0) { + /* Stat the current level. */ + if (lstat(up, &s)) + goto err; + + /* Save current node values. */ + ino = s.st_ino; + dev = s.st_dev; + + /* Check for reaching root. */ + if (root_dev == dev && root_ino == ino) { + *--bpt = '/'; + /* + * It's unclear that it's a requirement to copy the + * path to the beginning of the buffer, but it's always + * been that way and stuff would probably break. + */ + bcopy(bpt, pt, ept - bpt); + free(up); + return (pt); + } + + /* + * Build pointer to the parent directory, allocating memory + * as necessary. Max length is 3 for "../", the largest + * possible component name, plus a trailing NUL. + */ + while (bup + 3 + MAXNAMLEN + 1 >= eup) { + if ((up = reallocf(up, upsize *= 2)) == NULL) + goto err; + bup = up; + eup = up + upsize; + } + *bup++ = '.'; + *bup++ = '.'; + *bup = '\0'; + + /* Open and stat parent directory. */ + if (!(dir = opendir(up)) || _fstat(dirfd(dir), &s)) + goto err; + + /* Add trailing slash for next directory. */ + *bup++ = '/'; + *bup = '\0'; + + /* + * If it's a mount point, have to stat each element because + * the inode number in the directory is for the entry in the + * parent directory, not the inode number of the mounted file. + */ + save_errno = 0; + if (s.st_dev == dev) { + for (;;) { + if (!(dp = readdir(dir))) + goto notfound; + if (dp->d_fileno == ino) + break; + } + } else + for (;;) { + if (!(dp = readdir(dir))) + goto notfound; + if (ISDOT(dp)) + continue; + bcopy(dp->d_name, bup, dp->d_namlen + 1); + + /* Save the first error for later. */ + if (lstat(up, &s)) { + if (!save_errno) + save_errno = errno; + errno = 0; + continue; + } + if (s.st_dev == dev && s.st_ino == ino) + break; + } + + /* + * Check for length of the current name, preceding slash, + * leading slash. + */ + while (bpt - pt < dp->d_namlen + (first ? 1 : 2)) { + size_t len, off; + + if (!ptsize) { + errno = ERANGE; + goto err; + } + off = bpt - pt; + len = ept - bpt; + if ((pt = reallocf(pt, ptsize *= 2)) == NULL) + goto err; + bpt = pt + off; + ept = pt + ptsize; + bcopy(bpt, ept - len, len); + bpt = ept - len; + } + if (!first) + *--bpt = '/'; + bpt -= dp->d_namlen; + bcopy(dp->d_name, bpt, dp->d_namlen); + (void) closedir(dir); + dir = NULL; + + /* Truncate any file name. */ + *bup = '\0'; + } + +notfound: + /* + * If readdir set errno, use it, not any saved error; otherwise, + * didn't find the current directory in its parent directory, set + * errno to ENOENT. + */ + if (!errno) + errno = save_errno ? save_errno : ENOENT; + /* FALLTHROUGH */ +err: + save_errno = errno; + + if (ptsize) + free(pt); + if (dir) + (void) closedir(dir); + free(up); + + errno = save_errno; + return (NULL); +} diff --git a/lib/libc/gen/getdomainname.c b/lib/libc/gen/getdomainname.c new file mode 100644 index 0000000..05441d7 --- /dev/null +++ b/lib/libc/gen/getdomainname.c @@ -0,0 +1,59 @@ +/* + * Copyright (c) 1989, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)gethostname.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/getdomainname.c,v 1.7 2002/02/01 00:57:29 obrien Exp $"); + +#include +#include + +#include + +int +getdomainname(name, namelen) + char *name; + int namelen; +{ + int mib[2]; + size_t size; + + mib[0] = CTL_KERN; + mib[1] = KERN_NISDOMAINNAME; + size = namelen; + if (sysctl(mib, 2, name, &size, NULL, 0) == -1) + return (-1); + return (0); +} diff --git a/lib/libc/gen/getgrent.c b/lib/libc/gen/getgrent.c new file mode 100644 index 0000000..53e7c73 --- /dev/null +++ b/lib/libc/gen/getgrent.c @@ -0,0 +1,1162 @@ +/*- + * Copyright (c) 2003 Networks Associates Technology, Inc. + * All rights reserved. + * + * This software was developed for the FreeBSD Project by + * Jacques A. Vidrine, Safeport Network Services, and Network + * Associates Laboratories, the Security Research Division of Network + * Associates, Inc. under DARPA/SPAWAR contract N66001-01-C-8035 + * ("CBOSS"), as part of the DARPA CHATS research program. + * + * 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 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 AUTHOR 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 +__FBSDID("$FreeBSD: src/lib/libc/gen/getgrent.c,v 1.32.8.2 2006/07/28 16:17:49 maxim Exp $"); + +#include "namespace.h" +#include +#ifdef YP +#include +#include +#include +#endif +#include +#include +#ifdef HESIOD +#include +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "un-namespace.h" +#include "libc_private.h" +#include "nss_tls.h" + + +enum constants { + GRP_STORAGE_INITIAL = 1 << 10, /* 1 KByte */ + GRP_STORAGE_MAX = 1 << 20, /* 1 MByte */ + SETGRENT = 1, + ENDGRENT = 2, + HESIOD_NAME_MAX = 256, +}; + +static const ns_src defaultsrc[] = { + { NSSRC_COMPAT, NS_SUCCESS }, + { NULL, 0 } +}; + +int __gr_match_entry(const char *, size_t, enum nss_lookup_type, + const char *, gid_t); +int __gr_parse_entry(char *, size_t, struct group *, char *, size_t, + int *); + +static int is_comment_line(const char *, size_t); + +union key { + const char *name; + gid_t gid; +}; +static struct group *getgr(int (*)(union key, struct group *, char *, size_t, + struct group **), union key); +static int wrap_getgrnam_r(union key, struct group *, char *, size_t, + struct group **); +static int wrap_getgrgid_r(union key, struct group *, char *, size_t, + struct group **); +static int wrap_getgrent_r(union key, struct group *, char *, size_t, + struct group **); + +struct files_state { + FILE *fp; + int stayopen; +}; +static void files_endstate(void *); +NSS_TLS_HANDLING(files); +static int files_setgrent(void *, void *, va_list); +static int files_group(void *, void *, va_list); + + +#ifdef HESIOD +struct dns_state { + long counter; +}; +static void dns_endstate(void *); +NSS_TLS_HANDLING(dns); +static int dns_setgrent(void *, void *, va_list); +static int dns_group(void *, void *, va_list); +#endif + + +#ifdef YP +struct nis_state { + char domain[MAXHOSTNAMELEN]; + int done; + char *key; + int keylen; +}; +static void nis_endstate(void *); +NSS_TLS_HANDLING(nis); +static int nis_setgrent(void *, void *, va_list); +static int nis_group(void *, void *, va_list); +#endif + +struct compat_state { + FILE *fp; + int stayopen; + char *name; + enum _compat { + COMPAT_MODE_OFF = 0, + COMPAT_MODE_ALL, + COMPAT_MODE_NAME + } compat; +}; +static void compat_endstate(void *); +NSS_TLS_HANDLING(compat); +static int compat_setgrent(void *, void *, va_list); +static int compat_group(void *, void *, va_list); + + +/* XXX IEEE Std 1003.1, 2003 specifies `void setgrent(void)' */ +int +setgrent(void) +{ + static const ns_dtab dtab[] = { + { NSSRC_FILES, files_setgrent, (void *)SETGRENT }, +#ifdef HESIOD + { NSSRC_DNS, dns_setgrent, (void *)SETGRENT }, +#endif +#ifdef YP + { NSSRC_NIS, nis_setgrent, (void *)SETGRENT }, +#endif + { NSSRC_COMPAT, compat_setgrent, (void *)SETGRENT }, + { NULL, NULL, NULL } + }; + (void)_nsdispatch(NULL, dtab, NSDB_GROUP, "setgrent", defaultsrc, 0); + return (1); +} + + +int +setgroupent(int stayopen) +{ + static const ns_dtab dtab[] = { + { NSSRC_FILES, files_setgrent, (void *)SETGRENT }, +#ifdef HESIOD + { NSSRC_DNS, dns_setgrent, (void *)SETGRENT }, +#endif +#ifdef YP + { NSSRC_NIS, nis_setgrent, (void *)SETGRENT }, +#endif + { NSSRC_COMPAT, compat_setgrent, (void *)SETGRENT }, + { NULL, NULL, NULL } + }; + (void)_nsdispatch(NULL, dtab, NSDB_GROUP, "setgrent", defaultsrc, + stayopen); + return (1); +} + + +void +endgrent(void) +{ + static const ns_dtab dtab[] = { + { NSSRC_FILES, files_setgrent, (void *)ENDGRENT }, +#ifdef HESIOD + { NSSRC_DNS, dns_setgrent, (void *)ENDGRENT }, +#endif +#ifdef YP + { NSSRC_NIS, nis_setgrent, (void *)ENDGRENT }, +#endif + { NSSRC_COMPAT, compat_setgrent, (void *)ENDGRENT }, + { NULL, NULL, NULL } + }; + (void)_nsdispatch(NULL, dtab, NSDB_GROUP, "endgrent", defaultsrc); +} + + +int +getgrent_r(struct group *grp, char *buffer, size_t bufsize, + struct group **result) +{ + static const ns_dtab dtab[] = { + { NSSRC_FILES, files_group, (void *)nss_lt_all }, +#ifdef HESIOD + { NSSRC_DNS, dns_group, (void *)nss_lt_all }, +#endif +#ifdef YP + { NSSRC_NIS, nis_group, (void *)nss_lt_all }, +#endif + { NSSRC_COMPAT, compat_group, (void *)nss_lt_all }, + { NULL, NULL, NULL } + }; + int rv, ret_errno; + + ret_errno = 0; + *result = NULL; + rv = _nsdispatch(result, dtab, NSDB_GROUP, "getgrent_r", defaultsrc, + grp, buffer, bufsize, &ret_errno); + if (rv == NS_SUCCESS) + return (0); + else + return (ret_errno); +} + + +int +getgrnam_r(const char *name, struct group *grp, char *buffer, size_t bufsize, + struct group **result) +{ + static const ns_dtab dtab[] = { + { NSSRC_FILES, files_group, (void *)nss_lt_name }, +#ifdef HESIOD + { NSSRC_DNS, dns_group, (void *)nss_lt_name }, +#endif +#ifdef YP + { NSSRC_NIS, nis_group, (void *)nss_lt_name }, +#endif + { NSSRC_COMPAT, compat_group, (void *)nss_lt_name }, + { NULL, NULL, NULL } + }; + int rv, ret_errno; + + ret_errno = 0; + *result = NULL; + rv = _nsdispatch(result, dtab, NSDB_GROUP, "getgrnam_r", defaultsrc, + name, grp, buffer, bufsize, &ret_errno); + if (rv == NS_SUCCESS) + return (0); + else + return (ret_errno); +} + + +int +getgrgid_r(gid_t gid, struct group *grp, char *buffer, size_t bufsize, + struct group **result) +{ + static const ns_dtab dtab[] = { + { NSSRC_FILES, files_group, (void *)nss_lt_id }, +#ifdef HESIOD + { NSSRC_DNS, dns_group, (void *)nss_lt_id }, +#endif +#ifdef YP + { NSSRC_NIS, nis_group, (void *)nss_lt_id }, +#endif + { NSSRC_COMPAT, compat_group, (void *)nss_lt_id }, + { NULL, NULL, NULL } + }; + int rv, ret_errno; + + ret_errno = 0; + *result = NULL; + rv = _nsdispatch(result, dtab, NSDB_GROUP, "getgrgid_r", defaultsrc, + gid, grp, buffer, bufsize, &ret_errno); + if (rv == NS_SUCCESS) + return (0); + else + return (ret_errno); +} + + +static struct group grp; +static char *grp_storage; +static size_t grp_storage_size; + +static struct group * +getgr(int (*fn)(union key, struct group *, char *, size_t, struct group **), + union key key) +{ + int rv; + struct group *res; + + if (grp_storage == NULL) { + grp_storage = malloc(GRP_STORAGE_INITIAL); + if (grp_storage == NULL) + return (NULL); + grp_storage_size = GRP_STORAGE_INITIAL; + } + do { + rv = fn(key, &grp, grp_storage, grp_storage_size, &res); + if (res == NULL && rv == ERANGE) { + free(grp_storage); + if ((grp_storage_size << 1) > GRP_STORAGE_MAX) { + grp_storage = NULL; + errno = ERANGE; + return (NULL); + } + grp_storage_size <<= 1; + grp_storage = malloc(grp_storage_size); + if (grp_storage == NULL) + return (NULL); + } + } while (res == NULL && rv == ERANGE); + if (rv != 0) + errno = rv; + return (res); +} + + +static int +wrap_getgrnam_r(union key key, struct group *grp, char *buffer, size_t bufsize, + struct group **res) +{ + return (getgrnam_r(key.name, grp, buffer, bufsize, res)); +} + + +static int +wrap_getgrgid_r(union key key, struct group *grp, char *buffer, size_t bufsize, + struct group **res) +{ + return (getgrgid_r(key.gid, grp, buffer, bufsize, res)); +} + + +static int +wrap_getgrent_r(union key key __unused, struct group *grp, char *buffer, + size_t bufsize, struct group **res) +{ + return (getgrent_r(grp, buffer, bufsize, res)); +} + + +struct group * +getgrnam(const char *name) +{ + union key key; + + key.name = name; + return (getgr(wrap_getgrnam_r, key)); +} + + +struct group * +getgrgid(gid_t gid) +{ + union key key; + + key.gid = gid; + return (getgr(wrap_getgrgid_r, key)); +} + + +struct group * +getgrent(void) +{ + union key key; + + key.gid = 0; /* not used */ + return (getgr(wrap_getgrent_r, key)); +} + + +static int +is_comment_line(const char *s, size_t n) +{ + const char *eom; + + eom = &s[n]; + + for (; s < eom; s++) + if (*s == '#' || !isspace((unsigned char)*s)) + break; + return (*s == '#' || s == eom); +} + + +/* + * files backend + */ +static void +files_endstate(void *p) +{ + + if (p == NULL) + return; + if (((struct files_state *)p)->fp != NULL) + fclose(((struct files_state *)p)->fp); + free(p); +} + + +static int +files_setgrent(void *retval, void *mdata, va_list ap) +{ + struct files_state *st; + int rv, stayopen; + + rv = files_getstate(&st); + if (rv != 0) + return (NS_UNAVAIL); + switch ((enum constants)mdata) { + case SETGRENT: + stayopen = va_arg(ap, int); + if (st->fp != NULL) + rewind(st->fp); + else if (stayopen) + st->fp = fopen(_PATH_GROUP, "r"); + break; + case ENDGRENT: + if (st->fp != NULL) { + fclose(st->fp); + st->fp = NULL; + } + break; + default: + break; + } + return (NS_UNAVAIL); +} + + +static int +files_group(void *retval, void *mdata, va_list ap) +{ + struct files_state *st; + enum nss_lookup_type how; + const char *name, *line; + struct group *grp; + gid_t gid; + char *buffer; + size_t bufsize, linesize; + off_t pos; + int rv, stayopen, *errnop; + + name = NULL; + gid = (gid_t)-1; + how = (enum nss_lookup_type)mdata; + switch (how) { + case nss_lt_name: + name = va_arg(ap, const char *); + break; + case nss_lt_id: + gid = va_arg(ap, gid_t); + break; + case nss_lt_all: + break; + default: + return (NS_NOTFOUND); + } + grp = va_arg(ap, struct group *); + buffer = va_arg(ap, char *); + bufsize = va_arg(ap, size_t); + errnop = va_arg(ap, int *); + *errnop = files_getstate(&st); + if (*errnop != 0) + return (NS_UNAVAIL); + if (st->fp == NULL && + ((st->fp = fopen(_PATH_GROUP, "r")) == NULL)) { + *errnop = errno; + return (NS_UNAVAIL); + } + if (how == nss_lt_all) + stayopen = 1; + else { + rewind(st->fp); + stayopen = st->stayopen; + } + rv = NS_NOTFOUND; + pos = ftello(st->fp); + while ((line = fgetln(st->fp, &linesize)) != NULL) { + if (line[linesize-1] == '\n') + linesize--; + rv = __gr_match_entry(line, linesize, how, name, gid); + if (rv != NS_SUCCESS) + continue; + /* We need room at least for the line, a string NUL + * terminator, alignment padding, and one (char *) + * pointer for the member list terminator. + */ + if (bufsize <= linesize + _ALIGNBYTES + sizeof(char *)) { + *errnop = ERANGE; + rv = NS_RETURN; + break; + } + memcpy(buffer, line, linesize); + buffer[linesize] = '\0'; + rv = __gr_parse_entry(buffer, linesize, grp, + &buffer[linesize + 1], bufsize - linesize - 1, errnop); + if (rv & NS_TERMINATE) + break; + pos = ftello(st->fp); + } + if (!stayopen && st->fp != NULL) { + fclose(st->fp); + st->fp = NULL; + } + if (rv == NS_SUCCESS && retval != NULL) + *(struct group **)retval = grp; + else if (*errnop == ERANGE) + fseeko(st->fp, pos, SEEK_SET); + return (rv); +} + + +#ifdef HESIOD +/* + * dns backend + */ +static void +dns_endstate(void *p) +{ + + free(p); +} + + +static int +dns_setgrent(void *retval, void *cb_data, va_list ap) +{ + struct dns_state *st; + int rv; + + rv = dns_getstate(&st); + if (rv != 0) + return (NS_UNAVAIL); + st->counter = 0; + return (NS_UNAVAIL); +} + + +static int +dns_group(void *retval, void *mdata, va_list ap) +{ + char buf[HESIOD_NAME_MAX]; + struct dns_state *st; + struct group *grp; + const char *name, *label; + void *ctx; + char *buffer, **hes; + size_t bufsize, adjsize, linesize; + gid_t gid; + enum nss_lookup_type how; + int rv, *errnop; + + ctx = NULL; + hes = NULL; + name = NULL; + gid = (gid_t)-1; + how = (enum nss_lookup_type)mdata; + switch (how) { + case nss_lt_name: + name = va_arg(ap, const char *); + break; + case nss_lt_id: + gid = va_arg(ap, gid_t); + break; + case nss_lt_all: + break; + } + grp = va_arg(ap, struct group *); + buffer = va_arg(ap, char *); + bufsize = va_arg(ap, size_t); + errnop = va_arg(ap, int *); + *errnop = dns_getstate(&st); + if (*errnop != 0) + return (NS_UNAVAIL); + if (hesiod_init(&ctx) != 0) { + *errnop = errno; + rv = NS_UNAVAIL; + goto fin; + } + do { + rv = NS_NOTFOUND; + switch (how) { + case nss_lt_name: + label = name; + break; + case nss_lt_id: + if (snprintf(buf, sizeof(buf), "%lu", + (unsigned long)gid) >= sizeof(buf)) + goto fin; + label = buf; + break; + case nss_lt_all: + if (st->counter < 0) + goto fin; + if (snprintf(buf, sizeof(buf), "group-%ld", + st->counter++) >= sizeof(buf)) + goto fin; + label = buf; + break; + } + hes = hesiod_resolve(ctx, label, + how == nss_lt_id ? "gid" : "group"); + if ((how == nss_lt_id && hes == NULL && + (hes = hesiod_resolve(ctx, buf, "group")) == NULL) || + hes == NULL) { + if (how == nss_lt_all) + st->counter = -1; + if (errno != ENOENT) + *errnop = errno; + goto fin; + } + rv = __gr_match_entry(hes[0], strlen(hes[0]), how, name, gid); + if (rv != NS_SUCCESS) { + hesiod_free_list(ctx, hes); + hes = NULL; + continue; + } + /* We need room at least for the line, a string NUL + * terminator, alignment padding, and one (char *) + * pointer for the member list terminator. + */ + adjsize = bufsize - _ALIGNBYTES - sizeof(char *); + linesize = strlcpy(buffer, hes[0], adjsize); + if (linesize >= adjsize) { + *errnop = ERANGE; + rv = NS_RETURN; + goto fin; + } + hesiod_free_list(ctx, hes); + hes = NULL; + rv = __gr_parse_entry(buffer, linesize, grp, + &buffer[linesize + 1], bufsize - linesize - 1, errnop); + } while (how == nss_lt_all && !(rv & NS_TERMINATE)); +fin: + if (hes != NULL) + hesiod_free_list(ctx, hes); + if (ctx != NULL) + hesiod_end(ctx); + if (rv == NS_SUCCESS && retval != NULL) + *(struct group **)retval = grp; + return (rv); +} +#endif /* HESIOD */ + + +#ifdef YP +/* + * nis backend + */ +static void +nis_endstate(void *p) +{ + + if (p == NULL) + return; + free(((struct nis_state *)p)->key); + free(p); +} + + +static int +nis_setgrent(void *retval, void *cb_data, va_list ap) +{ + struct nis_state *st; + int rv; + + rv = nis_getstate(&st); + if (rv != 0) + return (NS_UNAVAIL); + st->done = 0; + free(st->key); + st->key = NULL; + return (NS_UNAVAIL); +} + + +static int +nis_group(void *retval, void *mdata, va_list ap) +{ + char *map; + struct nis_state *st; + struct group *grp; + const char *name; + char *buffer, *key, *result; + size_t bufsize; + gid_t gid; + enum nss_lookup_type how; + int *errnop, keylen, resultlen, rv; + + name = NULL; + gid = (gid_t)-1; + how = (enum nss_lookup_type)mdata; + switch (how) { + case nss_lt_name: + name = va_arg(ap, const char *); + map = "group.byname"; + break; + case nss_lt_id: + gid = va_arg(ap, gid_t); + map = "group.bygid"; + break; + case nss_lt_all: + map = "group.byname"; + break; + } + grp = va_arg(ap, struct group *); + buffer = va_arg(ap, char *); + bufsize = va_arg(ap, size_t); + errnop = va_arg(ap, int *); + *errnop = nis_getstate(&st); + if (*errnop != 0) + return (NS_UNAVAIL); + if (st->domain[0] == '\0') { + if (getdomainname(st->domain, sizeof(st->domain)) != 0) { + *errnop = errno; + return (NS_UNAVAIL); + } + } + result = NULL; + do { + rv = NS_NOTFOUND; + switch (how) { + case nss_lt_name: + if (strlcpy(buffer, name, bufsize) >= bufsize) + goto erange; + break; + case nss_lt_id: + if (snprintf(buffer, bufsize, "%lu", + (unsigned long)gid) >= bufsize) + goto erange; + break; + case nss_lt_all: + if (st->done) + goto fin; + break; + } + result = NULL; + if (how == nss_lt_all) { + if (st->key == NULL) + rv = yp_first(st->domain, map, &st->key, + &st->keylen, &result, &resultlen); + else { + key = st->key; + keylen = st->keylen; + st->key = NULL; + rv = yp_next(st->domain, map, key, keylen, + &st->key, &st->keylen, &result, + &resultlen); + free(key); + } + if (rv != 0) { + free(result); + free(st->key); + st->key = NULL; + if (rv == YPERR_NOMORE) { + st->done = 1; + rv = NS_NOTFOUND; + } else + rv = NS_UNAVAIL; + goto fin; + } + } else { + rv = yp_match(st->domain, map, buffer, strlen(buffer), + &result, &resultlen); + if (rv == YPERR_KEY) { + rv = NS_NOTFOUND; + continue; + } else if (rv != 0) { + free(result); + rv = NS_UNAVAIL; + continue; + } + } + /* We need room at least for the line, a string NUL + * terminator, alignment padding, and one (char *) + * pointer for the member list terminator. + */ + if (resultlen >= bufsize - _ALIGNBYTES - sizeof(char *)) + goto erange; + memcpy(buffer, result, resultlen); + buffer[resultlen] = '\0'; + free(result); + rv = __gr_match_entry(buffer, resultlen, how, name, gid); + if (rv == NS_SUCCESS) + rv = __gr_parse_entry(buffer, resultlen, grp, + &buffer[resultlen+1], bufsize - resultlen - 1, + errnop); + } while (how == nss_lt_all && !(rv & NS_TERMINATE)); +fin: + if (rv == NS_SUCCESS && retval != NULL) + *(struct group **)retval = grp; + return (rv); +erange: + *errnop = ERANGE; + return (NS_RETURN); +} +#endif /* YP */ + + + +/* + * compat backend + */ +static void +compat_endstate(void *p) +{ + struct compat_state *st; + + if (p == NULL) + return; + st = (struct compat_state *)p; + free(st->name); + if (st->fp != NULL) + fclose(st->fp); + free(p); +} + + +static int +compat_setgrent(void *retval, void *mdata, va_list ap) +{ + static const ns_src compatsrc[] = { +#ifdef YP + { NSSRC_NIS, NS_SUCCESS }, +#endif + { NULL, 0 } + }; + ns_dtab dtab[] = { +#ifdef HESIOD + { NSSRC_DNS, dns_setgrent, NULL }, +#endif +#ifdef YP + { NSSRC_NIS, nis_setgrent, NULL }, +#endif + { NULL, NULL, NULL } + }; + struct compat_state *st; + int rv, stayopen; + +#define set_setent(x, y) do { \ + int i; \ + \ + for (i = 0; i < (sizeof(x)/sizeof(x[0])) - 1; i++) \ + x[i].mdata = (void *)y; \ +} while (0) + + rv = compat_getstate(&st); + if (rv != 0) + return (NS_UNAVAIL); + switch ((enum constants)mdata) { + case SETGRENT: + stayopen = va_arg(ap, int); + if (st->fp != NULL) + rewind(st->fp); + else if (stayopen) + st->fp = fopen(_PATH_GROUP, "r"); + set_setent(dtab, mdata); + (void)_nsdispatch(NULL, dtab, NSDB_GROUP_COMPAT, "setgrent", + compatsrc, 0); + break; + case ENDGRENT: + if (st->fp != NULL) { + fclose(st->fp); + st->fp = NULL; + } + set_setent(dtab, mdata); + (void)_nsdispatch(NULL, dtab, NSDB_GROUP_COMPAT, "endgrent", + compatsrc, 0); + break; + default: + break; + } + st->compat = COMPAT_MODE_OFF; + free(st->name); + st->name = NULL; + return (NS_UNAVAIL); +#undef set_setent +} + + +static int +compat_group(void *retval, void *mdata, va_list ap) +{ + static const ns_src compatsrc[] = { +#ifdef YP + { NSSRC_NIS, NS_SUCCESS }, +#endif + { NULL, 0 } + }; + ns_dtab dtab[] = { +#ifdef YP + { NSSRC_NIS, nis_group, NULL }, +#endif +#ifdef HESIOD + { NSSRC_DNS, dns_group, NULL }, +#endif + { NULL, NULL, NULL } + }; + struct compat_state *st; + enum nss_lookup_type how; + const char *name, *line; + struct group *grp; + gid_t gid; + char *buffer, *p; + void *discard; + size_t bufsize, linesize; + off_t pos; + int rv, stayopen, *errnop; + +#define set_lookup_type(x, y) do { \ + int i; \ + \ + for (i = 0; i < (sizeof(x)/sizeof(x[0])) - 1; i++) \ + x[i].mdata = (void *)y; \ +} while (0) + + name = NULL; + gid = (gid_t)-1; + how = (enum nss_lookup_type)mdata; + switch (how) { + case nss_lt_name: + name = va_arg(ap, const char *); + break; + case nss_lt_id: + gid = va_arg(ap, gid_t); + break; + case nss_lt_all: + break; + default: + return (NS_NOTFOUND); + } + grp = va_arg(ap, struct group *); + buffer = va_arg(ap, char *); + bufsize = va_arg(ap, size_t); + errnop = va_arg(ap, int *); + *errnop = compat_getstate(&st); + if (*errnop != 0) + return (NS_UNAVAIL); + if (st->fp == NULL && + ((st->fp = fopen(_PATH_GROUP, "r")) == NULL)) { + *errnop = errno; + rv = NS_UNAVAIL; + goto fin; + } + if (how == nss_lt_all) + stayopen = 1; + else { + rewind(st->fp); + stayopen = st->stayopen; + } +docompat: + switch (st->compat) { + case COMPAT_MODE_ALL: + set_lookup_type(dtab, how); + switch (how) { + case nss_lt_all: + rv = _nsdispatch(&discard, dtab, NSDB_GROUP_COMPAT, + "getgrent_r", compatsrc, grp, buffer, bufsize, + errnop); + break; + case nss_lt_id: + rv = _nsdispatch(&discard, dtab, NSDB_GROUP_COMPAT, + "getgrgid_r", compatsrc, gid, grp, buffer, bufsize, + errnop); + break; + case nss_lt_name: + rv = _nsdispatch(&discard, dtab, NSDB_GROUP_COMPAT, + "getgrnam_r", compatsrc, name, grp, buffer, + bufsize, errnop); + break; + } + if (rv & NS_TERMINATE) + goto fin; + st->compat = COMPAT_MODE_OFF; + break; + case COMPAT_MODE_NAME: + set_lookup_type(dtab, nss_lt_name); + rv = _nsdispatch(&discard, dtab, NSDB_GROUP_COMPAT, + "getgrnam_r", compatsrc, st->name, grp, buffer, bufsize, + errnop); + switch (rv) { + case NS_SUCCESS: + switch (how) { + case nss_lt_name: + if (strcmp(name, grp->gr_name) != 0) + rv = NS_NOTFOUND; + break; + case nss_lt_id: + if (gid != grp->gr_gid) + rv = NS_NOTFOUND; + break; + default: + break; + } + break; + case NS_RETURN: + goto fin; + default: + break; + } + free(st->name); + st->name = NULL; + st->compat = COMPAT_MODE_OFF; + if (rv == NS_SUCCESS) + goto fin; + break; + default: + break; + } + rv = NS_NOTFOUND; + pos = ftello(st->fp); + while ((line = fgetln(st->fp, &linesize)) != NULL) { + if (line[linesize-1] == '\n') + linesize--; + if (linesize > 2 && line[0] == '+') { + p = memchr(&line[1], ':', linesize); + if (p == NULL || p == &line[1]) + st->compat = COMPAT_MODE_ALL; + else { + st->name = malloc(p - line); + if (st->name == NULL) { + syslog(LOG_ERR, + "getgrent memory allocation failure"); + *errnop = ENOMEM; + rv = NS_UNAVAIL; + break; + } + memcpy(st->name, &line[1], p - line - 1); + st->name[p - line - 1] = '\0'; + st->compat = COMPAT_MODE_NAME; + } + goto docompat; + } + rv = __gr_match_entry(line, linesize, how, name, gid); + if (rv != NS_SUCCESS) + continue; + /* We need room at least for the line, a string NUL + * terminator, alignment padding, and one (char *) + * pointer for the member list terminator. + */ + if (bufsize <= linesize + _ALIGNBYTES + sizeof(char *)) { + *errnop = ERANGE; + rv = NS_RETURN; + break; + } + memcpy(buffer, line, linesize); + buffer[linesize] = '\0'; + rv = __gr_parse_entry(buffer, linesize, grp, + &buffer[linesize + 1], bufsize - linesize - 1, errnop); + if (rv & NS_TERMINATE) + break; + pos = ftello(st->fp); + } +fin: + if (!stayopen && st->fp != NULL) { + fclose(st->fp); + st->fp = NULL; + } + if (rv == NS_SUCCESS && retval != NULL) + *(struct group **)retval = grp; + else if (*errnop == ERANGE) + fseeko(st->fp, pos, SEEK_SET); + return (rv); +#undef set_lookup_type +} + + +/* + * common group line matching and parsing + */ +int +__gr_match_entry(const char *line, size_t linesize, enum nss_lookup_type how, + const char *name, gid_t gid) +{ + size_t namesize; + const char *p, *eol; + char *q; + unsigned long n; + int i, needed; + + if (linesize == 0 || is_comment_line(line, linesize)) + return (NS_NOTFOUND); + switch (how) { + case nss_lt_name: needed = 1; break; + case nss_lt_id: needed = 2; break; + default: needed = 2; break; + } + eol = &line[linesize]; + for (p = line, i = 0; i < needed && p < eol; p++) + if (*p == ':') + i++; + if (i < needed) + return (NS_NOTFOUND); + switch (how) { + case nss_lt_name: + namesize = strlen(name); + if (namesize + 1 == (size_t)(p - line) && + memcmp(line, name, namesize) == 0) + return (NS_SUCCESS); + break; + case nss_lt_id: + n = strtoul(p, &q, 10); + if (q < eol && *q == ':' && gid == (gid_t)n) + return (NS_SUCCESS); + break; + case nss_lt_all: + return (NS_SUCCESS); + default: + break; + } + return (NS_NOTFOUND); +} + + +int +__gr_parse_entry(char *line, size_t linesize, struct group *grp, char *membuf, + size_t membufsize, int *errnop) +{ + char *s_gid, *s_mem, *p, **members; + unsigned long n; + int maxmembers; + + memset(grp, 0, sizeof(*grp)); + members = (char **)_ALIGN(membuf); + membufsize -= (char *)members - membuf; + maxmembers = membufsize / sizeof(*members); + if (maxmembers <= 0 || + (grp->gr_name = strsep(&line, ":")) == NULL || + grp->gr_name[0] == '\0' || + (grp->gr_passwd = strsep(&line, ":")) == NULL || + (s_gid = strsep(&line, ":")) == NULL || + s_gid[0] == '\0') + return (NS_NOTFOUND); + s_mem = line; + n = strtoul(s_gid, &s_gid, 10); + if (s_gid[0] != '\0') + return (NS_NOTFOUND); + grp->gr_gid = (gid_t)n; + grp->gr_mem = members; + while (maxmembers > 1 && s_mem != NULL) { + p = strsep(&s_mem, ","); + if (p != NULL && *p != '\0') { + *members++ = p; + maxmembers--; + } + } + *members = NULL; + if (s_mem == NULL) + return (NS_SUCCESS); + else { + *errnop = ERANGE; + return (NS_RETURN); + } +} diff --git a/lib/libc/gen/getgrouplist.c b/lib/libc/gen/getgrouplist.c new file mode 100644 index 0000000..3fa62c5 --- /dev/null +++ b/lib/libc/gen/getgrouplist.c @@ -0,0 +1,91 @@ +/*- + * Copyright (c) 1991, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)getgrouplist.c 8.2 (Berkeley) 12/8/94"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/getgrouplist.c,v 1.14 2005/05/03 16:20:03 delphij Exp $"); + +/* + * get credential + */ +#include + +#include +#include +#include + +int +getgrouplist(const char *uname, gid_t agroup, gid_t *groups, int *grpcnt) +{ + const struct group *grp; + int i, maxgroups, ngroups, ret; + + ret = 0; + ngroups = 0; + maxgroups = *grpcnt; + /* + * When installing primary group, duplicate it; + * the first element of groups is the effective gid + * and will be overwritten when a setgid file is executed. + */ + groups[ngroups++] = agroup; + if (maxgroups > 1) + groups[ngroups++] = agroup; + /* + * Scan the group file to find additional groups. + */ + setgrent(); + while ((grp = getgrent()) != NULL) { + for (i = 0; i < ngroups; i++) { + if (grp->gr_gid == groups[i]) + goto skip; + } + for (i = 0; grp->gr_mem[i]; i++) { + if (!strcmp(grp->gr_mem[i], uname)) { + if (ngroups >= maxgroups) { + ret = -1; + break; + } + groups[ngroups++] = grp->gr_gid; + break; + } + } +skip: + ; + } + endgrent(); + *grpcnt = ngroups; + return (ret); +} diff --git a/lib/libc/gen/gethostname.c b/lib/libc/gen/gethostname.c new file mode 100644 index 0000000..9071be2 --- /dev/null +++ b/lib/libc/gen/gethostname.c @@ -0,0 +1,63 @@ +/* + * Copyright (c) 1989, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)gethostname.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/gethostname.c,v 1.5 2003/08/19 23:01:46 wollman Exp $"); + +#include +#include + +#include + +int +gethostname(name, namelen) + char *name; + size_t namelen; +{ + int mib[2]; + + /* Kluge to avoid ABI breakage. */ + namelen = (int)namelen; + + mib[0] = CTL_KERN; + mib[1] = KERN_HOSTNAME; + if (sysctl(mib, 2, name, &namelen, NULL, 0) == -1) { + if (errno == ENOMEM) + errno = ENAMETOOLONG; + return (-1); + } + return (0); +} diff --git a/lib/libc/gen/getloadavg.c b/lib/libc/gen/getloadavg.c new file mode 100644 index 0000000..c3450f1 --- /dev/null +++ b/lib/libc/gen/getloadavg.c @@ -0,0 +1,73 @@ +/*- + * Copyright (c) 1989, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)getloadavg.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/getloadavg.c,v 1.2 2002/03/22 21:52:05 obrien Exp $"); + +#include +#include +#include +#include +#include + +#include + +/* + * getloadavg() -- Get system load averages. + * + * Put `nelem' samples into `loadavg' array. + * Return number of samples retrieved, or -1 on error. + */ +int +getloadavg(loadavg, nelem) + double loadavg[]; + int nelem; +{ + struct loadavg loadinfo; + int i, mib[2]; + size_t size; + + mib[0] = CTL_VM; + mib[1] = VM_LOADAVG; + size = sizeof(loadinfo); + if (sysctl(mib, 2, &loadinfo, &size, NULL, 0) < 0) + return (-1); + + nelem = MIN(nelem, sizeof(loadinfo.ldavg) / sizeof(fixpt_t)); + for (i = 0; i < nelem; i++) + loadavg[i] = (double) loadinfo.ldavg[i] / loadinfo.fscale; + return (nelem); +} diff --git a/lib/libc/gen/getlogin.c b/lib/libc/gen/getlogin.c new file mode 100644 index 0000000..6e3208c --- /dev/null +++ b/lib/libc/gen/getlogin.c @@ -0,0 +1,106 @@ +/* + * Copyright (c) 1988, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)getlogin.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/getlogin.c,v 1.9 2003/10/29 10:45:01 tjr Exp $"); + +#include +#include +#include +#include +#include +#include +#include +#include "namespace.h" +#include +#include "un-namespace.h" + +#include "libc_private.h" + +#define THREAD_LOCK() if (__isthreaded) _pthread_mutex_lock(&logname_mutex) +#define THREAD_UNLOCK() if (__isthreaded) _pthread_mutex_unlock(&logname_mutex) + +extern int _getlogin(char *, int); + +int _logname_valid; /* known to setlogin() */ +static pthread_mutex_t logname_mutex = PTHREAD_MUTEX_INITIALIZER; + +static char * +getlogin_basic(int *status) +{ + static char logname[MAXLOGNAME]; + + if (_logname_valid == 0) { + if (_getlogin(logname, sizeof(logname)) < 0) { + *status = errno; + return (NULL); + } + _logname_valid = 1; + } + *status = 0; + return (*logname ? logname : NULL); +} + +char * +getlogin(void) +{ + char *result; + int status; + + THREAD_LOCK(); + result = getlogin_basic(&status); + THREAD_UNLOCK(); + return (result); +} + +int +getlogin_r(char *logname, int namelen) +{ + char *result; + int len; + int status; + + THREAD_LOCK(); + result = getlogin_basic(&status); + if (status == 0) { + if ((len = strlen(result) + 1) > namelen) + status = ERANGE; + else + strncpy(logname, result, len); + } + THREAD_UNLOCK(); + return (status); +} diff --git a/lib/libc/gen/getmntinfo.c b/lib/libc/gen/getmntinfo.c new file mode 100644 index 0000000..383df1e --- /dev/null +++ b/lib/libc/gen/getmntinfo.c @@ -0,0 +1,72 @@ +/* + * Copyright (c) 1989, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)getmntinfo.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/getmntinfo.c,v 1.4 2002/02/01 00:57:29 obrien Exp $"); + +#include +#include +#include +#include + +/* + * Return information about mounted filesystems. + */ +int +getmntinfo(mntbufp, flags) + struct statfs **mntbufp; + int flags; +{ + static struct statfs *mntbuf; + static int mntsize; + static long bufsize; + + if (mntsize <= 0 && (mntsize = getfsstat(0, 0, MNT_NOWAIT)) < 0) + return (0); + if (bufsize > 0 && (mntsize = getfsstat(mntbuf, bufsize, flags)) < 0) + return (0); + while (bufsize <= mntsize * sizeof(struct statfs)) { + if (mntbuf) + free(mntbuf); + bufsize = (mntsize + 1) * sizeof(struct statfs); + if ((mntbuf = (struct statfs *)malloc(bufsize)) == 0) + return (0); + if ((mntsize = getfsstat(mntbuf, bufsize, flags)) < 0) + return (0); + } + *mntbufp = mntbuf; + return (mntsize); +} diff --git a/lib/libc/gen/getnetgrent.c b/lib/libc/gen/getnetgrent.c new file mode 100644 index 0000000..de7d43b --- /dev/null +++ b/lib/libc/gen/getnetgrent.c @@ -0,0 +1,642 @@ +/* + * Copyright (c) 1992, 1993 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * Rick Macklem at The University of Guelph. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)getnetgrent.c 8.2 (Berkeley) 4/27/95"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/getnetgrent.c,v 1.33.2.1 2005/10/07 19:38:07 jon Exp $"); + +#include +#include +#include +#include +#include + +#ifdef YP +/* + * Notes: + * We want to be able to use NIS netgroups properly while retaining + * the ability to use a local /etc/netgroup file. Unfortunately, you + * can't really do both at the same time - at least, not efficiently. + * NetBSD deals with this problem by creating a netgroup database + * using Berkeley DB (just like the password database) that allows + * for lookups using netgroup, netgroup.byuser or netgroup.byhost + * searches. This is a neat idea, but I don't have time to implement + * something like that now. (I think ultimately it would be nice + * if we DB-fied the group and netgroup stuff all in one shot, but + * for now I'm satisfied just to have something that works well + * without requiring massive code changes.) + * + * Therefore, to still permit the use of the local file and maintain + * optimum NIS performance, we allow for the following conditions: + * + * - If /etc/netgroup does not exist and NIS is turned on, we use + * NIS netgroups only. + * + * - If /etc/netgroup exists but is empty, we use NIS netgroups + * only. + * + * - If /etc/netgroup exists and contains _only_ a '+', we use + * NIS netgroups only. + * + * - If /etc/netgroup exists, contains locally defined netgroups + * and a '+', we use a mixture of NIS and the local entries. + * This method should return the same NIS data as just using + * NIS alone, but it will be slower if the NIS netgroup database + * is large (innetgr() in particular will suffer since extra + * processing has to be done in order to determine memberships + * using just the raw netgroup data). + * + * - If /etc/netgroup exists and contains only locally defined + * netgroup entries, we use just those local entries and ignore + * NIS (this is the original, pre-NIS behavior). + */ + +#include +#include +#include +#include +#include +#include +#include +static char *_netgr_yp_domain; +int _use_only_yp; +static int _netgr_yp_enabled; +static int _yp_innetgr; +#endif + +#ifndef _PATH_NETGROUP +#define _PATH_NETGROUP "/etc/netgroup" +#endif + +/* + * Static Variables and functions used by setnetgrent(), getnetgrent() and + * endnetgrent(). + * There are two linked lists: + * - linelist is just used by setnetgrent() to parse the net group file via. + * parse_netgrp() + * - netgrp is the list of entries for the current netgroup + */ +struct linelist { + struct linelist *l_next; /* Chain ptr. */ + int l_parsed; /* Flag for cycles */ + char *l_groupname; /* Name of netgroup */ + char *l_line; /* Netgroup entrie(s) to be parsed */ +}; + +struct netgrp { + struct netgrp *ng_next; /* Chain ptr */ + char *ng_str[3]; /* Field pointers, see below */ +}; +#define NG_HOST 0 /* Host name */ +#define NG_USER 1 /* User name */ +#define NG_DOM 2 /* and Domain name */ + +static struct linelist *linehead = (struct linelist *)0; +static struct netgrp *nextgrp = (struct netgrp *)0; +static struct { + struct netgrp *gr; + char *grname; +} grouphead = { + (struct netgrp *)0, + (char *)0, +}; +static FILE *netf = (FILE *)0; + +static int parse_netgrp(const char *); +static struct linelist *read_for_group(const char *); +void setnetgrent(const char *); +void endnetgrent(void); +int getnetgrent(char **, char **, char **); +int innetgr(const char *, const char *, const char *, const char *); + +#define LINSIZ 1024 /* Length of netgroup file line */ + +/* + * setnetgrent() + * Parse the netgroup file looking for the netgroup and build the list + * of netgrp structures. Let parse_netgrp() and read_for_group() do + * most of the work. + */ +void +setnetgrent(const char *group) +{ +#ifdef YP + struct stat _yp_statp; + char _yp_plus; +#endif + + /* Sanity check */ + + if (group == NULL || !strlen(group)) + return; + + if (grouphead.gr == (struct netgrp *)0 || + strcmp(group, grouphead.grname)) { + endnetgrent(); +#ifdef YP + /* Presumed guilty until proven innocent. */ + _use_only_yp = 0; + /* + * If /etc/netgroup doesn't exist or is empty, + * use NIS exclusively. + */ + if (((stat(_PATH_NETGROUP, &_yp_statp) < 0) && + errno == ENOENT) || _yp_statp.st_size == 0) + _use_only_yp = _netgr_yp_enabled = 1; + if ((netf = fopen(_PATH_NETGROUP,"r")) != NULL ||_use_only_yp){ + /* + * Icky: grab the first character of the netgroup file + * and turn on NIS if it's a '+'. rewind the stream + * afterwards so we don't goof up read_for_group() later. + */ + if (netf) { + fscanf(netf, "%c", &_yp_plus); + rewind(netf); + if (_yp_plus == '+') + _use_only_yp = _netgr_yp_enabled = 1; + } + /* + * If we were called specifically for an innetgr() + * lookup and we're in NIS-only mode, short-circuit + * parse_netgroup() and cut directly to the chase. + */ + if (_use_only_yp && _yp_innetgr) { + /* dohw! */ + if (netf != NULL) + fclose(netf); + return; + } +#else + if ((netf = fopen(_PATH_NETGROUP, "r"))) { +#endif + if (parse_netgrp(group)) + endnetgrent(); + else { + grouphead.grname = (char *) + malloc(strlen(group) + 1); + strcpy(grouphead.grname, group); + } + if (netf) + fclose(netf); + } + } + nextgrp = grouphead.gr; +} + +/* + * Get the next netgroup off the list. + */ +int +getnetgrent(char **hostp, char **userp, char **domp) +{ +#ifdef YP + _yp_innetgr = 0; +#endif + + if (nextgrp) { + *hostp = nextgrp->ng_str[NG_HOST]; + *userp = nextgrp->ng_str[NG_USER]; + *domp = nextgrp->ng_str[NG_DOM]; + nextgrp = nextgrp->ng_next; + return (1); + } + return (0); +} + +/* + * endnetgrent() - cleanup + */ +void +endnetgrent(void) +{ + struct linelist *lp, *olp; + struct netgrp *gp, *ogp; + + lp = linehead; + while (lp) { + olp = lp; + lp = lp->l_next; + free(olp->l_groupname); + free(olp->l_line); + free((char *)olp); + } + linehead = (struct linelist *)0; + if (grouphead.grname) { + free(grouphead.grname); + grouphead.grname = (char *)0; + } + gp = grouphead.gr; + while (gp) { + ogp = gp; + gp = gp->ng_next; + if (ogp->ng_str[NG_HOST]) + free(ogp->ng_str[NG_HOST]); + if (ogp->ng_str[NG_USER]) + free(ogp->ng_str[NG_USER]); + if (ogp->ng_str[NG_DOM]) + free(ogp->ng_str[NG_DOM]); + free((char *)ogp); + } + grouphead.gr = (struct netgrp *)0; + nextgrp = (struct netgrp *)0; +#ifdef YP + _netgr_yp_enabled = 0; +#endif +} + +#ifdef YP +static int +_listmatch(const char *list, const char *group, int len) +{ + const char *ptr = list; + const char *cptr; + int glen = strlen(group); + + /* skip possible leading whitespace */ + while(isspace((unsigned char)*ptr)) + ptr++; + + while (ptr < list + len) { + cptr = ptr; + while(*ptr != ',' && *ptr != '\0' && !isspace((unsigned char)*ptr)) + ptr++; + if (strncmp(cptr, group, glen) == 0 && glen == (ptr - cptr)) + return(1); + while(*ptr == ',' || isspace((unsigned char)*ptr)) + ptr++; + } + + return(0); +} + +static int +_revnetgr_lookup(char* lookupdom, char* map, const char* str, + const char* dom, const char* group) +{ + int y, rv, rot; + char key[MAXHOSTNAMELEN]; + char *result; + int resultlen; + + for (rot = 0; ; rot++) { + switch (rot) { + case(0): snprintf(key, MAXHOSTNAMELEN, "%s.%s", + str, dom?dom:lookupdom); + break; + case(1): snprintf(key, MAXHOSTNAMELEN, "%s.*", + str); + break; + case(2): snprintf(key, MAXHOSTNAMELEN, "*.%s", + dom?dom:lookupdom); + break; + case(3): snprintf(key, MAXHOSTNAMELEN, "*.*"); + break; + default: return(0); + } + y = yp_match(lookupdom, map, key, strlen(key), &result, + &resultlen); + if (y == 0) { + rv = _listmatch(result, group, resultlen); + free(result); + if (rv) return(1); + } else if (y != YPERR_KEY) { + /* + * If we get an error other than 'no + * such key in map' then something is + * wrong and we should stop the search. + */ + return(-1); + } + } +} +#endif + +/* + * Search for a match in a netgroup. + */ +int +innetgr(const char *group, const char *host, const char *user, const char *dom) +{ + char *hst, *usr, *dm; + /* Sanity check */ + + if (group == NULL || !strlen(group)) + return (0); + +#ifdef YP + _yp_innetgr = 1; +#endif + setnetgrent(group); +#ifdef YP + _yp_innetgr = 0; + /* + * If we're in NIS-only mode, do the search using + * NIS 'reverse netgroup' lookups. + * + * What happens with 'reverse netgroup' lookups: + * + * 1) try 'reverse netgroup' lookup + * 1.a) if host is specified and user is null: + * look in netgroup.byhost + * (try host.domain, host.*, *.domain or *.*) + * if found, return yes + * 1.b) if user is specified and host is null: + * look in netgroup.byuser + * (try host.domain, host.*, *.domain or *.*) + * if found, return yes + * 1.c) if both host and user are specified, + * don't do 'reverse netgroup' lookup. It won't work. + * 1.d) if neither host ane user are specified (why?!?) + * don't do 'reverse netgroup' lookup either. + * 2) if domain is specified and 'reverse lookup' is done: + * 'reverse lookup' was authoritative. bye bye. + * 3) otherwise, too bad, try it the slow way. + */ + if (_use_only_yp && (host == NULL) != (user == NULL)) { + int ret; + if(yp_get_default_domain(&_netgr_yp_domain)) + return(0); + ret = _revnetgr_lookup(_netgr_yp_domain, + host?"netgroup.byhost":"netgroup.byuser", + host?host:user, dom, group); + if (ret == 1) + return(1); + else if (ret == 0 && dom != NULL) + return(0); + } + + setnetgrent(group); +#endif /* YP */ + + while (getnetgrent(&hst, &usr, &dm)) + if ((host == NULL || hst == NULL || !strcmp(host, hst)) && + (user == NULL || usr == NULL || !strcmp(user, usr)) && + ( dom == NULL || dm == NULL || !strcmp(dom, dm))) { + endnetgrent(); + return (1); + } + endnetgrent(); + return (0); +} + +/* + * Parse the netgroup file setting up the linked lists. + */ +static int +parse_netgrp(const char *group) +{ + char *spos, *epos; + int len, strpos; +#ifdef DEBUG + int fields; +#endif + char *pos, *gpos; + struct netgrp *grp; + struct linelist *lp = linehead; + + /* + * First, see if the line has already been read in. + */ + while (lp) { + if (!strcmp(group, lp->l_groupname)) + break; + lp = lp->l_next; + } + if (lp == (struct linelist *)0 && + (lp = read_for_group(group)) == (struct linelist *)0) + return (1); + if (lp->l_parsed) { +#ifdef DEBUG + /* + * This error message is largely superflous since the + * code handles the error condition sucessfully, and + * spewing it out from inside libc can actually hose + * certain programs. + */ + fprintf(stderr, "Cycle in netgroup %s\n", lp->l_groupname); +#endif + return (1); + } else + lp->l_parsed = 1; + pos = lp->l_line; + /* Watch for null pointer dereferences, dammit! */ + while (pos != NULL && *pos != '\0') { + if (*pos == '(') { + grp = (struct netgrp *)malloc(sizeof (struct netgrp)); + bzero((char *)grp, sizeof (struct netgrp)); + grp->ng_next = grouphead.gr; + grouphead.gr = grp; + pos++; + gpos = strsep(&pos, ")"); +#ifdef DEBUG + fields = 0; +#endif + for (strpos = 0; strpos < 3; strpos++) { + if ((spos = strsep(&gpos, ","))) { +#ifdef DEBUG + fields++; +#endif + while (*spos == ' ' || *spos == '\t') + spos++; + if ((epos = strpbrk(spos, " \t"))) { + *epos = '\0'; + len = epos - spos; + } else + len = strlen(spos); + if (len > 0) { + grp->ng_str[strpos] = (char *) + malloc(len + 1); + bcopy(spos, grp->ng_str[strpos], + len + 1); + } + } else { + /* + * All other systems I've tested + * return NULL for empty netgroup + * fields. It's up to user programs + * to handle the NULLs appropriately. + */ + grp->ng_str[strpos] = NULL; + } + } +#ifdef DEBUG + /* + * Note: on other platforms, malformed netgroup + * entries are not normally flagged. While we + * can catch bad entries and report them, we should + * stay silent by default for compatibility's sake. + */ + if (fields < 3) + fprintf(stderr, "Bad entry (%s%s%s%s%s) in netgroup \"%s\"\n", + grp->ng_str[NG_HOST] == NULL ? "" : grp->ng_str[NG_HOST], + grp->ng_str[NG_USER] == NULL ? "" : ",", + grp->ng_str[NG_USER] == NULL ? "" : grp->ng_str[NG_USER], + grp->ng_str[NG_DOM] == NULL ? "" : ",", + grp->ng_str[NG_DOM] == NULL ? "" : grp->ng_str[NG_DOM], + lp->l_groupname); +#endif + } else { + spos = strsep(&pos, ", \t"); + if (parse_netgrp(spos)) + continue; + } + if (pos == NULL) + break; + while (*pos == ' ' || *pos == ',' || *pos == '\t') + pos++; + } + return (0); +} + +/* + * Read the netgroup file and save lines until the line for the netgroup + * is found. Return 1 if eof is encountered. + */ +static struct linelist * +read_for_group(const char *group) +{ + char *pos, *spos, *linep, *olinep; + int len, olen; + int cont; + struct linelist *lp; + char line[LINSIZ + 2]; +#ifdef YP + char *result; + int resultlen; + + while (_netgr_yp_enabled || fgets(line, LINSIZ, netf) != NULL) { + if (_netgr_yp_enabled) { + if(!_netgr_yp_domain) + if(yp_get_default_domain(&_netgr_yp_domain)) + continue; + if (yp_match(_netgr_yp_domain, "netgroup", group, + strlen(group), &result, &resultlen)) { + free(result); + if (_use_only_yp) + return ((struct linelist *)0); + else { + _netgr_yp_enabled = 0; + continue; + } + } + snprintf(line, LINSIZ, "%s %s", group, result); + free(result); + } +#else + while (fgets(line, LINSIZ, netf) != NULL) { +#endif + pos = (char *)&line; +#ifdef YP + if (*pos == '+') { + _netgr_yp_enabled = 1; + continue; + } +#endif + if (*pos == '#') + continue; + while (*pos == ' ' || *pos == '\t') + pos++; + spos = pos; + while (*pos != ' ' && *pos != '\t' && *pos != '\n' && + *pos != '\0') + pos++; + len = pos - spos; + while (*pos == ' ' || *pos == '\t') + pos++; + if (*pos != '\n' && *pos != '\0') { + lp = (struct linelist *)malloc(sizeof (*lp)); + lp->l_parsed = 0; + lp->l_groupname = (char *)malloc(len + 1); + bcopy(spos, lp->l_groupname, len); + *(lp->l_groupname + len) = '\0'; + len = strlen(pos); + olen = 0; + + /* + * Loop around handling line continuations. + */ + do { + if (*(pos + len - 1) == '\n') + len--; + if (*(pos + len - 1) == '\\') { + len--; + cont = 1; + } else + cont = 0; + if (len > 0) { + linep = (char *)malloc(olen + len + 1); + if (olen > 0) { + bcopy(olinep, linep, olen); + free(olinep); + } + bcopy(pos, linep + olen, len); + olen += len; + *(linep + olen) = '\0'; + olinep = linep; + } + if (cont) { + if (fgets(line, LINSIZ, netf)) { + pos = line; + len = strlen(pos); + } else + cont = 0; + } + } while (cont); + lp->l_line = linep; + lp->l_next = linehead; + linehead = lp; + + /* + * If this is the one we wanted, we are done. + */ + if (!strcmp(lp->l_groupname, group)) + return (lp); + } + } +#ifdef YP + /* + * Yucky. The recursive nature of this whole mess might require + * us to make more than one pass through the netgroup file. + * This might be best left outside the #ifdef YP, but YP is + * defined by default anyway, so I'll leave it like this + * until I know better. + */ + rewind(netf); +#endif + return ((struct linelist *)0); +} diff --git a/lib/libc/gen/getobjformat.c b/lib/libc/gen/getobjformat.c new file mode 100644 index 0000000..d1ac7df --- /dev/null +++ b/lib/libc/gen/getobjformat.c @@ -0,0 +1,44 @@ +/*- + * Copyright (c) 1998 John D. Polstra + * 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 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 AUTHOR 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 +__FBSDID("$FreeBSD: src/lib/libc/gen/getobjformat.c,v 1.7 2002/09/17 01:48:50 peter Exp $"); + +#include +#include +#include +#include +#include + +int +getobjformat(char *buf, size_t bufsize, int *argcp, char **argv) +{ + + if (bufsize < 4) + return -1; + strcpy(buf, "elf"); + return 3; +} diff --git a/lib/libc/gen/getosreldate.c b/lib/libc/gen/getosreldate.c new file mode 100644 index 0000000..97cd9bf --- /dev/null +++ b/lib/libc/gen/getosreldate.c @@ -0,0 +1,56 @@ +/* + * Copyright (c) 1989, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)gethostid.c 8.1 (Berkeley) 6/2/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/getosreldate.c,v 1.6 2002/05/28 16:59:39 alfred Exp $"); + +#include +#include + +int +getosreldate(void) +{ + int mib[2]; + size_t size; + int value; + + mib[0] = CTL_KERN; + mib[1] = KERN_OSRELDATE; + size = sizeof value; + if (sysctl(mib, 2, &value, &size, NULL, 0) == -1) + return (-1); + return (value); +} diff --git a/lib/libc/gen/getpagesize.c b/lib/libc/gen/getpagesize.c new file mode 100644 index 0000000..3c8881e --- /dev/null +++ b/lib/libc/gen/getpagesize.c @@ -0,0 +1,66 @@ +/* + * Copyright (c) 1989, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)getpagesize.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/getpagesize.c,v 1.4 2002/02/01 00:57:29 obrien Exp $"); + +#include +#include + +/* + * This is unlikely to change over the running time of any + * program, so we cache the result to save some syscalls. + * + * NB: This function may be called from malloc(3) at initialization + * NB: so must not result in a malloc(3) related call! + */ + +int +getpagesize() +{ + int mib[2]; + static int value; + size_t size; + + if (!value) { + mib[0] = CTL_HW; + mib[1] = HW_PAGESIZE; + size = sizeof value; + if (sysctl(mib, 2, &value, &size, NULL, 0) == -1) + return (-1); + } + return (value); +} diff --git a/lib/libc/gen/getpeereid.c b/lib/libc/gen/getpeereid.c new file mode 100644 index 0000000..5608c48 --- /dev/null +++ b/lib/libc/gen/getpeereid.c @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2001 Dima Dorfman. + * 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 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 AUTHOR 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 +__FBSDID("$FreeBSD: src/lib/libc/gen/getpeereid.c,v 1.6 2002/12/16 13:42:13 maxim Exp $"); + +#include +#include +#include +#include + +#include +#include + +int +getpeereid(int s, uid_t *euid, gid_t *egid) +{ + struct xucred xuc; + socklen_t xuclen; + int error; + + xuclen = sizeof(xuc); + error = getsockopt(s, 0, LOCAL_PEERCRED, &xuc, &xuclen); + if (error != 0) + return (error); + if (xuc.cr_version != XUCRED_VERSION) + return (EINVAL); + *euid = xuc.cr_uid; + *egid = xuc.cr_gid; + return (0); +} diff --git a/lib/libc/gen/getprogname.c b/lib/libc/gen/getprogname.c new file mode 100644 index 0000000..456477b --- /dev/null +++ b/lib/libc/gen/getprogname.c @@ -0,0 +1,14 @@ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/getprogname.c,v 1.4 2002/03/29 22:43:41 markm Exp $"); + +#include "namespace.h" +#include +#include "un-namespace.h" + +#include "libc_private.h" + +__weak_reference(_getprogname, getprogname); + +const char *_getprogname(void) { + return (__progname); + } diff --git a/lib/libc/gen/getpwent.c b/lib/libc/gen/getpwent.c new file mode 100644 index 0000000..cba41da --- /dev/null +++ b/lib/libc/gen/getpwent.c @@ -0,0 +1,1732 @@ +/*- + * Copyright (c) 2003 Networks Associates Technology, Inc. + * All rights reserved. + * + * This software was developed for the FreeBSD Project by + * Jacques A. Vidrine, Safeport Network Services, and Network + * Associates Laboratories, the Security Research Division of Network + * Associates, Inc. under DARPA/SPAWAR contract N66001-01-C-8035 + * ("CBOSS"), as part of the DARPA CHATS research program. + * + * 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 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 AUTHOR 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 +__FBSDID("$FreeBSD: src/lib/libc/gen/getpwent.c,v 1.89 2004/05/17 18:27:05 kientzle Exp $"); + +#include "namespace.h" +#include +#ifdef YP +#include +#include +#include +#endif +#include +#include +#include +#ifdef HESIOD +#include +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "un-namespace.h" +#include +#include "libc_private.h" +#include "pw_scan.h" +#include "nss_tls.h" + +#ifndef CTASSERT +#define CTASSERT(x) _CTASSERT(x, __LINE__) +#define _CTASSERT(x, y) __CTASSERT(x, y) +#define __CTASSERT(x, y) typedef char __assert_ ## y [(x) ? 1 : -1] +#endif + +/* Counter as stored in /etc/pwd.db */ +typedef int pwkeynum; + +CTASSERT(MAXLOGNAME > sizeof(uid_t)); +CTASSERT(MAXLOGNAME > sizeof(pwkeynum)); + +enum constants { + PWD_STORAGE_INITIAL = 1 << 10, /* 1 KByte */ + PWD_STORAGE_MAX = 1 << 20, /* 1 MByte */ + SETPWENT = 1, + ENDPWENT = 2, + HESIOD_NAME_MAX = 256 +}; + +static const ns_src defaultsrc[] = { + { NSSRC_COMPAT, NS_SUCCESS }, + { NULL, 0 } +}; + +int __pw_match_entry(const char *, size_t, enum nss_lookup_type, + const char *, uid_t); +int __pw_parse_entry(char *, size_t, struct passwd *, int, int *errnop); + +static void pwd_init(struct passwd *); + +union key { + const char *name; + uid_t uid; +}; + +static struct passwd *getpw(int (*fn)(union key, struct passwd *, char *, + size_t, struct passwd **), union key); +static int wrap_getpwnam_r(union key, struct passwd *, char *, + size_t, struct passwd **); +static int wrap_getpwuid_r(union key, struct passwd *, char *, size_t, + struct passwd **); +static int wrap_getpwent_r(union key, struct passwd *, char *, size_t, + struct passwd **); + +static int pwdb_match_entry_v3(char *, size_t, enum nss_lookup_type, + const char *, uid_t); +static int pwdb_parse_entry_v3(char *, size_t, struct passwd *, int *); +static int pwdb_match_entry_v4(char *, size_t, enum nss_lookup_type, + const char *, uid_t); +static int pwdb_parse_entry_v4(char *, size_t, struct passwd *, int *); + + +struct { + int (*match)(char *, size_t, enum nss_lookup_type, const char *, + uid_t); + int (*parse)(char *, size_t, struct passwd *, int *); +} pwdb_versions[] = { + { NULL, NULL }, /* version 0 */ + { NULL, NULL }, /* version 1 */ + { NULL, NULL }, /* version 2 */ + { pwdb_match_entry_v3, pwdb_parse_entry_v3 }, /* version 3 */ + { pwdb_match_entry_v4, pwdb_parse_entry_v4 }, /* version 4 */ +}; + + +struct files_state { + DB *db; + pwkeynum keynum; + int stayopen; + int version; +}; +static void files_endstate(void *); +NSS_TLS_HANDLING(files); +static DB *pwdbopen(int *); +static void files_endstate(void *); +static int files_setpwent(void *, void *, va_list); +static int files_passwd(void *, void *, va_list); + + +#ifdef HESIOD +struct dns_state { + long counter; +}; +static void dns_endstate(void *); +NSS_TLS_HANDLING(dns); +static int dns_setpwent(void *, void *, va_list); +static int dns_passwd(void *, void *, va_list); +#endif + + +#ifdef YP +struct nis_state { + char domain[MAXHOSTNAMELEN]; + int done; + char *key; + int keylen; +}; +static void nis_endstate(void *); +NSS_TLS_HANDLING(nis); +static int nis_setpwent(void *, void *, va_list); +static int nis_passwd(void *, void *, va_list); +static int nis_map(char *, enum nss_lookup_type, char *, size_t, int *); +static int nis_adjunct(char *, const char *, char *, size_t); +#endif + + +struct compat_state { + DB *db; + pwkeynum keynum; + int stayopen; + int version; + DB *exclude; + struct passwd template; + char *name; + enum _compat { + COMPAT_MODE_OFF = 0, + COMPAT_MODE_ALL, + COMPAT_MODE_NAME, + COMPAT_MODE_NETGROUP + } compat; +}; +static void compat_endstate(void *); +NSS_TLS_HANDLING(compat); +static int compat_setpwent(void *, void *, va_list); +static int compat_passwd(void *, void *, va_list); +static void compat_clear_template(struct passwd *); +static int compat_set_template(struct passwd *, struct passwd *); +static int compat_use_template(struct passwd *, struct passwd *, char *, + size_t); +static int compat_redispatch(struct compat_state *, enum nss_lookup_type, + enum nss_lookup_type, const char *, const char *, uid_t, + struct passwd *, char *, size_t, int *); +void +setpwent(void) +{ + static const ns_dtab dtab[] = { + { NSSRC_FILES, files_setpwent, (void *)SETPWENT }, +#ifdef HESIOD + { NSSRC_DNS, dns_setpwent, (void *)SETPWENT }, +#endif +#ifdef YP + { NSSRC_NIS, nis_setpwent, (void *)SETPWENT }, +#endif + { NSSRC_COMPAT, compat_setpwent, (void *)SETPWENT }, + { NULL, NULL, NULL } + }; + (void)_nsdispatch(NULL, dtab, NSDB_PASSWD, "setpwent", defaultsrc, 0); +} + + +int +setpassent(int stayopen) +{ + static const ns_dtab dtab[] = { + { NSSRC_FILES, files_setpwent, (void *)SETPWENT }, +#ifdef HESIOD + { NSSRC_DNS, dns_setpwent, (void *)SETPWENT }, +#endif +#ifdef YP + { NSSRC_NIS, nis_setpwent, (void *)SETPWENT }, +#endif + { NSSRC_COMPAT, compat_setpwent, (void *)SETPWENT }, + { NULL, NULL, NULL } + }; + (void)_nsdispatch(NULL, dtab, NSDB_PASSWD, "setpwent", defaultsrc, + stayopen); + return (1); +} + + +void +endpwent(void) +{ + static const ns_dtab dtab[] = { + { NSSRC_FILES, files_setpwent, (void *)ENDPWENT }, +#ifdef HESIOD + { NSSRC_DNS, dns_setpwent, (void *)ENDPWENT }, +#endif +#ifdef YP + { NSSRC_NIS, nis_setpwent, (void *)ENDPWENT }, +#endif + { NSSRC_COMPAT, compat_setpwent, (void *)ENDPWENT }, + { NULL, NULL, NULL } + }; + (void)_nsdispatch(NULL, dtab, NSDB_PASSWD, "endpwent", defaultsrc); +} + + +int +getpwent_r(struct passwd *pwd, char *buffer, size_t bufsize, + struct passwd **result) +{ + static const ns_dtab dtab[] = { + { NSSRC_FILES, files_passwd, (void *)nss_lt_all }, +#ifdef HESIOD + { NSSRC_DNS, dns_passwd, (void *)nss_lt_all }, +#endif +#ifdef YP + { NSSRC_NIS, nis_passwd, (void *)nss_lt_all }, +#endif + { NSSRC_COMPAT, compat_passwd, (void *)nss_lt_all }, + { NULL, NULL, NULL } + }; + int rv, ret_errno; + + pwd_init(pwd); + ret_errno = 0; + *result = NULL; + rv = _nsdispatch(result, dtab, NSDB_PASSWD, "getpwent_r", defaultsrc, + pwd, buffer, bufsize, &ret_errno); + if (rv == NS_SUCCESS) + return (0); + else + return (ret_errno); +} + + +int +getpwnam_r(const char *name, struct passwd *pwd, char *buffer, size_t bufsize, + struct passwd **result) +{ + static const ns_dtab dtab[] = { + { NSSRC_FILES, files_passwd, (void *)nss_lt_name }, +#ifdef HESIOD + { NSSRC_DNS, dns_passwd, (void *)nss_lt_name }, +#endif +#ifdef YP + { NSSRC_NIS, nis_passwd, (void *)nss_lt_name }, +#endif + { NSSRC_COMPAT, compat_passwd, (void *)nss_lt_name }, + { NULL, NULL, NULL } + }; + int rv, ret_errno; + + pwd_init(pwd); + ret_errno = 0; + *result = NULL; + rv = _nsdispatch(result, dtab, NSDB_PASSWD, "getpwnam_r", defaultsrc, + name, pwd, buffer, bufsize, &ret_errno); + if (rv == NS_SUCCESS) + return (0); + else + return (ret_errno); +} + + +int +getpwuid_r(uid_t uid, struct passwd *pwd, char *buffer, size_t bufsize, + struct passwd **result) +{ + static const ns_dtab dtab[] = { + { NSSRC_FILES, files_passwd, (void *)nss_lt_id }, +#ifdef HESIOD + { NSSRC_DNS, dns_passwd, (void *)nss_lt_id }, +#endif +#ifdef YP + { NSSRC_NIS, nis_passwd, (void *)nss_lt_id }, +#endif + { NSSRC_COMPAT, compat_passwd, (void *)nss_lt_id }, + { NULL, NULL, NULL } + }; + int rv, ret_errno; + + pwd_init(pwd); + ret_errno = 0; + *result = NULL; + rv = _nsdispatch(result, dtab, NSDB_PASSWD, "getpwuid_r", defaultsrc, + uid, pwd, buffer, bufsize, &ret_errno); + if (rv == NS_SUCCESS) + return (0); + else + return (ret_errno); +} + + +static void +pwd_init(struct passwd *pwd) +{ + static char nul[] = ""; + + memset(pwd, 0, sizeof(*pwd)); + pwd->pw_uid = (uid_t)-1; /* Considered least likely to lead to */ + pwd->pw_gid = (gid_t)-1; /* a security issue. */ + pwd->pw_name = nul; + pwd->pw_passwd = nul; + pwd->pw_class = nul; + pwd->pw_gecos = nul; + pwd->pw_dir = nul; + pwd->pw_shell = nul; +} + + +static struct passwd pwd; +static char *pwd_storage; +static size_t pwd_storage_size; + + +static struct passwd * +getpw(int (*fn)(union key, struct passwd *, char *, size_t, struct passwd **), + union key key) +{ + int rv; + struct passwd *res; + + if (pwd_storage == NULL) { + pwd_storage = malloc(PWD_STORAGE_INITIAL); + if (pwd_storage == NULL) + return (NULL); + pwd_storage_size = PWD_STORAGE_INITIAL; + } + do { + rv = fn(key, &pwd, pwd_storage, pwd_storage_size, &res); + if (res == NULL && rv == ERANGE) { + free(pwd_storage); + if ((pwd_storage_size << 1) > PWD_STORAGE_MAX) { + pwd_storage = NULL; + errno = ERANGE; + return (NULL); + } + pwd_storage_size <<= 1; + pwd_storage = malloc(pwd_storage_size); + if (pwd_storage == NULL) + return (NULL); + } + } while (res == NULL && rv == ERANGE); + if (rv != 0) + errno = rv; + return (res); +} + + +static int +wrap_getpwnam_r(union key key, struct passwd *pwd, char *buffer, + size_t bufsize, struct passwd **res) +{ + return (getpwnam_r(key.name, pwd, buffer, bufsize, res)); +} + + +static int +wrap_getpwuid_r(union key key, struct passwd *pwd, char *buffer, + size_t bufsize, struct passwd **res) +{ + return (getpwuid_r(key.uid, pwd, buffer, bufsize, res)); +} + + +static int +wrap_getpwent_r(union key key __unused, struct passwd *pwd, char *buffer, + size_t bufsize, struct passwd **res) +{ + return (getpwent_r(pwd, buffer, bufsize, res)); +} + + +struct passwd * +getpwnam(const char *name) +{ + union key key; + + key.name = name; + return (getpw(wrap_getpwnam_r, key)); +} + + +struct passwd * +getpwuid(uid_t uid) +{ + union key key; + + key.uid = uid; + return (getpw(wrap_getpwuid_r, key)); +} + + +struct passwd * +getpwent(void) +{ + union key key; + + key.uid = 0; /* not used */ + return (getpw(wrap_getpwent_r, key)); +} + + +/* + * files backend + */ +static DB * +pwdbopen(int *version) +{ + DB *res; + DBT key, entry; + int rv; + + if (geteuid() != 0 || + (res = dbopen(_PATH_SMP_DB, O_RDONLY, 0, DB_HASH, NULL)) == NULL) + res = dbopen(_PATH_MP_DB, O_RDONLY, 0, DB_HASH, NULL); + if (res == NULL) + return (NULL); + key.data = _PWD_VERSION_KEY; + key.size = strlen(_PWD_VERSION_KEY); + rv = res->get(res, &key, &entry, 0); + if (rv == 0) + *version = *(unsigned char *)entry.data; + else + *version = 3; + if (*version < 3 || + *version >= sizeof(pwdb_versions)/sizeof(pwdb_versions[0])) { + syslog(LOG_CRIT, "Unsupported password database version %d", + *version); + res->close(res); + res = NULL; + } + return (res); +} + + +static void +files_endstate(void *p) +{ + DB *db; + + if (p == NULL) + return; + db = ((struct files_state *)p)->db; + if (db != NULL) + db->close(db); + free(p); +} + + +static int +files_setpwent(void *retval, void *mdata, va_list ap) +{ + struct files_state *st; + int rv, stayopen; + + rv = files_getstate(&st); + if (rv != 0) + return (NS_UNAVAIL); + switch ((enum constants)mdata) { + case SETPWENT: + stayopen = va_arg(ap, int); + st->keynum = 0; + if (stayopen) + st->db = pwdbopen(&st->version); + st->stayopen = stayopen; + break; + case ENDPWENT: + if (st->db != NULL) { + (void)st->db->close(st->db); + st->db = NULL; + } + break; + default: + break; + } + return (NS_UNAVAIL); +} + + +static int +files_passwd(void *retval, void *mdata, va_list ap) +{ + char keybuf[MAXLOGNAME + 1]; + DBT key, entry; + struct files_state *st; + enum nss_lookup_type how; + const char *name; + struct passwd *pwd; + char *buffer; + size_t bufsize, namesize; + uid_t uid; + uint32_t store; + int rv, stayopen, *errnop; + + name = NULL; + uid = (uid_t)-1; + how = (enum nss_lookup_type)mdata; + switch (how) { + case nss_lt_name: + name = va_arg(ap, const char *); + keybuf[0] = _PW_KEYBYNAME; + break; + case nss_lt_id: + uid = va_arg(ap, uid_t); + keybuf[0] = _PW_KEYBYUID; + break; + case nss_lt_all: + keybuf[0] = _PW_KEYBYNUM; + break; + default: + rv = NS_NOTFOUND; + goto fin; + } + pwd = va_arg(ap, struct passwd *); + buffer = va_arg(ap, char *); + bufsize = va_arg(ap, size_t); + errnop = va_arg(ap, int *); + *errnop = files_getstate(&st); + if (*errnop != 0) + return (NS_UNAVAIL); + if (how == nss_lt_all && st->keynum < 0) { + rv = NS_NOTFOUND; + goto fin; + } + if (st->db == NULL && + (st->db = pwdbopen(&st->version)) == NULL) { + *errnop = errno; + rv = NS_UNAVAIL; + goto fin; + } + if (how == nss_lt_all) + stayopen = 1; + else + stayopen = st->stayopen; + key.data = keybuf; + do { + switch (how) { + case nss_lt_name: + /* MAXLOGNAME includes NUL byte, but we do not + * include the NUL byte in the key. + */ + namesize = strlcpy(&keybuf[1], name, sizeof(keybuf)-1); + if (namesize >= sizeof(keybuf)-1) { + *errnop = EINVAL; + rv = NS_NOTFOUND; + goto fin; + } + key.size = namesize + 1; + break; + case nss_lt_id: + if (st->version < _PWD_CURRENT_VERSION) { + memcpy(&keybuf[1], &uid, sizeof(uid)); + key.size = sizeof(uid) + 1; + } else { + store = htonl(uid); + memcpy(&keybuf[1], &store, sizeof(store)); + key.size = sizeof(store) + 1; + } + break; + case nss_lt_all: + st->keynum++; + if (st->version < _PWD_CURRENT_VERSION) { + memcpy(&keybuf[1], &st->keynum, + sizeof(st->keynum)); + key.size = sizeof(st->keynum) + 1; + } else { + store = htonl(st->keynum); + memcpy(&keybuf[1], &store, sizeof(store)); + key.size = sizeof(store) + 1; + } + break; + } + keybuf[0] = _PW_VERSIONED(keybuf[0], st->version); + rv = st->db->get(st->db, &key, &entry, 0); + if (rv < 0 || rv > 1) { /* should never return > 1 */ + *errnop = errno; + rv = NS_UNAVAIL; + goto fin; + } else if (rv == 1) { + if (how == nss_lt_all) + st->keynum = -1; + rv = NS_NOTFOUND; + goto fin; + } + rv = pwdb_versions[st->version].match(entry.data, entry.size, + how, name, uid); + if (rv != NS_SUCCESS) + continue; + if (entry.size > bufsize) { + *errnop = ERANGE; + rv = NS_RETURN; + break; + } + memcpy(buffer, entry.data, entry.size); + rv = pwdb_versions[st->version].parse(buffer, entry.size, pwd, + errnop); + } while (how == nss_lt_all && !(rv & NS_TERMINATE)); +fin: + if (!stayopen && st->db != NULL) { + (void)st->db->close(st->db); + st->db = NULL; + } + if (rv == NS_SUCCESS) { + pwd->pw_fields &= ~_PWF_SOURCE; + pwd->pw_fields |= _PWF_FILES; + if (retval != NULL) + *(struct passwd **)retval = pwd; + } + return (rv); +} + + +static int +pwdb_match_entry_v3(char *entry, size_t entrysize, enum nss_lookup_type how, + const char *name, uid_t uid) +{ + const char *p, *eom; + uid_t uid2; + + eom = &entry[entrysize]; + for (p = entry; p < eom; p++) + if (*p == '\0') + break; + if (*p != '\0') + return (NS_NOTFOUND); + if (how == nss_lt_all) + return (NS_SUCCESS); + if (how == nss_lt_name) + return (strcmp(name, entry) == 0 ? NS_SUCCESS : NS_NOTFOUND); + for (p++; p < eom; p++) + if (*p == '\0') + break; + if (*p != '\0' || (++p) + sizeof(uid) >= eom) + return (NS_NOTFOUND); + memcpy(&uid2, p, sizeof(uid2)); + return (uid == uid2 ? NS_SUCCESS : NS_NOTFOUND); +} + + +static int +pwdb_parse_entry_v3(char *buffer, size_t bufsize, struct passwd *pwd, + int *errnop) +{ + char *p, *eom; + int32_t pw_change, pw_expire; + + /* THIS CODE MUST MATCH THAT IN pwd_mkdb. */ + p = buffer; + eom = &buffer[bufsize]; +#define STRING(field) do { \ + (field) = p; \ + while (p < eom && *p != '\0') \ + p++; \ + if (p >= eom) \ + return (NS_NOTFOUND); \ + p++; \ + } while (0) +#define SCALAR(field) do { \ + if (p + sizeof(field) > eom) \ + return (NS_NOTFOUND); \ + memcpy(&(field), p, sizeof(field)); \ + p += sizeof(field); \ + } while (0) + STRING(pwd->pw_name); + STRING(pwd->pw_passwd); + SCALAR(pwd->pw_uid); + SCALAR(pwd->pw_gid); + SCALAR(pw_change); + STRING(pwd->pw_class); + STRING(pwd->pw_gecos); + STRING(pwd->pw_dir); + STRING(pwd->pw_shell); + SCALAR(pw_expire); + SCALAR(pwd->pw_fields); +#undef STRING +#undef SCALAR + pwd->pw_change = pw_change; + pwd->pw_expire = pw_expire; + return (NS_SUCCESS); +} + + +static int +pwdb_match_entry_v4(char *entry, size_t entrysize, enum nss_lookup_type how, + const char *name, uid_t uid) +{ + const char *p, *eom; + uint32_t uid2; + + eom = &entry[entrysize]; + for (p = entry; p < eom; p++) + if (*p == '\0') + break; + if (*p != '\0') + return (NS_NOTFOUND); + if (how == nss_lt_all) + return (NS_SUCCESS); + if (how == nss_lt_name) + return (strcmp(name, entry) == 0 ? NS_SUCCESS : NS_NOTFOUND); + for (p++; p < eom; p++) + if (*p == '\0') + break; + if (*p != '\0' || (++p) + sizeof(uid) >= eom) + return (NS_NOTFOUND); + memcpy(&uid2, p, sizeof(uid2)); + uid2 = ntohl(uid2); + return (uid == (uid_t)uid2 ? NS_SUCCESS : NS_NOTFOUND); +} + + +static int +pwdb_parse_entry_v4(char *buffer, size_t bufsize, struct passwd *pwd, + int *errnop) +{ + char *p, *eom; + uint32_t n; + + /* THIS CODE MUST MATCH THAT IN pwd_mkdb. */ + p = buffer; + eom = &buffer[bufsize]; +#define STRING(field) do { \ + (field) = p; \ + while (p < eom && *p != '\0') \ + p++; \ + if (p >= eom) \ + return (NS_NOTFOUND); \ + p++; \ + } while (0) +#define SCALAR(field) do { \ + if (p + sizeof(n) > eom) \ + return (NS_NOTFOUND); \ + memcpy(&n, p, sizeof(n)); \ + (field) = ntohl(n); \ + p += sizeof(n); \ + } while (0) + STRING(pwd->pw_name); + STRING(pwd->pw_passwd); + SCALAR(pwd->pw_uid); + SCALAR(pwd->pw_gid); + SCALAR(pwd->pw_change); + STRING(pwd->pw_class); + STRING(pwd->pw_gecos); + STRING(pwd->pw_dir); + STRING(pwd->pw_shell); + SCALAR(pwd->pw_expire); + SCALAR(pwd->pw_fields); +#undef STRING +#undef SCALAR + return (NS_SUCCESS); +} + + +#ifdef HESIOD +/* + * dns backend + */ +static void +dns_endstate(void *p) +{ + free(p); +} + + +static int +dns_setpwent(void *retval, void *mdata, va_list ap) +{ + struct dns_state *st; + int rv; + + rv = dns_getstate(&st); + if (rv != 0) + return (NS_UNAVAIL); + st->counter = 0; + return (NS_UNAVAIL); +} + + +static int +dns_passwd(void *retval, void *mdata, va_list ap) +{ + char buf[HESIOD_NAME_MAX]; + struct dns_state *st; + struct passwd *pwd; + const char *name, *label; + void *ctx; + char *buffer, **hes; + size_t bufsize, linesize; + uid_t uid; + enum nss_lookup_type how; + int rv, *errnop; + + ctx = NULL; + hes = NULL; + name = NULL; + uid = (uid_t)-1; + how = (enum nss_lookup_type)mdata; + switch (how) { + case nss_lt_name: + name = va_arg(ap, const char *); + break; + case nss_lt_id: + uid = va_arg(ap, uid_t); + break; + case nss_lt_all: + break; + } + pwd = va_arg(ap, struct passwd *); + buffer = va_arg(ap, char *); + bufsize = va_arg(ap, size_t); + errnop = va_arg(ap, int *); + *errnop = dns_getstate(&st); + if (*errnop != 0) + return (NS_UNAVAIL); + if (hesiod_init(&ctx) != 0) { + *errnop = errno; + rv = NS_UNAVAIL; + goto fin; + } + do { + rv = NS_NOTFOUND; + switch (how) { + case nss_lt_name: + label = name; + break; + case nss_lt_id: + if (snprintf(buf, sizeof(buf), "%lu", + (unsigned long)uid) >= sizeof(buf)) + goto fin; + label = buf; + break; + case nss_lt_all: + if (st->counter < 0) + goto fin; + if (snprintf(buf, sizeof(buf), "passwd-%ld", + st->counter++) >= sizeof(buf)) + goto fin; + label = buf; + break; + } + hes = hesiod_resolve(ctx, label, + how == nss_lt_id ? "uid" : "passwd"); + if (hes == NULL) { + if (how == nss_lt_all) + st->counter = -1; + if (errno != ENOENT) + *errnop = errno; + goto fin; + } + rv = __pw_match_entry(hes[0], strlen(hes[0]), how, name, uid); + if (rv != NS_SUCCESS) { + hesiod_free_list(ctx, hes); + hes = NULL; + continue; + } + linesize = strlcpy(buffer, hes[0], bufsize); + if (linesize >= bufsize) { + *errnop = ERANGE; + rv = NS_RETURN; + continue; + } + hesiod_free_list(ctx, hes); + hes = NULL; + rv = __pw_parse_entry(buffer, bufsize, pwd, 0, errnop); + } while (how == nss_lt_all && !(rv & NS_TERMINATE)); +fin: + if (hes != NULL) + hesiod_free_list(ctx, hes); + if (ctx != NULL) + hesiod_end(ctx); + if (rv == NS_SUCCESS) { + pwd->pw_fields &= ~_PWF_SOURCE; + pwd->pw_fields |= _PWF_HESIOD; + if (retval != NULL) + *(struct passwd **)retval = pwd; + } + return (rv); +} +#endif /* HESIOD */ + + +#ifdef YP +/* + * nis backend + */ +static void +nis_endstate(void *p) +{ + free(((struct nis_state *)p)->key); + free(p); +} + +/* + * Test for the presence of special FreeBSD-specific master.passwd.by* + * maps. We do this using yp_order(). If it fails, then either the server + * doesn't have the map, or the YPPROC_ORDER procedure isn't supported by + * the server (Sun NIS+ servers in YP compat mode behave this way). If + * the master.passwd.by* maps don't exist, then let the lookup routine try + * the regular passwd.by* maps instead. If the lookup routine fails, it + * can return an error as needed. + */ +static int +nis_map(char *domain, enum nss_lookup_type how, char *buffer, size_t bufsize, + int *master) +{ + int rv, order; + + *master = 0; + if (geteuid() == 0) { + if (snprintf(buffer, bufsize, "master.passwd.by%s", + (how == nss_lt_id) ? "uid" : "name") >= bufsize) + return (NS_UNAVAIL); + rv = yp_order(domain, buffer, &order); + if (rv == 0) { + *master = 1; + return (NS_SUCCESS); + } + } + + if (snprintf(buffer, bufsize, "passwd.by%s", + (how == nss_lt_id) ? "uid" : "name") >= bufsize) + return (NS_UNAVAIL); + + return (NS_SUCCESS); +} + + +static int +nis_adjunct(char *domain, const char *name, char *buffer, size_t bufsize) +{ + int rv; + char *result, *p, *q, *eor; + int resultlen; + + result = NULL; + rv = yp_match(domain, "passwd.adjunct.byname", name, strlen(name), + &result, &resultlen); + if (rv != 0) + rv = 1; + else { + eor = &result[resultlen]; + p = memchr(result, ':', eor - result); + if (p != NULL && ++p < eor && + (q = memchr(p, ':', eor - p)) != NULL) { + if (q - p >= bufsize) + rv = -1; + else { + memcpy(buffer, p, q - p); + buffer[q - p] ='\0'; + } + } else + rv = 1; + } + free(result); + return (rv); +} + + +static int +nis_setpwent(void *retval, void *mdata, va_list ap) +{ + struct nis_state *st; + int rv; + + rv = nis_getstate(&st); + if (rv != 0) + return (NS_UNAVAIL); + st->done = 0; + free(st->key); + st->key = NULL; + return (NS_UNAVAIL); +} + + +static int +nis_passwd(void *retval, void *mdata, va_list ap) +{ + char map[YPMAXMAP]; + struct nis_state *st; + struct passwd *pwd; + const char *name; + char *buffer, *key, *result; + size_t bufsize; + uid_t uid; + enum nss_lookup_type how; + int *errnop, keylen, resultlen, rv, master; + + name = NULL; + uid = (uid_t)-1; + how = (enum nss_lookup_type)mdata; + switch (how) { + case nss_lt_name: + name = va_arg(ap, const char *); + break; + case nss_lt_id: + uid = va_arg(ap, uid_t); + break; + case nss_lt_all: + break; + } + pwd = va_arg(ap, struct passwd *); + buffer = va_arg(ap, char *); + bufsize = va_arg(ap, size_t); + errnop = va_arg(ap, int *); + *errnop = nis_getstate(&st); + if (*errnop != 0) + return (NS_UNAVAIL); + if (st->domain[0] == '\0') { + if (getdomainname(st->domain, sizeof(st->domain)) != 0) { + *errnop = errno; + return (NS_UNAVAIL); + } + } + rv = nis_map(st->domain, how, map, sizeof(map), &master); + if (rv != NS_SUCCESS) + return (rv); + result = NULL; + do { + rv = NS_NOTFOUND; + switch (how) { + case nss_lt_name: + if (strlcpy(buffer, name, bufsize) >= bufsize) + goto erange; + break; + case nss_lt_id: + if (snprintf(buffer, bufsize, "%lu", + (unsigned long)uid) >= bufsize) + goto erange; + break; + case nss_lt_all: + if (st->done) + goto fin; + break; + } + result = NULL; + if (how == nss_lt_all) { + if (st->key == NULL) + rv = yp_first(st->domain, map, &st->key, + &st->keylen, &result, &resultlen); + else { + key = st->key; + keylen = st->keylen; + st->key = NULL; + rv = yp_next(st->domain, map, key, keylen, + &st->key, &st->keylen, &result, + &resultlen); + free(key); + } + if (rv != 0) { + free(result); + free(st->key); + st->key = NULL; + if (rv == YPERR_NOMORE) + st->done = 1; + else + rv = NS_UNAVAIL; + goto fin; + } + } else { + rv = yp_match(st->domain, map, buffer, strlen(buffer), + &result, &resultlen); + if (rv == YPERR_KEY) { + rv = NS_NOTFOUND; + continue; + } else if (rv != 0) { + free(result); + rv = NS_UNAVAIL; + continue; + } + } + if (resultlen >= bufsize) + goto erange; + memcpy(buffer, result, resultlen); + buffer[resultlen] = '\0'; + free(result); + rv = __pw_match_entry(buffer, resultlen, how, name, uid); + if (rv == NS_SUCCESS) + rv = __pw_parse_entry(buffer, resultlen, pwd, master, + errnop); + } while (how == nss_lt_all && !(rv & NS_TERMINATE)); +fin: + if (rv == NS_SUCCESS) { + if (strstr(pwd->pw_passwd, "##") != NULL) { + rv = nis_adjunct(st->domain, pwd->pw_name, + &buffer[resultlen+1], bufsize-resultlen-1); + if (rv < 0) + goto erange; + else if (rv == 0) + pwd->pw_passwd = &buffer[resultlen+1]; + } + pwd->pw_fields &= ~_PWF_SOURCE; + pwd->pw_fields |= _PWF_NIS; + if (retval != NULL) + *(struct passwd **)retval = pwd; + rv = NS_SUCCESS; + } + return (rv); +erange: + *errnop = ERANGE; + return (NS_RETURN); +} +#endif /* YP */ + + +/* + * compat backend + */ +static void +compat_clear_template(struct passwd *template) +{ + + free(template->pw_passwd); + free(template->pw_gecos); + free(template->pw_dir); + free(template->pw_shell); + memset(template, 0, sizeof(*template)); +} + + +static int +compat_set_template(struct passwd *src, struct passwd *template) +{ + + compat_clear_template(template); +#ifdef PW_OVERRIDE_PASSWD + if ((src->pw_fields & _PWF_PASSWD) && + (template->pw_passwd = strdup(src->pw_passwd)) == NULL) + goto enomem; +#endif + if (src->pw_fields & _PWF_UID) + template->pw_uid = src->pw_uid; + if (src->pw_fields & _PWF_GID) + template->pw_gid = src->pw_gid; + if ((src->pw_fields & _PWF_GECOS) && + (template->pw_gecos = strdup(src->pw_gecos)) == NULL) + goto enomem; + if ((src->pw_fields & _PWF_DIR) && + (template->pw_dir = strdup(src->pw_dir)) == NULL) + goto enomem; + if ((src->pw_fields & _PWF_SHELL) && + (template->pw_shell = strdup(src->pw_shell)) == NULL) + goto enomem; + template->pw_fields = src->pw_fields; + return (0); +enomem: + syslog(LOG_ERR, "getpwent memory allocation failure"); + return (-1); +} + + +static int +compat_use_template(struct passwd *pwd, struct passwd *template, char *buffer, + size_t bufsize) +{ + struct passwd hold; + char *copy, *p, *q, *eob; + size_t n; + + /* We cannot know the layout of the password fields in `buffer', + * so we have to copy everything. + */ + if (template->pw_fields == 0) /* nothing to fill-in */ + return (0); + n = 0; + n += pwd->pw_name != NULL ? strlen(pwd->pw_name) + 1 : 0; + n += pwd->pw_passwd != NULL ? strlen(pwd->pw_passwd) + 1 : 0; + n += pwd->pw_class != NULL ? strlen(pwd->pw_class) + 1 : 0; + n += pwd->pw_gecos != NULL ? strlen(pwd->pw_gecos) + 1 : 0; + n += pwd->pw_dir != NULL ? strlen(pwd->pw_dir) + 1 : 0; + n += pwd->pw_shell != NULL ? strlen(pwd->pw_shell) + 1 : 0; + copy = malloc(n); + if (copy == NULL) { + syslog(LOG_ERR, "getpwent memory allocation failure"); + return (ENOMEM); + } + p = copy; + eob = ©[n]; +#define COPY(field) do { \ + if (pwd->field == NULL) \ + hold.field = NULL; \ + else { \ + hold.field = p; \ + p += strlcpy(p, pwd->field, eob-p) + 1; \ + } \ +} while (0) + COPY(pw_name); + COPY(pw_passwd); + COPY(pw_class); + COPY(pw_gecos); + COPY(pw_dir); + COPY(pw_shell); +#undef COPY + p = buffer; + eob = &buffer[bufsize]; +#define COPY(field, flag) do { \ + q = (template->pw_fields & flag) ? template->field : hold.field; \ + if (q == NULL) \ + pwd->field = NULL; \ + else { \ + pwd->field = p; \ + if ((n = strlcpy(p, q, eob-p)) >= eob-p) { \ + free(copy); \ + return (ERANGE); \ + } \ + p += n + 1; \ + } \ +} while (0) + COPY(pw_name, 0); +#ifdef PW_OVERRIDE_PASSWD + COPY(pw_passwd, _PWF_PASSWD); +#else + COPY(pw_passwd, 0); +#endif + COPY(pw_class, 0); + COPY(pw_gecos, _PWF_GECOS); + COPY(pw_dir, _PWF_DIR); + COPY(pw_shell, _PWF_SHELL); +#undef COPY +#define COPY(field, flag) do { \ + if (template->pw_fields & flag) \ + pwd->field = template->field; \ +} while (0) + COPY(pw_uid, _PWF_UID); + COPY(pw_gid, _PWF_GID); +#undef COPY + free(copy); + return (0); +} + + +static int +compat_exclude(const char *name, DB **db) +{ + DBT key, data; + + if (*db == NULL && + (*db = dbopen(NULL, O_RDWR, 600, DB_HASH, 0)) == NULL) + return (errno); + key.size = strlen(name); + key.data = (char *)name; + data.size = 0; + data.data = NULL; + + if ((*db)->put(*db, &key, &data, 0) == -1) + return (errno); + return (0); +} + + +static int +compat_is_excluded(const char *name, DB *db) +{ + DBT key, data; + + if (db == NULL) + return (0); + key.size = strlen(name); + key.data = (char *)name; + return (db->get(db, &key, &data, 0) == 0); +} + + +static int +compat_redispatch(struct compat_state *st, enum nss_lookup_type how, + enum nss_lookup_type lookup_how, const char *name, const char *lookup_name, + uid_t uid, struct passwd *pwd, char *buffer, size_t bufsize, int *errnop) +{ + static const ns_src compatsrc[] = { +#ifdef YP + { NSSRC_NIS, NS_SUCCESS }, +#endif + { NULL, 0 } + }; + ns_dtab dtab[] = { +#ifdef YP + { NSSRC_NIS, nis_passwd, NULL }, +#endif +#ifdef HESIOD + { NSSRC_DNS, dns_passwd, NULL }, +#endif + { NULL, NULL, NULL } + }; + void *discard; + int rv, e, i; + + for (i = 0; i < sizeof(dtab)/sizeof(dtab[0]) - 1; i++) + dtab[i].mdata = (void *)lookup_how; +more: + pwd_init(pwd); + switch (lookup_how) { + case nss_lt_all: + rv = _nsdispatch(&discard, dtab, NSDB_PASSWD_COMPAT, + "getpwent_r", compatsrc, pwd, buffer, bufsize, + errnop); + break; + case nss_lt_id: + rv = _nsdispatch(&discard, dtab, NSDB_PASSWD_COMPAT, + "getpwuid_r", compatsrc, uid, pwd, buffer, + bufsize, errnop); + break; + case nss_lt_name: + rv = _nsdispatch(&discard, dtab, NSDB_PASSWD_COMPAT, + "getpwnam_r", compatsrc, lookup_name, pwd, buffer, + bufsize, errnop); + break; + default: + return (NS_UNAVAIL); + } + if (rv != NS_SUCCESS) + return (rv); + if (compat_is_excluded(pwd->pw_name, st->exclude)) { + if (how == nss_lt_all) + goto more; + return (NS_NOTFOUND); + } + e = compat_use_template(pwd, &st->template, buffer, bufsize); + if (e != 0) { + *errnop = e; + if (e == ERANGE) + return (NS_RETURN); + else + return (NS_UNAVAIL); + } + switch (how) { + case nss_lt_name: + if (strcmp(name, pwd->pw_name) != 0) + return (NS_NOTFOUND); + break; + case nss_lt_id: + if (uid != pwd->pw_uid) + return (NS_NOTFOUND); + break; + default: + break; + } + return (NS_SUCCESS); +} + + +static void +compat_endstate(void *p) +{ + struct compat_state *st; + + if (p == NULL) + return; + st = (struct compat_state *)p; + if (st->db != NULL) + st->db->close(st->db); + if (st->exclude != NULL) + st->exclude->close(st->exclude); + compat_clear_template(&st->template); + free(p); +} + + +static int +compat_setpwent(void *retval, void *mdata, va_list ap) +{ + static const ns_src compatsrc[] = { +#ifdef YP + { NSSRC_NIS, NS_SUCCESS }, +#endif + { NULL, 0 } + }; + ns_dtab dtab[] = { +#ifdef YP + { NSSRC_NIS, nis_setpwent, NULL }, +#endif +#ifdef HESIOD + { NSSRC_DNS, dns_setpwent, NULL }, +#endif + { NULL, NULL, NULL } + }; + struct compat_state *st; + int rv, stayopen; + +#define set_setent(x, y) do { \ + int i; \ + \ + for (i = 0; i < (sizeof(x)/sizeof(x[0])) - 1; i++) \ + x[i].mdata = (void *)y; \ +} while (0) + + rv = compat_getstate(&st); + if (rv != 0) + return (NS_UNAVAIL); + switch ((enum constants)mdata) { + case SETPWENT: + stayopen = va_arg(ap, int); + st->keynum = 0; + if (stayopen) + st->db = pwdbopen(&st->version); + st->stayopen = stayopen; + set_setent(dtab, mdata); + (void)_nsdispatch(NULL, dtab, NSDB_PASSWD_COMPAT, "setpwent", + compatsrc, 0); + break; + case ENDPWENT: + if (st->db != NULL) { + (void)st->db->close(st->db); + st->db = NULL; + } + set_setent(dtab, mdata); + (void)_nsdispatch(NULL, dtab, NSDB_PASSWD_COMPAT, "endpwent", + compatsrc, 0); + break; + default: + break; + } + return (NS_UNAVAIL); +#undef set_setent +} + + +static int +compat_passwd(void *retval, void *mdata, va_list ap) +{ + char keybuf[MAXLOGNAME + 1]; + DBT key, entry; + struct compat_state *st; + enum nss_lookup_type how; + const char *name; + struct passwd *pwd; + char *buffer, *pw_name; + char *host, *user, *domain; + size_t bufsize; + uid_t uid; + uint32_t store; + int rv, from_compat, stayopen, *errnop; + + from_compat = 0; + name = NULL; + uid = (uid_t)-1; + how = (enum nss_lookup_type)mdata; + switch (how) { + case nss_lt_name: + name = va_arg(ap, const char *); + break; + case nss_lt_id: + uid = va_arg(ap, uid_t); + break; + case nss_lt_all: + break; + default: + rv = NS_NOTFOUND; + goto fin; + } + pwd = va_arg(ap, struct passwd *); + buffer = va_arg(ap, char *); + bufsize = va_arg(ap, size_t); + errnop = va_arg(ap, int *); + *errnop = compat_getstate(&st); + if (*errnop != 0) + return (NS_UNAVAIL); + if (how == nss_lt_all && st->keynum < 0) { + rv = NS_NOTFOUND; + goto fin; + } + if (st->db == NULL && + (st->db = pwdbopen(&st->version)) == NULL) { + *errnop = errno; + rv = NS_UNAVAIL; + goto fin; + } + if (how == nss_lt_all) { + if (st->keynum < 0) { + rv = NS_NOTFOUND; + goto fin; + } + stayopen = 1; + } else { + st->keynum = 0; + stayopen = st->stayopen; + } +docompat: + rv = NS_NOTFOUND; + switch (st->compat) { + case COMPAT_MODE_ALL: + rv = compat_redispatch(st, how, how, name, name, uid, pwd, + buffer, bufsize, errnop); + if (rv != NS_SUCCESS) + st->compat = COMPAT_MODE_OFF; + break; + case COMPAT_MODE_NETGROUP: + /* XXX getnetgrent is not thread-safe. */ + do { + rv = getnetgrent(&host, &user, &domain); + if (rv == 0) { + endnetgrent(); + st->compat = COMPAT_MODE_OFF; + rv = NS_NOTFOUND; + continue; + } else if (user == NULL || user[0] == '\0') + continue; + rv = compat_redispatch(st, how, nss_lt_name, name, + user, uid, pwd, buffer, bufsize, errnop); + } while (st->compat == COMPAT_MODE_NETGROUP && + !(rv & NS_TERMINATE)); + break; + case COMPAT_MODE_NAME: + rv = compat_redispatch(st, how, nss_lt_name, name, st->name, + uid, pwd, buffer, bufsize, errnop); + free(st->name); + st->name = NULL; + st->compat = COMPAT_MODE_OFF; + break; + default: + break; + } + if (rv & NS_TERMINATE) { + from_compat = 1; + goto fin; + } + key.data = keybuf; + rv = NS_NOTFOUND; + while (st->keynum >= 0) { + st->keynum++; + if (st->version < _PWD_CURRENT_VERSION) { + memcpy(&keybuf[1], &st->keynum, sizeof(st->keynum)); + key.size = sizeof(st->keynum) + 1; + } else { + store = htonl(st->keynum); + memcpy(&keybuf[1], &store, sizeof(store)); + key.size = sizeof(store) + 1; + } + keybuf[0] = _PW_VERSIONED(_PW_KEYBYNUM, st->version); + rv = st->db->get(st->db, &key, &entry, 0); + if (rv < 0 || rv > 1) { /* should never return > 1 */ + *errnop = errno; + rv = NS_UNAVAIL; + goto fin; + } else if (rv == 1) { + st->keynum = -1; + rv = NS_NOTFOUND; + goto fin; + } + pw_name = (char *)entry.data; + switch (pw_name[0]) { + case '+': + switch (pw_name[1]) { + case '\0': + st->compat = COMPAT_MODE_ALL; + break; + case '@': + setnetgrent(&pw_name[2]); + st->compat = COMPAT_MODE_NETGROUP; + break; + default: + st->name = strdup(&pw_name[1]); + if (st->name == NULL) { + syslog(LOG_ERR, + "getpwent memory allocation failure"); + *errnop = ENOMEM; + rv = NS_UNAVAIL; + break; + } + st->compat = COMPAT_MODE_NAME; + } + if (entry.size > bufsize) { + *errnop = ERANGE; + rv = NS_RETURN; + goto fin; + } + memcpy(buffer, entry.data, entry.size); + rv = pwdb_versions[st->version].parse(buffer, + entry.size, pwd, errnop); + if (rv != NS_SUCCESS) + ; + else if (compat_set_template(pwd, &st->template) < 0) { + *errnop = ENOMEM; + rv = NS_UNAVAIL; + goto fin; + } + goto docompat; + case '-': + switch (pw_name[1]) { + case '\0': + /* XXX Maybe syslog warning */ + continue; + case '@': + setnetgrent(&pw_name[2]); + while (getnetgrent(&host, &user, &domain) != + 0) { + if (user != NULL && user[0] != '\0') + compat_exclude(user, + &st->exclude); + } + endnetgrent(); + continue; + default: + compat_exclude(&pw_name[1], &st->exclude); + continue; + } + break; + default: + break; + } + if (compat_is_excluded((char *)entry.data, st->exclude)) + continue; + rv = pwdb_versions[st->version].match(entry.data, entry.size, + how, name, uid); + if (rv == NS_RETURN) + break; + else if (rv != NS_SUCCESS) + continue; + if (entry.size > bufsize) { + *errnop = ERANGE; + rv = NS_RETURN; + break; + } + memcpy(buffer, entry.data, entry.size); + rv = pwdb_versions[st->version].parse(buffer, entry.size, pwd, + errnop); + if (rv & NS_TERMINATE) + break; + } +fin: + if (!stayopen && st->db != NULL) { + (void)st->db->close(st->db); + st->db = NULL; + } + if (rv == NS_SUCCESS) { + if (!from_compat) { + pwd->pw_fields &= ~_PWF_SOURCE; + pwd->pw_fields |= _PWF_FILES; + } + if (retval != NULL) + *(struct passwd **)retval = pwd; + } + return (rv); +} + + +/* + * common passwd line matching and parsing + */ +int +__pw_match_entry(const char *entry, size_t entrysize, enum nss_lookup_type how, + const char *name, uid_t uid) +{ + const char *p, *eom; + char *q; + size_t len; + unsigned long m; + + eom = entry + entrysize; + for (p = entry; p < eom; p++) + if (*p == ':') + break; + if (*p != ':') + return (NS_NOTFOUND); + if (how == nss_lt_all) + return (NS_SUCCESS); + if (how == nss_lt_name) { + len = strlen(name); + if (len == (p - entry) && memcmp(name, entry, len) == 0) + return (NS_SUCCESS); + else + return (NS_NOTFOUND); + } + for (p++; p < eom; p++) + if (*p == ':') + break; + if (*p != ':') + return (NS_NOTFOUND); + m = strtoul(++p, &q, 10); + if (q[0] != ':' || (uid_t)m != uid) + return (NS_NOTFOUND); + else + return (NS_SUCCESS); +} + + +/* XXX buffer must be NUL-terminated. errnop is not set correctly. */ +int +__pw_parse_entry(char *buffer, size_t bufsize __unused, struct passwd *pwd, + int master, int *errnop __unused) +{ + + if (__pw_scan(buffer, pwd, master ? _PWSCAN_MASTER : 0) == 0) + return (NS_NOTFOUND); + else + return (NS_SUCCESS); +} diff --git a/lib/libc/gen/getttyent.c b/lib/libc/gen/getttyent.c new file mode 100644 index 0000000..12d92a4 --- /dev/null +++ b/lib/libc/gen/getttyent.c @@ -0,0 +1,267 @@ +/* + * Copyright (c) 1989, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)getttyent.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/getttyent.c,v 1.12.14.1 2005/07/25 20:19:39 mdodd Exp $"); + +#include +#include +#include +#include +#include + +static char zapchar; +static FILE *tf; +static size_t lbsize; +static char *line; + +#define MALLOCCHUNK 100 + +static char *skip(char *); +static char *value(char *); + +struct ttyent * +getttynam(tty) + const char *tty; +{ + struct ttyent *t; + + if (strncmp(tty, "/dev/", 5) == 0) + tty += 5; + setttyent(); + while ( (t = getttyent()) ) + if (!strcmp(tty, t->ty_name)) + break; + endttyent(); + return (t); +} + +struct ttyent * +getttyent() +{ + static struct ttyent tty; + char *p; + int c; + size_t i; + + if (!tf && !setttyent()) + return (NULL); + for (;;) { + if (!fgets(p = line, lbsize, tf)) + return (NULL); + /* extend buffer if line was too big, and retry */ + while (!index(p, '\n')) { + i = strlen(p); + lbsize += MALLOCCHUNK; + if ((p = realloc(line, lbsize)) == NULL) { + (void)endttyent(); + return (NULL); + } + line = p; + if (!fgets(&line[i], lbsize - i, tf)) + return (NULL); + } + while (isspace((unsigned char)*p)) + ++p; + if (*p && *p != '#') + break; + } + +#define scmp(e) !strncmp(p, e, sizeof(e) - 1) && isspace((unsigned char)p[sizeof(e) - 1]) +#define vcmp(e) !strncmp(p, e, sizeof(e) - 1) && p[sizeof(e) - 1] == '=' + + zapchar = 0; + tty.ty_name = p; + tty.ty_status = 0; + tty.ty_window = NULL; + tty.ty_group = _TTYS_NOGROUP; + + p = skip(p); + if (!*(tty.ty_getty = p)) + tty.ty_getty = tty.ty_type = NULL; + else { + p = skip(p); + if (!*(tty.ty_type = p)) + tty.ty_type = NULL; + else { + /* compatibility kludge: handle network/dialup specially */ + if (scmp(_TTYS_DIALUP)) + tty.ty_status |= TTY_DIALUP; + else if (scmp(_TTYS_NETWORK)) + tty.ty_status |= TTY_NETWORK; + p = skip(p); + } + } + + for (; *p; p = skip(p)) { + if (scmp(_TTYS_OFF)) + tty.ty_status &= ~TTY_ON; + else if (scmp(_TTYS_ON)) + tty.ty_status |= TTY_ON; + else if (scmp(_TTYS_SECURE)) + tty.ty_status |= TTY_SECURE; + else if (scmp(_TTYS_INSECURE)) + tty.ty_status &= ~TTY_SECURE; + else if (scmp(_TTYS_DIALUP)) + tty.ty_status |= TTY_DIALUP; + else if (scmp(_TTYS_NETWORK)) + tty.ty_status |= TTY_NETWORK; + else if (vcmp(_TTYS_WINDOW)) + tty.ty_window = value(p); + else if (vcmp(_TTYS_GROUP)) + tty.ty_group = value(p); + else + break; + } + + if (zapchar == '#' || *p == '#') + while ((c = *++p) == ' ' || c == '\t') + ; + tty.ty_comment = p; + if (*p == 0) + tty.ty_comment = 0; + if ( (p = index(p, '\n')) ) + *p = '\0'; + return (&tty); +} + +#define QUOTED 1 + +/* + * Skip over the current field, removing quotes, and return a pointer to + * the next field. + */ +static char * +skip(p) + char *p; +{ + char *t; + int c, q; + + for (q = 0, t = p; (c = *p) != '\0'; p++) { + if (c == '"') { + q ^= QUOTED; /* obscure, but nice */ + continue; + } + if (q == QUOTED && *p == '\\' && *(p+1) == '"') + p++; + *t++ = *p; + if (q == QUOTED) + continue; + if (c == '#') { + zapchar = c; + *p = 0; + break; + } + if (c == '\t' || c == ' ' || c == '\n') { + zapchar = c; + *p++ = 0; + while ((c = *p) == '\t' || c == ' ' || c == '\n') + p++; + break; + } + } + *--t = '\0'; + return (p); +} + +static char * +value(p) + char *p; +{ + + return ((p = index(p, '=')) ? ++p : NULL); +} + +int +setttyent() +{ + + if (line == NULL) { + if ((line = malloc(MALLOCCHUNK)) == NULL) + return (0); + lbsize = MALLOCCHUNK; + } + if (tf) { + rewind(tf); + return (1); + } else if ( (tf = fopen(_PATH_TTYS, "r")) ) + return (1); + return (0); +} + +int +endttyent() +{ + int rval; + + /* + * NB: Don't free `line' because getttynam() + * may still be referencing it + */ + if (tf) { + rval = (fclose(tf) != EOF); + tf = NULL; + return (rval); + } + return (1); +} + +static int +isttystat(tty, flag) + const char *tty; + int flag; +{ + struct ttyent *t; + + return ((t = getttynam(tty)) == NULL) ? 0 : !!(t->ty_status & flag); +} + + +int +isdialuptty(tty) + const char *tty; +{ + + return isttystat(tty, TTY_DIALUP); +} + +int isnettty(tty) + const char *tty; +{ + + return isttystat(tty, TTY_NETWORK); +} diff --git a/lib/libc/gen/getusershell.c b/lib/libc/gen/getusershell.c new file mode 100644 index 0000000..b8fd9b4 --- /dev/null +++ b/lib/libc/gen/getusershell.c @@ -0,0 +1,274 @@ +/* + * 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. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)getusershell.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +/* $NetBSD: getusershell.c,v 1.17 1999/01/25 01:09:34 lukem Exp $ */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/getusershell.c,v 1.9 2003/04/24 20:16:21 nectar Exp $"); + +#include "namespace.h" +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef HESIOD +#include +#endif +#ifdef YP +#include +#include +#include +#endif +#include "un-namespace.h" + +/* + * Local shells should NOT be added here. They should be added in + * /etc/shells. + */ + +static const char *const okshells[] = { _PATH_BSHELL, _PATH_CSHELL, NULL }; +static const char *const *curshell; +static StringList *sl; + +static const char *const *initshells(void); + +/* + * Get a list of shells from "shells" nsswitch database + */ +char * +getusershell(void) +{ + char *ret; + + if (curshell == NULL) + curshell = initshells(); + /*LINTED*/ + ret = (char *)*curshell; + if (ret != NULL) + curshell++; + return (ret); +} + +void +endusershell(void) +{ + if (sl) { + sl_free(sl, 1); + sl = NULL; + } + curshell = NULL; +} + +void +setusershell(void) +{ + + curshell = initshells(); +} + + +static int _local_initshells(void *, void *, va_list); + +/*ARGSUSED*/ +static int +_local_initshells(rv, cb_data, ap) + void *rv; + void *cb_data; + va_list ap; +{ + char *sp, *cp; + FILE *fp; + char line[MAXPATHLEN + 2]; + + if (sl) + sl_free(sl, 1); + sl = sl_init(); + + if ((fp = fopen(_PATH_SHELLS, "r")) == NULL) + return NS_UNAVAIL; + + sp = cp = line; + while (fgets(cp, MAXPATHLEN + 1, fp) != NULL) { + while (*cp != '#' && *cp != '/' && *cp != '\0') + cp++; + if (*cp == '#' || *cp == '\0') + continue; + sp = cp; + while (!isspace(*cp) && *cp != '#' && *cp != '\0') + cp++; + *cp++ = '\0'; + sl_add(sl, strdup(sp)); + } + (void)fclose(fp); + return NS_SUCCESS; +} + +#ifdef HESIOD +static int _dns_initshells(void *, void *, va_list); + +/*ARGSUSED*/ +static int +_dns_initshells(rv, cb_data, ap) + void *rv; + void *cb_data; + va_list ap; +{ + char shellname[] = "shells-XXXXX"; + int hsindex, hpi, r; + char **hp; + void *context; + + if (sl) + sl_free(sl, 1); + sl = sl_init(); + r = NS_UNAVAIL; + if (hesiod_init(&context) == -1) + return (r); + + for (hsindex = 0; ; hsindex++) { + snprintf(shellname, sizeof(shellname)-1, "shells-%d", hsindex); + hp = hesiod_resolve(context, shellname, "shells"); + if (hp == NULL) { + if (errno == ENOENT) { + if (hsindex == 0) + r = NS_NOTFOUND; + else + r = NS_SUCCESS; + } + break; + } else { + for (hpi = 0; hp[hpi]; hpi++) + sl_add(sl, hp[hpi]); + free(hp); + } + } + hesiod_end(context); + return (r); +} +#endif /* HESIOD */ + +#ifdef YP +static int _nis_initshells(void *, void *, va_list); + +/*ARGSUSED*/ +static int +_nis_initshells(rv, cb_data, ap) + void *rv; + void *cb_data; + va_list ap; +{ + static char *ypdomain; + char *key, *data; + char *lastkey; + int keylen, datalen; + int r; + + if (sl) + sl_free(sl, 1); + sl = sl_init(); + + if (ypdomain == NULL) { + switch (yp_get_default_domain(&ypdomain)) { + case 0: + break; + case YPERR_RESRC: + return NS_TRYAGAIN; + default: + return NS_UNAVAIL; + } + } + + /* + * `key' and `data' point to strings dynamically allocated by + * the yp_... functions. + * `data' is directly put into the stringlist of shells. + */ + key = data = NULL; + if (yp_first(ypdomain, "shells", &key, &keylen, &data, &datalen)) + return NS_UNAVAIL; + do { + data[datalen] = '\0'; /* clear trailing \n */ + sl_add(sl, data); + + lastkey = key; + r = yp_next(ypdomain, "shells", lastkey, keylen, + &key, &keylen, &data, &datalen); + free(lastkey); + } while (r == 0); + + if (r == YPERR_NOMORE) { + /* + * `data' and `key' ought to be NULL - do not try to free them. + */ + return NS_SUCCESS; + } + + return NS_UNAVAIL; +} +#endif /* YP */ + +static const char *const * +initshells() +{ + static const ns_dtab dtab[] = { + NS_FILES_CB(_local_initshells, NULL) + NS_DNS_CB(_dns_initshells, NULL) + NS_NIS_CB(_nis_initshells, NULL) + { 0 } + }; + if (sl) + sl_free(sl, 1); + sl = sl_init(); + + if (_nsdispatch(NULL, dtab, NSDB_SHELLS, "initshells", __nsdefaultsrc) + != NS_SUCCESS) { + if (sl) + sl_free(sl, 1); + sl = NULL; + return (okshells); + } + sl_add(sl, NULL); + + return (const char *const *)(sl->sl_str); +} diff --git a/lib/libc/gen/getvfsbyname.c b/lib/libc/gen/getvfsbyname.c new file mode 100644 index 0000000..be93b00 --- /dev/null +++ b/lib/libc/gen/getvfsbyname.c @@ -0,0 +1,80 @@ +/* + * Copyright (c) 1995 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)kvm_getvfsbyname.c 8.1 (Berkeley) 4/3/95"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/getvfsbyname.c,v 1.10 2003/10/29 10:45:01 tjr Exp $"); + +#include +#include +#include +#include +#include +#include + +/* + * Given a filesystem name, determine if it is resident in the kernel, + * and if it is resident, return its xvfsconf structure. + */ +int +getvfsbyname(fsname, vfcp) + const char *fsname; + struct xvfsconf *vfcp; +{ + struct xvfsconf *xvfsp; + size_t buflen; + int cnt, i; + + if (sysctlbyname("vfs.conflist", NULL, &buflen, NULL, 0) < 0) + return (-1); + xvfsp = malloc(buflen); + if (xvfsp == NULL) + return (-1); + if (sysctlbyname("vfs.conflist", xvfsp, &buflen, NULL, 0) < 0) { + free(xvfsp); + return (-1); + } + cnt = buflen / sizeof(struct xvfsconf); + for (i = 0; i < cnt; i++) { + if (strcmp(fsname, xvfsp[i].vfc_name) == 0) { + memcpy(vfcp, xvfsp + i, sizeof(struct xvfsconf)); + free(xvfsp); + return (0); + } + } + free(xvfsp); + errno = ENOENT; + return (-1); +} diff --git a/lib/libc/gen/glob.c b/lib/libc/gen/glob.c new file mode 100644 index 0000000..e237262 --- /dev/null +++ b/lib/libc/gen/glob.c @@ -0,0 +1,956 @@ +/* + * Copyright (c) 1989, 1993 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * Guido van Rossum. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)glob.c 8.3 (Berkeley) 10/13/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/glob.c,v 1.22.8.1 2005/10/04 14:31:10 ache Exp $"); + +/* + * glob(3) -- a superset of the one defined in POSIX 1003.2. + * + * The [!...] convention to negate a range is supported (SysV, Posix, ksh). + * + * Optional extra services, controlled by flags not defined by POSIX: + * + * GLOB_QUOTE: + * Escaping convention: \ inhibits any special meaning the following + * character might have (except \ at end of string is retained). + * GLOB_MAGCHAR: + * Set in gl_flags if pattern contained a globbing character. + * GLOB_NOMAGIC: + * Same as GLOB_NOCHECK, but it will only append pattern if it did + * not contain any magic characters. [Used in csh style globbing] + * GLOB_ALTDIRFUNC: + * Use alternately specified directory access functions. + * GLOB_TILDE: + * expand ~user/foo to the /home/dir/of/user/foo + * GLOB_BRACE: + * expand {1,2}{a,b} to 1a 1b 2a 2b + * gl_matchc: + * Number of matches in the current invocation of glob. + */ + +/* + * Some notes on multibyte character support: + * 1. Patterns with illegal byte sequences match nothing - even if + * GLOB_NOCHECK is specified. + * 2. Illegal byte sequences in filenames are handled by treating them as + * single-byte characters with a value of the first byte of the sequence + * cast to wchar_t. + * 3. State-dependent encodings are not currently supported. + */ + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "collate.h" + +#define DOLLAR '$' +#define DOT '.' +#define EOS '\0' +#define LBRACKET '[' +#define NOT '!' +#define QUESTION '?' +#define QUOTE '\\' +#define RANGE '-' +#define RBRACKET ']' +#define SEP '/' +#define STAR '*' +#define TILDE '~' +#define UNDERSCORE '_' +#define LBRACE '{' +#define RBRACE '}' +#define SLASH '/' +#define COMMA ',' + +#ifndef DEBUG + +#define M_QUOTE 0x8000000000ULL +#define M_PROTECT 0x4000000000ULL +#define M_MASK 0xffffffffffULL +#define M_CHAR 0x00ffffffffULL + +typedef uint_fast64_t Char; + +#else + +#define M_QUOTE 0x80 +#define M_PROTECT 0x40 +#define M_MASK 0xff +#define M_CHAR 0x7f + +typedef char Char; + +#endif + + +#define CHAR(c) ((Char)((c)&M_CHAR)) +#define META(c) ((Char)((c)|M_QUOTE)) +#define M_ALL META('*') +#define M_END META(']') +#define M_NOT META('!') +#define M_ONE META('?') +#define M_RNG META('-') +#define M_SET META('[') +#define ismeta(c) (((c)&M_QUOTE) != 0) + + +static int compare(const void *, const void *); +static int g_Ctoc(const Char *, char *, u_int); +static int g_lstat(Char *, struct stat *, glob_t *); +static DIR *g_opendir(Char *, glob_t *); +static Char *g_strchr(Char *, wchar_t); +#ifdef notdef +static Char *g_strcat(Char *, const Char *); +#endif +static int g_stat(Char *, struct stat *, glob_t *); +static int glob0(const Char *, glob_t *, int *); +static int glob1(Char *, glob_t *, int *); +static int glob2(Char *, Char *, Char *, Char *, glob_t *, int *); +static int glob3(Char *, Char *, Char *, Char *, Char *, glob_t *, int *); +static int globextend(const Char *, glob_t *, int *); +static const Char * + globtilde(const Char *, Char *, size_t, glob_t *); +static int globexp1(const Char *, glob_t *, int *); +static int globexp2(const Char *, const Char *, glob_t *, int *, int *); +static int match(Char *, Char *, Char *); +#ifdef DEBUG +static void qprintf(const char *, Char *); +#endif + +int +glob(pattern, flags, errfunc, pglob) + const char *pattern; + int flags, (*errfunc)(const char *, int); + glob_t *pglob; +{ + const u_char *patnext; + int limit; + Char *bufnext, *bufend, patbuf[MAXPATHLEN], prot; + mbstate_t mbs; + wchar_t wc; + size_t clen; + + patnext = (u_char *) pattern; + if (!(flags & GLOB_APPEND)) { + pglob->gl_pathc = 0; + pglob->gl_pathv = NULL; + if (!(flags & GLOB_DOOFFS)) + pglob->gl_offs = 0; + } + if (flags & GLOB_LIMIT) { + limit = pglob->gl_matchc; + if (limit == 0) + limit = ARG_MAX; + } else + limit = 0; + pglob->gl_flags = flags & ~GLOB_MAGCHAR; + pglob->gl_errfunc = errfunc; + pglob->gl_matchc = 0; + + bufnext = patbuf; + bufend = bufnext + MAXPATHLEN - 1; + if (flags & GLOB_NOESCAPE) { + memset(&mbs, 0, sizeof(mbs)); + while (bufend - bufnext >= MB_CUR_MAX) { + clen = mbrtowc(&wc, patnext, MB_LEN_MAX, &mbs); + if (clen == (size_t)-1 || clen == (size_t)-2) + return (GLOB_NOMATCH); + else if (clen == 0) + break; + *bufnext++ = wc; + patnext += clen; + } + } else { + /* Protect the quoted characters. */ + memset(&mbs, 0, sizeof(mbs)); + while (bufend - bufnext >= MB_CUR_MAX) { + if (*patnext == QUOTE) { + if (*++patnext == EOS) { + *bufnext++ = QUOTE | M_PROTECT; + continue; + } + prot = M_PROTECT; + } else + prot = 0; + clen = mbrtowc(&wc, patnext, MB_LEN_MAX, &mbs); + if (clen == (size_t)-1 || clen == (size_t)-2) + return (GLOB_NOMATCH); + else if (clen == 0) + break; + *bufnext++ = wc | prot; + patnext += clen; + } + } + *bufnext = EOS; + + if (flags & GLOB_BRACE) + return globexp1(patbuf, pglob, &limit); + else + return glob0(patbuf, pglob, &limit); +} + +/* + * Expand recursively a glob {} pattern. When there is no more expansion + * invoke the standard globbing routine to glob the rest of the magic + * characters + */ +static int +globexp1(pattern, pglob, limit) + const Char *pattern; + glob_t *pglob; + int *limit; +{ + const Char* ptr = pattern; + int rv; + + /* Protect a single {}, for find(1), like csh */ + if (pattern[0] == LBRACE && pattern[1] == RBRACE && pattern[2] == EOS) + return glob0(pattern, pglob, limit); + + while ((ptr = (const Char *) g_strchr((Char *) ptr, LBRACE)) != NULL) + if (!globexp2(ptr, pattern, pglob, &rv, limit)) + return rv; + + return glob0(pattern, pglob, limit); +} + + +/* + * Recursive brace globbing helper. Tries to expand a single brace. + * If it succeeds then it invokes globexp1 with the new pattern. + * If it fails then it tries to glob the rest of the pattern and returns. + */ +static int +globexp2(ptr, pattern, pglob, rv, limit) + const Char *ptr, *pattern; + glob_t *pglob; + int *rv, *limit; +{ + int i; + Char *lm, *ls; + const Char *pe, *pm, *pm1, *pl; + Char patbuf[MAXPATHLEN]; + + /* copy part up to the brace */ + for (lm = patbuf, pm = pattern; pm != ptr; *lm++ = *pm++) + continue; + *lm = EOS; + ls = lm; + + /* Find the balanced brace */ + for (i = 0, pe = ++ptr; *pe; pe++) + if (*pe == LBRACKET) { + /* Ignore everything between [] */ + for (pm = pe++; *pe != RBRACKET && *pe != EOS; pe++) + continue; + if (*pe == EOS) { + /* + * We could not find a matching RBRACKET. + * Ignore and just look for RBRACE + */ + pe = pm; + } + } + else if (*pe == LBRACE) + i++; + else if (*pe == RBRACE) { + if (i == 0) + break; + i--; + } + + /* Non matching braces; just glob the pattern */ + if (i != 0 || *pe == EOS) { + *rv = glob0(patbuf, pglob, limit); + return 0; + } + + for (i = 0, pl = pm = ptr; pm <= pe; pm++) + switch (*pm) { + case LBRACKET: + /* Ignore everything between [] */ + for (pm1 = pm++; *pm != RBRACKET && *pm != EOS; pm++) + continue; + if (*pm == EOS) { + /* + * We could not find a matching RBRACKET. + * Ignore and just look for RBRACE + */ + pm = pm1; + } + break; + + case LBRACE: + i++; + break; + + case RBRACE: + if (i) { + i--; + break; + } + /* FALLTHROUGH */ + case COMMA: + if (i && *pm == COMMA) + break; + else { + /* Append the current string */ + for (lm = ls; (pl < pm); *lm++ = *pl++) + continue; + /* + * Append the rest of the pattern after the + * closing brace + */ + for (pl = pe + 1; (*lm++ = *pl++) != EOS;) + continue; + + /* Expand the current pattern */ +#ifdef DEBUG + qprintf("globexp2:", patbuf); +#endif + *rv = globexp1(patbuf, pglob, limit); + + /* move after the comma, to the next string */ + pl = pm + 1; + } + break; + + default: + break; + } + *rv = 0; + return 0; +} + + + +/* + * expand tilde from the passwd file. + */ +static const Char * +globtilde(pattern, patbuf, patbuf_len, pglob) + const Char *pattern; + Char *patbuf; + size_t patbuf_len; + glob_t *pglob; +{ + struct passwd *pwd; + char *h; + const Char *p; + Char *b, *eb; + + if (*pattern != TILDE || !(pglob->gl_flags & GLOB_TILDE)) + return pattern; + + /* + * Copy up to the end of the string or / + */ + eb = &patbuf[patbuf_len - 1]; + for (p = pattern + 1, h = (char *) patbuf; + h < (char *)eb && *p && *p != SLASH; *h++ = *p++) + continue; + + *h = EOS; + + if (((char *) patbuf)[0] == EOS) { + /* + * handle a plain ~ or ~/ by expanding $HOME first (iff + * we're not running setuid or setgid) and then trying + * the password file + */ + if (issetugid() != 0 || + (h = getenv("HOME")) == NULL) { + if (((h = getlogin()) != NULL && + (pwd = getpwnam(h)) != NULL) || + (pwd = getpwuid(getuid())) != NULL) + h = pwd->pw_dir; + else + return pattern; + } + } + else { + /* + * Expand a ~user + */ + if ((pwd = getpwnam((char*) patbuf)) == NULL) + return pattern; + else + h = pwd->pw_dir; + } + + /* Copy the home directory */ + for (b = patbuf; b < eb && *h; *b++ = *h++) + continue; + + /* Append the rest of the pattern */ + while (b < eb && (*b++ = *p++) != EOS) + continue; + *b = EOS; + + return patbuf; +} + + +/* + * The main glob() routine: compiles the pattern (optionally processing + * quotes), calls glob1() to do the real pattern matching, and finally + * sorts the list (unless unsorted operation is requested). Returns 0 + * if things went well, nonzero if errors occurred. + */ +static int +glob0(pattern, pglob, limit) + const Char *pattern; + glob_t *pglob; + int *limit; +{ + const Char *qpatnext; + int c, err, oldpathc; + Char *bufnext, patbuf[MAXPATHLEN]; + + qpatnext = globtilde(pattern, patbuf, MAXPATHLEN, pglob); + oldpathc = pglob->gl_pathc; + bufnext = patbuf; + + /* We don't need to check for buffer overflow any more. */ + while ((c = *qpatnext++) != EOS) { + switch (c) { + case LBRACKET: + c = *qpatnext; + if (c == NOT) + ++qpatnext; + if (*qpatnext == EOS || + g_strchr((Char *) qpatnext+1, RBRACKET) == NULL) { + *bufnext++ = LBRACKET; + if (c == NOT) + --qpatnext; + break; + } + *bufnext++ = M_SET; + if (c == NOT) + *bufnext++ = M_NOT; + c = *qpatnext++; + do { + *bufnext++ = CHAR(c); + if (*qpatnext == RANGE && + (c = qpatnext[1]) != RBRACKET) { + *bufnext++ = M_RNG; + *bufnext++ = CHAR(c); + qpatnext += 2; + } + } while ((c = *qpatnext++) != RBRACKET); + pglob->gl_flags |= GLOB_MAGCHAR; + *bufnext++ = M_END; + break; + case QUESTION: + pglob->gl_flags |= GLOB_MAGCHAR; + *bufnext++ = M_ONE; + break; + case STAR: + pglob->gl_flags |= GLOB_MAGCHAR; + /* collapse adjacent stars to one, + * to avoid exponential behavior + */ + if (bufnext == patbuf || bufnext[-1] != M_ALL) + *bufnext++ = M_ALL; + break; + default: + *bufnext++ = CHAR(c); + break; + } + } + *bufnext = EOS; +#ifdef DEBUG + qprintf("glob0:", patbuf); +#endif + + if ((err = glob1(patbuf, pglob, limit)) != 0) + return(err); + + /* + * If there was no match we are going to append the pattern + * if GLOB_NOCHECK was specified or if GLOB_NOMAGIC was specified + * and the pattern did not contain any magic characters + * GLOB_NOMAGIC is there just for compatibility with csh. + */ + if (pglob->gl_pathc == oldpathc) { + if (((pglob->gl_flags & GLOB_NOCHECK) || + ((pglob->gl_flags & GLOB_NOMAGIC) && + !(pglob->gl_flags & GLOB_MAGCHAR)))) + return(globextend(pattern, pglob, limit)); + else + return(GLOB_NOMATCH); + } + if (!(pglob->gl_flags & GLOB_NOSORT)) + qsort(pglob->gl_pathv + pglob->gl_offs + oldpathc, + pglob->gl_pathc - oldpathc, sizeof(char *), compare); + return(0); +} + +static int +compare(p, q) + const void *p, *q; +{ + return(strcmp(*(char **)p, *(char **)q)); +} + +static int +glob1(pattern, pglob, limit) + Char *pattern; + glob_t *pglob; + int *limit; +{ + Char pathbuf[MAXPATHLEN]; + + /* A null pathname is invalid -- POSIX 1003.1 sect. 2.4. */ + if (*pattern == EOS) + return(0); + return(glob2(pathbuf, pathbuf, pathbuf + MAXPATHLEN - 1, + pattern, pglob, limit)); +} + +/* + * The functions glob2 and glob3 are mutually recursive; there is one level + * of recursion for each segment in the pattern that contains one or more + * meta characters. + */ +static int +glob2(pathbuf, pathend, pathend_last, pattern, pglob, limit) + Char *pathbuf, *pathend, *pathend_last, *pattern; + glob_t *pglob; + int *limit; +{ + struct stat sb; + Char *p, *q; + int anymeta; + + /* + * Loop over pattern segments until end of pattern or until + * segment with meta character found. + */ + for (anymeta = 0;;) { + if (*pattern == EOS) { /* End of pattern? */ + *pathend = EOS; + if (g_lstat(pathbuf, &sb, pglob)) + return(0); + + if (((pglob->gl_flags & GLOB_MARK) && + pathend[-1] != SEP) && (S_ISDIR(sb.st_mode) + || (S_ISLNK(sb.st_mode) && + (g_stat(pathbuf, &sb, pglob) == 0) && + S_ISDIR(sb.st_mode)))) { + if (pathend + 1 > pathend_last) + return (GLOB_ABORTED); + *pathend++ = SEP; + *pathend = EOS; + } + ++pglob->gl_matchc; + return(globextend(pathbuf, pglob, limit)); + } + + /* Find end of next segment, copy tentatively to pathend. */ + q = pathend; + p = pattern; + while (*p != EOS && *p != SEP) { + if (ismeta(*p)) + anymeta = 1; + if (q + 1 > pathend_last) + return (GLOB_ABORTED); + *q++ = *p++; + } + + if (!anymeta) { /* No expansion, do next segment. */ + pathend = q; + pattern = p; + while (*pattern == SEP) { + if (pathend + 1 > pathend_last) + return (GLOB_ABORTED); + *pathend++ = *pattern++; + } + } else /* Need expansion, recurse. */ + return(glob3(pathbuf, pathend, pathend_last, pattern, p, + pglob, limit)); + } + /* NOTREACHED */ +} + +static int +glob3(pathbuf, pathend, pathend_last, pattern, restpattern, pglob, limit) + Char *pathbuf, *pathend, *pathend_last, *pattern, *restpattern; + glob_t *pglob; + int *limit; +{ + struct dirent *dp; + DIR *dirp; + int err; + char buf[MAXPATHLEN]; + + /* + * The readdirfunc declaration can't be prototyped, because it is + * assigned, below, to two functions which are prototyped in glob.h + * and dirent.h as taking pointers to differently typed opaque + * structures. + */ + struct dirent *(*readdirfunc)(); + + if (pathend > pathend_last) + return (GLOB_ABORTED); + *pathend = EOS; + errno = 0; + + if ((dirp = g_opendir(pathbuf, pglob)) == NULL) { + /* TODO: don't call for ENOENT or ENOTDIR? */ + if (pglob->gl_errfunc) { + if (g_Ctoc(pathbuf, buf, sizeof(buf))) + return (GLOB_ABORTED); + if (pglob->gl_errfunc(buf, errno) || + pglob->gl_flags & GLOB_ERR) + return (GLOB_ABORTED); + } + return(0); + } + + err = 0; + + /* Search directory for matching names. */ + if (pglob->gl_flags & GLOB_ALTDIRFUNC) + readdirfunc = pglob->gl_readdir; + else + readdirfunc = readdir; + while ((dp = (*readdirfunc)(dirp))) { + u_char *sc; + Char *dc; + wchar_t wc; + size_t clen; + mbstate_t mbs; + + /* Initial DOT must be matched literally. */ + if (dp->d_name[0] == DOT && *pattern != DOT) + continue; + memset(&mbs, 0, sizeof(mbs)); + dc = pathend; + sc = (u_char *) dp->d_name; + while (dc < pathend_last) { + clen = mbrtowc(&wc, sc, MB_LEN_MAX, &mbs); + if (clen == (size_t)-1 || clen == (size_t)-2) { + wc = *sc; + clen = 1; + memset(&mbs, 0, sizeof(mbs)); + } + if ((*dc++ = wc) == EOS) + break; + sc += clen; + } + if (!match(pathend, pattern, restpattern)) { + *pathend = EOS; + continue; + } + err = glob2(pathbuf, --dc, pathend_last, restpattern, + pglob, limit); + if (err) + break; + } + + if (pglob->gl_flags & GLOB_ALTDIRFUNC) + (*pglob->gl_closedir)(dirp); + else + closedir(dirp); + return(err); +} + + +/* + * Extend the gl_pathv member of a glob_t structure to accomodate a new item, + * add the new item, and update gl_pathc. + * + * This assumes the BSD realloc, which only copies the block when its size + * crosses a power-of-two boundary; for v7 realloc, this would cause quadratic + * behavior. + * + * Return 0 if new item added, error code if memory couldn't be allocated. + * + * Invariant of the glob_t structure: + * Either gl_pathc is zero and gl_pathv is NULL; or gl_pathc > 0 and + * gl_pathv points to (gl_offs + gl_pathc + 1) items. + */ +static int +globextend(path, pglob, limit) + const Char *path; + glob_t *pglob; + int *limit; +{ + char **pathv; + int i; + u_int newsize, len; + char *copy; + const Char *p; + + if (*limit && pglob->gl_pathc > *limit) { + errno = 0; + return (GLOB_NOSPACE); + } + + newsize = sizeof(*pathv) * (2 + pglob->gl_pathc + pglob->gl_offs); + pathv = pglob->gl_pathv ? + realloc((char *)pglob->gl_pathv, newsize) : + malloc(newsize); + if (pathv == NULL) { + if (pglob->gl_pathv) { + free(pglob->gl_pathv); + pglob->gl_pathv = NULL; + } + return(GLOB_NOSPACE); + } + + if (pglob->gl_pathv == NULL && pglob->gl_offs > 0) { + /* first time around -- clear initial gl_offs items */ + pathv += pglob->gl_offs; + for (i = pglob->gl_offs; --i >= 0; ) + *--pathv = NULL; + } + pglob->gl_pathv = pathv; + + for (p = path; *p++;) + continue; + len = MB_CUR_MAX * (size_t)(p - path); /* XXX overallocation */ + if ((copy = malloc(len)) != NULL) { + if (g_Ctoc(path, copy, len)) { + free(copy); + return (GLOB_NOSPACE); + } + pathv[pglob->gl_offs + pglob->gl_pathc++] = copy; + } + pathv[pglob->gl_offs + pglob->gl_pathc] = NULL; + return(copy == NULL ? GLOB_NOSPACE : 0); +} + +/* + * pattern matching function for filenames. Each occurrence of the * + * pattern causes a recursion level. + */ +static int +match(name, pat, patend) + Char *name, *pat, *patend; +{ + int ok, negate_range; + Char c, k; + + while (pat < patend) { + c = *pat++; + switch (c & M_MASK) { + case M_ALL: + if (pat == patend) + return(1); + do + if (match(name, pat, patend)) + return(1); + while (*name++ != EOS); + return(0); + case M_ONE: + if (*name++ == EOS) + return(0); + break; + case M_SET: + ok = 0; + if ((k = *name++) == EOS) + return(0); + if ((negate_range = ((*pat & M_MASK) == M_NOT)) != EOS) + ++pat; + while (((c = *pat++) & M_MASK) != M_END) + if ((*pat & M_MASK) == M_RNG) { + if (__collate_load_error ? + CHAR(c) <= CHAR(k) && CHAR(k) <= CHAR(pat[1]) : + __collate_range_cmp(CHAR(c), CHAR(k)) <= 0 + && __collate_range_cmp(CHAR(k), CHAR(pat[1])) <= 0 + ) + ok = 1; + pat += 2; + } else if (c == k) + ok = 1; + if (ok == negate_range) + return(0); + break; + default: + if (*name++ != c) + return(0); + break; + } + } + return(*name == EOS); +} + +/* Free allocated data belonging to a glob_t structure. */ +void +globfree(pglob) + glob_t *pglob; +{ + int i; + char **pp; + + if (pglob->gl_pathv != NULL) { + pp = pglob->gl_pathv + pglob->gl_offs; + for (i = pglob->gl_pathc; i--; ++pp) + if (*pp) + free(*pp); + free(pglob->gl_pathv); + pglob->gl_pathv = NULL; + } +} + +static DIR * +g_opendir(str, pglob) + Char *str; + glob_t *pglob; +{ + char buf[MAXPATHLEN]; + + if (!*str) + strcpy(buf, "."); + else { + if (g_Ctoc(str, buf, sizeof(buf))) + return (NULL); + } + + if (pglob->gl_flags & GLOB_ALTDIRFUNC) + return((*pglob->gl_opendir)(buf)); + + return(opendir(buf)); +} + +static int +g_lstat(fn, sb, pglob) + Char *fn; + struct stat *sb; + glob_t *pglob; +{ + char buf[MAXPATHLEN]; + + if (g_Ctoc(fn, buf, sizeof(buf))) { + errno = ENAMETOOLONG; + return (-1); + } + if (pglob->gl_flags & GLOB_ALTDIRFUNC) + return((*pglob->gl_lstat)(buf, sb)); + return(lstat(buf, sb)); +} + +static int +g_stat(fn, sb, pglob) + Char *fn; + struct stat *sb; + glob_t *pglob; +{ + char buf[MAXPATHLEN]; + + if (g_Ctoc(fn, buf, sizeof(buf))) { + errno = ENAMETOOLONG; + return (-1); + } + if (pglob->gl_flags & GLOB_ALTDIRFUNC) + return((*pglob->gl_stat)(buf, sb)); + return(stat(buf, sb)); +} + +static Char * +g_strchr(str, ch) + Char *str; + wchar_t ch; +{ + do { + if (*str == ch) + return (str); + } while (*str++); + return (NULL); +} + +static int +g_Ctoc(str, buf, len) + const Char *str; + char *buf; + u_int len; +{ + mbstate_t mbs; + size_t clen; + + memset(&mbs, 0, sizeof(mbs)); + while (len >= MB_CUR_MAX) { + clen = wcrtomb(buf, *str, &mbs); + if (clen == (size_t)-1) + return (1); + if (*str == L'\0') + return (0); + str++; + buf += clen; + len -= clen; + } + return (1); +} + +#ifdef DEBUG +static void +qprintf(str, s) + const char *str; + Char *s; +{ + Char *p; + + (void)printf("%s:\n", str); + for (p = s; *p; p++) + (void)printf("%c", CHAR(*p)); + (void)printf("\n"); + for (p = s; *p; p++) + (void)printf("%c", *p & M_PROTECT ? '"' : ' '); + (void)printf("\n"); + for (p = s; *p; p++) + (void)printf("%c", ismeta(*p) ? '_' : ' '); + (void)printf("\n"); +} +#endif diff --git a/lib/libc/gen/initgroups.c b/lib/libc/gen/initgroups.c new file mode 100644 index 0000000..50c910a --- /dev/null +++ b/lib/libc/gen/initgroups.c @@ -0,0 +1,63 @@ +/* + * Copyright (c) 1983, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)initgroups.c 8.1 (Berkeley) 6/4/93"; +#endif +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/initgroups.c,v 1.8 2003/11/19 15:51:26 dds Exp $"); + +#include + +#include +#include "namespace.h" +#include +#include "un-namespace.h" +#include + +int +initgroups(uname, agroup) + const char *uname; + gid_t agroup; +{ + int ngroups; + /* + * Provide space for one group more than NGROUPS to allow + * setgroups to fail and set errno. + */ + gid_t groups[NGROUPS + 1]; + + ngroups = NGROUPS + 1; + getgrouplist(uname, agroup, groups, &ngroups); + return (setgroups(ngroups, groups)); +} diff --git a/lib/libc/gen/isatty.c b/lib/libc/gen/isatty.c new file mode 100644 index 0000000..d16a963 --- /dev/null +++ b/lib/libc/gen/isatty.c @@ -0,0 +1,52 @@ +/* + * Copyright (c) 1988, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)isatty.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/isatty.c,v 1.5 2002/02/01 00:57:29 obrien Exp $"); + +#include +#include + +int +isatty(fd) + int fd; +{ + int retval; + struct termios t; + + retval = (tcgetattr(fd, &t) != -1); + return(retval); +} diff --git a/lib/libc/gen/isinf.c b/lib/libc/gen/isinf.c new file mode 100644 index 0000000..932675d --- /dev/null +++ b/lib/libc/gen/isinf.c @@ -0,0 +1,70 @@ +/*- + * Copyright (c) 2004 David Schultz + * 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 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 AUTHOR 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. + * + * $FreeBSD: src/lib/libc/gen/isinf.c,v 1.2 2004/07/10 15:52:26 marcel Exp $ + */ + +#include + +#include "fpmath.h" + +/* + * XXX These routines belong in libm, but they must remain in libc for + * binary compat until we can bump libm's major version number. + */ + +__weak_reference(__isinf, isinf); + +int +__isinf(double d) +{ + union IEEEd2bits u; + + u.d = d; + return (u.bits.exp == 2047 && u.bits.manl == 0 && u.bits.manh == 0); +} + +int +__isinff(float f) +{ + union IEEEf2bits u; + + u.f = f; + return (u.bits.exp == 255 && u.bits.man == 0); +} + +int +__isinfl(long double e) +{ + union IEEEl2bits u; + + u.e = e; + mask_nbit_l(u); +#ifndef __alpha__ + return (u.bits.exp == 32767 && u.bits.manl == 0 && u.bits.manh == 0); +#else + return (u.bits.exp == 2047 && u.bits.manl == 0 && u.bits.manh == 0); +#endif +} diff --git a/lib/libc/gen/isnan.c b/lib/libc/gen/isnan.c new file mode 100644 index 0000000..fd9f029 --- /dev/null +++ b/lib/libc/gen/isnan.c @@ -0,0 +1,57 @@ +/*- + * Copyright (c) 2004 David Schultz + * 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 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 AUTHOR 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. + * + * $FreeBSD: src/lib/libc/gen/isnan.c,v 1.2 2004/09/24 06:33:22 das Exp $ + */ + +#include + +#include "fpmath.h" + +/* + * XXX These routines belong in libm, but they must remain in libc for + * binary compat until we can bump libm's major version number. + */ + +__weak_reference(__isnan, isnan); +__weak_reference(__isnanf, isnanf); + +int +__isnan(double d) +{ + union IEEEd2bits u; + + u.d = d; + return (u.bits.exp == 2047 && (u.bits.manl != 0 || u.bits.manh != 0)); +} + +int +__isnanf(float f) +{ + union IEEEf2bits u; + + u.f = f; + return (u.bits.exp == 255 && u.bits.man != 0); +} diff --git a/lib/libc/gen/jrand48.c b/lib/libc/gen/jrand48.c new file mode 100644 index 0000000..f47bf2a --- /dev/null +++ b/lib/libc/gen/jrand48.c @@ -0,0 +1,24 @@ +/* + * 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 +__FBSDID("$FreeBSD: src/lib/libc/gen/jrand48.c,v 1.2 2002/03/22 21:52:05 obrien Exp $"); + +#include "rand48.h" + +long +jrand48(unsigned short xseed[3]) +{ + _dorand48(xseed); + return ((long) xseed[2] << 16) + (long) xseed[1]; +} diff --git a/lib/libc/gen/lcong48.c b/lib/libc/gen/lcong48.c new file mode 100644 index 0000000..8b11e08 --- /dev/null +++ b/lib/libc/gen/lcong48.c @@ -0,0 +1,33 @@ +/* + * 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 +__FBSDID("$FreeBSD: src/lib/libc/gen/lcong48.c,v 1.2 2002/03/22 21:52:05 obrien Exp $"); + +#include "rand48.h" + +extern unsigned short _rand48_seed[3]; +extern unsigned short _rand48_mult[3]; +extern unsigned short _rand48_add; + +void +lcong48(unsigned short p[7]) +{ + _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]; +} diff --git a/lib/libc/gen/ldexp.c b/lib/libc/gen/ldexp.c new file mode 100644 index 0000000..ce9e999 --- /dev/null +++ b/lib/libc/gen/ldexp.c @@ -0,0 +1,123 @@ +/* @(#)s_scalbn.c 5.1 93/09/24 */ +/* @(#)fdlibm.h 5.1 93/09/24 */ +/* + * ==================================================== + * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. + * + * Developed at SunPro, a Sun Microsystems, Inc. business. + * Permission to use, copy, modify, and distribute this + * software is freely granted, provided that this notice + * is preserved. + * ==================================================== + */ + +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/ldexp.c,v 1.1 2005/01/22 06:03:40 das Exp $"); + +#include +#include +#include + +/* Bit fiddling routines copied from msun/src/math_private.h,v 1.15 */ + +#if BYTE_ORDER == BIG_ENDIAN + +typedef union +{ + double value; + struct + { + uint32_t msw; + uint32_t lsw; + } parts; +} ieee_double_shape_type; + +#endif + +#if BYTE_ORDER == LITTLE_ENDIAN + +typedef union +{ + double value; + struct + { + uint32_t lsw; + uint32_t msw; + } parts; +} ieee_double_shape_type; + +#endif + +/* Get two 32 bit ints from a double. */ + +#define EXTRACT_WORDS(ix0,ix1,d) \ +do { \ + ieee_double_shape_type ew_u; \ + ew_u.value = (d); \ + (ix0) = ew_u.parts.msw; \ + (ix1) = ew_u.parts.lsw; \ +} while (0) + +/* Get the more significant 32 bit int from a double. */ + +#define GET_HIGH_WORD(i,d) \ +do { \ + ieee_double_shape_type gh_u; \ + gh_u.value = (d); \ + (i) = gh_u.parts.msw; \ +} while (0) + +/* Set the more significant 32 bits of a double from an int. */ + +#define SET_HIGH_WORD(d,v) \ +do { \ + ieee_double_shape_type sh_u; \ + sh_u.value = (d); \ + sh_u.parts.msw = (v); \ + (d) = sh_u.value; \ +} while (0) + + +static const double +two54 = 1.80143985094819840000e+16, /* 0x43500000, 0x00000000 */ +twom54 = 5.55111512312578270212e-17, /* 0x3C900000, 0x00000000 */ +huge = 1.0e+300, +tiny = 1.0e-300; + +static double +_copysign(double x, double y) +{ + uint32_t hx,hy; + GET_HIGH_WORD(hx,x); + GET_HIGH_WORD(hy,y); + SET_HIGH_WORD(x,(hx&0x7fffffff)|(hy&0x80000000)); + return x; +} + +double +ldexp(double x, int n) +{ + int32_t k,hx,lx; + EXTRACT_WORDS(hx,lx,x); + k = (hx&0x7ff00000)>>20; /* extract exponent */ + if (k==0) { /* 0 or subnormal x */ + if ((lx|(hx&0x7fffffff))==0) return x; /* +-0 */ + x *= two54; + GET_HIGH_WORD(hx,x); + k = ((hx&0x7ff00000)>>20) - 54; + if (n< -50000) return tiny*x; /*underflow*/ + } + if (k==0x7ff) return x+x; /* NaN or Inf */ + k = k+n; + if (k > 0x7fe) return huge*_copysign(huge,x); /* overflow */ + if (k > 0) /* normal result */ + {SET_HIGH_WORD(x,(hx&0x800fffff)|(k<<20)); return x;} + if (k <= -54) { + if (n > 50000) /* in case integer overflow in n+k */ + return huge*_copysign(huge,x); /*overflow*/ + else return tiny*_copysign(tiny,x); /*underflow*/ + } + k += 54; /* subnormal result */ + SET_HIGH_WORD(x,(hx&0x800fffff)|(k<<20)); + return x*twom54; +} diff --git a/lib/libc/gen/lockf.c b/lib/libc/gen/lockf.c new file mode 100644 index 0000000..375b2ce --- /dev/null +++ b/lib/libc/gen/lockf.c @@ -0,0 +1,89 @@ +/*- + * Copyright (c) 1997 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. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the NetBSD + * Foundation, Inc. and its contributors. + * 4. Neither the name of The NetBSD Foundation 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 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. + */ + +/* $NetBSD: lockf.c,v 1.1 1997/12/20 20:23:18 kleink Exp $ */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/lockf.c,v 1.8 2002/02/01 00:57:29 obrien Exp $"); + +#include "namespace.h" +#include +#include +#include +#include "un-namespace.h" + +int +lockf(filedes, function, size) + int filedes; + int function; + off_t size; +{ + struct flock fl; + int cmd; + + fl.l_start = 0; + fl.l_len = size; + fl.l_whence = SEEK_CUR; + + switch (function) { + case F_ULOCK: + cmd = F_SETLK; + fl.l_type = F_UNLCK; + break; + case F_LOCK: + cmd = F_SETLKW; + fl.l_type = F_WRLCK; + break; + case F_TLOCK: + cmd = F_SETLK; + fl.l_type = F_WRLCK; + break; + case F_TEST: + fl.l_type = F_WRLCK; + if (_fcntl(filedes, F_GETLK, &fl) == -1) + return (-1); + if (fl.l_type == F_UNLCK || fl.l_pid == getpid()) + return (0); + errno = EAGAIN; + return (-1); + /* NOTREACHED */ + default: + errno = EINVAL; + return (-1); + /* NOTREACHED */ + } + + return (_fcntl(filedes, cmd, &fl)); +} diff --git a/lib/libc/gen/lrand48.c b/lib/libc/gen/lrand48.c new file mode 100644 index 0000000..948b923 --- /dev/null +++ b/lib/libc/gen/lrand48.c @@ -0,0 +1,26 @@ +/* + * 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 +__FBSDID("$FreeBSD: src/lib/libc/gen/lrand48.c,v 1.2 2002/03/22 21:52:05 obrien Exp $"); + +#include "rand48.h" + +extern unsigned short _rand48_seed[3]; + +long +lrand48(void) +{ + _dorand48(_rand48_seed); + return ((long) _rand48_seed[2] << 15) + ((long) _rand48_seed[1] >> 1); +} diff --git a/lib/libc/gen/mrand48.c b/lib/libc/gen/mrand48.c new file mode 100644 index 0000000..f65ed77 --- /dev/null +++ b/lib/libc/gen/mrand48.c @@ -0,0 +1,26 @@ +/* + * 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 +__FBSDID("$FreeBSD: src/lib/libc/gen/mrand48.c,v 1.2 2002/03/22 21:52:05 obrien Exp $"); + +#include "rand48.h" + +extern unsigned short _rand48_seed[3]; + +long +mrand48(void) +{ + _dorand48(_rand48_seed); + return ((long) _rand48_seed[2] << 16) + (long) _rand48_seed[1]; +} diff --git a/lib/libc/gen/nftw.c b/lib/libc/gen/nftw.c new file mode 100644 index 0000000..01b099a --- /dev/null +++ b/lib/libc/gen/nftw.c @@ -0,0 +1,117 @@ +/* $OpenBSD: nftw.c,v 1.4 2004/07/07 16:05:23 millert Exp $ */ + +/* + * Copyright (c) 2003, 2004 Todd C. Miller + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + * Sponsored in part by the Defense Advanced Research Projects + * Agency (DARPA) and Air Force Research Laboratory, Air Force + * Materiel Command, USAF, under agreement number F39502-99-1-0512. + */ + +#if 0 +#if defined(LIBC_SCCS) && !defined(lint) +static const char rcsid[] = "$OpenBSD: nftw.c,v 1.4 2004/07/07 16:05:23 millert Exp $"; +#endif /* LIBC_SCCS and not lint */ +#endif + +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/nftw.c,v 1.1 2004/08/24 13:00:55 tjr Exp $"); + +#include +#include +#include +#include +#include +#include + +int +nftw(const char *path, int (*fn)(const char *, const struct stat *, int, + struct FTW *), int nfds, int ftwflags) +{ + char * const paths[2] = { (char *)path, NULL }; + struct FTW ftw; + FTSENT *cur; + FTS *ftsp; + int error = 0, ftsflags, fnflag, postorder, sverrno; + + /* XXX - nfds is currently unused */ + if (nfds < 1 || nfds > OPEN_MAX) { + errno = EINVAL; + return (-1); + } + + ftsflags = FTS_COMFOLLOW; + if (!(ftwflags & FTW_CHDIR)) + ftsflags |= FTS_NOCHDIR; + if (ftwflags & FTW_MOUNT) + ftsflags |= FTS_XDEV; + if (ftwflags & FTW_PHYS) + ftsflags |= FTS_PHYSICAL; + else + ftsflags |= FTS_LOGICAL; + postorder = (ftwflags & FTW_DEPTH) != 0; + ftsp = fts_open(paths, ftsflags, NULL); + if (ftsp == NULL) + return (-1); + while ((cur = fts_read(ftsp)) != NULL) { + switch (cur->fts_info) { + case FTS_D: + if (postorder) + continue; + fnflag = FTW_D; + break; + case FTS_DNR: + fnflag = FTW_DNR; + break; + case FTS_DP: + if (!postorder) + continue; + fnflag = FTW_DP; + break; + case FTS_F: + case FTS_DEFAULT: + fnflag = FTW_F; + break; + case FTS_NS: + case FTS_NSOK: + fnflag = FTW_NS; + break; + case FTS_SL: + fnflag = FTW_SL; + break; + case FTS_SLNONE: + fnflag = FTW_SLN; + break; + case FTS_DC: + errno = ELOOP; + /* FALLTHROUGH */ + default: + error = -1; + goto done; + } + ftw.base = cur->fts_pathlen - cur->fts_namelen; + ftw.level = cur->fts_level; + error = fn(cur->fts_path, cur->fts_statp, fnflag, &ftw); + if (error != 0) + break; + } +done: + sverrno = errno; + if (fts_close(ftsp) != 0 && error == 0) + error = -1; + else + errno = sverrno; + return (error); +} diff --git a/lib/libc/gen/nice.c b/lib/libc/gen/nice.c new file mode 100644 index 0000000..453caa7 --- /dev/null +++ b/lib/libc/gen/nice.c @@ -0,0 +1,60 @@ +/* + * Copyright (c) 1983, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)nice.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/nice.c,v 1.3 2002/03/22 21:52:05 obrien Exp $"); + +#include +#include +#include +#include +#include + +/* + * Backwards compatible nice. + */ +int +nice(incr) + int incr; +{ + int prio; + + errno = 0; + prio = getpriority(PRIO_PROCESS, 0); + if (prio == -1 && errno) + return (-1); + return (setpriority(PRIO_PROCESS, 0, prio + incr)); +} diff --git a/lib/libc/gen/nlist.c b/lib/libc/gen/nlist.c new file mode 100644 index 0000000..9acfb15 --- /dev/null +++ b/lib/libc/gen/nlist.c @@ -0,0 +1,416 @@ +/* + * Copyright (c) 1989, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)nlist.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/nlist.c,v 1.18.12.1 2005/12/30 22:13:56 marcel Exp $"); + +#include "namespace.h" +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include "un-namespace.h" + +#define _NLIST_DO_AOUT +#define _NLIST_DO_ELF + +#ifdef _NLIST_DO_ELF +#include +#include +#endif + +int __fdnlist(int, struct nlist *); +int __aout_fdnlist(int, struct nlist *); +int __elf_fdnlist(int, struct nlist *); + +int +nlist(name, list) + const char *name; + struct nlist *list; +{ + int fd, n; + + fd = _open(name, O_RDONLY, 0); + if (fd < 0) + return (-1); + n = __fdnlist(fd, list); + (void)_close(fd); + return (n); +} + +static struct nlist_handlers { + int (*fn)(int fd, struct nlist *list); +} nlist_fn[] = { +#ifdef _NLIST_DO_AOUT + { __aout_fdnlist }, +#endif +#ifdef _NLIST_DO_ELF + { __elf_fdnlist }, +#endif +}; + +int +__fdnlist(fd, list) + int fd; + struct nlist *list; +{ + int n = -1, i; + + for (i = 0; i < sizeof(nlist_fn) / sizeof(nlist_fn[0]); i++) { + n = (nlist_fn[i].fn)(fd, list); + if (n != -1) + break; + } + return (n); +} + +#define ISLAST(p) (p->n_un.n_name == 0 || p->n_un.n_name[0] == 0) + +#ifdef _NLIST_DO_AOUT +int +__aout_fdnlist(fd, list) + int fd; + struct nlist *list; +{ + struct nlist *p, *symtab; + caddr_t strtab, a_out_mmap; + off_t stroff, symoff; + u_long symsize; + int nent; + struct exec * exec; + struct stat st; + + /* check that file is at least as large as struct exec! */ + if ((_fstat(fd, &st) < 0) || (st.st_size < sizeof(struct exec))) + return (-1); + + /* Check for files too large to mmap. */ + if (st.st_size > SIZE_T_MAX) { + errno = EFBIG; + return (-1); + } + + /* + * Map the whole a.out file into our address space. + * We then find the string table withing this area. + * We do not just mmap the string table, as it probably + * does not start at a page boundary - we save ourselves a + * lot of nastiness by mmapping the whole file. + * + * This gives us an easy way to randomly access all the strings, + * without making the memory allocation permanent as with + * malloc/free (i.e., munmap will return it to the system). + */ + a_out_mmap = mmap(NULL, (size_t)st.st_size, PROT_READ, MAP_PRIVATE, fd, (off_t)0); + if (a_out_mmap == MAP_FAILED) + return (-1); + + exec = (struct exec *)a_out_mmap; + if (N_BADMAG(*exec)) { + munmap(a_out_mmap, (size_t)st.st_size); + return (-1); + } + + symoff = N_SYMOFF(*exec); + symsize = exec->a_syms; + stroff = symoff + symsize; + + /* find the string table in our mmapped area */ + strtab = a_out_mmap + stroff; + symtab = (struct nlist *)(a_out_mmap + symoff); + + /* + * clean out any left-over information for all valid entries. + * Type and value defined to be 0 if not found; historical + * versions cleared other and desc as well. Also figure out + * the largest string length so don't read any more of the + * string table than we have to. + * + * XXX clearing anything other than n_type and n_value violates + * the semantics given in the man page. + */ + nent = 0; + for (p = list; !ISLAST(p); ++p) { + p->n_type = 0; + p->n_other = 0; + p->n_desc = 0; + p->n_value = 0; + ++nent; + } + + while (symsize > 0) { + int soff; + + symsize-= sizeof(struct nlist); + soff = symtab->n_un.n_strx; + + + if (soff != 0 && (symtab->n_type & N_STAB) == 0) + for (p = list; !ISLAST(p); p++) + if (!strcmp(&strtab[soff], p->n_un.n_name)) { + p->n_value = symtab->n_value; + p->n_type = symtab->n_type; + p->n_desc = symtab->n_desc; + p->n_other = symtab->n_other; + if (--nent <= 0) + break; + } + symtab++; + } + munmap(a_out_mmap, (size_t)st.st_size); + return (nent); +} +#endif + +#ifdef _NLIST_DO_ELF +static void elf_sym_to_nlist(struct nlist *, Elf_Sym *, Elf_Shdr *, int); + +/* + * __elf_is_okay__ - Determine if ehdr really + * is ELF and valid for the target platform. + * + * WARNING: This is NOT an ELF ABI function and + * as such its use should be restricted. + */ +int +__elf_is_okay__(ehdr) + Elf_Ehdr *ehdr; +{ + int retval = 0; + /* + * We need to check magic, class size, endianess, + * and version before we look at the rest of the + * Elf_Ehdr structure. These few elements are + * represented in a machine independant fashion. + */ + if (IS_ELF(*ehdr) && + ehdr->e_ident[EI_CLASS] == ELF_TARG_CLASS && + ehdr->e_ident[EI_DATA] == ELF_TARG_DATA && + ehdr->e_ident[EI_VERSION] == ELF_TARG_VER) { + + /* Now check the machine dependant header */ + if (ehdr->e_machine == ELF_TARG_MACH && + ehdr->e_version == ELF_TARG_VER) + retval = 1; + } + return retval; +} + +int +__elf_fdnlist(fd, list) + int fd; + struct nlist *list; +{ + struct nlist *p; + Elf_Off symoff = 0, symstroff = 0; + Elf_Size symsize = 0, symstrsize = 0; + Elf_Ssize cc, i; + int nent = -1; + int errsave; + Elf_Sym sbuf[1024]; + Elf_Sym *s; + Elf_Ehdr ehdr; + char *strtab = NULL; + Elf_Shdr *shdr = NULL; + Elf_Size shdr_size; + void *base; + struct stat st; + + /* Make sure obj is OK */ + if (lseek(fd, (off_t)0, SEEK_SET) == -1 || + _read(fd, &ehdr, sizeof(Elf_Ehdr)) != sizeof(Elf_Ehdr) || + !__elf_is_okay__(&ehdr) || + _fstat(fd, &st) < 0) + return (-1); + + /* calculate section header table size */ + shdr_size = ehdr.e_shentsize * ehdr.e_shnum; + + /* Make sure it's not too big to mmap */ + if (shdr_size > SIZE_T_MAX) { + errno = EFBIG; + return (-1); + } + + /* mmap section header table */ + base = mmap(NULL, (size_t)shdr_size, PROT_READ, 0, fd, + (off_t)ehdr.e_shoff); + if (base == MAP_FAILED) + return (-1); + shdr = (Elf_Shdr *)base; + + /* + * Find the symbol table entry and it's corresponding + * string table entry. Version 1.1 of the ABI states + * that there is only one symbol table but that this + * could change in the future. + */ + for (i = 0; i < ehdr.e_shnum; i++) { + if (shdr[i].sh_type == SHT_SYMTAB) { + symoff = shdr[i].sh_offset; + symsize = shdr[i].sh_size; + symstroff = shdr[shdr[i].sh_link].sh_offset; + symstrsize = shdr[shdr[i].sh_link].sh_size; + break; + } + } + + /* Check for files too large to mmap. */ + if (symstrsize > SIZE_T_MAX) { + errno = EFBIG; + goto done; + } + /* + * Map string table into our address space. This gives us + * an easy way to randomly access all the strings, without + * making the memory allocation permanent as with malloc/free + * (i.e., munmap will return it to the system). + */ + base = mmap(NULL, (size_t)symstrsize, PROT_READ, 0, fd, + (off_t)symstroff); + if (base == MAP_FAILED) + goto done; + strtab = (char *)base; + + /* + * clean out any left-over information for all valid entries. + * Type and value defined to be 0 if not found; historical + * versions cleared other and desc as well. Also figure out + * the largest string length so don't read any more of the + * string table than we have to. + * + * XXX clearing anything other than n_type and n_value violates + * the semantics given in the man page. + */ + nent = 0; + for (p = list; !ISLAST(p); ++p) { + p->n_type = 0; + p->n_other = 0; + p->n_desc = 0; + p->n_value = 0; + ++nent; + } + + /* Don't process any further if object is stripped. */ + if (symoff == 0) + goto done; + + if (lseek(fd, (off_t) symoff, SEEK_SET) == -1) { + nent = -1; + goto done; + } + + while (symsize > 0 && nent > 0) { + cc = MIN(symsize, sizeof(sbuf)); + if (_read(fd, sbuf, cc) != cc) + break; + symsize -= cc; + for (s = sbuf; cc > 0 && nent > 0; ++s, cc -= sizeof(*s)) { + char *name; + struct nlist *p; + + name = strtab + s->st_name; + if (name[0] == '\0') + continue; + for (p = list; !ISLAST(p); p++) { + if ((p->n_un.n_name[0] == '_' && + strcmp(name, p->n_un.n_name+1) == 0) + || strcmp(name, p->n_un.n_name) == 0) { + elf_sym_to_nlist(p, s, shdr, + ehdr.e_shnum); + if (--nent <= 0) + break; + } + } + } + } + done: + errsave = errno; + if (strtab != NULL) + munmap(strtab, symstrsize); + if (shdr != NULL) + munmap(shdr, shdr_size); + errno = errsave; + return (nent); +} + +/* + * Convert an Elf_Sym into an nlist structure. This fills in only the + * n_value and n_type members. + */ +static void +elf_sym_to_nlist(nl, s, shdr, shnum) + struct nlist *nl; + Elf_Sym *s; + Elf_Shdr *shdr; + int shnum; +{ + nl->n_value = s->st_value; + + switch (s->st_shndx) { + case SHN_UNDEF: + case SHN_COMMON: + nl->n_type = N_UNDF; + break; + case SHN_ABS: + nl->n_type = ELF_ST_TYPE(s->st_info) == STT_FILE ? + N_FN : N_ABS; + break; + default: + if (s->st_shndx >= shnum) + nl->n_type = N_UNDF; + else { + Elf_Shdr *sh = shdr + s->st_shndx; + + nl->n_type = sh->sh_type == SHT_PROGBITS ? + (sh->sh_flags & SHF_WRITE ? N_DATA : N_TEXT) : + (sh->sh_type == SHT_NOBITS ? N_BSS : N_UNDF); + } + break; + } + + if (ELF_ST_BIND(s->st_info) == STB_GLOBAL || + ELF_ST_BIND(s->st_info) == STB_WEAK) + nl->n_type |= N_EXT; +} +#endif /* _NLIST_DO_ELF */ diff --git a/lib/libc/gen/nrand48.c b/lib/libc/gen/nrand48.c new file mode 100644 index 0000000..3a21c3f --- /dev/null +++ b/lib/libc/gen/nrand48.c @@ -0,0 +1,24 @@ +/* + * 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 +__FBSDID("$FreeBSD: src/lib/libc/gen/nrand48.c,v 1.2 2002/03/22 21:52:05 obrien Exp $"); + +#include "rand48.h" + +long +nrand48(unsigned short xseed[3]) +{ + _dorand48(xseed); + return ((long) xseed[2] << 15) + ((long) xseed[1] >> 1); +} diff --git a/lib/libc/gen/opendir.c b/lib/libc/gen/opendir.c new file mode 100644 index 0000000..9148240 --- /dev/null +++ b/lib/libc/gen/opendir.c @@ -0,0 +1,287 @@ +/* + * Copyright (c) 1983, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)opendir.c 8.8 (Berkeley) 5/1/95"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/opendir.c,v 1.22 2004/08/14 17:46:10 stefanf Exp $"); + +#include "namespace.h" +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include "un-namespace.h" + +#include "telldir.h" +/* + * Open a directory. + */ +DIR * +opendir(name) + const char *name; +{ + + return (__opendir2(name, DTF_HIDEW|DTF_NODUP)); +} + +DIR * +__opendir2(name, flags) + const char *name; + int flags; +{ + DIR *dirp; + int fd; + int incr; + int saved_errno; + int unionstack; + struct stat statb; + + /* + * stat() before _open() because opening of special files may be + * harmful. _fstat() after open because the file may have changed. + */ + if (stat(name, &statb) != 0) + return (NULL); + if (!S_ISDIR(statb.st_mode)) { + errno = ENOTDIR; + return (NULL); + } + if ((fd = _open(name, O_RDONLY | O_NONBLOCK)) == -1) + return (NULL); + dirp = NULL; + if (_fstat(fd, &statb) != 0) + goto fail; + if (!S_ISDIR(statb.st_mode)) { + errno = ENOTDIR; + goto fail; + } + if (_fcntl(fd, F_SETFD, FD_CLOEXEC) == -1 || + (dirp = malloc(sizeof(DIR) + sizeof(struct _telldir))) == NULL) + goto fail; + + dirp->dd_td = (struct _telldir *)((char *)dirp + sizeof(DIR)); + LIST_INIT(&dirp->dd_td->td_locq); + dirp->dd_td->td_loccnt = 0; + + /* + * Use the system page size if that is a multiple of DIRBLKSIZ. + * Hopefully this can be a big win someday by allowing page + * trades to user space to be done by _getdirentries(). + */ + incr = getpagesize(); + if ((incr % DIRBLKSIZ) != 0) + incr = DIRBLKSIZ; + + /* + * Determine whether this directory is the top of a union stack. + */ + if (flags & DTF_NODUP) { + struct statfs sfb; + + if (_fstatfs(fd, &sfb) < 0) + goto fail; + unionstack = !strcmp(sfb.f_fstypename, "unionfs") + || (sfb.f_flags & MNT_UNION); + } else { + unionstack = 0; + } + + if (unionstack) { + int len = 0; + int space = 0; + char *buf = 0; + char *ddptr = 0; + char *ddeptr; + int n; + struct dirent **dpv; + + /* + * The strategy here is to read all the directory + * entries into a buffer, sort the buffer, and + * remove duplicate entries by setting the inode + * number to zero. + */ + + do { + /* + * Always make at least DIRBLKSIZ bytes + * available to _getdirentries + */ + if (space < DIRBLKSIZ) { + space += incr; + len += incr; + buf = reallocf(buf, len); + if (buf == NULL) + goto fail; + ddptr = buf + (len - space); + } + + n = _getdirentries(fd, ddptr, space, &dirp->dd_seek); + if (n > 0) { + ddptr += n; + space -= n; + } + } while (n > 0); + + ddeptr = ddptr; + flags |= __DTF_READALL; + + /* + * Re-open the directory. + * This has the effect of rewinding back to the + * top of the union stack and is needed by + * programs which plan to fchdir to a descriptor + * which has also been read -- see fts.c. + */ + if (flags & DTF_REWIND) { + (void)_close(fd); + if ((fd = _open(name, O_RDONLY)) == -1) { + saved_errno = errno; + free(buf); + free(dirp); + errno = saved_errno; + return (NULL); + } + } + + /* + * There is now a buffer full of (possibly) duplicate + * names. + */ + dirp->dd_buf = buf; + + /* + * Go round this loop twice... + * + * Scan through the buffer, counting entries. + * On the second pass, save pointers to each one. + * Then sort the pointers and remove duplicate names. + */ + for (dpv = 0;;) { + n = 0; + ddptr = buf; + while (ddptr < ddeptr) { + struct dirent *dp; + + dp = (struct dirent *) ddptr; + if ((long)dp & 03L) + break; + if ((dp->d_reclen <= 0) || + (dp->d_reclen > (ddeptr + 1 - ddptr))) + break; + ddptr += dp->d_reclen; + if (dp->d_fileno) { + if (dpv) + dpv[n] = dp; + n++; + } + } + + if (dpv) { + struct dirent *xp; + + /* + * This sort must be stable. + */ + mergesort(dpv, n, sizeof(*dpv), alphasort); + + dpv[n] = NULL; + xp = NULL; + + /* + * Scan through the buffer in sort order, + * zapping the inode number of any + * duplicate names. + */ + for (n = 0; dpv[n]; n++) { + struct dirent *dp = dpv[n]; + + if ((xp == NULL) || + strcmp(dp->d_name, xp->d_name)) { + xp = dp; + } else { + dp->d_fileno = 0; + } + if (dp->d_type == DT_WHT && + (flags & DTF_HIDEW)) + dp->d_fileno = 0; + } + + free(dpv); + break; + } else { + dpv = malloc((n+1) * sizeof(struct dirent *)); + if (dpv == NULL) + break; + } + } + + dirp->dd_len = len; + dirp->dd_size = ddptr - dirp->dd_buf; + } else { + dirp->dd_len = incr; + dirp->dd_size = 0; + dirp->dd_buf = malloc(dirp->dd_len); + if (dirp->dd_buf == NULL) + goto fail; + dirp->dd_seek = 0; + flags &= ~DTF_REWIND; + } + + dirp->dd_loc = 0; + dirp->dd_fd = fd; + dirp->dd_flags = flags; + dirp->dd_lock = NULL; + + /* + * Set up seek point for rewinddir. + */ + dirp->dd_rewind = telldir(dirp); + + return (dirp); + +fail: + saved_errno = errno; + free(dirp); + (void)_close(fd); + errno = saved_errno; + return (NULL); +} diff --git a/lib/libc/gen/pause.c b/lib/libc/gen/pause.c new file mode 100644 index 0000000..4f56289 --- /dev/null +++ b/lib/libc/gen/pause.c @@ -0,0 +1,52 @@ +/* + * Copyright (c) 1983, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)pause.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/pause.c,v 1.6 2002/02/01 00:57:29 obrien Exp $"); + +#include +#include + +/* + * Backwards compatible pause. + */ +int +__pause() +{ + return sigpause(sigblock(0L)); +} +__weak_reference(__pause, pause); +__weak_reference(__pause, _pause); diff --git a/lib/libc/gen/pmadvise.c b/lib/libc/gen/pmadvise.c new file mode 100644 index 0000000..744c6e5 --- /dev/null +++ b/lib/libc/gen/pmadvise.c @@ -0,0 +1,16 @@ +/* + * The contents of this file are in the public domain. + * Written by Garrett A. Wollman, 2000-10-07. + * + */ + +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/pmadvise.c,v 1.3 2003/08/09 03:23:24 bms Exp $"); + +#include + +int +posix_madvise(void *address, size_t size, int how) +{ + return madvise(address, size, how); +} diff --git a/lib/libc/gen/popen.c b/lib/libc/gen/popen.c new file mode 100644 index 0000000..0ed5657 --- /dev/null +++ b/lib/libc/gen/popen.c @@ -0,0 +1,208 @@ +/* + * Copyright (c) 1988, 1993 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software written by Ken Arnold and + * published in UNIX Review, Vol. 6, No. 8. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)popen.c 8.3 (Berkeley) 5/3/95"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/popen.c,v 1.18 2003/01/04 00:15:15 tjr Exp $"); + +#include "namespace.h" +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include "un-namespace.h" +#include "libc_private.h" + +extern char **environ; + +static struct pid { + struct pid *next; + FILE *fp; + pid_t pid; +} *pidlist; +static pthread_mutex_t pidlist_mutex = PTHREAD_MUTEX_INITIALIZER; + +#define THREAD_LOCK() if (__isthreaded) _pthread_mutex_lock(&pidlist_mutex) +#define THREAD_UNLOCK() if (__isthreaded) _pthread_mutex_unlock(&pidlist_mutex) + +FILE * +popen(command, type) + const char *command, *type; +{ + struct pid *cur; + FILE *iop; + int pdes[2], pid, twoway; + char *argv[4]; + struct pid *p; + + /* + * Lite2 introduced two-way popen() pipes using _socketpair(). + * FreeBSD's pipe() is bidirectional, so we use that. + */ + if (strchr(type, '+')) { + twoway = 1; + type = "r+"; + } else { + twoway = 0; + if ((*type != 'r' && *type != 'w') || type[1]) + return (NULL); + } + if (pipe(pdes) < 0) + return (NULL); + + if ((cur = malloc(sizeof(struct pid))) == NULL) { + (void)_close(pdes[0]); + (void)_close(pdes[1]); + return (NULL); + } + + argv[0] = "sh"; + argv[1] = "-c"; + argv[2] = (char *)command; + argv[3] = NULL; + + THREAD_LOCK(); + switch (pid = vfork()) { + case -1: /* Error. */ + THREAD_UNLOCK(); + (void)_close(pdes[0]); + (void)_close(pdes[1]); + free(cur); + return (NULL); + /* NOTREACHED */ + case 0: /* Child. */ + if (*type == 'r') { + /* + * The _dup2() to STDIN_FILENO is repeated to avoid + * writing to pdes[1], which might corrupt the + * parent's copy. This isn't good enough in + * general, since the _exit() is no return, so + * the compiler is free to corrupt all the local + * variables. + */ + (void)_close(pdes[0]); + if (pdes[1] != STDOUT_FILENO) { + (void)_dup2(pdes[1], STDOUT_FILENO); + (void)_close(pdes[1]); + if (twoway) + (void)_dup2(STDOUT_FILENO, STDIN_FILENO); + } else if (twoway && (pdes[1] != STDIN_FILENO)) + (void)_dup2(pdes[1], STDIN_FILENO); + } else { + if (pdes[0] != STDIN_FILENO) { + (void)_dup2(pdes[0], STDIN_FILENO); + (void)_close(pdes[0]); + } + (void)_close(pdes[1]); + } + for (p = pidlist; p; p = p->next) { + (void)_close(fileno(p->fp)); + } + _execve(_PATH_BSHELL, argv, environ); + _exit(127); + /* NOTREACHED */ + } + THREAD_UNLOCK(); + + /* Parent; assume fdopen can't fail. */ + if (*type == 'r') { + iop = fdopen(pdes[0], type); + (void)_close(pdes[1]); + } else { + iop = fdopen(pdes[1], type); + (void)_close(pdes[0]); + } + + /* Link into list of file descriptors. */ + cur->fp = iop; + cur->pid = pid; + THREAD_LOCK(); + cur->next = pidlist; + pidlist = cur; + THREAD_UNLOCK(); + + return (iop); +} + +/* + * pclose -- + * Pclose returns -1 if stream is not associated with a `popened' command, + * if already `pclosed', or waitpid returns an error. + */ +int +pclose(iop) + FILE *iop; +{ + struct pid *cur, *last; + int pstat; + pid_t pid; + + /* + * Find the appropriate file pointer and remove it from the list. + */ + THREAD_LOCK(); + for (last = NULL, cur = pidlist; cur; last = cur, cur = cur->next) + if (cur->fp == iop) + break; + if (cur == NULL) { + THREAD_UNLOCK(); + return (-1); + } + if (last == NULL) + pidlist = cur->next; + else + last->next = cur->next; + THREAD_UNLOCK(); + + (void)fclose(iop); + + do { + pid = _wait4(cur->pid, &pstat, 0, (struct rusage *)0); + } while (pid == -1 && errno == EINTR); + + free(cur); + + return (pid == -1 ? -1 : pstat); +} diff --git a/lib/libc/gen/posixshm.c b/lib/libc/gen/posixshm.c new file mode 100644 index 0000000..0baa700 --- /dev/null +++ b/lib/libc/gen/posixshm.c @@ -0,0 +1,72 @@ +/* + * Copyright 2000 Massachusetts Institute of Technology + * + * Permission to use, copy, modify, and distribute this software and + * its documentation for any purpose and without fee is hereby + * granted, provided that both the above copyright notice and this + * permission notice appear in all copies, that both the above + * copyright notice and this permission notice appear in all + * supporting documentation, and that the name of M.I.T. not be used + * in advertising or publicity pertaining to distribution of the + * software without specific, written prior permission. M.I.T. makes + * no representations about the suitability of this software for any + * purpose. It is provided "as is" without express or implied + * warranty. + * + * THIS SOFTWARE IS PROVIDED BY M.I.T. ``AS IS''. M.I.T. DISCLAIMS + * ALL EXPRESS OR IMPLIED WARRANTIES WITH REGARD TO THIS SOFTWARE, + * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT + * SHALL M.I.T. 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 +__FBSDID("$FreeBSD: src/lib/libc/gen/posixshm.c,v 1.4 2002/02/01 00:57:29 obrien Exp $"); + +#include "namespace.h" +#include +#include +#include +#include + +#include +#include +#include "un-namespace.h" + +int +shm_open(const char *path, int flags, mode_t mode) +{ + int fd; + struct stat stab; + + if ((flags & O_ACCMODE) == O_WRONLY) + return (EINVAL); + + fd = _open(path, flags, mode); + if (fd != -1) { + if (_fstat(fd, &stab) != 0 || !S_ISREG(stab.st_mode)) { + _close(fd); + errno = EINVAL; + return (-1); + } + + if (_fcntl(fd, F_SETFL, (int)FPOSIXSHM) != 0) { + _close(fd); + return (-1); + } + } + return (fd); +} + +int +shm_unlink(const char *path) +{ + return (unlink(path)); +} diff --git a/lib/libc/gen/pselect.c b/lib/libc/gen/pselect.c new file mode 100644 index 0000000..13b2553 --- /dev/null +++ b/lib/libc/gen/pselect.c @@ -0,0 +1,78 @@ +/* + * Copyright 2000 Massachusetts Institute of Technology + * + * Permission to use, copy, modify, and distribute this software and + * its documentation for any purpose and without fee is hereby + * granted, provided that both the above copyright notice and this + * permission notice appear in all copies, that both the above + * copyright notice and this permission notice appear in all + * supporting documentation, and that the name of M.I.T. not be used + * in advertising or publicity pertaining to distribution of the + * software without specific, written prior permission. M.I.T. makes + * no representations about the suitability of this software for any + * purpose. It is provided "as is" without express or implied + * warranty. + * + * THIS SOFTWARE IS PROVIDED BY M.I.T. ``AS IS''. M.I.T. DISCLAIMS + * ALL EXPRESS OR IMPLIED WARRANTIES WITH REGARD TO THIS SOFTWARE, + * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT + * SHALL M.I.T. 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 +__FBSDID("$FreeBSD: src/lib/libc/gen/pselect.c,v 1.6 2002/10/12 16:13:37 mike Exp $"); + +#include "namespace.h" +#include +#include + +#include +#include +#include "un-namespace.h" + +__weak_reference(__pselect, pselect); + +/* + * Emulate the POSIX 1003.1g-2000 `pselect' interface. This is the + * same as the traditional BSD `select' function, except that it uses + * a timespec rather than a timeval, doesn't modify the timeout argument, + * and allows the user to specify a signal mask to apply during the select. + */ +int +__pselect(int count, fd_set * __restrict rfds, fd_set * __restrict wfds, + fd_set * __restrict efds, const struct timespec * __restrict timo, + const sigset_t * __restrict mask) +{ + sigset_t omask; + struct timeval tvtimo, *tvp; + int rv, sverrno; + + if (timo) { + TIMESPEC_TO_TIMEVAL(&tvtimo, timo); + tvp = &tvtimo; + } else + tvp = 0; + + if (mask != 0) { + rv = _sigprocmask(SIG_SETMASK, mask, &omask); + if (rv != 0) + return rv; + } + + rv = _select(count, rfds, wfds, efds, tvp); + if (mask != 0) { + sverrno = errno; + _sigprocmask(SIG_SETMASK, &omask, (sigset_t *)0); + errno = sverrno; + } + + return rv; +} diff --git a/lib/libc/gen/psignal.c b/lib/libc/gen/psignal.c new file mode 100644 index 0000000..832e04b --- /dev/null +++ b/lib/libc/gen/psignal.c @@ -0,0 +1,67 @@ +/* + * Copyright (c) 1983, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)psignal.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/psignal.c,v 1.7 2002/02/01 01:08:48 obrien Exp $"); + +/* + * Print the name of the signal indicated + * along with the supplied message. + */ +#include "namespace.h" +#include +#include +#include +#include "un-namespace.h" + +void +psignal(sig, s) + unsigned int sig; + const char *s; +{ + const char *c; + + if (sig < NSIG) + c = sys_siglist[sig]; + else + c = "Unknown signal"; + if (s != NULL && *s != '\0') { + (void)_write(STDERR_FILENO, s, strlen(s)); + (void)_write(STDERR_FILENO, ": ", 2); + } + (void)_write(STDERR_FILENO, c, strlen(c)); + (void)_write(STDERR_FILENO, "\n", 1); +} diff --git a/lib/libc/gen/pw_scan.c b/lib/libc/gen/pw_scan.c new file mode 100644 index 0000000..a5057f9 --- /dev/null +++ b/lib/libc/gen/pw_scan.c @@ -0,0 +1,205 @@ +/*- + * Copyright (c) 1990, 1993, 1994 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)pw_scan.c 8.3 (Berkeley) 4/2/94"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/pw_scan.c,v 1.25 2004/01/18 21:33:25 charnier Exp $"); + +/* + * This module is used to "verify" password entries by chpass(1) and + * pwd_mkdb(8). + */ + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "pw_scan.h" + +/* + * Some software assumes that IDs are short. We should emit warnings + * for id's which cannot be stored in a short, but we are more liberal + * by default, warning for IDs greater than USHRT_MAX. + * + * If pw_big_ids_warning is -1 on entry to pw_scan(), it will be set based + * on the existence of PW_SCAN_BIG_IDS in the environment. + */ +static int pw_big_ids_warning = -1; + +int +__pw_scan(char *bp, struct passwd *pw, int flags) +{ + uid_t id; + int root; + char *ep, *p, *sh; + + if (pw_big_ids_warning == -1) + pw_big_ids_warning = getenv("PW_SCAN_BIG_IDS") == NULL ? 1 : 0; + + pw->pw_fields = 0; + if (!(pw->pw_name = strsep(&bp, ":"))) /* login */ + goto fmt; + root = !strcmp(pw->pw_name, "root"); + if (pw->pw_name[0] && (pw->pw_name[0] != '+' || pw->pw_name[1] == '\0')) + pw->pw_fields |= _PWF_NAME; + + if (!(pw->pw_passwd = strsep(&bp, ":"))) /* passwd */ + goto fmt; + if (pw->pw_passwd[0]) + pw->pw_fields |= _PWF_PASSWD; + + if (!(p = strsep(&bp, ":"))) /* uid */ + goto fmt; + if (p[0]) + pw->pw_fields |= _PWF_UID; + else { + if (pw->pw_name[0] != '+' && pw->pw_name[0] != '-') { + if (flags & _PWSCAN_WARN) + warnx("no uid for user %s", pw->pw_name); + return (0); + } + } + id = strtoul(p, &ep, 10); + if (errno == ERANGE) { + if (flags & _PWSCAN_WARN) + warnx("%s > max uid value (%lu)", p, ULONG_MAX); + return (0); + } + if (*ep != '\0') { + if (flags & _PWSCAN_WARN) + warnx("%s uid is incorrect", p); + return (0); + } + if (root && id) { + if (flags & _PWSCAN_WARN) + warnx("root uid should be 0"); + return (0); + } + if (flags & _PWSCAN_WARN && pw_big_ids_warning && id > USHRT_MAX) { + warnx("%s > recommended max uid value (%u)", p, USHRT_MAX); + /*return (0);*/ /* THIS SHOULD NOT BE FATAL! */ + } + pw->pw_uid = id; + + if (!(p = strsep(&bp, ":"))) /* gid */ + goto fmt; + if (p[0]) + pw->pw_fields |= _PWF_GID; + else { + if (pw->pw_name[0] != '+' && pw->pw_name[0] != '-') { + if (flags & _PWSCAN_WARN) + warnx("no gid for user %s", pw->pw_name); + return (0); + } + } + id = strtoul(p, &ep, 10); + if (errno == ERANGE) { + if (flags & _PWSCAN_WARN) + warnx("%s > max gid value (%lu)", p, ULONG_MAX); + return (0); + } + if (*ep != '\0') { + if (flags & _PWSCAN_WARN) + warnx("%s gid is incorrect", p); + return (0); + } + if (flags & _PWSCAN_WARN && pw_big_ids_warning && id > USHRT_MAX) { + warnx("%s > recommended max gid value (%u)", p, USHRT_MAX); + /* return (0); This should not be fatal! */ + } + pw->pw_gid = id; + + if (flags & _PWSCAN_MASTER ) { + if (!(pw->pw_class = strsep(&bp, ":"))) /* class */ + goto fmt; + if (pw->pw_class[0]) + pw->pw_fields |= _PWF_CLASS; + + if (!(p = strsep(&bp, ":"))) /* change */ + goto fmt; + if (p[0]) + pw->pw_fields |= _PWF_CHANGE; + pw->pw_change = atol(p); + + if (!(p = strsep(&bp, ":"))) /* expire */ + goto fmt; + if (p[0]) + pw->pw_fields |= _PWF_EXPIRE; + pw->pw_expire = atol(p); + } + if (!(pw->pw_gecos = strsep(&bp, ":"))) /* gecos */ + goto fmt; + if (pw->pw_gecos[0]) + pw->pw_fields |= _PWF_GECOS; + + if (!(pw->pw_dir = strsep(&bp, ":"))) /* directory */ + goto fmt; + if (pw->pw_dir[0]) + pw->pw_fields |= _PWF_DIR; + + if (!(pw->pw_shell = strsep(&bp, ":"))) /* shell */ + goto fmt; + + p = pw->pw_shell; + if (root && *p) { /* empty == /bin/sh */ + for (setusershell();;) { + if (!(sh = getusershell())) { + if (flags & _PWSCAN_WARN) + warnx("warning, unknown root shell"); + break; + } + if (!strcmp(p, sh)) + break; + } + endusershell(); + } + if (p[0]) + pw->pw_fields |= _PWF_SHELL; + + if ((p = strsep(&bp, ":"))) { /* too many */ +fmt: + if (flags & _PWSCAN_WARN) + warnx("corrupted entry"); + return (0); + } + return (1); +} diff --git a/lib/libc/gen/pw_scan.h b/lib/libc/gen/pw_scan.h new file mode 100644 index 0000000..28669f7 --- /dev/null +++ b/lib/libc/gen/pw_scan.h @@ -0,0 +1,40 @@ +/*- + * Copyright (c) 1994 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * @(#)pw_scan.h 8.1 (Berkeley) 4/1/94 + * $FreeBSD: src/lib/libc/gen/pw_scan.h,v 1.6 2002/03/22 23:41:42 obrien Exp $ + */ + +#define _PWSCAN_MASTER 0x01 +#define _PWSCAN_WARN 0x02 + +extern int __pw_scan(char *, struct passwd *, int); diff --git a/lib/libc/gen/pwcache.c b/lib/libc/gen/pwcache.c new file mode 100644 index 0000000..2d4b272 --- /dev/null +++ b/lib/libc/gen/pwcache.c @@ -0,0 +1,117 @@ +/* + * Copyright (c) 1989, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)pwcache.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/pwcache.c,v 1.10 2002/03/22 02:35:47 imp Exp $"); + +#include + +#include +#include +#include +#include +#include + +#define NCACHE 64 /* power of 2 */ +#define MASK (NCACHE - 1) /* bits to store with */ + +const char * +user_from_uid(uid_t uid, int nouser) +{ + static struct ncache { + uid_t uid; + int found; + char name[UT_NAMESIZE + 1]; + } c_uid[NCACHE]; + static int pwopen; + struct passwd *pw; + struct ncache *cp; + + cp = c_uid + (uid & MASK); + if (cp->uid != uid || !*cp->name) { + if (pwopen == 0) { + setpassent(1); + pwopen = 1; + } + pw = getpwuid(uid); + cp->uid = uid; + if (pw != NULL) { + cp->found = 1; + (void)strncpy(cp->name, pw->pw_name, UT_NAMESIZE); + cp->name[UT_NAMESIZE] = '\0'; + } else { + cp->found = 0; + (void)snprintf(cp->name, UT_NAMESIZE, "%u", uid); + if (nouser) + return (NULL); + } + } + return ((nouser && !cp->found) ? NULL : cp->name); +} + +const char * +group_from_gid(gid_t gid, int nogroup) +{ + static struct ncache { + gid_t gid; + int found; + char name[UT_NAMESIZE + 1]; + } c_gid[NCACHE]; + static int gropen; + struct group *gr; + struct ncache *cp; + + cp = c_gid + (gid & MASK); + if (cp->gid != gid || !*cp->name) { + if (gropen == 0) { + setgroupent(1); + gropen = 1; + } + gr = getgrgid(gid); + cp->gid = gid; + if (gr != NULL) { + cp->found = 1; + (void)strncpy(cp->name, gr->gr_name, UT_NAMESIZE); + cp->name[UT_NAMESIZE] = '\0'; + } else { + cp->found = 0; + (void)snprintf(cp->name, UT_NAMESIZE, "%u", gid); + if (nogroup) + return (NULL); + } + } + return ((nogroup && !cp->found) ? NULL : cp->name); +} diff --git a/lib/libc/gen/raise.c b/lib/libc/gen/raise.c new file mode 100644 index 0000000..4a94cb9 --- /dev/null +++ b/lib/libc/gen/raise.c @@ -0,0 +1,51 @@ +/*- + * Copyright (c) 1990, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)raise.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/raise.c,v 1.4 2003/07/19 05:22:56 davidxu Exp $"); + +#include +#include + +__weak_reference(__raise, raise); +__weak_reference(__raise, _raise); + +int +__raise(s) + int s; +{ + return(kill(getpid(), s)); +} diff --git a/lib/libc/gen/rand48.h b/lib/libc/gen/rand48.h new file mode 100644 index 0000000..0a3d83d --- /dev/null +++ b/lib/libc/gen/rand48.h @@ -0,0 +1,32 @@ +/* + * 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. + * + * $FreeBSD: src/lib/libc/gen/rand48.h,v 1.2 2002/02/01 01:32:19 obrien Exp $ + */ + +#ifndef _RAND48_H_ +#define _RAND48_H_ + +#include +#include + +void _dorand48(unsigned short[3]); + +#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_ */ diff --git a/lib/libc/gen/readdir.c b/lib/libc/gen/readdir.c new file mode 100644 index 0000000..fa0438c --- /dev/null +++ b/lib/libc/gen/readdir.c @@ -0,0 +1,134 @@ +/* + * Copyright (c) 1983, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)readdir.c 8.3 (Berkeley) 9/29/94"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/readdir.c,v 1.11 2002/02/26 21:39:32 alfred Exp $"); + +#include "namespace.h" +#include +#include +#include +#include +#include +#include "un-namespace.h" + +#include "libc_private.h" + +/* + * get next entry in a directory. + */ +struct dirent * +_readdir_unlocked(dirp) + DIR *dirp; +{ + struct dirent *dp; + + for (;;) { + if (dirp->dd_loc >= dirp->dd_size) { + if (dirp->dd_flags & __DTF_READALL) + return (NULL); + dirp->dd_loc = 0; + } + if (dirp->dd_loc == 0 && !(dirp->dd_flags & __DTF_READALL)) { + dirp->dd_size = _getdirentries(dirp->dd_fd, + dirp->dd_buf, dirp->dd_len, &dirp->dd_seek); + if (dirp->dd_size <= 0) + return (NULL); + } + dp = (struct dirent *)(dirp->dd_buf + dirp->dd_loc); + if ((long)dp & 03L) /* bogus pointer check */ + return (NULL); + if (dp->d_reclen <= 0 || + dp->d_reclen > dirp->dd_len + 1 - dirp->dd_loc) + return (NULL); + dirp->dd_loc += dp->d_reclen; + if (dp->d_ino == 0) + continue; + if (dp->d_type == DT_WHT && (dirp->dd_flags & DTF_HIDEW)) + continue; + return (dp); + } +} + +struct dirent * +readdir(dirp) + DIR *dirp; +{ + struct dirent *dp; + + if (__isthreaded) { + _pthread_mutex_lock((pthread_mutex_t *)&dirp->dd_lock); + dp = _readdir_unlocked(dirp); + _pthread_mutex_unlock((pthread_mutex_t *)&dirp->dd_lock); + } + else + dp = _readdir_unlocked(dirp); + return (dp); +} + +int +readdir_r(dirp, entry, result) + DIR *dirp; + struct dirent *entry; + struct dirent **result; +{ + struct dirent *dp; + int saved_errno; + + saved_errno = errno; + errno = 0; + if (__isthreaded) { + _pthread_mutex_lock((pthread_mutex_t *)&dirp->dd_lock); + if ((dp = _readdir_unlocked(dirp)) != NULL) + memcpy(entry, dp, _GENERIC_DIRSIZ(dp)); + _pthread_mutex_unlock((pthread_mutex_t *)&dirp->dd_lock); + } + else if ((dp = _readdir_unlocked(dirp)) != NULL) + memcpy(entry, dp, _GENERIC_DIRSIZ(dp)); + + if (errno != 0) { + if (dp == NULL) + return (errno); + } else + errno = saved_errno; + + if (dp != NULL) + *result = entry; + else + *result = NULL; + + return (0); +} diff --git a/lib/libc/gen/readpassphrase.c b/lib/libc/gen/readpassphrase.c new file mode 100644 index 0000000..d100be4 --- /dev/null +++ b/lib/libc/gen/readpassphrase.c @@ -0,0 +1,178 @@ +/* $OpenBSD: readpassphrase.c,v 1.12 2001/12/15 05:41:00 millert Exp $ */ + +/* + * Copyright (c) 2000 Todd C. Miller + * 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 not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED ``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. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static const char rcsid[] = "$OpenBSD: readpassphrase.c,v 1.12 2001/12/15 05:41:00 millert Exp $"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/readpassphrase.c,v 1.6 2002/03/09 03:16:41 green Exp $"); + +#include "namespace.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "un-namespace.h" + +static volatile sig_atomic_t signo; + +static void handler(int); + +char * +readpassphrase(const char *prompt, char *buf, size_t bufsiz, int flags) +{ + ssize_t nr; + int input, output, save_errno; + char ch, *p, *end; + struct termios term, oterm; + struct sigaction sa, saveint, savehup, savequit, saveterm; + struct sigaction savetstp, savettin, savettou; + + /* I suppose we could alloc on demand in this case (XXX). */ + if (bufsiz == 0) { + errno = EINVAL; + return(NULL); + } + +restart: + /* + * Read and write to /dev/tty if available. If not, read from + * stdin and write to stderr unless a tty is required. + */ + if ((input = output = _open(_PATH_TTY, O_RDWR)) == -1) { + if (flags & RPP_REQUIRE_TTY) { + errno = ENOTTY; + return(NULL); + } + input = STDIN_FILENO; + output = STDERR_FILENO; + } + + /* + * Catch signals that would otherwise cause the user to end + * up with echo turned off in the shell. Don't worry about + * things like SIGALRM and SIGPIPE for now. + */ + sigemptyset(&sa.sa_mask); + sa.sa_flags = 0; /* don't restart system calls */ + sa.sa_handler = handler; + (void)_sigaction(SIGINT, &sa, &saveint); + (void)_sigaction(SIGHUP, &sa, &savehup); + (void)_sigaction(SIGQUIT, &sa, &savequit); + (void)_sigaction(SIGTERM, &sa, &saveterm); + (void)_sigaction(SIGTSTP, &sa, &savetstp); + (void)_sigaction(SIGTTIN, &sa, &savettin); + (void)_sigaction(SIGTTOU, &sa, &savettou); + + /* Turn off echo if possible. */ + if (tcgetattr(input, &oterm) == 0) { + memcpy(&term, &oterm, sizeof(term)); + if (!(flags & RPP_ECHO_ON)) + term.c_lflag &= ~(ECHO | ECHONL); + if (term.c_cc[VSTATUS] != _POSIX_VDISABLE) + term.c_cc[VSTATUS] = _POSIX_VDISABLE; + (void)tcsetattr(input, TCSAFLUSH|TCSASOFT, &term); + } else { + memset(&term, 0, sizeof(term)); + memset(&oterm, 0, sizeof(oterm)); + } + + (void)_write(output, prompt, strlen(prompt)); + end = buf + bufsiz - 1; + for (p = buf; (nr = _read(input, &ch, 1)) == 1 && ch != '\n' && ch != '\r';) { + if (p < end) { + if ((flags & RPP_SEVENBIT)) + ch &= 0x7f; + if (isalpha(ch)) { + if ((flags & RPP_FORCELOWER)) + ch = tolower(ch); + if ((flags & RPP_FORCEUPPER)) + ch = toupper(ch); + } + *p++ = ch; + } + } + *p = '\0'; + save_errno = errno; + if (!(term.c_lflag & ECHO)) + (void)_write(output, "\n", 1); + + /* Restore old terminal settings and signals. */ + if (memcmp(&term, &oterm, sizeof(term)) != 0) + (void)tcsetattr(input, TCSANOW|TCSASOFT, &oterm); + (void)_sigaction(SIGINT, &saveint, NULL); + (void)_sigaction(SIGHUP, &savehup, NULL); + (void)_sigaction(SIGQUIT, &savequit, NULL); + (void)_sigaction(SIGTERM, &saveterm, NULL); + (void)_sigaction(SIGTSTP, &savetstp, NULL); + (void)_sigaction(SIGTTIN, &savettin, NULL); + (void)_sigaction(SIGTTOU, &savettou, NULL); + if (input != STDIN_FILENO) + (void)_close(input); + + /* + * If we were interrupted by a signal, resend it to ourselves + * now that we have restored the signal handlers. + */ + if (signo) { + kill(getpid(), signo); + switch (signo) { + case SIGTSTP: + case SIGTTIN: + case SIGTTOU: + signo = 0; + goto restart; + } + } + + errno = save_errno; + return(nr == -1 ? NULL : buf); +} + +char * +getpass(const char *prompt) +{ + static char buf[_PASSWORD_LEN + 1]; + + if (readpassphrase(prompt, buf, sizeof(buf), RPP_ECHO_OFF) == NULL) + buf[0] = '\0'; + return(buf); +} + +static void handler(int s) +{ + + signo = s; +} diff --git a/lib/libc/gen/rewinddir.c b/lib/libc/gen/rewinddir.c new file mode 100644 index 0000000..dae75cc --- /dev/null +++ b/lib/libc/gen/rewinddir.c @@ -0,0 +1,52 @@ +/*- + * Copyright (c) 1990, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)rewinddir.c 8.1 (Berkeley) 6/8/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/rewinddir.c,v 1.5 2002/02/01 00:57:29 obrien Exp $"); + +#include +#include + +#include "telldir.h" + +void +rewinddir(dirp) + DIR *dirp; +{ + + _seekdir(dirp, dirp->dd_rewind); + dirp->dd_rewind = telldir(dirp); +} diff --git a/lib/libc/gen/scandir.c b/lib/libc/gen/scandir.c new file mode 100644 index 0000000..cf79bce --- /dev/null +++ b/lib/libc/gen/scandir.c @@ -0,0 +1,150 @@ +/* + * Copyright (c) 1983, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)scandir.c 8.3 (Berkeley) 1/2/94"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/scandir.c,v 1.7 2002/02/01 01:32:19 obrien Exp $"); + +/* + * Scan the directory dirname calling select to make a list of selected + * directory entries then sort using qsort and compare routine dcomp. + * Returns the number of entries and a pointer to a list of pointers to + * struct dirent (through namelist). Returns -1 if there were any errors. + */ + +#include "namespace.h" +#include +#include +#include +#include +#include +#include "un-namespace.h" + +/* + * The DIRSIZ macro is the minimum record length which will hold the directory + * entry. This requires the amount of space in struct dirent without the + * d_name field, plus enough space for the name and a terminating nul byte + * (dp->d_namlen + 1), rounded up to a 4 byte boundary. + */ +#undef DIRSIZ +#define DIRSIZ(dp) \ + ((sizeof(struct dirent) - sizeof(dp)->d_name) + \ + (((dp)->d_namlen + 1 + 3) &~ 3)) + +int +scandir(dirname, namelist, select, dcomp) + const char *dirname; + struct dirent ***namelist; + int (*select)(struct dirent *); + int (*dcomp)(const void *, const void *); +{ + struct dirent *d, *p, **names = NULL; + size_t nitems = 0; + struct stat stb; + long arraysz; + DIR *dirp; + + if ((dirp = opendir(dirname)) == NULL) + return(-1); + if (_fstat(dirp->dd_fd, &stb) < 0) + goto fail; + + /* + * estimate the array size by taking the size of the directory file + * and dividing it by a multiple of the minimum size entry. + */ + arraysz = (stb.st_size / 24); + names = (struct dirent **)malloc(arraysz * sizeof(struct dirent *)); + if (names == NULL) + goto fail; + + while ((d = readdir(dirp)) != NULL) { + if (select != NULL && !(*select)(d)) + continue; /* just selected names */ + /* + * Make a minimum size copy of the data + */ + p = (struct dirent *)malloc(DIRSIZ(d)); + if (p == NULL) + goto fail; + p->d_fileno = d->d_fileno; + p->d_type = d->d_type; + p->d_reclen = d->d_reclen; + p->d_namlen = d->d_namlen; + bcopy(d->d_name, p->d_name, p->d_namlen + 1); + /* + * Check to make sure the array has space left and + * realloc the maximum size. + */ + if (nitems >= arraysz) { + const int inc = 10; /* increase by this much */ + struct dirent **names2; + + names2 = (struct dirent **)realloc((char *)names, + (arraysz + inc) * sizeof(struct dirent *)); + if (names2 == NULL) { + free(p); + goto fail; + } + names = names2; + arraysz += inc; + } + names[nitems++] = p; + } + closedir(dirp); + if (nitems && dcomp != NULL) + qsort(names, nitems, sizeof(struct dirent *), dcomp); + *namelist = names; + return(nitems); + +fail: + while (nitems > 0) + free(names[--nitems]); + free(names); + closedir(dirp); + return -1; +} + +/* + * Alphabetic order comparison routine for those who want it. + */ +int +alphasort(d1, d2) + const void *d1; + const void *d2; +{ + return(strcmp((*(struct dirent **)d1)->d_name, + (*(struct dirent **)d2)->d_name)); +} diff --git a/lib/libc/gen/seed48.c b/lib/libc/gen/seed48.c new file mode 100644 index 0000000..94167a7 --- /dev/null +++ b/lib/libc/gen/seed48.c @@ -0,0 +1,39 @@ +/* + * 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 +__FBSDID("$FreeBSD: src/lib/libc/gen/seed48.c,v 1.2 2002/03/22 21:52:05 obrien Exp $"); + +#include "rand48.h" + +extern unsigned short _rand48_seed[3]; +extern unsigned short _rand48_mult[3]; +extern unsigned short _rand48_add; + +unsigned short * +seed48(unsigned short xseed[3]) +{ + static unsigned short sseed[3]; + + 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; +} diff --git a/lib/libc/gen/seekdir.c b/lib/libc/gen/seekdir.c new file mode 100644 index 0000000..5385819 --- /dev/null +++ b/lib/libc/gen/seekdir.c @@ -0,0 +1,63 @@ +/* + * Copyright (c) 1983, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)seekdir.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/seekdir.c,v 1.5 2002/02/01 00:57:29 obrien Exp $"); + +#include "namespace.h" +#include +#include +#include +#include "un-namespace.h" + +#include "libc_private.h" +#include "telldir.h" + +/* + * Seek to an entry in a directory. + * _seekdir is in telldir.c so that it can share opaque data structures. + */ +void +seekdir(dirp, loc) + DIR *dirp; + long loc; +{ + if (__isthreaded) + _pthread_mutex_lock((pthread_mutex_t *)&dirp->dd_lock); + _seekdir(dirp, loc); + if (__isthreaded) + _pthread_mutex_unlock((pthread_mutex_t *)&dirp->dd_lock); +} diff --git a/lib/libc/gen/sem.c b/lib/libc/gen/sem.c new file mode 100644 index 0000000..b7d3739 --- /dev/null +++ b/lib/libc/gen/sem.c @@ -0,0 +1,360 @@ +/* + * Copyright (C) 2000 Jason Evans . + * 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/gen/sem.c,v 1.13 2004/02/06 15:15:44 deischen Exp $ + */ + +/* + * Some notes about this implementation. + * + * This is mostly a simple implementation of POSIX semaphores that + * does not need threading. Any semaphore created is a kernel-based + * semaphore regardless of the pshared attribute. This is necessary + * because libc's stub for pthread_cond_wait() doesn't really wait, + * and it is not worth the effort impose this behavior on libc. + * + * All functions here are designed to be thread-safe so that a + * threads library need not provide wrappers except to make + * sem_wait() and sem_timedwait() cancellation points or to + * provide a faster userland implementation for non-pshared + * semaphores. + * + * Also, this implementation of semaphores cannot really support + * real pshared semaphores. The sem_t is an allocated object + * and can't be seen by other processes when placed in shared + * memory. It should work across forks as long as the semaphore + * is created before any forks. + * + * The function sem_init() should be overridden by a threads + * library if it wants to provide a different userland version + * of semaphores. The functions sem_wait() and sem_timedwait() + * need to be wrapped to provide cancellation points. The function + * sem_post() may need to be wrapped to be signal-safe. + */ +#include "namespace.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include <_semaphore.h> +#include "un-namespace.h" +#include "libc_private.h" + +static sem_t sem_alloc(unsigned int value, semid_t semid, int system_sem); +static void sem_free(sem_t sem); + +static LIST_HEAD(, sem) named_sems = LIST_HEAD_INITIALIZER(&named_sems); +static pthread_mutex_t named_sems_mtx = PTHREAD_MUTEX_INITIALIZER; + +__weak_reference(__sem_init, sem_init); +__weak_reference(__sem_destroy, sem_destroy); +__weak_reference(__sem_open, sem_open); +__weak_reference(__sem_close, sem_close); +__weak_reference(__sem_unlink, sem_unlink); +__weak_reference(__sem_wait, sem_wait); +__weak_reference(__sem_trywait, sem_trywait); +__weak_reference(__sem_timedwait, sem_timedwait); +__weak_reference(__sem_post, sem_post); +__weak_reference(__sem_getvalue, sem_getvalue); + + +static inline int +sem_check_validity(sem_t *sem) +{ + + if ((sem != NULL) && ((*sem)->magic == SEM_MAGIC)) + return (0); + else { + errno = EINVAL; + return (-1); + } +} + +static void +sem_free(sem_t sem) +{ + + _pthread_mutex_destroy(&sem->lock); + _pthread_cond_destroy(&sem->gtzero); + sem->magic = 0; + free(sem); +} + +static sem_t +sem_alloc(unsigned int value, semid_t semid, int system_sem) +{ + sem_t sem; + + if (value > SEM_VALUE_MAX) { + errno = EINVAL; + return (NULL); + } + + sem = (sem_t)malloc(sizeof(struct sem)); + if (sem == NULL) { + errno = ENOSPC; + return (NULL); + } + + sem->count = (uint32_t)value; + sem->nwaiters = 0; + sem->magic = SEM_MAGIC; + sem->semid = semid; + sem->syssem = system_sem; + sem->lock = PTHREAD_MUTEX_INITIALIZER; + sem->gtzero = PTHREAD_COND_INITIALIZER; + return (sem); +} + +int +__sem_init(sem_t *sem, int pshared, unsigned int value) +{ + semid_t semid; + + /* + * We always have to create the kernel semaphore if the + * threads library isn't present since libc's version of + * pthread_cond_wait() is just a stub that doesn't really + * wait. + */ + if (ksem_init(&semid, value) != 0) + return (-1); + + (*sem) = sem_alloc(value, semid, 1); + if ((*sem) == NULL) { + ksem_destroy(semid); + return (-1); + } + return (0); +} + +int +__sem_destroy(sem_t *sem) +{ + int retval; + + if (sem_check_validity(sem) != 0) + return (-1); + + _pthread_mutex_lock(&(*sem)->lock); + /* + * If this is a system semaphore let the kernel track it otherwise + * make sure there are no waiters. + */ + if ((*sem)->syssem != 0) + retval = ksem_destroy((*sem)->semid); + else if ((*sem)->nwaiters > 0) { + errno = EBUSY; + retval = -1; + } + else { + retval = 0; + (*sem)->magic = 0; + } + _pthread_mutex_unlock(&(*sem)->lock); + + if (retval == 0) { + _pthread_mutex_destroy(&(*sem)->lock); + _pthread_cond_destroy(&(*sem)->gtzero); + sem_free(*sem); + } + return (retval); +} + +sem_t * +__sem_open(const char *name, int oflag, ...) +{ + sem_t *sem; + sem_t s; + semid_t semid; + mode_t mode; + unsigned int value; + + mode = 0; + value = 0; + + if ((oflag & O_CREAT) != 0) { + va_list ap; + + va_start(ap, oflag); + mode = va_arg(ap, int); + value = va_arg(ap, unsigned int); + va_end(ap); + } + /* + * we can be lazy and let the kernel handle the "oflag", + * we'll just merge duplicate IDs into our list. + */ + if (ksem_open(&semid, name, oflag, mode, value) == -1) + return (SEM_FAILED); + /* + * search for a duplicate ID, we must return the same sem_t * + * if we locate one. + */ + _pthread_mutex_lock(&named_sems_mtx); + LIST_FOREACH(s, &named_sems, entry) { + if (s->semid == semid) { + sem = s->backpointer; + _pthread_mutex_unlock(&named_sems_mtx); + return (sem); + } + } + sem = (sem_t *)malloc(sizeof(*sem)); + if (sem == NULL) + goto err; + *sem = sem_alloc(value, semid, 1); + if ((*sem) == NULL) + goto err; + LIST_INSERT_HEAD(&named_sems, *sem, entry); + (*sem)->backpointer = sem; + _pthread_mutex_unlock(&named_sems_mtx); + return (sem); +err: + _pthread_mutex_unlock(&named_sems_mtx); + ksem_close(semid); + if (sem != NULL) { + if (*sem != NULL) + sem_free(*sem); + else + errno = ENOSPC; + free(sem); + } else { + errno = ENOSPC; + } + return (SEM_FAILED); +} + +int +__sem_close(sem_t *sem) +{ + + if (sem_check_validity(sem) != 0) + return (-1); + + if ((*sem)->syssem == 0) { + errno = EINVAL; + return (-1); + } + + _pthread_mutex_lock(&named_sems_mtx); + if (ksem_close((*sem)->semid) != 0) { + _pthread_mutex_unlock(&named_sems_mtx); + return (-1); + } + LIST_REMOVE((*sem), entry); + _pthread_mutex_unlock(&named_sems_mtx); + sem_free(*sem); + *sem = NULL; + free(sem); + return (0); +} + +int +__sem_unlink(const char *name) +{ + + return (ksem_unlink(name)); +} + +int +__sem_wait(sem_t *sem) +{ + + if (sem_check_validity(sem) != 0) + return (-1); + + return (ksem_wait((*sem)->semid)); +} + +int +__sem_trywait(sem_t *sem) +{ + int retval; + + if (sem_check_validity(sem) != 0) + return (-1); + + if ((*sem)->syssem != 0) + retval = ksem_trywait((*sem)->semid); + else { + _pthread_mutex_lock(&(*sem)->lock); + if ((*sem)->count > 0) { + (*sem)->count--; + retval = 0; + } else { + errno = EAGAIN; + retval = -1; + } + _pthread_mutex_unlock(&(*sem)->lock); + } + return (retval); +} + +int +__sem_timedwait(sem_t * __restrict sem, + struct timespec * __restrict abs_timeout) +{ + if (sem_check_validity(sem) != 0) + return (-1); + + return (ksem_timedwait((*sem)->semid, abs_timeout)); +} + +int +__sem_post(sem_t *sem) +{ + + if (sem_check_validity(sem) != 0) + return (-1); + + return (ksem_post((*sem)->semid)); +} + +int +__sem_getvalue(sem_t * __restrict sem, int * __restrict sval) +{ + int retval; + + if (sem_check_validity(sem) != 0) + return (-1); + + if ((*sem)->syssem != 0) + retval = ksem_getvalue((*sem)->semid, sval); + else { + _pthread_mutex_lock(&(*sem)->lock); + *sval = (int)(*sem)->count; + _pthread_mutex_unlock(&(*sem)->lock); + + retval = 0; + } + return (retval); +} diff --git a/lib/libc/gen/semctl.c b/lib/libc/gen/semctl.c new file mode 100644 index 0000000..4c0b249 --- /dev/null +++ b/lib/libc/gen/semctl.c @@ -0,0 +1,57 @@ +/*- + * Copyright (c) 2002 Doug Rabson + * 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 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 AUTHOR 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 +__FBSDID("$FreeBSD: src/lib/libc/gen/semctl.c,v 1.9 2003/02/16 17:29:09 nectar Exp $"); + +#include +#include +#include +#include +#include + +extern int __semctl(int semid, int semnum, int cmd, union semun *arg); + +int semctl(int semid, int semnum, int cmd, ...) +{ + va_list ap; + union semun semun; + union semun *semun_ptr; + + va_start(ap, cmd); + if (cmd == IPC_SET || cmd == IPC_STAT || cmd == GETALL + || cmd == SETVAL || cmd == SETALL) { + semun = va_arg(ap, union semun); + semun_ptr = &semun; + } else { + semun_ptr = NULL; + } + va_end(ap); + + return (__semctl(semid, semnum, cmd, semun_ptr)); +} diff --git a/lib/libc/gen/setdomainname.c b/lib/libc/gen/setdomainname.c new file mode 100644 index 0000000..571a73f --- /dev/null +++ b/lib/libc/gen/setdomainname.c @@ -0,0 +1,55 @@ +/* + * Copyright (c) 1989, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)sethostname.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/setdomainname.c,v 1.7 2002/02/01 00:57:29 obrien Exp $"); + +#include +#include + +#include + +int +setdomainname(const char *name, int namelen) +{ + int mib[2]; + + mib[0] = CTL_KERN; + mib[1] = KERN_NISDOMAINNAME; + if (sysctl(mib, 2, NULL, NULL, (void *)name, namelen) == -1) + return (-1); + return (0); +} diff --git a/lib/libc/gen/sethostname.c b/lib/libc/gen/sethostname.c new file mode 100644 index 0000000..3a15727 --- /dev/null +++ b/lib/libc/gen/sethostname.c @@ -0,0 +1,53 @@ +/* + * Copyright (c) 1989, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)sethostname.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/sethostname.c,v 1.4 2002/05/28 16:59:39 alfred Exp $"); + +#include +#include + +int +sethostname(const char *name, int namelen) +{ + int mib[2]; + + mib[0] = CTL_KERN; + mib[1] = KERN_HOSTNAME; + if (sysctl(mib, 2, NULL, NULL, (void *)name, namelen) == -1) + return (-1); + return (0); +} diff --git a/lib/libc/gen/setjmperr.c b/lib/libc/gen/setjmperr.c new file mode 100644 index 0000000..d5d8d06 --- /dev/null +++ b/lib/libc/gen/setjmperr.c @@ -0,0 +1,57 @@ +/* + * Copyright (c) 1980, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)setjmperr.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/setjmperr.c,v 1.5 2002/02/01 00:57:29 obrien Exp $"); + +/* + * This routine is called from longjmp() when an error occurs. + * Programs that wish to exit gracefully from this error may + * write their own versions. + * If this routine returns, the program is aborted. + */ + +#include "namespace.h" +#include +#include +#include "un-namespace.h" + +void +longjmperror() +{ +#define ERRMSG "longjmp botch.\n" + (void)_write(STDERR_FILENO, ERRMSG, sizeof(ERRMSG) - 1); +} diff --git a/lib/libc/gen/setmode.c b/lib/libc/gen/setmode.c new file mode 100644 index 0000000..0ffa82d --- /dev/null +++ b/lib/libc/gen/setmode.c @@ -0,0 +1,450 @@ +/* + * Copyright (c) 1989, 1993, 1994 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * Dave Borman at Cray Research, Inc. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)setmode.c 8.2 (Berkeley) 3/25/94"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/setmode.c,v 1.10 2005/04/08 21:15:38 stefanf Exp $"); + +#include "namespace.h" +#include +#include + +#include +#include +#include +#include +#include + +#ifdef SETMODE_DEBUG +#include +#endif +#include "un-namespace.h" + +#define SET_LEN 6 /* initial # of bitcmd struct to malloc */ +#define SET_LEN_INCR 4 /* # of bitcmd structs to add as needed */ + +typedef struct bitcmd { + char cmd; + char cmd2; + mode_t bits; +} BITCMD; + +#define CMD2_CLR 0x01 +#define CMD2_SET 0x02 +#define CMD2_GBITS 0x04 +#define CMD2_OBITS 0x08 +#define CMD2_UBITS 0x10 + +static BITCMD *addcmd(BITCMD *, int, int, int, u_int); +static void compress_mode(BITCMD *); +#ifdef SETMODE_DEBUG +static void dumpmode(BITCMD *); +#endif + +/* + * Given the old mode and an array of bitcmd structures, apply the operations + * described in the bitcmd structures to the old mode, and return the new mode. + * Note that there is no '=' command; a strict assignment is just a '-' (clear + * bits) followed by a '+' (set bits). + */ +mode_t +getmode(const void *bbox, mode_t omode) +{ + const BITCMD *set; + mode_t clrval, newmode, value; + + set = (const BITCMD *)bbox; + newmode = omode; + for (value = 0;; set++) + switch(set->cmd) { + /* + * When copying the user, group or other bits around, we "know" + * where the bits are in the mode so that we can do shifts to + * copy them around. If we don't use shifts, it gets real + * grundgy with lots of single bit checks and bit sets. + */ + case 'u': + value = (newmode & S_IRWXU) >> 6; + goto common; + + case 'g': + value = (newmode & S_IRWXG) >> 3; + goto common; + + case 'o': + value = newmode & S_IRWXO; +common: if (set->cmd2 & CMD2_CLR) { + clrval = + (set->cmd2 & CMD2_SET) ? S_IRWXO : value; + if (set->cmd2 & CMD2_UBITS) + newmode &= ~((clrval<<6) & set->bits); + if (set->cmd2 & CMD2_GBITS) + newmode &= ~((clrval<<3) & set->bits); + if (set->cmd2 & CMD2_OBITS) + newmode &= ~(clrval & set->bits); + } + if (set->cmd2 & CMD2_SET) { + if (set->cmd2 & CMD2_UBITS) + newmode |= (value<<6) & set->bits; + if (set->cmd2 & CMD2_GBITS) + newmode |= (value<<3) & set->bits; + if (set->cmd2 & CMD2_OBITS) + newmode |= value & set->bits; + } + break; + + case '+': + newmode |= set->bits; + break; + + case '-': + newmode &= ~set->bits; + break; + + case 'X': + if (omode & (S_IFDIR|S_IXUSR|S_IXGRP|S_IXOTH)) + newmode |= set->bits; + break; + + case '\0': + default: +#ifdef SETMODE_DEBUG + (void)printf("getmode:%04o -> %04o\n", omode, newmode); +#endif + return (newmode); + } +} + +#define ADDCMD(a, b, c, d) \ + if (set >= endset) { \ + BITCMD *newset; \ + setlen += SET_LEN_INCR; \ + newset = realloc(saveset, sizeof(BITCMD) * setlen); \ + if (!newset) { \ + if (saveset) \ + free(saveset); \ + saveset = NULL; \ + return (NULL); \ + } \ + set = newset + (set - saveset); \ + saveset = newset; \ + endset = newset + (setlen - 2); \ + } \ + set = addcmd(set, (a), (b), (c), (d)) + +#define STANDARD_BITS (S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO) + +void * +setmode(const char *p) +{ + int perm, who; + char op, *ep; + BITCMD *set, *saveset, *endset; + sigset_t sigset, sigoset; + mode_t mask; + int equalopdone=0, permXbits, setlen; + long perml; + + if (!*p) + return (NULL); + + /* + * Get a copy of the mask for the permissions that are mask relative. + * Flip the bits, we want what's not set. Since it's possible that + * the caller is opening files inside a signal handler, protect them + * as best we can. + */ + sigfillset(&sigset); + (void)_sigprocmask(SIG_BLOCK, &sigset, &sigoset); + (void)umask(mask = umask(0)); + mask = ~mask; + (void)_sigprocmask(SIG_SETMASK, &sigoset, NULL); + + setlen = SET_LEN + 2; + + if ((set = malloc((u_int)(sizeof(BITCMD) * setlen))) == NULL) + return (NULL); + saveset = set; + endset = set + (setlen - 2); + + /* + * If an absolute number, get it and return; disallow non-octal digits + * or illegal bits. + */ + if (isdigit((unsigned char)*p)) { + perml = strtol(p, &ep, 8); + if (*ep || perml < 0 || perml & ~(STANDARD_BITS|S_ISTXT)) { + free(saveset); + return (NULL); + } + perm = (mode_t)perml; + ADDCMD('=', (STANDARD_BITS|S_ISTXT), perm, mask); + set->cmd = 0; + return (saveset); + } + + /* + * Build list of structures to set/clear/copy bits as described by + * each clause of the symbolic mode. + */ + for (;;) { + /* First, find out which bits might be modified. */ + for (who = 0;; ++p) { + switch (*p) { + case 'a': + who |= STANDARD_BITS; + break; + case 'u': + who |= S_ISUID|S_IRWXU; + break; + case 'g': + who |= S_ISGID|S_IRWXG; + break; + case 'o': + who |= S_IRWXO; + break; + default: + goto getop; + } + } + +getop: if ((op = *p++) != '+' && op != '-' && op != '=') { + free(saveset); + return (NULL); + } + if (op == '=') + equalopdone = 0; + + who &= ~S_ISTXT; + for (perm = 0, permXbits = 0;; ++p) { + switch (*p) { + case 'r': + perm |= S_IRUSR|S_IRGRP|S_IROTH; + break; + case 's': + /* If only "other" bits ignore set-id. */ + if (!who || who & ~S_IRWXO) + perm |= S_ISUID|S_ISGID; + break; + case 't': + /* If only "other" bits ignore sticky. */ + if (!who || who & ~S_IRWXO) { + who |= S_ISTXT; + perm |= S_ISTXT; + } + break; + case 'w': + perm |= S_IWUSR|S_IWGRP|S_IWOTH; + break; + case 'X': + permXbits = S_IXUSR|S_IXGRP|S_IXOTH; + break; + case 'x': + perm |= S_IXUSR|S_IXGRP|S_IXOTH; + break; + case 'u': + case 'g': + case 'o': + /* + * When ever we hit 'u', 'g', or 'o', we have + * to flush out any partial mode that we have, + * and then do the copying of the mode bits. + */ + if (perm) { + ADDCMD(op, who, perm, mask); + perm = 0; + } + if (op == '=') + equalopdone = 1; + if (op == '+' && permXbits) { + ADDCMD('X', who, permXbits, mask); + permXbits = 0; + } + ADDCMD(*p, who, op, mask); + break; + + default: + /* + * Add any permissions that we haven't already + * done. + */ + if (perm || (op == '=' && !equalopdone)) { + if (op == '=') + equalopdone = 1; + ADDCMD(op, who, perm, mask); + perm = 0; + } + if (permXbits) { + ADDCMD('X', who, permXbits, mask); + permXbits = 0; + } + goto apply; + } + } + +apply: if (!*p) + break; + if (*p != ',') + goto getop; + ++p; + } + set->cmd = 0; +#ifdef SETMODE_DEBUG + (void)printf("Before compress_mode()\n"); + dumpmode(saveset); +#endif + compress_mode(saveset); +#ifdef SETMODE_DEBUG + (void)printf("After compress_mode()\n"); + dumpmode(saveset); +#endif + return (saveset); +} + +static BITCMD * +addcmd(BITCMD *set, int op, int who, int oparg, u_int mask) +{ + switch (op) { + case '=': + set->cmd = '-'; + set->bits = who ? who : STANDARD_BITS; + set++; + + op = '+'; + /* FALLTHROUGH */ + case '+': + case '-': + case 'X': + set->cmd = op; + set->bits = (who ? who : mask) & oparg; + break; + + case 'u': + case 'g': + case 'o': + set->cmd = op; + if (who) { + set->cmd2 = ((who & S_IRUSR) ? CMD2_UBITS : 0) | + ((who & S_IRGRP) ? CMD2_GBITS : 0) | + ((who & S_IROTH) ? CMD2_OBITS : 0); + set->bits = (mode_t)~0; + } else { + set->cmd2 = CMD2_UBITS | CMD2_GBITS | CMD2_OBITS; + set->bits = mask; + } + + if (oparg == '+') + set->cmd2 |= CMD2_SET; + else if (oparg == '-') + set->cmd2 |= CMD2_CLR; + else if (oparg == '=') + set->cmd2 |= CMD2_SET|CMD2_CLR; + break; + } + return (set + 1); +} + +#ifdef SETMODE_DEBUG +static void +dumpmode(BITCMD *set) +{ + for (; set->cmd; ++set) + (void)printf("cmd: '%c' bits %04o%s%s%s%s%s%s\n", + set->cmd, set->bits, set->cmd2 ? " cmd2:" : "", + set->cmd2 & CMD2_CLR ? " CLR" : "", + set->cmd2 & CMD2_SET ? " SET" : "", + set->cmd2 & CMD2_UBITS ? " UBITS" : "", + set->cmd2 & CMD2_GBITS ? " GBITS" : "", + set->cmd2 & CMD2_OBITS ? " OBITS" : ""); +} +#endif + +/* + * Given an array of bitcmd structures, compress by compacting consecutive + * '+', '-' and 'X' commands into at most 3 commands, one of each. The 'u', + * 'g' and 'o' commands continue to be separate. They could probably be + * compacted, but it's not worth the effort. + */ +static void +compress_mode(BITCMD *set) +{ + BITCMD *nset; + int setbits, clrbits, Xbits, op; + + for (nset = set;;) { + /* Copy over any 'u', 'g' and 'o' commands. */ + while ((op = nset->cmd) != '+' && op != '-' && op != 'X') { + *set++ = *nset++; + if (!op) + return; + } + + for (setbits = clrbits = Xbits = 0;; nset++) { + if ((op = nset->cmd) == '-') { + clrbits |= nset->bits; + setbits &= ~nset->bits; + Xbits &= ~nset->bits; + } else if (op == '+') { + setbits |= nset->bits; + clrbits &= ~nset->bits; + Xbits &= ~nset->bits; + } else if (op == 'X') + Xbits |= nset->bits & ~setbits; + else + break; + } + if (clrbits) { + set->cmd = '-'; + set->cmd2 = 0; + set->bits = clrbits; + set++; + } + if (setbits) { + set->cmd = '+'; + set->cmd2 = 0; + set->bits = setbits; + set++; + } + if (Xbits) { + set->cmd = 'X'; + set->cmd2 = 0; + set->bits = Xbits; + set++; + } + } +} diff --git a/lib/libc/gen/setproctitle.c b/lib/libc/gen/setproctitle.c new file mode 100644 index 0000000..433bba2 --- /dev/null +++ b/lib/libc/gen/setproctitle.c @@ -0,0 +1,176 @@ +/* + * Copyright (c) 1995 Peter Wemm + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, is permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice immediately at the beginning of the file, without modification, + * 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. Absolutely no warranty of function or purpose is made by the author + * Peter Wemm. + */ + +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/setproctitle.c,v 1.18 2003/07/01 09:45:35 alfred Exp $"); + +#include "namespace.h" +#include +#include +#include +#include + +#include +#include +#include + +#include +#include +#include +#include +#include "un-namespace.h" + +#include "libc_private.h" + +/* + * Older FreeBSD 2.0, 2.1 and 2.2 had different ps_strings structures and + * in different locations. + * 1: old_ps_strings at the very top of the stack. + * 2: old_ps_strings at SPARE_USRSPACE below the top of the stack. + * 3: ps_strings at the very top of the stack. + * This attempts to support a kernel built in the #2 and #3 era. + */ + +struct old_ps_strings { + char *old_ps_argvstr; + int old_ps_nargvstr; + char *old_ps_envstr; + int old_ps_nenvstr; +}; +#define OLD_PS_STRINGS ((struct old_ps_strings *) \ + (USRSTACK - SPARE_USRSPACE - sizeof(struct old_ps_strings))) + +#include + +#define SPT_BUFSIZE 2048 /* from other parts of sendmail */ + +void +setproctitle(const char *fmt, ...) +{ + static struct ps_strings *ps_strings; + static char *buf = NULL; + static char *obuf = NULL; + static char **oargv, *kbuf; + static int oargc = -1; + static char *nargv[2] = { NULL, NULL }; + char **nargvp; + int nargc; + int i; + va_list ap; + size_t len; + unsigned long ul_ps_strings; + int oid[4]; + + if (buf == NULL) { + buf = malloc(SPT_BUFSIZE); + if (buf == NULL) + return; + nargv[0] = buf; + } + + if (obuf == NULL ) { + obuf = malloc(SPT_BUFSIZE); + if (obuf == NULL) + return; + *obuf = '\0'; + } + + va_start(ap, fmt); + + if (fmt) { + buf[SPT_BUFSIZE - 1] = '\0'; + + if (fmt[0] == '-') { + /* skip program name prefix */ + fmt++; + len = 0; + } else { + /* print program name heading for grep */ + (void)snprintf(buf, SPT_BUFSIZE, "%s: ", _getprogname()); + len = strlen(buf); + } + + /* print the argument string */ + (void) vsnprintf(buf + len, SPT_BUFSIZE - len, fmt, ap); + + nargvp = nargv; + nargc = 1; + kbuf = buf; + } else if (*obuf != '\0') { + /* Idea from NetBSD - reset the title on fmt == NULL */ + nargvp = oargv; + nargc = oargc; + kbuf = obuf; + } else + /* Nothing to restore */ + return; + + va_end(ap); + + /* Set the title into the kernel cached command line */ + oid[0] = CTL_KERN; + oid[1] = KERN_PROC; + oid[2] = KERN_PROC_ARGS; + oid[3] = getpid(); + sysctl(oid, 4, 0, 0, kbuf, strlen(kbuf) + 1); + + if (ps_strings == NULL) { + len = sizeof(ul_ps_strings); + if (sysctlbyname("kern.ps_strings", &ul_ps_strings, &len, NULL, + 0) == -1) + ul_ps_strings = PS_STRINGS; + ps_strings = (struct ps_strings *)ul_ps_strings; + } + + /* PS_STRINGS points to zeroed memory on a style #2 kernel */ + if (ps_strings->ps_argvstr) { + /* style #3 */ + if (oargc == -1) { + /* Record our original args */ + oargc = ps_strings->ps_nargvstr; + oargv = ps_strings->ps_argvstr; + for (i = len = 0; i < oargc; i++) { + /* + * The program may have scribbled into its + * argv array, e.g., to remove some arguments. + * If that has happened, break out before + * trying to call strlen on a NULL pointer. + */ + if (oargv[i] == NULL) { + oargc = i; + break; + } + snprintf(obuf + len, SPT_BUFSIZE - len, "%s%s", + len ? " " : "", oargv[i]); + if (len) + len++; + len += strlen(oargv[i]); + if (len >= SPT_BUFSIZE) + break; + } + } + ps_strings->ps_nargvstr = nargc; + ps_strings->ps_argvstr = nargvp; + } else { + /* style #2 - we can only restore our first arg :-( */ + if (*obuf == '\0') + strncpy(obuf, OLD_PS_STRINGS->old_ps_argvstr, + SPT_BUFSIZE - 1); + OLD_PS_STRINGS->old_ps_nargvstr = 1; + OLD_PS_STRINGS->old_ps_argvstr = nargvp[0]; + } +} diff --git a/lib/libc/gen/setprogname.c b/lib/libc/gen/setprogname.c new file mode 100644 index 0000000..654bef4 --- /dev/null +++ b/lib/libc/gen/setprogname.c @@ -0,0 +1,19 @@ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/setprogname.c,v 1.8 2002/03/29 22:43:41 markm Exp $"); + +#include +#include + +#include "libc_private.h" + +void +setprogname(const char *progname) +{ + const char *p; + + p = strrchr(progname, '/'); + if (p != NULL) + __progname = p + 1; + else + __progname = progname; +} diff --git a/lib/libc/gen/siginterrupt.c b/lib/libc/gen/siginterrupt.c new file mode 100644 index 0000000..8c719f8 --- /dev/null +++ b/lib/libc/gen/siginterrupt.c @@ -0,0 +1,67 @@ +/* + * Copyright (c) 1989, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)siginterrupt.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/siginterrupt.c,v 1.4 2002/02/01 00:57:29 obrien Exp $"); + +#include "namespace.h" +#include +#include "un-namespace.h" +#include "libc_private.h" + +/* + * Set signal state to prevent restart of system calls + * after an instance of the indicated signal. + */ +int +siginterrupt(sig, flag) + int sig, flag; +{ + extern sigset_t _sigintr; + struct sigaction sa; + int ret; + + if ((ret = _sigaction(sig, (struct sigaction *)0, &sa)) < 0) + return (ret); + if (flag) { + sigaddset(&_sigintr, sig); + sa.sa_flags &= ~SA_RESTART; + } else { + sigdelset(&_sigintr, sig); + sa.sa_flags |= SA_RESTART; + } + return (_sigaction(sig, &sa, (struct sigaction *)0)); +} diff --git a/lib/libc/gen/siglist.c b/lib/libc/gen/siglist.c new file mode 100644 index 0000000..f269026 --- /dev/null +++ b/lib/libc/gen/siglist.c @@ -0,0 +1,112 @@ +/* + * Copyright (c) 1983, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)siglist.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/siglist.c,v 1.4 2002/09/07 08:14:19 jmallett Exp $"); + +#include +#include + +const char *const sys_signame[NSIG] = { + "Signal 0", + "hup", /* SIGHUP */ + "int", /* SIGINT */ + "quit", /* SIGQUIT */ + "ill", /* SIGILL */ + "trap", /* SIGTRAP */ + "abrt", /* SIGABRT */ + "emt", /* SIGEMT */ + "fpe", /* SIGFPE */ + "kill", /* SIGKILL */ + "bus", /* SIGBUS */ + "segv", /* SIGSEGV */ + "sys", /* SIGSYS */ + "pipe", /* SIGPIPE */ + "alrm", /* SIGALRM */ + "term", /* SIGTERM */ + "urg", /* SIGURG */ + "stop", /* SIGSTOP */ + "tstp", /* SIGTSTP */ + "cont", /* SIGCONT */ + "chld", /* SIGCHLD */ + "ttin", /* SIGTTIN */ + "ttou", /* SIGTTOU */ + "io", /* SIGIO */ + "xcpu", /* SIGXCPU */ + "xfsz", /* SIGXFSZ */ + "vtalrm", /* SIGVTALRM */ + "prof", /* SIGPROF */ + "winch", /* SIGWINCH */ + "info", /* SIGINFO */ + "usr1", /* SIGUSR1 */ + "usr2" /* SIGUSR2 */ +}; + +const char *const sys_siglist[NSIG] = { + "Signal 0", + "Hangup", /* SIGHUP */ + "Interrupt", /* SIGINT */ + "Quit", /* SIGQUIT */ + "Illegal instruction", /* SIGILL */ + "Trace/BPT trap", /* SIGTRAP */ + "Abort trap", /* SIGABRT */ + "EMT trap", /* SIGEMT */ + "Floating point exception", /* SIGFPE */ + "Killed", /* SIGKILL */ + "Bus error", /* SIGBUS */ + "Segmentation fault", /* SIGSEGV */ + "Bad system call", /* SIGSYS */ + "Broken pipe", /* SIGPIPE */ + "Alarm clock", /* SIGALRM */ + "Terminated", /* SIGTERM */ + "Urgent I/O condition", /* SIGURG */ + "Suspended (signal)", /* SIGSTOP */ + "Suspended", /* SIGTSTP */ + "Continued", /* SIGCONT */ + "Child exited", /* SIGCHLD */ + "Stopped (tty input)", /* SIGTTIN */ + "Stopped (tty output)", /* SIGTTOU */ + "I/O possible", /* SIGIO */ + "Cputime limit exceeded", /* SIGXCPU */ + "Filesize limit exceeded", /* SIGXFSZ */ + "Virtual timer expired", /* SIGVTALRM */ + "Profiling timer expired", /* SIGPROF */ + "Window size changes", /* SIGWINCH */ + "Information request", /* SIGINFO */ + "User defined signal 1", /* SIGUSR1 */ + "User defined signal 2" /* SIGUSR2 */ +}; +const int sys_nsig = sizeof(sys_siglist) / sizeof(sys_siglist[0]); diff --git a/lib/libc/gen/signal.c b/lib/libc/gen/signal.c new file mode 100644 index 0000000..a958347 --- /dev/null +++ b/lib/libc/gen/signal.c @@ -0,0 +1,65 @@ +/* + * Copyright (c) 1985, 1989, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)signal.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/signal.c,v 1.3 2002/02/01 00:57:29 obrien Exp $"); + +/* + * Almost backwards compatible signal. + */ +#include "namespace.h" +#include +#include "un-namespace.h" +#include "libc_private.h" + +sigset_t _sigintr; /* shared with siginterrupt */ + +sig_t +signal(s, a) + int s; + sig_t a; +{ + struct sigaction sa, osa; + + sa.sa_handler = a; + sigemptyset(&sa.sa_mask); + sa.sa_flags = 0; + if (!sigismember(&_sigintr, s)) + sa.sa_flags |= SA_RESTART; + if (_sigaction(s, &sa, &osa) < 0) + return (SIG_ERR); + return (osa.sa_handler); +} diff --git a/lib/libc/gen/sigsetops.c b/lib/libc/gen/sigsetops.c new file mode 100644 index 0000000..e345f26 --- /dev/null +++ b/lib/libc/gen/sigsetops.c @@ -0,0 +1,106 @@ +/*- + * Copyright (c) 1989, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * @(#)sigsetops.c 8.1 (Berkeley) 6/4/93 + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)sigsetops.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/sigsetops.c,v 1.8 2002/02/01 00:57:29 obrien Exp $"); + +#include +#include + +int +sigaddset(set, signo) + sigset_t *set; + int signo; +{ + + if (signo <= 0 || signo > _SIG_MAXSIG) { + errno = EINVAL; + return (-1); + } + set->__bits[_SIG_WORD(signo)] |= _SIG_BIT(signo); + return (0); +} + +int +sigdelset(set, signo) + sigset_t *set; + int signo; +{ + + if (signo <= 0 || signo > _SIG_MAXSIG) { + errno = EINVAL; + return (-1); + } + set->__bits[_SIG_WORD(signo)] &= ~_SIG_BIT(signo); + return (0); +} + +int +sigemptyset(set) + sigset_t *set; +{ + int i; + + for (i = 0; i < _SIG_WORDS; i++) + set->__bits[i] = 0; + return (0); +} + +int +sigfillset(set) + sigset_t *set; +{ + int i; + + for (i = 0; i < _SIG_WORDS; i++) + set->__bits[i] = ~0U; + return (0); +} + +int +sigismember(set, signo) + const sigset_t *set; + int signo; +{ + + if (signo <= 0 || signo > _SIG_MAXSIG) { + errno = EINVAL; + return (-1); + } + return ((set->__bits[_SIG_WORD(signo)] & _SIG_BIT(signo)) ? 1 : 0); +} diff --git a/lib/libc/gen/sleep.c b/lib/libc/gen/sleep.c new file mode 100644 index 0000000..bd48358 --- /dev/null +++ b/lib/libc/gen/sleep.c @@ -0,0 +1,72 @@ +/* + * Copyright (c) 1989, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)sleep.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/sleep.c,v 1.31 2002/02/01 00:57:29 obrien Exp $"); + +#include "namespace.h" +#include +#include +#include +#include +#include "un-namespace.h" + +unsigned int +__sleep(seconds) + unsigned int seconds; +{ + struct timespec time_to_sleep; + struct timespec time_remaining; + + /* + * Avoid overflow when `seconds' is huge. This assumes that + * the maximum value for a time_t is >= INT_MAX. + */ + if (seconds > INT_MAX) + return (seconds - INT_MAX + __sleep(INT_MAX)); + + time_to_sleep.tv_sec = seconds; + time_to_sleep.tv_nsec = 0; + if (_nanosleep(&time_to_sleep, &time_remaining) != -1) + return (0); + if (errno != EINTR) + return (seconds); /* best guess */ + return (time_remaining.tv_sec + + (time_remaining.tv_nsec != 0)); /* round up */ +} + +__weak_reference(__sleep, sleep); +__weak_reference(__sleep, _sleep); diff --git a/lib/libc/gen/srand48.c b/lib/libc/gen/srand48.c new file mode 100644 index 0000000..fd369a0 --- /dev/null +++ b/lib/libc/gen/srand48.c @@ -0,0 +1,30 @@ +/* + * 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 "rand48.h" + +extern unsigned short _rand48_seed[3]; +extern unsigned short _rand48_mult[3]; +extern unsigned short _rand48_add; + +void +srand48(long seed) +{ + _rand48_seed[0] = RAND48_SEED_0; + _rand48_seed[1] = (unsigned short) seed; + _rand48_seed[2] = (unsigned short) (seed >> 16); + _rand48_mult[0] = RAND48_MULT_0; + _rand48_mult[1] = RAND48_MULT_1; + _rand48_mult[2] = RAND48_MULT_2; + _rand48_add = RAND48_ADD; +} diff --git a/lib/libc/gen/statvfs.c b/lib/libc/gen/statvfs.c new file mode 100644 index 0000000..303950b --- /dev/null +++ b/lib/libc/gen/statvfs.c @@ -0,0 +1,160 @@ +/* + * Copyright 2002 Massachusetts Institute of Technology + * + * Permission to use, copy, modify, and distribute this software and + * its documentation for any purpose and without fee is hereby + * granted, provided that both the above copyright notice and this + * permission notice appear in all copies, that both the above + * copyright notice and this permission notice appear in all + * supporting documentation, and that the name of M.I.T. not be used + * in advertising or publicity pertaining to distribution of the + * software without specific, written prior permission. M.I.T. makes + * no representations about the suitability of this software for any + * purpose. It is provided "as is" without express or implied + * warranty. + * + * THIS SOFTWARE IS PROVIDED BY M.I.T. ``AS IS''. M.I.T. DISCLAIMS + * ALL EXPRESS OR IMPLIED WARRANTIES WITH REGARD TO THIS SOFTWARE, + * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT + * SHALL M.I.T. 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 +__FBSDID("$FreeBSD: src/lib/libc/gen/statvfs.c,v 1.2 2002/09/06 11:23:40 tjr Exp $"); + +#include "namespace.h" +#include +#include +#include + +#include +#include +#include +#include "un-namespace.h" + +static int sfs2svfs(const struct statfs *from, struct statvfs *to); + +int +fstatvfs(int fd, struct statvfs *result) +{ + struct statfs sfs; + int rv; + long pcval; + + rv = _fstatfs(fd, &sfs); + if (rv != 0) + return (rv); + + rv = sfs2svfs(&sfs, result); + if (rv != 0) + return (rv); + + /* + * Whether pathconf's -1 return means error or unlimited does not + * make any difference in this best-effort implementation. + */ + pcval = _fpathconf(fd, _PC_NAME_MAX); + if (pcval == -1) + result->f_namemax = ~0UL; + else + result->f_namemax = (unsigned long)pcval; + return (0); +} + +int +statvfs(const char * __restrict path, struct statvfs * __restrict result) +{ + struct statfs sfs; + int rv; + long pcval; + + rv = statfs(path, &sfs); + if (rv != 0) + return (rv); + + sfs2svfs(&sfs, result); + + /* + * Whether pathconf's -1 return means error or unlimited does not + * make any difference in this best-effort implementation. + */ + pcval = pathconf(path, _PC_NAME_MAX); + if (pcval == -1) + result->f_namemax = ~0UL; + else + result->f_namemax = (unsigned long)pcval; + return (0); +} + +static int +sfs2svfs(const struct statfs *from, struct statvfs *to) +{ + static const struct statvfs zvfs; + + *to = zvfs; + + if (from->f_flags & MNT_RDONLY) + to->f_flag |= ST_RDONLY; + if (from->f_flags & MNT_NOSUID) + to->f_flag |= ST_NOSUID; + + /* XXX should we clamp negative values? */ +#define COPY(field) \ + do { \ + to->field = from->field; \ + if (from->field != to->field) { \ + errno = EOVERFLOW; \ + return (-1); \ + } \ + } while(0) + + COPY(f_bavail); + COPY(f_bfree); + COPY(f_blocks); + COPY(f_ffree); + COPY(f_files); + to->f_bsize = from->f_iosize; + to->f_frsize = from->f_bsize; + to->f_favail = to->f_ffree; + return (0); +} + +#ifdef MAIN +#include +#include +#include + +int +main(int argc, char **argv) +{ + struct statvfs buf; + + if (statvfs(argv[1], &buf) < 0) + err(1, "statvfs"); + +#define SHOW(field) \ + printf(#field ": %ju\n", (uintmax_t)buf.field) + + SHOW(f_bavail); + SHOW(f_bfree); + SHOW(f_blocks); + SHOW(f_favail); + SHOW(f_ffree); + SHOW(f_files); + SHOW(f_bsize); + SHOW(f_frsize); + SHOW(f_namemax); + printf("f_flag: %lx\n", (unsigned long)buf.f_flag); + + return 0; +} + +#endif /* MAIN */ diff --git a/lib/libc/gen/stringlist.c b/lib/libc/gen/stringlist.c new file mode 100644 index 0000000..1d977e4 --- /dev/null +++ b/lib/libc/gen/stringlist.c @@ -0,0 +1,125 @@ +/* + * Copyright (c) 1994 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. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by Christos Zoulas. + * 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. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char *rcsid = "$NetBSD: stringlist.c,v 1.2 1997/01/17 07:26:20 lukem Exp $"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/stringlist.c,v 1.7 2003/01/19 01:16:01 obrien Exp $"); + +#include "namespace.h" +#include +#include +#include +#include +#include +#include "un-namespace.h" + +#define _SL_CHUNKSIZE 20 + +/* + * sl_init(): Initialize a string list + */ +StringList * +sl_init() +{ + StringList *sl; + + sl = malloc(sizeof(StringList)); + if (sl == NULL) + _err(1, "stringlist: %m"); + + sl->sl_cur = 0; + sl->sl_max = _SL_CHUNKSIZE; + sl->sl_str = malloc(sl->sl_max * sizeof(char *)); + if (sl->sl_str == NULL) + _err(1, "stringlist: %m"); + return sl; +} + + +/* + * sl_add(): Add an item to the string list + */ +int +sl_add(sl, name) + StringList *sl; + char *name; +{ + if (sl->sl_cur == sl->sl_max - 1) { + sl->sl_max += _SL_CHUNKSIZE; + sl->sl_str = reallocf(sl->sl_str, sl->sl_max * sizeof(char *)); + if (sl->sl_str == NULL) + return (-1); + } + sl->sl_str[sl->sl_cur++] = name; + return (0); +} + + +/* + * sl_free(): Free a stringlist + */ +void +sl_free(sl, all) + StringList *sl; + int all; +{ + size_t i; + + if (sl == NULL) + return; + if (sl->sl_str) { + if (all) + for (i = 0; i < sl->sl_cur; i++) + free(sl->sl_str[i]); + free(sl->sl_str); + } + free(sl); +} + + +/* + * sl_find(): Find a name in the string list + */ +char * +sl_find(sl, name) + StringList *sl; + char *name; +{ + size_t i; + + for (i = 0; i < sl->sl_cur; i++) + if (strcmp(sl->sl_str[i], name) == 0) + return sl->sl_str[i]; + + return NULL; +} diff --git a/lib/libc/gen/strtofflags.c b/lib/libc/gen/strtofflags.c new file mode 100644 index 0000000..20a5c9f --- /dev/null +++ b/lib/libc/gen/strtofflags.c @@ -0,0 +1,158 @@ +/*- + * Copyright (c) 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)stat_flags.c 8.1 (Berkeley) 5/31/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/strtofflags.c,v 1.22 2002/04/16 11:03:22 joe Exp $"); + +#include +#include + +#include +#include +#include + +static struct { + char *name; + u_long flag; + int invert; +} mapping[] = { + /* shorter names per flag first, all prefixed by "no" */ + { "nosappnd", SF_APPEND, 0 }, + { "nosappend", SF_APPEND, 0 }, + { "noarch", SF_ARCHIVED, 0 }, + { "noarchived", SF_ARCHIVED, 0 }, + { "noschg", SF_IMMUTABLE, 0 }, + { "noschange", SF_IMMUTABLE, 0 }, + { "nosimmutable", SF_IMMUTABLE, 0 }, + { "nosunlnk", SF_NOUNLINK, 0 }, + { "nosunlink", SF_NOUNLINK, 0 }, +#ifdef SF_SNAPSHOT + { "nosnapshot", SF_SNAPSHOT, 0 }, +#endif + { "nouappnd", UF_APPEND, 0 }, + { "nouappend", UF_APPEND, 0 }, + { "nouchg", UF_IMMUTABLE, 0 }, + { "nouchange", UF_IMMUTABLE, 0 }, + { "nouimmutable", UF_IMMUTABLE, 0 }, + { "nodump", UF_NODUMP, 1 }, + { "noopaque", UF_OPAQUE, 0 }, + { "nouunlnk", UF_NOUNLINK, 0 }, + { "nouunlink", UF_NOUNLINK, 0 } +}; +#define longestflaglen 12 +#define nmappings (sizeof(mapping) / sizeof(mapping[0])) + +/* + * fflagstostr -- + * Convert file flags to a comma-separated string. If no flags + * are set, return the empty string. + */ +char * +fflagstostr(flags) + u_long flags; +{ + char *string; + char *sp, *dp; + u_long setflags; + int i; + + if ((string = (char *)malloc(nmappings * (longestflaglen + 1))) == NULL) + return (NULL); + + setflags = flags; + dp = string; + for (i = 0; i < nmappings; i++) { + if (setflags & mapping[i].flag) { + if (dp > string) + *dp++ = ','; + for (sp = mapping[i].invert ? mapping[i].name : + mapping[i].name + 2; *sp; *dp++ = *sp++) ; + setflags &= ~mapping[i].flag; + } + } + *dp = '\0'; + return (string); +} + +/* + * strtofflags -- + * Take string of arguments and return file flags. Return 0 on + * success, 1 on failure. On failure, stringp is set to point + * to the offending token. + */ +int +strtofflags(stringp, setp, clrp) + char **stringp; + u_long *setp, *clrp; +{ + char *string, *p; + int i; + + if (setp) + *setp = 0; + if (clrp) + *clrp = 0; + string = *stringp; + while ((p = strsep(&string, "\t ,")) != NULL) { + *stringp = p; + if (*p == '\0') + continue; + for (i = 0; i < nmappings; i++) { + if (strcmp(p, mapping[i].name + 2) == 0) { + if (mapping[i].invert) { + if (clrp) + *clrp |= mapping[i].flag; + } else { + if (setp) + *setp |= mapping[i].flag; + } + break; + } else if (strcmp(p, mapping[i].name) == 0) { + if (mapping[i].invert) { + if (setp) + *setp |= mapping[i].flag; + } else { + if (clrp) + *clrp |= mapping[i].flag; + } + break; + } + } + if (i == nmappings) + return 1; + } + return 0; +} diff --git a/lib/libc/gen/swapcontext.c b/lib/libc/gen/swapcontext.c new file mode 100644 index 0000000..1725068 --- /dev/null +++ b/lib/libc/gen/swapcontext.c @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2001 Daniel M. Eischen + * 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. Neither the name of the author 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 AUTHOR 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 AUTHOR 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 +__FBSDID("$FreeBSD: src/lib/libc/gen/swapcontext.c,v 1.5 2002/09/20 08:13:21 mini Exp $"); + +#include +#include +#include + +#include +#include + +__weak_reference(__swapcontext, swapcontext); + +int +__swapcontext(ucontext_t *oucp, const ucontext_t *ucp) +{ + int ret; + + if ((oucp == NULL) || (ucp == NULL)) { + errno = EINVAL; + return (-1); + } + oucp->uc_flags &= ~UCF_SWAPPED; + ret = getcontext(oucp); + if ((ret == 0) && !(oucp->uc_flags & UCF_SWAPPED)) { + oucp->uc_flags |= UCF_SWAPPED; + ret = setcontext(ucp); + } + return (ret); +} diff --git a/lib/libc/gen/sysconf.c b/lib/libc/gen/sysconf.c new file mode 100644 index 0000000..309e163 --- /dev/null +++ b/lib/libc/gen/sysconf.c @@ -0,0 +1,582 @@ +/*- + * Copyright (c) 1993 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * Sean Eric Fagan of Cygnus Support. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)sysconf.c 8.2 (Berkeley) 3/20/94"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/sysconf.c,v 1.20 2002/11/17 08:54:29 dougb Exp $"); + +#include +#include +#include +#include +#include + +#include +#include +#include +#include /* we just need the limits */ +#include +#include + +#include "../stdlib/atexit.h" +#include "../stdtime/tzfile.h" + +#define _PATH_ZONEINFO TZDIR /* from tzfile.h */ + +/* + * sysconf -- + * get configurable system variables. + * + * XXX + * POSIX 1003.1 (ISO/IEC 9945-1, 4.8.1.3) states that the variable values + * not change during the lifetime of the calling process. This would seem + * to require that any change to system limits kill all running processes. + * A workaround might be to cache the values when they are first retrieved + * and then simply return the cached value on subsequent calls. This is + * less useful than returning up-to-date values, however. + */ +long +sysconf(name) + int name; +{ + struct rlimit rl; + size_t len; + int mib[2], sverrno, value; + long defaultresult; + const char *path; + + len = sizeof(value); + defaultresult = -1; + + switch (name) { + case _SC_ARG_MAX: + mib[0] = CTL_KERN; + mib[1] = KERN_ARGMAX; + break; + case _SC_CHILD_MAX: + if (getrlimit(RLIMIT_NPROC, &rl) != 0) + return (-1); + if (rl.rlim_cur == RLIM_INFINITY) + return (-1); + if (rl.rlim_cur > LONG_MAX) { + errno = EOVERFLOW; + return (-1); + } + return ((long)rl.rlim_cur); + case _SC_CLK_TCK: + return (CLK_TCK); + case _SC_NGROUPS_MAX: + mib[0] = CTL_KERN; + mib[1] = KERN_NGROUPS; + break; + case _SC_OPEN_MAX: + case _SC_STREAM_MAX: /* assume fds run out before memory does */ + if (getrlimit(RLIMIT_NOFILE, &rl) != 0) + return (-1); + if (rl.rlim_cur == RLIM_INFINITY) + return (-1); + if (rl.rlim_cur > LONG_MAX) { + errno = EOVERFLOW; + return (-1); + } + return ((long)rl.rlim_cur); + case _SC_JOB_CONTROL: + return (_POSIX_JOB_CONTROL); + case _SC_SAVED_IDS: + /* XXX - must be 1 */ + mib[0] = CTL_KERN; + mib[1] = KERN_SAVED_IDS; + goto yesno; + case _SC_VERSION: + mib[0] = CTL_KERN; + mib[1] = KERN_POSIX1; + break; + case _SC_BC_BASE_MAX: + return (BC_BASE_MAX); + case _SC_BC_DIM_MAX: + return (BC_DIM_MAX); + case _SC_BC_SCALE_MAX: + return (BC_SCALE_MAX); + case _SC_BC_STRING_MAX: + return (BC_STRING_MAX); + case _SC_COLL_WEIGHTS_MAX: + return (COLL_WEIGHTS_MAX); + case _SC_EXPR_NEST_MAX: + return (EXPR_NEST_MAX); + case _SC_LINE_MAX: + return (LINE_MAX); + case _SC_RE_DUP_MAX: + return (RE_DUP_MAX); + case _SC_2_VERSION: + /* + * This is something of a lie, but it would be silly at + * this point to try to deduce this from the contents + * of the filesystem. + */ + return (_POSIX2_VERSION); + case _SC_2_C_BIND: + return (_POSIX2_C_BIND); + case _SC_2_C_DEV: + return (_POSIX2_C_DEV); + case _SC_2_CHAR_TERM: + return (_POSIX2_CHAR_TERM); + case _SC_2_FORT_DEV: + return (_POSIX2_FORT_DEV); + case _SC_2_FORT_RUN: + return (_POSIX2_FORT_RUN); + case _SC_2_LOCALEDEF: + return (_POSIX2_LOCALEDEF); + case _SC_2_SW_DEV: + return (_POSIX2_SW_DEV); + case _SC_2_UPE: + return (_POSIX2_UPE); + case _SC_TZNAME_MAX: + path = _PATH_ZONEINFO; +do_NAME_MAX: + sverrno = errno; + errno = 0; + value = pathconf(path, _PC_NAME_MAX); + if (value == -1 && errno != 0) + return (-1); + errno = sverrno; + return (value); + + case _SC_ASYNCHRONOUS_IO: +#if _POSIX_ASYNCHRONOUS_IO == 0 + mib[0] = CTL_P1003_1B; + mib[1] = CTL_P1003_1B_ASYNCHRONOUS_IO; + break; +#else + return (_POSIX_ASYNCHRONOUS_IO); +#endif + case _SC_MAPPED_FILES: + return (_POSIX_MAPPED_FILES); + case _SC_MEMLOCK: + return (_POSIX_MEMLOCK); + case _SC_MEMLOCK_RANGE: + return (_POSIX_MEMLOCK_RANGE); + case _SC_MEMORY_PROTECTION: + return (_POSIX_MEMORY_PROTECTION); + case _SC_MESSAGE_PASSING: +#if _POSIX_MESSAGE_PASSING == 0 + mib[0] = CTL_P1003_1B; + mib[1] = CTL_P1003_1B_MESSAGE_PASSING; + goto yesno; +#else + return (_POSIX_MESSAGE_PASSING); +#endif + case _SC_PRIORITIZED_IO: +#if _POSIX_PRIORITIZED_IO == 0 + mib[0] = CTL_P1003_1B; + mib[1] = CTL_P1003_1B_PRIORITIZED_IO; + goto yesno; +#else + return (_POSIX_PRIORITIZED_IO); +#endif + case _SC_PRIORITY_SCHEDULING: +#if _POSIX_PRIORITY_SCHEDULING == 0 + mib[0] = CTL_P1003_1B; + mib[1] = CTL_P1003_1B_PRIORITY_SCHEDULING; + goto yesno; +#else + return (_POSIX_PRIORITY_SCHEDULING); +#endif + case _SC_REALTIME_SIGNALS: +#if _POSIX_REALTIME_SIGNALS == 0 + mib[0] = CTL_P1003_1B; + mib[1] = CTL_P1003_1B_REALTIME_SIGNALS; + goto yesno; +#else + return (_POSIX_REALTIME_SIGNALS); +#endif + case _SC_SEMAPHORES: +#if _POSIX_SEMAPHORES == 0 + mib[0] = CTL_P1003_1B; + mib[1] = CTL_P1003_1B_SEMAPHORES; + goto yesno; +#else + return (_POSIX_SEMAPHORES); +#endif + case _SC_FSYNC: + return (_POSIX_FSYNC); + + case _SC_SHARED_MEMORY_OBJECTS: + return (_POSIX_SHARED_MEMORY_OBJECTS); + case _SC_SYNCHRONIZED_IO: +#if _POSIX_SYNCHRONIZED_IO == 0 + mib[0] = CTL_P1003_1B; + mib[1] = CTL_P1003_1B_SYNCHRONIZED_IO; + goto yesno; +#else + return (_POSIX_SYNCHRONIZED_IO); +#endif + case _SC_TIMERS: +#if _POSIX_TIMERS == 0 + mib[0] = CTL_P1003_1B; + mib[1] = CTL_P1003_1B_TIMERS; + goto yesno; +#else + return (_POSIX_TIMERS); +#endif + case _SC_AIO_LISTIO_MAX: + mib[0] = CTL_P1003_1B; + mib[1] = CTL_P1003_1B_AIO_LISTIO_MAX; + break; + case _SC_AIO_MAX: + mib[0] = CTL_P1003_1B; + mib[1] = CTL_P1003_1B_AIO_MAX; + break; + case _SC_AIO_PRIO_DELTA_MAX: + mib[0] = CTL_P1003_1B; + mib[1] = CTL_P1003_1B_AIO_PRIO_DELTA_MAX; + break; + case _SC_DELAYTIMER_MAX: + mib[0] = CTL_P1003_1B; + mib[1] = CTL_P1003_1B_DELAYTIMER_MAX; + goto yesno; + case _SC_MQ_OPEN_MAX: + mib[0] = CTL_P1003_1B; + mib[1] = CTL_P1003_1B_MQ_OPEN_MAX; + goto yesno; + case _SC_PAGESIZE: + defaultresult = getpagesize(); + mib[0] = CTL_P1003_1B; + mib[1] = CTL_P1003_1B_PAGESIZE; + goto yesno; + case _SC_RTSIG_MAX: + mib[0] = CTL_P1003_1B; + mib[1] = CTL_P1003_1B_RTSIG_MAX; + goto yesno; + case _SC_SEM_NSEMS_MAX: + mib[0] = CTL_P1003_1B; + mib[1] = CTL_P1003_1B_SEM_NSEMS_MAX; + goto yesno; + case _SC_SEM_VALUE_MAX: + mib[0] = CTL_P1003_1B; + mib[1] = CTL_P1003_1B_SEM_VALUE_MAX; + goto yesno; + case _SC_SIGQUEUE_MAX: + mib[0] = CTL_P1003_1B; + mib[1] = CTL_P1003_1B_SIGQUEUE_MAX; + goto yesno; + case _SC_TIMER_MAX: + mib[0] = CTL_P1003_1B; + mib[1] = CTL_P1003_1B_TIMER_MAX; + +yesno: if (sysctl(mib, 2, &value, &len, NULL, 0) == -1) + return (-1); + if (value == 0) + return (defaultresult); + return (value); + + case _SC_2_PBS: + case _SC_2_PBS_ACCOUNTING: + case _SC_2_PBS_CHECKPOINT: + case _SC_2_PBS_LOCATE: + case _SC_2_PBS_MESSAGE: + case _SC_2_PBS_TRACK: +#if _POSIX2_PBS == 0 +#error "don't know how to determine _SC_2_PBS" + /* + * This probably requires digging through the filesystem + * to see if the appropriate package has been installed. + * Since we don't currently support this option at all, + * it's not worth the effort to write the code now. + * Figuring out which of the sub-options are supported + * would be even more difficult, so it's probably easier + * to always say ``no''. + */ +#else + return (_POSIX2_PBS); +#endif + case _SC_ADVISORY_INFO: +#if _POSIX_ADVISORY_INFO == 0 +#error "_POSIX_ADVISORY_INFO" +#else + return (_POSIX_ADVISORY_INFO); +#endif + case _SC_BARRIERS: +#if _POSIX_BARRIERS == 0 +#error "_POSIX_BARRIERS" +#else + return (_POSIX_BARRIERS); +#endif + case _SC_CLOCK_SELECTION: +#if _POSIX_CLOCK_SELECTION == 0 +#error "_POSIX_CLOCK_SELECTION" +#else + return (_POSIX_CLOCK_SELECTION); +#endif + case _SC_CPUTIME: +#if _POSIX_CPUTIME == 0 +#error "_POSIX_CPUTIME" +#else + return (_POSIX_CPUTIME); +#endif +#ifdef notdef + case _SC_FILE_LOCKING: + /* + * XXX - The standard doesn't tell us how to define + * _POSIX_FILE_LOCKING, so we can't answer this one. + */ +#endif +#if _POSIX_THREAD_SAFE_FUNCTIONS > -1 + case _SC_GETGR_R_SIZE_MAX: + case _SC_GETPW_R_SIZE_MAX: +#error "somebody needs to implement this" +#endif + case _SC_HOST_NAME_MAX: + return (MAXHOSTNAMELEN - 1); /* does not include \0 */ + case _SC_LOGIN_NAME_MAX: + return (MAXLOGNAME); + case _SC_MONOTONIC_CLOCK: +#if _POSIX_MONOTONIC_CLOCK == 0 +#error "_POSIX_MONOTONIC_CLOCK" +#else + return (_POSIX_MONOTONIC_CLOCK); +#endif +#if _POSIX_MESSAGE_PASSING > -1 + case _SC_MQ_PRIO_MAX: + return (MQ_PRIO_MAX); +#endif + case _SC_READER_WRITER_LOCKS: + return (_POSIX_READER_WRITER_LOCKS); + case _SC_REGEXP: + return (_POSIX_REGEXP); + case _SC_SHELL: + return (_POSIX_SHELL); + case _SC_SPAWN: + return (_POSIX_SPAWN); + case _SC_SPIN_LOCKS: + return (_POSIX_SPIN_LOCKS); + case _SC_SPORADIC_SERVER: +#if _POSIX_SPORADIC_SERVER == 0 +#error "_POSIX_SPORADIC_SERVER" +#else + return (_POSIX_SPORADIC_SERVER); +#endif + case _SC_THREAD_ATTR_STACKADDR: + return (_POSIX_THREAD_ATTR_STACKADDR); + case _SC_THREAD_ATTR_STACKSIZE: + return (_POSIX_THREAD_ATTR_STACKSIZE); + case _SC_THREAD_CPUTIME: + return (_POSIX_THREAD_CPUTIME); + case _SC_THREAD_DESTRUCTOR_ITERATIONS: + return (PTHREAD_DESTRUCTOR_ITERATIONS); + case _SC_THREAD_KEYS_MAX: + return (PTHREAD_KEYS_MAX); + case _SC_THREAD_PRIO_INHERIT: + return (_POSIX_THREAD_PRIO_INHERIT); + case _SC_THREAD_PRIO_PROTECT: + return (_POSIX_THREAD_PRIO_PROTECT); + case _SC_THREAD_PRIORITY_SCHEDULING: + return (_POSIX_THREAD_PRIORITY_SCHEDULING); + case _SC_THREAD_PROCESS_SHARED: + return (_POSIX_THREAD_PROCESS_SHARED); + case _SC_THREAD_SAFE_FUNCTIONS: + return (_POSIX_THREAD_SAFE_FUNCTIONS); + case _SC_THREAD_STACK_MIN: + return (PTHREAD_STACK_MIN); + case _SC_THREAD_THREADS_MAX: + return (PTHREAD_THREADS_MAX); /* XXX wrong type! */ + case _SC_TIMEOUTS: + return (_POSIX_TIMEOUTS); + case _SC_THREADS: + return (_POSIX_THREADS); + case _SC_TRACE: +#if _POSIX_TRACE == 0 +#error "_POSIX_TRACE" + /* While you're implementing this, also do the ones below. */ +#else + return (_POSIX_TRACE); +#endif +#if _POSIX_TRACE > -1 + case _SC_TRACE_EVENT_FILTER: + return (_POSIX_TRACE_EVENT_FILTER); + case _SC_TRACE_INHERIT: + return (_POSIX_TRACE_INHERIT); + case _SC_TRACE_LOG: + return (_POSIX_TRACE_LOG); +#endif + case _SC_TTY_NAME_MAX: + path = _PATH_DEV; + goto do_NAME_MAX; + case _SC_TYPED_MEMORY_OBJECTS: +#if _POSIX_TYPED_MEMORY_OBJECTS == 0 +#error "_POSIX_TYPED_MEMORY_OBJECTS" +#else + return (_POSIX_TYPED_MEMORY_OBJECTS); +#endif + case _SC_V6_ILP32_OFF32: +#if _V6_ILP32_OFF32 == 0 + if (sizeof(int) * CHAR_BIT == 32 && + sizeof(int) == sizeof(long) && + sizeof(long) == sizeof(void *) && + sizeof(void *) == sizeof(off_t)) + return 1; + else + return -1; +#else + return (_V6_ILP32_OFF32); +#endif + case _SC_V6_ILP32_OFFBIG: +#if _V6_ILP32_OFFBIG == 0 + if (sizeof(int) * CHAR_BIT == 32 && + sizeof(int) == sizeof(long) && + sizeof(long) == sizeof(void *) && + sizeof(off_t) * CHAR_BIT >= 64) + return 1; + else + return -1; +#else + return (_V6_ILP32_OFFBIG); +#endif + case _SC_V6_LP64_OFF64: +#if _V6_LP64_OFF64 == 0 + if (sizeof(int) * CHAR_BIT == 32 && + sizeof(long) * CHAR_BIT == 64 && + sizeof(long) == sizeof(void *) && + sizeof(void *) == sizeof(off_t)) + return 1; + else + return -1; +#else + return (_V6_LP64_OFF64); +#endif + case _SC_V6_LPBIG_OFFBIG: +#if _V6_LPBIG_OFFBIG == 0 + if (sizeof(int) * CHAR_BIT >= 32 && + sizeof(long) * CHAR_BIT >= 64 && + sizeof(void *) * CHAR_BIT >= 64 && + sizeof(off_t) * CHAR_BIT >= 64) + return 1; + else + return -1; +#else + return (_V6_LPBIG_OFFBIG); +#endif + case _SC_ATEXIT_MAX: + return (ATEXIT_SIZE); + case _SC_IOV_MAX: + mib[0] = CTL_KERN; + mib[1] = KERN_IOV_MAX; + break; + case _SC_XOPEN_CRYPT: + return (_XOPEN_CRYPT); + case _SC_XOPEN_ENH_I18N: + return (_XOPEN_ENH_I18N); + case _SC_XOPEN_LEGACY: + return (_XOPEN_LEGACY); + case _SC_XOPEN_REALTIME: +#if _XOPEN_REALTIME == 0 + sverrno = errno; + value = sysconf(_SC_ASYNCHRONOUS_IO) > 0 && + sysconf(_SC_MEMLOCK) > 0 && + sysconf(_SC_MEMLOCK_RANGE) > 0 && + sysconf(_SC_MESSAGE_PASSING) > 0 && + sysconf(_SC_PRIORITY_SCHEDULING) > 0 && + sysconf(_SC_REALTIME_SIGNALS) > 0 && + sysconf(_SC_SEMAPHORES) > 0 && + sysconf(_SC_SHARED_MEMORY_OBJECTS) > 0 && + sysconf(_SC_SYNCHRONIZED_IO) > 0 && + sysconf(_SC_TIMERS) > 0; + errno = sverrno; + if (value) + return (200112L); + else + return (-1); +#else + return (_XOPEN_REALTIME); +#endif + case _SC_XOPEN_REALTIME_THREADS: +#if _XOPEN_REALTIME_THREADS == 0 +#error "_XOPEN_REALTIME_THREADS" +#else + return (_XOPEN_REALTIME_THREADS); +#endif + case _SC_XOPEN_SHM: + sverrno = errno; + if (sysctlbyname("kern.ipc.shmmin", &value, &len, NULL, + 0) == -1) { + errno = sverrno; + return (-1); + } + errno = sverrno; + return (1); + case _SC_XOPEN_STREAMS: + return (_XOPEN_STREAMS); + case _SC_XOPEN_UNIX: + return (_XOPEN_UNIX); +#ifdef _XOPEN_VERSION + case _SC_XOPEN_VERSION: + return (_XOPEN_VERSION); +#endif +#ifdef _XOPEN_XCU_VERSION + case _SC_XOPEN_XCU_VERSION: + return (_XOPEN_XCU_VERSION); +#endif + case _SC_SYMLOOP_MAX: + return (MAXSYMLINKS); + case _SC_RAW_SOCKETS: + return (_POSIX_RAW_SOCKETS); + case _SC_IPV6: +#if _POSIX_IPV6 == 0 + sverrno = errno; + value = socket(PF_INET6, SOCK_DGRAM, 0); + errno = sverrno; + if (value >= 0) { + close(value); + return (200112L); + } else + return (0); +#else + return (_POSIX_IPV6); +#endif + + case _SC_NPROCESSORS_CONF: + case _SC_NPROCESSORS_ONLN: + mib[0] = CTL_HW; + mib[1] = HW_NCPU; + break; + + default: + errno = EINVAL; + return (-1); + } + return (sysctl(mib, 2, &value, &len, NULL, 0) == -1 ? -1 : value); +} diff --git a/lib/libc/gen/sysctl.c b/lib/libc/gen/sysctl.c new file mode 100644 index 0000000..b6c89a0 --- /dev/null +++ b/lib/libc/gen/sysctl.c @@ -0,0 +1,187 @@ +/*- + * Copyright (c) 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)sysctl.c 8.2 (Berkeley) 1/4/94"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/sysctl.c,v 1.5 2003/02/16 17:29:09 nectar Exp $"); + +#include +#include + +#include +#include +#include +#include +#include +#include + +extern int __sysctl(int *name, u_int namelen, void *oldp, size_t *oldlenp, + void *newp, size_t newlen); + +int +sysctl(name, namelen, oldp, oldlenp, newp, newlen) + int *name; + u_int namelen; + void *oldp, *newp; + size_t *oldlenp, newlen; +{ + if (name[0] != CTL_USER) + return (__sysctl(name, namelen, oldp, oldlenp, newp, newlen)); + + if (newp != NULL) { + errno = EPERM; + return (-1); + } + if (namelen != 2) { + errno = EINVAL; + return (-1); + } + + switch (name[1]) { + case USER_CS_PATH: + if (oldp && *oldlenp < sizeof(_PATH_STDPATH)) { + errno = ENOMEM; + return -1; + } + *oldlenp = sizeof(_PATH_STDPATH); + if (oldp != NULL) + memmove(oldp, _PATH_STDPATH, sizeof(_PATH_STDPATH)); + return (0); + } + + if (oldp && *oldlenp < sizeof(int)) { + errno = ENOMEM; + return (-1); + } + *oldlenp = sizeof(int); + if (oldp == NULL) + return (0); + + switch (name[1]) { + case USER_BC_BASE_MAX: + *(int *)oldp = BC_BASE_MAX; + return (0); + case USER_BC_DIM_MAX: + *(int *)oldp = BC_DIM_MAX; + return (0); + case USER_BC_SCALE_MAX: + *(int *)oldp = BC_SCALE_MAX; + return (0); + case USER_BC_STRING_MAX: + *(int *)oldp = BC_STRING_MAX; + return (0); + case USER_COLL_WEIGHTS_MAX: + *(int *)oldp = COLL_WEIGHTS_MAX; + return (0); + case USER_EXPR_NEST_MAX: + *(int *)oldp = EXPR_NEST_MAX; + return (0); + case USER_LINE_MAX: + *(int *)oldp = LINE_MAX; + return (0); + case USER_RE_DUP_MAX: + *(int *)oldp = RE_DUP_MAX; + return (0); + case USER_POSIX2_VERSION: + *(int *)oldp = _POSIX2_VERSION; + return (0); + case USER_POSIX2_C_BIND: +#ifdef POSIX2_C_BIND + *(int *)oldp = 1; +#else + *(int *)oldp = 0; +#endif + return (0); + case USER_POSIX2_C_DEV: +#ifdef POSIX2_C_DEV + *(int *)oldp = 1; +#else + *(int *)oldp = 0; +#endif + return (0); + case USER_POSIX2_CHAR_TERM: +#ifdef POSIX2_CHAR_TERM + *(int *)oldp = 1; +#else + *(int *)oldp = 0; +#endif + return (0); + case USER_POSIX2_FORT_DEV: +#ifdef POSIX2_FORT_DEV + *(int *)oldp = 1; +#else + *(int *)oldp = 0; +#endif + return (0); + case USER_POSIX2_FORT_RUN: +#ifdef POSIX2_FORT_RUN + *(int *)oldp = 1; +#else + *(int *)oldp = 0; +#endif + return (0); + case USER_POSIX2_LOCALEDEF: +#ifdef POSIX2_LOCALEDEF + *(int *)oldp = 1; +#else + *(int *)oldp = 0; +#endif + return (0); + case USER_POSIX2_SW_DEV: +#ifdef POSIX2_SW_DEV + *(int *)oldp = 1; +#else + *(int *)oldp = 0; +#endif + return (0); + case USER_POSIX2_UPE: +#ifdef POSIX2_UPE + *(int *)oldp = 1; +#else + *(int *)oldp = 0; +#endif + return (0); + case USER_STREAM_MAX: + *(int *)oldp = FOPEN_MAX; + return (0); + case USER_TZNAME_MAX: + *(int *)oldp = NAME_MAX; + return (0); + default: + errno = EINVAL; + return (-1); + } + /* NOTREACHED */ +} diff --git a/lib/libc/gen/sysctlbyname.c b/lib/libc/gen/sysctlbyname.c new file mode 100644 index 0000000..e949a5c --- /dev/null +++ b/lib/libc/gen/sysctlbyname.c @@ -0,0 +1,39 @@ +/* + * ---------------------------------------------------------------------------- + * "THE BEER-WARE LICENSE" (Revision 42): + * wrote this file. As long as you retain this notice you + * can do whatever you want with this stuff. If we meet some day, and you think + * this stuff is worth it, you can buy me a beer in return. Poul-Henning Kamp + * ---------------------------------------------------------------------------- + * + */ + +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/sysctlbyname.c,v 1.5 2002/02/01 00:57:29 obrien Exp $"); + +#include +#include +#include + +int +sysctlbyname(const char *name, void *oldp, size_t *oldlenp, void *newp, + size_t newlen) +{ + int name2oid_oid[2]; + int real_oid[CTL_MAXNAME+2]; + int error; + size_t oidlen; + + name2oid_oid[0] = 0; /* This is magic & undocumented! */ + name2oid_oid[1] = 3; + + oidlen = sizeof(real_oid); + error = sysctl(name2oid_oid, 2, real_oid, &oidlen, (void *)name, + strlen(name)); + if (error < 0) + return error; + oidlen /= sizeof (int); + error = sysctl(real_oid, oidlen, oldp, oldlenp, newp, newlen); + return (error); +} + diff --git a/lib/libc/gen/sysctlnametomib.c b/lib/libc/gen/sysctlnametomib.c new file mode 100644 index 0000000..1a932ec --- /dev/null +++ b/lib/libc/gen/sysctlnametomib.c @@ -0,0 +1,55 @@ +/* + * Copyright 2001 The FreeBSD Project. 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 FREEBSD PROJECT ``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 FREEBSD PROJECT 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 +__FBSDID("$FreeBSD: src/lib/libc/gen/sysctlnametomib.c,v 1.4 2003/01/04 00:11:11 tjr Exp $"); + +#include +#include +#include + +/* + * This function uses a presently undocumented interface to the kernel + * to walk the tree and get the type so it can print the value. + * This interface is under work and consideration, and should probably + * be killed with a big axe by the first person who can find the time. + * (be aware though, that the proper interface isn't as obvious as it + * may seem, there are various conflicting requirements. + */ +int +sysctlnametomib(const char *name, int *mibp, size_t *sizep) +{ + int oid[2]; + int error; + + oid[0] = 0; + oid[1] = 3; + + *sizep *= sizeof (int); + error = sysctl(oid, 2, mibp, sizep, (void *)name, strlen(name)); + *sizep /= sizeof (int); + return (error); +} diff --git a/lib/libc/gen/syslog.c b/lib/libc/gen/syslog.c new file mode 100644 index 0000000..af907bb --- /dev/null +++ b/lib/libc/gen/syslog.c @@ -0,0 +1,439 @@ +/* + * Copyright (c) 1983, 1988, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)syslog.c 8.5 (Berkeley) 4/29/95"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/syslog.c,v 1.35.2.2 2006/09/01 12:33:22 phk Exp $"); + +#include "namespace.h" +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include "un-namespace.h" + +#include "libc_private.h" + +static int LogFile = -1; /* fd for log */ +static int status; /* connection status */ +static int opened; /* have done openlog() */ +static int LogStat = 0; /* status bits, set by openlog() */ +static const char *LogTag = NULL; /* string to tag the entry with */ +static int LogFacility = LOG_USER; /* default facility code */ +static int LogMask = 0xff; /* mask of priorities to be logged */ +static pthread_mutex_t syslog_mutex = PTHREAD_MUTEX_INITIALIZER; + +#define THREAD_LOCK() \ + do { \ + if (__isthreaded) _pthread_mutex_lock(&syslog_mutex); \ + } while(0) +#define THREAD_UNLOCK() \ + do { \ + if (__isthreaded) _pthread_mutex_unlock(&syslog_mutex); \ + } while(0) + +static void disconnectlog(void); /* disconnect from syslogd */ +static void connectlog(void); /* (re)connect to syslogd */ +static void openlog_unlocked(const char *, int, int); + +enum { + NOCONN = 0, + CONNDEF, + CONNPRIV, +}; + +/* + * Format of the magic cookie passed through the stdio hook + */ +struct bufcookie { + char *base; /* start of buffer */ + int left; +}; + +/* + * stdio write hook for writing to a static string buffer + * XXX: Maybe one day, dynamically allocate it so that the line length + * is `unlimited'. + */ +static int +writehook(void *cookie, const char *buf, int len) +{ + struct bufcookie *h; /* private `handle' */ + + h = (struct bufcookie *)cookie; + if (len > h->left) { + /* clip in case of wraparound */ + len = h->left; + } + if (len > 0) { + (void)memcpy(h->base, buf, len); /* `write' it. */ + h->base += len; + h->left -= len; + } + return len; +} + +/* + * syslog, vsyslog -- + * print message on log file; output is intended for syslogd(8). + */ +void +syslog(int pri, const char *fmt, ...) +{ + va_list ap; + + va_start(ap, fmt); + vsyslog(pri, fmt, ap); + va_end(ap); +} + +void +vsyslog(int pri, const char *fmt, va_list ap) +{ + int cnt; + char ch, *p; + time_t now; + int fd, saved_errno; + char *stdp, tbuf[2048], fmt_cpy[1024], timbuf[26], errstr[64]; + FILE *fp, *fmt_fp; + struct bufcookie tbuf_cookie; + struct bufcookie fmt_cookie; + +#define INTERNALLOG LOG_ERR|LOG_CONS|LOG_PERROR|LOG_PID + /* Check for invalid bits. */ + if (pri & ~(LOG_PRIMASK|LOG_FACMASK)) { + syslog(INTERNALLOG, + "syslog: unknown facility/priority: %x", pri); + pri &= LOG_PRIMASK|LOG_FACMASK; + } + + saved_errno = errno; + + THREAD_LOCK(); + + /* Check priority against setlogmask values. */ + if (!(LOG_MASK(LOG_PRI(pri)) & LogMask)) { + THREAD_UNLOCK(); + return; + } + + /* Set default facility if none specified. */ + if ((pri & LOG_FACMASK) == 0) + pri |= LogFacility; + + /* Create the primary stdio hook */ + tbuf_cookie.base = tbuf; + tbuf_cookie.left = sizeof(tbuf); + fp = fwopen(&tbuf_cookie, writehook); + if (fp == NULL) { + THREAD_UNLOCK(); + return; + } + + /* Build the message. */ + (void)time(&now); + (void)fprintf(fp, "<%d>", pri); + (void)fprintf(fp, "%.15s ", ctime_r(&now, timbuf) + 4); + if (LogStat & LOG_PERROR) { + /* Transfer to string buffer */ + (void)fflush(fp); + stdp = tbuf + (sizeof(tbuf) - tbuf_cookie.left); + } + if (LogTag == NULL) + LogTag = _getprogname(); + if (LogTag != NULL) + (void)fprintf(fp, "%s", LogTag); + if (LogStat & LOG_PID) + (void)fprintf(fp, "[%d]", getpid()); + if (LogTag != NULL) { + (void)fprintf(fp, ": "); + } + + /* Check to see if we can skip expanding the %m */ + if (strstr(fmt, "%m")) { + + /* Create the second stdio hook */ + fmt_cookie.base = fmt_cpy; + fmt_cookie.left = sizeof(fmt_cpy) - 1; + fmt_fp = fwopen(&fmt_cookie, writehook); + if (fmt_fp == NULL) { + fclose(fp); + THREAD_UNLOCK(); + return; + } + + /* + * Substitute error message for %m. Be careful not to + * molest an escaped percent "%%m". We want to pass it + * on untouched as the format is later parsed by vfprintf. + */ + for ( ; (ch = *fmt); ++fmt) { + if (ch == '%' && fmt[1] == 'm') { + ++fmt; + strerror_r(saved_errno, errstr, sizeof(errstr)); + fputs(errstr, fmt_fp); + } else if (ch == '%' && fmt[1] == '%') { + ++fmt; + fputc(ch, fmt_fp); + fputc(ch, fmt_fp); + } else { + fputc(ch, fmt_fp); + } + } + + /* Null terminate if room */ + fputc(0, fmt_fp); + fclose(fmt_fp); + + /* Guarantee null termination */ + fmt_cpy[sizeof(fmt_cpy) - 1] = '\0'; + + fmt = fmt_cpy; + } + + (void)vfprintf(fp, fmt, ap); + (void)fclose(fp); + + cnt = sizeof(tbuf) - tbuf_cookie.left; + + /* Remove a trailing newline */ + if (tbuf[cnt - 1] == '\n') + cnt--; + + /* Output to stderr if requested. */ + if (LogStat & LOG_PERROR) { + struct iovec iov[2]; + struct iovec *v = iov; + + v->iov_base = stdp; + v->iov_len = cnt - (stdp - tbuf); + ++v; + v->iov_base = "\n"; + v->iov_len = 1; + (void)_writev(STDERR_FILENO, iov, 2); + } + + /* Get connected, output the message to the local logger. */ + if (!opened) + openlog_unlocked(LogTag, LogStat | LOG_NDELAY, 0); + connectlog(); + + /* + * If the send() failed, there are two likely scenarios: + * 1) syslogd was restarted + * 2) /var/run/log is out of socket buffer space, which + * in most cases means local DoS. + * We attempt to reconnect to /var/run/log to take care of + * case #1 and keep send()ing data to cover case #2 + * to give syslogd a chance to empty its socket buffer. + * + * If we are working with a priveleged socket, then take + * only one attempt, because we don't want to freeze a + * critical application like su(1) or sshd(8). + * + */ + + if (send(LogFile, tbuf, cnt, 0) < 0) { + if (errno != ENOBUFS) { + disconnectlog(); + connectlog(); + } + do { + _usleep(1); + if (send(LogFile, tbuf, cnt, 0) >= 0) { + THREAD_UNLOCK(); + return; + } + if (status == CONNPRIV) + break; + } while (errno == ENOBUFS); + } else { + THREAD_UNLOCK(); + return; + } + + /* + * Output the message to the console; try not to block + * as a blocking console should not stop other processes. + * Make sure the error reported is the one from the syslogd failure. + */ + if (LogStat & LOG_CONS && + (fd = _open(_PATH_CONSOLE, O_WRONLY|O_NONBLOCK, 0)) >= 0) { + struct iovec iov[2]; + struct iovec *v = iov; + + p = strchr(tbuf, '>') + 1; + v->iov_base = p; + v->iov_len = cnt - (p - tbuf); + ++v; + v->iov_base = "\r\n"; + v->iov_len = 2; + (void)_writev(fd, iov, 2); + (void)_close(fd); + } + + THREAD_UNLOCK(); +} + +/* Should be called with mutex acquired */ +static void +disconnectlog(void) +{ + /* + * If the user closed the FD and opened another in the same slot, + * that's their problem. They should close it before calling on + * system services. + */ + if (LogFile != -1) { + _close(LogFile); + LogFile = -1; + } + status = NOCONN; /* retry connect */ +} + +/* Should be called with mutex acquired */ +static void +connectlog(void) +{ + struct sockaddr_un SyslogAddr; /* AF_UNIX address of local logger */ + + if (LogFile == -1) { + if ((LogFile = _socket(AF_UNIX, SOCK_DGRAM, 0)) == -1) + return; + (void)_fcntl(LogFile, F_SETFD, 1); + } + if (LogFile != -1 && status == NOCONN) { + SyslogAddr.sun_len = sizeof(SyslogAddr); + SyslogAddr.sun_family = AF_UNIX; + + /* + * First try priveleged socket. If no success, + * then try default socket. + */ + (void)strncpy(SyslogAddr.sun_path, _PATH_LOG_PRIV, + sizeof SyslogAddr.sun_path); + if (_connect(LogFile, (struct sockaddr *)&SyslogAddr, + sizeof(SyslogAddr)) != -1) + status = CONNPRIV; + + if (status == NOCONN) { + (void)strncpy(SyslogAddr.sun_path, _PATH_LOG, + sizeof SyslogAddr.sun_path); + if (_connect(LogFile, (struct sockaddr *)&SyslogAddr, + sizeof(SyslogAddr)) != -1) + status = CONNDEF; + } + + if (status == NOCONN) { + /* + * Try the old "/dev/log" path, for backward + * compatibility. + */ + (void)strncpy(SyslogAddr.sun_path, _PATH_OLDLOG, + sizeof SyslogAddr.sun_path); + if (_connect(LogFile, (struct sockaddr *)&SyslogAddr, + sizeof(SyslogAddr)) != -1) + status = CONNDEF; + } + + if (status == NOCONN) { + (void)_close(LogFile); + LogFile = -1; + } + } +} + +static void +openlog_unlocked(const char *ident, int logstat, int logfac) +{ + if (ident != NULL) + LogTag = ident; + LogStat = logstat; + if (logfac != 0 && (logfac &~ LOG_FACMASK) == 0) + LogFacility = logfac; + + if (LogStat & LOG_NDELAY) /* open immediately */ + connectlog(); + + opened = 1; /* ident and facility has been set */ +} + +void +openlog(const char *ident, int logstat, int logfac) +{ + THREAD_LOCK(); + openlog_unlocked(ident, logstat, logfac); + THREAD_UNLOCK(); +} + + +void +closelog(void) +{ + THREAD_LOCK(); + (void)_close(LogFile); + LogFile = -1; + LogTag = NULL; + status = NOCONN; + THREAD_UNLOCK(); +} + +/* setlogmask -- set the log mask level */ +int +setlogmask(int pmask) +{ + int omask; + + THREAD_LOCK(); + omask = LogMask; + if (pmask != 0) + LogMask = pmask; + THREAD_UNLOCK(); + return (omask); +} diff --git a/lib/libc/gen/telldir.c b/lib/libc/gen/telldir.c new file mode 100644 index 0000000..f321910 --- /dev/null +++ b/lib/libc/gen/telldir.c @@ -0,0 +1,133 @@ +/* + * Copyright (c) 1983, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)telldir.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/telldir.c,v 1.8 2002/02/01 00:57:29 obrien Exp $"); + +#include "namespace.h" +#include +#include +#include +#include +#include +#include +#include "un-namespace.h" + +#include "libc_private.h" +#include "telldir.h" + +/* + * The option SINGLEUSE may be defined to say that a telldir + * cookie may be used only once before it is freed. This option + * is used to avoid having memory usage grow without bound. + */ +#define SINGLEUSE + +/* + * return a pointer into a directory + */ +long +telldir(dirp) + DIR *dirp; +{ + struct ddloc *lp; + + if ((lp = (struct ddloc *)malloc(sizeof(struct ddloc))) == NULL) + return (-1); + if (__isthreaded) + _pthread_mutex_lock((pthread_mutex_t *)&dirp->dd_lock); + lp->loc_index = dirp->dd_td->td_loccnt++; + lp->loc_seek = dirp->dd_seek; + lp->loc_loc = dirp->dd_loc; + LIST_INSERT_HEAD(&dirp->dd_td->td_locq, lp, loc_lqe); + if (__isthreaded) + _pthread_mutex_unlock((pthread_mutex_t *)&dirp->dd_lock); + return (lp->loc_index); +} + +/* + * seek to an entry in a directory. + * Only values returned by "telldir" should be passed to seekdir. + */ +void +_seekdir(dirp, loc) + DIR *dirp; + long loc; +{ + struct ddloc *lp; + struct dirent *dp; + + LIST_FOREACH(lp, &dirp->dd_td->td_locq, loc_lqe) { + if (lp->loc_index == loc) + break; + } + if (lp == NULL) + return; + if (lp->loc_loc == dirp->dd_loc && lp->loc_seek == dirp->dd_seek) + goto found; + (void) lseek(dirp->dd_fd, (off_t)lp->loc_seek, SEEK_SET); + dirp->dd_seek = lp->loc_seek; + dirp->dd_loc = 0; + while (dirp->dd_loc < lp->loc_loc) { + dp = _readdir_unlocked(dirp); + if (dp == NULL) + break; + } +found: +#ifdef SINGLEUSE + LIST_REMOVE(lp, loc_lqe); + free((caddr_t)lp); +#endif +} + +/* + * Reclaim memory for telldir cookies which weren't used. + */ +void +_reclaim_telldir(dirp) + DIR *dirp; +{ + struct ddloc *lp; + struct ddloc *templp; + + lp = LIST_FIRST(&dirp->dd_td->td_locq); + while (lp != NULL) { + templp = lp; + lp = LIST_NEXT(lp, loc_lqe); + free(templp); + } + LIST_INIT(&dirp->dd_td->td_locq); +} diff --git a/lib/libc/gen/telldir.h b/lib/libc/gen/telldir.h new file mode 100644 index 0000000..82cf9c1 --- /dev/null +++ b/lib/libc/gen/telldir.h @@ -0,0 +1,66 @@ +/* + * Copyright (c) 1983, 1993 + * The Regents of the University of California. All rights reserved. + * + * Copyright (c) 2000 + * Daniel Eischen. 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. + * + * $FreeBSD: src/lib/libc/gen/telldir.h,v 1.2 2001/01/24 12:59:24 deischen Exp $ + */ + +#ifndef _TELLDIR_H_ +#define _TELLDIR_H_ + +#include + +/* + * One of these structures is malloced to describe the current directory + * position each time telldir is called. It records the current magic + * cookie returned by getdirentries and the offset within the buffer + * associated with that return value. + */ +struct ddloc { + LIST_ENTRY(ddloc) loc_lqe; /* entry in list */ + long loc_index; /* key associated with structure */ + long loc_seek; /* magic cookie returned by getdirentries */ + long loc_loc; /* offset of entry in buffer */ +}; + +/* + * One of these structures is malloced for each DIR to record telldir + * positions. + */ +struct _telldir { + LIST_HEAD(, ddloc) td_locq; /* list of locations */ + long td_loccnt; /* index of entry for sequential readdir's */ +}; + +struct dirent *_readdir_unlocked(DIR *); +void _reclaim_telldir(DIR *); +void _seekdir(DIR *, long); + +#endif diff --git a/lib/libc/gen/termios.c b/lib/libc/gen/termios.c new file mode 100644 index 0000000..65f8141 --- /dev/null +++ b/lib/libc/gen/termios.c @@ -0,0 +1,245 @@ +/*- + * Copyright (c) 1989, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)termios.c 8.2 (Berkeley) 2/21/94"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/termios.c,v 1.13 2002/05/28 16:59:39 alfred Exp $"); + +#include "namespace.h" +#include +#include +#include +#include + +#include +#include +#include +#include "un-namespace.h" + +int +tcgetattr(fd, t) + int fd; + struct termios *t; +{ + + return (_ioctl(fd, TIOCGETA, t)); +} + +int +tcsetattr(fd, opt, t) + int fd, opt; + const struct termios *t; +{ + struct termios localterm; + + if (opt & TCSASOFT) { + localterm = *t; + localterm.c_cflag |= CIGNORE; + t = &localterm; + } + switch (opt & ~TCSASOFT) { + case TCSANOW: + return (_ioctl(fd, TIOCSETA, t)); + case TCSADRAIN: + return (_ioctl(fd, TIOCSETAW, t)); + case TCSAFLUSH: + return (_ioctl(fd, TIOCSETAF, t)); + default: + errno = EINVAL; + return (-1); + } +} + +int +tcsetpgrp(int fd, pid_t pgrp) +{ + int s; + + s = pgrp; + return (_ioctl(fd, TIOCSPGRP, &s)); +} + +pid_t +tcgetpgrp(fd) + int fd; +{ + int s; + + if (_ioctl(fd, TIOCGPGRP, &s) < 0) + return ((pid_t)-1); + + return ((pid_t)s); +} + +speed_t +cfgetospeed(t) + const struct termios *t; +{ + + return (t->c_ospeed); +} + +speed_t +cfgetispeed(t) + const struct termios *t; +{ + + return (t->c_ispeed); +} + +int +cfsetospeed(t, speed) + struct termios *t; + speed_t speed; +{ + + t->c_ospeed = speed; + return (0); +} + +int +cfsetispeed(t, speed) + struct termios *t; + speed_t speed; +{ + + t->c_ispeed = speed; + return (0); +} + +int +cfsetspeed(t, speed) + struct termios *t; + speed_t speed; +{ + + t->c_ispeed = t->c_ospeed = speed; + return (0); +} + +/* + * Make a pre-existing termios structure into "raw" mode: character-at-a-time + * mode with no characters interpreted, 8-bit data path. + */ +void +cfmakeraw(t) + struct termios *t; +{ + + t->c_iflag &= ~(IMAXBEL|IXOFF|INPCK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON|IGNPAR); + t->c_iflag |= IGNBRK; + t->c_oflag &= ~OPOST; + t->c_lflag &= ~(ECHO|ECHOE|ECHOK|ECHONL|ICANON|ISIG|IEXTEN|NOFLSH|TOSTOP|PENDIN); + t->c_cflag &= ~(CSIZE|PARENB); + t->c_cflag |= CS8|CREAD; + t->c_cc[VMIN] = 1; + t->c_cc[VTIME] = 0; +} + +int +tcsendbreak(fd, len) + int fd, len; +{ + struct timeval sleepytime; + + sleepytime.tv_sec = 0; + sleepytime.tv_usec = 400000; + if (_ioctl(fd, TIOCSBRK, 0) == -1) + return (-1); + (void)_select(0, 0, 0, 0, &sleepytime); + if (_ioctl(fd, TIOCCBRK, 0) == -1) + return (-1); + return (0); +} + +int +__tcdrain(fd) + int fd; +{ + return (_ioctl(fd, TIOCDRAIN, 0)); +} + +__weak_reference(__tcdrain, tcdrain); +__weak_reference(__tcdrain, _tcdrain); + +int +tcflush(fd, which) + int fd, which; +{ + int com; + + switch (which) { + case TCIFLUSH: + com = FREAD; + break; + case TCOFLUSH: + com = FWRITE; + break; + case TCIOFLUSH: + com = FREAD | FWRITE; + break; + default: + errno = EINVAL; + return (-1); + } + return (_ioctl(fd, TIOCFLUSH, &com)); +} + +int +tcflow(fd, action) + int fd, action; +{ + struct termios term; + u_char c; + + switch (action) { + case TCOOFF: + return (_ioctl(fd, TIOCSTOP, 0)); + case TCOON: + return (_ioctl(fd, TIOCSTART, 0)); + case TCION: + case TCIOFF: + if (tcgetattr(fd, &term) == -1) + return (-1); + c = term.c_cc[action == TCIOFF ? VSTOP : VSTART]; + if (c != _POSIX_VDISABLE && _write(fd, &c, sizeof(c)) == -1) + return (-1); + return (0); + default: + errno = EINVAL; + return (-1); + } + /* NOTREACHED */ +} diff --git a/lib/libc/gen/time.c b/lib/libc/gen/time.c new file mode 100644 index 0000000..5bf0ce0 --- /dev/null +++ b/lib/libc/gen/time.c @@ -0,0 +1,57 @@ +/* + * Copyright (c) 1983, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)time.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/time.c,v 1.4 2003/07/19 02:53:46 wollman Exp $"); + +#include +#include + +time_t +time(t) + time_t *t; +{ + struct timeval tt; + time_t retval; + + if (gettimeofday(&tt, (struct timezone *)0) < 0) + retval = -1; + else + retval = tt.tv_sec; + if (t != NULL) + *t = retval; + return (retval); +} diff --git a/lib/libc/gen/times.c b/lib/libc/gen/times.c new file mode 100644 index 0000000..8c3700a --- /dev/null +++ b/lib/libc/gen/times.c @@ -0,0 +1,71 @@ +/*- + * Copyright (c) 1990, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)times.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/times.c,v 1.3 2005/03/08 08:12:35 phk Exp $"); + +#include +#include +#include +#include + +/* + * Convert usec to clock ticks; could do (usec * CLK_TCK) / 1000000, + * but this would overflow if we switch to nanosec. + */ +#define CONVTCK(r) (r.tv_sec * CLK_TCK + r.tv_usec / (1000000 / CLK_TCK)) + +clock_t +times(tp) + struct tms *tp; +{ + struct rusage ru; + struct timespec t; + clock_t c; + + if (getrusage(RUSAGE_SELF, &ru) < 0) + return ((clock_t)-1); + tp->tms_utime = CONVTCK(ru.ru_utime); + tp->tms_stime = CONVTCK(ru.ru_stime); + if (getrusage(RUSAGE_CHILDREN, &ru) < 0) + return ((clock_t)-1); + tp->tms_cutime = CONVTCK(ru.ru_utime); + tp->tms_cstime = CONVTCK(ru.ru_stime); + if (clock_gettime(CLOCK_MONOTONIC, &t)) + return ((clock_t)-1); + c = t.tv_sec * CLK_TCK + t.tv_nsec / (1000000000 / CLK_TCK); + return (c); +} diff --git a/lib/libc/gen/timezone.c b/lib/libc/gen/timezone.c new file mode 100644 index 0000000..8d8139a --- /dev/null +++ b/lib/libc/gen/timezone.c @@ -0,0 +1,137 @@ +/* + * 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. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)timezone.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/timezone.c,v 1.5 2002/02/01 01:08:48 obrien Exp $"); + +#include +#include +#include +#include +#include +#define TZ_MAX_CHARS 255 + +char *_tztab(); + +/* + * timezone -- + * The arguments are the number of minutes of time you are westward + * from Greenwich and whether DST is in effect. It returns a string + * giving the name of the local timezone. Should be replaced, in the + * application code, by a call to localtime. + */ + +static char czone[TZ_MAX_CHARS]; /* space for zone name */ + +char * +timezone(zone, dst) + int zone, + dst; +{ + char *beg, + *end; + + if ( (beg = getenv("TZNAME")) ) { /* set in environment */ + if ( (end = index(beg, ',')) ) {/* "PST,PDT" */ + if (dst) + return(++end); + *end = '\0'; + (void)strncpy(czone,beg,sizeof(czone) - 1); + czone[sizeof(czone) - 1] = '\0'; + *end = ','; + return(czone); + } + return(beg); + } + return(_tztab(zone,dst)); /* default: table or created zone */ +} + +static struct zone { + int offset; + char *stdzone; + char *dlzone; +} zonetab[] = { + {-1*60, "MET", "MET DST"}, /* Middle European */ + {-2*60, "EET", "EET DST"}, /* Eastern European */ + {4*60, "AST", "ADT"}, /* Atlantic */ + {5*60, "EST", "EDT"}, /* Eastern */ + {6*60, "CST", "CDT"}, /* Central */ + {7*60, "MST", "MDT"}, /* Mountain */ + {8*60, "PST", "PDT"}, /* Pacific */ +#ifdef notdef + /* there's no way to distinguish this from WET */ + {0, "GMT", 0}, /* Greenwich */ +#endif + {0*60, "WET", "WET DST"}, /* Western European */ + {-10*60,"EST", "EST"}, /* Aust: Eastern */ + {-10*60+30,"CST", "CST"}, /* Aust: Central */ + {-8*60, "WST", 0}, /* Aust: Western */ + {-1} +}; + +/* + * _tztab -- + * check static tables or create a new zone name; broken out so that + * we can make a guess as to what the zone is if the standard tables + * aren't in place in /etc. DO NOT USE THIS ROUTINE OUTSIDE OF THE + * STANDARD LIBRARY. + */ +char * +_tztab(zone,dst) + int zone; + int dst; +{ + struct zone *zp; + char sign; + + for (zp = zonetab; zp->offset != -1;++zp) /* static tables */ + if (zp->offset == zone) { + if (dst && zp->dlzone) + return(zp->dlzone); + if (!dst && zp->stdzone) + return(zp->stdzone); + } + + if (zone < 0) { /* create one */ + zone = -zone; + sign = '+'; + } + else + sign = '-'; + (void)snprintf(czone, sizeof(czone), + "GMT%c%d:%02d",sign,zone / 60,zone % 60); + return(czone); +} diff --git a/lib/libc/gen/tls.c b/lib/libc/gen/tls.c new file mode 100644 index 0000000..d4a0fd0 --- /dev/null +++ b/lib/libc/gen/tls.c @@ -0,0 +1,306 @@ +/*- + * Copyright (c) 2004 Doug Rabson + * 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 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 AUTHOR 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. + * + * $FreeBSD: src/lib/libc/gen/tls.c,v 1.8.2.1 2006/09/02 20:38:13 marcel Exp $ + */ + +/* + * Define stubs for TLS internals so that programs and libraries can + * link. These functions will be replaced by functional versions at + * runtime from ld-elf.so.1. + */ + +#include +#include +#include +#include +#include + +#include "libc_private.h" + +__weak_reference(__libc_allocate_tls, _rtld_allocate_tls); +__weak_reference(__libc_free_tls, _rtld_free_tls); + +#ifdef __i386__ + +__weak_reference(___libc_tls_get_addr, ___tls_get_addr); +__attribute__((__regparm__(1))) void * ___libc_tls_get_addr(void *); + +#endif + +void * __libc_tls_get_addr(void *); +__weak_reference(__libc_tls_get_addr, __tls_get_addr); + +void *_rtld_allocate_tls(void *oldtls, size_t tcbsize, size_t tcbalign); +void _rtld_free_tls(void *tls, size_t tcbsize, size_t tcbalign); +void *__libc_allocate_tls(void *oldtls, size_t tcbsize, size_t tcbalign); +void __libc_free_tls(void *tls, size_t tcbsize, size_t tcbalign); + +#if defined(__ia64__) || defined(__alpha__) || defined(__powerpc__) +#define TLS_VARIANT_I +#endif +#if defined(__i386__) || defined(__amd64__) || defined(__sparc64__) || \ + defined(__arm__) +#define TLS_VARIANT_II +#endif + +#ifndef PIC + +#define round(size, align) \ + (((size) + (align) - 1) & ~((align) - 1)) + +static size_t tls_static_space; +static size_t tls_init_size; +static void *tls_init; +#endif + +#ifdef __i386__ + +/* GNU ABI */ + +__attribute__((__regparm__(1))) +void * +___libc_tls_get_addr(void *ti __unused) +{ + return (0); +} + +#endif + +void * +__libc_tls_get_addr(void *ti __unused) +{ + return (0); +} + +#ifndef PIC + +#ifdef TLS_VARIANT_I + +#define TLS_TCB_SIZE (2 * sizeof(void *)) + +/* + * Free Static TLS using the Variant I method. + */ +void +__libc_free_tls(void *tcb, size_t tcbsize, size_t tcbalign __unused) +{ + Elf_Addr *dtv; + Elf_Addr **tls; + + tls = (Elf_Addr **)((Elf_Addr)tcb + tcbsize - TLS_TCB_SIZE); + dtv = tls[0]; + free(dtv); + free(tcb); +} + +/* + * Allocate Static TLS using the Variant I method. + */ +void * +__libc_allocate_tls(void *oldtcb, size_t tcbsize, size_t tcbalign __unused) +{ + Elf_Addr *dtv; + Elf_Addr **tls; + char *tcb; + + if (oldtcb != NULL && tcbsize == TLS_TCB_SIZE) + return (oldtcb); + + tcb = malloc(tls_static_space + tcbsize); + tls = (Elf_Addr **)(tcb + tcbsize - TLS_TCB_SIZE); + + if (oldtcb != NULL) { + memcpy(tls, oldtcb, tls_static_space + TLS_TCB_SIZE); + free(oldtcb); + + /* Adjust the DTV. */ + dtv = tls[0]; + dtv[2] = (Elf_Addr)tls + TLS_TCB_SIZE; + } else { + dtv = malloc(3 * sizeof(Elf_Addr)); + tls[0] = dtv; + dtv[0] = 1; + dtv[1] = 1; + dtv[2] = (Elf_Addr)tls + TLS_TCB_SIZE; + + if (tls_init_size > 0) + memcpy((void*)dtv[2], tls_init, tls_init_size); + if (tls_static_space > tls_init_size) + memset((void*)(dtv[2] + tls_init_size), 0, + tls_static_space - tls_init_size); + } + + return(tcb); +} + +#endif + +#ifdef TLS_VARIANT_II + +#define TLS_TCB_SIZE (3 * sizeof(Elf_Addr)) + +/* + * Free Static TLS using the Variant II method. + */ +void +__libc_free_tls(void *tcb, size_t tcbsize __unused, size_t tcbalign) +{ + size_t size; + Elf_Addr* dtv; + Elf_Addr tlsstart, tlsend; + + /* + * Figure out the size of the initial TLS block so that we can + * find stuff which ___tls_get_addr() allocated dynamically. + */ + size = round(tls_static_space, tcbalign); + + dtv = ((Elf_Addr**)tcb)[1]; + tlsend = (Elf_Addr) tcb; + tlsstart = tlsend - size; + free((void*) tlsstart); + free(dtv); +} + +/* + * Allocate Static TLS using the Variant II method. + */ +void * +__libc_allocate_tls(void *oldtls, size_t tcbsize, size_t tcbalign) +{ + size_t size; + char *tls; + Elf_Addr *dtv; + Elf_Addr segbase, oldsegbase; + + size = round(tls_static_space, tcbalign); + + assert(tcbsize >= 2*sizeof(Elf_Addr)); + tls = malloc(size + tcbsize); + dtv = malloc(3 * sizeof(Elf_Addr)); + + segbase = (Elf_Addr)(tls + size); + ((Elf_Addr*)segbase)[0] = segbase; + ((Elf_Addr*)segbase)[1] = (Elf_Addr) dtv; + + dtv[0] = 1; + dtv[1] = 1; + dtv[2] = segbase - tls_static_space; + + if (oldtls) { + /* + * Copy the static TLS block over whole. + */ + oldsegbase = (Elf_Addr) oldtls; + memcpy((void *)(segbase - tls_static_space), + (const void *)(oldsegbase - tls_static_space), + tls_static_space); + + /* + * We assume that this block was the one we created with + * allocate_initial_tls(). + */ + _rtld_free_tls(oldtls, 2*sizeof(Elf_Addr), sizeof(Elf_Addr)); + } else { + memcpy((void *)(segbase - tls_static_space), + tls_init, tls_init_size); + memset((void *)(segbase - tls_static_space + tls_init_size), + 0, tls_static_space - tls_init_size); + } + + return (void*) segbase; +} + +#endif /* TLS_VARIANT_II */ + +#else + +void * +__libc_allocate_tls(void *oldtls __unused, size_t tcbsize __unused, + size_t tcbalign __unused) +{ + return (0); +} + +void +__libc_free_tls(void *tcb __unused, size_t tcbsize __unused, + size_t tcbalign __unused) +{ +} + +#endif /* PIC */ + +extern char **environ; + +void +_init_tls() +{ +#ifndef PIC + Elf_Addr *sp; + Elf_Auxinfo *aux, *auxp; + Elf_Phdr *phdr; + size_t phent, phnum; + int i; + void *tls; + + sp = (Elf_Addr *) environ; + while (*sp++ != 0) + ; + aux = (Elf_Auxinfo *) sp; + phdr = 0; + phent = phnum = 0; + for (auxp = aux; auxp->a_type != AT_NULL; auxp++) { + switch (auxp->a_type) { + case AT_PHDR: + phdr = auxp->a_un.a_ptr; + break; + + case AT_PHENT: + phent = auxp->a_un.a_val; + break; + + case AT_PHNUM: + phnum = auxp->a_un.a_val; + break; + } + } + if (phdr == 0 || phent != sizeof(Elf_Phdr) || phnum == 0) + return; + + for (i = 0; (unsigned) i < phnum; i++) { + if (phdr[i].p_type == PT_TLS) { + tls_static_space = round(phdr[i].p_memsz, + phdr[i].p_align); + tls_init_size = phdr[i].p_filesz; + tls_init = (void*) phdr[i].p_vaddr; + } + } + + tls = _rtld_allocate_tls(NULL, TLS_TCB_SIZE, 1); + + _set_tp(tls); +#endif +} diff --git a/lib/libc/gen/ttyname.c b/lib/libc/gen/ttyname.c new file mode 100644 index 0000000..4341ed4 --- /dev/null +++ b/lib/libc/gen/ttyname.c @@ -0,0 +1,124 @@ +/* + * Copyright (c) 1988, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)ttyname.c 8.2 (Berkeley) 1/27/94"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/ttyname.c,v 1.23 2005/05/20 15:39:20 ume Exp $"); + +#include "namespace.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "reentrant.h" +#include "un-namespace.h" + +#include "libc_private.h" + +static char ttyname_buf[sizeof(_PATH_DEV) + MAXNAMLEN]; + +static once_t ttyname_init_once = ONCE_INITIALIZER; +static thread_key_t ttyname_key; +static int ttyname_keycreated = 0; + +int +ttyname_r(int fd, char *buf, size_t len) +{ + struct stat sb; + struct fiodgname_arg fgn; + size_t used; + + *buf = '\0'; + + /* Must be a terminal. */ + if (!isatty(fd)) + return (ENOTTY); + /* Must be a character device. */ + if (_fstat(fd, &sb) || !S_ISCHR(sb.st_mode)) + return (ENOTTY); + /* Must have enough room */ + if (len <= sizeof(_PATH_DEV)) + return (ERANGE); + + strcpy(buf, _PATH_DEV); + used = strlen(buf); + fgn.len = len - used; + fgn.buf = buf + used; + if (!_ioctl(fd, FIODGNAME, &fgn)) + return (0); + used = strlen(buf); + devname_r(sb.st_rdev, S_IFCHR, buf + used, len - used); + return (0); +} + +static void +ttyname_keycreate(void) +{ + ttyname_keycreated = (thr_keycreate(&ttyname_key, free) == 0); +} + +char * +ttyname(int fd) +{ + char *buf; + + if (thr_main() != 0) + buf = ttyname_buf; + else { + if (thr_once(&ttyname_init_once, ttyname_keycreate) != 0 || + !ttyname_keycreated) + return (NULL); + if ((buf = thr_getspecific(ttyname_key)) == NULL) { + if ((buf = malloc(sizeof ttyname_buf)) == NULL) + return (NULL); + if (thr_setspecific(ttyname_key, buf) != 0) { + free(buf); + return (NULL); + } + } + } + + if (ttyname_r(fd, buf, sizeof ttyname_buf) != 0) + return (NULL); + return (buf); +} diff --git a/lib/libc/gen/ttyslot.c b/lib/libc/gen/ttyslot.c new file mode 100644 index 0000000..0d7359c --- /dev/null +++ b/lib/libc/gen/ttyslot.c @@ -0,0 +1,70 @@ +/* + * Copyright (c) 1988, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)ttyslot.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/ttyslot.c,v 1.4 2002/02/01 01:08:48 obrien Exp $"); + +#include +#include +#include +#include + +int +ttyslot() +{ + struct ttyent *ttyp; + int slot; + char *p; + int cnt; + char *name; + + setttyent(); + for (cnt = 0; cnt < 3; ++cnt) + if ( (name = ttyname(cnt)) ) { + if ( (p = rindex(name, '/')) ) + ++p; + else + p = name; + for (slot = 1; (ttyp = getttyent()); ++slot) + if (!strcmp(ttyp->ty_name, p)) { + endttyent(); + return(slot); + } + break; + } + endttyent(); + return(0); +} diff --git a/lib/libc/gen/ualarm.c b/lib/libc/gen/ualarm.c new file mode 100644 index 0000000..a9200ae --- /dev/null +++ b/lib/libc/gen/ualarm.c @@ -0,0 +1,67 @@ +/* + * 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. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)ualarm.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/ualarm.c,v 1.4 2002/12/29 00:59:09 mike Exp $"); + +#include +#include + +#define USPS 1000000 /* # of microseconds in a second */ + +/* + * Generate a SIGALRM signal in ``usecs'' microseconds. + * If ``reload'' is non-zero, keep generating SIGALRM + * every ``reload'' microseconds after the first signal. + */ +useconds_t +ualarm(usecs, reload) + useconds_t usecs; + useconds_t reload; +{ + struct itimerval new, old; + + new.it_interval.tv_usec = reload % USPS; + new.it_interval.tv_sec = reload / USPS; + + new.it_value.tv_usec = usecs % USPS; + new.it_value.tv_sec = usecs / USPS; + + if (setitimer(ITIMER_REAL, &new, &old) == 0) + return (old.it_value.tv_sec * USPS + old.it_value.tv_usec); + /* else */ + return (-1); +} diff --git a/lib/libc/gen/ulimit.c b/lib/libc/gen/ulimit.c new file mode 100644 index 0000000..d25ff47 --- /dev/null +++ b/lib/libc/gen/ulimit.c @@ -0,0 +1,68 @@ +/*- + * Copyright (c) 2002 Kyle Martin + * 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 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 AUTHOR 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. + * + * $FreeBSD: src/lib/libc/gen/ulimit.c,v 1.3 2003/01/04 01:11:49 tjr Exp $ + */ + +#include +#include +#include + +#include +#include +#include +#include + +long +ulimit(int cmd, ...) +{ + struct rlimit limit; + va_list ap; + long arg; + + if (cmd == UL_GETFSIZE) { + if (getrlimit(RLIMIT_FSIZE, &limit) == -1) + return (-1); + limit.rlim_cur /= 512; + if (limit.rlim_cur > LONG_MAX) + return (LONG_MAX); + return ((long)limit.rlim_cur); + } else if (cmd == UL_SETFSIZE) { + va_start(ap, cmd); + arg = va_arg(ap, long); + va_end(ap); + limit.rlim_max = limit.rlim_cur = (rlim_t)arg * 512; + + /* The setrlimit() function sets errno to EPERM if needed. */ + if (setrlimit(RLIMIT_FSIZE, &limit) == -1) + return (-1); + if (arg * 512 > LONG_MAX) + return (LONG_MAX); + return (arg); + } else { + errno = EINVAL; + return (-1); + } +} diff --git a/lib/libc/gen/uname.c b/lib/libc/gen/uname.c new file mode 100644 index 0000000..699e7b2 --- /dev/null +++ b/lib/libc/gen/uname.c @@ -0,0 +1,51 @@ +/*- + * Copyright (c) 1994 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "From: @(#)uname.c 8.1 (Berkeley) 1/4/94"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/uname.c,v 1.9 2002/02/01 00:57:29 obrien Exp $"); + +#define uname wrapped_uname +#include +#include +#include +#include +#undef uname + +int +uname(struct utsname *name) +{ + return __xuname(32, name); +} diff --git a/lib/libc/gen/unvis.c b/lib/libc/gen/unvis.c new file mode 100644 index 0000000..35443d1 --- /dev/null +++ b/lib/libc/gen/unvis.c @@ -0,0 +1,297 @@ +/*- + * Copyright (c) 1989, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)unvis.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/unvis.c,v 1.9 2004/08/02 08:46:23 stefanf Exp $"); + +#include +#include +#include + +/* + * decode driven by state machine + */ +#define S_GROUND 0 /* haven't seen escape char */ +#define S_START 1 /* start decoding special sequence */ +#define S_META 2 /* metachar started (M) */ +#define S_META1 3 /* metachar more, regular char (-) */ +#define S_CTRL 4 /* control char started (^) */ +#define S_OCTAL2 5 /* octal digit 2 */ +#define S_OCTAL3 6 /* octal digit 3 */ +#define S_HEX2 7 /* hex digit 2 */ + +#define S_HTTP 0x080 /* %HEXHEX escape */ + +#define isoctal(c) (((u_char)(c)) >= '0' && ((u_char)(c)) <= '7') +#define ishex(c) ((((u_char)(c)) >= '0' && ((u_char)(c)) <= '9') || (((u_char)(c)) >= 'a' && ((u_char)(c)) <= 'f')) + +/* + * unvis - decode characters previously encoded by vis + */ +int +unvis(char *cp, int c, int *astate, int flag) +{ + + if (flag & UNVIS_END) { + if (*astate == S_OCTAL2 || *astate == S_OCTAL3) { + *astate = S_GROUND; + return (UNVIS_VALID); + } + return (*astate == S_GROUND ? UNVIS_NOCHAR : UNVIS_SYNBAD); + } + + switch (*astate & ~S_HTTP) { + + case S_GROUND: + *cp = 0; + if (c == '\\') { + *astate = S_START; + return (0); + } + if (flag & VIS_HTTPSTYLE && c == '%') { + *astate = S_START | S_HTTP; + return (0); + } + *cp = c; + return (UNVIS_VALID); + + case S_START: + if (*astate & S_HTTP) { + if (ishex(tolower(c))) { + *cp = isdigit(c) ? (c - '0') : (tolower(c) - 'a'); + *astate = S_HEX2; + return (0); + } + } + switch(c) { + case '\\': + *cp = c; + *astate = S_GROUND; + return (UNVIS_VALID); + case '0': case '1': case '2': case '3': + case '4': case '5': case '6': case '7': + *cp = (c - '0'); + *astate = S_OCTAL2; + return (0); + case 'M': + *cp = 0200; + *astate = S_META; + return (0); + case '^': + *astate = S_CTRL; + return (0); + case 'n': + *cp = '\n'; + *astate = S_GROUND; + return (UNVIS_VALID); + case 'r': + *cp = '\r'; + *astate = S_GROUND; + return (UNVIS_VALID); + case 'b': + *cp = '\b'; + *astate = S_GROUND; + return (UNVIS_VALID); + case 'a': + *cp = '\007'; + *astate = S_GROUND; + return (UNVIS_VALID); + case 'v': + *cp = '\v'; + *astate = S_GROUND; + return (UNVIS_VALID); + case 't': + *cp = '\t'; + *astate = S_GROUND; + return (UNVIS_VALID); + case 'f': + *cp = '\f'; + *astate = S_GROUND; + return (UNVIS_VALID); + case 's': + *cp = ' '; + *astate = S_GROUND; + return (UNVIS_VALID); + case 'E': + *cp = '\033'; + *astate = S_GROUND; + return (UNVIS_VALID); + case '\n': + /* + * hidden newline + */ + *astate = S_GROUND; + return (UNVIS_NOCHAR); + case '$': + /* + * hidden marker + */ + *astate = S_GROUND; + return (UNVIS_NOCHAR); + } + *astate = S_GROUND; + return (UNVIS_SYNBAD); + + case S_META: + if (c == '-') + *astate = S_META1; + else if (c == '^') + *astate = S_CTRL; + else { + *astate = S_GROUND; + return (UNVIS_SYNBAD); + } + return (0); + + case S_META1: + *astate = S_GROUND; + *cp |= c; + return (UNVIS_VALID); + + case S_CTRL: + if (c == '?') + *cp |= 0177; + else + *cp |= c & 037; + *astate = S_GROUND; + return (UNVIS_VALID); + + case S_OCTAL2: /* second possible octal digit */ + if (isoctal(c)) { + /* + * yes - and maybe a third + */ + *cp = (*cp << 3) + (c - '0'); + *astate = S_OCTAL3; + return (0); + } + /* + * no - done with current sequence, push back passed char + */ + *astate = S_GROUND; + return (UNVIS_VALIDPUSH); + + case S_OCTAL3: /* third possible octal digit */ + *astate = S_GROUND; + if (isoctal(c)) { + *cp = (*cp << 3) + (c - '0'); + return (UNVIS_VALID); + } + /* + * we were done, push back passed char + */ + return (UNVIS_VALIDPUSH); + + case S_HEX2: /* second mandatory hex digit */ + if (ishex(tolower(c))) { + *cp = (isdigit(c) ? (*cp << 4) + (c - '0') : (*cp << 4) + (tolower(c) - 'a' + 10)); + } + *astate = S_GROUND; + return (UNVIS_VALID); + + default: + /* + * decoder in unknown state - (probably uninitialized) + */ + *astate = S_GROUND; + return (UNVIS_SYNBAD); + } +} + +/* + * strunvis - decode src into dst + * + * Number of chars decoded into dst is returned, -1 on error. + * Dst is null terminated. + */ + +int +strunvis(char *dst, const char *src) +{ + char c; + char *start = dst; + int state = 0; + + while ( (c = *src++) ) { + again: + switch (unvis(dst, c, &state, 0)) { + case UNVIS_VALID: + dst++; + break; + case UNVIS_VALIDPUSH: + dst++; + goto again; + case 0: + case UNVIS_NOCHAR: + break; + default: + return (-1); + } + } + if (unvis(dst, c, &state, UNVIS_END) == UNVIS_VALID) + dst++; + *dst = '\0'; + return (dst - start); +} + +int +strunvisx(char *dst, const char *src, int flag) +{ + char c; + char *start = dst; + int state = 0; + + while ( (c = *src++) ) { + again: + switch (unvis(dst, c, &state, flag)) { + case UNVIS_VALID: + dst++; + break; + case UNVIS_VALIDPUSH: + dst++; + goto again; + case 0: + case UNVIS_NOCHAR: + break; + default: + return (-1); + } + } + if (unvis(dst, c, &state, UNVIS_END) == UNVIS_VALID) + dst++; + *dst = '\0'; + return (dst - start); +} diff --git a/lib/libc/gen/usleep.c b/lib/libc/gen/usleep.c new file mode 100644 index 0000000..ba0820c --- /dev/null +++ b/lib/libc/gen/usleep.c @@ -0,0 +1,57 @@ +/* + * Copyright (c) 1989, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)usleep.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/usleep.c,v 1.28.12.1 2005/10/08 17:56:53 delphij Exp $"); + +#include "namespace.h" +#include +#include +#include "un-namespace.h" + +int +__usleep(useconds) + useconds_t useconds; +{ + struct timespec time_to_sleep; + + time_to_sleep.tv_nsec = (useconds % 1000000) * 1000; + time_to_sleep.tv_sec = useconds / 1000000; + return (_nanosleep(&time_to_sleep, NULL)); +} + +__weak_reference(__usleep, usleep); +__weak_reference(__usleep, _usleep); diff --git a/lib/libc/gen/utime.c b/lib/libc/gen/utime.c new file mode 100644 index 0000000..cefa020 --- /dev/null +++ b/lib/libc/gen/utime.c @@ -0,0 +1,59 @@ +/*- + * Copyright (c) 1990, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)utime.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/utime.c,v 1.2 2002/03/22 21:52:05 obrien Exp $"); + +#include + +#include + +int +utime(path, times) + const char *path; + const struct utimbuf *times; +{ + struct timeval tv[2], *tvp; + + if (times) { + tv[0].tv_sec = times->actime; + tv[1].tv_sec = times->modtime; + tv[0].tv_usec = tv[1].tv_usec = 0; + tvp = tv; + } else + tvp = NULL; + return (utimes(path, tvp)); +} diff --git a/lib/libc/gen/valloc.c b/lib/libc/gen/valloc.c new file mode 100644 index 0000000..206a7e8 --- /dev/null +++ b/lib/libc/gen/valloc.c @@ -0,0 +1,52 @@ +/* + * Copyright (c) 1980, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)valloc.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/valloc.c,v 1.3 2002/03/22 21:52:05 obrien Exp $"); + +#include +#include + +void * +valloc(i) + size_t i; +{ + long valsiz = getpagesize(), j; + void *cp = malloc(i + (valsiz-1)); + + j = ((long)cp + (valsiz-1)) &~ (valsiz-1); + return ((void *)j); +} diff --git a/lib/libc/gen/vis.c b/lib/libc/gen/vis.c new file mode 100644 index 0000000..8b82877 --- /dev/null +++ b/lib/libc/gen/vis.c @@ -0,0 +1,205 @@ +/*- + * Copyright (c) 1989, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)vis.c 8.1 (Berkeley) 7/19/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/vis.c,v 1.13 2003/10/30 12:41:50 phk Exp $"); + +#include +#include +#include +#include +#include + +#define isoctal(c) (((u_char)(c)) >= '0' && ((u_char)(c)) <= '7') + +/* + * vis - visually encode characters + */ +char * +vis(dst, c, flag, nextc) + char *dst; + int c, nextc; + int flag; +{ + c = (unsigned char)c; + + if (flag & VIS_HTTPSTYLE) { + /* Described in RFC 1808 */ + if (!(isalnum(c) /* alpha-numeric */ + /* safe */ + || c == '$' || c == '-' || c == '_' || c == '.' || c == '+' + /* extra */ + || c == '!' || c == '*' || c == '\'' || c == '(' + || c == ')' || c == ',')) { + *dst++ = '%'; + snprintf(dst, 4, (c < 16 ? "0%X" : "%X"), c); + dst += 2; + goto done; + } + } + + if ((flag & VIS_GLOB) && + (c == '*' || c == '?' || c == '[' || c == '#')) + ; + else if (isgraph(c) || + ((flag & VIS_SP) == 0 && c == ' ') || + ((flag & VIS_TAB) == 0 && c == '\t') || + ((flag & VIS_NL) == 0 && c == '\n') || + ((flag & VIS_SAFE) && (c == '\b' || c == '\007' || c == '\r'))) { + *dst++ = c; + if (c == '\\' && (flag & VIS_NOSLASH) == 0) + *dst++ = '\\'; + *dst = '\0'; + return (dst); + } + + if (flag & VIS_CSTYLE) { + switch(c) { + case '\n': + *dst++ = '\\'; + *dst++ = 'n'; + goto done; + case '\r': + *dst++ = '\\'; + *dst++ = 'r'; + goto done; + case '\b': + *dst++ = '\\'; + *dst++ = 'b'; + goto done; + case '\a': + *dst++ = '\\'; + *dst++ = 'a'; + goto done; + case '\v': + *dst++ = '\\'; + *dst++ = 'v'; + goto done; + case '\t': + *dst++ = '\\'; + *dst++ = 't'; + goto done; + case '\f': + *dst++ = '\\'; + *dst++ = 'f'; + goto done; + case ' ': + *dst++ = '\\'; + *dst++ = 's'; + goto done; + case '\0': + *dst++ = '\\'; + *dst++ = '0'; + if (isoctal(nextc)) { + *dst++ = '0'; + *dst++ = '0'; + } + goto done; + } + } + if (((c & 0177) == ' ') || isgraph(c) || (flag & VIS_OCTAL)) { + *dst++ = '\\'; + *dst++ = ((u_char)c >> 6 & 07) + '0'; + *dst++ = ((u_char)c >> 3 & 07) + '0'; + *dst++ = ((u_char)c & 07) + '0'; + goto done; + } + if ((flag & VIS_NOSLASH) == 0) + *dst++ = '\\'; + if (c & 0200) { + c &= 0177; + *dst++ = 'M'; + } + if (iscntrl(c)) { + *dst++ = '^'; + if (c == 0177) + *dst++ = '?'; + else + *dst++ = c + '@'; + } else { + *dst++ = '-'; + *dst++ = c; + } +done: + *dst = '\0'; + return (dst); +} + +/* + * strvis, strvisx - visually encode characters from src into dst + * + * Dst must be 4 times the size of src to account for possible + * expansion. The length of dst, not including the trailing NUL, + * is returned. + * + * Strvisx encodes exactly len bytes from src into dst. + * This is useful for encoding a block of data. + */ +int +strvis(dst, src, flag) + char *dst; + const char *src; + int flag; +{ + char c; + char *start; + + for (start = dst; (c = *src); ) + dst = vis(dst, c, flag, *++src); + *dst = '\0'; + return (dst - start); +} + +int +strvisx(dst, src, len, flag) + char *dst; + const char *src; + size_t len; + int flag; +{ + int c; + char *start; + + for (start = dst; len > 1; len--) { + c = *src; + dst = vis(dst, c, flag, *++src); + } + if (len) + dst = vis(dst, *src, flag, '\0'); + *dst = '\0'; + + return (dst - start); +} diff --git a/lib/libc/gen/wait.c b/lib/libc/gen/wait.c new file mode 100644 index 0000000..8cb80a4 --- /dev/null +++ b/lib/libc/gen/wait.c @@ -0,0 +1,54 @@ +/* + * Copyright (c) 1988, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)wait.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/wait.c,v 1.6 2002/02/01 00:57:29 obrien Exp $"); + +#include "namespace.h" +#include +#include +#include +#include +#include "un-namespace.h" + +pid_t +__wait(int *istat) +{ + return (_wait4(WAIT_ANY, istat, 0, (struct rusage *)0)); +} + +__weak_reference(__wait, wait); +__weak_reference(__wait, _wait); diff --git a/lib/libc/gen/wait3.c b/lib/libc/gen/wait3.c new file mode 100644 index 0000000..a4b91a7 --- /dev/null +++ b/lib/libc/gen/wait3.c @@ -0,0 +1,54 @@ +/* + * Copyright (c) 1988, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)wait3.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/wait3.c,v 1.3 2002/02/01 00:57:29 obrien Exp $"); + +#include "namespace.h" +#include +#include +#include +#include +#include "un-namespace.h" + +pid_t +wait3(istat, options, rup) + int *istat; + int options; + struct rusage *rup; +{ + return (_wait4(WAIT_ANY, istat, options, rup)); +} diff --git a/lib/libc/gen/waitpid.c b/lib/libc/gen/waitpid.c new file mode 100644 index 0000000..273d1f3 --- /dev/null +++ b/lib/libc/gen/waitpid.c @@ -0,0 +1,54 @@ +/* + * Copyright (c) 1988, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)waitpid.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/gen/waitpid.c,v 1.6 2002/02/01 00:57:29 obrien Exp $"); + +#include "namespace.h" +#include +#include +#include +#include +#include "un-namespace.h" + +pid_t +__waitpid(pid_t pid, int *istat, int options) +{ + return (_wait4(pid, istat, options, (struct rusage *)0)); +} + +__weak_reference(__waitpid, waitpid); +__weak_reference(__waitpid, _waitpid); diff --git a/lib/libc/gen/wordexp.c b/lib/libc/gen/wordexp.c new file mode 100644 index 0000000..b09d397 --- /dev/null +++ b/lib/libc/gen/wordexp.c @@ -0,0 +1,316 @@ +/*- + * Copyright (c) 2002 Tim J. Robbins. + * 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 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 AUTHOR 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 "namespace.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "un-namespace.h" + +__FBSDID("$FreeBSD: src/lib/libc/gen/wordexp.c,v 1.6 2004/06/30 13:55:08 tjr Exp $"); + +static int we_askshell(const char *, wordexp_t *, int); +static int we_check(const char *, int); + +/* + * wordexp -- + * Perform shell word expansion on `words' and place the resulting list + * of words in `we'. See wordexp(3). + * + * Specified by IEEE Std. 1003.1-2001. + */ +int +wordexp(const char * __restrict words, wordexp_t * __restrict we, int flags) +{ + int error; + + if (flags & WRDE_REUSE) + wordfree(we); + if ((flags & WRDE_APPEND) == 0) { + we->we_wordc = 0; + we->we_wordv = NULL; + we->we_strings = NULL; + we->we_nbytes = 0; + } + if ((error = we_check(words, flags)) != 0) { + wordfree(we); + return (error); + } + if ((error = we_askshell(words, we, flags)) != 0) { + wordfree(we); + return (error); + } + return (0); +} + +/* + * we_askshell -- + * Use the `wordexp' /bin/sh builtin function to do most of the work + * in expanding the word string. This function is complicated by + * memory management. + */ +static int +we_askshell(const char *words, wordexp_t *we, int flags) +{ + int pdes[2]; /* Pipe to child */ + char bbuf[9]; /* Buffer for byte count */ + char wbuf[9]; /* Buffer for word count */ + long nwords, nbytes; /* Number of words, bytes from child */ + long i; /* Handy integer */ + size_t sofs; /* Offset into we->we_strings */ + size_t vofs; /* Offset into we->we_wordv */ + pid_t pid; /* Process ID of child */ + int status; /* Child exit status */ + char *ifs; /* IFS env. var. */ + char *np, *p; /* Handy pointers */ + char *nstrings; /* Temporary for realloc() */ + char **nwv; /* Temporary for realloc() */ + + if ((ifs = getenv("IFS")) == NULL) + ifs = " \t\n"; + + if (pipe(pdes) < 0) + return (WRDE_NOSPACE); /* XXX */ + if ((pid = fork()) < 0) { + _close(pdes[0]); + _close(pdes[1]); + return (WRDE_NOSPACE); /* XXX */ + } + else if (pid == 0) { + /* + * We are the child; just get /bin/sh to run the wordexp + * builtin on `words'. + */ + int devnull; + char *cmd; + + _close(pdes[0]); + if (_dup2(pdes[1], STDOUT_FILENO) < 0) + _exit(1); + _close(pdes[1]); + if (asprintf(&cmd, "wordexp%c%s\n", *ifs, words) < 0) + _exit(1); + if ((flags & WRDE_SHOWERR) == 0) { + if ((devnull = _open(_PATH_DEVNULL, O_RDWR, 0666)) < 0) + _exit(1); + if (_dup2(devnull, STDERR_FILENO) < 0) + _exit(1); + _close(devnull); + } + execl(_PATH_BSHELL, "sh", flags & WRDE_UNDEF ? "-u" : "+u", + "-c", cmd, (char *)NULL); + _exit(1); + } + + /* + * We are the parent; read the output of the shell wordexp function, + * which is a 32-bit hexadecimal word count, a 32-bit hexadecimal + * byte count (not including terminating null bytes), followed by + * the expanded words separated by nulls. + */ + _close(pdes[1]); + if (_read(pdes[0], wbuf, 8) != 8 || _read(pdes[0], bbuf, 8) != 8) { + _close(pdes[0]); + _waitpid(pid, &status, 0); + return (flags & WRDE_UNDEF ? WRDE_BADVAL : WRDE_SYNTAX); + } + wbuf[8] = bbuf[8] = '\0'; + nwords = strtol(wbuf, NULL, 16); + nbytes = strtol(bbuf, NULL, 16) + nwords; + + /* + * Allocate or reallocate (when flags & WRDE_APPEND) the word vector + * and string storage buffers for the expanded words we're about to + * read from the child. + */ + sofs = we->we_nbytes; + vofs = we->we_wordc; + if ((flags & (WRDE_DOOFFS|WRDE_APPEND)) == (WRDE_DOOFFS|WRDE_APPEND)) + vofs += we->we_offs; + we->we_wordc += nwords; + we->we_nbytes += nbytes; + if ((nwv = realloc(we->we_wordv, (we->we_wordc + 1 + + (flags & WRDE_DOOFFS ? we->we_offs : 0)) * + sizeof(char *))) == NULL) { + _close(pdes[0]); + _waitpid(pid, &status, 0); + return (WRDE_NOSPACE); + } + we->we_wordv = nwv; + if ((nstrings = realloc(we->we_strings, we->we_nbytes)) == NULL) { + _close(pdes[0]); + _waitpid(pid, &status, 0); + return (WRDE_NOSPACE); + } + for (i = 0; i < vofs; i++) + if (we->we_wordv[i] != NULL) + we->we_wordv[i] += nstrings - we->we_strings; + we->we_strings = nstrings; + + if (_read(pdes[0], we->we_strings + sofs, nbytes) != nbytes) { + _close(pdes[0]); + _waitpid(pid, &status, 0); + return (flags & WRDE_UNDEF ? WRDE_BADVAL : WRDE_SYNTAX); + } + + if (_waitpid(pid, &status, 0) < 0 || !WIFEXITED(status) || + WEXITSTATUS(status) != 0) { + _close(pdes[0]); + return (flags & WRDE_UNDEF ? WRDE_BADVAL : WRDE_SYNTAX); + } + _close(pdes[0]); + + /* + * Break the null-terminated expanded word strings out into + * the vector. + */ + if (vofs == 0 && flags & WRDE_DOOFFS) + while (vofs < we->we_offs) + we->we_wordv[vofs++] = NULL; + p = we->we_strings + sofs; + while (nwords-- != 0) { + we->we_wordv[vofs++] = p; + if ((np = memchr(p, '\0', nbytes)) == NULL) + return (WRDE_NOSPACE); /* XXX */ + nbytes -= np - p + 1; + p = np + 1; + } + we->we_wordv[vofs] = NULL; + + return (0); +} + +/* + * we_check -- + * Check that the string contains none of the following unquoted + * special characters: |&;<>(){} + * or command substitutions when WRDE_NOCMD is set in flags. + */ +static int +we_check(const char *words, int flags) +{ + char c; + int dquote, level, quote, squote; + + quote = squote = dquote = 0; + while ((c = *words++) != '\0') { + switch (c) { + case '\\': + quote ^= 1; + continue; + case '\'': + if (quote + dquote == 0) + squote ^= 1; + break; + case '"': + if (quote + squote == 0) + dquote ^= 1; + break; + case '`': + if (quote + squote == 0 && flags & WRDE_NOCMD) + return (WRDE_CMDSUB); + while ((c = *words++) != '\0' && c != '`') + if (c == '\\' && (c = *words++) == '\0') + break; + if (c == '\0') + return (WRDE_SYNTAX); + break; + case '|': case '&': case ';': case '<': case '>': + case '{': case '}': case '(': case ')': case '\n': + if (quote + squote + dquote == 0) + return (WRDE_BADCHAR); + break; + case '$': + if ((c = *words++) == '\0') + break; + else if (quote + squote == 0 && c == '(') { + if (flags & WRDE_NOCMD && *words != '(') + return (WRDE_CMDSUB); + level = 1; + while ((c = *words++) != '\0') { + if (c == '\\') { + if ((c = *words++) == '\0') + break; + } else if (c == '(') + level++; + else if (c == ')' && --level == 0) + break; + } + if (c == '\0' || level != 0) + return (WRDE_SYNTAX); + } else if (quote + squote == 0 && c == '{') { + level = 1; + while ((c = *words++) != '\0') { + if (c == '\\') { + if ((c = *words++) == '\0') + break; + } else if (c == '{') + level++; + else if (c == '}' && --level == 0) + break; + } + if (c == '\0' || level != 0) + return (WRDE_SYNTAX); + } else + c = *--words; + break; + default: + break; + } + quote = 0; + } + if (quote + squote + dquote != 0) + return (WRDE_SYNTAX); + + return (0); +} + +/* + * wordfree -- + * Free the result of wordexp(). See wordexp(3). + * + * Specified by IEEE Std. 1003.1-2001. + */ +void +wordfree(wordexp_t *we) +{ + + if (we == NULL) + return; + free(we->we_wordv); + free(we->we_strings); + we->we_wordv = NULL; + we->we_strings = NULL; + we->we_nbytes = 0; + we->we_wordc = 0; +} diff --git a/lib/libc/gmon/Makefile b/lib/libc/gmon/Makefile new file mode 100644 index 0000000..2e35617 --- /dev/null +++ b/lib/libc/gmon/Makefile @@ -0,0 +1,35 @@ +# $Id: Makefile 89 2016-01-12 00:20:40Z reddawg $ +# The System Makefile (C) 2002 The UbixOS Project + +# Include Global 'Source' Options +include ../../../Makefile.incl +include ../../Makefile.incl +include ../Makefile.incl + +INCLUDES += -I../locale/ + +#Objects +OBJS = gmon.o mcount.o + +all: $(OBJS) + +# Compile the source files +.cc.o: + $(CXX) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -c -o $@ $< + +.cc.s: + $(CXX) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -S -o $@ $< + +.c.o: + $(CC) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -c $< + +.c.s: + $(CC) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -S -o $@ $< + +.S.o: + $(CC) $(CFLAGS) -Wall -nostdlib -c -o $@ $< + +# Clean up the junk +clean: + $(REMOVE) $(OBJS) + diff --git a/lib/libc/gmon/gmon.c b/lib/libc/gmon/gmon.c new file mode 100644 index 0000000..d18abbd --- /dev/null +++ b/lib/libc/gmon/gmon.c @@ -0,0 +1,267 @@ +/*- + * Copyright (c) 1983, 1992, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)gmon.c 8.1 (Berkeley) 6/4/93"; +#endif +#include +__FBSDID("$FreeBSD: src/lib/libc/gmon/gmon.c,v 1.20 2004/10/16 06:32:43 obrien Exp $"); + +#include "namespace.h" +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include "un-namespace.h" + +#include "libc_private.h" + +#if defined(__i386__) || defined(__sparc64__) || defined(__amd64__) +extern char *minbrk __asm (".minbrk"); +#else +extern char *minbrk __asm ("minbrk"); +#endif + +struct gmonparam _gmonparam = { GMON_PROF_OFF }; + +static int s_scale; +/* see profil(2) where this is describe (incorrectly) */ +#define SCALE_1_TO_1 0x10000L + +#define ERR(s) _write(2, s, sizeof(s)) + +void moncontrol(int); +static int hertz(void); + +void +monstartup(lowpc, highpc) + u_long lowpc; + u_long highpc; +{ + int o; + char *cp; + struct gmonparam *p = &_gmonparam; + + /* + * round lowpc and highpc to multiples of the density we're using + * so the rest of the scaling (here and in gprof) stays in ints. + */ + p->lowpc = ROUNDDOWN(lowpc, HISTFRACTION * sizeof(HISTCOUNTER)); + p->highpc = ROUNDUP(highpc, HISTFRACTION * sizeof(HISTCOUNTER)); + p->textsize = p->highpc - p->lowpc; + p->kcountsize = p->textsize / HISTFRACTION; + p->hashfraction = HASHFRACTION; + p->fromssize = p->textsize / HASHFRACTION; + p->tolimit = p->textsize * ARCDENSITY / 100; + if (p->tolimit < MINARCS) + p->tolimit = MINARCS; + else if (p->tolimit > MAXARCS) + p->tolimit = MAXARCS; + p->tossize = p->tolimit * sizeof(struct tostruct); + + cp = sbrk(p->kcountsize + p->fromssize + p->tossize); + if (cp == (char *)-1) { + ERR("monstartup: out of memory\n"); + return; + } +#ifdef notdef + bzero(cp, p->kcountsize + p->fromssize + p->tossize); +#endif + p->tos = (struct tostruct *)cp; + cp += p->tossize; + p->kcount = (u_short *)cp; + cp += p->kcountsize; + p->froms = (u_short *)cp; + + minbrk = sbrk(0); + p->tos[0].link = 0; + + o = p->highpc - p->lowpc; + if (p->kcountsize < o) { +#ifndef hp300 + s_scale = ((float)p->kcountsize / o ) * SCALE_1_TO_1; +#else /* avoid floating point */ + int quot = o / p->kcountsize; + + if (quot >= 0x10000) + s_scale = 1; + else if (quot >= 0x100) + s_scale = 0x10000 / quot; + else if (o >= 0x800000) + s_scale = 0x1000000 / (o / (p->kcountsize >> 8)); + else + s_scale = 0x1000000 / ((o << 8) / p->kcountsize); +#endif + } else + s_scale = SCALE_1_TO_1; + + moncontrol(1); +} + +void +_mcleanup() +{ + int fd; + int fromindex; + int endfrom; + u_long frompc; + int toindex; + struct rawarc rawarc; + struct gmonparam *p = &_gmonparam; + struct gmonhdr gmonhdr, *hdr; + struct clockinfo clockinfo; + char outname[128]; + int mib[2]; + size_t size; +#ifdef DEBUG + int log, len; + char buf[200]; +#endif + + if (p->state == GMON_PROF_ERROR) + ERR("_mcleanup: tos overflow\n"); + + size = sizeof(clockinfo); + mib[0] = CTL_KERN; + mib[1] = KERN_CLOCKRATE; + if (sysctl(mib, 2, &clockinfo, &size, NULL, 0) < 0) { + /* + * Best guess + */ + clockinfo.profhz = hertz(); + } else if (clockinfo.profhz == 0) { + if (clockinfo.hz != 0) + clockinfo.profhz = clockinfo.hz; + else + clockinfo.profhz = hertz(); + } + + moncontrol(0); + snprintf(outname, sizeof(outname), "%s.gmon", _getprogname()); + fd = _open(outname, O_CREAT|O_TRUNC|O_WRONLY, 0666); + if (fd < 0) { + _warn("_mcleanup: %s", outname); + return; + } +#ifdef DEBUG + log = _open("gmon.log", O_CREAT|O_TRUNC|O_WRONLY, 0664); + if (log < 0) { + _warn("_mcleanup: gmon.log"); + return; + } + len = sprintf(buf, "[mcleanup1] kcount 0x%p ssiz %lu\n", + p->kcount, p->kcountsize); + _write(log, buf, len); +#endif + hdr = (struct gmonhdr *)&gmonhdr; + bzero(hdr, sizeof(*hdr)); + hdr->lpc = p->lowpc; + hdr->hpc = p->highpc; + hdr->ncnt = p->kcountsize + sizeof(gmonhdr); + hdr->version = GMONVERSION; + hdr->profrate = clockinfo.profhz; + _write(fd, (char *)hdr, sizeof *hdr); + _write(fd, p->kcount, p->kcountsize); + endfrom = p->fromssize / sizeof(*p->froms); + for (fromindex = 0; fromindex < endfrom; fromindex++) { + if (p->froms[fromindex] == 0) + continue; + + frompc = p->lowpc; + frompc += fromindex * p->hashfraction * sizeof(*p->froms); + for (toindex = p->froms[fromindex]; toindex != 0; + toindex = p->tos[toindex].link) { +#ifdef DEBUG + len = sprintf(buf, + "[mcleanup2] frompc 0x%lx selfpc 0x%lx count %lu\n" , + frompc, p->tos[toindex].selfpc, + p->tos[toindex].count); + _write(log, buf, len); +#endif + rawarc.raw_frompc = frompc; + rawarc.raw_selfpc = p->tos[toindex].selfpc; + rawarc.raw_count = p->tos[toindex].count; + _write(fd, &rawarc, sizeof rawarc); + } + } + _close(fd); +} + +/* + * Control profiling + * profiling is what mcount checks to see if + * all the data structures are ready. + */ +void +moncontrol(mode) + int mode; +{ + struct gmonparam *p = &_gmonparam; + + if (mode) { + /* start */ + profil((char *)p->kcount, p->kcountsize, p->lowpc, s_scale); + p->state = GMON_PROF_ON; + } else { + /* stop */ + profil((char *)0, 0, 0, 0); + p->state = GMON_PROF_OFF; + } +} + +/* + * discover the tick frequency of the machine + * if something goes wrong, we return 0, an impossible hertz. + */ +static int +hertz() +{ + struct itimerval tim; + + tim.it_interval.tv_sec = 0; + tim.it_interval.tv_usec = 1; + tim.it_value.tv_sec = 0; + tim.it_value.tv_usec = 0; + setitimer(ITIMER_REAL, &tim, 0); + setitimer(ITIMER_REAL, 0, &tim); + if (tim.it_interval.tv_usec < 2) + return(0); + return (1000000 / tim.it_interval.tv_usec); +} diff --git a/lib/libc/gmon/mcount.c b/lib/libc/gmon/mcount.c new file mode 100644 index 0000000..fd26a77 --- /dev/null +++ b/lib/libc/gmon/mcount.c @@ -0,0 +1,325 @@ +/*- + * Copyright (c) 1983, 1992, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if !defined(_KERNEL) && defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)mcount.c 8.1 (Berkeley) 6/4/93"; +#endif +#include +__FBSDID("$FreeBSD: src/lib/libc/gmon/mcount.c,v 1.21 2005/05/06 07:37:01 davidxu Exp $"); + +#include +#include +#ifdef _KERNEL +#include +#include +#include +#include +void bintr(void); +void btrap(void); +void eintr(void); +void user(void); +#endif +#include + +/* + * mcount is called on entry to each function compiled with the profiling + * switch set. _mcount(), which is declared in a machine-dependent way + * with _MCOUNT_DECL, does the actual work and is either inlined into a + * C routine or called by an assembly stub. In any case, this magic is + * taken care of by the MCOUNT definition in . + * + * _mcount updates data structures that represent traversals of the + * program's call graph edges. frompc and selfpc are the return + * address and function address that represents the given call graph edge. + * + * Note: the original BSD code used the same variable (frompcindex) for + * both frompcindex and frompc. Any reasonable, modern compiler will + * perform this optimization. + */ +/* _mcount; may be static, inline, etc */ +_MCOUNT_DECL(uintfptr_t frompc, uintfptr_t selfpc) +{ +#ifdef GUPROF + u_int delta; +#endif + fptrdiff_t frompci; + u_short *frompcindex; + struct tostruct *top, *prevtop; + struct gmonparam *p; + long toindex; +#ifdef _KERNEL + MCOUNT_DECL(s) +#endif + + p = &_gmonparam; +#ifndef GUPROF /* XXX */ + /* + * check that we are profiling + * and that we aren't recursively invoked. + */ + if (p->state != GMON_PROF_ON) + return; +#endif +#ifdef _KERNEL + MCOUNT_ENTER(s); +#else + if (!atomic_cmpset_acq_int(&p->state, GMON_PROF_ON, GMON_PROF_BUSY)) + return; +#endif + frompci = frompc - p->lowpc; + +#ifdef _KERNEL + /* + * When we are called from an exception handler, frompci may be + * for a user address. Convert such frompci's to the index of + * user() to merge all user counts. + */ + if (frompci >= p->textsize) { + if (frompci + p->lowpc + >= (uintfptr_t)(VM_MAXUSER_ADDRESS + UPAGES * PAGE_SIZE)) + goto done; + frompci = (uintfptr_t)user - p->lowpc; + if (frompci >= p->textsize) + goto done; + } +#endif + +#ifdef GUPROF + if (p->state != GMON_PROF_HIRES) + goto skip_guprof_stuff; + /* + * Look at the clock and add the count of clock cycles since the + * clock was last looked at to a counter for frompc. This + * solidifies the count for the function containing frompc and + * effectively starts another clock for the current function. + * The count for the new clock will be solidified when another + * function call is made or the function returns. + * + * We use the usual sampling counters since they can be located + * efficiently. 4-byte counters are usually necessary. + * + * There are many complications for subtracting the profiling + * overheads from the counts for normal functions and adding + * them to the counts for mcount(), mexitcount() and cputime(). + * We attempt to handle fractional cycles, but the overheads + * are usually underestimated because they are calibrated for + * a simpler than usual setup. + */ + delta = cputime() - p->mcount_overhead; + p->cputime_overhead_resid += p->cputime_overhead_frac; + p->mcount_overhead_resid += p->mcount_overhead_frac; + if ((int)delta < 0) + *p->mcount_count += delta + p->mcount_overhead + - p->cputime_overhead; + else if (delta != 0) { + if (p->cputime_overhead_resid >= CALIB_SCALE) { + p->cputime_overhead_resid -= CALIB_SCALE; + ++*p->cputime_count; + --delta; + } + if (delta != 0) { + if (p->mcount_overhead_resid >= CALIB_SCALE) { + p->mcount_overhead_resid -= CALIB_SCALE; + ++*p->mcount_count; + --delta; + } + KCOUNT(p, frompci) += delta; + } + *p->mcount_count += p->mcount_overhead_sub; + } + *p->cputime_count += p->cputime_overhead; +skip_guprof_stuff: +#endif /* GUPROF */ + +#ifdef _KERNEL + /* + * When we are called from an exception handler, frompc is faked + * to be for where the exception occurred. We've just solidified + * the count for there. Now convert frompci to the index of btrap() + * for trap handlers and bintr() for interrupt handlers to make + * exceptions appear in the call graph as calls from btrap() and + * bintr() instead of calls from all over. + */ + if ((uintfptr_t)selfpc >= (uintfptr_t)btrap + && (uintfptr_t)selfpc < (uintfptr_t)eintr) { + if ((uintfptr_t)selfpc >= (uintfptr_t)bintr) + frompci = (uintfptr_t)bintr - p->lowpc; + else + frompci = (uintfptr_t)btrap - p->lowpc; + } +#endif + + /* + * check that frompc is a reasonable pc value. + * for example: signal catchers get called from the stack, + * not from text space. too bad. + */ + if (frompci >= p->textsize) + goto done; + + frompcindex = &p->froms[frompci / (p->hashfraction * sizeof(*p->froms))]; + toindex = *frompcindex; + if (toindex == 0) { + /* + * first time traversing this arc + */ + toindex = ++p->tos[0].link; + if (toindex >= p->tolimit) + /* halt further profiling */ + goto overflow; + + *frompcindex = toindex; + top = &p->tos[toindex]; + top->selfpc = selfpc; + top->count = 1; + top->link = 0; + goto done; + } + top = &p->tos[toindex]; + if (top->selfpc == selfpc) { + /* + * arc at front of chain; usual case. + */ + top->count++; + goto done; + } + /* + * have to go looking down chain for it. + * top points to what we are looking at, + * prevtop points to previous top. + * we know it is not at the head of the chain. + */ + for (; /* goto done */; ) { + if (top->link == 0) { + /* + * top is end of the chain and none of the chain + * had top->selfpc == selfpc. + * so we allocate a new tostruct + * and link it to the head of the chain. + */ + toindex = ++p->tos[0].link; + if (toindex >= p->tolimit) + goto overflow; + + top = &p->tos[toindex]; + top->selfpc = selfpc; + top->count = 1; + top->link = *frompcindex; + *frompcindex = toindex; + goto done; + } + /* + * otherwise, check the next arc on the chain. + */ + prevtop = top; + top = &p->tos[top->link]; + if (top->selfpc == selfpc) { + /* + * there it is. + * increment its count + * move it to the head of the chain. + */ + top->count++; + toindex = prevtop->link; + prevtop->link = top->link; + top->link = *frompcindex; + *frompcindex = toindex; + goto done; + } + + } +done: +#ifdef _KERNEL + MCOUNT_EXIT(s); +#else + atomic_store_rel_int(&p->state, GMON_PROF_ON); +#endif + return; +overflow: + atomic_store_rel_int(&p->state, GMON_PROF_ERROR); +#ifdef _KERNEL + MCOUNT_EXIT(s); +#endif + return; +} + +/* + * Actual definition of mcount function. Defined in , + * which is included by . + */ +MCOUNT + +#ifdef GUPROF +void +mexitcount(selfpc) + uintfptr_t selfpc; +{ + struct gmonparam *p; + uintfptr_t selfpcdiff; + + p = &_gmonparam; + selfpcdiff = selfpc - (uintfptr_t)p->lowpc; + if (selfpcdiff < p->textsize) { + u_int delta; + + /* + * Solidify the count for the current function. + */ + delta = cputime() - p->mexitcount_overhead; + p->cputime_overhead_resid += p->cputime_overhead_frac; + p->mexitcount_overhead_resid += p->mexitcount_overhead_frac; + if ((int)delta < 0) + *p->mexitcount_count += delta + p->mexitcount_overhead + - p->cputime_overhead; + else if (delta != 0) { + if (p->cputime_overhead_resid >= CALIB_SCALE) { + p->cputime_overhead_resid -= CALIB_SCALE; + ++*p->cputime_count; + --delta; + } + if (delta != 0) { + if (p->mexitcount_overhead_resid + >= CALIB_SCALE) { + p->mexitcount_overhead_resid + -= CALIB_SCALE; + ++*p->mexitcount_count; + --delta; + } + KCOUNT(p, selfpcdiff) += delta; + } + *p->mexitcount_count += p->mexitcount_overhead_sub; + } + *p->cputime_count += p->cputime_overhead; + } +} +#endif /* GUPROF */ diff --git a/lib/libc/i386/Makefile b/lib/libc/i386/Makefile new file mode 100755 index 0000000..98810a2 --- /dev/null +++ b/lib/libc/i386/Makefile @@ -0,0 +1,20 @@ +# $Id: Makefile 89 2016-01-12 00:20:40Z reddawg $ +# The System Makefile (C) 2002 The UbixOS Project + +all: + (cd gen;make) + (cd net;make) + (cd stdlib;make) + (cd string;make) + (cd sys;make) + (cd syscalls;make) + +# Clean up the junk +clean: + (cd gen;make clean) + (cd net;make clean) + (cd stdlib;make clean) + (cd string;make clean) + (cd sys;make clean) + (cd syscalls;make clean) + diff --git a/lib/libc/i386/Makefile.incl b/lib/libc/i386/Makefile.incl new file mode 100755 index 0000000..eeb7ba5 --- /dev/null +++ b/lib/libc/i386/Makefile.incl @@ -0,0 +1,2 @@ +INCLUDES = -I../../include -I../../../../include.new +CFLAGS += -DPORTMAP -D__DBINTERFACE_PRIVATE -nostdinc #-DPIC diff --git a/lib/libc/i386/SYS.h b/lib/libc/i386/SYS.h new file mode 100644 index 0000000..50589f8 --- /dev/null +++ b/lib/libc/i386/SYS.h @@ -0,0 +1,61 @@ +/*- + * Copyright (c) 1990 The Regents of the University of California. + * All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * William Jolitz. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * @(#)SYS.h 5.5 (Berkeley) 5/7/91 + * $FreeBSD: src/lib/libc/i386/SYS.h,v 1.24 2002/09/17 01:48:51 peter Exp $ + */ + +#include +#include + +#define SYSCALL(x) 2: PIC_PROLOGUE; jmp PIC_PLT(HIDENAME(cerror)); \ + ENTRY(__CONCAT(__sys_,x)); \ + .weak CNAME(x); \ + .set CNAME(x),CNAME(__CONCAT(__sys_,x)); \ + .weak CNAME(__CONCAT(_,x)); \ + .set CNAME(__CONCAT(_,x)),CNAME(__CONCAT(__sys_,x)); \ + mov __CONCAT($SYS_,x),%eax; KERNCALL; jb 2b + +#define RSYSCALL(x) SYSCALL(x); ret + +#define PSEUDO(x) ENTRY(__CONCAT(__sys_,x)); \ + .weak CNAME(__CONCAT(_,x)); \ + .set CNAME(__CONCAT(_,x)),CNAME(__CONCAT(__sys_,x)); \ + mov __CONCAT($SYS_,x),%eax; KERNCALL; ret + +/* gas messes up offset -- although we don't currently need it, do for BCS */ +#define LCALL(x,y) .byte 0x9a ; .long y; .word x + +#define KERNCALL int $0x81 diff --git a/lib/libc/i386/_fpmath.h b/lib/libc/i386/_fpmath.h new file mode 100644 index 0000000..92719d9 --- /dev/null +++ b/lib/libc/i386/_fpmath.h @@ -0,0 +1,49 @@ +/*- + * Copyright (c) 2002, 2003 David Schultz + * 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 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 AUTHOR 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. + * + * $FreeBSD: src/lib/libc/i386/_fpmath.h,v 1.5 2005/03/07 04:55:22 das Exp $ + */ + +union IEEEl2bits { + long double e; + struct { + unsigned int manl :32; + unsigned int manh :32; + unsigned int exp :15; + unsigned int sign :1; + unsigned int junk :16; + } bits; +}; + +#define LDBL_NBIT 0x80000000 +#define mask_nbit_l(u) ((u).bits.manh &= ~LDBL_NBIT) + +#define LDBL_MANH_SIZE 32 +#define LDBL_MANL_SIZE 32 + +#define LDBL_TO_ARRAY32(u, a) do { \ + (a)[0] = (uint32_t)(u).bits.manl; \ + (a)[1] = (uint32_t)(u).bits.manh; \ +} while(0) diff --git a/lib/libc/i386/arith.h b/lib/libc/i386/arith.h new file mode 100644 index 0000000..c55a4df --- /dev/null +++ b/lib/libc/i386/arith.h @@ -0,0 +1,15 @@ +/* + * MD header for contrib/gdtoa + * + * $FreeBSD: src/lib/libc/i386/arith.h,v 1.2 2003/05/08 13:50:43 das Exp $ + */ + +/* + * NOTE: The definitions in this file must be correct or strtod(3) and + * floating point formats in printf(3) will break! The file can be + * generated by running contrib/gdtoa/arithchk.c on the target + * architecture. See contrib/gdtoa/gdtoaimp.h for details. + */ + +#define IEEE_8087 +#define Arith_Kind_ASL 1 diff --git a/lib/libc/i386/gen/Makefile b/lib/libc/i386/gen/Makefile new file mode 100644 index 0000000..7b84a9b --- /dev/null +++ b/lib/libc/i386/gen/Makefile @@ -0,0 +1,37 @@ +# $Id: Makefile 89 2016-01-12 00:20:40Z reddawg $ +# The System Makefile (C) 2002 The UbixOS Project + +# Include Global 'Source' Options +include ../../../../Makefile.incl +include ../../../Makefile.incl +include ../Makefile.incl + +INCLUDES += -I../ + +#Objects +OBJS = _ctx_start.o _set_tp.o _setjmp.o alloca.o fabs.o flt_rounds.o infinity.o ldexp.o makecontext.o modf.o rfork_thread.o setjmp.o signalcontext.o sigsetjmp.o +#Output +OUTPUT = libc.so + +$(OUTPUT): $(OBJS) + +# Compile the source files +.cc.o: + $(CXX) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -c -o $@ $< + +.cc.s: + $(CXX) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -S -o $@ $< + +.c.o: + $(CC) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -c $< + +.c.s: + $(CC) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -S -o $@ $< + +.S.o: + $(CC) $(CFLAGS) -Wall -nostdlib $(INCLUDES) -c -o $@ $< + +# Clean up the junk +clean: + $(REMOVE) $(OBJS) $(OUTPUT) + diff --git a/lib/libc/i386/gen/_ctx_start.S b/lib/libc/i386/gen/_ctx_start.S new file mode 100644 index 0000000..39ec6d8 --- /dev/null +++ b/lib/libc/i386/gen/_ctx_start.S @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2001 Daniel Eischen + * 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. Neither the name of the author 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 AUTHOR 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 AUTHOR 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 +__FBSDID("$FreeBSD: src/lib/libc/i386/gen/_ctx_start.S,v 1.3.8.1 2006/07/05 12:43:13 kib Exp $"); + +/* + * _ctx_start((void *func)(int arg1, ..., argn), + * int arg1, ..., argn, ucontext_t *ucp) + * + * 0(%esp) - func + * 4(%esp) - arg1 + * 8(%esp) - arg2 + * ... + * (4*n)(%esp) - argn + * (4*(n + 1))(%esp) - ucp, %ebp setup to point here (base of stack) + */ +ENTRY(_ctx_start) + popl %eax /* get start function */ + call *%eax /* call start function */ + PIC_PROLOGUE + movl %esi, %esp /* + * setup stack for completion routine; + * ucp is now at top of stack + */ + call PIC_PLT(_ctx_done) /* should never return */ + call PIC_PLT(abort) /* fubar */ + ret diff --git a/lib/libc/i386/gen/_set_tp.c b/lib/libc/i386/gen/_set_tp.c new file mode 100644 index 0000000..9a83fda --- /dev/null +++ b/lib/libc/i386/gen/_set_tp.c @@ -0,0 +1,38 @@ +/*- + * Copyright (c) 2004 Doug Rabson + * 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 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 AUTHOR 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. + * + * $FreeBSD: src/lib/libc/i386/gen/_set_tp.c,v 1.6 2005/06/29 23:15:35 peter Exp $ + */ + +#include +#include +#include + +void +_set_tp(void *tp) +{ + + i386_set_gsbase(tp); +} diff --git a/lib/libc/i386/gen/_setjmp.S b/lib/libc/i386/gen/_setjmp.S new file mode 100644 index 0000000..c2fa562 --- /dev/null +++ b/lib/libc/i386/gen/_setjmp.S @@ -0,0 +1,83 @@ +/*- + * Copyright (c) 1990 The Regents of the University of California. + * All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * William Jolitz. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) + .asciz "@(#)_setjmp.s 5.1 (Berkeley) 4/23/90" +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/i386/gen/_setjmp.S,v 1.16 2002/03/23 02:05:17 obrien Exp $"); + +/* + * C library -- _setjmp, _longjmp + * + * _longjmp(a,v) + * will generate a "return(v)" from the last call to + * _setjmp(a) + * by restoring registers from the environment 'a'. + * The previous signal state is NOT restored. + */ + +ENTRY(_setjmp) + movl 4(%esp),%eax + movl 0(%esp),%edx + movl %edx, 0(%eax) /* rta */ + movl %ebx, 4(%eax) + movl %esp, 8(%eax) + movl %ebp,12(%eax) + movl %esi,16(%eax) + movl %edi,20(%eax) + fnstcw 24(%eax) + xorl %eax,%eax + ret + + .weak CNAME(_longjmp) + .set CNAME(_longjmp),CNAME(___longjmp) +ENTRY(___longjmp) + movl 4(%esp),%edx + movl 8(%esp),%eax + movl 0(%edx),%ecx + movl 4(%edx),%ebx + movl 8(%edx),%esp + movl 12(%edx),%ebp + movl 16(%edx),%esi + movl 20(%edx),%edi + fninit + fldcw 24(%edx) + testl %eax,%eax + jnz 1f + incl %eax +1: movl %ecx,0(%esp) + ret diff --git a/lib/libc/i386/gen/alloca.S b/lib/libc/i386/gen/alloca.S new file mode 100644 index 0000000..dbf6fb8 --- /dev/null +++ b/lib/libc/i386/gen/alloca.S @@ -0,0 +1,62 @@ +/*- + * Copyright (c) 1990 The Regents of the University of California. + * All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * William Jolitz. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if !defined(__GNUC__) && !defined(__INTEL_COMPILER) +#error Please add alloca support for this compiler on FreeBSD. + +#if defined(LIBC_SCCS) && !defined(lint) + .asciz "@(#)alloca.s 5.2 (Berkeley) 5/14/90" +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/i386/gen/alloca.S,v 1.12 2003/06/25 19:06:40 obrien Exp $"); + + +/* like alloc, but automatic automatic free in return */ + +ENTRY(alloca) + popl %edx /* pop return addr */ + popl %eax /* pop amount to allocate */ + movl %esp,%ecx + addl $3,%eax /* round up to next word */ + andl $0xfffffffc,%eax + subl %eax,%esp + movl %esp,%eax /* base of newly allocated space */ + pushl 8(%ecx) /* copy possible saved registers */ + pushl 4(%ecx) + pushl 0(%ecx) + pushl %eax /* dummy to pop at callsite */ + jmp *%edx /* "return" */ +#endif /*!__GNUC__*/ diff --git a/lib/libc/i386/gen/fabs.S b/lib/libc/i386/gen/fabs.S new file mode 100644 index 0000000..4350f18 --- /dev/null +++ b/lib/libc/i386/gen/fabs.S @@ -0,0 +1,46 @@ +/*- + * Copyright (c) 1990 The Regents of the University of California. + * All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * William Jolitz. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) + .asciz "@(#)fabs.s 5.2 (Berkeley) 12/17/90" +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/i386/gen/fabs.S,v 1.9 2002/03/23 02:44:18 obrien Exp $"); + +ENTRY(fabs) + fldl 4(%esp) + fabs + ret diff --git a/lib/libc/i386/gen/flt_rounds.c b/lib/libc/i386/gen/flt_rounds.c new file mode 100644 index 0000000..2856636 --- /dev/null +++ b/lib/libc/i386/gen/flt_rounds.c @@ -0,0 +1,25 @@ +/* + * Written by J.T. Conklin, Apr 10, 1995 + * Public domain. + */ + +#include +__FBSDID("$FreeBSD: src/lib/libc/i386/gen/flt_rounds.c,v 1.1 2004/07/19 08:17:24 das Exp $"); + +#include + +static const int map[] = { + 1, /* round to nearest */ + 3, /* round to zero */ + 2, /* round to negative infinity */ + 0 /* round to positive infinity */ +}; + +int +__flt_rounds(void) +{ + int x; + + __asm("fnstcw %0" : "=m" (x)); + return (map[(x >> 10) & 0x03]); +} diff --git a/lib/libc/i386/gen/infinity.c b/lib/libc/i386/gen/infinity.c new file mode 100644 index 0000000..dd54481 --- /dev/null +++ b/lib/libc/i386/gen/infinity.c @@ -0,0 +1,14 @@ +/* + * infinity.c + */ + +#include +__FBSDID("$FreeBSD: src/lib/libc/i386/gen/infinity.c,v 1.10 2003/02/08 20:37:52 mike Exp $"); + +#include + +/* bytes for +Infinity on a 387 */ +const union __infinity_un __infinity = { { 0, 0, 0, 0, 0, 0, 0xf0, 0x7f } }; + +/* bytes for NaN */ +const union __nan_un __nan = { { 0, 0, 0xc0, 0xff } }; diff --git a/lib/libc/i386/gen/ldexp.c b/lib/libc/i386/gen/ldexp.c new file mode 100644 index 0000000..596c8dc --- /dev/null +++ b/lib/libc/i386/gen/ldexp.c @@ -0,0 +1,66 @@ +/*- + * Copyright (c) 1990, 1993 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * Sean Eric Fagan. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)ldexp.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/i386/gen/ldexp.c,v 1.11 2004/02/16 10:03:02 das Exp $"); + +/* + * ldexp(value, exp): return value * (2 ** exp). + * + * Written by Sean Eric Fagan (sef@kithrup.COM) + * Sun Mar 11 20:27:09 PST 1990 + */ + +/* + * We do the conversion in C to let gcc optimize it away, if possible. + */ +double +ldexp (double value, int exp) +{ + double temp, texp, temp2; + texp = exp; +#ifdef __GNUC__ + __asm ("fscale " + : "=u" (temp2), "=t" (temp) + : "0" (texp), "1" (value)); +#else +#error unknown asm +#endif + return (temp); +} diff --git a/lib/libc/i386/gen/makecontext.c b/lib/libc/i386/gen/makecontext.c new file mode 100644 index 0000000..27e7f73 --- /dev/null +++ b/lib/libc/i386/gen/makecontext.c @@ -0,0 +1,163 @@ +/* + * Copyright (c) 2001 Daniel M. Eischen + * 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. Neither the name of the author 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 AUTHOR 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 AUTHOR 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 +__FBSDID("$FreeBSD: src/lib/libc/i386/gen/makecontext.c,v 1.5 2004/12/05 21:22:08 deischen Exp $"); + +#include +#include +#include + +#include +#include +#include +#include + +/* Prototypes */ +extern void _ctx_start(ucontext_t *, int argc, ...); + + +__weak_reference(__makecontext, makecontext); + +void +_ctx_done (ucontext_t *ucp) +{ + if (ucp->uc_link == NULL) + exit(0); + else { + /* + * Since this context has finished, don't allow it + * to be restarted without being reinitialized (via + * setcontext or swapcontext). + */ + ucp->uc_mcontext.mc_len = 0; + + /* Set context to next one in link */ + /* XXX - what to do for error, abort? */ + setcontext((const ucontext_t *)ucp->uc_link); + abort(); /* should never get here */ + } +} + +void +__makecontext(ucontext_t *ucp, void (*start)(void), int argc, ...) +{ + va_list ap; + char *stack_top; + intptr_t *argp; + int i; + + if (ucp == NULL) + return; + else if ((ucp->uc_stack.ss_sp == NULL) || + (ucp->uc_stack.ss_size < MINSIGSTKSZ)) { + /* + * This should really return -1 with errno set to ENOMEM + * or something, but the spec says that makecontext is + * a void function. At least make sure that the context + * isn't valid so it can't be used without an error. + */ + ucp->uc_mcontext.mc_len = 0; + } + /* XXX - Do we want to sanity check argc? */ + else if ((argc < 0) || (argc > NCARGS)) { + ucp->uc_mcontext.mc_len = 0; + } + /* Make sure the context is valid. */ + else if (ucp->uc_mcontext.mc_len == sizeof(mcontext_t)) { + /* + * Arrange the stack as follows: + * + * _ctx_start() - context start wrapper + * start() - user start routine + * arg1 - first argument, aligned(16) + * ... + * argn + * ucp - this context, %ebp points here + * + * When the context is started, control will return to + * the context start wrapper which will pop the user + * start routine from the top of the stack. After that, + * the top of the stack will be setup with all arguments + * necessary for calling the start routine. When the + * start routine returns, the context wrapper then sets + * the stack pointer to %ebp which was setup to point to + * the base of the stack (and where ucp is stored). It + * will then call _ctx_done() to swap in the next context + * (uc_link != 0) or exit the program (uc_link == 0). + */ + stack_top = (char *)(ucp->uc_stack.ss_sp + + ucp->uc_stack.ss_size - sizeof(intptr_t)); + + /* + * Adjust top of stack to allow for 3 pointers (return + * address, _ctx_start, and ucp) and argc arguments. + * We allow the arguments to be pointers also. The first + * argument to the user function must be properly aligned. + */ + stack_top = stack_top - (sizeof(intptr_t) * (1 + argc)); + stack_top = (char *)((unsigned)stack_top & ~15); + stack_top = stack_top - (2 * sizeof(intptr_t)); + argp = (intptr_t *)stack_top; + + /* + * Setup the top of the stack with the user start routine + * followed by all of its aguments and the pointer to the + * ucontext. We need to leave a spare spot at the top of + * the stack because setcontext will move eip to the top + * of the stack before returning. + */ + *argp = (intptr_t)_ctx_start; /* overwritten with same value */ + argp++; + *argp = (intptr_t)start; + argp++; + + /* Add all the arguments: */ + va_start(ap, argc); + for (i = 0; i < argc; i++) { + *argp = va_arg(ap, intptr_t); + argp++; + } + va_end(ap); + + /* The ucontext is placed at the bottom of the stack. */ + *argp = (intptr_t)ucp; + + /* + * Set the machine context to point to the top of the + * stack and the program counter to the context start + * wrapper. Note that setcontext() pushes the return + * address onto the top of the stack, so allow for this + * by adjusting the stack downward 1 slot. Also set + * %esi to point to the base of the stack where ucp + * is stored. + */ + ucp->uc_mcontext.mc_esi = (int)argp; + ucp->uc_mcontext.mc_ebp = 0; + ucp->uc_mcontext.mc_esp = (int)stack_top + sizeof(caddr_t); + ucp->uc_mcontext.mc_eip = (int)_ctx_start; + } +} diff --git a/lib/libc/i386/gen/modf.S b/lib/libc/i386/gen/modf.S new file mode 100644 index 0000000..de7c96a --- /dev/null +++ b/lib/libc/i386/gen/modf.S @@ -0,0 +1,76 @@ +/*- + * Copyright (c) 1990 The Regents of the University of California. + * All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * Sean Eric Fagan. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) + .asciz "@(#)modf.s 5.5 (Berkeley) 3/18/91" +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/i386/gen/modf.S,v 1.9 2002/03/23 02:05:17 obrien Exp $"); + +/* + * modf(value, iptr): return fractional part of value, and stores the + * integral part into iptr (a pointer to double). + * + * Written by Sean Eric Fagan (sef@kithrup.COM) + * Sun Mar 11 20:27:30 PST 1990 + */ + +/* With CHOP mode on, frndint behaves as TRUNC does. Useful. */ + +ENTRY(modf) + pushl %ebp + movl %esp,%ebp + subl $16,%esp + fnstcw -12(%ebp) + movw -12(%ebp),%dx + orw $3072,%dx + movw %dx,-16(%ebp) + fldcw -16(%ebp) + fldl 8(%ebp) + frndint + fstpl -8(%ebp) + fldcw -12(%ebp) + movl 16(%ebp),%eax + movl -8(%ebp),%edx + movl -4(%ebp),%ecx + movl %edx,(%eax) + movl %ecx,4(%eax) + fldl 8(%ebp) + fsubl -8(%ebp) + jmp L1 +L1: + leave + ret diff --git a/lib/libc/i386/gen/rfork_thread.S b/lib/libc/i386/gen/rfork_thread.S new file mode 100644 index 0000000..04ad549 --- /dev/null +++ b/lib/libc/i386/gen/rfork_thread.S @@ -0,0 +1,117 @@ +/*- + * Copyright (c) 2000 Peter Wemm + * 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 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 AUTHOR 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 +__FBSDID("$FreeBSD: src/lib/libc/i386/gen/rfork_thread.S,v 1.5 2003/05/07 17:23:25 jhb Exp $"); + +/* + * With thanks to John Dyson for the original version of this. + */ + +#include + +/* + * 8 12 16 20 + * rfork_thread(flags, stack_addr, start_fnc, start_arg); + * + * flags: Flags to rfork system call. See rfork(2). + * stack_addr: Top of stack for thread. + * start_fnc: Address of thread function to call in child. + * start_arg: Argument to pass to the thread function in child. + */ + +ENTRY(rfork_thread) + pushl %ebp + movl %esp, %ebp + pushl %esi + + /* + * Push thread info onto the new thread's stack + */ + movl 12(%ebp), %esi # get stack addr + + subl $4, %esi + movl 20(%ebp), %eax # get start argument + movl %eax, (%esi) + + subl $4, %esi + movl 16(%ebp), %eax # get start thread address + movl %eax, (%esi) + + /* + * Prepare and execute the thread creation syscall + */ + pushl 8(%ebp) + pushl $0 + movl $SYS_rfork, %eax + KERNCALL + jb 2f + + /* + * Check to see if we are in the parent or child + */ + cmpl $0, %edx + jnz 1f + addl $8, %esp + popl %esi + movl %ebp, %esp + popl %ebp + ret + .p2align 2 + + /* + * If we are in the child (new thread), then + * set-up the call to the internal subroutine. If it + * returns, then call __exit. + */ +1: + movl %esi,%esp + popl %eax + call *%eax + addl $4, %esp + + /* + * Exit system call + */ + pushl %eax + pushl $0 +#ifdef SYS_exit + movl $SYS_exit, %eax +#else + movl $SYS_sys_exit, %eax +#endif + KERNCALL + + /* + * Branch here if the thread creation fails: + */ +2: + addl $8, %esp + popl %esi + movl %ebp, %esp + popl %ebp + PIC_PROLOGUE + jmp PIC_PLT(HIDENAME(cerror)) diff --git a/lib/libc/i386/gen/setjmp.S b/lib/libc/i386/gen/setjmp.S new file mode 100644 index 0000000..89c2b56 --- /dev/null +++ b/lib/libc/i386/gen/setjmp.S @@ -0,0 +1,103 @@ +/*- + * Copyright (c) 1990 The Regents of the University of California. + * All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * William Jolitz. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) + .asciz "@(#)setjmp.s 5.1 (Berkeley) 4/23/90" +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/i386/gen/setjmp.S,v 1.22 2002/03/23 02:05:17 obrien Exp $"); + +/* + * C library -- _setjmp, _longjmp + * + * longjmp(a,v) + * will generate a "return(v)" from the last call to + * setjmp(a) + * by restoring registers from the environment 'a'. + * The previous signal state is restored. + */ + +#include "SYS.h" + +ENTRY(setjmp) + movl 4(%esp),%ecx + PIC_PROLOGUE + leal 28(%ecx), %eax + pushl %eax /* (sigset_t*)oset */ + pushl $0 /* (sigset_t*)set */ + pushl $1 /* SIG_BLOCK */ + call PIC_PLT(CNAME(_sigprocmask)) + addl $12,%esp + PIC_EPILOGUE + movl 4(%esp),%ecx + movl 0(%esp),%edx + movl %edx, 0(%ecx) + movl %ebx, 4(%ecx) + movl %esp, 8(%ecx) + movl %ebp,12(%ecx) + movl %esi,16(%ecx) + movl %edi,20(%ecx) + fnstcw 24(%ecx) + xorl %eax,%eax + ret + + .weak CNAME(longjmp) + .set CNAME(longjmp),CNAME(__longjmp) +ENTRY(__longjmp) + movl 4(%esp),%edx + PIC_PROLOGUE + pushl $0 /* (sigset_t*)oset */ + leal 28(%edx), %eax + pushl %eax /* (sigset_t*)set */ + pushl $3 /* SIG_SETMASK */ + call PIC_PLT(CNAME(_sigprocmask)) + addl $12,%esp + PIC_EPILOGUE + movl 4(%esp),%edx + movl 8(%esp),%eax + movl 0(%edx),%ecx + movl 4(%edx),%ebx + movl 8(%edx),%esp + movl 12(%edx),%ebp + movl 16(%edx),%esi + movl 20(%edx),%edi + fninit + fldcw 24(%edx) + testl %eax,%eax + jnz 1f + incl %eax +1: movl %ecx,0(%esp) + ret diff --git a/lib/libc/i386/gen/signalcontext.c b/lib/libc/i386/gen/signalcontext.c new file mode 100644 index 0000000..6beb809 --- /dev/null +++ b/lib/libc/i386/gen/signalcontext.c @@ -0,0 +1,79 @@ +/*- + * Copyright (c) 2002 Jonathan Mini + * 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 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 AUTHOR 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 +__FBSDID("$FreeBSD: src/lib/libc/i386/gen/signalcontext.c,v 1.7 2004/07/02 23:20:05 davidxu Exp $"); + +#include +#include +#include +#include +#include +#include + +__weak_reference(__signalcontext, signalcontext); + +extern void _ctx_start(ucontext_t *, int argc, ...); + +int +__signalcontext(ucontext_t *ucp, int sig, __sighandler_t *func) +{ + register_t *p; + struct sigframe *sfp; + + /*- + * Set up stack. + * (n = sizeof(int)) + * 2n+sizeof(struct sigframe) ucp + * 2n struct sigframe + * 1n &func + * 0n &_ctx_start + */ + p = (register_t *)(void *)(intptr_t)ucp->uc_mcontext.mc_esp; + *--p = (register_t)(intptr_t)ucp; + p = (register_t *)((u_register_t)p & ~0xF); /* Align to 16 bytes. */ + p = (register_t *)((u_register_t)p - sizeof(struct sigframe)); + sfp = (struct sigframe *)p; + bzero(sfp, sizeof(struct sigframe)); + sfp->sf_signum = sig; + sfp->sf_siginfo = (register_t)(intptr_t)&sfp->sf_si; + sfp->sf_ucontext = (register_t)(intptr_t)&sfp->sf_uc; + sfp->sf_ahu.sf_action = (__siginfohandler_t *)func; + bcopy(ucp, &sfp->sf_uc, sizeof(ucontext_t)); + sfp->sf_si.si_signo = sig; + *--p = (register_t)(intptr_t)func; + + /* + * Set up ucontext_t. + */ + ucp->uc_mcontext.mc_esi = ucp->uc_mcontext.mc_esp - sizeof(int); + ucp->uc_mcontext.mc_esp = (register_t)(intptr_t)p; + ucp->uc_mcontext.mc_eip = (register_t)(intptr_t)_ctx_start; + ucp->uc_mcontext.mc_eflags &= ~PSL_T; + ucp->uc_link = &sfp->sf_uc; + sigdelset(&ucp->uc_sigmask, sig); + return (0); +} diff --git a/lib/libc/i386/gen/sigsetjmp.S b/lib/libc/i386/gen/sigsetjmp.S new file mode 100644 index 0000000..c5ee63b --- /dev/null +++ b/lib/libc/i386/gen/sigsetjmp.S @@ -0,0 +1,114 @@ +/*- + * Copyright (c) 1990 The Regents of the University of California. + * All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * William Jolitz. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * @(#)setjmp.s 5.1 (Berkeley) 4/23/90" + */ + +#if defined(LIBC_SCCS) && !defined(lint) + .text + .asciz "$Id: sigsetjmp.S 89 2016-01-12 00:20:40Z reddawg $" +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/i386/gen/sigsetjmp.S,v 1.24 2002/03/23 02:05:19 obrien Exp $"); + +#include "SYS.h" + +/*- + * TODO: + * Rename sigsetjmp to __sigsetjmp and siglongjmp to __siglongjmp, + * remove the other *jmp functions and define everything in terms + * of the renamed functions. This requires compiler support for + * the renamed functions (introduced in gcc-2.5.3; previous versions + * only supported *jmp with 0 or 1 leading underscores). + * + * Restore _all_ the registers and the signal mask atomically. Can + * use sigreturn() if sigreturn() works. + */ + +ENTRY(sigsetjmp) + movl 8(%esp),%eax + movl 4(%esp),%ecx + movl %eax,44(%ecx) + testl %eax,%eax + jz 2f + PIC_PROLOGUE + leal 28(%ecx), %eax + pushl %eax /* (sigset_t*)oset */ + pushl $0 /* (sigset_t*)set */ + pushl $1 /* SIG_BLOCK */ + call PIC_PLT(CNAME(_sigprocmask)) + addl $12,%esp + PIC_EPILOGUE + movl 4(%esp),%ecx +2: movl 0(%esp),%edx + movl %edx, 0(%ecx) + movl %ebx, 4(%ecx) + movl %esp, 8(%ecx) + movl %ebp,12(%ecx) + movl %esi,16(%ecx) + movl %edi,20(%ecx) + fnstcw 24(%ecx) + xorl %eax,%eax + ret + + .weak CNAME(siglongjmp); + .set CNAME(siglongjmp),CNAME(__siglongjmp); +ENTRY(__siglongjmp); + movl 4(%esp),%edx + cmpl $0,44(%edx) + jz 2f + PIC_PROLOGUE + pushl $0 /* (sigset_t*)oset */ + leal 28(%edx), %eax + pushl %eax /* (sigset_t*)set */ + pushl $3 /* SIG_SETMASK */ + call PIC_PLT(CNAME(_sigprocmask)) + addl $12,%esp + PIC_EPILOGUE + movl 4(%esp),%edx +2: movl 8(%esp),%eax + movl 0(%edx),%ecx + movl 4(%edx),%ebx + movl 8(%edx),%esp + movl 12(%edx),%ebp + movl 16(%edx),%esi + movl 20(%edx),%edi + fninit + fldcw 24(%edx) + testl %eax,%eax + jnz 1f + incl %eax +1: movl %ecx,0(%esp) + ret diff --git a/lib/libc/i386/net/Makefile b/lib/libc/i386/net/Makefile new file mode 100644 index 0000000..0c19920 --- /dev/null +++ b/lib/libc/i386/net/Makefile @@ -0,0 +1,35 @@ +# $Id: Makefile 89 2016-01-12 00:20:40Z reddawg $ +# The System Makefile (C) 2002 The UbixOS Project + +# Include Global 'Source' Options +include ../../../../Makefile.incl +include ../../../Makefile.incl +include ../Makefile.incl + +INCLUDES += -I../ + +#Objects +OBJS = htonl.o htons.o ntohl.o ntohs.o + +all: $(OBJS) + +# Compile the source files +.cc.o: + $(CXX) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -c -o $@ $< + +.cc.s: + $(CXX) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -S -o $@ $< + +.c.o: + $(CC) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -c $< + +.c.s: + $(CC) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -S -o $@ $< + +.S.o: + $(CC) $(CFLAGS) -Wall -nostdlib $(INCLUDES) -c -o $@ $< + +# Clean up the junk +clean: + $(REMOVE) $(OBJS) + diff --git a/lib/libc/i386/net/htonl.S b/lib/libc/i386/net/htonl.S new file mode 100644 index 0000000..ceeaa91 --- /dev/null +++ b/lib/libc/i386/net/htonl.S @@ -0,0 +1,50 @@ +/*- + * Copyright (c) 1990 The Regents of the University of California. + * All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * William Jolitz. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) + .asciz "@(#)htonl.s 5.3 (Berkeley) 12/17/90" +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/i386/net/htonl.S,v 1.11 2004/11/16 21:01:31 jhb Exp $"); + +/* netorder = htonl(hostorder) */ + + .weak CNAME(htonl) + .set CNAME(htonl),CNAME(__htonl) +ENTRY(__htonl) + movl 4(%esp),%eax + bswap %eax + ret diff --git a/lib/libc/i386/net/htons.S b/lib/libc/i386/net/htons.S new file mode 100644 index 0000000..37b92a6 --- /dev/null +++ b/lib/libc/i386/net/htons.S @@ -0,0 +1,50 @@ +/*- + * Copyright (c) 1990 The Regents of the University of California. + * All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * William Jolitz. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) + .asciz "@(#)htons.s 5.2 (Berkeley) 12/17/90" +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/i386/net/htons.S,v 1.9 2002/03/23 02:06:08 obrien Exp $"); + +/* netorder = htons(hostorder) */ + + .weak CNAME(htons) + .set CNAME(htons),CNAME(__htons) +ENTRY(__htons) + movzwl 4(%esp),%eax + xchgb %al,%ah + ret diff --git a/lib/libc/i386/net/ntohl.S b/lib/libc/i386/net/ntohl.S new file mode 100644 index 0000000..dedcbbb --- /dev/null +++ b/lib/libc/i386/net/ntohl.S @@ -0,0 +1,50 @@ +/*- + * Copyright (c) 1990 The Regents of the University of California. + * All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * William Jolitz. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) + .asciz "@(#)ntohl.s 5.2 (Berkeley) 12/17/90" +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/i386/net/ntohl.S,v 1.11 2004/11/16 21:01:31 jhb Exp $"); + +/* hostorder = ntohl(netorder) */ + + .weak CNAME(ntohl) + .set CNAME(ntohl),CNAME(__ntohl) +ENTRY(__ntohl) + movl 4(%esp),%eax + bswap %eax + ret diff --git a/lib/libc/i386/net/ntohs.S b/lib/libc/i386/net/ntohs.S new file mode 100644 index 0000000..676b3ea --- /dev/null +++ b/lib/libc/i386/net/ntohs.S @@ -0,0 +1,52 @@ +/*- + * Copyright (c) 1990 The Regents of the University of California. + * All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * William Jolitz. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) + .asciz "@(#)ntohs.s 5.2 (Berkeley) 12/17/90" +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/i386/net/ntohs.S,v 1.9 2002/03/23 02:06:08 obrien Exp $"); + +/* hostorder = ntohs(netorder) */ + +#include + + .weak CNAME(ntohs) + .set CNAME(ntohs),CNAME(__ntohs) +ENTRY(__ntohs) + movzwl 4(%esp),%eax + xchgb %al,%ah + ret diff --git a/lib/libc/i386/stdlib/Makefile b/lib/libc/i386/stdlib/Makefile new file mode 100644 index 0000000..6036550 --- /dev/null +++ b/lib/libc/i386/stdlib/Makefile @@ -0,0 +1,35 @@ +# $Id: Makefile 89 2016-01-12 00:20:40Z reddawg $ +# The System Makefile (C) 2002 The UbixOS Project + +# Include Global 'Source' Options +include ../../../../Makefile.incl +include ../../../Makefile.incl +include ../Makefile.incl + +INCLUDES += -I../ + +#Objects +OBJS = abs.o div.o labs.o ldiv.o + +all: $(OBJS) + +# Compile the source files +.cc.o: + $(CXX) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -c -o $@ $< + +.cc.s: + $(CXX) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -S -o $@ $< + +.c.o: + $(CC) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -c $< + +.c.s: + $(CC) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -S -o $@ $< + +.S.o: + $(CC) $(CFLAGS) -Wall -nostdlib $(INCLUDES) -c -o $@ $< + +# Clean up the junk +clean: + $(REMOVE) $(OBJS) + diff --git a/lib/libc/i386/stdlib/abs.S b/lib/libc/i386/stdlib/abs.S new file mode 100644 index 0000000..31d7531 --- /dev/null +++ b/lib/libc/i386/stdlib/abs.S @@ -0,0 +1,50 @@ +/*- + * Copyright (c) 1990 The Regents of the University of California. + * All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * William Jolitz. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) + .text + .asciz "@(#)abs.s 5.2 (Berkeley) 12/17/90" +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/i386/stdlib/abs.S,v 1.9 2002/03/23 02:07:11 obrien Exp $"); + + +ENTRY(abs) + movl 4(%esp),%eax + testl %eax,%eax + jns 1f + negl %eax +1: ret diff --git a/lib/libc/i386/stdlib/div.S b/lib/libc/i386/stdlib/div.S new file mode 100644 index 0000000..383b31f --- /dev/null +++ b/lib/libc/i386/stdlib/div.S @@ -0,0 +1,41 @@ +/* + * Copyright (c) 1993 Winning Strategies, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by Winning Strategies, Inc. + * 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. + */ + +#include +__FBSDID("$FreeBSD: src/lib/libc/i386/stdlib/div.S,v 1.10 2002/12/22 06:41:09 kan Exp $"); + +ENTRY(div) + movl 4(%esp),%eax + movl 8(%esp),%ecx + cdq + idiv %ecx + movl %eax,4(%esp) + movl %edx,8(%esp) + ret diff --git a/lib/libc/i386/stdlib/labs.S b/lib/libc/i386/stdlib/labs.S new file mode 100644 index 0000000..3268520 --- /dev/null +++ b/lib/libc/i386/stdlib/labs.S @@ -0,0 +1,50 @@ +/*- + * Copyright (c) 1990 The Regents of the University of California. + * All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * William Jolitz. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) + .text + .asciz "@(#)abs.s 5.2 (Berkeley) 12/17/90" +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/i386/stdlib/labs.S,v 1.9 2002/03/23 02:07:11 obrien Exp $"); + + +ENTRY(labs) + movl 4(%esp),%eax + testl %eax,%eax + jns 1f + negl %eax +1: ret diff --git a/lib/libc/i386/stdlib/ldiv.S b/lib/libc/i386/stdlib/ldiv.S new file mode 100644 index 0000000..91e132a --- /dev/null +++ b/lib/libc/i386/stdlib/ldiv.S @@ -0,0 +1,41 @@ +/* + * Copyright (c) 1993 Winning Strategies, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by Winning Strategies, Inc. + * 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. + */ + +#include +__FBSDID("$FreeBSD: src/lib/libc/i386/stdlib/ldiv.S,v 1.10 2002/12/22 06:41:09 kan Exp $"); + +ENTRY(ldiv) + movl 4(%esp),%eax + movl 8(%esp),%ecx + cdq + idiv %ecx + movl %eax,4(%esp) + movl %edx,8(%esp) + ret diff --git a/lib/libc/i386/string/Makefile b/lib/libc/i386/string/Makefile new file mode 100644 index 0000000..f9a2878 --- /dev/null +++ b/lib/libc/i386/string/Makefile @@ -0,0 +1,35 @@ +# $Id: Makefile 89 2016-01-12 00:20:40Z reddawg $ +# The System Makefile (C) 2002 The UbixOS Project + +# Include Global 'Source' Options +include ../../../../Makefile.incl +include ../../../Makefile.incl +include ../Makefile.incl + +INCLUDES += -I../ + +#Objects +OBJS = bcmp.o bcopy.o bzero.o ffs.o index.o memchr.o memcmp.o memcpy.o memmove.o memset.o rindex.o strcat.o strchr.o strcmp.o strcpy.o strlen.o strncmp.o strrchr.o swab.o wcschr.o wcscmp.o wcslen.o wmemchr.o + +all: $(OBJS) + +# Compile the source files +.cc.o: + $(CXX) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -c -o $@ $< + +.cc.s: + $(CXX) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -S -o $@ $< + +.c.o: + $(CC) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -c $< + +.c.s: + $(CC) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -S -o $@ $< + +.S.o: + $(CC) $(CFLAGS) -Wall -nostdlib $(INCLUDES) -c -o $@ $< + +# Clean up the junk +clean: + $(REMOVE) $(OBJS) + diff --git a/lib/libc/i386/string/bcmp.S b/lib/libc/i386/string/bcmp.S new file mode 100644 index 0000000..5a09d7b --- /dev/null +++ b/lib/libc/i386/string/bcmp.S @@ -0,0 +1,63 @@ +/* + * Copyright (c) 1993 Winning Strategies, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by Winning Strategies, Inc. + * 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. + */ + +#include +__FBSDID("$FreeBSD: src/lib/libc/i386/string/bcmp.S,v 1.9 2005/04/21 23:07:20 alc Exp $"); + +/* + * bcmp (void *b1, void *b2, size_t len) + * + * Written by: + * J.T. Conklin (jtc@wimsey.com), Winning Strategies, Inc. + */ + +ENTRY(bcmp) + pushl %edi + pushl %esi + movl 12(%esp),%edi + movl 16(%esp),%esi + cld /* set compare direction forward */ + + movl 20(%esp),%ecx /* compare by words */ + shrl $2,%ecx + repe + cmpsl + jne L1 + + movl 20(%esp),%ecx /* compare remainder by bytes */ + andl $3,%ecx + repe + cmpsb +L1: + setne %al + movsbl %al,%eax + popl %esi + popl %edi + ret diff --git a/lib/libc/i386/string/bcopy.S b/lib/libc/i386/string/bcopy.S new file mode 100644 index 0000000..be2f9f4 --- /dev/null +++ b/lib/libc/i386/string/bcopy.S @@ -0,0 +1,103 @@ +/*- + * Copyright (c) 1990 The Regents of the University of California. + * All rights reserved. + * + * This code is derived from locore.s. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#include +__FBSDID("$FreeBSD: src/lib/libc/i386/string/bcopy.S,v 1.10 2002/10/15 09:50:07 sobomax Exp $"); + +#if 0 + RCSID("$NetBSD: bcopy.S,v 1.6 1996/11/12 00:50:06 jtc Exp $") +#endif + + /* + * (ov)bcopy (src,dst,cnt) + * ws@tools.de (Wolfgang Solfrank, TooLs GmbH) +49-228-985800 + */ + +#ifdef MEMCOPY +ENTRY(memcpy) +#else +#ifdef MEMMOVE +ENTRY(memmove) +#else +ENTRY(bcopy) +#endif +#endif + pushl %esi + pushl %edi +#if defined(MEMCOPY) || defined(MEMMOVE) + movl 12(%esp),%edi + movl 16(%esp),%esi + movl %edi,%eax +#else + movl 12(%esp),%esi + movl 16(%esp),%edi +#endif + movl 20(%esp),%ecx + movl %edi,%edx + subl %esi,%edx + cmpl %ecx,%edx /* overlapping? */ + jb 1f + cld /* nope, copy forwards. */ + movl %ecx,%edx + shrl $2,%ecx /* copy by words */ + rep + movsl + movl %edx,%ecx + andl $3,%ecx /* any bytes left? */ + rep + movsb + popl %edi + popl %esi + ret +1: + addl %ecx,%edi /* copy backwards. */ + addl %ecx,%esi + std + movl %ecx,%edx + andl $3,%ecx /* any fractional bytes? */ + decl %edi + decl %esi + rep + movsb + movl %edx,%ecx /* copy remainder by words */ + shrl $2,%ecx + subl $3,%esi + subl $3,%edi + rep + movsl + popl %edi + popl %esi + cld + ret diff --git a/lib/libc/i386/string/bzero.S b/lib/libc/i386/string/bzero.S new file mode 100644 index 0000000..fb84201 --- /dev/null +++ b/lib/libc/i386/string/bzero.S @@ -0,0 +1,81 @@ +/* + * Copyright (c) 1993 Winning Strategies, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by Winning Strategies, Inc. + * 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. + */ + +#include +__FBSDID("$FreeBSD: src/lib/libc/i386/string/bzero.S,v 1.9 2002/06/02 20:05:36 schweikh Exp $"); + +/* + * bzero (void *b, size_t len) + * write len zero bytes to the string b. + * + * Written by: + * J.T. Conklin (jtc@wimsey.com), Winning Strategies, Inc. + */ + +ENTRY(bzero) + pushl %edi + pushl %ebx + movl 12(%esp),%edi + movl 16(%esp),%ecx + + cld /* set fill direction forward */ + xorl %eax,%eax /* set fill data to 0 */ + + /* + * if the string is too short, it's really not worth the overhead + * of aligning to word boundries, etc. So we jump to a plain + * unaligned set. + */ + cmpl $0x0f,%ecx + jle L1 + + movl %edi,%edx /* compute misalignment */ + negl %edx + andl $3,%edx + movl %ecx,%ebx + subl %edx,%ebx + + movl %edx,%ecx /* zero until word aligned */ + rep + stosb + + movl %ebx,%ecx /* zero by words */ + shrl $2,%ecx + rep + stosl + + movl %ebx,%ecx + andl $3,%ecx /* zero remainder by bytes */ +L1: rep + stosb + + popl %ebx + popl %edi + ret diff --git a/lib/libc/i386/string/ffs.S b/lib/libc/i386/string/ffs.S new file mode 100644 index 0000000..b64411d --- /dev/null +++ b/lib/libc/i386/string/ffs.S @@ -0,0 +1,53 @@ +/* + * Copyright (c) 1993 Winning Strategies, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by Winning Strategies, Inc. + * 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. + */ + +#include +__FBSDID("$FreeBSD: src/lib/libc/i386/string/ffs.S,v 1.9 2002/06/02 20:05:37 schweikh Exp $"); + +/* + * ffs(value) + * finds the first bit set in value and returns the index of + * that bit. Bits are numbered starting from 1, starting at the + * rightmost bit. A return value of 0 means that the argument + * was zero. + * + * Written by: + * J.T. Conklin (jtc@wimsey.com), Winning Strategies, Inc. + */ + +ENTRY(ffs) + bsfl 4(%esp),%eax + jz L1 /* ZF is set if all bits are 0 */ + incl %eax /* bits numbered from 1, not 0 */ + ret + + .align 2 +L1: xorl %eax,%eax /* clear result */ + ret diff --git a/lib/libc/i386/string/index.S b/lib/libc/i386/string/index.S new file mode 100644 index 0000000..4bdde08 --- /dev/null +++ b/lib/libc/i386/string/index.S @@ -0,0 +1,63 @@ +/* + * Copyright (c) 1993 Winning Strategies, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by Winning Strategies, Inc. + * 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. + */ + +#include +__FBSDID("$FreeBSD: src/lib/libc/i386/string/index.S,v 1.9 2002/06/02 20:05:37 schweikh Exp $"); + +/* + * index(s, c) + * return a pointer to the first occurance of the character c in + * string s, or NULL if c does not occur in the string. + * + * %edx - pointer iterating through string + * %eax - pointer to first occurance of 'c' + * %cl - character we're comparing against + * %bl - character at %edx + * + * Written by: + * J.T. Conklin (jtc@wimsey.com), Winning Strategies, Inc. + */ + +ENTRY(index) + pushl %ebx + movl 8(%esp),%eax + movb 12(%esp),%cl + .align 2,0x90 +L1: + movb (%eax),%bl + cmpb %bl,%cl /* found char??? */ + je L2 + incl %eax + testb %bl,%bl /* null terminator??? */ + jne L1 + xorl %eax,%eax +L2: + popl %ebx + ret diff --git a/lib/libc/i386/string/memchr.S b/lib/libc/i386/string/memchr.S new file mode 100644 index 0000000..5f4951a --- /dev/null +++ b/lib/libc/i386/string/memchr.S @@ -0,0 +1,58 @@ +/* + * Copyright (c) 1993 Winning Strategies, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by Winning Strategies, Inc. + * 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. + */ + +#include +__FBSDID("$FreeBSD: src/lib/libc/i386/string/memchr.S,v 1.12 2002/06/02 20:05:37 schweikh Exp $"); + +/* + * memchr (b, c, len) + * locates the first occurance of c in string b. + * + * Written by: + * J.T. Conklin (jtc@wimsey.com), Winning Strategies, Inc. + */ + +ENTRY(memchr) + pushl %edi + movl 8(%esp),%edi /* string address */ + movl 12(%esp),%eax /* set character to search for */ + movl 16(%esp),%ecx /* set length of search */ + testl %esp,%esp /* clear Z flag, for len == 0 */ + cld /* set search forward */ + repne /* search! */ + scasb + jnz L1 /* scan failed, return null */ + leal -1(%edi),%eax /* adjust result of scan */ + popl %edi + ret + .align 2,0x90 +L1: xorl %eax,%eax + popl %edi + ret diff --git a/lib/libc/i386/string/memcmp.S b/lib/libc/i386/string/memcmp.S new file mode 100644 index 0000000..27c479c --- /dev/null +++ b/lib/libc/i386/string/memcmp.S @@ -0,0 +1,75 @@ +/* + * Copyright (c) 1993 Winning Strategies, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by Winning Strategies, Inc. + * 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. + */ + +#include +__FBSDID("$FreeBSD: src/lib/libc/i386/string/memcmp.S,v 1.8 2002/03/23 02:44:19 obrien Exp $"); + +/* + * memcmp (void *b1, void *b2, size_t len) + * + * Written by: + * J.T. Conklin (jtc@wimsey.com), Winning Strategies, Inc. + */ + +ENTRY(memcmp) + pushl %edi + pushl %esi + movl 12(%esp),%edi + movl 16(%esp),%esi + cld /* set compare direction forward */ + + movl 20(%esp),%ecx /* compare by words */ + shrl $2,%ecx + repe + cmpsl + jne L5 /* do we match so far? */ + + movl 20(%esp),%ecx /* compare remainder by bytes */ + andl $3,%ecx + repe + cmpsb + jne L6 /* do we match? */ + + xorl %eax,%eax /* we match, return zero */ + popl %esi + popl %edi + ret + +L5: movl $4,%ecx /* We know that one of the next */ + subl %ecx,%edi /* four pairs of bytes do not */ + subl %ecx,%esi /* match. */ + repe + cmpsb +L6: movzbl -1(%edi),%eax /* Perform unsigned comparison */ + movzbl -1(%esi),%edx + subl %edx,%eax + popl %esi + popl %edi + ret diff --git a/lib/libc/i386/string/memcpy.S b/lib/libc/i386/string/memcpy.S new file mode 100644 index 0000000..5102bc7 --- /dev/null +++ b/lib/libc/i386/string/memcpy.S @@ -0,0 +1,5 @@ +#include +__FBSDID("$FreeBSD: src/lib/libc/i386/string/memcpy.S,v 1.2 2002/03/23 02:44:19 obrien Exp $"); + +#define MEMCOPY +#include "bcopy.S" diff --git a/lib/libc/i386/string/memmove.S b/lib/libc/i386/string/memmove.S new file mode 100644 index 0000000..42b5263 --- /dev/null +++ b/lib/libc/i386/string/memmove.S @@ -0,0 +1,5 @@ +#include +__FBSDID("$FreeBSD: src/lib/libc/i386/string/memmove.S,v 1.7 2002/03/23 02:44:19 obrien Exp $"); + +#define MEMMOVE +#include "bcopy.S" diff --git a/lib/libc/i386/string/memset.S b/lib/libc/i386/string/memset.S new file mode 100644 index 0000000..27eca36 --- /dev/null +++ b/lib/libc/i386/string/memset.S @@ -0,0 +1,89 @@ +/* + * Copyright (c) 1993 Winning Strategies, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by Winning Strategies, Inc. + * 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. + */ + +#include +__FBSDID("$FreeBSD: src/lib/libc/i386/string/memset.S,v 1.8 2002/03/23 02:44:19 obrien Exp $"); + +/* + * memset(void *b, int c, size_t len) + * write len bytes of value c (converted to an unsigned char) to + * the string b. + * + * Written by: + * J.T. Conklin (jtc@wimsey.com), Winning Strategies, Inc. + */ + +ENTRY(memset) + pushl %edi + pushl %ebx + movl 12(%esp),%edi + movzbl 16(%esp),%eax /* unsigned char, zero extend */ + movl 20(%esp),%ecx + pushl %edi /* push address of buffer */ + + cld /* set fill direction forward */ + + /* + * if the string is too short, it's really not worth the overhead + * of aligning to word boundries, etc. So we jump to a plain + * unaligned set. + */ + cmpl $0x0f,%ecx + jle L1 + + movb %al,%ah /* copy char to all bytes in word */ + movl %eax,%edx + sall $16,%eax + orl %edx,%eax + + movl %edi,%edx /* compute misalignment */ + negl %edx + andl $3,%edx + movl %ecx,%ebx + subl %edx,%ebx + + movl %edx,%ecx /* set until word aligned */ + rep + stosb + + movl %ebx,%ecx + shrl $2,%ecx /* set by words */ + rep + stosl + + movl %ebx,%ecx /* set remainder by bytes */ + andl $3,%ecx +L1: rep + stosb + + popl %eax /* pop address of buffer */ + popl %ebx + popl %edi + ret diff --git a/lib/libc/i386/string/rindex.S b/lib/libc/i386/string/rindex.S new file mode 100644 index 0000000..c76cf8f --- /dev/null +++ b/lib/libc/i386/string/rindex.S @@ -0,0 +1,64 @@ +/* + * Copyright (c) 1993 Winning Strategies, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by Winning Strategies, Inc. + * 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. + */ + +#include +__FBSDID("$FreeBSD: src/lib/libc/i386/string/rindex.S,v 1.9 2002/06/02 20:05:37 schweikh Exp $"); + +/* + * rindex(s, c) + * return a pointer to the last occurance of the character c in + * string s, or NULL if c does not occur in the string. + * + * %edx - pointer iterating through string + * %eax - pointer to last occurance of 'c' + * %cl - character we're comparing against + * %bl - character at %edx + * + * Written by: + * J.T. Conklin (jtc@wimsey.com), Winning Strategies, Inc. + */ + +ENTRY(rindex) + pushl %ebx + movl 8(%esp),%edx + movb 12(%esp),%cl + xorl %eax,%eax /* init pointer to null */ + .align 2,0x90 +L1: + movb (%edx),%bl + cmpb %bl,%cl + jne L2 + movl %edx,%eax +L2: + incl %edx + testb %bl,%bl /* null terminator??? */ + jne L1 + popl %ebx + ret diff --git a/lib/libc/i386/string/strcat.S b/lib/libc/i386/string/strcat.S new file mode 100644 index 0000000..a175d5b --- /dev/null +++ b/lib/libc/i386/string/strcat.S @@ -0,0 +1,100 @@ +/* + * Copyright (c) 1993 Winning Strategies, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by Winning Strategies, Inc. + * 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. + */ + +#include +__FBSDID("$FreeBSD: src/lib/libc/i386/string/strcat.S,v 1.10 2002/06/02 20:05:37 schweikh Exp $"); + +/* + * strcat(s, append) + * append a copy of the null-terminated string "append" to the end + * of the null-terminated string s, then add a terminating `\0'. + * + * Written by: + * J.T. Conklin (jtc@wimsey.com), Winning Strategies, Inc. + */ + +/* + * I've unrolled the loop eight times: large enough to make a + * significant difference, and small enough not to totally trash the + * cache. + */ + +ENTRY(strcat) + pushl %edi /* save edi */ + movl 8(%esp),%edi /* dst address */ + movl 12(%esp),%edx /* src address */ + pushl %edi /* push destination address */ + + cld /* set search forward */ + xorl %eax,%eax /* set search for null terminator */ + movl $-1,%ecx /* set search for lots of characters */ + repne /* search! */ + scasb + + leal -1(%edi),%ecx /* correct dst address */ + + .align 2,0x90 +L1: movb (%edx),%al /* unroll loop, but not too much */ + movb %al,(%ecx) + testb %al,%al + je L2 + movb 1(%edx),%al + movb %al,1(%ecx) + testb %al,%al + je L2 + movb 2(%edx),%al + movb %al,2(%ecx) + testb %al,%al + je L2 + movb 3(%edx),%al + movb %al,3(%ecx) + testb %al,%al + je L2 + movb 4(%edx),%al + movb %al,4(%ecx) + testb %al,%al + je L2 + movb 5(%edx),%al + movb %al,5(%ecx) + testb %al,%al + je L2 + movb 6(%edx),%al + movb %al,6(%ecx) + testb %al,%al + je L2 + movb 7(%edx),%al + movb %al,7(%ecx) + addl $8,%edx + addl $8,%ecx + testb %al,%al + jne L1 +L2: popl %eax /* pop destination address */ + popl %edi /* restore edi */ + ret diff --git a/lib/libc/i386/string/strchr.S b/lib/libc/i386/string/strchr.S new file mode 100644 index 0000000..87d4fda --- /dev/null +++ b/lib/libc/i386/string/strchr.S @@ -0,0 +1,63 @@ +/* + * Copyright (c) 1993 Winning Strategies, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by Winning Strategies, Inc. + * 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. + */ + +#include +__FBSDID("$FreeBSD: src/lib/libc/i386/string/strchr.S,v 1.9 2002/06/02 20:05:37 schweikh Exp $"); + +/* + * strchr(s, c) + * return a pointer to the first occurance of the character c in + * string s, or NULL if c does not occur in the string. + * + * %edx - pointer iterating through string + * %eax - pointer to first occurance of 'c' + * %cl - character we're comparing against + * %bl - character at %edx + * + * Written by: + * J.T. Conklin (jtc@wimsey.com), Winning Strategies, Inc. + */ + +ENTRY(strchr) + pushl %ebx + movl 8(%esp),%eax + movb 12(%esp),%cl + .align 2,0x90 +L1: + movb (%eax),%bl + cmpb %bl,%cl /* found char??? */ + je L2 + incl %eax + testb %bl,%bl /* null terminator??? */ + jne L1 + xorl %eax,%eax +L2: + popl %ebx + ret diff --git a/lib/libc/i386/string/strcmp.S b/lib/libc/i386/string/strcmp.S new file mode 100644 index 0000000..6e98893 --- /dev/null +++ b/lib/libc/i386/string/strcmp.S @@ -0,0 +1,119 @@ +/* + * Copyright (c) 1993 Winning Strategies, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by Winning Strategies, Inc. + * 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. + */ + +#include +__FBSDID("$FreeBSD: src/lib/libc/i386/string/strcmp.S,v 1.10 2002/06/02 20:05:37 schweikh Exp $"); + +/* + * strcmp(s1, s2) + * return an integer greater than, equal to, or less than 0, + * according as string s1 is greater than, equal to, or less + * than the string s2. + * + * %eax - pointer to s1 + * %edx - pointer to s2 + * + * Written by: + * J.T. Conklin (jtc@wimsey.com), Winning Strategies, Inc. + */ + +/* + * I've unrolled the loop eight times: large enough to make a + * significant difference, and small enough not to totally trash the + * cache. + */ + +ENTRY(strcmp) + movl 0x04(%esp),%eax + movl 0x08(%esp),%edx + jmp L2 /* Jump into the loop! */ + + .align 2,0x90 +L1: incl %eax + incl %edx +L2: movb (%eax),%cl + testb %cl,%cl + je L3 + cmpb %cl,(%edx) + jne L3 + incl %eax + incl %edx + movb (%eax),%cl + testb %cl,%cl + je L3 + cmpb %cl,(%edx) + jne L3 + incl %eax + incl %edx + movb (%eax),%cl + testb %cl,%cl + je L3 + cmpb %cl,(%edx) + jne L3 + incl %eax + incl %edx + movb (%eax),%cl + testb %cl,%cl + je L3 + cmpb %cl,(%edx) + jne L3 + incl %eax + incl %edx + movb (%eax),%cl + testb %cl,%cl + je L3 + cmpb %cl,(%edx) + jne L3 + incl %eax + incl %edx + movb (%eax),%cl + testb %cl,%cl + je L3 + cmpb %cl,(%edx) + jne L3 + incl %eax + incl %edx + movb (%eax),%cl + testb %cl,%cl + je L3 + cmpb %cl,(%edx) + jne L3 + incl %eax + incl %edx + movb (%eax),%cl + testb %cl,%cl + je L3 + cmpb %cl,(%edx) + je L1 + .align 2, 0x90 +L3: movzbl (%eax),%eax /* unsigned comparison */ + movzbl (%edx),%edx + subl %edx,%eax + ret diff --git a/lib/libc/i386/string/strcpy.S b/lib/libc/i386/string/strcpy.S new file mode 100644 index 0000000..237175a --- /dev/null +++ b/lib/libc/i386/string/strcpy.S @@ -0,0 +1,89 @@ +/* + * Copyright (c) 1993 Winning Strategies, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by Winning Strategies, Inc. + * 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. + */ + +#include +__FBSDID("$FreeBSD: src/lib/libc/i386/string/strcpy.S,v 1.10 2002/06/02 20:05:37 schweikh Exp $"); + +/* + * strcpy (dst, src) + * copy the string src to dst. + * + * Written by: + * J.T. Conklin (jtc@wimsey.com), Winning Strategies, Inc. + */ + +/* + * I've unrolled the loop eight times: large enough to make a + * significant difference, and small enough not to totally trash the + * cache. + */ + +ENTRY(strcpy) + movl 4(%esp),%ecx /* dst address */ + movl 8(%esp),%edx /* src address */ + pushl %ecx /* push dst address */ + + .align 2,0x90 +L1: movb (%edx),%al /* unroll loop, but not too much */ + movb %al,(%ecx) + testb %al,%al + je L2 + movb 1(%edx),%al + movb %al,1(%ecx) + testb %al,%al + je L2 + movb 2(%edx),%al + movb %al,2(%ecx) + testb %al,%al + je L2 + movb 3(%edx),%al + movb %al,3(%ecx) + testb %al,%al + je L2 + movb 4(%edx),%al + movb %al,4(%ecx) + testb %al,%al + je L2 + movb 5(%edx),%al + movb %al,5(%ecx) + testb %al,%al + je L2 + movb 6(%edx),%al + movb %al,6(%ecx) + testb %al,%al + je L2 + movb 7(%edx),%al + movb %al,7(%ecx) + addl $8,%edx + addl $8,%ecx + testb %al,%al + jne L1 +L2: popl %eax /* pop dst address */ + ret diff --git a/lib/libc/i386/string/strlen.S b/lib/libc/i386/string/strlen.S new file mode 100644 index 0000000..3f4ee5b --- /dev/null +++ b/lib/libc/i386/string/strlen.S @@ -0,0 +1,53 @@ +/* + * Copyright (c) 1993 Winning Strategies, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by Winning Strategies, Inc. + * 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. + */ + +#include +__FBSDID("$FreeBSD: src/lib/libc/i386/string/strlen.S,v 1.9 2002/06/02 20:05:38 schweikh Exp $"); + +/* + * strlen (s) + * compute the length of the string s. + * + * Written by: + * J.T. Conklin (jtc@wimsey.com), Winning Strategies, Inc. + */ + +ENTRY(strlen) + pushl %edi + movl 8(%esp),%edi /* string address */ + cld /* set search forward */ + xorl %eax,%eax /* set search for null terminator */ + movl $-1,%ecx /* set search for lots of characters */ + repne /* search! */ + scasb + notl %ecx /* get length by taking complement */ + leal -1(%ecx),%eax /* and subtracting one */ + popl %edi + ret diff --git a/lib/libc/i386/string/strncmp.S b/lib/libc/i386/string/strncmp.S new file mode 100644 index 0000000..b6c1648 --- /dev/null +++ b/lib/libc/i386/string/strncmp.S @@ -0,0 +1,166 @@ +/* + * Copyright (c) 1993,94 Winning Strategies, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by Winning Strategies, Inc. + * 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. + */ + +#include +__FBSDID("$FreeBSD: src/lib/libc/i386/string/strncmp.S,v 1.9 2002/03/23 02:44:19 obrien Exp $"); + +/* + * strncmp(s1, s2, n) + * return an integer greater than, equal to, or less than 0, + * according as the first n characters of string s1 is greater + * than, equal to, or less than the string s2. + * + * %eax - pointer to s1 + * %ecx - pointer to s2 + * %edx - length + * + * Written by: + * J.T. Conklin (jtc@wimsey.com), Winning Strategies, Inc. + */ + +/* + * I've unrolled the loop eight times: large enough to make a + * significant difference, and small enough not to totally trash the + * cache. + * + * TODO: change all the jz's back to je for consistency. + */ + +ENTRY(strncmp) + pushl %ebx + movl 8(%esp),%eax + movl 12(%esp),%ecx + movl 16(%esp),%edx + testl %edx,%edx + jmp L2 /* Jump into the loop! */ + + .align 2,0x90 +L1: incl %eax + incl %ecx + decl %edx +L2: jz L4 /* strings are equal */ + movb (%eax),%bl + testb %bl,%bl + jz L3 + cmpb %bl,(%ecx) + jne L3 + +/* + * XXX it might be best to move the next 4 instructions to the end of the + * unrolled part of the loop. The unrolled part would then be + * movb n(%eax),%bl; testb %bl, %bl; je L3; cmpb n(%ecx); jne L3 + * or maybe better + * movb n(%eax),%bl; cmpb n(%ecx); jne L3; testb %bl,%bl; je return_0 + * for n = 0, 1, ..., 8. The end of the loop would be + * L1: addl $8,%eax; addl $8,%ecx; subl $8,%edx; cmpl $8,%edx; jae Lx + * where residual counts of 0 to 7 are handled at Lx. However, this would + * be slower for short strings. Cache effects are probably not so + * important because we are only handling a byte at a time. + */ + incl %eax + incl %ecx + decl %edx + jz L4 + movb (%eax),%bl + testb %bl,%bl + jz L3 + cmpb %bl,(%ecx) + jne L3 + + incl %eax + incl %ecx + decl %edx + jz L4 + movb (%eax),%bl + testb %bl,%bl + jz L3 + cmpb %bl,(%ecx) + jne L3 + + incl %eax + incl %ecx + decl %edx + jz L4 + movb (%eax),%bl + testb %bl,%bl + jz L3 + cmpb %bl,(%ecx) + jne L3 + + incl %eax + incl %ecx + decl %edx + jz L4 + movb (%eax),%bl + testb %bl,%bl + jz L3 + cmpb %bl,(%ecx) + jne L3 + + incl %eax + incl %ecx + decl %edx + jz L4 + movb (%eax),%bl + testb %bl,%bl + jz L3 + cmpb %bl,(%ecx) + jne L3 + + incl %eax + incl %ecx + decl %edx + jz L4 + movb (%eax),%bl + testb %bl,%bl + jz L3 + cmpb %bl,(%ecx) + jne L3 + + incl %eax + incl %ecx + decl %edx + jz L4 + movb (%eax),%bl + testb %bl,%bl + jz L3 + cmpb %bl,(%ecx) + je L1 + + .align 2,0x90 +L3: movzbl (%eax),%eax /* unsigned comparison */ + movzbl (%ecx),%ecx + subl %ecx,%eax + popl %ebx + ret + .align 2,0x90 +L4: xorl %eax,%eax + popl %ebx + ret diff --git a/lib/libc/i386/string/strrchr.S b/lib/libc/i386/string/strrchr.S new file mode 100644 index 0000000..9547d25 --- /dev/null +++ b/lib/libc/i386/string/strrchr.S @@ -0,0 +1,64 @@ +/* + * Copyright (c) 1993 Winning Strategies, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by Winning Strategies, Inc. + * 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. + */ + +#include +__FBSDID("$FreeBSD: src/lib/libc/i386/string/strrchr.S,v 1.9 2002/06/02 20:05:38 schweikh Exp $"); + +/* + * strrchr(s, c) + * return a pointer to the last occurance of the character c in + * string s, or NULL if c does not occur in the string. + * + * %edx - pointer iterating through string + * %eax - pointer to last occurance of 'c' + * %cl - character we're comparing against + * %bl - character at %edx + * + * Written by: + * J.T. Conklin (jtc@wimsey.com), Winning Strategies, Inc. + */ + +ENTRY(strrchr) + pushl %ebx + movl 8(%esp),%edx + movb 12(%esp),%cl + xorl %eax,%eax /* init pointer to null */ + .align 2,0x90 +L1: + movb (%edx),%bl + cmpb %bl,%cl + jne L2 + movl %edx,%eax +L2: + incl %edx + testb %bl,%bl /* null terminator??? */ + jne L1 + popl %ebx + ret diff --git a/lib/libc/i386/string/swab.S b/lib/libc/i386/string/swab.S new file mode 100644 index 0000000..40a48a6 --- /dev/null +++ b/lib/libc/i386/string/swab.S @@ -0,0 +1,99 @@ +/* + * Copyright (c) 1993,94 Winning Strategies, Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by Winning Strategies, Inc. + * 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. + */ + +#include +__FBSDID("$FreeBSD: src/lib/libc/i386/string/swab.S,v 1.9 2003/01/01 18:48:42 schweikh Exp $"); + +/* + * void + * swab (const void *src, void *dst, size_t len) + * copy len bytes from src to dst, swapping adjacent bytes + * + * On the i486, this code is negligibly faster than the code generated + * by gcc at about half the size. If my i386 databook is correct, it + * should be considerably faster than the gcc code on an i386. + * + * Written by: + * J.T. Conklin (jtc@wimsey.com), Winning Strategies, Inc. + */ + +ENTRY(swab) + pushl %esi + pushl %edi + movl 12(%esp),%esi + movl 16(%esp),%edi + movl 20(%esp),%ecx + + cld # set direction forward + + shrl $1,%ecx + testl $7,%ecx # copy first group of 1 to 7 words + jz L2 # while swaping alternate bytes. + .align 2,0x90 +L1: lodsw + rorw $8,%ax + stosw + decl %ecx + testl $7,%ecx + jnz L1 + +L2: shrl $3,%ecx # copy remainder 8 words at a time + jz L4 # while swapping alternate bytes. + .align 2,0x90 +L3: lodsw + rorw $8,%ax + stosw + lodsw + rorw $8,%ax + stosw + lodsw + rorw $8,%ax + stosw + lodsw + rorw $8,%ax + stosw + lodsw + rorw $8,%ax + stosw + lodsw + rorw $8,%ax + stosw + lodsw + rorw $8,%ax + stosw + lodsw + rorw $8,%ax + stosw + decl %ecx + jnz L3 + +L4: popl %edi + popl %esi + ret diff --git a/lib/libc/i386/string/wcschr.S b/lib/libc/i386/string/wcschr.S new file mode 100644 index 0000000..588a68b --- /dev/null +++ b/lib/libc/i386/string/wcschr.S @@ -0,0 +1,76 @@ +/*- + * Copyright (c) 2003 Tim J. Robbins. + * 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 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 AUTHOR 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 +__FBSDID("$FreeBSD: src/lib/libc/i386/string/wcschr.S,v 1.1 2003/04/05 04:17:05 tjr Exp $"); + +/* + * wchar_t * + * wcschr(const wchar_t *s, wchar_t c) -- + * Return pointer to first occurrence of the character `c' in the wide + * character string `s', or NULL if not found. + */ +ENTRY(wcschr) + movl 4(%esp),%ecx /* String */ + movl 8(%esp),%eax /* Character */ + pushl %ebx +.p2align 4,0x90 +L1: movl (%ecx),%ebx + cmpl %eax,%ebx + je found0 + testl %ebx,%ebx + jz no + movl 4(%ecx),%ebx + cmpl %eax,%ebx + je found1 + testl %ebx,%ebx + jz no + movl 8(%ecx),%ebx + cmpl %eax,%ebx + je found2 + testl %ebx,%ebx + jz no + movl 12(%ecx),%ebx + cmpl %eax,%ebx + je found3 + testl %ebx,%ebx + jz no + leal 16(%ecx),%ecx + jmp L1 +.p2align 2,0x90 +found3: leal 4(%ecx),%ecx +.p2align 2,0x90 +found2: leal 4(%ecx),%ecx +.p2align 2,0x90 +found1: leal 4(%ecx),%ecx +.p2align 2,0x90 +found0: popl %ebx + movl %ecx,%eax + ret +.p2align 2,0x90 +no: popl %ebx + xorl %eax,%eax + ret diff --git a/lib/libc/i386/string/wcscmp.S b/lib/libc/i386/string/wcscmp.S new file mode 100644 index 0000000..c609544 --- /dev/null +++ b/lib/libc/i386/string/wcscmp.S @@ -0,0 +1,79 @@ +/*- + * Copyright (c) 2003 Tim J. Robbins. + * 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 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 AUTHOR 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 +__FBSDID("$FreeBSD: src/lib/libc/i386/string/wcscmp.S,v 1.1 2003/03/10 10:54:36 tjr Exp $"); + +/* + * int + * wcscmp(const wchar_t *s1, const wchar_t *s2) -- + * Return an integer greater than, equal to, or less than 0, when + * the string s1 is greater than, equal to, or less than the string s2. + */ +ENTRY(wcscmp) + pushl %edi + pushl %esi + movl 12(%esp),%edi /* s1 */ + movl 16(%esp),%esi /* s2 */ +.p2align 4,0x90 +top: movl (%edi),%eax + cmpl %eax,(%esi) + jne no0 + testl %eax,%eax + jz same + movl 4(%edi),%eax + cmpl %eax,4(%esi) + jne no4 + testl %eax,%eax + jz same + movl 8(%edi),%eax + cmpl %eax,8(%esi) + jne no8 + testl %eax,%eax + jz same + movl 12(%edi),%eax + cmpl %eax,12(%esi) + jne no12 + leal 16(%edi),%edi + leal 16(%esi),%esi + testl %eax,%eax + jnz top +.p2align 2,0x90 +same: xorl %eax,%eax + popl %esi + popl %edi + ret +.p2align 2,0x90 +no12: leal 4(%esi),%esi +.p2align 2,0x90 +no8: leal 4(%esi),%esi +.p2align 2,0x90 +no4: leal 4(%esi),%esi +.p2align 2,0x90 +no0: subl (%esi),%eax + popl %esi + popl %edi + ret diff --git a/lib/libc/i386/string/wcslen.S b/lib/libc/i386/string/wcslen.S new file mode 100644 index 0000000..bb9c380 --- /dev/null +++ b/lib/libc/i386/string/wcslen.S @@ -0,0 +1,68 @@ +/*- + * Copyright (c) 2003 Tim J. Robbins. + * 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 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 AUTHOR 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 +__FBSDID("$FreeBSD: src/lib/libc/i386/string/wcslen.S,v 1.1 2003/03/14 11:01:12 tjr Exp $"); + +/* + * size_t + * wcslen(const wchar_t *s) -- + * Find the length of a wide character string. + */ +ENTRY(wcslen) + movl 4(%esp),%ecx /* String */ + pushl %ebx + xorl %ebx,%ebx + xorl %eax,%eax +.p2align 4,0x90 +L1: cmpl %ebx,(%ecx) + jz found0 + cmpl %ebx,4(%ecx) + jz found1 + cmpl %ebx,8(%ecx) + jz found2 + cmpl %ebx,12(%ecx) + jz found3 + cmpl %ebx,16(%ecx) + jz found4 + cmpl %ebx,20(%ecx) + jz found5 + cmpl %ebx,24(%ecx) + jz found6 + cmpl %ebx,28(%ecx) + jz found7 + leal 32(%ecx),%ecx + addl $8,%eax + jmp L1 +found7: incl %eax +found6: incl %eax +found5: incl %eax +found4: incl %eax +found3: incl %eax +found2: incl %eax +found1: incl %eax +found0: popl %ebx + ret diff --git a/lib/libc/i386/string/wmemchr.S b/lib/libc/i386/string/wmemchr.S new file mode 100644 index 0000000..9e0b41a --- /dev/null +++ b/lib/libc/i386/string/wmemchr.S @@ -0,0 +1,105 @@ +/*- + * Copyright (c) 2003 Tim J. Robbins. + * 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 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 AUTHOR 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 +__FBSDID("$FreeBSD: src/lib/libc/i386/string/wmemchr.S,v 1.2 2003/03/12 06:46:16 tjr Exp $"); + +/* + * wchar_t * + * wmemchr(const wchar_t *buf, wchar_t c, size_t n) -- + * Search the wide character array `buf', which has length `n', + * the character `c', return a pointer to it if found, or NULL on + * failure. + */ +ENTRY(wmemchr) + pushl %edi + pushl %ebx + movl 12(%esp),%edi /* Buffer */ + movl 16(%esp),%eax /* Wide character */ + movl 20(%esp),%ecx /* Length of buffer */ + + /* + * Search in chunks of 8 wide characters (32 bytes). + */ + movl %ecx,%ebx + shrl $3,%ecx + jz small +.p2align 4,0x90 +bigloop:cmpl %eax,(%edi) + je found + cmpl %eax,4(%edi) + je found4 + cmpl %eax,8(%edi) + je found8 + cmpl %eax,12(%edi) + je found12 + cmpl %eax,16(%edi) + je found16 + cmpl %eax,20(%edi) + je found20 + cmpl %eax,24(%edi) + je found24 + cmpl %eax,28(%edi) + je found28 + leal 32(%edi),%edi + decl %ecx + jnz bigloop + jmp small +found: movl %edi,%eax + popl %ebx + popl %edi + ret +found4: leal 4(%edi),%edi + jmp found +found8: leal 8(%edi),%edi + jmp found +found12:leal 12(%edi),%edi + jmp found +found16:leal 16(%edi),%edi + jmp found +found20:leal 20(%edi),%edi + jmp found +found24:leal 24(%edi),%edi + jmp found +found28:leal 28(%edi),%edi + jmp found + + /* + * Search remaining part of string. + */ +small: movl %ebx,%ecx + andl $7,%ecx + jz no +.p2align 2,0x90 +smltop: cmpl %eax,(%edi) + je found + leal 4(%edi),%edi + decl %ecx + jnz smltop +no: xorl %eax,%eax + popl %ebx + popl %edi + ret diff --git a/lib/libc/i386/sys/Makefile b/lib/libc/i386/sys/Makefile new file mode 100644 index 0000000..7ec3776 --- /dev/null +++ b/lib/libc/i386/sys/Makefile @@ -0,0 +1,35 @@ +# $Id: Makefile 89 2016-01-12 00:20:40Z reddawg $ +# The System Makefile (C) 2002 The UbixOS Project + +# Include Global 'Source' Options +include ../../../../Makefile.incl +include ../../../Makefile.incl +include ../Makefile.incl + +INCLUDES += -I../ + +#Objects +OBJS = Ovfork.o brk.o cerror.o exect.o getcontext.o i386_clr_watch.o i386_get_fsbase.o i386_get_gsbase.o i386_get_ioperm.o i386_get_ldt.o i386_set_fsbase.o i386_set_gsbase.o i386_set_ioperm.o i386_set_ldt.o i386_set_watch.o i386_vm86.o pipe.o ptrace.o reboot.o sbrk.o setlogin.o sigreturn.o syscall.o + +all: $(OBJS) + +# Compile the source files +.cc.o: + $(CXX) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -c -o $@ $< + +.cc.s: + $(CXX) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -S -o $@ $< + +.c.o: + $(CC) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -c $< + +.c.s: + $(CC) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -S -o $@ $< + +.S.o: + $(CC) $(CFLAGS) -Wall -nostdlib $(INCLUDES) -c -o $@ $< + +# Clean up the junk +clean: + $(REMOVE) $(OBJS) + diff --git a/lib/libc/i386/sys/Ovfork.S b/lib/libc/i386/sys/Ovfork.S new file mode 100644 index 0000000..a3ce2c9 --- /dev/null +++ b/lib/libc/i386/sys/Ovfork.S @@ -0,0 +1,58 @@ +/*- + * Copyright (c) 1990 The Regents of the University of California. + * All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * William Jolitz. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(SYSLIBC_SCCS) && !defined(lint) + .asciz "@(#)Ovfork.s 5.1 (Berkeley) 4/23/90" +#endif /* SYSLIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/i386/sys/Ovfork.S,v 1.19 2002/03/23 02:10:28 obrien Exp $"); + +#include "SYS.h" + + .weak _vfork + .set _vfork,__sys_vfork + .weak vfork + .set vfork,__sys_vfork +ENTRY(__sys_vfork) + popl %ecx /* my rta into ecx */ + mov $SYS_vfork,%eax + KERNCALL + jb 1f + jmp *%ecx +1: + pushl %ecx + PIC_PROLOGUE + jmp PIC_PLT(HIDENAME(cerror)) diff --git a/lib/libc/i386/sys/brk.S b/lib/libc/i386/sys/brk.S new file mode 100644 index 0000000..1bc5359 --- /dev/null +++ b/lib/libc/i386/sys/brk.S @@ -0,0 +1,90 @@ +/*- + * Copyright (c) 1990 The Regents of the University of California. + * All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * William Jolitz. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(SYSLIBC_SCCS) && !defined(lint) + .asciz "@(#)brk.s 5.2 (Berkeley) 12/17/90" +#endif /* SYSLIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/i386/sys/brk.S,v 1.10 2002/03/23 02:10:28 obrien Exp $"); + +#include "SYS.h" + + .globl HIDENAME(curbrk) + .globl HIDENAME(minbrk) +ENTRY(_brk) + jmp ok + +ENTRY(brk) +#ifdef PIC + movl 4(%esp),%eax + PIC_PROLOGUE + movl PIC_GOT(HIDENAME(curbrk)),%edx # set up GOT addressing + movl PIC_GOT(HIDENAME(minbrk)),%ecx # + PIC_EPILOGUE + cmpl %eax,(%ecx) + jbe ok + movl (%ecx),%eax + movl %eax,4(%esp) +ok: + mov $SYS_break,%eax + KERNCALL + jb err + movl 4(%esp),%eax + movl %eax,(%edx) + movl $0,%eax + ret +err: + PIC_PROLOGUE + jmp PIC_PLT(HIDENAME(cerror)) + +#else + + movl 4(%esp),%eax + cmpl %eax,HIDENAME(minbrk) + jbe ok + movl HIDENAME(minbrk),%eax + movl %eax,4(%esp) +ok: + mov $SYS_break,%eax + KERNCALL + jb err + movl 4(%esp),%eax + movl %eax,HIDENAME(curbrk) + movl $0,%eax + ret +err: + jmp HIDENAME(cerror) +#endif diff --git a/lib/libc/i386/sys/cerror.S b/lib/libc/i386/sys/cerror.S new file mode 100644 index 0000000..5d7248b --- /dev/null +++ b/lib/libc/i386/sys/cerror.S @@ -0,0 +1,69 @@ +/*- + * Copyright (c) 1990 The Regents of the University of California. + * All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * William Jolitz. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(SYSLIBC_SCCS) && !defined(lint) + .asciz "@(#)cerror.s 5.1 (Berkeley) 4/23/90" +#endif /* SYSLIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/i386/sys/cerror.S,v 1.12 2002/03/23 02:10:28 obrien Exp $"); + +#include "SYS.h" + + .globl HIDENAME(cerror) + + /* + * The __error() function is thread aware. For non-threaded + * programs and the initial threaded in threaded programs, + * it returns a pointer to the global errno variable. + */ + .globl CNAME(__error) + .type CNAME(__error),@function +HIDENAME(cerror): + pushl %eax +#ifdef PIC + /* The caller must execute the PIC prologue before jumping to cerror. */ + call PIC_PLT(CNAME(__error)) + popl %ecx + PIC_EPILOGUE +#else + call CNAME(__error) + popl %ecx +#endif + movl %ecx,(%eax) + movl $-1,%eax + movl $-1,%edx + ret + diff --git a/lib/libc/i386/sys/exect.S b/lib/libc/i386/sys/exect.S new file mode 100644 index 0000000..a7a6888 --- /dev/null +++ b/lib/libc/i386/sys/exect.S @@ -0,0 +1,55 @@ +/*- + * Copyright (c) 1990 The Regents of the University of California. + * All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * William Jolitz. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(SYSLIBC_SCCS) && !defined(lint) + .asciz "@(#)exect.s 5.1 (Berkeley) 4/23/90" +#endif /* SYSLIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/i386/sys/exect.S,v 1.9 2002/03/23 02:10:28 obrien Exp $"); + +#include "SYS.h" +#include + +ENTRY(exect) + mov $SYS_execve,%eax + pushf + popl %edx + orl $ PSL_T,%edx + pushl %edx + popf + KERNCALL + PIC_PROLOGUE + jmp PIC_PLT(HIDENAME(cerror)) /* exect(file, argv, env); */ diff --git a/lib/libc/i386/sys/getcontext.S b/lib/libc/i386/sys/getcontext.S new file mode 100644 index 0000000..97f6a01 --- /dev/null +++ b/lib/libc/i386/sys/getcontext.S @@ -0,0 +1,50 @@ +/*- + * Copyright (c) 2003 Peter Wemm + * 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 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 AUTHOR 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 +__FBSDID("$FreeBSD: src/lib/libc/i386/sys/getcontext.S,v 1.1 2003/09/04 00:20:40 peter Exp $"); + +#include + +/* + * This has to be magic to handle the multiple returns. + * Otherwise, the setcontext() syscall will return here and we'll + * pop off the return address and go to the *setcontext* call. + */ + .weak _getcontext + .set _getcontext,__sys_getcontext + .weak getcontext + .set getcontext,__sys_getcontext +ENTRY(__sys_getcontext) + movl (%esp),%ecx /* save getcontext return address */ + mov $SYS_getcontext,%eax + KERNCALL + jb 1f + addl $4,%esp /* remove stale (setcontext) return address */ + jmp *%ecx /* restore return address */ +1: + PIC_PROLOGUE + jmp PIC_PLT(HIDENAME(cerror)) diff --git a/lib/libc/i386/sys/i386_clr_watch.c b/lib/libc/i386/sys/i386_clr_watch.c new file mode 100644 index 0000000..1b0e935 --- /dev/null +++ b/lib/libc/i386/sys/i386_clr_watch.c @@ -0,0 +1,46 @@ +/* + * Copyright 2000 Brian S. Dean + * 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 BRIAN S. DEAN ``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 BRIAN S. DEAN 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 +__FBSDID("$FreeBSD: src/lib/libc/i386/sys/i386_clr_watch.c,v 1.3 2002/10/21 03:47:22 sam Exp $"); + +#include +#include + +int +i386_clr_watch(int watchnum, struct dbreg * d) +{ + + if (watchnum < 0 || watchnum >= 4) + return -1; + + DBREG_DRX(d,7) = DBREG_DRX(d,7) & ~((0x3 << (watchnum*2)) | (0x0f << (watchnum*4+16))); + DBREG_DRX(d,watchnum) = 0; + + return 0; +} diff --git a/lib/libc/i386/sys/i386_get_fsbase.c b/lib/libc/i386/sys/i386_get_fsbase.c new file mode 100644 index 0000000..bc040d7 --- /dev/null +++ b/lib/libc/i386/sys/i386_get_fsbase.c @@ -0,0 +1,37 @@ +/*- + * Copyright (c) 2005 Peter Wemm + * 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 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 AUTHOR 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 +__FBSDID("$FreeBSD: src/lib/libc/i386/sys/i386_get_fsbase.c,v 1.1 2005/04/14 00:01:35 peter Exp $"); + +#include + +int +i386_get_fsbase(void **addr) +{ + + return (sysarch(I386_GET_FSBASE, addr)); +} diff --git a/lib/libc/i386/sys/i386_get_gsbase.c b/lib/libc/i386/sys/i386_get_gsbase.c new file mode 100644 index 0000000..aca5738 --- /dev/null +++ b/lib/libc/i386/sys/i386_get_gsbase.c @@ -0,0 +1,37 @@ +/*- + * Copyright (c) 2005 Peter Wemm + * 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 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 AUTHOR 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 +__FBSDID("$FreeBSD: src/lib/libc/i386/sys/i386_get_gsbase.c,v 1.1 2005/04/14 00:01:35 peter Exp $"); + +#include + +int +i386_get_gsbase(void **addr) +{ + + return (sysarch(I386_GET_GSBASE, addr)); +} diff --git a/lib/libc/i386/sys/i386_get_ioperm.c b/lib/libc/i386/sys/i386_get_ioperm.c new file mode 100644 index 0000000..fb3f48b --- /dev/null +++ b/lib/libc/i386/sys/i386_get_ioperm.c @@ -0,0 +1,48 @@ +/*- + * Copyright (c) 1998 Jonathan Lemon + * 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 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 AUTHOR 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 +__FBSDID("$FreeBSD: src/lib/libc/i386/sys/i386_get_ioperm.c,v 1.8 2004/01/09 16:52:09 nectar Exp $"); + +#include + +int +i386_get_ioperm(unsigned int start, unsigned int *length, int *enable) +{ + struct i386_ioperm_args p; + int error; + + p.start = start; + p.length = *length; + p.enable = *enable; + + error = sysarch(I386_GET_IOPERM, &p); + + *length = p.length; + *enable = p.enable; + + return (error); +} diff --git a/lib/libc/i386/sys/i386_get_ldt.c b/lib/libc/i386/sys/i386_get_ldt.c new file mode 100644 index 0000000..51ac9ef --- /dev/null +++ b/lib/libc/i386/sys/i386_get_ldt.c @@ -0,0 +1,46 @@ +/* + * 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 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. + */ + +#include +__FBSDID("$FreeBSD: src/lib/libc/i386/sys/i386_get_ldt.c,v 1.11 2004/01/09 16:52:09 nectar Exp $"); + +#include +#include +#include + +int +i386_get_ldt(int start, union descriptor *descs, int num) +{ + struct i386_ldt_args p; + + p.start = start; + p.descs = descs; + p.num = num; + + return sysarch(I386_GET_LDT, &p); +} diff --git a/lib/libc/i386/sys/i386_set_fsbase.c b/lib/libc/i386/sys/i386_set_fsbase.c new file mode 100644 index 0000000..733a658 --- /dev/null +++ b/lib/libc/i386/sys/i386_set_fsbase.c @@ -0,0 +1,37 @@ +/*- + * Copyright (c) 2005 Peter Wemm + * 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 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 AUTHOR 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 +__FBSDID("$FreeBSD: src/lib/libc/i386/sys/i386_set_fsbase.c,v 1.1 2005/04/14 00:01:35 peter Exp $"); + +#include + +int +i386_set_fsbase(void *addr) +{ + + return (sysarch(I386_SET_FSBASE, &addr)); +} diff --git a/lib/libc/i386/sys/i386_set_gsbase.c b/lib/libc/i386/sys/i386_set_gsbase.c new file mode 100644 index 0000000..4013e96 --- /dev/null +++ b/lib/libc/i386/sys/i386_set_gsbase.c @@ -0,0 +1,37 @@ +/*- + * Copyright (c) 2005 Peter Wemm + * 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 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 AUTHOR 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 +__FBSDID("$FreeBSD: src/lib/libc/i386/sys/i386_set_gsbase.c,v 1.1 2005/04/14 00:01:35 peter Exp $"); + +#include + +int +i386_set_gsbase(void *addr) +{ + + return (sysarch(I386_SET_GSBASE, &addr)); +} diff --git a/lib/libc/i386/sys/i386_set_ioperm.c b/lib/libc/i386/sys/i386_set_ioperm.c new file mode 100644 index 0000000..cb3f776 --- /dev/null +++ b/lib/libc/i386/sys/i386_set_ioperm.c @@ -0,0 +1,42 @@ +/*- + * Copyright (c) 1998 Jonathan Lemon + * 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 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 AUTHOR 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 +__FBSDID("$FreeBSD: src/lib/libc/i386/sys/i386_set_ioperm.c,v 1.8 2004/01/09 16:52:09 nectar Exp $"); + +#include + +int +i386_set_ioperm(unsigned int start, unsigned int length, int enable) +{ + struct i386_ioperm_args p; + + p.start = start; + p.length = length; + p.enable = enable; + + return (sysarch(I386_SET_IOPERM, &p)); +} diff --git a/lib/libc/i386/sys/i386_set_ldt.c b/lib/libc/i386/sys/i386_set_ldt.c new file mode 100644 index 0000000..df65f9f --- /dev/null +++ b/lib/libc/i386/sys/i386_set_ldt.c @@ -0,0 +1,46 @@ +/* + * 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 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. + */ + +#include +__FBSDID("$FreeBSD: src/lib/libc/i386/sys/i386_set_ldt.c,v 1.11 2004/01/09 16:52:09 nectar Exp $"); + +#include +#include +#include + +int +i386_set_ldt(int start, union descriptor *descs, int num) +{ + struct i386_ldt_args p; + + p.start = start; + p.descs = descs; + p.num = num; + + return sysarch(I386_SET_LDT, &p); +} diff --git a/lib/libc/i386/sys/i386_set_watch.c b/lib/libc/i386/sys/i386_set_watch.c new file mode 100644 index 0000000..325aff7 --- /dev/null +++ b/lib/libc/i386/sys/i386_set_watch.c @@ -0,0 +1,84 @@ +/* + * Copyright 2000 Brian S. Dean + * 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 BRIAN S. DEAN ``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 BRIAN S. DEAN 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 +__FBSDID("$FreeBSD: src/lib/libc/i386/sys/i386_set_watch.c,v 1.3 2002/10/21 03:47:22 sam Exp $"); + +#include +#include + +int +i386_set_watch(int watchnum, unsigned int watchaddr, int size, + int access, struct dbreg * d) +{ + int i; + unsigned int mask; + + if (watchnum == -1) { + for (i = 0, mask = 0x3; i < 4; i++, mask <<= 2) + if ((DBREG_DRX(d,7) & mask) == 0) + break; + if (i < 4) + watchnum = i; + else + return -1; + } + + switch (access) { + case DBREG_DR7_EXEC: + size = 1; /* size must be 1 for an execution breakpoint */ + /* fall through */ + case DBREG_DR7_WRONLY: + case DBREG_DR7_RDWR: + break; + default : return -1; break; + } + + /* + * we can watch a 1, 2, or 4 byte sized location + */ + switch (size) { + case 1 : mask = 0x00; break; + case 2 : mask = 0x01 << 2; break; + case 4 : mask = 0x03 << 2; break; + default : return -1; break; + } + + mask |= access; + + /* clear the bits we are about to affect */ + DBREG_DRX(d,7) &= ~((0x3 << (watchnum*2)) | (0x0f << (watchnum*4+16))); + + /* set drN register to the address, N=watchnum */ + DBREG_DRX(d,watchnum) = watchaddr; + + /* enable the watchpoint */ + DBREG_DRX(d,7) |= (0x2 << (watchnum*2)) | (mask << (watchnum*4+16)); + + return watchnum; +} diff --git a/lib/libc/i386/sys/i386_vm86.c b/lib/libc/i386/sys/i386_vm86.c new file mode 100644 index 0000000..02b3446 --- /dev/null +++ b/lib/libc/i386/sys/i386_vm86.c @@ -0,0 +1,41 @@ +/*- + * Copyright (c) 1998 Jonathan Lemon + * 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 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 AUTHOR 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 +__FBSDID("$FreeBSD: src/lib/libc/i386/sys/i386_vm86.c,v 1.7 2004/01/09 16:52:09 nectar Exp $"); + +#include + +int +i386_vm86(int fcn, void *data) +{ + struct i386_vm86_args p; + + p.sub_op = fcn; + p.sub_args = (char *)data; + + return (sysarch(I386_VM86, &p)); +} diff --git a/lib/libc/i386/sys/pipe.S b/lib/libc/i386/sys/pipe.S new file mode 100644 index 0000000..c6042ca --- /dev/null +++ b/lib/libc/i386/sys/pipe.S @@ -0,0 +1,50 @@ +/*- + * Copyright (c) 1990 The Regents of the University of California. + * All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * William Jolitz. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(SYSLIBC_SCCS) && !defined(lint) + .asciz "@(#)pipe.s 5.1 (Berkeley) 4/23/90" +#endif /* SYSLIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/i386/sys/pipe.S,v 1.11 2002/03/23 02:10:28 obrien Exp $"); + +#include "SYS.h" + +SYSCALL(pipe) + movl 4(%esp),%ecx + movl %eax,(%ecx) + movl %edx,4(%ecx) + movl $0,%eax + ret diff --git a/lib/libc/i386/sys/ptrace.S b/lib/libc/i386/sys/ptrace.S new file mode 100644 index 0000000..fb35a49 --- /dev/null +++ b/lib/libc/i386/sys/ptrace.S @@ -0,0 +1,61 @@ +/*- + * Copyright (c) 1990 The Regents of the University of California. + * All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * William Jolitz. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(SYSLIBC_SCCS) && !defined(lint) + .asciz "@(#)ptrace.s 5.1 (Berkeley) 4/23/90" +#endif /* SYSLIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/i386/sys/ptrace.S,v 1.9 2002/03/23 02:10:28 obrien Exp $"); + +#include "SYS.h" + +ENTRY(ptrace) + xorl %eax,%eax +#ifdef PIC + PIC_PROLOGUE + movl PIC_GOT(CNAME(errno)),%edx + movl %eax,(%edx) + PIC_EPILOGUE +#else + movl %eax,CNAME(errno) +#endif + mov $SYS_ptrace,%eax + KERNCALL + jb err + ret +err: + PIC_PROLOGUE + jmp PIC_PLT(HIDENAME(cerror)) diff --git a/lib/libc/i386/sys/reboot.S b/lib/libc/i386/sys/reboot.S new file mode 100644 index 0000000..11bb985 --- /dev/null +++ b/lib/libc/i386/sys/reboot.S @@ -0,0 +1,46 @@ +/*- + * Copyright (c) 1990 The Regents of the University of California. + * All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * William Jolitz. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(SYSLIBC_SCCS) && !defined(lint) + .asciz "@(#)reboot.s 5.1 (Berkeley) 4/23/90" +#endif /* SYSLIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/i386/sys/reboot.S,v 1.7 2002/03/23 02:10:28 obrien Exp $"); + +#include "SYS.h" + +SYSCALL(reboot) + iret diff --git a/lib/libc/i386/sys/sbrk.S b/lib/libc/i386/sys/sbrk.S new file mode 100644 index 0000000..917e187 --- /dev/null +++ b/lib/libc/i386/sys/sbrk.S @@ -0,0 +1,94 @@ +/*- + * Copyright (c) 1990 The Regents of the University of California. + * All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * William Jolitz. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(SYSLIBC_SCCS) && !defined(lint) + .asciz "@(#)sbrk.s 5.1 (Berkeley) 4/23/90" +#endif /* SYSLIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/i386/sys/sbrk.S,v 1.11 2002/08/08 17:28:07 kan Exp $"); + +#include "SYS.h" + + .globl CNAME(_end) + .globl HIDENAME(minbrk) + .globl HIDENAME(curbrk) + + .data +HIDENAME(minbrk): .long CNAME(_end) +HIDENAME(curbrk): .long CNAME(_end) + .text + +ENTRY(sbrk) +#ifdef PIC + movl 4(%esp),%ecx + PIC_PROLOGUE + movl PIC_GOT(HIDENAME(curbrk)),%edx + movl (%edx),%eax + PIC_EPILOGUE + testl %ecx,%ecx + jz back + addl %eax,4(%esp) + mov $SYS_break,%eax + KERNCALL + jb err + PIC_PROLOGUE + movl PIC_GOT(HIDENAME(curbrk)),%edx + movl (%edx),%eax + addl %ecx,(%edx) + PIC_EPILOGUE +back: + ret +err: + PIC_PROLOGUE + jmp PIC_PLT(HIDENAME(cerror)) + +#else /* !PIC */ + + movl 4(%esp),%ecx + movl HIDENAME(curbrk),%eax + testl %ecx,%ecx + jz back + addl %eax,4(%esp) + mov $SYS_break,%eax + KERNCALL + jb err + movl HIDENAME(curbrk),%eax + addl %ecx,HIDENAME(curbrk) +back: + ret +err: + jmp HIDENAME(cerror) +#endif /* PIC */ diff --git a/lib/libc/i386/sys/setlogin.S b/lib/libc/i386/sys/setlogin.S new file mode 100644 index 0000000..9dfd39e --- /dev/null +++ b/lib/libc/i386/sys/setlogin.S @@ -0,0 +1,58 @@ +/*- + * Copyright (c) 1991 The Regents of the University of California. + * All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * William Jolitz. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) + .asciz "@(#)setlogin.s 5.2 (Berkeley) 4/12/91" +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/i386/sys/setlogin.S,v 1.9 2002/03/23 02:10:28 obrien Exp $"); + +#include "SYS.h" + +.globl CNAME(_logname_valid) /* in _getlogin() */ + +SYSCALL(setlogin) +#ifdef PIC + PIC_PROLOGUE + pushl %eax + movl PIC_GOT(CNAME(_logname_valid)),%eax + movl $0,(%eax) + popl %eax + PIC_EPILOGUE +#else + movl $0,CNAME(_logname_valid) +#endif + ret /* setlogin(name) */ diff --git a/lib/libc/i386/sys/sigreturn.S b/lib/libc/i386/sys/sigreturn.S new file mode 100644 index 0000000..ff705c9 --- /dev/null +++ b/lib/libc/i386/sys/sigreturn.S @@ -0,0 +1,50 @@ +/*- + * Copyright (c) 1990 The Regents of the University of California. + * All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * William Jolitz. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(SYSLIBC_SCCS) && !defined(lint) + .asciz "@(#)sigreturn.s 5.2 (Berkeley) 12/17/90" +#endif /* SYSLIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/i386/sys/sigreturn.S,v 1.12 2002/03/23 02:10:28 obrien Exp $"); + +#include "SYS.h" + +/* + * NOTE: If the profiling ENTRY() code ever changes any registers, they + * must be saved. On FreeBSD, this is not the case. + */ + +RSYSCALL(sigreturn) diff --git a/lib/libc/i386/sys/syscall.S b/lib/libc/i386/sys/syscall.S new file mode 100644 index 0000000..3035e55 --- /dev/null +++ b/lib/libc/i386/sys/syscall.S @@ -0,0 +1,56 @@ +/*- + * Copyright (c) 1990 The Regents of the University of California. + * All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * William Jolitz. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(SYSLIBC_SCCS) && !defined(lint) + .asciz "@(#)syscall.s 5.1 (Berkeley) 4/23/90" +#endif /* SYSLIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/i386/sys/syscall.S,v 1.8 2002/03/23 02:10:28 obrien Exp $"); + +#include "SYS.h" + +ENTRY(syscall) + pop %ecx /* rta */ + pop %eax /* syscall number */ + push %ecx + KERNCALL + push %ecx /* need to push a word to keep stack frame intact + upon return; the word must be the return address. */ + jb 1f + ret +1: + PIC_PROLOGUE + jmp PIC_PLT(HIDENAME(cerror)) diff --git a/lib/libc/i386/syscalls/Makefile b/lib/libc/i386/syscalls/Makefile new file mode 100644 index 0000000..c8abba3 --- /dev/null +++ b/lib/libc/i386/syscalls/Makefile @@ -0,0 +1,35 @@ +# $Id: Makefile 89 2016-01-12 00:20:40Z reddawg $ +# The System Makefile (C) 2002 The UbixOS Project + +# Include Global 'Source' Options +include ../../../../Makefile.incl +include ../../../Makefile.incl +include ../Makefile.incl + +INCLUDES += -I../ + +#Objects +OBJS = __acl_aclcheck_fd.o __acl_aclcheck_file.o __acl_aclcheck_link.o __acl_delete_fd.o __acl_delete_file.o __acl_delete_link.o __acl_get_fd.o __acl_get_file.o __acl_get_link.o __acl_set_fd.o __acl_set_file.o __acl_set_link.o __getcwd.o __mac_execve.o __mac_get_fd.o __mac_get_file.o __mac_get_link.o __mac_get_pid.o __mac_get_proc.o __mac_set_fd.o __mac_set_file.o __mac_set_link.o __mac_set_proc.o __semctl.o __setugid.o __syscall.o __sysctl.o _exit.o _getlogin.o _umtx_lock.o _umtx_op.o _umtx_unlock.o accept.o access.o acct.o adjtime.o aio_cancel.o aio_error.o aio_read.o aio_return.o aio_suspend.o aio_waitcomplete.o aio_write.o audit.o auditctl.o auditon.o bind.o chdir.o chflags.o chmod.o chown.o chroot.o clock_getres.o clock_gettime.o clock_settime.o close.o connect.o dup.o dup2.o eaccess.o execve.o extattr_delete_fd.o extattr_delete_file.o extattr_delete_link.o extattr_get_fd.o extattr_get_file.o extattr_get_link.o extattr_list_fd.o extattr_list_file.o extattr_list_link.o extattr_set_fd.o extattr_set_file.o extattr_set_link.o extattrctl.o fchdir.o fchflags.o fchmod.o fchown.o fcntl.o fhopen.o fhstat.o fhstatfs.o flock.o fork.o fpathconf.o fstat.o fstatfs.o fsync.o futimes.o getaudit.o getaudit_addr.o getauid.o getdents.o getdirentries.o getdtablesize.o getegid.o geteuid.o getfh.o getfsstat.o getgid.o getgroups.o getitimer.o getpeername.o getpgid.o getpgrp.o getpid.o getppid.o getpriority.o getresgid.o getresuid.o getrlimit.o getrusage.o getsid.o getsockname.o getsockopt.o gettimeofday.o getuid.o ioctl.o issetugid.o jail.o jail_attach.o kenv.o kevent.o kill.o kldfind.o kldfirstmod.o kldload.o kldnext.o kldstat.o kldsym.o kldunload.o kldunloadf.o kqueue.o kse_create.o kse_exit.o kse_release.o kse_switchin.o kse_thr_interrupt.o kse_wakeup.o ksem_close.o ksem_destroy.o ksem_getvalue.o ksem_init.o ksem_open.o ksem_post.o ksem_timedwait.o ksem_trywait.o ksem_unlink.o ksem_wait.o ktrace.o lchflags.o lchmod.o lchown.o lgetfh.o link.o lio_listio.o listen.o lstat.o lutimes.o mac_syscall.o madvise.o mincore.o minherit.o mkdir.o mkfifo.o mknod.o mlock.o mlockall.o modfind.o modfnext.o modnext.o modstat.o mount.o mprotect.o msgctl.o msgget.o msgrcv.o msgsnd.o msgsys.o msync.o munlock.o munlockall.o munmap.o nanosleep.o netbsd_lchown.o netbsd_msync.o nfsclnt.o nfssvc.o nfstat.o nlstat.o nmount.o nstat.o ntp_adjtime.o ntp_gettime.o open.o pathconf.o poll.o preadv.o profil.o pwritev.o quotactl.o read.o readlink.o readv.o recvfrom.o recvmsg.o rename.o revoke.o rfork.o rmdir.o rtprio.o sched_get_priority_max.o sched_get_priority_min.o sched_getparam.o sched_getscheduler.o sched_rr_get_interval.o sched_setparam.o sched_setscheduler.o sched_yield.o select.o semget.o semop.o semsys.o sendfile.o sendmsg.o sendto.o setaudit.o setaudit_addr.o setauid.o setcontext.o setegid.o seteuid.o setgid.o setgroups.o setitimer.o setpgid.o setpriority.o setregid.o setresgid.o setresuid.o setreuid.o setrlimit.o setsid.o setsockopt.o settimeofday.o setuid.o shmat.o shmctl.o shmdt.o shmget.o shmsys.o shutdown.o sigaction.o sigaltstack.o sigpending.o sigprocmask.o sigsuspend.o sigtimedwait.o sigwait.o sigwaitinfo.o socket.o socketpair.o stat.o statfs.o swapcontext.o swapoff.o swapon.o symlink.o sync.o sysarch.o thr_create.o thr_exit.o thr_kill.o thr_new.o thr_self.o thr_suspend.o thr_wake.o umask.o undelete.o unlink.o unmount.o utimes.o utrace.o uuidgen.o vadvise.o wait4.o write.o writev.o + +all: $(OBJS) + +# Compile the source files +.cc.o: + $(CXX) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -c -o $@ $< + +.cc.s: + $(CXX) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -S -o $@ $< + +.c.o: + $(CC) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -c $< + +.c.s: + $(CC) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -S -o $@ $< + +.S.o: + $(CC) $(CFLAGS) -Wall -nostdlib $(INCLUDES) -c -o $@ $< + +# Clean up the junk +clean: + $(REMOVE) $(OBJS) + diff --git a/lib/libc/i386/syscalls/__acl_aclcheck_fd.S b/lib/libc/i386/syscalls/__acl_aclcheck_fd.S new file mode 100644 index 0000000..c7c6a9b --- /dev/null +++ b/lib/libc/i386/syscalls/__acl_aclcheck_fd.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(__acl_aclcheck_fd) diff --git a/lib/libc/i386/syscalls/__acl_aclcheck_file.S b/lib/libc/i386/syscalls/__acl_aclcheck_file.S new file mode 100644 index 0000000..b86751f --- /dev/null +++ b/lib/libc/i386/syscalls/__acl_aclcheck_file.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(__acl_aclcheck_file) diff --git a/lib/libc/i386/syscalls/__acl_aclcheck_link.S b/lib/libc/i386/syscalls/__acl_aclcheck_link.S new file mode 100644 index 0000000..0682a61 --- /dev/null +++ b/lib/libc/i386/syscalls/__acl_aclcheck_link.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(__acl_aclcheck_link) diff --git a/lib/libc/i386/syscalls/__acl_delete_fd.S b/lib/libc/i386/syscalls/__acl_delete_fd.S new file mode 100644 index 0000000..bb72292 --- /dev/null +++ b/lib/libc/i386/syscalls/__acl_delete_fd.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(__acl_delete_fd) diff --git a/lib/libc/i386/syscalls/__acl_delete_file.S b/lib/libc/i386/syscalls/__acl_delete_file.S new file mode 100644 index 0000000..e98118a --- /dev/null +++ b/lib/libc/i386/syscalls/__acl_delete_file.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(__acl_delete_file) diff --git a/lib/libc/i386/syscalls/__acl_delete_link.S b/lib/libc/i386/syscalls/__acl_delete_link.S new file mode 100644 index 0000000..c3d7ed6 --- /dev/null +++ b/lib/libc/i386/syscalls/__acl_delete_link.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(__acl_delete_link) diff --git a/lib/libc/i386/syscalls/__acl_get_fd.S b/lib/libc/i386/syscalls/__acl_get_fd.S new file mode 100644 index 0000000..63185d7 --- /dev/null +++ b/lib/libc/i386/syscalls/__acl_get_fd.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(__acl_get_fd) diff --git a/lib/libc/i386/syscalls/__acl_get_file.S b/lib/libc/i386/syscalls/__acl_get_file.S new file mode 100644 index 0000000..97b1369 --- /dev/null +++ b/lib/libc/i386/syscalls/__acl_get_file.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(__acl_get_file) diff --git a/lib/libc/i386/syscalls/__acl_get_link.S b/lib/libc/i386/syscalls/__acl_get_link.S new file mode 100644 index 0000000..f36ebba --- /dev/null +++ b/lib/libc/i386/syscalls/__acl_get_link.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(__acl_get_link) diff --git a/lib/libc/i386/syscalls/__acl_set_fd.S b/lib/libc/i386/syscalls/__acl_set_fd.S new file mode 100644 index 0000000..248e9e5 --- /dev/null +++ b/lib/libc/i386/syscalls/__acl_set_fd.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(__acl_set_fd) diff --git a/lib/libc/i386/syscalls/__acl_set_file.S b/lib/libc/i386/syscalls/__acl_set_file.S new file mode 100644 index 0000000..d93d185 --- /dev/null +++ b/lib/libc/i386/syscalls/__acl_set_file.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(__acl_set_file) diff --git a/lib/libc/i386/syscalls/__acl_set_link.S b/lib/libc/i386/syscalls/__acl_set_link.S new file mode 100644 index 0000000..3b58db1 --- /dev/null +++ b/lib/libc/i386/syscalls/__acl_set_link.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(__acl_set_link) diff --git a/lib/libc/i386/syscalls/__getcwd.S b/lib/libc/i386/syscalls/__getcwd.S new file mode 100644 index 0000000..77c06a6 --- /dev/null +++ b/lib/libc/i386/syscalls/__getcwd.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(__getcwd) diff --git a/lib/libc/i386/syscalls/__mac_execve.S b/lib/libc/i386/syscalls/__mac_execve.S new file mode 100644 index 0000000..0b63225 --- /dev/null +++ b/lib/libc/i386/syscalls/__mac_execve.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(__mac_execve) diff --git a/lib/libc/i386/syscalls/__mac_get_fd.S b/lib/libc/i386/syscalls/__mac_get_fd.S new file mode 100644 index 0000000..699471b --- /dev/null +++ b/lib/libc/i386/syscalls/__mac_get_fd.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(__mac_get_fd) diff --git a/lib/libc/i386/syscalls/__mac_get_file.S b/lib/libc/i386/syscalls/__mac_get_file.S new file mode 100644 index 0000000..c0a5ef1 --- /dev/null +++ b/lib/libc/i386/syscalls/__mac_get_file.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(__mac_get_file) diff --git a/lib/libc/i386/syscalls/__mac_get_link.S b/lib/libc/i386/syscalls/__mac_get_link.S new file mode 100644 index 0000000..47447a3 --- /dev/null +++ b/lib/libc/i386/syscalls/__mac_get_link.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(__mac_get_link) diff --git a/lib/libc/i386/syscalls/__mac_get_pid.S b/lib/libc/i386/syscalls/__mac_get_pid.S new file mode 100644 index 0000000..0773f6f --- /dev/null +++ b/lib/libc/i386/syscalls/__mac_get_pid.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(__mac_get_pid) diff --git a/lib/libc/i386/syscalls/__mac_get_proc.S b/lib/libc/i386/syscalls/__mac_get_proc.S new file mode 100644 index 0000000..f137643 --- /dev/null +++ b/lib/libc/i386/syscalls/__mac_get_proc.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(__mac_get_proc) diff --git a/lib/libc/i386/syscalls/__mac_set_fd.S b/lib/libc/i386/syscalls/__mac_set_fd.S new file mode 100644 index 0000000..be55370 --- /dev/null +++ b/lib/libc/i386/syscalls/__mac_set_fd.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(__mac_set_fd) diff --git a/lib/libc/i386/syscalls/__mac_set_file.S b/lib/libc/i386/syscalls/__mac_set_file.S new file mode 100644 index 0000000..37f6dc4 --- /dev/null +++ b/lib/libc/i386/syscalls/__mac_set_file.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(__mac_set_file) diff --git a/lib/libc/i386/syscalls/__mac_set_link.S b/lib/libc/i386/syscalls/__mac_set_link.S new file mode 100644 index 0000000..e82b229 --- /dev/null +++ b/lib/libc/i386/syscalls/__mac_set_link.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(__mac_set_link) diff --git a/lib/libc/i386/syscalls/__mac_set_proc.S b/lib/libc/i386/syscalls/__mac_set_proc.S new file mode 100644 index 0000000..5720ff9 --- /dev/null +++ b/lib/libc/i386/syscalls/__mac_set_proc.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(__mac_set_proc) diff --git a/lib/libc/i386/syscalls/__semctl.S b/lib/libc/i386/syscalls/__semctl.S new file mode 100644 index 0000000..585cb40 --- /dev/null +++ b/lib/libc/i386/syscalls/__semctl.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(__semctl) diff --git a/lib/libc/i386/syscalls/__setugid.S b/lib/libc/i386/syscalls/__setugid.S new file mode 100644 index 0000000..6a21306 --- /dev/null +++ b/lib/libc/i386/syscalls/__setugid.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(__setugid) diff --git a/lib/libc/i386/syscalls/__syscall.S b/lib/libc/i386/syscalls/__syscall.S new file mode 100644 index 0000000..31b08ba --- /dev/null +++ b/lib/libc/i386/syscalls/__syscall.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(__syscall) diff --git a/lib/libc/i386/syscalls/__sysctl.S b/lib/libc/i386/syscalls/__sysctl.S new file mode 100644 index 0000000..a44409c --- /dev/null +++ b/lib/libc/i386/syscalls/__sysctl.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(__sysctl) diff --git a/lib/libc/i386/syscalls/_exit.S b/lib/libc/i386/syscalls/_exit.S new file mode 100644 index 0000000..aaff187 --- /dev/null +++ b/lib/libc/i386/syscalls/_exit.S @@ -0,0 +1,2 @@ +#include "SYS.h" +PSEUDO(exit) diff --git a/lib/libc/i386/syscalls/_getlogin.S b/lib/libc/i386/syscalls/_getlogin.S new file mode 100644 index 0000000..9e260f9 --- /dev/null +++ b/lib/libc/i386/syscalls/_getlogin.S @@ -0,0 +1,2 @@ +#include "SYS.h" +PSEUDO(getlogin) diff --git a/lib/libc/i386/syscalls/_umtx_lock.S b/lib/libc/i386/syscalls/_umtx_lock.S new file mode 100644 index 0000000..ce7f6b0 --- /dev/null +++ b/lib/libc/i386/syscalls/_umtx_lock.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(_umtx_lock) diff --git a/lib/libc/i386/syscalls/_umtx_op.S b/lib/libc/i386/syscalls/_umtx_op.S new file mode 100644 index 0000000..1a05bc4 --- /dev/null +++ b/lib/libc/i386/syscalls/_umtx_op.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(_umtx_op) diff --git a/lib/libc/i386/syscalls/_umtx_unlock.S b/lib/libc/i386/syscalls/_umtx_unlock.S new file mode 100644 index 0000000..dcfb0d2 --- /dev/null +++ b/lib/libc/i386/syscalls/_umtx_unlock.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(_umtx_unlock) diff --git a/lib/libc/i386/syscalls/accept.S b/lib/libc/i386/syscalls/accept.S new file mode 100644 index 0000000..d1248bc --- /dev/null +++ b/lib/libc/i386/syscalls/accept.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(accept) diff --git a/lib/libc/i386/syscalls/access.S b/lib/libc/i386/syscalls/access.S new file mode 100644 index 0000000..f7edd1e --- /dev/null +++ b/lib/libc/i386/syscalls/access.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(access) diff --git a/lib/libc/i386/syscalls/acct.S b/lib/libc/i386/syscalls/acct.S new file mode 100644 index 0000000..56c8653 --- /dev/null +++ b/lib/libc/i386/syscalls/acct.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(acct) diff --git a/lib/libc/i386/syscalls/adjtime.S b/lib/libc/i386/syscalls/adjtime.S new file mode 100644 index 0000000..b6d8c0f --- /dev/null +++ b/lib/libc/i386/syscalls/adjtime.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(adjtime) diff --git a/lib/libc/i386/syscalls/aio_cancel.S b/lib/libc/i386/syscalls/aio_cancel.S new file mode 100644 index 0000000..48f8f09 --- /dev/null +++ b/lib/libc/i386/syscalls/aio_cancel.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(aio_cancel) diff --git a/lib/libc/i386/syscalls/aio_error.S b/lib/libc/i386/syscalls/aio_error.S new file mode 100644 index 0000000..9a6e5d2 --- /dev/null +++ b/lib/libc/i386/syscalls/aio_error.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(aio_error) diff --git a/lib/libc/i386/syscalls/aio_read.S b/lib/libc/i386/syscalls/aio_read.S new file mode 100644 index 0000000..46e0b32 --- /dev/null +++ b/lib/libc/i386/syscalls/aio_read.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(aio_read) diff --git a/lib/libc/i386/syscalls/aio_return.S b/lib/libc/i386/syscalls/aio_return.S new file mode 100644 index 0000000..2b28b2c --- /dev/null +++ b/lib/libc/i386/syscalls/aio_return.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(aio_return) diff --git a/lib/libc/i386/syscalls/aio_suspend.S b/lib/libc/i386/syscalls/aio_suspend.S new file mode 100644 index 0000000..119bf4c --- /dev/null +++ b/lib/libc/i386/syscalls/aio_suspend.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(aio_suspend) diff --git a/lib/libc/i386/syscalls/aio_waitcomplete.S b/lib/libc/i386/syscalls/aio_waitcomplete.S new file mode 100644 index 0000000..b340a4c --- /dev/null +++ b/lib/libc/i386/syscalls/aio_waitcomplete.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(aio_waitcomplete) diff --git a/lib/libc/i386/syscalls/aio_write.S b/lib/libc/i386/syscalls/aio_write.S new file mode 100644 index 0000000..13484bc --- /dev/null +++ b/lib/libc/i386/syscalls/aio_write.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(aio_write) diff --git a/lib/libc/i386/syscalls/audit.S b/lib/libc/i386/syscalls/audit.S new file mode 100644 index 0000000..da2c4bd --- /dev/null +++ b/lib/libc/i386/syscalls/audit.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(audit) diff --git a/lib/libc/i386/syscalls/auditctl.S b/lib/libc/i386/syscalls/auditctl.S new file mode 100644 index 0000000..ae0cf2f --- /dev/null +++ b/lib/libc/i386/syscalls/auditctl.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(auditctl) diff --git a/lib/libc/i386/syscalls/auditon.S b/lib/libc/i386/syscalls/auditon.S new file mode 100644 index 0000000..ba4f726 --- /dev/null +++ b/lib/libc/i386/syscalls/auditon.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(auditon) diff --git a/lib/libc/i386/syscalls/bind.S b/lib/libc/i386/syscalls/bind.S new file mode 100644 index 0000000..c2602ad --- /dev/null +++ b/lib/libc/i386/syscalls/bind.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(bind) diff --git a/lib/libc/i386/syscalls/chdir.S b/lib/libc/i386/syscalls/chdir.S new file mode 100644 index 0000000..a654a24 --- /dev/null +++ b/lib/libc/i386/syscalls/chdir.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(chdir) diff --git a/lib/libc/i386/syscalls/chflags.S b/lib/libc/i386/syscalls/chflags.S new file mode 100644 index 0000000..ca2a2f5 --- /dev/null +++ b/lib/libc/i386/syscalls/chflags.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(chflags) diff --git a/lib/libc/i386/syscalls/chmod.S b/lib/libc/i386/syscalls/chmod.S new file mode 100644 index 0000000..151628e --- /dev/null +++ b/lib/libc/i386/syscalls/chmod.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(chmod) diff --git a/lib/libc/i386/syscalls/chown.S b/lib/libc/i386/syscalls/chown.S new file mode 100644 index 0000000..87b071b --- /dev/null +++ b/lib/libc/i386/syscalls/chown.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(chown) diff --git a/lib/libc/i386/syscalls/chroot.S b/lib/libc/i386/syscalls/chroot.S new file mode 100644 index 0000000..09aabdf --- /dev/null +++ b/lib/libc/i386/syscalls/chroot.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(chroot) diff --git a/lib/libc/i386/syscalls/clock_getres.S b/lib/libc/i386/syscalls/clock_getres.S new file mode 100644 index 0000000..c329b93 --- /dev/null +++ b/lib/libc/i386/syscalls/clock_getres.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(clock_getres) diff --git a/lib/libc/i386/syscalls/clock_gettime.S b/lib/libc/i386/syscalls/clock_gettime.S new file mode 100644 index 0000000..ba27b14 --- /dev/null +++ b/lib/libc/i386/syscalls/clock_gettime.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(clock_gettime) diff --git a/lib/libc/i386/syscalls/clock_settime.S b/lib/libc/i386/syscalls/clock_settime.S new file mode 100644 index 0000000..f5a7fb7 --- /dev/null +++ b/lib/libc/i386/syscalls/clock_settime.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(clock_settime) diff --git a/lib/libc/i386/syscalls/close.S b/lib/libc/i386/syscalls/close.S new file mode 100644 index 0000000..70f8240 --- /dev/null +++ b/lib/libc/i386/syscalls/close.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(close) diff --git a/lib/libc/i386/syscalls/connect.S b/lib/libc/i386/syscalls/connect.S new file mode 100644 index 0000000..35ee704 --- /dev/null +++ b/lib/libc/i386/syscalls/connect.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(connect) diff --git a/lib/libc/i386/syscalls/dup.S b/lib/libc/i386/syscalls/dup.S new file mode 100644 index 0000000..d30d954 --- /dev/null +++ b/lib/libc/i386/syscalls/dup.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(dup) diff --git a/lib/libc/i386/syscalls/dup2.S b/lib/libc/i386/syscalls/dup2.S new file mode 100644 index 0000000..64faa8a --- /dev/null +++ b/lib/libc/i386/syscalls/dup2.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(dup2) diff --git a/lib/libc/i386/syscalls/eaccess.S b/lib/libc/i386/syscalls/eaccess.S new file mode 100644 index 0000000..92da4b5 --- /dev/null +++ b/lib/libc/i386/syscalls/eaccess.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(eaccess) diff --git a/lib/libc/i386/syscalls/execve.S b/lib/libc/i386/syscalls/execve.S new file mode 100644 index 0000000..ef93f01 --- /dev/null +++ b/lib/libc/i386/syscalls/execve.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(execve) diff --git a/lib/libc/i386/syscalls/extattr_delete_fd.S b/lib/libc/i386/syscalls/extattr_delete_fd.S new file mode 100644 index 0000000..7c5857c --- /dev/null +++ b/lib/libc/i386/syscalls/extattr_delete_fd.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(extattr_delete_fd) diff --git a/lib/libc/i386/syscalls/extattr_delete_file.S b/lib/libc/i386/syscalls/extattr_delete_file.S new file mode 100644 index 0000000..6526d69 --- /dev/null +++ b/lib/libc/i386/syscalls/extattr_delete_file.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(extattr_delete_file) diff --git a/lib/libc/i386/syscalls/extattr_delete_link.S b/lib/libc/i386/syscalls/extattr_delete_link.S new file mode 100644 index 0000000..cf93bde --- /dev/null +++ b/lib/libc/i386/syscalls/extattr_delete_link.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(extattr_delete_link) diff --git a/lib/libc/i386/syscalls/extattr_get_fd.S b/lib/libc/i386/syscalls/extattr_get_fd.S new file mode 100644 index 0000000..5fe4202 --- /dev/null +++ b/lib/libc/i386/syscalls/extattr_get_fd.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(extattr_get_fd) diff --git a/lib/libc/i386/syscalls/extattr_get_file.S b/lib/libc/i386/syscalls/extattr_get_file.S new file mode 100644 index 0000000..6014d2f --- /dev/null +++ b/lib/libc/i386/syscalls/extattr_get_file.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(extattr_get_file) diff --git a/lib/libc/i386/syscalls/extattr_get_link.S b/lib/libc/i386/syscalls/extattr_get_link.S new file mode 100644 index 0000000..24b0e15 --- /dev/null +++ b/lib/libc/i386/syscalls/extattr_get_link.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(extattr_get_link) diff --git a/lib/libc/i386/syscalls/extattr_list_fd.S b/lib/libc/i386/syscalls/extattr_list_fd.S new file mode 100644 index 0000000..28e0eb2 --- /dev/null +++ b/lib/libc/i386/syscalls/extattr_list_fd.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(extattr_list_fd) diff --git a/lib/libc/i386/syscalls/extattr_list_file.S b/lib/libc/i386/syscalls/extattr_list_file.S new file mode 100644 index 0000000..7d298bc --- /dev/null +++ b/lib/libc/i386/syscalls/extattr_list_file.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(extattr_list_file) diff --git a/lib/libc/i386/syscalls/extattr_list_link.S b/lib/libc/i386/syscalls/extattr_list_link.S new file mode 100644 index 0000000..e687f85 --- /dev/null +++ b/lib/libc/i386/syscalls/extattr_list_link.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(extattr_list_link) diff --git a/lib/libc/i386/syscalls/extattr_set_fd.S b/lib/libc/i386/syscalls/extattr_set_fd.S new file mode 100644 index 0000000..7fe77cb --- /dev/null +++ b/lib/libc/i386/syscalls/extattr_set_fd.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(extattr_set_fd) diff --git a/lib/libc/i386/syscalls/extattr_set_file.S b/lib/libc/i386/syscalls/extattr_set_file.S new file mode 100644 index 0000000..ce26532 --- /dev/null +++ b/lib/libc/i386/syscalls/extattr_set_file.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(extattr_set_file) diff --git a/lib/libc/i386/syscalls/extattr_set_link.S b/lib/libc/i386/syscalls/extattr_set_link.S new file mode 100644 index 0000000..c6d316e --- /dev/null +++ b/lib/libc/i386/syscalls/extattr_set_link.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(extattr_set_link) diff --git a/lib/libc/i386/syscalls/extattrctl.S b/lib/libc/i386/syscalls/extattrctl.S new file mode 100644 index 0000000..add5285 --- /dev/null +++ b/lib/libc/i386/syscalls/extattrctl.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(extattrctl) diff --git a/lib/libc/i386/syscalls/fchdir.S b/lib/libc/i386/syscalls/fchdir.S new file mode 100644 index 0000000..73c19ca --- /dev/null +++ b/lib/libc/i386/syscalls/fchdir.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(fchdir) diff --git a/lib/libc/i386/syscalls/fchflags.S b/lib/libc/i386/syscalls/fchflags.S new file mode 100644 index 0000000..a871f3a --- /dev/null +++ b/lib/libc/i386/syscalls/fchflags.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(fchflags) diff --git a/lib/libc/i386/syscalls/fchmod.S b/lib/libc/i386/syscalls/fchmod.S new file mode 100644 index 0000000..6b745f6 --- /dev/null +++ b/lib/libc/i386/syscalls/fchmod.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(fchmod) diff --git a/lib/libc/i386/syscalls/fchown.S b/lib/libc/i386/syscalls/fchown.S new file mode 100644 index 0000000..d2aa42f --- /dev/null +++ b/lib/libc/i386/syscalls/fchown.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(fchown) diff --git a/lib/libc/i386/syscalls/fcntl.S b/lib/libc/i386/syscalls/fcntl.S new file mode 100644 index 0000000..f4b358f --- /dev/null +++ b/lib/libc/i386/syscalls/fcntl.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(fcntl) diff --git a/lib/libc/i386/syscalls/fhopen.S b/lib/libc/i386/syscalls/fhopen.S new file mode 100644 index 0000000..2a75704 --- /dev/null +++ b/lib/libc/i386/syscalls/fhopen.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(fhopen) diff --git a/lib/libc/i386/syscalls/fhstat.S b/lib/libc/i386/syscalls/fhstat.S new file mode 100644 index 0000000..4a3b4fd --- /dev/null +++ b/lib/libc/i386/syscalls/fhstat.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(fhstat) diff --git a/lib/libc/i386/syscalls/fhstatfs.S b/lib/libc/i386/syscalls/fhstatfs.S new file mode 100644 index 0000000..2b75ba7 --- /dev/null +++ b/lib/libc/i386/syscalls/fhstatfs.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(fhstatfs) diff --git a/lib/libc/i386/syscalls/flock.S b/lib/libc/i386/syscalls/flock.S new file mode 100644 index 0000000..a316d0c --- /dev/null +++ b/lib/libc/i386/syscalls/flock.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(flock) diff --git a/lib/libc/i386/syscalls/fork.S b/lib/libc/i386/syscalls/fork.S new file mode 100644 index 0000000..377d3dc --- /dev/null +++ b/lib/libc/i386/syscalls/fork.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(fork) diff --git a/lib/libc/i386/syscalls/fpathconf.S b/lib/libc/i386/syscalls/fpathconf.S new file mode 100644 index 0000000..0c72b52 --- /dev/null +++ b/lib/libc/i386/syscalls/fpathconf.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(fpathconf) diff --git a/lib/libc/i386/syscalls/fstat.S b/lib/libc/i386/syscalls/fstat.S new file mode 100644 index 0000000..b50eb2e --- /dev/null +++ b/lib/libc/i386/syscalls/fstat.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(fstat) diff --git a/lib/libc/i386/syscalls/fstatfs.S b/lib/libc/i386/syscalls/fstatfs.S new file mode 100644 index 0000000..e6c93ed --- /dev/null +++ b/lib/libc/i386/syscalls/fstatfs.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(fstatfs) diff --git a/lib/libc/i386/syscalls/fsync.S b/lib/libc/i386/syscalls/fsync.S new file mode 100644 index 0000000..83a1245 --- /dev/null +++ b/lib/libc/i386/syscalls/fsync.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(fsync) diff --git a/lib/libc/i386/syscalls/futimes.S b/lib/libc/i386/syscalls/futimes.S new file mode 100644 index 0000000..685665b --- /dev/null +++ b/lib/libc/i386/syscalls/futimes.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(futimes) diff --git a/lib/libc/i386/syscalls/getaudit.S b/lib/libc/i386/syscalls/getaudit.S new file mode 100644 index 0000000..026d8ea --- /dev/null +++ b/lib/libc/i386/syscalls/getaudit.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(getaudit) diff --git a/lib/libc/i386/syscalls/getaudit_addr.S b/lib/libc/i386/syscalls/getaudit_addr.S new file mode 100644 index 0000000..ca02bbf --- /dev/null +++ b/lib/libc/i386/syscalls/getaudit_addr.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(getaudit_addr) diff --git a/lib/libc/i386/syscalls/getauid.S b/lib/libc/i386/syscalls/getauid.S new file mode 100644 index 0000000..4ed3986 --- /dev/null +++ b/lib/libc/i386/syscalls/getauid.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(getauid) diff --git a/lib/libc/i386/syscalls/getdents.S b/lib/libc/i386/syscalls/getdents.S new file mode 100644 index 0000000..c59df9a --- /dev/null +++ b/lib/libc/i386/syscalls/getdents.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(getdents) diff --git a/lib/libc/i386/syscalls/getdirentries.S b/lib/libc/i386/syscalls/getdirentries.S new file mode 100644 index 0000000..8e35eef --- /dev/null +++ b/lib/libc/i386/syscalls/getdirentries.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(getdirentries) diff --git a/lib/libc/i386/syscalls/getdtablesize.S b/lib/libc/i386/syscalls/getdtablesize.S new file mode 100644 index 0000000..53dbb2f --- /dev/null +++ b/lib/libc/i386/syscalls/getdtablesize.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(getdtablesize) diff --git a/lib/libc/i386/syscalls/getegid.S b/lib/libc/i386/syscalls/getegid.S new file mode 100644 index 0000000..b65aa4b --- /dev/null +++ b/lib/libc/i386/syscalls/getegid.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(getegid) diff --git a/lib/libc/i386/syscalls/geteuid.S b/lib/libc/i386/syscalls/geteuid.S new file mode 100644 index 0000000..e9b276e --- /dev/null +++ b/lib/libc/i386/syscalls/geteuid.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(geteuid) diff --git a/lib/libc/i386/syscalls/getfh.S b/lib/libc/i386/syscalls/getfh.S new file mode 100644 index 0000000..7560c6a --- /dev/null +++ b/lib/libc/i386/syscalls/getfh.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(getfh) diff --git a/lib/libc/i386/syscalls/getfsstat.S b/lib/libc/i386/syscalls/getfsstat.S new file mode 100644 index 0000000..0032a9b --- /dev/null +++ b/lib/libc/i386/syscalls/getfsstat.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(getfsstat) diff --git a/lib/libc/i386/syscalls/getgid.S b/lib/libc/i386/syscalls/getgid.S new file mode 100644 index 0000000..77a8458 --- /dev/null +++ b/lib/libc/i386/syscalls/getgid.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(getgid) diff --git a/lib/libc/i386/syscalls/getgroups.S b/lib/libc/i386/syscalls/getgroups.S new file mode 100644 index 0000000..94ee224 --- /dev/null +++ b/lib/libc/i386/syscalls/getgroups.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(getgroups) diff --git a/lib/libc/i386/syscalls/getitimer.S b/lib/libc/i386/syscalls/getitimer.S new file mode 100644 index 0000000..6dcc3cb --- /dev/null +++ b/lib/libc/i386/syscalls/getitimer.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(getitimer) diff --git a/lib/libc/i386/syscalls/getpeername.S b/lib/libc/i386/syscalls/getpeername.S new file mode 100644 index 0000000..b8260e4 --- /dev/null +++ b/lib/libc/i386/syscalls/getpeername.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(getpeername) diff --git a/lib/libc/i386/syscalls/getpgid.S b/lib/libc/i386/syscalls/getpgid.S new file mode 100644 index 0000000..8f0d7a4 --- /dev/null +++ b/lib/libc/i386/syscalls/getpgid.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(getpgid) diff --git a/lib/libc/i386/syscalls/getpgrp.S b/lib/libc/i386/syscalls/getpgrp.S new file mode 100644 index 0000000..99e916e --- /dev/null +++ b/lib/libc/i386/syscalls/getpgrp.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(getpgrp) diff --git a/lib/libc/i386/syscalls/getpid.S b/lib/libc/i386/syscalls/getpid.S new file mode 100644 index 0000000..3ceb237 --- /dev/null +++ b/lib/libc/i386/syscalls/getpid.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(getpid) diff --git a/lib/libc/i386/syscalls/getppid.S b/lib/libc/i386/syscalls/getppid.S new file mode 100644 index 0000000..391efca --- /dev/null +++ b/lib/libc/i386/syscalls/getppid.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(getppid) diff --git a/lib/libc/i386/syscalls/getpriority.S b/lib/libc/i386/syscalls/getpriority.S new file mode 100644 index 0000000..722272e --- /dev/null +++ b/lib/libc/i386/syscalls/getpriority.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(getpriority) diff --git a/lib/libc/i386/syscalls/getresgid.S b/lib/libc/i386/syscalls/getresgid.S new file mode 100644 index 0000000..a09525a --- /dev/null +++ b/lib/libc/i386/syscalls/getresgid.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(getresgid) diff --git a/lib/libc/i386/syscalls/getresuid.S b/lib/libc/i386/syscalls/getresuid.S new file mode 100644 index 0000000..b43cbf9 --- /dev/null +++ b/lib/libc/i386/syscalls/getresuid.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(getresuid) diff --git a/lib/libc/i386/syscalls/getrlimit.S b/lib/libc/i386/syscalls/getrlimit.S new file mode 100644 index 0000000..b369dce --- /dev/null +++ b/lib/libc/i386/syscalls/getrlimit.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(getrlimit) diff --git a/lib/libc/i386/syscalls/getrusage.S b/lib/libc/i386/syscalls/getrusage.S new file mode 100644 index 0000000..e2cb42d --- /dev/null +++ b/lib/libc/i386/syscalls/getrusage.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(getrusage) diff --git a/lib/libc/i386/syscalls/getsid.S b/lib/libc/i386/syscalls/getsid.S new file mode 100644 index 0000000..65f0214 --- /dev/null +++ b/lib/libc/i386/syscalls/getsid.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(getsid) diff --git a/lib/libc/i386/syscalls/getsockname.S b/lib/libc/i386/syscalls/getsockname.S new file mode 100644 index 0000000..c39ff3b --- /dev/null +++ b/lib/libc/i386/syscalls/getsockname.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(getsockname) diff --git a/lib/libc/i386/syscalls/getsockopt.S b/lib/libc/i386/syscalls/getsockopt.S new file mode 100644 index 0000000..d752057 --- /dev/null +++ b/lib/libc/i386/syscalls/getsockopt.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(getsockopt) diff --git a/lib/libc/i386/syscalls/gettimeofday.S b/lib/libc/i386/syscalls/gettimeofday.S new file mode 100644 index 0000000..1fbfb52 --- /dev/null +++ b/lib/libc/i386/syscalls/gettimeofday.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(gettimeofday) diff --git a/lib/libc/i386/syscalls/getuid.S b/lib/libc/i386/syscalls/getuid.S new file mode 100644 index 0000000..7917e5b --- /dev/null +++ b/lib/libc/i386/syscalls/getuid.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(getuid) diff --git a/lib/libc/i386/syscalls/ioctl.S b/lib/libc/i386/syscalls/ioctl.S new file mode 100644 index 0000000..a538e56 --- /dev/null +++ b/lib/libc/i386/syscalls/ioctl.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(ioctl) diff --git a/lib/libc/i386/syscalls/issetugid.S b/lib/libc/i386/syscalls/issetugid.S new file mode 100644 index 0000000..45e5e62 --- /dev/null +++ b/lib/libc/i386/syscalls/issetugid.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(issetugid) diff --git a/lib/libc/i386/syscalls/jail.S b/lib/libc/i386/syscalls/jail.S new file mode 100644 index 0000000..f8f1557 --- /dev/null +++ b/lib/libc/i386/syscalls/jail.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(jail) diff --git a/lib/libc/i386/syscalls/jail_attach.S b/lib/libc/i386/syscalls/jail_attach.S new file mode 100644 index 0000000..fb18318 --- /dev/null +++ b/lib/libc/i386/syscalls/jail_attach.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(jail_attach) diff --git a/lib/libc/i386/syscalls/kenv.S b/lib/libc/i386/syscalls/kenv.S new file mode 100644 index 0000000..d65528b --- /dev/null +++ b/lib/libc/i386/syscalls/kenv.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(kenv) diff --git a/lib/libc/i386/syscalls/kevent.S b/lib/libc/i386/syscalls/kevent.S new file mode 100644 index 0000000..ce12203 --- /dev/null +++ b/lib/libc/i386/syscalls/kevent.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(kevent) diff --git a/lib/libc/i386/syscalls/kill.S b/lib/libc/i386/syscalls/kill.S new file mode 100644 index 0000000..5d72465 --- /dev/null +++ b/lib/libc/i386/syscalls/kill.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(kill) diff --git a/lib/libc/i386/syscalls/kldfind.S b/lib/libc/i386/syscalls/kldfind.S new file mode 100644 index 0000000..69a70c9 --- /dev/null +++ b/lib/libc/i386/syscalls/kldfind.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(kldfind) diff --git a/lib/libc/i386/syscalls/kldfirstmod.S b/lib/libc/i386/syscalls/kldfirstmod.S new file mode 100644 index 0000000..0969884 --- /dev/null +++ b/lib/libc/i386/syscalls/kldfirstmod.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(kldfirstmod) diff --git a/lib/libc/i386/syscalls/kldload.S b/lib/libc/i386/syscalls/kldload.S new file mode 100644 index 0000000..9ea1fd4 --- /dev/null +++ b/lib/libc/i386/syscalls/kldload.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(kldload) diff --git a/lib/libc/i386/syscalls/kldnext.S b/lib/libc/i386/syscalls/kldnext.S new file mode 100644 index 0000000..82bb04e --- /dev/null +++ b/lib/libc/i386/syscalls/kldnext.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(kldnext) diff --git a/lib/libc/i386/syscalls/kldstat.S b/lib/libc/i386/syscalls/kldstat.S new file mode 100644 index 0000000..b397167 --- /dev/null +++ b/lib/libc/i386/syscalls/kldstat.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(kldstat) diff --git a/lib/libc/i386/syscalls/kldsym.S b/lib/libc/i386/syscalls/kldsym.S new file mode 100644 index 0000000..9aaaa58 --- /dev/null +++ b/lib/libc/i386/syscalls/kldsym.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(kldsym) diff --git a/lib/libc/i386/syscalls/kldunload.S b/lib/libc/i386/syscalls/kldunload.S new file mode 100644 index 0000000..a5e25e5 --- /dev/null +++ b/lib/libc/i386/syscalls/kldunload.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(kldunload) diff --git a/lib/libc/i386/syscalls/kldunloadf.S b/lib/libc/i386/syscalls/kldunloadf.S new file mode 100644 index 0000000..28b6114 --- /dev/null +++ b/lib/libc/i386/syscalls/kldunloadf.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(kldunloadf) diff --git a/lib/libc/i386/syscalls/kqueue.S b/lib/libc/i386/syscalls/kqueue.S new file mode 100644 index 0000000..fcb66ae --- /dev/null +++ b/lib/libc/i386/syscalls/kqueue.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(kqueue) diff --git a/lib/libc/i386/syscalls/kse_create.S b/lib/libc/i386/syscalls/kse_create.S new file mode 100644 index 0000000..fbe66d0 --- /dev/null +++ b/lib/libc/i386/syscalls/kse_create.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(kse_create) diff --git a/lib/libc/i386/syscalls/kse_exit.S b/lib/libc/i386/syscalls/kse_exit.S new file mode 100644 index 0000000..e349bdb --- /dev/null +++ b/lib/libc/i386/syscalls/kse_exit.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(kse_exit) diff --git a/lib/libc/i386/syscalls/kse_release.S b/lib/libc/i386/syscalls/kse_release.S new file mode 100644 index 0000000..97d18cb --- /dev/null +++ b/lib/libc/i386/syscalls/kse_release.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(kse_release) diff --git a/lib/libc/i386/syscalls/kse_switchin.S b/lib/libc/i386/syscalls/kse_switchin.S new file mode 100644 index 0000000..f0442ad --- /dev/null +++ b/lib/libc/i386/syscalls/kse_switchin.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(kse_switchin) diff --git a/lib/libc/i386/syscalls/kse_thr_interrupt.S b/lib/libc/i386/syscalls/kse_thr_interrupt.S new file mode 100644 index 0000000..1a5df00 --- /dev/null +++ b/lib/libc/i386/syscalls/kse_thr_interrupt.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(kse_thr_interrupt) diff --git a/lib/libc/i386/syscalls/kse_wakeup.S b/lib/libc/i386/syscalls/kse_wakeup.S new file mode 100644 index 0000000..0350a0d --- /dev/null +++ b/lib/libc/i386/syscalls/kse_wakeup.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(kse_wakeup) diff --git a/lib/libc/i386/syscalls/ksem_close.S b/lib/libc/i386/syscalls/ksem_close.S new file mode 100644 index 0000000..410085f --- /dev/null +++ b/lib/libc/i386/syscalls/ksem_close.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(ksem_close) diff --git a/lib/libc/i386/syscalls/ksem_destroy.S b/lib/libc/i386/syscalls/ksem_destroy.S new file mode 100644 index 0000000..b82aac6 --- /dev/null +++ b/lib/libc/i386/syscalls/ksem_destroy.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(ksem_destroy) diff --git a/lib/libc/i386/syscalls/ksem_getvalue.S b/lib/libc/i386/syscalls/ksem_getvalue.S new file mode 100644 index 0000000..b855218 --- /dev/null +++ b/lib/libc/i386/syscalls/ksem_getvalue.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(ksem_getvalue) diff --git a/lib/libc/i386/syscalls/ksem_init.S b/lib/libc/i386/syscalls/ksem_init.S new file mode 100644 index 0000000..dccf624 --- /dev/null +++ b/lib/libc/i386/syscalls/ksem_init.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(ksem_init) diff --git a/lib/libc/i386/syscalls/ksem_open.S b/lib/libc/i386/syscalls/ksem_open.S new file mode 100644 index 0000000..3e7feba --- /dev/null +++ b/lib/libc/i386/syscalls/ksem_open.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(ksem_open) diff --git a/lib/libc/i386/syscalls/ksem_post.S b/lib/libc/i386/syscalls/ksem_post.S new file mode 100644 index 0000000..64993bd --- /dev/null +++ b/lib/libc/i386/syscalls/ksem_post.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(ksem_post) diff --git a/lib/libc/i386/syscalls/ksem_timedwait.S b/lib/libc/i386/syscalls/ksem_timedwait.S new file mode 100644 index 0000000..3027534 --- /dev/null +++ b/lib/libc/i386/syscalls/ksem_timedwait.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(ksem_timedwait) diff --git a/lib/libc/i386/syscalls/ksem_trywait.S b/lib/libc/i386/syscalls/ksem_trywait.S new file mode 100644 index 0000000..9d4913f --- /dev/null +++ b/lib/libc/i386/syscalls/ksem_trywait.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(ksem_trywait) diff --git a/lib/libc/i386/syscalls/ksem_unlink.S b/lib/libc/i386/syscalls/ksem_unlink.S new file mode 100644 index 0000000..d6a5132 --- /dev/null +++ b/lib/libc/i386/syscalls/ksem_unlink.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(ksem_unlink) diff --git a/lib/libc/i386/syscalls/ksem_wait.S b/lib/libc/i386/syscalls/ksem_wait.S new file mode 100644 index 0000000..65e2141 --- /dev/null +++ b/lib/libc/i386/syscalls/ksem_wait.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(ksem_wait) diff --git a/lib/libc/i386/syscalls/ktrace.S b/lib/libc/i386/syscalls/ktrace.S new file mode 100644 index 0000000..71da6dc --- /dev/null +++ b/lib/libc/i386/syscalls/ktrace.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(ktrace) diff --git a/lib/libc/i386/syscalls/lchflags.S b/lib/libc/i386/syscalls/lchflags.S new file mode 100644 index 0000000..96602c6 --- /dev/null +++ b/lib/libc/i386/syscalls/lchflags.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(lchflags) diff --git a/lib/libc/i386/syscalls/lchmod.S b/lib/libc/i386/syscalls/lchmod.S new file mode 100644 index 0000000..f4c378c --- /dev/null +++ b/lib/libc/i386/syscalls/lchmod.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(lchmod) diff --git a/lib/libc/i386/syscalls/lchown.S b/lib/libc/i386/syscalls/lchown.S new file mode 100644 index 0000000..a73b5e9 --- /dev/null +++ b/lib/libc/i386/syscalls/lchown.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(lchown) diff --git a/lib/libc/i386/syscalls/lgetfh.S b/lib/libc/i386/syscalls/lgetfh.S new file mode 100644 index 0000000..5612b2b --- /dev/null +++ b/lib/libc/i386/syscalls/lgetfh.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(lgetfh) diff --git a/lib/libc/i386/syscalls/link.S b/lib/libc/i386/syscalls/link.S new file mode 100644 index 0000000..f47b152 --- /dev/null +++ b/lib/libc/i386/syscalls/link.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(link) diff --git a/lib/libc/i386/syscalls/lio_listio.S b/lib/libc/i386/syscalls/lio_listio.S new file mode 100644 index 0000000..40e81b8 --- /dev/null +++ b/lib/libc/i386/syscalls/lio_listio.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(lio_listio) diff --git a/lib/libc/i386/syscalls/listen.S b/lib/libc/i386/syscalls/listen.S new file mode 100644 index 0000000..236b637 --- /dev/null +++ b/lib/libc/i386/syscalls/listen.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(listen) diff --git a/lib/libc/i386/syscalls/lstat.S b/lib/libc/i386/syscalls/lstat.S new file mode 100644 index 0000000..686ff37 --- /dev/null +++ b/lib/libc/i386/syscalls/lstat.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(lstat) diff --git a/lib/libc/i386/syscalls/lutimes.S b/lib/libc/i386/syscalls/lutimes.S new file mode 100644 index 0000000..13083a4 --- /dev/null +++ b/lib/libc/i386/syscalls/lutimes.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(lutimes) diff --git a/lib/libc/i386/syscalls/mac_syscall.S b/lib/libc/i386/syscalls/mac_syscall.S new file mode 100644 index 0000000..2f014c1 --- /dev/null +++ b/lib/libc/i386/syscalls/mac_syscall.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(mac_syscall) diff --git a/lib/libc/i386/syscalls/madvise.S b/lib/libc/i386/syscalls/madvise.S new file mode 100644 index 0000000..6ca3748 --- /dev/null +++ b/lib/libc/i386/syscalls/madvise.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(madvise) diff --git a/lib/libc/i386/syscalls/mincore.S b/lib/libc/i386/syscalls/mincore.S new file mode 100644 index 0000000..358b9b7 --- /dev/null +++ b/lib/libc/i386/syscalls/mincore.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(mincore) diff --git a/lib/libc/i386/syscalls/minherit.S b/lib/libc/i386/syscalls/minherit.S new file mode 100644 index 0000000..fc57003 --- /dev/null +++ b/lib/libc/i386/syscalls/minherit.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(minherit) diff --git a/lib/libc/i386/syscalls/mkdir.S b/lib/libc/i386/syscalls/mkdir.S new file mode 100644 index 0000000..e2ec24e --- /dev/null +++ b/lib/libc/i386/syscalls/mkdir.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(mkdir) diff --git a/lib/libc/i386/syscalls/mkfifo.S b/lib/libc/i386/syscalls/mkfifo.S new file mode 100644 index 0000000..9ceccfd --- /dev/null +++ b/lib/libc/i386/syscalls/mkfifo.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(mkfifo) diff --git a/lib/libc/i386/syscalls/mknod.S b/lib/libc/i386/syscalls/mknod.S new file mode 100644 index 0000000..684241d --- /dev/null +++ b/lib/libc/i386/syscalls/mknod.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(mknod) diff --git a/lib/libc/i386/syscalls/mlock.S b/lib/libc/i386/syscalls/mlock.S new file mode 100644 index 0000000..345cb28 --- /dev/null +++ b/lib/libc/i386/syscalls/mlock.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(mlock) diff --git a/lib/libc/i386/syscalls/mlockall.S b/lib/libc/i386/syscalls/mlockall.S new file mode 100644 index 0000000..9df44c9 --- /dev/null +++ b/lib/libc/i386/syscalls/mlockall.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(mlockall) diff --git a/lib/libc/i386/syscalls/modfind.S b/lib/libc/i386/syscalls/modfind.S new file mode 100644 index 0000000..8f6e242 --- /dev/null +++ b/lib/libc/i386/syscalls/modfind.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(modfind) diff --git a/lib/libc/i386/syscalls/modfnext.S b/lib/libc/i386/syscalls/modfnext.S new file mode 100644 index 0000000..4e28d45 --- /dev/null +++ b/lib/libc/i386/syscalls/modfnext.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(modfnext) diff --git a/lib/libc/i386/syscalls/modnext.S b/lib/libc/i386/syscalls/modnext.S new file mode 100644 index 0000000..e092a40 --- /dev/null +++ b/lib/libc/i386/syscalls/modnext.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(modnext) diff --git a/lib/libc/i386/syscalls/modstat.S b/lib/libc/i386/syscalls/modstat.S new file mode 100644 index 0000000..324a6aa --- /dev/null +++ b/lib/libc/i386/syscalls/modstat.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(modstat) diff --git a/lib/libc/i386/syscalls/mount.S b/lib/libc/i386/syscalls/mount.S new file mode 100644 index 0000000..1e7296d --- /dev/null +++ b/lib/libc/i386/syscalls/mount.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(mount) diff --git a/lib/libc/i386/syscalls/mprotect.S b/lib/libc/i386/syscalls/mprotect.S new file mode 100644 index 0000000..3416d37 --- /dev/null +++ b/lib/libc/i386/syscalls/mprotect.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(mprotect) diff --git a/lib/libc/i386/syscalls/msgctl.S b/lib/libc/i386/syscalls/msgctl.S new file mode 100644 index 0000000..20d1fd0 --- /dev/null +++ b/lib/libc/i386/syscalls/msgctl.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(msgctl) diff --git a/lib/libc/i386/syscalls/msgget.S b/lib/libc/i386/syscalls/msgget.S new file mode 100644 index 0000000..ca1bbea --- /dev/null +++ b/lib/libc/i386/syscalls/msgget.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(msgget) diff --git a/lib/libc/i386/syscalls/msgrcv.S b/lib/libc/i386/syscalls/msgrcv.S new file mode 100644 index 0000000..fbccd0a --- /dev/null +++ b/lib/libc/i386/syscalls/msgrcv.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(msgrcv) diff --git a/lib/libc/i386/syscalls/msgsnd.S b/lib/libc/i386/syscalls/msgsnd.S new file mode 100644 index 0000000..afcbef5 --- /dev/null +++ b/lib/libc/i386/syscalls/msgsnd.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(msgsnd) diff --git a/lib/libc/i386/syscalls/msgsys.S b/lib/libc/i386/syscalls/msgsys.S new file mode 100644 index 0000000..9d486b2 --- /dev/null +++ b/lib/libc/i386/syscalls/msgsys.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(msgsys) diff --git a/lib/libc/i386/syscalls/msync.S b/lib/libc/i386/syscalls/msync.S new file mode 100644 index 0000000..536e116 --- /dev/null +++ b/lib/libc/i386/syscalls/msync.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(msync) diff --git a/lib/libc/i386/syscalls/munlock.S b/lib/libc/i386/syscalls/munlock.S new file mode 100644 index 0000000..503d21d --- /dev/null +++ b/lib/libc/i386/syscalls/munlock.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(munlock) diff --git a/lib/libc/i386/syscalls/munlockall.S b/lib/libc/i386/syscalls/munlockall.S new file mode 100644 index 0000000..7bac8e0 --- /dev/null +++ b/lib/libc/i386/syscalls/munlockall.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(munlockall) diff --git a/lib/libc/i386/syscalls/munmap.S b/lib/libc/i386/syscalls/munmap.S new file mode 100644 index 0000000..a0fa128 --- /dev/null +++ b/lib/libc/i386/syscalls/munmap.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(munmap) diff --git a/lib/libc/i386/syscalls/nanosleep.S b/lib/libc/i386/syscalls/nanosleep.S new file mode 100644 index 0000000..88676fc --- /dev/null +++ b/lib/libc/i386/syscalls/nanosleep.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(nanosleep) diff --git a/lib/libc/i386/syscalls/netbsd_lchown.S b/lib/libc/i386/syscalls/netbsd_lchown.S new file mode 100644 index 0000000..e9ee40d --- /dev/null +++ b/lib/libc/i386/syscalls/netbsd_lchown.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(netbsd_lchown) diff --git a/lib/libc/i386/syscalls/netbsd_msync.S b/lib/libc/i386/syscalls/netbsd_msync.S new file mode 100644 index 0000000..b1b261e --- /dev/null +++ b/lib/libc/i386/syscalls/netbsd_msync.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(netbsd_msync) diff --git a/lib/libc/i386/syscalls/nfsclnt.S b/lib/libc/i386/syscalls/nfsclnt.S new file mode 100644 index 0000000..60fed78 --- /dev/null +++ b/lib/libc/i386/syscalls/nfsclnt.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(nfsclnt) diff --git a/lib/libc/i386/syscalls/nfssvc.S b/lib/libc/i386/syscalls/nfssvc.S new file mode 100644 index 0000000..82f0c67 --- /dev/null +++ b/lib/libc/i386/syscalls/nfssvc.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(nfssvc) diff --git a/lib/libc/i386/syscalls/nfstat.S b/lib/libc/i386/syscalls/nfstat.S new file mode 100644 index 0000000..7840e81 --- /dev/null +++ b/lib/libc/i386/syscalls/nfstat.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(nfstat) diff --git a/lib/libc/i386/syscalls/nlstat.S b/lib/libc/i386/syscalls/nlstat.S new file mode 100644 index 0000000..af02f82 --- /dev/null +++ b/lib/libc/i386/syscalls/nlstat.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(nlstat) diff --git a/lib/libc/i386/syscalls/nmount.S b/lib/libc/i386/syscalls/nmount.S new file mode 100644 index 0000000..af017c7 --- /dev/null +++ b/lib/libc/i386/syscalls/nmount.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(nmount) diff --git a/lib/libc/i386/syscalls/nstat.S b/lib/libc/i386/syscalls/nstat.S new file mode 100644 index 0000000..31dc735 --- /dev/null +++ b/lib/libc/i386/syscalls/nstat.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(nstat) diff --git a/lib/libc/i386/syscalls/ntp_adjtime.S b/lib/libc/i386/syscalls/ntp_adjtime.S new file mode 100644 index 0000000..0a06968 --- /dev/null +++ b/lib/libc/i386/syscalls/ntp_adjtime.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(ntp_adjtime) diff --git a/lib/libc/i386/syscalls/ntp_gettime.S b/lib/libc/i386/syscalls/ntp_gettime.S new file mode 100644 index 0000000..7848961 --- /dev/null +++ b/lib/libc/i386/syscalls/ntp_gettime.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(ntp_gettime) diff --git a/lib/libc/i386/syscalls/open.S b/lib/libc/i386/syscalls/open.S new file mode 100644 index 0000000..492455b --- /dev/null +++ b/lib/libc/i386/syscalls/open.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(open) diff --git a/lib/libc/i386/syscalls/pathconf.S b/lib/libc/i386/syscalls/pathconf.S new file mode 100644 index 0000000..346c2f3 --- /dev/null +++ b/lib/libc/i386/syscalls/pathconf.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(pathconf) diff --git a/lib/libc/i386/syscalls/poll.S b/lib/libc/i386/syscalls/poll.S new file mode 100644 index 0000000..b16dabe --- /dev/null +++ b/lib/libc/i386/syscalls/poll.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(poll) diff --git a/lib/libc/i386/syscalls/preadv.S b/lib/libc/i386/syscalls/preadv.S new file mode 100644 index 0000000..682a0d2 --- /dev/null +++ b/lib/libc/i386/syscalls/preadv.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(preadv) diff --git a/lib/libc/i386/syscalls/profil.S b/lib/libc/i386/syscalls/profil.S new file mode 100644 index 0000000..c19dc91 --- /dev/null +++ b/lib/libc/i386/syscalls/profil.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(profil) diff --git a/lib/libc/i386/syscalls/pwritev.S b/lib/libc/i386/syscalls/pwritev.S new file mode 100644 index 0000000..976421e --- /dev/null +++ b/lib/libc/i386/syscalls/pwritev.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(pwritev) diff --git a/lib/libc/i386/syscalls/quotactl.S b/lib/libc/i386/syscalls/quotactl.S new file mode 100644 index 0000000..9183a58 --- /dev/null +++ b/lib/libc/i386/syscalls/quotactl.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(quotactl) diff --git a/lib/libc/i386/syscalls/read.S b/lib/libc/i386/syscalls/read.S new file mode 100644 index 0000000..43e74f6 --- /dev/null +++ b/lib/libc/i386/syscalls/read.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(read) diff --git a/lib/libc/i386/syscalls/readlink.S b/lib/libc/i386/syscalls/readlink.S new file mode 100644 index 0000000..fbed0e4 --- /dev/null +++ b/lib/libc/i386/syscalls/readlink.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(readlink) diff --git a/lib/libc/i386/syscalls/readv.S b/lib/libc/i386/syscalls/readv.S new file mode 100644 index 0000000..7cfa298 --- /dev/null +++ b/lib/libc/i386/syscalls/readv.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(readv) diff --git a/lib/libc/i386/syscalls/recvfrom.S b/lib/libc/i386/syscalls/recvfrom.S new file mode 100644 index 0000000..ed9412e --- /dev/null +++ b/lib/libc/i386/syscalls/recvfrom.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(recvfrom) diff --git a/lib/libc/i386/syscalls/recvmsg.S b/lib/libc/i386/syscalls/recvmsg.S new file mode 100644 index 0000000..bbb1a23 --- /dev/null +++ b/lib/libc/i386/syscalls/recvmsg.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(recvmsg) diff --git a/lib/libc/i386/syscalls/rename.S b/lib/libc/i386/syscalls/rename.S new file mode 100644 index 0000000..5eb5da8 --- /dev/null +++ b/lib/libc/i386/syscalls/rename.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(rename) diff --git a/lib/libc/i386/syscalls/revoke.S b/lib/libc/i386/syscalls/revoke.S new file mode 100644 index 0000000..0e65363 --- /dev/null +++ b/lib/libc/i386/syscalls/revoke.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(revoke) diff --git a/lib/libc/i386/syscalls/rfork.S b/lib/libc/i386/syscalls/rfork.S new file mode 100644 index 0000000..478d399 --- /dev/null +++ b/lib/libc/i386/syscalls/rfork.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(rfork) diff --git a/lib/libc/i386/syscalls/rmdir.S b/lib/libc/i386/syscalls/rmdir.S new file mode 100644 index 0000000..3232880 --- /dev/null +++ b/lib/libc/i386/syscalls/rmdir.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(rmdir) diff --git a/lib/libc/i386/syscalls/rtprio.S b/lib/libc/i386/syscalls/rtprio.S new file mode 100644 index 0000000..43f0d3f --- /dev/null +++ b/lib/libc/i386/syscalls/rtprio.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(rtprio) diff --git a/lib/libc/i386/syscalls/sched_get_priority_max.S b/lib/libc/i386/syscalls/sched_get_priority_max.S new file mode 100644 index 0000000..8bd78ff --- /dev/null +++ b/lib/libc/i386/syscalls/sched_get_priority_max.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(sched_get_priority_max) diff --git a/lib/libc/i386/syscalls/sched_get_priority_min.S b/lib/libc/i386/syscalls/sched_get_priority_min.S new file mode 100644 index 0000000..d4629fd --- /dev/null +++ b/lib/libc/i386/syscalls/sched_get_priority_min.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(sched_get_priority_min) diff --git a/lib/libc/i386/syscalls/sched_getparam.S b/lib/libc/i386/syscalls/sched_getparam.S new file mode 100644 index 0000000..7c0c8f1 --- /dev/null +++ b/lib/libc/i386/syscalls/sched_getparam.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(sched_getparam) diff --git a/lib/libc/i386/syscalls/sched_getscheduler.S b/lib/libc/i386/syscalls/sched_getscheduler.S new file mode 100644 index 0000000..eac7abe --- /dev/null +++ b/lib/libc/i386/syscalls/sched_getscheduler.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(sched_getscheduler) diff --git a/lib/libc/i386/syscalls/sched_rr_get_interval.S b/lib/libc/i386/syscalls/sched_rr_get_interval.S new file mode 100644 index 0000000..3feb807 --- /dev/null +++ b/lib/libc/i386/syscalls/sched_rr_get_interval.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(sched_rr_get_interval) diff --git a/lib/libc/i386/syscalls/sched_setparam.S b/lib/libc/i386/syscalls/sched_setparam.S new file mode 100644 index 0000000..ad2764a --- /dev/null +++ b/lib/libc/i386/syscalls/sched_setparam.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(sched_setparam) diff --git a/lib/libc/i386/syscalls/sched_setscheduler.S b/lib/libc/i386/syscalls/sched_setscheduler.S new file mode 100644 index 0000000..16d8e9e --- /dev/null +++ b/lib/libc/i386/syscalls/sched_setscheduler.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(sched_setscheduler) diff --git a/lib/libc/i386/syscalls/sched_yield.S b/lib/libc/i386/syscalls/sched_yield.S new file mode 100644 index 0000000..7247493 --- /dev/null +++ b/lib/libc/i386/syscalls/sched_yield.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(sched_yield) diff --git a/lib/libc/i386/syscalls/select.S b/lib/libc/i386/syscalls/select.S new file mode 100644 index 0000000..2f5e60d --- /dev/null +++ b/lib/libc/i386/syscalls/select.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(select) diff --git a/lib/libc/i386/syscalls/semget.S b/lib/libc/i386/syscalls/semget.S new file mode 100644 index 0000000..3f13897 --- /dev/null +++ b/lib/libc/i386/syscalls/semget.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(semget) diff --git a/lib/libc/i386/syscalls/semop.S b/lib/libc/i386/syscalls/semop.S new file mode 100644 index 0000000..c89ea11 --- /dev/null +++ b/lib/libc/i386/syscalls/semop.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(semop) diff --git a/lib/libc/i386/syscalls/semsys.S b/lib/libc/i386/syscalls/semsys.S new file mode 100644 index 0000000..59357cf --- /dev/null +++ b/lib/libc/i386/syscalls/semsys.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(semsys) diff --git a/lib/libc/i386/syscalls/sendfile.S b/lib/libc/i386/syscalls/sendfile.S new file mode 100644 index 0000000..b488ffb --- /dev/null +++ b/lib/libc/i386/syscalls/sendfile.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(sendfile) diff --git a/lib/libc/i386/syscalls/sendmsg.S b/lib/libc/i386/syscalls/sendmsg.S new file mode 100644 index 0000000..6113c75 --- /dev/null +++ b/lib/libc/i386/syscalls/sendmsg.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(sendmsg) diff --git a/lib/libc/i386/syscalls/sendto.S b/lib/libc/i386/syscalls/sendto.S new file mode 100644 index 0000000..4fe8adf --- /dev/null +++ b/lib/libc/i386/syscalls/sendto.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(sendto) diff --git a/lib/libc/i386/syscalls/setaudit.S b/lib/libc/i386/syscalls/setaudit.S new file mode 100644 index 0000000..75d0aa6 --- /dev/null +++ b/lib/libc/i386/syscalls/setaudit.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(setaudit) diff --git a/lib/libc/i386/syscalls/setaudit_addr.S b/lib/libc/i386/syscalls/setaudit_addr.S new file mode 100644 index 0000000..405ce98 --- /dev/null +++ b/lib/libc/i386/syscalls/setaudit_addr.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(setaudit_addr) diff --git a/lib/libc/i386/syscalls/setauid.S b/lib/libc/i386/syscalls/setauid.S new file mode 100644 index 0000000..c28de3a --- /dev/null +++ b/lib/libc/i386/syscalls/setauid.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(setauid) diff --git a/lib/libc/i386/syscalls/setcontext.S b/lib/libc/i386/syscalls/setcontext.S new file mode 100644 index 0000000..2022220 --- /dev/null +++ b/lib/libc/i386/syscalls/setcontext.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(setcontext) diff --git a/lib/libc/i386/syscalls/setegid.S b/lib/libc/i386/syscalls/setegid.S new file mode 100644 index 0000000..530b1aa --- /dev/null +++ b/lib/libc/i386/syscalls/setegid.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(setegid) diff --git a/lib/libc/i386/syscalls/seteuid.S b/lib/libc/i386/syscalls/seteuid.S new file mode 100644 index 0000000..c8d84ac --- /dev/null +++ b/lib/libc/i386/syscalls/seteuid.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(seteuid) diff --git a/lib/libc/i386/syscalls/setgid.S b/lib/libc/i386/syscalls/setgid.S new file mode 100644 index 0000000..e9ed7b7 --- /dev/null +++ b/lib/libc/i386/syscalls/setgid.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(setgid) diff --git a/lib/libc/i386/syscalls/setgroups.S b/lib/libc/i386/syscalls/setgroups.S new file mode 100644 index 0000000..3798ba8 --- /dev/null +++ b/lib/libc/i386/syscalls/setgroups.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(setgroups) diff --git a/lib/libc/i386/syscalls/setitimer.S b/lib/libc/i386/syscalls/setitimer.S new file mode 100644 index 0000000..a0b7d98 --- /dev/null +++ b/lib/libc/i386/syscalls/setitimer.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(setitimer) diff --git a/lib/libc/i386/syscalls/setpgid.S b/lib/libc/i386/syscalls/setpgid.S new file mode 100644 index 0000000..b41eba6 --- /dev/null +++ b/lib/libc/i386/syscalls/setpgid.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(setpgid) diff --git a/lib/libc/i386/syscalls/setpriority.S b/lib/libc/i386/syscalls/setpriority.S new file mode 100644 index 0000000..eba15c8 --- /dev/null +++ b/lib/libc/i386/syscalls/setpriority.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(setpriority) diff --git a/lib/libc/i386/syscalls/setregid.S b/lib/libc/i386/syscalls/setregid.S new file mode 100644 index 0000000..2cddae3 --- /dev/null +++ b/lib/libc/i386/syscalls/setregid.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(setregid) diff --git a/lib/libc/i386/syscalls/setresgid.S b/lib/libc/i386/syscalls/setresgid.S new file mode 100644 index 0000000..451425c --- /dev/null +++ b/lib/libc/i386/syscalls/setresgid.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(setresgid) diff --git a/lib/libc/i386/syscalls/setresuid.S b/lib/libc/i386/syscalls/setresuid.S new file mode 100644 index 0000000..cc1ce37 --- /dev/null +++ b/lib/libc/i386/syscalls/setresuid.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(setresuid) diff --git a/lib/libc/i386/syscalls/setreuid.S b/lib/libc/i386/syscalls/setreuid.S new file mode 100644 index 0000000..cd771fc --- /dev/null +++ b/lib/libc/i386/syscalls/setreuid.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(setreuid) diff --git a/lib/libc/i386/syscalls/setrlimit.S b/lib/libc/i386/syscalls/setrlimit.S new file mode 100644 index 0000000..3ee8676 --- /dev/null +++ b/lib/libc/i386/syscalls/setrlimit.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(setrlimit) diff --git a/lib/libc/i386/syscalls/setsid.S b/lib/libc/i386/syscalls/setsid.S new file mode 100644 index 0000000..fe21202 --- /dev/null +++ b/lib/libc/i386/syscalls/setsid.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(setsid) diff --git a/lib/libc/i386/syscalls/setsockopt.S b/lib/libc/i386/syscalls/setsockopt.S new file mode 100644 index 0000000..656b302 --- /dev/null +++ b/lib/libc/i386/syscalls/setsockopt.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(setsockopt) diff --git a/lib/libc/i386/syscalls/settimeofday.S b/lib/libc/i386/syscalls/settimeofday.S new file mode 100644 index 0000000..6f298c2 --- /dev/null +++ b/lib/libc/i386/syscalls/settimeofday.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(settimeofday) diff --git a/lib/libc/i386/syscalls/setuid.S b/lib/libc/i386/syscalls/setuid.S new file mode 100644 index 0000000..71cf5a9 --- /dev/null +++ b/lib/libc/i386/syscalls/setuid.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(setuid) diff --git a/lib/libc/i386/syscalls/shmat.S b/lib/libc/i386/syscalls/shmat.S new file mode 100644 index 0000000..2b6383f --- /dev/null +++ b/lib/libc/i386/syscalls/shmat.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(shmat) diff --git a/lib/libc/i386/syscalls/shmctl.S b/lib/libc/i386/syscalls/shmctl.S new file mode 100644 index 0000000..8d15408 --- /dev/null +++ b/lib/libc/i386/syscalls/shmctl.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(shmctl) diff --git a/lib/libc/i386/syscalls/shmdt.S b/lib/libc/i386/syscalls/shmdt.S new file mode 100644 index 0000000..25473d5 --- /dev/null +++ b/lib/libc/i386/syscalls/shmdt.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(shmdt) diff --git a/lib/libc/i386/syscalls/shmget.S b/lib/libc/i386/syscalls/shmget.S new file mode 100644 index 0000000..14efc3a --- /dev/null +++ b/lib/libc/i386/syscalls/shmget.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(shmget) diff --git a/lib/libc/i386/syscalls/shmsys.S b/lib/libc/i386/syscalls/shmsys.S new file mode 100644 index 0000000..0874914 --- /dev/null +++ b/lib/libc/i386/syscalls/shmsys.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(shmsys) diff --git a/lib/libc/i386/syscalls/shutdown.S b/lib/libc/i386/syscalls/shutdown.S new file mode 100644 index 0000000..2b92fae --- /dev/null +++ b/lib/libc/i386/syscalls/shutdown.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(shutdown) diff --git a/lib/libc/i386/syscalls/sigaction.S b/lib/libc/i386/syscalls/sigaction.S new file mode 100644 index 0000000..7ce1841 --- /dev/null +++ b/lib/libc/i386/syscalls/sigaction.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(sigaction) diff --git a/lib/libc/i386/syscalls/sigaltstack.S b/lib/libc/i386/syscalls/sigaltstack.S new file mode 100644 index 0000000..b711230 --- /dev/null +++ b/lib/libc/i386/syscalls/sigaltstack.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(sigaltstack) diff --git a/lib/libc/i386/syscalls/sigpending.S b/lib/libc/i386/syscalls/sigpending.S new file mode 100644 index 0000000..e872beb --- /dev/null +++ b/lib/libc/i386/syscalls/sigpending.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(sigpending) diff --git a/lib/libc/i386/syscalls/sigprocmask.S b/lib/libc/i386/syscalls/sigprocmask.S new file mode 100644 index 0000000..2af68f9 --- /dev/null +++ b/lib/libc/i386/syscalls/sigprocmask.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(sigprocmask) diff --git a/lib/libc/i386/syscalls/sigsuspend.S b/lib/libc/i386/syscalls/sigsuspend.S new file mode 100644 index 0000000..1198cb9 --- /dev/null +++ b/lib/libc/i386/syscalls/sigsuspend.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(sigsuspend) diff --git a/lib/libc/i386/syscalls/sigtimedwait.S b/lib/libc/i386/syscalls/sigtimedwait.S new file mode 100644 index 0000000..1e99891 --- /dev/null +++ b/lib/libc/i386/syscalls/sigtimedwait.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(sigtimedwait) diff --git a/lib/libc/i386/syscalls/sigwait.S b/lib/libc/i386/syscalls/sigwait.S new file mode 100644 index 0000000..4fe35d9 --- /dev/null +++ b/lib/libc/i386/syscalls/sigwait.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(sigwait) diff --git a/lib/libc/i386/syscalls/sigwaitinfo.S b/lib/libc/i386/syscalls/sigwaitinfo.S new file mode 100644 index 0000000..fd69b8b --- /dev/null +++ b/lib/libc/i386/syscalls/sigwaitinfo.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(sigwaitinfo) diff --git a/lib/libc/i386/syscalls/socket.S b/lib/libc/i386/syscalls/socket.S new file mode 100644 index 0000000..1444bb9 --- /dev/null +++ b/lib/libc/i386/syscalls/socket.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(socket) diff --git a/lib/libc/i386/syscalls/socketpair.S b/lib/libc/i386/syscalls/socketpair.S new file mode 100644 index 0000000..3c2bac1 --- /dev/null +++ b/lib/libc/i386/syscalls/socketpair.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(socketpair) diff --git a/lib/libc/i386/syscalls/stat.S b/lib/libc/i386/syscalls/stat.S new file mode 100644 index 0000000..319844f --- /dev/null +++ b/lib/libc/i386/syscalls/stat.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(stat) diff --git a/lib/libc/i386/syscalls/statfs.S b/lib/libc/i386/syscalls/statfs.S new file mode 100644 index 0000000..1d75077 --- /dev/null +++ b/lib/libc/i386/syscalls/statfs.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(statfs) diff --git a/lib/libc/i386/syscalls/swapcontext.S b/lib/libc/i386/syscalls/swapcontext.S new file mode 100644 index 0000000..dc3aa02 --- /dev/null +++ b/lib/libc/i386/syscalls/swapcontext.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(swapcontext) diff --git a/lib/libc/i386/syscalls/swapoff.S b/lib/libc/i386/syscalls/swapoff.S new file mode 100644 index 0000000..beee1fe --- /dev/null +++ b/lib/libc/i386/syscalls/swapoff.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(swapoff) diff --git a/lib/libc/i386/syscalls/swapon.S b/lib/libc/i386/syscalls/swapon.S new file mode 100644 index 0000000..07859da --- /dev/null +++ b/lib/libc/i386/syscalls/swapon.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(swapon) diff --git a/lib/libc/i386/syscalls/symlink.S b/lib/libc/i386/syscalls/symlink.S new file mode 100644 index 0000000..792fa4b --- /dev/null +++ b/lib/libc/i386/syscalls/symlink.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(symlink) diff --git a/lib/libc/i386/syscalls/sync.S b/lib/libc/i386/syscalls/sync.S new file mode 100644 index 0000000..fb64a13 --- /dev/null +++ b/lib/libc/i386/syscalls/sync.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(sync) diff --git a/lib/libc/i386/syscalls/sysarch.S b/lib/libc/i386/syscalls/sysarch.S new file mode 100644 index 0000000..9ffd321 --- /dev/null +++ b/lib/libc/i386/syscalls/sysarch.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(sysarch) diff --git a/lib/libc/i386/syscalls/thr_create.S b/lib/libc/i386/syscalls/thr_create.S new file mode 100644 index 0000000..3383958 --- /dev/null +++ b/lib/libc/i386/syscalls/thr_create.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(thr_create) diff --git a/lib/libc/i386/syscalls/thr_exit.S b/lib/libc/i386/syscalls/thr_exit.S new file mode 100644 index 0000000..b6cf3f9 --- /dev/null +++ b/lib/libc/i386/syscalls/thr_exit.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(thr_exit) diff --git a/lib/libc/i386/syscalls/thr_kill.S b/lib/libc/i386/syscalls/thr_kill.S new file mode 100644 index 0000000..79fb078 --- /dev/null +++ b/lib/libc/i386/syscalls/thr_kill.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(thr_kill) diff --git a/lib/libc/i386/syscalls/thr_new.S b/lib/libc/i386/syscalls/thr_new.S new file mode 100644 index 0000000..ec67103 --- /dev/null +++ b/lib/libc/i386/syscalls/thr_new.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(thr_new) diff --git a/lib/libc/i386/syscalls/thr_self.S b/lib/libc/i386/syscalls/thr_self.S new file mode 100644 index 0000000..f6979ab --- /dev/null +++ b/lib/libc/i386/syscalls/thr_self.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(thr_self) diff --git a/lib/libc/i386/syscalls/thr_suspend.S b/lib/libc/i386/syscalls/thr_suspend.S new file mode 100644 index 0000000..c41953e --- /dev/null +++ b/lib/libc/i386/syscalls/thr_suspend.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(thr_suspend) diff --git a/lib/libc/i386/syscalls/thr_wake.S b/lib/libc/i386/syscalls/thr_wake.S new file mode 100644 index 0000000..49563cf --- /dev/null +++ b/lib/libc/i386/syscalls/thr_wake.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(thr_wake) diff --git a/lib/libc/i386/syscalls/umask.S b/lib/libc/i386/syscalls/umask.S new file mode 100644 index 0000000..28232c3 --- /dev/null +++ b/lib/libc/i386/syscalls/umask.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(umask) diff --git a/lib/libc/i386/syscalls/undelete.S b/lib/libc/i386/syscalls/undelete.S new file mode 100644 index 0000000..ddd700c --- /dev/null +++ b/lib/libc/i386/syscalls/undelete.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(undelete) diff --git a/lib/libc/i386/syscalls/unlink.S b/lib/libc/i386/syscalls/unlink.S new file mode 100644 index 0000000..3ae339f --- /dev/null +++ b/lib/libc/i386/syscalls/unlink.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(unlink) diff --git a/lib/libc/i386/syscalls/unmount.S b/lib/libc/i386/syscalls/unmount.S new file mode 100644 index 0000000..16f92a6 --- /dev/null +++ b/lib/libc/i386/syscalls/unmount.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(unmount) diff --git a/lib/libc/i386/syscalls/utimes.S b/lib/libc/i386/syscalls/utimes.S new file mode 100644 index 0000000..516bd9d --- /dev/null +++ b/lib/libc/i386/syscalls/utimes.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(utimes) diff --git a/lib/libc/i386/syscalls/utrace.S b/lib/libc/i386/syscalls/utrace.S new file mode 100644 index 0000000..04f63ab --- /dev/null +++ b/lib/libc/i386/syscalls/utrace.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(utrace) diff --git a/lib/libc/i386/syscalls/uuidgen.S b/lib/libc/i386/syscalls/uuidgen.S new file mode 100644 index 0000000..76cac75 --- /dev/null +++ b/lib/libc/i386/syscalls/uuidgen.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(uuidgen) diff --git a/lib/libc/i386/syscalls/vadvise.S b/lib/libc/i386/syscalls/vadvise.S new file mode 100644 index 0000000..9c01914 --- /dev/null +++ b/lib/libc/i386/syscalls/vadvise.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(vadvise) diff --git a/lib/libc/i386/syscalls/wait4.S b/lib/libc/i386/syscalls/wait4.S new file mode 100644 index 0000000..8966372 --- /dev/null +++ b/lib/libc/i386/syscalls/wait4.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(wait4) diff --git a/lib/libc/i386/syscalls/write.S b/lib/libc/i386/syscalls/write.S new file mode 100644 index 0000000..edc3e73 --- /dev/null +++ b/lib/libc/i386/syscalls/write.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(write) diff --git a/lib/libc/i386/syscalls/writev.S b/lib/libc/i386/syscalls/writev.S new file mode 100644 index 0000000..7c80c3a --- /dev/null +++ b/lib/libc/i386/syscalls/writev.S @@ -0,0 +1,2 @@ +#include "SYS.h" +RSYSCALL(writev) diff --git a/lib/libc/include/fpmath.h b/lib/libc/include/fpmath.h new file mode 100644 index 0000000..88f0e38 --- /dev/null +++ b/lib/libc/include/fpmath.h @@ -0,0 +1,65 @@ +/*- + * Copyright (c) 2003 Mike Barcroft + * Copyright (c) 2002 David Schultz + * 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 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 AUTHOR 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 +#include "_fpmath.h" + +union IEEEf2bits { + float f; + struct { +#if _BYTE_ORDER == _LITTLE_ENDIAN + unsigned int man :23; + unsigned int exp :8; + unsigned int sign :1; +#else /* _BIG_ENDIAN */ + unsigned int sign :1; + unsigned int exp :8; + unsigned int man :23; +#endif + } bits; +}; + +#define DBL_MANH_SIZE 20 +#define DBL_MANL_SIZE 32 + +union IEEEd2bits { + double d; + struct { +#if _BYTE_ORDER == _LITTLE_ENDIAN + unsigned int manl :32; + unsigned int manh :20; + unsigned int exp :11; + unsigned int sign :1; +#else /* _BIG_ENDIAN */ + unsigned int sign :1; + unsigned int exp :11; + unsigned int manh :20; + unsigned int manl :32; +#endif + } bits; +}; diff --git a/lib/libc/include/isc/eventlib.h b/lib/libc/include/isc/eventlib.h new file mode 100644 index 0000000..49ba4b3 --- /dev/null +++ b/lib/libc/include/isc/eventlib.h @@ -0,0 +1,203 @@ +/* + * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC") + * Copyright (c) 1995-1999 by Internet Software Consortium + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT + * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +/* eventlib.h - exported interfaces for eventlib + * vix 09sep95 [initial] + * + * $Id: eventlib.h 89 2016-01-12 00:20:40Z reddawg $ + * $FreeBSD: src/lib/libc/include/isc/eventlib.h,v 1.1.1.1.2.1 2006/07/17 10:09:55 ume Exp $ + */ + +#ifndef _EVENTLIB_H +#define _EVENTLIB_H + +#include +#include +#include +#include + +#ifndef __P +# define __EVENTLIB_P_DEFINED +# ifdef __STDC__ +# define __P(x) x +# else +# define __P(x) () +# endif +#endif + +/* In the absence of branded types... */ +typedef struct { void *opaque; } evConnID; +typedef struct { void *opaque; } evFileID; +typedef struct { void *opaque; } evStreamID; +typedef struct { void *opaque; } evTimerID; +typedef struct { void *opaque; } evWaitID; +typedef struct { void *opaque; } evContext; +typedef struct { void *opaque; } evEvent; + +#define evInitID(id) ((id)->opaque = NULL) +#define evTestID(id) ((id).opaque != NULL) + +typedef void (*evConnFunc)__P((evContext, void *, int, const void *, int, + const void *, int)); +typedef void (*evFileFunc)__P((evContext, void *, int, int)); +typedef void (*evStreamFunc)__P((evContext, void *, int, int)); +typedef void (*evTimerFunc)__P((evContext, void *, + struct timespec, struct timespec)); +typedef void (*evWaitFunc)__P((evContext, void *, const void *)); + +typedef struct { unsigned char mask[256/8]; } evByteMask; +#define EV_BYTEMASK_BYTE(b) ((b) / 8) +#define EV_BYTEMASK_MASK(b) (1 << ((b) % 8)) +#define EV_BYTEMASK_SET(bm, b) \ + ((bm).mask[EV_BYTEMASK_BYTE(b)] |= EV_BYTEMASK_MASK(b)) +#define EV_BYTEMASK_CLR(bm, b) \ + ((bm).mask[EV_BYTEMASK_BYTE(b)] &= ~EV_BYTEMASK_MASK(b)) +#define EV_BYTEMASK_TST(bm, b) \ + ((bm).mask[EV_BYTEMASK_BYTE(b)] & EV_BYTEMASK_MASK(b)) + +#define EV_POLL 1 +#define EV_WAIT 2 +#define EV_NULL 4 + +#define EV_READ 1 +#define EV_WRITE 2 +#define EV_EXCEPT 4 + +#define EV_WASNONBLOCKING 8 /* Internal library use. */ + +/* eventlib.c */ +#define evCreate __evCreate +#define evSetDebug __evSetDebug +#define evDestroy __evDestroy +#define evGetNext __evGetNext +#define evDispatch __evDispatch +#define evDrop __evDrop +#define evMainLoop __evMainLoop +#define evHighestFD __evHighestFD +#define evGetOption __evGetOption +#define evSetOption __evSetOption + +int evCreate __P((evContext *)); +void evSetDebug __P((evContext, int, FILE *)); +int evDestroy __P((evContext)); +int evGetNext __P((evContext, evEvent *, int)); +int evDispatch __P((evContext, evEvent)); +void evDrop __P((evContext, evEvent)); +int evMainLoop __P((evContext)); +int evHighestFD __P((evContext)); +int evGetOption __P((evContext *, const char *, int *)); +int evSetOption __P((evContext *, const char *, int)); + +/* ev_connects.c */ +#define evListen __evListen +#define evConnect __evConnect +#define evCancelConn __evCancelConn +#define evHold __evHold +#define evUnhold __evUnhold +#define evTryAccept __evTryAccept + +int evListen __P((evContext, int, int, evConnFunc, void *, evConnID *)); +int evConnect __P((evContext, int, const void *, int, + evConnFunc, void *, evConnID *)); +int evCancelConn __P((evContext, evConnID)); +int evHold __P((evContext, evConnID)); +int evUnhold __P((evContext, evConnID)); +int evTryAccept __P((evContext, evConnID, int *)); + +/* ev_files.c */ +#define evSelectFD __evSelectFD +#define evDeselectFD __evDeselectFD + +int evSelectFD __P((evContext, int, int, evFileFunc, void *, evFileID *)); +int evDeselectFD __P((evContext, evFileID)); + +/* ev_streams.c */ +#define evConsIovec __evConsIovec +#define evWrite __evWrite +#define evRead __evRead +#define evTimeRW __evTimeRW +#define evUntimeRW __evUntimeRW +#define evCancelRW __evCancelRW + +struct iovec evConsIovec __P((void *, size_t)); +int evWrite __P((evContext, int, const struct iovec *, int, + evStreamFunc func, void *, evStreamID *)); +int evRead __P((evContext, int, const struct iovec *, int, + evStreamFunc func, void *, evStreamID *)); +int evTimeRW __P((evContext, evStreamID, evTimerID timer)); +int evUntimeRW __P((evContext, evStreamID)); +int evCancelRW __P((evContext, evStreamID)); + +/* ev_timers.c */ +#define evConsTime __evConsTime +#define evAddTime __evAddTime +#define evSubTime __evSubTime +#define evCmpTime __evCmpTime +#define evTimeSpec __evTimeSpec +#define evTimeVal __evTimeVal + +#define evNowTime __evNowTime +#define evUTCTime __evUTCTime +#define evLastEventTime __evLastEventTime +#define evSetTimer __evSetTimer +#define evClearTimer __evClearTimer +#define evConfigTimer __evConfigTimer +#define evResetTimer __evResetTimer +#define evSetIdleTimer __evSetIdleTimer +#define evClearIdleTimer __evClearIdleTimer +#define evResetIdleTimer __evResetIdleTimer +#define evTouchIdleTimer __evTouchIdleTimer + +struct timespec evConsTime __P((time_t sec, long nsec)); +struct timespec evAddTime __P((struct timespec, struct timespec)); +struct timespec evSubTime __P((struct timespec, struct timespec)); +struct timespec evNowTime __P((void)); +struct timespec evUTCTime __P((void)); +struct timespec evLastEventTime __P((evContext)); +struct timespec evTimeSpec __P((struct timeval)); +struct timeval evTimeVal __P((struct timespec)); +int evCmpTime __P((struct timespec, struct timespec)); +int evSetTimer __P((evContext, evTimerFunc, void *, struct timespec, + struct timespec, evTimerID *)); +int evClearTimer __P((evContext, evTimerID)); +int evConfigTimer __P((evContext, evTimerID, const char *param, + int value)); +int evResetTimer __P((evContext, evTimerID, evTimerFunc, void *, + struct timespec, struct timespec)); +int evSetIdleTimer __P((evContext, evTimerFunc, void *, struct timespec, + evTimerID *)); +int evClearIdleTimer __P((evContext, evTimerID)); +int evResetIdleTimer __P((evContext, evTimerID, evTimerFunc, void *, + struct timespec)); +int evTouchIdleTimer __P((evContext, evTimerID)); + +/* ev_waits.c */ +#define evWaitFor __evWaitFor +#define evDo __evDo +#define evUnwait __evUnwait +#define evDefer __evDefer + +int evWaitFor __P((evContext, const void *, evWaitFunc, void *, evWaitID *)); +int evDo __P((evContext, const void *)); +int evUnwait __P((evContext, evWaitID)); +int evDefer __P((evContext, evWaitFunc, void *)); + +#ifdef __EVENTLIB_P_DEFINED +# undef __P +#endif + +#endif /*_EVENTLIB_H*/ diff --git a/lib/libc/include/libc_private.h b/lib/libc/include/libc_private.h new file mode 100644 index 0000000..6513a69 --- /dev/null +++ b/lib/libc/include/libc_private.h @@ -0,0 +1,137 @@ +/* + * Copyright (c) 1998 John Birrell . + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by John Birrell. + * 4. Neither the name of the author nor the names of any co-contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY JOHN BIRRELL 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. + * + * + * Private definitions for libc, libc_r and libpthread. + * + */ + +#ifndef _LIBC_PRIVATE_H_ +#define _LIBC_PRIVATE_H_ + +/* + * This global flag is non-zero when a process has created one + * or more threads. It is used to avoid calling locking functions + * when they are not required. + */ +extern int __isthreaded; + +/* + * File lock contention is difficult to diagnose without knowing + * where locks were set. Allow a debug library to be built which + * records the source file and line number of each lock call. + */ +#ifdef _FLOCK_DEBUG +#define _FLOCKFILE(x) _flockfile_debug(x, __FILE__, __LINE__) +#else +#define _FLOCKFILE(x) _flockfile(x) +#endif + +/* + * Macros for locking and unlocking FILEs. These test if the + * process is threaded to avoid locking when not required. + */ +#define FLOCKFILE(fp) if (__isthreaded) _FLOCKFILE(fp) +#define FUNLOCKFILE(fp) if (__isthreaded) _funlockfile(fp) + +/* + * Indexes into the pthread jump table. + * + * Warning! If you change this type, you must also change the threads + * libraries that reference it (libc_r, libpthread). + */ +typedef enum { + PJT_COND_BROADCAST, + PJT_COND_DESTROY, + PJT_COND_INIT, + PJT_COND_SIGNAL, + PJT_COND_WAIT, + PJT_GETSPECIFIC, + PJT_KEY_CREATE, + PJT_KEY_DELETE, + PJT_MAIN_NP, + PJT_MUTEX_DESTROY, + PJT_MUTEX_INIT, + PJT_MUTEX_LOCK, + PJT_MUTEX_TRYLOCK, + PJT_MUTEX_UNLOCK, + PJT_MUTEXATTR_DESTROY, + PJT_MUTEXATTR_INIT, + PJT_MUTEXATTR_SETTYPE, + PJT_ONCE, + PJT_RWLOCK_DESTROY, + PJT_RWLOCK_INIT, + PJT_RWLOCK_RDLOCK, + PJT_RWLOCK_TRYRDLOCK, + PJT_RWLOCK_TRYWRLOCK, + PJT_RWLOCK_UNLOCK, + PJT_RWLOCK_WRLOCK, + PJT_SELF, + PJT_SETSPECIFIC, + PJT_SIGMASK, + PJT_MAX +} pjt_index_t; + +typedef int (*pthread_func_t)(void); +typedef pthread_func_t pthread_func_entry_t[2]; + +extern pthread_func_entry_t __thr_jtable[]; + +/* + * yplib internal interfaces + */ +#ifdef YP +int _yp_check(char **); +#endif + +/* + * Initialise TLS for static programs + */ +void _init_tls(void); + +/* + * Set the TLS thread pointer + */ +void _set_tp(void *tp); + +/* + * This is a pointer in the C run-time startup code. It is used + * by getprogname() and setprogname(). + */ +extern const char *__progname; + +/* + * This is the lock to make malloc() thread-safe. It is externalized + * so that thread libraries can protect malloc across fork(). + */ +extern struct _spinlock *__malloc_lock; + +#endif /* _LIBC_PRIVATE_H_ */ diff --git a/lib/libc/include/namespace.h b/lib/libc/include/namespace.h new file mode 100644 index 0000000..7ce00b0 --- /dev/null +++ b/lib/libc/include/namespace.h @@ -0,0 +1,163 @@ +/* + * Copyright (c) 2001 Daniel Eischen . + * 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 AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + */ + +#ifndef _NAMESPACE_H_ +#define _NAMESPACE_H_ + +/* + * Adjust names so that headers declare "hidden" names. + * + * README: When modifying this file don't forget to make the appropriate + * changes in un-namespace.h!!! + */ + +/* + * ISO C (C90) section. Most names in libc aren't in ISO C, so they + * should be here. Most aren't here... + */ +#define err _err +#define warn _warn +#define nsdispatch _nsdispatch + +/* + * Prototypes for syscalls/functions that need to be overridden + * in libc_r/libpthread. + */ +#define accept _accept +#define __acl_aclcheck_fd ___acl_aclcheck_fd +#define __acl_delete_fd ___acl_delete_fd +#define __acl_get_fd ___acl_get_fd +#define __acl_set_fd ___acl_set_fd +#define bind _bind +#define __cap_get_fd ___cap_get_fd +#define __cap_set_fd ___cap_set_fd +#define close _close +#define connect _connect +#define dup _dup +#define dup2 _dup2 +#define execve _execve +#define fcntl _fcntl +/*#define flock _flock */ +#define flockfile _flockfile +#define fpathconf _fpathconf +#define fstat _fstat +#define fstatfs _fstatfs +#define fsync _fsync +#define funlockfile _funlockfile +#define getdirentries _getdirentries +#define getlogin _getlogin +#define getpeername _getpeername +#define getprogname _getprogname +#define getsockname _getsockname +#define getsockopt _getsockopt +#define ioctl _ioctl +/* #define kevent _kevent */ +#define listen _listen +#define nanosleep _nanosleep +#define open _open +#define poll _poll +#define pthread_cond_broadcast _pthread_cond_broadcast +#define pthread_cond_destroy _pthread_cond_destroy +#define pthread_cond_init _pthread_cond_init +#define pthread_cond_signal _pthread_cond_signal +#define pthread_cond_timedwait _pthread_cond_timedwait +#define pthread_cond_wait _pthread_cond_wait +#define pthread_exit _pthread_exit +#define pthread_getspecific _pthread_getspecific +#define pthread_key_create _pthread_key_create +#define pthread_key_delete _pthread_key_delete +#define pthread_main_np _pthread_main_np +#define pthread_mutex_destroy _pthread_mutex_destroy +#define pthread_mutex_init _pthread_mutex_init +#define pthread_mutex_lock _pthread_mutex_lock +#define pthread_mutex_trylock _pthread_mutex_trylock +#define pthread_mutex_unlock _pthread_mutex_unlock +#define pthread_mutexattr_destroy _pthread_mutexattr_destroy +#define pthread_mutexattr_init _pthread_mutexattr_init +#define pthread_mutexattr_settype _pthread_mutexattr_settype +#define pthread_once _pthread_once +#define pthread_rwlock_destroy _pthread_rwlock_destroy +#define pthread_rwlock_init _pthread_rwlock_init +#define pthread_rwlock_rdlock _pthread_rwlock_rdlock +#define pthread_rwlock_wrlock _pthread_rwlock_wrlock +#define pthread_rwlock_tryrdlock _pthread_rwlock_tryrdlock +#define pthread_rwlock_trywrlock _pthread_rwlock_trywrlock +#define pthread_rwlock_unlock _pthread_rwlock_unlock +#define pthread_self _pthread_self +#define pthread_setspecific _pthread_setspecific +#define pthread_sigmask _pthread_sigmask +#define read _read +#define readv _readv +#define recvfrom _recvfrom +#define recvmsg _recvmsg +#define select _select +#define sendmsg _sendmsg +#define sendto _sendto +#define setsockopt _setsockopt +/*#define sigaction _sigaction*/ +#define sigprocmask _sigprocmask +#define sigsuspend _sigsuspend +#define socket _socket +#define socketpair _socketpair +#define usleep _usleep +#define wait4 _wait4 +#define waitpid _waitpid +#define write _write +#define writev _writev + + +/* + * Other hidden syscalls/functions that libc_r needs to override + * but are not used internally by libc. + * + * XXX - When modifying libc to use one of the following, remove + * the prototype from below and place it in the list above. + */ +#if 0 +#define creat _creat +#define fchflags _fchflags +#define fchmod _fchmod +#define ftrylockfile _ftrylockfile +#define msync _msync +#define nfssvc _nfssvc +#define pause _pause +#define pthread_rwlockattr_init _pthread_rwlockattr_init +#define pthread_rwlockattr_destroy _pthread_rwlockattr_destroy +#define sched_yield _sched_yield +#define sendfile _sendfile +#define shutdown _shutdown +#define sigaltstack _sigaltstack +#define sigpending _sigpending +#define sigreturn _sigreturn +#define sigsetmask _sigsetmask +#define sleep _sleep +#define system _system +#define tcdrain _tcdrain +#define wait _wait +#endif + +#endif /* _NAMESPACE_H_ */ diff --git a/lib/libc/include/nss_tls.h b/lib/libc/include/nss_tls.h new file mode 100644 index 0000000..58ea2e1 --- /dev/null +++ b/lib/libc/include/nss_tls.h @@ -0,0 +1,79 @@ +/*- + * Copyright (c) 2003 Networks Associates Technology, Inc. + * All rights reserved. + * + * This software was developed for the FreeBSD Project by + * Jacques A. Vidrine, Safeport Network Services, and Network + * Associates Laboratories, the Security Research Division of Network + * Associates, Inc. under DARPA/SPAWAR contract N66001-01-C-8035 + * ("CBOSS"), as part of the DARPA CHATS research program. + * + * 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 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 AUTHOR 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. + * + * + * Macros which generate thread local storage handling code in NSS modules. + */ +#ifndef _NSS_TLS_H_ +#define _NSS_TLS_H_ + +#define NSS_TLS_HANDLING(name) \ +static pthread_key_t name##_state_key; \ +static void name##_keyinit(void); \ +static int name##_getstate(struct name##_state **); \ +\ +static void \ +name##_keyinit(void) \ +{ \ + (void)_pthread_key_create(&name##_state_key, name##_endstate); \ +} \ +\ +static int \ +name##_getstate(struct name##_state **p) \ +{ \ + static struct name##_state st; \ + static pthread_once_t keyinit = PTHREAD_ONCE_INIT; \ + int rv; \ + \ + if (!__isthreaded || _pthread_main_np() != 0) { \ + *p = &st; \ + return (0); \ + } \ + rv = _pthread_once(&keyinit, name##_keyinit); \ + if (rv != 0) \ + return (rv); \ + *p = _pthread_getspecific(name##_state_key); \ + if (*p != NULL) \ + return (0); \ + *p = calloc(1, sizeof(**p)); \ + if (*p == NULL) \ + return (ENOMEM); \ + rv = _pthread_setspecific(name##_state_key, *p); \ + if (rv != 0) { \ + free(*p); \ + *p = NULL; \ + } \ + return (rv); \ +} \ +/* allow the macro invocation to end with a semicolon */ \ +struct _clashproof_bmVjdGFy + +#endif /* _NSS_TLS_H_ */ diff --git a/lib/libc/include/port_after.h b/lib/libc/include/port_after.h new file mode 100644 index 0000000..cf951c0 --- /dev/null +++ b/lib/libc/include/port_after.h @@ -0,0 +1,9 @@ +#ifndef _PORT_AFTER_H_ +#define _PORT_AFTER_H_ + +#define HAVE_SA_LEN 1 +#define HAS_INET6_STRUCTS 1 +#define HAVE_SIN6_SCOPE_ID 1 +#define HAVE_TIME_R 1 + +#endif /* _PORT_AFTER_H_ */ diff --git a/lib/libc/include/port_before.h b/lib/libc/include/port_before.h new file mode 100644 index 0000000..f5f70f0 --- /dev/null +++ b/lib/libc/include/port_before.h @@ -0,0 +1,20 @@ +#ifndef _PORT_BEFORE_H_ +#define _PORT_BEFORE_H_ + +#define _LIBC 1 +#define DO_PTHREADS 1 +#define USE_KQUEUE 1 + +#define ISC_SOCKLEN_T socklen_t +#define ISC_FORMAT_PRINTF(fmt, args) \ + __attribute__((__format__(__printf__, fmt, args))) +#define DE_CONST(konst, var) \ + do { \ + union { const void *k; void *v; } _u; \ + _u.k = konst; \ + var = _u.v; \ + } while (0) + +#define UNUSED(x) (x) = (x) + +#endif /* _PORT_BEFORE_H_ */ diff --git a/lib/libc/include/reentrant.h b/lib/libc/include/reentrant.h new file mode 100644 index 0000000..d3a27c8 --- /dev/null +++ b/lib/libc/include/reentrant.h @@ -0,0 +1,134 @@ +/*- + * Copyright (c) 1997,98 The NetBSD Foundation, Inc. + * All rights reserved. + * + * This code is derived from software contributed to The NetBSD Foundation + * by J.T. Conklin. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the NetBSD + * Foundation, Inc. and its contributors. + * 4. Neither the name of The NetBSD Foundation 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 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. + * + */ + +/* + * Requirements: + * + * 1. The thread safe mechanism should be lightweight so the library can + * be used by non-threaded applications without unreasonable overhead. + * + * 2. There should be no dependency on a thread engine for non-threaded + * applications. + * + * 3. There should be no dependency on any particular thread engine. + * + * 4. The library should be able to be compiled without support for thread + * safety. + * + * + * Rationale: + * + * One approach for thread safety is to provide discrete versions of the + * library: one thread safe, the other not. The disadvantage of this is + * that libc is rather large, and two copies of a library which are 99%+ + * identical is not an efficent use of resources. + * + * Another approach is to provide a single thread safe library. However, + * it should not add significant run time or code size overhead to non- + * threaded applications. + * + * Since the NetBSD C library is used in other projects, it should be + * easy to replace the mutual exclusion primitives with ones provided by + * another system. Similarly, it should also be easy to remove all + * support for thread safety completely if the target environment does + * not support threads. + * + * + * Implementation Details: + * + * The mutex primitives used by the library (mutex_t, mutex_lock, etc.) + * are macros which expand to the cooresponding primitives provided by + * the thread engine or to nothing. The latter is used so that code is + * not unreasonably cluttered with #ifdefs when all thread safe support + * is removed. + * + * The mutex macros can be directly mapped to the mutex primitives from + * pthreads, however it should be reasonably easy to wrap another mutex + * implementation so it presents a similar interface. + * + * Stub implementations of the mutex functions are provided with *weak* + * linkage. These functions simply return success. When linked with a + * thread library (i.e. -lpthread), the functions will override the + * stubs. + */ + +#include +#include +#include "libc_private.h" + +#define mutex_t pthread_mutex_t +#define cond_t pthread_cond_t +#define rwlock_t pthread_rwlock_t +#define once_t pthread_once_t + +#define thread_key_t pthread_key_t +#define MUTEX_INITIALIZER PTHREAD_MUTEX_INITIALIZER +#define RWLOCK_INITIALIZER PTHREAD_RWLOCK_INITIALIZER +#define ONCE_INITIALIZER PTHREAD_ONCE_INIT + +#define mutex_init(m, a) _pthread_mutex_init(m, a) +#define mutex_lock(m) if (__isthreaded) \ + _pthread_mutex_lock(m) +#define mutex_unlock(m) if (__isthreaded) \ + _pthread_mutex_unlock(m) +#define mutex_trylock(m) (__isthreaded ? 0 : _pthread_mutex_trylock(m)) + +#define cond_init(c, a, p) _pthread_cond_init(c, a) +#define cond_signal(m) if (__isthreaded) \ + _pthread_cond_signal(m) +#define cond_broadcast(m) if (__isthreaded) \ + _pthread_cond_broadcast(m) +#define cond_wait(c, m) if (__isthreaded) \ + _pthread_cond_wait(c, m) + +#define rwlock_init(l, a) _pthread_rwlock_init(l, a) +#define rwlock_rdlock(l) if (__isthreaded) \ + _pthread_rwlock_rdlock(l) +#define rwlock_wrlock(l) if (__isthreaded) \ + _pthread_rwlock_wrlock(l) +#define rwlock_unlock(l) if (__isthreaded) \ + _pthread_rwlock_unlock(l) + +#define thr_keycreate(k, d) _pthread_key_create(k, d) +#define thr_setspecific(k, p) _pthread_setspecific(k, p) +#define thr_getspecific(k) _pthread_getspecific(k) +#define thr_sigsetmask(f, n, o) _pthread_sigmask(f, n, o) + +#define thr_once(o, i) _pthread_once(o, i) +#define thr_self() _pthread_self() +#define thr_exit(x) _pthread_exit(x) +#define thr_main() _pthread_main_np() diff --git a/lib/libc/include/resolv_mt.h b/lib/libc/include/resolv_mt.h new file mode 100644 index 0000000..27963a1 --- /dev/null +++ b/lib/libc/include/resolv_mt.h @@ -0,0 +1,47 @@ +#ifndef _RESOLV_MT_H +#define _RESOLV_MT_H + +#include +#include +#include +#include + +/* Access functions for the libresolv private interface */ + +int __res_enable_mt(void); +int __res_disable_mt(void); + +/* Per-thread context */ + +typedef struct { +int no_hosts_fallback_private; +int retry_save; +int retry_private; +char inet_nsap_ntoa_tmpbuf[255*3]; +char sym_ntos_unname[20]; +char sym_ntop_unname[20]; +char p_option_nbuf[40]; +char p_time_nbuf[40]; +char precsize_ntoa_retbuf[sizeof "90000000.00"]; +char loc_ntoa_tmpbuf[sizeof +"1000 60 60.000 N 1000 60 60.000 W -12345678.00m 90000000.00m 90000000.00m 90000000.00m"]; +char p_secstodate_output[15]; +} mtctxres_t; + +/* Thread-specific data (TSD) */ + +mtctxres_t *___mtctxres(void); +#define mtctxres (___mtctxres()) + +/* Various static data that should be TSD */ + +#define sym_ntos_unname (mtctxres->sym_ntos_unname) +#define sym_ntop_unname (mtctxres->sym_ntop_unname) +#define inet_nsap_ntoa_tmpbuf (mtctxres->inet_nsap_ntoa_tmpbuf) +#define p_option_nbuf (mtctxres->p_option_nbuf) +#define p_time_nbuf (mtctxres->p_time_nbuf) +#define precsize_ntoa_retbuf (mtctxres->precsize_ntoa_retbuf) +#define loc_ntoa_tmpbuf (mtctxres->loc_ntoa_tmpbuf) +#define p_secstodate_output (mtctxres->p_secstodate_output) + +#endif /* _RESOLV_MT_H */ diff --git a/lib/libc/include/spinlock.h b/lib/libc/include/spinlock.h new file mode 100644 index 0000000..f537360 --- /dev/null +++ b/lib/libc/include/spinlock.h @@ -0,0 +1,72 @@ +/* + * Copyright (c) 1998 John Birrell . + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by John Birrell. + * 4. Neither the name of the author nor the names of any co-contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY JOHN BIRRELL 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. + * + * + * Lock definitions used in both libc and libpthread. + * + */ + +#ifndef _SPINLOCK_H_ +#define _SPINLOCK_H_ +#include +#include + +/* + * Lock structure with room for debugging information. + */ +struct _spinlock { + volatile long access_lock; + volatile long lock_owner; + volatile char *fname; + volatile int lineno; +}; +typedef struct _spinlock spinlock_t; + +#define _SPINLOCK_INITIALIZER { 0, 0, 0, 0 } + +#define _SPINUNLOCK(_lck) _spinunlock(_lck); +#ifdef _LOCK_DEBUG +#define _SPINLOCK(_lck) _spinlock_debug(_lck, __FILE__, __LINE__) +#else +#define _SPINLOCK(_lck) _spinlock(_lck) +#endif + +/* + * Thread function prototype definitions: + */ +__BEGIN_DECLS +long _atomic_lock(volatile long *); +void _spinlock(spinlock_t *); +void _spinunlock(spinlock_t *); +void _spinlock_debug(spinlock_t *, char *, int); +__END_DECLS + +#endif /* _SPINLOCK_H_ */ diff --git a/lib/libc/include/un-namespace.h b/lib/libc/include/un-namespace.h new file mode 100644 index 0000000..8c1fca1 --- /dev/null +++ b/lib/libc/include/un-namespace.h @@ -0,0 +1,153 @@ +/* + * Copyright (c) 2001 Daniel Eischen . + * 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 AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + */ + +#ifndef _UN_NAMESPACE_H_ +#define _UN_NAMESPACE_H_ + +#undef accept +#undef __acl_aclcheck_fd +#undef __acl_delete_fd +#undef __acl_get_fd +#undef __acl_set_fd +#undef bind +#undef __cap_get_fd +#undef __cap_set_fd +#undef close +#undef connect +#undef dup +#undef dup2 +#undef execve +#undef fcntl +#undef flock +#undef flockfile +#undef fpathconf +#undef fstat +#undef fstatfs +#undef fsync +#undef funlockfile +#undef getdirentries +#undef getlogin +#undef getpeername +#undef getprogname +#undef getsockname +#undef getsockopt +#undef ioctl +#undef kevent +#undef listen +#undef nanosleep +#undef open +#undef poll +#undef pthread_cond_broadcast +#undef pthread_cond_destroy +#undef pthread_cond_init +#undef pthread_cond_signal +#undef pthread_cond_timedwait +#undef pthread_cond_wait +#undef pthread_exit +#undef pthread_getspecific +#undef pthread_key_create +#undef pthread_key_delete +#undef pthread_main_np +#undef pthread_mutex_destroy +#undef pthread_mutex_init +#undef pthread_mutex_lock +#undef pthread_mutex_trylock +#undef pthread_mutex_unlock +#undef pthread_mutexattr_init +#undef pthread_mutexattr_destroy +#undef pthread_mutexattr_settype +#undef pthread_once +#undef pthread_rwlock_destroy +#undef pthread_rwlock_init +#undef pthread_rwlock_rdlock +#undef pthread_rwlock_wrlock +#undef pthread_rwlock_tryrdlock +#undef pthread_rwlock_trywrlock +#undef pthread_rwlock_unlock +#undef pthread_self +#undef pthread_setspecific +#undef pthread_sigmask +#undef read +#undef readv +#undef recvfrom +#undef recvmsg +#undef select +#undef sendmsg +#undef sendto +#undef setsockopt +#undef sigaction +#undef sigprocmask +#undef sigsuspend +#undef socket +#undef socketpair +#undef usleep +#undef wait4 +#undef waitpid +#undef write +#undef writev + +#if 0 +#undef creat +#undef fchflags +#undef fchmod +#undef ftrylockfile +#undef msync +#undef nfssvc +#undef pause +#undef pthread_rwlockattr_init +#undef pthread_rwlockattr_destroy +#undef sched_yield +#undef sendfile +#undef shutdown +#undef sigaltstack +#undef sigpending +#undef sigreturn +#undef sigsetmask +#undef sleep +#undef system +#undef tcdrain +#undef wait +#endif /* 0 */ + +#ifdef _SIGNAL_H_ +int _sigaction(int, const struct sigaction *, struct sigaction *); +#endif + +#ifdef _SYS_EVENT_H_ +int _kevent(int, const struct kevent *, int, struct kevent *, + int, const struct timespec *); +#endif + +#ifdef _SYS_FCNTL_H_ +int _flock(int, int); +#endif + +#undef err +#undef warn +#undef nsdispatch + +#endif /* _UN_NAMESPACE_H_ */ diff --git a/lib/libc/inet/Makefile b/lib/libc/inet/Makefile new file mode 100644 index 0000000..e6be2e2 --- /dev/null +++ b/lib/libc/inet/Makefile @@ -0,0 +1,35 @@ +# $Id: Makefile 89 2016-01-12 00:20:40Z reddawg $ +# The System Makefile (C) 2002 The UbixOS Project + +# Include Global 'Source' Options +include ../../../Makefile.incl +include ../../Makefile.incl +include ../Makefile.incl + +INCLUDES += -I../locale/ + +#Objects +OBJS = inet_addr.o inet_cidr_ntop.o inet_cidr_pton.o inet_lnaof.o inet_makeaddr.o inet_net_ntop.o inet_net_pton.o inet_neta.o inet_netof.o inet_network.o inet_ntoa.o inet_ntop.o inet_pton.o nsap_addr.o + +all: $(OBJS) + +# Compile the source files +.cc.o: + $(CXX) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -c -o $@ $< + +.cc.s: + $(CXX) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -S -o $@ $< + +.c.o: + $(CC) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -c $< + +.c.s: + $(CC) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -S -o $@ $< + +.S.o: + $(CC) $(CFLAGS) -Wall -nostdlib -c -o $@ $< + +# Clean up the junk +clean: + $(REMOVE) $(OBJS) + diff --git a/lib/libc/inet/inet_addr.c b/lib/libc/inet/inet_addr.c new file mode 100644 index 0000000..c00032d --- /dev/null +++ b/lib/libc/inet/inet_addr.c @@ -0,0 +1,217 @@ +/* + * Copyright (c) 1983, 1990, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +/* + * Portions Copyright (c) 1993 by Digital Equipment Corporation. + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies, and that + * the name of Digital Equipment Corporation not be used in advertising or + * publicity pertaining to distribution of the document or software without + * specific, written prior permission. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL + * WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL DIGITAL EQUIPMENT + * CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL + * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR + * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS + * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS + * SOFTWARE. + */ + +/* + * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC") + * Portions Copyright (c) 1996-1999 by Internet Software Consortium. + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT + * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static const char sccsid[] = "@(#)inet_addr.c 8.1 (Berkeley) 6/17/93"; +static const char rcsid[] = "$Id: inet_addr.c 89 2016-01-12 00:20:40Z reddawg $"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/inet/inet_addr.c,v 1.2.2.1 2006/07/17 10:09:56 ume Exp $"); + +#include "port_before.h" + +#include +#include + +#include +#include + +#include + +#include "port_after.h" + +/* + * Ascii internet address interpretation routine. + * The value returned is in network order. + */ +in_addr_t /* XXX should be struct in_addr :( */ +inet_addr(const char *cp) { + struct in_addr val; + + if (inet_aton(cp, &val)) + return (val.s_addr); + return (INADDR_NONE); +} + +/* + * Check whether "cp" is a valid ascii representation + * of an Internet address and convert to a binary address. + * Returns 1 if the address is valid, 0 if not. + * This replaces inet_addr, the return value from which + * cannot distinguish between failure and a local broadcast address. + */ +int +inet_aton(const char *cp, struct in_addr *addr) { + u_long val; + int base, n; + char c; + u_int8_t parts[4]; + u_int8_t *pp = parts; + int digit; + + c = *cp; + for (;;) { + /* + * Collect number up to ``.''. + * Values are specified as for C: + * 0x=hex, 0=octal, isdigit=decimal. + */ + if (!isdigit((unsigned char)c)) + return (0); + val = 0; base = 10; digit = 0; + if (c == '0') { + c = *++cp; + if (c == 'x' || c == 'X') + base = 16, c = *++cp; + else { + base = 8; + digit = 1 ; + } + } + for (;;) { + if (isascii(c) && isdigit((unsigned char)c)) { + if (base == 8 && (c == '8' || c == '9')) + return (0); + val = (val * base) + (c - '0'); + c = *++cp; + digit = 1; + } else if (base == 16 && isascii(c) && + isxdigit((unsigned char)c)) { + val = (val << 4) | + (c + 10 - (islower((unsigned char)c) ? 'a' : 'A')); + c = *++cp; + digit = 1; + } else + break; + } + if (c == '.') { + /* + * Internet format: + * a.b.c.d + * a.b.c (with c treated as 16 bits) + * a.b (with b treated as 24 bits) + */ + if (pp >= parts + 3 || val > 0xffU) + return (0); + *pp++ = val; + c = *++cp; + } else + break; + } + /* + * Check for trailing characters. + */ + if (c != '\0' && (!isascii(c) || !isspace((unsigned char)c))) + return (0); + /* + * Did we get a valid digit? + */ + if (!digit) + return (0); + /* + * Concoct the address according to + * the number of parts specified. + */ + n = pp - parts + 1; + switch (n) { + case 1: /* a -- 32 bits */ + break; + + case 2: /* a.b -- 8.24 bits */ + if (val > 0xffffffU) + return (0); + val |= parts[0] << 24; + break; + + case 3: /* a.b.c -- 8.8.16 bits */ + if (val > 0xffffU) + return (0); + val |= (parts[0] << 24) | (parts[1] << 16); + break; + + case 4: /* a.b.c.d -- 8.8.8.8 bits */ + if (val > 0xffU) + return (0); + val |= (parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8); + break; + } + if (addr != NULL) + addr->s_addr = htonl(val); + return (1); +} + +/* + * Weak aliases for applications that use certain private entry points, + * and fail to include . + */ +#undef inet_addr +__weak_reference(__inet_addr, inet_addr); +#undef inet_aton +__weak_reference(__inet_aton, inet_aton); diff --git a/lib/libc/inet/inet_cidr_ntop.c b/lib/libc/inet/inet_cidr_ntop.c new file mode 100644 index 0000000..7b4f065 --- /dev/null +++ b/lib/libc/inet/inet_cidr_ntop.c @@ -0,0 +1,263 @@ +/* + * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC") + * Copyright (c) 1998,1999 by Internet Software Consortium. + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT + * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static const char rcsid[] = "$Id: inet_cidr_ntop.c 89 2016-01-12 00:20:40Z reddawg $"; +#endif +#include +__FBSDID("$FreeBSD: src/lib/libc/inet/inet_cidr_ntop.c,v 1.1.1.1.2.1 2006/07/17 10:09:56 ume Exp $"); + +#include "port_before.h" + +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include "port_after.h" + +#ifdef SPRINTF_CHAR +# define SPRINTF(x) strlen(sprintf/**/x) +#else +# define SPRINTF(x) ((size_t)sprintf x) +#endif + +static char * inet_cidr_ntop_ipv4 __P((const u_char *src, int bits, + char *dst, size_t size)); +static char * inet_cidr_ntop_ipv6 __P((const u_char *src, int bits, + char *dst, size_t size)); + +/* + * char * + * inet_cidr_ntop(af, src, bits, dst, size) + * convert network address from network to presentation format. + * "src"'s size is determined from its "af". + * return: + * pointer to dst, or NULL if an error occurred (check errno). + * note: + * 192.5.5.1/28 has a nonzero host part, which means it isn't a network + * as called for by inet_net_ntop() but it can be a host address with + * an included netmask. + * author: + * Paul Vixie (ISC), October 1998 + */ +char * +inet_cidr_ntop(int af, const void *src, int bits, char *dst, size_t size) { + switch (af) { + case AF_INET: + return (inet_cidr_ntop_ipv4(src, bits, dst, size)); + case AF_INET6: + return (inet_cidr_ntop_ipv6(src, bits, dst, size)); + default: + errno = EAFNOSUPPORT; + return (NULL); + } +} + +static int +decoct(const u_char *src, int bytes, char *dst, size_t size) { + char *odst = dst; + char *t; + int b; + + for (b = 1; b <= bytes; b++) { + if (size < sizeof "255.") + return (0); + t = dst; + dst += SPRINTF((dst, "%u", *src++)); + if (b != bytes) { + *dst++ = '.'; + *dst = '\0'; + } + size -= (size_t)(dst - t); + } + return (dst - odst); +} + +/* + * static char * + * inet_cidr_ntop_ipv4(src, bits, dst, size) + * convert IPv4 network address from network to presentation format. + * "src"'s size is determined from its "af". + * return: + * pointer to dst, or NULL if an error occurred (check errno). + * note: + * network byte order assumed. this means 192.5.5.240/28 has + * 0b11110000 in its fourth octet. + * author: + * Paul Vixie (ISC), October 1998 + */ +static char * +inet_cidr_ntop_ipv4(const u_char *src, int bits, char *dst, size_t size) { + char *odst = dst; + size_t len = 4; + size_t b; + size_t bytes; + + if ((bits < -1) || (bits > 32)) { + errno = EINVAL; + return (NULL); + } + + /* Find number of significant bytes in address. */ + if (bits == -1) + len = 4; + else + for (len = 1, b = 1 ; b < 4U; b++) + if (*(src + b)) + len = b + 1; + + /* Format whole octets plus nonzero trailing octets. */ + bytes = (((bits <= 0) ? 1 : bits) + 7) / 8; + if (len > bytes) + bytes = len; + b = decoct(src, bytes, dst, size); + if (b == 0U) + goto emsgsize; + dst += b; + size -= b; + + if (bits != -1) { + /* Format CIDR /width. */ + if (size < sizeof "/32") + goto emsgsize; + dst += SPRINTF((dst, "/%u", bits)); + } + + return (odst); + + emsgsize: + errno = EMSGSIZE; + return (NULL); +} + +static char * +inet_cidr_ntop_ipv6(const u_char *src, int bits, char *dst, size_t size) { + /* + * Note that int32_t and int16_t need only be "at least" large enough + * to contain a value of the specified size. On some systems, like + * Crays, there is no such thing as an integer variable with 16 bits. + * Keep this in mind if you think this function should have been coded + * to use pointer overlays. All the world's not a VAX. + */ + char tmp[sizeof "ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255/128"]; + char *tp; + struct { int base, len; } best, cur; + u_int words[NS_IN6ADDRSZ / NS_INT16SZ]; + int i; + + if ((bits < -1) || (bits > 128)) { + errno = EINVAL; + return (NULL); + } + + /* + * Preprocess: + * Copy the input (bytewise) array into a wordwise array. + * Find the longest run of 0x00's in src[] for :: shorthanding. + */ + memset(words, '\0', sizeof words); + for (i = 0; i < NS_IN6ADDRSZ; i++) + words[i / 2] |= (src[i] << ((1 - (i % 2)) << 3)); + best.base = -1; + best.len = 0; + cur.base = -1; + cur.len = 0; + for (i = 0; i < (NS_IN6ADDRSZ / NS_INT16SZ); i++) { + if (words[i] == 0) { + if (cur.base == -1) + cur.base = i, cur.len = 1; + else + cur.len++; + } else { + if (cur.base != -1) { + if (best.base == -1 || cur.len > best.len) + best = cur; + cur.base = -1; + } + } + } + if (cur.base != -1) { + if (best.base == -1 || cur.len > best.len) + best = cur; + } + if (best.base != -1 && best.len < 2) + best.base = -1; + + /* + * Format the result. + */ + tp = tmp; + for (i = 0; i < (NS_IN6ADDRSZ / NS_INT16SZ); i++) { + /* Are we inside the best run of 0x00's? */ + if (best.base != -1 && i >= best.base && + i < (best.base + best.len)) { + if (i == best.base) + *tp++ = ':'; + continue; + } + /* Are we following an initial run of 0x00s or any real hex? */ + if (i != 0) + *tp++ = ':'; + /* Is this address an encapsulated IPv4? */ + if (i == 6 && best.base == 0 && (best.len == 6 || + (best.len == 7 && words[7] != 0x0001) || + (best.len == 5 && words[5] == 0xffff))) { + int n; + + if (src[15] || bits == -1 || bits > 120) + n = 4; + else if (src[14] || bits > 112) + n = 3; + else + n = 2; + n = decoct(src+12, n, tp, sizeof tmp - (tp - tmp)); + if (n == 0) { + errno = EMSGSIZE; + return (NULL); + } + tp += strlen(tp); + break; + } + tp += SPRINTF((tp, "%x", words[i])); + } + + /* Was it a trailing run of 0x00's? */ + if (best.base != -1 && (best.base + best.len) == + (NS_IN6ADDRSZ / NS_INT16SZ)) + *tp++ = ':'; + *tp = '\0'; + + if (bits != -1) + tp += SPRINTF((tp, "/%u", bits)); + + /* + * Check for overflow, copy, and we're done. + */ + if ((size_t)(tp - tmp) > size) { + errno = EMSGSIZE; + return (NULL); + } + strcpy(dst, tmp); + return (dst); +} diff --git a/lib/libc/inet/inet_cidr_pton.c b/lib/libc/inet/inet_cidr_pton.c new file mode 100644 index 0000000..5192bee --- /dev/null +++ b/lib/libc/inet/inet_cidr_pton.c @@ -0,0 +1,277 @@ +/* + * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC") + * Copyright (c) 1998,1999 by Internet Software Consortium. + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT + * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static const char rcsid[] = "$Id: inet_cidr_pton.c 89 2016-01-12 00:20:40Z reddawg $"; +#endif +#include +__FBSDID("$FreeBSD: src/lib/libc/inet/inet_cidr_pton.c,v 1.2.2.1 2006/07/17 10:09:56 ume Exp $"); + +#include "port_before.h" + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include "port_after.h" + +#ifdef SPRINTF_CHAR +# define SPRINTF(x) strlen(sprintf/**/x) +#else +# define SPRINTF(x) ((size_t)sprintf x) +#endif + +static int inet_cidr_pton_ipv4 __P((const char *src, u_char *dst, + int *bits, int ipv6)); +static int inet_cidr_pton_ipv6 __P((const char *src, u_char *dst, + int *bits)); + +static int getbits(const char *, int ipv6); + +/* + * int + * inet_cidr_pton(af, src, dst, *bits) + * convert network address from presentation to network format. + * accepts inet_pton()'s input for this "af" plus trailing "/CIDR". + * "dst" is assumed large enough for its "af". "bits" is set to the + * /CIDR prefix length, which can have defaults (like /32 for IPv4). + * return: + * -1 if an error occurred (inspect errno; ENOENT means bad format). + * 0 if successful conversion occurred. + * note: + * 192.5.5.1/28 has a nonzero host part, which means it isn't a network + * as called for by inet_net_pton() but it can be a host address with + * an included netmask. + * author: + * Paul Vixie (ISC), October 1998 + */ +int +inet_cidr_pton(int af, const char *src, void *dst, int *bits) { + switch (af) { + case AF_INET: + return (inet_cidr_pton_ipv4(src, dst, bits, 0)); + case AF_INET6: + return (inet_cidr_pton_ipv6(src, dst, bits)); + default: + errno = EAFNOSUPPORT; + return (-1); + } +} + +static const char digits[] = "0123456789"; + +static int +inet_cidr_pton_ipv4(const char *src, u_char *dst, int *pbits, int ipv6) { + const u_char *odst = dst; + int n, ch, tmp, bits; + size_t size = 4; + + /* Get the mantissa. */ + while (ch = *src++, (isascii(ch) && isdigit(ch))) { + tmp = 0; + do { + n = strchr(digits, ch) - digits; + assert(n >= 0 && n <= 9); + tmp *= 10; + tmp += n; + if (tmp > 255) + goto enoent; + } while ((ch = *src++) != '\0' && isascii(ch) && isdigit(ch)); + if (size-- == 0U) + goto emsgsize; + *dst++ = (u_char) tmp; + if (ch == '\0' || ch == '/') + break; + if (ch != '.') + goto enoent; + } + + /* Get the prefix length if any. */ + bits = -1; + if (ch == '/' && dst > odst) { + bits = getbits(src, ipv6); + if (bits == -2) + goto enoent; + } else if (ch != '\0') + goto enoent; + + /* Prefix length can default to /32 only if all four octets spec'd. */ + if (bits == -1) { + if (dst - odst == 4) + bits = ipv6 ? 128 : 32; + else + goto enoent; + } + + /* If nothing was written to the destination, we found no address. */ + if (dst == odst) + goto enoent; + + /* If prefix length overspecifies mantissa, life is bad. */ + if (((bits - (ipv6 ? 96 : 0)) / 8) > (dst - odst)) + goto enoent; + + /* Extend address to four octets. */ + while (size-- > 0U) + *dst++ = 0; + + *pbits = bits; + return (0); + + enoent: + errno = ENOENT; + return (-1); + + emsgsize: + errno = EMSGSIZE; + return (-1); +} + +static int +inet_cidr_pton_ipv6(const char *src, u_char *dst, int *pbits) { + static const char xdigits_l[] = "0123456789abcdef", + xdigits_u[] = "0123456789ABCDEF"; + u_char tmp[NS_IN6ADDRSZ], *tp, *endp, *colonp; + const char *xdigits, *curtok; + int ch, saw_xdigit; + u_int val; + int bits; + + memset((tp = tmp), '\0', NS_IN6ADDRSZ); + endp = tp + NS_IN6ADDRSZ; + colonp = NULL; + /* Leading :: requires some special handling. */ + if (*src == ':') + if (*++src != ':') + return (0); + curtok = src; + saw_xdigit = 0; + val = 0; + bits = -1; + while ((ch = *src++) != '\0') { + const char *pch; + + if ((pch = strchr((xdigits = xdigits_l), ch)) == NULL) + pch = strchr((xdigits = xdigits_u), ch); + if (pch != NULL) { + val <<= 4; + val |= (pch - xdigits); + if (val > 0xffff) + return (0); + saw_xdigit = 1; + continue; + } + if (ch == ':') { + curtok = src; + if (!saw_xdigit) { + if (colonp) + return (0); + colonp = tp; + continue; + } else if (*src == '\0') { + return (0); + } + if (tp + NS_INT16SZ > endp) + return (0); + *tp++ = (u_char) (val >> 8) & 0xff; + *tp++ = (u_char) val & 0xff; + saw_xdigit = 0; + val = 0; + continue; + } + if (ch == '.' && ((tp + NS_INADDRSZ) <= endp) && + inet_cidr_pton_ipv4(curtok, tp, &bits, 1) == 0) { + tp += NS_INADDRSZ; + saw_xdigit = 0; + break; /* '\0' was seen by inet_pton4(). */ + } + if (ch == '/') { + bits = getbits(src, 1); + if (bits == -2) + goto enoent; + break; + } + goto enoent; + } + if (saw_xdigit) { + if (tp + NS_INT16SZ > endp) + goto emsgsize; + *tp++ = (u_char) (val >> 8) & 0xff; + *tp++ = (u_char) val & 0xff; + } + if (colonp != NULL) { + /* + * Since some memmove()'s erroneously fail to handle + * overlapping regions, we'll do the shift by hand. + */ + const int n = tp - colonp; + int i; + + if (tp == endp) + goto enoent; + for (i = 1; i <= n; i++) { + endp[- i] = colonp[n - i]; + colonp[n - i] = 0; + } + tp = endp; + } + + memcpy(dst, tmp, NS_IN6ADDRSZ); + + *pbits = bits; + return (0); + + enoent: + errno = ENOENT; + return (-1); + + emsgsize: + errno = EMSGSIZE; + return (-1); +} + +static int +getbits(const char *src, int ipv6) { + int bits = 0; + char *cp, ch; + + if (*src == '\0') /* syntax */ + return (-2); + do { + ch = *src++; + cp = strchr(digits, ch); + if (cp == NULL) /* syntax */ + return (-2); + bits *= 10; + bits += cp - digits; + if (bits == 0 && *src != '\0') /* no leading zeros */ + return (-2); + if (bits > (ipv6 ? 128 : 32)) /* range error */ + return (-2); + } while (*src != '\0'); + + return (bits); +} diff --git a/lib/libc/inet/inet_lnaof.c b/lib/libc/inet/inet_lnaof.c new file mode 100644 index 0000000..692e4ed --- /dev/null +++ b/lib/libc/inet/inet_lnaof.c @@ -0,0 +1,72 @@ +/* + * Copyright (c) 1983, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static const char sccsid[] = "@(#)inet_lnaof.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/inet/inet_lnaof.c,v 1.2.2.1 2006/07/17 10:09:56 ume Exp $"); + +#include "port_before.h" + +#include +#include +#include + +#include "port_after.h" + +/* + * Return the local network address portion of an + * internet address; handles class a/b/c network + * number formats. + */ +in_addr_t +inet_lnaof(in) + struct in_addr in; +{ + in_addr_t i = ntohl(in.s_addr); + + if (IN_CLASSA(i)) + return ((i)&IN_CLASSA_HOST); + else if (IN_CLASSB(i)) + return ((i)&IN_CLASSB_HOST); + else + return ((i)&IN_CLASSC_HOST); +} + +/* + * Weak aliases for applications that use certain private entry points, + * and fail to include . + */ +#undef inet_lnaof +__weak_reference(__inet_lnaof, inet_lnaof); diff --git a/lib/libc/inet/inet_makeaddr.c b/lib/libc/inet/inet_makeaddr.c new file mode 100644 index 0000000..3ea0400 --- /dev/null +++ b/lib/libc/inet/inet_makeaddr.c @@ -0,0 +1,75 @@ +/* + * Copyright (c) 1983, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static const char sccsid[] = "@(#)inet_makeaddr.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/inet/inet_makeaddr.c,v 1.2.2.1 2006/07/17 10:09:56 ume Exp $"); + +#include "port_before.h" + +#include +#include +#include + +#include "port_after.h" + +/* + * Formulate an Internet address from network + host. Used in + * building addresses stored in the ifnet structure. + */ +struct in_addr +inet_makeaddr(net, host) + in_addr_t net, host; +{ + struct in_addr a; + + if (net < 128U) + a.s_addr = (net << IN_CLASSA_NSHIFT) | (host & IN_CLASSA_HOST); + else if (net < 65536U) + a.s_addr = (net << IN_CLASSB_NSHIFT) | (host & IN_CLASSB_HOST); + else if (net < 16777216L) + a.s_addr = (net << IN_CLASSC_NSHIFT) | (host & IN_CLASSC_HOST); + else + a.s_addr = net | host; + a.s_addr = htonl(a.s_addr); + return (a); +} + +/* + * Weak aliases for applications that use certain private entry points, + * and fail to include . + */ +#undef inet_makeaddr +__weak_reference(__inet_makeaddr, inet_makeaddr); diff --git a/lib/libc/inet/inet_net_ntop.c b/lib/libc/inet/inet_net_ntop.c new file mode 100644 index 0000000..1476e42 --- /dev/null +++ b/lib/libc/inet/inet_net_ntop.c @@ -0,0 +1,286 @@ +/* + * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC") + * Copyright (c) 1996,1999 by Internet Software Consortium. + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT + * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static const char rcsid[] = "$Id: inet_net_ntop.c 89 2016-01-12 00:20:40Z reddawg $"; +#endif +#include +__FBSDID("$FreeBSD: src/lib/libc/inet/inet_net_ntop.c,v 1.2.2.1 2006/07/17 10:09:56 ume Exp $"); + +#include "port_before.h" + +#include +#include +#include +#include + +#include +#include +#include +#include + +#include "port_after.h" + +#ifdef SPRINTF_CHAR +# define SPRINTF(x) strlen(sprintf/**/x) +#else +# define SPRINTF(x) ((size_t)sprintf x) +#endif + +static char * inet_net_ntop_ipv4(const u_char *src, int bits, char *dst, + size_t size); +static char * inet_net_ntop_ipv6(const u_char *src, int bits, char *dst, + size_t size); + +/* + * char * + * inet_net_ntop(af, src, bits, dst, size) + * convert network number from network to presentation format. + * generates CIDR style result always. + * return: + * pointer to dst, or NULL if an error occurred (check errno). + * author: + * Paul Vixie (ISC), July 1996 + */ +char * +inet_net_ntop(af, src, bits, dst, size) + int af; + const void *src; + int bits; + char *dst; + size_t size; +{ + switch (af) { + case AF_INET: + return (inet_net_ntop_ipv4(src, bits, dst, size)); + case AF_INET6: + return (inet_net_ntop_ipv6(src, bits, dst, size)); + default: + errno = EAFNOSUPPORT; + return (NULL); + } +} + +/* + * static char * + * inet_net_ntop_ipv4(src, bits, dst, size) + * convert IPv4 network number from network to presentation format. + * generates CIDR style result always. + * return: + * pointer to dst, or NULL if an error occurred (check errno). + * note: + * network byte order assumed. this means 192.5.5.240/28 has + * 0b11110000 in its fourth octet. + * author: + * Paul Vixie (ISC), July 1996 + */ +static char * +inet_net_ntop_ipv4(src, bits, dst, size) + const u_char *src; + int bits; + char *dst; + size_t size; +{ + char *odst = dst; + char *t; + u_int m; + int b; + + if (bits < 0 || bits > 32) { + errno = EINVAL; + return (NULL); + } + + if (bits == 0) { + if (size < sizeof "0") + goto emsgsize; + *dst++ = '0'; + size--; + *dst = '\0'; + } + + /* Format whole octets. */ + for (b = bits / 8; b > 0; b--) { + if (size <= sizeof "255.") + goto emsgsize; + t = dst; + dst += SPRINTF((dst, "%u", *src++)); + if (b > 1) { + *dst++ = '.'; + *dst = '\0'; + } + size -= (size_t)(dst - t); + } + + /* Format partial octet. */ + b = bits % 8; + if (b > 0) { + if (size <= sizeof ".255") + goto emsgsize; + t = dst; + if (dst != odst) + *dst++ = '.'; + m = ((1 << b) - 1) << (8 - b); + dst += SPRINTF((dst, "%u", *src & m)); + size -= (size_t)(dst - t); + } + + /* Format CIDR /width. */ + if (size <= sizeof "/32") + goto emsgsize; + dst += SPRINTF((dst, "/%u", bits)); + return (odst); + + emsgsize: + errno = EMSGSIZE; + return (NULL); +} + +/* + * static char * + * inet_net_ntop_ipv6(src, bits, fakebits, dst, size) + * convert IPv6 network number from network to presentation format. + * generates CIDR style result always. Picks the shortest representation + * unless the IP is really IPv4. + * always prints specified number of bits (bits). + * return: + * pointer to dst, or NULL if an error occurred (check errno). + * note: + * network byte order assumed. this means 192.5.5.240/28 has + * 0b11110000 in its fourth octet. + * author: + * Vadim Kogan (UCB), June 2001 + * Original version (IPv4) by Paul Vixie (ISC), July 1996 + */ + +static char * +inet_net_ntop_ipv6(const u_char *src, int bits, char *dst, size_t size) { + u_int m; + int b; + int p; + int zero_s, zero_l, tmp_zero_s, tmp_zero_l; + int i; + int is_ipv4 = 0; + unsigned char inbuf[16]; + char outbuf[sizeof("xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:255.255.255.255/128")]; + char *cp; + int words; + u_char *s; + + if (bits < 0 || bits > 128) { + errno = EINVAL; + return (NULL); + } + + cp = outbuf; + + if (bits == 0) { + *cp++ = ':'; + *cp++ = ':'; + *cp = '\0'; + } else { + /* Copy src to private buffer. Zero host part. */ + p = (bits + 7) / 8; + memcpy(inbuf, src, p); + memset(inbuf + p, 0, 16 - p); + b = bits % 8; + if (b != 0) { + m = ~0 << (8 - b); + inbuf[p-1] &= m; + } + + s = inbuf; + + /* how many words need to be displayed in output */ + words = (bits + 15) / 16; + if (words == 1) + words = 2; + + /* Find the longest substring of zero's */ + zero_s = zero_l = tmp_zero_s = tmp_zero_l = 0; + for (i = 0; i < (words * 2); i += 2) { + if ((s[i] | s[i+1]) == 0) { + if (tmp_zero_l == 0) + tmp_zero_s = i / 2; + tmp_zero_l++; + } else { + if (tmp_zero_l && zero_l < tmp_zero_l) { + zero_s = tmp_zero_s; + zero_l = tmp_zero_l; + tmp_zero_l = 0; + } + } + } + + if (tmp_zero_l && zero_l < tmp_zero_l) { + zero_s = tmp_zero_s; + zero_l = tmp_zero_l; + } + + if (zero_l != words && zero_s == 0 && ((zero_l == 6) || + ((zero_l == 5 && s[10] == 0xff && s[11] == 0xff) || + ((zero_l == 7 && s[14] != 0 && s[15] != 1))))) + is_ipv4 = 1; + + /* Format whole words. */ + for (p = 0; p < words; p++) { + if (zero_l != 0 && p >= zero_s && p < zero_s + zero_l) { + /* Time to skip some zeros */ + if (p == zero_s) + *cp++ = ':'; + if (p == words - 1) + *cp++ = ':'; + s++; + s++; + continue; + } + + if (is_ipv4 && p > 5 ) { + *cp++ = (p == 6) ? ':' : '.'; + cp += SPRINTF((cp, "%u", *s++)); + /* we can potentially drop the last octet */ + if (p != 7 || bits > 120) { + *cp++ = '.'; + cp += SPRINTF((cp, "%u", *s++)); + } + } else { + if (cp != outbuf) + *cp++ = ':'; + cp += SPRINTF((cp, "%x", *s * 256 + s[1])); + s += 2; + } + } + } + /* Format CIDR /width. */ + SPRINTF((cp, "/%u", bits)); + if (strlen(outbuf) + 1 > size) + goto emsgsize; + strcpy(dst, outbuf); + + return (dst); + +emsgsize: + errno = EMSGSIZE; + return (NULL); +} + +/* + * Weak aliases for applications that use certain private entry points, + * and fail to include . + */ +#undef inet_net_ntop +__weak_reference(__inet_net_ntop, inet_net_ntop); diff --git a/lib/libc/inet/inet_net_pton.c b/lib/libc/inet/inet_net_pton.c new file mode 100644 index 0000000..a7f8a39 --- /dev/null +++ b/lib/libc/inet/inet_net_pton.c @@ -0,0 +1,414 @@ +/* + * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC") + * Copyright (c) 1996,1999 by Internet Software Consortium. + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT + * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static const char rcsid[] = "$Id: inet_net_pton.c 89 2016-01-12 00:20:40Z reddawg $"; +#endif +#include +__FBSDID("$FreeBSD: src/lib/libc/inet/inet_net_pton.c,v 1.2.2.1 2006/07/17 10:09:56 ume Exp $"); + +#include "port_before.h" + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include "port_after.h" + +#ifdef SPRINTF_CHAR +# define SPRINTF(x) strlen(sprintf/**/x) +#else +# define SPRINTF(x) ((size_t)sprintf x) +#endif + +/* + * static int + * inet_net_pton_ipv4(src, dst, size) + * convert IPv4 network number from presentation to network format. + * accepts hex octets, hex strings, decimal octets, and /CIDR. + * "size" is in bytes and describes "dst". + * return: + * number of bits, either imputed classfully or specified with /CIDR, + * or -1 if some failure occurred (check errno). ENOENT means it was + * not an IPv4 network specification. + * note: + * network byte order assumed. this means 192.5.5.240/28 has + * 0b11110000 in its fourth octet. + * author: + * Paul Vixie (ISC), June 1996 + */ +static int +inet_net_pton_ipv4(const char *src, u_char *dst, size_t size) { + static const char xdigits[] = "0123456789abcdef"; + static const char digits[] = "0123456789"; + int n, ch, tmp = 0, dirty, bits; + const u_char *odst = dst; + + ch = *src++; + if (ch == '0' && (src[0] == 'x' || src[0] == 'X') + && isascii((unsigned char)(src[1])) + && isxdigit((unsigned char)(src[1]))) { + /* Hexadecimal: Eat nybble string. */ + if (size <= 0U) + goto emsgsize; + dirty = 0; + src++; /* skip x or X. */ + while ((ch = *src++) != '\0' && isascii(ch) && isxdigit(ch)) { + if (isupper(ch)) + ch = tolower(ch); + n = strchr(xdigits, ch) - xdigits; + assert(n >= 0 && n <= 15); + if (dirty == 0) + tmp = n; + else + tmp = (tmp << 4) | n; + if (++dirty == 2) { + if (size-- <= 0U) + goto emsgsize; + *dst++ = (u_char) tmp; + dirty = 0; + } + } + if (dirty) { /* Odd trailing nybble? */ + if (size-- <= 0U) + goto emsgsize; + *dst++ = (u_char) (tmp << 4); + } + } else if (isascii(ch) && isdigit(ch)) { + /* Decimal: eat dotted digit string. */ + for (;;) { + tmp = 0; + do { + n = strchr(digits, ch) - digits; + assert(n >= 0 && n <= 9); + tmp *= 10; + tmp += n; + if (tmp > 255) + goto enoent; + } while ((ch = *src++) != '\0' && + isascii(ch) && isdigit(ch)); + if (size-- <= 0U) + goto emsgsize; + *dst++ = (u_char) tmp; + if (ch == '\0' || ch == '/') + break; + if (ch != '.') + goto enoent; + ch = *src++; + if (!isascii(ch) || !isdigit(ch)) + goto enoent; + } + } else + goto enoent; + + bits = -1; + if (ch == '/' && isascii((unsigned char)(src[0])) && + isdigit((unsigned char)(src[0])) && dst > odst) { + /* CIDR width specifier. Nothing can follow it. */ + ch = *src++; /* Skip over the /. */ + bits = 0; + do { + n = strchr(digits, ch) - digits; + assert(n >= 0 && n <= 9); + bits *= 10; + bits += n; + } while ((ch = *src++) != '\0' && isascii(ch) && isdigit(ch)); + if (ch != '\0') + goto enoent; + if (bits > 32) + goto emsgsize; + } + + /* Firey death and destruction unless we prefetched EOS. */ + if (ch != '\0') + goto enoent; + + /* If nothing was written to the destination, we found no address. */ + if (dst == odst) + goto enoent; + /* If no CIDR spec was given, infer width from net class. */ + if (bits == -1) { + if (*odst >= 240) /* Class E */ + bits = 32; + else if (*odst >= 224) /* Class D */ + bits = 8; + else if (*odst >= 192) /* Class C */ + bits = 24; + else if (*odst >= 128) /* Class B */ + bits = 16; + else /* Class A */ + bits = 8; + /* If imputed mask is narrower than specified octets, widen. */ + if (bits < ((dst - odst) * 8)) + bits = (dst - odst) * 8; + /* + * If there are no additional bits specified for a class D + * address adjust bits to 4. + */ + if (bits == 8 && *odst == 224) + bits = 4; + } + /* Extend network to cover the actual mask. */ + while (bits > ((dst - odst) * 8)) { + if (size-- <= 0U) + goto emsgsize; + *dst++ = '\0'; + } + return (bits); + + enoent: + errno = ENOENT; + return (-1); + + emsgsize: + errno = EMSGSIZE; + return (-1); +} + +static int +getbits(const char *src, int *bitsp) { + static const char digits[] = "0123456789"; + int n; + int val; + char ch; + + val = 0; + n = 0; + while ((ch = *src++) != '\0') { + const char *pch; + + pch = strchr(digits, ch); + if (pch != NULL) { + if (n++ != 0 && val == 0) /* no leading zeros */ + return (0); + val *= 10; + val += (pch - digits); + if (val > 128) /* range */ + return (0); + continue; + } + return (0); + } + if (n == 0) + return (0); + *bitsp = val; + return (1); +} + +static int +getv4(const char *src, u_char *dst, int *bitsp) { + static const char digits[] = "0123456789"; + u_char *odst = dst; + int n; + u_int val; + char ch; + + val = 0; + n = 0; + while ((ch = *src++) != '\0') { + const char *pch; + + pch = strchr(digits, ch); + if (pch != NULL) { + if (n++ != 0 && val == 0) /* no leading zeros */ + return (0); + val *= 10; + val += (pch - digits); + if (val > 255) /* range */ + return (0); + continue; + } + if (ch == '.' || ch == '/') { + if (dst - odst > 3) /* too many octets? */ + return (0); + *dst++ = val; + if (ch == '/') + return (getbits(src, bitsp)); + val = 0; + n = 0; + continue; + } + return (0); + } + if (n == 0) + return (0); + if (dst - odst > 3) /* too many octets? */ + return (0); + *dst++ = val; + return (1); +} + +static int +inet_net_pton_ipv6(const char *src, u_char *dst, size_t size) { + static const char xdigits_l[] = "0123456789abcdef", + xdigits_u[] = "0123456789ABCDEF"; + u_char tmp[NS_IN6ADDRSZ], *tp, *endp, *colonp; + const char *xdigits, *curtok; + int ch, saw_xdigit; + u_int val; + int digits; + int bits; + size_t bytes; + int words; + int ipv4; + + memset((tp = tmp), '\0', NS_IN6ADDRSZ); + endp = tp + NS_IN6ADDRSZ; + colonp = NULL; + /* Leading :: requires some special handling. */ + if (*src == ':') + if (*++src != ':') + goto enoent; + curtok = src; + saw_xdigit = 0; + val = 0; + digits = 0; + bits = -1; + ipv4 = 0; + while ((ch = *src++) != '\0') { + const char *pch; + + if ((pch = strchr((xdigits = xdigits_l), ch)) == NULL) + pch = strchr((xdigits = xdigits_u), ch); + if (pch != NULL) { + val <<= 4; + val |= (pch - xdigits); + if (++digits > 4) + goto enoent; + saw_xdigit = 1; + continue; + } + if (ch == ':') { + curtok = src; + if (!saw_xdigit) { + if (colonp) + goto enoent; + colonp = tp; + continue; + } else if (*src == '\0') + goto enoent; + if (tp + NS_INT16SZ > endp) + return (0); + *tp++ = (u_char) (val >> 8) & 0xff; + *tp++ = (u_char) val & 0xff; + saw_xdigit = 0; + digits = 0; + val = 0; + continue; + } + if (ch == '.' && ((tp + NS_INADDRSZ) <= endp) && + getv4(curtok, tp, &bits) > 0) { + tp += NS_INADDRSZ; + saw_xdigit = 0; + ipv4 = 1; + break; /* '\0' was seen by inet_pton4(). */ + } + if (ch == '/' && getbits(src, &bits) > 0) + break; + goto enoent; + } + if (saw_xdigit) { + if (tp + NS_INT16SZ > endp) + goto enoent; + *tp++ = (u_char) (val >> 8) & 0xff; + *tp++ = (u_char) val & 0xff; + } + if (bits == -1) + bits = 128; + + words = (bits + 15) / 16; + if (words < 2) + words = 2; + if (ipv4) + words = 8; + endp = tmp + 2 * words; + + if (colonp != NULL) { + /* + * Since some memmove()'s erroneously fail to handle + * overlapping regions, we'll do the shift by hand. + */ + const int n = tp - colonp; + int i; + + if (tp == endp) + goto enoent; + for (i = 1; i <= n; i++) { + endp[- i] = colonp[n - i]; + colonp[n - i] = 0; + } + tp = endp; + } + if (tp != endp) + goto enoent; + + bytes = (bits + 7) / 8; + if (bytes > size) + goto emsgsize; + memcpy(dst, tmp, bytes); + return (bits); + + enoent: + errno = ENOENT; + return (-1); + + emsgsize: + errno = EMSGSIZE; + return (-1); +} + +/* + * int + * inet_net_pton(af, src, dst, size) + * convert network number from presentation to network format. + * accepts hex octets, hex strings, decimal octets, and /CIDR. + * "size" is in bytes and describes "dst". + * return: + * number of bits, either imputed classfully or specified with /CIDR, + * or -1 if some failure occurred (check errno). ENOENT means it was + * not a valid network specification. + * author: + * Paul Vixie (ISC), June 1996 + */ +int +inet_net_pton(int af, const char *src, void *dst, size_t size) { + switch (af) { + case AF_INET: + return (inet_net_pton_ipv4(src, dst, size)); + case AF_INET6: + return (inet_net_pton_ipv6(src, dst, size)); + default: + errno = EAFNOSUPPORT; + return (-1); + } +} + +/* + * Weak aliases for applications that use certain private entry points, + * and fail to include . + */ +#undef inet_net_pton +__weak_reference(__inet_net_pton, inet_net_pton); diff --git a/lib/libc/inet/inet_neta.c b/lib/libc/inet/inet_neta.c new file mode 100644 index 0000000..728958c --- /dev/null +++ b/lib/libc/inet/inet_neta.c @@ -0,0 +1,96 @@ +/* + * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC") + * Copyright (c) 1996,1999 by Internet Software Consortium. + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT + * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static const char rcsid[] = "$Id: inet_neta.c 89 2016-01-12 00:20:40Z reddawg $"; +#endif +#include +__FBSDID("$FreeBSD: src/lib/libc/inet/inet_neta.c,v 1.2.2.1 2006/07/17 10:09:56 ume Exp $"); + +#include "port_before.h" + +#include +#include +#include +#include + +#include +#include +#include + +#include "port_after.h" + +#ifdef SPRINTF_CHAR +# define SPRINTF(x) strlen(sprintf/**/x) +#else +# define SPRINTF(x) ((size_t)sprintf x) +#endif + +/* + * char * + * inet_neta(src, dst, size) + * format an in_addr_t network number into presentation format. + * return: + * pointer to dst, or NULL if an error occurred (check errno). + * note: + * format of ``src'' is as for inet_network(). + * author: + * Paul Vixie (ISC), July 1996 + */ +char * +inet_neta(src, dst, size) + in_addr_t src; + char *dst; + size_t size; +{ + char *odst = dst; + char *tp; + + while (src & 0xffffffff) { + u_char b = (src & 0xff000000) >> 24; + + src <<= 8; + if (b) { + if (size < sizeof "255.") + goto emsgsize; + tp = dst; + dst += SPRINTF((dst, "%u", b)); + if (src != 0L) { + *dst++ = '.'; + *dst = '\0'; + } + size -= (size_t)(dst - tp); + } + } + if (dst == odst) { + if (size < sizeof "0.0.0.0") + goto emsgsize; + strcpy(dst, "0.0.0.0"); + } + return (odst); + + emsgsize: + errno = EMSGSIZE; + return (NULL); +} + +/* + * Weak aliases for applications that use certain private entry points, + * and fail to include . + */ +#undef inet_neta +__weak_reference(__inet_neta, inet_neta); diff --git a/lib/libc/inet/inet_netof.c b/lib/libc/inet/inet_netof.c new file mode 100644 index 0000000..d577ee4 --- /dev/null +++ b/lib/libc/inet/inet_netof.c @@ -0,0 +1,71 @@ +/* + * Copyright (c) 1983, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static const char sccsid[] = "@(#)inet_netof.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/inet/inet_netof.c,v 1.2.2.1 2006/07/17 10:09:56 ume Exp $"); + +#include "port_before.h" + +#include +#include +#include + +#include "port_after.h" + +/* + * Return the network number from an internet + * address; handles class a/b/c network #'s. + */ +in_addr_t +inet_netof(in) + struct in_addr in; +{ + in_addr_t i = ntohl(in.s_addr); + + if (IN_CLASSA(i)) + return (((i)&IN_CLASSA_NET) >> IN_CLASSA_NSHIFT); + else if (IN_CLASSB(i)) + return (((i)&IN_CLASSB_NET) >> IN_CLASSB_NSHIFT); + else + return (((i)&IN_CLASSC_NET) >> IN_CLASSC_NSHIFT); +} + +/* + * Weak aliases for applications that use certain private entry points, + * and fail to include . + */ +#undef inet_netof +__weak_reference(__inet_netof, inet_netof); diff --git a/lib/libc/inet/inet_network.c b/lib/libc/inet/inet_network.c new file mode 100644 index 0000000..8586441 --- /dev/null +++ b/lib/libc/inet/inet_network.c @@ -0,0 +1,113 @@ +/* + * Copyright (c) 1983, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static const char sccsid[] = "@(#)inet_network.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/inet/inet_network.c,v 1.2.2.1 2006/07/17 10:09:56 ume Exp $"); + +#include "port_before.h" + +#include +#include +#include +#include + +#include "port_after.h" + +/* + * Internet network address interpretation routine. + * The library routines call this routine to interpret + * network numbers. + */ +in_addr_t +inet_network(cp) + const char *cp; +{ + in_addr_t val, base, n; + char c; + in_addr_t parts[4], *pp = parts; + int i, digit; + +again: + val = 0; base = 10; digit = 0; + if (*cp == '0') + digit = 1, base = 8, cp++; + if (*cp == 'x' || *cp == 'X') + base = 16, cp++; + while ((c = *cp) != 0) { + if (isdigit((unsigned char)c)) { + if (base == 8U && (c == '8' || c == '9')) + return (INADDR_NONE); + val = (val * base) + (c - '0'); + cp++; + digit = 1; + continue; + } + if (base == 16U && isxdigit((unsigned char)c)) { + val = (val << 4) + + (c + 10 - (islower((unsigned char)c) ? 'a' : 'A')); + cp++; + digit = 1; + continue; + } + break; + } + if (!digit) + return (INADDR_NONE); + if (*cp == '.') { + if (pp >= parts + 4 || val > 0xffU) + return (INADDR_NONE); + *pp++ = val, cp++; + goto again; + } + if (*cp && !isspace(*cp&0xff)) + return (INADDR_NONE); + *pp++ = val; + n = pp - parts; + if (n > 4U) + return (INADDR_NONE); + for (val = 0, i = 0; i < n; i++) { + val <<= 8; + val |= parts[i] & 0xff; + } + return (val); +} + +/* + * Weak aliases for applications that use certain private entry points, + * and fail to include . + */ +#undef inet_network +__weak_reference(__inet_network, inet_network); diff --git a/lib/libc/inet/inet_ntoa.c b/lib/libc/inet/inet_ntoa.c new file mode 100644 index 0000000..8aaa81f --- /dev/null +++ b/lib/libc/inet/inet_ntoa.c @@ -0,0 +1,71 @@ +/* + * Copyright (c) 1983, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static const char sccsid[] = "@(#)inet_ntoa.c 8.1 (Berkeley) 6/4/93"; +static const char rcsid[] = "$Id: inet_ntoa.c 89 2016-01-12 00:20:40Z reddawg $"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/inet/inet_ntoa.c,v 1.2.2.1 2006/07/17 10:09:56 ume Exp $"); + +#include "port_before.h" + +#include +#include +#include +#include + +#include +#include + +#include "port_after.h" + +/* + * Convert network-format internet address + * to base 256 d.d.d.d representation. + */ +/*const*/ char * +inet_ntoa(struct in_addr in) { + static char ret[18]; + + strcpy(ret, "[inet_ntoa error]"); + (void) inet_ntop(AF_INET, &in, ret, sizeof ret); + return (ret); +} + +/* + * Weak aliases for applications that use certain private entry points, + * and fail to include . + */ +#undef inet_ntoa +__weak_reference(__inet_ntoa, inet_ntoa); diff --git a/lib/libc/inet/inet_ntop.c b/lib/libc/inet/inet_ntop.c new file mode 100644 index 0000000..ec5ea4e --- /dev/null +++ b/lib/libc/inet/inet_ntop.c @@ -0,0 +1,201 @@ +/* + * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC") + * Copyright (c) 1996-1999 by Internet Software Consortium. + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT + * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static const char rcsid[] = "$Id: inet_ntop.c 89 2016-01-12 00:20:40Z reddawg $"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/inet/inet_ntop.c,v 1.2.2.1 2006/07/17 10:09:56 ume Exp $"); + +#include "port_before.h" + +#include +#include +#include + +#include +#include +#include + +#include +#include +#include + +#include "port_after.h" + +/* + * WARNING: Don't even consider trying to compile this on a system where + * sizeof(int) < 4. sizeof(int) > 4 is fine; all the world's not a VAX. + */ + +static const char *inet_ntop4(const u_char *src, char *dst, socklen_t size); +static const char *inet_ntop6(const u_char *src, char *dst, socklen_t size); + +/* char * + * inet_ntop(af, src, dst, size) + * convert a network format address to presentation format. + * return: + * pointer to presentation format address (`dst'), or NULL (see errno). + * author: + * Paul Vixie, 1996. + */ +const char * +inet_ntop(int af, const void * __restrict src, char * __restrict dst, + socklen_t size) +{ + switch (af) { + case AF_INET: + return (inet_ntop4(src, dst, size)); + case AF_INET6: + return (inet_ntop6(src, dst, size)); + default: + errno = EAFNOSUPPORT; + return (NULL); + } + /* NOTREACHED */ +} + +/* const char * + * inet_ntop4(src, dst, size) + * format an IPv4 address + * return: + * `dst' (as a const) + * notes: + * (1) uses no statics + * (2) takes a u_char* not an in_addr as input + * author: + * Paul Vixie, 1996. + */ +static const char * +inet_ntop4(const u_char *src, char *dst, socklen_t size) +{ + static const char fmt[] = "%u.%u.%u.%u"; + char tmp[sizeof "255.255.255.255"]; + int l; + + l = snprintf(tmp, sizeof(tmp), fmt, src[0], src[1], src[2], src[3]); + if (l <= 0 || (socklen_t) l >= size) { + errno = ENOSPC; + return (NULL); + } + strlcpy(dst, tmp, size); + return (dst); +} + +/* const char * + * inet_ntop6(src, dst, size) + * convert IPv6 binary address into presentation (printable) format + * author: + * Paul Vixie, 1996. + */ +static const char * +inet_ntop6(const u_char *src, char *dst, socklen_t size) +{ + /* + * Note that int32_t and int16_t need only be "at least" large enough + * to contain a value of the specified size. On some systems, like + * Crays, there is no such thing as an integer variable with 16 bits. + * Keep this in mind if you think this function should have been coded + * to use pointer overlays. All the world's not a VAX. + */ + char tmp[sizeof "ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255"], *tp; + struct { int base, len; } best, cur; + u_int words[NS_IN6ADDRSZ / NS_INT16SZ]; + int i; + + /* + * Preprocess: + * Copy the input (bytewise) array into a wordwise array. + * Find the longest run of 0x00's in src[] for :: shorthanding. + */ + memset(words, '\0', sizeof words); + for (i = 0; i < NS_IN6ADDRSZ; i++) + words[i / 2] |= (src[i] << ((1 - (i % 2)) << 3)); + best.base = -1; + best.len = 0; + cur.base = -1; + cur.len = 0; + for (i = 0; i < (NS_IN6ADDRSZ / NS_INT16SZ); i++) { + if (words[i] == 0) { + if (cur.base == -1) + cur.base = i, cur.len = 1; + else + cur.len++; + } else { + if (cur.base != -1) { + if (best.base == -1 || cur.len > best.len) + best = cur; + cur.base = -1; + } + } + } + if (cur.base != -1) { + if (best.base == -1 || cur.len > best.len) + best = cur; + } + if (best.base != -1 && best.len < 2) + best.base = -1; + + /* + * Format the result. + */ + tp = tmp; + for (i = 0; i < (NS_IN6ADDRSZ / NS_INT16SZ); i++) { + /* Are we inside the best run of 0x00's? */ + if (best.base != -1 && i >= best.base && + i < (best.base + best.len)) { + if (i == best.base) + *tp++ = ':'; + continue; + } + /* Are we following an initial run of 0x00s or any real hex? */ + if (i != 0) + *tp++ = ':'; + /* Is this address an encapsulated IPv4? */ + if (i == 6 && best.base == 0 && (best.len == 6 || + (best.len == 7 && words[7] != 0x0001) || + (best.len == 5 && words[5] == 0xffff))) { + if (!inet_ntop4(src+12, tp, sizeof tmp - (tp - tmp))) + return (NULL); + tp += strlen(tp); + break; + } + tp += sprintf(tp, "%x", words[i]); + } + /* Was it a trailing run of 0x00's? */ + if (best.base != -1 && (best.base + best.len) == + (NS_IN6ADDRSZ / NS_INT16SZ)) + *tp++ = ':'; + *tp++ = '\0'; + + /* + * Check for overflow, copy, and we're done. + */ + if ((socklen_t)(tp - tmp) > size) { + errno = ENOSPC; + return (NULL); + } + strcpy(dst, tmp); + return (dst); +} + +/* + * Weak aliases for applications that use certain private entry points, + * and fail to include . + */ +#undef inet_ntop +__weak_reference(__inet_ntop, inet_ntop); diff --git a/lib/libc/inet/inet_pton.c b/lib/libc/inet/inet_pton.c new file mode 100644 index 0000000..b5a7b1f --- /dev/null +++ b/lib/libc/inet/inet_pton.c @@ -0,0 +1,223 @@ +/* + * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC") + * Copyright (c) 1996,1999 by Internet Software Consortium. + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT + * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static const char rcsid[] = "$Id: inet_pton.c 89 2016-01-12 00:20:40Z reddawg $"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/inet/inet_pton.c,v 1.2.2.1 2006/07/17 10:09:56 ume Exp $"); + +#include "port_before.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include "port_after.h" + +/* + * WARNING: Don't even consider trying to compile this on a system where + * sizeof(int) < 4. sizeof(int) > 4 is fine; all the world's not a VAX. + */ + +static int inet_pton4(const char *src, u_char *dst); +static int inet_pton6(const char *src, u_char *dst); + +/* int + * inet_pton(af, src, dst) + * convert from presentation format (which usually means ASCII printable) + * to network format (which is usually some kind of binary format). + * return: + * 1 if the address was valid for the specified address family + * 0 if the address wasn't valid (`dst' is untouched in this case) + * -1 if some other error occurred (`dst' is untouched in this case, too) + * author: + * Paul Vixie, 1996. + */ +int +inet_pton(int af, const char * __restrict src, void * __restrict dst) +{ + switch (af) { + case AF_INET: + return (inet_pton4(src, dst)); + case AF_INET6: + return (inet_pton6(src, dst)); + default: + errno = EAFNOSUPPORT; + return (-1); + } + /* NOTREACHED */ +} + +/* int + * inet_pton4(src, dst) + * like inet_aton() but without all the hexadecimal and shorthand. + * return: + * 1 if `src' is a valid dotted quad, else 0. + * notice: + * does not touch `dst' unless it's returning 1. + * author: + * Paul Vixie, 1996. + */ +static int +inet_pton4(const char *src, u_char *dst) +{ + static const char digits[] = "0123456789"; + int saw_digit, octets, ch; + u_char tmp[NS_INADDRSZ], *tp; + + saw_digit = 0; + octets = 0; + *(tp = tmp) = 0; + while ((ch = *src++) != '\0') { + const char *pch; + + if ((pch = strchr(digits, ch)) != NULL) { + u_int new = *tp * 10 + (pch - digits); + + if (saw_digit && *tp == 0) + return (0); + if (new > 255) + return (0); + *tp = new; + if (!saw_digit) { + if (++octets > 4) + return (0); + saw_digit = 1; + } + } else if (ch == '.' && saw_digit) { + if (octets == 4) + return (0); + *++tp = 0; + saw_digit = 0; + } else + return (0); + } + if (octets < 4) + return (0); + memcpy(dst, tmp, NS_INADDRSZ); + return (1); +} + +/* int + * inet_pton6(src, dst) + * convert presentation level address to network order binary form. + * return: + * 1 if `src' is a valid [RFC1884 2.2] address, else 0. + * notice: + * (1) does not touch `dst' unless it's returning 1. + * (2) :: in a full address is silently ignored. + * credit: + * inspired by Mark Andrews. + * author: + * Paul Vixie, 1996. + */ +static int +inet_pton6(const char *src, u_char *dst) +{ + static const char xdigits_l[] = "0123456789abcdef", + xdigits_u[] = "0123456789ABCDEF"; + u_char tmp[NS_IN6ADDRSZ], *tp, *endp, *colonp; + const char *xdigits, *curtok; + int ch, seen_xdigits; + u_int val; + + memset((tp = tmp), '\0', NS_IN6ADDRSZ); + endp = tp + NS_IN6ADDRSZ; + colonp = NULL; + /* Leading :: requires some special handling. */ + if (*src == ':') + if (*++src != ':') + return (0); + curtok = src; + seen_xdigits = 0; + val = 0; + while ((ch = *src++) != '\0') { + const char *pch; + + if ((pch = strchr((xdigits = xdigits_l), ch)) == NULL) + pch = strchr((xdigits = xdigits_u), ch); + if (pch != NULL) { + val <<= 4; + val |= (pch - xdigits); + if (++seen_xdigits > 4) + return (0); + continue; + } + if (ch == ':') { + curtok = src; + if (!seen_xdigits) { + if (colonp) + return (0); + colonp = tp; + continue; + } else if (*src == '\0') { + return (0); + } + if (tp + NS_INT16SZ > endp) + return (0); + *tp++ = (u_char) (val >> 8) & 0xff; + *tp++ = (u_char) val & 0xff; + seen_xdigits = 0; + val = 0; + continue; + } + if (ch == '.' && ((tp + NS_INADDRSZ) <= endp) && + inet_pton4(curtok, tp) > 0) { + tp += NS_INADDRSZ; + seen_xdigits = 0; + break; /* '\0' was seen by inet_pton4(). */ + } + return (0); + } + if (seen_xdigits) { + if (tp + NS_INT16SZ > endp) + return (0); + *tp++ = (u_char) (val >> 8) & 0xff; + *tp++ = (u_char) val & 0xff; + } + if (colonp != NULL) { + /* + * Since some memmove()'s erroneously fail to handle + * overlapping regions, we'll do the shift by hand. + */ + const int n = tp - colonp; + int i; + + if (tp == endp) + return (0); + for (i = 1; i <= n; i++) { + endp[- i] = colonp[n - i]; + colonp[n - i] = 0; + } + tp = endp; + } + if (tp != endp) + return (0); + memcpy(dst, tmp, NS_IN6ADDRSZ); + return (1); +} + +/* + * Weak aliases for applications that use certain private entry points, + * and fail to include . + */ +#undef inet_pton +__weak_reference(__inet_pton, inet_pton); diff --git a/lib/libc/inet/nsap_addr.c b/lib/libc/inet/nsap_addr.c new file mode 100644 index 0000000..e642477 --- /dev/null +++ b/lib/libc/inet/nsap_addr.c @@ -0,0 +1,120 @@ +/* + * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC") + * Copyright (c) 1996-1999 by Internet Software Consortium. + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT + * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static const char rcsid[] = "$Id: nsap_addr.c 89 2016-01-12 00:20:40Z reddawg $"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/inet/nsap_addr.c,v 1.2.2.1 2006/07/17 10:09:56 ume Exp $"); + +#include "port_before.h" + +#include +#include +#include + +#include +#include +#include + +#include +#include +#include + +#include "port_after.h" + +static char +xtob(int c) { + return (c - (((c >= '0') && (c <= '9')) ? '0' : '7')); +} + +u_int +inet_nsap_addr(const char *ascii, u_char *binary, int maxlen) { + u_char c, nib; + u_int len = 0; + + if (ascii[0] != '0' || (ascii[1] != 'x' && ascii[1] != 'X')) + return (0); + ascii += 2; + + while ((c = *ascii++) != '\0' && len < (u_int)maxlen) { + if (c == '.' || c == '+' || c == '/') + continue; + if (!isascii(c)) + return (0); + if (islower(c)) + c = toupper(c); + if (isxdigit(c)) { + nib = xtob(c); + c = *ascii++; + if (c != '\0') { + c = toupper(c); + if (isxdigit(c)) { + *binary++ = (nib << 4) | xtob(c); + len++; + } else + return (0); + } + else + return (0); + } + else + return (0); + } + return (len); +} + +char * +inet_nsap_ntoa(int binlen, const u_char *binary, char *ascii) { + int nib; + int i; + char *tmpbuf = inet_nsap_ntoa_tmpbuf; + char *start; + + if (ascii) + start = ascii; + else { + ascii = tmpbuf; + start = tmpbuf; + } + + *ascii++ = '0'; + *ascii++ = 'x'; + + if (binlen > 255) + binlen = 255; + + for (i = 0; i < binlen; i++) { + nib = *binary >> 4; + *ascii++ = nib + (nib < 10 ? '0' : '7'); + nib = *binary++ & 0x0f; + *ascii++ = nib + (nib < 10 ? '0' : '7'); + if (((i % 2) == 0 && (i + 1) < binlen)) + *ascii++ = '.'; + } + *ascii = '\0'; + return (start); +} + +/* + * Weak aliases for applications that use certain private entry points, + * and fail to include . + */ +#undef inet_nsap_addr +__weak_reference(__inet_nsap_addr, inet_nsap_addr); +#undef inet_nsap_ntoa +__weak_reference(__inet_nsap_ntoa, inet_nsap_ntoa); diff --git a/lib/libc/isc/Makefile b/lib/libc/isc/Makefile new file mode 100644 index 0000000..3866201 --- /dev/null +++ b/lib/libc/isc/Makefile @@ -0,0 +1,35 @@ +# $Id: Makefile 89 2016-01-12 00:20:40Z reddawg $ +# The System Makefile (C) 2002 The UbixOS Project + +# Include Global 'Source' Options +include ../../../Makefile.incl +include ../../Makefile.incl +include ../Makefile.incl + +INCLUDES += -I../locale/ + +#Objects +OBJS = ev_streams.o ev_timers.o + +all: $(OBJS) + +# Compile the source files +.cc.o: + $(CXX) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -c -o $@ $< + +.cc.s: + $(CXX) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -S -o $@ $< + +.c.o: + $(CC) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -c $< + +.c.s: + $(CC) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -S -o $@ $< + +.S.o: + $(CC) $(CFLAGS) -Wall -nostdlib -c -o $@ $< + +# Clean up the junk +clean: + $(REMOVE) $(OBJS) + diff --git a/lib/libc/isc/ev_streams.c b/lib/libc/isc/ev_streams.c new file mode 100644 index 0000000..b390a1a --- /dev/null +++ b/lib/libc/isc/ev_streams.c @@ -0,0 +1,316 @@ +/* + * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC") + * Copyright (c) 1996-1999 by Internet Software Consortium + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT + * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +/* ev_streams.c - implement asynch stream file IO for the eventlib + * vix 04mar96 [initial] + */ + +#if !defined(LINT) && !defined(CODECENTER) +static const char rcsid[] = "$Id: ev_streams.c 89 2016-01-12 00:20:40Z reddawg $"; +#endif +#include +__FBSDID("$FreeBSD: src/lib/libc/isc/ev_streams.c,v 1.2.2.1 2006/07/17 10:09:56 ume Exp $"); + +#include "port_before.h" +#ifndef _LIBC +#include "fd_setsize.h" +#endif + +#include +#include + +#include + +#include +#ifndef _LIBC +#include +#endif +#include "eventlib_p.h" + +#include "port_after.h" + +#ifndef _LIBC +static int copyvec(evStream *str, const struct iovec *iov, int iocnt); +static void consume(evStream *str, size_t bytes); +static void done(evContext opaqueCtx, evStream *str); +static void writable(evContext opaqueCtx, void *uap, int fd, int evmask); +static void readable(evContext opaqueCtx, void *uap, int fd, int evmask); +#endif + +struct iovec +evConsIovec(void *buf, size_t cnt) { + struct iovec ret; + + memset(&ret, 0xf5, sizeof ret); + ret.iov_base = buf; + ret.iov_len = cnt; + return (ret); +} + +#ifndef _LIBC +int +evWrite(evContext opaqueCtx, int fd, const struct iovec *iov, int iocnt, + evStreamFunc func, void *uap, evStreamID *id) +{ + evContext_p *ctx = opaqueCtx.opaque; + evStream *new; + int save; + + OKNEW(new); + new->func = func; + new->uap = uap; + new->fd = fd; + new->flags = 0; + if (evSelectFD(opaqueCtx, fd, EV_WRITE, writable, new, &new->file) < 0) + goto free; + if (copyvec(new, iov, iocnt) < 0) + goto free; + new->prevDone = NULL; + new->nextDone = NULL; + if (ctx->streams != NULL) + ctx->streams->prev = new; + new->prev = NULL; + new->next = ctx->streams; + ctx->streams = new; + if (id != NULL) + id->opaque = new; + return (0); + free: + save = errno; + FREE(new); + errno = save; + return (-1); +} + +int +evRead(evContext opaqueCtx, int fd, const struct iovec *iov, int iocnt, + evStreamFunc func, void *uap, evStreamID *id) +{ + evContext_p *ctx = opaqueCtx.opaque; + evStream *new; + int save; + + OKNEW(new); + new->func = func; + new->uap = uap; + new->fd = fd; + new->flags = 0; + if (evSelectFD(opaqueCtx, fd, EV_READ, readable, new, &new->file) < 0) + goto free; + if (copyvec(new, iov, iocnt) < 0) + goto free; + new->prevDone = NULL; + new->nextDone = NULL; + if (ctx->streams != NULL) + ctx->streams->prev = new; + new->prev = NULL; + new->next = ctx->streams; + ctx->streams = new; + if (id) + id->opaque = new; + return (0); + free: + save = errno; + FREE(new); + errno = save; + return (-1); +} + +int +evTimeRW(evContext opaqueCtx, evStreamID id, evTimerID timer) /*ARGSUSED*/ { + evStream *str = id.opaque; + + UNUSED(opaqueCtx); + + str->timer = timer; + str->flags |= EV_STR_TIMEROK; + return (0); +} + +int +evUntimeRW(evContext opaqueCtx, evStreamID id) /*ARGSUSED*/ { + evStream *str = id.opaque; + + UNUSED(opaqueCtx); + + str->flags &= ~EV_STR_TIMEROK; + return (0); +} + +int +evCancelRW(evContext opaqueCtx, evStreamID id) { + evContext_p *ctx = opaqueCtx.opaque; + evStream *old = id.opaque; + + /* + * The streams list is doubly threaded. First, there's ctx->streams + * that's used by evDestroy() to find and cancel all streams. Second, + * there's ctx->strDone (head) and ctx->strLast (tail) which thread + * through the potentially smaller number of "IO completed" streams, + * used in evGetNext() to avoid scanning the entire list. + */ + + /* Unlink from ctx->streams. */ + if (old->prev != NULL) + old->prev->next = old->next; + else + ctx->streams = old->next; + if (old->next != NULL) + old->next->prev = old->prev; + + /* + * If 'old' is on the ctx->strDone list, remove it. Update + * ctx->strLast if necessary. + */ + if (old->prevDone == NULL && old->nextDone == NULL) { + /* + * Either 'old' is the only item on the done list, or it's + * not on the done list. If the former, then we unlink it + * from the list. If the latter, we leave the list alone. + */ + if (ctx->strDone == old) { + ctx->strDone = NULL; + ctx->strLast = NULL; + } + } else { + if (old->prevDone != NULL) + old->prevDone->nextDone = old->nextDone; + else + ctx->strDone = old->nextDone; + if (old->nextDone != NULL) + old->nextDone->prevDone = old->prevDone; + else + ctx->strLast = old->prevDone; + } + + /* Deallocate the stream. */ + if (old->file.opaque) + evDeselectFD(opaqueCtx, old->file); + memput(old->iovOrig, sizeof (struct iovec) * old->iovOrigCount); + FREE(old); + return (0); +} + +/* Copy a scatter/gather vector and initialize a stream handler's IO. */ +static int +copyvec(evStream *str, const struct iovec *iov, int iocnt) { + int i; + + str->iovOrig = (struct iovec *)memget(sizeof(struct iovec) * iocnt); + if (str->iovOrig == NULL) { + errno = ENOMEM; + return (-1); + } + str->ioTotal = 0; + for (i = 0; i < iocnt; i++) { + str->iovOrig[i] = iov[i]; + str->ioTotal += iov[i].iov_len; + } + str->iovOrigCount = iocnt; + str->iovCur = str->iovOrig; + str->iovCurCount = str->iovOrigCount; + str->ioDone = 0; + return (0); +} + +/* Pull off or truncate lead iovec(s). */ +static void +consume(evStream *str, size_t bytes) { + while (bytes > 0U) { + if (bytes < (size_t)str->iovCur->iov_len) { + str->iovCur->iov_len -= bytes; + str->iovCur->iov_base = (void *) + ((u_char *)str->iovCur->iov_base + bytes); + str->ioDone += bytes; + bytes = 0; + } else { + bytes -= str->iovCur->iov_len; + str->ioDone += str->iovCur->iov_len; + str->iovCur++; + str->iovCurCount--; + } + } +} + +/* Add a stream to Done list and deselect the FD. */ +static void +done(evContext opaqueCtx, evStream *str) { + evContext_p *ctx = opaqueCtx.opaque; + + if (ctx->strLast != NULL) { + str->prevDone = ctx->strLast; + ctx->strLast->nextDone = str; + ctx->strLast = str; + } else { + INSIST(ctx->strDone == NULL); + ctx->strDone = ctx->strLast = str; + } + evDeselectFD(opaqueCtx, str->file); + str->file.opaque = NULL; + /* evDrop() will call evCancelRW() on us. */ +} + +/* Dribble out some bytes on the stream. (Called by evDispatch().) */ +static void +writable(evContext opaqueCtx, void *uap, int fd, int evmask) { + evStream *str = uap; + int bytes; + + UNUSED(evmask); + + bytes = writev(fd, str->iovCur, str->iovCurCount); + if (bytes > 0) { + if ((str->flags & EV_STR_TIMEROK) != 0) + evTouchIdleTimer(opaqueCtx, str->timer); + consume(str, bytes); + } else { + if (bytes < 0 && errno != EINTR) { + str->ioDone = -1; + str->ioErrno = errno; + } + } + if (str->ioDone == -1 || str->ioDone == str->ioTotal) + done(opaqueCtx, str); +} + +/* Scoop up some bytes from the stream. (Called by evDispatch().) */ +static void +readable(evContext opaqueCtx, void *uap, int fd, int evmask) { + evStream *str = uap; + int bytes; + + UNUSED(evmask); + + bytes = readv(fd, str->iovCur, str->iovCurCount); + if (bytes > 0) { + if ((str->flags & EV_STR_TIMEROK) != 0) + evTouchIdleTimer(opaqueCtx, str->timer); + consume(str, bytes); + } else { + if (bytes == 0) + str->ioDone = 0; + else { + if (errno != EINTR) { + str->ioDone = -1; + str->ioErrno = errno; + } + } + } + if (str->ioDone <= 0 || str->ioDone == str->ioTotal) + done(opaqueCtx, str); +} +#endif diff --git a/lib/libc/isc/ev_timers.c b/lib/libc/isc/ev_timers.c new file mode 100644 index 0000000..c514068 --- /dev/null +++ b/lib/libc/isc/ev_timers.c @@ -0,0 +1,513 @@ +/* + * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC") + * Copyright (c) 1995-1999 by Internet Software Consortium + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT + * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +/* ev_timers.c - implement timers for the eventlib + * vix 09sep95 [initial] + */ + +#if !defined(LINT) && !defined(CODECENTER) +static const char rcsid[] = "$Id: ev_timers.c 89 2016-01-12 00:20:40Z reddawg $"; +#endif +#include +__FBSDID("$FreeBSD: src/lib/libc/isc/ev_timers.c,v 1.2.2.1 2006/07/17 10:09:56 ume Exp $"); + +/* Import. */ + +#include "port_before.h" +#ifndef _LIBC +#include "fd_setsize.h" +#endif + +#include + +#ifndef _LIBC +#include +#endif +#include +#include "eventlib_p.h" + +#include "port_after.h" + +/* Constants. */ + +#define MILLION 1000000 +#define BILLION 1000000000 + +/* Forward. */ + +#ifdef _LIBC +static int __evOptMonoTime; +#else +static int due_sooner(void *, void *); +static void set_index(void *, int); +static void free_timer(void *, void *); +static void print_timer(void *, void *); +static void idle_timeout(evContext, void *, struct timespec, struct timespec); + +/* Private type. */ + +typedef struct { + evTimerFunc func; + void * uap; + struct timespec lastTouched; + struct timespec max_idle; + evTimer * timer; +} idle_timer; +#endif + +/* Public. */ + +struct timespec +evConsTime(time_t sec, long nsec) { + struct timespec x; + + x.tv_sec = sec; + x.tv_nsec = nsec; + return (x); +} + +struct timespec +evAddTime(struct timespec addend1, struct timespec addend2) { + struct timespec x; + + x.tv_sec = addend1.tv_sec + addend2.tv_sec; + x.tv_nsec = addend1.tv_nsec + addend2.tv_nsec; + if (x.tv_nsec >= BILLION) { + x.tv_sec++; + x.tv_nsec -= BILLION; + } + return (x); +} + +struct timespec +evSubTime(struct timespec minuend, struct timespec subtrahend) { + struct timespec x; + + x.tv_sec = minuend.tv_sec - subtrahend.tv_sec; + if (minuend.tv_nsec >= subtrahend.tv_nsec) + x.tv_nsec = minuend.tv_nsec - subtrahend.tv_nsec; + else { + x.tv_nsec = BILLION - subtrahend.tv_nsec + minuend.tv_nsec; + x.tv_sec--; + } + return (x); +} + +int +evCmpTime(struct timespec a, struct timespec b) { + long x = a.tv_sec - b.tv_sec; + + if (x == 0L) + x = a.tv_nsec - b.tv_nsec; + return (x < 0L ? (-1) : x > 0L ? (1) : (0)); +} + +struct timespec +evNowTime() { + struct timeval now; +#ifdef CLOCK_REALTIME + struct timespec tsnow; + int m = CLOCK_REALTIME; + +#ifdef CLOCK_MONOTONIC + if (__evOptMonoTime) + m = CLOCK_MONOTONIC; +#endif + if (clock_gettime(m, &tsnow) == 0) + return (tsnow); +#endif + if (gettimeofday(&now, NULL) < 0) + return (evConsTime(0, 0)); + return (evTimeSpec(now)); +} + +struct timespec +evUTCTime() { + struct timeval now; +#ifdef CLOCK_REALTIME + struct timespec tsnow; + if (clock_gettime(CLOCK_REALTIME, &tsnow) == 0) + return (tsnow); +#endif + if (gettimeofday(&now, NULL) < 0) + return (evConsTime(0, 0)); + return (evTimeSpec(now)); +} + +#ifndef _LIBC +struct timespec +evLastEventTime(evContext opaqueCtx) { + evContext_p *ctx = opaqueCtx.opaque; + + return (ctx->lastEventTime); +} +#endif + +struct timespec +evTimeSpec(struct timeval tv) { + struct timespec ts; + + ts.tv_sec = tv.tv_sec; + ts.tv_nsec = tv.tv_usec * 1000; + return (ts); +} + +#if !defined(USE_KQUEUE) || !defined(_LIBC) +struct timeval +evTimeVal(struct timespec ts) { + struct timeval tv; + + tv.tv_sec = ts.tv_sec; + tv.tv_usec = ts.tv_nsec / 1000; + return (tv); +} +#endif + +#ifndef _LIBC +int +evSetTimer(evContext opaqueCtx, + evTimerFunc func, + void *uap, + struct timespec due, + struct timespec inter, + evTimerID *opaqueID +) { + evContext_p *ctx = opaqueCtx.opaque; + evTimer *id; + + evPrintf(ctx, 1, +"evSetTimer(ctx %p, func %p, uap %p, due %ld.%09ld, inter %ld.%09ld)\n", + ctx, func, uap, + (long)due.tv_sec, due.tv_nsec, + (long)inter.tv_sec, inter.tv_nsec); + +#ifdef __hpux + /* + * tv_sec and tv_nsec are unsigned. + */ + if (due.tv_nsec >= BILLION) + EV_ERR(EINVAL); + + if (inter.tv_nsec >= BILLION) + EV_ERR(EINVAL); +#else + if (due.tv_sec < 0 || due.tv_nsec < 0 || due.tv_nsec >= BILLION) + EV_ERR(EINVAL); + + if (inter.tv_sec < 0 || inter.tv_nsec < 0 || inter.tv_nsec >= BILLION) + EV_ERR(EINVAL); +#endif + + /* due={0,0} is a magic cookie meaning "now." */ + if (due.tv_sec == (time_t)0 && due.tv_nsec == 0L) + due = evNowTime(); + + /* Allocate and fill. */ + OKNEW(id); + id->func = func; + id->uap = uap; + id->due = due; + id->inter = inter; + + if (heap_insert(ctx->timers, id) < 0) + return (-1); + + /* Remember the ID if the caller provided us a place for it. */ + if (opaqueID) + opaqueID->opaque = id; + + if (ctx->debug > 7) { + evPrintf(ctx, 7, "timers after evSetTimer:\n"); + (void) heap_for_each(ctx->timers, print_timer, (void *)ctx); + } + + return (0); +} + +int +evClearTimer(evContext opaqueCtx, evTimerID id) { + evContext_p *ctx = opaqueCtx.opaque; + evTimer *del = id.opaque; + + if (ctx->cur != NULL && + ctx->cur->type == Timer && + ctx->cur->u.timer.this == del) { + evPrintf(ctx, 8, "deferring delete of timer (executing)\n"); + /* + * Setting the interval to zero ensures that evDrop() will + * clean up the timer. + */ + del->inter = evConsTime(0, 0); + return (0); + } + + if (heap_element(ctx->timers, del->index) != del) + EV_ERR(ENOENT); + + if (heap_delete(ctx->timers, del->index) < 0) + return (-1); + FREE(del); + + if (ctx->debug > 7) { + evPrintf(ctx, 7, "timers after evClearTimer:\n"); + (void) heap_for_each(ctx->timers, print_timer, (void *)ctx); + } + + return (0); +} + +int +evConfigTimer(evContext opaqueCtx, + evTimerID id, + const char *param, + int value +) { + evContext_p *ctx = opaqueCtx.opaque; + evTimer *timer = id.opaque; + int result=0; + + UNUSED(value); + + if (heap_element(ctx->timers, timer->index) != timer) + EV_ERR(ENOENT); + + if (strcmp(param, "rate") == 0) + timer->mode |= EV_TMR_RATE; + else if (strcmp(param, "interval") == 0) + timer->mode &= ~EV_TMR_RATE; + else + EV_ERR(EINVAL); + + return (result); +} + +int +evResetTimer(evContext opaqueCtx, + evTimerID id, + evTimerFunc func, + void *uap, + struct timespec due, + struct timespec inter +) { + evContext_p *ctx = opaqueCtx.opaque; + evTimer *timer = id.opaque; + struct timespec old_due; + int result=0; + + if (heap_element(ctx->timers, timer->index) != timer) + EV_ERR(ENOENT); + +#ifdef __hpux + /* + * tv_sec and tv_nsec are unsigned. + */ + if (due.tv_nsec >= BILLION) + EV_ERR(EINVAL); + + if (inter.tv_nsec >= BILLION) + EV_ERR(EINVAL); +#else + if (due.tv_sec < 0 || due.tv_nsec < 0 || due.tv_nsec >= BILLION) + EV_ERR(EINVAL); + + if (inter.tv_sec < 0 || inter.tv_nsec < 0 || inter.tv_nsec >= BILLION) + EV_ERR(EINVAL); +#endif + + old_due = timer->due; + + timer->func = func; + timer->uap = uap; + timer->due = due; + timer->inter = inter; + + switch (evCmpTime(due, old_due)) { + case -1: + result = heap_increased(ctx->timers, timer->index); + break; + case 0: + result = 0; + break; + case 1: + result = heap_decreased(ctx->timers, timer->index); + break; + } + + if (ctx->debug > 7) { + evPrintf(ctx, 7, "timers after evResetTimer:\n"); + (void) heap_for_each(ctx->timers, print_timer, (void *)ctx); + } + + return (result); +} + +int +evSetIdleTimer(evContext opaqueCtx, + evTimerFunc func, + void *uap, + struct timespec max_idle, + evTimerID *opaqueID +) { + evContext_p *ctx = opaqueCtx.opaque; + idle_timer *tt; + + /* Allocate and fill. */ + OKNEW(tt); + tt->func = func; + tt->uap = uap; + tt->lastTouched = ctx->lastEventTime; + tt->max_idle = max_idle; + + if (evSetTimer(opaqueCtx, idle_timeout, tt, + evAddTime(ctx->lastEventTime, max_idle), + max_idle, opaqueID) < 0) { + FREE(tt); + return (-1); + } + + tt->timer = opaqueID->opaque; + + return (0); +} + +int +evClearIdleTimer(evContext opaqueCtx, evTimerID id) { + evTimer *del = id.opaque; + idle_timer *tt = del->uap; + + FREE(tt); + return (evClearTimer(opaqueCtx, id)); +} + +int +evResetIdleTimer(evContext opaqueCtx, + evTimerID opaqueID, + evTimerFunc func, + void *uap, + struct timespec max_idle +) { + evContext_p *ctx = opaqueCtx.opaque; + evTimer *timer = opaqueID.opaque; + idle_timer *tt = timer->uap; + + tt->func = func; + tt->uap = uap; + tt->lastTouched = ctx->lastEventTime; + tt->max_idle = max_idle; + + return (evResetTimer(opaqueCtx, opaqueID, idle_timeout, tt, + evAddTime(ctx->lastEventTime, max_idle), + max_idle)); +} + +int +evTouchIdleTimer(evContext opaqueCtx, evTimerID id) { + evContext_p *ctx = opaqueCtx.opaque; + evTimer *t = id.opaque; + idle_timer *tt = t->uap; + + tt->lastTouched = ctx->lastEventTime; + + return (0); +} + +/* Public to the rest of eventlib. */ + +heap_context +evCreateTimers(const evContext_p *ctx) { + + UNUSED(ctx); + + return (heap_new(due_sooner, set_index, 2048)); +} + +void +evDestroyTimers(const evContext_p *ctx) { + (void) heap_for_each(ctx->timers, free_timer, NULL); + (void) heap_free(ctx->timers); +} + +/* Private. */ + +static int +due_sooner(void *a, void *b) { + evTimer *a_timer, *b_timer; + + a_timer = a; + b_timer = b; + return (evCmpTime(a_timer->due, b_timer->due) < 0); +} + +static void +set_index(void *what, int index) { + evTimer *timer; + + timer = what; + timer->index = index; +} + +static void +free_timer(void *what, void *uap) { + evTimer *t = what; + + UNUSED(uap); + + FREE(t); +} + +static void +print_timer(void *what, void *uap) { + evTimer *cur = what; + evContext_p *ctx = uap; + + cur = what; + evPrintf(ctx, 7, + " func %p, uap %p, due %ld.%09ld, inter %ld.%09ld\n", + cur->func, cur->uap, + (long)cur->due.tv_sec, cur->due.tv_nsec, + (long)cur->inter.tv_sec, cur->inter.tv_nsec); +} + +static void +idle_timeout(evContext opaqueCtx, + void *uap, + struct timespec due, + struct timespec inter +) { + evContext_p *ctx = opaqueCtx.opaque; + idle_timer *this = uap; + struct timespec idle; + + UNUSED(due); + UNUSED(inter); + + idle = evSubTime(ctx->lastEventTime, this->lastTouched); + if (evCmpTime(idle, this->max_idle) >= 0) { + (this->func)(opaqueCtx, this->uap, this->timer->due, + this->max_idle); + /* + * Setting the interval to zero will cause the timer to + * be cleaned up in evDrop(). + */ + this->timer->inter = evConsTime(0, 0); + FREE(this); + } else { + /* evDrop() will reschedule the timer. */ + this->timer->inter = evSubTime(this->max_idle, idle); + } +} +#endif diff --git a/lib/libc/isc/eventlib_p.h b/lib/libc/isc/eventlib_p.h new file mode 100644 index 0000000..5c24f10 --- /dev/null +++ b/lib/libc/isc/eventlib_p.h @@ -0,0 +1,285 @@ +/* + * Copyright (c) 2005 by Internet Systems Consortium, Inc. ("ISC") + * Copyright (c) 1995-1999 by Internet Software Consortium + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT + * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +/* eventlib_p.h - private interfaces for eventlib + * vix 09sep95 [initial] + * + * $Id: eventlib_p.h 89 2016-01-12 00:20:40Z reddawg $ + * $FreeBSD: src/lib/libc/isc/eventlib_p.h,v 1.2.2.1 2006/07/17 10:09:56 ume Exp $ + */ + +#ifndef _EVENTLIB_P_H +#define _EVENTLIB_P_H + +#include +#include +#include +#include +#include + +#define EVENTLIB_DEBUG 1 + +#include +#include +#include +#include +#include + +#ifndef _LIBC +#include +#include +#include +#endif + +#define EV_MASK_ALL (EV_READ | EV_WRITE | EV_EXCEPT) +#define EV_ERR(e) return (errno = (e), -1) +#define OK(x) if ((x) < 0) EV_ERR(errno); else (void)NULL + +#define NEW(p) if (((p) = memget(sizeof *(p))) != NULL) \ + FILL(p); \ + else \ + (void)NULL; +#define OKNEW(p) if (!((p) = memget(sizeof *(p)))) { \ + errno = ENOMEM; \ + return (-1); \ + } else \ + FILL(p) +#define FREE(p) memput((p), sizeof *(p)) + +#if EVENTLIB_DEBUG +#define FILL(p) memset((p), 0xF5, sizeof *(p)) +#else +#define FILL(p) +#endif + +#ifdef USE_POLL +#ifdef HAVE_STROPTS_H +#include +#endif +#include +#endif /* USE_POLL */ + +typedef struct evConn { + evConnFunc func; + void * uap; + int fd; + int flags; +#define EV_CONN_LISTEN 0x0001 /* Connection is a listener. */ +#define EV_CONN_SELECTED 0x0002 /* evSelectFD(conn->file). */ +#define EV_CONN_BLOCK 0x0004 /* Listener fd was blocking. */ + evFileID file; + struct evConn * prev; + struct evConn * next; +} evConn; + +#ifndef _LIBC +typedef struct evAccept { + int fd; + union { + struct sockaddr sa; + struct sockaddr_in in; +#ifndef NO_SOCKADDR_UN + struct sockaddr_un un; +#endif + } la; + ISC_SOCKLEN_T lalen; + union { + struct sockaddr sa; + struct sockaddr_in in; +#ifndef NO_SOCKADDR_UN + struct sockaddr_un un; +#endif + } ra; + ISC_SOCKLEN_T ralen; + int ioErrno; + evConn * conn; + LINK(struct evAccept) link; +} evAccept; + +typedef struct evFile { + evFileFunc func; + void * uap; + int fd; + int eventmask; + int preemptive; + struct evFile * prev; + struct evFile * next; + struct evFile * fdprev; + struct evFile * fdnext; +} evFile; + +typedef struct evStream { + evStreamFunc func; + void * uap; + evFileID file; + evTimerID timer; + int flags; +#define EV_STR_TIMEROK 0x0001 /* IFF timer valid. */ + int fd; + struct iovec * iovOrig; + int iovOrigCount; + struct iovec * iovCur; + int iovCurCount; + int ioTotal; + int ioDone; + int ioErrno; + struct evStream *prevDone, *nextDone; + struct evStream *prev, *next; +} evStream; + +typedef struct evTimer { + evTimerFunc func; + void * uap; + struct timespec due, inter; + int index; + int mode; +#define EV_TMR_RATE 1 +} evTimer; + +typedef struct evWait { + evWaitFunc func; + void * uap; + const void * tag; + struct evWait * next; +} evWait; + +typedef struct evWaitList { + evWait * first; + evWait * last; + struct evWaitList * prev; + struct evWaitList * next; +} evWaitList; + +typedef struct evEvent_p { + enum { Accept, File, Stream, Timer, Wait, Free, Null } type; + union { + struct { evAccept *this; } accept; + struct { evFile *this; int eventmask; } file; + struct { evStream *this; } stream; + struct { evTimer *this; } timer; + struct { evWait *this; } wait; + struct { struct evEvent_p *next; } free; + struct { const void *placeholder; } null; + } u; +} evEvent_p; +#endif + +#ifdef USE_POLL +typedef struct { + void *ctx; /* pointer to the evContext_p */ + uint32_t type; /* READ, WRITE, EXCEPT, nonblk */ + uint32_t result; /* 1 => revents, 0 => events */ +} __evEmulMask; + +#define emulMaskInit(ctx, field, ev, lastnext) \ + ctx->field.ctx = ctx; \ + ctx->field.type = ev; \ + ctx->field.result = lastnext; + +extern short *__fd_eventfield(int fd, __evEmulMask *maskp); +extern short __poll_event(__evEmulMask *maskp); +extern void __fd_clr(int fd, __evEmulMask *maskp); +extern void __fd_set(int fd, __evEmulMask *maskp); + +#undef FD_ZERO +#define FD_ZERO(maskp) + +#undef FD_SET +#define FD_SET(fd, maskp) \ + __fd_set(fd, maskp) + +#undef FD_CLR +#define FD_CLR(fd, maskp) \ + __fd_clr(fd, maskp) + +#undef FD_ISSET +#define FD_ISSET(fd, maskp) \ + ((*__fd_eventfield(fd, maskp) & __poll_event(maskp)) != 0) + +#endif /* USE_POLL */ + +#ifndef _LIBC +typedef struct { + /* Global. */ + const evEvent_p *cur; + /* Debugging. */ + int debug; + FILE *output; + /* Connections. */ + evConn *conns; + LIST(evAccept) accepts; + /* Files. */ + evFile *files, *fdNext; +#ifndef USE_POLL + fd_set rdLast, rdNext; + fd_set wrLast, wrNext; + fd_set exLast, exNext; + fd_set nonblockBefore; + int fdMax, fdCount, highestFD; + evFile *fdTable[FD_SETSIZE]; +#else + struct pollfd *pollfds; /* Allocated as needed */ + evFile **fdTable; /* Ditto */ + int maxnfds; /* # elements in above */ + int firstfd; /* First active fd */ + int fdMax; /* Last active fd */ + int fdCount; /* # fd:s with I/O */ + int highestFD; /* max fd allowed by OS */ + __evEmulMask rdLast, rdNext; + __evEmulMask wrLast, wrNext; + __evEmulMask exLast, exNext; + __evEmulMask nonblockBefore; +#endif /* USE_POLL */ +#ifdef EVENTLIB_TIME_CHECKS + struct timespec lastSelectTime; + int lastFdCount; +#endif + /* Streams. */ + evStream *streams; + evStream *strDone, *strLast; + /* Timers. */ + struct timespec lastEventTime; + heap_context timers; + /* Waits. */ + evWaitList *waitLists; + evWaitList waitDone; +} evContext_p; + +/* eventlib.c */ +#define evPrintf __evPrintf +void evPrintf(const evContext_p *ctx, int level, const char *fmt, ...) + ISC_FORMAT_PRINTF(3, 4); + +#ifdef USE_POLL +extern int evPollfdRealloc(evContext_p *ctx, int pollfd_chunk_size, int fd); +#endif /* USE_POLL */ + +/* ev_timers.c */ +#define evCreateTimers __evCreateTimers +heap_context evCreateTimers(const evContext_p *); +#define evDestroyTimers __evDestroyTimers +void evDestroyTimers(const evContext_p *); + +/* ev_waits.c */ +#define evFreeWait __evFreeWait +evWait *evFreeWait(evContext_p *ctx, evWait *old); +#endif + +/* Global options */ +extern int __evOptMonoTime; + +#endif /*_EVENTLIB_P_H*/ diff --git a/lib/libc/locale/Makefile b/lib/libc/locale/Makefile new file mode 100644 index 0000000..89f58b9 --- /dev/null +++ b/lib/libc/locale/Makefile @@ -0,0 +1,35 @@ +# $Id: Makefile 89 2016-01-12 00:20:40Z reddawg $ +# The System Makefile (C) 2002 The UbixOS Project + +# Include Global 'Source' Options +include ../../../Makefile.incl +include ../../Makefile.incl +include ../Makefile.incl + +INCLUDES += -I../locale/ + +#Objects +OBJS = big5.o btowc.o collate.o collcmp.o euc.o fix_grouping.o gb18030.o gb2312.o gbk.o isctype.o iswctype.o ldpart.o lmessages.o lmonetary.o lnumeric.o localeconv.o mblen.o mbrlen.o mbrtowc.o mbsinit.o mbsnrtowcs.o mbsrtowcs.o mbstowcs.o mbtowc.o mskanji.o nextwctype.o nl_langinfo.o nomacros.o none.o rpmatch.o rune.o runetype.o setlocale.o setrunelocale.o table.o tolower.o toupper.o utf8.o wcrtomb.o wcsftime.o wcsnrtombs.o wcsrtombs.o wcstod.o wcstof.o wcstoimax.o wcstol.o wcstold.o wcstoll.o wcstombs.o wcstoul.o wcstoull.o wcstoumax.o wctob.o wctomb.o wctrans.o wctype.o wcwidth.o + +all: $(OBJS) + +# Compile the source files +.cc.o: + $(CXX) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -c -o $@ $< + +.cc.s: + $(CXX) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -S -o $@ $< + +.c.o: + $(CC) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -c $< + +.c.s: + $(CC) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -S -o $@ $< + +.S.o: + $(CC) $(CFLAGS) -Wall -nostdlib -c -o $@ $< + +# Clean up the junk +clean: + $(REMOVE) $(OBJS) + diff --git a/lib/libc/locale/big5.c b/lib/libc/locale/big5.c new file mode 100644 index 0000000..7837591 --- /dev/null +++ b/lib/libc/locale/big5.c @@ -0,0 +1,172 @@ +/*- + * Copyright (c) 2002-2004 Tim J. Robbins. All rights reserved. + * Copyright (c) 1993 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * Paul Borman at Krystal Technologies. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)big5.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/locale/big5.c,v 1.17 2005/02/27 15:11:09 phantom Exp $"); + +#include +#include +#include +#include +#include +#include +#include "mblocal.h" + +static size_t _BIG5_mbrtowc(wchar_t * __restrict, const char * __restrict, + size_t, mbstate_t * __restrict); +static int _BIG5_mbsinit(const mbstate_t *); +static size_t _BIG5_wcrtomb(char * __restrict, wchar_t, + mbstate_t * __restrict); + +typedef struct { + wchar_t ch; +} _BIG5State; + +int +_BIG5_init(_RuneLocale *rl) +{ + + __mbrtowc = _BIG5_mbrtowc; + __wcrtomb = _BIG5_wcrtomb; + __mbsinit = _BIG5_mbsinit; + _CurrentRuneLocale = rl; + __mb_cur_max = 2; + return (0); +} + +static int +_BIG5_mbsinit(const mbstate_t *ps) +{ + + return (ps == NULL || ((const _BIG5State *)ps)->ch == 0); +} + +static __inline int +_big5_check(u_int c) +{ + + c &= 0xff; + return ((c >= 0xa1 && c <= 0xfe) ? 2 : 1); +} + +static size_t +_BIG5_mbrtowc(wchar_t * __restrict pwc, const char * __restrict s, size_t n, + mbstate_t * __restrict ps) +{ + _BIG5State *bs; + wchar_t wc; + size_t len; + + bs = (_BIG5State *)ps; + + if ((bs->ch & ~0xFF) != 0) { + /* Bad conversion state. */ + errno = EINVAL; + return ((size_t)-1); + } + + if (s == NULL) { + s = ""; + n = 1; + pwc = NULL; + } + + if (n == 0) + /* Incomplete multibyte sequence */ + return ((size_t)-2); + + if (bs->ch != 0) { + if (*s == '\0') { + errno = EILSEQ; + return ((size_t)-1); + } + wc = (bs->ch << 8) | (*s & 0xFF); + if (pwc != NULL) + *pwc = wc; + bs->ch = 0; + return (1); + } + + len = (size_t)_big5_check(*s); + wc = *s++ & 0xff; + if (len == 2) { + if (n < 2) { + /* Incomplete multibyte sequence */ + bs->ch = wc; + return ((size_t)-2); + } + if (*s == '\0') { + errno = EILSEQ; + return ((size_t)-1); + } + wc = (wc << 8) | (*s++ & 0xff); + if (pwc != NULL) + *pwc = wc; + return (2); + } else { + if (pwc != NULL) + *pwc = wc; + return (wc == L'\0' ? 0 : 1); + } +} + +static size_t +_BIG5_wcrtomb(char * __restrict s, wchar_t wc, mbstate_t * __restrict ps) +{ + _BIG5State *bs; + + bs = (_BIG5State *)ps; + + if (bs->ch != 0) { + errno = EINVAL; + return ((size_t)-1); + } + + if (s == NULL) + /* Reset to initial shift state (no-op) */ + return (1); + if (wc & 0x8000) { + *s++ = (wc >> 8) & 0xff; + *s = wc & 0xff; + return (2); + } + *s = wc & 0xff; + return (1); +} diff --git a/lib/libc/locale/btowc.c b/lib/libc/locale/btowc.c new file mode 100644 index 0000000..44b501e --- /dev/null +++ b/lib/libc/locale/btowc.c @@ -0,0 +1,53 @@ +/*- + * Copyright (c) 2002, 2003 Tim J. Robbins. + * 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 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 AUTHOR 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 +__FBSDID("$FreeBSD: src/lib/libc/locale/btowc.c,v 1.4 2004/05/12 14:26:54 tjr Exp $"); + +#include +#include +#include "mblocal.h" + +wint_t +btowc(int c) +{ + static const mbstate_t initial; + mbstate_t mbs = initial; + char cc; + wchar_t wc; + + if (c == EOF) + return (WEOF); + /* + * We expect mbrtowc() to return 0 or 1, hence the check for n > 1 + * which detects error return values as well as "impossible" byte + * counts. + */ + cc = (char)c; + if (__mbrtowc(&wc, &cc, 1, &mbs) > 1) + return (WEOF); + return (wc); +} diff --git a/lib/libc/locale/collate.c b/lib/libc/locale/collate.c new file mode 100644 index 0000000..184fac6 --- /dev/null +++ b/lib/libc/locale/collate.c @@ -0,0 +1,298 @@ +/*- + * Copyright (c) 1995 Alex Tatmanjants + * at Electronni Visti IA, Kiev, Ukraine. + * 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. + */ + +#include +__FBSDID("$FreeBSD: src/lib/libc/locale/collate.c,v 1.35 2005/02/27 20:31:13 ru Exp $"); + +#include "namespace.h" +#include +#include +#include +#include +#include +#include +#include +#include "un-namespace.h" + +#include "collate.h" +#include "setlocale.h" +#include "ldpart.h" + +#include "libc_private.h" + +int __collate_load_error = 1; +int __collate_substitute_nontrivial; + +u_char __collate_substitute_table[UCHAR_MAX + 1][STR_LEN]; +struct __collate_st_char_pri __collate_char_pri_table[UCHAR_MAX + 1]; +struct __collate_st_chain_pri *__collate_chain_pri_table; + +void __collate_err(int ex, const char *f) __dead2; + +int +__collate_load_tables(const char *encoding) +{ + FILE *fp; + int i, saverr, chains; + uint32_t u32; + char strbuf[STR_LEN], buf[PATH_MAX]; + void *TMP_substitute_table, *TMP_char_pri_table, *TMP_chain_pri_table; + static char collate_encoding[ENCODING_LEN + 1]; + + /* 'encoding' must be already checked. */ + if (strcmp(encoding, "C") == 0 || strcmp(encoding, "POSIX") == 0) { + __collate_load_error = 1; + return (_LDP_CACHE); + } + + /* + * If the locale name is the same as our cache, use the cache. + */ + if (strcmp(encoding, collate_encoding) == 0) { + __collate_load_error = 0; + return (_LDP_CACHE); + } + + /* + * Slurp the locale file into the cache. + */ + + /* 'PathLocale' must be already set & checked. */ + /* Range checking not needed, encoding has fixed size */ + (void)strcpy(buf, _PathLocale); + (void)strcat(buf, "/"); + (void)strcat(buf, encoding); + (void)strcat(buf, "/LC_COLLATE"); + if ((fp = fopen(buf, "r")) == NULL) + return (_LDP_ERROR); + + if (fread(strbuf, sizeof(strbuf), 1, fp) != 1) { + saverr = errno; + (void)fclose(fp); + errno = saverr; + return (_LDP_ERROR); + } + chains = -1; + if (strcmp(strbuf, COLLATE_VERSION) == 0) + chains = 0; + else if (strcmp(strbuf, COLLATE_VERSION1_2) == 0) + chains = 1; + if (chains < 0) { + (void)fclose(fp); + errno = EFTYPE; + return (_LDP_ERROR); + } + if (chains) { + if (fread(&u32, sizeof(u32), 1, fp) != 1) { + saverr = errno; + (void)fclose(fp); + errno = saverr; + return (_LDP_ERROR); + } + if ((chains = (int)ntohl(u32)) < 1) { + (void)fclose(fp); + errno = EFTYPE; + return (_LDP_ERROR); + } + } else + chains = TABLE_SIZE; + + if ((TMP_substitute_table = + malloc(sizeof(__collate_substitute_table))) == NULL) { + saverr = errno; + (void)fclose(fp); + errno = saverr; + return (_LDP_ERROR); + } + if ((TMP_char_pri_table = + malloc(sizeof(__collate_char_pri_table))) == NULL) { + saverr = errno; + free(TMP_substitute_table); + (void)fclose(fp); + errno = saverr; + return (_LDP_ERROR); + } + if ((TMP_chain_pri_table = + malloc(sizeof(*__collate_chain_pri_table) * chains)) == NULL) { + saverr = errno; + free(TMP_substitute_table); + free(TMP_char_pri_table); + (void)fclose(fp); + errno = saverr; + return (_LDP_ERROR); + } + +#define FREAD(a, b, c, d) \ +{ \ + if (fread(a, b, c, d) != c) { \ + saverr = errno; \ + free(TMP_substitute_table); \ + free(TMP_char_pri_table); \ + free(TMP_chain_pri_table); \ + (void)fclose(d); \ + errno = saverr; \ + return (_LDP_ERROR); \ + } \ +} + + FREAD(TMP_substitute_table, sizeof(__collate_substitute_table), 1, fp); + FREAD(TMP_char_pri_table, sizeof(__collate_char_pri_table), 1, fp); + FREAD(TMP_chain_pri_table, + sizeof(*__collate_chain_pri_table), chains, fp); + (void)fclose(fp); + + (void)strcpy(collate_encoding, encoding); + if (__collate_substitute_table_ptr != NULL) + free(__collate_substitute_table_ptr); + __collate_substitute_table_ptr = TMP_substitute_table; + if (__collate_char_pri_table_ptr != NULL) + free(__collate_char_pri_table_ptr); + __collate_char_pri_table_ptr = TMP_char_pri_table; + for (i = 0; i < UCHAR_MAX + 1; i++) { + __collate_char_pri_table[i].prim = + ntohl(__collate_char_pri_table[i].prim); + __collate_char_pri_table[i].sec = + ntohl(__collate_char_pri_table[i].sec); + } + if (__collate_chain_pri_table != NULL) + free(__collate_chain_pri_table); + __collate_chain_pri_table = TMP_chain_pri_table; + for (i = 0; i < chains; i++) { + __collate_chain_pri_table[i].prim = + ntohl(__collate_chain_pri_table[i].prim); + __collate_chain_pri_table[i].sec = + ntohl(__collate_chain_pri_table[i].sec); + } + __collate_substitute_nontrivial = 0; + for (i = 0; i < UCHAR_MAX + 1; i++) { + if (__collate_substitute_table[i][0] != i || + __collate_substitute_table[i][1] != 0) { + __collate_substitute_nontrivial = 1; + break; + } + } + __collate_load_error = 0; + + return (_LDP_LOADED); +} + +u_char * +__collate_substitute(const u_char *s) +{ + int dest_len, len, nlen; + int delta = strlen(s); + u_char *dest_str = NULL; + + if (s == NULL || *s == '\0') + return (__collate_strdup("")); + delta += delta / 8; + dest_str = malloc(dest_len = delta); + if (dest_str == NULL) + __collate_err(EX_OSERR, __func__); + len = 0; + while (*s) { + nlen = len + strlen(__collate_substitute_table[*s]); + if (dest_len <= nlen) { + dest_str = reallocf(dest_str, dest_len = nlen + delta); + if (dest_str == NULL) + __collate_err(EX_OSERR, __func__); + } + (void)strcpy(dest_str + len, __collate_substitute_table[*s++]); + len = nlen; + } + return (dest_str); +} + +void +__collate_lookup(const u_char *t, int *len, int *prim, int *sec) +{ + struct __collate_st_chain_pri *p2; + + *len = 1; + *prim = *sec = 0; + for (p2 = __collate_chain_pri_table; p2->str[0] != '\0'; p2++) { + if (*t == p2->str[0] && + strncmp(t, p2->str, strlen(p2->str)) == 0) { + *len = strlen(p2->str); + *prim = p2->prim; + *sec = p2->sec; + return; + } + } + *prim = __collate_char_pri_table[*t].prim; + *sec = __collate_char_pri_table[*t].sec; +} + +u_char * +__collate_strdup(u_char *s) +{ + u_char *t = strdup(s); + + if (t == NULL) + __collate_err(EX_OSERR, __func__); + return (t); +} + +void +__collate_err(int ex, const char *f) +{ + const char *s; + int serrno = errno; + + s = _getprogname(); + _write(STDERR_FILENO, s, strlen(s)); + _write(STDERR_FILENO, ": ", 2); + s = f; + _write(STDERR_FILENO, s, strlen(s)); + _write(STDERR_FILENO, ": ", 2); + s = strerror(serrno); + _write(STDERR_FILENO, s, strlen(s)); + _write(STDERR_FILENO, "\n", 1); + exit(ex); +} + +#ifdef COLLATE_DEBUG +void +__collate_print_tables() +{ + int i; + struct __collate_st_chain_pri *p2; + + printf("Substitute table:\n"); + for (i = 0; i < UCHAR_MAX + 1; i++) + if (i != *__collate_substitute_table[i]) + printf("\t'%c' --> \"%s\"\n", i, + __collate_substitute_table[i]); + printf("Chain priority table:\n"); + for (p2 = __collate_chain_pri_table; p2->str[0] != '\0'; p2++) + printf("\t\"%s\" : %d %d\n", p2->str, p2->prim, p2->sec); + printf("Char priority table:\n"); + for (i = 0; i < UCHAR_MAX + 1; i++) + printf("\t'%c' : %d %d\n", i, __collate_char_pri_table[i].prim, + __collate_char_pri_table[i].sec); +} +#endif diff --git a/lib/libc/locale/collate.h b/lib/libc/locale/collate.h new file mode 100644 index 0000000..a8d2176 --- /dev/null +++ b/lib/libc/locale/collate.h @@ -0,0 +1,69 @@ +/*- + * Copyright (c) 1995 Alex Tatmanjants + * at Electronni Visti IA, Kiev, Ukraine. + * 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. + * + * $FreeBSD: src/lib/libc/locale/collate.h,v 1.15 2005/02/27 20:31:13 ru Exp $ + */ + +#ifndef _COLLATE_H_ +#define _COLLATE_H_ + +#include +#include +#include + +#define STR_LEN 10 +#define TABLE_SIZE 100 +#define COLLATE_VERSION "1.0\n" +#define COLLATE_VERSION1_2 "1.2\n" + +struct __collate_st_char_pri { + int prim, sec; +}; +struct __collate_st_chain_pri { + u_char str[STR_LEN]; + int prim, sec; +}; + +extern int __collate_load_error; +extern int __collate_substitute_nontrivial; +#define __collate_substitute_table (*__collate_substitute_table_ptr) +extern u_char __collate_substitute_table[UCHAR_MAX + 1][STR_LEN]; +#define __collate_char_pri_table (*__collate_char_pri_table_ptr) +extern struct __collate_st_char_pri __collate_char_pri_table[UCHAR_MAX + 1]; +extern struct __collate_st_chain_pri *__collate_chain_pri_table; + +__BEGIN_DECLS +u_char *__collate_strdup(u_char *); +u_char *__collate_substitute(const u_char *); +int __collate_load_tables(const char *); +void __collate_lookup(const u_char *, int *, int *, int *); +int __collate_range_cmp(int, int); +#ifdef COLLATE_DEBUG +void __collate_print_tables(void); +#endif +__END_DECLS + +#endif /* !_COLLATE_H_ */ diff --git a/lib/libc/locale/collcmp.c b/lib/libc/locale/collcmp.c new file mode 100644 index 0000000..dde67a4 --- /dev/null +++ b/lib/libc/locale/collcmp.c @@ -0,0 +1,44 @@ +/* + * Copyright (C) 1996 by Andrey A. Chernov, Moscow, Russia. + * 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 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 +__FBSDID("$FreeBSD: src/lib/libc/locale/collcmp.c,v 1.18 2005/02/27 14:54:23 phantom Exp $"); + +#include +#include "collate.h" + +/* + * Compare two characters using collate + */ + +int __collate_range_cmp(int c1, int c2) +{ + static char s1[2], s2[2]; + + s1[0] = c1; + s2[0] = c2; + return (strcoll(s1, s2)); +} diff --git a/lib/libc/locale/euc.c b/lib/libc/locale/euc.c new file mode 100644 index 0000000..32f8fb8 --- /dev/null +++ b/lib/libc/locale/euc.c @@ -0,0 +1,265 @@ +/*- + * Copyright (c) 2002-2004 Tim J. Robbins. All rights reserved. + * Copyright (c) 1993 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * Paul Borman at Krystal Technologies. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)euc.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/locale/euc.c,v 1.21 2005/02/27 15:11:09 phantom Exp $"); + +#include +#include +#include +#include +#include +#include +#include "mblocal.h" + +static size_t _EUC_mbrtowc(wchar_t * __restrict, const char * __restrict, + size_t, mbstate_t * __restrict); +static int _EUC_mbsinit(const mbstate_t *); +static size_t _EUC_wcrtomb(char * __restrict, wchar_t, + mbstate_t * __restrict); + +typedef struct { + int count[4]; + wchar_t bits[4]; + wchar_t mask; +} _EucInfo; + +typedef struct { + wchar_t ch; + int set; + int want; +} _EucState; + +int +_EUC_init(_RuneLocale *rl) +{ + _EucInfo *ei; + int x, new__mb_cur_max; + char *v, *e; + + if (rl->__variable == NULL) + return (EFTYPE); + + v = (char *)rl->__variable; + + while (*v == ' ' || *v == '\t') + ++v; + + if ((ei = malloc(sizeof(_EucInfo))) == NULL) + return (errno == 0 ? ENOMEM : errno); + + new__mb_cur_max = 0; + for (x = 0; x < 4; ++x) { + ei->count[x] = (int)strtol(v, &e, 0); + if (v == e || !(v = e)) { + free(ei); + return (EFTYPE); + } + if (new__mb_cur_max < ei->count[x]) + new__mb_cur_max = ei->count[x]; + while (*v == ' ' || *v == '\t') + ++v; + ei->bits[x] = (int)strtol(v, &e, 0); + if (v == e || !(v = e)) { + free(ei); + return (EFTYPE); + } + while (*v == ' ' || *v == '\t') + ++v; + } + ei->mask = (int)strtol(v, &e, 0); + if (v == e || !(v = e)) { + free(ei); + return (EFTYPE); + } + rl->__variable = ei; + rl->__variable_len = sizeof(_EucInfo); + _CurrentRuneLocale = rl; + __mb_cur_max = new__mb_cur_max; + __mbrtowc = _EUC_mbrtowc; + __wcrtomb = _EUC_wcrtomb; + __mbsinit = _EUC_mbsinit; + return (0); +} + +static int +_EUC_mbsinit(const mbstate_t *ps) +{ + + return (ps == NULL || ((const _EucState *)ps)->want == 0); +} + +#define CEI ((_EucInfo *)(_CurrentRuneLocale->__variable)) + +#define _SS2 0x008e +#define _SS3 0x008f + +#define GR_BITS 0x80808080 /* XXX: to be fixed */ + +static __inline int +_euc_set(u_int c) +{ + + c &= 0xff; + return ((c & 0x80) ? c == _SS3 ? 3 : c == _SS2 ? 2 : 1 : 0); +} + +static size_t +_EUC_mbrtowc(wchar_t * __restrict pwc, const char * __restrict s, size_t n, + mbstate_t * __restrict ps) +{ + _EucState *es; + int i, set, want; + wchar_t wc; + const char *os; + + es = (_EucState *)ps; + + if (es->want < 0 || es->want > MB_CUR_MAX || es->set < 0 || + es->set > 3) { + errno = EINVAL; + return ((size_t)-1); + } + + if (s == NULL) { + s = ""; + n = 1; + pwc = NULL; + } + + if (n == 0) + /* Incomplete multibyte sequence */ + return ((size_t)-2); + + os = s; + + if (es->want == 0) { + want = CEI->count[set = _euc_set(*s)]; + if (set == 2 || set == 3) { + --want; + if (--n == 0) { + /* Incomplete multibyte sequence */ + es->set = set; + es->want = want; + es->ch = 0; + return ((size_t)-2); + } + ++s; + if (*s == '\0') { + errno = EILSEQ; + return ((size_t)-1); + } + } + wc = (unsigned char)*s++; + } else { + set = es->set; + want = es->want; + wc = es->ch; + } + for (i = (es->want == 0) ? 1 : 0; i < MIN(want, n); i++) { + if (*s == '\0') { + errno = EILSEQ; + return ((size_t)-1); + } + wc = (wc << 8) | (unsigned char)*s++; + } + if (i < want) { + /* Incomplete multibyte sequence */ + es->set = set; + es->want = want - i; + es->ch = wc; + return ((size_t)-2); + } + wc = (wc & ~CEI->mask) | CEI->bits[set]; + if (pwc != NULL) + *pwc = wc; + es->want = 0; + return (wc == L'\0' ? 0 : s - os); +} + +static size_t +_EUC_wcrtomb(char * __restrict s, wchar_t wc, mbstate_t * __restrict ps) +{ + _EucState *es; + wchar_t m, nm; + int i, len; + + es = (_EucState *)ps; + + if (es->want != 0) { + errno = EINVAL; + return ((size_t)-1); + } + + if (s == NULL) + /* Reset to initial shift state (no-op) */ + return (1); + + m = wc & CEI->mask; + nm = wc & ~m; + + if (m == CEI->bits[1]) { +CodeSet1: + /* Codeset 1: The first byte must have 0x80 in it. */ + i = len = CEI->count[1]; + while (i-- > 0) + *s++ = (nm >> (i << 3)) | 0x80; + } else { + if (m == CEI->bits[0]) + i = len = CEI->count[0]; + else if (m == CEI->bits[2]) { + i = len = CEI->count[2]; + *s++ = _SS2; + --i; + /* SS2 designates G2 into GR */ + nm |= GR_BITS; + } else if (m == CEI->bits[3]) { + i = len = CEI->count[3]; + *s++ = _SS3; + --i; + /* SS3 designates G3 into GR */ + nm |= GR_BITS; + } else + goto CodeSet1; /* Bletch */ + while (i-- > 0) + *s++ = (nm >> (i << 3)) & 0xff; + } + return (len); +} diff --git a/lib/libc/locale/fix_grouping.c b/lib/libc/locale/fix_grouping.c new file mode 100644 index 0000000..ab08f3f --- /dev/null +++ b/lib/libc/locale/fix_grouping.c @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2001 Alexey Zelkin + * 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 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 AUTHOR 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 +__FBSDID("$FreeBSD: src/lib/libc/locale/fix_grouping.c,v 1.8 2003/06/26 10:46:16 phantom Exp $"); + +#include +#include +#include + +static const char nogrouping[] = { CHAR_MAX, '\0' }; + +/* + * Internal helper used to convert grouping sequences from string + * representation into POSIX specified form, i.e. + * + * "3;3;-1" -> "\003\003\177\000" + */ + +const char * +__fix_locale_grouping_str(const char *str) +{ + char *src, *dst; + char n; + + if (str == NULL || *str == '\0') { + return nogrouping; + } + + for (src = (char*)str, dst = (char*)str; *src != '\0'; src++) { + + /* input string examples: "3;3", "3;2;-1" */ + if (*src == ';') + continue; + + if (*src == '-' && *(src+1) == '1') { + *dst++ = CHAR_MAX; + src++; + continue; + } + + if (!isdigit((unsigned char)*src)) { + /* broken grouping string */ + return nogrouping; + } + + /* assume all numbers <= 99 */ + n = *src - '0'; + if (isdigit((unsigned char)*(src+1))) { + src++; + n *= 10; + n += *src - '0'; + } + + *dst = n; + /* NOTE: assume all input started with "0" as 'no grouping' */ + if (*dst == '\0') + return (dst == (char*)str) ? nogrouping : str; + dst++; + } + *dst = '\0'; + return str; +} diff --git a/lib/libc/locale/gb18030.c b/lib/libc/locale/gb18030.c new file mode 100644 index 0000000..b5c5240 --- /dev/null +++ b/lib/libc/locale/gb18030.c @@ -0,0 +1,218 @@ +/*- + * Copyright (c) 2002-2004 Tim J. Robbins + * 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 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 AUTHOR 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. + */ +/* + * PRC National Standard GB 18030-2000 encoding of Chinese text. + * + * See gb18030(5) for details. + */ + +#include +__FBSDID("$FreeBSD: src/lib/libc/locale/gb18030.c,v 1.7 2005/02/27 15:11:09 phantom Exp $"); + +#include +#include +#include +#include +#include +#include "mblocal.h" + +static size_t _GB18030_mbrtowc(wchar_t * __restrict, const char * __restrict, + size_t, mbstate_t * __restrict); +static int _GB18030_mbsinit(const mbstate_t *); +static size_t _GB18030_wcrtomb(char * __restrict, wchar_t, + mbstate_t * __restrict); + +typedef struct { + int count; + u_char bytes[4]; +} _GB18030State; + +int +_GB18030_init(_RuneLocale *rl) +{ + + __mbrtowc = _GB18030_mbrtowc; + __wcrtomb = _GB18030_wcrtomb; + __mbsinit = _GB18030_mbsinit; + _CurrentRuneLocale = rl; + __mb_cur_max = 4; + + return (0); +} + +static int +_GB18030_mbsinit(const mbstate_t *ps) +{ + + return (ps == NULL || ((const _GB18030State *)ps)->count == 0); +} + +static size_t +_GB18030_mbrtowc(wchar_t * __restrict pwc, const char * __restrict s, + size_t n, mbstate_t * __restrict ps) +{ + _GB18030State *gs; + wchar_t wch; + int ch, len, ocount; + size_t ncopy; + + gs = (_GB18030State *)ps; + + if (gs->count < 0 || gs->count > sizeof(gs->bytes)) { + errno = EINVAL; + return ((size_t)-1); + } + + if (s == NULL) { + s = ""; + n = 1; + pwc = NULL; + } + + ncopy = MIN(MIN(n, MB_CUR_MAX), sizeof(gs->bytes) - gs->count); + memcpy(gs->bytes + gs->count, s, ncopy); + ocount = gs->count; + gs->count += ncopy; + s = (char *)gs->bytes; + n = gs->count; + + if (n == 0) + /* Incomplete multibyte sequence */ + return ((size_t)-2); + + /* + * Single byte: [00-7f] + * Two byte: [81-fe][40-7e,80-fe] + * Four byte: [81-fe][30-39][81-fe][30-39] + */ + ch = (unsigned char)*s++; + if (ch <= 0x7f) { + len = 1; + wch = ch; + } else if (ch >= 0x81 && ch <= 0xfe) { + wch = ch; + if (n < 2) + return ((size_t)-2); + ch = (unsigned char)*s++; + if ((ch >= 0x40 && ch <= 0x7e) || (ch >= 0x80 && ch <= 0xfe)) { + wch = (wch << 8) | ch; + len = 2; + } else if (ch >= 0x30 && ch <= 0x39) { + /* + * Strip high bit off the wide character we will + * eventually output so that it is positive when + * cast to wint_t on 32-bit twos-complement machines. + */ + wch = ((wch & 0x7f) << 8) | ch; + if (n < 3) + return ((size_t)-2); + ch = (unsigned char)*s++; + if (ch < 0x81 || ch > 0xfe) + goto ilseq; + wch = (wch << 8) | ch; + if (n < 4) + return ((size_t)-2); + ch = (unsigned char)*s++; + if (ch < 0x30 || ch > 0x39) + goto ilseq; + wch = (wch << 8) | ch; + len = 4; + } else + goto ilseq; + } else + goto ilseq; + + if (pwc != NULL) + *pwc = wch; + gs->count = 0; + return (wch == L'\0' ? 0 : len - ocount); +ilseq: + errno = EILSEQ; + return ((size_t)-1); +} + +static size_t +_GB18030_wcrtomb(char * __restrict s, wchar_t wc, mbstate_t * __restrict ps) +{ + _GB18030State *gs; + size_t len; + int c; + + gs = (_GB18030State *)ps; + + if (gs->count != 0) { + errno = EINVAL; + return ((size_t)-1); + } + + if (s == NULL) + /* Reset to initial shift state (no-op) */ + return (1); + if ((wc & ~0x7fffffff) != 0) + goto ilseq; + if (wc & 0x7f000000) { + /* Replace high bit that mbrtowc() removed. */ + wc |= 0x80000000; + c = (wc >> 24) & 0xff; + if (c < 0x81 || c > 0xfe) + goto ilseq; + *s++ = c; + c = (wc >> 16) & 0xff; + if (c < 0x30 || c > 0x39) + goto ilseq; + *s++ = c; + c = (wc >> 8) & 0xff; + if (c < 0x81 || c > 0xfe) + goto ilseq; + *s++ = c; + c = wc & 0xff; + if (c < 0x30 || c > 0x39) + goto ilseq; + *s++ = c; + len = 4; + } else if (wc & 0x00ff0000) + goto ilseq; + else if (wc & 0x0000ff00) { + c = (wc >> 8) & 0xff; + if (c < 0x81 || c > 0xfe) + goto ilseq; + *s++ = c; + c = wc & 0xff; + if (c < 0x40 || c == 0x7f || c == 0xff) + goto ilseq; + *s++ = c; + len = 2; + } else if (wc <= 0x7f) { + *s++ = wc; + len = 1; + } else + goto ilseq; + + return (len); +ilseq: + errno = EILSEQ; + return ((size_t)-1); +} diff --git a/lib/libc/locale/gb2312.c b/lib/libc/locale/gb2312.c new file mode 100644 index 0000000..0f89ddb --- /dev/null +++ b/lib/libc/locale/gb2312.c @@ -0,0 +1,154 @@ +/*- + * Copyright (c) 2004 Tim J. Robbins. All rights reserved. + * Copyright (c) 2003 David Xu + * 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 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 AUTHOR 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 +__FBSDID("$FreeBSD: src/lib/libc/locale/gb2312.c,v 1.9 2005/02/27 15:11:09 phantom Exp $"); + +#include +#include +#include +#include +#include +#include "mblocal.h" + +static size_t _GB2312_mbrtowc(wchar_t * __restrict, const char * __restrict, + size_t, mbstate_t * __restrict); +static int _GB2312_mbsinit(const mbstate_t *); +static size_t _GB2312_wcrtomb(char * __restrict, wchar_t, + mbstate_t * __restrict); + +typedef struct { + int count; + u_char bytes[2]; +} _GB2312State; + +int +_GB2312_init(_RuneLocale *rl) +{ + + _CurrentRuneLocale = rl; + __mbrtowc = _GB2312_mbrtowc; + __wcrtomb = _GB2312_wcrtomb; + __mbsinit = _GB2312_mbsinit; + __mb_cur_max = 2; + return (0); +} + +static int +_GB2312_mbsinit(const mbstate_t *ps) +{ + + return (ps == NULL || ((const _GB2312State *)ps)->count == 0); +} + +static __inline int +_GB2312_check(const char *str, size_t n) +{ + const u_char *s = (const u_char *)str; + + if (n == 0) + /* Incomplete multibyte sequence */ + return (-2); + if (s[0] >= 0xa1 && s[0] <= 0xfe) { + if (n < 2) + /* Incomplete multibyte sequence */ + return (-2); + if (s[1] < 0xa1 || s[1] > 0xfe) + /* Invalid multibyte sequence */ + return (-1); + return (2); + } else if (s[0] & 0x80) { + /* Invalid multibyte sequence */ + return (-1); + } + return (1); +} + +static size_t +_GB2312_mbrtowc(wchar_t * __restrict pwc, const char * __restrict s, size_t n, + mbstate_t * __restrict ps) +{ + _GB2312State *gs; + wchar_t wc; + int i, len, ocount; + size_t ncopy; + + gs = (_GB2312State *)ps; + + if (gs->count < 0 || gs->count > sizeof(gs->bytes)) { + errno = EINVAL; + return ((size_t)-1); + } + + if (s == NULL) { + s = ""; + n = 1; + pwc = NULL; + } + + ncopy = MIN(MIN(n, MB_CUR_MAX), sizeof(gs->bytes) - gs->count); + memcpy(gs->bytes + gs->count, s, ncopy); + ocount = gs->count; + gs->count += ncopy; + s = (char *)gs->bytes; + n = gs->count; + + if ((len = _GB2312_check(s, n)) < 0) + return ((size_t)len); + wc = 0; + i = len; + while (i-- > 0) + wc = (wc << 8) | (unsigned char)*s++; + if (pwc != NULL) + *pwc = wc; + gs->count = 0; + return (wc == L'\0' ? 0 : len - ocount); +} + +static size_t +_GB2312_wcrtomb(char * __restrict s, wchar_t wc, mbstate_t * __restrict ps) +{ + _GB2312State *gs; + + gs = (_GB2312State *)ps; + + if (gs->count != 0) { + errno = EINVAL; + return ((size_t)-1); + } + + if (s == NULL) + /* Reset to initial shift state (no-op) */ + return (1); + if (wc & 0x8000) { + *s++ = (wc >> 8) & 0xff; + *s = wc & 0xff; + return (2); + } + *s = wc & 0xff; + return (1); +} diff --git a/lib/libc/locale/gbk.c b/lib/libc/locale/gbk.c new file mode 100644 index 0000000..33f5e48 --- /dev/null +++ b/lib/libc/locale/gbk.c @@ -0,0 +1,169 @@ +/*- + * Copyright (c) 2002-2004 Tim J. Robbins. All rights reserved. + * Copyright (c) 1993 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * Paul Borman at Krystal Technologies. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#include +__FBSDID("$FreeBSD: src/lib/libc/locale/gbk.c,v 1.12 2005/02/27 15:11:09 phantom Exp $"); + +#include +#include +#include +#include +#include +#include +#include "mblocal.h" + +static size_t _GBK_mbrtowc(wchar_t * __restrict, const char * __restrict, + size_t, mbstate_t * __restrict); +static int _GBK_mbsinit(const mbstate_t *); +static size_t _GBK_wcrtomb(char * __restrict, wchar_t, + mbstate_t * __restrict); + +typedef struct { + wchar_t ch; +} _GBKState; + +int +_GBK_init(_RuneLocale *rl) +{ + + __mbrtowc = _GBK_mbrtowc; + __wcrtomb = _GBK_wcrtomb; + __mbsinit = _GBK_mbsinit; + _CurrentRuneLocale = rl; + __mb_cur_max = 2; + return (0); +} + +static int +_GBK_mbsinit(const mbstate_t *ps) +{ + + return (ps == NULL || ((const _GBKState *)ps)->ch == 0); +} + +static __inline int +_gbk_check(u_int c) +{ + + c &= 0xff; + return ((c >= 0x81 && c <= 0xfe) ? 2 : 1); +} + +static size_t +_GBK_mbrtowc(wchar_t * __restrict pwc, const char * __restrict s, size_t n, + mbstate_t * __restrict ps) +{ + _GBKState *gs; + wchar_t wc; + size_t len; + + gs = (_GBKState *)ps; + + if ((gs->ch & ~0xFF) != 0) { + /* Bad conversion state. */ + errno = EINVAL; + return ((size_t)-1); + } + + if (s == NULL) { + s = ""; + n = 1; + pwc = NULL; + } + + if (n == 0) + /* Incomplete multibyte sequence */ + return ((size_t)-2); + + if (gs->ch != 0) { + if (*s == '\0') { + errno = EILSEQ; + return ((size_t)-1); + } + wc = (gs->ch << 8) | (*s & 0xFF); + if (pwc != NULL) + *pwc = wc; + gs->ch = 0; + return (1); + } + + len = (size_t)_gbk_check(*s); + wc = *s++ & 0xff; + if (len == 2) { + if (n < 2) { + /* Incomplete multibyte sequence */ + gs->ch = wc; + return ((size_t)-2); + } + if (*s == '\0') { + errno = EILSEQ; + return ((size_t)-1); + } + wc = (wc << 8) | (*s++ & 0xff); + if (pwc != NULL) + *pwc = wc; + return (2); + } else { + if (pwc != NULL) + *pwc = wc; + return (wc == L'\0' ? 0 : 1); + } +} + +static size_t +_GBK_wcrtomb(char * __restrict s, wchar_t wc, mbstate_t * __restrict ps) +{ + _GBKState *gs; + + gs = (_GBKState *)ps; + + if (gs->ch != 0) { + errno = EINVAL; + return ((size_t)-1); + } + + if (s == NULL) + /* Reset to initial shift state (no-op) */ + return (1); + if (wc & 0x8000) { + *s++ = (wc >> 8) & 0xff; + *s = wc & 0xff; + return (2); + } + *s = wc & 0xff; + return (1); +} diff --git a/lib/libc/locale/isctype.c b/lib/libc/locale/isctype.c new file mode 100644 index 0000000..d718b77 --- /dev/null +++ b/lib/libc/locale/isctype.c @@ -0,0 +1,233 @@ +/* + * Copyright (c) 1989, 1993 + * The Regents of the University of California. All rights reserved. + * (c) UNIX System Laboratories, Inc. + * All or some portions of this file are derived from material licensed + * to the University of California by American Telephone and Telegraph + * Co. or Unix System Laboratories, Inc. and are reproduced herein with + * the permission of UNIX System Laboratories, Inc. + * + * This code is derived from software contributed to Berkeley by + * Paul Borman at Krystal Technologies. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)isctype.c 8.3 (Berkeley) 2/24/94"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/locale/isctype.c,v 1.9 2002/08/17 20:03:44 ache Exp $"); + +#include + +#undef digittoint +int +digittoint(c) + int c; +{ + return (__maskrune(c, 0xFF)); +} + +#undef isalnum +int +isalnum(c) + int c; +{ + return (__istype(c, _CTYPE_A|_CTYPE_D)); +} + +#undef isalpha +int +isalpha(c) + int c; +{ + return (__istype(c, _CTYPE_A)); +} + +#undef isascii +int +isascii(c) + int c; +{ + return ((c & ~0x7F) == 0); +} + +#undef isblank +int +isblank(c) + int c; +{ + return (__istype(c, _CTYPE_B)); +} + +#undef iscntrl +int +iscntrl(c) + int c; +{ + return (__istype(c, _CTYPE_C)); +} + +#undef isdigit +int +isdigit(c) + int c; +{ + return (__isctype(c, _CTYPE_D)); +} + +#undef isgraph +int +isgraph(c) + int c; +{ + return (__istype(c, _CTYPE_G)); +} + +#undef ishexnumber +int +ishexnumber(c) + int c; +{ + return (__istype(c, _CTYPE_X)); +} + +#undef isideogram +int +isideogram(c) + int c; +{ + return (__istype(c, _CTYPE_I)); +} + +#undef islower +int +islower(c) + int c; +{ + return (__istype(c, _CTYPE_L)); +} + +#undef isnumber +int +isnumber(c) + int c; +{ + return (__istype(c, _CTYPE_D)); +} + +#undef isphonogram +int +isphonogram(c) + int c; +{ + return (__istype(c, _CTYPE_Q)); +} + +#undef isprint +int +isprint(c) + int c; +{ + return (__istype(c, _CTYPE_R)); +} + +#undef ispunct +int +ispunct(c) + int c; +{ + return (__istype(c, _CTYPE_P)); +} + +#undef isrune +int +isrune(c) + int c; +{ + return (__istype(c, 0xFFFFFF00L)); +} + +#undef isspace +int +isspace(c) + int c; +{ + return (__istype(c, _CTYPE_S)); +} + +#undef isspecial +int +isspecial(c) + int c; +{ + return (__istype(c, _CTYPE_T)); +} + +#undef isupper +int +isupper(c) + int c; +{ + return (__istype(c, _CTYPE_U)); +} + +#undef isxdigit +int +isxdigit(c) + int c; +{ + return (__isctype(c, _CTYPE_X)); +} + +#undef toascii +int +toascii(c) + int c; +{ + return (c & 0x7F); +} + +#undef tolower +int +tolower(c) + int c; +{ + return (__tolower(c)); +} + +#undef toupper +int +toupper(c) + int c; +{ + return (__toupper(c)); +} + diff --git a/lib/libc/locale/iswctype.c b/lib/libc/locale/iswctype.c new file mode 100644 index 0000000..37e2656 --- /dev/null +++ b/lib/libc/locale/iswctype.c @@ -0,0 +1,214 @@ +/* + * Copyright (c) 1989, 1993 + * The Regents of the University of California. All rights reserved. + * (c) UNIX System Laboratories, Inc. + * All or some portions of this file are derived from material licensed + * to the University of California by American Telephone and Telegraph + * Co. or Unix System Laboratories, Inc. and are reproduced herein with + * the permission of UNIX System Laboratories, Inc. + * + * This code is derived from software contributed to Berkeley by + * Paul Borman at Krystal Technologies. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#include +__FBSDID("$FreeBSD: src/lib/libc/locale/iswctype.c,v 1.6 2002/08/17 20:30:34 ache Exp $"); + +#include + +#undef iswalnum +int +iswalnum(wc) + wint_t wc; +{ + return (__istype(wc, _CTYPE_A|_CTYPE_D)); +} + +#undef iswalpha +int +iswalpha(wc) + wint_t wc; +{ + return (__istype(wc, _CTYPE_A)); +} + +#undef iswascii +int +iswascii(wc) + wint_t wc; +{ + return ((wc & ~0x7F) == 0); +} + +#undef iswblank +int +iswblank(wc) + wint_t wc; +{ + return (__istype(wc, _CTYPE_B)); +} + +#undef iswcntrl +int +iswcntrl(wc) + wint_t wc; +{ + return (__istype(wc, _CTYPE_C)); +} + +#undef iswdigit +int +iswdigit(wc) + wint_t wc; +{ + return (__isctype(wc, _CTYPE_D)); +} + +#undef iswgraph +int +iswgraph(wc) + wint_t wc; +{ + return (__istype(wc, _CTYPE_G)); +} + +#undef iswhexnumber +int +iswhexnumber(wc) + wint_t wc; +{ + return (__istype(wc, _CTYPE_X)); +} + +#undef iswideogram +int +iswideogram(wc) + wint_t wc; +{ + return (__istype(wc, _CTYPE_I)); +} + +#undef iswlower +int +iswlower(wc) + wint_t wc; +{ + return (__istype(wc, _CTYPE_L)); +} + +#undef iswnumber +int +iswnumber(wc) + wint_t wc; +{ + return (__istype(wc, _CTYPE_D)); +} + +#undef iswphonogram +int +iswphonogram(wc) + wint_t wc; +{ + return (__istype(wc, _CTYPE_Q)); +} + +#undef iswprint +int +iswprint(wc) + wint_t wc; +{ + return (__istype(wc, _CTYPE_R)); +} + +#undef iswpunct +int +iswpunct(wc) + wint_t wc; +{ + return (__istype(wc, _CTYPE_P)); +} + +#undef iswrune +int +iswrune(wc) + wint_t wc; +{ + return (__istype(wc, 0xFFFFFF00L)); +} + +#undef iswspace +int +iswspace(wc) + wint_t wc; +{ + return (__istype(wc, _CTYPE_S)); +} + +#undef iswspecial +int +iswspecial(wc) + wint_t wc; +{ + return (__istype(wc, _CTYPE_T)); +} + +#undef iswupper +int +iswupper(wc) + wint_t wc; +{ + return (__istype(wc, _CTYPE_U)); +} + +#undef iswxdigit +int +iswxdigit(wc) + wint_t wc; +{ + return (__isctype(wc, _CTYPE_X)); +} + +#undef towlower +wint_t +towlower(wc) + wint_t wc; +{ + return (__tolower(wc)); +} + +#undef towupper +wint_t +towupper(wc) + wint_t wc; +{ + return (__toupper(wc)); +} + diff --git a/lib/libc/locale/ldpart.c b/lib/libc/locale/ldpart.c new file mode 100644 index 0000000..932165f --- /dev/null +++ b/lib/libc/locale/ldpart.c @@ -0,0 +1,166 @@ +/* + * Copyright (c) 2000, 2001 Alexey Zelkin + * 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 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 AUTHOR 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 +__FBSDID("$FreeBSD: src/lib/libc/locale/ldpart.c,v 1.15 2004/04/25 19:56:50 ache Exp $"); + +#include "namespace.h" +#include +#include + +#include +#include +#include +#include +#include +#include +#include "un-namespace.h" + +#include "ldpart.h" +#include "setlocale.h" + +static int split_lines(char *, const char *); + +int +__part_load_locale(const char *name, + int *using_locale, + char **locale_buf, + const char *category_filename, + int locale_buf_size_max, + int locale_buf_size_min, + const char **dst_localebuf) +{ + int saverr, fd, i, num_lines; + char *lbuf, *p; + const char *plim; + char filename[PATH_MAX]; + struct stat st; + size_t namesize, bufsize; + + /* 'name' must be already checked. */ + if (strcmp(name, "C") == 0 || strcmp(name, "POSIX") == 0) { + *using_locale = 0; + return (_LDP_CACHE); + } + + /* + * If the locale name is the same as our cache, use the cache. + */ + if (*locale_buf != NULL && strcmp(name, *locale_buf) == 0) { + *using_locale = 1; + return (_LDP_CACHE); + } + + /* + * Slurp the locale file into the cache. + */ + namesize = strlen(name) + 1; + + /* 'PathLocale' must be already set & checked. */ + + /* Range checking not needed, 'name' size is limited */ + strcpy(filename, _PathLocale); + strcat(filename, "/"); + strcat(filename, name); + strcat(filename, "/"); + strcat(filename, category_filename); + if ((fd = _open(filename, O_RDONLY)) < 0) + return (_LDP_ERROR); + if (_fstat(fd, &st) != 0) + goto bad_locale; + if (st.st_size <= 0) { + errno = EFTYPE; + goto bad_locale; + } + bufsize = namesize + st.st_size; + if ((lbuf = malloc(bufsize)) == NULL) { + errno = ENOMEM; + goto bad_locale; + } + (void)strcpy(lbuf, name); + p = lbuf + namesize; + plim = p + st.st_size; + if (_read(fd, p, (size_t) st.st_size) != st.st_size) + goto bad_lbuf; + /* + * Parse the locale file into localebuf. + */ + if (plim[-1] != '\n') { + errno = EFTYPE; + goto bad_lbuf; + } + num_lines = split_lines(p, plim); + if (num_lines >= locale_buf_size_max) + num_lines = locale_buf_size_max; + else if (num_lines >= locale_buf_size_min) + num_lines = locale_buf_size_min; + else { + errno = EFTYPE; + goto bad_lbuf; + } + (void)_close(fd); + /* + * Record the successful parse in the cache. + */ + if (*locale_buf != NULL) + free(*locale_buf); + *locale_buf = lbuf; + for (p = *locale_buf, i = 0; i < num_lines; i++) + dst_localebuf[i] = (p += strlen(p) + 1); + for (i = num_lines; i < locale_buf_size_max; i++) + dst_localebuf[i] = NULL; + *using_locale = 1; + + return (_LDP_LOADED); + +bad_lbuf: + saverr = errno; + free(lbuf); + errno = saverr; +bad_locale: + saverr = errno; + (void)_close(fd); + errno = saverr; + + return (_LDP_ERROR); +} + +static int +split_lines(char *p, const char *plim) +{ + int i; + + i = 0; + while (p < plim) { + if (*p == '\n') { + *p = '\0'; + i++; + } + p++; + } + return (i); +} + diff --git a/lib/libc/locale/ldpart.h b/lib/libc/locale/ldpart.h new file mode 100644 index 0000000..02e0c95 --- /dev/null +++ b/lib/libc/locale/ldpart.h @@ -0,0 +1,39 @@ +/*- + * Copyright (c) 2000, 2001 Alexey Zelkin + * 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 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 AUTHOR 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. + * + * $FreeBSD: src/lib/libc/locale/ldpart.h,v 1.6 2003/06/13 00:14:07 jkh Exp $ + */ + +#ifndef _LDPART_H_ +#define _LDPART_H_ + +#define _LDP_LOADED 0 +#define _LDP_ERROR (-1) +#define _LDP_CACHE 1 + +int __part_load_locale(const char *, int*, char **, const char *, + int, int, const char **); + +#endif /* !_LDPART_H_ */ diff --git a/lib/libc/locale/lmessages.c b/lib/libc/locale/lmessages.c new file mode 100644 index 0000000..488b572 --- /dev/null +++ b/lib/libc/locale/lmessages.c @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2001 Alexey Zelkin + * 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 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 AUTHOR 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 +__FBSDID("$FreeBSD: src/lib/libc/locale/lmessages.c,v 1.14 2003/06/26 10:46:16 phantom Exp $"); + +#include + +#include "ldpart.h" +#include "lmessages.h" + +#define LCMESSAGES_SIZE_FULL (sizeof(struct lc_messages_T) / sizeof(char *)) +#define LCMESSAGES_SIZE_MIN \ + (offsetof(struct lc_messages_T, yesstr) / sizeof(char *)) + +static char empty[] = ""; + +static const struct lc_messages_T _C_messages_locale = { + "^[yY]" , /* yesexpr */ + "^[nN]" , /* noexpr */ + "yes" , /* yesstr */ + "no" /* nostr */ +}; + +static struct lc_messages_T _messages_locale; +static int _messages_using_locale; +static char *_messages_locale_buf; + +int +__messages_load_locale(const char *name) +{ + int ret; + + ret = __part_load_locale(name, &_messages_using_locale, + &_messages_locale_buf, "LC_MESSAGES", + LCMESSAGES_SIZE_FULL, LCMESSAGES_SIZE_MIN, + (const char **)&_messages_locale); + if (ret == _LDP_LOADED) { + if (_messages_locale.yesstr == NULL) + _messages_locale.yesstr = empty; + if (_messages_locale.nostr == NULL) + _messages_locale.nostr = empty; + } + return (ret); +} + +struct lc_messages_T * +__get_current_messages_locale(void) +{ + return (_messages_using_locale + ? &_messages_locale + : (struct lc_messages_T *)&_C_messages_locale); +} + +#ifdef LOCALE_DEBUG +void +msgdebug() { +printf( "yesexpr = %s\n" + "noexpr = %s\n" + "yesstr = %s\n" + "nostr = %s\n", + _messages_locale.yesexpr, + _messages_locale.noexpr, + _messages_locale.yesstr, + _messages_locale.nostr +); +} +#endif /* LOCALE_DEBUG */ diff --git a/lib/libc/locale/lmessages.h b/lib/libc/locale/lmessages.h new file mode 100644 index 0000000..ee690ae --- /dev/null +++ b/lib/libc/locale/lmessages.h @@ -0,0 +1,42 @@ +/*- + * Copyright (c) 2000, 2001 Alexey Zelkin + * 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 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 AUTHOR 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. + * + * $FreeBSD: src/lib/libc/locale/lmessages.h,v 1.3 2001/12/20 18:28:52 phantom Exp $ + */ + +#ifndef _LMESSAGES_H_ +#define _LMESSAGES_H_ + +struct lc_messages_T { + const char *yesexpr; + const char *noexpr; + const char *yesstr; + const char *nostr; +}; + +struct lc_messages_T *__get_current_messages_locale(void); +int __messages_load_locale(const char *); + +#endif /* !_LMESSAGES_H_ */ diff --git a/lib/libc/locale/lmonetary.c b/lib/libc/locale/lmonetary.c new file mode 100644 index 0000000..e3e7095 --- /dev/null +++ b/lib/libc/locale/lmonetary.c @@ -0,0 +1,192 @@ +/* + * Copyright (c) 2000, 2001 Alexey Zelkin + * 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 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 AUTHOR 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 +__FBSDID("$FreeBSD: src/lib/libc/locale/lmonetary.c,v 1.19 2003/06/26 10:46:16 phantom Exp $"); + +#include +#include +#include + +#include "ldpart.h" +#include "lmonetary.h" + +extern int __mlocale_changed; +extern const char * __fix_locale_grouping_str(const char *); + +#define LCMONETARY_SIZE_FULL (sizeof(struct lc_monetary_T) / sizeof(char *)) +#define LCMONETARY_SIZE_MIN \ + (offsetof(struct lc_monetary_T, int_p_cs_precedes) / \ + sizeof(char *)) + +static char empty[] = ""; +static char numempty[] = { CHAR_MAX, '\0'}; + +static const struct lc_monetary_T _C_monetary_locale = { + empty, /* int_curr_symbol */ + empty, /* currency_symbol */ + empty, /* mon_decimal_point */ + empty, /* mon_thousands_sep */ + numempty, /* mon_grouping */ + empty, /* positive_sign */ + empty, /* negative_sign */ + numempty, /* int_frac_digits */ + numempty, /* frac_digits */ + numempty, /* p_cs_precedes */ + numempty, /* p_sep_by_space */ + numempty, /* n_cs_precedes */ + numempty, /* n_sep_by_space */ + numempty, /* p_sign_posn */ + numempty, /* n_sign_posn */ + numempty, /* int_p_cs_precedes */ + numempty, /* int_n_cs_precedes */ + numempty, /* int_p_sep_by_space */ + numempty, /* int_n_sep_by_space */ + numempty, /* int_p_sign_posn */ + numempty /* int_n_sign_posn */ +}; + +static struct lc_monetary_T _monetary_locale; +static int _monetary_using_locale; +static char *_monetary_locale_buf; + +static char +cnv(const char *str) +{ + int i = strtol(str, NULL, 10); + + if (i == -1) + i = CHAR_MAX; + return ((char)i); +} + +int +__monetary_load_locale(const char *name) +{ + int ret; + + ret = __part_load_locale(name, &_monetary_using_locale, + &_monetary_locale_buf, "LC_MONETARY", + LCMONETARY_SIZE_FULL, LCMONETARY_SIZE_MIN, + (const char **)&_monetary_locale); + if (ret != _LDP_ERROR) + __mlocale_changed = 1; + if (ret == _LDP_LOADED) { + _monetary_locale.mon_grouping = + __fix_locale_grouping_str(_monetary_locale.mon_grouping); + +#define M_ASSIGN_CHAR(NAME) (((char *)_monetary_locale.NAME)[0] = \ + cnv(_monetary_locale.NAME)) + + M_ASSIGN_CHAR(int_frac_digits); + M_ASSIGN_CHAR(frac_digits); + M_ASSIGN_CHAR(p_cs_precedes); + M_ASSIGN_CHAR(p_sep_by_space); + M_ASSIGN_CHAR(n_cs_precedes); + M_ASSIGN_CHAR(n_sep_by_space); + M_ASSIGN_CHAR(p_sign_posn); + M_ASSIGN_CHAR(n_sign_posn); + + /* + * The six additional C99 international monetary formatting + * parameters default to the national parameters when + * reading FreeBSD LC_MONETARY data files. + */ +#define M_ASSIGN_ICHAR(NAME) \ + do { \ + if (_monetary_locale.int_##NAME == NULL) \ + _monetary_locale.int_##NAME = \ + _monetary_locale.NAME; \ + else \ + M_ASSIGN_CHAR(int_##NAME); \ + } while (0) + + M_ASSIGN_ICHAR(p_cs_precedes); + M_ASSIGN_ICHAR(n_cs_precedes); + M_ASSIGN_ICHAR(p_sep_by_space); + M_ASSIGN_ICHAR(n_sep_by_space); + M_ASSIGN_ICHAR(p_sign_posn); + M_ASSIGN_ICHAR(n_sign_posn); + } + return (ret); +} + +struct lc_monetary_T * +__get_current_monetary_locale(void) +{ + return (_monetary_using_locale + ? &_monetary_locale + : (struct lc_monetary_T *)&_C_monetary_locale); +} + +#ifdef LOCALE_DEBUG +void +monetdebug() { +printf( "int_curr_symbol = %s\n" + "currency_symbol = %s\n" + "mon_decimal_point = %s\n" + "mon_thousands_sep = %s\n" + "mon_grouping = %s\n" + "positive_sign = %s\n" + "negative_sign = %s\n" + "int_frac_digits = %d\n" + "frac_digits = %d\n" + "p_cs_precedes = %d\n" + "p_sep_by_space = %d\n" + "n_cs_precedes = %d\n" + "n_sep_by_space = %d\n" + "p_sign_posn = %d\n" + "n_sign_posn = %d\n", + "int_p_cs_precedes = %d\n" + "int_p_sep_by_space = %d\n" + "int_n_cs_precedes = %d\n" + "int_n_sep_by_space = %d\n" + "int_p_sign_posn = %d\n" + "int_n_sign_posn = %d\n", + _monetary_locale.int_curr_symbol, + _monetary_locale.currency_symbol, + _monetary_locale.mon_decimal_point, + _monetary_locale.mon_thousands_sep, + _monetary_locale.mon_grouping, + _monetary_locale.positive_sign, + _monetary_locale.negative_sign, + _monetary_locale.int_frac_digits[0], + _monetary_locale.frac_digits[0], + _monetary_locale.p_cs_precedes[0], + _monetary_locale.p_sep_by_space[0], + _monetary_locale.n_cs_precedes[0], + _monetary_locale.n_sep_by_space[0], + _monetary_locale.p_sign_posn[0], + _monetary_locale.n_sign_posn[0], + _monetary_locale.int_p_cs_precedes[0], + _monetary_locale.int_p_sep_by_space[0], + _monetary_locale.int_n_cs_precedes[0], + _monetary_locale.int_n_sep_by_space[0], + _monetary_locale.int_p_sign_posn[0], + _monetary_locale.int_n_sign_posn[0] +); +} +#endif /* LOCALE_DEBUG */ diff --git a/lib/libc/locale/lmonetary.h b/lib/libc/locale/lmonetary.h new file mode 100644 index 0000000..e278ea5 --- /dev/null +++ b/lib/libc/locale/lmonetary.h @@ -0,0 +1,59 @@ +/*- + * Copyright (c) 2000, 2001 Alexey Zelkin + * 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 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 AUTHOR 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. + * + * $FreeBSD: src/lib/libc/locale/lmonetary.h,v 1.4 2002/10/09 09:19:28 tjr Exp $ + */ + +#ifndef _LMONETARY_H_ +#define _LMONETARY_H_ + +struct lc_monetary_T { + const char *int_curr_symbol; + const char *currency_symbol; + const char *mon_decimal_point; + const char *mon_thousands_sep; + const char *mon_grouping; + const char *positive_sign; + const char *negative_sign; + const char *int_frac_digits; + const char *frac_digits; + const char *p_cs_precedes; + const char *p_sep_by_space; + const char *n_cs_precedes; + const char *n_sep_by_space; + const char *p_sign_posn; + const char *n_sign_posn; + const char *int_p_cs_precedes; + const char *int_n_cs_precedes; + const char *int_p_sep_by_space; + const char *int_n_sep_by_space; + const char *int_p_sign_posn; + const char *int_n_sign_posn; +}; + +struct lc_monetary_T *__get_current_monetary_locale(void); +int __monetary_load_locale(const char *); + +#endif /* !_LMONETARY_H_ */ diff --git a/lib/libc/locale/lnumeric.c b/lib/libc/locale/lnumeric.c new file mode 100644 index 0000000..ff9c948 --- /dev/null +++ b/lib/libc/locale/lnumeric.c @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2000, 2001 Alexey Zelkin + * 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 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 AUTHOR 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 +__FBSDID("$FreeBSD: src/lib/libc/locale/lnumeric.c,v 1.16 2003/06/26 10:46:16 phantom Exp $"); + +#include + +#include "ldpart.h" +#include "lnumeric.h" + +extern int __nlocale_changed; +extern const char *__fix_locale_grouping_str(const char *); + +#define LCNUMERIC_SIZE (sizeof(struct lc_numeric_T) / sizeof(char *)) + +static char numempty[] = { CHAR_MAX, '\0' }; + +static const struct lc_numeric_T _C_numeric_locale = { + ".", /* decimal_point */ + "", /* thousands_sep */ + numempty /* grouping */ +}; + +static struct lc_numeric_T _numeric_locale; +static int _numeric_using_locale; +static char *_numeric_locale_buf; + +int +__numeric_load_locale(const char *name) +{ + int ret; + + ret = __part_load_locale(name, &_numeric_using_locale, + &_numeric_locale_buf, "LC_NUMERIC", + LCNUMERIC_SIZE, LCNUMERIC_SIZE, + (const char **)&_numeric_locale); + if (ret != _LDP_ERROR) + __nlocale_changed = 1; + if (ret == _LDP_LOADED) { + /* Can't be empty according to C99 */ + if (*_numeric_locale.decimal_point == '\0') + _numeric_locale.decimal_point = + _C_numeric_locale.decimal_point; + _numeric_locale.grouping = + __fix_locale_grouping_str(_numeric_locale.grouping); + } + return (ret); +} + +struct lc_numeric_T * +__get_current_numeric_locale(void) +{ + return (_numeric_using_locale + ? &_numeric_locale + : (struct lc_numeric_T *)&_C_numeric_locale); +} + +#ifdef LOCALE_DEBUG +void +numericdebug(void) { +printf( "decimal_point = %s\n" + "thousands_sep = %s\n" + "grouping = %s\n", + _numeric_locale.decimal_point, + _numeric_locale.thousands_sep, + _numeric_locale.grouping +); +} +#endif /* LOCALE_DEBUG */ diff --git a/lib/libc/locale/lnumeric.h b/lib/libc/locale/lnumeric.h new file mode 100644 index 0000000..9678c1f --- /dev/null +++ b/lib/libc/locale/lnumeric.h @@ -0,0 +1,41 @@ +/*- + * Copyright (c) 2000, 2001 Alexey Zelkin + * 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 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 AUTHOR 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. + * + * $FreeBSD: src/lib/libc/locale/lnumeric.h,v 1.3 2001/12/20 18:28:52 phantom Exp $ + */ + +#ifndef _LNUMERIC_H_ +#define _LNUMERIC_H_ + +struct lc_numeric_T { + const char *decimal_point; + const char *thousands_sep; + const char *grouping; +}; + +struct lc_numeric_T *__get_current_numeric_locale(void); +int __numeric_load_locale(const char *); + +#endif /* !_LNUMERIC_H_ */ diff --git a/lib/libc/locale/localeconv.c b/lib/libc/locale/localeconv.c new file mode 100644 index 0000000..1420aa8 --- /dev/null +++ b/lib/libc/locale/localeconv.c @@ -0,0 +1,112 @@ +/* + * Copyright (c) 2001 Alexey Zelkin + * Copyright (c) 1991, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)localeconv.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/locale/localeconv.c,v 1.13 2003/06/26 10:46:16 phantom Exp $"); + +#include + +#include "lmonetary.h" +#include "lnumeric.h" + +/* + * The localeconv() function constructs a struct lconv from the current + * monetary and numeric locales. + * + * Because localeconv() may be called many times (especially by library + * routines like printf() & strtod()), the approprate members of the + * lconv structure are computed only when the monetary or numeric + * locale has been changed. + */ +int __mlocale_changed = 1; +int __nlocale_changed = 1; + +/* + * Return the current locale conversion. + */ +struct lconv * +localeconv() +{ + static struct lconv ret; + + if (__mlocale_changed) { + /* LC_MONETARY part */ + struct lc_monetary_T * mptr; + +#define M_ASSIGN_STR(NAME) (ret.NAME = (char*)mptr->NAME) +#define M_ASSIGN_CHAR(NAME) (ret.NAME = mptr->NAME[0]) + + mptr = __get_current_monetary_locale(); + M_ASSIGN_STR(int_curr_symbol); + M_ASSIGN_STR(currency_symbol); + M_ASSIGN_STR(mon_decimal_point); + M_ASSIGN_STR(mon_thousands_sep); + M_ASSIGN_STR(mon_grouping); + M_ASSIGN_STR(positive_sign); + M_ASSIGN_STR(negative_sign); + M_ASSIGN_CHAR(int_frac_digits); + M_ASSIGN_CHAR(frac_digits); + M_ASSIGN_CHAR(p_cs_precedes); + M_ASSIGN_CHAR(p_sep_by_space); + M_ASSIGN_CHAR(n_cs_precedes); + M_ASSIGN_CHAR(n_sep_by_space); + M_ASSIGN_CHAR(p_sign_posn); + M_ASSIGN_CHAR(n_sign_posn); + M_ASSIGN_CHAR(int_p_cs_precedes); + M_ASSIGN_CHAR(int_n_cs_precedes); + M_ASSIGN_CHAR(int_p_sep_by_space); + M_ASSIGN_CHAR(int_n_sep_by_space); + M_ASSIGN_CHAR(int_p_sign_posn); + M_ASSIGN_CHAR(int_n_sign_posn); + __mlocale_changed = 0; + } + + if (__nlocale_changed) { + /* LC_NUMERIC part */ + struct lc_numeric_T * nptr; + +#define N_ASSIGN_STR(NAME) (ret.NAME = (char*)nptr->NAME) + + nptr = __get_current_numeric_locale(); + N_ASSIGN_STR(decimal_point); + N_ASSIGN_STR(thousands_sep); + N_ASSIGN_STR(grouping); + __nlocale_changed = 0; + } + + return (&ret); +} diff --git a/lib/libc/locale/mblen.c b/lib/libc/locale/mblen.c new file mode 100644 index 0000000..2891e90 --- /dev/null +++ b/lib/libc/locale/mblen.c @@ -0,0 +1,50 @@ +/*- + * Copyright (c) 2002-2004 Tim J. Robbins. + * 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 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 AUTHOR 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 +__FBSDID("$FreeBSD: src/lib/libc/locale/mblen.c,v 1.9 2004/07/29 06:18:40 tjr Exp $"); + +#include +#include +#include "mblocal.h" + +int +mblen(const char *s, size_t n) +{ + static const mbstate_t initial; + static mbstate_t mbs; + size_t rval; + + if (s == NULL) { + /* No support for state dependent encodings. */ + mbs = initial; + return (0); + } + rval = __mbrtowc(NULL, s, n, &mbs); + if (rval == (size_t)-1 || rval == (size_t)-2) + return (-1); + return ((int)rval); +} diff --git a/lib/libc/locale/mblocal.h b/lib/libc/locale/mblocal.h new file mode 100644 index 0000000..63c5b16 --- /dev/null +++ b/lib/libc/locale/mblocal.h @@ -0,0 +1,61 @@ +/*- + * Copyright (c) 2004 Tim J. Robbins. + * 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 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 AUTHOR 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. + * + * $FreeBSD: src/lib/libc/locale/mblocal.h,v 1.5 2005/02/27 15:11:09 phantom Exp $ + */ + +#ifndef _MBLOCAL_H_ +#define _MBLOCAL_H_ + +/* + * Rune initialization function prototypes. + */ +int _none_init(_RuneLocale *); +int _UTF8_init(_RuneLocale *); +int _EUC_init(_RuneLocale *); +int _GB18030_init(_RuneLocale *); +int _GB2312_init(_RuneLocale *); +int _GBK_init(_RuneLocale *); +int _BIG5_init(_RuneLocale *); +int _MSKanji_init(_RuneLocale *); + +/* + * Conversion function pointers for current encoding. + */ +extern size_t (*__mbrtowc)(wchar_t * __restrict, const char * __restrict, + size_t, mbstate_t * __restrict); +extern int (*__mbsinit)(const mbstate_t *); +extern size_t (*__mbsnrtowcs)(wchar_t * __restrict, const char ** __restrict, + size_t, size_t, mbstate_t * __restrict); +extern size_t (*__wcrtomb)(char * __restrict, wchar_t, mbstate_t * __restrict); +extern size_t (*__wcsnrtombs)(char * __restrict, const wchar_t ** __restrict, + size_t, size_t, mbstate_t * __restrict); + +extern size_t __mbsnrtowcs_std(wchar_t * __restrict, const char ** __restrict, + size_t, size_t, mbstate_t * __restrict); +extern size_t __wcsnrtombs_std(char * __restrict, const wchar_t ** __restrict, + size_t, size_t, mbstate_t * __restrict); + +#endif /* _MBLOCAL_H_ */ diff --git a/lib/libc/locale/mbrlen.c b/lib/libc/locale/mbrlen.c new file mode 100644 index 0000000..33f7ea0 --- /dev/null +++ b/lib/libc/locale/mbrlen.c @@ -0,0 +1,41 @@ +/*- + * Copyright (c) 2002-2004 Tim J. Robbins. + * 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 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 AUTHOR 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 +__FBSDID("$FreeBSD: src/lib/libc/locale/mbrlen.c,v 1.4 2004/05/12 14:26:54 tjr Exp $"); + +#include +#include "mblocal.h" + +size_t +mbrlen(const char * __restrict s, size_t n, mbstate_t * __restrict ps) +{ + static mbstate_t mbs; + + if (ps == NULL) + ps = &mbs; + return (__mbrtowc(NULL, s, n, ps)); +} diff --git a/lib/libc/locale/mbrtowc.c b/lib/libc/locale/mbrtowc.c new file mode 100644 index 0000000..9b19d10 --- /dev/null +++ b/lib/libc/locale/mbrtowc.c @@ -0,0 +1,42 @@ +/*- + * Copyright (c) 2002-2004 Tim J. Robbins. + * 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 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 AUTHOR 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 +__FBSDID("$FreeBSD: src/lib/libc/locale/mbrtowc.c,v 1.7 2004/05/12 14:09:04 tjr Exp $"); + +#include +#include "mblocal.h" + +size_t +mbrtowc(wchar_t * __restrict pwc, const char * __restrict s, + size_t n, mbstate_t * __restrict ps) +{ + static mbstate_t mbs; + + if (ps == NULL) + ps = &mbs; + return (__mbrtowc(pwc, s, n, ps)); +} diff --git a/lib/libc/locale/mbsinit.c b/lib/libc/locale/mbsinit.c new file mode 100644 index 0000000..cddb567 --- /dev/null +++ b/lib/libc/locale/mbsinit.c @@ -0,0 +1,38 @@ +/*- + * Copyright (c) 2002-2004 Tim J. Robbins. + * 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 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 AUTHOR 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 +__FBSDID("$FreeBSD: src/lib/libc/locale/mbsinit.c,v 1.3 2004/05/12 14:09:04 tjr Exp $"); + +#include +#include "mblocal.h" + +int +mbsinit(const mbstate_t *ps) +{ + + return (__mbsinit(ps)); +} diff --git a/lib/libc/locale/mbsnrtowcs.c b/lib/libc/locale/mbsnrtowcs.c new file mode 100644 index 0000000..3e65b15 --- /dev/null +++ b/lib/libc/locale/mbsnrtowcs.c @@ -0,0 +1,91 @@ +/*- + * Copyright (c) 2002-2004 Tim J. Robbins. + * 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 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 AUTHOR 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 +__FBSDID("$FreeBSD: src/lib/libc/locale/mbsnrtowcs.c,v 1.1 2004/07/21 10:54:57 tjr Exp $"); + +#include +#include +#include +#include +#include "mblocal.h" + +size_t +mbsnrtowcs(wchar_t * __restrict dst, const char ** __restrict src, + size_t nms, size_t len, mbstate_t * __restrict ps) +{ + static mbstate_t mbs; + + if (ps == NULL) + ps = &mbs; + return (__mbsnrtowcs(dst, src, nms, len, ps)); +} + +size_t +__mbsnrtowcs_std(wchar_t * __restrict dst, const char ** __restrict src, + size_t nms, size_t len, mbstate_t * __restrict ps) +{ + const char *s; + size_t nchr; + wchar_t wc; + size_t nb; + + s = *src; + nchr = 0; + + if (dst == NULL) { + for (;;) { + if ((nb = __mbrtowc(&wc, s, nms, ps)) == (size_t)-1) + /* Invalid sequence - mbrtowc() sets errno. */ + return ((size_t)-1); + else if (nb == 0 || nb == (size_t)-2) + return (nchr); + s += nb; + nms -= nb; + nchr++; + } + /*NOTREACHED*/ + } + + while (len-- > 0) { + if ((nb = __mbrtowc(dst, s, nms, ps)) == (size_t)-1) { + *src = s; + return ((size_t)-1); + } else if (nb == (size_t)-2) { + *src = s + nms; + return (nchr); + } else if (nb == 0) { + *src = NULL; + return (nchr); + } + s += nb; + nms -= nb; + nchr++; + dst++; + } + *src = s; + return (nchr); +} diff --git a/lib/libc/locale/mbsrtowcs.c b/lib/libc/locale/mbsrtowcs.c new file mode 100644 index 0000000..12feaab --- /dev/null +++ b/lib/libc/locale/mbsrtowcs.c @@ -0,0 +1,45 @@ +/*- + * Copyright (c) 2002-2004 Tim J. Robbins. + * 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 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 AUTHOR 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 +__FBSDID("$FreeBSD: src/lib/libc/locale/mbsrtowcs.c,v 1.6 2004/07/21 10:54:57 tjr Exp $"); + +#include +#include +#include +#include +#include "mblocal.h" + +size_t +mbsrtowcs(wchar_t * __restrict dst, const char ** __restrict src, size_t len, + mbstate_t * __restrict ps) +{ + static mbstate_t mbs; + + if (ps == NULL) + ps = &mbs; + return (__mbsnrtowcs(dst, src, SIZE_T_MAX, len, ps)); +} diff --git a/lib/libc/locale/mbstowcs.c b/lib/libc/locale/mbstowcs.c new file mode 100644 index 0000000..ab2e849 --- /dev/null +++ b/lib/libc/locale/mbstowcs.c @@ -0,0 +1,43 @@ +/*- + * Copyright (c) 2002-2004 Tim J. Robbins. + * 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 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 AUTHOR 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 +__FBSDID("$FreeBSD: src/lib/libc/locale/mbstowcs.c,v 1.11 2004/07/21 10:54:57 tjr Exp $"); + +#include +#include +#include +#include "mblocal.h" + +size_t +mbstowcs(wchar_t * __restrict pwcs, const char * __restrict s, size_t n) +{ + static const mbstate_t initial; + mbstate_t mbs; + + mbs = initial; + return (__mbsnrtowcs(pwcs, &s, SIZE_T_MAX, n, &mbs)); +} diff --git a/lib/libc/locale/mbtowc.c b/lib/libc/locale/mbtowc.c new file mode 100644 index 0000000..5e3a368 --- /dev/null +++ b/lib/libc/locale/mbtowc.c @@ -0,0 +1,50 @@ +/*- + * Copyright (c) 2002-2004 Tim J. Robbins. + * 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 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 AUTHOR 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 +__FBSDID("$FreeBSD: src/lib/libc/locale/mbtowc.c,v 1.11 2004/07/29 06:18:40 tjr Exp $"); + +#include +#include +#include "mblocal.h" + +int +mbtowc(wchar_t * __restrict pwc, const char * __restrict s, size_t n) +{ + static const mbstate_t initial; + static mbstate_t mbs; + size_t rval; + + if (s == NULL) { + /* No support for state dependent encodings. */ + mbs = initial; + return (0); + } + rval = __mbrtowc(pwc, s, n, &mbs); + if (rval == (size_t)-1 || rval == (size_t)-2) + return (-1); + return ((int)rval); +} diff --git a/lib/libc/locale/mskanji.c b/lib/libc/locale/mskanji.c new file mode 100644 index 0000000..9735d3a --- /dev/null +++ b/lib/libc/locale/mskanji.c @@ -0,0 +1,157 @@ +/* + * Copyright (c) 2002-2004 Tim J. Robbins. All rights reserved. + * + * ja_JP.SJIS locale table for BSD4.4/rune + * version 1.0 + * (C) Sin'ichiro MIYATANI / Phase One, Inc + * May 12, 1995 + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by Phase One, Inc. + * 4. The name of Phase One, Inc. may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)mskanji.c 1.0 (Phase One) 5/5/95"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/locale/mskanji.c,v 1.17 2005/02/27 15:11:09 phantom Exp $"); + +#include +#include +#include +#include +#include +#include +#include "mblocal.h" + +static size_t _MSKanji_mbrtowc(wchar_t * __restrict, const char * __restrict, + size_t, mbstate_t * __restrict); +static int _MSKanji_mbsinit(const mbstate_t *); +static size_t _MSKanji_wcrtomb(char * __restrict, wchar_t, + mbstate_t * __restrict); + +typedef struct { + wchar_t ch; +} _MSKanjiState; + +int +_MSKanji_init(_RuneLocale *rl) +{ + + __mbrtowc = _MSKanji_mbrtowc; + __wcrtomb = _MSKanji_wcrtomb; + __mbsinit = _MSKanji_mbsinit; + _CurrentRuneLocale = rl; + __mb_cur_max = 2; + return (0); +} + +static int +_MSKanji_mbsinit(const mbstate_t *ps) +{ + + return (ps == NULL || ((const _MSKanjiState *)ps)->ch == 0); +} + +static size_t +_MSKanji_mbrtowc(wchar_t * __restrict pwc, const char * __restrict s, size_t n, + mbstate_t * __restrict ps) +{ + _MSKanjiState *ms; + wchar_t wc; + + ms = (_MSKanjiState *)ps; + + if ((ms->ch & ~0xFF) != 0) { + /* Bad conversion state. */ + errno = EINVAL; + return ((size_t)-1); + } + + if (s == NULL) { + s = ""; + n = 1; + pwc = NULL; + } + + if (n == 0) + /* Incomplete multibyte sequence */ + return ((size_t)-2); + + if (ms->ch != 0) { + if (*s == '\0') { + errno = EILSEQ; + return ((size_t)-1); + } + wc = (ms->ch << 8) | (*s & 0xFF); + if (pwc != NULL) + *pwc = wc; + ms->ch = 0; + return (1); + } + wc = *s++ & 0xff; + if ((wc > 0x80 && wc < 0xa0) || (wc >= 0xe0 && wc < 0xfd)) { + if (n < 2) { + /* Incomplete multibyte sequence */ + ms->ch = wc; + return ((size_t)-2); + } + if (*s == '\0') { + errno = EILSEQ; + return ((size_t)-1); + } + wc = (wc << 8) | (*s++ & 0xff); + if (pwc != NULL) + *pwc = wc; + return (2); + } else { + if (pwc != NULL) + *pwc = wc; + return (wc == L'\0' ? 0 : 1); + } +} + +static size_t +_MSKanji_wcrtomb(char * __restrict s, wchar_t wc, mbstate_t * __restrict ps) +{ + _MSKanjiState *ms; + int len, i; + + ms = (_MSKanjiState *)ps; + + if (ms->ch != 0) { + errno = EINVAL; + return ((size_t)-1); + } + + if (s == NULL) + /* Reset to initial shift state (no-op) */ + return (1); + len = (wc > 0x100) ? 2 : 1; + for (i = len; i-- > 0; ) + *s++ = wc >> (i << 3); + return (len); +} diff --git a/lib/libc/locale/nextwctype.c b/lib/libc/locale/nextwctype.c new file mode 100644 index 0000000..89c63df --- /dev/null +++ b/lib/libc/locale/nextwctype.c @@ -0,0 +1,90 @@ +/*- + * Copyright (c) 2004 Tim J. Robbins. + * 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 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 AUTHOR 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 +__FBSDID("$FreeBSD: src/lib/libc/locale/nextwctype.c,v 1.1 2004/07/08 06:43:37 tjr Exp $"); + +#include +#include +#include + +wint_t +nextwctype(wint_t wc, wctype_t wct) +{ + size_t lim; + _RuneRange *rr = &_CurrentRuneLocale->__runetype_ext; + _RuneEntry *base, *re; + int noinc; + + noinc = 0; + if (wc < _CACHED_RUNES) { + wc++; + while (wc < _CACHED_RUNES) { + if (_CurrentRuneLocale->__runetype[wc] & wct) + return (wc); + wc++; + } + wc--; + } + if (rr->__ranges != NULL && wc < rr->__ranges[0].__min) { + wc = rr->__ranges[0].__min; + noinc = 1; + } + + /* Binary search -- see bsearch.c for explanation. */ + base = rr->__ranges; + for (lim = rr->__nranges; lim != 0; lim >>= 1) { + re = base + (lim >> 1); + if (re->__min <= wc && wc <= re->__max) + goto found; + else if (wc > re->__max) { + base = re + 1; + lim--; + } + } + return (-1); +found: + if (!noinc) + wc++; + if (re->__min <= wc && wc <= re->__max) { + if (re->__types != NULL) { + for (; wc <= re->__max; wc++) + if (re->__types[wc - re->__min] & wct) + return (wc); + } else if (re->__map & wct) + return (wc); + } + while (++re < rr->__ranges + rr->__nranges) { + wc = re->__min; + if (re->__types != NULL) { + for (; wc <= re->__max; wc++) + if (re->__types[wc - re->__min] & wct) + return (wc); + } else if (re->__map & wct) + return (wc); + } + return (-1); +} diff --git a/lib/libc/locale/nl_langinfo.c b/lib/libc/locale/nl_langinfo.c new file mode 100644 index 0000000..22d27a3 --- /dev/null +++ b/lib/libc/locale/nl_langinfo.c @@ -0,0 +1,175 @@ +/*- + * Copyright (c) 2001, 2003 Alexey Zelkin + * 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 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 AUTHOR 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 +__FBSDID("$FreeBSD: src/lib/libc/locale/nl_langinfo.c,v 1.17 2003/06/26 10:46:16 phantom Exp $"); + +#include +#include +#include +#include +#include + +#include "lnumeric.h" +#include "lmessages.h" +#include "lmonetary.h" +#include "../stdtime/timelocal.h" + +#define _REL(BASE) ((int)item-BASE) + +char * +nl_langinfo(nl_item item) +{ + char *ret, *s, *cs; + static char *csym = NULL; + + switch (item) { + case CODESET: + ret = ""; + if ((s = setlocale(LC_CTYPE, NULL)) != NULL) { + if ((cs = strchr(s, '.')) != NULL) + ret = cs + 1; + else if (strcmp(s, "C") == 0 || + strcmp(s, "POSIX") == 0) + ret = "US-ASCII"; + } + break; + case D_T_FMT: + ret = (char *) __get_current_time_locale()->c_fmt; + break; + case D_FMT: + ret = (char *) __get_current_time_locale()->x_fmt; + break; + case T_FMT: + ret = (char *) __get_current_time_locale()->X_fmt; + break; + case T_FMT_AMPM: + ret = (char *) __get_current_time_locale()->ampm_fmt; + break; + case AM_STR: + ret = (char *) __get_current_time_locale()->am; + break; + case PM_STR: + ret = (char *) __get_current_time_locale()->pm; + break; + case DAY_1: case DAY_2: case DAY_3: + case DAY_4: case DAY_5: case DAY_6: case DAY_7: + ret = (char*) __get_current_time_locale()->weekday[_REL(DAY_1)]; + break; + case ABDAY_1: case ABDAY_2: case ABDAY_3: + case ABDAY_4: case ABDAY_5: case ABDAY_6: case ABDAY_7: + ret = (char*) __get_current_time_locale()->wday[_REL(ABDAY_1)]; + break; + case MON_1: case MON_2: case MON_3: case MON_4: + case MON_5: case MON_6: case MON_7: case MON_8: + case MON_9: case MON_10: case MON_11: case MON_12: + ret = (char*) __get_current_time_locale()->month[_REL(MON_1)]; + break; + case ABMON_1: case ABMON_2: case ABMON_3: case ABMON_4: + case ABMON_5: case ABMON_6: case ABMON_7: case ABMON_8: + case ABMON_9: case ABMON_10: case ABMON_11: case ABMON_12: + ret = (char*) __get_current_time_locale()->mon[_REL(ABMON_1)]; + break; + case ERA: + /* XXX: need to be implemented */ + ret = ""; + break; + case ERA_D_FMT: + /* XXX: need to be implemented */ + ret = ""; + break; + case ERA_D_T_FMT: + /* XXX: need to be implemented */ + ret = ""; + break; + case ERA_T_FMT: + /* XXX: need to be implemented */ + ret = ""; + break; + case ALT_DIGITS: + /* XXX: need to be implemented */ + ret = ""; + break; + case RADIXCHAR: + ret = (char*) __get_current_numeric_locale()->decimal_point; + break; + case THOUSEP: + ret = (char*) __get_current_numeric_locale()->thousands_sep; + break; + case YESEXPR: + ret = (char*) __get_current_messages_locale()->yesexpr; + break; + case NOEXPR: + ret = (char*) __get_current_messages_locale()->noexpr; + break; + /* + * YESSTR and NOSTR items marked with LEGACY are available, but not + * recomended by SUSv2 to be used in portable applications since + * they're subject to remove in future specification editions. + */ + case YESSTR: /* LEGACY */ + ret = (char*) __get_current_messages_locale()->yesstr; + break; + case NOSTR: /* LEGACY */ + ret = (char*) __get_current_messages_locale()->nostr; + break; + /* + * SUSv2 special formatted currency string + */ + case CRNCYSTR: + ret = ""; + cs = (char*) __get_current_monetary_locale()->currency_symbol; + if (*cs != '\0') { + char pos = localeconv()->p_cs_precedes; + + if (pos == localeconv()->n_cs_precedes) { + char psn = '\0'; + + if (pos == CHAR_MAX) { + if (strcmp(cs, __get_current_monetary_locale()->mon_decimal_point) == 0) + psn = '.'; + } else + psn = pos ? '-' : '+'; + if (psn != '\0') { + int clen = strlen(cs); + + if ((csym = reallocf(csym, clen + 2)) != NULL) { + *csym = psn; + strcpy(csym + 1, cs); + ret = csym; + } + } + } + } + break; + case D_MD_ORDER: /* FreeBSD local extension */ + ret = (char *) __get_current_time_locale()->md_order; + break; + default: + ret = ""; + } + return (ret); +} diff --git a/lib/libc/locale/nomacros.c b/lib/libc/locale/nomacros.c new file mode 100644 index 0000000..eea37d0 --- /dev/null +++ b/lib/libc/locale/nomacros.c @@ -0,0 +1,12 @@ +#include +__FBSDID("$FreeBSD: src/lib/libc/locale/nomacros.c,v 1.5 2002/03/22 21:52:18 obrien Exp $"); + +/* + * Tell to generate extern versions of all its inline + * functions. The extern versions get called if the system doesn't + * support inlines or the user defines _DONT_USE_CTYPE_INLINE_ + * before including . + */ +#define _EXTERNALIZE_CTYPE_INLINES_ + +#include diff --git a/lib/libc/locale/none.c b/lib/libc/locale/none.c new file mode 100644 index 0000000..6381019 --- /dev/null +++ b/lib/libc/locale/none.c @@ -0,0 +1,193 @@ +/*- + * Copyright (c) 2002-2004 Tim J. Robbins. All rights reserved. + * Copyright (c) 1993 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * Paul Borman at Krystal Technologies. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)none.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/locale/none.c,v 1.13 2005/02/27 15:11:09 phantom Exp $"); + +#include +#include +#include +#include +#include +#include +#include +#include +#include "mblocal.h" + +static size_t _none_mbrtowc(wchar_t * __restrict, const char * __restrict, + size_t, mbstate_t * __restrict); +static int _none_mbsinit(const mbstate_t *); +static size_t _none_mbsnrtowcs(wchar_t * __restrict dst, + const char ** __restrict src, size_t nms, size_t len, + mbstate_t * __restrict ps __unused); +static size_t _none_wcrtomb(char * __restrict, wchar_t, + mbstate_t * __restrict); +static size_t _none_wcsnrtombs(char * __restrict, const wchar_t ** __restrict, + size_t, size_t, mbstate_t * __restrict); + +int +_none_init(_RuneLocale *rl) +{ + + __mbrtowc = _none_mbrtowc; + __mbsinit = _none_mbsinit; + __mbsnrtowcs = _none_mbsnrtowcs; + __wcrtomb = _none_wcrtomb; + __wcsnrtombs = _none_wcsnrtombs; + _CurrentRuneLocale = rl; + __mb_cur_max = 1; + return(0); +} + +static int +_none_mbsinit(const mbstate_t *ps __unused) +{ + + /* + * Encoding is not state dependent - we are always in the + * initial state. + */ + return (1); +} + +static size_t +_none_mbrtowc(wchar_t * __restrict pwc, const char * __restrict s, size_t n, + mbstate_t * __restrict ps __unused) +{ + + if (s == NULL) + /* Reset to initial shift state (no-op) */ + return (0); + if (n == 0) + /* Incomplete multibyte sequence */ + return ((size_t)-2); + if (pwc != NULL) + *pwc = (unsigned char)*s; + return (*s == '\0' ? 0 : 1); +} + +static size_t +_none_wcrtomb(char * __restrict s, wchar_t wc, + mbstate_t * __restrict ps __unused) +{ + + if (s == NULL) + /* Reset to initial shift state (no-op) */ + return (1); + if (wc < 0 || wc > UCHAR_MAX) { + errno = EILSEQ; + return ((size_t)-1); + } + *s = (unsigned char)wc; + return (1); +} + +static size_t +_none_mbsnrtowcs(wchar_t * __restrict dst, const char ** __restrict src, + size_t nms, size_t len, mbstate_t * __restrict ps __unused) +{ + const char *s; + size_t nchr; + + if (dst == NULL) { + s = memchr(*src, '\0', nms); + return (s != NULL ? s - *src : nms); + } + + s = *src; + nchr = 0; + while (len-- > 0 && nms-- > 0) { + if ((*dst++ = (unsigned char)*s++) == L'\0') { + *src = NULL; + return (nchr); + } + nchr++; + } + *src = s; + return (nchr); +} + +static size_t +_none_wcsnrtombs(char * __restrict dst, const wchar_t ** __restrict src, + size_t nwc, size_t len, mbstate_t * __restrict ps __unused) +{ + const wchar_t *s; + size_t nchr; + + if (dst == NULL) { + for (s = *src; nwc > 0 && *s != L'\0'; s++, nwc--) { + if (*s < 0 || *s > UCHAR_MAX) { + errno = EILSEQ; + return ((size_t)-1); + } + } + return (s - *src); + } + + s = *src; + nchr = 0; + while (len-- > 0 && nwc-- > 0) { + if (*s < 0 || *s > UCHAR_MAX) { + errno = EILSEQ; + return ((size_t)-1); + } + if ((*dst++ = *s++) == '\0') { + *src = NULL; + return (nchr); + } + nchr++; + } + *src = s; + return (nchr); +} + +/* setup defaults */ + +int __mb_cur_max = 1; +size_t (*__mbrtowc)(wchar_t * __restrict, const char * __restrict, size_t, + mbstate_t * __restrict) = _none_mbrtowc; +int (*__mbsinit)(const mbstate_t *) = _none_mbsinit; +size_t (*__mbsnrtowcs)(wchar_t * __restrict, const char ** __restrict, + size_t, size_t, mbstate_t * __restrict) = _none_mbsnrtowcs; +size_t (*__wcrtomb)(char * __restrict, wchar_t, mbstate_t * __restrict) = + _none_wcrtomb; +size_t (*__wcsnrtombs)(char * __restrict, const wchar_t ** __restrict, + size_t, size_t, mbstate_t * __restrict) = _none_wcsnrtombs; + diff --git a/lib/libc/locale/rpmatch.c b/lib/libc/locale/rpmatch.c new file mode 100644 index 0000000..370f23d --- /dev/null +++ b/lib/libc/locale/rpmatch.c @@ -0,0 +1,55 @@ +/*- + * Copyright (c) 2004-2005 Tim J. Robbins. + * 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 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 AUTHOR 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 +__FBSDID("$FreeBSD: src/lib/libc/locale/rpmatch.c,v 1.1 2005/01/09 03:55:13 tjr Exp $"); + +#include +#include +#include + +int +rpmatch(const char *response) +{ + regex_t yes, no; + int ret; + + if (regcomp(&yes, nl_langinfo(YESEXPR), REG_EXTENDED|REG_NOSUB) != 0) + return (-1); + if (regcomp(&no, nl_langinfo(NOEXPR), REG_EXTENDED|REG_NOSUB) != 0) { + regfree(&yes); + return (-1); + } + if (regexec(&yes, response, 0, NULL, 0) == 0) + ret = 1; + else if (regexec(&no, response, 0, NULL, 0) == 0) + ret = 0; + else + ret = -1; + regfree(&yes); + regfree(&no); + return (ret); +} diff --git a/lib/libc/locale/rune.c b/lib/libc/locale/rune.c new file mode 100644 index 0000000..bcb70f9 --- /dev/null +++ b/lib/libc/locale/rune.c @@ -0,0 +1,290 @@ +/*- + * Copyright (c) 1993 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * Paul Borman at Krystal Technologies. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)rune.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/locale/rune.c,v 1.14 2005/05/16 09:32:41 ru Exp $"); + +#include "namespace.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include "un-namespace.h" + +#include "runefile.h" + +_RuneLocale *_Read_RuneMagi(FILE *); + +_RuneLocale * +_Read_RuneMagi(FILE *fp) +{ + char *fdata, *data; + void *lastp; + _FileRuneLocale *frl; + _RuneLocale *rl; + _FileRuneEntry *frr; + _RuneEntry *rr; + struct stat sb; + int x, saverr; + void *variable; + _FileRuneEntry *runetype_ext_ranges; + _FileRuneEntry *maplower_ext_ranges; + _FileRuneEntry *mapupper_ext_ranges; + int runetype_ext_len = 0; + + if (_fstat(fileno(fp), &sb) < 0) + return (NULL); + + if ((size_t)sb.st_size < sizeof(_FileRuneLocale)) { + errno = EFTYPE; + return (NULL); + } + + if ((fdata = malloc(sb.st_size)) == NULL) + return (NULL); + + errno = 0; + rewind(fp); /* Someone might have read the magic number once already */ + if (errno) { + saverr = errno; + free(fdata); + errno = saverr; + return (NULL); + } + + if (fread(fdata, sb.st_size, 1, fp) != 1) { + saverr = errno; + free(fdata); + errno = saverr; + return (NULL); + } + + frl = (_FileRuneLocale *)fdata; + lastp = fdata + sb.st_size; + + variable = frl + 1; + + if (memcmp(frl->magic, _FILE_RUNE_MAGIC_1, sizeof(frl->magic))) { + free(fdata); + errno = EFTYPE; + return (NULL); + } + + frl->variable_len = ntohl(frl->variable_len); + frl->runetype_ext_nranges = ntohl(frl->runetype_ext_nranges); + frl->maplower_ext_nranges = ntohl(frl->maplower_ext_nranges); + frl->mapupper_ext_nranges = ntohl(frl->mapupper_ext_nranges); + + for (x = 0; x < _CACHED_RUNES; ++x) { + frl->runetype[x] = ntohl(frl->runetype[x]); + frl->maplower[x] = ntohl(frl->maplower[x]); + frl->mapupper[x] = ntohl(frl->mapupper[x]); + } + + runetype_ext_ranges = (_FileRuneEntry *)variable; + variable = runetype_ext_ranges + frl->runetype_ext_nranges; + if (variable > lastp) { + free(fdata); + errno = EFTYPE; + return (NULL); + } + + maplower_ext_ranges = (_FileRuneEntry *)variable; + variable = maplower_ext_ranges + frl->maplower_ext_nranges; + if (variable > lastp) { + free(fdata); + errno = EFTYPE; + return (NULL); + } + + mapupper_ext_ranges = (_FileRuneEntry *)variable; + variable = mapupper_ext_ranges + frl->mapupper_ext_nranges; + if (variable > lastp) { + free(fdata); + errno = EFTYPE; + return (NULL); + } + + frr = runetype_ext_ranges; + for (x = 0; x < frl->runetype_ext_nranges; ++x) { + uint32_t *types; + + frr[x].min = ntohl(frr[x].min); + frr[x].max = ntohl(frr[x].max); + frr[x].map = ntohl(frr[x].map); + if (frr[x].map == 0) { + int len = frr[x].max - frr[x].min + 1; + types = variable; + variable = types + len; + runetype_ext_len += len; + if (variable > lastp) { + free(fdata); + errno = EFTYPE; + return (NULL); + } + while (len-- > 0) + types[len] = ntohl(types[len]); + } + } + + frr = maplower_ext_ranges; + for (x = 0; x < frl->maplower_ext_nranges; ++x) { + frr[x].min = ntohl(frr[x].min); + frr[x].max = ntohl(frr[x].max); + frr[x].map = ntohl(frr[x].map); + } + + frr = mapupper_ext_ranges; + for (x = 0; x < frl->mapupper_ext_nranges; ++x) { + frr[x].min = ntohl(frr[x].min); + frr[x].max = ntohl(frr[x].max); + frr[x].map = ntohl(frr[x].map); + } + if ((char *)variable + frl->variable_len > (char *)lastp) { + free(fdata); + errno = EFTYPE; + return (NULL); + } + + /* + * Convert from disk format to host format. + */ + data = malloc(sizeof(_RuneLocale) + + (frl->runetype_ext_nranges + frl->maplower_ext_nranges + + frl->mapupper_ext_nranges) * sizeof(_RuneEntry) + + runetype_ext_len * sizeof(*rr->__types) + + frl->variable_len); + if (data == NULL) { + saverr = errno; + free(fdata); + errno = saverr; + return (NULL); + } + + rl = (_RuneLocale *)data; + rl->__variable = rl + 1; + + memcpy(rl->__magic, _RUNE_MAGIC_1, sizeof(rl->__magic)); + memcpy(rl->__encoding, frl->encoding, sizeof(rl->__encoding)); + rl->__invalid_rune = 0; + + rl->__variable_len = frl->variable_len; + rl->__runetype_ext.__nranges = frl->runetype_ext_nranges; + rl->__maplower_ext.__nranges = frl->maplower_ext_nranges; + rl->__mapupper_ext.__nranges = frl->mapupper_ext_nranges; + + for (x = 0; x < _CACHED_RUNES; ++x) { + rl->__runetype[x] = frl->runetype[x]; + rl->__maplower[x] = frl->maplower[x]; + rl->__mapupper[x] = frl->mapupper[x]; + } + + rl->__runetype_ext.__ranges = (_RuneEntry *)rl->__variable; + rl->__variable = rl->__runetype_ext.__ranges + + rl->__runetype_ext.__nranges; + + rl->__maplower_ext.__ranges = (_RuneEntry *)rl->__variable; + rl->__variable = rl->__maplower_ext.__ranges + + rl->__maplower_ext.__nranges; + + rl->__mapupper_ext.__ranges = (_RuneEntry *)rl->__variable; + rl->__variable = rl->__mapupper_ext.__ranges + + rl->__mapupper_ext.__nranges; + + variable = mapupper_ext_ranges + frl->mapupper_ext_nranges; + frr = runetype_ext_ranges; + rr = rl->__runetype_ext.__ranges; + for (x = 0; x < rl->__runetype_ext.__nranges; ++x) { + uint32_t *types; + + rr[x].__min = frr[x].min; + rr[x].__max = frr[x].max; + rr[x].__map = frr[x].map; + if (rr[x].__map == 0) { + int len = rr[x].__max - rr[x].__min + 1; + types = variable; + variable = types + len; + rr[x].__types = rl->__variable; + rl->__variable = rr[x].__types + len; + while (len-- > 0) + rr[x].__types[len] = types[len]; + } else + rr[x].__types = NULL; + } + + frr = maplower_ext_ranges; + rr = rl->__maplower_ext.__ranges; + for (x = 0; x < rl->__maplower_ext.__nranges; ++x) { + rr[x].__min = frr[x].min; + rr[x].__max = frr[x].max; + rr[x].__map = frr[x].map; + } + + frr = mapupper_ext_ranges; + rr = rl->__mapupper_ext.__ranges; + for (x = 0; x < rl->__mapupper_ext.__nranges; ++x) { + rr[x].__min = frr[x].min; + rr[x].__max = frr[x].max; + rr[x].__map = frr[x].map; + } + + memcpy(rl->__variable, variable, rl->__variable_len); + free(fdata); + + /* + * Go out and zero pointers that should be zero. + */ + if (!rl->__variable_len) + rl->__variable = NULL; + + if (!rl->__runetype_ext.__nranges) + rl->__runetype_ext.__ranges = NULL; + + if (!rl->__maplower_ext.__nranges) + rl->__maplower_ext.__ranges = NULL; + + if (!rl->__mapupper_ext.__nranges) + rl->__mapupper_ext.__ranges = NULL; + + return (rl); +} diff --git a/lib/libc/locale/runefile.h b/lib/libc/locale/runefile.h new file mode 100644 index 0000000..cacc66f --- /dev/null +++ b/lib/libc/locale/runefile.h @@ -0,0 +1,61 @@ +/*- + * Copyright (c) 2005 Ruslan Ermilov + * 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 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 AUTHOR 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. + * + * $FreeBSD: src/lib/libc/locale/runefile.h,v 1.1 2005/05/16 09:32:41 ru Exp $ + */ + +#ifndef _RUNEFILE_H_ +#define _RUNEFILE_H_ + +#include + +#ifndef _CACHED_RUNES +#define _CACHED_RUNES (1 << 8) +#endif + +typedef struct { + int32_t min; + int32_t max; + int32_t map; +} _FileRuneEntry; + +typedef struct { + char magic[8]; + char encoding[32]; + + uint32_t runetype[_CACHED_RUNES]; + int32_t maplower[_CACHED_RUNES]; + int32_t mapupper[_CACHED_RUNES]; + + int32_t runetype_ext_nranges; + int32_t maplower_ext_nranges; + int32_t mapupper_ext_nranges; + + int32_t variable_len; +} _FileRuneLocale; + +#define _FILE_RUNE_MAGIC_1 "RuneMag1" + +#endif /* !_RUNEFILE_H_ */ diff --git a/lib/libc/locale/runetype.c b/lib/libc/locale/runetype.c new file mode 100644 index 0000000..d62ed9b --- /dev/null +++ b/lib/libc/locale/runetype.c @@ -0,0 +1,69 @@ +/*- + * Copyright (c) 1993 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * Paul Borman at Krystal Technologies. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#include +__FBSDID("$FreeBSD: src/lib/libc/locale/runetype.c,v 1.12 2005/02/27 14:54:23 phantom Exp $"); + +#include +#include + +unsigned long +___runetype(__ct_rune_t c) +{ + size_t lim; + _RuneRange *rr = &_CurrentRuneLocale->__runetype_ext; + _RuneEntry *base, *re; + + if (c < 0 || c == EOF) + return(0L); + + /* Binary search -- see bsearch.c for explanation. */ + base = rr->__ranges; + for (lim = rr->__nranges; lim != 0; lim >>= 1) { + re = base + (lim >> 1); + if (re->__min <= c && c <= re->__max) { + if (re->__types) + return(re->__types[c - re->__min]); + else + return(re->__map); + } else if (c > re->__max) { + base = re + 1; + lim--; + } + } + + return(0L); +} diff --git a/lib/libc/locale/setlocale.c b/lib/libc/locale/setlocale.c new file mode 100644 index 0000000..e42f53a --- /dev/null +++ b/lib/libc/locale/setlocale.c @@ -0,0 +1,336 @@ +/* + * Copyright (c) 1996 - 2002 FreeBSD Project + * Copyright (c) 1991, 1993 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * Paul Borman at Krystal Technologies. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)setlocale.c 8.1 (Berkeley) 7/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/locale/setlocale.c,v 1.50 2004/01/31 19:15:32 ache Exp $"); + +#include +#include +#include +#include +#include +#include /* for _PATH_LOCALE */ +#include +#include +#include +#include "collate.h" +#include "lmonetary.h" /* for __monetary_load_locale() */ +#include "lnumeric.h" /* for __numeric_load_locale() */ +#include "lmessages.h" /* for __messages_load_locale() */ +#include "setlocale.h" +#include "ldpart.h" +#include "../stdtime/timelocal.h" /* for __time_load_locale() */ + +/* + * Category names for getenv() + */ +static char *categories[_LC_LAST] = { + "LC_ALL", + "LC_COLLATE", + "LC_CTYPE", + "LC_MONETARY", + "LC_NUMERIC", + "LC_TIME", + "LC_MESSAGES", +}; + +/* + * Current locales for each category + */ +static char current_categories[_LC_LAST][ENCODING_LEN + 1] = { + "C", + "C", + "C", + "C", + "C", + "C", + "C", +}; + +/* + * Path to locale storage directory + */ +char *_PathLocale; + +/* + * The locales we are going to try and load + */ +static char new_categories[_LC_LAST][ENCODING_LEN + 1]; +static char saved_categories[_LC_LAST][ENCODING_LEN + 1]; + +static char current_locale_string[_LC_LAST * (ENCODING_LEN + 1/*"/"*/ + 1)]; + +static char *currentlocale(void); +static char *loadlocale(int); +static const char *__get_locale_env(int); + +char * +setlocale(category, locale) + int category; + const char *locale; +{ + int i, j, len, saverr; + const char *env, *r; + + if (category < LC_ALL || category >= _LC_LAST) { + errno = EINVAL; + return (NULL); + } + + if (locale == NULL) + return (category != LC_ALL ? + current_categories[category] : currentlocale()); + + /* + * Default to the current locale for everything. + */ + for (i = 1; i < _LC_LAST; ++i) + (void)strcpy(new_categories[i], current_categories[i]); + + /* + * Now go fill up new_categories from the locale argument + */ + if (!*locale) { + if (category == LC_ALL) { + for (i = 1; i < _LC_LAST; ++i) { + env = __get_locale_env(i); + if (strlen(env) > ENCODING_LEN) { + errno = EINVAL; + return (NULL); + } + (void)strcpy(new_categories[i], env); + } + } else { + env = __get_locale_env(category); + if (strlen(env) > ENCODING_LEN) { + errno = EINVAL; + return (NULL); + } + (void)strcpy(new_categories[category], env); + } + } else if (category != LC_ALL) { + if (strlen(locale) > ENCODING_LEN) { + errno = EINVAL; + return (NULL); + } + (void)strcpy(new_categories[category], locale); + } else { + if ((r = strchr(locale, '/')) == NULL) { + if (strlen(locale) > ENCODING_LEN) { + errno = EINVAL; + return (NULL); + } + for (i = 1; i < _LC_LAST; ++i) + (void)strcpy(new_categories[i], locale); + } else { + for (i = 1; r[1] == '/'; ++r) + ; + if (!r[1]) { + errno = EINVAL; + return (NULL); /* Hmm, just slashes... */ + } + do { + if (i == _LC_LAST) + break; /* Too many slashes... */ + if ((len = r - locale) > ENCODING_LEN) { + errno = EINVAL; + return (NULL); + } + (void)strlcpy(new_categories[i], locale, + len + 1); + i++; + while (*r == '/') + r++; + locale = r; + while (*r && *r != '/') + r++; + } while (*locale); + while (i < _LC_LAST) { + (void)strcpy(new_categories[i], + new_categories[i-1]); + i++; + } + } + } + + if (category != LC_ALL) + return (loadlocale(category)); + + for (i = 1; i < _LC_LAST; ++i) { + (void)strcpy(saved_categories[i], current_categories[i]); + if (loadlocale(i) == NULL) { + saverr = errno; + for (j = 1; j < i; j++) { + (void)strcpy(new_categories[j], + saved_categories[j]); + if (loadlocale(j) == NULL) { + (void)strcpy(new_categories[j], "C"); + (void)loadlocale(j); + } + } + errno = saverr; + return (NULL); + } + } + return (currentlocale()); +} + +static char * +currentlocale() +{ + int i; + + (void)strcpy(current_locale_string, current_categories[1]); + + for (i = 2; i < _LC_LAST; ++i) + if (strcmp(current_categories[1], current_categories[i])) { + for (i = 2; i < _LC_LAST; ++i) { + (void)strcat(current_locale_string, "/"); + (void)strcat(current_locale_string, + current_categories[i]); + } + break; + } + return (current_locale_string); +} + +static char * +loadlocale(category) + int category; +{ + char *new = new_categories[category]; + char *old = current_categories[category]; + int (*func)(const char *); + int saved_errno; + + if ((new[0] == '.' && + (new[1] == '\0' || (new[1] == '.' && new[2] == '\0'))) || + strchr(new, '/') != NULL) { + errno = EINVAL; + return (NULL); + } + + saved_errno = errno; + errno = __detect_path_locale(); + if (errno != 0) + return (NULL); + errno = saved_errno; + + switch (category) { + case LC_CTYPE: + func = __wrap_setrunelocale; + break; + case LC_COLLATE: + func = __collate_load_tables; + break; + case LC_TIME: + func = __time_load_locale; + break; + case LC_NUMERIC: + func = __numeric_load_locale; + break; + case LC_MONETARY: + func = __monetary_load_locale; + break; + case LC_MESSAGES: + func = __messages_load_locale; + break; + default: + errno = EINVAL; + return (NULL); + } + + if (strcmp(new, old) == 0) + return (old); + + if (func(new) != _LDP_ERROR) { + (void)strcpy(old, new); + return (old); + } + + return (NULL); +} + +static const char * +__get_locale_env(category) + int category; +{ + const char *env; + + /* 1. check LC_ALL. */ + env = getenv(categories[0]); + + /* 2. check LC_* */ + if (env == NULL || !*env) + env = getenv(categories[category]); + + /* 3. check LANG */ + if (env == NULL || !*env) + env = getenv("LANG"); + + /* 4. if none is set, fall to "C" */ + if (env == NULL || !*env) + env = "C"; + + return (env); +} + +/* + * Detect locale storage location and store its value to _PathLocale variable + */ +int +__detect_path_locale(void) +{ + if (_PathLocale == NULL) { + char *p = getenv("PATH_LOCALE"); + + if (p != NULL && !issetugid()) { + if (strlen(p) + 1/*"/"*/ + ENCODING_LEN + + 1/*"/"*/ + CATEGORY_LEN >= PATH_MAX) + return (ENAMETOOLONG); + _PathLocale = strdup(p); + if (_PathLocale == NULL) + return (errno == 0 ? ENOMEM : errno); + } else + _PathLocale = _PATH_LOCALE; + } + return (0); +} + diff --git a/lib/libc/locale/setlocale.h b/lib/libc/locale/setlocale.h new file mode 100644 index 0000000..82462ee --- /dev/null +++ b/lib/libc/locale/setlocale.h @@ -0,0 +1,40 @@ +/*- + * Copyright (C) 1997 by Andrey A. Chernov, Moscow, Russia. + * 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 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. + * + * $FreeBSD: src/lib/libc/locale/setlocale.h,v 1.6 2003/07/06 02:03:37 ache Exp $ + */ + +#ifndef _SETLOCALE_H_ +#define _SETLOCALE_H_ + +#define ENCODING_LEN 31 +#define CATEGORY_LEN 11 + +extern char *_PathLocale; + +int __detect_path_locale(void); +int __wrap_setrunelocale(const char *); + +#endif /* !_SETLOCALE_H_ */ diff --git a/lib/libc/locale/setrunelocale.c b/lib/libc/locale/setrunelocale.c new file mode 100644 index 0000000..fd71947 --- /dev/null +++ b/lib/libc/locale/setrunelocale.c @@ -0,0 +1,177 @@ +/*- + * Copyright (c) 1993 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * Paul Borman at Krystal Technologies. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#include +__FBSDID("$FreeBSD: src/lib/libc/locale/setrunelocale.c,v 1.45 2005/02/27 15:11:09 phantom Exp $"); + +#include +#include +#include +#include +#include +#include +#include +#include +#include "ldpart.h" +#include "mblocal.h" +#include "setlocale.h" + +extern _RuneLocale *_Read_RuneMagi(FILE *); + +static int __setrunelocale(const char *); + +static int +__setrunelocale(const char *encoding) +{ + FILE *fp; + char name[PATH_MAX]; + _RuneLocale *rl; + int saverr, ret; + static char ctype_encoding[ENCODING_LEN + 1]; + static _RuneLocale *CachedRuneLocale; + static int Cached__mb_cur_max; + static size_t (*Cached__mbrtowc)(wchar_t * __restrict, + const char * __restrict, size_t, mbstate_t * __restrict); + static size_t (*Cached__wcrtomb)(char * __restrict, wchar_t, + mbstate_t * __restrict); + static int (*Cached__mbsinit)(const mbstate_t *); + static size_t (*Cached__mbsnrtowcs)(wchar_t * __restrict, + const char ** __restrict, size_t, size_t, mbstate_t * __restrict); + static size_t (*Cached__wcsnrtombs)(char * __restrict, + const wchar_t ** __restrict, size_t, size_t, + mbstate_t * __restrict); + + /* + * The "C" and "POSIX" locale are always here. + */ + if (strcmp(encoding, "C") == 0 || strcmp(encoding, "POSIX") == 0) { + _none_init(&_DefaultRuneLocale); + return (0); + } + + /* + * If the locale name is the same as our cache, use the cache. + */ + if (CachedRuneLocale != NULL && + strcmp(encoding, ctype_encoding) == 0) { + _CurrentRuneLocale = CachedRuneLocale; + __mb_cur_max = Cached__mb_cur_max; + __mbrtowc = Cached__mbrtowc; + __mbsinit = Cached__mbsinit; + __mbsnrtowcs = Cached__mbsnrtowcs; + __wcrtomb = Cached__wcrtomb; + __wcsnrtombs = Cached__wcsnrtombs; + return (0); + } + + /* + * Slurp the locale file into the cache. + */ + + /* Range checking not needed, encoding length already checked before */ + (void) strcpy(name, _PathLocale); + (void) strcat(name, "/"); + (void) strcat(name, encoding); + (void) strcat(name, "/LC_CTYPE"); + + if ((fp = fopen(name, "r")) == NULL) + return (errno == 0 ? ENOENT : errno); + + if ((rl = _Read_RuneMagi(fp)) == NULL) { + saverr = (errno == 0 ? EFTYPE : errno); + (void)fclose(fp); + return (saverr); + } + (void)fclose(fp); + + __mbrtowc = NULL; + __mbsinit = NULL; + __mbsnrtowcs = __mbsnrtowcs_std; + __wcrtomb = NULL; + __wcsnrtombs = __wcsnrtombs_std; + rl->__sputrune = NULL; + rl->__sgetrune = NULL; + if (strcmp(rl->__encoding, "NONE") == 0) + ret = _none_init(rl); + else if (strcmp(rl->__encoding, "UTF-8") == 0) + ret = _UTF8_init(rl); + else if (strcmp(rl->__encoding, "EUC") == 0) + ret = _EUC_init(rl); + else if (strcmp(rl->__encoding, "GB18030") == 0) + ret = _GB18030_init(rl); + else if (strcmp(rl->__encoding, "GB2312") == 0) + ret = _GB2312_init(rl); + else if (strcmp(rl->__encoding, "GBK") == 0) + ret = _GBK_init(rl); + else if (strcmp(rl->__encoding, "BIG5") == 0) + ret = _BIG5_init(rl); + else if (strcmp(rl->__encoding, "MSKanji") == 0) + ret = _MSKanji_init(rl); + else + ret = EFTYPE; + if (ret == 0) { + if (CachedRuneLocale != NULL) { + /* See euc.c */ + if (strcmp(CachedRuneLocale->__encoding, "EUC") == 0) + free(CachedRuneLocale->__variable); + free(CachedRuneLocale); + } + CachedRuneLocale = _CurrentRuneLocale; + Cached__mb_cur_max = __mb_cur_max; + Cached__mbrtowc = __mbrtowc; + Cached__mbsinit = __mbsinit; + Cached__mbsnrtowcs = __mbsnrtowcs; + Cached__wcrtomb = __wcrtomb; + Cached__wcsnrtombs = __wcsnrtombs; + (void)strcpy(ctype_encoding, encoding); + } else + free(rl); + + return (ret); +} + +int +__wrap_setrunelocale(const char *locale) +{ + int ret = __setrunelocale(locale); + + if (ret != 0) { + errno = ret; + return (_LDP_ERROR); + } + return (_LDP_LOADED); +} + diff --git a/lib/libc/locale/table.c b/lib/libc/locale/table.c new file mode 100644 index 0000000..b393d30 --- /dev/null +++ b/lib/libc/locale/table.c @@ -0,0 +1,253 @@ +/*- + * Copyright (c) 1993 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * Paul Borman at Krystal Technologies. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)table.c 8.1 (Berkeley) 6/27/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/locale/table.c,v 1.27 2005/02/27 15:11:09 phantom Exp $"); + +#include +#include +#include +#include "mblocal.h" + +_RuneLocale _DefaultRuneLocale = { + _RUNE_MAGIC_1, + "NONE", + NULL, + NULL, + 0xFFFD, + + { /*00*/ _CTYPE_C, + _CTYPE_C, + _CTYPE_C, + _CTYPE_C, + _CTYPE_C, + _CTYPE_C, + _CTYPE_C, + _CTYPE_C, + /*08*/ _CTYPE_C, + _CTYPE_C|_CTYPE_S|_CTYPE_B, + _CTYPE_C|_CTYPE_S, + _CTYPE_C|_CTYPE_S, + _CTYPE_C|_CTYPE_S, + _CTYPE_C|_CTYPE_S, + _CTYPE_C, + _CTYPE_C, + /*10*/ _CTYPE_C, + _CTYPE_C, + _CTYPE_C, + _CTYPE_C, + _CTYPE_C, + _CTYPE_C, + _CTYPE_C, + _CTYPE_C, + /*18*/ _CTYPE_C, + _CTYPE_C, + _CTYPE_C, + _CTYPE_C, + _CTYPE_C, + _CTYPE_C, + _CTYPE_C, + _CTYPE_C, + /*20*/ _CTYPE_S|_CTYPE_B|_CTYPE_R, + _CTYPE_P|_CTYPE_R|_CTYPE_G, + _CTYPE_P|_CTYPE_R|_CTYPE_G, + _CTYPE_P|_CTYPE_R|_CTYPE_G, + _CTYPE_P|_CTYPE_R|_CTYPE_G, + _CTYPE_P|_CTYPE_R|_CTYPE_G, + _CTYPE_P|_CTYPE_R|_CTYPE_G, + _CTYPE_P|_CTYPE_R|_CTYPE_G, + /*28*/ _CTYPE_P|_CTYPE_R|_CTYPE_G, + _CTYPE_P|_CTYPE_R|_CTYPE_G, + _CTYPE_P|_CTYPE_R|_CTYPE_G, + _CTYPE_P|_CTYPE_R|_CTYPE_G, + _CTYPE_P|_CTYPE_R|_CTYPE_G, + _CTYPE_P|_CTYPE_R|_CTYPE_G, + _CTYPE_P|_CTYPE_R|_CTYPE_G, + _CTYPE_P|_CTYPE_R|_CTYPE_G, + /*30*/ _CTYPE_D|_CTYPE_R|_CTYPE_G|_CTYPE_X|0, + _CTYPE_D|_CTYPE_R|_CTYPE_G|_CTYPE_X|1, + _CTYPE_D|_CTYPE_R|_CTYPE_G|_CTYPE_X|2, + _CTYPE_D|_CTYPE_R|_CTYPE_G|_CTYPE_X|3, + _CTYPE_D|_CTYPE_R|_CTYPE_G|_CTYPE_X|4, + _CTYPE_D|_CTYPE_R|_CTYPE_G|_CTYPE_X|5, + _CTYPE_D|_CTYPE_R|_CTYPE_G|_CTYPE_X|6, + _CTYPE_D|_CTYPE_R|_CTYPE_G|_CTYPE_X|7, + /*38*/ _CTYPE_D|_CTYPE_R|_CTYPE_G|_CTYPE_X|8, + _CTYPE_D|_CTYPE_R|_CTYPE_G|_CTYPE_X|9, + _CTYPE_P|_CTYPE_R|_CTYPE_G, + _CTYPE_P|_CTYPE_R|_CTYPE_G, + _CTYPE_P|_CTYPE_R|_CTYPE_G, + _CTYPE_P|_CTYPE_R|_CTYPE_G, + _CTYPE_P|_CTYPE_R|_CTYPE_G, + _CTYPE_P|_CTYPE_R|_CTYPE_G, + /*40*/ _CTYPE_P|_CTYPE_R|_CTYPE_G, + _CTYPE_U|_CTYPE_X|_CTYPE_R|_CTYPE_G|_CTYPE_A|10, + _CTYPE_U|_CTYPE_X|_CTYPE_R|_CTYPE_G|_CTYPE_A|11, + _CTYPE_U|_CTYPE_X|_CTYPE_R|_CTYPE_G|_CTYPE_A|12, + _CTYPE_U|_CTYPE_X|_CTYPE_R|_CTYPE_G|_CTYPE_A|13, + _CTYPE_U|_CTYPE_X|_CTYPE_R|_CTYPE_G|_CTYPE_A|14, + _CTYPE_U|_CTYPE_X|_CTYPE_R|_CTYPE_G|_CTYPE_A|15, + _CTYPE_U|_CTYPE_R|_CTYPE_G|_CTYPE_A, + /*48*/ _CTYPE_U|_CTYPE_R|_CTYPE_G|_CTYPE_A, + _CTYPE_U|_CTYPE_R|_CTYPE_G|_CTYPE_A, + _CTYPE_U|_CTYPE_R|_CTYPE_G|_CTYPE_A, + _CTYPE_U|_CTYPE_R|_CTYPE_G|_CTYPE_A, + _CTYPE_U|_CTYPE_R|_CTYPE_G|_CTYPE_A, + _CTYPE_U|_CTYPE_R|_CTYPE_G|_CTYPE_A, + _CTYPE_U|_CTYPE_R|_CTYPE_G|_CTYPE_A, + _CTYPE_U|_CTYPE_R|_CTYPE_G|_CTYPE_A, + /*50*/ _CTYPE_U|_CTYPE_R|_CTYPE_G|_CTYPE_A, + _CTYPE_U|_CTYPE_R|_CTYPE_G|_CTYPE_A, + _CTYPE_U|_CTYPE_R|_CTYPE_G|_CTYPE_A, + _CTYPE_U|_CTYPE_R|_CTYPE_G|_CTYPE_A, + _CTYPE_U|_CTYPE_R|_CTYPE_G|_CTYPE_A, + _CTYPE_U|_CTYPE_R|_CTYPE_G|_CTYPE_A, + _CTYPE_U|_CTYPE_R|_CTYPE_G|_CTYPE_A, + _CTYPE_U|_CTYPE_R|_CTYPE_G|_CTYPE_A, + /*58*/ _CTYPE_U|_CTYPE_R|_CTYPE_G|_CTYPE_A, + _CTYPE_U|_CTYPE_R|_CTYPE_G|_CTYPE_A, + _CTYPE_U|_CTYPE_R|_CTYPE_G|_CTYPE_A, + _CTYPE_P|_CTYPE_R|_CTYPE_G, + _CTYPE_P|_CTYPE_R|_CTYPE_G, + _CTYPE_P|_CTYPE_R|_CTYPE_G, + _CTYPE_P|_CTYPE_R|_CTYPE_G, + _CTYPE_P|_CTYPE_R|_CTYPE_G, + /*60*/ _CTYPE_P|_CTYPE_R|_CTYPE_G, + _CTYPE_L|_CTYPE_X|_CTYPE_R|_CTYPE_G|_CTYPE_A|10, + _CTYPE_L|_CTYPE_X|_CTYPE_R|_CTYPE_G|_CTYPE_A|11, + _CTYPE_L|_CTYPE_X|_CTYPE_R|_CTYPE_G|_CTYPE_A|12, + _CTYPE_L|_CTYPE_X|_CTYPE_R|_CTYPE_G|_CTYPE_A|13, + _CTYPE_L|_CTYPE_X|_CTYPE_R|_CTYPE_G|_CTYPE_A|14, + _CTYPE_L|_CTYPE_X|_CTYPE_R|_CTYPE_G|_CTYPE_A|15, + _CTYPE_L|_CTYPE_R|_CTYPE_G|_CTYPE_A, + /*68*/ _CTYPE_L|_CTYPE_R|_CTYPE_G|_CTYPE_A, + _CTYPE_L|_CTYPE_R|_CTYPE_G|_CTYPE_A, + _CTYPE_L|_CTYPE_R|_CTYPE_G|_CTYPE_A, + _CTYPE_L|_CTYPE_R|_CTYPE_G|_CTYPE_A, + _CTYPE_L|_CTYPE_R|_CTYPE_G|_CTYPE_A, + _CTYPE_L|_CTYPE_R|_CTYPE_G|_CTYPE_A, + _CTYPE_L|_CTYPE_R|_CTYPE_G|_CTYPE_A, + _CTYPE_L|_CTYPE_R|_CTYPE_G|_CTYPE_A, + /*70*/ _CTYPE_L|_CTYPE_R|_CTYPE_G|_CTYPE_A, + _CTYPE_L|_CTYPE_R|_CTYPE_G|_CTYPE_A, + _CTYPE_L|_CTYPE_R|_CTYPE_G|_CTYPE_A, + _CTYPE_L|_CTYPE_R|_CTYPE_G|_CTYPE_A, + _CTYPE_L|_CTYPE_R|_CTYPE_G|_CTYPE_A, + _CTYPE_L|_CTYPE_R|_CTYPE_G|_CTYPE_A, + _CTYPE_L|_CTYPE_R|_CTYPE_G|_CTYPE_A, + _CTYPE_L|_CTYPE_R|_CTYPE_G|_CTYPE_A, + /*78*/ _CTYPE_L|_CTYPE_R|_CTYPE_G|_CTYPE_A, + _CTYPE_L|_CTYPE_R|_CTYPE_G|_CTYPE_A, + _CTYPE_L|_CTYPE_R|_CTYPE_G|_CTYPE_A, + _CTYPE_P|_CTYPE_R|_CTYPE_G, + _CTYPE_P|_CTYPE_R|_CTYPE_G, + _CTYPE_P|_CTYPE_R|_CTYPE_G, + _CTYPE_P|_CTYPE_R|_CTYPE_G, + _CTYPE_C, + }, + { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, + 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, + 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, + 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, + 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, + 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, + 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, + 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, + 0x40, 'a', 'b', 'c', 'd', 'e', 'f', 'g', + 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', + 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', + 'x', 'y', 'z', 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, + 0x60, 'a', 'b', 'c', 'd', 'e', 'f', 'g', + 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', + 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', + 'x', 'y', 'z', 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, + 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, + 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, + 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, + 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, + 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, + 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, + 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, + 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, + 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, + 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, + 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, + 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, + 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, + 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, + 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, + 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, + }, + { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, + 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, + 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, + 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, + 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, + 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, + 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, + 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, + 0x40, 'A', 'B', 'C', 'D', 'E', 'F', 'G', + 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', + 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', + 'X', 'Y', 'Z', 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, + 0x60, 'A', 'B', 'C', 'D', 'E', 'F', 'G', + 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', + 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', + 'X', 'Y', 'Z', 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, + 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, + 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, + 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, + 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, + 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, + 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, + 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, + 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, + 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, + 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, + 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, + 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, + 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, + 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, + 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, + 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, + }, +}; + +_RuneLocale *_CurrentRuneLocale = &_DefaultRuneLocale; + diff --git a/lib/libc/locale/tolower.c b/lib/libc/locale/tolower.c new file mode 100644 index 0000000..24694e7 --- /dev/null +++ b/lib/libc/locale/tolower.c @@ -0,0 +1,67 @@ +/*- + * Copyright (c) 1993 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * Paul Borman at Krystal Technologies. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#include +__FBSDID("$FreeBSD: src/lib/libc/locale/tolower.c,v 1.11 2004/07/29 06:16:19 tjr Exp $"); + +#include +#include + +__ct_rune_t +___tolower(c) + __ct_rune_t c; +{ + size_t lim; + _RuneRange *rr = &_CurrentRuneLocale->__maplower_ext; + _RuneEntry *base, *re; + + if (c < 0 || c == EOF) + return(c); + + /* Binary search -- see bsearch.c for explanation. */ + base = rr->__ranges; + for (lim = rr->__nranges; lim != 0; lim >>= 1) { + re = base + (lim >> 1); + if (re->__min <= c && c <= re->__max) + return (re->__map + c - re->__min); + else if (c > re->__max) { + base = re + 1; + lim--; + } + } + + return(c); +} diff --git a/lib/libc/locale/toupper.c b/lib/libc/locale/toupper.c new file mode 100644 index 0000000..bb7f36a --- /dev/null +++ b/lib/libc/locale/toupper.c @@ -0,0 +1,67 @@ +/*- + * Copyright (c) 1993 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * Paul Borman at Krystal Technologies. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#include +__FBSDID("$FreeBSD: src/lib/libc/locale/toupper.c,v 1.11 2004/07/29 06:16:19 tjr Exp $"); + +#include +#include + +__ct_rune_t +___toupper(c) + __ct_rune_t c; +{ + size_t lim; + _RuneRange *rr = &_CurrentRuneLocale->__mapupper_ext; + _RuneEntry *base, *re; + + if (c < 0 || c == EOF) + return(c); + + /* Binary search -- see bsearch.c for explanation. */ + base = rr->__ranges; + for (lim = rr->__nranges; lim != 0; lim >>= 1) { + re = base + (lim >> 1); + if (re->__min <= c && c <= re->__max) + return (re->__map + c - re->__min); + else if (c > re->__max) { + base = re + 1; + lim--; + } + } + + return(c); +} diff --git a/lib/libc/locale/utf8.c b/lib/libc/locale/utf8.c new file mode 100644 index 0000000..08b8c2d --- /dev/null +++ b/lib/libc/locale/utf8.c @@ -0,0 +1,421 @@ +/*- + * Copyright (c) 2002-2004 Tim J. Robbins + * 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 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 AUTHOR 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 +__FBSDID("$FreeBSD: src/lib/libc/locale/utf8.c,v 1.13.2.1 2006/05/17 13:26:01 trhodes Exp $"); + +#include +#include +#include +#include +#include +#include +#include "mblocal.h" + +static size_t _UTF8_mbrtowc(wchar_t * __restrict, const char * __restrict, + size_t, mbstate_t * __restrict); +static int _UTF8_mbsinit(const mbstate_t *); +static size_t _UTF8_mbsnrtowcs(wchar_t * __restrict, + const char ** __restrict, size_t, size_t, + mbstate_t * __restrict); +static size_t _UTF8_wcrtomb(char * __restrict, wchar_t, + mbstate_t * __restrict); +static size_t _UTF8_wcsnrtombs(char * __restrict, const wchar_t ** __restrict, + size_t, size_t, mbstate_t * __restrict); + +typedef struct { + wchar_t ch; + int want; + wchar_t lbound; +} _UTF8State; + +int +_UTF8_init(_RuneLocale *rl) +{ + + __mbrtowc = _UTF8_mbrtowc; + __wcrtomb = _UTF8_wcrtomb; + __mbsinit = _UTF8_mbsinit; + __mbsnrtowcs = _UTF8_mbsnrtowcs; + __wcsnrtombs = _UTF8_wcsnrtombs; + _CurrentRuneLocale = rl; + __mb_cur_max = 6; + + return (0); +} + +static int +_UTF8_mbsinit(const mbstate_t *ps) +{ + + return (ps == NULL || ((const _UTF8State *)ps)->want == 0); +} + +static size_t +_UTF8_mbrtowc(wchar_t * __restrict pwc, const char * __restrict s, size_t n, + mbstate_t * __restrict ps) +{ + _UTF8State *us; + int ch, i, mask, want; + wchar_t lbound, wch; + + us = (_UTF8State *)ps; + + if (us->want < 0 || us->want > 6) { + errno = EINVAL; + return ((size_t)-1); + } + + if (s == NULL) { + s = ""; + n = 1; + pwc = NULL; + } + + if (n == 0) + /* Incomplete multibyte sequence */ + return ((size_t)-2); + + if (us->want == 0 && ((ch = (unsigned char)*s) & ~0x7f) == 0) { + /* Fast path for plain ASCII characters. */ + if (pwc != NULL) + *pwc = ch; + return (ch != '\0' ? 1 : 0); + } + + if (us->want == 0) { + /* + * Determine the number of octets that make up this character + * from the first octet, and a mask that extracts the + * interesting bits of the first octet. We already know + * the character is at least two bytes long. + * + * We also specify a lower bound for the character code to + * detect redundant, non-"shortest form" encodings. For + * example, the sequence C0 80 is _not_ a legal representation + * of the null character. This enforces a 1-to-1 mapping + * between character codes and their multibyte representations. + */ + ch = (unsigned char)*s; + if ((ch & 0x80) == 0) { + mask = 0x7f; + want = 1; + lbound = 0; + } else if ((ch & 0xe0) == 0xc0) { + mask = 0x1f; + want = 2; + lbound = 0x80; + } else if ((ch & 0xf0) == 0xe0) { + mask = 0x0f; + want = 3; + lbound = 0x800; + } else if ((ch & 0xf8) == 0xf0) { + mask = 0x07; + want = 4; + lbound = 0x10000; + } else if ((ch & 0xfc) == 0xf8) { + mask = 0x03; + want = 5; + lbound = 0x200000; + } else if ((ch & 0xfe) == 0xfc) { + mask = 0x01; + want = 6; + lbound = 0x4000000; + } else { + /* + * Malformed input; input is not UTF-8. + */ + errno = EILSEQ; + return ((size_t)-1); + } + } else { + want = us->want; + lbound = us->lbound; + } + + /* + * Decode the octet sequence representing the character in chunks + * of 6 bits, most significant first. + */ + if (us->want == 0) + wch = (unsigned char)*s++ & mask; + else + wch = us->ch; + for (i = (us->want == 0) ? 1 : 0; i < MIN(want, n); i++) { + if ((*s & 0xc0) != 0x80) { + /* + * Malformed input; bad characters in the middle + * of a character. + */ + errno = EILSEQ; + return ((size_t)-1); + } + wch <<= 6; + wch |= *s++ & 0x3f; + } + if (i < want) { + /* Incomplete multibyte sequence. */ + us->want = want - i; + us->lbound = lbound; + us->ch = wch; + return ((size_t)-2); + } + if (wch < lbound) { + /* + * Malformed input; redundant encoding. + */ + errno = EILSEQ; + return ((size_t)-1); + } + if (pwc != NULL) + *pwc = wch; + us->want = 0; + return (wch == L'\0' ? 0 : want); +} + +static size_t +_UTF8_mbsnrtowcs(wchar_t * __restrict dst, const char ** __restrict src, + size_t nms, size_t len, mbstate_t * __restrict ps) +{ + _UTF8State *us; + const char *s; + size_t nchr; + wchar_t wc; + size_t nb; + + us = (_UTF8State *)ps; + + s = *src; + nchr = 0; + + if (dst == NULL) { + /* + * The fast path in the loop below is not safe if an ASCII + * character appears as anything but the first byte of a + * multibyte sequence. Check now to avoid doing it in the loop. + */ + if (nms > 0 && us->want > 0 && (signed char)*s > 0) { + errno = EILSEQ; + return ((size_t)-1); + } + for (;;) { + if (nms > 0 && (signed char)*s > 0) + /* + * Fast path for plain ASCII characters + * excluding NUL. + */ + nb = 1; + else if ((nb = _UTF8_mbrtowc(&wc, s, nms, ps)) == + (size_t)-1) + /* Invalid sequence - mbrtowc() sets errno. */ + return ((size_t)-1); + else if (nb == 0 || nb == (size_t)-2) + return (nchr); + s += nb; + nms -= nb; + nchr++; + } + /*NOTREACHED*/ + } + + /* + * The fast path in the loop below is not safe if an ASCII + * character appears as anything but the first byte of a + * multibyte sequence. Check now to avoid doing it in the loop. + */ + if (nms > 0 && len > 0 && us->want > 0 && (signed char)*s > 0) { + errno = EILSEQ; + return ((size_t)-1); + } + while (len-- > 0) { + if (nms > 0 && (signed char)*s > 0) { + /* + * Fast path for plain ASCII characters + * excluding NUL. + */ + *dst = (wchar_t)*s; + nb = 1; + } else if ((nb = _UTF8_mbrtowc(dst, s, nms, ps)) == + (size_t)-1) { + *src = s; + return ((size_t)-1); + } else if (nb == (size_t)-2) { + *src = s + nms; + return (nchr); + } else if (nb == 0) { + *src = NULL; + return (nchr); + } + s += nb; + nms -= nb; + nchr++; + dst++; + } + *src = s; + return (nchr); +} + +static size_t +_UTF8_wcrtomb(char * __restrict s, wchar_t wc, mbstate_t * __restrict ps) +{ + _UTF8State *us; + unsigned char lead; + int i, len; + + us = (_UTF8State *)ps; + + if (us->want != 0) { + errno = EINVAL; + return ((size_t)-1); + } + + if (s == NULL) + /* Reset to initial shift state (no-op) */ + return (1); + + if ((wc & ~0x7f) == 0) { + /* Fast path for plain ASCII characters. */ + *s = (char)wc; + return (1); + } + + /* + * Determine the number of octets needed to represent this character. + * We always output the shortest sequence possible. Also specify the + * first few bits of the first octet, which contains the information + * about the sequence length. + */ + if ((wc & ~0x7f) == 0) { + lead = 0; + len = 1; + } else if ((wc & ~0x7ff) == 0) { + lead = 0xc0; + len = 2; + } else if ((wc & ~0xffff) == 0) { + lead = 0xe0; + len = 3; + } else if ((wc & ~0x1fffff) == 0) { + lead = 0xf0; + len = 4; + } else if ((wc & ~0x3ffffff) == 0) { + lead = 0xf8; + len = 5; + } else if ((wc & ~0x7fffffff) == 0) { + lead = 0xfc; + len = 6; + } else { + errno = EILSEQ; + return ((size_t)-1); + } + + /* + * Output the octets representing the character in chunks + * of 6 bits, least significant last. The first octet is + * a special case because it contains the sequence length + * information. + */ + for (i = len - 1; i > 0; i--) { + s[i] = (wc & 0x3f) | 0x80; + wc >>= 6; + } + *s = (wc & 0xff) | lead; + + return (len); +} + +static size_t +_UTF8_wcsnrtombs(char * __restrict dst, const wchar_t ** __restrict src, + size_t nwc, size_t len, mbstate_t * __restrict ps) +{ + _UTF8State *us; + char buf[MB_LEN_MAX]; + const wchar_t *s; + size_t nbytes; + size_t nb; + + us = (_UTF8State *)ps; + + if (us->want != 0) { + errno = EINVAL; + return ((size_t)-1); + } + + s = *src; + nbytes = 0; + + if (dst == NULL) { + while (nwc-- > 0) { + if (0 <= *s && *s < 0x80) + /* Fast path for plain ASCII characters. */ + nb = 1; + else if ((nb = _UTF8_wcrtomb(buf, *s, ps)) == + (size_t)-1) + /* Invalid character - wcrtomb() sets errno. */ + return ((size_t)-1); + if (*s == L'\0') + return (nbytes + nb - 1); + s++; + nbytes += nb; + } + return (nbytes); + } + + while (len > 0 && nwc-- > 0) { + if (0 <= *s && *s < 0x80) { + /* Fast path for plain ASCII characters. */ + nb = 1; + *dst = *s; + } else if (len > (size_t)MB_CUR_MAX) { + /* Enough space to translate in-place. */ + if ((nb = _UTF8_wcrtomb(dst, *s, ps)) == (size_t)-1) { + *src = s; + return ((size_t)-1); + } + } else { + /* + * May not be enough space; use temp. buffer. + */ + if ((nb = _UTF8_wcrtomb(buf, *s, ps)) == (size_t)-1) { + *src = s; + return ((size_t)-1); + } + if (nb > (int)len) + /* MB sequence for character won't fit. */ + break; + memcpy(dst, buf, nb); + } + if (*s == L'\0') { + *src = NULL; + return (nbytes + nb - 1); + } + s++; + dst += nb; + len -= nb; + nbytes += nb; + } + *src = s; + return (nbytes); +} diff --git a/lib/libc/locale/wcrtomb.c b/lib/libc/locale/wcrtomb.c new file mode 100644 index 0000000..4d7b115 --- /dev/null +++ b/lib/libc/locale/wcrtomb.c @@ -0,0 +1,41 @@ +/*- + * Copyright (c) 2002-2004 Tim J. Robbins. + * 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 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 AUTHOR 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 +__FBSDID("$FreeBSD: src/lib/libc/locale/wcrtomb.c,v 1.8 2004/05/12 14:09:04 tjr Exp $"); + +#include +#include "mblocal.h" + +size_t +wcrtomb(char * __restrict s, wchar_t wc, mbstate_t * __restrict ps) +{ + static mbstate_t mbs; + + if (ps == NULL) + ps = &mbs; + return (__wcrtomb(s, wc, ps)); +} diff --git a/lib/libc/locale/wcsftime.c b/lib/libc/locale/wcsftime.c new file mode 100644 index 0000000..2598043 --- /dev/null +++ b/lib/libc/locale/wcsftime.c @@ -0,0 +1,105 @@ +/*- + * Copyright (c) 2002 Tim J. Robbins + * 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 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 AUTHOR 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 +__FBSDID("$FreeBSD: src/lib/libc/locale/wcsftime.c,v 1.4 2004/04/07 09:47:56 tjr Exp $"); + +#include +#include +#include +#include +#include + +/* + * Convert date and time to a wide-character string. + * + * This is the wide-character counterpart of strftime(). So that we do not + * have to duplicate the code of strftime(), we convert the format string to + * multibyte, call strftime(), then convert the result back into wide + * characters. + * + * This technique loses in the presence of stateful multibyte encoding if any + * of the conversions in the format string change conversion state. When + * stateful encoding is implemented, we will need to reset the state between + * format specifications in the format string. + */ +size_t +wcsftime(wchar_t * __restrict wcs, size_t maxsize, + const wchar_t * __restrict format, const struct tm * __restrict timeptr) +{ + static const mbstate_t initial; + mbstate_t mbs; + char *dst, *dstp, *sformat; + size_t n, sflen; + int sverrno; + + sformat = dst = NULL; + + /* + * Convert the supplied format string to a multibyte representation + * for strftime(), which only handles single-byte characters. + */ + mbs = initial; + sflen = wcsrtombs(NULL, &format, 0, &mbs); + if (sflen == (size_t)-1) + goto error; + if ((sformat = malloc(sflen + 1)) == NULL) + goto error; + mbs = initial; + wcsrtombs(sformat, &format, sflen + 1, &mbs); + + /* + * Allocate memory for longest multibyte sequence that will fit + * into the caller's buffer and call strftime() to fill it. + * Then, copy and convert the result back into wide characters in + * the caller's buffer. + */ + if (SIZE_T_MAX / MB_CUR_MAX <= maxsize) { + /* maxsize is prepostorously large - avoid int. overflow. */ + errno = EINVAL; + goto error; + } + if ((dst = malloc(maxsize * MB_CUR_MAX)) == NULL) + goto error; + if (strftime(dst, maxsize, sformat, timeptr) == 0) + goto error; + dstp = dst; + mbs = initial; + n = mbsrtowcs(wcs, (const char **)&dstp, maxsize, &mbs); + if (n == (size_t)-2 || n == (size_t)-1 || dstp != NULL) + goto error; + + free(sformat); + free(dst); + return (n); + +error: + sverrno = errno; + free(sformat); + free(dst); + errno = sverrno; + return (0); +} diff --git a/lib/libc/locale/wcsnrtombs.c b/lib/libc/locale/wcsnrtombs.c new file mode 100644 index 0000000..89cd9b7 --- /dev/null +++ b/lib/libc/locale/wcsnrtombs.c @@ -0,0 +1,111 @@ +/*- + * Copyright (c) 2002-2004 Tim J. Robbins. + * 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 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 AUTHOR 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 +__FBSDID("$FreeBSD: src/lib/libc/locale/wcsnrtombs.c,v 1.3 2005/02/12 08:45:12 stefanf Exp $"); + +#include +#include +#include +#include +#include "mblocal.h" + +size_t +wcsnrtombs(char * __restrict dst, const wchar_t ** __restrict src, size_t nwc, + size_t len, mbstate_t * __restrict ps) +{ + static mbstate_t mbs; + + if (ps == NULL) + ps = &mbs; + return (__wcsnrtombs(dst, src, nwc, len, ps)); +} + +size_t +__wcsnrtombs_std(char * __restrict dst, const wchar_t ** __restrict src, + size_t nwc, size_t len, mbstate_t * __restrict ps) +{ + mbstate_t mbsbak; + char buf[MB_LEN_MAX]; + const wchar_t *s; + size_t nbytes; + size_t nb; + + s = *src; + nbytes = 0; + + if (dst == NULL) { + while (nwc-- > 0) { + if ((nb = __wcrtomb(buf, *s, ps)) == (size_t)-1) + /* Invalid character - wcrtomb() sets errno. */ + return ((size_t)-1); + else if (*s == L'\0') + return (nbytes + nb - 1); + s++; + nbytes += nb; + } + return (nbytes); + } + + while (len > 0 && nwc-- > 0) { + if (len > (size_t)MB_CUR_MAX) { + /* Enough space to translate in-place. */ + if ((nb = __wcrtomb(dst, *s, ps)) == (size_t)-1) { + *src = s; + return ((size_t)-1); + } + } else { + /* + * May not be enough space; use temp. buffer. + * + * We need to save a copy of the conversion state + * here so we can restore it if the multibyte + * character is too long for the buffer. + */ + mbsbak = *ps; + if ((nb = __wcrtomb(buf, *s, ps)) == (size_t)-1) { + *src = s; + return ((size_t)-1); + } + if (nb > (int)len) { + /* MB sequence for character won't fit. */ + *ps = mbsbak; + break; + } + memcpy(dst, buf, nb); + } + if (*s == L'\0') { + *src = NULL; + return (nbytes + nb - 1); + } + s++; + dst += nb; + len -= nb; + nbytes += nb; + } + *src = s; + return (nbytes); +} diff --git a/lib/libc/locale/wcsrtombs.c b/lib/libc/locale/wcsrtombs.c new file mode 100644 index 0000000..61e5432 --- /dev/null +++ b/lib/libc/locale/wcsrtombs.c @@ -0,0 +1,45 @@ +/*- + * Copyright (c) 2002-2004 Tim J. Robbins. + * 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 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 AUTHOR 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 +__FBSDID("$FreeBSD: src/lib/libc/locale/wcsrtombs.c,v 1.6 2004/07/21 10:54:57 tjr Exp $"); + +#include +#include +#include +#include +#include "mblocal.h" + +size_t +wcsrtombs(char * __restrict dst, const wchar_t ** __restrict src, size_t len, + mbstate_t * __restrict ps) +{ + static mbstate_t mbs; + + if (ps == NULL) + ps = &mbs; + return (__wcsnrtombs(dst, src, SIZE_T_MAX, len, ps)); +} diff --git a/lib/libc/locale/wcstod.c b/lib/libc/locale/wcstod.c new file mode 100644 index 0000000..da90f16 --- /dev/null +++ b/lib/libc/locale/wcstod.c @@ -0,0 +1,94 @@ +/*- + * Copyright (c) 2002 Tim J. Robbins + * 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 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 AUTHOR 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 +__FBSDID("$FreeBSD: src/lib/libc/locale/wcstod.c,v 1.4 2004/04/07 09:47:56 tjr Exp $"); + +#include +#include +#include + +/* + * Convert a string to a double-precision number. + * + * This is the wide-character counterpart of strtod(). So that we do not + * have to duplicate the code of strtod() here, we convert the supplied + * wide character string to multibyte and call strtod() on the result. + * This assumes that the multibyte encoding is compatible with ASCII + * for at least the digits, radix character and letters. + */ +double +wcstod(const wchar_t * __restrict nptr, wchar_t ** __restrict endptr) +{ + static const mbstate_t initial; + mbstate_t mbs; + double val; + char *buf, *end; + const wchar_t *wcp; + size_t len; + + while (iswspace(*nptr)) + nptr++; + + /* + * Convert the supplied numeric wide char. string to multibyte. + * + * We could attempt to find the end of the numeric portion of the + * wide char. string to avoid converting unneeded characters but + * choose not to bother; optimising the uncommon case where + * the input string contains a lot of text after the number + * duplicates a lot of strtod()'s functionality and slows down the + * most common cases. + */ + wcp = nptr; + mbs = initial; + if ((len = wcsrtombs(NULL, &wcp, 0, &mbs)) == (size_t)-1) { + if (endptr != NULL) + *endptr = (wchar_t *)nptr; + return (0.0); + } + if ((buf = malloc(len + 1)) == NULL) + return (0.0); + mbs = initial; + wcsrtombs(buf, &wcp, len + 1, &mbs); + + /* Let strtod() do most of the work for us. */ + val = strtod(buf, &end); + + /* + * We only know where the number ended in the _multibyte_ + * representation of the string. If the caller wants to know + * where it ended, count multibyte characters to find the + * corresponding position in the wide char string. + */ + if (endptr != NULL) + /* XXX Assume each wide char is one byte. */ + *endptr = (wchar_t *)nptr + (end - buf); + + free(buf); + + return (val); +} diff --git a/lib/libc/locale/wcstof.c b/lib/libc/locale/wcstof.c new file mode 100644 index 0000000..a68b382 --- /dev/null +++ b/lib/libc/locale/wcstof.c @@ -0,0 +1,70 @@ +/*- + * Copyright (c) 2002, 2003 Tim J. Robbins + * 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 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 AUTHOR 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 +__FBSDID("$FreeBSD: src/lib/libc/locale/wcstof.c,v 1.3 2004/04/07 09:47:56 tjr Exp $"); + +#include +#include +#include + +/* + * See wcstod() for comments as to the logic used. + */ +float +wcstof(const wchar_t * __restrict nptr, wchar_t ** __restrict endptr) +{ + static const mbstate_t initial; + mbstate_t mbs; + float val; + char *buf, *end; + const wchar_t *wcp; + size_t len; + + while (iswspace(*nptr)) + nptr++; + + wcp = nptr; + mbs = initial; + if ((len = wcsrtombs(NULL, &wcp, 0, &mbs)) == (size_t)-1) { + if (endptr != NULL) + *endptr = (wchar_t *)nptr; + return (0.0); + } + if ((buf = malloc(len + 1)) == NULL) + return (0.0); + mbs = initial; + wcsrtombs(buf, &wcp, len + 1, &mbs); + + val = strtof(buf, &end); + + if (endptr != NULL) + *endptr = (wchar_t *)nptr + (end - buf); + + free(buf); + + return (val); +} diff --git a/lib/libc/locale/wcstoimax.c b/lib/libc/locale/wcstoimax.c new file mode 100644 index 0000000..09e7817 --- /dev/null +++ b/lib/libc/locale/wcstoimax.c @@ -0,0 +1,128 @@ +/*- + * 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. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#include +#if 0 +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "from @(#)strtol.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +__FBSDID("FreeBSD: src/lib/libc/stdlib/strtoimax.c,v 1.8 2002/09/06 11:23:59 tjr Exp "); +#endif +__FBSDID("$FreeBSD: src/lib/libc/locale/wcstoimax.c,v 1.2 2003/01/01 18:48:43 schweikh Exp $"); + +#include +#include +#include +#include +#include + +/* + * Convert a wide character string to an intmax_t integer. + */ +intmax_t +wcstoimax(const wchar_t * __restrict nptr, wchar_t ** __restrict endptr, + int base) +{ + const wchar_t *s; + uintmax_t acc; + wchar_t c; + uintmax_t cutoff; + int neg, any, cutlim; + + /* + * See strtoimax for comments as to the logic used. + */ + s = nptr; + do { + c = *s++; + } while (iswspace(c)); + if (c == L'-') { + neg = 1; + c = *s++; + } else { + neg = 0; + if (c == L'+') + c = *s++; + } + if ((base == 0 || base == 16) && + c == L'0' && (*s == L'x' || *s == L'X')) { + c = s[1]; + s += 2; + base = 16; + } + if (base == 0) + base = c == L'0' ? 8 : 10; + acc = any = 0; + if (base < 2 || base > 36) + goto noconv; + + cutoff = neg ? (uintmax_t)-(INTMAX_MIN + INTMAX_MAX) + INTMAX_MAX + : INTMAX_MAX; + cutlim = cutoff % base; + cutoff /= base; + for ( ; ; c = *s++) { +#ifdef notyet + if (iswdigit(c)) + c = digittoint(c); + else +#endif + if (c >= L'0' && c <= L'9') + c -= L'0'; + else if (c >= L'A' && c <= L'Z') + c -= L'A' - 10; + else if (c >= 'a' && c <= 'z') + c -= L'a' - 10; + else + break; + if (c >= base) + break; + if (any < 0 || acc > cutoff || (acc == cutoff && c > cutlim)) + any = -1; + else { + any = 1; + acc *= base; + acc += c; + } + } + if (any < 0) { + acc = neg ? INTMAX_MIN : INTMAX_MAX; + errno = ERANGE; + } else if (!any) { +noconv: + errno = EINVAL; + } else if (neg) + acc = -acc; + if (endptr != NULL) + *endptr = (wchar_t *)(any ? s - 1 : nptr); + return (acc); +} diff --git a/lib/libc/locale/wcstol.c b/lib/libc/locale/wcstol.c new file mode 100644 index 0000000..ae51c2e --- /dev/null +++ b/lib/libc/locale/wcstol.c @@ -0,0 +1,121 @@ +/*- + * Copyright (c) 1990, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#include +__FBSDID("$FreeBSD: src/lib/libc/locale/wcstol.c,v 1.1 2002/09/08 13:27:26 tjr Exp $"); + +#include +#include +#include +#include +#include + +/* + * Convert a string to a long integer. + */ +long +wcstol(const wchar_t * __restrict nptr, wchar_t ** __restrict endptr, int base) +{ + const wchar_t *s; + unsigned long acc; + wchar_t c; + unsigned long cutoff; + int neg, any, cutlim; + + /* + * See strtol for comments as to the logic used. + */ + s = nptr; + do { + c = *s++; + } while (iswspace(c)); + if (c == '-') { + neg = 1; + c = *s++; + } else { + neg = 0; + if (c == L'+') + c = *s++; + } + if ((base == 0 || base == 16) && + c == L'0' && (*s == L'x' || *s == L'X')) { + c = s[1]; + s += 2; + base = 16; + } + if (base == 0) + base = c == L'0' ? 8 : 10; + acc = any = 0; + if (base < 2 || base > 36) + goto noconv; + + cutoff = neg ? (unsigned long)-(LONG_MIN + LONG_MAX) + LONG_MAX + : LONG_MAX; + cutlim = cutoff % base; + cutoff /= base; + for ( ; ; c = *s++) { +#ifdef notyet + if (iswdigit(c)) + c = digittoint(c); + else +#endif + if (c >= L'0' && c <= L'9') + c -= L'0'; + else if (c >= L'A' && c <= L'Z') + c -= L'A' - 10; + else if (c >= L'a' && c <= L'z') + c -= L'a' - 10; + else + break; + if (c >= base) + break; + if (any < 0 || acc > cutoff || (acc == cutoff && c > cutlim)) + any = -1; + else { + any = 1; + acc *= base; + acc += c; + } + } + if (any < 0) { + acc = neg ? LONG_MIN : LONG_MAX; + errno = ERANGE; + } else if (!any) { +noconv: + errno = EINVAL; + } else if (neg) + acc = -acc; + if (endptr != NULL) + *endptr = (wchar_t *)(any ? s - 1 : nptr); + return (acc); +} diff --git a/lib/libc/locale/wcstold.c b/lib/libc/locale/wcstold.c new file mode 100644 index 0000000..c50ffbd --- /dev/null +++ b/lib/libc/locale/wcstold.c @@ -0,0 +1,70 @@ +/*- + * Copyright (c) 2002, 2003 Tim J. Robbins + * 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 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 AUTHOR 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 +__FBSDID("$FreeBSD: src/lib/libc/locale/wcstold.c,v 1.4 2004/04/07 09:47:56 tjr Exp $"); + +#include +#include +#include + +/* + * See wcstod() for comments as to the logic used. + */ +long double +wcstold(const wchar_t * __restrict nptr, wchar_t ** __restrict endptr) +{ + static const mbstate_t initial; + mbstate_t mbs; + long double val; + char *buf, *end; + const wchar_t *wcp; + size_t len; + + while (iswspace(*nptr)) + nptr++; + + wcp = nptr; + mbs = initial; + if ((len = wcsrtombs(NULL, &wcp, 0, &mbs)) == (size_t)-1) { + if (endptr != NULL) + *endptr = (wchar_t *)nptr; + return (0.0); + } + if ((buf = malloc(len + 1)) == NULL) + return (0.0); + mbs = initial; + wcsrtombs(buf, &wcp, len + 1, &mbs); + + val = strtold(buf, &end); + + if (endptr != NULL) + *endptr = (wchar_t *)nptr + (end - buf); + + free(buf); + + return (val); +} diff --git a/lib/libc/locale/wcstoll.c b/lib/libc/locale/wcstoll.c new file mode 100644 index 0000000..a48056c --- /dev/null +++ b/lib/libc/locale/wcstoll.c @@ -0,0 +1,127 @@ +/*- + * 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. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#include +#if 0 +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)strtoq.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +__FBSDID("FreeBSD: src/lib/libc/stdlib/strtoll.c,v 1.19 2002/09/06 11:23:59 tjr Exp "); +#endif +__FBSDID("$FreeBSD: src/lib/libc/locale/wcstoll.c,v 1.1 2002/09/22 08:06:45 tjr Exp $"); + +#include +#include +#include +#include +#include + +/* + * Convert a wide character string to a long long integer. + */ +long long +wcstoll(const wchar_t * __restrict nptr, wchar_t ** __restrict endptr, int base) +{ + const wchar_t *s; + unsigned long long acc; + wchar_t c; + unsigned long long cutoff; + int neg, any, cutlim; + + /* + * See strtoll for comments as to the logic used. + */ + s = nptr; + do { + c = *s++; + } while (iswspace(c)); + if (c == L'-') { + neg = 1; + c = *s++; + } else { + neg = 0; + if (c == L'+') + c = *s++; + } + if ((base == 0 || base == 16) && + c == L'0' && (*s == L'x' || *s == L'X')) { + c = s[1]; + s += 2; + base = 16; + } + if (base == 0) + base = c == L'0' ? 8 : 10; + acc = any = 0; + if (base < 2 || base > 36) + goto noconv; + + cutoff = neg ? (unsigned long long)-(LLONG_MIN + LLONG_MAX) + LLONG_MAX + : LLONG_MAX; + cutlim = cutoff % base; + cutoff /= base; + for ( ; ; c = *s++) { +#ifdef notyet + if (iswdigit(c)) + c = digittoint(c); + else +#endif + if (c >= L'0' && c <= L'9') + c -= L'0'; + else if (c >= L'A' && c <= L'Z') + c -= L'A' - 10; + else if (c >= L'a' && c <= L'z') + c -= L'a' - 10; + else + break; + if (c >= base) + break; + if (any < 0 || acc > cutoff || (acc == cutoff && c > cutlim)) + any = -1; + else { + any = 1; + acc *= base; + acc += c; + } + } + if (any < 0) { + acc = neg ? LLONG_MIN : LLONG_MAX; + errno = ERANGE; + } else if (!any) { +noconv: + errno = EINVAL; + } else if (neg) + acc = -acc; + if (endptr != NULL) + *endptr = (wchar_t *)(any ? s - 1 : nptr); + return (acc); +} diff --git a/lib/libc/locale/wcstombs.c b/lib/libc/locale/wcstombs.c new file mode 100644 index 0000000..b798c9e --- /dev/null +++ b/lib/libc/locale/wcstombs.c @@ -0,0 +1,43 @@ +/*- + * Copyright (c) 2002-2004 Tim J. Robbins. + * 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 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 AUTHOR 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 +__FBSDID("$FreeBSD: src/lib/libc/locale/wcstombs.c,v 1.10 2004/07/21 10:54:57 tjr Exp $"); + +#include +#include +#include +#include "mblocal.h" + +size_t +wcstombs(char * __restrict s, const wchar_t * __restrict pwcs, size_t n) +{ + static const mbstate_t initial; + mbstate_t mbs; + + mbs = initial; + return (__wcsnrtombs(s, &pwcs, SIZE_T_MAX, n, &mbs)); +} diff --git a/lib/libc/locale/wcstoul.c b/lib/libc/locale/wcstoul.c new file mode 100644 index 0000000..f3b8b49 --- /dev/null +++ b/lib/libc/locale/wcstoul.c @@ -0,0 +1,119 @@ +/* + * Copyright (c) 1990, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#include +__FBSDID("$FreeBSD: src/lib/libc/locale/wcstoul.c,v 1.1 2002/09/08 13:27:26 tjr Exp $"); + +#include +#include +#include +#include +#include + +/* + * Convert a wide character string to an unsigned long integer. + */ +unsigned long +wcstoul(const wchar_t * __restrict nptr, wchar_t ** __restrict endptr, int base) +{ + const wchar_t *s; + unsigned long acc; + wchar_t c; + unsigned long cutoff; + int neg, any, cutlim; + + /* + * See strtol for comments as to the logic used. + */ + s = nptr; + do { + c = *s++; + } while (iswspace(c)); + if (c == L'-') { + neg = 1; + c = *s++; + } else { + neg = 0; + if (c == L'+') + c = *s++; + } + if ((base == 0 || base == 16) && + c == L'0' && (*s == L'x' || *s == L'X')) { + c = s[1]; + s += 2; + base = 16; + } + if (base == 0) + base = c == L'0' ? 8 : 10; + acc = any = 0; + if (base < 2 || base > 36) + goto noconv; + + cutoff = ULONG_MAX / base; + cutlim = ULONG_MAX % base; + for ( ; ; c = *s++) { +#ifdef notyet + if (iswdigit(c)) + c = digittoint(c); + else +#endif + if (c >= L'0' && c <= L'9') + c -= L'0'; + else if (c >= L'A' && c <= L'Z') + c -= L'A' - 10; + else if (c >= L'a' && c <= L'z') + c -= L'a' - 10; + else + break; + if (c >= base) + break; + if (any < 0 || acc > cutoff || (acc == cutoff && c > cutlim)) + any = -1; + else { + any = 1; + acc *= base; + acc += c; + } + } + if (any < 0) { + acc = ULONG_MAX; + errno = ERANGE; + } else if (!any) { +noconv: + errno = EINVAL; + } else if (neg) + acc = -acc; + if (endptr != NULL) + *endptr = (wchar_t *)(any ? s - 1 : nptr); + return (acc); +} diff --git a/lib/libc/locale/wcstoull.c b/lib/libc/locale/wcstoull.c new file mode 100644 index 0000000..fd9558b --- /dev/null +++ b/lib/libc/locale/wcstoull.c @@ -0,0 +1,126 @@ +/*- + * 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. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#include +#if 0 +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)strtouq.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +__FBSDID("FreeBSD: src/lib/libc/stdlib/strtoull.c,v 1.18 2002/09/06 11:23:59 tjr Exp "); +#endif +__FBSDID("$FreeBSD: src/lib/libc/locale/wcstoull.c,v 1.1 2002/09/22 08:06:45 tjr Exp $"); + +#include +#include +#include +#include +#include + +/* + * Convert a wide character string to an unsigned long long integer. + */ +unsigned long long +wcstoull(const wchar_t * __restrict nptr, wchar_t ** __restrict endptr, + int base) +{ + const wchar_t *s; + unsigned long long acc; + wchar_t c; + unsigned long long cutoff; + int neg, any, cutlim; + + /* + * See strtoull for comments as to the logic used. + */ + s = nptr; + do { + c = *s++; + } while (iswspace(c)); + if (c == L'-') { + neg = 1; + c = *s++; + } else { + neg = 0; + if (c == L'+') + c = *s++; + } + if ((base == 0 || base == 16) && + c == L'0' && (*s == L'x' || *s == L'X')) { + c = s[1]; + s += 2; + base = 16; + } + if (base == 0) + base = c == L'0' ? 8 : 10; + acc = any = 0; + if (base < 2 || base > 36) + goto noconv; + + cutoff = ULLONG_MAX / base; + cutlim = ULLONG_MAX % base; + for ( ; ; c = *s++) { +#ifdef notyet + if (iswdigit(c)) + c = digittoint(c); + else +#endif + if (c >= L'0' && c <= L'9') + c -= L'0'; + else if (c >= L'A' && c <= L'Z') + c -= L'A' - 10; + else if (c >= L'a' && c <= L'z') + c -= L'a' - 10; + else + break; + if (c >= base) + break; + if (any < 0 || acc > cutoff || (acc == cutoff && c > cutlim)) + any = -1; + else { + any = 1; + acc *= base; + acc += c; + } + } + if (any < 0) { + acc = ULLONG_MAX; + errno = ERANGE; + } else if (!any) { +noconv: + errno = EINVAL; + } else if (neg) + acc = -acc; + if (endptr != NULL) + *endptr = (wchar_t *)(any ? s - 1 : nptr); + return (acc); +} diff --git a/lib/libc/locale/wcstoumax.c b/lib/libc/locale/wcstoumax.c new file mode 100644 index 0000000..01e25d5 --- /dev/null +++ b/lib/libc/locale/wcstoumax.c @@ -0,0 +1,126 @@ +/*- + * 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. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#include +#if 0 +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "from @(#)strtoul.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +__FBSDID("FreeBSD: src/lib/libc/stdlib/strtoumax.c,v 1.8 2002/09/06 11:23:59 tjr Exp "); +#endif +__FBSDID("$FreeBSD: src/lib/libc/locale/wcstoumax.c,v 1.1 2002/09/22 08:06:45 tjr Exp $"); + +#include +#include +#include +#include +#include + +/* + * Convert a wide character string to a uintmax_t integer. + */ +uintmax_t +wcstoumax(const wchar_t * __restrict nptr, wchar_t ** __restrict endptr, + int base) +{ + const wchar_t *s; + uintmax_t acc; + wchar_t c; + uintmax_t cutoff; + int neg, any, cutlim; + + /* + * See strtoimax for comments as to the logic used. + */ + s = nptr; + do { + c = *s++; + } while (iswspace(c)); + if (c == L'-') { + neg = 1; + c = *s++; + } else { + neg = 0; + if (c == L'+') + c = *s++; + } + if ((base == 0 || base == 16) && + c == L'0' && (*s == L'x' || *s == L'X')) { + c = s[1]; + s += 2; + base = 16; + } + if (base == 0) + base = c == L'0' ? 8 : 10; + acc = any = 0; + if (base < 2 || base > 36) + goto noconv; + + cutoff = UINTMAX_MAX / base; + cutlim = UINTMAX_MAX % base; + for ( ; ; c = *s++) { +#ifdef notyet + if (iswdigit(c)) + c = digittoint(c); + else +#endif + if (c >= L'0' && c <= L'9') + c -= L'0'; + else if (c >= L'A' && c <= L'Z') + c -= L'A' - 10; + else if (c >= L'a' && c <= L'z') + c -= L'a' - 10; + else + break; + if (c >= base) + break; + if (any < 0 || acc > cutoff || (acc == cutoff && c > cutlim)) + any = -1; + else { + any = 1; + acc *= base; + acc += c; + } + } + if (any < 0) { + acc = UINTMAX_MAX; + errno = ERANGE; + } else if (!any) { +noconv: + errno = EINVAL; + } else if (neg) + acc = -acc; + if (endptr != NULL) + *endptr = (wchar_t *)(any ? s - 1 : nptr); + return (acc); +} diff --git a/lib/libc/locale/wctob.c b/lib/libc/locale/wctob.c new file mode 100644 index 0000000..a8f0056 --- /dev/null +++ b/lib/libc/locale/wctob.c @@ -0,0 +1,45 @@ +/*- + * Copyright (c) 2002-2004 Tim J. Robbins. + * 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 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 AUTHOR 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 +__FBSDID("$FreeBSD: src/lib/libc/locale/wctob.c,v 1.4 2004/05/12 14:26:54 tjr Exp $"); + +#include +#include +#include +#include "mblocal.h" + +int +wctob(wint_t c) +{ + static const mbstate_t initial; + mbstate_t mbs = initial; + char buf[MB_LEN_MAX]; + + if (c == WEOF || __wcrtomb(buf, c, &mbs) != 1) + return (EOF); + return ((unsigned char)*buf); +} diff --git a/lib/libc/locale/wctomb.c b/lib/libc/locale/wctomb.c new file mode 100644 index 0000000..701b3ca --- /dev/null +++ b/lib/libc/locale/wctomb.c @@ -0,0 +1,49 @@ +/*- + * Copyright (c) 2002-2004 Tim J. Robbins. + * 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 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 AUTHOR 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 +__FBSDID("$FreeBSD: src/lib/libc/locale/wctomb.c,v 1.8 2004/07/29 06:18:40 tjr Exp $"); + +#include +#include +#include "mblocal.h" + +int +wctomb(char *s, wchar_t wchar) +{ + static const mbstate_t initial; + static mbstate_t mbs; + size_t rval; + + if (s == NULL) { + /* No support for state dependent encodings. */ + mbs = initial; + return (0); + } + if ((rval = __wcrtomb(s, wchar, &mbs)) == (size_t)-1) + return (-1); + return ((int)rval); +} diff --git a/lib/libc/locale/wctrans.c b/lib/libc/locale/wctrans.c new file mode 100644 index 0000000..a86e5c7 --- /dev/null +++ b/lib/libc/locale/wctrans.c @@ -0,0 +1,80 @@ +/*- + * Copyright (c) 2002 Tim J. Robbins. + * 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 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 AUTHOR 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 +__FBSDID("$FreeBSD: src/lib/libc/locale/wctrans.c,v 1.3 2003/11/01 08:20:58 tjr Exp $"); + +#include +#include +#include + +enum { + _WCT_ERROR = 0, + _WCT_TOLOWER = 1, + _WCT_TOUPPER = 2 +}; + +wint_t +towctrans(wint_t wc, wctrans_t desc) +{ + + switch (desc) { + case _WCT_TOLOWER: + wc = towlower(wc); + break; + case _WCT_TOUPPER: + wc = towupper(wc); + break; + case _WCT_ERROR: + default: + errno = EINVAL; + break; + } + + return (wc); +} + +wctrans_t +wctrans(const char *charclass) +{ + struct { + const char *name; + wctrans_t trans; + } ccls[] = { + { "tolower", _WCT_TOLOWER }, + { "toupper", _WCT_TOUPPER }, + { NULL, _WCT_ERROR }, /* Default */ + }; + int i; + + i = 0; + while (ccls[i].name != NULL && strcmp(ccls[i].name, charclass) != 0) + i++; + + if (ccls[i].trans == _WCT_ERROR) + errno = EINVAL; + return (ccls[i].trans); +} diff --git a/lib/libc/locale/wctype.c b/lib/libc/locale/wctype.c new file mode 100644 index 0000000..a0e21bc --- /dev/null +++ b/lib/libc/locale/wctype.c @@ -0,0 +1,74 @@ +/*- + * Copyright (c) 2002 Tim J. Robbins. + * 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 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 AUTHOR 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 +__FBSDID("$FreeBSD: src/lib/libc/locale/wctype.c,v 1.3 2004/03/27 08:59:21 tjr Exp $"); + +#include +#include +#include + +#undef iswctype +int +iswctype(wint_t wc, wctype_t charclass) +{ + + return (__istype(wc, charclass)); +} + +wctype_t +wctype(const char *property) +{ + struct { + const char *name; + wctype_t mask; + } props[] = { + { "alnum", _CTYPE_A|_CTYPE_D }, + { "alpha", _CTYPE_A }, + { "blank", _CTYPE_B }, + { "cntrl", _CTYPE_C }, + { "digit", _CTYPE_D }, + { "graph", _CTYPE_G }, + { "lower", _CTYPE_L }, + { "print", _CTYPE_R }, + { "punct", _CTYPE_P }, + { "space", _CTYPE_S }, + { "upper", _CTYPE_U }, + { "xdigit", _CTYPE_X }, + { "ideogram", _CTYPE_I }, /* BSD extension */ + { "special", _CTYPE_T }, /* BSD extension */ + { "phonogram", _CTYPE_Q }, /* BSD extension */ + { "rune", 0xFFFFFF00L }, /* BSD extension */ + { NULL, 0UL }, /* Default */ + }; + int i; + + i = 0; + while (props[i].name != NULL && strcmp(props[i].name, property) != 0) + i++; + + return (props[i].mask); +} diff --git a/lib/libc/locale/wcwidth.c b/lib/libc/locale/wcwidth.c new file mode 100644 index 0000000..288a60d --- /dev/null +++ b/lib/libc/locale/wcwidth.c @@ -0,0 +1,54 @@ +/* + * Copyright (c) 1989, 1993 + * The Regents of the University of California. All rights reserved. + * (c) UNIX System Laboratories, Inc. + * All or some portions of this file are derived from material licensed + * to the University of California by American Telephone and Telegraph + * Co. or Unix System Laboratories, Inc. and are reproduced herein with + * the permission of UNIX System Laboratories, Inc. + * + * This code is derived from software contributed to Berkeley by + * Paul Borman at Krystal Technologies. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#include +__FBSDID("$FreeBSD: src/lib/libc/locale/wcwidth.c,v 1.7 2004/08/12 12:19:11 tjr Exp $"); + +#include + +#undef wcwidth + +int +wcwidth(wchar_t wc) +{ + + return (__wcwidth(wc)); +} diff --git a/lib/libc/nameser/Makefile b/lib/libc/nameser/Makefile new file mode 100644 index 0000000..d05c7bd --- /dev/null +++ b/lib/libc/nameser/Makefile @@ -0,0 +1,35 @@ +# $Id: Makefile 89 2016-01-12 00:20:40Z reddawg $ +# The System Makefile (C) 2002 The UbixOS Project + +# Include Global 'Source' Options +include ../../../Makefile.incl +include ../../Makefile.incl +include ../Makefile.incl + +INCLUDES += -I../locale/ + +#Objects +OBJS = ns_name.o ns_netint.o ns_parse.o ns_print.o ns_samedomain.o ns_ttl.o + +all: $(OBJS) + +# Compile the source files +.cc.o: + $(CXX) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -c -o $@ $< + +.cc.s: + $(CXX) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -S -o $@ $< + +.c.o: + $(CC) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -c $< + +.c.s: + $(CC) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -S -o $@ $< + +.S.o: + $(CC) $(CFLAGS) -Wall -nostdlib -c -o $@ $< + +# Clean up the junk +clean: + $(REMOVE) $(OBJS) + diff --git a/lib/libc/nameser/ns_name.c b/lib/libc/nameser/ns_name.c new file mode 100644 index 0000000..df9de8a --- /dev/null +++ b/lib/libc/nameser/ns_name.c @@ -0,0 +1,965 @@ +/* + * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC") + * Copyright (c) 1996,1999 by Internet Software Consortium. + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT + * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +#ifndef lint +static const char rcsid[] = "$Id: ns_name.c 89 2016-01-12 00:20:40Z reddawg $"; +#endif +#include +__FBSDID("$FreeBSD: src/lib/libc/nameser/ns_name.c,v 1.1.1.1.2.1 2006/07/17 10:09:56 ume Exp $"); + +#include "port_before.h" + +#include + +#include +#include + +#include +#include +#include +#include +#include +#include + +#include "port_after.h" + +#ifdef SPRINTF_CHAR +# define SPRINTF(x) strlen(sprintf/**/x) +#else +# define SPRINTF(x) ((size_t)sprintf x) +#endif + +#define NS_TYPE_ELT 0x40 /* EDNS0 extended label type */ +#define DNS_LABELTYPE_BITSTRING 0x41 + +/* Data. */ + +static const char digits[] = "0123456789"; + +static const char digitvalue[256] = { + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /*16*/ + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /*32*/ + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /*48*/ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, /*64*/ + -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, /*80*/ + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /*96*/ + -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, /*112*/ + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /*128*/ + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /*256*/ +}; + +/* Forward. */ + +static int special(int); +static int printable(int); +static int dn_find(const u_char *, const u_char *, + const u_char * const *, + const u_char * const *); +static int encode_bitsring(const char **, const char *, + unsigned char **, unsigned char **, + unsigned const char *); +static int labellen(const u_char *); +static int decode_bitstring(const unsigned char **, + char *, const char *); + +/* Public. */ + +/* + * ns_name_ntop(src, dst, dstsiz) + * Convert an encoded domain name to printable ascii as per RFC1035. + * return: + * Number of bytes written to buffer, or -1 (with errno set) + * notes: + * The root is returned as "." + * All other domains are returned in non absolute form + */ +int +ns_name_ntop(const u_char *src, char *dst, size_t dstsiz) +{ + const u_char *cp; + char *dn, *eom; + u_char c; + u_int n; + int l; + + cp = src; + dn = dst; + eom = dst + dstsiz; + + while ((n = *cp++) != 0) { + if ((n & NS_CMPRSFLGS) == NS_CMPRSFLGS) { + /* Some kind of compression pointer. */ + errno = EMSGSIZE; + return (-1); + } + if (dn != dst) { + if (dn >= eom) { + errno = EMSGSIZE; + return (-1); + } + *dn++ = '.'; + } + if ((l = labellen(cp - 1)) < 0) { + errno = EMSGSIZE; /* XXX */ + return(-1); + } + if (dn + l >= eom) { + errno = EMSGSIZE; + return (-1); + } + if ((n & NS_CMPRSFLGS) == NS_TYPE_ELT) { + int m; + + if (n != DNS_LABELTYPE_BITSTRING) { + /* XXX: labellen should reject this case */ + errno = EINVAL; + return(-1); + } + if ((m = decode_bitstring(&cp, dn, eom)) < 0) + { + errno = EMSGSIZE; + return(-1); + } + dn += m; + continue; + } + for ((void)NULL; l > 0; l--) { + c = *cp++; + if (special(c)) { + if (dn + 1 >= eom) { + errno = EMSGSIZE; + return (-1); + } + *dn++ = '\\'; + *dn++ = (char)c; + } else if (!printable(c)) { + if (dn + 3 >= eom) { + errno = EMSGSIZE; + return (-1); + } + *dn++ = '\\'; + *dn++ = digits[c / 100]; + *dn++ = digits[(c % 100) / 10]; + *dn++ = digits[c % 10]; + } else { + if (dn >= eom) { + errno = EMSGSIZE; + return (-1); + } + *dn++ = (char)c; + } + } + } + if (dn == dst) { + if (dn >= eom) { + errno = EMSGSIZE; + return (-1); + } + *dn++ = '.'; + } + if (dn >= eom) { + errno = EMSGSIZE; + return (-1); + } + *dn++ = '\0'; + return (dn - dst); +} + +/* + * ns_name_pton(src, dst, dstsiz) + * Convert a ascii string into an encoded domain name as per RFC1035. + * return: + * -1 if it fails + * 1 if string was fully qualified + * 0 is string was not fully qualified + * notes: + * Enforces label and domain length limits. + */ + +int +ns_name_pton(const char *src, u_char *dst, size_t dstsiz) +{ + u_char *label, *bp, *eom; + int c, n, escaped, e = 0; + char *cp; + + escaped = 0; + bp = dst; + eom = dst + dstsiz; + label = bp++; + + while ((c = *src++) != 0) { + if (escaped) { + if (c == '[') { /* start a bit string label */ + if ((cp = strchr(src, ']')) == NULL) { + errno = EINVAL; /* ??? */ + return(-1); + } + if ((e = encode_bitsring(&src, cp + 2, + &label, &bp, eom)) + != 0) { + errno = e; + return(-1); + } + escaped = 0; + label = bp++; + if ((c = *src++) == 0) + goto done; + else if (c != '.') { + errno = EINVAL; + return(-1); + } + continue; + } + else if ((cp = strchr(digits, c)) != NULL) { + n = (cp - digits) * 100; + if ((c = *src++) == 0 || + (cp = strchr(digits, c)) == NULL) { + errno = EMSGSIZE; + return (-1); + } + n += (cp - digits) * 10; + if ((c = *src++) == 0 || + (cp = strchr(digits, c)) == NULL) { + errno = EMSGSIZE; + return (-1); + } + n += (cp - digits); + if (n > 255) { + errno = EMSGSIZE; + return (-1); + } + c = n; + } + escaped = 0; + } else if (c == '\\') { + escaped = 1; + continue; + } else if (c == '.') { + c = (bp - label - 1); + if ((c & NS_CMPRSFLGS) != 0) { /* Label too big. */ + errno = EMSGSIZE; + return (-1); + } + if (label >= eom) { + errno = EMSGSIZE; + return (-1); + } + *label = c; + /* Fully qualified ? */ + if (*src == '\0') { + if (c != 0) { + if (bp >= eom) { + errno = EMSGSIZE; + return (-1); + } + *bp++ = '\0'; + } + if ((bp - dst) > MAXCDNAME) { + errno = EMSGSIZE; + return (-1); + } + return (1); + } + if (c == 0 || *src == '.') { + errno = EMSGSIZE; + return (-1); + } + label = bp++; + continue; + } + if (bp >= eom) { + errno = EMSGSIZE; + return (-1); + } + *bp++ = (u_char)c; + } + c = (bp - label - 1); + if ((c & NS_CMPRSFLGS) != 0) { /* Label too big. */ + errno = EMSGSIZE; + return (-1); + } + done: + if (label >= eom) { + errno = EMSGSIZE; + return (-1); + } + *label = c; + if (c != 0) { + if (bp >= eom) { + errno = EMSGSIZE; + return (-1); + } + *bp++ = 0; + } + if ((bp - dst) > MAXCDNAME) { /* src too big */ + errno = EMSGSIZE; + return (-1); + } + return (0); +} + +/* + * ns_name_ntol(src, dst, dstsiz) + * Convert a network strings labels into all lowercase. + * return: + * Number of bytes written to buffer, or -1 (with errno set) + * notes: + * Enforces label and domain length limits. + */ + +int +ns_name_ntol(const u_char *src, u_char *dst, size_t dstsiz) +{ + const u_char *cp; + u_char *dn, *eom; + u_char c; + u_int n; + int l; + + cp = src; + dn = dst; + eom = dst + dstsiz; + + if (dn >= eom) { + errno = EMSGSIZE; + return (-1); + } + while ((n = *cp++) != 0) { + if ((n & NS_CMPRSFLGS) == NS_CMPRSFLGS) { + /* Some kind of compression pointer. */ + errno = EMSGSIZE; + return (-1); + } + *dn++ = n; + if ((l = labellen(cp - 1)) < 0) { + errno = EMSGSIZE; + return (-1); + } + if (dn + l >= eom) { + errno = EMSGSIZE; + return (-1); + } + for ((void)NULL; l > 0; l--) { + c = *cp++; + if (isupper(c)) + *dn++ = tolower(c); + else + *dn++ = c; + } + } + *dn++ = '\0'; + return (dn - dst); +} + +/* + * ns_name_unpack(msg, eom, src, dst, dstsiz) + * Unpack a domain name from a message, source may be compressed. + * return: + * -1 if it fails, or consumed octets if it succeeds. + */ +int +ns_name_unpack(const u_char *msg, const u_char *eom, const u_char *src, + u_char *dst, size_t dstsiz) +{ + const u_char *srcp, *dstlim; + u_char *dstp; + int n, len, checked, l; + + len = -1; + checked = 0; + dstp = dst; + srcp = src; + dstlim = dst + dstsiz; + if (srcp < msg || srcp >= eom) { + errno = EMSGSIZE; + return (-1); + } + /* Fetch next label in domain name. */ + while ((n = *srcp++) != 0) { + /* Check for indirection. */ + switch (n & NS_CMPRSFLGS) { + case 0: + case NS_TYPE_ELT: + /* Limit checks. */ + if ((l = labellen(srcp - 1)) < 0) { + errno = EMSGSIZE; + return(-1); + } + if (dstp + l + 1 >= dstlim || srcp + l >= eom) { + errno = EMSGSIZE; + return (-1); + } + checked += l + 1; + *dstp++ = n; + memcpy(dstp, srcp, l); + dstp += l; + srcp += l; + break; + + case NS_CMPRSFLGS: + if (srcp >= eom) { + errno = EMSGSIZE; + return (-1); + } + if (len < 0) + len = srcp - src + 1; + srcp = msg + (((n & 0x3f) << 8) | (*srcp & 0xff)); + if (srcp < msg || srcp >= eom) { /* Out of range. */ + errno = EMSGSIZE; + return (-1); + } + checked += 2; + /* + * Check for loops in the compressed name; + * if we've looked at the whole message, + * there must be a loop. + */ + if (checked >= eom - msg) { + errno = EMSGSIZE; + return (-1); + } + break; + + default: + errno = EMSGSIZE; + return (-1); /* flag error */ + } + } + *dstp = '\0'; + if (len < 0) + len = srcp - src; + return (len); +} + +/* + * ns_name_pack(src, dst, dstsiz, dnptrs, lastdnptr) + * Pack domain name 'domain' into 'comp_dn'. + * return: + * Size of the compressed name, or -1. + * notes: + * 'dnptrs' is an array of pointers to previous compressed names. + * dnptrs[0] is a pointer to the beginning of the message. The array + * ends with NULL. + * 'lastdnptr' is a pointer to the end of the array pointed to + * by 'dnptrs'. + * Side effects: + * The list of pointers in dnptrs is updated for labels inserted into + * the message as we compress the name. If 'dnptr' is NULL, we don't + * try to compress names. If 'lastdnptr' is NULL, we don't update the + * list. + */ +int +ns_name_pack(const u_char *src, u_char *dst, int dstsiz, + const u_char **dnptrs, const u_char **lastdnptr) +{ + u_char *dstp; + const u_char **cpp, **lpp, *eob, *msg; + const u_char *srcp; + int n, l, first = 1; + + srcp = src; + dstp = dst; + eob = dstp + dstsiz; + lpp = cpp = NULL; + if (dnptrs != NULL) { + if ((msg = *dnptrs++) != NULL) { + for (cpp = dnptrs; *cpp != NULL; cpp++) + (void)NULL; + lpp = cpp; /* end of list to search */ + } + } else + msg = NULL; + + /* make sure the domain we are about to add is legal */ + l = 0; + do { + int l0; + + n = *srcp; + if ((n & NS_CMPRSFLGS) == NS_CMPRSFLGS) { + errno = EMSGSIZE; + return (-1); + } + if ((l0 = labellen(srcp)) < 0) { + errno = EINVAL; + return(-1); + } + l += l0 + 1; + if (l > MAXCDNAME) { + errno = EMSGSIZE; + return (-1); + } + srcp += l0 + 1; + } while (n != 0); + + /* from here on we need to reset compression pointer array on error */ + srcp = src; + do { + /* Look to see if we can use pointers. */ + n = *srcp; + if (n != 0 && msg != NULL) { + l = dn_find(srcp, msg, (const u_char * const *)dnptrs, + (const u_char * const *)lpp); + if (l >= 0) { + if (dstp + 1 >= eob) { + goto cleanup; + } + *dstp++ = (l >> 8) | NS_CMPRSFLGS; + *dstp++ = l % 256; + return (dstp - dst); + } + /* Not found, save it. */ + if (lastdnptr != NULL && cpp < lastdnptr - 1 && + (dstp - msg) < 0x4000 && first) { + *cpp++ = dstp; + *cpp = NULL; + first = 0; + } + } + /* copy label to buffer */ + if ((n & NS_CMPRSFLGS) == NS_CMPRSFLGS) { + /* Should not happen. */ + goto cleanup; + } + n = labellen(srcp); + if (dstp + 1 + n >= eob) { + goto cleanup; + } + memcpy(dstp, srcp, n + 1); + srcp += n + 1; + dstp += n + 1; + } while (n != 0); + + if (dstp > eob) { +cleanup: + if (msg != NULL) + *lpp = NULL; + errno = EMSGSIZE; + return (-1); + } + return (dstp - dst); +} + +/* + * ns_name_uncompress(msg, eom, src, dst, dstsiz) + * Expand compressed domain name to presentation format. + * return: + * Number of bytes read out of `src', or -1 (with errno set). + * note: + * Root domain returns as "." not "". + */ +int +ns_name_uncompress(const u_char *msg, const u_char *eom, const u_char *src, + char *dst, size_t dstsiz) +{ + u_char tmp[NS_MAXCDNAME]; + int n; + + if ((n = ns_name_unpack(msg, eom, src, tmp, sizeof tmp)) == -1) + return (-1); + if (ns_name_ntop(tmp, dst, dstsiz) == -1) + return (-1); + return (n); +} + +/* + * ns_name_compress(src, dst, dstsiz, dnptrs, lastdnptr) + * Compress a domain name into wire format, using compression pointers. + * return: + * Number of bytes consumed in `dst' or -1 (with errno set). + * notes: + * 'dnptrs' is an array of pointers to previous compressed names. + * dnptrs[0] is a pointer to the beginning of the message. + * The list ends with NULL. 'lastdnptr' is a pointer to the end of the + * array pointed to by 'dnptrs'. Side effect is to update the list of + * pointers for labels inserted into the message as we compress the name. + * If 'dnptr' is NULL, we don't try to compress names. If 'lastdnptr' + * is NULL, we don't update the list. + */ +int +ns_name_compress(const char *src, u_char *dst, size_t dstsiz, + const u_char **dnptrs, const u_char **lastdnptr) +{ + u_char tmp[NS_MAXCDNAME]; + + if (ns_name_pton(src, tmp, sizeof tmp) == -1) + return (-1); + return (ns_name_pack(tmp, dst, dstsiz, dnptrs, lastdnptr)); +} + +/* + * Reset dnptrs so that there are no active references to pointers at or + * after src. + */ +void +ns_name_rollback(const u_char *src, const u_char **dnptrs, + const u_char **lastdnptr) +{ + while (dnptrs < lastdnptr && *dnptrs != NULL) { + if (*dnptrs >= src) { + *dnptrs = NULL; + break; + } + dnptrs++; + } +} + +/* + * ns_name_skip(ptrptr, eom) + * Advance *ptrptr to skip over the compressed name it points at. + * return: + * 0 on success, -1 (with errno set) on failure. + */ +int +ns_name_skip(const u_char **ptrptr, const u_char *eom) +{ + const u_char *cp; + u_int n; + int l; + + cp = *ptrptr; + while (cp < eom && (n = *cp++) != 0) { + /* Check for indirection. */ + switch (n & NS_CMPRSFLGS) { + case 0: /* normal case, n == len */ + cp += n; + continue; + case NS_TYPE_ELT: /* EDNS0 extended label */ + if ((l = labellen(cp - 1)) < 0) { + errno = EMSGSIZE; /* XXX */ + return(-1); + } + cp += l; + continue; + case NS_CMPRSFLGS: /* indirection */ + cp++; + break; + default: /* illegal type */ + errno = EMSGSIZE; + return (-1); + } + break; + } + if (cp > eom) { + errno = EMSGSIZE; + return (-1); + } + *ptrptr = cp; + return (0); +} + +/* Private. */ + +/* + * special(ch) + * Thinking in noninternationalized USASCII (per the DNS spec), + * is this characted special ("in need of quoting") ? + * return: + * boolean. + */ +static int +special(int ch) { + switch (ch) { + case 0x22: /* '"' */ + case 0x2E: /* '.' */ + case 0x3B: /* ';' */ + case 0x5C: /* '\\' */ + case 0x28: /* '(' */ + case 0x29: /* ')' */ + /* Special modifiers in zone files. */ + case 0x40: /* '@' */ + case 0x24: /* '$' */ + return (1); + default: + return (0); + } +} + +/* + * printable(ch) + * Thinking in noninternationalized USASCII (per the DNS spec), + * is this character visible and not a space when printed ? + * return: + * boolean. + */ +static int +printable(int ch) { + return (ch > 0x20 && ch < 0x7f); +} + +/* + * Thinking in noninternationalized USASCII (per the DNS spec), + * convert this character to lower case if it's upper case. + */ +static int +mklower(int ch) { + if (ch >= 0x41 && ch <= 0x5A) + return (ch + 0x20); + return (ch); +} + +/* + * dn_find(domain, msg, dnptrs, lastdnptr) + * Search for the counted-label name in an array of compressed names. + * return: + * offset from msg if found, or -1. + * notes: + * dnptrs is the pointer to the first name on the list, + * not the pointer to the start of the message. + */ +static int +dn_find(const u_char *domain, const u_char *msg, + const u_char * const *dnptrs, + const u_char * const *lastdnptr) +{ + const u_char *dn, *cp, *sp; + const u_char * const *cpp; + u_int n; + + for (cpp = dnptrs; cpp < lastdnptr; cpp++) { + sp = *cpp; + /* + * terminate search on: + * root label + * compression pointer + * unusable offset + */ + while (*sp != 0 && (*sp & NS_CMPRSFLGS) == 0 && + (sp - msg) < 0x4000) { + dn = domain; + cp = sp; + while ((n = *cp++) != 0) { + /* + * check for indirection + */ + switch (n & NS_CMPRSFLGS) { + case 0: /* normal case, n == len */ + n = labellen(cp - 1); /* XXX */ + + if (n != *dn++) + goto next; + + for ((void)NULL; n > 0; n--) + if (mklower(*dn++) != + mklower(*cp++)) + goto next; + /* Is next root for both ? */ + if (*dn == '\0' && *cp == '\0') + return (sp - msg); + if (*dn) + continue; + goto next; + case NS_CMPRSFLGS: /* indirection */ + cp = msg + (((n & 0x3f) << 8) | *cp); + break; + + default: /* illegal type */ + errno = EMSGSIZE; + return (-1); + } + } + next: ; + sp += *sp + 1; + } + } + errno = ENOENT; + return (-1); +} + +static int +decode_bitstring(const unsigned char **cpp, char *dn, const char *eom) +{ + const unsigned char *cp = *cpp; + char *beg = dn, tc; + int b, blen, plen, i; + + if ((blen = (*cp & 0xff)) == 0) + blen = 256; + plen = (blen + 3) / 4; + plen += sizeof("\\[x/]") + (blen > 99 ? 3 : (blen > 9) ? 2 : 1); + if (dn + plen >= eom) + return(-1); + + cp++; + i = SPRINTF((dn, "\\[x")); + if (i < 0) + return (-1); + dn += i; + for (b = blen; b > 7; b -= 8, cp++) { + i = SPRINTF((dn, "%02x", *cp & 0xff)); + if (i < 0) + return (-1); + dn += i; + } + if (b > 4) { + tc = *cp++; + i = SPRINTF((dn, "%02x", tc & (0xff << (8 - b)))); + if (i < 0) + return (-1); + dn += i; + } else if (b > 0) { + tc = *cp++; + i = SPRINTF((dn, "%1x", + ((tc >> 4) & 0x0f) & (0x0f << (4 - b)))); + if (i < 0) + return (-1); + dn += i; + } + i = SPRINTF((dn, "/%d]", blen)); + if (i < 0) + return (-1); + dn += i; + + *cpp = cp; + return(dn - beg); +} + +static int +encode_bitsring(const char **bp, const char *end, unsigned char **labelp, + unsigned char ** dst, unsigned const char *eom) +{ + int afterslash = 0; + const char *cp = *bp; + unsigned char *tp; + char c; + const char *beg_blen; + char *end_blen = NULL; + int value = 0, count = 0, tbcount = 0, blen = 0; + + beg_blen = end_blen = NULL; + + /* a bitstring must contain at least 2 characters */ + if (end - cp < 2) + return(EINVAL); + + /* XXX: currently, only hex strings are supported */ + if (*cp++ != 'x') + return(EINVAL); + if (!isxdigit((*cp) & 0xff)) /* reject '\[x/BLEN]' */ + return(EINVAL); + + for (tp = *dst + 1; cp < end && tp < eom; cp++) { + switch((c = *cp)) { + case ']': /* end of the bitstring */ + if (afterslash) { + if (beg_blen == NULL) + return(EINVAL); + blen = (int)strtol(beg_blen, &end_blen, 10); + if (*end_blen != ']') + return(EINVAL); + } + if (count) + *tp++ = ((value << 4) & 0xff); + cp++; /* skip ']' */ + goto done; + case '/': + afterslash = 1; + break; + default: + if (afterslash) { + if (!isdigit(c&0xff)) + return(EINVAL); + if (beg_blen == NULL) { + + if (c == '0') { + /* blen never begings with 0 */ + return(EINVAL); + } + beg_blen = cp; + } + } else { + if (!isxdigit(c&0xff)) + return(EINVAL); + value <<= 4; + value += digitvalue[(int)c]; + count += 4; + tbcount += 4; + if (tbcount > 256) + return(EINVAL); + if (count == 8) { + *tp++ = value; + count = 0; + } + } + break; + } + } + done: + if (cp >= end || tp >= eom) + return(EMSGSIZE); + + /* + * bit length validation: + * If a is present, the number of digits in the + * MUST be just sufficient to contain the number of bits specified + * by the . If there are insignificant bits in a final + * hexadecimal or octal digit, they MUST be zero. + * RFC 2673, Section 3.2. + */ + if (blen > 0) { + int traillen; + + if (((blen + 3) & ~3) != tbcount) + return(EINVAL); + traillen = tbcount - blen; /* between 0 and 3 */ + if (((value << (8 - traillen)) & 0xff) != 0) + return(EINVAL); + } + else + blen = tbcount; + if (blen == 256) + blen = 0; + + /* encode the type and the significant bit fields */ + **labelp = DNS_LABELTYPE_BITSTRING; + **dst = blen; + + *bp = cp; + *dst = tp; + + return(0); +} + +static int +labellen(const u_char *lp) +{ + int bitlen; + u_char l = *lp; + + if ((l & NS_CMPRSFLGS) == NS_CMPRSFLGS) { + /* should be avoided by the caller */ + return(-1); + } + + if ((l & NS_CMPRSFLGS) == NS_TYPE_ELT) { + if (l == DNS_LABELTYPE_BITSTRING) { + if ((bitlen = *(lp + 1)) == 0) + bitlen = 256; + return((bitlen + 7 ) / 8 + 1); + } + return(-1); /* unknwon ELT */ + } + return(l); +} diff --git a/lib/libc/nameser/ns_netint.c b/lib/libc/nameser/ns_netint.c new file mode 100644 index 0000000..90aede9 --- /dev/null +++ b/lib/libc/nameser/ns_netint.c @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC") + * Copyright (c) 1996,1999 by Internet Software Consortium. + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT + * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +#ifndef lint +static const char rcsid[] = "$Id: ns_netint.c 89 2016-01-12 00:20:40Z reddawg $"; +#endif +#include +__FBSDID("$FreeBSD: src/lib/libc/nameser/ns_netint.c,v 1.1.1.1.2.1 2006/07/17 10:09:56 ume Exp $"); + +/* Import. */ + +#include "port_before.h" + +#include + +#include "port_after.h" + +/* Public. */ + +u_int +ns_get16(const u_char *src) { + u_int dst; + + NS_GET16(dst, src); + return (dst); +} + +u_long +ns_get32(const u_char *src) { + u_long dst; + + NS_GET32(dst, src); + return (dst); +} + +void +ns_put16(u_int src, u_char *dst) { + NS_PUT16(src, dst); +} + +void +ns_put32(u_long src, u_char *dst) { + NS_PUT32(src, dst); +} diff --git a/lib/libc/nameser/ns_parse.c b/lib/libc/nameser/ns_parse.c new file mode 100644 index 0000000..3056fcc --- /dev/null +++ b/lib/libc/nameser/ns_parse.c @@ -0,0 +1,211 @@ +/* + * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC") + * Copyright (c) 1996,1999 by Internet Software Consortium. + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT + * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +#ifndef lint +static const char rcsid[] = "$Id: ns_parse.c 89 2016-01-12 00:20:40Z reddawg $"; +#endif +#include +__FBSDID("$FreeBSD: src/lib/libc/nameser/ns_parse.c,v 1.1.1.1.2.1 2006/07/17 10:09:56 ume Exp $"); + +/* Import. */ + +#include "port_before.h" + +#include + +#include +#include + +#include +#include +#include + +#include "port_after.h" + +/* Forward. */ + +static void setsection(ns_msg *msg, ns_sect sect); + +/* Macros. */ + +#ifndef SOLARIS2 +#define RETERR(err) do { errno = (err); return (-1); } while (0) +#else +#define RETERR(err) \ + do { errno = (err); if (errno == errno) return (-1); } while (0) +#endif + +/* Public. */ + +/* These need to be in the same order as the nres.h:ns_flag enum. */ +struct _ns_flagdata _ns_flagdata[16] = { + { 0x8000, 15 }, /* qr. */ + { 0x7800, 11 }, /* opcode. */ + { 0x0400, 10 }, /* aa. */ + { 0x0200, 9 }, /* tc. */ + { 0x0100, 8 }, /* rd. */ + { 0x0080, 7 }, /* ra. */ + { 0x0040, 6 }, /* z. */ + { 0x0020, 5 }, /* ad. */ + { 0x0010, 4 }, /* cd. */ + { 0x000f, 0 }, /* rcode. */ + { 0x0000, 0 }, /* expansion (1/6). */ + { 0x0000, 0 }, /* expansion (2/6). */ + { 0x0000, 0 }, /* expansion (3/6). */ + { 0x0000, 0 }, /* expansion (4/6). */ + { 0x0000, 0 }, /* expansion (5/6). */ + { 0x0000, 0 }, /* expansion (6/6). */ +}; + +int ns_msg_getflag(ns_msg handle, int flag) { + return(((handle)._flags & _ns_flagdata[flag].mask) >> _ns_flagdata[flag].shift); +} + +int +ns_skiprr(const u_char *ptr, const u_char *eom, ns_sect section, int count) { + const u_char *optr = ptr; + + for ((void)NULL; count > 0; count--) { + int b, rdlength; + + b = dn_skipname(ptr, eom); + if (b < 0) + RETERR(EMSGSIZE); + ptr += b/*Name*/ + NS_INT16SZ/*Type*/ + NS_INT16SZ/*Class*/; + if (section != ns_s_qd) { + if (ptr + NS_INT32SZ + NS_INT16SZ > eom) + RETERR(EMSGSIZE); + ptr += NS_INT32SZ/*TTL*/; + NS_GET16(rdlength, ptr); + ptr += rdlength/*RData*/; + } + } + if (ptr > eom) + RETERR(EMSGSIZE); + return (ptr - optr); +} + +int +ns_initparse(const u_char *msg, int msglen, ns_msg *handle) { + const u_char *eom = msg + msglen; + int i; + + memset(handle, 0x5e, sizeof *handle); + handle->_msg = msg; + handle->_eom = eom; + if (msg + NS_INT16SZ > eom) + RETERR(EMSGSIZE); + NS_GET16(handle->_id, msg); + if (msg + NS_INT16SZ > eom) + RETERR(EMSGSIZE); + NS_GET16(handle->_flags, msg); + for (i = 0; i < ns_s_max; i++) { + if (msg + NS_INT16SZ > eom) + RETERR(EMSGSIZE); + NS_GET16(handle->_counts[i], msg); + } + for (i = 0; i < ns_s_max; i++) + if (handle->_counts[i] == 0) + handle->_sections[i] = NULL; + else { + int b = ns_skiprr(msg, eom, (ns_sect)i, + handle->_counts[i]); + + if (b < 0) + return (-1); + handle->_sections[i] = msg; + msg += b; + } + if (msg != eom) + RETERR(EMSGSIZE); + setsection(handle, ns_s_max); + return (0); +} + +int +ns_parserr(ns_msg *handle, ns_sect section, int rrnum, ns_rr *rr) { + int b; + int tmp; + + /* Make section right. */ + tmp = section; + if (tmp < 0 || section >= ns_s_max) + RETERR(ENODEV); + if (section != handle->_sect) + setsection(handle, section); + + /* Make rrnum right. */ + if (rrnum == -1) + rrnum = handle->_rrnum; + if (rrnum < 0 || rrnum >= handle->_counts[(int)section]) + RETERR(ENODEV); + if (rrnum < handle->_rrnum) + setsection(handle, section); + if (rrnum > handle->_rrnum) { + b = ns_skiprr(handle->_msg_ptr, handle->_eom, section, + rrnum - handle->_rrnum); + + if (b < 0) + return (-1); + handle->_msg_ptr += b; + handle->_rrnum = rrnum; + } + + /* Do the parse. */ + b = dn_expand(handle->_msg, handle->_eom, + handle->_msg_ptr, rr->name, NS_MAXDNAME); + if (b < 0) + return (-1); + handle->_msg_ptr += b; + if (handle->_msg_ptr + NS_INT16SZ + NS_INT16SZ > handle->_eom) + RETERR(EMSGSIZE); + NS_GET16(rr->type, handle->_msg_ptr); + NS_GET16(rr->rr_class, handle->_msg_ptr); + if (section == ns_s_qd) { + rr->ttl = 0; + rr->rdlength = 0; + rr->rdata = NULL; + } else { + if (handle->_msg_ptr + NS_INT32SZ + NS_INT16SZ > handle->_eom) + RETERR(EMSGSIZE); + NS_GET32(rr->ttl, handle->_msg_ptr); + NS_GET16(rr->rdlength, handle->_msg_ptr); + if (handle->_msg_ptr + rr->rdlength > handle->_eom) + RETERR(EMSGSIZE); + rr->rdata = handle->_msg_ptr; + handle->_msg_ptr += rr->rdlength; + } + if (++handle->_rrnum > handle->_counts[(int)section]) + setsection(handle, (ns_sect)((int)section + 1)); + + /* All done. */ + return (0); +} + +/* Private. */ + +static void +setsection(ns_msg *msg, ns_sect sect) { + msg->_sect = sect; + if (sect == ns_s_max) { + msg->_rrnum = -1; + msg->_msg_ptr = NULL; + } else { + msg->_rrnum = 0; + msg->_msg_ptr = msg->_sections[(int)sect]; + } +} diff --git a/lib/libc/nameser/ns_print.c b/lib/libc/nameser/ns_print.c new file mode 100644 index 0000000..a57579c --- /dev/null +++ b/lib/libc/nameser/ns_print.c @@ -0,0 +1,909 @@ +/* + * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC") + * Copyright (c) 1996-1999 by Internet Software Consortium. + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT + * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +#ifndef lint +static const char rcsid[] = "$Id: ns_print.c 89 2016-01-12 00:20:40Z reddawg $"; +#endif +#include +__FBSDID("$FreeBSD: src/lib/libc/nameser/ns_print.c,v 1.2.2.1 2006/07/17 10:09:56 ume Exp $"); + +/* Import. */ + +#include "port_before.h" + +#include +#include + +#include +#include +#include + +#ifdef _LIBC +#include +#define INSIST(cond) assert(cond) +#else +#include +#include +#endif +#include +#include +#include +#include + +#include "port_after.h" + +#ifdef SPRINTF_CHAR +# define SPRINTF(x) strlen(sprintf/**/x) +#else +# define SPRINTF(x) ((size_t)sprintf x) +#endif + +/* Forward. */ + +static size_t prune_origin(const char *name, const char *origin); +static int charstr(const u_char *rdata, const u_char *edata, + char **buf, size_t *buflen); +static int addname(const u_char *msg, size_t msglen, + const u_char **p, const char *origin, + char **buf, size_t *buflen); +static void addlen(size_t len, char **buf, size_t *buflen); +static int addstr(const char *src, size_t len, + char **buf, size_t *buflen); +static int addtab(size_t len, size_t target, int spaced, + char **buf, size_t *buflen); + +/* Macros. */ + +#define T(x) \ + do { \ + if ((x) < 0) \ + return (-1); \ + } while (0) + +/* Public. */ + +/* + * int + * ns_sprintrr(handle, rr, name_ctx, origin, buf, buflen) + * Convert an RR to presentation format. + * return: + * Number of characters written to buf, or -1 (check errno). + */ +int +ns_sprintrr(const ns_msg *handle, const ns_rr *rr, + const char *name_ctx, const char *origin, + char *buf, size_t buflen) +{ + int n; + + n = ns_sprintrrf(ns_msg_base(*handle), ns_msg_size(*handle), + ns_rr_name(*rr), ns_rr_class(*rr), ns_rr_type(*rr), + ns_rr_ttl(*rr), ns_rr_rdata(*rr), ns_rr_rdlen(*rr), + name_ctx, origin, buf, buflen); + return (n); +} + +/* + * int + * ns_sprintrrf(msg, msglen, name, class, type, ttl, rdata, rdlen, + * name_ctx, origin, buf, buflen) + * Convert the fields of an RR into presentation format. + * return: + * Number of characters written to buf, or -1 (check errno). + */ +int +ns_sprintrrf(const u_char *msg, size_t msglen, + const char *name, ns_class class, ns_type type, + u_long ttl, const u_char *rdata, size_t rdlen, + const char *name_ctx, const char *origin, + char *buf, size_t buflen) +{ + const char *obuf = buf; + const u_char *edata = rdata + rdlen; + int spaced = 0; + + const char *comment; + char tmp[100]; + int len, x; + + /* + * Owner. + */ + if (name_ctx != NULL && ns_samename(name_ctx, name) == 1) { + T(addstr("\t\t\t", 3, &buf, &buflen)); + } else { + len = prune_origin(name, origin); + if (*name == '\0') { + goto root; + } else if (len == 0) { + T(addstr("@\t\t\t", 4, &buf, &buflen)); + } else { + T(addstr(name, len, &buf, &buflen)); + /* Origin not used or not root, and no trailing dot? */ + if (((origin == NULL || origin[0] == '\0') || + (origin[0] != '.' && origin[1] != '\0' && + name[len] == '\0')) && name[len - 1] != '.') { + root: + T(addstr(".", 1, &buf, &buflen)); + len++; + } + T(spaced = addtab(len, 24, spaced, &buf, &buflen)); + } + } + + /* + * TTL, Class, Type. + */ + T(x = ns_format_ttl(ttl, buf, buflen)); + addlen(x, &buf, &buflen); + len = SPRINTF((tmp, " %s %s", p_class(class), p_type(type))); + T(addstr(tmp, len, &buf, &buflen)); + T(spaced = addtab(x + len, 16, spaced, &buf, &buflen)); + + /* + * RData. + */ + switch (type) { + case ns_t_a: + if (rdlen != (size_t)NS_INADDRSZ) + goto formerr; + (void) inet_ntop(AF_INET, rdata, buf, buflen); + addlen(strlen(buf), &buf, &buflen); + break; + + case ns_t_cname: + case ns_t_mb: + case ns_t_mg: + case ns_t_mr: + case ns_t_ns: + case ns_t_ptr: + case ns_t_dname: + T(addname(msg, msglen, &rdata, origin, &buf, &buflen)); + break; + + case ns_t_hinfo: + case ns_t_isdn: + /* First word. */ + T(len = charstr(rdata, edata, &buf, &buflen)); + if (len == 0) + goto formerr; + rdata += len; + T(addstr(" ", 1, &buf, &buflen)); + + + /* Second word, optional in ISDN records. */ + if (type == ns_t_isdn && rdata == edata) + break; + + T(len = charstr(rdata, edata, &buf, &buflen)); + if (len == 0) + goto formerr; + rdata += len; + break; + + case ns_t_soa: { + u_long t; + + /* Server name. */ + T(addname(msg, msglen, &rdata, origin, &buf, &buflen)); + T(addstr(" ", 1, &buf, &buflen)); + + /* Administrator name. */ + T(addname(msg, msglen, &rdata, origin, &buf, &buflen)); + T(addstr(" (\n", 3, &buf, &buflen)); + spaced = 0; + + if ((edata - rdata) != 5*NS_INT32SZ) + goto formerr; + + /* Serial number. */ + t = ns_get32(rdata); rdata += NS_INT32SZ; + T(addstr("\t\t\t\t\t", 5, &buf, &buflen)); + len = SPRINTF((tmp, "%lu", t)); + T(addstr(tmp, len, &buf, &buflen)); + T(spaced = addtab(len, 16, spaced, &buf, &buflen)); + T(addstr("; serial\n", 9, &buf, &buflen)); + spaced = 0; + + /* Refresh interval. */ + t = ns_get32(rdata); rdata += NS_INT32SZ; + T(addstr("\t\t\t\t\t", 5, &buf, &buflen)); + T(len = ns_format_ttl(t, buf, buflen)); + addlen(len, &buf, &buflen); + T(spaced = addtab(len, 16, spaced, &buf, &buflen)); + T(addstr("; refresh\n", 10, &buf, &buflen)); + spaced = 0; + + /* Retry interval. */ + t = ns_get32(rdata); rdata += NS_INT32SZ; + T(addstr("\t\t\t\t\t", 5, &buf, &buflen)); + T(len = ns_format_ttl(t, buf, buflen)); + addlen(len, &buf, &buflen); + T(spaced = addtab(len, 16, spaced, &buf, &buflen)); + T(addstr("; retry\n", 8, &buf, &buflen)); + spaced = 0; + + /* Expiry. */ + t = ns_get32(rdata); rdata += NS_INT32SZ; + T(addstr("\t\t\t\t\t", 5, &buf, &buflen)); + T(len = ns_format_ttl(t, buf, buflen)); + addlen(len, &buf, &buflen); + T(spaced = addtab(len, 16, spaced, &buf, &buflen)); + T(addstr("; expiry\n", 9, &buf, &buflen)); + spaced = 0; + + /* Minimum TTL. */ + t = ns_get32(rdata); rdata += NS_INT32SZ; + T(addstr("\t\t\t\t\t", 5, &buf, &buflen)); + T(len = ns_format_ttl(t, buf, buflen)); + addlen(len, &buf, &buflen); + T(addstr(" )", 2, &buf, &buflen)); + T(spaced = addtab(len, 16, spaced, &buf, &buflen)); + T(addstr("; minimum\n", 10, &buf, &buflen)); + + break; + } + + case ns_t_mx: + case ns_t_afsdb: + case ns_t_rt: { + u_int t; + + if (rdlen < (size_t)NS_INT16SZ) + goto formerr; + + /* Priority. */ + t = ns_get16(rdata); + rdata += NS_INT16SZ; + len = SPRINTF((tmp, "%u ", t)); + T(addstr(tmp, len, &buf, &buflen)); + + /* Target. */ + T(addname(msg, msglen, &rdata, origin, &buf, &buflen)); + + break; + } + + case ns_t_px: { + u_int t; + + if (rdlen < (size_t)NS_INT16SZ) + goto formerr; + + /* Priority. */ + t = ns_get16(rdata); + rdata += NS_INT16SZ; + len = SPRINTF((tmp, "%u ", t)); + T(addstr(tmp, len, &buf, &buflen)); + + /* Name1. */ + T(addname(msg, msglen, &rdata, origin, &buf, &buflen)); + T(addstr(" ", 1, &buf, &buflen)); + + /* Name2. */ + T(addname(msg, msglen, &rdata, origin, &buf, &buflen)); + + break; + } + + case ns_t_x25: + T(len = charstr(rdata, edata, &buf, &buflen)); + if (len == 0) + goto formerr; + rdata += len; + break; + + case ns_t_txt: + while (rdata < edata) { + T(len = charstr(rdata, edata, &buf, &buflen)); + if (len == 0) + goto formerr; + rdata += len; + if (rdata < edata) + T(addstr(" ", 1, &buf, &buflen)); + } + break; + + case ns_t_nsap: { + char t[2+255*3]; + + (void) inet_nsap_ntoa(rdlen, rdata, t); + T(addstr(t, strlen(t), &buf, &buflen)); + break; + } + + case ns_t_aaaa: + if (rdlen != (size_t)NS_IN6ADDRSZ) + goto formerr; + (void) inet_ntop(AF_INET6, rdata, buf, buflen); + addlen(strlen(buf), &buf, &buflen); + break; + + case ns_t_loc: { + char t[255]; + + /* XXX protocol format checking? */ + (void) loc_ntoa(rdata, t); + T(addstr(t, strlen(t), &buf, &buflen)); + break; + } + + case ns_t_naptr: { + u_int order, preference; + char t[50]; + + if (rdlen < 2U*NS_INT16SZ) + goto formerr; + + /* Order, Precedence. */ + order = ns_get16(rdata); rdata += NS_INT16SZ; + preference = ns_get16(rdata); rdata += NS_INT16SZ; + len = SPRINTF((t, "%u %u ", order, preference)); + T(addstr(t, len, &buf, &buflen)); + + /* Flags. */ + T(len = charstr(rdata, edata, &buf, &buflen)); + if (len == 0) + goto formerr; + rdata += len; + T(addstr(" ", 1, &buf, &buflen)); + + /* Service. */ + T(len = charstr(rdata, edata, &buf, &buflen)); + if (len == 0) + goto formerr; + rdata += len; + T(addstr(" ", 1, &buf, &buflen)); + + /* Regexp. */ + T(len = charstr(rdata, edata, &buf, &buflen)); + if (len < 0) + return (-1); + if (len == 0) + goto formerr; + rdata += len; + T(addstr(" ", 1, &buf, &buflen)); + + /* Server. */ + T(addname(msg, msglen, &rdata, origin, &buf, &buflen)); + break; + } + + case ns_t_srv: { + u_int priority, weight, port; + char t[50]; + + if (rdlen < 3U*NS_INT16SZ) + goto formerr; + + /* Priority, Weight, Port. */ + priority = ns_get16(rdata); rdata += NS_INT16SZ; + weight = ns_get16(rdata); rdata += NS_INT16SZ; + port = ns_get16(rdata); rdata += NS_INT16SZ; + len = SPRINTF((t, "%u %u %u ", priority, weight, port)); + T(addstr(t, len, &buf, &buflen)); + + /* Server. */ + T(addname(msg, msglen, &rdata, origin, &buf, &buflen)); + break; + } + + case ns_t_minfo: + case ns_t_rp: + /* Name1. */ + T(addname(msg, msglen, &rdata, origin, &buf, &buflen)); + T(addstr(" ", 1, &buf, &buflen)); + + /* Name2. */ + T(addname(msg, msglen, &rdata, origin, &buf, &buflen)); + + break; + + case ns_t_wks: { + int n, lcnt; + + if (rdlen < 1U + NS_INT32SZ) + goto formerr; + + /* Address. */ + (void) inet_ntop(AF_INET, rdata, buf, buflen); + addlen(strlen(buf), &buf, &buflen); + rdata += NS_INADDRSZ; + + /* Protocol. */ + len = SPRINTF((tmp, " %u ( ", *rdata)); + T(addstr(tmp, len, &buf, &buflen)); + rdata += NS_INT8SZ; + + /* Bit map. */ + n = 0; + lcnt = 0; + while (rdata < edata) { + u_int c = *rdata++; + do { + if (c & 0200) { + if (lcnt == 0) { + T(addstr("\n\t\t\t\t", 5, + &buf, &buflen)); + lcnt = 10; + spaced = 0; + } + len = SPRINTF((tmp, "%d ", n)); + T(addstr(tmp, len, &buf, &buflen)); + lcnt--; + } + c <<= 1; + } while (++n & 07); + } + T(addstr(")", 1, &buf, &buflen)); + + break; + } + + case ns_t_key: { + char base64_key[NS_MD5RSA_MAX_BASE64]; + u_int keyflags, protocol, algorithm, key_id; + const char *leader; + int n; + + if (rdlen < 0U + NS_INT16SZ + NS_INT8SZ + NS_INT8SZ) + goto formerr; + + /* Key flags, Protocol, Algorithm. */ +#ifndef _LIBC + key_id = dst_s_dns_key_id(rdata, edata-rdata); +#else + key_id = 0; +#endif + keyflags = ns_get16(rdata); rdata += NS_INT16SZ; + protocol = *rdata++; + algorithm = *rdata++; + len = SPRINTF((tmp, "0x%04x %u %u", + keyflags, protocol, algorithm)); + T(addstr(tmp, len, &buf, &buflen)); + + /* Public key data. */ + len = b64_ntop(rdata, edata - rdata, + base64_key, sizeof base64_key); + if (len < 0) + goto formerr; + if (len > 15) { + T(addstr(" (", 2, &buf, &buflen)); + leader = "\n\t\t"; + spaced = 0; + } else + leader = " "; + for (n = 0; n < len; n += 48) { + T(addstr(leader, strlen(leader), &buf, &buflen)); + T(addstr(base64_key + n, MIN(len - n, 48), + &buf, &buflen)); + } + if (len > 15) + T(addstr(" )", 2, &buf, &buflen)); + n = SPRINTF((tmp, " ; key_tag= %u", key_id)); + T(addstr(tmp, n, &buf, &buflen)); + + break; + } + + case ns_t_sig: { + char base64_key[NS_MD5RSA_MAX_BASE64]; + u_int type, algorithm, labels, footprint; + const char *leader; + u_long t; + int n; + + if (rdlen < 22U) + goto formerr; + + /* Type covered, Algorithm, Label count, Original TTL. */ + type = ns_get16(rdata); rdata += NS_INT16SZ; + algorithm = *rdata++; + labels = *rdata++; + t = ns_get32(rdata); rdata += NS_INT32SZ; + len = SPRINTF((tmp, "%s %d %d %lu ", + p_type(type), algorithm, labels, t)); + T(addstr(tmp, len, &buf, &buflen)); + if (labels > (u_int)dn_count_labels(name)) + goto formerr; + + /* Signature expiry. */ + t = ns_get32(rdata); rdata += NS_INT32SZ; + len = SPRINTF((tmp, "%s ", p_secstodate(t))); + T(addstr(tmp, len, &buf, &buflen)); + + /* Time signed. */ + t = ns_get32(rdata); rdata += NS_INT32SZ; + len = SPRINTF((tmp, "%s ", p_secstodate(t))); + T(addstr(tmp, len, &buf, &buflen)); + + /* Signature Footprint. */ + footprint = ns_get16(rdata); rdata += NS_INT16SZ; + len = SPRINTF((tmp, "%u ", footprint)); + T(addstr(tmp, len, &buf, &buflen)); + + /* Signer's name. */ + T(addname(msg, msglen, &rdata, origin, &buf, &buflen)); + + /* Signature. */ + len = b64_ntop(rdata, edata - rdata, + base64_key, sizeof base64_key); + if (len > 15) { + T(addstr(" (", 2, &buf, &buflen)); + leader = "\n\t\t"; + spaced = 0; + } else + leader = " "; + if (len < 0) + goto formerr; + for (n = 0; n < len; n += 48) { + T(addstr(leader, strlen(leader), &buf, &buflen)); + T(addstr(base64_key + n, MIN(len - n, 48), + &buf, &buflen)); + } + if (len > 15) + T(addstr(" )", 2, &buf, &buflen)); + break; + } + + case ns_t_nxt: { + int n, c; + + /* Next domain name. */ + T(addname(msg, msglen, &rdata, origin, &buf, &buflen)); + + /* Type bit map. */ + n = edata - rdata; + for (c = 0; c < n*8; c++) + if (NS_NXT_BIT_ISSET(c, rdata)) { + len = SPRINTF((tmp, " %s", p_type(c))); + T(addstr(tmp, len, &buf, &buflen)); + } + break; + } + + case ns_t_cert: { + u_int c_type, key_tag, alg; + int n; + unsigned int siz; + char base64_cert[8192], tmp[40]; + const char *leader; + + c_type = ns_get16(rdata); rdata += NS_INT16SZ; + key_tag = ns_get16(rdata); rdata += NS_INT16SZ; + alg = (u_int) *rdata++; + + len = SPRINTF((tmp, "%d %d %d ", c_type, key_tag, alg)); + T(addstr(tmp, len, &buf, &buflen)); + siz = (edata-rdata)*4/3 + 4; /* "+4" accounts for trailing \0 */ + if (siz > sizeof(base64_cert) * 3/4) { + const char *str = "record too long to print"; + T(addstr(str, strlen(str), &buf, &buflen)); + } + else { + len = b64_ntop(rdata, edata-rdata, base64_cert, siz); + + if (len < 0) + goto formerr; + else if (len > 15) { + T(addstr(" (", 2, &buf, &buflen)); + leader = "\n\t\t"; + spaced = 0; + } + else + leader = " "; + + for (n = 0; n < len; n += 48) { + T(addstr(leader, strlen(leader), + &buf, &buflen)); + T(addstr(base64_cert + n, MIN(len - n, 48), + &buf, &buflen)); + } + if (len > 15) + T(addstr(" )", 2, &buf, &buflen)); + } + break; + } + + case ns_t_tkey: { + /* KJD - need to complete this */ + u_long t; + int mode, err, keysize; + + /* Algorithm name. */ + T(addname(msg, msglen, &rdata, origin, &buf, &buflen)); + T(addstr(" ", 1, &buf, &buflen)); + + /* Inception. */ + t = ns_get32(rdata); rdata += NS_INT32SZ; + len = SPRINTF((tmp, "%s ", p_secstodate(t))); + T(addstr(tmp, len, &buf, &buflen)); + + /* Experation. */ + t = ns_get32(rdata); rdata += NS_INT32SZ; + len = SPRINTF((tmp, "%s ", p_secstodate(t))); + T(addstr(tmp, len, &buf, &buflen)); + + /* Mode , Error, Key Size. */ + /* Priority, Weight, Port. */ + mode = ns_get16(rdata); rdata += NS_INT16SZ; + err = ns_get16(rdata); rdata += NS_INT16SZ; + keysize = ns_get16(rdata); rdata += NS_INT16SZ; + len = SPRINTF((tmp, "%u %u %u ", mode, err, keysize)); + T(addstr(tmp, len, &buf, &buflen)); + + /* XXX need to dump key, print otherdata length & other data */ + break; + } + + case ns_t_tsig: { + /* BEW - need to complete this */ + int n; + + T(len = addname(msg, msglen, &rdata, origin, &buf, &buflen)); + T(addstr(" ", 1, &buf, &buflen)); + rdata += 8; /* time */ + n = ns_get16(rdata); rdata += INT16SZ; + rdata += n; /* sig */ + n = ns_get16(rdata); rdata += INT16SZ; /* original id */ + sprintf(buf, "%d", ns_get16(rdata)); + rdata += INT16SZ; + addlen(strlen(buf), &buf, &buflen); + break; + } + + case ns_t_a6: { + struct in6_addr a; + int pbyte, pbit; + + /* prefix length */ + if (rdlen == 0U) goto formerr; + len = SPRINTF((tmp, "%d ", *rdata)); + T(addstr(tmp, len, &buf, &buflen)); + pbit = *rdata; + if (pbit > 128) goto formerr; + pbyte = (pbit & ~7) / 8; + rdata++; + + /* address suffix: provided only when prefix len != 128 */ + if (pbit < 128) { + if (rdata + pbyte >= edata) goto formerr; + memset(&a, 0, sizeof(a)); + memcpy(&a.s6_addr[pbyte], rdata, sizeof(a) - pbyte); + (void) inet_ntop(AF_INET6, &a, buf, buflen); + addlen(strlen(buf), &buf, &buflen); + rdata += sizeof(a) - pbyte; + } + + /* prefix name: provided only when prefix len > 0 */ + if (pbit == 0) + break; + if (rdata >= edata) goto formerr; + T(addstr(" ", 1, &buf, &buflen)); + T(addname(msg, msglen, &rdata, origin, &buf, &buflen)); + + break; + } + + case ns_t_opt: { + len = SPRINTF((tmp, "%u bytes", class)); + T(addstr(tmp, len, &buf, &buflen)); + break; + } + + default: + comment = "unknown RR type"; + goto hexify; + } + return (buf - obuf); + formerr: + comment = "RR format error"; + hexify: { + int n, m; + char *p; + + len = SPRINTF((tmp, "\\# %u%s\t; %s", (unsigned)(edata - rdata), + rdlen != 0U ? " (" : "", comment)); + T(addstr(tmp, len, &buf, &buflen)); + while (rdata < edata) { + p = tmp; + p += SPRINTF((p, "\n\t")); + spaced = 0; + n = MIN(16, edata - rdata); + for (m = 0; m < n; m++) + p += SPRINTF((p, "%02x ", rdata[m])); + T(addstr(tmp, p - tmp, &buf, &buflen)); + if (n < 16) { + T(addstr(")", 1, &buf, &buflen)); + T(addtab(p - tmp + 1, 48, spaced, &buf, &buflen)); + } + p = tmp; + p += SPRINTF((p, "; ")); + for (m = 0; m < n; m++) + *p++ = (isascii(rdata[m]) && isprint(rdata[m])) + ? rdata[m] + : '.'; + T(addstr(tmp, p - tmp, &buf, &buflen)); + rdata += n; + } + return (buf - obuf); + } +} + +/* Private. */ + +/* + * size_t + * prune_origin(name, origin) + * Find out if the name is at or under the current origin. + * return: + * Number of characters in name before start of origin, + * or length of name if origin does not match. + * notes: + * This function should share code with samedomain(). + */ +static size_t +prune_origin(const char *name, const char *origin) { + const char *oname = name; + + while (*name != '\0') { + if (origin != NULL && ns_samename(name, origin) == 1) + return (name - oname - (name > oname)); + while (*name != '\0') { + if (*name == '\\') { + name++; + /* XXX need to handle \nnn form. */ + if (*name == '\0') + break; + } else if (*name == '.') { + name++; + break; + } + name++; + } + } + return (name - oname); +} + +/* + * int + * charstr(rdata, edata, buf, buflen) + * Format a into the presentation buffer. + * return: + * Number of rdata octets consumed + * 0 for protocol format error + * -1 for output buffer error + * side effects: + * buffer is advanced on success. + */ +static int +charstr(const u_char *rdata, const u_char *edata, char **buf, size_t *buflen) { + const u_char *odata = rdata; + size_t save_buflen = *buflen; + char *save_buf = *buf; + + if (addstr("\"", 1, buf, buflen) < 0) + goto enospc; + if (rdata < edata) { + int n = *rdata; + + if (rdata + 1 + n <= edata) { + rdata++; + while (n-- > 0) { + if (strchr("\n\"\\", *rdata) != NULL) + if (addstr("\\", 1, buf, buflen) < 0) + goto enospc; + if (addstr((const char *)rdata, 1, + buf, buflen) < 0) + goto enospc; + rdata++; + } + } + } + if (addstr("\"", 1, buf, buflen) < 0) + goto enospc; + return (rdata - odata); + enospc: + errno = ENOSPC; + *buf = save_buf; + *buflen = save_buflen; + return (-1); +} + +static int +addname(const u_char *msg, size_t msglen, + const u_char **pp, const char *origin, + char **buf, size_t *buflen) +{ + size_t newlen, save_buflen = *buflen; + char *save_buf = *buf; + int n; + + n = dn_expand(msg, msg + msglen, *pp, *buf, *buflen); + if (n < 0) + goto enospc; /* Guess. */ + newlen = prune_origin(*buf, origin); + if (**buf == '\0') { + goto root; + } else if (newlen == 0U) { + /* Use "@" instead of name. */ + if (newlen + 2 > *buflen) + goto enospc; /* No room for "@\0". */ + (*buf)[newlen++] = '@'; + (*buf)[newlen] = '\0'; + } else { + if (((origin == NULL || origin[0] == '\0') || + (origin[0] != '.' && origin[1] != '\0' && + (*buf)[newlen] == '\0')) && (*buf)[newlen - 1] != '.') { + /* No trailing dot. */ + root: + if (newlen + 2 > *buflen) + goto enospc; /* No room for ".\0". */ + (*buf)[newlen++] = '.'; + (*buf)[newlen] = '\0'; + } + } + *pp += n; + addlen(newlen, buf, buflen); + **buf = '\0'; + return (newlen); + enospc: + errno = ENOSPC; + *buf = save_buf; + *buflen = save_buflen; + return (-1); +} + +static void +addlen(size_t len, char **buf, size_t *buflen) { + INSIST(len <= *buflen); + *buf += len; + *buflen -= len; +} + +static int +addstr(const char *src, size_t len, char **buf, size_t *buflen) { + if (len >= *buflen) { + errno = ENOSPC; + return (-1); + } + memcpy(*buf, src, len); + addlen(len, buf, buflen); + **buf = '\0'; + return (0); +} + +static int +addtab(size_t len, size_t target, int spaced, char **buf, size_t *buflen) { + size_t save_buflen = *buflen; + char *save_buf = *buf; + int t; + + if (spaced || len >= target - 1) { + T(addstr(" ", 2, buf, buflen)); + spaced = 1; + } else { + for (t = (target - len - 1) / 8; t >= 0; t--) + if (addstr("\t", 1, buf, buflen) < 0) { + *buflen = save_buflen; + *buf = save_buf; + return (-1); + } + spaced = 0; + } + return (spaced); +} diff --git a/lib/libc/nameser/ns_samedomain.c b/lib/libc/nameser/ns_samedomain.c new file mode 100644 index 0000000..438047c --- /dev/null +++ b/lib/libc/nameser/ns_samedomain.c @@ -0,0 +1,210 @@ +/* + * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC") + * Copyright (c) 1995,1999 by Internet Software Consortium. + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT + * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +#ifndef lint +static const char rcsid[] = "$Id: ns_samedomain.c 89 2016-01-12 00:20:40Z reddawg $"; +#endif +#include +__FBSDID("$FreeBSD: src/lib/libc/nameser/ns_samedomain.c,v 1.3.2.1 2006/07/17 10:09:56 ume Exp $"); + +#include "port_before.h" + +#include +#include +#include +#include + +#include "port_after.h" + +#ifndef _LIBC +/* + * int + * ns_samedomain(a, b) + * Check whether a name belongs to a domain. + * Inputs: + * a - the domain whose ancestory is being verified + * b - the potential ancestor we're checking against + * Return: + * boolean - is a at or below b? + * Notes: + * Trailing dots are first removed from name and domain. + * Always compare complete subdomains, not only whether the + * domain name is the trailing string of the given name. + * + * "host.foobar.top" lies in "foobar.top" and in "top" and in "" + * but NOT in "bar.top" + */ + +int +ns_samedomain(const char *a, const char *b) { + size_t la, lb; + int diff, i, escaped; + const char *cp; + + la = strlen(a); + lb = strlen(b); + + /* Ignore a trailing label separator (i.e. an unescaped dot) in 'a'. */ + if (la != 0U && a[la - 1] == '.') { + escaped = 0; + /* Note this loop doesn't get executed if la==1. */ + for (i = la - 2; i >= 0; i--) + if (a[i] == '\\') { + if (escaped) + escaped = 0; + else + escaped = 1; + } else + break; + if (!escaped) + la--; + } + + /* Ignore a trailing label separator (i.e. an unescaped dot) in 'b'. */ + if (lb != 0U && b[lb - 1] == '.') { + escaped = 0; + /* note this loop doesn't get executed if lb==1 */ + for (i = lb - 2; i >= 0; i--) + if (b[i] == '\\') { + if (escaped) + escaped = 0; + else + escaped = 1; + } else + break; + if (!escaped) + lb--; + } + + /* lb == 0 means 'b' is the root domain, so 'a' must be in 'b'. */ + if (lb == 0U) + return (1); + + /* 'b' longer than 'a' means 'a' can't be in 'b'. */ + if (lb > la) + return (0); + + /* 'a' and 'b' being equal at this point indicates sameness. */ + if (lb == la) + return (strncasecmp(a, b, lb) == 0); + + /* Ok, we know la > lb. */ + + diff = la - lb; + + /* + * If 'a' is only 1 character longer than 'b', then it can't be + * a subdomain of 'b' (because of the need for the '.' label + * separator). + */ + if (diff < 2) + return (0); + + /* + * If the character before the last 'lb' characters of 'b' + * isn't '.', then it can't be a match (this lets us avoid + * having "foobar.com" match "bar.com"). + */ + if (a[diff - 1] != '.') + return (0); + + /* + * We're not sure about that '.', however. It could be escaped + * and thus not a really a label separator. + */ + escaped = 0; + for (i = diff - 2; i >= 0; i--) + if (a[i] == '\\') { + if (escaped) + escaped = 0; + else + escaped = 1; + } else + break; + if (escaped) + return (0); + + /* Now compare aligned trailing substring. */ + cp = a + diff; + return (strncasecmp(cp, b, lb) == 0); +} + +/* + * int + * ns_subdomain(a, b) + * is "a" a subdomain of "b"? + */ +int +ns_subdomain(const char *a, const char *b) { + return (ns_samename(a, b) != 1 && ns_samedomain(a, b)); +} +#endif + +/* + * int + * ns_makecanon(src, dst, dstsize) + * make a canonical copy of domain name "src" + * notes: + * foo -> foo. + * foo. -> foo. + * foo.. -> foo. + * foo\. -> foo\.. + * foo\\. -> foo\\. + */ + +int +ns_makecanon(const char *src, char *dst, size_t dstsize) { + size_t n = strlen(src); + + if (n + sizeof "." > dstsize) { /* Note: sizeof == 2 */ + errno = EMSGSIZE; + return (-1); + } + strcpy(dst, src); + while (n >= 1U && dst[n - 1] == '.') /* Ends in "." */ + if (n >= 2U && dst[n - 2] == '\\' && /* Ends in "\." */ + (n < 3U || dst[n - 3] != '\\')) /* But not "\\." */ + break; + else + dst[--n] = '\0'; + dst[n++] = '.'; + dst[n] = '\0'; + return (0); +} + +/* + * int + * ns_samename(a, b) + * determine whether domain name "a" is the same as domain name "b" + * return: + * -1 on error + * 0 if names differ + * 1 if names are the same + */ + +int +ns_samename(const char *a, const char *b) { + char ta[NS_MAXDNAME], tb[NS_MAXDNAME]; + + if (ns_makecanon(a, ta, sizeof ta) < 0 || + ns_makecanon(b, tb, sizeof tb) < 0) + return (-1); + if (strcasecmp(ta, tb) == 0) + return (1); + else + return (0); +} diff --git a/lib/libc/nameser/ns_ttl.c b/lib/libc/nameser/ns_ttl.c new file mode 100644 index 0000000..7482a61 --- /dev/null +++ b/lib/libc/nameser/ns_ttl.c @@ -0,0 +1,162 @@ +/* + * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC") + * Copyright (c) 1996,1999 by Internet Software Consortium. + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT + * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +#ifndef lint +static const char rcsid[] = "$Id: ns_ttl.c 89 2016-01-12 00:20:40Z reddawg $"; +#endif +#include +__FBSDID("$FreeBSD: src/lib/libc/nameser/ns_ttl.c,v 1.1.1.1.2.1 2006/07/17 10:09:56 ume Exp $"); + +/* Import. */ + +#include "port_before.h" + +#include + +#include +#include +#include +#include + +#include "port_after.h" + +#ifdef SPRINTF_CHAR +# define SPRINTF(x) strlen(sprintf/**/x) +#else +# define SPRINTF(x) ((size_t)sprintf x) +#endif + +/* Forward. */ + +static int fmt1(int t, char s, char **buf, size_t *buflen); + +/* Macros. */ + +#define T(x) if ((x) < 0) return (-1); else (void)NULL + +/* Public. */ + +int +ns_format_ttl(u_long src, char *dst, size_t dstlen) { + char *odst = dst; + int secs, mins, hours, days, weeks, x; + char *p; + + secs = src % 60; src /= 60; + mins = src % 60; src /= 60; + hours = src % 24; src /= 24; + days = src % 7; src /= 7; + weeks = src; src = 0; + + x = 0; + if (weeks) { + T(fmt1(weeks, 'W', &dst, &dstlen)); + x++; + } + if (days) { + T(fmt1(days, 'D', &dst, &dstlen)); + x++; + } + if (hours) { + T(fmt1(hours, 'H', &dst, &dstlen)); + x++; + } + if (mins) { + T(fmt1(mins, 'M', &dst, &dstlen)); + x++; + } + if (secs || !(weeks || days || hours || mins)) { + T(fmt1(secs, 'S', &dst, &dstlen)); + x++; + } + + if (x > 1) { + int ch; + + for (p = odst; (ch = *p) != '\0'; p++) + if (isascii(ch) && isupper(ch)) + *p = tolower(ch); + } + + return (dst - odst); +} + +int +ns_parse_ttl(const char *src, u_long *dst) { + u_long ttl, tmp; + int ch, digits, dirty; + + ttl = 0; + tmp = 0; + digits = 0; + dirty = 0; + while ((ch = *src++) != '\0') { + if (!isascii(ch) || !isprint(ch)) + goto einval; + if (isdigit(ch)) { + tmp *= 10; + tmp += (ch - '0'); + digits++; + continue; + } + if (digits == 0) + goto einval; + if (islower(ch)) + ch = toupper(ch); + switch (ch) { + case 'W': tmp *= 7; + case 'D': tmp *= 24; + case 'H': tmp *= 60; + case 'M': tmp *= 60; + case 'S': break; + default: goto einval; + } + ttl += tmp; + tmp = 0; + digits = 0; + dirty = 1; + } + if (digits > 0) { + if (dirty) + goto einval; + else + ttl += tmp; + } else if (!dirty) + goto einval; + *dst = ttl; + return (0); + + einval: + errno = EINVAL; + return (-1); +} + +/* Private. */ + +static int +fmt1(int t, char s, char **buf, size_t *buflen) { + char tmp[50]; + size_t len; + + len = SPRINTF((tmp, "%d%c", t, s)); + if (len + 1 > *buflen) + return (-1); + strcpy(*buf, tmp); + *buf += len; + *buflen -= len; + return (0); +} diff --git a/lib/libc/net/Makefile b/lib/libc/net/Makefile new file mode 100644 index 0000000..4387190 --- /dev/null +++ b/lib/libc/net/Makefile @@ -0,0 +1,35 @@ +# $Id: Makefile 89 2016-01-12 00:20:40Z reddawg $ +# The System Makefile (C) 2002 The UbixOS Project + +# Include Global 'Source' Options +include ../../../Makefile.incl +include ../../Makefile.incl +include ../Makefile.incl + +INCLUDES += -I../locale/ -I../resolv + +#Objects +OBJS = addr2ascii.o ascii2addr.o base64.o ether_addr.o eui64.o gai_strerror.o getaddrinfo.o gethostbydns.o gethostbyht.o gethostbynis.o gethostnamadr.o getifaddrs.o getifmaddrs.o getnameinfo.o getnetbydns.o getnetbyht.o getnetbynis.o getnetnamadr.o getproto.o getprotoent.o getprotoname.o getservbyname.o getservbyport.o getservent.o hesiod.o if_indextoname.o if_nameindex.o if_nametoindex.o ip6opt.o linkaddr.o map_v4v6.o name6.o nsdispatch.o nslexer.o nsparser.o nss_compat.o rcmd.o rcmdsh.o recv.o res_mkupdate.o res_update.o rthdr.o send.o sockatmark.o vars.o + +all: $(OBJS) + +# Compile the source files +.cc.o: + $(CXX) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -c -o $@ $< + +.cc.s: + $(CXX) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -S -o $@ $< + +.c.o: + $(CC) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -c $< + +.c.s: + $(CC) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -S -o $@ $< + +.S.o: + $(CC) $(CFLAGS) -Wall -nostdlib -c -o $@ $< + +# Clean up the junk +clean: + $(REMOVE) $(OBJS) + diff --git a/lib/libc/net/addr2ascii.c b/lib/libc/net/addr2ascii.c new file mode 100644 index 0000000..20c53ef --- /dev/null +++ b/lib/libc/net/addr2ascii.c @@ -0,0 +1,94 @@ +/* + * Copyright 1996 Massachusetts Institute of Technology + * + * Permission to use, copy, modify, and distribute this software and + * its documentation for any purpose and without fee is hereby + * granted, provided that both the above copyright notice and this + * permission notice appear in all copies, that both the above + * copyright notice and this permission notice appear in all + * supporting documentation, and that the name of M.I.T. not be used + * in advertising or publicity pertaining to distribution of the + * software without specific, written prior permission. M.I.T. makes + * no representations about the suitability of this software for any + * purpose. It is provided "as is" without express or implied + * warranty. + * + * THIS SOFTWARE IS PROVIDED BY M.I.T. ``AS IS''. M.I.T. DISCLAIMS + * ALL EXPRESS OR IMPLIED WARRANTIES WITH REGARD TO THIS SOFTWARE, + * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT + * SHALL M.I.T. 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. + * + * $ANA: addr2ascii.c,v 1.1 1996/06/13 18:41:46 wollman Exp $ + */ + +#include + +#include +#include + +#include +#include + +#include +#include +#include + +/*- + * Convert a network address from binary to printable numeric format. + * This API is copied from INRIA's IPv6 implementation, but it is a + * bit bogus in two ways: + * + * 1) There is no value in passing both an address family and + * an address length; either one should imply the other, + * or we should be passing sockaddrs instead. + * 2) There should by contrast be /added/ a length for the buffer + * that we pass in, so that programmers are spared the need to + * manually calculate (read: ``guess'') the maximum length. + * + * Flash: the API is also the same in the NRL implementation, and seems to + * be some sort of standard, so we appear to be stuck with both the bad + * naming and the poor choice of arguments. + */ +char * +addr2ascii(af, addrp, len, buf) + int af; + const void *addrp; + int len; /* should be size_t XXX */ + char *buf; /* XXX should pass length of buffer */ +{ + static char staticbuf[64]; /* 64 for AF_LINK > 16 for AF_INET */ + + if (!buf) + buf = staticbuf; + + switch(af) { + case AF_INET: + if (len != sizeof(struct in_addr)) { + errno = ENAMETOOLONG; + return 0; + } + strcpy(buf, inet_ntoa(*(const struct in_addr *)addrp)); + break; + + case AF_LINK: + if (len != sizeof(struct sockaddr_dl)) { + errno = ENAMETOOLONG; + return 0; + } + strcpy(buf, link_ntoa((const struct sockaddr_dl *)addrp)); + break; + + default: + errno = EPROTONOSUPPORT; + return 0; + } + return buf; +} diff --git a/lib/libc/net/ascii2addr.c b/lib/libc/net/ascii2addr.c new file mode 100644 index 0000000..6110283 --- /dev/null +++ b/lib/libc/net/ascii2addr.c @@ -0,0 +1,74 @@ +/* + * Copyright 1996 Massachusetts Institute of Technology + * + * Permission to use, copy, modify, and distribute this software and + * its documentation for any purpose and without fee is hereby + * granted, provided that both the above copyright notice and this + * permission notice appear in all copies, that both the above + * copyright notice and this permission notice appear in all + * supporting documentation, and that the name of M.I.T. not be used + * in advertising or publicity pertaining to distribution of the + * software without specific, written prior permission. M.I.T. makes + * no representations about the suitability of this software for any + * purpose. It is provided "as is" without express or implied + * warranty. + * + * THIS SOFTWARE IS PROVIDED BY M.I.T. ``AS IS''. M.I.T. DISCLAIMS + * ALL EXPRESS OR IMPLIED WARRANTIES WITH REGARD TO THIS SOFTWARE, + * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT + * SHALL M.I.T. 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. + * + * $ANA: ascii2addr.c,v 1.2 1996/06/13 18:46:02 wollman Exp $ + */ + +#include + +#include +#include + +#include +#include + +#include +#include +#include + +int +ascii2addr(af, ascii, result) + int af; + const char *ascii; + void *result; +{ + struct in_addr *ina; + char strbuf[4*sizeof("123")]; /* long enough for V4 only */ + + switch(af) { + case AF_INET: + ina = result; + strbuf[0] = '\0'; + strncat(strbuf, ascii, (sizeof strbuf)-1); + if (inet_aton(strbuf, ina)) + return sizeof(struct in_addr); + errno = EINVAL; + break; + + case AF_LINK: + link_addr(ascii, result); + /* oops... no way to detect failure */ + return sizeof(struct sockaddr_dl); + + default: + errno = EPROTONOSUPPORT; + break; + } + + return -1; +} diff --git a/lib/libc/net/base64.c b/lib/libc/net/base64.c new file mode 100644 index 0000000..2de4726 --- /dev/null +++ b/lib/libc/net/base64.c @@ -0,0 +1,314 @@ +/* + * Copyright (c) 1996, 1998 by Internet Software Consortium. + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM DISCLAIMS + * ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL INTERNET SOFTWARE + * CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL + * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR + * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS + * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS + * SOFTWARE. + */ + +/* + * Portions Copyright (c) 1995 by International Business Machines, Inc. + * + * International Business Machines, Inc. (hereinafter called IBM) grants + * permission under its copyrights to use, copy, modify, and distribute this + * Software with or without fee, provided that the above copyright notice and + * all paragraphs of this notice appear in all copies, and that the name of IBM + * not be used in connection with the marketing of any product incorporating + * the Software or modifications thereof, without specific, written prior + * permission. + * + * To the extent it has a right to do so, IBM grants an immunity from suit + * under its patents, if any, for the use, sale or manufacture of products to + * the extent that such products are used for performing Domain Name System + * dynamic updates in TCP/IP networks by means of the Software. No immunity is + * granted for any product per se or for any other function of any product. + * + * THE SOFTWARE IS PROVIDED "AS IS", AND IBM DISCLAIMS ALL WARRANTIES, + * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A + * PARTICULAR PURPOSE. IN NO EVENT SHALL IBM BE LIABLE FOR ANY SPECIAL, + * DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER ARISING + * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE, EVEN + * IF IBM IS APPRISED OF THE POSSIBILITY OF SUCH DAMAGES. + */ + +#include + +#include +#include +#include + +#include +#include +#include + +#include +#include +#include +#include +#include + +#define Assert(Cond) if (!(Cond)) abort() + +static const char Base64[] = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; +static const char Pad64 = '='; + +/* (From RFC1521 and draft-ietf-dnssec-secext-03.txt) + The following encoding technique is taken from RFC 1521 by Borenstein + and Freed. It is reproduced here in a slightly edited form for + convenience. + + A 65-character subset of US-ASCII is used, enabling 6 bits to be + represented per printable character. (The extra 65th character, "=", + is used to signify a special processing function.) + + The encoding process represents 24-bit groups of input bits as output + strings of 4 encoded characters. Proceeding from left to right, a + 24-bit input group is formed by concatenating 3 8-bit input groups. + These 24 bits are then treated as 4 concatenated 6-bit groups, each + of which is translated into a single digit in the base64 alphabet. + + Each 6-bit group is used as an index into an array of 64 printable + characters. The character referenced by the index is placed in the + output string. + + Table 1: The Base64 Alphabet + + Value Encoding Value Encoding Value Encoding Value Encoding + 0 A 17 R 34 i 51 z + 1 B 18 S 35 j 52 0 + 2 C 19 T 36 k 53 1 + 3 D 20 U 37 l 54 2 + 4 E 21 V 38 m 55 3 + 5 F 22 W 39 n 56 4 + 6 G 23 X 40 o 57 5 + 7 H 24 Y 41 p 58 6 + 8 I 25 Z 42 q 59 7 + 9 J 26 a 43 r 60 8 + 10 K 27 b 44 s 61 9 + 11 L 28 c 45 t 62 + + 12 M 29 d 46 u 63 / + 13 N 30 e 47 v + 14 O 31 f 48 w (pad) = + 15 P 32 g 49 x + 16 Q 33 h 50 y + + Special processing is performed if fewer than 24 bits are available + at the end of the data being encoded. A full encoding quantum is + always completed at the end of a quantity. When fewer than 24 input + bits are available in an input group, zero bits are added (on the + right) to form an integral number of 6-bit groups. Padding at the + end of the data is performed using the '=' character. + + Since all base64 input is an integral number of octets, only the + ------------------------------------------------- + following cases can arise: + + (1) the final quantum of encoding input is an integral + multiple of 24 bits; here, the final unit of encoded + output will be an integral multiple of 4 characters + with no "=" padding, + (2) the final quantum of encoding input is exactly 8 bits; + here, the final unit of encoded output will be two + characters followed by two "=" padding characters, or + (3) the final quantum of encoding input is exactly 16 bits; + here, the final unit of encoded output will be three + characters followed by one "=" padding character. + */ + +int +b64_ntop(u_char const *src, size_t srclength, char *target, size_t targsize) { + size_t datalength = 0; + u_char input[3]; + u_char output[4]; + size_t i; + + while (2 < srclength) { + input[0] = *src++; + input[1] = *src++; + input[2] = *src++; + srclength -= 3; + + output[0] = input[0] >> 2; + output[1] = ((input[0] & 0x03) << 4) + (input[1] >> 4); + output[2] = ((input[1] & 0x0f) << 2) + (input[2] >> 6); + output[3] = input[2] & 0x3f; + Assert(output[0] < 64); + Assert(output[1] < 64); + Assert(output[2] < 64); + Assert(output[3] < 64); + + if (datalength + 4 > targsize) + return (-1); + target[datalength++] = Base64[output[0]]; + target[datalength++] = Base64[output[1]]; + target[datalength++] = Base64[output[2]]; + target[datalength++] = Base64[output[3]]; + } + + /* Now we worry about padding. */ + if (0 != srclength) { + /* Get what's left. */ + input[0] = input[1] = input[2] = '\0'; + for (i = 0; i < srclength; i++) + input[i] = *src++; + + output[0] = input[0] >> 2; + output[1] = ((input[0] & 0x03) << 4) + (input[1] >> 4); + output[2] = ((input[1] & 0x0f) << 2) + (input[2] >> 6); + Assert(output[0] < 64); + Assert(output[1] < 64); + Assert(output[2] < 64); + + if (datalength + 4 > targsize) + return (-1); + target[datalength++] = Base64[output[0]]; + target[datalength++] = Base64[output[1]]; + if (srclength == 1) + target[datalength++] = Pad64; + else + target[datalength++] = Base64[output[2]]; + target[datalength++] = Pad64; + } + if (datalength >= targsize) + return (-1); + target[datalength] = '\0'; /* Returned value doesn't count \0. */ + return (datalength); +} + +/* skips all whitespace anywhere. + converts characters, four at a time, starting at (or after) + src from base - 64 numbers into three 8 bit bytes in the target area. + it returns the number of data bytes stored at the target, or -1 on error. + */ + +int +b64_pton(src, target, targsize) + char const *src; + u_char *target; + size_t targsize; +{ + int tarindex, state, ch; + char *pos; + + state = 0; + tarindex = 0; + + while ((ch = *src++) != '\0') { + if (isspace((unsigned char)ch)) /* Skip whitespace anywhere. */ + continue; + + if (ch == Pad64) + break; + + pos = strchr(Base64, ch); + if (pos == 0) /* A non-base64 character. */ + return (-1); + + switch (state) { + case 0: + if (target) { + if ((size_t)tarindex >= targsize) + return (-1); + target[tarindex] = (pos - Base64) << 2; + } + state = 1; + break; + case 1: + if (target) { + if ((size_t)tarindex + 1 >= targsize) + return (-1); + target[tarindex] |= (pos - Base64) >> 4; + target[tarindex+1] = ((pos - Base64) & 0x0f) + << 4 ; + } + tarindex++; + state = 2; + break; + case 2: + if (target) { + if ((size_t)tarindex + 1 >= targsize) + return (-1); + target[tarindex] |= (pos - Base64) >> 2; + target[tarindex+1] = ((pos - Base64) & 0x03) + << 6; + } + tarindex++; + state = 3; + break; + case 3: + if (target) { + if ((size_t)tarindex >= targsize) + return (-1); + target[tarindex] |= (pos - Base64); + } + tarindex++; + state = 0; + break; + default: + abort(); + } + } + + /* + * We are done decoding Base-64 chars. Let's see if we ended + * on a byte boundary, and/or with erroneous trailing characters. + */ + + if (ch == Pad64) { /* We got a pad char. */ + ch = *src++; /* Skip it, get next. */ + switch (state) { + case 0: /* Invalid = in first position */ + case 1: /* Invalid = in second position */ + return (-1); + + case 2: /* Valid, means one byte of info */ + /* Skip any number of spaces. */ + for ((void)NULL; ch != '\0'; ch = *src++) + if (!isspace((unsigned char)ch)) + break; + /* Make sure there is another trailing = sign. */ + if (ch != Pad64) + return (-1); + ch = *src++; /* Skip the = */ + /* Fall through to "single trailing =" case. */ + /* FALLTHROUGH */ + + case 3: /* Valid, means two bytes of info */ + /* + * We know this char is an =. Is there anything but + * whitespace after it? + */ + for ((void)NULL; ch != '\0'; ch = *src++) + if (!isspace((unsigned char)ch)) + return (-1); + + /* + * Now make sure for cases 2 and 3 that the "extra" + * bits that slopped past the last full byte were + * zeros. If we don't check them, they become a + * subliminal channel. + */ + if (target && target[tarindex] != 0) + return (-1); + } + } else { + /* + * We ended by seeing the end of the string. Make sure we + * have no partial bytes lying around. + */ + if (state != 0) + return (-1); + } + + return (tarindex); +} diff --git a/lib/libc/net/ether_addr.c b/lib/libc/net/ether_addr.c new file mode 100644 index 0000000..76e21b0 --- /dev/null +++ b/lib/libc/net/ether_addr.c @@ -0,0 +1,230 @@ +/* + * Copyright (c) 1995 + * Bill Paul . All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by Bill Paul. + * 4. Neither the name of the author nor the names of any co-contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY Bill Paul 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. + * + * ethernet address conversion and lookup routines + * + * Written by Bill Paul + * Center for Telecommunications Research + * Columbia University, New York City + */ + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef YP +#include +#include +#include +#endif + +#ifndef _PATH_ETHERS +#define _PATH_ETHERS "/etc/ethers" +#endif + +/* + * Parse a string of text containing an ethernet address and hostname + * and separate it into its component parts. + */ +int +ether_line(l, e, hostname) + const char *l; + struct ether_addr *e; + char *hostname; +{ + int i, o[6]; + + i = sscanf(l, "%x:%x:%x:%x:%x:%x %s", &o[0], &o[1], &o[2], + &o[3], &o[4], &o[5], + hostname); + if (i != 7) + return (i); + + for (i=0; i<6; i++) + e->octet[i] = o[i]; + return (0); +} + +/* + * Convert an ASCII representation of an ethernet address to + * binary form. + */ +struct +ether_addr *ether_aton(a) + const char *a; +{ + int i; + static struct ether_addr o; + unsigned int o0, o1, o2, o3, o4, o5; + + i = sscanf(a, "%x:%x:%x:%x:%x:%x", &o0, &o1, &o2, &o3, &o4, &o5); + + if (i != 6) + return (NULL); + + o.octet[0]=o0; + o.octet[1]=o1; + o.octet[2]=o2; + o.octet[3]=o3; + o.octet[4]=o4; + o.octet[5]=o5; + + return ((struct ether_addr *)&o); +} + +/* + * Convert a binary representation of an ethernet address to + * an ASCII string. + */ +char +*ether_ntoa(n) + const struct ether_addr *n; +{ + int i; + static char a[18]; + + i = sprintf(a, "%02x:%02x:%02x:%02x:%02x:%02x", + n->octet[0], n->octet[1], n->octet[2], + n->octet[3], n->octet[4], n->octet[5]); + if (i < 17) + return (NULL); + return ((char *)&a); +} + +/* + * Map an ethernet address to a hostname. Use either /etc/ethers or + * NIS/YP. + */ +int +ether_ntohost(hostname, e) + char *hostname; + const struct ether_addr *e; +{ + FILE *fp; + char buf[BUFSIZ + 2]; + struct ether_addr local_ether; + char local_host[MAXHOSTNAMELEN]; +#ifdef YP + char *result; + int resultlen; + char *ether_a; + char *yp_domain; +#endif + if ((fp = fopen(_PATH_ETHERS, "r")) == NULL) + return (1); + + while (fgets(buf,BUFSIZ,fp)) { + if (buf[0] == '#') + continue; +#ifdef YP + if (buf[0] == '+') { + if (yp_get_default_domain(&yp_domain)) + continue; + ether_a = ether_ntoa(e); + if (yp_match(yp_domain, "ethers.byaddr", ether_a, + strlen(ether_a), &result, &resultlen)) { + continue; + } + strncpy(buf, result, resultlen); + buf[resultlen] = '\0'; + free(result); + } +#endif + if (!ether_line(buf, &local_ether, local_host)) { + if (!bcmp((char *)&local_ether.octet[0], + (char *)&e->octet[0], 6)) { + /* We have a match */ + strcpy(hostname, local_host); + fclose(fp); + return(0); + } + } + } + fclose(fp); + return (1); +} + +/* + * Map a hostname to an ethernet address using /etc/ethers or + * NIS/YP. + */ +int +ether_hostton(hostname, e) + const char *hostname; + struct ether_addr *e; +{ + FILE *fp; + char buf[BUFSIZ + 2]; + struct ether_addr local_ether; + char local_host[MAXHOSTNAMELEN]; +#ifdef YP + char *result; + int resultlen; + char *yp_domain; +#endif + if ((fp = fopen(_PATH_ETHERS, "r")) == NULL) + return (1); + + while (fgets(buf,BUFSIZ,fp)) { + if (buf[0] == '#') + continue; +#ifdef YP + if (buf[0] == '+') { + if (yp_get_default_domain(&yp_domain)) + continue; + if (yp_match(yp_domain, "ethers.byname", hostname, + strlen(hostname), &result, &resultlen)) { + continue; + } + strncpy(buf, result, resultlen); + buf[resultlen] = '\0'; + free(result); + } +#endif + if (!ether_line(buf, &local_ether, local_host)) { + if (!strcmp(hostname, local_host)) { + /* We have a match */ + bcopy((char *)&local_ether.octet[0], + (char *)&e->octet[0], 6); + fclose(fp); + return(0); + } + } + } + fclose(fp); + return (1); +} diff --git a/lib/libc/net/eui64.c b/lib/libc/net/eui64.c new file mode 100644 index 0000000..3c1e344 --- /dev/null +++ b/lib/libc/net/eui64.c @@ -0,0 +1,310 @@ +/* + * Copyright 2004 The Aerospace Corporation. 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 Aerospace Corporation may not be used to endorse or + * promote products derived from this software. + * + * THIS SOFTWARE IS PROVIDED BY THE AEROSPACE CORPORATION "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 AEROSPACE CORPORATION 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. + * + * Copyright (c) 1995 + * Bill Paul . All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by Bill Paul. + * 4. Neither the name of the author nor the names of any co-contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY Bill Paul 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. + * + * EUI-64 conversion and lookup routines + * + * + * Converted from ether_addr.c rev + * FreeBSD: src/lib/libc/net/eui64.c,v 1.15 2002/04/08 07:51:10 ru Exp + * by Brooks Davis + * + * Written by Bill Paul + * Center for Telecommunications Research + * Columbia University, New York City + */ + +#include + +#include +#include +#include +#include +#include +#include +#include +#ifdef YP +#include +#include +#include +#endif + +#ifndef _PATH_EUI64 +#define _PATH_EUI64 "/etc/eui64" +#endif + +static int eui64_line(const char *l, struct eui64 *e, char *hostname, + size_t len); + +/* + * Parse a string of text containing an EUI-64 and hostname + * and separate it into its component parts. + */ +static int +eui64_line(const char *l, struct eui64 *e, char *hostname, size_t len) +{ + char *line, *linehead, *cur; + + linehead = strdup(l); + if (linehead == NULL) + return (-1); + line = linehead; + + /* Find and parse the EUI64 */ + while ((cur = strsep(&line, " \t\r\n")) != NULL) { + if (*cur != '\0') { + if (eui64_aton(cur, e) == 0) + break; + else + goto bad; + } + } + + /* Find the hostname */ + while ((cur = strsep(&line, " \t\r\n")) != NULL) { + if (*cur != '\0') { + if (strlcpy(hostname, cur, len) <= len) + break; + else + goto bad; + } + } + + /* Make sure what remains is either whitespace or a comment */ + while ((cur = strsep(&line, " \t\r\n")) != NULL) { + if (*cur == '#') + break; + if (*cur != '\0') + goto bad; + } + + return (0); + +bad: + free(linehead); + return (-1); +} + +/* + * Convert an ASCII representation of an EUI-64 to binary form. + */ +int +eui64_aton(const char *a, struct eui64 *e) +{ + int i; + unsigned int o0, o1, o2, o3, o4, o5, o6, o7; + + /* canonical form */ + i = sscanf(a, "%x-%x-%x-%x-%x-%x-%x-%x", + &o0, &o1, &o2, &o3, &o4, &o5, &o6, &o7); + if (i == EUI64_LEN) + goto good; + /* ethernet form */ + i = sscanf(a, "%x:%x:%x:%x:%x:%x:%x:%x", + &o0, &o1, &o2, &o3, &o4, &o5, &o6, &o7); + if (i == EUI64_LEN) + goto good; + /* classic fwcontrol/dconschat form */ + i = sscanf(a, "0x%2x%2x%2x%2x%2x%2x%2x%2x", + &o0, &o1, &o2, &o3, &o4, &o5, &o6, &o7); + if (i == EUI64_LEN) + goto good; + /* MAC format (-) */ + i = sscanf(a, "%x-%x-%x-%x-%x-%x", + &o0, &o1, &o2, &o5, &o6, &o7); + if (i == 6) { + o3 = 0xff; + o4 = 0xfe; + goto good; + } + /* MAC format (:) */ + i = sscanf(a, "%x:%x:%x:%x:%x:%x", + &o0, &o1, &o2, &o5, &o6, &o7); + if (i == 6) { + o3 = 0xff; + o4 = 0xfe; + goto good; + } + + return (-1); + +good: + e->octet[0]=o0; + e->octet[1]=o1; + e->octet[2]=o2; + e->octet[3]=o3; + e->octet[4]=o4; + e->octet[5]=o5; + e->octet[6]=o6; + e->octet[7]=o7; + + return (0); +} + +/* + * Convert a binary representation of an EUI-64 to an ASCII string. + */ +int +eui64_ntoa(const struct eui64 *id, char *a, size_t len) +{ + int i; + + i = snprintf(a, len, "%02x-%02x-%02x-%02x-%02x-%02x-%02x-%02x", + id->octet[0], id->octet[1], id->octet[2], id->octet[3], + id->octet[4], id->octet[5], id->octet[6], id->octet[7]); + if (i < 23 || i >= len) + return (-1); + return (0); +} + +/* + * Map an EUI-64 to a hostname. Use either /etc/eui64 or NIS/YP. + */ +int +eui64_ntohost(char *hostname, size_t len, const struct eui64 *id) +{ + FILE *fp; + char buf[BUFSIZ + 2]; + struct eui64 local_eui64; + char local_host[MAXHOSTNAMELEN]; +#ifdef YP + char *result; + int resultlen; + char eui64_a[24]; + char *yp_domain; +#endif + if ((fp = fopen(_PATH_EUI64, "r")) == NULL) + return (1); + + while (fgets(buf,BUFSIZ,fp)) { + if (buf[0] == '#') + continue; +#ifdef YP + if (buf[0] == '+') { + if (yp_get_default_domain(&yp_domain)) + continue; + eui64_ntoa(id, eui64_a, sizeof(eui64_a)); + if (yp_match(yp_domain, "eui64.byid", eui64_a, + strlen(eui64_a), &result, &resultlen)) { + continue; + } + strncpy(buf, result, resultlen); + buf[resultlen] = '\0'; + free(result); + } +#endif + if (eui64_line(buf, &local_eui64, local_host, + sizeof(local_host)) == 0) { + if (bcmp(&local_eui64.octet[0], + &id->octet[0], EUI64_LEN) == 0) { + /* We have a match */ + strcpy(hostname, local_host); + fclose(fp); + return(0); + } + } + } + fclose(fp); + return (1); +} + +/* + * Map a hostname to an EUI-64 using /etc/eui64 or NIS/YP. + */ +int +eui64_hostton(const char *hostname, struct eui64 *id) +{ + FILE *fp; + char buf[BUFSIZ + 2]; + struct eui64 local_eui64; + char local_host[MAXHOSTNAMELEN]; +#ifdef YP + char *result; + int resultlen; + char *yp_domain; +#endif + if ((fp = fopen(_PATH_EUI64, "r")) == NULL) + return (1); + + while (fgets(buf,BUFSIZ,fp)) { + if (buf[0] == '#') + continue; +#ifdef YP + if (buf[0] == '+') { + if (yp_get_default_domain(&yp_domain)) + continue; + if (yp_match(yp_domain, "eui64.byname", hostname, + strlen(hostname), &result, &resultlen)) { + continue; + } + strncpy(buf, result, resultlen); + buf[resultlen] = '\0'; + free(result); + } +#endif + if (eui64_line(buf, &local_eui64, local_host, + sizeof(local_host)) == 0) { + if (strcmp(hostname, local_host) == 0) { + /* We have a match */ + bcopy(&local_eui64, id, sizeof(struct eui64)); + fclose(fp); + return(0); + } + } + } + fclose(fp); + return (1); +} diff --git a/lib/libc/net/gai_strerror.c b/lib/libc/net/gai_strerror.c new file mode 100644 index 0000000..81e01a3 --- /dev/null +++ b/lib/libc/net/gai_strerror.c @@ -0,0 +1,59 @@ +/* + * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project. + * 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 project 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 PROJECT 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 PROJECT 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 + +#include + +/* Entries EAI_ADDRFAMILY (1) and EAI_NODATA (7) are obsoleted, but left */ +/* for backward compatibility with userland code prior to 2553bis-02 */ +static const char *ai_errlist[] = { + "Success", /* 0 */ + "Address family for hostname not supported", /* 1 */ + "Temporary failure in name resolution", /* EAI_AGAIN */ + "Invalid value for ai_flags", /* EAI_BADFLAGS */ + "Non-recoverable failure in name resolution", /* EAI_FAIL */ + "ai_family not supported", /* EAI_FAMILY */ + "Memory allocation failure", /* EAI_MEMORY */ + "No address associated with hostname", /* 7 */ + "hostname nor servname provided, or not known", /* EAI_NONAME */ + "servname not supported for ai_socktype", /* EAI_SERVICE */ + "ai_socktype not supported", /* EAI_SOCKTYPE */ + "System error returned in errno", /* EAI_SYSTEM */ + "Invalid value for hints", /* EAI_BADHINTS */ + "Resolved protocol is unknown" /* EAI_PROTOCOL */ +}; + +const char * +gai_strerror(int ecode) +{ + if (ecode >= 0 && ecode < EAI_MAX) + return ai_errlist[ecode]; + return "Unknown error"; +} diff --git a/lib/libc/net/getaddrinfo.c b/lib/libc/net/getaddrinfo.c new file mode 100644 index 0000000..26e59ca --- /dev/null +++ b/lib/libc/net/getaddrinfo.c @@ -0,0 +1,2546 @@ +/* $KAME: getaddrinfo.c,v 1.15 2000/07/09 04:37:24 itojun Exp $ */ + +/* + * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project. + * 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 project 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 PROJECT 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 PROJECT 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. + */ + +/* + * "#ifdef FAITH" part is local hack for supporting IPv4-v6 translator. + * + * Issues to be discussed: + * - Return values. There are nonstandard return values defined and used + * in the source code. This is because RFC2553 is silent about which error + * code must be returned for which situation. + * - freeaddrinfo(NULL). RFC2553 is silent about it. XNET 5.2 says it is + * invalid. current code - SEGV on freeaddrinfo(NULL) + * + * Note: + * - The code filters out AFs that are not supported by the kernel, + * when globbing NULL hostname (to loopback, or wildcard). Is it the right + * thing to do? What is the relationship with post-RFC2553 AI_ADDRCONFIG + * in ai_flags? + * - (post-2553) semantics of AI_ADDRCONFIG itself is too vague. + * (1) what should we do against numeric hostname (2) what should we do + * against NULL hostname (3) what is AI_ADDRCONFIG itself. AF not ready? + * non-loopback address configured? global address configured? + * + * OS specific notes for freebsd4: + * - FreeBSD supported $GAI. The code does not. + */ + +#include + +#include "namespace.h" +#include +#include +#include +#include +#include +#include +#ifdef INET6 +#include +#include +#include +#include /* XXX */ +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "res_config.h" + +#ifdef DEBUG +#include +#endif + +#include +#include +#include "un-namespace.h" +#include "libc_private.h" + +#if defined(__KAME__) && defined(INET6) +# define FAITH +#endif + +#define SUCCESS 0 +#define ANY 0 +#define YES 1 +#define NO 0 + +static const char in_addrany[] = { 0, 0, 0, 0 }; +static const char in_loopback[] = { 127, 0, 0, 1 }; +#ifdef INET6 +static const char in6_addrany[] = { + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 +}; +static const char in6_loopback[] = { + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 +}; +#endif + +struct policyqueue { + TAILQ_ENTRY(policyqueue) pc_entry; +#ifdef INET6 + struct in6_addrpolicy pc_policy; +#endif +}; +TAILQ_HEAD(policyhead, policyqueue); + +static const struct afd { + int a_af; + int a_addrlen; + socklen_t a_socklen; + int a_off; + const char *a_addrany; + const char *a_loopback; + int a_scoped; +} afdl [] = { +#ifdef INET6 +#define N_INET6 0 + {PF_INET6, sizeof(struct in6_addr), + sizeof(struct sockaddr_in6), + offsetof(struct sockaddr_in6, sin6_addr), + in6_addrany, in6_loopback, 1}, +#define N_INET 1 +#else +#define N_INET 0 +#endif + {PF_INET, sizeof(struct in_addr), + sizeof(struct sockaddr_in), + offsetof(struct sockaddr_in, sin_addr), + in_addrany, in_loopback, 0}, + {0, 0, 0, 0, NULL, NULL, 0}, +}; + +struct explore { + int e_af; + int e_socktype; + int e_protocol; + const char *e_protostr; + int e_wild; +#define WILD_AF(ex) ((ex)->e_wild & 0x01) +#define WILD_SOCKTYPE(ex) ((ex)->e_wild & 0x02) +#define WILD_PROTOCOL(ex) ((ex)->e_wild & 0x04) +}; + +static const struct explore explore[] = { +#if 0 + { PF_LOCAL, 0, ANY, ANY, NULL, 0x01 }, +#endif +#ifdef INET6 + { PF_INET6, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 }, + { PF_INET6, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 }, + { PF_INET6, SOCK_RAW, ANY, NULL, 0x05 }, +#endif + { PF_INET, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 }, + { PF_INET, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 }, + { PF_INET, SOCK_RAW, ANY, NULL, 0x05 }, + { PF_UNSPEC, SOCK_DGRAM, IPPROTO_UDP, "udp", 0x07 }, + { PF_UNSPEC, SOCK_STREAM, IPPROTO_TCP, "tcp", 0x07 }, + { PF_UNSPEC, SOCK_RAW, ANY, NULL, 0x05 }, + { -1, 0, 0, NULL, 0 }, +}; + +#ifdef INET6 +#define PTON_MAX 16 +#else +#define PTON_MAX 4 +#endif + +#define AIO_SRCFLAG_DEPRECATED 0x1 + +struct ai_order { + union { + struct sockaddr_storage aiou_ss; + struct sockaddr aiou_sa; + } aio_src_un; +#define aio_srcsa aio_src_un.aiou_sa + uint32_t aio_srcflag; + int aio_srcscope; + int aio_dstscope; + struct policyqueue *aio_srcpolicy; + struct policyqueue *aio_dstpolicy; + struct addrinfo *aio_ai; + int aio_matchlen; +}; + +static const ns_src default_dns_files[] = { + { NSSRC_FILES, NS_SUCCESS }, + { NSSRC_DNS, NS_SUCCESS }, + { 0 } +}; + +struct res_target { + struct res_target *next; + const char *name; /* domain name */ + int qclass, qtype; /* class and type of query */ + u_char *answer; /* buffer to put answer */ + int anslen; /* size of answer buffer */ + int n; /* result length */ +}; + +#define MAXPACKET (64*1024) + +typedef union { + HEADER hdr; + u_char buf[MAXPACKET]; +} querybuf; + +static int str2number(const char *, int *); +static int explore_null(const struct addrinfo *, + const char *, struct addrinfo **); +static int explore_numeric(const struct addrinfo *, const char *, + const char *, struct addrinfo **, const char *); +static int explore_numeric_scope(const struct addrinfo *, const char *, + const char *, struct addrinfo **); +static int get_canonname(const struct addrinfo *, + struct addrinfo *, const char *); +static struct addrinfo *get_ai(const struct addrinfo *, + const struct afd *, const char *); +static int get_portmatch(const struct addrinfo *, const char *); +static int get_port(struct addrinfo *, const char *, int); +static const struct afd *find_afd(int); +static int addrconfig(struct addrinfo *); +static void set_source(struct ai_order *, struct policyhead *); +static int comp_dst(const void *, const void *); +#ifdef INET6 +static int ip6_str2scopeid(char *, struct sockaddr_in6 *, uint32_t *); +#endif +static int gai_addr2scopetype(struct sockaddr *); + +static int explore_fqdn(const struct addrinfo *, const char *, + const char *, struct addrinfo **); + +static int reorder(struct addrinfo *); +static int get_addrselectpolicy(struct policyhead *); +static void free_addrselectpolicy(struct policyhead *); +static struct policyqueue *match_addrselectpolicy(struct sockaddr *, + struct policyhead *); +static int matchlen(struct sockaddr *, struct sockaddr *); + +static struct addrinfo *getanswer(const querybuf *, int, const char *, int, + const struct addrinfo *, res_state); +#if defined(RESOLVSORT) +static int addr4sort(struct addrinfo *, res_state); +#endif +static int _dns_getaddrinfo(void *, void *, va_list); +static void _sethtent(FILE **); +static void _endhtent(FILE **); +static struct addrinfo *_gethtent(FILE **, const char *, + const struct addrinfo *); +static int _files_getaddrinfo(void *, void *, va_list); +#ifdef YP +static struct addrinfo *_yphostent(char *, const struct addrinfo *); +static int _yp_getaddrinfo(void *, void *, va_list); +#endif + +static int res_queryN(const char *, struct res_target *, res_state); +static int res_searchN(const char *, struct res_target *, res_state); +static int res_querydomainN(const char *, const char *, + struct res_target *, res_state); + +/* XXX macros that make external reference is BAD. */ + +#define GET_AI(ai, afd, addr) \ +do { \ + /* external reference: pai, error, and label free */ \ + (ai) = get_ai(pai, (afd), (addr)); \ + if ((ai) == NULL) { \ + error = EAI_MEMORY; \ + goto free; \ + } \ +} while (/*CONSTCOND*/0) + +#define GET_PORT(ai, serv) \ +do { \ + /* external reference: error and label free */ \ + error = get_port((ai), (serv), 0); \ + if (error != 0) \ + goto free; \ +} while (/*CONSTCOND*/0) + +#define GET_CANONNAME(ai, str) \ +do { \ + /* external reference: pai, error and label free */ \ + error = get_canonname(pai, (ai), (str)); \ + if (error != 0) \ + goto free; \ +} while (/*CONSTCOND*/0) + +#define ERR(err) \ +do { \ + /* external reference: error, and label bad */ \ + error = (err); \ + goto bad; \ + /*NOTREACHED*/ \ +} while (/*CONSTCOND*/0) + +#define MATCH_FAMILY(x, y, w) \ + ((x) == (y) || (/*CONSTCOND*/(w) && ((x) == PF_UNSPEC || (y) == PF_UNSPEC))) +#define MATCH(x, y, w) \ + ((x) == (y) || (/*CONSTCOND*/(w) && ((x) == ANY || (y) == ANY))) + +void +freeaddrinfo(struct addrinfo *ai) +{ + struct addrinfo *next; + + do { + next = ai->ai_next; + if (ai->ai_canonname) + free(ai->ai_canonname); + /* no need to free(ai->ai_addr) */ + free(ai); + ai = next; + } while (ai); +} + +static int +str2number(const char *p, int *portp) +{ + char *ep; + unsigned long v; + + if (*p == '\0') + return -1; + ep = NULL; + errno = 0; + v = strtoul(p, &ep, 10); + if (errno == 0 && ep && *ep == '\0' && v <= UINT_MAX) { + *portp = v; + return 0; + } else + return -1; +} + +int +getaddrinfo(const char *hostname, const char *servname, + const struct addrinfo *hints, struct addrinfo **res) +{ + struct addrinfo sentinel; + struct addrinfo *cur; + int error = 0; + struct addrinfo ai; + struct addrinfo ai0; + struct addrinfo *pai; + const struct explore *ex; + int numeric = 0; + + memset(&sentinel, 0, sizeof(sentinel)); + cur = &sentinel; + pai = &ai; + pai->ai_flags = 0; + pai->ai_family = PF_UNSPEC; + pai->ai_socktype = ANY; + pai->ai_protocol = ANY; + pai->ai_addrlen = 0; + pai->ai_canonname = NULL; + pai->ai_addr = NULL; + pai->ai_next = NULL; + + if (hostname == NULL && servname == NULL) + return EAI_NONAME; + if (hints) { + /* error check for hints */ + if (hints->ai_addrlen || hints->ai_canonname || + hints->ai_addr || hints->ai_next) + ERR(EAI_BADHINTS); /* xxx */ + if (hints->ai_flags & ~AI_MASK) + ERR(EAI_BADFLAGS); + switch (hints->ai_family) { + case PF_UNSPEC: + case PF_INET: +#ifdef INET6 + case PF_INET6: +#endif + break; + default: + ERR(EAI_FAMILY); + } + memcpy(pai, hints, sizeof(*pai)); + + /* + * if both socktype/protocol are specified, check if they + * are meaningful combination. + */ + if (pai->ai_socktype != ANY && pai->ai_protocol != ANY) { + for (ex = explore; ex->e_af >= 0; ex++) { + if (pai->ai_family != ex->e_af) + continue; + if (ex->e_socktype == ANY) + continue; + if (ex->e_protocol == ANY) + continue; + if (pai->ai_socktype == ex->e_socktype && + pai->ai_protocol != ex->e_protocol) { + ERR(EAI_BADHINTS); + } + } + } + } + + /* + * post-2553: AI_ALL and AI_V4MAPPED are effective only against + * AF_INET6 query. They need to be ignored if specified in other + * occassions. + */ + switch (pai->ai_flags & (AI_ALL | AI_V4MAPPED)) { + case AI_V4MAPPED: + case AI_ALL | AI_V4MAPPED: + if (pai->ai_family != AF_INET6) + pai->ai_flags &= ~(AI_ALL | AI_V4MAPPED); + break; + case AI_ALL: +#if 1 + /* illegal */ + ERR(EAI_BADFLAGS); +#else + pai->ai_flags &= ~(AI_ALL | AI_V4MAPPED); +#endif + break; + } + + /* + * check for special cases. (1) numeric servname is disallowed if + * socktype/protocol are left unspecified. (2) servname is disallowed + * for raw and other inet{,6} sockets. + */ + if (MATCH_FAMILY(pai->ai_family, PF_INET, 1) +#ifdef PF_INET6 + || MATCH_FAMILY(pai->ai_family, PF_INET6, 1) +#endif + ) { + ai0 = *pai; /* backup *pai */ + + if (pai->ai_family == PF_UNSPEC) { +#ifdef PF_INET6 + pai->ai_family = PF_INET6; +#else + pai->ai_family = PF_INET; +#endif + } + error = get_portmatch(pai, servname); + if (error) + ERR(error); + + *pai = ai0; + } + + ai0 = *pai; + + /* NULL hostname, or numeric hostname */ + for (ex = explore; ex->e_af >= 0; ex++) { + *pai = ai0; + + /* PF_UNSPEC entries are prepared for DNS queries only */ + if (ex->e_af == PF_UNSPEC) + continue; + + if (!MATCH_FAMILY(pai->ai_family, ex->e_af, WILD_AF(ex))) + continue; + if (!MATCH(pai->ai_socktype, ex->e_socktype, WILD_SOCKTYPE(ex))) + continue; + if (!MATCH(pai->ai_protocol, ex->e_protocol, WILD_PROTOCOL(ex))) + continue; + + if (pai->ai_family == PF_UNSPEC) + pai->ai_family = ex->e_af; + if (pai->ai_socktype == ANY && ex->e_socktype != ANY) + pai->ai_socktype = ex->e_socktype; + if (pai->ai_protocol == ANY && ex->e_protocol != ANY) + pai->ai_protocol = ex->e_protocol; + + if (hostname == NULL) + error = explore_null(pai, servname, &cur->ai_next); + else + error = explore_numeric_scope(pai, hostname, servname, + &cur->ai_next); + + if (error) + goto free; + + while (cur && cur->ai_next) + cur = cur->ai_next; + } + + /* + * XXX + * If numreic representation of AF1 can be interpreted as FQDN + * representation of AF2, we need to think again about the code below. + */ + if (sentinel.ai_next) { + numeric = 1; + goto good; + } + + if (hostname == NULL) + ERR(EAI_NONAME); /* used to be EAI_NODATA */ + if (pai->ai_flags & AI_NUMERICHOST) + ERR(EAI_NONAME); + + if ((pai->ai_flags & AI_ADDRCONFIG) != 0 && !addrconfig(&ai0)) + ERR(EAI_FAIL); + + /* + * hostname as alphabetical name. + * we would like to prefer AF_INET6 than AF_INET, so we'll make a + * outer loop by AFs. + */ + for (ex = explore; ex->e_af >= 0; ex++) { + *pai = ai0; + + /* require exact match for family field */ + if (pai->ai_family != ex->e_af) + continue; + + if (!MATCH(pai->ai_socktype, ex->e_socktype, + WILD_SOCKTYPE(ex))) { + continue; + } + if (!MATCH(pai->ai_protocol, ex->e_protocol, + WILD_PROTOCOL(ex))) { + continue; + } + + if (pai->ai_socktype == ANY && ex->e_socktype != ANY) + pai->ai_socktype = ex->e_socktype; + if (pai->ai_protocol == ANY && ex->e_protocol != ANY) + pai->ai_protocol = ex->e_protocol; + + error = explore_fqdn(pai, hostname, servname, + &cur->ai_next); + + while (cur && cur->ai_next) + cur = cur->ai_next; + } + + /* XXX inhibit errors if we have the result */ + if (sentinel.ai_next) + error = 0; + +good: + /* + * ensure we return either: + * - error == 0, non-NULL *res + * - error != 0, NULL *res + */ + if (error == 0) { + if (sentinel.ai_next) { + /* + * If the returned entry is for an active connection, + * and the given name is not numeric, reorder the + * list, so that the application would try the list + * in the most efficient order. + */ + if (hints == NULL || !(hints->ai_flags & AI_PASSIVE)) { + if (!numeric) + (void)reorder(&sentinel); + } + *res = sentinel.ai_next; + return SUCCESS; + } else + error = EAI_FAIL; + } +free: +bad: + if (sentinel.ai_next) + freeaddrinfo(sentinel.ai_next); + *res = NULL; + return error; +} + +static int +reorder(struct addrinfo *sentinel) +{ + struct addrinfo *ai, **aip; + struct ai_order *aio; + int i, n; + struct policyhead policyhead; + + /* count the number of addrinfo elements for sorting. */ + for (n = 0, ai = sentinel->ai_next; ai != NULL; ai = ai->ai_next, n++) + ; + + /* + * If the number is small enough, we can skip the reordering process. + */ + if (n <= 1) + return(n); + + /* allocate a temporary array for sort and initialization of it. */ + if ((aio = malloc(sizeof(*aio) * n)) == NULL) + return(n); /* give up reordering */ + memset(aio, 0, sizeof(*aio) * n); + + /* retrieve address selection policy from the kernel */ + TAILQ_INIT(&policyhead); + if (!get_addrselectpolicy(&policyhead)) { + /* no policy is installed into kernel, we don't sort. */ + free(aio); + return (n); + } + + for (i = 0, ai = sentinel->ai_next; i < n; ai = ai->ai_next, i++) { + aio[i].aio_ai = ai; + aio[i].aio_dstscope = gai_addr2scopetype(ai->ai_addr); + aio[i].aio_dstpolicy = match_addrselectpolicy(ai->ai_addr, + &policyhead); + set_source(&aio[i], &policyhead); + } + + /* perform sorting. */ + qsort(aio, n, sizeof(*aio), comp_dst); + + /* reorder the addrinfo chain. */ + for (i = 0, aip = &sentinel->ai_next; i < n; i++) { + *aip = aio[i].aio_ai; + aip = &aio[i].aio_ai->ai_next; + } + *aip = NULL; + + /* cleanup and return */ + free(aio); + free_addrselectpolicy(&policyhead); + return(n); +} + +static int +get_addrselectpolicy(struct policyhead *head) +{ +#ifdef INET6 + int mib[] = { CTL_NET, PF_INET6, IPPROTO_IPV6, IPV6CTL_ADDRCTLPOLICY }; + size_t l; + char *buf; + struct in6_addrpolicy *pol, *ep; + + if (sysctl(mib, sizeof(mib) / sizeof(mib[0]), NULL, &l, NULL, 0) < 0) + return (0); + if ((buf = malloc(l)) == NULL) + return (0); + if (sysctl(mib, sizeof(mib) / sizeof(mib[0]), buf, &l, NULL, 0) < 0) { + free(buf); + return (0); + } + + ep = (struct in6_addrpolicy *)(buf + l); + for (pol = (struct in6_addrpolicy *)buf; pol + 1 <= ep; pol++) { + struct policyqueue *new; + + if ((new = malloc(sizeof(*new))) == NULL) { + free_addrselectpolicy(head); /* make the list empty */ + break; + } + new->pc_policy = *pol; + TAILQ_INSERT_TAIL(head, new, pc_entry); + } + + free(buf); + return (1); +#else + return (0); +#endif +} + +static void +free_addrselectpolicy(struct policyhead *head) +{ + struct policyqueue *ent, *nent; + + for (ent = TAILQ_FIRST(head); ent; ent = nent) { + nent = TAILQ_NEXT(ent, pc_entry); + TAILQ_REMOVE(head, ent, pc_entry); + free(ent); + } +} + +static struct policyqueue * +match_addrselectpolicy(struct sockaddr *addr, struct policyhead *head) +{ +#ifdef INET6 + struct policyqueue *ent, *bestent = NULL; + struct in6_addrpolicy *pol; + int matchlen, bestmatchlen = -1; + u_char *mp, *ep, *k, *p, m; + struct sockaddr_in6 key; + + switch(addr->sa_family) { + case AF_INET6: + key = *(struct sockaddr_in6 *)addr; + break; + case AF_INET: + /* convert the address into IPv4-mapped IPv6 address. */ + memset(&key, 0, sizeof(key)); + key.sin6_family = AF_INET6; + key.sin6_len = sizeof(key); + key.sin6_addr.s6_addr[10] = 0xff; + key.sin6_addr.s6_addr[11] = 0xff; + memcpy(&key.sin6_addr.s6_addr[12], + &((struct sockaddr_in *)addr)->sin_addr, 4); + break; + default: + return(NULL); + } + + for (ent = TAILQ_FIRST(head); ent; ent = TAILQ_NEXT(ent, pc_entry)) { + pol = &ent->pc_policy; + matchlen = 0; + + mp = (u_char *)&pol->addrmask.sin6_addr; + ep = mp + 16; /* XXX: scope field? */ + k = (u_char *)&key.sin6_addr; + p = (u_char *)&pol->addr.sin6_addr; + for (; mp < ep && *mp; mp++, k++, p++) { + m = *mp; + if ((*k & m) != *p) + goto next; /* not match */ + if (m == 0xff) /* short cut for a typical case */ + matchlen += 8; + else { + while (m >= 0x80) { + matchlen++; + m <<= 1; + } + } + } + + /* matched. check if this is better than the current best. */ + if (matchlen > bestmatchlen) { + bestent = ent; + bestmatchlen = matchlen; + } + + next: + continue; + } + + return(bestent); +#else + return(NULL); +#endif + +} + +static void +set_source(struct ai_order *aio, struct policyhead *ph) +{ + struct addrinfo ai = *aio->aio_ai; + struct sockaddr_storage ss; + socklen_t srclen; + int s; + + /* set unspec ("no source is available"), just in case */ + aio->aio_srcsa.sa_family = AF_UNSPEC; + aio->aio_srcscope = -1; + + switch(ai.ai_family) { + case AF_INET: +#ifdef INET6 + case AF_INET6: +#endif + break; + default: /* ignore unsupported AFs explicitly */ + return; + } + + /* XXX: make a dummy addrinfo to call connect() */ + ai.ai_socktype = SOCK_DGRAM; + ai.ai_protocol = IPPROTO_UDP; /* is UDP too specific? */ + ai.ai_next = NULL; + memset(&ss, 0, sizeof(ss)); + memcpy(&ss, ai.ai_addr, ai.ai_addrlen); + ai.ai_addr = (struct sockaddr *)&ss; + get_port(&ai, "1", 0); + + /* open a socket to get the source address for the given dst */ + if ((s = _socket(ai.ai_family, ai.ai_socktype, ai.ai_protocol)) < 0) + return; /* give up */ + if (_connect(s, ai.ai_addr, ai.ai_addrlen) < 0) + goto cleanup; + srclen = ai.ai_addrlen; + if (_getsockname(s, &aio->aio_srcsa, &srclen) < 0) { + aio->aio_srcsa.sa_family = AF_UNSPEC; + goto cleanup; + } + aio->aio_srcscope = gai_addr2scopetype(&aio->aio_srcsa); + aio->aio_srcpolicy = match_addrselectpolicy(&aio->aio_srcsa, ph); + aio->aio_matchlen = matchlen(&aio->aio_srcsa, aio->aio_ai->ai_addr); +#ifdef INET6 + if (ai.ai_family == AF_INET6) { + struct in6_ifreq ifr6; + uint32_t flags6; + + /* XXX: interface name should not be hardcoded */ + strncpy(ifr6.ifr_name, "lo0", sizeof(ifr6.ifr_name)); + memset(&ifr6, 0, sizeof(ifr6)); + memcpy(&ifr6.ifr_addr, ai.ai_addr, ai.ai_addrlen); + if (_ioctl(s, SIOCGIFAFLAG_IN6, &ifr6) == 0) { + flags6 = ifr6.ifr_ifru.ifru_flags6; + if ((flags6 & IN6_IFF_DEPRECATED)) + aio->aio_srcflag |= AIO_SRCFLAG_DEPRECATED; + } + } +#endif + + cleanup: + _close(s); + return; +} + +static int +matchlen(struct sockaddr *src, struct sockaddr *dst) +{ + int match = 0; + u_char *s, *d; + u_char *lim, r; + int addrlen; + + switch (src->sa_family) { +#ifdef INET6 + case AF_INET6: + s = (u_char *)&((struct sockaddr_in6 *)src)->sin6_addr; + d = (u_char *)&((struct sockaddr_in6 *)dst)->sin6_addr; + addrlen = sizeof(struct in6_addr); + lim = s + addrlen; + break; +#endif + case AF_INET: + s = (u_char *)&((struct sockaddr_in *)src)->sin_addr; + d = (u_char *)&((struct sockaddr_in *)dst)->sin_addr; + addrlen = sizeof(struct in_addr); + lim = s + addrlen; + break; + default: + return(0); + } + + while (s < lim) + if ((r = (*d++ ^ *s++)) != 0) { + while (r < addrlen * 8) { + match++; + r <<= 1; + } + break; + } else + match += 8; + return(match); +} + +static int +comp_dst(const void *arg1, const void *arg2) +{ + const struct ai_order *dst1 = arg1, *dst2 = arg2; + + /* + * Rule 1: Avoid unusable destinations. + * XXX: we currently do not consider if an appropriate route exists. + */ + if (dst1->aio_srcsa.sa_family != AF_UNSPEC && + dst2->aio_srcsa.sa_family == AF_UNSPEC) { + return(-1); + } + if (dst1->aio_srcsa.sa_family == AF_UNSPEC && + dst2->aio_srcsa.sa_family != AF_UNSPEC) { + return(1); + } + + /* Rule 2: Prefer matching scope. */ + if (dst1->aio_dstscope == dst1->aio_srcscope && + dst2->aio_dstscope != dst2->aio_srcscope) { + return(-1); + } + if (dst1->aio_dstscope != dst1->aio_srcscope && + dst2->aio_dstscope == dst2->aio_srcscope) { + return(1); + } + + /* Rule 3: Avoid deprecated addresses. */ + if (dst1->aio_srcsa.sa_family != AF_UNSPEC && + dst2->aio_srcsa.sa_family != AF_UNSPEC) { + if (!(dst1->aio_srcflag & AIO_SRCFLAG_DEPRECATED) && + (dst2->aio_srcflag & AIO_SRCFLAG_DEPRECATED)) { + return(-1); + } + if ((dst1->aio_srcflag & AIO_SRCFLAG_DEPRECATED) && + !(dst2->aio_srcflag & AIO_SRCFLAG_DEPRECATED)) { + return(1); + } + } + + /* Rule 4: Prefer home addresses. */ + /* XXX: not implemented yet */ + + /* Rule 5: Prefer matching label. */ +#ifdef INET6 + if (dst1->aio_srcpolicy && dst1->aio_dstpolicy && + dst1->aio_srcpolicy->pc_policy.label == + dst1->aio_dstpolicy->pc_policy.label && + (dst2->aio_srcpolicy == NULL || dst2->aio_dstpolicy == NULL || + dst2->aio_srcpolicy->pc_policy.label != + dst2->aio_dstpolicy->pc_policy.label)) { + return(-1); + } + if (dst2->aio_srcpolicy && dst2->aio_dstpolicy && + dst2->aio_srcpolicy->pc_policy.label == + dst2->aio_dstpolicy->pc_policy.label && + (dst1->aio_srcpolicy == NULL || dst1->aio_dstpolicy == NULL || + dst1->aio_srcpolicy->pc_policy.label != + dst1->aio_dstpolicy->pc_policy.label)) { + return(1); + } +#endif + + /* Rule 6: Prefer higher precedence. */ +#ifdef INET6 + if (dst1->aio_dstpolicy && + (dst2->aio_dstpolicy == NULL || + dst1->aio_dstpolicy->pc_policy.preced > + dst2->aio_dstpolicy->pc_policy.preced)) { + return(-1); + } + if (dst2->aio_dstpolicy && + (dst1->aio_dstpolicy == NULL || + dst2->aio_dstpolicy->pc_policy.preced > + dst1->aio_dstpolicy->pc_policy.preced)) { + return(1); + } +#endif + + /* Rule 7: Prefer native transport. */ + /* XXX: not implemented yet */ + + /* Rule 8: Prefer smaller scope. */ + if (dst1->aio_dstscope >= 0 && + dst1->aio_dstscope < dst2->aio_dstscope) { + return(-1); + } + if (dst2->aio_dstscope >= 0 && + dst2->aio_dstscope < dst1->aio_dstscope) { + return(1); + } + + /* + * Rule 9: Use longest matching prefix. + * We compare the match length in a same AF only. + */ + if (dst1->aio_ai->ai_addr->sa_family == + dst2->aio_ai->ai_addr->sa_family) { + if (dst1->aio_matchlen > dst2->aio_matchlen) { + return(-1); + } + if (dst1->aio_matchlen < dst2->aio_matchlen) { + return(1); + } + } + + /* Rule 10: Otherwise, leave the order unchanged. */ + return(-1); +} + +/* + * Copy from scope.c. + * XXX: we should standardize the functions and link them as standard + * library. + */ +static int +gai_addr2scopetype(struct sockaddr *sa) +{ +#ifdef INET6 + struct sockaddr_in6 *sa6; +#endif + struct sockaddr_in *sa4; + + switch(sa->sa_family) { +#ifdef INET6 + case AF_INET6: + sa6 = (struct sockaddr_in6 *)sa; + if (IN6_IS_ADDR_MULTICAST(&sa6->sin6_addr)) { + /* just use the scope field of the multicast address */ + return(sa6->sin6_addr.s6_addr[2] & 0x0f); + } + /* + * Unicast addresses: map scope type to corresponding scope + * value defined for multcast addresses. + * XXX: hardcoded scope type values are bad... + */ + if (IN6_IS_ADDR_LOOPBACK(&sa6->sin6_addr)) + return(1); /* node local scope */ + if (IN6_IS_ADDR_LINKLOCAL(&sa6->sin6_addr)) + return(2); /* link-local scope */ + if (IN6_IS_ADDR_SITELOCAL(&sa6->sin6_addr)) + return(5); /* site-local scope */ + return(14); /* global scope */ + break; +#endif + case AF_INET: + /* + * IPv4 pseudo scoping according to RFC 3484. + */ + sa4 = (struct sockaddr_in *)sa; + /* IPv4 autoconfiguration addresses have link-local scope. */ + if (((u_char *)&sa4->sin_addr)[0] == 169 && + ((u_char *)&sa4->sin_addr)[1] == 254) + return(2); + /* Private addresses have site-local scope. */ + if (((u_char *)&sa4->sin_addr)[0] == 10 || + (((u_char *)&sa4->sin_addr)[0] == 172 && + (((u_char *)&sa4->sin_addr)[1] & 0xf0) == 16) || + (((u_char *)&sa4->sin_addr)[0] == 192 && + ((u_char *)&sa4->sin_addr)[1] == 168)) + return(14); /* XXX: It should be 5 unless NAT */ + /* Loopback addresses have link-local scope. */ + if (((u_char *)&sa4->sin_addr)[0] == 127) + return(2); + return(14); + break; + default: + errno = EAFNOSUPPORT; /* is this a good error? */ + return(-1); + } +} + +/* + * hostname == NULL. + * passive socket -> anyaddr (0.0.0.0 or ::) + * non-passive socket -> localhost (127.0.0.1 or ::1) + */ +static int +explore_null(const struct addrinfo *pai, const char *servname, + struct addrinfo **res) +{ + int s; + const struct afd *afd; + struct addrinfo *ai; + int error; + + *res = NULL; + ai = NULL; + + /* + * filter out AFs that are not supported by the kernel + * XXX errno? + */ + s = _socket(pai->ai_family, SOCK_DGRAM, 0); + if (s < 0) { + if (errno != EMFILE) + return 0; + } else + _close(s); + + /* + * if the servname does not match socktype/protocol, ignore it. + */ + if (get_portmatch(pai, servname) != 0) + return 0; + + afd = find_afd(pai->ai_family); + if (afd == NULL) + return 0; + + if (pai->ai_flags & AI_PASSIVE) { + GET_AI(ai, afd, afd->a_addrany); + GET_PORT(ai, servname); + } else { + GET_AI(ai, afd, afd->a_loopback); + GET_PORT(ai, servname); + } + + *res = ai; + return 0; + +free: + if (ai != NULL) + freeaddrinfo(ai); + return error; +} + +/* + * numeric hostname + */ +static int +explore_numeric(const struct addrinfo *pai, const char *hostname, + const char *servname, struct addrinfo **res, const char *canonname) +{ + const struct afd *afd; + struct addrinfo *ai; + int error; + char pton[PTON_MAX]; + + *res = NULL; + ai = NULL; + + /* + * if the servname does not match socktype/protocol, ignore it. + */ + if (get_portmatch(pai, servname) != 0) + return 0; + + afd = find_afd(pai->ai_family); + if (afd == NULL) + return 0; + + switch (afd->a_af) { + case AF_INET: + /* + * RFC3493 requires getaddrinfo() to accept AF_INET formats + * that are accepted by inet_addr() and its family. The + * accepted forms includes the "classful" one, which inet_pton + * does not accept. So we need to separate the case for + * AF_INET. + */ + if (inet_aton(hostname, (struct in_addr *)pton) != 1) + return 0; + break; + default: + if (inet_pton(afd->a_af, hostname, pton) != 1) + return 0; + break; + } + + if (pai->ai_family == afd->a_af) { + GET_AI(ai, afd, pton); + GET_PORT(ai, servname); + if ((pai->ai_flags & AI_CANONNAME)) { + /* + * Set the numeric address itself as the canonical + * name, based on a clarification in RFC3493. + */ + GET_CANONNAME(ai, canonname); + } + } else { + /* + * XXX: This should not happen since we already matched the AF + * by find_afd. + */ + ERR(EAI_FAMILY); + } + + *res = ai; + return 0; + +free: +bad: + if (ai != NULL) + freeaddrinfo(ai); + return error; +} + +/* + * numeric hostname with scope + */ +static int +explore_numeric_scope(const struct addrinfo *pai, const char *hostname, + const char *servname, struct addrinfo **res) +{ +#if !defined(SCOPE_DELIMITER) || !defined(INET6) + return explore_numeric(pai, hostname, servname, res, hostname); +#else + const struct afd *afd; + struct addrinfo *cur; + int error; + char *cp, *hostname2 = NULL, *scope, *addr; + struct sockaddr_in6 *sin6; + + /* + * if the servname does not match socktype/protocol, ignore it. + */ + if (get_portmatch(pai, servname) != 0) + return 0; + + afd = find_afd(pai->ai_family); + if (afd == NULL) + return 0; + + if (!afd->a_scoped) + return explore_numeric(pai, hostname, servname, res, hostname); + + cp = strchr(hostname, SCOPE_DELIMITER); + if (cp == NULL) + return explore_numeric(pai, hostname, servname, res, hostname); + + /* + * Handle special case of + */ + hostname2 = strdup(hostname); + if (hostname2 == NULL) + return EAI_MEMORY; + /* terminate at the delimiter */ + hostname2[cp - hostname] = '\0'; + addr = hostname2; + scope = cp + 1; + + error = explore_numeric(pai, addr, servname, res, hostname); + if (error == 0) { + uint32_t scopeid; + + for (cur = *res; cur; cur = cur->ai_next) { + if (cur->ai_family != AF_INET6) + continue; + sin6 = (struct sockaddr_in6 *)(void *)cur->ai_addr; + if (ip6_str2scopeid(scope, sin6, &scopeid) == -1) { + free(hostname2); + return(EAI_NONAME); /* XXX: is return OK? */ + } + sin6->sin6_scope_id = scopeid; + } + } + + free(hostname2); + + return error; +#endif +} + +static int +get_canonname(const struct addrinfo *pai, struct addrinfo *ai, const char *str) +{ + if ((pai->ai_flags & AI_CANONNAME) != 0) { + ai->ai_canonname = strdup(str); + if (ai->ai_canonname == NULL) + return EAI_MEMORY; + } + return 0; +} + +static struct addrinfo * +get_ai(const struct addrinfo *pai, const struct afd *afd, const char *addr) +{ + char *p; + struct addrinfo *ai; +#ifdef FAITH + struct in6_addr faith_prefix; + char *fp_str; + int translate = 0; +#endif + +#ifdef FAITH + /* + * Transfrom an IPv4 addr into a special IPv6 addr format for + * IPv6->IPv4 translation gateway. (only TCP is supported now) + * + * +-----------------------------------+------------+ + * | faith prefix part (12 bytes) | embedded | + * | | IPv4 addr part (4 bytes) + * +-----------------------------------+------------+ + * + * faith prefix part is specified as ascii IPv6 addr format + * in environmental variable GAI. + * For FAITH to work correctly, routing to faith prefix must be + * setup toward a machine where a FAITH daemon operates. + * Also, the machine must enable some mechanizm + * (e.g. faith interface hack) to divert those packet with + * faith prefixed destination addr to user-land FAITH daemon. + */ + fp_str = getenv("GAI"); + if (fp_str && inet_pton(AF_INET6, fp_str, &faith_prefix) == 1 && + afd->a_af == AF_INET && pai->ai_socktype == SOCK_STREAM) { + uint32_t v4a; + u_int8_t v4a_top; + + memcpy(&v4a, addr, sizeof v4a); + v4a_top = v4a >> IN_CLASSA_NSHIFT; + if (!IN_MULTICAST(v4a) && !IN_EXPERIMENTAL(v4a) && + v4a_top != 0 && v4a != IN_LOOPBACKNET) { + afd = &afdl[N_INET6]; + memcpy(&faith_prefix.s6_addr[12], addr, + sizeof(struct in_addr)); + translate = 1; + } + } +#endif + + ai = (struct addrinfo *)malloc(sizeof(struct addrinfo) + + (afd->a_socklen)); + if (ai == NULL) + return NULL; + + memcpy(ai, pai, sizeof(struct addrinfo)); + ai->ai_addr = (struct sockaddr *)(void *)(ai + 1); + memset(ai->ai_addr, 0, (size_t)afd->a_socklen); + ai->ai_addr->sa_len = afd->a_socklen; + ai->ai_addrlen = afd->a_socklen; + ai->ai_addr->sa_family = ai->ai_family = afd->a_af; + p = (char *)(void *)(ai->ai_addr); +#ifdef FAITH + if (translate == 1) + memcpy(p + afd->a_off, &faith_prefix, (size_t)afd->a_addrlen); + else +#endif + memcpy(p + afd->a_off, addr, (size_t)afd->a_addrlen); + return ai; +} + +static int +get_portmatch(const struct addrinfo *ai, const char *servname) +{ + + /* get_port does not touch first argument when matchonly == 1. */ + /* LINTED const cast */ + return get_port((struct addrinfo *)ai, servname, 1); +} + +static int +get_port(struct addrinfo *ai, const char *servname, int matchonly) +{ + const char *proto; + struct servent *sp; + int port, error; + int allownumeric; + + if (servname == NULL) + return 0; + switch (ai->ai_family) { + case AF_INET: +#ifdef AF_INET6 + case AF_INET6: +#endif + break; + default: + return 0; + } + + switch (ai->ai_socktype) { + case SOCK_RAW: + return EAI_SERVICE; + case SOCK_DGRAM: + case SOCK_STREAM: + allownumeric = 1; + break; + case ANY: + allownumeric = 0; + break; + default: + return EAI_SOCKTYPE; + } + + error = str2number(servname, &port); + if (error == 0) { + if (!allownumeric) + return EAI_SERVICE; + if (port < 0 || port > 65535) + return EAI_SERVICE; + port = htons(port); + } else { + if (ai->ai_flags & AI_NUMERICSERV) + return EAI_NONAME; + switch (ai->ai_socktype) { + case SOCK_DGRAM: + proto = "udp"; + break; + case SOCK_STREAM: + proto = "tcp"; + break; + default: + proto = NULL; + break; + } + + if ((sp = getservbyname(servname, proto)) == NULL) + return EAI_SERVICE; + port = sp->s_port; + } + + if (!matchonly) { + switch (ai->ai_family) { + case AF_INET: + ((struct sockaddr_in *)(void *) + ai->ai_addr)->sin_port = port; + break; +#ifdef INET6 + case AF_INET6: + ((struct sockaddr_in6 *)(void *) + ai->ai_addr)->sin6_port = port; + break; +#endif + } + } + + return 0; +} + +static const struct afd * +find_afd(int af) +{ + const struct afd *afd; + + if (af == PF_UNSPEC) + return NULL; + for (afd = afdl; afd->a_af; afd++) { + if (afd->a_af == af) + return afd; + } + return NULL; +} + +/* + * post-2553: AI_ADDRCONFIG check. if we use getipnodeby* as backend, backend + * will take care of it. + * the semantics of AI_ADDRCONFIG is not defined well. we are not sure + * if the code is right or not. + * + * XXX PF_UNSPEC -> PF_INET6 + PF_INET mapping needs to be in sync with + * _dns_getaddrinfo. + */ +static int +addrconfig(struct addrinfo *pai) +{ + int s, af; + + /* + * TODO: + * Note that implementation dependent test for address + * configuration should be done everytime called + * (or apropriate interval), + * because addresses will be dynamically assigned or deleted. + */ + af = pai->ai_family; + if (af == AF_UNSPEC) { + if ((s = _socket(AF_INET6, SOCK_DGRAM, 0)) < 0) + af = AF_INET; + else { + _close(s); + if ((s = _socket(AF_INET, SOCK_DGRAM, 0)) < 0) + af = AF_INET6; + else + _close(s); + } + } + if (af != AF_UNSPEC) { + if ((s = _socket(af, SOCK_DGRAM, 0)) < 0) + return 0; + _close(s); + } + pai->ai_family = af; + return 1; +} + +#ifdef INET6 +/* convert a string to a scope identifier. XXX: IPv6 specific */ +static int +ip6_str2scopeid(char *scope, struct sockaddr_in6 *sin6, uint32_t *scopeid) +{ + u_long lscopeid; + struct in6_addr *a6; + char *ep; + + a6 = &sin6->sin6_addr; + + /* empty scopeid portion is invalid */ + if (*scope == '\0') + return -1; + + if (IN6_IS_ADDR_LINKLOCAL(a6) || IN6_IS_ADDR_MC_LINKLOCAL(a6)) { + /* + * We currently assume a one-to-one mapping between links + * and interfaces, so we simply use interface indices for + * like-local scopes. + */ + *scopeid = if_nametoindex(scope); + if (*scopeid == 0) + goto trynumeric; + return 0; + } + + /* still unclear about literal, allow numeric only - placeholder */ + if (IN6_IS_ADDR_SITELOCAL(a6) || IN6_IS_ADDR_MC_SITELOCAL(a6)) + goto trynumeric; + if (IN6_IS_ADDR_MC_ORGLOCAL(a6)) + goto trynumeric; + else + goto trynumeric; /* global */ + + /* try to convert to a numeric id as a last resort */ + trynumeric: + errno = 0; + lscopeid = strtoul(scope, &ep, 10); + *scopeid = (uint32_t)(lscopeid & 0xffffffffUL); + if (errno == 0 && ep && *ep == '\0' && *scopeid == lscopeid) + return 0; + else + return -1; +} +#endif + +/* + * FQDN hostname, DNS lookup + */ +static int +explore_fqdn(const struct addrinfo *pai, const char *hostname, + const char *servname, struct addrinfo **res) +{ + struct addrinfo *result; + struct addrinfo *cur; + int error = 0; + static const ns_dtab dtab[] = { + NS_FILES_CB(_files_getaddrinfo, NULL) + { NSSRC_DNS, _dns_getaddrinfo, NULL }, /* force -DHESIOD */ + NS_NIS_CB(_yp_getaddrinfo, NULL) + { 0 } + }; + + result = NULL; + + /* + * if the servname does not match socktype/protocol, ignore it. + */ + if (get_portmatch(pai, servname) != 0) + return 0; + + switch (_nsdispatch(&result, dtab, NSDB_HOSTS, "getaddrinfo", + default_dns_files, hostname, pai)) { + case NS_TRYAGAIN: + error = EAI_AGAIN; + goto free; + case NS_UNAVAIL: + error = EAI_FAIL; + goto free; + case NS_NOTFOUND: + error = EAI_NONAME; + goto free; + case NS_SUCCESS: + error = 0; + for (cur = result; cur; cur = cur->ai_next) { + GET_PORT(cur, servname); + /* canonname should be filled already */ + } + break; + } + + *res = result; + + return 0; + +free: + if (result) + freeaddrinfo(result); + return error; +} + +#ifdef DEBUG +static const char AskedForGot[] = + "gethostby*.getanswer: asked for \"%s\", got \"%s\""; +#endif + +static struct addrinfo * +getanswer(const querybuf *answer, int anslen, const char *qname, int qtype, + const struct addrinfo *pai, res_state res) +{ + struct addrinfo sentinel, *cur; + struct addrinfo ai; + const struct afd *afd; + char *canonname; + const HEADER *hp; + const u_char *cp; + int n; + const u_char *eom; + char *bp, *ep; + int type, class, ancount, qdcount; + int haveanswer, had_error; + char tbuf[MAXDNAME]; + int (*name_ok)(const char *); + char hostbuf[8*1024]; + + memset(&sentinel, 0, sizeof(sentinel)); + cur = &sentinel; + + canonname = NULL; + eom = answer->buf + anslen; + switch (qtype) { + case T_A: + case T_AAAA: + case T_ANY: /*use T_ANY only for T_A/T_AAAA lookup*/ + name_ok = res_hnok; + break; + default: + return (NULL); /* XXX should be abort(); */ + } + /* + * find first satisfactory answer + */ + hp = &answer->hdr; + ancount = ntohs(hp->ancount); + qdcount = ntohs(hp->qdcount); + bp = hostbuf; + ep = hostbuf + sizeof hostbuf; + cp = answer->buf + HFIXEDSZ; + if (qdcount != 1) { + RES_SET_H_ERRNO(res, NO_RECOVERY); + return (NULL); + } + n = dn_expand(answer->buf, eom, cp, bp, ep - bp); + if ((n < 0) || !(*name_ok)(bp)) { + RES_SET_H_ERRNO(res, NO_RECOVERY); + return (NULL); + } + cp += n + QFIXEDSZ; + if (qtype == T_A || qtype == T_AAAA || qtype == T_ANY) { + /* res_send() has already verified that the query name is the + * same as the one we sent; this just gets the expanded name + * (i.e., with the succeeding search-domain tacked on). + */ + n = strlen(bp) + 1; /* for the \0 */ + if (n >= MAXHOSTNAMELEN) { + RES_SET_H_ERRNO(res, NO_RECOVERY); + return (NULL); + } + canonname = bp; + bp += n; + /* The qname can be abbreviated, but h_name is now absolute. */ + qname = canonname; + } + haveanswer = 0; + had_error = 0; + while (ancount-- > 0 && cp < eom && !had_error) { + n = dn_expand(answer->buf, eom, cp, bp, ep - bp); + if ((n < 0) || !(*name_ok)(bp)) { + had_error++; + continue; + } + cp += n; /* name */ + type = _getshort(cp); + cp += INT16SZ; /* type */ + class = _getshort(cp); + cp += INT16SZ + INT32SZ; /* class, TTL */ + n = _getshort(cp); + cp += INT16SZ; /* len */ + if (class != C_IN) { + /* XXX - debug? syslog? */ + cp += n; + continue; /* XXX - had_error++ ? */ + } + if ((qtype == T_A || qtype == T_AAAA || qtype == T_ANY) && + type == T_CNAME) { + n = dn_expand(answer->buf, eom, cp, tbuf, sizeof tbuf); + if ((n < 0) || !(*name_ok)(tbuf)) { + had_error++; + continue; + } + cp += n; + /* Get canonical name. */ + n = strlen(tbuf) + 1; /* for the \0 */ + if (n > ep - bp || n >= MAXHOSTNAMELEN) { + had_error++; + continue; + } + strlcpy(bp, tbuf, ep - bp); + canonname = bp; + bp += n; + continue; + } + if (qtype == T_ANY) { + if (!(type == T_A || type == T_AAAA)) { + cp += n; + continue; + } + } else if (type != qtype) { +#ifdef DEBUG + if (type != T_KEY && type != T_SIG) + syslog(LOG_NOTICE|LOG_AUTH, + "gethostby*.getanswer: asked for \"%s %s %s\", got type \"%s\"", + qname, p_class(C_IN), p_type(qtype), + p_type(type)); +#endif + cp += n; + continue; /* XXX - had_error++ ? */ + } + switch (type) { + case T_A: + case T_AAAA: + if (strcasecmp(canonname, bp) != 0) { +#ifdef DEBUG + syslog(LOG_NOTICE|LOG_AUTH, + AskedForGot, canonname, bp); +#endif + cp += n; + continue; /* XXX - had_error++ ? */ + } + if (type == T_A && n != INADDRSZ) { + cp += n; + continue; + } + if (type == T_AAAA && n != IN6ADDRSZ) { + cp += n; + continue; + } +#ifdef FILTER_V4MAPPED + if (type == T_AAAA) { + struct in6_addr in6; + memcpy(&in6, cp, sizeof(in6)); + if (IN6_IS_ADDR_V4MAPPED(&in6)) { + cp += n; + continue; + } + } +#endif + if (!haveanswer) { + int nn; + + canonname = bp; + nn = strlen(bp) + 1; /* for the \0 */ + bp += nn; + } + + /* don't overwrite pai */ + ai = *pai; + ai.ai_family = (type == T_A) ? AF_INET : AF_INET6; + afd = find_afd(ai.ai_family); + if (afd == NULL) { + cp += n; + continue; + } + cur->ai_next = get_ai(&ai, afd, (const char *)cp); + if (cur->ai_next == NULL) + had_error++; + while (cur && cur->ai_next) + cur = cur->ai_next; + cp += n; + break; + default: + abort(); + } + if (!had_error) + haveanswer++; + } + if (haveanswer) { +#if defined(RESOLVSORT) + /* + * We support only IPv4 address for backward + * compatibility against gethostbyname(3). + */ + if (res->nsort && qtype == T_A) { + if (addr4sort(&sentinel, res) < 0) { + freeaddrinfo(sentinel.ai_next); + RES_SET_H_ERRNO(res, NO_RECOVERY); + return NULL; + } + } +#endif /*RESOLVSORT*/ + if (!canonname) + (void)get_canonname(pai, sentinel.ai_next, qname); + else + (void)get_canonname(pai, sentinel.ai_next, canonname); + RES_SET_H_ERRNO(res, NETDB_SUCCESS); + return sentinel.ai_next; + } + + RES_SET_H_ERRNO(res, NO_RECOVERY); + return NULL; +} + +#ifdef RESOLVSORT +struct addr_ptr { + struct addrinfo *ai; + int aval; +}; + +static int +addr4sort(struct addrinfo *sentinel, res_state res) +{ + struct addrinfo *ai; + struct addr_ptr *addrs, addr; + struct sockaddr_in *sin; + int naddrs, i, j; + int needsort = 0; + + if (!sentinel) + return -1; + naddrs = 0; + for (ai = sentinel->ai_next; ai; ai = ai->ai_next) + naddrs++; + if (naddrs < 2) + return 0; /* We don't need sorting. */ + if ((addrs = malloc(sizeof(struct addr_ptr) * naddrs)) == NULL) + return -1; + i = 0; + for (ai = sentinel->ai_next; ai; ai = ai->ai_next) { + sin = (struct sockaddr_in *)ai->ai_addr; + for (j = 0; (unsigned)j < res->nsort; j++) { + if (res->sort_list[j].addr.s_addr == + (sin->sin_addr.s_addr & res->sort_list[j].mask)) + break; + } + addrs[i].ai = ai; + addrs[i].aval = j; + if (needsort == 0 && i > 0 && j < addrs[i - 1].aval) + needsort = i; + i++; + } + if (!needsort) { + free(addrs); + return 0; + } + + while (needsort < naddrs) { + for (j = needsort - 1; j >= 0; j--) { + if (addrs[j].aval > addrs[j+1].aval) { + addr = addrs[j]; + addrs[j] = addrs[j + 1]; + addrs[j + 1] = addr; + } else + break; + } + needsort++; + } + + ai = sentinel; + for (i = 0; i < naddrs; ++i) { + ai->ai_next = addrs[i].ai; + ai = ai->ai_next; + } + ai->ai_next = NULL; + free(addrs); + return 0; +} +#endif /*RESOLVSORT*/ + +/*ARGSUSED*/ +static int +_dns_getaddrinfo(void *rv, void *cb_data, va_list ap) +{ + struct addrinfo *ai; + querybuf *buf, *buf2; + const char *hostname; + const struct addrinfo *pai; + struct addrinfo sentinel, *cur; + struct res_target q, q2; + res_state res; + + hostname = va_arg(ap, char *); + pai = va_arg(ap, const struct addrinfo *); + + memset(&q, 0, sizeof(q2)); + memset(&q2, 0, sizeof(q2)); + memset(&sentinel, 0, sizeof(sentinel)); + cur = &sentinel; + + buf = malloc(sizeof(*buf)); + if (!buf) { + RES_SET_H_ERRNO(res, NETDB_INTERNAL); + return NS_NOTFOUND; + } + buf2 = malloc(sizeof(*buf2)); + if (!buf2) { + free(buf); + RES_SET_H_ERRNO(res, NETDB_INTERNAL); + return NS_NOTFOUND; + } + + switch (pai->ai_family) { + case AF_UNSPEC: + q.name = hostname; + q.qclass = C_IN; + q.qtype = T_A; + q.answer = buf->buf; + q.anslen = sizeof(buf->buf); + q.next = &q2; + q2.name = hostname; + q2.qclass = C_IN; + q2.qtype = T_AAAA; + q2.answer = buf2->buf; + q2.anslen = sizeof(buf2->buf); + break; + case AF_INET: + q.name = hostname; + q.qclass = C_IN; + q.qtype = T_A; + q.answer = buf->buf; + q.anslen = sizeof(buf->buf); + break; + case AF_INET6: + q.name = hostname; + q.qclass = C_IN; + q.qtype = T_AAAA; + q.answer = buf->buf; + q.anslen = sizeof(buf->buf); + break; + default: + free(buf); + free(buf2); + return NS_UNAVAIL; + } + + res = __res_state(); + if ((res->options & RES_INIT) == 0 && res_ninit(res) == -1) { + RES_SET_H_ERRNO(res, NETDB_INTERNAL); + free(buf); + free(buf2); + return NS_NOTFOUND; + } + + if (res_searchN(hostname, &q, res) < 0) { + free(buf); + free(buf2); + return NS_NOTFOUND; + } + /* prefer IPv6 */ + if (q.next) { + ai = getanswer(buf2, q2.n, q2.name, q2.qtype, pai, res); + if (ai) { + cur->ai_next = ai; + while (cur && cur->ai_next) + cur = cur->ai_next; + } + } + ai = getanswer(buf, q.n, q.name, q.qtype, pai, res); + if (ai) + cur->ai_next = ai; + free(buf); + free(buf2); + if (sentinel.ai_next == NULL) + switch (res->res_h_errno) { + case HOST_NOT_FOUND: + return NS_NOTFOUND; + case TRY_AGAIN: + return NS_TRYAGAIN; + default: + return NS_UNAVAIL; + } + *((struct addrinfo **)rv) = sentinel.ai_next; + return NS_SUCCESS; +} + +static void +_sethtent(FILE **hostf) +{ + if (!*hostf) + *hostf = fopen(_PATH_HOSTS, "r"); + else + rewind(*hostf); +} + +static void +_endhtent(FILE **hostf) +{ + if (*hostf) { + (void) fclose(*hostf); + *hostf = NULL; + } +} + +static struct addrinfo * +_gethtent(FILE **hostf, const char *name, const struct addrinfo *pai) +{ + char *p; + char *cp, *tname, *cname; + struct addrinfo hints, *res0, *res; + int error; + const char *addr; + char hostbuf[8*1024]; + + if (!*hostf && !(*hostf = fopen(_PATH_HOSTS, "r"))) + return (NULL); +again: + if (!(p = fgets(hostbuf, sizeof hostbuf, *hostf))) + return (NULL); + if (*p == '#') + goto again; + cp = strpbrk(p, "#\n"); + if (cp != NULL) + *cp = '\0'; + if (!(cp = strpbrk(p, " \t"))) + goto again; + *cp++ = '\0'; + addr = p; + cname = NULL; + /* if this is not something we're looking for, skip it. */ + while (cp && *cp) { + if (*cp == ' ' || *cp == '\t') { + cp++; + continue; + } + tname = cp; + if (cname == NULL) + cname = cp; + if ((cp = strpbrk(cp, " \t")) != NULL) + *cp++ = '\0'; + if (strcasecmp(name, tname) == 0) + goto found; + } + goto again; + +found: + /* we should not glob socktype/protocol here */ + memset(&hints, 0, sizeof(hints)); + hints.ai_family = pai->ai_family; + hints.ai_socktype = SOCK_DGRAM; + hints.ai_protocol = 0; + hints.ai_flags = AI_NUMERICHOST; + error = getaddrinfo(addr, "0", &hints, &res0); + if (error) + goto again; +#ifdef FILTER_V4MAPPED + /* XXX should check all items in the chain */ + if (res0->ai_family == AF_INET6 && + IN6_IS_ADDR_V4MAPPED(&((struct sockaddr_in6 *)res0->ai_addr)->sin6_addr)) { + freeaddrinfo(res0); + goto again; + } +#endif + for (res = res0; res; res = res->ai_next) { + /* cover it up */ + res->ai_flags = pai->ai_flags; + res->ai_socktype = pai->ai_socktype; + res->ai_protocol = pai->ai_protocol; + + if (pai->ai_flags & AI_CANONNAME) { + if (get_canonname(pai, res, cname) != 0) { + freeaddrinfo(res0); + goto again; + } + } + } + return res0; +} + +/*ARGSUSED*/ +static int +_files_getaddrinfo(void *rv, void *cb_data, va_list ap) +{ + const char *name; + const struct addrinfo *pai; + struct addrinfo sentinel, *cur; + struct addrinfo *p; + FILE *hostf = NULL; + + name = va_arg(ap, char *); + pai = va_arg(ap, struct addrinfo *); + + memset(&sentinel, 0, sizeof(sentinel)); + cur = &sentinel; + + _sethtent(&hostf); + while ((p = _gethtent(&hostf, name, pai)) != NULL) { + cur->ai_next = p; + while (cur && cur->ai_next) + cur = cur->ai_next; + } + _endhtent(&hostf); + + *((struct addrinfo **)rv) = sentinel.ai_next; + if (sentinel.ai_next == NULL) + return NS_NOTFOUND; + return NS_SUCCESS; +} + +#ifdef YP +/*ARGSUSED*/ +static struct addrinfo * +_yphostent(char *line, const struct addrinfo *pai) +{ + struct addrinfo sentinel, *cur; + struct addrinfo hints, *res, *res0; + int error; + char *p = line; + const char *addr, *canonname; + char *nextline; + char *cp; + + addr = canonname = NULL; + + memset(&sentinel, 0, sizeof(sentinel)); + cur = &sentinel; + +nextline: + /* terminate line */ + cp = strchr(p, '\n'); + if (cp) { + *cp++ = '\0'; + nextline = cp; + } else + nextline = NULL; + + cp = strpbrk(p, " \t"); + if (cp == NULL) { + if (canonname == NULL) + return (NULL); + else + goto done; + } + *cp++ = '\0'; + + addr = p; + + while (cp && *cp) { + if (*cp == ' ' || *cp == '\t') { + cp++; + continue; + } + if (!canonname) + canonname = cp; + if ((cp = strpbrk(cp, " \t")) != NULL) + *cp++ = '\0'; + } + + hints = *pai; + hints.ai_flags = AI_NUMERICHOST; + error = getaddrinfo(addr, NULL, &hints, &res0); + if (error == 0) { + for (res = res0; res; res = res->ai_next) { + /* cover it up */ + res->ai_flags = pai->ai_flags; + + if (pai->ai_flags & AI_CANONNAME) + (void)get_canonname(pai, res, canonname); + } + } else + res0 = NULL; + if (res0) { + cur->ai_next = res0; + while (cur && cur->ai_next) + cur = cur->ai_next; + } + + if (nextline) { + p = nextline; + goto nextline; + } + +done: + return sentinel.ai_next; +} + +/*ARGSUSED*/ +static int +_yp_getaddrinfo(void *rv, void *cb_data, va_list ap) +{ + struct addrinfo sentinel, *cur; + struct addrinfo *ai = NULL; + char *ypbuf; + int ypbuflen, r; + const char *name; + const struct addrinfo *pai; + char *ypdomain; + + if (_yp_check(&ypdomain) == 0) + return NS_UNAVAIL; + + name = va_arg(ap, char *); + pai = va_arg(ap, const struct addrinfo *); + + memset(&sentinel, 0, sizeof(sentinel)); + cur = &sentinel; + + /* hosts.byname is only for IPv4 (Solaris8) */ + if (pai->ai_family == PF_UNSPEC || pai->ai_family == PF_INET) { + r = yp_match(ypdomain, "hosts.byname", name, + (int)strlen(name), &ypbuf, &ypbuflen); + if (r == 0) { + struct addrinfo ai4; + + ai4 = *pai; + ai4.ai_family = AF_INET; + ai = _yphostent(ypbuf, &ai4); + if (ai) { + cur->ai_next = ai; + while (cur && cur->ai_next) + cur = cur->ai_next; + } + free(ypbuf); + } + } + + /* ipnodes.byname can hold both IPv4/v6 */ + r = yp_match(ypdomain, "ipnodes.byname", name, + (int)strlen(name), &ypbuf, &ypbuflen); + if (r == 0) { + ai = _yphostent(ypbuf, pai); + if (ai) + cur->ai_next = ai; + free(ypbuf); + } + + if (sentinel.ai_next == NULL) { + RES_SET_H_ERRNO(__res_state(), HOST_NOT_FOUND); + return NS_NOTFOUND; + } + *((struct addrinfo **)rv) = sentinel.ai_next; + return NS_SUCCESS; +} +#endif + +/* resolver logic */ + +/* + * Formulate a normal query, send, and await answer. + * Returned answer is placed in supplied buffer "answer". + * Perform preliminary check of answer, returning success only + * if no error is indicated and the answer count is nonzero. + * Return the size of the response on success, -1 on error. + * Error number is left in h_errno. + * + * Caller must parse answer and determine whether it answers the question. + */ +static int +res_queryN(const char *name, struct res_target *target, res_state res) +{ + u_char *buf; + HEADER *hp; + int n; + u_int oflags; + struct res_target *t; + int rcode; + int ancount; + + rcode = NOERROR; + ancount = 0; + + buf = malloc(MAXPACKET); + if (!buf) { + RES_SET_H_ERRNO(res, NETDB_INTERNAL); + return -1; + } + + for (t = target; t; t = t->next) { + int class, type; + u_char *answer; + int anslen; + + hp = (HEADER *)(void *)t->answer; + + /* make it easier... */ + class = t->qclass; + type = t->qtype; + answer = t->answer; + anslen = t->anslen; + + oflags = res->_flags; + +again: + hp->rcode = NOERROR; /* default */ + +#ifdef DEBUG + if (res->options & RES_DEBUG) + printf(";; res_query(%s, %d, %d)\n", name, class, type); +#endif + + n = res_nmkquery(res, QUERY, name, class, type, NULL, 0, NULL, + buf, MAXPACKET); + if (n > 0 && (res->_flags & RES_F_EDNS0ERR) == 0 && + (res->options & (RES_USE_EDNS0|RES_USE_DNSSEC)) != 0U) + n = res_nopt(res, n, buf, MAXPACKET, anslen); + if (n <= 0) { +#ifdef DEBUG + if (res->options & RES_DEBUG) + printf(";; res_query: mkquery failed\n"); +#endif + free(buf); + RES_SET_H_ERRNO(res, NO_RECOVERY); + return (n); + } + n = res_nsend(res, buf, n, answer, anslen); + if (n < 0) { + /* + * if the query choked with EDNS0, retry + * without EDNS0 + */ + if ((res->options & (RES_USE_EDNS0|RES_USE_DNSSEC)) + != 0U && + ((oflags ^ res->_flags) & RES_F_EDNS0ERR) != 0) { + res->_flags |= RES_F_EDNS0ERR; + if (res->options & RES_DEBUG) + printf(";; res_nquery: retry without EDNS0\n"); + goto again; + } + rcode = hp->rcode; /* record most recent error */ +#ifdef DEBUG + if (res->options & RES_DEBUG) + printf(";; res_query: send error\n"); +#endif + continue; + } + + if (n > anslen) + hp->rcode = FORMERR; /* XXX not very informative */ + if (hp->rcode != NOERROR || ntohs(hp->ancount) == 0) { + rcode = hp->rcode; /* record most recent error */ +#ifdef DEBUG + if (res->options & RES_DEBUG) + printf(";; rcode = %u, ancount=%u\n", hp->rcode, + ntohs(hp->ancount)); +#endif + continue; + } + + ancount += ntohs(hp->ancount); + + t->n = n; + } + + free(buf); + + if (ancount == 0) { + switch (rcode) { + case NXDOMAIN: + RES_SET_H_ERRNO(res, HOST_NOT_FOUND); + break; + case SERVFAIL: + RES_SET_H_ERRNO(res, TRY_AGAIN); + break; + case NOERROR: + RES_SET_H_ERRNO(res, NO_DATA); + break; + case FORMERR: + case NOTIMP: + case REFUSED: + default: + RES_SET_H_ERRNO(res, NO_RECOVERY); + break; + } + return (-1); + } + return (ancount); +} + +/* + * Formulate a normal query, send, and retrieve answer in supplied buffer. + * Return the size of the response on success, -1 on error. + * If enabled, implement search rules until answer or unrecoverable failure + * is detected. Error code, if any, is left in h_errno. + */ +static int +res_searchN(const char *name, struct res_target *target, res_state res) +{ + const char *cp, * const *domain; + HEADER *hp = (HEADER *)(void *)target->answer; /*XXX*/ + u_int dots; + int trailing_dot, ret, saved_herrno; + int got_nodata = 0, got_servfail = 0, root_on_list = 0; + int tried_as_is = 0; + int searched = 0; + char abuf[MAXDNAME]; + + errno = 0; + RES_SET_H_ERRNO(res, HOST_NOT_FOUND); /* default, if we never query */ + dots = 0; + for (cp = name; *cp; cp++) + dots += (*cp == '.'); + trailing_dot = 0; + if (cp > name && *--cp == '.') + trailing_dot++; + + /* + * if there aren't any dots, it could be a user-level alias + */ + if (!dots && + (cp = res_hostalias(res, name, abuf, sizeof(abuf))) != NULL) + return (res_queryN(cp, target, res)); + + /* + * If there are enough dots in the name, let's just give it a + * try 'as is'. The threshold can be set with the "ndots" option. + * Also, query 'as is', if there is a trailing dot in the name. + */ + saved_herrno = -1; + if (dots >= res->ndots || trailing_dot) { + ret = res_querydomainN(name, NULL, target, res); + if (ret > 0 || trailing_dot) + return (ret); + if (errno == ECONNREFUSED) { + RES_SET_H_ERRNO(res, TRY_AGAIN); + return (-1); + } + switch (res->res_h_errno) { + case NO_DATA: + case HOST_NOT_FOUND: + break; + case TRY_AGAIN: + if (hp->rcode == SERVFAIL) + break; + /* FALLTHROUGH */ + default: + return (-1); + } + saved_herrno = res->res_h_errno; + tried_as_is++; + } + + /* + * We do at least one level of search if + * - there is no dot and RES_DEFNAME is set, or + * - there is at least one dot, there is no trailing dot, + * and RES_DNSRCH is set. + */ + if ((!dots && (res->options & RES_DEFNAMES)) || + (dots && !trailing_dot && (res->options & RES_DNSRCH))) { + int done = 0; + + for (domain = (const char * const *)res->dnsrch; + *domain && !done; + domain++) { + searched = 1; + + if (domain[0][0] == '\0' || + (domain[0][0] == '.' && domain[0][1] == '\0')) + root_on_list++; + + if (root_on_list && tried_as_is) + continue; + + ret = res_querydomainN(name, *domain, target, res); + if (ret > 0) + return (ret); + + /* + * If no server present, give up. + * If name isn't found in this domain, + * keep trying higher domains in the search list + * (if that's enabled). + * On a NO_DATA error, keep trying, otherwise + * a wildcard entry of another type could keep us + * from finding this entry higher in the domain. + * If we get some other error (negative answer or + * server failure), then stop searching up, + * but try the input name below in case it's + * fully-qualified. + */ + if (errno == ECONNREFUSED) { + RES_SET_H_ERRNO(res, TRY_AGAIN); + return (-1); + } + + switch (res->res_h_errno) { + case NO_DATA: + got_nodata++; + /* FALLTHROUGH */ + case HOST_NOT_FOUND: + /* keep trying */ + break; + case TRY_AGAIN: + got_servfail++; + if (hp->rcode == SERVFAIL) { + /* try next search element, if any */ + break; + } + /* FALLTHROUGH */ + default: + /* anything else implies that we're done */ + done++; + } + /* + * if we got here for some reason other than DNSRCH, + * we only wanted one iteration of the loop, so stop. + */ + if (!(res->options & RES_DNSRCH)) + done++; + } + } + + switch (res->res_h_errno) { + case NO_DATA: + case HOST_NOT_FOUND: + break; + case TRY_AGAIN: + if (hp->rcode == SERVFAIL) + break; + /* FALLTHROUGH */ + default: + goto giveup; + } + + /* + * If the query has not already been tried as is then try it + * unless RES_NOTLDQUERY is set and there were no dots. + */ + if ((dots || !searched || !(res->options & RES_NOTLDQUERY)) && + !(tried_as_is || root_on_list)) { + ret = res_querydomainN(name, NULL, target, res); + if (ret > 0) + return (ret); + } + + /* + * if we got here, we didn't satisfy the search. + * if we did an initial full query, return that query's h_errno + * (note that we wouldn't be here if that query had succeeded). + * else if we ever got a nodata, send that back as the reason. + * else send back meaningless h_errno, that being the one from + * the last DNSRCH we did. + */ +giveup: + if (saved_herrno != -1) + RES_SET_H_ERRNO(res, saved_herrno); + else if (got_nodata) + RES_SET_H_ERRNO(res, NO_DATA); + else if (got_servfail) + RES_SET_H_ERRNO(res, TRY_AGAIN); + return (-1); +} + +/* + * Perform a call on res_query on the concatenation of name and domain, + * removing a trailing dot from name if domain is NULL. + */ +static int +res_querydomainN(const char *name, const char *domain, + struct res_target *target, res_state res) +{ + char nbuf[MAXDNAME]; + const char *longname = nbuf; + size_t n, d; + +#ifdef DEBUG + if (res->options & RES_DEBUG) + printf(";; res_querydomain(%s, %s)\n", + name, domain?domain:""); +#endif + if (domain == NULL) { + /* + * Check for trailing '.'; + * copy without '.' if present. + */ + n = strlen(name); + if (n >= MAXDNAME) { + RES_SET_H_ERRNO(res, NO_RECOVERY); + return (-1); + } + if (n > 0 && name[--n] == '.') { + strncpy(nbuf, name, n); + nbuf[n] = '\0'; + } else + longname = name; + } else { + n = strlen(name); + d = strlen(domain); + if (n + d + 1 >= MAXDNAME) { + RES_SET_H_ERRNO(res, NO_RECOVERY); + return (-1); + } + snprintf(nbuf, sizeof(nbuf), "%s.%s", name, domain); + } + return (res_queryN(longname, target, res)); +} diff --git a/lib/libc/net/gethostbydns.c b/lib/libc/net/gethostbydns.c new file mode 100644 index 0000000..5c3d578 --- /dev/null +++ b/lib/libc/net/gethostbydns.c @@ -0,0 +1,761 @@ +/* + * ++Copyright++ 1985, 1988, 1993 + * - + * Copyright (c) 1985, 1988, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * - + * Portions Copyright (c) 1993 by Digital Equipment Corporation. + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies, and that + * the name of Digital Equipment Corporation not be used in advertising or + * publicity pertaining to distribution of the document or software without + * specific, written prior permission. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL + * WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL DIGITAL EQUIPMENT + * CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL + * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR + * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS + * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS + * SOFTWARE. + * - + * --Copyright-- + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)gethostnamadr.c 8.1 (Berkeley) 6/4/93"; +static char fromrcsid[] = "From: Id: gethnamaddr.c,v 8.23 1998/04/07 04:59:46 vixie Exp $"; +#endif /* LIBC_SCCS and not lint */ +#include + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "netdb_private.h" +#include "res_config.h" + +#define SPRINTF(x) ((size_t)sprintf x) + +static const char AskedForGot[] = + "gethostby*.gethostanswer: asked for \"%s\", got \"%s\""; + +#ifdef RESOLVSORT +static void addrsort(char **, int, res_state); +#endif + +#ifdef DEBUG +static void dprintf(char *, int, res_state) __printflike(1, 0); +#endif + +#define MAXPACKET (64*1024) + +typedef union { + HEADER hdr; + u_char buf[MAXPACKET]; +} querybuf; + +typedef union { + int32_t al; + char ac; +} align; + +int _dns_ttl_; + +#ifdef DEBUG +static void +dprintf(msg, num, res) + char *msg; + int num; + res_state res; +{ + if (res->options & RES_DEBUG) { + int save = errno; + + printf(msg, num); + errno = save; + } +} +#else +# define dprintf(msg, num, res) /*nada*/ +#endif + +#define BOUNDED_INCR(x) \ + do { \ + cp += x; \ + if (cp > eom) { \ + RES_SET_H_ERRNO(statp, NO_RECOVERY); \ + return (-1); \ + } \ + } while (0) + +#define BOUNDS_CHECK(ptr, count) \ + do { \ + if ((ptr) + (count) > eom) { \ + RES_SET_H_ERRNO(statp, NO_RECOVERY); \ + return (-1); \ + } \ + } while (0) + +static int +gethostanswer(const querybuf *answer, int anslen, const char *qname, int qtype, + struct hostent *he, struct hostent_data *hed, res_state statp) +{ + const HEADER *hp; + const u_char *cp; + int n; + const u_char *eom, *erdata; + char *bp, *ep, **ap, **hap; + int type, class, ancount, qdcount; + int haveanswer, had_error; + int toobig = 0; + char tbuf[MAXDNAME]; + const char *tname; + int (*name_ok)(const char *); + + tname = qname; + he->h_name = NULL; + eom = answer->buf + anslen; + switch (qtype) { + case T_A: + case T_AAAA: + name_ok = res_hnok; + break; + case T_PTR: + name_ok = res_dnok; + break; + default: + RES_SET_H_ERRNO(statp, NO_RECOVERY); + return (-1); /* XXX should be abort(); */ + } + /* + * find first satisfactory answer + */ + hp = &answer->hdr; + ancount = ntohs(hp->ancount); + qdcount = ntohs(hp->qdcount); + bp = hed->hostbuf; + ep = hed->hostbuf + sizeof hed->hostbuf; + cp = answer->buf; + BOUNDED_INCR(HFIXEDSZ); + if (qdcount != 1) { + RES_SET_H_ERRNO(statp, NO_RECOVERY); + return (-1); + } + n = dn_expand(answer->buf, eom, cp, bp, ep - bp); + if ((n < 0) || !(*name_ok)(bp)) { + RES_SET_H_ERRNO(statp, NO_RECOVERY); + return (-1); + } + BOUNDED_INCR(n + QFIXEDSZ); + if (qtype == T_A || qtype == T_AAAA) { + /* res_send() has already verified that the query name is the + * same as the one we sent; this just gets the expanded name + * (i.e., with the succeeding search-domain tacked on). + */ + n = strlen(bp) + 1; /* for the \0 */ + if (n >= MAXHOSTNAMELEN) { + RES_SET_H_ERRNO(statp, NO_RECOVERY); + return (-1); + } + he->h_name = bp; + bp += n; + /* The qname can be abbreviated, but h_name is now absolute. */ + qname = he->h_name; + } + ap = hed->host_aliases; + *ap = NULL; + he->h_aliases = hed->host_aliases; + hap = hed->h_addr_ptrs; + *hap = NULL; + he->h_addr_list = hed->h_addr_ptrs; + haveanswer = 0; + had_error = 0; + _dns_ttl_ = -1; + while (ancount-- > 0 && cp < eom && !had_error) { + n = dn_expand(answer->buf, eom, cp, bp, ep - bp); + if ((n < 0) || !(*name_ok)(bp)) { + had_error++; + continue; + } + cp += n; /* name */ + BOUNDS_CHECK(cp, 3 * INT16SZ + INT32SZ); + type = _getshort(cp); + cp += INT16SZ; /* type */ + class = _getshort(cp); + cp += INT16SZ; /* class */ + if (qtype == T_A && type == T_A) + _dns_ttl_ = _getlong(cp); + cp += INT32SZ; /* TTL */ + n = _getshort(cp); + cp += INT16SZ; /* len */ + BOUNDS_CHECK(cp, n); + erdata = cp + n; + if (class != C_IN) { + /* XXX - debug? syslog? */ + cp += n; + continue; /* XXX - had_error++ ? */ + } + if ((qtype == T_A || qtype == T_AAAA) && type == T_CNAME) { + if (ap >= &hed->host_aliases[_MAXALIASES-1]) + continue; + n = dn_expand(answer->buf, eom, cp, tbuf, sizeof tbuf); + if ((n < 0) || !(*name_ok)(tbuf)) { + had_error++; + continue; + } + cp += n; + if (cp != erdata) { + RES_SET_H_ERRNO(statp, NO_RECOVERY); + return (-1); + } + /* Store alias. */ + *ap++ = bp; + n = strlen(bp) + 1; /* for the \0 */ + if (n >= MAXHOSTNAMELEN) { + had_error++; + continue; + } + bp += n; + /* Get canonical name. */ + n = strlen(tbuf) + 1; /* for the \0 */ + if (n > ep - bp || n >= MAXHOSTNAMELEN) { + had_error++; + continue; + } + strcpy(bp, tbuf); + he->h_name = bp; + bp += n; + continue; + } + if (qtype == T_PTR && type == T_CNAME) { + n = dn_expand(answer->buf, eom, cp, tbuf, sizeof tbuf); + if (n < 0 || !res_dnok(tbuf)) { + had_error++; + continue; + } + cp += n; + if (cp != erdata) { + RES_SET_H_ERRNO(statp, NO_RECOVERY); + return (-1); + } + /* Get canonical name. */ + n = strlen(tbuf) + 1; /* for the \0 */ + if (n > ep - bp || n >= MAXHOSTNAMELEN) { + had_error++; + continue; + } + strcpy(bp, tbuf); + tname = bp; + bp += n; + continue; + } + if (type != qtype) { + if (type != T_SIG) + syslog(LOG_NOTICE|LOG_AUTH, + "gethostby*.gethostanswer: asked for \"%s %s %s\", got type \"%s\"", + qname, p_class(C_IN), p_type(qtype), + p_type(type)); + cp += n; + continue; /* XXX - had_error++ ? */ + } + switch (type) { + case T_PTR: + if (strcasecmp(tname, bp) != 0) { + syslog(LOG_NOTICE|LOG_AUTH, + AskedForGot, qname, bp); + cp += n; + continue; /* XXX - had_error++ ? */ + } + n = dn_expand(answer->buf, eom, cp, bp, ep - bp); + if ((n < 0) || !res_hnok(bp)) { + had_error++; + break; + } +#if MULTI_PTRS_ARE_ALIASES + cp += n; + if (cp != erdata) { + RES_SET_H_ERRNO(statp, NO_RECOVERY); + return (-1); + } + if (!haveanswer) + he->h_name = bp; + else if (ap < &hed->host_aliases[_MAXALIASES-1]) + *ap++ = bp; + else + n = -1; + if (n != -1) { + n = strlen(bp) + 1; /* for the \0 */ + if (n >= MAXHOSTNAMELEN) { + had_error++; + break; + } + bp += n; + } + break; +#else + he->h_name = bp; + if (statp->options & RES_USE_INET6) { + n = strlen(bp) + 1; /* for the \0 */ + if (n >= MAXHOSTNAMELEN) { + had_error++; + break; + } + bp += n; + _map_v4v6_hostent(he, &bp, ep); + } + RES_SET_H_ERRNO(statp, NETDB_SUCCESS); + return (0); +#endif + case T_A: + case T_AAAA: + if (strcasecmp(he->h_name, bp) != 0) { + syslog(LOG_NOTICE|LOG_AUTH, + AskedForGot, he->h_name, bp); + cp += n; + continue; /* XXX - had_error++ ? */ + } + if (n != he->h_length) { + cp += n; + continue; + } + if (!haveanswer) { + int nn; + + he->h_name = bp; + nn = strlen(bp) + 1; /* for the \0 */ + bp += nn; + } + + bp += sizeof(align) - ((u_long)bp % sizeof(align)); + + if (bp + n >= ep) { + dprintf("size (%d) too big\n", n, statp); + had_error++; + continue; + } + if (hap >= &hed->h_addr_ptrs[_MAXADDRS-1]) { + if (!toobig++) + dprintf("Too many addresses (%d)\n", + _MAXADDRS, statp); + cp += n; + continue; + } + memcpy(*hap++ = bp, cp, n); + bp += n; + cp += n; + if (cp != erdata) { + RES_SET_H_ERRNO(statp, NO_RECOVERY); + return (-1); + } + break; + default: + dprintf("Impossible condition (type=%d)\n", type, + statp); + RES_SET_H_ERRNO(statp, NO_RECOVERY); + return (-1); + /* BIND has abort() here, too risky on bad data */ + } + if (!had_error) + haveanswer++; + } + if (haveanswer) { + *ap = NULL; + *hap = NULL; +# if defined(RESOLVSORT) + /* + * Note: we sort even if host can take only one address + * in its return structures - should give it the "best" + * address in that case, not some random one + */ + if (statp->nsort && haveanswer > 1 && qtype == T_A) + addrsort(hed->h_addr_ptrs, haveanswer, statp); +# endif /*RESOLVSORT*/ + if (!he->h_name) { + n = strlen(qname) + 1; /* for the \0 */ + if (n > ep - bp || n >= MAXHOSTNAMELEN) + goto no_recovery; + strcpy(bp, qname); + he->h_name = bp; + bp += n; + } + if (statp->options & RES_USE_INET6) + _map_v4v6_hostent(he, &bp, ep); + RES_SET_H_ERRNO(statp, NETDB_SUCCESS); + return (0); + } + no_recovery: + RES_SET_H_ERRNO(statp, NO_RECOVERY); + return (-1); +} + +/* XXX: for async DNS resolver in ypserv */ +struct hostent * +__dns_getanswer(const char *answer, int anslen, const char *qname, int qtype) +{ + struct hostent *he; + struct hostent_data *hed; + int error; + res_state statp; + + statp = __res_state(); + if ((he = __hostent_init()) == NULL || + (hed = __hostent_data_init()) == NULL) { + RES_SET_H_ERRNO(statp, NETDB_INTERNAL); + return (NULL); + } + switch (qtype) { + case T_AAAA: + he->h_addrtype = AF_INET6; + he->h_length = NS_IN6ADDRSZ; + break; + case T_A: + default: + he->h_addrtype = AF_INET; + he->h_length = NS_INADDRSZ; + break; + } + + error = gethostanswer((const querybuf *)answer, anslen, qname, qtype, + he, hed, statp); + return (error == 0) ? he : NULL; +} + +int +_dns_gethostbyname(void *rval, void *cb_data, va_list ap) +{ + const char *name; + int af; + char *buffer; + size_t buflen; + int *errnop, *h_errnop; + struct hostent *hptr, he; + struct hostent_data *hed; + querybuf *buf; + int n, type, error; + res_state statp; + + name = va_arg(ap, const char *); + af = va_arg(ap, int); + hptr = va_arg(ap, struct hostent *); + buffer = va_arg(ap, char *); + buflen = va_arg(ap, size_t); + errnop = va_arg(ap, int *); + h_errnop = va_arg(ap, int *); + + *((struct hostent **)rval) = NULL; + + statp = __res_state(); + if ((hed = __hostent_data_init()) == NULL) { + RES_SET_H_ERRNO(statp, NETDB_INTERNAL); + *h_errnop = statp->res_h_errno; + return (NS_NOTFOUND); + } + + he.h_addrtype = af; + switch (af) { + case AF_INET: + he.h_length = NS_INADDRSZ; + type = T_A; + break; + case AF_INET6: + he.h_length = NS_IN6ADDRSZ; + type = T_AAAA; + break; + default: + RES_SET_H_ERRNO(statp, NETDB_INTERNAL); + *h_errnop = statp->res_h_errno; + errno = EAFNOSUPPORT; + return (NS_UNAVAIL); + } + + if ((buf = malloc(sizeof(*buf))) == NULL) { + RES_SET_H_ERRNO(statp, NETDB_INTERNAL); + *h_errnop = statp->res_h_errno; + return (NS_NOTFOUND); + } + n = res_nsearch(statp, name, C_IN, type, buf->buf, sizeof(buf->buf)); + if (n < 0) { + free(buf); + dprintf("res_nsearch failed (%d)\n", n, statp); + *h_errnop = statp->res_h_errno; + return (0); + } else if (n > sizeof(buf->buf)) { + free(buf); + dprintf("static buffer is too small (%d)\n", n, statp); + *h_errnop = statp->res_h_errno; + return (0); + } + error = gethostanswer(buf, n, name, type, &he, hed, statp); + free(buf); + if (error != 0) { + *h_errnop = statp->res_h_errno; + return (NS_NOTFOUND); + } + if (__copy_hostent(&he, hptr, buffer, buflen) != 0) { + *h_errnop = statp->res_h_errno; + return (NS_NOTFOUND); + } + *((struct hostent **)rval) = hptr; + return (NS_SUCCESS); +} + +int +_dns_gethostbyaddr(void *rval, void *cb_data, va_list ap) +{ + const void *addr; + socklen_t len; + int af; + char *buffer; + size_t buflen; + int *errnop, *h_errnop; + const u_char *uaddr; + struct hostent *hptr, he; + struct hostent_data *hed; + int n; + querybuf *buf; + char qbuf[MAXDNAME+1], *qp; + res_state statp; +#ifdef SUNSECURITY + struct hostdata rhd; + struct hostent *rhe; + char **haddr; + u_long old_options; + char hname2[MAXDNAME+1], numaddr[46]; + int ret_h_error; +#endif /*SUNSECURITY*/ + + addr = va_arg(ap, const void *); + len = va_arg(ap, socklen_t); + af = va_arg(ap, int); + hptr = va_arg(ap, struct hostent *); + buffer = va_arg(ap, char *); + buflen = va_arg(ap, size_t); + errnop = va_arg(ap, int *); + h_errnop = va_arg(ap, int *); + uaddr = (const u_char *)addr; + + *((struct hostent **)rval) = NULL; + + statp = __res_state(); + if ((hed = __hostent_data_init()) == NULL) { + RES_SET_H_ERRNO(statp, NETDB_INTERNAL); + *h_errnop = statp->res_h_errno; + return (NS_NOTFOUND); + } + + switch (af) { + case AF_INET: + (void) sprintf(qbuf, "%u.%u.%u.%u.in-addr.arpa", + (uaddr[3] & 0xff), + (uaddr[2] & 0xff), + (uaddr[1] & 0xff), + (uaddr[0] & 0xff)); + break; + case AF_INET6: + qp = qbuf; + for (n = NS_IN6ADDRSZ - 1; n >= 0; n--) { + qp += SPRINTF((qp, "%x.%x.", + uaddr[n] & 0xf, + (uaddr[n] >> 4) & 0xf)); + } + strlcat(qbuf, "ip6.arpa", sizeof(qbuf)); + break; + default: + abort(); + } + if ((buf = malloc(sizeof(*buf))) == NULL) { + RES_SET_H_ERRNO(statp, NETDB_INTERNAL); + *h_errnop = statp->res_h_errno; + return NS_NOTFOUND; + } + n = res_nquery(statp, qbuf, C_IN, T_PTR, (u_char *)buf->buf, + sizeof buf->buf); + if (n < 0) { + free(buf); + dprintf("res_nquery failed (%d)\n", n, statp); + *h_errnop = statp->res_h_errno; + return (NS_UNAVAIL); + } + if (n > sizeof buf->buf) { + free(buf); + dprintf("static buffer is too small (%d)\n", n, statp); + *h_errnop = statp->res_h_errno; + return (NS_UNAVAIL); + } + if (gethostanswer(buf, n, qbuf, T_PTR, &he, hed, statp) != 0) { + free(buf); + *h_errnop = statp->res_h_errno; + return (NS_NOTFOUND); /* h_errno was set by gethostanswer() */ + } + free(buf); +#ifdef SUNSECURITY + if (af == AF_INET) { + /* + * turn off search as the name should be absolute, + * 'localhost' should be matched by defnames + */ + strncpy(hname2, he.h_name, MAXDNAME); + hname2[MAXDNAME] = '\0'; + old_options = statp->options; + statp->options &= ~RES_DNSRCH; + statp->options |= RES_DEFNAMES; + memset(&rhd, 0, sizeof rhd); + rhe = gethostbyname_r(hname2, &rhd.host, &rhd.data, + sizeof(rhd.data), &ret_h_error); + if (rhe == NULL) { + if (inet_ntop(af, addr, numaddr, sizeof(numaddr)) == NULL) + strlcpy(numaddr, "UNKNOWN", sizeof(numaddr)); + syslog(LOG_NOTICE|LOG_AUTH, + "gethostbyaddr: No A record for %s (verifying [%s])", + hname2, numaddr); + statp->options = old_options; + RES_SET_H_ERRNO(statp, HOST_NOT_FOUND); + *h_errnop = statp->res_h_errno; + return (NS_NOTFOUND); + } + statp->options = old_options; + for (haddr = rhe->h_addr_list; *haddr; haddr++) + if (!memcmp(*haddr, addr, NS_INADDRSZ)) + break; + if (!*haddr) { + if (inet_ntop(af, addr, numaddr, sizeof(numaddr)) == NULL) + strlcpy(numaddr, "UNKNOWN", sizeof(numaddr)); + syslog(LOG_NOTICE|LOG_AUTH, + "gethostbyaddr: A record of %s != PTR record [%s]", + hname2, numaddr); + RES_SET_H_ERRNO(statp, HOST_NOT_FOUND); + *h_errnop = statp->res_h_errno; + return (NS_NOTFOUND); + } + } +#endif /*SUNSECURITY*/ + he.h_addrtype = af; + he.h_length = len; + memcpy(hed->host_addr, uaddr, len); + hed->h_addr_ptrs[0] = (char *)hed->host_addr; + hed->h_addr_ptrs[1] = NULL; + if (af == AF_INET && (statp->options & RES_USE_INET6)) { + _map_v4v6_address((char*)hed->host_addr, (char*)hed->host_addr); + he.h_addrtype = AF_INET6; + he.h_length = NS_IN6ADDRSZ; + } + RES_SET_H_ERRNO(statp, NETDB_SUCCESS); + if (__copy_hostent(&he, hptr, buffer, buflen) != 0) { + *h_errnop = statp->res_h_errno; + return (NS_NOTFOUND); + } + *((struct hostent **)rval) = hptr; + return (NS_SUCCESS); +} + +#ifdef RESOLVSORT +static void +addrsort(char **ap, int num, res_state res) +{ + int i, j; + char **p; + short aval[_MAXADDRS]; + int needsort = 0; + + p = ap; + for (i = 0; i < num; i++, p++) { + for (j = 0 ; (unsigned)j < res->nsort; j++) + if (res->sort_list[j].addr.s_addr == + (((struct in_addr *)(*p))->s_addr & res->sort_list[j].mask)) + break; + aval[i] = j; + if (needsort == 0 && i > 0 && j < aval[i-1]) + needsort = i; + } + if (!needsort) + return; + + while (needsort < num) { + for (j = needsort - 1; j >= 0; j--) { + if (aval[j] > aval[j+1]) { + char *hp; + + i = aval[j]; + aval[j] = aval[j+1]; + aval[j+1] = i; + + hp = ap[j]; + ap[j] = ap[j+1]; + ap[j+1] = hp; + + } else + break; + } + needsort++; + } +} +#endif + +void +_sethostdnsent(int stayopen) +{ + res_state statp; + + statp = __res_state(); + if ((statp->options & RES_INIT) == 0 && res_ninit(statp) == -1) + return; + if (stayopen) + statp->options |= RES_STAYOPEN | RES_USEVC; +} + +void +_endhostdnsent() +{ + res_state statp; + + statp = __res_state(); + statp->options &= ~(RES_STAYOPEN | RES_USEVC); + res_nclose(statp); +} diff --git a/lib/libc/net/gethostbyht.c b/lib/libc/net/gethostbyht.c new file mode 100644 index 0000000..b3ea443 --- /dev/null +++ b/lib/libc/net/gethostbyht.c @@ -0,0 +1,334 @@ +/*- + * Copyright (c) 1985, 1988, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * - + * Portions Copyright (c) 1993 by Digital Equipment Corporation. + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies, and that + * the name of Digital Equipment Corporation not be used in advertising or + * publicity pertaining to distribution of the document or software without + * specific, written prior permission. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL + * WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL DIGITAL EQUIPMENT + * CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL + * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR + * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS + * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS + * SOFTWARE. + * - + * --Copyright-- + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)gethostnamadr.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include /* XXX */ +#include /* XXX */ +#include "netdb_private.h" + +void +_sethosthtent(int f, struct hostent_data *hed) +{ + if (!hed->hostf) + hed->hostf = fopen(_PATH_HOSTS, "r"); + else + rewind(hed->hostf); + hed->stayopen = f; +} + +void +_endhosthtent(struct hostent_data *hed) +{ + if (hed->hostf && !hed->stayopen) { + (void) fclose(hed->hostf); + hed->hostf = NULL; + } +} + +static int +gethostent_p(struct hostent *he, struct hostent_data *hed, int mapped, + res_state statp) +{ + char *p, *bp, *ep; + char *cp, **q; + int af, len; + char hostbuf[BUFSIZ + 1]; + + if (!hed->hostf && !(hed->hostf = fopen(_PATH_HOSTS, "r"))) { + RES_SET_H_ERRNO(statp, NETDB_INTERNAL); + return (-1); + } + again: + if (!(p = fgets(hostbuf, sizeof hostbuf, hed->hostf))) { + RES_SET_H_ERRNO(statp, HOST_NOT_FOUND); + return (-1); + } + if (*p == '#') + goto again; + cp = strpbrk(p, "#\n"); + if (cp != NULL) + *cp = '\0'; + if (!(cp = strpbrk(p, " \t"))) + goto again; + *cp++ = '\0'; + if (inet_pton(AF_INET6, p, hed->host_addr) > 0) { + af = AF_INET6; + len = IN6ADDRSZ; + } else if (inet_pton(AF_INET, p, hed->host_addr) > 0) { + if (mapped) { + _map_v4v6_address((char *)hed->host_addr, + (char *)hed->host_addr); + af = AF_INET6; + len = IN6ADDRSZ; + } else { + af = AF_INET; + len = INADDRSZ; + } + } else { + goto again; + } + hed->h_addr_ptrs[0] = (char *)hed->host_addr; + hed->h_addr_ptrs[1] = NULL; + he->h_addr_list = hed->h_addr_ptrs; + he->h_length = len; + he->h_addrtype = af; + while (*cp == ' ' || *cp == '\t') + cp++; + bp = hed->hostbuf; + ep = hed->hostbuf + sizeof hed->hostbuf; + he->h_name = bp; + q = he->h_aliases = hed->host_aliases; + if ((p = strpbrk(cp, " \t")) != NULL) + *p++ = '\0'; + len = strlen(cp) + 1; + if (ep - bp < len) { + RES_SET_H_ERRNO(statp, NO_RECOVERY); + return (-1); + } + strlcpy(bp, cp, ep - bp); + bp += len; + cp = p; + while (cp && *cp) { + if (*cp == ' ' || *cp == '\t') { + cp++; + continue; + } + if (q >= &hed->host_aliases[_MAXALIASES - 1]) + break; + if ((p = strpbrk(cp, " \t")) != NULL) + *p++ = '\0'; + len = strlen(cp) + 1; + if (ep - bp < len) + break; + strlcpy(bp, cp, ep - bp); + *q++ = bp; + bp += len; + cp = p; + } + *q = NULL; + RES_SET_H_ERRNO(statp, NETDB_SUCCESS); + return (0); +} + +int +gethostent_r(struct hostent *hptr, char *buffer, size_t buflen, + struct hostent **result, int *h_errnop) +{ + struct hostent_data *hed; + struct hostent he; + res_state statp; + + statp = __res_state(); + if ((statp->options & RES_INIT) == 0 && res_ninit(statp) == -1) { + RES_SET_H_ERRNO(statp, NETDB_INTERNAL); + *h_errnop = statp->res_h_errno; + return (-1); + } + if ((hed = __hostent_data_init()) == NULL) { + RES_SET_H_ERRNO(statp, NETDB_INTERNAL); + *h_errnop = statp->res_h_errno; + return (-1); + } + if (gethostent_p(&he, hed, statp->options & RES_USE_INET6, statp) != 0) + return (-1); + if (__copy_hostent(&he, hptr, buffer, buflen) != 0) + return (-1); + *result = hptr; + return (0); +} + +struct hostent * +gethostent(void) +{ + struct hostdata *hd; + struct hostent *rval; + int ret_h_errno; + + if ((hd = __hostdata_init()) == NULL) + return (NULL); + if (gethostent_r(&hd->host, hd->data, sizeof(hd->data), &rval, + &ret_h_errno) != 0) + return (NULL); + return (rval); +} + +int +_ht_gethostbyname(void *rval, void *cb_data, va_list ap) +{ + const char *name; + int af; + char *buffer; + size_t buflen; + int *errnop, *h_errnop; + struct hostent *hptr, he; + struct hostent_data *hed; + char **cp; + res_state statp; + int error; + + name = va_arg(ap, const char *); + af = va_arg(ap, int); + hptr = va_arg(ap, struct hostent *); + buffer = va_arg(ap, char *); + buflen = va_arg(ap, size_t); + errnop = va_arg(ap, int *); + h_errnop = va_arg(ap, int *); + + *((struct hostent **)rval) = NULL; + + statp = __res_state(); + if ((hed = __hostent_data_init()) == NULL) { + RES_SET_H_ERRNO(statp, NETDB_INTERNAL); + *h_errnop = statp->res_h_errno; + return (NS_NOTFOUND); + } + + _sethosthtent(0, hed); + while ((error = gethostent_p(&he, hed, 0, statp)) == 0) { + if (he.h_addrtype != af) + continue; + if (he.h_addrtype == AF_INET && + statp->options & RES_USE_INET6) { + _map_v4v6_address(he.h_addr, he.h_addr); + he.h_length = IN6ADDRSZ; + he.h_addrtype = AF_INET6; + } + if (strcasecmp(he.h_name, name) == 0) + break; + for (cp = he.h_aliases; *cp != 0; cp++) + if (strcasecmp(*cp, name) == 0) + goto found; + } +found: + _endhosthtent(hed); + + if (error != 0) { + *h_errnop = statp->res_h_errno; + return (NS_NOTFOUND); + } + if (__copy_hostent(&he, hptr, buffer, buflen) != 0) { + *h_errnop = statp->res_h_errno; + return (NS_NOTFOUND); + } + *((struct hostent **)rval) = hptr; + return (NS_SUCCESS); +} + +int +_ht_gethostbyaddr(void *rval, void *cb_data, va_list ap) +{ + const void *addr; + socklen_t len; + int af; + char *buffer; + size_t buflen; + int *errnop, *h_errnop; + struct hostent *hptr, he; + struct hostent_data *hed; + res_state statp; + int error; + + addr = va_arg(ap, const void *); + len = va_arg(ap, socklen_t); + af = va_arg(ap, int); + hptr = va_arg(ap, struct hostent *); + buffer = va_arg(ap, char *); + buflen = va_arg(ap, size_t); + errnop = va_arg(ap, int *); + h_errnop = va_arg(ap, int *); + + *((struct hostent **)rval) = NULL; + + statp = __res_state(); + if ((hed = __hostent_data_init()) == NULL) { + RES_SET_H_ERRNO(statp, NETDB_INTERNAL); + *h_errnop = statp->res_h_errno; + return (NS_NOTFOUND); + } + + _sethosthtent(0, hed); + while ((error = gethostent_p(&he, hed, 0, statp)) == 0) + if (he.h_addrtype == af && !bcmp(he.h_addr, addr, len)) { + if (he.h_addrtype == AF_INET && + statp->options & RES_USE_INET6) { + _map_v4v6_address(he.h_addr, he.h_addr); + he.h_length = IN6ADDRSZ; + he.h_addrtype = AF_INET6; + } + break; + } + _endhosthtent(hed); + + if (error != 0) + return (NS_NOTFOUND); + if (__copy_hostent(&he, hptr, buffer, buflen) != 0) { + *h_errnop = statp->res_h_errno; + return (NS_NOTFOUND); + } + *((struct hostent **)rval) = hptr; + return (NS_SUCCESS); +} diff --git a/lib/libc/net/gethostbynis.c b/lib/libc/net/gethostbynis.c new file mode 100644 index 0000000..4f1cf42 --- /dev/null +++ b/lib/libc/net/gethostbynis.c @@ -0,0 +1,347 @@ +/*- + * Copyright (c) 1994, Garrett Wollman + * + * 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 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 + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include /* XXX */ +#ifdef YP +#include +#include +#include +#endif +#include "netdb_private.h" + +#ifdef YP +static int +_gethostbynis(const char *name, char *map, int af, struct hostent *he, + struct hostent_data *hed) +{ + char *p, *bp, *ep; + char *cp, **q; + char *result; + int resultlen, size, addrok = 0; + char ypbuf[YPMAXRECORD + 2]; + res_state statp; + + statp = __res_state(); + switch(af) { + case AF_INET: + size = NS_INADDRSZ; + break; + case AF_INET6: + size = NS_IN6ADDRSZ; + break; + default: + errno = EAFNOSUPPORT; + RES_SET_H_ERRNO(statp, NETDB_INTERNAL); + return (-1); + } + + if (hed->yp_domain == (char *)NULL) + if (yp_get_default_domain (&hed->yp_domain)) { + RES_SET_H_ERRNO(statp, NETDB_INTERNAL); + return (-1); + } + + if (yp_match(hed->yp_domain, map, name, strlen(name), &result, + &resultlen)) { + RES_SET_H_ERRNO(statp, HOST_NOT_FOUND); + return (-1); + } + + /* avoid potential memory leak */ + bcopy((char *)result, (char *)&ypbuf, resultlen); + ypbuf[resultlen] = '\0'; + free(result); + result = (char *)&ypbuf; + + if ((cp = index(result, '\n'))) + *cp = '\0'; + + cp = strpbrk(result, " \t"); + *cp++ = '\0'; + he->h_addr_list = hed->h_addr_ptrs; + he->h_addr = (char *)hed->host_addr; + switch (af) { + case AF_INET: + addrok = inet_aton(result, (struct in_addr *)hed->host_addr); + if (addrok != 1) + break; + if (statp->options & RES_USE_INET6) { + _map_v4v6_address((char *)hed->host_addr, + (char *)hed->host_addr); + af = AF_INET6; + size = NS_IN6ADDRSZ; + } + break; + case AF_INET6: + addrok = inet_pton(af, result, hed->host_addr); + break; + } + if (addrok != 1) { + RES_SET_H_ERRNO(statp, HOST_NOT_FOUND); + return (-1); + } + he->h_addr_list[1] = NULL; + he->h_length = size; + he->h_addrtype = af; + while (*cp == ' ' || *cp == '\t') + cp++; + bp = hed->hostbuf; + ep = hed->hostbuf + sizeof hed->hostbuf; + he->h_name = bp; + q = he->h_aliases = hed->host_aliases; + p = strpbrk(cp, " \t"); + if (p != NULL) + *p++ = '\0'; + size = strlen(cp) + 1; + if (ep - bp < size) { + RES_SET_H_ERRNO(statp, NO_RECOVERY); + return (-1); + } + strlcpy(bp, cp, ep - bp); + bp += size; + cp = p; + while (cp && *cp) { + if (*cp == ' ' || *cp == '\t') { + cp++; + continue; + } + if (q >= &hed->host_aliases[_MAXALIASES - 1]) + break; + p = strpbrk(cp, " \t"); + if (p != NULL) + *p++ = '\0'; + size = strlen(cp) + 1; + if (ep - bp < size) + break; + strlcpy(bp, cp, ep - bp); + *q++ = bp; + bp += size; + cp = p; + } + *q = NULL; + return (0); +} + +static int +_gethostbynisname_r(const char *name, int af, struct hostent *he, + struct hostent_data *hed) +{ + char *map; + + switch (af) { + case AF_INET: + map = "hosts.byname"; + break; + default: + map = "ipnodes.byname"; + break; + } + return (_gethostbynis(name, map, af, he, hed)); +} + +static int +_gethostbynisaddr_r(const void *addr, socklen_t len, int af, + struct hostent *he, struct hostent_data *hed) +{ + char *map; + char numaddr[46]; + + switch (af) { + case AF_INET: + map = "hosts.byaddr"; + break; + default: + map = "ipnodes.byaddr"; + break; + } + if (inet_ntop(af, addr, numaddr, sizeof(numaddr)) == NULL) + return (-1); + return (_gethostbynis(numaddr, map, af, he, hed)); +} +#endif /* YP */ + +/* XXX _gethostbynisname/_gethostbynisaddr only used by getipnodeby*() */ +struct hostent * +_gethostbynisname(const char *name, int af) +{ +#ifdef YP + struct hostent *he; + struct hostent_data *hed; + u_long oresopt; + int error; + res_state statp; + + statp = __res_state(); + if ((he = __hostent_init()) == NULL || + (hed = __hostent_data_init()) == NULL) { + RES_SET_H_ERRNO(statp, NETDB_INTERNAL); + return (NULL); + } + + oresopt = statp->options; + statp->options &= ~RES_USE_INET6; + error = _gethostbynisname_r(name, af, he, hed); + statp->options = oresopt; + return (error == 0) ? he : NULL; +#else + return (NULL); +#endif +} + +struct hostent * +_gethostbynisaddr(const void *addr, socklen_t len, int af) +{ +#ifdef YP + struct hostent *he; + struct hostent_data *hed; + u_long oresopt; + int error; + res_state statp; + + statp = __res_state(); + if ((he = __hostent_init()) == NULL || + (hed = __hostent_data_init()) == NULL) { + RES_SET_H_ERRNO(statp, NETDB_INTERNAL); + return (NULL); + } + + oresopt = statp->options; + statp->options &= ~RES_USE_INET6; + error = _gethostbynisaddr_r(addr, len, af, he, hed); + statp->options = oresopt; + return (error == 0) ? he : NULL; +#else + return (NULL); +#endif +} + +int +_nis_gethostbyname(void *rval, void *cb_data, va_list ap) +{ +#ifdef YP + const char *name; + int af; + char *buffer; + size_t buflen; + int *errnop, *h_errnop; + struct hostent *hptr, he; + struct hostent_data *hed; + res_state statp; + + name = va_arg(ap, const char *); + af = va_arg(ap, int); + hptr = va_arg(ap, struct hostent *); + buffer = va_arg(ap, char *); + buflen = va_arg(ap, size_t); + errnop = va_arg(ap, int *); + h_errnop = va_arg(ap, int *); + + *((struct hostent **)rval) = NULL; + + statp = __res_state(); + if ((hed = __hostent_data_init()) == NULL) { + RES_SET_H_ERRNO(statp, NETDB_INTERNAL); + *h_errnop = statp->res_h_errno; + return (NS_NOTFOUND); + } + + if (_gethostbynisname_r(name, af, &he, hed) != 0) { + *h_errnop = statp->res_h_errno; + return (NS_NOTFOUND); + } + if (__copy_hostent(&he, hptr, buffer, buflen) != 0) { + *h_errnop = statp->res_h_errno; + return (NS_NOTFOUND); + } + *((struct hostent **)rval) = hptr; + return (NS_SUCCESS); +#else + *((struct hostent **)rval) = NULL; + return (NS_UNAVAIL); +#endif +} + +int +_nis_gethostbyaddr(void *rval, void *cb_data, va_list ap) +{ +#ifdef YP + const void *addr; + socklen_t len; + int af; + char *buffer; + size_t buflen; + int *errnop, *h_errnop; + struct hostent *hptr, he; + struct hostent_data *hed; + res_state statp; + + addr = va_arg(ap, const void *); + len = va_arg(ap, socklen_t); + af = va_arg(ap, int); + hptr = va_arg(ap, struct hostent *); + buffer = va_arg(ap, char *); + buflen = va_arg(ap, size_t); + errnop = va_arg(ap, int *); + h_errnop = va_arg(ap, int *); + + *((struct hostent **)rval) = NULL; + + statp = __res_state(); + if ((hed = __hostent_data_init()) == NULL) { + RES_SET_H_ERRNO(statp, NETDB_INTERNAL); + *h_errnop = statp->res_h_errno; + return (NS_NOTFOUND); + } + + if (_gethostbynisaddr_r(addr, len, af, &he, hed) != 0) { + *h_errnop = statp->res_h_errno; + return (NS_NOTFOUND); + } + if (__copy_hostent(&he, hptr, buffer, buflen) != 0) { + *h_errnop = statp->res_h_errno; + return (NS_NOTFOUND); + } + *((struct hostent **)rval) = hptr; + return (NS_SUCCESS); +#else + *((struct hostent **)rval) = NULL; + return (NS_UNAVAIL); +#endif +} diff --git a/lib/libc/net/gethostnamadr.c b/lib/libc/net/gethostnamadr.c new file mode 100644 index 0000000..1311802 --- /dev/null +++ b/lib/libc/net/gethostnamadr.c @@ -0,0 +1,420 @@ +/*- + * Copyright (c) 1994, Garrett Wollman + * + * 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 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 + +#include "namespace.h" +#include "reentrant.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include /* XXX hack for _res */ +#include /* XXX hack for _res */ +#include "un-namespace.h" +#include "netdb_private.h" + +extern int _ht_gethostbyname(void *, void *, va_list); +extern int _dns_gethostbyname(void *, void *, va_list); +extern int _nis_gethostbyname(void *, void *, va_list); +extern int _ht_gethostbyaddr(void *, void *, va_list); +extern int _dns_gethostbyaddr(void *, void *, va_list); +extern int _nis_gethostbyaddr(void *, void *, va_list); + +static int gethostbyname_internal(const char *, int, struct hostent *, char *, + size_t, struct hostent **, int *, res_state); + +/* Host lookup order if nsswitch.conf is broken or nonexistant */ +static const ns_src default_src[] = { + { NSSRC_FILES, NS_SUCCESS }, + { NSSRC_DNS, NS_SUCCESS }, + { 0 } +}; + +NETDB_THREAD_ALLOC(hostent) +NETDB_THREAD_ALLOC(hostent_data) +NETDB_THREAD_ALLOC(hostdata) + +static void +hostent_free(void *ptr) +{ + free(ptr); +} + +static void +hostent_data_free(void *ptr) +{ + struct hostent_data *hed = ptr; + + if (hed == NULL) + return; + hed->stayopen = 0; + _endhosthtent(hed); + free(hed); +} + +static void +hostdata_free(void *ptr) +{ + free(ptr); +} + +int +__copy_hostent(struct hostent *he, struct hostent *hptr, char *buf, + size_t buflen) +{ + char *cp; + char **ptr; + int i, n; + int nptr, len; + + /* Find out the amount of space required to store the answer. */ + nptr = 2; /* NULL ptrs */ + len = (char *)ALIGN(buf) - buf; + for (i = 0; he->h_addr_list[i]; i++, nptr++) { + len += he->h_length; + } + for (i = 0; he->h_aliases[i]; i++, nptr++) { + len += strlen(he->h_aliases[i]) + 1; + } + len += strlen(he->h_name) + 1; + len += nptr * sizeof(char*); + + if (len > buflen) { + errno = ERANGE; + return (-1); + } + + /* copy address size and type */ + hptr->h_addrtype = he->h_addrtype; + n = hptr->h_length = he->h_length; + + ptr = (char **)ALIGN(buf); + cp = (char *)ALIGN(buf) + nptr * sizeof(char *); + + /* copy address list */ + hptr->h_addr_list = ptr; + for (i = 0; he->h_addr_list[i]; i++ , ptr++) { + memcpy(cp, he->h_addr_list[i], n); + hptr->h_addr_list[i] = cp; + cp += n; + } + hptr->h_addr_list[i] = NULL; + ptr++; + + /* copy official name */ + n = strlen(he->h_name) + 1; + strcpy(cp, he->h_name); + hptr->h_name = cp; + cp += n; + + /* copy aliases */ + hptr->h_aliases = ptr; + for (i = 0 ; he->h_aliases[i]; i++) { + n = strlen(he->h_aliases[i]) + 1; + strcpy(cp, he->h_aliases[i]); + hptr->h_aliases[i] = cp; + cp += n; + } + hptr->h_aliases[i] = NULL; + + return (0); +} + +static int +fakeaddr(const char *name, int af, struct hostent *hp, char *buf, +size_t buflen, res_state statp) +{ + struct hostent_data *hed; + struct hostent he; + + if ((hed = __hostent_data_init()) == NULL) { + errno = ENOMEM; + RES_SET_H_ERRNO(statp, NETDB_INTERNAL); + return (-1); + } + + if ((af != AF_INET || + inet_aton(name, (struct in_addr *)hed->host_addr) != 1) && + inet_pton(af, name, hed->host_addr) != 1) { + RES_SET_H_ERRNO(statp, HOST_NOT_FOUND); + return (-1); + } + strncpy(hed->hostbuf, name, MAXDNAME); + hed->hostbuf[MAXDNAME] = '\0'; + if (af == AF_INET && (statp->options & RES_USE_INET6) != 0U) { + _map_v4v6_address((char *)hed->host_addr, + (char *)hed->host_addr); + af = AF_INET6; + } + he.h_addrtype = af; + switch(af) { + case AF_INET: + he.h_length = NS_INADDRSZ; + break; + case AF_INET6: + he.h_length = NS_IN6ADDRSZ; + break; + default: + errno = EAFNOSUPPORT; + RES_SET_H_ERRNO(statp, NETDB_INTERNAL); + return (-1); + } + he.h_name = hed->hostbuf; + he.h_aliases = hed->host_aliases; + hed->host_aliases[0] = NULL; + hed->h_addr_ptrs[0] = (char *)hed->host_addr; + hed->h_addr_ptrs[1] = NULL; + he.h_addr_list = hed->h_addr_ptrs; + RES_SET_H_ERRNO(statp, NETDB_SUCCESS); + return (__copy_hostent(&he, hp, buf, buflen)); +} + +int +gethostbyname_r(const char *name, struct hostent *he, char *buffer, + size_t buflen, struct hostent **result, int *h_errnop) +{ + res_state statp; + + statp = __res_state(); + if ((statp->options & RES_INIT) == 0 && res_ninit(statp) == -1) { + RES_SET_H_ERRNO(statp, NETDB_INTERNAL); + return (-1); + } + if (statp->options & RES_USE_INET6) { + if (fakeaddr(name, AF_INET, he, buffer, buflen, statp) == 0) { + *result = he; + return (0); + } + if (gethostbyname_internal(name, AF_INET6, he, buffer, buflen, + result, h_errnop, statp) == 0) + return (0); + } + return (gethostbyname_internal(name, AF_INET, he, buffer, buflen, + result, h_errnop, statp)); +} + +int +gethostbyname2_r(const char *name, int af, struct hostent *he, char *buffer, + size_t buflen, struct hostent **result, int *h_errnop) +{ + res_state statp; + + statp = __res_state(); + if ((statp->options & RES_INIT) == 0 && res_ninit(statp) == -1) { + RES_SET_H_ERRNO(statp, NETDB_INTERNAL); + return (-1); + } + return (gethostbyname_internal(name, af, he, buffer, buflen, result, + h_errnop, statp)); +} + +int +gethostbyname_internal(const char *name, int af, struct hostent *hp, char *buf, + size_t buflen, struct hostent **result, int *h_errnop, res_state statp) +{ + const char *cp; + int rval, ret_errno; + char abuf[MAXDNAME]; + + static const ns_dtab dtab[] = { + NS_FILES_CB(_ht_gethostbyname, NULL) + { NSSRC_DNS, _dns_gethostbyname, NULL }, + NS_NIS_CB(_nis_gethostbyname, NULL) /* force -DHESIOD */ + { 0 } + }; + + switch (af) { + case AF_INET: + case AF_INET6: + break; + default: + RES_SET_H_ERRNO(statp, NETDB_INTERNAL); + *h_errnop = statp->res_h_errno; + errno = EAFNOSUPPORT; + return (-1); + } + + /* + * if there aren't any dots, it could be a user-level alias. + * this is also done in res_query() since we are not the only + * function that looks up host names. + */ + if (!strchr(name, '.') && + (cp = res_hostalias(statp, name, abuf, sizeof abuf))) + name = cp; + + if (fakeaddr(name, af, hp, buf, buflen, statp) == 0) { + *result = hp; + return (0); + } + + rval = _nsdispatch((void *)result, dtab, NSDB_HOSTS, + "gethostbyname2_r", default_src, name, af, hp, buf, buflen, + &ret_errno, h_errnop); + + return ((rval == NS_SUCCESS) ? 0 : -1); +} + +int +gethostbyaddr_r(const void *addr, socklen_t len, int af, struct hostent *hp, + char *buf, size_t buflen, struct hostent **result, int *h_errnop) +{ + const u_char *uaddr = (const u_char *)addr; + const struct in6_addr *addr6; + socklen_t size; + int rval, ret_errno; + res_state statp; + + static const ns_dtab dtab[] = { + NS_FILES_CB(_ht_gethostbyaddr, NULL) + { NSSRC_DNS, _dns_gethostbyaddr, NULL }, + NS_NIS_CB(_nis_gethostbyaddr, NULL) /* force -DHESIOD */ + { 0 } + }; + + statp = __res_state(); + if ((statp->options & RES_INIT) == 0 && res_ninit(statp) == -1) { + RES_SET_H_ERRNO(statp, NETDB_INTERNAL); + *h_errnop = statp->res_h_errno; + return (-1); + } + + if (af == AF_INET6 && len == NS_IN6ADDRSZ) { + addr6 = (const struct in6_addr *)addr; + if (IN6_IS_ADDR_LINKLOCAL(addr6)) { + RES_SET_H_ERRNO(statp, HOST_NOT_FOUND); + *h_errnop = statp->res_h_errno; + return (-1); + } + if (IN6_IS_ADDR_V4MAPPED(addr6) || + IN6_IS_ADDR_V4COMPAT(addr6)) { + /* Unmap. */ + uaddr += NS_IN6ADDRSZ - NS_INADDRSZ; + af = AF_INET; + len = NS_INADDRSZ; + } + } + switch (af) { + case AF_INET: + size = NS_INADDRSZ; + break; + case AF_INET6: + size = NS_IN6ADDRSZ; + break; + default: + errno = EAFNOSUPPORT; + RES_SET_H_ERRNO(statp, NETDB_INTERNAL); + *h_errnop = statp->res_h_errno; + return (-1); + } + if (size != len) { + errno = EINVAL; + RES_SET_H_ERRNO(statp, NETDB_INTERNAL); + *h_errnop = statp->res_h_errno; + return (-1); + } + + rval = _nsdispatch((void *)result, dtab, NSDB_HOSTS, + "gethostbyaddr_r", default_src, uaddr, len, af, hp, buf, buflen, + &ret_errno, h_errnop); + + return ((rval == NS_SUCCESS) ? 0 : -1); +} + +struct hostent * +gethostbyname(const char *name) +{ + struct hostdata *hd; + struct hostent *rval; + int ret_h_errno; + + if ((hd = __hostdata_init()) == NULL) + return (NULL); + if (gethostbyname_r(name, &hd->host, hd->data, sizeof(hd->data), &rval, + &ret_h_errno) != 0) + return (NULL); + return (rval); +} + +struct hostent * +gethostbyname2(const char *name, int af) +{ + struct hostdata *hd; + struct hostent *rval; + int ret_h_errno; + + if ((hd = __hostdata_init()) == NULL) + return (NULL); + if (gethostbyname2_r(name, af, &hd->host, hd->data, sizeof(hd->data), + &rval, &ret_h_errno) != 0) + return (NULL); + return (rval); +} + +struct hostent * +gethostbyaddr(const void *addr, int len, int af) +{ + struct hostdata *hd; + struct hostent *rval; + int ret_h_errno; + + if ((hd = __hostdata_init()) == NULL) + return (NULL); + if (gethostbyaddr_r(addr, (socklen_t)len, af, &hd->host, hd->data, + sizeof(hd->data), &rval, &ret_h_errno) != 0) + return (NULL); + return (rval); +} + +void +sethostent(int stayopen) +{ + struct hostent_data *hed; + + if ((hed = __hostent_data_init()) == NULL) + return; + _sethosthtent(stayopen, hed); + _sethostdnsent(stayopen); +} + +void +endhostent(void) +{ + struct hostent_data *hed; + + if ((hed = __hostent_data_init()) == NULL) + return; + _endhosthtent(hed); + _endhostdnsent(); +} diff --git a/lib/libc/net/getifaddrs.c b/lib/libc/net/getifaddrs.c new file mode 100644 index 0000000..eb78c4f --- /dev/null +++ b/lib/libc/net/getifaddrs.c @@ -0,0 +1,417 @@ +/* $KAME: getifaddrs.c,v 1.9 2001/08/20 02:31:20 itojun Exp $ */ + +/* + * Copyright (c) 1995, 1999 + * Berkeley Software Design, Inc. 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. + * + * THIS SOFTWARE IS PROVIDED BY Berkeley Software Design, Inc. ``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 Berkeley Software Design, Inc. 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. + * + * BSDI getifaddrs.c,v 2.12 2000/02/23 14:51:59 dab Exp + */ +/* + * NOTE: SIOCGIFCONF case is not LP64 friendly. it also does not perform + * try-and-error for region size. + */ + +#include + +#include "namespace.h" +#include +#include +#include +#include +#ifdef NET_RT_IFLIST +#include +#include +#include +#include +#endif + +#include +#include +#include +#include +#include "un-namespace.h" + +#if !defined(AF_LINK) +#define SA_LEN(sa) sizeof(struct sockaddr) +#endif + +#if !defined(SA_LEN) +#define SA_LEN(sa) (sa)->sa_len +#endif + +#define SALIGN (sizeof(long) - 1) +#define SA_RLEN(sa) ((sa)->sa_len ? (((sa)->sa_len + SALIGN) & ~SALIGN) : (SALIGN + 1)) + +#ifndef ALIGNBYTES +/* + * On systems with a routing socket, ALIGNBYTES should match the value + * that the kernel uses when building the messages. + */ +#define ALIGNBYTES XXX +#endif +#ifndef ALIGN +#define ALIGN(p) (((u_long)(p) + ALIGNBYTES) &~ ALIGNBYTES) +#endif + +#if _BSDI_VERSION >= 199701 +#define HAVE_IFM_DATA +#endif + +#if _BSDI_VERSION >= 199802 +/* ifam_data is very specific to recent versions of bsdi */ +#define HAVE_IFAM_DATA +#endif + +#if defined(__NetBSD__) || defined(__OpenBSD__) || defined(__FreeBSD__) +#define HAVE_IFM_DATA +#endif + +#define MAX_SYSCTL_TRY 5 + +int +getifaddrs(struct ifaddrs **pif) +{ + int icnt = 1; + int dcnt = 0; + int ncnt = 0; +#ifdef NET_RT_IFLIST + int ntry = 0; + int mib[6]; + size_t needed; + char *buf; + char *next; + struct ifaddrs *cif = 0; + char *p, *p0; + struct rt_msghdr *rtm; + struct if_msghdr *ifm; + struct ifa_msghdr *ifam; + struct sockaddr_dl *dl; + struct sockaddr *sa; + struct ifaddrs *ifa, *ift; + u_short idx = 0; +#else /* NET_RT_IFLIST */ + char buf[1024]; + int m, sock; + struct ifconf ifc; + struct ifreq *ifr; + struct ifreq *lifr; +#endif /* NET_RT_IFLIST */ + int i; + size_t len, alen; + char *data; + char *names; + +#ifdef NET_RT_IFLIST + mib[0] = CTL_NET; + mib[1] = PF_ROUTE; + mib[2] = 0; /* protocol */ + mib[3] = 0; /* wildcard address family */ + mib[4] = NET_RT_IFLIST; + mib[5] = 0; /* no flags */ + do { + /* + * We'll try to get addresses several times in case that + * the number of addresses is unexpectedly increased during + * the two sysctl calls. This should rarely happen, but we'll + * try to do our best for applications that assume success of + * this library (which should usually be the case). + * Portability note: since FreeBSD does not add margin of + * memory at the first sysctl, the possibility of failure on + * the second sysctl call is a bit higher. + */ + + if (sysctl(mib, 6, NULL, &needed, NULL, 0) < 0) + return (-1); + if ((buf = malloc(needed)) == NULL) + return (-1); + if (sysctl(mib, 6, buf, &needed, NULL, 0) < 0) { + if (errno != ENOMEM || ++ntry >= MAX_SYSCTL_TRY) { + free(buf); + return (-1); + } + free(buf); + buf = NULL; + } + } while (buf == NULL); + + for (next = buf; next < buf + needed; next += rtm->rtm_msglen) { + rtm = (struct rt_msghdr *)(void *)next; + if (rtm->rtm_version != RTM_VERSION) + continue; + switch (rtm->rtm_type) { + case RTM_IFINFO: + ifm = (struct if_msghdr *)(void *)rtm; + if (ifm->ifm_addrs & RTA_IFP) { + idx = ifm->ifm_index; + ++icnt; + dl = (struct sockaddr_dl *)(void *)(ifm + 1); + dcnt += SA_RLEN((struct sockaddr *)(void*)dl) + + ALIGNBYTES; +#ifdef HAVE_IFM_DATA + dcnt += sizeof(ifm->ifm_data); +#endif /* HAVE_IFM_DATA */ + ncnt += dl->sdl_nlen + 1; + } else + idx = 0; + break; + + case RTM_NEWADDR: + ifam = (struct ifa_msghdr *)(void *)rtm; + if (idx && ifam->ifam_index != idx) + abort(); /* this cannot happen */ + +#define RTA_MASKS (RTA_NETMASK | RTA_IFA | RTA_BRD) + if (idx == 0 || (ifam->ifam_addrs & RTA_MASKS) == 0) + break; + p = (char *)(void *)(ifam + 1); + ++icnt; +#ifdef HAVE_IFAM_DATA + dcnt += sizeof(ifam->ifam_data) + ALIGNBYTES; +#endif /* HAVE_IFAM_DATA */ + /* Scan to look for length of address */ + alen = 0; + for (p0 = p, i = 0; i < RTAX_MAX; i++) { + if ((RTA_MASKS & ifam->ifam_addrs & (1 << i)) + == 0) + continue; + sa = (struct sockaddr *)(void *)p; + len = SA_RLEN(sa); + if (i == RTAX_IFA) { + alen = len; + break; + } + p += len; + } + for (p = p0, i = 0; i < RTAX_MAX; i++) { + if ((RTA_MASKS & ifam->ifam_addrs & (1 << i)) + == 0) + continue; + sa = (struct sockaddr *)(void *)p; + len = SA_RLEN(sa); + if (i == RTAX_NETMASK && SA_LEN(sa) == 0) + dcnt += alen; + else + dcnt += len; + p += len; + } + break; + } + } +#else /* NET_RT_IFLIST */ + ifc.ifc_buf = buf; + ifc.ifc_len = sizeof(buf); + + if ((sock = _socket(AF_INET, SOCK_STREAM, 0)) < 0) + return (-1); + i = _ioctl(sock, SIOCGIFCONF, (char *)&ifc); + _close(sock); + if (i < 0) + return (-1); + + ifr = ifc.ifc_req; + lifr = (struct ifreq *)&ifc.ifc_buf[ifc.ifc_len]; + + while (ifr < lifr) { + struct sockaddr *sa; + + sa = &ifr->ifr_addr; + ++icnt; + dcnt += SA_RLEN(sa); + ncnt += sizeof(ifr->ifr_name) + 1; + + if (SA_LEN(sa) < sizeof(*sa)) + ifr = (struct ifreq *)(((char *)sa) + sizeof(*sa)); + else + ifr = (struct ifreq *)(((char *)sa) + SA_LEN(sa)); + } +#endif /* NET_RT_IFLIST */ + + if (icnt + dcnt + ncnt == 1) { + *pif = NULL; + free(buf); + return (0); + } + data = malloc(sizeof(struct ifaddrs) * icnt + dcnt + ncnt); + if (data == NULL) { + free(buf); + return(-1); + } + + ifa = (struct ifaddrs *)(void *)data; + data += sizeof(struct ifaddrs) * icnt; + names = data + dcnt; + + memset(ifa, 0, sizeof(struct ifaddrs) * icnt); + ift = ifa; + +#ifdef NET_RT_IFLIST + idx = 0; + for (next = buf; next < buf + needed; next += rtm->rtm_msglen) { + rtm = (struct rt_msghdr *)(void *)next; + if (rtm->rtm_version != RTM_VERSION) + continue; + switch (rtm->rtm_type) { + case RTM_IFINFO: + ifm = (struct if_msghdr *)(void *)rtm; + if (ifm->ifm_addrs & RTA_IFP) { + idx = ifm->ifm_index; + dl = (struct sockaddr_dl *)(void *)(ifm + 1); + + cif = ift; + ift->ifa_name = names; + ift->ifa_flags = (int)ifm->ifm_flags; + memcpy(names, dl->sdl_data, + (size_t)dl->sdl_nlen); + names[dl->sdl_nlen] = 0; + names += dl->sdl_nlen + 1; + + ift->ifa_addr = (struct sockaddr *)(void *)data; + memcpy(data, dl, + (size_t)SA_LEN((struct sockaddr *) + (void *)dl)); + data += SA_RLEN((struct sockaddr *)(void *)dl); + +#ifdef HAVE_IFM_DATA + /* ifm_data needs to be aligned */ + ift->ifa_data = data = (void *)ALIGN(data); + memcpy(data, &ifm->ifm_data, sizeof(ifm->ifm_data)); + data += sizeof(ifm->ifm_data); +#else /* HAVE_IFM_DATA */ + ift->ifa_data = NULL; +#endif /* HAVE_IFM_DATA */ + + ift = (ift->ifa_next = ift + 1); + } else + idx = 0; + break; + + case RTM_NEWADDR: + ifam = (struct ifa_msghdr *)(void *)rtm; + if (idx && ifam->ifam_index != idx) + abort(); /* this cannot happen */ + + if (idx == 0 || (ifam->ifam_addrs & RTA_MASKS) == 0) + break; + ift->ifa_name = cif->ifa_name; + ift->ifa_flags = cif->ifa_flags; + ift->ifa_data = NULL; + p = (char *)(void *)(ifam + 1); + /* Scan to look for length of address */ + alen = 0; + for (p0 = p, i = 0; i < RTAX_MAX; i++) { + if ((RTA_MASKS & ifam->ifam_addrs & (1 << i)) + == 0) + continue; + sa = (struct sockaddr *)(void *)p; + len = SA_RLEN(sa); + if (i == RTAX_IFA) { + alen = len; + break; + } + p += len; + } + for (p = p0, i = 0; i < RTAX_MAX; i++) { + if ((RTA_MASKS & ifam->ifam_addrs & (1 << i)) + == 0) + continue; + sa = (struct sockaddr *)(void *)p; + len = SA_RLEN(sa); + switch (i) { + case RTAX_IFA: + ift->ifa_addr = + (struct sockaddr *)(void *)data; + memcpy(data, p, len); + data += len; + break; + + case RTAX_NETMASK: + ift->ifa_netmask = + (struct sockaddr *)(void *)data; + if (SA_LEN(sa) == 0) { + memset(data, 0, alen); + data += alen; + break; + } + memcpy(data, p, len); + data += len; + break; + + case RTAX_BRD: + ift->ifa_broadaddr = + (struct sockaddr *)(void *)data; + memcpy(data, p, len); + data += len; + break; + } + p += len; + } + +#ifdef HAVE_IFAM_DATA + /* ifam_data needs to be aligned */ + ift->ifa_data = data = (void *)ALIGN(data); + memcpy(data, &ifam->ifam_data, sizeof(ifam->ifam_data)); + data += sizeof(ifam->ifam_data); +#endif /* HAVE_IFAM_DATA */ + + ift = (ift->ifa_next = ift + 1); + break; + } + } + + free(buf); +#else /* NET_RT_IFLIST */ + ifr = ifc.ifc_req; + lifr = (struct ifreq *)&ifc.ifc_buf[ifc.ifc_len]; + + while (ifr < lifr) { + struct sockaddr *sa; + + ift->ifa_name = names; + names[sizeof(ifr->ifr_name)] = 0; + strncpy(names, ifr->ifr_name, sizeof(ifr->ifr_name)); + while (*names++) + ; + + ift->ifa_addr = (struct sockaddr *)data; + sa = &ifr->ifr_addr; + memcpy(data, sa, SA_LEN(sa)); + data += SA_RLEN(sa); + + ifr = (struct ifreq *)(((char *)sa) + SA_LEN(sa)); + ift = (ift->ifa_next = ift + 1); + } +#endif /* NET_RT_IFLIST */ + if (--ift >= ifa) { + ift->ifa_next = NULL; + *pif = ifa; + } else { + *pif = NULL; + free(ifa); + } + return (0); +} + +void +freeifaddrs(struct ifaddrs *ifp) +{ + + free(ifp); +} diff --git a/lib/libc/net/getifmaddrs.c b/lib/libc/net/getifmaddrs.c new file mode 100644 index 0000000..d28cc55 --- /dev/null +++ b/lib/libc/net/getifmaddrs.c @@ -0,0 +1,202 @@ +/* + * Copyright (c) 2003 Bruce M. Simpson. + * All rights reserved + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by Bruce M. Simpson. + * 4. Neither the name of Bruce M. Simpson nor the names of other + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY BRUCE M. SIMPSON AND AFFILIATES + * ``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 BRUCE M. SIMPSON 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 + +#include "namespace.h" +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include "un-namespace.h" + +#define SALIGN (sizeof(long) - 1) +#define SA_RLEN(sa) ((sa)->sa_len ? (((sa)->sa_len + SALIGN) & ~SALIGN) : \ + (SALIGN + 1)) +#define MAX_SYSCTL_TRY 5 +#define RTA_MASKS (RTA_GATEWAY | RTA_IFP | RTA_IFA) + +int +getifmaddrs(struct ifmaddrs **pif) +{ + int icnt = 1; + int dcnt = 0; + int ntry = 0; + size_t len; + size_t needed; + int mib[6]; + int i; + char *buf; + char *data; + char *next; + char *p; + struct ifma_msghdr *ifmam; + struct ifmaddrs *ifa, *ift; + struct rt_msghdr *rtm; + struct sockaddr *sa; + + mib[0] = CTL_NET; + mib[1] = PF_ROUTE; + mib[2] = 0; /* protocol */ + mib[3] = 0; /* wildcard address family */ + mib[4] = NET_RT_IFMALIST; + mib[5] = 0; /* no flags */ + do { + if (sysctl(mib, 6, NULL, &needed, NULL, 0) < 0) + return (-1); + if ((buf = malloc(needed)) == NULL) + return (-1); + if (sysctl(mib, 6, buf, &needed, NULL, 0) < 0) { + if (errno != ENOMEM || ++ntry >= MAX_SYSCTL_TRY) { + free(buf); + return (-1); + } + free(buf); + buf = NULL; + } + } while (buf == NULL); + + for (next = buf; next < buf + needed; next += rtm->rtm_msglen) { + rtm = (struct rt_msghdr *)(void *)next; + if (rtm->rtm_version != RTM_VERSION) + continue; + switch (rtm->rtm_type) { + case RTM_NEWMADDR: + ifmam = (struct ifma_msghdr *)(void *)rtm; + if ((ifmam->ifmam_addrs & RTA_IFA) == 0) + break; + icnt++; + p = (char *)(ifmam + 1); + for (i = 0; i < RTAX_MAX; i++) { + if ((RTA_MASKS & ifmam->ifmam_addrs & + (1 << i)) == 0) + continue; + sa = (struct sockaddr *)(void *)p; + len = SA_RLEN(sa); + dcnt += len; + p += len; + } + break; + } + } + + data = malloc(sizeof(struct ifmaddrs) * icnt + dcnt); + if (data == NULL) { + free(buf); + return (-1); + } + + ifa = (struct ifmaddrs *)(void *)data; + data += sizeof(struct ifmaddrs) * icnt; + + memset(ifa, 0, sizeof(struct ifmaddrs) * icnt); + ift = ifa; + + for (next = buf; next < buf + needed; next += rtm->rtm_msglen) { + rtm = (struct rt_msghdr *)(void *)next; + if (rtm->rtm_version != RTM_VERSION) + continue; + + switch (rtm->rtm_type) { + case RTM_NEWMADDR: + ifmam = (struct ifma_msghdr *)(void *)rtm; + if ((ifmam->ifmam_addrs & RTA_IFA) == 0) + break; + + p = (char *)(ifmam + 1); + for (i = 0; i < RTAX_MAX; i++) { + if ((RTA_MASKS & ifmam->ifmam_addrs & + (1 << i)) == 0) + continue; + sa = (struct sockaddr *)(void *)p; + len = SA_RLEN(sa); + switch (i) { + case RTAX_GATEWAY: + ift->ifma_lladdr = + (struct sockaddr *)(void *)data; + memcpy(data, p, len); + data += len; + break; + + case RTAX_IFP: + ift->ifma_name = + (struct sockaddr *)(void *)data; + memcpy(data, p, len); + data += len; + break; + + case RTAX_IFA: + ift->ifma_addr = + (struct sockaddr *)(void *)data; + memcpy(data, p, len); + data += len; + break; + + default: + data += len; + break; + } + p += len; + } + ift->ifma_next = ift + 1; + ift = ift->ifma_next; + break; + } + } + + free(buf); + + if (ift > ifa) { + ift--; + ift->ifma_next = NULL; + *pif = ifa; + } else { + *pif = NULL; + free(ifa); + } + return (0); +} + +void +freeifmaddrs(struct ifmaddrs *ifmp) +{ + + free(ifmp); +} diff --git a/lib/libc/net/getnameinfo.c b/lib/libc/net/getnameinfo.c new file mode 100644 index 0000000..8e25489 --- /dev/null +++ b/lib/libc/net/getnameinfo.c @@ -0,0 +1,344 @@ +/* $KAME: getnameinfo.c,v 1.61 2002/06/27 09:25:47 itojun Exp $ */ + +/* + * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project. + * 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 project 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 PROJECT 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 PROJECT 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. + */ + +/* + * Issues to be discussed: + * - Thread safe-ness must be checked + * - RFC2553 says that we should raise error on short buffer. X/Open says + * we need to truncate the result. We obey RFC2553 (and X/Open should be + * modified). ipngwg rough consensus seems to follow RFC2553. + * - What is "local" in NI_FQDN? + * - NI_NAMEREQD and NI_NUMERICHOST conflict with each other. + * - (KAME extension) always attach textual scopeid (fe80::1%lo0), if + * sin6_scope_id is filled - standardization status? + * XXX breaks backward compat for code that expects no scopeid. + * beware on merge. + */ + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static const struct afd { + int a_af; + size_t a_addrlen; + socklen_t a_socklen; + int a_off; +} afdl [] = { +#ifdef INET6 + {PF_INET6, sizeof(struct in6_addr), sizeof(struct sockaddr_in6), + offsetof(struct sockaddr_in6, sin6_addr)}, +#endif + {PF_INET, sizeof(struct in_addr), sizeof(struct sockaddr_in), + offsetof(struct sockaddr_in, sin_addr)}, + {0, 0, 0}, +}; + +struct sockinet { + u_char si_len; + u_char si_family; + u_short si_port; +}; + +#ifdef INET6 +static int ip6_parsenumeric(const struct sockaddr *, const char *, char *, + size_t, int); +static int ip6_sa2str(const struct sockaddr_in6 *, char *, size_t, int); +#endif + +int +getnameinfo(const struct sockaddr *sa, socklen_t salen, + char *host, size_t hostlen, char *serv, size_t servlen, + int flags) +{ + const struct afd *afd; + struct servent *sp; + struct hostent *hp; + u_short port; + int family, i; + const char *addr; + uint32_t v4a; + int h_error; + char numserv[512]; + char numaddr[512]; + + if (sa == NULL) + return EAI_FAIL; + + family = sa->sa_family; + for (i = 0; afdl[i].a_af; i++) + if (afdl[i].a_af == family) { + afd = &afdl[i]; + goto found; + } + return EAI_FAMILY; + + found: + if (salen != afd->a_socklen) + return EAI_FAIL; + + /* network byte order */ + port = ((const struct sockinet *)sa)->si_port; + addr = (const char *)sa + afd->a_off; + + if (serv == NULL || servlen == 0) { + /* + * do nothing in this case. + * in case you are wondering if "&&" is more correct than + * "||" here: rfc2553bis-03 says that serv == NULL OR + * servlen == 0 means that the caller does not want the result. + */ + } else { + if (flags & NI_NUMERICSERV) + sp = NULL; + else { + sp = getservbyport(port, + (flags & NI_DGRAM) ? "udp" : "tcp"); + } + if (sp) { + if (strlen(sp->s_name) + 1 > servlen) + return EAI_MEMORY; + strlcpy(serv, sp->s_name, servlen); + } else { + snprintf(numserv, sizeof(numserv), "%u", ntohs(port)); + if (strlen(numserv) + 1 > servlen) + return EAI_MEMORY; + strlcpy(serv, numserv, servlen); + } + } + + switch (sa->sa_family) { + case AF_INET: + v4a = (uint32_t) + ntohl(((const struct sockaddr_in *)sa)->sin_addr.s_addr); + if (IN_MULTICAST(v4a) || IN_EXPERIMENTAL(v4a)) + flags |= NI_NUMERICHOST; + v4a >>= IN_CLASSA_NSHIFT; + if (v4a == 0) + flags |= NI_NUMERICHOST; + break; +#ifdef INET6 + case AF_INET6: + { + const struct sockaddr_in6 *sin6; + sin6 = (const struct sockaddr_in6 *)sa; + switch (sin6->sin6_addr.s6_addr[0]) { + case 0x00: + if (IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) + ; + else if (IN6_IS_ADDR_LOOPBACK(&sin6->sin6_addr)) + ; + else + flags |= NI_NUMERICHOST; + break; + default: + if (IN6_IS_ADDR_LINKLOCAL(&sin6->sin6_addr)) { + flags |= NI_NUMERICHOST; + } + else if (IN6_IS_ADDR_MULTICAST(&sin6->sin6_addr)) + flags |= NI_NUMERICHOST; + break; + } + } + break; +#endif + } + if (host == NULL || hostlen == 0) { + /* + * do nothing in this case. + * in case you are wondering if "&&" is more correct than + * "||" here: rfc2553bis-03 says that host == NULL or + * hostlen == 0 means that the caller does not want the result. + */ + } else if (flags & NI_NUMERICHOST) { + size_t numaddrlen; + + /* NUMERICHOST and NAMEREQD conflicts with each other */ + if (flags & NI_NAMEREQD) + return EAI_NONAME; + + switch(afd->a_af) { +#ifdef INET6 + case AF_INET6: + { + int error; + + if ((error = ip6_parsenumeric(sa, addr, host, + hostlen, flags)) != 0) + return(error); + break; + } +#endif + default: + if (inet_ntop(afd->a_af, addr, numaddr, sizeof(numaddr)) + == NULL) + return EAI_SYSTEM; + numaddrlen = strlen(numaddr); + if (numaddrlen + 1 > hostlen) /* don't forget terminator */ + return EAI_MEMORY; + strlcpy(host, numaddr, hostlen); + break; + } + } else { + hp = getipnodebyaddr(addr, afd->a_addrlen, afd->a_af, &h_error); + + if (hp) { +#if 0 + /* + * commented out, since "for local host" is not + * implemented here - see RFC2553 p30 + */ + if (flags & NI_NOFQDN) { + char *p; + p = strchr(hp->h_name, '.'); + if (p) + *p = '\0'; + } +#endif + if (strlen(hp->h_name) + 1 > hostlen) { + freehostent(hp); + return EAI_MEMORY; + } + strlcpy(host, hp->h_name, hostlen); + freehostent(hp); + } else { + if (flags & NI_NAMEREQD) + return EAI_NONAME; + switch(afd->a_af) { +#ifdef INET6 + case AF_INET6: + { + int error; + + if ((error = ip6_parsenumeric(sa, addr, host, + hostlen, + flags)) != 0) + return(error); + break; + } +#endif + default: + if (inet_ntop(afd->a_af, addr, host, + hostlen) == NULL) + return EAI_SYSTEM; + break; + } + } + } + return(0); +} + +#ifdef INET6 +static int +ip6_parsenumeric(const struct sockaddr *sa, const char *addr, + char *host, size_t hostlen, int flags) +{ + size_t numaddrlen; + char numaddr[512]; + + if (inet_ntop(AF_INET6, addr, numaddr, sizeof(numaddr)) == NULL) + return EAI_SYSTEM; + + numaddrlen = strlen(numaddr); + if (numaddrlen + 1 > hostlen) /* don't forget terminator */ + return EAI_MEMORY; + strlcpy(host, numaddr, hostlen); + + if (((const struct sockaddr_in6 *)sa)->sin6_scope_id) { + char zonebuf[MAXHOSTNAMELEN]; + int zonelen; + + zonelen = ip6_sa2str( + (const struct sockaddr_in6 *)(const void *)sa, + zonebuf, sizeof(zonebuf), flags); + if (zonelen < 0) + return EAI_MEMORY; + if (zonelen + 1 + numaddrlen + 1 > hostlen) + return EAI_MEMORY; + + /* construct */ + memcpy(host + numaddrlen + 1, zonebuf, + (size_t)zonelen); + host[numaddrlen] = SCOPE_DELIMITER; + host[numaddrlen + 1 + zonelen] = '\0'; + } + + return 0; +} + +/* ARGSUSED */ +static int +ip6_sa2str(const struct sockaddr_in6 *sa6, char *buf, size_t bufsiz, int flags) +{ + unsigned int ifindex; + const struct in6_addr *a6; + int n; + + ifindex = (unsigned int)sa6->sin6_scope_id; + a6 = &sa6->sin6_addr; + +#ifdef NI_NUMERICSCOPE + if ((flags & NI_NUMERICSCOPE) != 0) { + n = snprintf(buf, bufsiz, "%u", sa6->sin6_scope_id); + if (n < 0 || n >= bufsiz) + return -1; + else + return n; + } +#endif + + /* if_indextoname() does not take buffer size. not a good api... */ + if ((IN6_IS_ADDR_LINKLOCAL(a6) || IN6_IS_ADDR_MC_LINKLOCAL(a6) || + IN6_IS_ADDR_MC_NODELOCAL(a6)) && bufsiz >= IF_NAMESIZE) { + char *p = if_indextoname(ifindex, buf); + if (p) { + return(strlen(p)); + } + } + + /* last resort */ + n = snprintf(buf, bufsiz, "%u", sa6->sin6_scope_id); + if (n < 0 || (size_t)n >= bufsiz) + return -1; + else + return n; +} +#endif /* INET6 */ diff --git a/lib/libc/net/getnetbydns.c b/lib/libc/net/getnetbydns.c new file mode 100644 index 0000000..b7632db --- /dev/null +++ b/lib/libc/net/getnetbydns.c @@ -0,0 +1,464 @@ +/*- + * Copyright (c) 1985, 1988, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * - + * Portions Copyright (c) 1993 by Digital Equipment Corporation. + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies, and that + * the name of Digital Equipment Corporation not be used in advertising or + * publicity pertaining to distribution of the document or software without + * specific, written prior permission. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL + * WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL DIGITAL EQUIPMENT + * CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL + * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR + * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS + * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS + * SOFTWARE. + * - + * --Copyright-- + */ +/* Portions Copyright (c) 1993 Carlos Leandro and Rui Salgueiro + * Dep. Matematica Universidade de Coimbra, Portugal, Europe + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)gethostnamadr.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "netdb_private.h" +#include "res_config.h" + +#define BYADDR 0 +#define BYNAME 1 + +#define MAXPACKET (64*1024) + +typedef union { + HEADER hdr; + u_char buf[MAXPACKET]; +} querybuf; + +typedef union { + long al; + char ac; +} align; + +/* + * Reverse the order of first four dotted entries of in. + * Out must contain space for at least strlen(in) characters. + * The result does not include any leading 0s of in. + */ +static void +ipreverse(char *in, char *out) +{ + char *pos[4]; + int len[4]; + char *p, *start; + int i = 0; + int leading = 1; + + /* Fill-in element positions and lengths: pos[], len[]. */ + start = p = in; + for (;;) { + if (*p == '.' || *p == '\0') { + /* Leading 0? */ + if (leading && p - start == 1 && *start == '0') + len[i] = 0; + else { + len[i] = p - start; + leading = 0; + } + pos[i] = start; + start = p + 1; + i++; + } + if (i == 4) + break; + if (*p == 0) { + for (; i < 4; i++) { + pos[i] = p; + len[i] = 0; + } + break; + } + p++; + } + + /* Copy the entries in reverse order */ + p = out; + leading = 1; + for (i = 3; i >= 0; i--) { + memcpy(p, pos[i], len[i]); + if (len[i]) + leading = 0; + p += len[i]; + /* Need a . separator? */ + if (!leading && i > 0 && len[i - 1]) + *p++ = '.'; + } + *p = '\0'; +} + +static int +getnetanswer(querybuf *answer, int anslen, int net_i, struct netent *ne, + struct netent_data *ned, res_state statp) +{ + + HEADER *hp; + u_char *cp; + int n; + u_char *eom; + int type, class, ancount, qdcount, haveanswer; + char aux[MAXHOSTNAMELEN]; + char ans[MAXHOSTNAMELEN]; + char *in, *bp, *ep, **ap; + + /* + * find first satisfactory answer + * + * answer --> +------------+ ( MESSAGE ) + * | Header | + * +------------+ + * | Question | the question for the name server + * +------------+ + * | Answer | RRs answering the question + * +------------+ + * | Authority | RRs pointing toward an authority + * | Additional | RRs holding additional information + * +------------+ + */ + eom = answer->buf + anslen; + hp = &answer->hdr; + ancount = ntohs(hp->ancount); /* #/records in the answer section */ + qdcount = ntohs(hp->qdcount); /* #/entries in the question section */ + bp = ned->netbuf; + ep = ned->netbuf + sizeof(ned->netbuf); + cp = answer->buf + HFIXEDSZ; + if (!qdcount) { + if (hp->aa) + RES_SET_H_ERRNO(statp, HOST_NOT_FOUND); + else + RES_SET_H_ERRNO(statp, TRY_AGAIN); + return (-1); + } + while (qdcount-- > 0) + cp += __dn_skipname(cp, eom) + QFIXEDSZ; + ap = ned->net_aliases; + *ap = NULL; + ne->n_aliases = ned->net_aliases; + haveanswer = 0; + while (--ancount >= 0 && cp < eom) { + n = dn_expand(answer->buf, eom, cp, bp, ep - bp); + if ((n < 0) || !res_dnok(bp)) + break; + cp += n; + ans[0] = '\0'; + (void)strncpy(&ans[0], bp, sizeof(ans) - 1); + ans[sizeof(ans) - 1] = '\0'; + GETSHORT(type, cp); + GETSHORT(class, cp); + cp += INT32SZ; /* TTL */ + GETSHORT(n, cp); + if (class == C_IN && type == T_PTR) { + n = dn_expand(answer->buf, eom, cp, bp, ep - bp); + if ((n < 0) || !res_hnok(bp)) { + cp += n; + return (-1); + } + cp += n; + *ap++ = bp; + n = strlen(bp) + 1; + bp += n; + ne->n_addrtype = (class == C_IN) ? AF_INET : AF_UNSPEC; + haveanswer++; + } + } + if (haveanswer) { + *ap = NULL; + switch (net_i) { + case BYADDR: + ne->n_name = *ne->n_aliases; + ne->n_net = 0L; + break; + case BYNAME: + in = *ne->n_aliases; + n = strlen(ans) + 1; + if (ep - bp < n) { + RES_SET_H_ERRNO(statp, NETDB_INTERNAL); + errno = ENOBUFS; + return (-1); + } + strlcpy(bp, ans, ep - bp); + ne->n_name = bp; + if (strlen(in) + 1 > sizeof(aux)) { + RES_SET_H_ERRNO(statp, NETDB_INTERNAL); + errno = ENOBUFS; + return (-1); + } + ipreverse(in, aux); + ne->n_net = inet_network(aux); + break; + } + ne->n_aliases++; + return (0); + } + RES_SET_H_ERRNO(statp, TRY_AGAIN); + return (-1); +} + +int +_dns_getnetbyaddr(void *rval, void *cb_data, va_list ap) +{ + uint32_t net; + int net_type; + char *buffer; + size_t buflen; + int *errnop, *h_errnop; + struct netent *nptr, ne; + struct netent_data *ned; + unsigned int netbr[4]; + int nn, anslen, error; + querybuf *buf; + char qbuf[MAXDNAME]; + uint32_t net2; + res_state statp; + + net = va_arg(ap, uint32_t); + net_type = va_arg(ap, int); + nptr = va_arg(ap, struct netent *); + buffer = va_arg(ap, char *); + buflen = va_arg(ap, size_t); + errnop = va_arg(ap, int *); + h_errnop = va_arg(ap, int *); + + statp = __res_state(); + if ((statp->options & RES_INIT) == 0 && res_ninit(statp) == -1) { + RES_SET_H_ERRNO(statp, NETDB_INTERNAL); + *h_errnop = statp->res_h_errno; + return (NS_UNAVAIL); + } + + if ((ned = __netent_data_init()) == NULL) { + RES_SET_H_ERRNO(statp, NETDB_INTERNAL); + *h_errnop = statp->res_h_errno; + return (NS_UNAVAIL); + } + + *((struct netent **)rval) = NULL; + + if (net_type != AF_INET) { + RES_SET_H_ERRNO(statp, NETDB_INTERNAL); + *h_errnop = statp->res_h_errno; + return (NS_UNAVAIL); + } + + for (nn = 4, net2 = net; net2; net2 >>= 8) + netbr[--nn] = net2 & 0xff; + switch (nn) { + case 3: /* Class A */ + sprintf(qbuf, "0.0.0.%u.in-addr.arpa", netbr[3]); + break; + case 2: /* Class B */ + sprintf(qbuf, "0.0.%u.%u.in-addr.arpa", netbr[3], netbr[2]); + break; + case 1: /* Class C */ + sprintf(qbuf, "0.%u.%u.%u.in-addr.arpa", netbr[3], netbr[2], + netbr[1]); + break; + case 0: /* Class D - E */ + sprintf(qbuf, "%u.%u.%u.%u.in-addr.arpa", netbr[3], netbr[2], + netbr[1], netbr[0]); + break; + } + if ((buf = malloc(sizeof(*buf))) == NULL) { + RES_SET_H_ERRNO(statp, NETDB_INTERNAL); + *h_errnop = statp->res_h_errno; + return (NS_NOTFOUND); + } + anslen = res_nquery(statp, qbuf, C_IN, T_PTR, (u_char *)buf, + sizeof(*buf)); + if (anslen < 0) { + free(buf); +#ifdef DEBUG + if (statp->options & RES_DEBUG) + printf("res_nsearch failed\n"); +#endif + *h_errnop = statp->res_h_errno; + return (NS_UNAVAIL); + } else if (anslen > sizeof(*buf)) { + free(buf); +#ifdef DEBUG + if (statp->options & RES_DEBUG) + printf("res_nsearch static buffer too small\n"); +#endif + *h_errnop = statp->res_h_errno; + return (NS_UNAVAIL); + } + error = getnetanswer(buf, anslen, BYADDR, &ne, ned, statp); + free(buf); + if (error == 0) { + /* Strip trailing zeros */ + while ((net & 0xff) == 0 && net != 0) + net >>= 8; + ne.n_net = net; + if (__copy_netent(&ne, nptr, buffer, buflen) != 0) { + *h_errnop = statp->res_h_errno; + return (NS_NOTFOUND); + } + *((struct netent **)rval) = nptr; + return (NS_SUCCESS); + } + *h_errnop = statp->res_h_errno; + return (NS_NOTFOUND); +} + +int +_dns_getnetbyname(void *rval, void *cb_data, va_list ap) +{ + const char *net; + char *buffer; + size_t buflen; + int *errnop, *h_errnop; + struct netent *nptr, ne; + struct netent_data *ned; + int anslen, error; + querybuf *buf; + char qbuf[MAXDNAME]; + res_state statp; + + net = va_arg(ap, const char *); + nptr = va_arg(ap, struct netent *); + buffer = va_arg(ap, char *); + buflen = va_arg(ap, size_t); + errnop = va_arg(ap, int *); + h_errnop = va_arg(ap, int *); + + statp = __res_state(); + if ((statp->options & RES_INIT) == 0 && res_ninit(statp) == -1) { + RES_SET_H_ERRNO(statp, NETDB_INTERNAL); + *h_errnop = statp->res_h_errno; + return (NS_UNAVAIL); + } + if ((ned = __netent_data_init()) == NULL) { + RES_SET_H_ERRNO(statp, NETDB_INTERNAL); + *h_errnop = statp->res_h_errno; + return (NS_UNAVAIL); + } + if ((buf = malloc(sizeof(*buf))) == NULL) { + RES_SET_H_ERRNO(statp, NETDB_INTERNAL); + *h_errnop = statp->res_h_errno; + return (NS_NOTFOUND); + } + + *((struct netent **)rval) = NULL; + + strncpy(qbuf, net, sizeof(qbuf) - 1); + qbuf[sizeof(qbuf) - 1] = '\0'; + anslen = res_nsearch(statp, qbuf, C_IN, T_PTR, (u_char *)buf, + sizeof(*buf)); + if (anslen < 0) { + free(buf); +#ifdef DEBUG + if (statp->options & RES_DEBUG) + printf("res_nsearch failed\n"); +#endif + return (NS_UNAVAIL); + } else if (anslen > sizeof(*buf)) { + free(buf); +#ifdef DEBUG + if (statp->options & RES_DEBUG) + printf("res_search static buffer too small\n"); +#endif + return (NS_UNAVAIL); + } + error = getnetanswer(buf, anslen, BYNAME, &ne, ned, statp); + free(buf); + if (error != 0) { + *h_errnop = statp->res_h_errno; + return (NS_NOTFOUND); + } + if (__copy_netent(&ne, nptr, buffer, buflen) != 0) { + *h_errnop = statp->res_h_errno; + return (NS_NOTFOUND); + } + *((struct netent **)rval) = nptr; + return (NS_SUCCESS); +} + +void +_setnetdnsent(int stayopen) +{ + res_state statp; + + statp = __res_state(); + if ((statp->options & RES_INIT) == 0 && res_ninit(statp) == -1) + return; + if (stayopen) + statp->options |= RES_STAYOPEN | RES_USEVC; +} + +void +_endnetdnsent() +{ + res_state statp; + + statp = __res_state(); + statp->options &= ~(RES_STAYOPEN | RES_USEVC); + res_nclose(statp); +} diff --git a/lib/libc/net/getnetbyht.c b/lib/libc/net/getnetbyht.c new file mode 100644 index 0000000..f99877c --- /dev/null +++ b/lib/libc/net/getnetbyht.c @@ -0,0 +1,283 @@ +/* + * Copyright (c) 1983, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +/* Portions Copyright (c) 1993 Carlos Leandro and Rui Salgueiro + * Dep. Matematica Universidade de Coimbra, Portugal, Europe + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * from getnetent.c 1.1 (Coimbra) 93/06/02 + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)getnetent.c 8.1 (Berkeley) 6/4/93"; +static char orig_rcsid[] = "From: Id: getnetent.c,v 8.4 1997/06/01 20:34:37 vixie Exp"; +#endif /* LIBC_SCCS and not lint */ +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "netdb_private.h" + +void +_setnethtent(int f, struct netent_data *ned) +{ + + if (ned->netf == NULL) + ned->netf = fopen(_PATH_NETWORKS, "r"); + else + rewind(ned->netf); + ned->stayopen |= f; +} + +void +_endnethtent(struct netent_data *ned) +{ + + if (ned->netf) { + fclose(ned->netf); + ned->netf = NULL; + } + ned->stayopen = 0; +} + +static int +getnetent_p(struct netent *ne, struct netent_data *ned) +{ + char *p, *bp, *ep; + char *cp, **q; + int len; + char line[BUFSIZ + 1]; + + if (ned->netf == NULL && + (ned->netf = fopen(_PATH_NETWORKS, "r")) == NULL) + return (-1); +again: + p = fgets(line, sizeof line, ned->netf); + if (p == NULL) + return (-1); + if (*p == '#') + goto again; + cp = strpbrk(p, "#\n"); + if (cp != NULL) + *cp = '\0'; + bp = ned->netbuf; + ep = ned->netbuf + sizeof ned->netbuf; + ne->n_name = bp; + cp = strpbrk(p, " \t"); + if (cp == NULL) + goto again; + *cp++ = '\0'; + len = strlen(p) + 1; + if (ep - bp < len) { + RES_SET_H_ERRNO(__res_state(), NO_RECOVERY); + return (-1); + } + strlcpy(bp, p, ep - bp); + bp += len; + while (*cp == ' ' || *cp == '\t') + cp++; + p = strpbrk(cp, " \t"); + if (p != NULL) + *p++ = '\0'; + ne->n_net = inet_network(cp); + ne->n_addrtype = AF_INET; + q = ne->n_aliases = ned->net_aliases; + if (p != NULL) { + cp = p; + while (cp && *cp) { + if (*cp == ' ' || *cp == '\t') { + cp++; + continue; + } + if (q >= &ned->net_aliases[_MAXALIASES - 1]) + break; + p = strpbrk(cp, " \t"); + if (p != NULL) + *p++ = '\0'; + len = strlen(cp) + 1; + if (ep - bp < len) + break; + strlcpy(bp, cp, ep - bp); + *q++ = bp; + bp += len; + cp = p; + } + } + *q = NULL; + return (0); +} + +int +getnetent_r(struct netent *nptr, char *buffer, size_t buflen, + struct netent **result, int *h_errnop) +{ + struct netent_data *ned; + struct netent ne; + res_state statp; + + statp = __res_state(); + if ((ned = __netent_data_init()) == NULL) { + RES_SET_H_ERRNO(statp, NETDB_INTERNAL); + *h_errnop = statp->res_h_errno; + return (-1); + } + if (getnetent_p(&ne, ned) != 0) + return (-1); + if (__copy_netent(&ne, nptr, buffer, buflen) != 0) + return (-1); + *result = nptr; + return (0); +} + +struct netent * +getnetent(void) +{ + struct netdata *nd; + struct netent *rval; + int ret_h_errno; + + if ((nd = __netdata_init()) == NULL) + return (NULL); + if (getnetent_r(&nd->net, nd->data, sizeof(nd->data), &rval, + &ret_h_errno) != 0) + return (NULL); + return (rval); +} + +int +_ht_getnetbyname(void *rval, void *cb_data, va_list ap) +{ + const char *name; + char *buffer; + size_t buflen; + int *errnop, *h_errnop; + struct netent *nptr, ne; + struct netent_data *ned; + char **cp; + res_state statp; + int error; + + name = va_arg(ap, const char *); + nptr = va_arg(ap, struct netent *); + buffer = va_arg(ap, char *); + buflen = va_arg(ap, size_t); + errnop = va_arg(ap, int *); + h_errnop = va_arg(ap, int *); + + statp = __res_state(); + if ((ned = __netent_data_init()) == NULL) { + RES_SET_H_ERRNO(statp, NETDB_INTERNAL); + *h_errnop = statp->res_h_errno; + return (NS_UNAVAIL); + } + + _setnethtent(ned->stayopen, ned); + while ((error = getnetent_p(&ne, ned)) == 0) { + if (strcasecmp(ne.n_name, name) == 0) + break; + for (cp = ne.n_aliases; *cp != 0; cp++) + if (strcasecmp(*cp, name) == 0) + goto found; + } +found: + if (!ned->stayopen) + _endnethtent(ned); + if (error != 0) { + *h_errnop = statp->res_h_errno; + return (NS_NOTFOUND); + } + if (__copy_netent(&ne, nptr, buffer, buflen) != 0) { + *h_errnop = statp->res_h_errno; + return (NS_NOTFOUND); + } + *((struct netent **)rval) = nptr; + return (NS_SUCCESS); +} + +int +_ht_getnetbyaddr(void *rval, void *cb_data, va_list ap) +{ + uint32_t net; + int type; + char *buffer; + size_t buflen; + int *errnop, *h_errnop; + struct netent *nptr, ne; + struct netent_data *ned; + res_state statp; + int error; + + net = va_arg(ap, uint32_t); + type = va_arg(ap, int); + nptr = va_arg(ap, struct netent *); + buffer = va_arg(ap, char *); + buflen = va_arg(ap, size_t); + errnop = va_arg(ap, int *); + h_errnop = va_arg(ap, int *); + + statp = __res_state(); + if ((ned = __netent_data_init()) == NULL) { + RES_SET_H_ERRNO(statp, NETDB_INTERNAL); + *h_errnop = statp->res_h_errno; + return (NS_UNAVAIL); + } + + _setnethtent(ned->stayopen, ned); + while ((error = getnetent_p(&ne, ned)) == 0) + if (ne.n_addrtype == type && ne.n_net == net) + break; + if (!ned->stayopen) + _endnethtent(ned); + if (error != 0) { + *h_errnop = statp->res_h_errno; + return (NS_NOTFOUND); + } + if (__copy_netent(&ne, nptr, buffer, buflen) != 0) { + *h_errnop = statp->res_h_errno; + return (NS_NOTFOUND); + } + *((struct netent **)rval) = nptr; + return (NS_SUCCESS); +} diff --git a/lib/libc/net/getnetbynis.c b/lib/libc/net/getnetbynis.c new file mode 100644 index 0000000..3475beb --- /dev/null +++ b/lib/libc/net/getnetbynis.c @@ -0,0 +1,254 @@ +/*- + * Copyright (c) 1994, Garrett Wollman + * + * 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 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 + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef YP +#include +#include +#include +#endif +#include "netdb_private.h" + +#ifdef YP +static int +_getnetbynis(const char *name, char *map, int af, struct netent *ne, + struct netent_data *ned) +{ + char *p, *bp, *ep; + char *cp, **q; + char *result; + int resultlen, len; + char ypbuf[YPMAXRECORD + 2]; + + switch(af) { + case AF_INET: + break; + default: + case AF_INET6: + errno = EAFNOSUPPORT; + return (-1); + } + + if (ned->yp_domain == (char *)NULL) + if (yp_get_default_domain (&ned->yp_domain)) + return (-1); + + if (yp_match(ned->yp_domain, map, name, strlen(name), &result, + &resultlen)) + return (-1); + + bcopy((char *)result, (char *)&ypbuf, resultlen); + ypbuf[resultlen] = '\0'; + free(result); + result = (char *)&ypbuf; + + if ((cp = index(result, '\n'))) + *cp = '\0'; + + cp = strpbrk(result, " \t"); + *cp++ = '\0'; + bp = ned->netbuf; + ep = ned->netbuf + sizeof ned->netbuf; + len = strlen(result) + 1; + if (ep - bp < len) { + RES_SET_H_ERRNO(__res_state(), NO_RECOVERY); + return (-1); + } + strlcpy(bp, result, ep - bp); + ne->n_name = bp; + bp += len; + + while (*cp == ' ' || *cp == '\t') + cp++; + + ne->n_net = inet_network(cp); + ne->n_addrtype = AF_INET; + + q = ne->n_aliases = ned->net_aliases; + cp = strpbrk(cp, " \t"); + if (cp != NULL) + *cp++ = '\0'; + while (cp && *cp) { + if (*cp == ' ' || *cp == '\t') { + cp++; + continue; + } + if (q > &ned->net_aliases[_MAXALIASES - 1]) + break; + p = strpbrk(cp, " \t"); + if (p != NULL) + *p++ = '\0'; + len = strlen(cp) + 1; + if (ep - bp < len) + break; + strlcpy(bp, cp, ep - bp); + *q++ = bp; + bp += len; + cp = p; + } + *q = NULL; + return (0); +} +#endif /* YP */ + +int +_nis_getnetbyname(void *rval, void *cb_data, va_list ap) +{ +#ifdef YP + const char *name; + char *buffer; + size_t buflen; + int *errnop, *h_errnop; + struct netent *nptr, ne; + struct netent_data *ned; + res_state statp; + + name = va_arg(ap, const char *); + nptr = va_arg(ap, struct netent *); + buffer = va_arg(ap, char *); + buflen = va_arg(ap, size_t); + errnop = va_arg(ap, int *); + h_errnop = va_arg(ap, int *); + + statp = __res_state(); + if ((ned = __netent_data_init()) == NULL) { + RES_SET_H_ERRNO(statp, NETDB_INTERNAL); + *h_errnop = statp->res_h_errno; + return (NS_UNAVAIL); + } + + if (_getnetbynis(name, "networks.byname", AF_INET, &ne, ned) != 0) { + *h_errnop = statp->res_h_errno; + return (NS_NOTFOUND); + } + if (__copy_netent(&ne, nptr, buffer, buflen) != 0) { + *h_errnop = statp->res_h_errno; + return (NS_NOTFOUND); + } + *((struct netent **)rval) = nptr; + return (NS_SUCCESS); +#else + return (NS_UNAVAIL); +#endif + +} + +int +_nis_getnetbyaddr(void *rval, void *cb_data, va_list ap) +{ +#ifdef YP + uint32_t addr; + int af; + char *buffer; + size_t buflen; + int *errnop, *h_errnop; + struct netent *nptr, ne; + struct netent_data *ned; + char *str, *cp; + uint32_t net2; + int nn; + unsigned int netbr[4]; + char buf[MAXDNAME]; + res_state statp; + + addr = va_arg(ap, uint32_t); + af = va_arg(ap, int); + nptr = va_arg(ap, struct netent *); + buffer = va_arg(ap, char *); + buflen = va_arg(ap, size_t); + errnop = va_arg(ap, int *); + h_errnop = va_arg(ap, int *); + + statp = __res_state(); + if ((ned = __netent_data_init()) == NULL) { + RES_SET_H_ERRNO(statp, NETDB_INTERNAL); + *h_errnop = statp->res_h_errno; + return (NS_UNAVAIL); + } + + if (af != AF_INET) { + RES_SET_H_ERRNO(statp, NETDB_INTERNAL); + *h_errnop = statp->res_h_errno; + errno = EAFNOSUPPORT; + return (NS_UNAVAIL); + } + + for (nn = 4, net2 = addr; net2; net2 >>= 8) { + netbr[--nn] = net2 & 0xff; + } + + switch (nn) { + case 3: /* Class A */ + sprintf(buf, "%u", netbr[3]); + break; + case 2: /* Class B */ + sprintf(buf, "%u.%u", netbr[2], netbr[3]); + break; + case 1: /* Class C */ + sprintf(buf, "%u.%u.%u", netbr[1], netbr[2], netbr[3]); + break; + case 0: /* Class D - E */ + sprintf(buf, "%u.%u.%u.%u", netbr[0], netbr[1], + netbr[2], netbr[3]); + break; + } + + str = (char *)&buf; + cp = str + (strlen(str) - 2); + + while(!strcmp(cp, ".0")) { + *cp = '\0'; + cp = str + (strlen(str) - 2); + } + + if (_getnetbynis(str, "networks.byaddr", af, &ne, ned) != 0) { + *h_errnop = statp->res_h_errno; + return (NS_NOTFOUND); + } + if (__copy_netent(&ne, nptr, buffer, buflen) != 0) { + *h_errnop = statp->res_h_errno; + return (NS_NOTFOUND); + } + *((struct netent **)rval) = nptr; + return (NS_SUCCESS); +#else + return (NS_UNAVAIL); +#endif /* YP */ +} diff --git a/lib/libc/net/getnetnamadr.c b/lib/libc/net/getnetnamadr.c new file mode 100644 index 0000000..32c6ce3 --- /dev/null +++ b/lib/libc/net/getnetnamadr.c @@ -0,0 +1,216 @@ +/*- + * Copyright (c) 1994, Garrett Wollman + * + * 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 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 + +#include "namespace.h" +#include "reentrant.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "un-namespace.h" +#include "netdb_private.h" + +extern int _ht_getnetbyname(void *, void *, va_list); +extern int _dns_getnetbyname(void *, void *, va_list); +extern int _nis_getnetbyname(void *, void *, va_list); +extern int _ht_getnetbyaddr(void *, void *, va_list); +extern int _dns_getnetbyaddr(void *, void *, va_list); +extern int _nis_getnetbyaddr(void *, void *, va_list); + +/* Network lookup order if nsswitch.conf is broken or nonexistant */ +static const ns_src default_src[] = { + { NSSRC_FILES, NS_SUCCESS }, + { NSSRC_DNS, NS_SUCCESS }, + { 0 } +}; + +NETDB_THREAD_ALLOC(netent_data) +NETDB_THREAD_ALLOC(netdata) + +static void +netent_data_free(void *ptr) +{ + struct netent_data *ned = ptr; + + if (ned == NULL) + return; + ned->stayopen = 0; + _endnethtent(ned); + free(ned); +} + +static void +netdata_free(void *ptr) +{ + free(ptr); +} + +int +__copy_netent(struct netent *ne, struct netent *nptr, char *buf, size_t buflen) +{ + char *cp; + int i, n; + int numptr, len; + + /* Find out the amount of space required to store the answer. */ + numptr = 1; /* NULL ptr */ + len = (char *)ALIGN(buf) - buf; + for (i = 0; ne->n_aliases[i]; i++, numptr++) { + len += strlen(ne->n_aliases[i]) + 1; + } + len += strlen(ne->n_name) + 1; + len += numptr * sizeof(char*); + + if (len > (int)buflen) { + errno = ERANGE; + return (-1); + } + + /* copy net value and type */ + nptr->n_addrtype = ne->n_addrtype; + nptr->n_net = ne->n_net; + + cp = (char *)ALIGN(buf) + numptr * sizeof(char *); + + /* copy official name */ + n = strlen(ne->n_name) + 1; + strcpy(cp, ne->n_name); + nptr->n_name = cp; + cp += n; + + /* copy aliases */ + nptr->n_aliases = (char **)ALIGN(buf); + for (i = 0 ; ne->n_aliases[i]; i++) { + n = strlen(ne->n_aliases[i]) + 1; + strcpy(cp, ne->n_aliases[i]); + nptr->n_aliases[i] = cp; + cp += n; + } + nptr->n_aliases[i] = NULL; + + return (0); +} + +int +getnetbyname_r(const char *name, struct netent *ne, char *buffer, + size_t buflen, struct netent **result, int *h_errorp) +{ + int rval, ret_errno; + + static const ns_dtab dtab[] = { + NS_FILES_CB(_ht_getnetbyname, NULL) + { NSSRC_DNS, _dns_getnetbyname, NULL }, + NS_NIS_CB(_nis_getnetbyname, NULL) /* force -DHESIOD */ + { 0 } + }; + + rval = _nsdispatch((void *)result, dtab, NSDB_NETWORKS, + "getnetbyname_r", default_src, name, ne, buffer, buflen, + &ret_errno, h_errorp); + + return ((rval == NS_SUCCESS) ? 0 : -1); +} + +int +getnetbyaddr_r(uint32_t addr, int af, struct netent *ne, char *buffer, + size_t buflen, struct netent **result, int *h_errorp) +{ + int rval, ret_errno; + + static const ns_dtab dtab[] = { + NS_FILES_CB(_ht_getnetbyaddr, NULL) + { NSSRC_DNS, _dns_getnetbyaddr, NULL }, + NS_NIS_CB(_nis_getnetbyaddr, NULL) /* force -DHESIOD */ + { 0 } + }; + + rval = _nsdispatch((void *)result, dtab, NSDB_NETWORKS, + "getnetbyaddr_r", default_src, addr, af, ne, buffer, buflen, + &ret_errno, h_errorp); + + return ((rval == NS_SUCCESS) ? 0 : -1); +} + +struct netent * +getnetbyname(const char *name) +{ + struct netdata *nd; + struct netent *rval; + int ret_h_errno; + + if ((nd = __netdata_init()) == NULL) + return (NULL); + if (getnetbyname_r(name, &nd->net, nd->data, sizeof(nd->data), &rval, + &ret_h_errno) != 0) + return (NULL); + return (rval); +} + +struct netent * +getnetbyaddr(uint32_t addr, int af) +{ + struct netdata *nd; + struct netent *rval; + int ret_h_errno; + + if ((nd = __netdata_init()) == NULL) + return (NULL); + if (getnetbyaddr_r(addr, af, &nd->net, nd->data, sizeof(nd->data), + &rval, &ret_h_errno) != 0) + return (NULL); + return (rval); +} + +void +setnetent(int stayopen) +{ + struct netent_data *ned; + + if ((ned = __netent_data_init()) == NULL) + return; + _setnethtent(stayopen, ned); + _setnetdnsent(stayopen); +} + +void +endnetent(void) +{ + struct netent_data *ned; + + if ((ned = __netent_data_init()) == NULL) + return; + _endnethtent(ned); + _endnetdnsent(); +} diff --git a/lib/libc/net/getproto.c b/lib/libc/net/getproto.c new file mode 100644 index 0000000..7264d85 --- /dev/null +++ b/lib/libc/net/getproto.c @@ -0,0 +1,78 @@ +/* + * Copyright (c) 1983, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)getproto.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include + +#include +#include "netdb_private.h" + +int +getprotobynumber_r(int proto, struct protoent *pptr, char *buffer, + size_t buflen, struct protoent **result) +{ + struct protoent pe; + struct protoent_data *ped; + int error; + + if ((ped = __protoent_data_init()) == NULL) + return (-1); + __setprotoent_p(ped->stayopen, ped); + while ((error = __getprotoent_p(&pe, ped)) == 0) + if (pe.p_proto == proto) + break; + if (!ped->stayopen) + __endprotoent_p(ped); + if (error != 0) + return (-1); + if (__copy_protoent(&pe, pptr, buffer, buflen) != 0) + return (-1); + *result = pptr; + return (0); +} + +struct protoent * +getprotobynumber(int proto) +{ + struct protodata *pd; + struct protoent *rval; + + if ((pd = __protodata_init()) == NULL) + return (NULL); + if (getprotobynumber_r(proto, &pd->proto, pd->data, sizeof(pd->data), + &rval) != 0) + return (NULL); + return (rval); +} diff --git a/lib/libc/net/getprotoent.c b/lib/libc/net/getprotoent.c new file mode 100644 index 0000000..45f588e --- /dev/null +++ b/lib/libc/net/getprotoent.c @@ -0,0 +1,244 @@ +/* + * Copyright (c) 1983, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)getprotoent.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include "namespace.h" +#include "reentrant.h" +#include "un-namespace.h" +#include "netdb_private.h" + +NETDB_THREAD_ALLOC(protoent_data) +NETDB_THREAD_ALLOC(protodata) + +static void +protoent_data_clear(struct protoent_data *ped) +{ + if (ped->fp) { + fclose(ped->fp); + ped->fp = NULL; + } +} + +static void +protoent_data_free(void *ptr) +{ + struct protoent_data *ped = ptr; + + protoent_data_clear(ped); + free(ped); +} + +static void +protodata_free(void *ptr) +{ + free(ptr); +} + +int +__copy_protoent(struct protoent *pe, struct protoent *pptr, char *buf, + size_t buflen) +{ + char *cp; + int i, n; + int numptr, len; + + /* Find out the amount of space required to store the answer. */ + numptr = 1; /* NULL ptr */ + len = (char *)ALIGN(buf) - buf; + for (i = 0; pe->p_aliases[i]; i++, numptr++) { + len += strlen(pe->p_aliases[i]) + 1; + } + len += strlen(pe->p_name) + 1; + len += numptr * sizeof(char*); + + if (len > (int)buflen) { + errno = ERANGE; + return (-1); + } + + /* copy protocol value*/ + pptr->p_proto = pe->p_proto; + + cp = (char *)ALIGN(buf) + numptr * sizeof(char *); + + /* copy official name */ + n = strlen(pe->p_name) + 1; + strcpy(cp, pe->p_name); + pptr->p_name = cp; + cp += n; + + /* copy aliases */ + pptr->p_aliases = (char **)ALIGN(buf); + for (i = 0 ; pe->p_aliases[i]; i++) { + n = strlen(pe->p_aliases[i]) + 1; + strcpy(cp, pe->p_aliases[i]); + pptr->p_aliases[i] = cp; + cp += n; + } + pptr->p_aliases[i] = NULL; + + return (0); +} + +void +__setprotoent_p(int f, struct protoent_data *ped) +{ + if (ped->fp == NULL) + ped->fp = fopen(_PATH_PROTOCOLS, "r"); + else + rewind(ped->fp); + ped->stayopen |= f; +} + +void +__endprotoent_p(struct protoent_data *ped) +{ + if (ped->fp) { + fclose(ped->fp); + ped->fp = NULL; + } + ped->stayopen = 0; +} + +int +__getprotoent_p(struct protoent *pe, struct protoent_data *ped) +{ + char *p; + char *cp, **q, *endp; + long l; + + if (ped->fp == NULL && (ped->fp = fopen(_PATH_PROTOCOLS, "r")) == NULL) + return (-1); +again: + if ((p = fgets(ped->line, sizeof ped->line, ped->fp)) == NULL) + return (-1); + if (*p == '#') + goto again; + cp = strpbrk(p, "#\n"); + if (cp != NULL) + *cp = '\0'; + pe->p_name = p; + cp = strpbrk(p, " \t"); + if (cp == NULL) + goto again; + *cp++ = '\0'; + while (*cp == ' ' || *cp == '\t') + cp++; + p = strpbrk(cp, " \t"); + if (p != NULL) + *p++ = '\0'; + l = strtol(cp, &endp, 10); + if (endp == cp || *endp != '\0' || l < 0 || l > USHRT_MAX) + goto again; + pe->p_proto = l; + q = pe->p_aliases = ped->aliases; + if (p != NULL) { + cp = p; + while (cp && *cp) { + if (*cp == ' ' || *cp == '\t') { + cp++; + continue; + } + if (q < &ped->aliases[_MAXALIASES - 1]) + *q++ = cp; + cp = strpbrk(cp, " \t"); + if (cp != NULL) + *cp++ = '\0'; + } + } + *q = NULL; + return (0); +} + +int +getprotoent_r(struct protoent *pptr, char *buffer, size_t buflen, + struct protoent **result) +{ + struct protoent pe; + struct protoent_data *ped; + + if ((ped = __protoent_data_init()) == NULL) + return (-1); + + if (__getprotoent_p(&pe, ped) != 0) + return (-1); + if (__copy_protoent(&pe, pptr, buffer, buflen) != 0) + return (-1); + *result = pptr; + return (0); +} + +void +setprotoent(int f) +{ + struct protoent_data *ped; + + if ((ped = __protoent_data_init()) == NULL) + return; + __setprotoent_p(f, ped); +} + +void +endprotoent(void) +{ + struct protoent_data *ped; + + if ((ped = __protoent_data_init()) == NULL) + return; + __endprotoent_p(ped); +} + +struct protoent * +getprotoent(void) +{ + struct protodata *pd; + struct protoent *rval; + + if ((pd = __protodata_init()) == NULL) + return (NULL); + if (getprotoent_r(&pd->proto, pd->data, sizeof(pd->data), &rval) != 0) + return (NULL); + return (rval); +} diff --git a/lib/libc/net/getprotoname.c b/lib/libc/net/getprotoname.c new file mode 100644 index 0000000..431b924 --- /dev/null +++ b/lib/libc/net/getprotoname.c @@ -0,0 +1,86 @@ +/* + * Copyright (c) 1983, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)getprotoname.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include + +#include +#include +#include "netdb_private.h" + +int +getprotobyname_r(const char *name, struct protoent *pptr, char *buffer, + size_t buflen, struct protoent **result) +{ + struct protoent pe; + struct protoent_data *ped; + char **cp; + int error; + + if ((ped = __protoent_data_init()) == NULL) + return (-1); + + __setprotoent_p(ped->stayopen, ped); + while ((error = __getprotoent_p(&pe, ped)) == 0) { + if (strcmp(pe.p_name, name) == 0) + break; + for (cp = pe.p_aliases; *cp != 0; cp++) + if (strcmp(*cp, name) == 0) + goto found; + } +found: + if (!ped->stayopen) + __endprotoent_p(ped); + if (error != 0) + return (-1); + if (__copy_protoent(&pe, pptr, buffer, buflen) != 0) + return (-1); + *result = pptr; + return (0); +} + +struct protoent * +getprotobyname(const char *name) +{ + struct protodata *pd; + struct protoent *rval; + + if ((pd = __protodata_init()) == NULL) + return (NULL); + if (getprotobyname_r(name, &pd->proto, pd->data, sizeof(pd->data), + &rval) != 0) + return (NULL); + return (rval); +} diff --git a/lib/libc/net/getservbyname.c b/lib/libc/net/getservbyname.c new file mode 100644 index 0000000..243465d --- /dev/null +++ b/lib/libc/net/getservbyname.c @@ -0,0 +1,100 @@ +/* + * Copyright (c) 1983, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)getservbyname.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include + +#include +#include +#include "netdb_private.h" + +int +getservbyname_r(const char *name, const char *proto, struct servent *sptr, + char *buffer, size_t buflen, struct servent **result) +{ + struct servent se; + struct servent_data *sed; + char **cp; + int error; + + if ((sed = __servent_data_init()) == NULL) + return (-1); + +#ifdef YP + sed->yp_name = (char *)name; + sed->yp_proto = (char *)proto; +#endif + + __setservent_p(sed->stayopen, sed); + while ((error = __getservent_p(&se, sed)) == 0) { + if (strcmp(name, se.s_name) == 0) + goto gotname; + for (cp = se.s_aliases; *cp; cp++) + if (strcmp(name, *cp) == 0) + goto gotname; + continue; +gotname: + if (proto == 0 || strcmp(se.s_proto, proto) == 0) + break; + } + if (!sed->stayopen) + __endservent_p(sed); + +#ifdef YP + sed->yp_name = NULL; + sed->yp_proto = NULL; +#endif + + if (error != 0) + return (-1); + if (__copy_servent(&se, sptr, buffer, buflen) != 0) + return (-1); + *result = sptr; + return (0); +} + +struct servent * +getservbyname(const char *name, const char *proto) +{ + struct servdata *sd; + struct servent *rval; + + if ((sd = __servdata_init()) == NULL) + return (NULL); + if (getservbyname_r(name, proto, &sd->serv, sd->data, sizeof(sd->data), + &rval) != 0) + return (NULL); + return (rval); +} diff --git a/lib/libc/net/getservbyport.c b/lib/libc/net/getservbyport.c new file mode 100644 index 0000000..f3dbec4 --- /dev/null +++ b/lib/libc/net/getservbyport.c @@ -0,0 +1,94 @@ +/* + * Copyright (c) 1983, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)getservbyport.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include + +#include +#include +#include "netdb_private.h" + +int +getservbyport_r(int port, const char *proto, struct servent *sptr, + char *buffer, size_t buflen, struct servent **result) +{ + struct servent se; + struct servent_data *sed; + int error; + + if ((sed = __servent_data_init()) == NULL) + return (-1); + +#ifdef YP + sed->yp_port = port; + sed->yp_proto = (char *)proto; +#endif + + __setservent_p(sed->stayopen, sed); + while ((error = __getservent_p(&se, sed)) == 0) { + if (se.s_port != port) + continue; + if (proto == 0 || strcmp(se.s_proto, proto) == 0) + break; + } + if (!sed->stayopen) + __endservent_p(sed); + +#ifdef YP + sed->yp_port = 0; + sed->yp_proto = NULL; +#endif + + if (error != 0) + return (-1); + if (__copy_servent(&se, sptr, buffer, buflen) != 0) + return (-1); + *result = sptr; + return (0); +} + +struct servent * +getservbyport(int port, const char *proto) +{ + struct servdata *sd; + struct servent *rval; + + if ((sd = __servdata_init()) == NULL) + return (NULL); + if (getservbyport_r(port, proto, &sd->serv, sd->data, + sizeof(sd->data), &rval) != 0) + return (NULL); + return (rval); +} diff --git a/lib/libc/net/getservent.c b/lib/libc/net/getservent.c new file mode 100644 index 0000000..ac712b5 --- /dev/null +++ b/lib/libc/net/getservent.c @@ -0,0 +1,403 @@ +/* + * Copyright (c) 1983, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)getservent.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef YP +#include +#include +#include +#endif +#include "namespace.h" +#include "reentrant.h" +#include "un-namespace.h" +#include "netdb_private.h" + +NETDB_THREAD_ALLOC(servent_data) +NETDB_THREAD_ALLOC(servdata) + +static void +servent_data_clear(struct servent_data *sed) +{ + if (sed->fp) { + fclose(sed->fp); + sed->fp = NULL; + } +#ifdef YP + free(sed->yp_key); + sed->yp_key = NULL; +#endif +} + +static void +servent_data_free(void *ptr) +{ + struct servent_data *sed = ptr; + + servent_data_clear(sed); + free(sed); +} + +static void +servdata_free(void *ptr) +{ + free(ptr); +} + +int +__copy_servent(struct servent *se, struct servent *sptr, char *buf, + size_t buflen) +{ + char *cp; + int i, n; + int numptr, len; + + /* Find out the amount of space required to store the answer. */ + numptr = 1; /* NULL ptr */ + len = (char *)ALIGN(buf) - buf; + for (i = 0; se->s_aliases[i]; i++, numptr++) { + len += strlen(se->s_aliases[i]) + 1; + } + len += strlen(se->s_name) + 1; + len += strlen(se->s_proto) + 1; + len += numptr * sizeof(char*); + + if (len > (int)buflen) { + errno = ERANGE; + return (-1); + } + + /* copy port value */ + sptr->s_port = se->s_port; + + cp = (char *)ALIGN(buf) + numptr * sizeof(char *); + + /* copy official name */ + n = strlen(se->s_name) + 1; + strcpy(cp, se->s_name); + sptr->s_name = cp; + cp += n; + + /* copy aliases */ + sptr->s_aliases = (char **)ALIGN(buf); + for (i = 0 ; se->s_aliases[i]; i++) { + n = strlen(se->s_aliases[i]) + 1; + strcpy(cp, se->s_aliases[i]); + sptr->s_aliases[i] = cp; + cp += n; + } + sptr->s_aliases[i] = NULL; + + /* copy proto */ + n = strlen(se->s_proto) + 1; + strcpy(cp, se->s_proto); + sptr->s_proto = cp; + cp += n; + + return (0); +} + +#ifdef YP +static int +_getservbyport_yp(struct servent_data *sed) +{ + char *result; + int resultlen; + char buf[YPMAXRECORD + 2]; + int rv; + + snprintf(buf, sizeof(buf), "%d/%s", ntohs(sed->yp_port), + sed->yp_proto); + + sed->yp_port = 0; + sed->yp_proto = NULL; + + if (!sed->yp_domain) { + if (yp_get_default_domain(&sed->yp_domain)) + return (0); + } + + /* + * We have to be a little flexible here. Ideally you're supposed + * to have both a services.byname and a services.byport map, but + * some systems have only services.byname. FreeBSD cheats a little + * by putting the services.byport information in the same map as + * services.byname so that either case will work. We allow for both + * possibilities here: if there is no services.byport map, we try + * services.byname instead. + */ + if ((rv = yp_match(sed->yp_domain, "services.byport", buf, strlen(buf), + &result, &resultlen))) { + if (rv == YPERR_MAP) { + if (yp_match(sed->yp_domain, "services.byname", buf, + strlen(buf), &result, &resultlen)) + return(0); + } else + return(0); + } + + /* getservent() expects lines terminated with \n -- make it happy */ + snprintf(sed->line, sizeof sed->line, "%.*s\n", resultlen, result); + + free(result); + return(1); +} + +static int +_getservbyname_yp(struct servent_data *sed) +{ + char *result; + int resultlen; + char buf[YPMAXRECORD + 2]; + + if(!sed->yp_domain) { + if(yp_get_default_domain(&sed->yp_domain)) + return (0); + } + + snprintf(buf, sizeof(buf), "%s/%s", sed->yp_name, sed->yp_proto); + + sed->yp_name = 0; + sed->yp_proto = NULL; + + if (yp_match(sed->yp_domain, "services.byname", buf, strlen(buf), + &result, &resultlen)) { + return(0); + } + + /* getservent() expects lines terminated with \n -- make it happy */ + snprintf(sed->line, sizeof sed->line, "%.*s\n", resultlen, result); + + free(result); + return(1); +} + +static int +_getservent_yp(struct servent_data *sed) +{ + char *lastkey, *result; + int resultlen; + int rv; + + if (!sed->yp_domain) { + if (yp_get_default_domain(&sed->yp_domain)) + return (0); + } + + if (!sed->yp_stepping) { + free(sed->yp_key); + rv = yp_first(sed->yp_domain, "services.byname", &sed->yp_key, + &sed->yp_keylen, &result, &resultlen); + if (rv) { + sed->yp_stepping = 0; + return(0); + } + sed->yp_stepping = 1; + } else { + lastkey = sed->yp_key; + rv = yp_next(sed->yp_domain, "services.byname", sed->yp_key, + sed->yp_keylen, &sed->yp_key, &sed->yp_keylen, &result, + &resultlen); + free(lastkey); + if (rv) { + sed->yp_stepping = 0; + return (0); + } + } + + /* getservent() expects lines terminated with \n -- make it happy */ + snprintf(sed->line, sizeof sed->line, "%.*s\n", resultlen, result); + + free(result); + + return(1); +} +#endif + +void +__setservent_p(int f, struct servent_data *sed) +{ + if (sed->fp == NULL) + sed->fp = fopen(_PATH_SERVICES, "r"); + else + rewind(sed->fp); + sed->stayopen |= f; +} + +void +__endservent_p(struct servent_data *sed) +{ + servent_data_clear(sed); + sed->stayopen = 0; +#ifdef YP + sed->yp_stepping = 0; + sed->yp_domain = NULL; +#endif +} + +int +__getservent_p(struct servent *se, struct servent_data *sed) +{ + char *p; + char *cp, **q, *endp; + long l; + +#ifdef YP + if (sed->yp_stepping && _getservent_yp(sed)) { + p = sed->line; + goto unpack; + } +tryagain: +#endif + if (sed->fp == NULL && (sed->fp = fopen(_PATH_SERVICES, "r")) == NULL) + return (-1); +again: + if ((p = fgets(sed->line, sizeof sed->line, sed->fp)) == NULL) + return (-1); +#ifdef YP + if (*p == '+' && _yp_check(NULL)) { + if (sed->yp_name != NULL) { + if (!_getservbyname_yp(sed)) + goto tryagain; + } + else if (sed->yp_port != 0) { + if (!_getservbyport_yp(sed)) + goto tryagain; + } + else if (!_getservent_yp(sed)) + goto tryagain; + } +unpack: +#endif + if (*p == '#') + goto again; + cp = strpbrk(p, "#\n"); + if (cp != NULL) + *cp = '\0'; + se->s_name = p; + p = strpbrk(p, " \t"); + if (p == NULL) + goto again; + *p++ = '\0'; + while (*p == ' ' || *p == '\t') + p++; + cp = strpbrk(p, ",/"); + if (cp == NULL) + goto again; + *cp++ = '\0'; + l = strtol(p, &endp, 10); + if (endp == p || *endp != '\0' || l < 0 || l > USHRT_MAX) + goto again; + se->s_port = htons((in_port_t)l); + se->s_proto = cp; + q = se->s_aliases = sed->aliases; + cp = strpbrk(cp, " \t"); + if (cp != NULL) + *cp++ = '\0'; + while (cp && *cp) { + if (*cp == ' ' || *cp == '\t') { + cp++; + continue; + } + if (q < &sed->aliases[_MAXALIASES - 1]) + *q++ = cp; + cp = strpbrk(cp, " \t"); + if (cp != NULL) + *cp++ = '\0'; + } + *q = NULL; + return (0); +} + +int +getservent_r(struct servent *sptr, char *buffer, size_t buflen, + struct servent **result) +{ + struct servent se; + struct servent_data *sed; + + if ((sed = __servent_data_init()) == NULL) + return (-1); + + if (__getservent_p(&se, sed) != 0) + return (-1); + if (__copy_servent(&se, sptr, buffer, buflen) != 0) + return (-1); + *result = sptr; + return (0); +} + +void +setservent(int f) +{ + struct servent_data *sed; + + if ((sed = __servent_data_init()) == NULL) + return; + __setservent_p(f, sed); +} + +void +endservent(void) +{ + struct servent_data *sed; + + if ((sed = __servent_data_init()) == NULL) + return; + __endservent_p(sed); +} + +struct servent * +getservent(void) +{ + struct servdata *sd; + struct servent *rval; + + if ((sd = __servdata_init()) == NULL) + return (NULL); + if (getservent_r(&sd->serv, sd->data, sizeof(sd->data), &rval) != 0) + return (NULL); + return (rval); +} diff --git a/lib/libc/net/hesiod.c b/lib/libc/net/hesiod.c new file mode 100644 index 0000000..fe2cb68 --- /dev/null +++ b/lib/libc/net/hesiod.c @@ -0,0 +1,582 @@ +/* $NetBSD: hesiod.c,v 1.9 1999/02/11 06:16:38 simonb Exp $ */ + +/* Copyright (c) 1996 by Internet Software Consortium. + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM DISCLAIMS + * ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL INTERNET SOFTWARE + * CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL + * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR + * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS + * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS + * SOFTWARE. + */ + +/* Copyright 1996 by the Massachusetts Institute of Technology. + * + * Permission to use, copy, modify, and distribute this + * software and its documentation for any purpose and without + * fee is hereby granted, provided that the above copyright + * notice appear in all copies and that both that copyright + * notice and this permission notice appear in supporting + * documentation, and that the name of M.I.T. not be used in + * advertising or publicity pertaining to distribution of the + * software without specific, written prior permission. + * M.I.T. makes no representations about the suitability of + * this software for any purpose. It is provided "as is" + * without express or implied warranty. + */ + +/* This file is part of the hesiod library. It implements the core + * portion of the hesiod resolver. + * + * This file is loosely based on an interim version of hesiod.c from + * the BIND IRS library, which was in turn based on an earlier version + * of this file. Extensive changes have been made on each step of the + * path. + * + * This implementation is not truly thread-safe at the moment because + * it uses res_send() and accesses _res. + */ + +#include + +#if 0 +static char *orig_rcsid = "$NetBSD: hesiod.c,v 1.9 1999/02/11 06:16:38 simonb Exp $"; +#endif +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +struct hesiod_p { + char *lhs; /* normally ".ns" */ + char *rhs; /* AKA the default hesiod domain */ + int classes[2]; /* The class search order. */ +}; + +#define MAX_HESRESP 1024 + +static int read_config_file(struct hesiod_p *, const char *); +static char **get_txt_records(int, const char *); +static int init_context(void); +static void translate_errors(void); + + +/* + * hesiod_init -- + * initialize a hesiod_p. + */ +int +hesiod_init(context) + void **context; +{ + struct hesiod_p *ctx; + const char *p, *configname; + + ctx = malloc(sizeof(struct hesiod_p)); + if (ctx) { + *context = ctx; + if (!issetugid()) + configname = getenv("HESIOD_CONFIG"); + else + configname = NULL; + if (!configname) + configname = _PATH_HESIOD_CONF; + if (read_config_file(ctx, configname) >= 0) { + /* + * The default rhs can be overridden by an + * environment variable. + */ + if (!issetugid()) + p = getenv("HES_DOMAIN"); + else + p = NULL; + if (p) { + if (ctx->rhs) + free(ctx->rhs); + ctx->rhs = malloc(strlen(p) + 2); + if (ctx->rhs) { + *ctx->rhs = '.'; + strcpy(ctx->rhs + 1, + (*p == '.') ? p + 1 : p); + return 0; + } else + errno = ENOMEM; + } else + return 0; + } + } else + errno = ENOMEM; + + if (ctx->lhs) + free(ctx->lhs); + if (ctx->rhs) + free(ctx->rhs); + if (ctx) + free(ctx); + return -1; +} + +/* + * hesiod_end -- + * Deallocates the hesiod_p. + */ +void +hesiod_end(context) + void *context; +{ + struct hesiod_p *ctx = (struct hesiod_p *) context; + + free(ctx->rhs); + if (ctx->lhs) + free(ctx->lhs); + free(ctx); +} + +/* + * hesiod_to_bind -- + * takes a hesiod (name, type) and returns a DNS + * name which is to be resolved. + */ +char * +hesiod_to_bind(void *context, const char *name, const char *type) +{ + struct hesiod_p *ctx = (struct hesiod_p *) context; + char bindname[MAXDNAME], *p, *ret, **rhs_list = NULL; + const char *rhs; + int len; + + if (strlcpy(bindname, name, sizeof(bindname)) >= sizeof(bindname)) { + errno = EMSGSIZE; + return NULL; + } + + /* + * Find the right right hand side to use, possibly + * truncating bindname. + */ + p = strchr(bindname, '@'); + if (p) { + *p++ = 0; + if (strchr(p, '.')) + rhs = name + (p - bindname); + else { + rhs_list = hesiod_resolve(context, p, "rhs-extension"); + if (rhs_list) + rhs = *rhs_list; + else { + errno = ENOENT; + return NULL; + } + } + } else + rhs = ctx->rhs; + + /* See if we have enough room. */ + len = strlen(bindname) + 1 + strlen(type); + if (ctx->lhs) + len += strlen(ctx->lhs) + ((ctx->lhs[0] != '.') ? 1 : 0); + len += strlen(rhs) + ((rhs[0] != '.') ? 1 : 0); + if (len > sizeof(bindname) - 1) { + if (rhs_list) + hesiod_free_list(context, rhs_list); + errno = EMSGSIZE; + return NULL; + } + /* Put together the rest of the domain. */ + strcat(bindname, "."); + strcat(bindname, type); + /* Only append lhs if it isn't empty. */ + if (ctx->lhs && ctx->lhs[0] != '\0' ) { + if (ctx->lhs[0] != '.') + strcat(bindname, "."); + strcat(bindname, ctx->lhs); + } + if (rhs[0] != '.') + strcat(bindname, "."); + strcat(bindname, rhs); + + /* rhs_list is no longer needed, since we're done with rhs. */ + if (rhs_list) + hesiod_free_list(context, rhs_list); + + /* Make a copy of the result and return it to the caller. */ + ret = strdup(bindname); + if (!ret) + errno = ENOMEM; + return ret; +} + +/* + * hesiod_resolve -- + * Given a hesiod name and type, return an array of strings returned + * by the resolver. + */ +char ** +hesiod_resolve(context, name, type) + void *context; + const char *name; + const char *type; +{ + struct hesiod_p *ctx = (struct hesiod_p *) context; + char *bindname, **retvec; + + bindname = hesiod_to_bind(context, name, type); + if (!bindname) + return NULL; + + retvec = get_txt_records(ctx->classes[0], bindname); + if (retvec == NULL && errno == ENOENT && ctx->classes[1]) + retvec = get_txt_records(ctx->classes[1], bindname); + + free(bindname); + return retvec; +} + +/*ARGSUSED*/ +void +hesiod_free_list(context, list) + void *context; + char **list; +{ + char **p; + + if (list == NULL) + return; + for (p = list; *p; p++) + free(*p); + free(list); +} + + +/* read_config_file -- + * Parse the /etc/hesiod.conf file. Returns 0 on success, + * -1 on failure. On failure, it might leave values in ctx->lhs + * or ctx->rhs which need to be freed by the caller. + */ +static int +read_config_file(ctx, filename) + struct hesiod_p *ctx; + const char *filename; +{ + char *key, *data, *p, **which; + char buf[MAXDNAME + 7]; + int n; + FILE *fp; + + /* Set default query classes. */ + ctx->classes[0] = C_IN; + ctx->classes[1] = C_HS; + + /* Try to open the configuration file. */ + fp = fopen(filename, "r"); + if (!fp) { + /* Use compiled in default domain names. */ + ctx->lhs = strdup(DEF_LHS); + ctx->rhs = strdup(DEF_RHS); + if (ctx->lhs && ctx->rhs) + return 0; + else { + errno = ENOMEM; + return -1; + } + } + ctx->lhs = NULL; + ctx->rhs = NULL; + while (fgets(buf, sizeof(buf), fp) != NULL) { + p = buf; + if (*p == '#' || *p == '\n' || *p == '\r') + continue; + while (*p == ' ' || *p == '\t') + p++; + key = p; + while (*p != ' ' && *p != '\t' && *p != '=') + p++; + *p++ = 0; + + while (isspace(*p) || *p == '=') + p++; + data = p; + while (!isspace(*p)) + p++; + *p = 0; + + if (strcasecmp(key, "lhs") == 0 || + strcasecmp(key, "rhs") == 0) { + which = (strcasecmp(key, "lhs") == 0) + ? &ctx->lhs : &ctx->rhs; + *which = strdup(data); + if (!*which) { + errno = ENOMEM; + return -1; + } + } else { + if (strcasecmp(key, "classes") == 0) { + n = 0; + while (*data && n < 2) { + p = data; + while (*p && *p != ',') + p++; + if (*p) + *p++ = 0; + if (strcasecmp(data, "IN") == 0) + ctx->classes[n++] = C_IN; + else + if (strcasecmp(data, "HS") == 0) + ctx->classes[n++] = + C_HS; + data = p; + } + while (n < 2) + ctx->classes[n++] = 0; + } + } + } + fclose(fp); + + if (!ctx->rhs || ctx->classes[0] == 0 || + ctx->classes[0] == ctx->classes[1]) { + errno = ENOEXEC; + return -1; + } + return 0; +} + +/* + * get_txt_records -- + * Given a DNS class and a DNS name, do a lookup for TXT records, and + * return a list of them. + */ +static char ** +get_txt_records(qclass, name) + int qclass; + const char *name; +{ + HEADER *hp; + unsigned char qbuf[PACKETSZ], abuf[MAX_HESRESP], *p, *eom, *eor; + char *dst, **list; + int ancount, qdcount, i, j, n, skip, type, class, len; + + /* Make sure the resolver is initialized. */ + if ((_res.options & RES_INIT) == 0 && res_init() == -1) + return NULL; + + /* Construct the query. */ + n = res_mkquery(QUERY, name, qclass, T_TXT, NULL, 0, + NULL, qbuf, PACKETSZ); + if (n < 0) + return NULL; + + /* Send the query. */ + n = res_send(qbuf, n, abuf, MAX_HESRESP); + if (n < 0 || n > MAX_HESRESP) { + errno = ECONNREFUSED; /* XXX */ + return NULL; + } + /* Parse the header of the result. */ + hp = (HEADER *) (void *) abuf; + ancount = ntohs(hp->ancount); + qdcount = ntohs(hp->qdcount); + p = abuf + sizeof(HEADER); + eom = abuf + n; + + /* + * Skip questions, trying to get to the answer section + * which follows. + */ + for (i = 0; i < qdcount; i++) { + skip = dn_skipname(p, eom); + if (skip < 0 || p + skip + QFIXEDSZ > eom) { + errno = EMSGSIZE; + return NULL; + } + p += skip + QFIXEDSZ; + } + + /* Allocate space for the text record answers. */ + list = malloc((ancount + 1) * sizeof(char *)); + if (!list) { + errno = ENOMEM; + return NULL; + } + /* Parse the answers. */ + j = 0; + for (i = 0; i < ancount; i++) { + /* Parse the header of this answer. */ + skip = dn_skipname(p, eom); + if (skip < 0 || p + skip + 10 > eom) + break; + type = p[skip + 0] << 8 | p[skip + 1]; + class = p[skip + 2] << 8 | p[skip + 3]; + len = p[skip + 8] << 8 | p[skip + 9]; + p += skip + 10; + if (p + len > eom) { + errno = EMSGSIZE; + break; + } + /* Skip entries of the wrong class and type. */ + if (class != qclass || type != T_TXT) { + p += len; + continue; + } + /* Allocate space for this answer. */ + list[j] = malloc((size_t)len); + if (!list[j]) { + errno = ENOMEM; + break; + } + dst = list[j++]; + + /* Copy answer data into the allocated area. */ + eor = p + len; + while (p < eor) { + n = (unsigned char) *p++; + if (p + n > eor) { + errno = EMSGSIZE; + break; + } + memcpy(dst, p, (size_t)n); + p += n; + dst += n; + } + if (p < eor) { + errno = EMSGSIZE; + break; + } + *dst = 0; + } + + /* + * If we didn't terminate the loop normally, something + * went wrong. + */ + if (i < ancount) { + for (i = 0; i < j; i++) + free(list[i]); + free(list); + return NULL; + } + if (j == 0) { + errno = ENOENT; + free(list); + return NULL; + } + list[j] = NULL; + return list; +} + + /* + * COMPATIBILITY FUNCTIONS + */ + +static int inited = 0; +static void *context; +static int errval = HES_ER_UNINIT; + +int +hes_init() +{ + init_context(); + return errval; +} + +char * +hes_to_bind(name, type) + const char *name; + const char *type; +{ + static char *bindname; + if (init_context() < 0) + return NULL; + if (bindname) + free(bindname); + bindname = hesiod_to_bind(context, name, type); + if (!bindname) + translate_errors(); + return bindname; +} + +char ** +hes_resolve(name, type) + const char *name; + const char *type; +{ + static char **list; + + if (init_context() < 0) + return NULL; + + /* + * In the old Hesiod interface, the caller was responsible for + * freeing the returned strings but not the vector of strings itself. + */ + if (list) + free(list); + + list = hesiod_resolve(context, name, type); + if (!list) + translate_errors(); + return list; +} + +int +hes_error() +{ + return errval; +} + +void +hes_free(hp) + char **hp; +{ + hesiod_free_list(context, hp); +} + +static int +init_context() +{ + if (!inited) { + inited = 1; + if (hesiod_init(&context) < 0) { + errval = HES_ER_CONFIG; + return -1; + } + errval = HES_ER_OK; + } + return 0; +} + +static void +translate_errors() +{ + switch (errno) { + case ENOENT: + errval = HES_ER_NOTFOUND; + break; + case ECONNREFUSED: + case EMSGSIZE: + errval = HES_ER_NET; + break; + case ENOMEM: + default: + /* Not a good match, but the best we can do. */ + errval = HES_ER_CONFIG; + break; + } +} diff --git a/lib/libc/net/if_indextoname.c b/lib/libc/net/if_indextoname.c new file mode 100644 index 0000000..bc3cf2a --- /dev/null +++ b/lib/libc/net/if_indextoname.c @@ -0,0 +1,87 @@ +/* $KAME: if_indextoname.c,v 1.7 2000/11/08 03:09:30 itojun Exp $ */ + +/*- + * Copyright (c) 1997, 2000 + * Berkeley Software Design, Inc. 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. + * + * THIS SOFTWARE IS PROVIDED BY Berkeley Software Design, Inc. ``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 Berkeley Software Design, Inc. 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. + * + * BSDI Id: if_indextoname.c,v 2.3 2000/04/17 22:38:05 dab Exp + */ + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +/* + * From RFC 2533: + * + * The second function maps an interface index into its corresponding + * name. + * + * #include + * + * char *if_indextoname(unsigned int ifindex, char *ifname); + * + * The ifname argument must point to a buffer of at least IF_NAMESIZE + * bytes into which the interface name corresponding to the specified + * index is returned. (IF_NAMESIZE is also defined in and + * its value includes a terminating null byte at the end of the + * interface name.) This pointer is also the return value of the + * function. If there is no interface corresponding to the specified + * index, NULL is returned, and errno is set to ENXIO, if there was a + * system error (such as running out of memory), if_indextoname returns + * NULL and errno would be set to the proper value (e.g., ENOMEM). + */ + +char * +if_indextoname(unsigned int ifindex, char *ifname) +{ + struct ifaddrs *ifaddrs, *ifa; + int error = 0; + + if (getifaddrs(&ifaddrs) < 0) + return(NULL); /* getifaddrs properly set errno */ + + for (ifa = ifaddrs; ifa != NULL; ifa = ifa->ifa_next) { + if (ifa->ifa_addr && + ifa->ifa_addr->sa_family == AF_LINK && + ifindex == ((struct sockaddr_dl*)ifa->ifa_addr)->sdl_index) + break; + } + + if (ifa == NULL) { + error = ENXIO; + ifname = NULL; + } + else + strncpy(ifname, ifa->ifa_name, IFNAMSIZ); + + freeifaddrs(ifaddrs); + + errno = error; + return(ifname); +} diff --git a/lib/libc/net/if_nameindex.c b/lib/libc/net/if_nameindex.c new file mode 100644 index 0000000..2d97751 --- /dev/null +++ b/lib/libc/net/if_nameindex.c @@ -0,0 +1,146 @@ +/* $KAME: if_nameindex.c,v 1.8 2000/11/24 08:20:01 itojun Exp $ */ + +/*- + * Copyright (c) 1997, 2000 + * Berkeley Software Design, Inc. 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. + * + * THIS SOFTWARE IS PROVIDED BY Berkeley Software Design, Inc. ``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 Berkeley Software Design, Inc. 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. + * + * BSDI Id: if_nameindex.c,v 2.3 2000/04/17 22:38:05 dab Exp + */ + +#include + +#include +#include +#include +#include +#include +#include +#include + +/* + * From RFC 2553: + * + * 4.3 Return All Interface Names and Indexes + * + * The if_nameindex structure holds the information about a single + * interface and is defined as a result of including the + * header. + * + * struct if_nameindex { + * unsigned int if_index; + * char *if_name; + * }; + * + * The final function returns an array of if_nameindex structures, one + * structure per interface. + * + * struct if_nameindex *if_nameindex(void); + * + * The end of the array of structures is indicated by a structure with + * an if_index of 0 and an if_name of NULL. The function returns a NULL + * pointer upon an error, and would set errno to the appropriate value. + * + * The memory used for this array of structures along with the interface + * names pointed to by the if_name members is obtained dynamically. + * This memory is freed by the next function. + * + * 4.4. Free Memory + * + * The following function frees the dynamic memory that was allocated by + * if_nameindex(). + * + * #include + * + * void if_freenameindex(struct if_nameindex *ptr); + * + * The argument to this function must be a pointer that was returned by + * if_nameindex(). + */ + +struct if_nameindex * +if_nameindex(void) +{ + struct ifaddrs *ifaddrs, *ifa; + unsigned int ni; + int nbytes; + struct if_nameindex *ifni, *ifni2; + char *cp; + + if (getifaddrs(&ifaddrs) < 0) + return(NULL); + + /* + * First, find out how many interfaces there are, and how + * much space we need for the string names. + */ + ni = 0; + nbytes = 0; + for (ifa = ifaddrs; ifa != NULL; ifa = ifa->ifa_next) { + if (ifa->ifa_addr && + ifa->ifa_addr->sa_family == AF_LINK) { + nbytes += strlen(ifa->ifa_name) + 1; + ni++; + } + } + + /* + * Next, allocate a chunk of memory, use the first part + * for the array of structures, and the last part for + * the strings. + */ + cp = malloc((ni + 1) * sizeof(struct if_nameindex) + nbytes); + ifni = (struct if_nameindex *)cp; + if (ifni == NULL) + goto out; + cp += (ni + 1) * sizeof(struct if_nameindex); + + /* + * Now just loop through the list of interfaces again, + * filling in the if_nameindex array and making copies + * of all the strings. + */ + ifni2 = ifni; + for (ifa = ifaddrs; ifa != NULL; ifa = ifa->ifa_next) { + if (ifa->ifa_addr && + ifa->ifa_addr->sa_family == AF_LINK) { + ifni2->if_index = + ((struct sockaddr_dl*)ifa->ifa_addr)->sdl_index; + ifni2->if_name = cp; + strcpy(cp, ifa->ifa_name); + ifni2++; + cp += strlen(cp) + 1; + } + } + /* + * Finally, don't forget to terminate the array. + */ + ifni2->if_index = 0; + ifni2->if_name = NULL; +out: + freeifaddrs(ifaddrs); + return(ifni); +} + +void +if_freenameindex(struct if_nameindex *ptr) +{ + free(ptr); +} diff --git a/lib/libc/net/if_nametoindex.c b/lib/libc/net/if_nametoindex.c new file mode 100644 index 0000000..3d8d346 --- /dev/null +++ b/lib/libc/net/if_nametoindex.c @@ -0,0 +1,98 @@ +/* $KAME: if_nametoindex.c,v 1.6 2000/11/24 08:18:54 itojun Exp $ */ + +/*- + * Copyright (c) 1997, 2000 + * Berkeley Software Design, Inc. 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. + * + * THIS SOFTWARE IS PROVIDED BY Berkeley Software Design, Inc. ``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 Berkeley Software Design, Inc. 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. + * + * BSDI Id: if_nametoindex.c,v 2.3 2000/04/17 22:38:05 dab Exp + */ + +#include + +#include "namespace.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "un-namespace.h" + +/* + * From RFC 2553: + * + * 4.1 Name-to-Index + * + * + * The first function maps an interface name into its corresponding + * index. + * + * #include + * + * unsigned int if_nametoindex(const char *ifname); + * + * If the specified interface name does not exist, the return value is + * 0, and errno is set to ENXIO. If there was a system error (such as + * running out of memory), the return value is 0 and errno is set to the + * proper value (e.g., ENOMEM). + */ + +unsigned int +if_nametoindex(const char *ifname) +{ + int s; + struct ifreq ifr; + struct ifaddrs *ifaddrs, *ifa; + unsigned int ni; + + s = _socket(AF_INET, SOCK_DGRAM, 0); + if (s != -1) { + strlcpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name)); + if (_ioctl(s, SIOCGIFINDEX, &ifr) != -1) { + _close(s); + return (ifr.ifr_index); + } + _close(s); + } + + if (getifaddrs(&ifaddrs) < 0) + return(0); + + ni = 0; + + for (ifa = ifaddrs; ifa != NULL; ifa = ifa->ifa_next) { + if (ifa->ifa_addr && + ifa->ifa_addr->sa_family == AF_LINK && + strcmp(ifa->ifa_name, ifname) == 0) { + ni = ((struct sockaddr_dl*)ifa->ifa_addr)->sdl_index; + break; + } + } + + freeifaddrs(ifaddrs); + if (!ni) + errno = ENXIO; + return(ni); +} diff --git a/lib/libc/net/ip6opt.c b/lib/libc/net/ip6opt.c new file mode 100644 index 0000000..f7296a9 --- /dev/null +++ b/lib/libc/net/ip6opt.c @@ -0,0 +1,609 @@ +/* $KAME: ip6opt.c,v 1.13 2003/06/06 10:08:20 suz Exp $ */ + +/* + * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project. + * 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 project 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 PROJECT 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 PROJECT 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 + +#include +#include +#include + +#include +#include + +#include +#include + +static int ip6optlen(u_int8_t *opt, u_int8_t *lim); +static void inet6_insert_padopt(u_char *p, int len); + +/* + * This function returns the number of bytes required to hold an option + * when it is stored as ancillary data, including the cmsghdr structure + * at the beginning, and any padding at the end (to make its size a + * multiple of 8 bytes). The argument is the size of the structure + * defining the option, which must include any pad bytes at the + * beginning (the value y in the alignment term "xn + y"), the type + * byte, the length byte, and the option data. + */ +int +inet6_option_space(nbytes) + int nbytes; +{ + nbytes += 2; /* we need space for nxt-hdr and length fields */ + return(CMSG_SPACE((nbytes + 7) & ~7)); +} + +/* + * This function is called once per ancillary data object that will + * contain either Hop-by-Hop or Destination options. It returns 0 on + * success or -1 on an error. + */ +int +inet6_option_init(bp, cmsgp, type) + void *bp; + struct cmsghdr **cmsgp; + int type; +{ + struct cmsghdr *ch = (struct cmsghdr *)bp; + + /* argument validation */ + if (type != IPV6_HOPOPTS && type != IPV6_DSTOPTS) + return(-1); + + ch->cmsg_level = IPPROTO_IPV6; + ch->cmsg_type = type; + ch->cmsg_len = CMSG_LEN(0); + + *cmsgp = ch; + return(0); +} + +/* + * This function appends a Hop-by-Hop option or a Destination option + * into an ancillary data object that has been initialized by + * inet6_option_init(). This function returns 0 if it succeeds or -1 on + * an error. + * multx is the value x in the alignment term "xn + y" described + * earlier. It must have a value of 1, 2, 4, or 8. + * plusy is the value y in the alignment term "xn + y" described + * earlier. It must have a value between 0 and 7, inclusive. + */ +int +inet6_option_append(cmsg, typep, multx, plusy) + struct cmsghdr *cmsg; + const u_int8_t *typep; + int multx; + int plusy; +{ + int padlen, optlen, off; + u_char *bp = (u_char *)cmsg + cmsg->cmsg_len; + struct ip6_ext *eh = (struct ip6_ext *)CMSG_DATA(cmsg); + + /* argument validation */ + if (multx != 1 && multx != 2 && multx != 4 && multx != 8) + return(-1); + if (plusy < 0 || plusy > 7) + return(-1); + + /* + * If this is the first option, allocate space for the + * first 2 bytes(for next header and length fields) of + * the option header. + */ + if (bp == (u_char *)eh) { + bp += 2; + cmsg->cmsg_len += 2; + } + + /* calculate pad length before the option. */ + off = bp - (u_char *)eh; + padlen = (((off % multx) + (multx - 1)) & ~(multx - 1)) - + (off % multx); + padlen += plusy; + padlen %= multx; /* keep the pad as short as possible */ + /* insert padding */ + inet6_insert_padopt(bp, padlen); + cmsg->cmsg_len += padlen; + bp += padlen; + + /* copy the option */ + if (typep[0] == IP6OPT_PAD1) + optlen = 1; + else + optlen = typep[1] + 2; + memcpy(bp, typep, optlen); + bp += optlen; + cmsg->cmsg_len += optlen; + + /* calculate pad length after the option and insert the padding */ + off = bp - (u_char *)eh; + padlen = ((off + 7) & ~7) - off; + inet6_insert_padopt(bp, padlen); + bp += padlen; + cmsg->cmsg_len += padlen; + + /* update the length field of the ip6 option header */ + eh->ip6e_len = ((bp - (u_char *)eh) >> 3) - 1; + + return(0); +} + +/* + * This function appends a Hop-by-Hop option or a Destination option + * into an ancillary data object that has been initialized by + * inet6_option_init(). This function returns a pointer to the 8-bit + * option type field that starts the option on success, or NULL on an + * error. + * The difference between this function and inet6_option_append() is + * that the latter copies the contents of a previously built option into + * the ancillary data object while the current function returns a + * pointer to the space in the data object where the option's TLV must + * then be built by the caller. + * + */ +u_int8_t * +inet6_option_alloc(cmsg, datalen, multx, plusy) + struct cmsghdr *cmsg; + int datalen; + int multx; + int plusy; +{ + int padlen, off; + u_int8_t *bp = (u_char *)cmsg + cmsg->cmsg_len; + u_int8_t *retval; + struct ip6_ext *eh = (struct ip6_ext *)CMSG_DATA(cmsg); + + /* argument validation */ + if (multx != 1 && multx != 2 && multx != 4 && multx != 8) + return(NULL); + if (plusy < 0 || plusy > 7) + return(NULL); + + /* + * If this is the first option, allocate space for the + * first 2 bytes(for next header and length fields) of + * the option header. + */ + if (bp == (u_char *)eh) { + bp += 2; + cmsg->cmsg_len += 2; + } + + /* calculate pad length before the option. */ + off = bp - (u_char *)eh; + padlen = (((off % multx) + (multx - 1)) & ~(multx - 1)) - + (off % multx); + padlen += plusy; + padlen %= multx; /* keep the pad as short as possible */ + /* insert padding */ + inet6_insert_padopt(bp, padlen); + cmsg->cmsg_len += padlen; + bp += padlen; + + /* keep space to store specified length of data */ + retval = bp; + bp += datalen; + cmsg->cmsg_len += datalen; + + /* calculate pad length after the option and insert the padding */ + off = bp - (u_char *)eh; + padlen = ((off + 7) & ~7) - off; + inet6_insert_padopt(bp, padlen); + bp += padlen; + cmsg->cmsg_len += padlen; + + /* update the length field of the ip6 option header */ + eh->ip6e_len = ((bp - (u_char *)eh) >> 3) - 1; + + return(retval); +} + +/* + * This function processes the next Hop-by-Hop option or Destination + * option in an ancillary data object. If another option remains to be + * processed, the return value of the function is 0 and *tptrp points to + * the 8-bit option type field (which is followed by the 8-bit option + * data length, followed by the option data). If no more options remain + * to be processed, the return value is -1 and *tptrp is NULL. If an + * error occurs, the return value is -1 and *tptrp is not NULL. + * (RFC 2292, 6.3.5) + */ +int +inet6_option_next(cmsg, tptrp) + const struct cmsghdr *cmsg; + u_int8_t **tptrp; +{ + struct ip6_ext *ip6e; + int hdrlen, optlen; + u_int8_t *lim; + + if (cmsg->cmsg_level != IPPROTO_IPV6 || + (cmsg->cmsg_type != IPV6_HOPOPTS && + cmsg->cmsg_type != IPV6_DSTOPTS)) + return(-1); + + /* message length validation */ + if (cmsg->cmsg_len < CMSG_SPACE(sizeof(struct ip6_ext))) + return(-1); + ip6e = (struct ip6_ext *)CMSG_DATA(cmsg); + hdrlen = (ip6e->ip6e_len + 1) << 3; + if (cmsg->cmsg_len < CMSG_SPACE(hdrlen)) + return(-1); + + /* + * If the caller does not specify the starting point, + * simply return the 1st option. + * Otherwise, search the option list for the next option. + */ + lim = (u_int8_t *)ip6e + hdrlen; + if (*tptrp == NULL) + *tptrp = (u_int8_t *)(ip6e + 1); + else { + if ((optlen = ip6optlen(*tptrp, lim)) == 0) + return(-1); + + *tptrp = *tptrp + optlen; + } + if (*tptrp >= lim) { /* there is no option */ + *tptrp = NULL; + return(-1); + } + /* + * Finally, checks if the next option is safely stored in the + * cmsg data. + */ + if (ip6optlen(*tptrp, lim) == 0) + return(-1); + else + return(0); +} + +/* + * This function is similar to the inet6_option_next() function, + * except this function lets the caller specify the option type to be + * searched for, instead of always returning the next option in the + * ancillary data object. + * Note: RFC 2292 says the type of tptrp is u_int8_t *, but we think + * it's a typo. The variable should be type of u_int8_t **. + */ +int +inet6_option_find(cmsg, tptrp, type) + const struct cmsghdr *cmsg; + u_int8_t **tptrp; + int type; +{ + struct ip6_ext *ip6e; + int hdrlen, optlen; + u_int8_t *optp, *lim; + + if (cmsg->cmsg_level != IPPROTO_IPV6 || + (cmsg->cmsg_type != IPV6_HOPOPTS && + cmsg->cmsg_type != IPV6_DSTOPTS)) + return(-1); + + /* message length validation */ + if (cmsg->cmsg_len < CMSG_SPACE(sizeof(struct ip6_ext))) + return(-1); + ip6e = (struct ip6_ext *)CMSG_DATA(cmsg); + hdrlen = (ip6e->ip6e_len + 1) << 3; + if (cmsg->cmsg_len < CMSG_SPACE(hdrlen)) + return(-1); + + /* + * If the caller does not specify the starting point, + * search from the beginning of the option list. + * Otherwise, search from *the next option* of the specified point. + */ + lim = (u_int8_t *)ip6e + hdrlen; + if (*tptrp == NULL) + *tptrp = (u_int8_t *)(ip6e + 1); + else { + if ((optlen = ip6optlen(*tptrp, lim)) == 0) + return(-1); + + *tptrp = *tptrp + optlen; + } + for (optp = *tptrp; optp < lim; optp += optlen) { + if (*optp == type) { + *tptrp = optp; + return(0); + } + if ((optlen = ip6optlen(optp, lim)) == 0) + return(-1); + } + + /* search failed */ + *tptrp = NULL; + return(-1); +} + +/* + * Calculate the length of a given IPv6 option. Also checks + * if the option is safely stored in user's buffer according to the + * calculated length and the limitation of the buffer. + */ +static int +ip6optlen(opt, lim) + u_int8_t *opt, *lim; +{ + int optlen; + + if (*opt == IP6OPT_PAD1) + optlen = 1; + else { + /* is there enough space to store type and len? */ + if (opt + 2 > lim) + return(0); + optlen = *(opt + 1) + 2; + } + if (opt + optlen <= lim) + return(optlen); + + return(0); +} + +static void +inet6_insert_padopt(u_char *p, int len) +{ + switch(len) { + case 0: + return; + case 1: + p[0] = IP6OPT_PAD1; + return; + default: + p[0] = IP6OPT_PADN; + p[1] = len - 2; + memset(&p[2], 0, len - 2); + return; + } +} + +/* + * The following functions are defined in RFC3542, which is a successor + * of RFC2292. + */ + +int +inet6_opt_init(void *extbuf, socklen_t extlen) +{ + struct ip6_ext *ext = (struct ip6_ext *)extbuf; + + if (extlen < 0 || (extlen % 8)) + return(-1); + + if (ext) { + if (extlen == 0) + return(-1); + ext->ip6e_len = (extlen >> 3) - 1; + } + + return(2); /* sizeof the next and the length fields */ +} + +int +inet6_opt_append(void *extbuf, socklen_t extlen, int offset, u_int8_t type, + socklen_t len, u_int8_t align, void **databufp) +{ + int currentlen = offset, padlen = 0; + + /* + * The option type must have a value from 2 to 255, inclusive. + * (0 and 1 are reserved for the Pad1 and PadN options, respectively.) + */ + if (type < 2) + return(-1); + + /* + * The option data length must have a value between 0 and 255, + * inclusive, and is the length of the option data that follows. + */ + if (len < 0 || len > 255) + return(-1); + + /* + * The align parameter must have a value of 1, 2, 4, or 8. + * The align value can not exceed the value of len. + */ + if (align != 1 && align != 2 && align != 4 && align != 8) + return(-1); + if (align > len) + return(-1); + + /* Calculate the padding length. */ + currentlen += 2 + len; /* 2 means "type + len" */ + if (currentlen % align) + padlen = align - (currentlen % align); + + /* The option must fit in the extension header buffer. */ + currentlen += padlen; + if (extlen && /* XXX: right? */ + currentlen > extlen) + return(-1); + + if (extbuf) { + u_int8_t *optp = (u_int8_t *)extbuf + offset; + + if (padlen == 1) { + /* insert a Pad1 option */ + *optp = IP6OPT_PAD1; + optp++; + } + else if (padlen > 0) { + /* insert a PadN option for alignment */ + *optp++ = IP6OPT_PADN; + *optp++ = padlen - 2; + memset(optp, 0, padlen - 2); + optp += (padlen - 2); + } + + *optp++ = type; + *optp++ = len; + + *databufp = optp; + } + + return(currentlen); +} + +int +inet6_opt_finish(void *extbuf, socklen_t extlen, int offset) +{ + int updatelen = offset > 0 ? (1 + ((offset - 1) | 7)) : 0;; + + if (extbuf) { + u_int8_t *padp; + int padlen = updatelen - offset; + + if (updatelen > extlen) + return(-1); + + padp = (u_int8_t *)extbuf + offset; + if (padlen == 1) + *padp = IP6OPT_PAD1; + else if (padlen > 0) { + *padp++ = IP6OPT_PADN; + *padp++ = (padlen - 2); + memset(padp, 0, padlen - 2); + } + } + + return(updatelen); +} + +int +inet6_opt_set_val(void *databuf, int offset, void *val, socklen_t vallen) +{ + + memcpy((u_int8_t *)databuf + offset, val, vallen); + return(offset + vallen); +} + +int +inet6_opt_next(void *extbuf, socklen_t extlen, int offset, u_int8_t *typep, + socklen_t *lenp, void **databufp) +{ + u_int8_t *optp, *lim; + int optlen; + + /* Validate extlen. XXX: is the variable really necessary?? */ + if (extlen == 0 || (extlen % 8)) + return(-1); + lim = (u_int8_t *)extbuf + extlen; + + /* + * If this is the first time this function called for this options + * header, simply return the 1st option. + * Otherwise, search the option list for the next option. + */ + if (offset == 0) { + optp = (u_int8_t *)((struct ip6_hbh *)extbuf + 1); + } + else + optp = (u_int8_t *)extbuf + offset; + + /* Find the next option skipping any padding options. */ + while(optp < lim) { + switch(*optp) { + case IP6OPT_PAD1: + optp++; + break; + case IP6OPT_PADN: + if ((optlen = ip6optlen(optp, lim)) == 0) + goto optend; + optp += optlen; + break; + default: /* found */ + if ((optlen = ip6optlen(optp, lim)) == 0) + goto optend; + *typep = *optp; + *lenp = optlen - 2; + *databufp = optp + 2; + return(optp + optlen - (u_int8_t *)extbuf); + } + } + + optend: + *databufp = NULL; /* for safety */ + return(-1); +} + +int +inet6_opt_find(void *extbuf, socklen_t extlen, int offset, u_int8_t type, + socklen_t *lenp, void **databufp) +{ + u_int8_t *optp, *lim; + int optlen; + + /* Validate extlen. XXX: is the variable really necessary?? */ + if (extlen == 0 || (extlen % 8)) + return(-1); + lim = (u_int8_t *)extbuf + extlen; + + /* + * If this is the first time this function called for this options + * header, simply return the 1st option. + * Otherwise, search the option list for the next option. + */ + if (offset == 0) { + optp = (u_int8_t *)((struct ip6_hbh *)extbuf + 1); + } + else + optp = (u_int8_t *)extbuf + offset; + + /* Find the specified option */ + while(optp < lim) { + if ((optlen = ip6optlen(optp, lim)) == 0) + goto optend; + + if (*optp == type) { /* found */ + *lenp = optlen - 2; + *databufp = optp + 2; + return(optp + optlen - (u_int8_t *)extbuf); + } + + optp += optlen; + } + + optend: + *databufp = NULL; /* for safety */ + return(-1); +} + +int +inet6_opt_get_val(void *databuf, int offset, void *val, socklen_t vallen) +{ + + /* we can't assume alignment here */ + memcpy(val, (u_int8_t *)databuf + offset, vallen); + + return(offset + vallen); +} diff --git a/lib/libc/net/linkaddr.c b/lib/libc/net/linkaddr.c new file mode 100644 index 0000000..cd38c1f --- /dev/null +++ b/lib/libc/net/linkaddr.c @@ -0,0 +1,159 @@ +/*- + * Copyright (c) 1990, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)linkaddr.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include + +#include +#include +#include +#include + +/* States*/ +#define NAMING 0 +#define GOTONE 1 +#define GOTTWO 2 +#define RESET 3 +/* Inputs */ +#define DIGIT (4*0) +#define END (4*1) +#define DELIM (4*2) +#define LETTER (4*3) + +void +link_addr(addr, sdl) + const char *addr; + struct sockaddr_dl *sdl; +{ + char *cp = sdl->sdl_data; + char *cplim = sdl->sdl_len + (char *)sdl; + int byte = 0, state = NAMING, new; + + bzero((char *)&sdl->sdl_family, sdl->sdl_len - 1); + sdl->sdl_family = AF_LINK; + do { + state &= ~LETTER; + if ((*addr >= '0') && (*addr <= '9')) { + new = *addr - '0'; + } else if ((*addr >= 'a') && (*addr <= 'f')) { + new = *addr - 'a' + 10; + } else if ((*addr >= 'A') && (*addr <= 'F')) { + new = *addr - 'A' + 10; + } else if (*addr == 0) { + state |= END; + } else if (state == NAMING && + (((*addr >= 'A') && (*addr <= 'Z')) || + ((*addr >= 'a') && (*addr <= 'z')))) + state |= LETTER; + else + state |= DELIM; + addr++; + switch (state /* | INPUT */) { + case NAMING | DIGIT: + case NAMING | LETTER: + *cp++ = addr[-1]; + continue; + case NAMING | DELIM: + state = RESET; + sdl->sdl_nlen = cp - sdl->sdl_data; + continue; + case GOTTWO | DIGIT: + *cp++ = byte; + /* FALLTHROUGH */ + case RESET | DIGIT: + state = GOTONE; + byte = new; + continue; + case GOTONE | DIGIT: + state = GOTTWO; + byte = new + (byte << 4); + continue; + default: /* | DELIM */ + state = RESET; + *cp++ = byte; + byte = 0; + continue; + case GOTONE | END: + case GOTTWO | END: + *cp++ = byte; + /* FALLTHROUGH */ + case RESET | END: + break; + } + break; + } while (cp < cplim); + sdl->sdl_alen = cp - LLADDR(sdl); + new = cp - (char *)sdl; + if (new > sizeof(*sdl)) + sdl->sdl_len = new; + return; +} + +static char hexlist[] = "0123456789abcdef"; + +char * +link_ntoa(sdl) + const struct sockaddr_dl *sdl; +{ + static char obuf[64]; + char *out = obuf; + int i; + u_char *in = (u_char *)LLADDR(sdl); + u_char *inlim = in + sdl->sdl_alen; + int firsttime = 1; + + if (sdl->sdl_nlen) { + bcopy(sdl->sdl_data, obuf, sdl->sdl_nlen); + out += sdl->sdl_nlen; + if (sdl->sdl_alen) + *out++ = ':'; + } + while (in < inlim) { + if (firsttime) + firsttime = 0; + else + *out++ = '.'; + i = *in++; + if (i > 0xf) { + out[1] = hexlist[i & 0xf]; + i >>= 4; + out[0] = hexlist[i]; + out += 2; + } else + *out++ = hexlist[i]; + } + *out = 0; + return (obuf); +} diff --git a/lib/libc/net/map_v4v6.c b/lib/libc/net/map_v4v6.c new file mode 100644 index 0000000..b095dae --- /dev/null +++ b/lib/libc/net/map_v4v6.c @@ -0,0 +1,122 @@ +/* + * ++Copyright++ 1985, 1988, 1993 + * - + * Copyright (c) 1985, 1988, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * - + * Portions Copyright (c) 1993 by Digital Equipment Corporation. + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies, and that + * the name of Digital Equipment Corporation not be used in advertising or + * publicity pertaining to distribution of the document or software without + * specific, written prior permission. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL + * WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL DIGITAL EQUIPMENT + * CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL + * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR + * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS + * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS + * SOFTWARE. + * - + * --Copyright-- + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)gethostnamadr.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +typedef union { + int32_t al; + char ac; +} align; + +void +_map_v4v6_address(const char *src, char *dst) +{ + u_char *p = (u_char *)dst; + char tmp[NS_INADDRSZ]; + int i; + + /* Stash a temporary copy so our caller can update in place. */ + memcpy(tmp, src, NS_INADDRSZ); + /* Mark this ipv6 addr as a mapped ipv4. */ + for (i = 0; i < 10; i++) + *p++ = 0x00; + *p++ = 0xff; + *p++ = 0xff; + /* Retrieve the saved copy and we're done. */ + memcpy((void*)p, tmp, NS_INADDRSZ); +} + +void +_map_v4v6_hostent(struct hostent *hp, char **bpp, char *ep) { + char **ap; + + if (hp->h_addrtype != AF_INET || hp->h_length != INADDRSZ) + return; + hp->h_addrtype = AF_INET6; + hp->h_length = IN6ADDRSZ; + for (ap = hp->h_addr_list; *ap; ap++) { + int i = (u_long)*bpp % sizeof(align); + + if (i != 0) + i = sizeof(align) - i; + + if ((ep - *bpp) < (i + IN6ADDRSZ)) { + /* Out of memory. Truncate address list here. */ + *ap = NULL; + return; + } + *bpp += i; + _map_v4v6_address(*ap, *bpp); + *ap = *bpp; + *bpp += IN6ADDRSZ; + } +} diff --git a/lib/libc/net/name6.c b/lib/libc/net/name6.c new file mode 100644 index 0000000..f40a30b --- /dev/null +++ b/lib/libc/net/name6.c @@ -0,0 +1,2166 @@ +/* $KAME: name6.c,v 1.25 2000/06/26 16:44:40 itojun Exp $ */ + +/* + * Copyright (C) 1995, 1996, 1997, 1998, and 1999 WIDE Project. + * 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 project 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 PROJECT 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 PROJECT 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. + */ +/* + * ++Copyright++ 1985, 1988, 1993 + * - + * Copyright (c) 1985, 1988, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * - + * Portions Copyright (c) 1993 by Digital Equipment Corporation. + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies, and that + * the name of Digital Equipment Corporation not be used in advertising or + * publicity pertaining to distribution of the document or software without + * specific, written prior permission. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL + * WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL DIGITAL EQUIPMENT + * CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL + * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR + * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS + * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS + * SOFTWARE. + * - + * --Copyright-- + */ + +/* + * Atsushi Onoe + */ + +#include + +#include "namespace.h" +#include +#include +#include +#include +#include +#ifdef INET6 +#include +#include +#include +#include +#include /* XXX */ +#endif + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "un-namespace.h" +#include "netdb_private.h" +#include "res_config.h" +#include "res_private.h" + +#ifndef _PATH_HOSTS +#define _PATH_HOSTS "/etc/hosts" +#endif + +#ifndef MAXALIASES +#define MAXALIASES 10 +#endif +#ifndef MAXADDRS +#define MAXADDRS 20 +#endif +#ifndef MAXDNAME +#define MAXDNAME 1025 +#endif + +#ifdef INET6 +#define ADDRLEN(af) ((af) == AF_INET6 ? sizeof(struct in6_addr) : \ + sizeof(struct in_addr)) +#else +#define ADDRLEN(af) sizeof(struct in_addr) +#endif + +#define MAPADDR(ab, ina) \ +do { \ + memcpy(&(ab)->map_inaddr, ina, sizeof(struct in_addr)); \ + memset((ab)->map_zero, 0, sizeof((ab)->map_zero)); \ + memset((ab)->map_one, 0xff, sizeof((ab)->map_one)); \ +} while (0) +#define MAPADDRENABLED(flags) \ + (((flags) & AI_V4MAPPED) || \ + (((flags) & AI_V4MAPPED_CFG) && _mapped_addr_enabled())) + +union inx_addr { + struct in_addr in_addr; +#ifdef INET6 + struct in6_addr in6_addr; +#endif + struct { + u_char mau_zero[10]; + u_char mau_one[2]; + struct in_addr mau_inaddr; + } map_addr_un; +#define map_zero map_addr_un.mau_zero +#define map_one map_addr_un.mau_one +#define map_inaddr map_addr_un.mau_inaddr +}; + +struct policyqueue { + TAILQ_ENTRY(policyqueue) pc_entry; +#ifdef INET6 + struct in6_addrpolicy pc_policy; +#endif +}; +TAILQ_HEAD(policyhead, policyqueue); + +#define AIO_SRCFLAG_DEPRECATED 0x1 + +struct hp_order { + union { + struct sockaddr_storage aiou_ss; + struct sockaddr aiou_sa; + } aio_src_un; +#define aio_srcsa aio_src_un.aiou_sa + uint32_t aio_srcflag; + int aio_srcscope; + int aio_dstscope; + struct policyqueue *aio_srcpolicy; + struct policyqueue *aio_dstpolicy; + union { + struct sockaddr_storage aiou_ss; + struct sockaddr aiou_sa; + } aio_un; +#define aio_sa aio_un.aiou_sa + int aio_matchlen; + char *aio_h_addr; +}; + +static struct hostent *_hpcopy(struct hostent *, int *); +static struct hostent *_hpaddr(int, const char *, void *, int *); +static struct hostent *_hpmerge(struct hostent *, struct hostent *, int *); +#ifdef INET6 +static struct hostent *_hpmapv6(struct hostent *, int *); +#endif +static struct hostent *_hpsort(struct hostent *, res_state); +static struct hostent *_ghbyname(const char *, int, int, int *); +static char *_hgetword(char **); +static int _mapped_addr_enabled(void); + +static struct hostent *_hpreorder(struct hostent *); +static int get_addrselectpolicy(struct policyhead *); +static void free_addrselectpolicy(struct policyhead *); +static struct policyqueue *match_addrselectpolicy(struct sockaddr *, + struct policyhead *); +static void set_source(struct hp_order *, struct policyhead *); +static int matchlen(struct sockaddr *, struct sockaddr *); +static int comp_dst(const void *, const void *); +static int gai_addr2scopetype(struct sockaddr *); + +static FILE *_files_open(int *); +static int _files_ghbyname(void *, void *, va_list); +static int _files_ghbyaddr(void *, void *, va_list); +#ifdef YP +static int _nis_ghbyname(void *, void *, va_list); +static int _nis_ghbyaddr(void *, void *, va_list); +#endif +static int _dns_ghbyname(void *, void *, va_list); +static int _dns_ghbyaddr(void *, void *, va_list); +static void _dns_shent(int) __unused; +static void _dns_ehent(void) __unused; +#ifdef ICMPNL +static int _icmp_ghbyaddr(void *, void *, va_list); +#endif /* ICMPNL */ + +/* Host lookup order if nsswitch.conf is broken or nonexistant */ +static const ns_src default_src[] = { + { NSSRC_FILES, NS_SUCCESS }, + { NSSRC_DNS, NS_SUCCESS }, +#ifdef ICMPNL +#define NSSRC_ICMP "icmp" + { NSSRC_ICMP, NS_SUCCESS }, +#endif + { 0 } +}; + +/* + * Check if kernel supports mapped address. + * implementation dependent + */ +#ifdef __KAME__ +#include +#endif /* __KAME__ */ + +static int +_mapped_addr_enabled(void) +{ + /* implementation dependent check */ +#if defined(__KAME__) && defined(IPV6CTL_MAPPED_ADDR) + int mib[4]; + size_t len; + int val; + + mib[0] = CTL_NET; + mib[1] = PF_INET6; + mib[2] = IPPROTO_IPV6; + mib[3] = IPV6CTL_MAPPED_ADDR; + len = sizeof(val); + if (sysctl(mib, 4, &val, &len, 0, 0) == 0 && val != 0) + return 1; +#endif /* __KAME__ && IPV6CTL_MAPPED_ADDR */ + return 0; +} + +/* + * Functions defined in RFC2553 + * getipnodebyname, getipnodebyaddr, freehostent + */ + +static struct hostent * +_ghbyname(const char *name, int af, int flags, int *errp) +{ + struct hostent *hp; + int rval; + + static const ns_dtab dtab[] = { + NS_FILES_CB(_files_ghbyname, NULL) + { NSSRC_DNS, _dns_ghbyname, NULL }, + NS_NIS_CB(_nis_ghbyname, NULL) + { 0 } + }; + + if (flags & AI_ADDRCONFIG) { + int s; + + if ((s = _socket(af, SOCK_DGRAM, 0)) < 0) + return NULL; + /* + * TODO: + * Note that implementation dependent test for address + * configuration should be done everytime called + * (or apropriate interval), + * because addresses will be dynamically assigned or deleted. + */ + _close(s); + } + + rval = _nsdispatch(&hp, dtab, NSDB_HOSTS, "ghbyname", default_src, + name, af, errp); + return (rval == NS_SUCCESS) ? hp : NULL; +} + +struct hostent * +getipnodebyname(const char *name, int af, int flags, int *errp) +{ + struct hostent *hp; + union inx_addr addrbuf; + res_state statp; + + switch (af) { + case AF_INET: +#ifdef INET6 + case AF_INET6: +#endif + break; + default: + *errp = NO_RECOVERY; + return NULL; + } + +#ifdef INET6 + /* special case for literal address */ + if (inet_pton(AF_INET6, name, &addrbuf) == 1) { + if (af != AF_INET6) { + *errp = HOST_NOT_FOUND; + return NULL; + } + return _hpaddr(af, name, &addrbuf, errp); + } +#endif + if (inet_aton(name, (struct in_addr *)&addrbuf) == 1) { + if (af != AF_INET) { + if (MAPADDRENABLED(flags)) { + MAPADDR(&addrbuf, &addrbuf.in_addr); + } else { + *errp = HOST_NOT_FOUND; + return NULL; + } + } + return _hpaddr(af, name, &addrbuf, errp); + } + + statp = __res_state(); + if ((statp->options & RES_INIT) == 0) { + if (res_ninit(statp) < 0) { + *errp = NETDB_INTERNAL; + return NULL; + } + } + + *errp = HOST_NOT_FOUND; + hp = _ghbyname(name, af, flags, errp); + +#ifdef INET6 + if (af == AF_INET6 && ((flags & AI_ALL) || hp == NULL) && + MAPADDRENABLED(flags)) { + struct hostent *hp2 = _ghbyname(name, AF_INET, flags, errp); + if (hp == NULL) + hp = _hpmapv6(hp2, errp); + else { + if (hp2 && strcmp(hp->h_name, hp2->h_name) != 0) { + freehostent(hp2); + hp2 = NULL; + } + hp = _hpmerge(hp, hp2, errp); + } + } +#endif + return _hpreorder(_hpsort(hp, statp)); +} + +struct hostent * +getipnodebyaddr(const void *src, size_t len, int af, int *errp) +{ + struct hostent *hp; + int rval; +#ifdef INET6 + struct in6_addr addrbuf; +#else + struct in_addr addrbuf; +#endif + + static const ns_dtab dtab[] = { + NS_FILES_CB(_files_ghbyaddr, NULL) + { NSSRC_DNS, _dns_ghbyaddr, NULL }, + NS_NIS_CB(_nis_ghbyaddr, NULL) +#ifdef ICMPNL + { NSSRC_ICMP, _icmp_ghbyaddr, NULL }, +#endif + { 0 } + }; + + *errp = HOST_NOT_FOUND; + + switch (af) { + case AF_INET: + if (len != sizeof(struct in_addr)) { + *errp = NO_RECOVERY; + return NULL; + } + if ((long)src & ~(sizeof(struct in_addr) - 1)) { + memcpy(&addrbuf, src, len); + src = &addrbuf; + } + if (((struct in_addr *)src)->s_addr == 0) + return NULL; + break; +#ifdef INET6 + case AF_INET6: + if (len != sizeof(struct in6_addr)) { + *errp = NO_RECOVERY; + return NULL; + } + if ((long)src & ~(sizeof(struct in6_addr) / 2 - 1)) { /*XXX*/ + memcpy(&addrbuf, src, len); + src = &addrbuf; + } + if (IN6_IS_ADDR_UNSPECIFIED((struct in6_addr *)src)) + return NULL; + if (IN6_IS_ADDR_V4MAPPED((struct in6_addr *)src) + || IN6_IS_ADDR_V4COMPAT((struct in6_addr *)src)) { + src = (char *)src + + (sizeof(struct in6_addr) - sizeof(struct in_addr)); + af = AF_INET; + len = sizeof(struct in_addr); + } + break; +#endif + default: + *errp = NO_RECOVERY; + return NULL; + } + + rval = _nsdispatch(&hp, dtab, NSDB_HOSTS, "ghbyaddr", default_src, + src, len, af, errp); + return (rval == NS_SUCCESS) ? hp : NULL; +} + +void +freehostent(struct hostent *ptr) +{ + free(ptr); +} + +/* + * Private utility functions + */ + +/* + * _hpcopy: allocate and copy hostent structure + */ +static struct hostent * +_hpcopy(struct hostent *hp, int *errp) +{ + struct hostent *nhp; + char *cp, **pp; + int size, addrsize; + int nalias = 0, naddr = 0; + int al_off; + int i; + + if (hp == NULL) + return hp; + + /* count size to be allocated */ + size = sizeof(struct hostent); + if (hp->h_name != NULL) + size += strlen(hp->h_name) + 1; + if ((pp = hp->h_aliases) != NULL) { + for (i = 0; *pp != NULL; i++, pp++) { + if (**pp != '\0') { + size += strlen(*pp) + 1; + nalias++; + } + } + } + /* adjust alignment */ + size = ALIGN(size); + al_off = size; + size += sizeof(char *) * (nalias + 1); + addrsize = ALIGN(hp->h_length); + if ((pp = hp->h_addr_list) != NULL) { + while (*pp++ != NULL) + naddr++; + } + size += addrsize * naddr; + size += sizeof(char *) * (naddr + 1); + + /* copy */ + if ((nhp = (struct hostent *)malloc(size)) == NULL) { + *errp = TRY_AGAIN; + return NULL; + } + cp = (char *)&nhp[1]; + if (hp->h_name != NULL) { + nhp->h_name = cp; + strcpy(cp, hp->h_name); + cp += strlen(cp) + 1; + } else + nhp->h_name = NULL; + nhp->h_aliases = (char **)((char *)nhp + al_off); + if ((pp = hp->h_aliases) != NULL) { + for (i = 0; *pp != NULL; pp++) { + if (**pp != '\0') { + nhp->h_aliases[i++] = cp; + strcpy(cp, *pp); + cp += strlen(cp) + 1; + } + } + } + nhp->h_aliases[nalias] = NULL; + cp = (char *)&nhp->h_aliases[nalias + 1]; + nhp->h_addrtype = hp->h_addrtype; + nhp->h_length = hp->h_length; + nhp->h_addr_list = (char **)cp; + if ((pp = hp->h_addr_list) != NULL) { + cp = (char *)&nhp->h_addr_list[naddr + 1]; + for (i = 0; *pp != NULL; pp++) { + nhp->h_addr_list[i++] = cp; + memcpy(cp, *pp, hp->h_length); + cp += addrsize; + } + } + nhp->h_addr_list[naddr] = NULL; + return nhp; +} + +/* + * _hpaddr: construct hostent structure with one address + */ +static struct hostent * +_hpaddr(int af, const char *name, void *addr, int *errp) +{ + struct hostent *hp, hpbuf; + char *addrs[2]; + + hp = &hpbuf; + hp->h_name = (char *)name; + hp->h_aliases = NULL; + hp->h_addrtype = af; + hp->h_length = ADDRLEN(af); + hp->h_addr_list = addrs; + addrs[0] = (char *)addr; + addrs[1] = NULL; + return _hpcopy(hp, errp); +} + +/* + * _hpmerge: merge 2 hostent structure, arguments will be freed + */ +static struct hostent * +_hpmerge(struct hostent *hp1, struct hostent *hp2, int *errp) +{ + int i, j; + int naddr, nalias; + char **pp; + struct hostent *hp, hpbuf; + char *aliases[MAXALIASES + 1], *addrs[MAXADDRS + 1]; + union inx_addr addrbuf[MAXADDRS]; + + if (hp1 == NULL) + return hp2; + if (hp2 == NULL) + return hp1; + +#define HP(i) (i == 1 ? hp1 : hp2) + hp = &hpbuf; + hp->h_name = (hp1->h_name != NULL ? hp1->h_name : hp2->h_name); + hp->h_aliases = aliases; + nalias = 0; + for (i = 1; i <= 2; i++) { + if ((pp = HP(i)->h_aliases) == NULL) + continue; + for (; nalias < MAXALIASES && *pp != NULL; pp++) { + /* check duplicates */ + for (j = 0; j < nalias; j++) + if (strcasecmp(*pp, aliases[j]) == 0) + break; + if (j == nalias) + aliases[nalias++] = *pp; + } + } + aliases[nalias] = NULL; +#ifdef INET6 + if (hp1->h_length != hp2->h_length) { + hp->h_addrtype = AF_INET6; + hp->h_length = sizeof(struct in6_addr); + } else { +#endif + hp->h_addrtype = hp1->h_addrtype; + hp->h_length = hp1->h_length; +#ifdef INET6 + } +#endif + hp->h_addr_list = addrs; + naddr = 0; + for (i = 1; i <= 2; i++) { + if ((pp = HP(i)->h_addr_list) == NULL) + continue; + if (HP(i)->h_length == hp->h_length) { + while (naddr < MAXADDRS && *pp != NULL) + addrs[naddr++] = *pp++; + } else { + /* copy IPv4 addr as mapped IPv6 addr */ + while (naddr < MAXADDRS && *pp != NULL) { + MAPADDR(&addrbuf[naddr], *pp++); + addrs[naddr] = (char *)&addrbuf[naddr]; + naddr++; + } + } + } + addrs[naddr] = NULL; + hp = _hpcopy(hp, errp); + freehostent(hp1); + freehostent(hp2); + return hp; +} + +/* + * _hpmapv6: convert IPv4 hostent into IPv4-mapped IPv6 addresses + */ +#ifdef INET6 +static struct hostent * +_hpmapv6(struct hostent *hp, int *errp) +{ + struct hostent *hp6; + + if (hp == NULL) + return NULL; + if (hp->h_addrtype == AF_INET6) + return hp; + + /* make dummy hostent to convert IPv6 address */ + if ((hp6 = (struct hostent *)malloc(sizeof(struct hostent))) == NULL) { + *errp = TRY_AGAIN; + return NULL; + } + hp6->h_name = NULL; + hp6->h_aliases = NULL; + hp6->h_addrtype = AF_INET6; + hp6->h_length = sizeof(struct in6_addr); + hp6->h_addr_list = NULL; + return _hpmerge(hp6, hp, errp); +} +#endif + +/* + * _hpsort: sort address by sortlist + */ +static struct hostent * +_hpsort(struct hostent *hp, res_state statp) +{ + int i, j, n; + u_char *ap, *sp, *mp, **pp; + char t; + char order[MAXADDRS]; + int nsort = statp->nsort; + + if (hp == NULL || hp->h_addr_list[1] == NULL || nsort == 0) + return hp; + for (i = 0; (ap = (u_char *)hp->h_addr_list[i]); i++) { + for (j = 0; j < nsort; j++) { +#ifdef INET6 + if (statp->_u._ext.ext->sort_list[j].af != + hp->h_addrtype) + continue; + sp = (u_char *)&statp->_u._ext.ext->sort_list[j].addr; + mp = (u_char *)&statp->_u._ext.ext->sort_list[j].mask; +#else + sp = (u_char *)&statp->sort_list[j].addr; + mp = (u_char *)&statp->sort_list[j].mask; +#endif + for (n = 0; n < hp->h_length; n++) { + if ((ap[n] & mp[n]) != sp[n]) + break; + } + if (n == hp->h_length) + break; + } + order[i] = j; + } + n = i; + pp = (u_char **)hp->h_addr_list; + for (i = 0; i < n - 1; i++) { + for (j = i + 1; j < n; j++) { + if (order[i] > order[j]) { + ap = pp[i]; + pp[i] = pp[j]; + pp[j] = ap; + t = order[i]; + order[i] = order[j]; + order[j] = t; + } + } + } + return hp; +} + +static char * +_hgetword(char **pp) +{ + char c, *p, *ret; + const char *sp; + static const char sep[] = "# \t\n"; + + ret = NULL; + for (p = *pp; (c = *p) != '\0'; p++) { + for (sp = sep; *sp != '\0'; sp++) { + if (c == *sp) + break; + } + if (c == '#') + p[1] = '\0'; /* ignore rest of line */ + if (ret == NULL) { + if (*sp == '\0') + ret = p; + } else { + if (*sp != '\0') { + *p++ = '\0'; + break; + } + } + } + *pp = p; + if (ret == NULL || *ret == '\0') + return NULL; + return ret; +} + +/* + * _hpreorder: sort address by default address selection + */ +static struct hostent * +_hpreorder(struct hostent *hp) +{ + struct hp_order *aio; + int i, n; + char *ap; + struct sockaddr *sa; + struct policyhead policyhead; + + if (hp == NULL) + return hp; + + switch (hp->h_addrtype) { + case AF_INET: +#ifdef INET6 + case AF_INET6: +#endif + break; + default: + free_addrselectpolicy(&policyhead); + return hp; + } + + /* count the number of addrinfo elements for sorting. */ + for (n = 0; hp->h_addr_list[n] != NULL; n++) + ; + + /* + * If the number is small enough, we can skip the reordering process. + */ + if (n <= 1) + return hp; + + /* allocate a temporary array for sort and initialization of it. */ + if ((aio = malloc(sizeof(*aio) * n)) == NULL) + return hp; /* give up reordering */ + memset(aio, 0, sizeof(*aio) * n); + + /* retrieve address selection policy from the kernel */ + TAILQ_INIT(&policyhead); + if (!get_addrselectpolicy(&policyhead)) { + /* no policy is installed into kernel, we don't sort. */ + free(aio); + return hp; + } + + for (i = 0; i < n; i++) { + ap = hp->h_addr_list[i]; + aio[i].aio_h_addr = ap; + sa = &aio[i].aio_sa; + switch (hp->h_addrtype) { + case AF_INET: + sa->sa_family = AF_INET; + sa->sa_len = sizeof(struct sockaddr_in); + memcpy(&((struct sockaddr_in *)sa)->sin_addr, ap, + sizeof(struct in_addr)); + break; +#ifdef INET6 + case AF_INET6: + if (IN6_IS_ADDR_V4MAPPED((struct in6_addr *)ap)) { + sa->sa_family = AF_INET; + sa->sa_len = sizeof(struct sockaddr_in); + memcpy(&((struct sockaddr_in *)sa)->sin_addr, + &ap[12], sizeof(struct in_addr)); + } else { + sa->sa_family = AF_INET6; + sa->sa_len = sizeof(struct sockaddr_in6); + memcpy(&((struct sockaddr_in6 *)sa)->sin6_addr, + ap, sizeof(struct in6_addr)); + } + break; +#endif + } + aio[i].aio_dstscope = gai_addr2scopetype(sa); + aio[i].aio_dstpolicy = match_addrselectpolicy(sa, &policyhead); + set_source(&aio[i], &policyhead); + } + + /* perform sorting. */ + qsort(aio, n, sizeof(*aio), comp_dst); + + /* reorder the h_addr_list. */ + for (i = 0; i < n; i++) + hp->h_addr_list[i] = aio[i].aio_h_addr; + + /* cleanup and return */ + free(aio); + free_addrselectpolicy(&policyhead); + return hp; +} + +static int +get_addrselectpolicy(struct policyhead *head) +{ +#ifdef INET6 + int mib[] = { CTL_NET, PF_INET6, IPPROTO_IPV6, IPV6CTL_ADDRCTLPOLICY }; + size_t l; + char *buf; + struct in6_addrpolicy *pol, *ep; + + if (sysctl(mib, sizeof(mib) / sizeof(mib[0]), NULL, &l, NULL, 0) < 0) + return (0); + if ((buf = malloc(l)) == NULL) + return (0); + if (sysctl(mib, sizeof(mib) / sizeof(mib[0]), buf, &l, NULL, 0) < 0) { + free(buf); + return (0); + } + + ep = (struct in6_addrpolicy *)(buf + l); + for (pol = (struct in6_addrpolicy *)buf; pol + 1 <= ep; pol++) { + struct policyqueue *new; + + if ((new = malloc(sizeof(*new))) == NULL) { + free_addrselectpolicy(head); /* make the list empty */ + break; + } + new->pc_policy = *pol; + TAILQ_INSERT_TAIL(head, new, pc_entry); + } + + free(buf); + return (1); +#else + return (0); +#endif +} + +static void +free_addrselectpolicy(struct policyhead *head) +{ + struct policyqueue *ent, *nent; + + for (ent = TAILQ_FIRST(head); ent; ent = nent) { + nent = TAILQ_NEXT(ent, pc_entry); + TAILQ_REMOVE(head, ent, pc_entry); + free(ent); + } +} + +static struct policyqueue * +match_addrselectpolicy(struct sockaddr *addr, struct policyhead *head) +{ +#ifdef INET6 + struct policyqueue *ent, *bestent = NULL; + struct in6_addrpolicy *pol; + int matchlen, bestmatchlen = -1; + u_char *mp, *ep, *k, *p, m; + struct sockaddr_in6 key; + + switch(addr->sa_family) { + case AF_INET6: + key = *(struct sockaddr_in6 *)addr; + break; + case AF_INET: + /* convert the address into IPv4-mapped IPv6 address. */ + memset(&key, 0, sizeof(key)); + key.sin6_family = AF_INET6; + key.sin6_len = sizeof(key); + key.sin6_addr.s6_addr[10] = 0xff; + key.sin6_addr.s6_addr[11] = 0xff; + memcpy(&key.sin6_addr.s6_addr[12], + &((struct sockaddr_in *)addr)->sin_addr, 4); + break; + default: + return(NULL); + } + + for (ent = TAILQ_FIRST(head); ent; ent = TAILQ_NEXT(ent, pc_entry)) { + pol = &ent->pc_policy; + matchlen = 0; + + mp = (u_char *)&pol->addrmask.sin6_addr; + ep = mp + 16; /* XXX: scope field? */ + k = (u_char *)&key.sin6_addr; + p = (u_char *)&pol->addr.sin6_addr; + for (; mp < ep && *mp; mp++, k++, p++) { + m = *mp; + if ((*k & m) != *p) + goto next; /* not match */ + if (m == 0xff) /* short cut for a typical case */ + matchlen += 8; + else { + while (m >= 0x80) { + matchlen++; + m <<= 1; + } + } + } + + /* matched. check if this is better than the current best. */ + if (matchlen > bestmatchlen) { + bestent = ent; + bestmatchlen = matchlen; + } + + next: + continue; + } + + return(bestent); +#else + return(NULL); +#endif + +} + +static void +set_source(struct hp_order *aio, struct policyhead *ph) +{ + struct sockaddr_storage ss = aio->aio_un.aiou_ss; + socklen_t srclen; + int s; + + /* set unspec ("no source is available"), just in case */ + aio->aio_srcsa.sa_family = AF_UNSPEC; + aio->aio_srcscope = -1; + + switch(ss.ss_family) { + case AF_INET: + ((struct sockaddr_in *)&ss)->sin_port = htons(1); + break; +#ifdef INET6 + case AF_INET6: + ((struct sockaddr_in6 *)&ss)->sin6_port = htons(1); + break; +#endif + default: /* ignore unsupported AFs explicitly */ + return; + } + + /* open a socket to get the source address for the given dst */ + if ((s = _socket(ss.ss_family, SOCK_DGRAM, IPPROTO_UDP)) < 0) + return; /* give up */ + if (_connect(s, (struct sockaddr *)&ss, ss.ss_len) < 0) + goto cleanup; + srclen = ss.ss_len; + if (_getsockname(s, &aio->aio_srcsa, &srclen) < 0) { + aio->aio_srcsa.sa_family = AF_UNSPEC; + goto cleanup; + } + aio->aio_srcscope = gai_addr2scopetype(&aio->aio_srcsa); + aio->aio_srcpolicy = match_addrselectpolicy(&aio->aio_srcsa, ph); + aio->aio_matchlen = matchlen(&aio->aio_srcsa, (struct sockaddr *)&ss); +#ifdef INET6 + if (ss.ss_family == AF_INET6) { + struct in6_ifreq ifr6; + uint32_t flags6; + + /* XXX: interface name should not be hardcoded */ + strncpy(ifr6.ifr_name, "lo0", sizeof(ifr6.ifr_name)); + memset(&ifr6, 0, sizeof(ifr6)); + memcpy(&ifr6.ifr_addr, &ss, ss.ss_len); + if (_ioctl(s, SIOCGIFAFLAG_IN6, &ifr6) == 0) { + flags6 = ifr6.ifr_ifru.ifru_flags6; + if ((flags6 & IN6_IFF_DEPRECATED)) + aio->aio_srcflag |= AIO_SRCFLAG_DEPRECATED; + } + } +#endif + + cleanup: + _close(s); + return; +} + +static int +matchlen(struct sockaddr *src, struct sockaddr *dst) +{ + int match = 0; + u_char *s, *d; + u_char *lim, r; + int addrlen; + + switch (src->sa_family) { +#ifdef INET6 + case AF_INET6: + s = (u_char *)&((struct sockaddr_in6 *)src)->sin6_addr; + d = (u_char *)&((struct sockaddr_in6 *)dst)->sin6_addr; + addrlen = sizeof(struct in6_addr); + lim = s + addrlen; + break; +#endif + case AF_INET: + s = (u_char *)&((struct sockaddr_in *)src)->sin_addr; + d = (u_char *)&((struct sockaddr_in *)dst)->sin_addr; + addrlen = sizeof(struct in_addr); + lim = s + addrlen; + break; + default: + return(0); + } + + while (s < lim) + if ((r = (*d++ ^ *s++)) != 0) { + while (r < addrlen * 8) { + match++; + r <<= 1; + } + break; + } else + match += 8; + return(match); +} + +static int +comp_dst(const void *arg1, const void *arg2) +{ + const struct hp_order *dst1 = arg1, *dst2 = arg2; + + /* + * Rule 1: Avoid unusable destinations. + * XXX: we currently do not consider if an appropriate route exists. + */ + if (dst1->aio_srcsa.sa_family != AF_UNSPEC && + dst2->aio_srcsa.sa_family == AF_UNSPEC) { + return(-1); + } + if (dst1->aio_srcsa.sa_family == AF_UNSPEC && + dst2->aio_srcsa.sa_family != AF_UNSPEC) { + return(1); + } + + /* Rule 2: Prefer matching scope. */ + if (dst1->aio_dstscope == dst1->aio_srcscope && + dst2->aio_dstscope != dst2->aio_srcscope) { + return(-1); + } + if (dst1->aio_dstscope != dst1->aio_srcscope && + dst2->aio_dstscope == dst2->aio_srcscope) { + return(1); + } + + /* Rule 3: Avoid deprecated addresses. */ + if (dst1->aio_srcsa.sa_family != AF_UNSPEC && + dst2->aio_srcsa.sa_family != AF_UNSPEC) { + if (!(dst1->aio_srcflag & AIO_SRCFLAG_DEPRECATED) && + (dst2->aio_srcflag & AIO_SRCFLAG_DEPRECATED)) { + return(-1); + } + if ((dst1->aio_srcflag & AIO_SRCFLAG_DEPRECATED) && + !(dst2->aio_srcflag & AIO_SRCFLAG_DEPRECATED)) { + return(1); + } + } + + /* Rule 4: Prefer home addresses. */ + /* XXX: not implemented yet */ + + /* Rule 5: Prefer matching label. */ +#ifdef INET6 + if (dst1->aio_srcpolicy && dst1->aio_dstpolicy && + dst1->aio_srcpolicy->pc_policy.label == + dst1->aio_dstpolicy->pc_policy.label && + (dst2->aio_srcpolicy == NULL || dst2->aio_dstpolicy == NULL || + dst2->aio_srcpolicy->pc_policy.label != + dst2->aio_dstpolicy->pc_policy.label)) { + return(-1); + } + if (dst2->aio_srcpolicy && dst2->aio_dstpolicy && + dst2->aio_srcpolicy->pc_policy.label == + dst2->aio_dstpolicy->pc_policy.label && + (dst1->aio_srcpolicy == NULL || dst1->aio_dstpolicy == NULL || + dst1->aio_srcpolicy->pc_policy.label != + dst1->aio_dstpolicy->pc_policy.label)) { + return(1); + } +#endif + + /* Rule 6: Prefer higher precedence. */ +#ifdef INET6 + if (dst1->aio_dstpolicy && + (dst2->aio_dstpolicy == NULL || + dst1->aio_dstpolicy->pc_policy.preced > + dst2->aio_dstpolicy->pc_policy.preced)) { + return(-1); + } + if (dst2->aio_dstpolicy && + (dst1->aio_dstpolicy == NULL || + dst2->aio_dstpolicy->pc_policy.preced > + dst1->aio_dstpolicy->pc_policy.preced)) { + return(1); + } +#endif + + /* Rule 7: Prefer native transport. */ + /* XXX: not implemented yet */ + + /* Rule 8: Prefer smaller scope. */ + if (dst1->aio_dstscope >= 0 && + dst1->aio_dstscope < dst2->aio_dstscope) { + return(-1); + } + if (dst2->aio_dstscope >= 0 && + dst2->aio_dstscope < dst1->aio_dstscope) { + return(1); + } + + /* + * Rule 9: Use longest matching prefix. + * We compare the match length in a same AF only. + */ + if (dst1->aio_sa.sa_family == dst2->aio_sa.sa_family) { + if (dst1->aio_matchlen > dst2->aio_matchlen) { + return(-1); + } + if (dst1->aio_matchlen < dst2->aio_matchlen) { + return(1); + } + } + + /* Rule 10: Otherwise, leave the order unchanged. */ + return(-1); +} + +/* + * Copy from scope.c. + * XXX: we should standardize the functions and link them as standard + * library. + */ +static int +gai_addr2scopetype(struct sockaddr *sa) +{ +#ifdef INET6 + struct sockaddr_in6 *sa6; +#endif + struct sockaddr_in *sa4; + + switch(sa->sa_family) { +#ifdef INET6 + case AF_INET6: + sa6 = (struct sockaddr_in6 *)sa; + if (IN6_IS_ADDR_MULTICAST(&sa6->sin6_addr)) { + /* just use the scope field of the multicast address */ + return(sa6->sin6_addr.s6_addr[2] & 0x0f); + } + /* + * Unicast addresses: map scope type to corresponding scope + * value defined for multcast addresses. + * XXX: hardcoded scope type values are bad... + */ + if (IN6_IS_ADDR_LOOPBACK(&sa6->sin6_addr)) + return(1); /* node local scope */ + if (IN6_IS_ADDR_LINKLOCAL(&sa6->sin6_addr)) + return(2); /* link-local scope */ + if (IN6_IS_ADDR_SITELOCAL(&sa6->sin6_addr)) + return(5); /* site-local scope */ + return(14); /* global scope */ + break; +#endif + case AF_INET: + /* + * IPv4 pseudo scoping according to RFC 3484. + */ + sa4 = (struct sockaddr_in *)sa; + /* IPv4 autoconfiguration addresses have link-local scope. */ + if (((u_char *)&sa4->sin_addr)[0] == 169 && + ((u_char *)&sa4->sin_addr)[1] == 254) + return(2); + /* Private addresses have site-local scope. */ + if (((u_char *)&sa4->sin_addr)[0] == 10 || + (((u_char *)&sa4->sin_addr)[0] == 172 && + (((u_char *)&sa4->sin_addr)[1] & 0xf0) == 16) || + (((u_char *)&sa4->sin_addr)[0] == 192 && + ((u_char *)&sa4->sin_addr)[1] == 168)) + return(14); /* XXX: It should be 5 unless NAT */ + /* Loopback addresses have link-local scope. */ + if (((u_char *)&sa4->sin_addr)[0] == 127) + return(2); + return(14); + break; + default: + errno = EAFNOSUPPORT; /* is this a good error? */ + return(-1); + } +} + +/* + * FILES (/etc/hosts) + */ + +static FILE * +_files_open(int *errp) +{ + FILE *fp; + fp = fopen(_PATH_HOSTS, "r"); + if (fp == NULL) + *errp = NO_RECOVERY; + return fp; +} + +static int +_files_ghbyname(void *rval, void *cb_data, va_list ap) +{ + const char *name; + int af; + int *errp; + int match, nalias; + char *p, *line, *addrstr, *cname; + FILE *fp; + struct hostent *rethp, *hp, hpbuf; + char *aliases[MAXALIASES + 1], *addrs[2]; + union inx_addr addrbuf; + char buf[BUFSIZ]; + + name = va_arg(ap, const char *); + af = va_arg(ap, int); + errp = va_arg(ap, int *); + + *(struct hostent **)rval = NULL; + + if ((fp = _files_open(errp)) == NULL) + return NS_UNAVAIL; + rethp = hp = NULL; + + while (fgets(buf, sizeof(buf), fp)) { + line = buf; + if ((addrstr = _hgetword(&line)) == NULL + || (cname = _hgetword(&line)) == NULL) + continue; + match = (strcasecmp(cname, name) == 0); + nalias = 0; + while ((p = _hgetword(&line)) != NULL) { + if (!match) + match = (strcasecmp(p, name) == 0); + if (nalias < MAXALIASES) + aliases[nalias++] = p; + } + if (!match) + continue; + switch (af) { + case AF_INET: + if (inet_aton(addrstr, (struct in_addr *)&addrbuf) + != 1) { + *errp = NO_DATA; /* name found */ + continue; + } + break; +#ifdef INET6 + case AF_INET6: + if (inet_pton(af, addrstr, &addrbuf) != 1) { + *errp = NO_DATA; /* name found */ + continue; + } + break; +#endif + } + hp = &hpbuf; + hp->h_name = cname; + hp->h_aliases = aliases; + aliases[nalias] = NULL; + hp->h_addrtype = af; + hp->h_length = ADDRLEN(af); + hp->h_addr_list = addrs; + addrs[0] = (char *)&addrbuf; + addrs[1] = NULL; + hp = _hpcopy(hp, errp); + rethp = _hpmerge(rethp, hp, errp); + } + fclose(fp); + *(struct hostent **)rval = rethp; + return (rethp != NULL) ? NS_SUCCESS : NS_NOTFOUND; +} + +static int +_files_ghbyaddr(void *rval, void *cb_data, va_list ap) +{ + const void *addr; + int addrlen; + int af; + int *errp; + int nalias; + char *p, *line; + FILE *fp; + struct hostent *hp, hpbuf; + char *aliases[MAXALIASES + 1], *addrs[2]; + union inx_addr addrbuf; + char buf[BUFSIZ]; + + addr = va_arg(ap, const void *); + addrlen = va_arg(ap, int); + af = va_arg(ap, int); + errp = va_arg(ap, int *); + + *(struct hostent**)rval = NULL; + + if ((fp = _files_open(errp)) == NULL) + return NS_UNAVAIL; + hp = NULL; + while (fgets(buf, sizeof(buf), fp)) { + line = buf; + if ((p = _hgetword(&line)) == NULL + || (af == AF_INET + ? inet_aton(p, (struct in_addr *)&addrbuf) + : inet_pton(af, p, &addrbuf)) != 1 + || memcmp(addr, &addrbuf, addrlen) != 0 + || (p = _hgetword(&line)) == NULL) + continue; + hp = &hpbuf; + hp->h_name = p; + hp->h_aliases = aliases; + nalias = 0; + while ((p = _hgetword(&line)) != NULL) { + if (nalias < MAXALIASES) + aliases[nalias++] = p; + } + aliases[nalias] = NULL; + hp->h_addrtype = af; + hp->h_length = addrlen; + hp->h_addr_list = addrs; + addrs[0] = (char *)&addrbuf; + addrs[1] = NULL; + hp = _hpcopy(hp, errp); + break; + } + fclose(fp); + *(struct hostent **)rval = hp; + return (hp != NULL) ? NS_SUCCESS : NS_NOTFOUND; +} + +#ifdef YP +/* + * NIS + * + * XXX actually a hack. + */ +static int +_nis_ghbyname(void *rval, void *cb_data, va_list ap) +{ + const char *name; + int af; + int *errp; + struct hostent *hp = NULL; + + name = va_arg(ap, const char *); + af = va_arg(ap, int); + errp = va_arg(ap, int *); + + hp = _gethostbynisname(name, af); + if (hp != NULL) + hp = _hpcopy(hp, errp); + + *(struct hostent **)rval = hp; + return (hp != NULL) ? NS_SUCCESS : NS_NOTFOUND; +} + +static int +_nis_ghbyaddr(void *rval, void *cb_data, va_list ap) +{ + const void *addr; + int addrlen; + int af; + int *errp; + struct hostent *hp = NULL; + + addr = va_arg(ap, const void *); + addrlen = va_arg(ap, int); + af = va_arg(ap, int); + + hp = _gethostbynisaddr(addr, addrlen, af); + if (hp != NULL) + hp = _hpcopy(hp, errp); + *(struct hostent **)rval = hp; + return (hp != NULL) ? NS_SUCCESS : NS_NOTFOUND; +} +#endif + +#define MAXPACKET (64*1024) + +typedef union { + HEADER hdr; + u_char buf[MAXPACKET]; +} querybuf; + +static struct hostent *getanswer(const querybuf *, int, const char *, int, + struct hostent *, int *); + +/* + * we don't need to take care about sorting, nor IPv4 mapped address here. + */ +static struct hostent * +getanswer(const querybuf *answer, int anslen, const char *qname, int qtype, + struct hostent *template, int *errp) +{ + const HEADER *hp; + const u_char *cp; + int n; + const u_char *eom, *erdata; + char *bp, *ep, **ap, **hap; + int type, class, ancount, qdcount; + int haveanswer, had_error; + char tbuf[MAXDNAME]; + const char *tname; + int (*name_ok)(const char *); + static char *h_addr_ptrs[MAXADDRS + 1]; + static char *host_aliases[MAXALIASES]; + static char hostbuf[8*1024]; + +#define BOUNDED_INCR(x) \ + do { \ + cp += x; \ + if (cp > eom) { \ + *errp = NO_RECOVERY; \ + return (NULL); \ + } \ + } while (0) + +#define BOUNDS_CHECK(ptr, count) \ + do { \ + if ((ptr) + (count) > eom) { \ + *errp = NO_RECOVERY; \ + return (NULL); \ + } \ + } while (0) + +/* XXX do {} while (0) cannot be put here */ +#define DNS_ASSERT(x) \ + { \ + if (!(x)) { \ + cp += n; \ + continue; \ + } \ + } + +/* XXX do {} while (0) cannot be put here */ +#define DNS_FATAL(x) \ + { \ + if (!(x)) { \ + had_error++; \ + continue; \ + } \ + } + + tname = qname; + template->h_name = NULL; + eom = answer->buf + anslen; + switch (qtype) { + case T_A: + case T_AAAA: + name_ok = res_hnok; + break; + case T_PTR: + name_ok = res_dnok; + break; + default: + return (NULL); /* XXX should be abort(); */ + } + /* + * find first satisfactory answer + */ + hp = &answer->hdr; + ancount = ntohs(hp->ancount); + qdcount = ntohs(hp->qdcount); + bp = hostbuf; + ep = hostbuf + sizeof hostbuf; + cp = answer->buf; + BOUNDED_INCR(HFIXEDSZ); + if (qdcount != 1) { + *errp = NO_RECOVERY; + return (NULL); + } + n = dn_expand(answer->buf, eom, cp, bp, ep - bp); + if ((n < 0) || !(*name_ok)(bp)) { + *errp = NO_RECOVERY; + return (NULL); + } + BOUNDED_INCR(n + QFIXEDSZ); + if (qtype == T_A || qtype == T_AAAA) { + /* res_send() has already verified that the query name is the + * same as the one we sent; this just gets the expanded name + * (i.e., with the succeeding search-domain tacked on). + */ + n = strlen(bp) + 1; /* for the \0 */ + if (n >= MAXHOSTNAMELEN) { + *errp = NO_RECOVERY; + return (NULL); + } + template->h_name = bp; + bp += n; + /* The qname can be abbreviated, but h_name is now absolute. */ + qname = template->h_name; + } + ap = host_aliases; + *ap = NULL; + template->h_aliases = host_aliases; + hap = h_addr_ptrs; + *hap = NULL; + template->h_addr_list = h_addr_ptrs; + haveanswer = 0; + had_error = 0; + while (ancount-- > 0 && cp < eom && !had_error) { + n = dn_expand(answer->buf, eom, cp, bp, ep - bp); + DNS_FATAL(n >= 0); + DNS_FATAL((*name_ok)(bp)); + cp += n; /* name */ + BOUNDS_CHECK(cp, 3 * INT16SZ + INT32SZ); + type = _getshort(cp); + cp += INT16SZ; /* type */ + class = _getshort(cp); + cp += INT16SZ + INT32SZ; /* class, TTL */ + n = _getshort(cp); + cp += INT16SZ; /* len */ + BOUNDS_CHECK(cp, n); + erdata = cp + n; + DNS_ASSERT(class == C_IN); + if ((qtype == T_A || qtype == T_AAAA) && type == T_CNAME) { + if (ap >= &host_aliases[MAXALIASES-1]) + continue; + n = dn_expand(answer->buf, eom, cp, tbuf, sizeof tbuf); + DNS_FATAL(n >= 0); + DNS_FATAL((*name_ok)(tbuf)); + cp += n; + if (cp != erdata) { + *errp = NO_RECOVERY; + return (NULL); + } + /* Store alias. */ + *ap++ = bp; + n = strlen(bp) + 1; /* for the \0 */ + DNS_FATAL(n < MAXHOSTNAMELEN); + bp += n; + /* Get canonical name. */ + n = strlen(tbuf) + 1; /* for the \0 */ + DNS_FATAL(n <= ep - bp); + DNS_FATAL(n < MAXHOSTNAMELEN); + strcpy(bp, tbuf); + template->h_name = bp; + bp += n; + continue; + } + if (qtype == T_PTR && type == T_CNAME) { + n = dn_expand(answer->buf, eom, cp, tbuf, sizeof tbuf); + if (n < 0 || !res_dnok(tbuf)) { + had_error++; + continue; + } + cp += n; + if (cp != erdata) { + *errp = NO_RECOVERY; + return (NULL); + } + /* Get canonical name. */ + n = strlen(tbuf) + 1; /* for the \0 */ + if (n > ep - bp || n >= MAXHOSTNAMELEN) { + had_error++; + continue; + } + strcpy(bp, tbuf); + tname = bp; + bp += n; + continue; + } + DNS_ASSERT(type == qtype); + switch (type) { + case T_PTR: + DNS_ASSERT(strcasecmp(tname, bp) == 0); + n = dn_expand(answer->buf, eom, cp, bp, ep - bp); + DNS_FATAL(n >= 0); + DNS_FATAL(res_hnok(bp)); +#if MULTI_PTRS_ARE_ALIASES + cp += n; + if (cp != erdata) { + *errp = NO_RECOVERY; + return (NULL); + } + if (!haveanswer) + template->h_name = bp; + else if (ap < &host_aliases[MAXALIASES-1]) + *ap++ = bp; + else + n = -1; + if (n != -1) { + n = strlen(bp) + 1; /* for the \0 */ + if (n >= MAXHOSTNAMELEN) { + had_error++; + break; + } + bp += n; + } + break; +#else + template->h_name = bp; + *errp = NETDB_SUCCESS; + return (template); +#endif + case T_A: + case T_AAAA: + DNS_ASSERT(strcasecmp(template->h_name, bp) == 0); + DNS_ASSERT(n == template->h_length); + if (!haveanswer) { + int nn; + + template->h_name = bp; + nn = strlen(bp) + 1; /* for the \0 */ + bp += nn; + } + bp = (char *)ALIGN(bp); + + DNS_FATAL(bp + n < ep); + DNS_ASSERT(hap < &h_addr_ptrs[MAXADDRS-1]); +#ifdef FILTER_V4MAPPED + if (type == T_AAAA) { + struct in6_addr in6; + memcpy(&in6, cp, sizeof(in6)); + DNS_ASSERT(IN6_IS_ADDR_V4MAPPED(&in6) == 0); + } +#endif + bcopy(cp, *hap++ = bp, n); + bp += n; + cp += n; + if (cp != erdata) { + *errp = NO_RECOVERY; + return (NULL); + } + break; + default: + abort(); + } + if (!had_error) + haveanswer++; + } + if (haveanswer) { + *ap = NULL; + *hap = NULL; + if (!template->h_name) { + n = strlen(qname) + 1; /* for the \0 */ + if (n > ep - bp || n >= MAXHOSTNAMELEN) + goto no_recovery; + strcpy(bp, qname); + template->h_name = bp; + bp += n; + } + *errp = NETDB_SUCCESS; + return (template); + } + no_recovery: + *errp = NO_RECOVERY; + return (NULL); + +#undef BOUNDED_INCR +#undef BOUNDS_CHECK +#undef DNS_ASSERT +#undef DNS_FATAL +} + +static int +_dns_ghbyname(void *rval, void *cb_data, va_list ap) +{ + const char *name; + int af; + int *errp; + int n; + struct hostent *hp; + int qtype; + struct hostent hbuf; + querybuf *buf; + res_state statp; + + name = va_arg(ap, const char *); + af = va_arg(ap, int); + errp = va_arg(ap, int *); + + statp = __res_state(); + + memset(&hbuf, 0, sizeof(hbuf)); + hbuf.h_addrtype = af; + hbuf.h_length = ADDRLEN(af); + + switch (af) { +#ifdef INET6 + case AF_INET6: + qtype = T_AAAA; + break; +#endif + case AF_INET: + qtype = T_A; + break; + default: + *errp = NO_RECOVERY; + return NS_NOTFOUND; + } + buf = malloc(sizeof(*buf)); + if (buf == NULL) { + *errp = NETDB_INTERNAL; + return NS_UNAVAIL; + } + n = res_nsearch(statp, name, C_IN, qtype, buf->buf, sizeof(buf->buf)); + if (n < 0) { + free(buf); + *errp = statp->res_h_errno; + return NS_UNAVAIL; + } + hp = getanswer(buf, n, name, qtype, &hbuf, errp); + free(buf); + if (!hp) { + *errp = NO_RECOVERY; + return NS_NOTFOUND; + } + *(struct hostent **)rval = _hpcopy(&hbuf, errp); + if (*(struct hostent **)rval != NULL) + return NS_SUCCESS; + else if (*errp == TRY_AGAIN) + return NS_TRYAGAIN; + else + return NS_NOTFOUND; +} + +static int +_dns_ghbyaddr(void *rval, void *cb_data, va_list ap) +{ + const void *addr; + int addrlen; + int af; + int *errp; + int n; + int err; + struct hostent *hp; + u_char c, *cp; + char *bp; + struct hostent hbuf; +#ifdef INET6 + static const char hex[] = "0123456789abcdef"; +#endif + querybuf *buf; + char qbuf[MAXDNAME+1]; + char *hlist[2]; + char *tld6[] = { "ip6.arpa", NULL }; + char *tld4[] = { "in-addr.arpa", NULL }; + char **tld; + res_state statp; + + addr = va_arg(ap, const void *); + addrlen = va_arg(ap, int); + af = va_arg(ap, int); + errp = va_arg(ap, int *); + + *(struct hostent **)rval = NULL; + +#ifdef INET6 + /* XXX */ + if (af == AF_INET6 && IN6_IS_ADDR_LINKLOCAL((struct in6_addr *)addr)) + return NS_NOTFOUND; +#endif + + switch (af) { +#ifdef INET6 + case AF_INET6: + tld = tld6; + break; +#endif + case AF_INET: + tld = tld4; + break; + default: + return NS_NOTFOUND; + } + + statp = __res_state(); + if ((statp->options & RES_INIT) == 0) { + if (res_ninit(statp) < 0) { + *errp = NETDB_INTERNAL; + return NS_UNAVAIL; + } + } + memset(&hbuf, 0, sizeof(hbuf)); + hbuf.h_name = NULL; + hbuf.h_addrtype = af; + hbuf.h_length = addrlen; + + buf = malloc(sizeof(*buf)); + if (buf == NULL) { + *errp = NETDB_INTERNAL; + return NS_UNAVAIL; + } + err = NS_SUCCESS; + for (/* nothing */; *tld; tld++) { + /* + * XXX assumes that MAXDNAME is big enough - error checks + * has been made by callers + */ + n = 0; + bp = qbuf; + cp = (u_char *)addr+addrlen-1; + switch (af) { +#ifdef INET6 + case AF_INET6: + for (; n < addrlen; n++, cp--) { + c = *cp; + *bp++ = hex[c & 0xf]; + *bp++ = '.'; + *bp++ = hex[c >> 4]; + *bp++ = '.'; + } + strcpy(bp, *tld); + break; +#endif + case AF_INET: + for (; n < addrlen; n++, cp--) { + c = *cp; + if (c >= 100) + *bp++ = '0' + c / 100; + if (c >= 10) + *bp++ = '0' + (c % 100) / 10; + *bp++ = '0' + c % 10; + *bp++ = '.'; + } + strcpy(bp, *tld); + break; + } + + n = res_nquery(statp, qbuf, C_IN, T_PTR, buf->buf, + sizeof buf->buf); + if (n < 0) { + *errp = statp->res_h_errno; + err = NS_UNAVAIL; + continue; + } else if (n > sizeof(buf->buf)) { +#if 0 + errno = ERANGE; /* XXX is it OK to set errno here? */ +#endif + *errp = NETDB_INTERNAL; + err = NS_UNAVAIL; + continue; + } + hp = getanswer(buf, n, qbuf, T_PTR, &hbuf, errp); + if (!hp) { + err = NS_NOTFOUND; + continue; + } + free(buf); + hbuf.h_addrtype = af; + hbuf.h_length = addrlen; + hbuf.h_addr_list = hlist; + hlist[0] = (char *)addr; + hlist[1] = NULL; + *(struct hostent **)rval = _hpcopy(&hbuf, errp); + return NS_SUCCESS; + } + free(buf); + return err; +} + +static void +_dns_shent(int stayopen) +{ + res_state statp; + + statp = __res_state(); + if ((statp->options & RES_INIT) == 0) { + if (res_ninit(statp) < 0) + return; + } + if (stayopen) + statp->options |= RES_STAYOPEN | RES_USEVC; +} + +static void +_dns_ehent(void) +{ + res_state statp; + + statp = __res_state(); + statp->options &= ~(RES_STAYOPEN | RES_USEVC); + res_nclose(statp); +} + +#ifdef ICMPNL + +/* + * experimental: + * draft-ietf-ipngwg-icmp-namelookups-09.txt + * ifindex is assumed to be encoded in addr. + */ +#include +#include +#include +#include + +#ifndef NI_QTYPE_NODENAME +#define NI_QTYPE_NODENAME NI_QTYPE_DNSNAME +#endif + +static char * +dnsdecode(sp, ep, base, buf, bufsiz) + const u_char **sp; + const u_char *ep; + const u_char *base; /*base for compressed name*/ + u_char *buf; + size_t bufsiz; +{ + int i; + const u_char *cp; + char cresult[MAXDNAME + 1]; + const u_char *comp; + int l; + + cp = *sp; + *buf = '\0'; + + if (cp >= ep) + return NULL; + while (cp < ep) { + i = *cp; + if (i == 0 || cp != *sp) { + if (strlcat(buf, ".", bufsiz) >= bufsiz) + return NULL; /* result overrun */ + } + if (i == 0) + break; + cp++; + + if ((i & 0xc0) == 0xc0 && cp - base > (i & 0x3f)) { + /* DNS compression */ + if (!base) + return NULL; + + comp = base + (i & 0x3f); + if (dnsdecode(&comp, cp, base, cresult, + sizeof(cresult)) == NULL) + return NULL; + if (strlcat(buf, cresult, bufsiz) >= bufsiz) + return NULL; /* result overrun */ + break; + } else if ((i & 0x3f) == i) { + if (i > ep - cp) + return NULL; /* source overrun */ + while (i-- > 0 && cp < ep) { + l = snprintf(cresult, sizeof(cresult), + isprint(*cp) ? "%c" : "\\%03o", *cp & 0xff); + if (l >= sizeof(cresult) || l < 0) + return NULL; + if (strlcat(buf, cresult, bufsiz) >= bufsiz) + return NULL; /* result overrun */ + cp++; + } + } else + return NULL; /* invalid label */ + } + if (i != 0) + return NULL; /* not terminated */ + cp++; + *sp = cp; + return buf; +} + +static char * +_icmp_nodeinfo_query(const struct in6_addr *addr, int ifindex, char *dnsname) +{ + int s; + struct icmp6_filter filter; + struct msghdr msg; + struct cmsghdr *cmsg; + struct in6_pktinfo *pkt; + char cbuf[256], buf[1024], *cp, *end; + int cc; + struct icmp6_nodeinfo niq, *nir; + struct sockaddr_in6 sin6; + struct iovec iov; + fd_set s_fds, fds; + struct timeval tout; + int len; + static int pid; + uint32_t r1, r2; + + if (pid == 0) + pid = getpid(); + + ICMP6_FILTER_SETBLOCKALL(&filter); + ICMP6_FILTER_SETPASS(ICMP6_NI_REPLY, &filter); + + FD_ZERO(&s_fds); + tout.tv_sec = 0; + tout.tv_usec = 500000; /* 500ms */ + + memset(&niq, 0, sizeof(niq)); + niq.ni_type = ICMP6_NI_QUERY; + niq.ni_code = ICMP6_NI_SUBJ_IPV6; + niq.ni_qtype = htons(NI_QTYPE_NODENAME); + niq.ni_flags = 0; + r1 = arc4random(); + r2 = arc4random(); + memcpy(&niq.icmp6_ni_nonce[0], &r1, sizeof(r1)); + memcpy(&niq.icmp6_ni_nonce[4], &r2, sizeof(r2)); + + memset(&sin6, 0, sizeof(sin6)); + sin6.sin6_family = AF_INET6; + sin6.sin6_addr = *addr; + + memset(&msg, 0, sizeof(msg)); + msg.msg_name = (caddr_t)&sin6; + msg.msg_namelen = sizeof(sin6); + msg.msg_iov = &iov; + msg.msg_iovlen = 1; + msg.msg_control = NULL; + msg.msg_controllen = 0; + iov.iov_base = (caddr_t)&niq; + iov.iov_len = sizeof(struct icmp6_nodeinfo); + + if (ifindex) { + msg.msg_control = cbuf; + msg.msg_controllen = sizeof(cbuf); + cmsg = CMSG_FIRSTHDR(&msg); + cmsg->cmsg_len = CMSG_LEN(sizeof(struct in6_pktinfo)); + cmsg->cmsg_level = IPPROTO_IPV6; + cmsg->cmsg_type = IPV6_PKTINFO; + pkt = (struct in6_pktinfo *)&cmsg[1]; + memset(&pkt->ipi6_addr, 0, sizeof(struct in6_addr)); + pkt->ipi6_ifindex = ifindex; + cmsg = CMSG_NXTHDR(&msg, cmsg); + msg.msg_controllen = (char *)cmsg - cbuf; + } + + /* XXX: we need root privilege here */ + if ((s = _socket(AF_INET6, SOCK_RAW, IPPROTO_ICMPV6)) < 0) + return NULL; + (void)_setsockopt(s, IPPROTO_ICMPV6, ICMP6_FILTER, + (char *)&filter, sizeof(filter)); + cc = _sendmsg(s, &msg, 0); + if (cc < 0) { + _close(s); + return (NULL); + } + FD_SET(s, &s_fds); + for (;;) { + fds = s_fds; + if (_select(s + 1, &fds, NULL, NULL, &tout) <= 0) { + _close(s); + return (NULL); + } + len = sizeof(sin6); + cc = _recvfrom(s, buf, sizeof(buf), 0, + (struct sockaddr *)&sin6, &len); + if (cc <= 0) { + _close(s); + return (NULL); + } + if (cc < sizeof(struct icmp6_hdr)) + continue; + nir = (struct icmp6_nodeinfo *)buf; + if (nir->ni_type != ICMP6_NI_REPLY) + continue; + if (nir->ni_qtype != htons(NI_QTYPE_NODENAME)) + continue; + if (memcmp(nir->icmp6_ni_nonce, niq.icmp6_ni_nonce, + sizeof(nir->icmp6_ni_nonce)) != 0) { + continue; + } + if (nir->ni_code != htons(ICMP6_NI_SUCCESS)) + continue; /* or should we fail? */ + + /* this is an expected reply. */ + break; + } + _close(s); + + memset(dnsname, 0, MAXDNAME + 1); + cp = (char *)(nir + 1); + end = ((char *)nir) + cc; + if (end - cp < sizeof(int32_t)) /* for TTL. we don't use it. */ + return (NULL); + cp += sizeof(int32_t); + if (*cp == end - cp - 1) { /* an old version */ + int nlen; + + cp++; /* skip length */ + nlen = end - cp; + if (nlen > MAXDNAME) + return (NULL); /* XXX: use it anyway? */ + memcpy(dnsname, cp, nlen); + } else { + /* XXX: should we use a generic function? */ + if (dnsdecode((const u_char **)(void *)&cp, end, + (const u_char *)(nir + 1), dnsname, MAXDNAME + 1) + == NULL) { + return (NULL); /* bogus name */ + } + /* Name-lookup special handling for truncated name. */ + if (cp + 1 <= end && !*cp && strlen(dnsname) > 0) + dnsname[strlen(dnsname) - 1] = '\0'; + + /* There may be other names, but we ignore them. */ + } + + return (dnsname); +} + +static int +_icmp_ghbyaddr(void *rval, void *cb_data, va_list ap) +{ + const void *addr; + int addrlen; + int af; + int *errp; + char *hname; + int ifindex = 0; + struct in6_addr addr6; + char dnsname[MAXDNAME + 1]; + + addr = va_arg(ap, const void *); + addrlen = va_arg(ap, int); + af = va_arg(ap, int); + errp = va_arg(ap, int *); + + *(struct hostent **)rval = NULL; + + if (af != AF_INET6 || addrlen != sizeof(addr6)) { + /* + * Note: rfc1788 defines Who Are You for IPv4, + * but no one implements it. + */ + return (NS_NOTFOUND); + } + + memcpy(&addr6, addr, addrlen); + if (IN6_IS_ADDR_LINKLOCAL(&addr6)) { + ifindex = (addr6.s6_addr[2] << 8) | addr6.s6_addr[3]; + addr6.s6_addr[2] = addr6.s6_addr[3] = 0; + } + + if ((hname = _icmp_nodeinfo_query(&addr6, ifindex, dnsname)) == NULL) + return (NS_NOTFOUND); + *(struct hostent **)rval =_hpaddr(af, hname, &addr6, errp); + return (NS_SUCCESS); +} +#endif /* ICMPNL */ diff --git a/lib/libc/net/netdb_private.h b/lib/libc/net/netdb_private.h new file mode 100644 index 0000000..3cf9257 --- /dev/null +++ b/lib/libc/net/netdb_private.h @@ -0,0 +1,172 @@ +/*- + * Copyright (C) 2005 The FreeBSD Project. 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 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. + * + * $FreeBSD: src/lib/libc/net/netdb_private.h,v 1.9.4.1 2006/07/17 10:09:57 ume Exp $ + */ + +#ifndef _NETDB_PRIVATE_H_ +#define _NETDB_PRIVATE_H_ + +#include /* XXX: for FILE */ + +#define NETDB_THREAD_ALLOC(name) \ +static struct name name; \ +static thread_key_t name##_key; \ +static once_t name##_init_once = ONCE_INITIALIZER; \ +static int name##_thr_keycreated = 0; \ +\ +static void name##_free(void *); \ +\ +static void \ +name##_keycreate(void) \ +{ \ + name##_thr_keycreated = \ + (thr_keycreate(&name##_key, name##_free) == 0); \ +} \ +\ +struct name * \ +__##name##_init(void) \ +{ \ + struct name *he; \ + \ + if (thr_main() != 0) \ + return (&name); \ + if (thr_once(&name##_init_once, name##_keycreate) != 0 || \ + !name##_thr_keycreated) \ + return (NULL); \ + if ((he = thr_getspecific(name##_key)) != NULL) \ + return (he); \ + if ((he = calloc(1, sizeof(*he))) == NULL) \ + return (NULL); \ + if (thr_setspecific(name##_key, he) == 0) \ + return (he); \ + free(he); \ + return (NULL); \ +} + +#define _MAXALIASES 35 +#define _MAXLINELEN 1024 +#define _MAXADDRS 35 +#define _HOSTBUFSIZE (8 * 1024) +#define _NETBUFSIZE 1025 + +struct hostent_data { + uint32_t host_addr[4]; /* IPv4 or IPv6 */ + char *h_addr_ptrs[_MAXADDRS + 1]; + char *host_aliases[_MAXALIASES]; + char hostbuf[_HOSTBUFSIZE]; + FILE *hostf; + int stayopen; +#ifdef YP + char *yp_domain; +#endif +}; + +struct netent_data { + char *net_aliases[_MAXALIASES]; + char netbuf[_NETBUFSIZE]; + FILE *netf; + int stayopen; +#ifdef YP + char *yp_domain; +#endif +}; + +struct protoent_data { + FILE *fp; + char *aliases[_MAXALIASES]; + int stayopen; + char line[_MAXLINELEN + 1]; +}; + +struct servent_data { + FILE *fp; + char *aliases[_MAXALIASES]; + int stayopen; + char line[_MAXLINELEN + 1]; +#ifdef YP + int yp_stepping; + char *yp_name; + char *yp_proto; + int yp_port; + char *yp_domain; + char *yp_key; + int yp_keylen; +#endif +}; + +struct hostdata { + struct hostent host; + char data[sizeof(struct hostent_data)]; +}; + +struct netdata { + struct netent net; + char data[sizeof(struct netent_data)]; +}; + +struct protodata { + struct protoent proto; + char data[sizeof(struct protoent_data)]; +}; + +struct servdata { + struct servent serv; + char data[sizeof(struct servent_data)]; +}; + +struct hostdata *__hostdata_init(void); +struct hostent *__hostent_init(void); +struct hostent_data *__hostent_data_init(void); +struct netdata *__netdata_init(void); +struct netent_data *__netent_data_init(void); +struct protodata *__protodata_init(void); +struct protoent_data *__protoent_data_init(void); +struct servdata *__servdata_init(void); +struct servent_data *__servent_data_init(void); +int __copy_hostent(struct hostent *, struct hostent *, char *, size_t); +int __copy_netent(struct netent *, struct netent *, char *, size_t); +int __copy_protoent(struct protoent *, struct protoent *, char *, size_t); +int __copy_servent(struct servent *, struct servent *, char *, size_t); + +void __endprotoent_p(struct protoent_data *); +void __endservent_p(struct servent_data *); +int __getprotoent_p(struct protoent *, struct protoent_data *); +int __getservent_p(struct servent *, struct servent_data *); +void __setprotoent_p(int, struct protoent_data *); +void __setservent_p(int, struct servent_data *); +void _endhostdnsent(void); +void _endhosthtent(struct hostent_data *); +void _endnetdnsent(void); +void _endnethtent(struct netent_data *); +struct hostent *_gethostbynisaddr(const void *, socklen_t, int); +struct hostent *_gethostbynisname(const char *, int); +void _map_v4v6_address(const char *, char *); +void _map_v4v6_hostent(struct hostent *, char **, char *); +void _sethostdnsent(int); +void _sethosthtent(int, struct hostent_data *); +void _setnetdnsent(int); +void _setnethtent(int, struct netent_data *); + +#endif /* _NETDB_PRIVATE_H_ */ diff --git a/lib/libc/net/nsdispatch.c b/lib/libc/net/nsdispatch.c new file mode 100644 index 0000000..aeb1b9d --- /dev/null +++ b/lib/libc/net/nsdispatch.c @@ -0,0 +1,627 @@ +/* $NetBSD: nsdispatch.c,v 1.9 1999/01/25 00:16:17 lukem Exp $ */ + +/*- + * Copyright (c) 1997, 1998, 1999 The NetBSD Foundation, Inc. + * All rights reserved. + * + * This code is derived from software contributed to The NetBSD Foundation + * by Luke Mewburn. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the NetBSD + * Foundation, Inc. and its contributors. + * 4. Neither the name of The NetBSD Foundation 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 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. + */ +/*- + * Copyright (c) 2003 Networks Associates Technology, Inc. + * All rights reserved. + * + * Portions of this software were developed for the FreeBSD Project by + * Jacques A. Vidrine, Safeport Network Services, and Network + * Associates Laboratories, the Security Research Division of Network + * Associates, Inc. under DARPA/SPAWAR contract N66001-01-C-8035 + * ("CBOSS"), as part of the DARPA CHATS research program. + * + * 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 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 AUTHOR 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 + +#include "namespace.h" +#include +#include + +#include +#include +#include +#define _NS_PRIVATE +#include +#include +#include +#include +#include +#include +#include +#include "un-namespace.h" + +enum _nss_constants { + /* Number of elements allocated when we grow a vector */ + ELEMSPERCHUNK = 8 +}; + +/* + * Global NSS data structures are mostly read-only, but we update + * them when we read or re-read the nsswitch.conf. + */ +static pthread_rwlock_t nss_lock = PTHREAD_RWLOCK_INITIALIZER; + +/* + * Runtime determination of whether we are dynamically linked or not. + */ +extern int _DYNAMIC __attribute__ ((weak)); +#define is_dynamic() (&_DYNAMIC != NULL) + +/* + * default sourcelist: `files' + */ +const ns_src __nsdefaultsrc[] = { + { NSSRC_FILES, NS_SUCCESS }, + { 0 }, +}; + +/* Database, source mappings. */ +static unsigned int _nsmapsize; +static ns_dbt *_nsmap = NULL; + +/* NSS modules. */ +static unsigned int _nsmodsize; +static ns_mod *_nsmod; + +/* Placeholder for builtin modules' dlopen `handle'. */ +static int __nss_builtin_handle; +static void *nss_builtin_handle = &__nss_builtin_handle; + +/* + * Attempt to spew relatively uniform messages to syslog. + */ +#define nss_log(level, fmt, ...) \ + syslog((level), "NSSWITCH(%s): " fmt, __func__, __VA_ARGS__) +#define nss_log_simple(level, s) \ + syslog((level), "NSSWITCH(%s): " s, __func__) + +/* + * Dynamically growable arrays are used for lists of databases, sources, + * and modules. The following `vector' interface is used to isolate the + * common operations. + */ +typedef int (*vector_comparison)(const void *, const void *); +typedef void (*vector_free_elem)(void *); +static void vector_sort(void *, unsigned int, size_t, + vector_comparison); +static void vector_free(void *, unsigned int *, size_t, + vector_free_elem); +static void *vector_ref(unsigned int, void *, unsigned int, size_t); +static void *vector_search(const void *, void *, unsigned int, size_t, + vector_comparison); +static void *vector_append(const void *, void *, unsigned int *, size_t); + + +/* + * Internal interfaces. + */ +static int string_compare(const void *, const void *); +static int mtab_compare(const void *, const void *); +static int nss_configure(void); +static void ns_dbt_free(ns_dbt *); +static void ns_mod_free(ns_mod *); +static void ns_src_free(ns_src **, int); +static void nss_load_builtin_modules(void); +static void nss_load_module(const char *, nss_module_register_fn); +static void nss_atexit(void); +/* nsparser */ +extern FILE *_nsyyin; + + +/* + * The vector operations + */ +static void +vector_sort(void *vec, unsigned int count, size_t esize, + vector_comparison comparison) +{ + qsort(vec, count, esize, comparison); +} + + +static void * +vector_search(const void *key, void *vec, unsigned int count, size_t esize, + vector_comparison comparison) +{ + return (bsearch(key, vec, count, esize, comparison)); +} + + +static void * +vector_append(const void *elem, void *vec, unsigned int *count, size_t esize) +{ + void *p; + + if ((*count % ELEMSPERCHUNK) == 0) { + p = realloc(vec, (*count + ELEMSPERCHUNK) * esize); + if (p == NULL) { + nss_log_simple(LOG_ERR, "memory allocation failure"); + return (vec); + } + vec = p; + } + memmove((void *)(((uintptr_t)vec) + (*count * esize)), elem, esize); + (*count)++; + return (vec); +} + + +static void * +vector_ref(unsigned int i, void *vec, unsigned int count, size_t esize) +{ + if (i < count) + return (void *)((uintptr_t)vec + (i * esize)); + else + return (NULL); +} + + +#define VECTOR_FREE(v, c, s, f) \ + do { vector_free(v, c, s, f); v = NULL; } while (0) +static void +vector_free(void *vec, unsigned int *count, size_t esize, + vector_free_elem free_elem) +{ + unsigned int i; + void *elem; + + for (i = 0; i < *count; i++) { + elem = vector_ref(i, vec, *count, esize); + if (elem != NULL) + free_elem(elem); + } + free(vec); + *count = 0; +} + + + +/* + * Comparison functions for vector_search. + */ +static int +string_compare(const void *a, const void *b) +{ + return (strcasecmp(*(const char * const *)a, *(const char * const *)b)); +} + + +static int +mtab_compare(const void *a, const void *b) +{ + int cmp; + + cmp = strcmp(((const ns_mtab *)a)->name, ((const ns_mtab *)b)->name); + if (cmp != 0) + return (cmp); + else + return (strcmp(((const ns_mtab *)a)->database, + ((const ns_mtab *)b)->database)); +} + + + +/* + * NSS nsmap management. + */ +void +_nsdbtaddsrc(ns_dbt *dbt, const ns_src *src) +{ + const ns_mod *modp; + + dbt->srclist = vector_append(src, dbt->srclist, &dbt->srclistsize, + sizeof(*src)); + modp = vector_search(&src->name, _nsmod, _nsmodsize, sizeof(*_nsmod), + string_compare); + if (modp == NULL) + nss_load_module(src->name, NULL); +} + + +#ifdef _NSS_DEBUG +void +_nsdbtdump(const ns_dbt *dbt) +{ + int i; + + printf("%s (%d source%s):", dbt->name, dbt->srclistsize, + dbt->srclistsize == 1 ? "" : "s"); + for (i = 0; i < (int)dbt->srclistsize; i++) { + printf(" %s", dbt->srclist[i].name); + if (!(dbt->srclist[i].flags & + (NS_UNAVAIL|NS_NOTFOUND|NS_TRYAGAIN)) && + (dbt->srclist[i].flags & NS_SUCCESS)) + continue; + printf(" ["); + if (!(dbt->srclist[i].flags & NS_SUCCESS)) + printf(" SUCCESS=continue"); + if (dbt->srclist[i].flags & NS_UNAVAIL) + printf(" UNAVAIL=return"); + if (dbt->srclist[i].flags & NS_NOTFOUND) + printf(" NOTFOUND=return"); + if (dbt->srclist[i].flags & NS_TRYAGAIN) + printf(" TRYAGAIN=return"); + printf(" ]"); + } + printf("\n"); +} +#endif + + +/* + * The first time nsdispatch is called (during a process's lifetime, + * or after nsswitch.conf has been updated), nss_configure will + * prepare global data needed by NSS. + */ +static int +nss_configure(void) +{ + static pthread_mutex_t conf_lock = PTHREAD_MUTEX_INITIALIZER; + static time_t confmod; + struct stat statbuf; + int result, isthreaded; + const char *path; + + result = 0; + isthreaded = __isthreaded; +#if defined(_NSS_DEBUG) && defined(_NSS_SHOOT_FOOT) + /* NOTE WELL: THIS IS A SECURITY HOLE. This must only be built + * for debugging purposes and MUST NEVER be used in production. + */ + path = getenv("NSSWITCH_CONF"); + if (path == NULL) +#endif + path = _PATH_NS_CONF; + if (stat(path, &statbuf) != 0) + return (0); + if (statbuf.st_mtime <= confmod) + return (0); + if (isthreaded) { + result = _pthread_mutex_trylock(&conf_lock); + if (result != 0) + return (0); + (void)_pthread_rwlock_unlock(&nss_lock); + result = _pthread_rwlock_wrlock(&nss_lock); + if (result != 0) + goto fin2; + } + _nsyyin = fopen(path, "r"); + if (_nsyyin == NULL) + goto fin; + VECTOR_FREE(_nsmap, &_nsmapsize, sizeof(*_nsmap), + (vector_free_elem)ns_dbt_free); + VECTOR_FREE(_nsmod, &_nsmodsize, sizeof(*_nsmod), + (vector_free_elem)ns_mod_free); + nss_load_builtin_modules(); + _nsyyparse(); + (void)fclose(_nsyyin); + vector_sort(_nsmap, _nsmapsize, sizeof(*_nsmap), string_compare); + if (confmod == 0) + (void)atexit(nss_atexit); + confmod = statbuf.st_mtime; +fin: + if (isthreaded) { + (void)_pthread_rwlock_unlock(&nss_lock); + if (result == 0) + result = _pthread_rwlock_rdlock(&nss_lock); + } +fin2: + if (isthreaded) + (void)_pthread_mutex_unlock(&conf_lock); + return (result); +} + + +void +_nsdbtput(const ns_dbt *dbt) +{ + unsigned int i; + ns_dbt *p; + + for (i = 0; i < _nsmapsize; i++) { + p = vector_ref(i, _nsmap, _nsmapsize, sizeof(*_nsmap)); + if (string_compare(&dbt->name, &p->name) == 0) { + /* overwrite existing entry */ + if (p->srclist != NULL) + ns_src_free(&p->srclist, p->srclistsize); + memmove(p, dbt, sizeof(*dbt)); + return; + } + } + _nsmap = vector_append(dbt, _nsmap, &_nsmapsize, sizeof(*_nsmap)); +} + + +static void +ns_dbt_free(ns_dbt *dbt) +{ + ns_src_free(&dbt->srclist, dbt->srclistsize); +} + + +static void +ns_src_free(ns_src **src, int srclistsize) +{ + int i; + + for (i = 0; i < srclistsize; i++) + if ((*src)[i].name != NULL) + /* This one was allocated by nslexer. You'll just + * have to trust me. + */ + free((void *)((*src)[i].name)); + free(*src); + *src = NULL; +} + + + +/* + * NSS module management. + */ +/* The built-in NSS modules are all loaded at once. */ +#define NSS_BACKEND(name, reg) \ +ns_mtab *reg(unsigned int *, nss_module_unregister_fn *); +#include "nss_backends.h" +#undef NSS_BACKEND + +static void +nss_load_builtin_modules(void) +{ +#define NSS_BACKEND(name, reg) nss_load_module(#name, reg); +#include "nss_backends.h" +#undef NSS_BACKEND +} + + +/* Load a built-in or dynamically linked module. If the `reg_fn' + * argument is non-NULL, assume a built-in module and use reg_fn to + * register it. Otherwise, search for a dynamic NSS module. + */ +static void +nss_load_module(const char *source, nss_module_register_fn reg_fn) +{ + char buf[PATH_MAX]; + ns_mod mod; + nss_module_register_fn fn; + + memset(&mod, 0, sizeof(mod)); + mod.name = strdup(source); + if (mod.name == NULL) { + nss_log_simple(LOG_ERR, "memory allocation failure"); + return; + } + if (reg_fn != NULL) { + /* The placeholder is required, as a NULL handle + * represents an invalid module. + */ + mod.handle = nss_builtin_handle; + fn = reg_fn; + } else if (!is_dynamic()) + goto fin; + else { + if (snprintf(buf, sizeof(buf), "nss_%s.so.%d", mod.name, + NSS_MODULE_INTERFACE_VERSION) >= (int)sizeof(buf)) + goto fin; + mod.handle = dlopen(buf, RTLD_LOCAL|RTLD_LAZY); + if (mod.handle == NULL) { +#ifdef _NSS_DEBUG + /* This gets pretty annoying since the built-in + * sources aren't modules yet. + */ + nss_log(LOG_DEBUG, "%s, %s", mod.name, dlerror()); +#endif + goto fin; + } + fn = (nss_module_register_fn)dlfunc(mod.handle, + "nss_module_register"); + if (fn == NULL) { + (void)dlclose(mod.handle); + mod.handle = NULL; + nss_log(LOG_ERR, "%s, %s", mod.name, dlerror()); + goto fin; + } + } + mod.mtab = fn(mod.name, &mod.mtabsize, &mod.unregister); + if (mod.mtab == NULL || mod.mtabsize == 0) { + if (mod.handle != nss_builtin_handle) + (void)dlclose(mod.handle); + mod.handle = NULL; + nss_log(LOG_ERR, "%s, registration failed", mod.name); + goto fin; + } + if (mod.mtabsize > 1) + qsort(mod.mtab, mod.mtabsize, sizeof(mod.mtab[0]), + mtab_compare); +fin: + _nsmod = vector_append(&mod, _nsmod, &_nsmodsize, sizeof(*_nsmod)); + vector_sort(_nsmod, _nsmodsize, sizeof(*_nsmod), string_compare); +} + + + +static void +ns_mod_free(ns_mod *mod) +{ + + free(mod->name); + if (mod->handle == NULL) + return; + if (mod->unregister != NULL) + mod->unregister(mod->mtab, mod->mtabsize); + if (mod->handle != nss_builtin_handle) + (void)dlclose(mod->handle); +} + + + +/* + * Cleanup + */ +static void +nss_atexit(void) +{ + int isthreaded; + + isthreaded = __isthreaded; + if (isthreaded) + (void)_pthread_rwlock_wrlock(&nss_lock); + VECTOR_FREE(_nsmap, &_nsmapsize, sizeof(*_nsmap), + (vector_free_elem)ns_dbt_free); + VECTOR_FREE(_nsmod, &_nsmodsize, sizeof(*_nsmod), + (vector_free_elem)ns_mod_free); + if (isthreaded) + (void)_pthread_rwlock_unlock(&nss_lock); +} + + + +/* + * Finally, the actual implementation. + */ +static nss_method +nss_method_lookup(const char *source, const char *database, + const char *method, const ns_dtab disp_tab[], void **mdata) +{ + ns_mod *mod; + ns_mtab *match, key; + int i; + + if (disp_tab != NULL) + for (i = 0; disp_tab[i].src != NULL; i++) + if (strcasecmp(source, disp_tab[i].src) == 0) { + *mdata = disp_tab[i].mdata; + return (disp_tab[i].method); + } + mod = vector_search(&source, _nsmod, _nsmodsize, sizeof(*_nsmod), + string_compare); + if (mod != NULL && mod->handle != NULL) { + key.database = database; + key.name = method; + match = bsearch(&key, mod->mtab, mod->mtabsize, + sizeof(mod->mtab[0]), mtab_compare); + if (match != NULL) { + *mdata = match->mdata; + return (match->method); + } + } + if (is_dynamic()) + nss_log(LOG_DEBUG, "%s, %s, %s, not found", source, database, + method); + *mdata = NULL; + return (NULL); +} + + +__weak_reference(_nsdispatch, nsdispatch); + +int +_nsdispatch(void *retval, const ns_dtab disp_tab[], const char *database, + const char *method_name, const ns_src defaults[], ...) +{ + va_list ap; + const ns_dbt *dbt; + const ns_src *srclist; + nss_method method; + void *mdata; + int isthreaded, serrno, i, result, srclistsize; + + isthreaded = __isthreaded; + serrno = errno; + if (isthreaded) { + result = _pthread_rwlock_rdlock(&nss_lock); + if (result != 0) { + result = NS_UNAVAIL; + goto fin; + } + } + result = nss_configure(); + if (result != 0) { + result = NS_UNAVAIL; + goto fin; + } + dbt = vector_search(&database, _nsmap, _nsmapsize, sizeof(*_nsmap), + string_compare); + if (dbt != NULL) { + srclist = dbt->srclist; + srclistsize = dbt->srclistsize; + } else { + srclist = defaults; + srclistsize = 0; + while (srclist[srclistsize].name != NULL) + srclistsize++; + } + for (i = 0; i < srclistsize; i++) { + result = NS_NOTFOUND; + method = nss_method_lookup(srclist[i].name, database, + method_name, disp_tab, &mdata); + if (method != NULL) { + va_start(ap, defaults); + result = method(retval, mdata, ap); + va_end(ap); + if (result & (srclist[i].flags)) + break; + } + } + if (isthreaded) + (void)_pthread_rwlock_unlock(&nss_lock); +fin: + errno = serrno; + return (result); +} diff --git a/lib/libc/net/nslexer.c b/lib/libc/net/nslexer.c new file mode 100644 index 0000000..805a1a8 --- /dev/null +++ b/lib/libc/net/nslexer.c @@ -0,0 +1,1730 @@ +#define yy_create_buffer _nsyy_create_buffer +#define yy_delete_buffer _nsyy_delete_buffer +#define yy_scan_buffer _nsyy_scan_buffer +#define yy_scan_string _nsyy_scan_string +#define yy_scan_bytes _nsyy_scan_bytes +#define yy_flex_debug _nsyy_flex_debug +#define yy_init_buffer _nsyy_init_buffer +#define yy_flush_buffer _nsyy_flush_buffer +#define yy_load_buffer_state _nsyy_load_buffer_state +#define yy_switch_to_buffer _nsyy_switch_to_buffer +#define yyin _nsyyin +#define yyleng _nsyyleng +#define yylex _nsyylex +#define yyout _nsyyout +#define yyrestart _nsyyrestart +#define yytext _nsyytext +#define yylineno _nsyylineno +#define yywrap _nsyywrap + +#line 21 "/dev/stdout" +/* A lexical scanner generated by flex */ + +/* Scanner skeleton version: + * $Header: /cvs/ubix2/src/lib/libc/net/nslexer.c,v 1.1 2006/10/27 00:58:52 reddawg Exp $ + * $FreeBSD: src/usr.bin/lex/flex.skl,v 1.8 2004/01/06 19:03:44 nectar Exp $ + */ + +#if defined(__FreeBSD__) +#include +#else +#define __unused +#endif + +#define FLEX_SCANNER +#define YY_FLEX_MAJOR_VERSION 2 +#define YY_FLEX_MINOR_VERSION 5 + +#include + + +/* cfront 1.2 defines "c_plusplus" instead of "__cplusplus" */ +#ifdef c_plusplus +#ifndef __cplusplus +#define __cplusplus +#endif +#endif + + +#ifdef __cplusplus + +#include +#include + +/* Use prototypes in function declarations. */ +#define YY_USE_PROTOS + +/* The "const" storage-class-modifier is valid. */ +#define YY_USE_CONST + +#else /* ! __cplusplus */ + +#if __STDC__ + +#define YY_USE_PROTOS +#define YY_USE_CONST + +#endif /* __STDC__ */ +#endif /* ! __cplusplus */ + +#ifdef __TURBOC__ + #pragma warn -rch + #pragma warn -use +#include +#include +#define YY_USE_CONST +#define YY_USE_PROTOS +#endif + +#ifdef YY_USE_CONST +#define yyconst const +#else +#define yyconst +#endif + + +#ifdef YY_USE_PROTOS +#define YY_PROTO(proto) proto +#else +#define YY_PROTO(proto) () +#endif + +/* Returned upon end-of-file. */ +#define YY_NULL 0 + +/* Promotes a possibly negative, possibly signed char to an unsigned + * integer for use as an array index. If the signed char is negative, + * we want to instead treat it as an 8-bit unsigned char, hence the + * double cast. + */ +#define YY_SC_TO_UI(c) ((unsigned int) (unsigned char) c) + +/* Enter a start condition. This macro really ought to take a parameter, + * but we do it the disgusting crufty way forced on us by the ()-less + * definition of BEGIN. + */ +#define BEGIN yy_start = 1 + 2 * + +/* Translate the current start state into a value that can be later handed + * to BEGIN to return to the state. The YYSTATE alias is for lex + * compatibility. + */ +#define YY_START ((yy_start - 1) / 2) +#define YYSTATE YY_START + +/* Action number for EOF rule of a given start state. */ +#define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1) + +/* Special action meaning "start processing a new file". */ +#define YY_NEW_FILE yyrestart( yyin ) + +#define YY_END_OF_BUFFER_CHAR 0 + +/* Size of default input buffer. */ +#define YY_BUF_SIZE 1024 + +typedef struct yy_buffer_state *YY_BUFFER_STATE; + +extern int yyleng; +extern FILE *yyin, *yyout; + +#define EOB_ACT_CONTINUE_SCAN 0 +#define EOB_ACT_END_OF_FILE 1 +#define EOB_ACT_LAST_MATCH 2 + +/* The funky do-while in the following #define is used to turn the definition + * int a single C statement (which needs a semi-colon terminator). This + * avoids problems with code like: + * + * if ( condition_holds ) + * yyless( 5 ); + * else + * do_something_else(); + * + * Prior to using the do-while the compiler would get upset at the + * "else" because it interpreted the "if" statement as being all + * done when it reached the ';' after the yyless() call. + */ + +/* Return all but the first 'n' matched characters back to the input stream. */ + +#define yyless(n) \ + do \ + { \ + /* Undo effects of setting up yytext. */ \ + *yy_cp = yy_hold_char; \ + YY_RESTORE_YY_MORE_OFFSET \ + yy_c_buf_p = yy_cp = yy_bp + n - YY_MORE_ADJ; \ + YY_DO_BEFORE_ACTION; /* set up yytext again */ \ + } \ + while ( 0 ) + +#define unput(c) yyunput( c, yytext_ptr ) + +/* The following is because we cannot portably get our hands on size_t + * (without autoconf's help, which isn't available because we want + * flex-generated scanners to compile on their own). + */ +typedef unsigned int yy_size_t; + + +struct yy_buffer_state + { + FILE *yy_input_file; + + char *yy_ch_buf; /* input buffer */ + char *yy_buf_pos; /* current position in input buffer */ + + /* Size of input buffer in bytes, not including room for EOB + * characters. + */ + yy_size_t yy_buf_size; + + /* Number of characters read into yy_ch_buf, not including EOB + * characters. + */ + int yy_n_chars; + + /* Whether we "own" the buffer - i.e., we know we created it, + * and can realloc() it to grow it, and should free() it to + * delete it. + */ + int yy_is_our_buffer; + + /* Whether this is an "interactive" input source; if so, and + * if we're using stdio for input, then we want to use getc() + * instead of fread(), to make sure we stop fetching input after + * each newline. + */ + int yy_is_interactive; + + /* Whether we're considered to be at the beginning of a line. + * If so, '^' rules will be active on the next match, otherwise + * not. + */ + int yy_at_bol; + + /* Whether to try to fill the input buffer when we reach the + * end of it. + */ + int yy_fill_buffer; + + int yy_buffer_status; +#define YY_BUFFER_NEW 0 +#define YY_BUFFER_NORMAL 1 + /* When an EOF's been seen but there's still some text to process + * then we mark the buffer as YY_EOF_PENDING, to indicate that we + * shouldn't try reading from the input source any more. We might + * still have a bunch of tokens to match, though, because of + * possible backing-up. + * + * When we actually see the EOF, we change the status to "new" + * (via yyrestart()), so that the user can continue scanning by + * just pointing yyin at a new input file. + */ +#define YY_BUFFER_EOF_PENDING 2 + }; + +static YY_BUFFER_STATE yy_current_buffer = 0; + +/* We provide macros for accessing buffer states in case in the + * future we want to put the buffer states in a more general + * "scanner state". + */ +#define YY_CURRENT_BUFFER yy_current_buffer + + +/* yy_hold_char holds the character lost when yytext is formed. */ +static char yy_hold_char; + +static int yy_n_chars; /* number of characters read into yy_ch_buf */ + + +int yyleng; + +/* Points to current character in buffer. */ +static char *yy_c_buf_p = (char *) 0; +static int yy_init = 1; /* whether we need to initialize */ +static int yy_start = 0; /* start state number */ + +/* Flag which is used to allow yywrap()'s to do buffer switches + * instead of setting up a fresh yyin. A bit of a hack ... + */ +static int yy_did_buffer_switch_on_eof; + +void yyrestart YY_PROTO(( FILE *input_file )); + +void yy_switch_to_buffer YY_PROTO(( YY_BUFFER_STATE new_buffer )); +void yy_load_buffer_state YY_PROTO(( void )); +YY_BUFFER_STATE yy_create_buffer YY_PROTO(( FILE *file, int size )); +void yy_delete_buffer YY_PROTO(( YY_BUFFER_STATE b )); +void yy_init_buffer YY_PROTO(( YY_BUFFER_STATE b, FILE *file )); +void yy_flush_buffer YY_PROTO(( YY_BUFFER_STATE b )); +#define YY_FLUSH_BUFFER yy_flush_buffer( yy_current_buffer ) + +YY_BUFFER_STATE yy_scan_buffer YY_PROTO(( char *base, yy_size_t size )); +YY_BUFFER_STATE yy_scan_string YY_PROTO(( yyconst char *yy_str )); +YY_BUFFER_STATE yy_scan_bytes YY_PROTO(( yyconst char *bytes, int len )); + +static void *yy_flex_alloc YY_PROTO(( yy_size_t )); +static void *yy_flex_realloc YY_PROTO(( void *, yy_size_t )) __unused; +static void yy_flex_free YY_PROTO(( void * )); + +#define yy_new_buffer yy_create_buffer + +#define yy_set_interactive(is_interactive) \ + { \ + if ( ! yy_current_buffer ) \ + yy_current_buffer = yy_create_buffer( yyin, YY_BUF_SIZE ); \ + yy_current_buffer->yy_is_interactive = is_interactive; \ + } + +#define yy_set_bol(at_bol) \ + { \ + if ( ! yy_current_buffer ) \ + yy_current_buffer = yy_create_buffer( yyin, YY_BUF_SIZE ); \ + yy_current_buffer->yy_at_bol = at_bol; \ + } + +#define YY_AT_BOL() (yy_current_buffer->yy_at_bol) + + +#define YY_USES_REJECT +typedef unsigned char YY_CHAR; +FILE *yyin = (FILE *) 0, *yyout = (FILE *) 0; +typedef int yy_state_type; +extern int yylineno; +int yylineno = 1; +extern char *yytext; +#define yytext_ptr yytext + +static yy_state_type yy_get_previous_state YY_PROTO(( void )); +static yy_state_type yy_try_NUL_trans YY_PROTO(( yy_state_type current_state )); +static int yy_get_next_buffer YY_PROTO(( void )); +static void yy_fatal_error YY_PROTO(( yyconst char msg[] )); + +/* Done after the current pattern has been matched and before the + * corresponding action - sets up yytext. + */ +#define YY_DO_BEFORE_ACTION \ + yytext_ptr = yy_bp; \ + yyleng = (int) (yy_cp - yy_bp); \ + yy_hold_char = *yy_cp; \ + *yy_cp = '\0'; \ + yy_c_buf_p = yy_cp; + +#define YY_NUM_RULES 13 +#define YY_END_OF_BUFFER 14 +static yyconst short int yy_acclist[83] = + { 0, + 14, 12, 13, 1, 12, 13, 4, 13, 2, 12, + 13, 11, 12, 13, 11, 12, 13, 11, 12, 13, + 11, 12, 13, 11, 12, 13, 11, 12, 13, 11, + 12, 13, 12, 13, 1, 2, 11, 11, 11, 11, + 11, 11, 11, 3, 11, 11, 11, 11, 11, 11, + 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, + 11, 11, 11, 11, 9, 11, 11, 11, 11, 11, + 11, 5, 11, 11, 6, 11, 10, 11, 7, 11, + 8, 11 + } ; + +static yyconst short int yy_accept[60] = + { 0, + 1, 1, 1, 2, 4, 7, 9, 12, 15, 18, + 21, 24, 27, 30, 33, 35, 36, 37, 38, 39, + 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, + 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, + 60, 61, 62, 63, 64, 65, 67, 68, 69, 70, + 71, 72, 74, 75, 77, 79, 81, 83, 83 + } ; + +static yyconst int yy_ec[256] = + { 0, + 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 2, 1, 1, 4, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5, 1, 1, 1, + 1, 1, 1, 1, 6, 7, 8, 9, 10, 11, + 12, 7, 13, 7, 7, 14, 7, 15, 16, 7, + 7, 17, 18, 19, 20, 21, 7, 7, 22, 7, + 1, 23, 1, 1, 5, 1, 6, 7, 8, 9, + + 10, 11, 12, 7, 13, 7, 7, 14, 7, 15, + 16, 7, 7, 17, 18, 19, 20, 21, 7, 7, + 22, 7, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1 + } ; + +static yyconst int yy_meta[24] = + { 0, + 1, 1, 2, 1, 3, 3, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 3, 3, 1 + } ; + +static yyconst short int yy_base[61] = + { 0, + 0, 0, 68, 69, 65, 69, 0, 0, 50, 49, + 54, 43, 45, 46, 57, 57, 0, 0, 43, 38, + 37, 47, 32, 47, 69, 33, 40, 30, 41, 42, + 26, 33, 29, 27, 33, 30, 35, 25, 19, 23, + 19, 30, 22, 14, 18, 0, 14, 18, 16, 19, + 19, 0, 12, 0, 0, 0, 0, 69, 23, 22 + } ; + +static yyconst short int yy_def[61] = + { 0, + 58, 1, 58, 58, 58, 58, 59, 60, 60, 60, + 60, 60, 60, 60, 58, 58, 59, 60, 60, 60, + 60, 60, 60, 60, 58, 60, 60, 60, 60, 60, + 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, + 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, + 60, 60, 60, 60, 60, 60, 60, 0, 58, 58 + } ; + +static yyconst short int yy_nxt[93] = + { 0, + 4, 5, 6, 7, 4, 8, 8, 9, 8, 8, + 8, 8, 8, 8, 10, 8, 11, 12, 13, 14, + 8, 8, 15, 17, 18, 17, 57, 56, 55, 54, + 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, + 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, + 33, 32, 31, 30, 29, 28, 27, 26, 16, 25, + 24, 23, 22, 21, 20, 19, 16, 58, 3, 58, + 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, + 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, + 58, 58 + + } ; + +static yyconst short int yy_chk[93] = + { 0, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 59, 60, 59, 53, 51, 50, 49, + 48, 47, 45, 44, 43, 42, 41, 40, 39, 38, + 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, + 27, 26, 24, 23, 22, 21, 20, 19, 16, 15, + 14, 13, 12, 11, 10, 9, 5, 3, 58, 58, + 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, + 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, + 58, 58 + + } ; + +static yy_state_type yy_state_buf[YY_BUF_SIZE + 2], *yy_state_ptr; +static char *yy_full_match; +static int yy_lp; +#define REJECT \ +{ \ +*yy_cp = yy_hold_char; /* undo effects of setting up yytext */ \ +yy_cp = yy_full_match; /* restore poss. backed-over text */ \ +++yy_lp; \ +goto find_rule; \ +} +#define yymore() yymore_used_but_not_detected +#define YY_MORE_ADJ 0 +#define YY_RESTORE_YY_MORE_OFFSET +char *yytext; +#line 1 "/usr/src/lib/libc/net/nslexer.l" +#define INITIAL 0 +#line 2 "/usr/src/lib/libc/net/nslexer.l" +/* $NetBSD: nslexer.l,v 1.3 1999/01/25 00:16:17 lukem Exp $ */ + +/*- + * Copyright (c) 1997, 1998, 1999 The NetBSD Foundation, Inc. + * All rights reserved. + * + * This code is derived from software contributed to The NetBSD Foundation + * by Luke Mewburn. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the NetBSD + * Foundation, Inc. and its contributors. + * 4. Neither the name of The NetBSD Foundation 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 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 +#if defined(LIBC_SCCS) && !defined(lint) +static char *rcsid = + "$FreeBSD: src/lib/libc/net/nslexer.l,v 1.5 2003/04/17 14:14:22 nectar Exp $"; +#endif /* LIBC_SCCS and not lint */ + +#include "namespace.h" +#include +#define _NS_PRIVATE +#include +#include +#include +#include "un-namespace.h" + +#include "nsparser.h" + +#define YY_NO_UNPUT + +#line 504 "/dev/stdout" + +/* Macros after this point can all be overridden by user definitions in + * section 1. + */ + +#ifndef YY_SKIP_YYWRAP +#ifdef __cplusplus +extern "C" int yywrap YY_PROTO(( void )); +#else +extern int yywrap YY_PROTO(( void )); +#endif +#endif + +#ifndef YY_NO_UNPUT +static void yyunput YY_PROTO(( int c, char *buf_ptr )); +#endif + +#ifndef yytext_ptr +static void yy_flex_strncpy YY_PROTO(( char *, yyconst char *, int )); +#endif + +#ifdef YY_NEED_STRLEN +static int yy_flex_strlen YY_PROTO(( yyconst char * )); +#endif + +#ifndef YY_NO_INPUT +#ifdef __cplusplus +static int yyinput YY_PROTO(( void )); +#else +static int input YY_PROTO(( void )); +#endif +#endif + +#if YY_STACK_USED +static int yy_start_stack_ptr = 0; +static int yy_start_stack_depth = 0; +static int *yy_start_stack = 0; +#ifndef YY_NO_PUSH_STATE +static void yy_push_state YY_PROTO(( int new_state )); +#endif +#ifndef YY_NO_POP_STATE +static void yy_pop_state YY_PROTO(( void )); +#endif +#ifndef YY_NO_TOP_STATE +static int yy_top_state YY_PROTO(( void )); +#endif + +#else +#define YY_NO_PUSH_STATE 1 +#define YY_NO_POP_STATE 1 +#define YY_NO_TOP_STATE 1 +#endif + +#ifdef YY_MALLOC_DECL +YY_MALLOC_DECL +#else +#if __STDC__ +#ifndef __cplusplus +#include +#endif +#else +/* Just try to get by without declaring the routines. This will fail + * miserably on non-ANSI systems for which sizeof(size_t) != sizeof(int) + * or sizeof(void*) != sizeof(int). + */ +#endif +#endif + +/* Amount of stuff to slurp up with each read. */ +#ifndef YY_READ_BUF_SIZE +#define YY_READ_BUF_SIZE 8192 +#endif + +/* Copy whatever the last rule matched to the standard output. */ + +#ifndef ECHO +/* This used to be an fputs(), but since the string might contain NUL's, + * we now use fwrite(). + */ +#define ECHO (void) fwrite( yytext, yyleng, 1, yyout ) +#endif + +/* Gets input and stuffs it into "buf". number of characters read, or YY_NULL, + * is returned in "result". + */ +#ifndef YY_INPUT +#define YY_INPUT(buf,result,max_size) \ + if ( yy_current_buffer->yy_is_interactive ) \ + { \ + int c = '*', n; \ + for ( n = 0; n < max_size && \ + (c = getc( yyin )) != EOF && c != '\n'; ++n ) \ + buf[n] = (char) c; \ + if ( c == '\n' ) \ + buf[n++] = (char) c; \ + if ( c == EOF && ferror( yyin ) ) \ + YY_FATAL_ERROR( "input in flex scanner failed" ); \ + result = n; \ + } \ + else if ( ((result = fread( buf, 1, max_size, yyin )) == 0) \ + && ferror( yyin ) ) \ + YY_FATAL_ERROR( "input in flex scanner failed" ); +#endif + +/* No semi-colon after return; correct usage is to write "yyterminate();" - + * we don't want an extra ';' after the "return" because that will cause + * some compilers to complain about unreachable statements. + */ +#ifndef yyterminate +#define yyterminate() return YY_NULL +#endif + +/* Number of entries by which start-condition stack grows. */ +#ifndef YY_START_STACK_INCR +#define YY_START_STACK_INCR 25 +#endif + +/* Report a fatal error. */ +#ifndef YY_FATAL_ERROR +#define YY_FATAL_ERROR(msg) yy_fatal_error( msg ) +#endif + +/* Default declaration of generated scanner - a define so the user can + * easily add parameters. + */ +#ifndef YY_DECL +#define YY_DECL int yylex YY_PROTO(( void )) +#endif + +/* Code executed at the beginning of each rule, after yytext and yyleng + * have been set up. + */ +#ifndef YY_USER_ACTION +#define YY_USER_ACTION +#endif + +/* Code executed at the end of each rule. */ +#ifndef YY_BREAK +#define YY_BREAK break; +#endif + +#define YY_RULE_SETUP \ + YY_USER_ACTION + +YY_DECL + { + register yy_state_type yy_current_state; + register char *yy_cp, *yy_bp; + register int yy_act; + +#line 66 "/usr/src/lib/libc/net/nslexer.l" + + +#line 658 "/dev/stdout" + + if ( yy_init ) + { + yy_init = 0; + +#ifdef YY_USER_INIT + YY_USER_INIT; +#endif + + if ( ! yy_start ) + yy_start = 1; /* first start state */ + + if ( ! yyin ) + yyin = stdin; + + if ( ! yyout ) + yyout = stdout; + + if ( ! yy_current_buffer ) + yy_current_buffer = + yy_create_buffer( yyin, YY_BUF_SIZE ); + + yy_load_buffer_state(); + } + + while ( 1 ) /* loops until end-of-file is reached */ + { + yy_cp = yy_c_buf_p; + + /* Support of yytext. */ + *yy_cp = yy_hold_char; + + /* yy_bp points to the position in yy_ch_buf of the start of + * the current run. + */ + yy_bp = yy_cp; + + yy_current_state = yy_start; + yy_state_ptr = yy_state_buf; + *yy_state_ptr++ = yy_current_state; +yy_match: + do + { + register YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)]; + while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) + { + yy_current_state = (int) yy_def[yy_current_state]; + if ( yy_current_state >= 59 ) + yy_c = yy_meta[(unsigned int) yy_c]; + } + yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; + *yy_state_ptr++ = yy_current_state; + ++yy_cp; + } + while ( yy_base[yy_current_state] != 69 ); + +yy_find_action: + yy_current_state = *--yy_state_ptr; + yy_lp = yy_accept[yy_current_state]; +goto find_rule; /* avoid `defined but not used' warning */ +find_rule: /* we branch to this label when backing up */ + for ( ; ; ) /* until we find what rule we matched */ + { + if ( yy_lp && yy_lp < yy_accept[yy_current_state + 1] ) + { + yy_act = yy_acclist[yy_lp]; + { + yy_full_match = yy_cp; + break; + } + } + --yy_cp; + yy_current_state = *--yy_state_ptr; + yy_lp = yy_accept[yy_current_state]; + } + + YY_DO_BEFORE_ACTION; + + if ( yy_act != YY_END_OF_BUFFER ) + { + int yyl; + for ( yyl = 0; yyl < yyleng; ++yyl ) + if ( yytext[yyl] == '\n' ) + ++yylineno; + } + +do_action: /* This label is used only to access EOF actions. */ + + + switch ( yy_act ) + { /* beginning of action switch */ +case 1: +YY_RULE_SETUP +#line 68 "/usr/src/lib/libc/net/nslexer.l" +; /* skip whitespace */ + YY_BREAK +case 2: +YY_RULE_SETUP +#line 70 "/usr/src/lib/libc/net/nslexer.l" +; /* skip comments */ + YY_BREAK +case 3: +YY_RULE_SETUP +#line 72 "/usr/src/lib/libc/net/nslexer.l" +; /* allow continuation */ + YY_BREAK +case 4: +YY_RULE_SETUP +#line 74 "/usr/src/lib/libc/net/nslexer.l" +return NL; + YY_BREAK +case 5: +YY_RULE_SETUP +#line 76 "/usr/src/lib/libc/net/nslexer.l" +return SUCCESS; + YY_BREAK +case 6: +YY_RULE_SETUP +#line 77 "/usr/src/lib/libc/net/nslexer.l" +return UNAVAIL; + YY_BREAK +case 7: +YY_RULE_SETUP +#line 78 "/usr/src/lib/libc/net/nslexer.l" +return NOTFOUND; + YY_BREAK +case 8: +YY_RULE_SETUP +#line 79 "/usr/src/lib/libc/net/nslexer.l" +return TRYAGAIN; + YY_BREAK +case 9: +YY_RULE_SETUP +#line 81 "/usr/src/lib/libc/net/nslexer.l" +return RETURN; + YY_BREAK +case 10: +YY_RULE_SETUP +#line 82 "/usr/src/lib/libc/net/nslexer.l" +return CONTINUE; + YY_BREAK +case 11: +YY_RULE_SETUP +#line 84 "/usr/src/lib/libc/net/nslexer.l" +{ + char *p; + int i; + + if ((p = strdup(yytext)) == NULL) { + syslog(LOG_ERR, + "NSSWITCH(nslexer): memory allocation failure"); + return ERRORTOKEN; + } + for (i = 0; i < strlen(p); i++) { + if (isupper((unsigned char)p[i])) + p[i] = tolower((unsigned char)p[i]); + } + _nsyylval.str = p; + return STRING; + } + YY_BREAK +case 12: +YY_RULE_SETUP +#line 101 "/usr/src/lib/libc/net/nslexer.l" +return yytext[0]; + YY_BREAK +case 13: +YY_RULE_SETUP +#line 103 "/usr/src/lib/libc/net/nslexer.l" +ECHO; + YY_BREAK +#line 830 "/dev/stdout" + case YY_STATE_EOF(INITIAL): + yyterminate(); + + case YY_END_OF_BUFFER: + { + /* Amount of text matched not including the EOB char. */ + int yy_amount_of_matched_text = (int) (yy_cp - yytext_ptr) - 1; + + /* Undo the effects of YY_DO_BEFORE_ACTION. */ + *yy_cp = yy_hold_char; + YY_RESTORE_YY_MORE_OFFSET + + if ( yy_current_buffer->yy_buffer_status == YY_BUFFER_NEW ) + { + /* We're scanning a new file or input source. It's + * possible that this happened because the user + * just pointed yyin at a new source and called + * yylex(). If so, then we have to assure + * consistency between yy_current_buffer and our + * globals. Here is the right place to do so, because + * this is the first action (other than possibly a + * back-up) that will match for the new input source. + */ + yy_n_chars = yy_current_buffer->yy_n_chars; + yy_current_buffer->yy_input_file = yyin; + yy_current_buffer->yy_buffer_status = YY_BUFFER_NORMAL; + } + + /* Note that here we test for yy_c_buf_p "<=" to the position + * of the first EOB in the buffer, since yy_c_buf_p will + * already have been incremented past the NUL character + * (since all states make transitions on EOB to the + * end-of-buffer state). Contrast this with the test + * in input(). + */ + if ( yy_c_buf_p <= &yy_current_buffer->yy_ch_buf[yy_n_chars] ) + { /* This was really a NUL. */ + yy_state_type yy_next_state; + + yy_c_buf_p = yytext_ptr + yy_amount_of_matched_text; + + yy_current_state = yy_get_previous_state(); + + /* Okay, we're now positioned to make the NUL + * transition. We couldn't have + * yy_get_previous_state() go ahead and do it + * for us because it doesn't know how to deal + * with the possibility of jamming (and we don't + * want to build jamming into it because then it + * will run more slowly). + */ + + yy_next_state = yy_try_NUL_trans( yy_current_state ); + + yy_bp = yytext_ptr + YY_MORE_ADJ; + + if ( yy_next_state ) + { + /* Consume the NUL. */ + yy_cp = ++yy_c_buf_p; + yy_current_state = yy_next_state; + goto yy_match; + } + + else + { + yy_cp = yy_c_buf_p; + goto yy_find_action; + } + } + + else switch ( yy_get_next_buffer() ) + { + case EOB_ACT_END_OF_FILE: + { + yy_did_buffer_switch_on_eof = 0; + + if ( yywrap() ) + { + /* Note: because we've taken care in + * yy_get_next_buffer() to have set up + * yytext, we can now set up + * yy_c_buf_p so that if some total + * hoser (like flex itself) wants to + * call the scanner after we return the + * YY_NULL, it'll still work - another + * YY_NULL will get returned. + */ + yy_c_buf_p = yytext_ptr + YY_MORE_ADJ; + + yy_act = YY_STATE_EOF(YY_START); + goto do_action; + } + + else + { + if ( ! yy_did_buffer_switch_on_eof ) + YY_NEW_FILE; + } + break; + } + + case EOB_ACT_CONTINUE_SCAN: + yy_c_buf_p = + yytext_ptr + yy_amount_of_matched_text; + + yy_current_state = yy_get_previous_state(); + + yy_cp = yy_c_buf_p; + yy_bp = yytext_ptr + YY_MORE_ADJ; + goto yy_match; + + case EOB_ACT_LAST_MATCH: + yy_c_buf_p = + &yy_current_buffer->yy_ch_buf[yy_n_chars]; + + yy_current_state = yy_get_previous_state(); + + yy_cp = yy_c_buf_p; + yy_bp = yytext_ptr + YY_MORE_ADJ; + goto yy_find_action; + } + break; + } + + default: + YY_FATAL_ERROR( + "fatal flex scanner internal error--no action found" ); + } /* end of action switch */ + } /* end of scanning one token */ + } /* end of yylex */ + + +/* yy_get_next_buffer - try to read in a new buffer + * + * Returns a code representing an action: + * EOB_ACT_LAST_MATCH - + * EOB_ACT_CONTINUE_SCAN - continue scanning from current position + * EOB_ACT_END_OF_FILE - end of file + */ + +static int yy_get_next_buffer() + { + register char *dest = yy_current_buffer->yy_ch_buf; + register char *source = yytext_ptr; + register int number_to_move, i; + int ret_val; + + if ( yy_c_buf_p > &yy_current_buffer->yy_ch_buf[yy_n_chars + 1] ) + YY_FATAL_ERROR( + "fatal flex scanner internal error--end of buffer missed" ); + + if ( yy_current_buffer->yy_fill_buffer == 0 ) + { /* Don't try to fill the buffer, so this is an EOF. */ + if ( yy_c_buf_p - yytext_ptr - YY_MORE_ADJ == 1 ) + { + /* We matched a single character, the EOB, so + * treat this as a final EOF. + */ + return EOB_ACT_END_OF_FILE; + } + + else + { + /* We matched some text prior to the EOB, first + * process it. + */ + return EOB_ACT_LAST_MATCH; + } + } + + /* Try to read more data. */ + + /* First move last chars to start of buffer. */ + number_to_move = (int) (yy_c_buf_p - yytext_ptr) - 1; + + for ( i = 0; i < number_to_move; ++i ) + *(dest++) = *(source++); + + if ( yy_current_buffer->yy_buffer_status == YY_BUFFER_EOF_PENDING ) + /* don't do the read, it's not guaranteed to return an EOF, + * just force an EOF + */ + yy_current_buffer->yy_n_chars = yy_n_chars = 0; + + else + { + int num_to_read = + yy_current_buffer->yy_buf_size - number_to_move - 1; + + while ( num_to_read <= 0 ) + { /* Not enough room in the buffer - grow it. */ +#ifdef YY_USES_REJECT + YY_FATAL_ERROR( +"input buffer overflow, can't enlarge buffer because scanner uses REJECT" ); +#else + + /* just a shorter name for the current buffer */ + YY_BUFFER_STATE b = yy_current_buffer; + + int yy_c_buf_p_offset = + (int) (yy_c_buf_p - b->yy_ch_buf); + + if ( b->yy_is_our_buffer ) + { + int new_size = b->yy_buf_size * 2; + + if ( new_size <= 0 ) + b->yy_buf_size += b->yy_buf_size / 8; + else + b->yy_buf_size *= 2; + + b->yy_ch_buf = (char *) + /* Include room in for 2 EOB chars. */ + yy_flex_realloc( (void *) b->yy_ch_buf, + b->yy_buf_size + 2 ); + } + else + /* Can't grow it, we don't own it. */ + b->yy_ch_buf = 0; + + if ( ! b->yy_ch_buf ) + YY_FATAL_ERROR( + "fatal error - scanner input buffer overflow" ); + + yy_c_buf_p = &b->yy_ch_buf[yy_c_buf_p_offset]; + + num_to_read = yy_current_buffer->yy_buf_size - + number_to_move - 1; +#endif + } + + if ( num_to_read > YY_READ_BUF_SIZE ) + num_to_read = YY_READ_BUF_SIZE; + + /* Read in more data. */ + YY_INPUT( (&yy_current_buffer->yy_ch_buf[number_to_move]), + yy_n_chars, num_to_read ); + + yy_current_buffer->yy_n_chars = yy_n_chars; + } + + if ( yy_n_chars == 0 ) + { + if ( number_to_move == YY_MORE_ADJ ) + { + ret_val = EOB_ACT_END_OF_FILE; + yyrestart( yyin ); + } + + else + { + ret_val = EOB_ACT_LAST_MATCH; + yy_current_buffer->yy_buffer_status = + YY_BUFFER_EOF_PENDING; + } + } + + else + ret_val = EOB_ACT_CONTINUE_SCAN; + + yy_n_chars += number_to_move; + yy_current_buffer->yy_ch_buf[yy_n_chars] = YY_END_OF_BUFFER_CHAR; + yy_current_buffer->yy_ch_buf[yy_n_chars + 1] = YY_END_OF_BUFFER_CHAR; + + yytext_ptr = &yy_current_buffer->yy_ch_buf[0]; + + return ret_val; + } + + +/* yy_get_previous_state - get the state just before the EOB char was reached */ + +static yy_state_type yy_get_previous_state() + { + register yy_state_type yy_current_state; + register char *yy_cp; + + yy_current_state = yy_start; + yy_state_ptr = yy_state_buf; + *yy_state_ptr++ = yy_current_state; + + for ( yy_cp = yytext_ptr + YY_MORE_ADJ; yy_cp < yy_c_buf_p; ++yy_cp ) + { + register YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1); + while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) + { + yy_current_state = (int) yy_def[yy_current_state]; + if ( yy_current_state >= 59 ) + yy_c = yy_meta[(unsigned int) yy_c]; + } + yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; + *yy_state_ptr++ = yy_current_state; + } + + return yy_current_state; + } + + +/* yy_try_NUL_trans - try to make a transition on the NUL character + * + * synopsis + * next_state = yy_try_NUL_trans( current_state ); + */ + +#ifdef YY_USE_PROTOS +static yy_state_type yy_try_NUL_trans( yy_state_type yy_current_state ) +#else +static yy_state_type yy_try_NUL_trans( yy_current_state ) +yy_state_type yy_current_state; +#endif + { + register int yy_is_jam; + + register YY_CHAR yy_c = 1; + while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) + { + yy_current_state = (int) yy_def[yy_current_state]; + if ( yy_current_state >= 59 ) + yy_c = yy_meta[(unsigned int) yy_c]; + } + yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; + yy_is_jam = (yy_current_state == 58); + if ( ! yy_is_jam ) + *yy_state_ptr++ = yy_current_state; + + return yy_is_jam ? 0 : yy_current_state; + } + + +#ifndef YY_NO_UNPUT +#ifdef YY_USE_PROTOS +static void yyunput( int c, register char *yy_bp ) +#else +static void yyunput( c, yy_bp ) +int c; +register char *yy_bp; +#endif + { + register char *yy_cp = yy_c_buf_p; + + /* undo effects of setting up yytext */ + *yy_cp = yy_hold_char; + + if ( yy_cp < yy_current_buffer->yy_ch_buf + 2 ) + { /* need to shift things up to make room */ + /* +2 for EOB chars. */ + register int number_to_move = yy_n_chars + 2; + register char *dest = &yy_current_buffer->yy_ch_buf[ + yy_current_buffer->yy_buf_size + 2]; + register char *source = + &yy_current_buffer->yy_ch_buf[number_to_move]; + + while ( source > yy_current_buffer->yy_ch_buf ) + *--dest = *--source; + + yy_cp += (int) (dest - source); + yy_bp += (int) (dest - source); + yy_current_buffer->yy_n_chars = + yy_n_chars = yy_current_buffer->yy_buf_size; + + if ( yy_cp < yy_current_buffer->yy_ch_buf + 2 ) + YY_FATAL_ERROR( "flex scanner push-back overflow" ); + } + + *--yy_cp = (char) c; + + if ( c == '\n' ) + --yylineno; + + yytext_ptr = yy_bp; + yy_hold_char = *yy_cp; + yy_c_buf_p = yy_cp; + } +#endif /* ifndef YY_NO_UNPUT */ + + +#ifdef __cplusplus +static int yyinput() +#else +static int input() +#endif + { + int c; + + *yy_c_buf_p = yy_hold_char; + + if ( *yy_c_buf_p == YY_END_OF_BUFFER_CHAR ) + { + /* yy_c_buf_p now points to the character we want to return. + * If this occurs *before* the EOB characters, then it's a + * valid NUL; if not, then we've hit the end of the buffer. + */ + if ( yy_c_buf_p < &yy_current_buffer->yy_ch_buf[yy_n_chars] ) + /* This was really a NUL. */ + *yy_c_buf_p = '\0'; + + else + { /* need more input */ + int offset = yy_c_buf_p - yytext_ptr; + ++yy_c_buf_p; + + switch ( yy_get_next_buffer() ) + { + case EOB_ACT_LAST_MATCH: + /* This happens because yy_g_n_b() + * sees that we've accumulated a + * token and flags that we need to + * try matching the token before + * proceeding. But for input(), + * there's no matching to consider. + * So convert the EOB_ACT_LAST_MATCH + * to EOB_ACT_END_OF_FILE. + */ + + /* Reset buffer status. */ + yyrestart( yyin ); + + /* fall through */ + + case EOB_ACT_END_OF_FILE: + { + if ( yywrap() ) + return EOF; + + if ( ! yy_did_buffer_switch_on_eof ) + YY_NEW_FILE; +#ifdef __cplusplus + return yyinput(); +#else + return input(); +#endif + } + + case EOB_ACT_CONTINUE_SCAN: + yy_c_buf_p = yytext_ptr + offset; + break; + } + } + } + + c = *(unsigned char *) yy_c_buf_p; /* cast for 8-bit char's */ + *yy_c_buf_p = '\0'; /* preserve yytext */ + yy_hold_char = *++yy_c_buf_p; + + if ( c == '\n' ) + ++yylineno; + + return c; + } + + +#ifdef YY_USE_PROTOS +void yyrestart( FILE *input_file ) +#else +void yyrestart( input_file ) +FILE *input_file; +#endif + { + if ( ! yy_current_buffer ) + yy_current_buffer = yy_create_buffer( yyin, YY_BUF_SIZE ); + + yy_init_buffer( yy_current_buffer, input_file ); + yy_load_buffer_state(); + } + + +#ifdef YY_USE_PROTOS +void yy_switch_to_buffer( YY_BUFFER_STATE new_buffer ) +#else +void yy_switch_to_buffer( new_buffer ) +YY_BUFFER_STATE new_buffer; +#endif + { + if ( yy_current_buffer == new_buffer ) + return; + + if ( yy_current_buffer ) + { + /* Flush out information for old buffer. */ + *yy_c_buf_p = yy_hold_char; + yy_current_buffer->yy_buf_pos = yy_c_buf_p; + yy_current_buffer->yy_n_chars = yy_n_chars; + } + + yy_current_buffer = new_buffer; + yy_load_buffer_state(); + + /* We don't actually know whether we did this switch during + * EOF (yywrap()) processing, but the only time this flag + * is looked at is after yywrap() is called, so it's safe + * to go ahead and always set it. + */ + yy_did_buffer_switch_on_eof = 1; + } + + +#ifdef YY_USE_PROTOS +void yy_load_buffer_state( void ) +#else +void yy_load_buffer_state() +#endif + { + yy_n_chars = yy_current_buffer->yy_n_chars; + yytext_ptr = yy_c_buf_p = yy_current_buffer->yy_buf_pos; + yyin = yy_current_buffer->yy_input_file; + yy_hold_char = *yy_c_buf_p; + } + + +#ifdef YY_USE_PROTOS +YY_BUFFER_STATE yy_create_buffer( FILE *file, int size ) +#else +YY_BUFFER_STATE yy_create_buffer( file, size ) +FILE *file; +int size; +#endif + { + YY_BUFFER_STATE b; + + b = (YY_BUFFER_STATE) yy_flex_alloc( sizeof( struct yy_buffer_state ) ); + if ( ! b ) + YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" ); + + b->yy_buf_size = size; + + /* yy_ch_buf has to be 2 characters longer than the size given because + * we need to put in 2 end-of-buffer characters. + */ + b->yy_ch_buf = (char *) yy_flex_alloc( b->yy_buf_size + 2 ); + if ( ! b->yy_ch_buf ) + YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" ); + + b->yy_is_our_buffer = 1; + + yy_init_buffer( b, file ); + + return b; + } + + +#ifdef YY_USE_PROTOS +void yy_delete_buffer( YY_BUFFER_STATE b ) +#else +void yy_delete_buffer( b ) +YY_BUFFER_STATE b; +#endif + { + if ( ! b ) + return; + + if ( b == yy_current_buffer ) + yy_current_buffer = (YY_BUFFER_STATE) 0; + + if ( b->yy_is_our_buffer ) + yy_flex_free( (void *) b->yy_ch_buf ); + + yy_flex_free( (void *) b ); + } + + +#ifndef YY_ALWAYS_INTERACTIVE +#ifndef YY_NEVER_INTERACTIVE +extern int isatty YY_PROTO(( int )); +#endif +#endif + +#ifdef YY_USE_PROTOS +void yy_init_buffer( YY_BUFFER_STATE b, FILE *file ) +#else +void yy_init_buffer( b, file ) +YY_BUFFER_STATE b; +FILE *file; +#endif + + + { + yy_flush_buffer( b ); + + b->yy_input_file = file; + b->yy_fill_buffer = 1; + +#if YY_ALWAYS_INTERACTIVE + b->yy_is_interactive = 1; +#else +#if YY_NEVER_INTERACTIVE + b->yy_is_interactive = 0; +#else + b->yy_is_interactive = file ? (isatty( fileno(file) ) > 0) : 0; +#endif +#endif + } + + +#ifdef YY_USE_PROTOS +void yy_flush_buffer( YY_BUFFER_STATE b ) +#else +void yy_flush_buffer( b ) +YY_BUFFER_STATE b; +#endif + + { + if ( ! b ) + return; + + b->yy_n_chars = 0; + + /* We always need two end-of-buffer characters. The first causes + * a transition to the end-of-buffer state. The second causes + * a jam in that state. + */ + b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR; + b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR; + + b->yy_buf_pos = &b->yy_ch_buf[0]; + + b->yy_at_bol = 1; + b->yy_buffer_status = YY_BUFFER_NEW; + + if ( b == yy_current_buffer ) + yy_load_buffer_state(); + } + + +#ifndef YY_NO_SCAN_BUFFER +#ifdef YY_USE_PROTOS +YY_BUFFER_STATE yy_scan_buffer( char *base, yy_size_t size ) +#else +YY_BUFFER_STATE yy_scan_buffer( base, size ) +char *base; +yy_size_t size; +#endif + { + YY_BUFFER_STATE b; + + if ( size < 2 || + base[size-2] != YY_END_OF_BUFFER_CHAR || + base[size-1] != YY_END_OF_BUFFER_CHAR ) + /* They forgot to leave room for the EOB's. */ + return 0; + + b = (YY_BUFFER_STATE) yy_flex_alloc( sizeof( struct yy_buffer_state ) ); + if ( ! b ) + YY_FATAL_ERROR( "out of dynamic memory in yy_scan_buffer()" ); + + b->yy_buf_size = size - 2; /* "- 2" to take care of EOB's */ + b->yy_buf_pos = b->yy_ch_buf = base; + b->yy_is_our_buffer = 0; + b->yy_input_file = 0; + b->yy_n_chars = b->yy_buf_size; + b->yy_is_interactive = 0; + b->yy_at_bol = 1; + b->yy_fill_buffer = 0; + b->yy_buffer_status = YY_BUFFER_NEW; + + yy_switch_to_buffer( b ); + + return b; + } +#endif + + +#ifndef YY_NO_SCAN_STRING +#ifdef YY_USE_PROTOS +YY_BUFFER_STATE yy_scan_string( yyconst char *yy_str ) +#else +YY_BUFFER_STATE yy_scan_string( yy_str ) +yyconst char *yy_str; +#endif + { + int len; + for ( len = 0; yy_str[len]; ++len ) + ; + + return yy_scan_bytes( yy_str, len ); + } +#endif + + +#ifndef YY_NO_SCAN_BYTES +#ifdef YY_USE_PROTOS +YY_BUFFER_STATE yy_scan_bytes( yyconst char *bytes, int len ) +#else +YY_BUFFER_STATE yy_scan_bytes( bytes, len ) +yyconst char *bytes; +int len; +#endif + { + YY_BUFFER_STATE b; + char *buf; + yy_size_t n; + int i; + + /* Get memory for full buffer, including space for trailing EOB's. */ + n = len + 2; + buf = (char *) yy_flex_alloc( n ); + if ( ! buf ) + YY_FATAL_ERROR( "out of dynamic memory in yy_scan_bytes()" ); + + for ( i = 0; i < len; ++i ) + buf[i] = bytes[i]; + + buf[len] = buf[len+1] = YY_END_OF_BUFFER_CHAR; + + b = yy_scan_buffer( buf, n ); + if ( ! b ) + YY_FATAL_ERROR( "bad buffer in yy_scan_bytes()" ); + + /* It's okay to grow etc. this buffer, and we should throw it + * away when we're done. + */ + b->yy_is_our_buffer = 1; + + return b; + } +#endif + + +#ifndef YY_NO_PUSH_STATE +#ifdef YY_USE_PROTOS +static void yy_push_state( int new_state ) +#else +static void yy_push_state( new_state ) +int new_state; +#endif + { + if ( yy_start_stack_ptr >= yy_start_stack_depth ) + { + yy_size_t new_size; + + yy_start_stack_depth += YY_START_STACK_INCR; + new_size = yy_start_stack_depth * sizeof( int ); + + if ( ! yy_start_stack ) + yy_start_stack = (int *) yy_flex_alloc( new_size ); + + else + yy_start_stack = (int *) yy_flex_realloc( + (void *) yy_start_stack, new_size ); + + if ( ! yy_start_stack ) + YY_FATAL_ERROR( + "out of memory expanding start-condition stack" ); + } + + yy_start_stack[yy_start_stack_ptr++] = YY_START; + + BEGIN(new_state); + } +#endif + + +#ifndef YY_NO_POP_STATE +static void yy_pop_state() + { + if ( --yy_start_stack_ptr < 0 ) + YY_FATAL_ERROR( "start-condition stack underflow" ); + + BEGIN(yy_start_stack[yy_start_stack_ptr]); + } +#endif + + +#ifndef YY_NO_TOP_STATE +static int yy_top_state() + { + return yy_start_stack[yy_start_stack_ptr - 1]; + } +#endif + +#ifndef YY_EXIT_FAILURE +#define YY_EXIT_FAILURE 2 +#endif + +#ifdef YY_USE_PROTOS +static void yy_fatal_error( yyconst char msg[] ) +#else +static void yy_fatal_error( msg ) +char msg[]; +#endif + { + (void) fprintf( stderr, "%s\n", msg ); + exit( YY_EXIT_FAILURE ); + } + + + +/* Redefine yyless() so it works in section 3 code. */ + +#undef yyless +#define yyless(n) \ + do \ + { \ + /* Undo effects of setting up yytext. */ \ + yytext[yyleng] = yy_hold_char; \ + yy_c_buf_p = yytext + n; \ + yy_hold_char = *yy_c_buf_p; \ + *yy_c_buf_p = '\0'; \ + yyleng = n; \ + } \ + while ( 0 ) + + +/* Internal utility routines. */ + +#ifndef yytext_ptr +#ifdef YY_USE_PROTOS +static void yy_flex_strncpy( char *s1, yyconst char *s2, int n ) +#else +static void yy_flex_strncpy( s1, s2, n ) +char *s1; +yyconst char *s2; +int n; +#endif + { + register int i; + for ( i = 0; i < n; ++i ) + s1[i] = s2[i]; + } +#endif + +#ifdef YY_NEED_STRLEN +#ifdef YY_USE_PROTOS +static int yy_flex_strlen( yyconst char *s ) +#else +static int yy_flex_strlen( s ) +yyconst char *s; +#endif + { + register int n; + for ( n = 0; s[n]; ++n ) + ; + + return n; + } +#endif + + +#ifdef YY_USE_PROTOS +static void *yy_flex_alloc( yy_size_t size ) +#else +static void *yy_flex_alloc( size ) +yy_size_t size; +#endif + { + return (void *) malloc( size ); + } + +#ifdef YY_USE_PROTOS +static void *yy_flex_realloc( void *ptr, yy_size_t size ) +#else +static void *yy_flex_realloc( ptr, size ) +void *ptr; +yy_size_t size; +#endif + { + /* The cast to (char *) in the following accommodates both + * implementations that use char* generic pointers, and those + * that use void* generic pointers. It works with the latter + * because both ANSI C and C++ allow castless assignment from + * any pointer type to void*, and deal with argument conversions + * as though doing an assignment. + */ + return (void *) realloc( (char *) ptr, size ); + } + +#ifdef YY_USE_PROTOS +static void yy_flex_free( void *ptr ) +#else +static void yy_flex_free( ptr ) +void *ptr; +#endif + { + free( ptr ); + } + +#if YY_MAIN +int main() + { + yylex(); + return 0; + } +#endif +#line 103 "/usr/src/lib/libc/net/nslexer.l" + + +#undef _nsyywrap +int +_nsyywrap() +{ + return 1; +} /* _nsyywrap */ + +void +_nsyyerror(msg) + const char *msg; +{ + + syslog(LOG_ERR, "NSSWITCH(nslexer): %s line %d: %s at '%s'", + _PATH_NS_CONF, yylineno, msg, yytext); +} /* _nsyyerror */ diff --git a/lib/libc/net/nslexer.l b/lib/libc/net/nslexer.l new file mode 100644 index 0000000..f87d66b --- /dev/null +++ b/lib/libc/net/nslexer.l @@ -0,0 +1,119 @@ +%{ +/* $NetBSD: nslexer.l,v 1.3 1999/01/25 00:16:17 lukem Exp $ */ + +/*- + * Copyright (c) 1997, 1998, 1999 The NetBSD Foundation, Inc. + * All rights reserved. + * + * This code is derived from software contributed to The NetBSD Foundation + * by Luke Mewburn. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the NetBSD + * Foundation, Inc. and its contributors. + * 4. Neither the name of The NetBSD Foundation 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 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 +#if defined(LIBC_SCCS) && !defined(lint) +static char *rcsid = + "$FreeBSD: src/lib/libc/net/nslexer.l,v 1.5 2003/04/17 14:14:22 nectar Exp $"; +#endif /* LIBC_SCCS and not lint */ + +#include "namespace.h" +#include +#define _NS_PRIVATE +#include +#include +#include +#include "un-namespace.h" + +#include "nsparser.h" + +#define YY_NO_UNPUT + +%} + +%option yylineno + +BLANK [ \t] +CR \n +STRING [a-zA-Z][a-zA-Z0-9_]* + +%% + +{BLANK}+ ; /* skip whitespace */ + +#.* ; /* skip comments */ + +\\{CR} ; /* allow continuation */ + +{CR} return NL; + +[sS][uU][cC][cC][eE][sS][sS] return SUCCESS; +[uU][nN][aA][vV][aA][iI][lL] return UNAVAIL; +[nN][oO][tT][fF][oO][uU][nN][dD] return NOTFOUND; +[tT][rR][yY][aA][gG][aA][iI][nN] return TRYAGAIN; + +[rR][eE][tT][uU][rR][nN] return RETURN; +[cC][oO][nN][tT][iI][nN][uU][eE] return CONTINUE; + +{STRING} { + char *p; + int i; + + if ((p = strdup(yytext)) == NULL) { + syslog(LOG_ERR, + "NSSWITCH(nslexer): memory allocation failure"); + return ERRORTOKEN; + } + for (i = 0; i < strlen(p); i++) { + if (isupper((unsigned char)p[i])) + p[i] = tolower((unsigned char)p[i]); + } + _nsyylval.str = p; + return STRING; + } + +. return yytext[0]; + +%% + +#undef _nsyywrap +int +_nsyywrap() +{ + return 1; +} /* _nsyywrap */ + +void +_nsyyerror(msg) + const char *msg; +{ + + syslog(LOG_ERR, "NSSWITCH(nslexer): %s line %d: %s at '%s'", + _PATH_NS_CONF, yylineno, msg, yytext); +} /* _nsyyerror */ diff --git a/lib/libc/net/nsparser.c b/lib/libc/net/nsparser.c new file mode 100644 index 0000000..59cc01e --- /dev/null +++ b/lib/libc/net/nsparser.c @@ -0,0 +1,613 @@ +#include +#ifndef lint +#ifdef __unused +__unused +#endif +static char const +yyrcsid[] = "$FreeBSD: src/usr.bin/yacc/skeleton.c,v 1.37 2003/02/12 18:03:55 davidc Exp $"; +#endif +#define YYBYACC 1 +#define YYMAJOR 1 +#define YYMINOR 9 +#define YYLEX yylex() +#define YYEMPTY -1 +#define yyclearin (yychar=(YYEMPTY)) +#define yyerrok (yyerrflag=0) +#define YYRECOVERING() (yyerrflag!=0) +#if defined(__cplusplus) || __STDC__ +static int yygrowstack(void); +#else +static int yygrowstack(); +#endif +#define yyparse _nsyyparse +#define yylex _nsyylex +#define yyerror _nsyyerror +#define yychar _nsyychar +#define yyval _nsyyval +#define yylval _nsyylval +#define yydebug _nsyydebug +#define yynerrs _nsyynerrs +#define yyerrflag _nsyyerrflag +#define yyss _nsyyss +#define yyssp _nsyyssp +#define yyvs _nsyyvs +#define yyvsp _nsyyvsp +#define yylhs _nsyylhs +#define yylen _nsyylen +#define yydefred _nsyydefred +#define yydgoto _nsyydgoto +#define yysindex _nsyysindex +#define yyrindex _nsyyrindex +#define yygindex _nsyygindex +#define yytable _nsyytable +#define yycheck _nsyycheck +#define yyname _nsyyname +#define yyrule _nsyyrule +#define yysslim _nsyysslim +#define yystacksize _nsyystacksize +#define YYPREFIX "_nsyy" +#line 2 "/usr/src/lib/libc/net/nsparser.y" +/* $NetBSD: nsparser.y,v 1.3 1999/01/25 00:16:18 lukem Exp $ */ + +/*- + * Copyright (c) 1997, 1998, 1999 The NetBSD Foundation, Inc. + * All rights reserved. + * + * This code is derived from software contributed to The NetBSD Foundation + * by Luke Mewburn. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the NetBSD + * Foundation, Inc. and its contributors. + * 4. Neither the name of The NetBSD Foundation 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 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 + +#include "namespace.h" +#define _NS_PRIVATE +#include +#include +#include +#include +#include "un-namespace.h" + +static void _nsaddsrctomap(const char *); + +static ns_dbt curdbt; +static ns_src cursrc; +#line 57 "/usr/src/lib/libc/net/nsparser.y" +typedef union { + char *str; + int mapval; +} YYSTYPE; +#line 109 "y.tab.c" +#define YYERRCODE 256 +#define NL 257 +#define SUCCESS 258 +#define UNAVAIL 259 +#define NOTFOUND 260 +#define TRYAGAIN 261 +#define RETURN 262 +#define CONTINUE 263 +#define ERRORTOKEN 264 +#define STRING 265 +const short _nsyylhs[] = { -1, + 0, 0, 3, 3, 4, 4, 4, 4, 5, 6, + 6, 7, 9, 7, 8, 8, 10, 1, 1, 1, + 1, 2, 2, +}; +const short _nsyylen[] = { 2, + 0, 1, 1, 2, 1, 3, 4, 2, 1, 1, + 2, 1, 0, 5, 1, 2, 3, 1, 1, 1, + 1, 1, 1, +}; +const short _nsyydefred[] = { 0, + 0, 5, 9, 0, 0, 3, 0, 8, 4, 0, + 6, 0, 0, 10, 13, 7, 11, 0, 18, 19, + 20, 21, 0, 0, 15, 0, 14, 16, 22, 23, + 17, +}; +const short _nsyydgoto[] = { 4, + 23, 31, 5, 6, 7, 13, 14, 24, 18, 25, +}; +const short _nsyysindex[] = { -255, + -249, 0, 0, 0, -255, 0, -49, 0, 0, -254, + 0, -73, -253, 0, 0, 0, 0, -244, 0, 0, + 0, 0, -42, -93, 0, -256, 0, 0, 0, 0, + 0, +}; +const short _nsyyrindex[] = { 20, + 0, 0, 0, 0, 21, 0, 0, 0, 0, 0, + 0, -252, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, +}; +const short _nsyygindex[] = { 0, + 0, 0, 0, 17, 0, 0, 10, 0, 0, 1, +}; +#define YYTABLESIZE 168 +const short _nsyytable[] = { 27, + 1, 2, 11, 16, 12, 29, 30, 8, 10, 3, + 12, 12, 12, 19, 20, 21, 22, 15, 26, 1, + 2, 9, 17, 0, 28, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 19, 20, 21, 22, +}; +const short _nsyycheck[] = { 93, + 256, 257, 257, 257, 257, 262, 263, 257, 58, 265, + 265, 265, 265, 258, 259, 260, 261, 91, 61, 0, + 0, 5, 13, -1, 24, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, 258, 259, 260, 261, +}; +#define YYFINAL 4 +#ifndef YYDEBUG +#define YYDEBUG 0 +#endif +#define YYMAXTOKEN 265 +#if YYDEBUG +const char * const _nsyyname[] = { +"end-of-file",0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, +0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,"':'",0,0,"'='",0,0,0,0,0,0,0,0, +0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,"'['",0,"']'",0,0,0,0,0,0,0,0,0,0,0,0, +0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, +0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, +0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, +0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,"NL","SUCCESS", +"UNAVAIL","NOTFOUND","TRYAGAIN","RETURN","CONTINUE","ERRORTOKEN","STRING", +}; +const char * const _nsyyrule[] = { +"$accept : File", +"File :", +"File : Lines", +"Lines : Entry", +"Lines : Lines Entry", +"Entry : NL", +"Entry : Database ':' NL", +"Entry : Database ':' Srclist NL", +"Entry : error NL", +"Database : STRING", +"Srclist : Item", +"Srclist : Srclist Item", +"Item : STRING", +"$$1 :", +"Item : STRING '[' $$1 Criteria ']'", +"Criteria : Criterion", +"Criteria : Criteria Criterion", +"Criterion : Status '=' Action", +"Status : SUCCESS", +"Status : UNAVAIL", +"Status : NOTFOUND", +"Status : TRYAGAIN", +"Action : RETURN", +"Action : CONTINUE", +}; +#endif +#if YYDEBUG +#include +#endif +#ifdef YYSTACKSIZE +#undef YYMAXDEPTH +#define YYMAXDEPTH YYSTACKSIZE +#else +#ifdef YYMAXDEPTH +#define YYSTACKSIZE YYMAXDEPTH +#else +#define YYSTACKSIZE 10000 +#define YYMAXDEPTH 10000 +#endif +#endif +#define YYINITSTACKSIZE 200 +int yydebug; +int yynerrs; +int yyerrflag; +int yychar; +short *yyssp; +YYSTYPE *yyvsp; +YYSTYPE yyval; +YYSTYPE yylval; +short *yyss; +short *yysslim; +YYSTYPE *yyvs; +int yystacksize; +#line 149 "/usr/src/lib/libc/net/nsparser.y" + +static void +_nsaddsrctomap(elem) + const char *elem; +{ + int i, lineno; + extern int _nsyylineno; + extern char * _nsyytext; + + lineno = _nsyylineno - (*_nsyytext == '\n' ? 1 : 0); + if (curdbt.srclistsize > 0) { + if ((strcasecmp(elem, NSSRC_COMPAT) == 0) || + (strcasecmp(curdbt.srclist[0].name, NSSRC_COMPAT) == 0)) { + syslog(LOG_ERR, + "NSSWITCH(nsparser): %s line %d: 'compat' used with other sources", + _PATH_NS_CONF, lineno); + return; + } + } + for (i = 0; i < curdbt.srclistsize; i++) { + if (strcasecmp(curdbt.srclist[i].name, elem) == 0) { + syslog(LOG_ERR, + "NSSWITCH(nsparser): %s line %d: duplicate source '%s'", + _PATH_NS_CONF, lineno, elem); + return; + } + } + cursrc.name = elem; + _nsdbtaddsrc(&curdbt, &cursrc); +} +#line 294 "y.tab.c" +/* allocate initial stack or double stack size, up to YYMAXDEPTH */ +static int yygrowstack() +{ + int newsize, i; + short *newss; + YYSTYPE *newvs; + + if ((newsize = yystacksize) == 0) + newsize = YYINITSTACKSIZE; + else if (newsize >= YYMAXDEPTH) + return -1; + else if ((newsize *= 2) > YYMAXDEPTH) + newsize = YYMAXDEPTH; + i = yyssp - yyss; + newss = yyss ? (short *)realloc(yyss, newsize * sizeof *newss) : + (short *)malloc(newsize * sizeof *newss); + if (newss == NULL) + return -1; + yyss = newss; + yyssp = newss + i; + newvs = yyvs ? (YYSTYPE *)realloc(yyvs, newsize * sizeof *newvs) : + (YYSTYPE *)malloc(newsize * sizeof *newvs); + if (newvs == NULL) + return -1; + yyvs = newvs; + yyvsp = newvs + i; + yystacksize = newsize; + yysslim = yyss + newsize - 1; + return 0; +} + +#define YYABORT goto yyabort +#define YYREJECT goto yyabort +#define YYACCEPT goto yyaccept +#define YYERROR goto yyerrlab + +#ifndef YYPARSE_PARAM +#if defined(__cplusplus) || __STDC__ +#define YYPARSE_PARAM_ARG void +#define YYPARSE_PARAM_DECL +#else /* ! ANSI-C/C++ */ +#define YYPARSE_PARAM_ARG +#define YYPARSE_PARAM_DECL +#endif /* ANSI-C/C++ */ +#else /* YYPARSE_PARAM */ +#ifndef YYPARSE_PARAM_TYPE +#define YYPARSE_PARAM_TYPE void * +#endif +#if defined(__cplusplus) || __STDC__ +#define YYPARSE_PARAM_ARG YYPARSE_PARAM_TYPE YYPARSE_PARAM +#define YYPARSE_PARAM_DECL +#else /* ! ANSI-C/C++ */ +#define YYPARSE_PARAM_ARG YYPARSE_PARAM +#define YYPARSE_PARAM_DECL YYPARSE_PARAM_TYPE YYPARSE_PARAM; +#endif /* ANSI-C/C++ */ +#endif /* ! YYPARSE_PARAM */ + +int +yyparse (YYPARSE_PARAM_ARG) + YYPARSE_PARAM_DECL +{ + int yym, yyn, yystate; +#if YYDEBUG + const char *yys; + + if ((yys = getenv("YYDEBUG"))) + { + yyn = *yys; + if (yyn >= '0' && yyn <= '9') + yydebug = yyn - '0'; + } +#endif + + yynerrs = 0; + yyerrflag = 0; + yychar = (-1); + + if (yyss == NULL && yygrowstack()) goto yyoverflow; + yyssp = yyss; + yyvsp = yyvs; + *yyssp = yystate = 0; + +yyloop: + if ((yyn = yydefred[yystate])) goto yyreduce; + if (yychar < 0) + { + if ((yychar = yylex()) < 0) yychar = 0; +#if YYDEBUG + if (yydebug) + { + yys = 0; + if (yychar <= YYMAXTOKEN) yys = yyname[yychar]; + if (!yys) yys = "illegal-symbol"; + printf("%sdebug: state %d, reading %d (%s)\n", + YYPREFIX, yystate, yychar, yys); + } +#endif + } + if ((yyn = yysindex[yystate]) && (yyn += yychar) >= 0 && + yyn <= YYTABLESIZE && yycheck[yyn] == yychar) + { +#if YYDEBUG + if (yydebug) + printf("%sdebug: state %d, shifting to state %d\n", + YYPREFIX, yystate, yytable[yyn]); +#endif + if (yyssp >= yysslim && yygrowstack()) + { + goto yyoverflow; + } + *++yyssp = yystate = yytable[yyn]; + *++yyvsp = yylval; + yychar = (-1); + if (yyerrflag > 0) --yyerrflag; + goto yyloop; + } + if ((yyn = yyrindex[yystate]) && (yyn += yychar) >= 0 && + yyn <= YYTABLESIZE && yycheck[yyn] == yychar) + { + yyn = yytable[yyn]; + goto yyreduce; + } + if (yyerrflag) goto yyinrecovery; +#if defined(lint) || defined(__GNUC__) + goto yynewerror; +#endif +yynewerror: + yyerror("syntax error"); +#if defined(lint) || defined(__GNUC__) + goto yyerrlab; +#endif +yyerrlab: + ++yynerrs; +yyinrecovery: + if (yyerrflag < 3) + { + yyerrflag = 3; + for (;;) + { + if ((yyn = yysindex[*yyssp]) && (yyn += YYERRCODE) >= 0 && + yyn <= YYTABLESIZE && yycheck[yyn] == YYERRCODE) + { +#if YYDEBUG + if (yydebug) + printf("%sdebug: state %d, error recovery shifting\ + to state %d\n", YYPREFIX, *yyssp, yytable[yyn]); +#endif + if (yyssp >= yysslim && yygrowstack()) + { + goto yyoverflow; + } + *++yyssp = yystate = yytable[yyn]; + *++yyvsp = yylval; + goto yyloop; + } + else + { +#if YYDEBUG + if (yydebug) + printf("%sdebug: error recovery discarding state %d\n", + YYPREFIX, *yyssp); +#endif + if (yyssp <= yyss) goto yyabort; + --yyssp; + --yyvsp; + } + } + } + else + { + if (yychar == 0) goto yyabort; +#if YYDEBUG + if (yydebug) + { + yys = 0; + if (yychar <= YYMAXTOKEN) yys = yyname[yychar]; + if (!yys) yys = "illegal-symbol"; + printf("%sdebug: state %d, error recovery discards token %d (%s)\n", + YYPREFIX, yystate, yychar, yys); + } +#endif + yychar = (-1); + goto yyloop; + } +yyreduce: +#if YYDEBUG + if (yydebug) + printf("%sdebug: state %d, reducing by rule %d (%s)\n", + YYPREFIX, yystate, yyn, yyrule[yyn]); +#endif + yym = yylen[yyn]; + yyval = yyvsp[1-yym]; + switch (yyn) + { +case 7: +#line 86 "/usr/src/lib/libc/net/nsparser.y" +{ + _nsdbtput(&curdbt); + } +break; +case 8: +#line 90 "/usr/src/lib/libc/net/nsparser.y" +{ + yyerrok; + } +break; +case 9: +#line 97 "/usr/src/lib/libc/net/nsparser.y" +{ + curdbt.name = yylval.str; + curdbt.srclist = NULL; + curdbt.srclistsize = 0; + } +break; +case 12: +#line 111 "/usr/src/lib/libc/net/nsparser.y" +{ + cursrc.flags = NS_TERMINATE; + _nsaddsrctomap(yyvsp[0].str); + } +break; +case 13: +#line 115 "/usr/src/lib/libc/net/nsparser.y" +{ cursrc.flags = NS_SUCCESS; } +break; +case 14: +#line 116 "/usr/src/lib/libc/net/nsparser.y" +{ + _nsaddsrctomap(yyvsp[-4].str); + } +break; +case 17: +#line 128 "/usr/src/lib/libc/net/nsparser.y" +{ + if (yyvsp[0].mapval) /* if action == RETURN set RETURN bit */ + cursrc.flags |= yyvsp[-2].mapval; + else /* else unset it */ + cursrc.flags &= ~yyvsp[-2].mapval; + } +break; +case 18: +#line 137 "/usr/src/lib/libc/net/nsparser.y" +{ yyval.mapval = NS_SUCCESS; } +break; +case 19: +#line 138 "/usr/src/lib/libc/net/nsparser.y" +{ yyval.mapval = NS_UNAVAIL; } +break; +case 20: +#line 139 "/usr/src/lib/libc/net/nsparser.y" +{ yyval.mapval = NS_NOTFOUND; } +break; +case 21: +#line 140 "/usr/src/lib/libc/net/nsparser.y" +{ yyval.mapval = NS_TRYAGAIN; } +break; +case 22: +#line 144 "/usr/src/lib/libc/net/nsparser.y" +{ yyval.mapval = NS_ACTION_RETURN; } +break; +case 23: +#line 145 "/usr/src/lib/libc/net/nsparser.y" +{ yyval.mapval = NS_ACTION_CONTINUE; } +break; +#line 559 "y.tab.c" + } + yyssp -= yym; + yystate = *yyssp; + yyvsp -= yym; + yym = yylhs[yyn]; + if (yystate == 0 && yym == 0) + { +#if YYDEBUG + if (yydebug) + printf("%sdebug: after reduction, shifting from state 0 to\ + state %d\n", YYPREFIX, YYFINAL); +#endif + yystate = YYFINAL; + *++yyssp = YYFINAL; + *++yyvsp = yyval; + if (yychar < 0) + { + if ((yychar = yylex()) < 0) yychar = 0; +#if YYDEBUG + if (yydebug) + { + yys = 0; + if (yychar <= YYMAXTOKEN) yys = yyname[yychar]; + if (!yys) yys = "illegal-symbol"; + printf("%sdebug: state %d, reading %d (%s)\n", + YYPREFIX, YYFINAL, yychar, yys); + } +#endif + } + if (yychar == 0) goto yyaccept; + goto yyloop; + } + if ((yyn = yygindex[yym]) && (yyn += yystate) >= 0 && + yyn <= YYTABLESIZE && yycheck[yyn] == yystate) + yystate = yytable[yyn]; + else + yystate = yydgoto[yym]; +#if YYDEBUG + if (yydebug) + printf("%sdebug: after reduction, shifting from state %d \ +to state %d\n", YYPREFIX, *yyssp, yystate); +#endif + if (yyssp >= yysslim && yygrowstack()) + { + goto yyoverflow; + } + *++yyssp = yystate; + *++yyvsp = yyval; + goto yyloop; +yyoverflow: + yyerror("yacc stack overflow"); +yyabort: + return (1); +yyaccept: + return (0); +} diff --git a/lib/libc/net/nsparser.h b/lib/libc/net/nsparser.h new file mode 100644 index 0000000..3433ae3 --- /dev/null +++ b/lib/libc/net/nsparser.h @@ -0,0 +1,18 @@ +#ifndef YYERRCODE +#define YYERRCODE 256 +#endif + +#define NL 257 +#define SUCCESS 258 +#define UNAVAIL 259 +#define NOTFOUND 260 +#define TRYAGAIN 261 +#define RETURN 262 +#define CONTINUE 263 +#define ERRORTOKEN 264 +#define STRING 265 +typedef union { + char *str; + int mapval; +} YYSTYPE; +extern YYSTYPE _nsyylval; diff --git a/lib/libc/net/nsparser.y b/lib/libc/net/nsparser.y new file mode 100644 index 0000000..a013a72 --- /dev/null +++ b/lib/libc/net/nsparser.y @@ -0,0 +1,178 @@ +%{ +/* $NetBSD: nsparser.y,v 1.3 1999/01/25 00:16:18 lukem Exp $ */ + +/*- + * Copyright (c) 1997, 1998, 1999 The NetBSD Foundation, Inc. + * All rights reserved. + * + * This code is derived from software contributed to The NetBSD Foundation + * by Luke Mewburn. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the NetBSD + * Foundation, Inc. and its contributors. + * 4. Neither the name of The NetBSD Foundation 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 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 +__FBSDID("$FreeBSD: src/lib/libc/net/nsparser.y,v 1.4 2003/04/17 14:14:22 nectar Exp $"); + +#include "namespace.h" +#define _NS_PRIVATE +#include +#include +#include +#include +#include "un-namespace.h" + +static void _nsaddsrctomap(const char *); + +static ns_dbt curdbt; +static ns_src cursrc; +%} + +%union { + char *str; + int mapval; +} + +%token NL +%token SUCCESS UNAVAIL NOTFOUND TRYAGAIN +%token RETURN CONTINUE +%token ERRORTOKEN +%token STRING + +%type Status Action + +%% + +File + : /* empty */ + | Lines + ; + +Lines + : Entry + | Lines Entry + ; + +Entry + : NL + | Database ':' NL + | Database ':' Srclist NL + { + _nsdbtput(&curdbt); + } + | error NL + { + yyerrok; + } + ; + +Database + : STRING + { + curdbt.name = yylval.str; + curdbt.srclist = NULL; + curdbt.srclistsize = 0; + } + ; + +Srclist + : Item + | Srclist Item + ; + +Item + : STRING + { + cursrc.flags = NS_TERMINATE; + _nsaddsrctomap($1); + } + | STRING '[' { cursrc.flags = NS_SUCCESS; } Criteria ']' + { + _nsaddsrctomap($1); + } + ; + +Criteria + : Criterion + | Criteria Criterion + ; + +Criterion + : Status '=' Action + { + if ($3) /* if action == RETURN set RETURN bit */ + cursrc.flags |= $1; + else /* else unset it */ + cursrc.flags &= ~$1; + } + ; + +Status + : SUCCESS { $$ = NS_SUCCESS; } + | UNAVAIL { $$ = NS_UNAVAIL; } + | NOTFOUND { $$ = NS_NOTFOUND; } + | TRYAGAIN { $$ = NS_TRYAGAIN; } + ; + +Action + : RETURN { $$ = NS_ACTION_RETURN; } + | CONTINUE { $$ = NS_ACTION_CONTINUE; } + ; + +%% + +static void +_nsaddsrctomap(elem) + const char *elem; +{ + int i, lineno; + extern int _nsyylineno; + extern char * _nsyytext; + + lineno = _nsyylineno - (*_nsyytext == '\n' ? 1 : 0); + if (curdbt.srclistsize > 0) { + if ((strcasecmp(elem, NSSRC_COMPAT) == 0) || + (strcasecmp(curdbt.srclist[0].name, NSSRC_COMPAT) == 0)) { + syslog(LOG_ERR, + "NSSWITCH(nsparser): %s line %d: 'compat' used with other sources", + _PATH_NS_CONF, lineno); + return; + } + } + for (i = 0; i < curdbt.srclistsize; i++) { + if (strcasecmp(curdbt.srclist[i].name, elem) == 0) { + syslog(LOG_ERR, + "NSSWITCH(nsparser): %s line %d: duplicate source '%s'", + _PATH_NS_CONF, lineno, elem); + return; + } + } + cursrc.name = elem; + _nsdbtaddsrc(&curdbt, &cursrc); +} diff --git a/lib/libc/net/nss_backends.h b/lib/libc/net/nss_backends.h new file mode 100644 index 0000000..e39a25a --- /dev/null +++ b/lib/libc/net/nss_backends.h @@ -0,0 +1,43 @@ +/*- + * Copyright (c) 2003 Networks Associates Technology, Inc. + * All rights reserved. + * + * This software was developed for the FreeBSD Project by + * Jacques A. Vidrine, Safeport Network Services, and Network + * Associates Laboratories, the Security Research Division of Network + * Associates, Inc. under DARPA/SPAWAR contract N66001-01-C-8035 + * ("CBOSS"), as part of the DARPA CHATS research program. + * + * 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 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 AUTHOR 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. + * + * $FreeBSD: src/lib/libc/net/nss_backends.h,v 1.1 2003/04/17 14:14:22 nectar Exp $ + */ +/* + * Eventually, the implementations of existing built-in NSS functions + * may be moved into NSS modules and live here. + */ +#if 0 +NSS_BACKEND( files, _files_nss_module_register ) +NSS_BACKEND( dns, _dns_nss_module_register ) +NSS_BACKEND( nis, _nis_nss_module_register ) +NSS_BACKEND( compat, _compat_nss_module_register ) +#endif diff --git a/lib/libc/net/nss_compat.c b/lib/libc/net/nss_compat.c new file mode 100644 index 0000000..16e50c8 --- /dev/null +++ b/lib/libc/net/nss_compat.c @@ -0,0 +1,277 @@ +/*- + * Copyright (c) 2003 Networks Associates Technology, Inc. + * All rights reserved. + * + * This software was developed for the FreeBSD Project by + * Jacques A. Vidrine, Safeport Network Services, and Network + * Associates Laboratories, the Security Research Division of Network + * Associates, Inc. under DARPA/SPAWAR contract N66001-01-C-8035 + * ("CBOSS"), as part of the DARPA CHATS research program. + * + * 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 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 AUTHOR 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. + * + * Compatibility shims for the GNU C Library-style nsswitch interface. + */ +#include + +#include "namespace.h" +#include +#include +#include +#include +#include +#include "un-namespace.h" +#include "libc_private.h" + + +struct group; +struct passwd; + +static int terminator; + +#define DECLARE_TERMINATOR(x) \ +static pthread_key_t _term_key_##x; \ +static void \ +_term_create_##x(void) \ +{ \ + (void)_pthread_key_create(&_term_key_##x, NULL); \ +} \ +static void *_term_main_##x; \ +static pthread_once_t _term_once_##x = PTHREAD_ONCE_INIT + +#define SET_TERMINATOR(x, y) \ +do { \ + if (!__isthreaded || _pthread_main_np()) \ + _term_main_##x = (y); \ + else { \ + (void)_pthread_once(&_term_once_##x, _term_create_##x); \ + (void)_pthread_setspecific(_term_key_##x, y); \ + } \ +} while (0) + +#define CHECK_TERMINATOR(x) \ +(!__isthreaded || _pthread_main_np() ? \ + (_term_main_##x) : \ + ((void)_pthread_once(&_term_once_##x, _term_create_##x), \ + _pthread_getspecific(_term_key_##x))) + + + +DECLARE_TERMINATOR(group); + + +int +__nss_compat_getgrnam_r(void *retval, void *mdata, va_list ap) +{ + int (*fn)(const char *, struct group *, char *, size_t, int *); + const char *name; + struct group *grp; + char *buffer; + int *errnop; + size_t bufsize; + enum nss_status status; + + fn = mdata; + name = va_arg(ap, const char *); + grp = va_arg(ap, struct group *); + buffer = va_arg(ap, char *); + bufsize = va_arg(ap, size_t); + errnop = va_arg(ap, int *); + status = fn(name, grp, buffer, bufsize, errnop); + status = __nss_compat_result(status, *errnop); + if (status == NS_SUCCESS) + *(struct group **)retval = grp; + return (status); +} + + +int +__nss_compat_getgrgid_r(void *retval, void *mdata, va_list ap) +{ + int (*fn)(gid_t, struct group *, char *, size_t, int *); + gid_t gid; + struct group *grp; + char *buffer; + int *errnop; + size_t bufsize; + enum nss_status status; + + fn = mdata; + gid = va_arg(ap, gid_t); + grp = va_arg(ap, struct group *); + buffer = va_arg(ap, char *); + bufsize = va_arg(ap, size_t); + errnop = va_arg(ap, int *); + status = fn(gid, grp, buffer, bufsize, errnop); + status = __nss_compat_result(status, *errnop); + if (status == NS_SUCCESS) + *(struct group **)retval = grp; + return (status); +} + + +int +__nss_compat_getgrent_r(void *retval, void *mdata, va_list ap) +{ + int (*fn)(struct group *, char *, size_t, int *); + struct group *grp; + char *buffer; + int *errnop; + size_t bufsize; + enum nss_status status; + + if (CHECK_TERMINATOR(group)) + return (NS_NOTFOUND); + fn = mdata; + grp = va_arg(ap, struct group *); + buffer = va_arg(ap, char *); + bufsize = va_arg(ap, size_t); + errnop = va_arg(ap, int *); + status = fn(grp, buffer, bufsize, errnop); + status = __nss_compat_result(status, *errnop); + if (status == NS_SUCCESS) + *(struct group **)retval = grp; + else if (status != NS_RETURN) + SET_TERMINATOR(group, &terminator); + return (status); +} + + +int +__nss_compat_setgrent(void *retval, void *mdata, va_list ap) +{ + + SET_TERMINATOR(group, NULL); + ((int (*)(void))mdata)(); + return (NS_UNAVAIL); +} + + +int +__nss_compat_endgrent(void *retval, void *mdata, va_list ap) +{ + + SET_TERMINATOR(group, NULL); + ((int (*)(void))mdata)(); + return (NS_UNAVAIL); +} + + + +DECLARE_TERMINATOR(passwd); + + +int +__nss_compat_getpwnam_r(void *retval, void *mdata, va_list ap) +{ + int (*fn)(const char *, struct passwd *, char *, size_t, int *); + const char *name; + struct passwd *pwd; + char *buffer; + int *errnop; + size_t bufsize; + enum nss_status status; + + fn = mdata; + name = va_arg(ap, const char *); + pwd = va_arg(ap, struct passwd *); + buffer = va_arg(ap, char *); + bufsize = va_arg(ap, size_t); + errnop = va_arg(ap, int *); + status = fn(name, pwd, buffer, bufsize, errnop); + status = __nss_compat_result(status, *errnop); + if (status == NS_SUCCESS) + *(struct passwd **)retval = pwd; + return (status); +} + + +int +__nss_compat_getpwuid_r(void *retval, void *mdata, va_list ap) +{ + int (*fn)(uid_t, struct passwd *, char *, size_t, int *); + uid_t uid; + struct passwd *pwd; + char *buffer; + int *errnop; + size_t bufsize; + enum nss_status status; + + fn = mdata; + uid = va_arg(ap, uid_t); + pwd = va_arg(ap, struct passwd *); + buffer = va_arg(ap, char *); + bufsize = va_arg(ap, size_t); + errnop = va_arg(ap, int *); + status = fn(uid, pwd, buffer, bufsize, errnop); + status = __nss_compat_result(status, *errnop); + if (status == NS_SUCCESS) + *(struct passwd **)retval = pwd; + return (status); +} + + +int +__nss_compat_getpwent_r(void *retval, void *mdata, va_list ap) +{ + int (*fn)(struct passwd *, char *, size_t, int *); + struct passwd *pwd; + char *buffer; + int *errnop; + size_t bufsize; + enum nss_status status; + + if (CHECK_TERMINATOR(passwd)) + return (NS_NOTFOUND); + fn = mdata; + pwd = va_arg(ap, struct passwd *); + buffer = va_arg(ap, char *); + bufsize = va_arg(ap, size_t); + errnop = va_arg(ap, int *); + status = fn(pwd, buffer, bufsize, errnop); + status = __nss_compat_result(status, *errnop); + if (status == NS_SUCCESS) + *(struct passwd **)retval = pwd; + else if (status != NS_RETURN) + SET_TERMINATOR(passwd, &terminator); + return (status); +} + + +int +__nss_compat_setpwent(void *retval, void *mdata, va_list ap) +{ + + SET_TERMINATOR(passwd, NULL); + ((int (*)(void))mdata)(); + return (NS_UNAVAIL); +} + + +int +__nss_compat_endpwent(void *retval, void *mdata, va_list ap) +{ + + SET_TERMINATOR(passwd, NULL); + ((int (*)(void))mdata)(); + return (NS_UNAVAIL); +} diff --git a/lib/libc/net/rcmd.c b/lib/libc/net/rcmd.c new file mode 100644 index 0000000..bacbc31 --- /dev/null +++ b/lib/libc/net/rcmd.c @@ -0,0 +1,764 @@ +/* + * Copyright (c) 1983, 1993, 1994 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)rcmd.c 8.3 (Berkeley) 3/26/94"; +#endif /* LIBC_SCCS and not lint */ +#include + +#include "namespace.h" +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef YP +#include +#include +#endif +#include +#include "un-namespace.h" + +extern int innetgr( const char *, const char *, const char *, const char * ); + +#define max(a, b) ((a > b) ? a : b) + +int __ivaliduser(FILE *, uint32_t, const char *, const char *); +int __ivaliduser_af(FILE *,const void *, const char *, const char *, int, int); +int __ivaliduser_sa(FILE *, const struct sockaddr *, socklen_t, const char *, + const char *); +static int __icheckhost(const struct sockaddr *, socklen_t, const char *); + +char paddr[NI_MAXHOST]; + +int +rcmd(ahost, rport, locuser, remuser, cmd, fd2p) + char **ahost; + u_short rport; + const char *locuser, *remuser, *cmd; + int *fd2p; +{ + return rcmd_af(ahost, rport, locuser, remuser, cmd, fd2p, AF_INET); +} + +int +rcmd_af(ahost, rport, locuser, remuser, cmd, fd2p, af) + char **ahost; + u_short rport; + const char *locuser, *remuser, *cmd; + int *fd2p; + int af; +{ + struct addrinfo hints, *res, *ai; + struct sockaddr_storage from; + fd_set reads; + sigset_t oldmask, newmask; + pid_t pid; + int s, aport, lport, timo, error; + char c, *p; + int refused, nres; + char num[8]; + static char canonnamebuf[MAXDNAME]; /* is it proper here? */ + + /* call rcmdsh() with specified remote shell if appropriate. */ + if (!issetugid() && (p = getenv("RSH"))) { + struct servent *sp = getservbyname("shell", "tcp"); + + if (sp && sp->s_port == rport) + return (rcmdsh(ahost, rport, locuser, remuser, + cmd, p)); + } + + /* use rsh(1) if non-root and remote port is shell. */ + if (geteuid()) { + struct servent *sp = getservbyname("shell", "tcp"); + + if (sp && sp->s_port == rport) + return (rcmdsh(ahost, rport, locuser, remuser, + cmd, NULL)); + } + + pid = getpid(); + + memset(&hints, 0, sizeof(hints)); + hints.ai_flags = AI_CANONNAME; + hints.ai_family = af; + hints.ai_socktype = SOCK_STREAM; + hints.ai_protocol = 0; + (void)snprintf(num, sizeof(num), "%d", ntohs(rport)); + error = getaddrinfo(*ahost, num, &hints, &res); + if (error) { + fprintf(stderr, "rcmd: getaddrinfo: %s\n", + gai_strerror(error)); + if (error == EAI_SYSTEM) + fprintf(stderr, "rcmd: getaddrinfo: %s\n", + strerror(errno)); + return (-1); + } + + if (res->ai_canonname + && strlen(res->ai_canonname) + 1 < sizeof(canonnamebuf)) { + strncpy(canonnamebuf, res->ai_canonname, sizeof(canonnamebuf)); + *ahost = canonnamebuf; + } + nres = 0; + for (ai = res; ai; ai = ai->ai_next) + nres++; + ai = res; + refused = 0; + sigemptyset(&newmask); + sigaddset(&newmask, SIGURG); + _sigprocmask(SIG_BLOCK, (const sigset_t *)&newmask, &oldmask); + for (timo = 1, lport = IPPORT_RESERVED - 1;;) { + s = rresvport_af(&lport, ai->ai_family); + if (s < 0) { + if (errno != EAGAIN && ai->ai_next) { + ai = ai->ai_next; + continue; + } + if (errno == EAGAIN) + (void)fprintf(stderr, + "rcmd: socket: All ports in use\n"); + else + (void)fprintf(stderr, "rcmd: socket: %s\n", + strerror(errno)); + freeaddrinfo(res); + _sigprocmask(SIG_SETMASK, (const sigset_t *)&oldmask, + NULL); + return (-1); + } + _fcntl(s, F_SETOWN, pid); + if (_connect(s, ai->ai_addr, ai->ai_addrlen) >= 0) + break; + (void)_close(s); + if (errno == EADDRINUSE) { + lport--; + continue; + } + if (errno == ECONNREFUSED) + refused = 1; + if (ai->ai_next == NULL && (!refused || timo > 16)) { + (void)fprintf(stderr, "%s: %s\n", + *ahost, strerror(errno)); + freeaddrinfo(res); + _sigprocmask(SIG_SETMASK, (const sigset_t *)&oldmask, + NULL); + return (-1); + } + if (nres > 1) { + int oerrno = errno; + + getnameinfo(ai->ai_addr, ai->ai_addrlen, paddr, + sizeof(paddr), NULL, 0, NI_NUMERICHOST); + (void)fprintf(stderr, "connect to address %s: ", + paddr); + errno = oerrno; + perror(0); + } + if ((ai = ai->ai_next) == NULL) { + /* refused && timo <= 16 */ + struct timespec time_to_sleep, time_remaining; + + time_to_sleep.tv_sec = timo; + time_to_sleep.tv_nsec = 0; + (void)_nanosleep(&time_to_sleep, &time_remaining); + timo *= 2; + ai = res; + refused = 0; + } + if (nres > 1) { + getnameinfo(ai->ai_addr, ai->ai_addrlen, paddr, + sizeof(paddr), NULL, 0, NI_NUMERICHOST); + fprintf(stderr, "Trying %s...\n", paddr); + } + } + lport--; + if (fd2p == 0) { + _write(s, "", 1); + lport = 0; + } else { + int s2 = rresvport_af(&lport, ai->ai_family), s3; + socklen_t len = ai->ai_addrlen; + int nfds; + + if (s2 < 0) + goto bad; + _listen(s2, 1); + (void)snprintf(num, sizeof(num), "%d", lport); + if (_write(s, num, strlen(num)+1) != strlen(num)+1) { + (void)fprintf(stderr, + "rcmd: write (setting up stderr): %s\n", + strerror(errno)); + (void)_close(s2); + goto bad; + } + nfds = max(s, s2)+1; + if(nfds > FD_SETSIZE) { + fprintf(stderr, "rcmd: too many files\n"); + (void)_close(s2); + goto bad; + } +again: + FD_ZERO(&reads); + FD_SET(s, &reads); + FD_SET(s2, &reads); + errno = 0; + if (_select(nfds, &reads, 0, 0, 0) < 1 || !FD_ISSET(s2, &reads)){ + if (errno != 0) + (void)fprintf(stderr, + "rcmd: select (setting up stderr): %s\n", + strerror(errno)); + else + (void)fprintf(stderr, + "select: protocol failure in circuit setup\n"); + (void)_close(s2); + goto bad; + } + s3 = _accept(s2, (struct sockaddr *)&from, &len); + switch (from.ss_family) { + case AF_INET: + aport = ntohs(((struct sockaddr_in *)&from)->sin_port); + break; +#ifdef INET6 + case AF_INET6: + aport = ntohs(((struct sockaddr_in6 *)&from)->sin6_port); + break; +#endif + default: + aport = 0; /* error */ + break; + } + /* + * XXX careful for ftp bounce attacks. If discovered, shut them + * down and check for the real auxiliary channel to connect. + */ + if (aport == 20) { + _close(s3); + goto again; + } + (void)_close(s2); + if (s3 < 0) { + (void)fprintf(stderr, + "rcmd: accept: %s\n", strerror(errno)); + lport = 0; + goto bad; + } + *fd2p = s3; + if (aport >= IPPORT_RESERVED || aport < IPPORT_RESERVED / 2) { + (void)fprintf(stderr, + "socket: protocol failure in circuit setup.\n"); + goto bad2; + } + } + (void)_write(s, locuser, strlen(locuser)+1); + (void)_write(s, remuser, strlen(remuser)+1); + (void)_write(s, cmd, strlen(cmd)+1); + if (_read(s, &c, 1) != 1) { + (void)fprintf(stderr, + "rcmd: %s: %s\n", *ahost, strerror(errno)); + goto bad2; + } + if (c != 0) { + while (_read(s, &c, 1) == 1) { + (void)_write(STDERR_FILENO, &c, 1); + if (c == '\n') + break; + } + goto bad2; + } + _sigprocmask(SIG_SETMASK, (const sigset_t *)&oldmask, NULL); + freeaddrinfo(res); + return (s); +bad2: + if (lport) + (void)_close(*fd2p); +bad: + (void)_close(s); + _sigprocmask(SIG_SETMASK, (const sigset_t *)&oldmask, NULL); + freeaddrinfo(res); + return (-1); +} + +int +rresvport(port) + int *port; +{ + return rresvport_af(port, AF_INET); +} + +int +rresvport_af(alport, family) + int *alport, family; +{ + int s; + struct sockaddr_storage ss; + u_short *sport; + + memset(&ss, 0, sizeof(ss)); + ss.ss_family = family; + switch (family) { + case AF_INET: + ((struct sockaddr *)&ss)->sa_len = sizeof(struct sockaddr_in); + sport = &((struct sockaddr_in *)&ss)->sin_port; + ((struct sockaddr_in *)&ss)->sin_addr.s_addr = INADDR_ANY; + break; +#ifdef INET6 + case AF_INET6: + ((struct sockaddr *)&ss)->sa_len = sizeof(struct sockaddr_in6); + sport = &((struct sockaddr_in6 *)&ss)->sin6_port; + ((struct sockaddr_in6 *)&ss)->sin6_addr = in6addr_any; + break; +#endif + default: + errno = EAFNOSUPPORT; + return -1; + } + + s = _socket(ss.ss_family, SOCK_STREAM, 0); + if (s < 0) + return (-1); +#if 0 /* compat_exact_traditional_rresvport_semantics */ + sin.sin_port = htons((u_short)*alport); + if (_bind(s, (struct sockaddr *)&sin, sizeof(sin)) >= 0) + return (s); + if (errno != EADDRINUSE) { + (void)_close(s); + return (-1); + } +#endif + *sport = 0; + if (bindresvport_sa(s, (struct sockaddr *)&ss) == -1) { + (void)_close(s); + return (-1); + } + *alport = (int)ntohs(*sport); + return (s); +} + +int __check_rhosts_file = 1; +char *__rcmd_errstr; + +int +ruserok(rhost, superuser, ruser, luser) + const char *rhost, *ruser, *luser; + int superuser; +{ + struct addrinfo hints, *res, *r; + int error; + + memset(&hints, 0, sizeof(hints)); + hints.ai_family = PF_UNSPEC; + hints.ai_socktype = SOCK_DGRAM; /*dummy*/ + error = getaddrinfo(rhost, "0", &hints, &res); + if (error) + return (-1); + + for (r = res; r; r = r->ai_next) { + if (iruserok_sa(r->ai_addr, r->ai_addrlen, superuser, ruser, + luser) == 0) { + freeaddrinfo(res); + return (0); + } + } + freeaddrinfo(res); + return (-1); +} + +/* + * New .rhosts strategy: We are passed an ip address. We spin through + * hosts.equiv and .rhosts looking for a match. When the .rhosts only + * has ip addresses, we don't have to trust a nameserver. When it + * contains hostnames, we spin through the list of addresses the nameserver + * gives us and look for a match. + * + * Returns 0 if ok, -1 if not ok. + */ +int +iruserok(raddr, superuser, ruser, luser) + unsigned long raddr; + int superuser; + const char *ruser, *luser; +{ + struct sockaddr_in sin; + + memset(&sin, 0, sizeof(sin)); + sin.sin_family = AF_INET; + sin.sin_len = sizeof(struct sockaddr_in); + memcpy(&sin.sin_addr, &raddr, sizeof(sin.sin_addr)); + return iruserok_sa((struct sockaddr *)&sin, sin.sin_len, superuser, + ruser, luser); +} + +/* + * AF independent extension of iruserok. + * + * Returns 0 if ok, -1 if not ok. + */ +int +iruserok_sa(ra, rlen, superuser, ruser, luser) + const void *ra; + int rlen; + int superuser; + const char *ruser, *luser; +{ + char *cp; + struct stat sbuf; + struct passwd *pwd; + FILE *hostf; + uid_t uid; + int first; + char pbuf[MAXPATHLEN]; + const struct sockaddr *raddr; + struct sockaddr_storage ss; + + /* avoid alignment issue */ + if (rlen > sizeof(ss)) + return(-1); + memcpy(&ss, ra, rlen); + raddr = (struct sockaddr *)&ss; + + first = 1; + hostf = superuser ? NULL : fopen(_PATH_HEQUIV, "r"); +again: + if (hostf) { + if (__ivaliduser_sa(hostf, raddr, rlen, luser, ruser) == 0) { + (void)fclose(hostf); + return (0); + } + (void)fclose(hostf); + } + if (first == 1 && (__check_rhosts_file || superuser)) { + first = 0; + if ((pwd = getpwnam(luser)) == NULL) + return (-1); + (void)strcpy(pbuf, pwd->pw_dir); + (void)strcat(pbuf, "/.rhosts"); + + /* + * Change effective uid while opening .rhosts. If root and + * reading an NFS mounted file system, can't read files that + * are protected read/write owner only. + */ + uid = geteuid(); + (void)seteuid(pwd->pw_uid); + hostf = fopen(pbuf, "r"); + (void)seteuid(uid); + + if (hostf == NULL) + return (-1); + /* + * If not a regular file, or is owned by someone other than + * user or root or if writeable by anyone but the owner, quit. + */ + cp = NULL; + if (lstat(pbuf, &sbuf) < 0) + cp = ".rhosts lstat failed"; + else if (!S_ISREG(sbuf.st_mode)) + cp = ".rhosts not regular file"; + else if (_fstat(fileno(hostf), &sbuf) < 0) + cp = ".rhosts fstat failed"; + else if (sbuf.st_uid && sbuf.st_uid != pwd->pw_uid) + cp = "bad .rhosts owner"; + else if (sbuf.st_mode & (S_IWGRP|S_IWOTH)) + cp = ".rhosts writeable by other than owner"; + /* If there were any problems, quit. */ + if (cp) { + __rcmd_errstr = cp; + (void)fclose(hostf); + return (-1); + } + goto again; + } + return (-1); +} + +/* + * XXX + * Don't make static, used by lpd(8). + * + * Returns 0 if ok, -1 if not ok. + */ +int +__ivaliduser(hostf, raddr, luser, ruser) + FILE *hostf; + uint32_t raddr; + const char *luser, *ruser; +{ + struct sockaddr_in sin; + + memset(&sin, 0, sizeof(sin)); + sin.sin_family = AF_INET; + sin.sin_len = sizeof(struct sockaddr_in); + memcpy(&sin.sin_addr, &raddr, sizeof(sin.sin_addr)); + return __ivaliduser_sa(hostf, (struct sockaddr *)&sin, sin.sin_len, + luser, ruser); +} + +/* + * Returns 0 if ok, -1 if not ok. + * + * XXX obsolete API. + */ +int +__ivaliduser_af(hostf, raddr, luser, ruser, af, len) + FILE *hostf; + const void *raddr; + const char *luser, *ruser; + int af, len; +{ + struct sockaddr *sa = NULL; + struct sockaddr_in *sin = NULL; +#ifdef INET6 + struct sockaddr_in6 *sin6 = NULL; +#endif + struct sockaddr_storage ss; + + memset(&ss, 0, sizeof(ss)); + switch (af) { + case AF_INET: + if (len != sizeof(sin->sin_addr)) + return -1; + sin = (struct sockaddr_in *)&ss; + sin->sin_family = AF_INET; + sin->sin_len = sizeof(struct sockaddr_in); + memcpy(&sin->sin_addr, raddr, sizeof(sin->sin_addr)); + break; +#ifdef INET6 + case AF_INET6: + if (len != sizeof(sin6->sin6_addr)) + return -1; + /* you will lose scope info */ + sin6 = (struct sockaddr_in6 *)&ss; + sin6->sin6_family = AF_INET6; + sin6->sin6_len = sizeof(struct sockaddr_in6); + memcpy(&sin6->sin6_addr, raddr, sizeof(sin6->sin6_addr)); + break; +#endif + default: + return -1; + } + + sa = (struct sockaddr *)&ss; + return __ivaliduser_sa(hostf, sa, sa->sa_len, luser, ruser); +} + +int +__ivaliduser_sa(hostf, raddr, salen, luser, ruser) + FILE *hostf; + const struct sockaddr *raddr; + socklen_t salen; + const char *luser, *ruser; +{ + char *user, *p; + int ch; + char buf[MAXHOSTNAMELEN + 128]; /* host + login */ + char hname[MAXHOSTNAMELEN]; + /* Presumed guilty until proven innocent. */ + int userok = 0, hostok = 0; +#ifdef YP + char *ypdomain; + + if (yp_get_default_domain(&ypdomain)) + ypdomain = NULL; +#else +#define ypdomain NULL +#endif + /* We need to get the damn hostname back for netgroup matching. */ + if (getnameinfo(raddr, salen, hname, sizeof(hname), NULL, 0, + NI_NAMEREQD) != 0) + hname[0] = '\0'; + + while (fgets(buf, sizeof(buf), hostf)) { + p = buf; + /* Skip lines that are too long. */ + if (strchr(p, '\n') == NULL) { + while ((ch = getc(hostf)) != '\n' && ch != EOF); + continue; + } + if (*p == '\n' || *p == '#') { + /* comment... */ + continue; + } + while (*p != '\n' && *p != ' ' && *p != '\t' && *p != '\0') { + *p = isupper((unsigned char)*p) ? tolower((unsigned char)*p) : *p; + p++; + } + if (*p == ' ' || *p == '\t') { + *p++ = '\0'; + while (*p == ' ' || *p == '\t') + p++; + user = p; + while (*p != '\n' && *p != ' ' && + *p != '\t' && *p != '\0') + p++; + } else + user = p; + *p = '\0'; + /* + * Do +/- and +@/-@ checking. This looks really nasty, + * but it matches SunOS's behavior so far as I can tell. + */ + switch(buf[0]) { + case '+': + if (!buf[1]) { /* '+' matches all hosts */ + hostok = 1; + break; + } + if (buf[1] == '@') /* match a host by netgroup */ + hostok = hname[0] != '\0' && + innetgr(&buf[2], hname, NULL, ypdomain); + else /* match a host by addr */ + hostok = __icheckhost(raddr, salen, + (char *)&buf[1]); + break; + case '-': /* reject '-' hosts and all their users */ + if (buf[1] == '@') { + if (hname[0] == '\0' || + innetgr(&buf[2], hname, NULL, ypdomain)) + return(-1); + } else { + if (__icheckhost(raddr, salen, + (char *)&buf[1])) + return(-1); + } + break; + default: /* if no '+' or '-', do a simple match */ + hostok = __icheckhost(raddr, salen, buf); + break; + } + switch(*user) { + case '+': + if (!*(user+1)) { /* '+' matches all users */ + userok = 1; + break; + } + if (*(user+1) == '@') /* match a user by netgroup */ + userok = innetgr(user+2, NULL, ruser, ypdomain); + else /* match a user by direct specification */ + userok = !(strcmp(ruser, user+1)); + break; + case '-': /* if we matched a hostname, */ + if (hostok) { /* check for user field rejections */ + if (!*(user+1)) + return(-1); + if (*(user+1) == '@') { + if (innetgr(user+2, NULL, + ruser, ypdomain)) + return(-1); + } else { + if (!strcmp(ruser, user+1)) + return(-1); + } + } + break; + default: /* no rejections: try to match the user */ + if (hostok) + userok = !(strcmp(ruser,*user ? user : luser)); + break; + } + if (hostok && userok) + return(0); + } + return (-1); +} + +/* + * Returns "true" if match, 0 if no match. + */ +static int +__icheckhost(raddr, salen, lhost) + const struct sockaddr *raddr; + socklen_t salen; + const char *lhost; +{ + struct sockaddr_in sin; + struct sockaddr_in6 *sin6; + struct addrinfo hints, *res, *r; + int error; + char h1[NI_MAXHOST], h2[NI_MAXHOST]; + + if (raddr->sa_family == AF_INET6) { + sin6 = (struct sockaddr_in6 *)raddr; + if (IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) { + memset(&sin, 0, sizeof(sin)); + sin.sin_family = AF_INET; + sin.sin_len = sizeof(struct sockaddr_in); + memcpy(&sin.sin_addr, &sin6->sin6_addr.s6_addr[12], + sizeof(sin.sin_addr)); + raddr = (struct sockaddr *)&sin; + salen = sin.sin_len; + } + } + + h1[0] = '\0'; + if (getnameinfo(raddr, salen, h1, sizeof(h1), NULL, 0, + NI_NUMERICHOST) != 0) + return (0); + + /* Resolve laddr into sockaddr */ + memset(&hints, 0, sizeof(hints)); + hints.ai_family = raddr->sa_family; + hints.ai_socktype = SOCK_DGRAM; /*XXX dummy*/ + res = NULL; + error = getaddrinfo(lhost, "0", &hints, &res); + if (error) + return (0); + + for (r = res; r ; r = r->ai_next) { + h2[0] = '\0'; + if (getnameinfo(r->ai_addr, r->ai_addrlen, h2, sizeof(h2), + NULL, 0, NI_NUMERICHOST) != 0) + continue; + if (strcmp(h1, h2) == 0) { + freeaddrinfo(res); + return (1); + } + } + + /* No match. */ + freeaddrinfo(res); + return (0); +} diff --git a/lib/libc/net/rcmdsh.c b/lib/libc/net/rcmdsh.c new file mode 100644 index 0000000..3ea0174 --- /dev/null +++ b/lib/libc/net/rcmdsh.c @@ -0,0 +1,169 @@ +/* $OpenBSD: rcmdsh.c,v 1.5 1998/04/25 16:23:58 millert Exp $ */ + +/* + * Copyright (c) 2001, MagniComp + * 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 MagniComp 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 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 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. + */ + +/* + * This is an rcmd() replacement originally by + * Chris Siebenmann . + */ + +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#ifndef _PATH_RSH +#define _PATH_RSH "/usr/bin/rsh" +#endif + +/* + * This is a replacement rcmd() function that uses the rsh(1) + * program in place of a direct rcmd(3) function call so as to + * avoid having to be root. Note that rport is ignored. + */ +int +rcmdsh(ahost, rport, locuser, remuser, cmd, rshprog) + char **ahost; + int rport; + const char *locuser, *remuser, *cmd, *rshprog; +{ + struct addrinfo hints, *res; + int cpid, sp[2], error; + char *p; + struct passwd *pw; + char num[8]; + static char hbuf[NI_MAXHOST]; + + /* What rsh/shell to use. */ + if (rshprog == NULL) + rshprog = _PATH_RSH; + + /* locuser must exist on this host. */ + if ((pw = getpwnam(locuser)) == NULL) { + (void)fprintf(stderr, "rcmdsh: unknown user: %s\n", locuser); + return (-1); + } + + /* Validate remote hostname. */ + if (strcmp(*ahost, "localhost") != 0) { + memset(&hints, 0, sizeof(hints)); + hints.ai_flags = AI_CANONNAME; + hints.ai_family = PF_UNSPEC; + hints.ai_socktype = SOCK_STREAM; + (void)snprintf(num, sizeof(num), "%u", + (unsigned int)ntohs(rport)); + error = getaddrinfo(*ahost, num, &hints, &res); + if (error) { + fprintf(stderr, "rcmdsh: getaddrinfo: %s\n", + gai_strerror(error)); + return (-1); + } + if (res->ai_canonname) { + strncpy(hbuf, res->ai_canonname, sizeof(hbuf) - 1); + hbuf[sizeof(hbuf) - 1] = '\0'; + *ahost = hbuf; + } + freeaddrinfo(res); + } + + /* Get a socketpair we'll use for stdin and stdout. */ + if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, sp) == -1) { + perror("rcmdsh: socketpair"); + return (-1); + } + + cpid = fork(); + if (cpid == -1) { + perror("rcmdsh: fork failed"); + return (-1); + } else if (cpid == 0) { + /* + * Child. We use sp[1] to be stdin/stdout, and close sp[0]. + */ + (void)close(sp[0]); + if (dup2(sp[1], 0) == -1 || dup2(0, 1) == -1) { + perror("rcmdsh: dup2 failed"); + _exit(255); + } + /* Fork again to lose parent. */ + cpid = fork(); + if (cpid == -1) { + perror("rcmdsh: fork to lose parent failed"); + _exit(255); + } + if (cpid > 0) + _exit(0); + + /* In grandchild here. Become local user for rshprog. */ + if (setuid(pw->pw_uid) == -1) { + (void)fprintf(stderr, "rcmdsh: setuid(%u): %s\n", + pw->pw_uid, strerror(errno)); + _exit(255); + } + + /* + * If remote host is "localhost" and local and remote users + * are the same, avoid running remote shell for efficiency. + */ + if (strcmp(*ahost, "localhost") == 0 && + strcmp(locuser, remuser) == 0) { + if (pw->pw_shell[0] == '\0') + rshprog = _PATH_BSHELL; + else + rshprog = pw->pw_shell; + p = strrchr(rshprog, '/'); + execlp(rshprog, p ? p + 1 : rshprog, "-c", cmd, + (char *)NULL); + } else { + p = strrchr(rshprog, '/'); + execlp(rshprog, p ? p + 1 : rshprog, *ahost, "-l", + remuser, cmd, (char *)NULL); + } + (void)fprintf(stderr, "rcmdsh: execlp %s failed: %s\n", + rshprog, strerror(errno)); + _exit(255); + } else { + /* Parent. close sp[1], return sp[0]. */ + (void)close(sp[1]); + /* Reap child. */ + (void)wait(NULL); + return (sp[0]); + } + /* NOTREACHED */ +} diff --git a/lib/libc/net/recv.c b/lib/libc/net/recv.c new file mode 100644 index 0000000..30aa59a --- /dev/null +++ b/lib/libc/net/recv.c @@ -0,0 +1,53 @@ +/* + * Copyright (c) 1988, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)recv.c 8.2 (Berkeley) 2/21/94"; +#endif /* LIBC_SCCS and not lint */ +#include + +#include "namespace.h" +#include +#include + +#include +#include "un-namespace.h" + +ssize_t +recv(s, buf, len, flags) + int s, flags; + size_t len; + void *buf; +{ + return (_recvfrom(s, buf, len, flags, NULL, 0)); +} diff --git a/lib/libc/net/res_config.h b/lib/libc/net/res_config.h new file mode 100644 index 0000000..30d8b5b --- /dev/null +++ b/lib/libc/net/res_config.h @@ -0,0 +1,6 @@ +/* $FreeBSD: src/lib/libc/net/res_config.h,v 1.8.14.1 2006/07/17 10:09:57 ume Exp $ */ + +#define DEBUG 1 /* enable debugging code (needed for dig) */ +#define RESOLVSORT /* allow sorting of addresses in gethostbyname */ +#undef SUNSECURITY /* verify gethostbyaddr() calls - WE DONT NEED IT */ +#define MULTI_PTRS_ARE_ALIASES 1 /* fold multiple PTR records into aliases */ diff --git a/lib/libc/net/res_mkupdate.c b/lib/libc/net/res_mkupdate.c new file mode 100644 index 0000000..64f0bd4 --- /dev/null +++ b/lib/libc/net/res_mkupdate.c @@ -0,0 +1,405 @@ +/* + * Copyright (c) 1996 by Internet Software Consortium. + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM DISCLAIMS + * ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL INTERNET SOFTWARE + * CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL + * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR + * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS + * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS + * SOFTWARE. + */ + +/* + * Based on the Dynamic DNS reference implementation by Viraj Bais + * + */ + +#include + +#include +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "res_config.h" + +static int getnum_str(u_char **, u_char *); +static int getword_str(char *, int, u_char **, u_char *); + +#define ShrinkBuffer(x) if ((buflen -= x) < 0) return (-2); + +/* + * Form update packets. + * Returns the size of the resulting packet if no error + * On error, + * returns -1 if error in reading a word/number in rdata + * portion for update packets + * -2 if length of buffer passed is insufficient + * -3 if zone section is not the first section in + * the linked list, or section order has a problem + * -4 on a number overflow + * -5 unknown operation or no records + */ +int +res_nmkupdate(res_state statp, ns_updrec *rrecp_in, u_char *buf, int buflen) { + ns_updrec *rrecp_start = rrecp_in; + HEADER *hp; + u_char *cp, *sp2, *startp, *endp; + int n, i, soanum, multiline; + ns_updrec *rrecp; + struct in_addr ina; + char buf2[MAXDNAME]; + int section, numrrs = 0, counts[ns_s_max]; + u_int16_t rtype, rclass; + uint32_t n1, rttl; + u_char *dnptrs[20], **dpp, **lastdnptr; + + /* + * Initialize header fields. + */ + if ((buf == NULL) || (buflen < HFIXEDSZ)) + return (-1); + memset(buf, 0, HFIXEDSZ); + hp = (HEADER *) buf; + hp->id = htons(++statp->id); + hp->opcode = ns_o_update; + hp->rcode = NOERROR; + cp = buf + HFIXEDSZ; + buflen -= HFIXEDSZ; + dpp = dnptrs; + *dpp++ = buf; + *dpp++ = NULL; + lastdnptr = dnptrs + sizeof dnptrs / sizeof dnptrs[0]; + + if (rrecp_start == NULL) + return (-5); + else if (rrecp_start->r_section != S_ZONE) + return (-3); + + memset(counts, 0, sizeof counts); + for (rrecp = rrecp_start; rrecp; rrecp = rrecp->r_grpnext) { + numrrs++; + section = rrecp->r_section; + if (section < 0 || section >= ns_s_max) + return (-1); + counts[section]++; + for (i = section + 1; i < ns_s_max; i++) + if (counts[i]) + return (-3); + rtype = rrecp->r_type; + rclass = rrecp->r_class; + rttl = rrecp->r_ttl; + /* overload class and type */ + if (section == S_PREREQ) { + rttl = 0; + switch (rrecp->r_opcode) { + case YXDOMAIN: + rclass = C_ANY; + rtype = T_ANY; + rrecp->r_size = 0; + break; + case NXDOMAIN: + rclass = C_NONE; + rtype = T_ANY; + rrecp->r_size = 0; + break; + case NXRRSET: + rclass = C_NONE; + rrecp->r_size = 0; + break; + case YXRRSET: + if (rrecp->r_size == 0) + rclass = C_ANY; + break; + default: + fprintf(stderr, + "res_nmkupdate: incorrect opcode: %d\n", + rrecp->r_opcode); + fflush(stderr); + return (-1); + } + } else if (section == S_UPDATE) { + switch (rrecp->r_opcode) { + case DELETE: + rclass = rrecp->r_size == 0 ? C_ANY : C_NONE; + break; + case ADD: + break; + default: + fprintf(stderr, + "res_nmkupdate: incorrect opcode: %d\n", + rrecp->r_opcode); + fflush(stderr); + return (-1); + } + } + + /* + * XXX appending default domain to owner name is omitted, + * fqdn must be provided + */ + if ((n = dn_comp(rrecp->r_dname, cp, buflen, dnptrs, + lastdnptr)) < 0) + return (-1); + cp += n; + ShrinkBuffer(n + 2*INT16SZ); + PUTSHORT(rtype, cp); + PUTSHORT(rclass, cp); + if (section == S_ZONE) { + if (numrrs != 1 || rrecp->r_type != T_SOA) + return (-3); + continue; + } + ShrinkBuffer(INT32SZ + INT16SZ); + PUTLONG(rttl, cp); + sp2 = cp; /* save pointer to length byte */ + cp += INT16SZ; + if (rrecp->r_size == 0) { + if (section == S_UPDATE && rclass != C_ANY) + return (-1); + else { + PUTSHORT(0, sp2); + continue; + } + } + startp = rrecp->r_data; + endp = startp + rrecp->r_size - 1; + /* XXX this should be done centrally. */ + switch (rrecp->r_type) { + case T_A: + if (!getword_str(buf2, sizeof buf2, &startp, endp)) + return (-1); + if (!inet_aton(buf2, &ina)) + return (-1); + n1 = ntohl(ina.s_addr); + ShrinkBuffer(INT32SZ); + PUTLONG(n1, cp); + break; + case T_CNAME: + case T_MB: + case T_MG: + case T_MR: + case T_NS: + case T_PTR: + if (!getword_str(buf2, sizeof buf2, &startp, endp)) + return (-1); + n = dn_comp(buf2, cp, buflen, dnptrs, lastdnptr); + if (n < 0) + return (-1); + cp += n; + ShrinkBuffer(n); + break; + case T_MINFO: + case T_SOA: + case T_RP: + for (i = 0; i < 2; i++) { + if (!getword_str(buf2, sizeof buf2, &startp, + endp)) + return (-1); + n = dn_comp(buf2, cp, buflen, + dnptrs, lastdnptr); + if (n < 0) + return (-1); + cp += n; + ShrinkBuffer(n); + } + if (rrecp->r_type == T_SOA) { + ShrinkBuffer(5 * INT32SZ); + while (isspace(*startp) || !*startp) + startp++; + if (*startp == '(') { + multiline = 1; + startp++; + } else + multiline = 0; + /* serial, refresh, retry, expire, minimum */ + for (i = 0; i < 5; i++) { + soanum = getnum_str(&startp, endp); + if (soanum < 0) + return (-1); + PUTLONG(soanum, cp); + } + if (multiline) { + while (isspace(*startp) || !*startp) + startp++; + if (*startp != ')') + return (-1); + } + } + break; + case T_MX: + case T_AFSDB: + case T_RT: + n = getnum_str(&startp, endp); + if (n < 0) + return (-1); + PUTSHORT(n, cp); + ShrinkBuffer(INT16SZ); + if (!getword_str(buf2, sizeof buf2, &startp, endp)) + return (-1); + n = dn_comp(buf2, cp, buflen, dnptrs, lastdnptr); + if (n < 0) + return (-1); + cp += n; + ShrinkBuffer(n); + break; + case T_PX: + n = getnum_str(&startp, endp); + if (n < 0) + return (-1); + PUTSHORT(n, cp); + ShrinkBuffer(INT16SZ); + for (i = 0; i < 2; i++) { + if (!getword_str(buf2, sizeof buf2, &startp, + endp)) + return (-1); + n = dn_comp(buf2, cp, buflen, dnptrs, + lastdnptr); + if (n < 0) + return (-1); + cp += n; + ShrinkBuffer(n); + } + break; + case T_WKS: + case T_HINFO: + case T_TXT: + case T_X25: + case T_ISDN: + case T_NSAP: + case T_LOC: + /* XXX - more fine tuning needed here */ + ShrinkBuffer(rrecp->r_size); + memcpy(cp, rrecp->r_data, rrecp->r_size); + cp += rrecp->r_size; + break; + default: + return (-1); + } /*switch*/ + n = (u_int16_t)((cp - sp2) - INT16SZ); + PUTSHORT(n, sp2); + } /*for*/ + + hp->qdcount = htons(counts[0]); + hp->ancount = htons(counts[1]); + hp->nscount = htons(counts[2]); + hp->arcount = htons(counts[3]); + return (cp - buf); +} + +/* + * Get a whitespace delimited word from a string (not file) + * into buf. modify the start pointer to point after the + * word in the string. + */ +static int +getword_str(char *buf, int size, u_char **startpp, u_char *endp) { + char *cp; + int c; + + for (cp = buf; *startpp <= endp; ) { + c = **startpp; + if (isspace(c) || c == '\0') { + if (cp != buf) /* trailing whitespace */ + break; + else { /* leading whitespace */ + (*startpp)++; + continue; + } + } + (*startpp)++; + if (cp >= buf+size-1) + break; + *cp++ = (u_char)c; + } + *cp = '\0'; + return (cp != buf); +} + +/* + * Get a whitespace delimited number from a string (not file) into buf + * update the start pointer to point after the number in the string. + */ +static int +getnum_str(u_char **startpp, u_char *endp) { + int c, n; + int seendigit = 0; + int m = 0; + + for (n = 0; *startpp <= endp; ) { + c = **startpp; + if (isspace(c) || c == '\0') { + if (seendigit) /* trailing whitespace */ + break; + else { /* leading whitespace */ + (*startpp)++; + continue; + } + } + if (c == ';') { + while ((*startpp <= endp) && + ((c = **startpp) != '\n')) + (*startpp)++; + if (seendigit) + break; + continue; + } + if (!isdigit(c)) { + if (c == ')' && seendigit) { + (*startpp)--; + break; + } + return (-1); + } + (*startpp)++; + n = n * 10 + (c - '0'); + seendigit = 1; + } + return (n + m); +} + +/* + * Allocate a resource record buffer & save rr info. + */ +ns_updrec * +res_mkupdrec(int section, const char *dname, + u_int class, u_int type, u_long ttl) { + ns_updrec *rrecp = (ns_updrec *)calloc(1, sizeof(ns_updrec)); + + if (!rrecp || !(rrecp->r_dname = strdup(dname))) + return (NULL); + rrecp->r_class = class; + rrecp->r_type = type; + rrecp->r_ttl = ttl; + rrecp->r_section = section; + return (rrecp); +} + +/* + * Free a resource record buffer created by res_mkupdrec. + */ +void +res_freeupdrec(ns_updrec *rrecp) { + /* Note: freeing r_dp is the caller's responsibility. */ + if (rrecp->r_dname != NULL) + free(rrecp->r_dname); + free(rrecp); +} diff --git a/lib/libc/net/res_update.c b/lib/libc/net/res_update.c new file mode 100644 index 0000000..c246600 --- /dev/null +++ b/lib/libc/net/res_update.c @@ -0,0 +1,521 @@ +/* + * Copyright (c) 1996 by Internet Software Consortium. + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM DISCLAIMS + * ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL INTERNET SOFTWARE + * CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL + * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR + * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS + * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS + * SOFTWARE. + */ + +/* + * Based on the Dynamic DNS reference implementation by Viraj Bais + * + */ + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* + * Separate a linked list of records into groups so that all records + * in a group will belong to a single zone on the nameserver. + * Create a dynamic update packet for each zone and send it to the + * nameservers for that zone, and await answer. + * Abort if error occurs in updating any zone. + * Return the number of zones updated on success, < 0 on error. + * + * On error, caller must deal with the unsynchronized zones + * eg. an A record might have been successfully added to the forward + * zone but the corresponding PTR record would be missing if error + * was encountered while updating the reverse zone. + */ + +#define NSMAX 16 + +struct ns1 { + char nsname[MAXDNAME]; + struct in_addr nsaddr1; +}; + +struct zonegrp { + char z_origin[MAXDNAME]; + int16_t z_class; + char z_soardata[MAXDNAME + 5 * INT32SZ]; + struct ns1 z_ns[NSMAX]; + int z_nscount; + ns_updrec * z_rr; + struct zonegrp *z_next; +}; + + +int +res_nupdate(res_state statp, ns_updrec *rrecp_in, ns_tsig_key *key) { + ns_updrec *rrecp, *tmprrecp; + u_char buf[PACKETSZ], answer[PACKETSZ], packet[2*PACKETSZ]; + char name[MAXDNAME], zname[MAXDNAME], primary[MAXDNAME], + mailaddr[MAXDNAME]; + u_char soardata[2*MAXCDNAME+5*INT32SZ]; + char *dname, *svdname, *cp1, *target; + u_char *cp, *eom; + HEADER *hp = (HEADER *) answer; + struct zonegrp *zptr = NULL, *tmpzptr, *prevzptr, *zgrp_start = NULL; + int i, j, k = 0, n, ancount, nscount, arcount, rcode, rdatasize, + newgroup, done, myzone, seen_before, numzones = 0; + u_int16_t dlen, class, qclass, type, qtype; + uint32_t ttl; + + if (key != NULL) { + /* TSIG is not supported. */ + RES_SET_H_ERRNO(statp, NO_RECOVERY); + return (-1); + } + + for (rrecp = rrecp_in; rrecp; rrecp = rrecp->r_next) { + dname = rrecp->r_dname; + n = strlen(dname); + if (dname[n-1] == '.') + dname[n-1] = '\0'; + qtype = T_SOA; + qclass = rrecp->r_class; + done = 0; + seen_before = 0; + + while (!done && dname) { + if (qtype == T_SOA) { + for (tmpzptr = zgrp_start; + tmpzptr && !seen_before; + tmpzptr = tmpzptr->z_next) { + if (strcasecmp(dname, + tmpzptr->z_origin) == 0 && + tmpzptr->z_class == qclass) + seen_before++; + for (tmprrecp = tmpzptr->z_rr; + tmprrecp && !seen_before; + tmprrecp = tmprrecp->r_grpnext) + if (strcasecmp(dname, tmprrecp->r_dname) == 0 + && tmprrecp->r_class == qclass) { + seen_before++; + break; + } + if (seen_before) { + /* + * Append to the end of + * current group. + */ + for (tmprrecp = tmpzptr->z_rr; + tmprrecp->r_grpnext; + tmprrecp = tmprrecp->r_grpnext) + (void)NULL; + tmprrecp->r_grpnext = rrecp; + rrecp->r_grpnext = NULL; + done = 1; + break; + } + } + } else if (qtype == T_A) { + for (tmpzptr = zgrp_start; + tmpzptr && !done; + tmpzptr = tmpzptr->z_next) + for (i = 0; i < tmpzptr->z_nscount; i++) + if (tmpzptr->z_class == qclass && + strcasecmp(tmpzptr->z_ns[i].nsname, + dname) == 0 && + tmpzptr->z_ns[i].nsaddr1.s_addr != 0) { + zptr->z_ns[k].nsaddr1.s_addr = + tmpzptr->z_ns[i].nsaddr1.s_addr; + done = 1; + break; + } + } + if (done) + break; + n = res_nmkquery(statp, QUERY, dname, qclass, qtype, NULL, + 0, NULL, buf, sizeof buf); + if (n <= 0) { + fprintf(stderr, "res_nupdate: mkquery failed\n"); + return (n); + } + n = res_nsend(statp, buf, n, answer, sizeof answer); + if (n < 0) { + fprintf(stderr, "res_nupdate: send error for %s\n", + rrecp->r_dname); + return (n); + } else if (n > sizeof(answer)) { + fprintf(stderr, "res_nupdate: buffer too small\n"); + return (-1); + } + if (n < HFIXEDSZ) + return (-1); + ancount = ntohs(hp->ancount); + nscount = ntohs(hp->nscount); + arcount = ntohs(hp->arcount); + rcode = hp->rcode; + cp = answer + HFIXEDSZ; + eom = answer + n; + /* skip the question section */ + n = dn_skipname(cp, eom); + if (n < 0 || cp + n + 2 * INT16SZ > eom) + return (-1); + cp += n + 2 * INT16SZ; + + if (qtype == T_SOA) { + if (ancount == 0 && nscount == 0 && arcount == 0) { + /* + * if (rcode == NOERROR) then the dname exists but + * has no soa record associated with it. + * if (rcode == NXDOMAIN) then the dname does not + * exist and the server is replying out of NCACHE. + * in either case, proceed with the next try + */ + dname = strchr(dname, '.'); + if (dname != NULL) + dname++; + continue; + } else if ((rcode == NOERROR || rcode == NXDOMAIN) && + ancount == 0 && + nscount == 1 && arcount == 0) { + /* + * name/data does not exist, soa record supplied in the + * authority section + */ + /* authority section must contain the soa record */ + if ((n = dn_expand(answer, eom, cp, zname, + sizeof zname)) < 0) + return (n); + cp += n; + if (cp + 2 * INT16SZ > eom) + return (-1); + GETSHORT(type, cp); + GETSHORT(class, cp); + if (type != T_SOA || class != qclass) { + fprintf(stderr, "unknown answer\n"); + return (-1); + } + myzone = 0; + svdname = dname; + while (dname) + if (strcasecmp(dname, zname) == 0) { + myzone = 1; + break; + } else if ((dname = strchr(dname, '.')) != NULL) + dname++; + if (!myzone) { + dname = strchr(svdname, '.'); + if (dname != NULL) + dname++; + continue; + } + nscount = 0; + /* fallthrough */ + } else if (rcode == NOERROR && ancount == 1) { + /* + * found the zone name + * new servers will supply NS records for the zone + * in authority section and A records for those + * nameservers in the additional section + * older servers have to be explicitly queried for + * NS records for the zone + */ + /* answer section must contain the soa record */ + if ((n = dn_expand(answer, eom, cp, zname, + sizeof zname)) < 0) + return (n); + else + cp += n; + if (cp + 2 * INT16SZ > eom) + return (-1); + GETSHORT(type, cp); + GETSHORT(class, cp); + if (type == T_CNAME) { + dname = strchr(dname, '.'); + if (dname != NULL) + dname++; + continue; + } + if (strcasecmp(dname, zname) != 0 || + type != T_SOA || + class != rrecp->r_class) { + fprintf(stderr, "unknown answer\n"); + return (-1); + } + /* FALLTHROUGH */ + } else { + fprintf(stderr, + "unknown response: ans=%d, auth=%d, add=%d, rcode=%d\n", + ancount, nscount, arcount, hp->rcode); + return (-1); + } + if (cp + INT32SZ + INT16SZ > eom) + return (-1); + /* continue processing the soa record */ + GETLONG(ttl, cp); + GETSHORT(dlen, cp); + if (cp + dlen > eom) + return (-1); + newgroup = 1; + zptr = zgrp_start; + prevzptr = NULL; + while (zptr) { + if (strcasecmp(zname, zptr->z_origin) == 0 && + type == T_SOA && class == qclass) { + newgroup = 0; + break; + } + prevzptr = zptr; + zptr = zptr->z_next; + } + if (!newgroup) { + for (tmprrecp = zptr->z_rr; + tmprrecp->r_grpnext; + tmprrecp = tmprrecp->r_grpnext) + ; + tmprrecp->r_grpnext = rrecp; + rrecp->r_grpnext = NULL; + done = 1; + cp += dlen; + break; + } else { + if ((n = dn_expand(answer, eom, cp, primary, + sizeof primary)) < 0) + return (n); + cp += n; + /* + * We don't have to bounds check here because the + * next use of 'cp' is in dn_expand(). + */ + cp1 = (char *)soardata; + strcpy(cp1, primary); + cp1 += strlen(cp1) + 1; + if ((n = dn_expand(answer, eom, cp, mailaddr, + sizeof mailaddr)) < 0) + return (n); + cp += n; + strcpy(cp1, mailaddr); + cp1 += strlen(cp1) + 1; + if (cp + 5*INT32SZ > eom) + return (-1); + memcpy(cp1, cp, 5*INT32SZ); + cp += 5*INT32SZ; + cp1 += 5*INT32SZ; + rdatasize = (u_char *)cp1 - soardata; + zptr = calloc(1, sizeof(struct zonegrp)); + if (zptr == NULL) + return (-1); + if (zgrp_start == NULL) + zgrp_start = zptr; + else + prevzptr->z_next = zptr; + zptr->z_rr = rrecp; + rrecp->r_grpnext = NULL; + strcpy(zptr->z_origin, zname); + zptr->z_class = class; + memcpy(zptr->z_soardata, soardata, rdatasize); + /* fallthrough to process NS and A records */ + } + } else if (qtype == T_NS) { + if (rcode == NOERROR && ancount > 0) { + strcpy(zname, dname); + for (zptr = zgrp_start; zptr; zptr = zptr->z_next) { + if (strcasecmp(zname, zptr->z_origin) == 0) + break; + } + if (zptr == NULL) + /* should not happen */ + return (-1); + if (nscount > 0) { + /* + * answer and authority sections contain + * the same information, skip answer section + */ + for (j = 0; j < ancount; j++) { + n = dn_skipname(cp, eom); + if (n < 0) + return (-1); + n += 2*INT16SZ + INT32SZ; + if (cp + n + INT16SZ > eom) + return (-1); + cp += n; + GETSHORT(dlen, cp); + cp += dlen; + } + } else + nscount = ancount; + /* fallthrough to process NS and A records */ + } else { + fprintf(stderr, "cannot determine nameservers for %s:\ +ans=%d, auth=%d, add=%d, rcode=%d\n", + dname, ancount, nscount, arcount, hp->rcode); + return (-1); + } + } else if (qtype == T_A) { + if (rcode == NOERROR && ancount > 0) { + arcount = ancount; + ancount = nscount = 0; + /* fallthrough to process A records */ + } else { + fprintf(stderr, "cannot determine address for %s:\ +ans=%d, auth=%d, add=%d, rcode=%d\n", + dname, ancount, nscount, arcount, hp->rcode); + return (-1); + } + } + /* process NS records for the zone */ + j = 0; + for (i = 0; i < nscount; i++) { + if ((n = dn_expand(answer, eom, cp, name, + sizeof name)) < 0) + return (n); + cp += n; + if (cp + 3 * INT16SZ + INT32SZ > eom) + return (-1); + GETSHORT(type, cp); + GETSHORT(class, cp); + GETLONG(ttl, cp); + GETSHORT(dlen, cp); + if (cp + dlen > eom) + return (-1); + if (strcasecmp(name, zname) == 0 && + type == T_NS && class == qclass) { + if ((n = dn_expand(answer, eom, cp, + name, sizeof name)) < 0) + return (n); + target = zptr->z_ns[j++].nsname; + strcpy(target, name); + } + cp += dlen; + } + if (zptr->z_nscount == 0) + zptr->z_nscount = j; + /* get addresses for the nameservers */ + for (i = 0; i < arcount; i++) { + if ((n = dn_expand(answer, eom, cp, name, + sizeof name)) < 0) + return (n); + cp += n; + if (cp + 3 * INT16SZ + INT32SZ > eom) + return (-1); + GETSHORT(type, cp); + GETSHORT(class, cp); + GETLONG(ttl, cp); + GETSHORT(dlen, cp); + if (cp + dlen > eom) + return (-1); + if (type == T_A && dlen == INT32SZ && class == qclass) { + for (j = 0; j < zptr->z_nscount; j++) + if (strcasecmp(name, zptr->z_ns[j].nsname) == 0) { + memcpy(&zptr->z_ns[j].nsaddr1.s_addr, cp, + INT32SZ); + break; + } + } + cp += dlen; + } + if (zptr->z_nscount == 0) { + dname = zname; + qtype = T_NS; + continue; + } + done = 1; + for (k = 0; k < zptr->z_nscount; k++) + if (zptr->z_ns[k].nsaddr1.s_addr == 0) { + done = 0; + dname = zptr->z_ns[k].nsname; + qtype = T_A; + } + + } /* while */ + } + + statp->options |= RES_DEBUG; + for (zptr = zgrp_start; zptr; zptr = zptr->z_next) { + + /* append zone section */ + rrecp = res_mkupdrec(ns_s_zn, zptr->z_origin, + zptr->z_class, ns_t_soa, 0); + if (rrecp == NULL) { + fprintf(stderr, "saverrec error\n"); + fflush(stderr); + return (-1); + } + rrecp->r_grpnext = zptr->z_rr; + zptr->z_rr = rrecp; + + n = res_nmkupdate(statp, zptr->z_rr, packet, sizeof packet); + if (n < 0) { + fprintf(stderr, "res_nmkupdate error\n"); + fflush(stderr); + return (-1); + } else + fprintf(stdout, "res_nmkupdate: packet size = %d\n", n); + + /* + * Override the list of NS records from res_ninit() with + * the authoritative nameservers for the zone being updated. + * Sort primary to be the first in the list of nameservers. + */ + for (i = 0; i < zptr->z_nscount; i++) { + if (strcasecmp(zptr->z_ns[i].nsname, + zptr->z_soardata) == 0) { + struct in_addr tmpaddr; + + if (i != 0) { + strcpy(zptr->z_ns[i].nsname, + zptr->z_ns[0].nsname); + strcpy(zptr->z_ns[0].nsname, + zptr->z_soardata); + tmpaddr = zptr->z_ns[i].nsaddr1; + zptr->z_ns[i].nsaddr1 = + zptr->z_ns[0].nsaddr1; + zptr->z_ns[0].nsaddr1 = tmpaddr; + } + break; + } + } + for (i = 0; i < MAXNS; i++) { + statp->nsaddr_list[i].sin_addr = zptr->z_ns[i].nsaddr1; + statp->nsaddr_list[i].sin_family = AF_INET; + statp->nsaddr_list[i].sin_port = htons(NAMESERVER_PORT); + } + statp->nscount = (zptr->z_nscount < MAXNS) ? + zptr->z_nscount : MAXNS; + n = res_nsend(statp, packet, n, answer, sizeof(answer)); + if (n < 0) { + fprintf(stderr, "res_nsend: send error, n=%d\n", n); + break; + } else if (n > sizeof(answer)) { + fprintf(stderr, "res_nsend: buffer too small\n"); + break; + } + numzones++; + } + + /* free malloc'ed memory */ + while(zgrp_start) { + zptr = zgrp_start; + zgrp_start = zgrp_start->z_next; + res_freeupdrec(zptr->z_rr); /* Zone section we allocated. */ + free((char *)zptr); + } + + return (numzones); +} diff --git a/lib/libc/net/rthdr.c b/lib/libc/net/rthdr.c new file mode 100644 index 0000000..dc6ca30 --- /dev/null +++ b/lib/libc/net/rthdr.c @@ -0,0 +1,441 @@ +/* $KAME: rthdr.c,v 1.19 2003/06/06 10:48:51 itojun Exp $ */ + +/* + * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project. + * 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 project 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 PROJECT 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 PROJECT 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 + +#include +#include +#include + +#include +#include + +#include +#include + +/* + * RFC2292 API + */ + +size_t +inet6_rthdr_space(type, seg) + int type, seg; +{ + switch (type) { + case IPV6_RTHDR_TYPE_0: + if (seg < 1 || seg > 23) + return (0); +#ifdef COMPAT_RFC2292 + return (CMSG_SPACE(sizeof(struct in6_addr) * (seg - 1) + + sizeof(struct ip6_rthdr0))); +#else + return (CMSG_SPACE(sizeof(struct in6_addr) * seg + + sizeof(struct ip6_rthdr0))); +#endif + default: + return (0); + } +} + +struct cmsghdr * +inet6_rthdr_init(bp, type) + void *bp; + int type; +{ + struct cmsghdr *ch = (struct cmsghdr *)bp; + struct ip6_rthdr *rthdr; + + rthdr = (struct ip6_rthdr *)CMSG_DATA(ch); + + ch->cmsg_level = IPPROTO_IPV6; + ch->cmsg_type = IPV6_RTHDR; + + switch (type) { + case IPV6_RTHDR_TYPE_0: +#ifdef COMPAT_RFC2292 + ch->cmsg_len = CMSG_LEN(sizeof(struct ip6_rthdr0) - + sizeof(struct in6_addr)); +#else + ch->cmsg_len = CMSG_LEN(sizeof(struct ip6_rthdr0)); +#endif + + bzero(rthdr, sizeof(struct ip6_rthdr0)); + rthdr->ip6r_type = IPV6_RTHDR_TYPE_0; + return (ch); + default: + return (NULL); + } +} + +/* ARGSUSED */ +int +inet6_rthdr_add(cmsg, addr, flags) + struct cmsghdr *cmsg; + const struct in6_addr *addr; + u_int flags; +{ + struct ip6_rthdr *rthdr; + + rthdr = (struct ip6_rthdr *)CMSG_DATA(cmsg); + + switch (rthdr->ip6r_type) { + case IPV6_RTHDR_TYPE_0: + { + struct ip6_rthdr0 *rt0 = (struct ip6_rthdr0 *)rthdr; + if (flags != IPV6_RTHDR_LOOSE && flags != IPV6_RTHDR_STRICT) + return (-1); + if (rt0->ip6r0_segleft == 23) + return (-1); + +#ifdef COMPAT_RFC1883 /* XXX */ + if (flags == IPV6_RTHDR_STRICT) { + int c, b; + c = rt0->ip6r0_segleft / 8; + b = rt0->ip6r0_segleft % 8; + rt0->ip6r0_slmap[c] |= (1 << (7 - b)); + } +#else + if (flags != IPV6_RTHDR_LOOSE) + return (-1); +#endif + rt0->ip6r0_segleft++; + bcopy(addr, (caddr_t)rt0 + ((rt0->ip6r0_len + 1) << 3), + sizeof(struct in6_addr)); + rt0->ip6r0_len += sizeof(struct in6_addr) >> 3; + cmsg->cmsg_len = CMSG_LEN((rt0->ip6r0_len + 1) << 3); + break; + } + default: + return (-1); + } + + return (0); +} + +/* ARGSUSED */ +int +inet6_rthdr_lasthop(cmsg, flags) + struct cmsghdr *cmsg; + unsigned int flags; +{ + struct ip6_rthdr *rthdr; + + rthdr = (struct ip6_rthdr *)CMSG_DATA(cmsg); + + switch (rthdr->ip6r_type) { + case IPV6_RTHDR_TYPE_0: + { + struct ip6_rthdr0 *rt0 = (struct ip6_rthdr0 *)rthdr; +#ifdef COMPAT_RFC1883 /* XXX */ + if (flags != IPV6_RTHDR_LOOSE && flags != IPV6_RTHDR_STRICT) + return (-1); +#endif /* COMPAT_RFC1883 */ + if (rt0->ip6r0_segleft > 23) + return (-1); +#ifdef COMPAT_RFC1883 /* XXX */ + if (flags == IPV6_RTHDR_STRICT) { + int c, b; + c = rt0->ip6r0_segleft / 8; + b = rt0->ip6r0_segleft % 8; + rt0->ip6r0_slmap[c] |= (1 << (7 - b)); + } +#else + if (flags != IPV6_RTHDR_LOOSE) + return (-1); +#endif /* COMPAT_RFC1883 */ + break; + } + default: + return (-1); + } + + return (0); +} + +#if 0 +int +inet6_rthdr_reverse(in, out) + const struct cmsghdr *in; + struct cmsghdr *out; +{ + + return (-1); +} +#endif + +int +inet6_rthdr_segments(cmsg) + const struct cmsghdr *cmsg; +{ + struct ip6_rthdr *rthdr; + + rthdr = (struct ip6_rthdr *)CMSG_DATA(cmsg); + + switch (rthdr->ip6r_type) { + case IPV6_RTHDR_TYPE_0: + { + struct ip6_rthdr0 *rt0 = (struct ip6_rthdr0 *)rthdr; + + if (rt0->ip6r0_len % 2 || 46 < rt0->ip6r0_len) + return (-1); + + return (rt0->ip6r0_len * 8) / sizeof(struct in6_addr); + } + + default: + return (-1); + } +} + +struct in6_addr * +inet6_rthdr_getaddr(cmsg, idx) + struct cmsghdr *cmsg; + int idx; +{ + struct ip6_rthdr *rthdr; + + rthdr = (struct ip6_rthdr *)CMSG_DATA(cmsg); + + switch (rthdr->ip6r_type) { + case IPV6_RTHDR_TYPE_0: + { + struct ip6_rthdr0 *rt0 = (struct ip6_rthdr0 *)rthdr; + int naddr; + + if (rt0->ip6r0_len % 2 || 46 < rt0->ip6r0_len) + return NULL; + naddr = (rt0->ip6r0_len * 8) / sizeof(struct in6_addr); + if (idx <= 0 || naddr < idx) + return NULL; +#ifdef COMPAT_RFC2292 + return (((struct in6_addr *)(rt0 + 1)) + idx - 1); +#else + return (((struct in6_addr *)(rt0 + 1)) + idx); +#endif + } + + default: + return NULL; + } +} + +int +inet6_rthdr_getflags(cmsg, idx) + const struct cmsghdr *cmsg; + int idx; +{ + struct ip6_rthdr *rthdr; + + rthdr = (struct ip6_rthdr *)CMSG_DATA(cmsg); + + switch (rthdr->ip6r_type) { + case IPV6_RTHDR_TYPE_0: + { + struct ip6_rthdr0 *rt0 = (struct ip6_rthdr0 *)rthdr; + int naddr; + + if (rt0->ip6r0_len % 2 || 46 < rt0->ip6r0_len) + return (-1); + naddr = (rt0->ip6r0_len * 8) / sizeof(struct in6_addr); + if (idx < 0 || naddr < idx) + return (-1); +#ifdef COMPAT_RFC1883 /* XXX */ + if (rt0->ip6r0_slmap[idx / 8] & (0x80 >> (idx % 8))) + return IPV6_RTHDR_STRICT; + else + return IPV6_RTHDR_LOOSE; +#else + return IPV6_RTHDR_LOOSE; +#endif /* COMPAT_RFC1883 */ + } + + default: + return (-1); + } +} + +/* + * RFC3542 API + */ + +socklen_t +inet6_rth_space(int type, int segments) +{ + switch (type) { + case IPV6_RTHDR_TYPE_0: + return (((segments * 2) + 1) << 3); + default: + return (0); /* type not suppported */ + } +} + +void * +inet6_rth_init(void *bp, socklen_t bp_len, int type, int segments) +{ + struct ip6_rthdr *rth = (struct ip6_rthdr *)bp; + struct ip6_rthdr0 *rth0; + + switch (type) { + case IPV6_RTHDR_TYPE_0: + /* length validation */ + if (bp_len < inet6_rth_space(IPV6_RTHDR_TYPE_0, segments)) + return (NULL); + + memset(bp, 0, bp_len); + rth0 = (struct ip6_rthdr0 *)rth; + rth0->ip6r0_len = segments * 2; + rth0->ip6r0_type = IPV6_RTHDR_TYPE_0; + rth0->ip6r0_segleft = 0; + rth0->ip6r0_reserved = 0; + break; + default: + return (NULL); /* type not supported */ + } + + return (bp); +} + +int +inet6_rth_add(void *bp, const struct in6_addr *addr) +{ + struct ip6_rthdr *rth = (struct ip6_rthdr *)bp; + struct ip6_rthdr0 *rth0; + struct in6_addr *nextaddr; + + switch (rth->ip6r_type) { + case IPV6_RTHDR_TYPE_0: + rth0 = (struct ip6_rthdr0 *)rth; + nextaddr = (struct in6_addr *)(rth0 + 1) + rth0->ip6r0_segleft; + *nextaddr = *addr; + rth0->ip6r0_segleft++; + break; + default: + return (-1); /* type not supported */ + } + + return (0); +} + +int +inet6_rth_reverse(const void *in, void *out) +{ + struct ip6_rthdr *rth_in = (struct ip6_rthdr *)in; + struct ip6_rthdr0 *rth0_in, *rth0_out; + int i, segments; + + switch (rth_in->ip6r_type) { + case IPV6_RTHDR_TYPE_0: + rth0_in = (struct ip6_rthdr0 *)in; + rth0_out = (struct ip6_rthdr0 *)out; + + /* parameter validation XXX too paranoid? */ + if (rth0_in->ip6r0_len % 2) + return (-1); + segments = rth0_in->ip6r0_len / 2; + + /* we can't use memcpy here, since in and out may overlap */ + memmove((void *)rth0_out, (void *)rth0_in, + ((rth0_in->ip6r0_len) + 1) << 3); + rth0_out->ip6r0_segleft = segments; + + /* reverse the addresses */ + for (i = 0; i < segments / 2; i++) { + struct in6_addr addr_tmp, *addr1, *addr2; + + addr1 = (struct in6_addr *)(rth0_out + 1) + i; + addr2 = (struct in6_addr *)(rth0_out + 1) + + (segments - i - 1); + addr_tmp = *addr1; + *addr1 = *addr2; + *addr2 = addr_tmp; + } + + break; + default: + return (-1); /* type not supported */ + } + + return (0); +} + +int +inet6_rth_segments(const void *bp) +{ + struct ip6_rthdr *rh = (struct ip6_rthdr *)bp; + struct ip6_rthdr0 *rh0; + int addrs; + + switch (rh->ip6r_type) { + case IPV6_RTHDR_TYPE_0: + rh0 = (struct ip6_rthdr0 *)bp; + + /* + * Validation for a type-0 routing header. + * Is this too strict? + */ + if ((rh0->ip6r0_len % 2) != 0 || + (addrs = (rh0->ip6r0_len >> 1)) < rh0->ip6r0_segleft) + return (-1); + + return (addrs); + default: + return (-1); /* unknown type */ + } +} + +struct in6_addr * +inet6_rth_getaddr(const void *bp, int idx) +{ + struct ip6_rthdr *rh = (struct ip6_rthdr *)bp; + struct ip6_rthdr0 *rh0; + int addrs; + + switch (rh->ip6r_type) { + case IPV6_RTHDR_TYPE_0: + rh0 = (struct ip6_rthdr0 *)bp; + + /* + * Validation for a type-0 routing header. + * Is this too strict? + */ + if ((rh0->ip6r0_len % 2) != 0 || + (addrs = (rh0->ip6r0_len >> 1)) < rh0->ip6r0_segleft) + return (NULL); + + if (idx < 0 || addrs <= idx) + return (NULL); + + return (((struct in6_addr *)(rh0 + 1)) + idx); + default: + return (NULL); /* unknown type */ + break; + } +} diff --git a/lib/libc/net/send.c b/lib/libc/net/send.c new file mode 100644 index 0000000..aea0620 --- /dev/null +++ b/lib/libc/net/send.c @@ -0,0 +1,53 @@ +/* + * Copyright (c) 1988, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)send.c 8.2 (Berkeley) 2/21/94"; +#endif /* LIBC_SCCS and not lint */ +#include + +#include "namespace.h" +#include +#include + +#include +#include "un-namespace.h" + +ssize_t +send(s, msg, len, flags) + int s, flags; + size_t len; + const void *msg; +{ + return (_sendto(s, msg, len, flags, NULL, 0)); +} diff --git a/lib/libc/net/sockatmark.c b/lib/libc/net/sockatmark.c new file mode 100644 index 0000000..497ce7f --- /dev/null +++ b/lib/libc/net/sockatmark.c @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2002 William C. Fenner. 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 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. + * + * $FreeBSD: src/lib/libc/net/sockatmark.c,v 1.1 2002/12/13 22:22:55 fenner Exp $ + */ +#include + +int sockatmark(int s) +{ + int atmark; + + if (ioctl(s, SIOCATMARK, &atmark) == -1) + return -1; + return atmark; +} diff --git a/lib/libc/net/vars.c b/lib/libc/net/vars.c new file mode 100644 index 0000000..756bf4d --- /dev/null +++ b/lib/libc/net/vars.c @@ -0,0 +1,44 @@ +/* $KAME: vars.c,v 1.2 2001/08/20 02:32:41 itojun Exp $ */ + +/* + * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project. + * 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 project 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 PROJECT 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 PROJECT 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 + +#include +#include + +/* + * Definitions of some costant IPv6 addresses. + */ +const struct in6_addr in6addr_any = IN6ADDR_ANY_INIT; +const struct in6_addr in6addr_loopback = IN6ADDR_LOOPBACK_INIT; +const struct in6_addr in6addr_nodelocal_allnodes = IN6ADDR_NODELOCAL_ALLNODES_INIT; +const struct in6_addr in6addr_linklocal_allnodes = IN6ADDR_LINKLOCAL_ALLNODES_INIT; + diff --git a/lib/libc/nls/C.msg b/lib/libc/nls/C.msg new file mode 100644 index 0000000..4d8699e --- /dev/null +++ b/lib/libc/nls/C.msg @@ -0,0 +1,249 @@ +$ $FreeBSD: src/lib/libc/nls/C.msg,v 1.1 2005/02/27 17:59:39 phantom Exp $ +$ +$ Message catalog for C locale (template) +$ +$ strerror() support catalog +$ +$set 1 +$ EPERM +1 Operation not permitted +$ ENOENT +2 No such file or directory +$ ESRCH +3 No such process +$ EINTR +4 Interrupted system call +$ EIO +5 Input/output error +$ ENXIO +6 Device not configured +$ E2BIG +7 Argument list too long +$ ENOEXEC +8 Exec format error +$ EBADF +9 Bad file descriptor +$ ECHILD +10 No child processes +$ EDEADLK +11 Resource deadlock avoided +$ ENOMEM +12 Cannot allocate memory +$ EACCES +13 Permission denied +$ EFAULT +14 Bad address +$ ENOTBLK +15 Block device required +$ EBUSY +16 Device busy +$ EEXIST +17 File exists +$ EXDEV +18 Cross-device link +$ ENODEV +19 Operation not supported by device +$ ENOTDIR +20 Not a directory +$ EISDIR +21 Is a directory +$ EINVAL +22 Invalid argument +$ ENFILE +23 Too many open files in system +$ EMFILE +24 Too many open files +$ ENOTTY +25 Inappropriate ioctl for device +$ ETXTBSY +26 Text file busy +$ EFBIG +27 File too large +$ ENOSPC +28 No space left on device +$ ESPIPE +29 Illegal seek +$ EROFS +30 Read-only file system +$ EMLINK +31 Too many links +$ EPIPE +32 Broken pipe +$ EDOM +33 Numerical argument out of domain +$ ERANGE +34 Result too large +$ EAGAIN, EWOULDBLOCK +35 Resource temporarily unavailable +$ EINPROGRESS +36 Operation now in progress +$ EALREADY +37 Operation already in progress +$ ENOTSOCK +38 Socket operation on non-socket +$ EDESTADDRREQ +39 Destination address required +$ EMSGSIZE +40 Message too long +$ EPROTOTYPE +41 Protocol wrong type for socket +$ ENOPROTOOPT +42 Protocol not available +$ EPROTONOSUPPORT +43 Protocol not supported +$ ESOCKTNOSUPPORT +44 Socket type not supported +$ EOPNOTSUPP +45 Operation not supported +$ EPFNOSUPPORT +46 Protocol family not supported +$ EAFNOSUPPORT +47 Address family not supported by protocol family +$ EADDRINUSE +48 Address already in use +$ EADDRNOTAVAIL +49 Can't assign requested address +$ ENETDOWN +50 Network is down +$ ENETUNREACH +51 Network is unreachable +$ ENETRESET +52 Network dropped connection on reset +$ ECONNABORTED +53 Software caused connection abort +$ ECONNRESET +54 Connection reset by peer +$ ENOBUFS +55 No buffer space available +$ EISCONN +56 Socket is already connected +$ ENOTCONN +57 Socket is not connected +$ ESHUTDOWN +58 Can't send after socket shutdown +$ ETOOMANYREFS +59 Too many references: can't splice +$ ETIMEDOUT +60 Operation timed out +$ ECONNREFUSED +61 Connection refused +$ ELOOP +62 Too many levels of symbolic links +$ ENAMETOOLONG +63 File name too long +$ EHOSTDOWN +64 Host is down +$ EHOSTUNREACH +65 No route to host +$ ENOTEMPTY +66 Directory not empty +$ EPROCLIM +67 Too many processes +$ EUSERS +68 Too many users +$ EDQUOT +69 Disc quota exceeded +$ ESTALE +70 Stale NFS file handle +$ EREMOTE +71 Too many levels of remote in path +$ EBADRPC +72 RPC struct is bad +$ ERPCMISMATCH +73 RPC version wrong +$ EPROGUNAVAIL +74 RPC prog. not avail +$ EPROGMISMATCH +75 Program version wrong +$ EPROCUNAVAIL +76 Bad procedure for program +$ ENOLCK +77 No locks available +$ ENOSYS +78 Function not implemented +$ EFTYPE +79 Inappropriate file type or format +$ EAUTH +80 Authentication error +$ ENEEDAUTH +81 Need authenticator +$ EIDRM +82 Identifier removed +$ ENOMSG +83 No message of desired type +$ EOVERFLOW +84 Value too large to be stored in data type +$ ECANCELED +85 Operation canceled +$ EILSEQ +86 Illegal byte sequence +$ ENOATTR +87 Attribute not found +$ EDOOFUS +88 Programming error +$ +$ strsignal() support catalog +$ +$set 2 +$ SIGHUP +1 Hangup +$ SIGINT +2 Interrupt +$ SIGQUIT +3 Quit +$ SIGILL +4 Illegal instruction +$ SIGTRAP +5 Trace/BPT trap +$ SIGABRT +6 Abort trap +$ SIGEMT +7 EMT trap +$ SIGFPE +8 Floating point exception +$ SIGKILL +9 Killed +$ SIGBUS +10 Bus error +$ SIGSEGV +11 Segmentation fault +$ SIGSYS +12 Bad system call +$ SIGPIPE +13 Broken pipe +$ SIGALRM +14 Alarm clock +$ SIGTERM +15 Terminated +$ SIGURG +16 Urgent I/O condition +$ SIGSTOP +17 Suspended (signal) +$ SIGTSTP +18 Suspended +$ SIGCONT +19 Continued +$ SIGCHLD +20 Child exited +$ SIGTTIN +21 Stopped (tty input) +$ SIGTTOU +22 Stopped (tty output) +$ SIGIO +23 I/O possible +$ SIGXCPU +24 Cputime limit exceeded +$ SIGXFSZ +25 Filesize limit exceeded +$ SIGVTALRM +26 Virtual timer expired +$ SIGPROF +27 Profiling timer expired +$ SIGWINCH +28 Window size changes +$ SIGINFO +29 Information request +$ SIGUSR1 +30 User defined signal 1 +$ SIGUSR2 +31 User defined signal 2 diff --git a/lib/libc/nls/Makefile b/lib/libc/nls/Makefile new file mode 100644 index 0000000..62c1f63 --- /dev/null +++ b/lib/libc/nls/Makefile @@ -0,0 +1,35 @@ +# $Id: Makefile 89 2016-01-12 00:20:40Z reddawg $ +# The System Makefile (C) 2002 The UbixOS Project + +# Include Global 'Source' Options +include ../../../Makefile.incl +include ../../Makefile.incl +include ../Makefile.incl + +INCLUDES += -I../locale/ + +#Objects +OBJS = msgcat.o + +all: $(OBJS) + +# Compile the source files +.cc.o: + $(CXX) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -c -o $@ $< + +.cc.s: + $(CXX) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -S -o $@ $< + +.c.o: + $(CC) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -c $< + +.c.s: + $(CC) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -S -o $@ $< + +.S.o: + $(CC) $(CFLAGS) -Wall -nostdlib -c -o $@ $< + +# Clean up the junk +clean: + $(REMOVE) $(OBJS) + diff --git a/lib/libc/nls/ko_KR.UTF-8.msg b/lib/libc/nls/ko_KR.UTF-8.msg new file mode 100644 index 0000000..bb90eaf --- /dev/null +++ b/lib/libc/nls/ko_KR.UTF-8.msg @@ -0,0 +1,249 @@ +$ $FreeBSD: src/lib/libc/nls/ko_KR.UTF-8.msg,v 1.1.2.1 2006/09/11 18:22:57 jkim Exp $ +$ +$ Message catalog for ko_KR.UTF-8 locale +$ +$ strerror() support catalog +$ +$set 1 +$ EPERM +1 명령이 허용되지 않습니다 +$ ENOENT +2 파일 또는 디렉터리가 없습니다 +$ ESRCH +3 존재하지 않는 프로세스입니다 +$ EINTR +4 시스템 호출이 중단되었습니다 +$ EIO +5 입출력 에러입니다 +$ ENXIO +6 장치가 설정되지 않았습니다 +$ E2BIG +7 인자가 너무 깁니다 +$ ENOEXEC +8 실행 파일 형식이 잘못되었습니다 +$ EBADF +9 잘못된 파일 디스크립터입니다 +$ ECHILD +10 자식 프로세스가 없습니다 +$ EDEADLK +11 자원 데드락을 중단하였습니다 +$ ENOMEM +12 메모리를 할당할 수 없습니다 +$ EACCES +13 권한이 없습니다 +$ EFAULT +14 잘못된 주소가 지정되었습니다 +$ ENOTBLK +15 블럭 장치여야 합니다 +$ EBUSY +16 장치가 사용 중입니다 +$ EEXIST +17 파일이 이미 존재합니다 +$ EXDEV +18 다른 장치 간의 연결입니다 +$ ENODEV +19 그 장치가 지원하지 않는 명령입니다 +$ ENOTDIR +20 디렉터리가 아닙니다 +$ EISDIR +21 디렉터리입니다 +$ EINVAL +22 인자가 잘못되었습니다 +$ ENFILE +23 시스템에 파일이 너무 많이 열려있습니다 +$ EMFILE +24 파일이 너무 많이 열려있습니다 +$ ENOTTY +25 장치가 지원하지 않는 ioctl입니다 +$ ETXTBSY +26 Text 파일이 사용 중입니다 +$ EFBIG +27 파일이 너무 큽니다 +$ ENOSPC +28 장치에 여유 공간이 남아있지 않습니다 +$ ESPIPE +29 잘못된 탐색입니다 +$ EROFS +30 읽기 전용 파일 시스템입니다 +$ EMLINK +31 연결이 너무 많습니다 +$ EPIPE +32 파이프가 끊어졌습니다 +$ EDOM +33 수치 인자가 영역을 벗어났습니다 +$ ERANGE +34 결과가 너무 큽니다 +$ EAGAIN, EWOULDBLOCK +35 자원을 잠시 사용할 수 없습니다 +$ EINPROGRESS +36 작업이 진행 중입니다 +$ EALREADY +37 작업이 이미 진행 중입니다 +$ ENOTSOCK +38 소켓이 아닌 객체에 대한 소켓 작업입니다 +$ EDESTADDRREQ +39 목적지 주소가 필요합니다 +$ EMSGSIZE +40 메시지가 너무 깁니다 +$ EPROTOTYPE +41 소켓에 사용할 수 없는 프로토콜 유형입니다 +$ ENOPROTOOPT +42 프로토콜을 사용할 수 없습니다 +$ EPROTONOSUPPORT +43 지원하지 않는 프로토콜입니다 +$ ESOCKTNOSUPPORT +44 지원하지 않는 종류의 소켓입니다 +$ EOPNOTSUPP +45 지원되지 않는 명령입니다 +$ EPFNOSUPPORT +46 지원되지 않는 프로토콜군입니다 +$ EAFNOSUPPORT +47 프로토콜군에서 지원되지 않는 주소군입니다 +$ EADDRINUSE +48 이미 사용 중인 주소입니다 +$ EADDRNOTAVAIL +49 요청한 주소를 할당할 수 없습니다 +$ ENETDOWN +50 네트워크가 단절되었습니다 +$ ENETUNREACH +51 네트워크에 도달할 수 없습니다 +$ ENETRESET +52 네트워크가 재설정되어 접속이 끊어졌습니다 +$ ECONNABORTED +53 소프트웨어적인 이유로 연결이 끊어졌습니다 +$ ECONNRESET +54 상대방이 연결을 끊었습니다 +$ ENOBUFS +55 버퍼 공간이 모자랍니다 +$ EISCONN +56 소켓이 이미 연결되있습니다 +$ ENOTCONN +57 소켓이 연결되어 있지 않습니다 +$ ESHUTDOWN +58 소켓이 이미 중단되어, 더 이상 전송할 수 없습니다 +$ ETOOMANYREFS +59 참조수가 너무 많아 나눌 수 없습니다 +$ ETIMEDOUT +60 시간이 너무 많이 지나 작업이 중단되었습니다 +$ ECONNREFUSED +61 접속이 거부되었습니다 +$ ELOOP +62 심볼릭 연결이 너무 많이 거쳐서 연결되었습니다 +$ ENAMETOOLONG +63 파일 이름이 너무 깁니다 +$ EHOSTDOWN +64 호스트가 죽었습니다 +$ EHOSTUNREACH +65 호스트로 갈 경로가 없습니다 +$ ENOTEMPTY +66 디렉터리가 비어있지 않습니다 +$ EPROCLIM +67 프로세스가 너무 많습니다 +$ EUSERS +68 사용자가 너무 많습니다 +$ EDQUOT +69 디스크 할당량을 초과했습니다 +$ ESTALE +70 끊어진 NFS 연결입니다 +$ EREMOTE +71 너무 많은 경로로 원격에 접근하였습니다 +$ EBADRPC +72 RPC 구조체가 잘못되었습니다 +$ ERPCMISMATCH +73 RPC 버전이 맞지 않습니다 +$ EPROGUNAVAIL +74 RPC 프로그램이 없습니다 +$ EPROGMISMATCH +75 프로그램 버전이 맞지 않습니다 +$ EPROCUNAVAIL +76 프로그램에 원격 프로시저가 없습니다 +$ ENOLCK +77 잠금이 불가능합니다 +$ ENOSYS +78 구현되지 않은 기능입니다 +$ EFTYPE +79 잘못된 파일 종류이거나 형식이 잘못됐습니다 +$ EAUTH +80 인증이 실패했습니다 +$ ENEEDAUTH +81 인증 서버가 지정되지 않았습니다 +$ EIDRM +82 식별자가 제거되었습니다 +$ ENOMSG +83 요청된 형식의 메시지는 없습니다 +$ EOVERFLOW +84 데이터 형식에 저장하기에 너무 큰 값입니다 +$ ECANCELED +85 작업이 취소되었습니다 +$ EILSEQ +86 바이트 배열이 잘못되었습니다 +$ ENOATTR +87 속성을 찾을 수 없습니다 +$ EDOOFUS +88 프로그램상 오류입니다 +$ +$ strsignal() support catalog +$ +$set 2 +$ SIGHUP +1 끊김 +$ SIGINT +2 중단 +$ SIGQUIT +3 종료 +$ SIGILL +4 잘못된 명령 +$ SIGTRAP +5 Trace/BPT 트랩 +$ SIGABRT +6 Abort 트랩 +$ SIGEMT +7 EMT 트랩 +$ SIGFPE +8 부동소수점 연산 예외 +$ SIGKILL +9 강제종료 +$ SIGBUS +10 버스 오류 +$ SIGSEGV +11 세그먼테이션 오류 +$ SIGSYS +12 잘못된 시스템 호출 +$ SIGPIPE +13 파이프가 끊김 +$ SIGALRM +14 시간 경보 +$ SIGTERM +15 종료됨 +$ SIGURG +16 긴급 I/O 조건 +$ SIGSTOP +17 일시정지 (시그널) +$ SIGTSTP +18 일시정지 +$ SIGCONT +19 계속 +$ SIGCHLD +20 자식 프로세스 종료 +$ SIGTTIN +21 정지 (터미널 입력) +$ SIGTTOU +22 정지 (터미널 출력) +$ SIGIO +23 I/O possible +$ SIGXCPU +24 CPU 사용 시간 초과 +$ SIGXFSZ +25 파일 용량 제한 초과 +$ SIGVTALRM +26 가상 타이머 만료 +$ SIGPROF +27 프로파일링 타이머 만료 +$ SIGWINCH +28 창 크기 변경 +$ SIGINFO +29 정보 요청 +$ SIGUSR1 +30 사용자 정의 시그널 1 +$ SIGUSR2 +31 사용자 정의 시그널 2 diff --git a/lib/libc/nls/ko_KR.eucKR.msg b/lib/libc/nls/ko_KR.eucKR.msg new file mode 100644 index 0000000..4412e6a --- /dev/null +++ b/lib/libc/nls/ko_KR.eucKR.msg @@ -0,0 +1,249 @@ +$ $FreeBSD: src/lib/libc/nls/ko_KR.eucKR.msg,v 1.1.2.1 2006/09/11 18:22:57 jkim Exp $ +$ +$ Message catalog for ko_KR.eucKR locale +$ +$ strerror() support catalog +$ +$set 1 +$ EPERM +1 ����� ������ �ʽ��ϴ� +$ ENOENT +2 ���� �Ǵ� ���͸��� �����ϴ� +$ ESRCH +3 �������� �ʴ� ���μ����Դϴ� +$ EINTR +4 �ý��� ȣ���� �ߴܵǾ����ϴ� +$ EIO +5 ����� �����Դϴ� +$ ENXIO +6 ��ġ�� �������� �ʾҽ��ϴ� +$ E2BIG +7 ���ڰ� �ʹ� ��ϴ� +$ ENOEXEC +8 ���� ���� ������ �߸��Ǿ����ϴ� +$ EBADF +9 �߸��� ���� ��ũ�����Դϴ� +$ ECHILD +10 �ڽ� ���μ����� �����ϴ� +$ EDEADLK +11 �ڿ� ������� �ߴ��Ͽ����ϴ� +$ ENOMEM +12 �޸𸮸� �Ҵ��� �� �����ϴ� +$ EACCES +13 ������ �����ϴ� +$ EFAULT +14 �߸��� �ּҰ� �����Ǿ����ϴ� +$ ENOTBLK +15 �� ��ġ���� �մϴ� +$ EBUSY +16 ��ġ�� ��� ���Դϴ� +$ EEXIST +17 ������ �̹� �����մϴ� +$ EXDEV +18 �ٸ� ��ġ ���� �����Դϴ� +$ ENODEV +19 �� ��ġ�� �������� �ʴ� ����Դϴ� +$ ENOTDIR +20 ���͸��� �ƴմϴ� +$ EISDIR +21 ���͸��Դϴ� +$ EINVAL +22 ���ڰ� �߸��Ǿ����ϴ� +$ ENFILE +23 �ý��ۿ� ������ �ʹ� ���� �����ֽ��ϴ� +$ EMFILE +24 ������ �ʹ� ���� �����ֽ��ϴ� +$ ENOTTY +25 ��ġ�� �������� �ʴ� ioctl�Դϴ� +$ ETXTBSY +26 Text ������ ��� ���Դϴ� +$ EFBIG +27 ������ �ʹ� Ů�ϴ� +$ ENOSPC +28 ��ġ�� ���� ������ �������� �ʽ��ϴ� +$ ESPIPE +29 �߸��� Ž���Դϴ� +$ EROFS +30 �б� ���� ���� �ý����Դϴ� +$ EMLINK +31 ������ �ʹ� �����ϴ� +$ EPIPE +32 �������� ���������ϴ� +$ EDOM +33 ��ġ ���ڰ� ������ ������ϴ� +$ ERANGE +34 ����� �ʹ� Ů�ϴ� +$ EAGAIN, EWOULDBLOCK +35 �ڿ��� ��� ����� �� �����ϴ� +$ EINPROGRESS +36 �۾��� ���� ���Դϴ� +$ EALREADY +37 �۾��� �̹� ���� ���Դϴ� +$ ENOTSOCK +38 ������ �ƴ� ��ü�� ���� ���� �۾��Դϴ� +$ EDESTADDRREQ +39 ������ �ּҰ� �ʿ��մϴ� +$ EMSGSIZE +40 �޽����� �ʹ� ��ϴ� +$ EPROTOTYPE +41 ���Ͽ� ����� �� ���� �������� �����Դϴ� +$ ENOPROTOOPT +42 ���������� ����� �� �����ϴ� +$ EPROTONOSUPPORT +43 �������� �ʴ� ���������Դϴ� +$ ESOCKTNOSUPPORT +44 �������� �ʴ� ������ �����Դϴ� +$ EOPNOTSUPP +45 �������� �ʴ� ����Դϴ� +$ EPFNOSUPPORT +46 �������� �ʴ� �������ݱ��Դϴ� +$ EAFNOSUPPORT +47 �������ݱ����� �������� �ʴ� �ּұ��Դϴ� +$ EADDRINUSE +48 �̹� ��� ���� �ּ��Դϴ� +$ EADDRNOTAVAIL +49 ��û�� �ּҸ� �Ҵ��� �� �����ϴ� +$ ENETDOWN +50 ��Ʈ��ũ�� �����Ǿ����ϴ� +$ ENETUNREACH +51 ��Ʈ��ũ�� ������ �� �����ϴ� +$ ENETRESET +52 ��Ʈ��ũ�� �缳���Ǿ� ������ ���������ϴ� +$ ECONNABORTED +53 ����Ʈ�������� ������ ������ ���������ϴ� +$ ECONNRESET +54 ������ ������ �������ϴ� +$ ENOBUFS +55 ���� ������ ���ڶ��ϴ� +$ EISCONN +56 ������ �̹� ������ֽ��ϴ� +$ ENOTCONN +57 ������ ����Ǿ� ���� �ʽ��ϴ� +$ ESHUTDOWN +58 ������ �̹� �ߴܵǾ�, �� �̻� ������ �� �����ϴ� +$ ETOOMANYREFS +59 �������� �ʹ� ���� ���� �� �����ϴ� +$ ETIMEDOUT +60 �ð��� �ʹ� ���� ���� �۾��� �ߴܵǾ����ϴ� +$ ECONNREFUSED +61 ������ �źεǾ����ϴ� +$ ELOOP +62 �ɺ��� ������ �ʹ� ���� ���ļ� ����Ǿ����ϴ� +$ ENAMETOOLONG +63 ���� �̸��� �ʹ� ��ϴ� +$ EHOSTDOWN +64 ȣ��Ʈ�� �׾����ϴ� +$ EHOSTUNREACH +65 ȣ��Ʈ�� �� ��ΰ� �����ϴ� +$ ENOTEMPTY +66 ���͸��� ������� �ʽ��ϴ� +$ EPROCLIM +67 ���μ����� �ʹ� �����ϴ� +$ EUSERS +68 ����ڰ� �ʹ� �����ϴ� +$ EDQUOT +69 ��ũ �Ҵ緮�� �ʰ��߽��ϴ� +$ ESTALE +70 ������ NFS �����Դϴ� +$ EREMOTE +71 �ʹ� ���� ��η� ���ݿ� �����Ͽ����ϴ� +$ EBADRPC +72 RPC ����ü�� �߸��Ǿ����ϴ� +$ ERPCMISMATCH +73 RPC ������ ���� �ʽ��ϴ� +$ EPROGUNAVAIL +74 RPC ���α׷��� �����ϴ� +$ EPROGMISMATCH +75 ���α׷� ������ ���� �ʽ��ϴ� +$ EPROCUNAVAIL +76 ���α׷��� ���� ���ν����� �����ϴ� +$ ENOLCK +77 ����� �Ұ����մϴ� +$ ENOSYS +78 �������� ���� ����Դϴ� +$ EFTYPE +79 �߸��� ���� �����̰ų� ������ �߸��ƽ��ϴ� +$ EAUTH +80 ������ �����߽��ϴ� +$ ENEEDAUTH +81 ���� ������ �������� �ʾҽ��ϴ� +$ EIDRM +82 �ĺ��ڰ� ���ŵǾ����ϴ� +$ ENOMSG +83 ��û�� ������ �޽����� �����ϴ� +$ EOVERFLOW +84 ������ ���Ŀ� �����ϱ⿡ �ʹ� ū ���Դϴ� +$ ECANCELED +85 �۾��� ��ҵǾ����ϴ� +$ EILSEQ +86 ����Ʈ �迭�� �߸��Ǿ����ϴ� +$ ENOATTR +87 �Ӽ��� ã�� �� �����ϴ� +$ EDOOFUS +88 ���α׷��� �����Դϴ� +$ +$ strsignal() support catalog +$ +$set 2 +$ SIGHUP +1 ���� +$ SIGINT +2 �ߴ� +$ SIGQUIT +3 ���� +$ SIGILL +4 �߸��� ��� +$ SIGTRAP +5 Trace/BPT Ʈ�� +$ SIGABRT +6 Abort Ʈ�� +$ SIGEMT +7 EMT Ʈ�� +$ SIGFPE +8 �ε��Ҽ��� ���� ���� +$ SIGKILL +9 �������� +$ SIGBUS +10 ���� ���� +$ SIGSEGV +11 ���׸����̼� ���� +$ SIGSYS +12 �߸��� �ý��� ȣ�� +$ SIGPIPE +13 �������� ���� +$ SIGALRM +14 �ð� �溸 +$ SIGTERM +15 ����� +$ SIGURG +16 ��� I/O ���� +$ SIGSTOP +17 �Ͻ����� (�ñ׳�) +$ SIGTSTP +18 �Ͻ����� +$ SIGCONT +19 ��� +$ SIGCHLD +20 �ڽ� ���μ��� ���� +$ SIGTTIN +21 ���� (�͹̳� �Է�) +$ SIGTTOU +22 ���� (�͹̳� ���) +$ SIGIO +23 I/O possible +$ SIGXCPU +24 CPU ��� �ð� �ʰ� +$ SIGXFSZ +25 ���� �뷮 ���� �ʰ� +$ SIGVTALRM +26 ���� Ÿ�̸� ���� +$ SIGPROF +27 �������ϸ� Ÿ�̸� ���� +$ SIGWINCH +28 â ũ�� ���� +$ SIGINFO +29 ���� ��û +$ SIGUSR1 +30 ����� ���� �ñ׳� 1 +$ SIGUSR2 +31 ����� ���� �ñ׳� 2 diff --git a/lib/libc/nls/msgcat.c b/lib/libc/nls/msgcat.c new file mode 100644 index 0000000..c3c0dde --- /dev/null +++ b/lib/libc/nls/msgcat.c @@ -0,0 +1,307 @@ +/*********************************************************** +Copyright 1990, by Alfalfa Software Incorporated, Cambridge, Massachusetts. + + All Rights Reserved + +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, +provided that the above copyright notice appear in all copies and that +both that copyright notice and this permission notice appear in +supporting documentation, and that Alfalfa's name not be used in +advertising or publicity pertaining to distribution of the software +without specific, written prior permission. + +ALPHALPHA DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING +ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL +ALPHALPHA BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR +ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS +SOFTWARE. + +If you make any modifications, bugfixes or other changes to this software +we'd appreciate it if you could send a copy to us so we can keep things +up-to-date. Many thanks. + Kee Hinckley + Alfalfa Software, Inc. + 267 Allston St., #3 + Cambridge, MA 02139 USA + nazgul@alfalfa.com + +******************************************************************/ + +#include +__FBSDID("$FreeBSD: src/lib/libc/nls/msgcat.c,v 1.50 2005/02/27 16:26:49 phantom Exp $"); + +#define _NLS_PRIVATE + +#include "namespace.h" +#include +#include +#include + +#include /* for ntohl() */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "un-namespace.h" + +#include "../locale/setlocale.h" /* for ENCODING_LEN */ + +#define _DEFAULT_NLS_PATH "/usr/share/nls/%L/%N.cat:/usr/share/nls/%N/%L:/usr/local/share/nls/%L/%N.cat:/usr/local/share/nls/%N/%L" + +#define NLERR ((nl_catd) -1) +#define NLRETERR(errc) { errno = errc; return (NLERR); } + +static nl_catd load_msgcat(const char *); + +nl_catd +catopen(const char *name, int type) +{ + int spcleft, saverr; + char path[PATH_MAX]; + char *nlspath, *lang, *base, *cptr, *pathP, *tmpptr; + char *cptr1, *plang, *pter, *pcode; + struct stat sbuf; + + if (name == NULL || *name == '\0') + NLRETERR(EINVAL); + + /* is it absolute path ? if yes, load immediately */ + if (strchr(name, '/') != NULL) + return (load_msgcat(name)); + + if (type == NL_CAT_LOCALE) + lang = setlocale(LC_MESSAGES, NULL); + else + lang = getenv("LANG"); + + if (lang == NULL || *lang == '\0' || strlen(lang) > ENCODING_LEN || + (lang[0] == '.' && + (lang[1] == '\0' || (lang[1] == '.' && lang[2] == '\0'))) || + strchr(lang, '/') != NULL) + lang = "C"; + + if ((plang = cptr1 = strdup(lang)) == NULL) + return (NLERR); + if ((cptr = strchr(cptr1, '@')) != NULL) + *cptr = '\0'; + pter = pcode = ""; + if ((cptr = strchr(cptr1, '_')) != NULL) { + *cptr++ = '\0'; + pter = cptr1 = cptr; + } + if ((cptr = strchr(cptr1, '.')) != NULL) { + *cptr++ = '\0'; + pcode = cptr; + } + + if ((nlspath = getenv("NLSPATH")) == NULL || issetugid()) + nlspath = _DEFAULT_NLS_PATH; + + if ((base = cptr = strdup(nlspath)) == NULL) { + saverr = errno; + free(plang); + errno = saverr; + return (NLERR); + } + + while ((nlspath = strsep(&cptr, ":")) != NULL) { + pathP = path; + if (*nlspath) { + for (; *nlspath; ++nlspath) { + if (*nlspath == '%') { + switch (*(nlspath + 1)) { + case 'l': + tmpptr = plang; + break; + case 't': + tmpptr = pter; + break; + case 'c': + tmpptr = pcode; + break; + case 'L': + tmpptr = lang; + break; + case 'N': + tmpptr = (char *)name; + break; + case '%': + ++nlspath; + /* fallthrough */ + default: + if (pathP - path >= + sizeof(path) - 1) + goto too_long; + *(pathP++) = *nlspath; + continue; + } + ++nlspath; + put_tmpptr: + spcleft = sizeof(path) - + (pathP - path) - 1; + if (strlcpy(pathP, tmpptr, spcleft) >= + spcleft) { + too_long: + free(plang); + free(base); + NLRETERR(ENAMETOOLONG); + } + pathP += strlen(tmpptr); + } else { + if (pathP - path >= sizeof(path) - 1) + goto too_long; + *(pathP++) = *nlspath; + } + } + *pathP = '\0'; + if (stat(path, &sbuf) == 0) { + free(plang); + free(base); + return (load_msgcat(path)); + } + } else { + tmpptr = (char *)name; + --nlspath; + goto put_tmpptr; + } + } + free(plang); + free(base); + NLRETERR(ENOENT); +} + +char * +catgets(nl_catd catd, int set_id, int msg_id, const char *s) +{ + struct _nls_cat_hdr *cat_hdr; + struct _nls_set_hdr *set_hdr; + struct _nls_msg_hdr *msg_hdr; + int l, u, i, r; + + if (catd == NULL || catd == NLERR) { + errno = EBADF; + /* LINTED interface problem */ + return (char *) s; +} + + cat_hdr = (struct _nls_cat_hdr *)catd->__data; + set_hdr = (struct _nls_set_hdr *)(void *)((char *)catd->__data + + sizeof(struct _nls_cat_hdr)); + + /* binary search, see knuth algorithm b */ + l = 0; + u = ntohl((uint32_t)cat_hdr->__nsets) - 1; + while (l <= u) { + i = (l + u) / 2; + r = set_id - ntohl((uint32_t)set_hdr[i].__setno); + + if (r == 0) { + msg_hdr = (struct _nls_msg_hdr *) + (void *)((char *)catd->__data + + sizeof(struct _nls_cat_hdr) + + ntohl((uint32_t)cat_hdr->__msg_hdr_offset)); + + l = ntohl((uint32_t)set_hdr[i].__index); + u = l + ntohl((uint32_t)set_hdr[i].__nmsgs) - 1; + while (l <= u) { + i = (l + u) / 2; + r = msg_id - + ntohl((uint32_t)msg_hdr[i].__msgno); + if (r == 0) { + return ((char *) catd->__data + + sizeof(struct _nls_cat_hdr) + + ntohl((uint32_t) + cat_hdr->__msg_txt_offset) + + ntohl((uint32_t) + msg_hdr[i].__offset)); + } else if (r < 0) { + u = i - 1; + } else { + l = i + 1; + } +} + + /* not found */ + goto notfound; + + } else if (r < 0) { + u = i - 1; + } else { + l = i + 1; + } +} + +notfound: + /* not found */ + errno = ENOMSG; + /* LINTED interface problem */ + return (char *) s; +} + +int +catclose(nl_catd catd) +{ + if (catd == NULL || catd == NLERR) { + errno = EBADF; + return (-1); + } + + munmap(catd->__data, (size_t)catd->__size); + free(catd); + return (0); +} + +/* + * Internal support functions + */ + +static nl_catd +load_msgcat(const char *path) +{ + struct stat st; + nl_catd catd; + void *data; + int fd; + + /* XXX: path != NULL? */ + + if ((fd = _open(path, O_RDONLY)) == -1) + return (NLERR); + + if (_fstat(fd, &st) != 0) { + _close(fd); + return (NLERR); + } + + data = mmap(0, (size_t)st.st_size, PROT_READ, MAP_FILE|MAP_SHARED, fd, + (off_t)0); + _close(fd); + + if (data == MAP_FAILED) + return (NLERR); + + if (ntohl((uint32_t)((struct _nls_cat_hdr *)data)->__magic) != + _NLS_MAGIC) { + munmap(data, (size_t)st.st_size); + NLRETERR(EINVAL); + } + + if ((catd = malloc(sizeof (*catd))) == NULL) { + munmap(data, (size_t)st.st_size); + return (NLERR); + } + + catd->__data = data; + catd->__size = (int)st.st_size; + return (catd); +} + diff --git a/lib/libc/nls/pl_PL.ISO8859-2.msg b/lib/libc/nls/pl_PL.ISO8859-2.msg new file mode 100644 index 0000000..43e944f --- /dev/null +++ b/lib/libc/nls/pl_PL.ISO8859-2.msg @@ -0,0 +1,249 @@ +$ $FreeBSD: src/lib/libc/nls/pl_PL.ISO8859-2.msg,v 1.1 2005/03/01 14:38:30 pjd Exp $ +$ +$ Message catalog for pl_PL.ISO8859-2 locale +$ +$ strerror() support catalog +$ +$set 1 +$ EPERM +1 Operacja niedozwolona +$ ENOENT +2 Nie ma takiego pliku/katalogu +$ ESRCH +3 Nie ma takiego procesu +$ EINTR +4 Wywo�anie systemowe przerwane +$ EIO +5 B��d wej�cia/wyj�cia +$ ENXIO +6 Nieskonfigurowane urz�dzenie +$ E2BIG +7 Zbyt d�uga lista argument�w +$ ENOEXEC +8 B��dny format pliku wykonywalnego +$ EBADF +9 Z�y deskryptor pliku +$ ECHILD +10 Brak proces�w potomnych +$ EDEADLK +11 Unikni�to zakleszczenia zasob�w +$ ENOMEM +12 Brak pami�ci do przydzia�u +$ EACCES +13 Brak dost�pu +$ EFAULT +14 Z�y adres +$ ENOTBLK +15 Wymagane urz�dzenie blokowe +$ EBUSY +16 Urz�dzenie zaj�te +$ EEXIST +17 Plik istnieje +$ EXDEV +18 Dowi�zanie miedzy urz�dzeniami +$ ENODEV +19 Operacja nieobs�ugiwana przez urz�dzenie +$ ENOTDIR +20 To nie jest katalog +$ EISDIR +21 To jest katalog +$ EINVAL +22 B��dny argument +$ ENFILE +23 Zbyt wiele otwartych plik�w w systemie +$ EMFILE +24 Zbyt wiele otwartych plik�w +$ ENOTTY +25 Niew�a�ciwy dost�p do urz�dzenia +$ ETXTBSY +26 Plik wykonywalny jest zaj�ty +$ EFBIG +27 Zbyt du�y plik +$ ENOSPC +28 Brak miejsca na urz�dzeniu +$ ESPIPE +29 B��dne przesuni�cie +$ EROFS +30 System plik�w tylko do odczytu +$ EMLINK +31 Zbyt wiele dowi�za� +$ EPIPE +32 Potok przerwany +$ EDOM +33 Argument liczbowy z poza zakresu +$ ERANGE +34 Wynik z poza zakresu +$ EAGAIN, EWOULDBLOCK +35 Zasoby chwilowo niedost�pne +$ EINPROGRESS +36 Operacja jest w�a�nie wykonywana +$ EALREADY +37 Operacja jest ju� wykonywana +$ ENOTSOCK +38 Operacja na obiekcie, kt�ry nie jest gniazdem +$ EDESTADDRREQ +39 Wymagany adres przeznaczenia +$ EMSGSIZE +40 Wiadomo�� zbyt d�uga +$ EPROTOTYPE +41 Typ protoko�u nie pasuje do gniazda +$ ENOPROTOOPT +42 Protok� nie jest dost�pny +$ EPROTONOSUPPORT +43 Nieobs�ugiwany protok� +$ ESOCKTNOSUPPORT +44 Nieobs�ugiwany typ gniazda +$ EOPNOTSUPP +45 Nieobs�ugiwana operacja +$ EPFNOSUPPORT +46 Nieobs�ugiwana rodzina protoko��w +$ EAFNOSUPPORT +47 Rodzina adres�w nie jest obs�ugiwana przez rodzin� protoko��w +$ EADDRINUSE +48 Adres jest ju� w u�yciu +$ EADDRNOTAVAIL +49 Adres nie mo�e by� przydzielony +$ ENETDOWN +50 Sie� nie dzia�a +$ ENETUNREACH +51 Sie� jest niedost�pna +$ ENETRESET +52 Sie� przerwa�a po��czenie po resecie +$ ECONNABORTED +53 Oprogramowanie spowodowa�o przerwanie po��czenia +$ ECONNRESET +54 Po��czenie zerwane przez drug� stron� +$ ENOBUFS +55 Brak miejsca w buforze +$ EISCONN +56 Gniazdo jest ju� po��czone +$ ENOTCONN +57 Gniazdo nie jest po��czone +$ ESHUTDOWN +58 Nie mo�na wysy�a� po zamkni�ciu gniazda +$ ETOOMANYREFS +59 Za du�o powi�za�: dowi�zanie niemo�liwe +$ ETIMEDOUT +60 Limit czasu operacji przekroczony +$ ECONNREFUSED +61 Po��czenie odrzucone +$ ELOOP +62 Zbyt wiele wzajemnych dowi�za� symbolicznych +$ ENAMETOOLONG +63 Zbyt d�uga nazwa pliku +$ EHOSTDOWN +64 Host jest wy��czony +$ EHOSTUNREACH +65 Brak drogi do hosta +$ ENOTEMPTY +66 Katalog nie jest pusty +$ EPROCLIM +67 Zbyt wiele proces�w +$ EUSERS +68 Zbyt wielu u�ytkownik�w +$ EDQUOT +69 Przekroczono limit miejsca na dysku +$ ESTALE +70 Uchwyt pliku NFS jest nieaktualny +$ EREMOTE +71 Zbyt wiele poziom�w zagnie�d�enia w �cie�ce +$ EBADRPC +72 RPC b��dna struktura +$ ERPCMISMATCH +73 RPC niekompatybilna wersja +$ EPROGUNAVAIL +74 RPC program niedost�pny +$ EPROGMISMATCH +75 Nieobs�ugiwana wersja programu +$ EPROCUNAVAIL +76 Nieobs�ugiwana procedura +$ ENOLCK +77 Wyczerpany limit blokad +$ ENOSYS +78 Nieobs�ugiwana funkcja +$ EFTYPE +79 Niew�a�ciwy typ lub format pliku +$ EAUTH +80 B��d uwierzytelnienia +$ ENEEDAUTH +81 Wymagane uwierzytelnienie +$ EIDRM +82 Identyfikator zosta� usuni�ty +$ ENOMSG +83 Brak komunikatu po��danego typu +$ EOVERFLOW +84 Warto�� zbyt du�a dla zdefiniowanego typu danych +$ ECANCELED +85 Operacja anulowana +$ EILSEQ +86 B��dna sekwencja bajt�w +$ ENOATTR +87 Nie znaleziono atrybutu +$ EDOOFUS +88 Wewn�trzny b��d programu +$ +$ strsignal() support catalog +$ +$set 2 +$ SIGHUP +1 Roz��czenie +$ SIGINT +2 Przerwanie +$ SIGQUIT +3 Wyj�cie +$ SIGILL +4 Nieznana instrukcja +$ SIGTRAP +5 Pu�apka debuggera/BPT +$ SIGABRT +6 Przerwana pu�apka +$ SIGEMT +7 Pu�apka EMT +$ SIGFPE +8 B��d w obliczeniach zmiennoprzecinkowych +$ SIGKILL +9 Unicestwiony +$ SIGBUS +10 B��d szyny +$ SIGSEGV +11 Naruszenie ochrony pami�ci +$ SIGSYS +12 B��dne wywo�anie systemowe +$ SIGPIPE +13 Przerwany potok +$ SIGALRM +14 Budzik +$ SIGTERM +15 Zako�czony +$ SIGURG +16 Nag�y wypadek I/O +$ SIGSTOP +17 Zatrzymany (sygna�) +$ SIGTSTP +18 Zatrzymany +$ SIGCONT +19 Kontynuacja +$ SIGCHLD +20 Proces potomny zako�czy� prac� +$ SIGTTIN +21 Zatrzymany (wej�cie z tty) +$ SIGTTOU +22 Zatrzymany (wyj�cie z tty) +$ SIGIO +23 Wej/Wyj dozwolone +$ SIGXCPU +24 Przekroczony limit czasu procesora +$ SIGXFSZ +25 Przekroczony limit wielko�ci pliku +$ SIGVTALRM +26 Alarm stopera wirtualnego +$ SIGPROF +27 Alarm stopera profiluj�cego +$ SIGWINCH +28 Zmiana rozmiaru okna +$ SIGINFO +29 ��danie informacji +$ SIGUSR1 +30 Sygna� u�ytkownika 1 +$ SIGUSR2 +31 Sygna� u�ytkownika 2 diff --git a/lib/libc/nls/ru_RU.KOI8-R.msg b/lib/libc/nls/ru_RU.KOI8-R.msg new file mode 100644 index 0000000..8400fca --- /dev/null +++ b/lib/libc/nls/ru_RU.KOI8-R.msg @@ -0,0 +1,256 @@ +$ $FreeBSD: src/lib/libc/nls/ru_RU.KOI8-R.msg,v 1.1 2005/02/27 18:09:09 phantom Exp $ +$ +$ Message catalog for ru_RU.KOI8-R locale +$ +$ strerror() support catalog +$ +$set 1 +$ EPERM +1 �������� �� ��������� +$ ENOENT +2 ��� ������ ����� ��� �������� +$ ESRCH +3 ��� ������ �������� +$ EINTR +4 ���������� ��������� ����� +$ EIO +5 ������ �����/������ +$ ENXIO +6 ���������� �� ���������������� +$ E2BIG +7 ������� ������� ������ ���������� +$ ENOEXEC +8 ������ ������� ������������ ����� +$ EBADF +9 ������������ ���������� ����� +$ ECHILD +10 ��� ����������� ��������� +$ EDEADLK +11 ������������� �������� ���������� ��� ������� � ������� +$ ENOMEM +12 ���������� �������� ������ +$ EACCES +13 ������������ ���������� +$ EFAULT +14 ������������ ����� +$ ENOTBLK +15 ���������� ������� ������� ���������� +$ EBUSY +16 ���������� ������ +$ EEXIST +17 ���� ���������� +$ EXDEV +18 ������ �� ������ ���������� +$ ENODEV +19 �������� �� �������������� ����������� +$ ENOTDIR +20 ��������� ���� �� �������� ��������� +$ EISDIR +21 ��������� ���� �������� ��������� +$ EINVAL +22 ������������ �������� +$ ENFILE +23 ������� ����� �������� ������ � ������� +$ EMFILE +24 ������� ����� �������� ������ +$ ENOTTY +25 ����� ioctl �� �������������� ����������� +$ ETXTBSY +26 ��������� ���� ����� +$ EFBIG +27 ������� ������� ���� +$ ENOSPC +28 �� ���������� �� �������� ����� +$ ESPIPE +29 ������������ �������� +$ EROFS +30 �������� ������� ������ ��� ������ +$ EMLINK +31 ������� ����� ������ +$ EPIPE +$ XXX??? +32 ����� �������� +$ EDOM +33 ������������ �������� ��������� ��������� +$ ERANGE +34 ������� ������� ��������� +$ EAGAIN, EWOULDBLOCK +35 ������ �������� ���������� +$ EINPROGRESS +36 �������� � �������� ���������� +$ EALREADY +$ XXX??? +37 �������� ��� ����������� +$ ENOTSOCK +38 �������� � ������� ��������� �� � ������ +$ EDESTADDRREQ +39 ��������� ������� ����� +$ EMSGSIZE +40 ������� ������� ��������� +$ EPROTOTYPE +41 �������� ��� ��������� ��� ������ +$ ENOPROTOOPT +42 �������� ���������� +$ EPROTONOSUPPORT +43 �������� �� �������������� +$ ESOCKTNOSUPPORT +44 ���� ��� ������ �� �������������� +$ EOPNOTSUPP +45 �������� �� �������������� +$ EPFNOSUPPORT +46 ��������� ���������� �� �������������� +$ EAFNOSUPPORT +47 ��������� ������� �� �������������� ���������� ���������� +$ EADDRINUSE +48 ����� ��� ������������ +$ EADDRNOTAVAIL +49 �� ���� ��������� ��������� ����� +$ ENETDOWN +50 ���� �� �������� +$ ENETUNREACH +51 ���� ����������� +$ ENETRESET +52 ���� ������� ����������� ��� ������ +$ ECONNABORTED +53 ��������� ������� ��������� ����������� ����������� +$ ECONNRESET +54 ����������� �������� ��������������� ������� +$ ENOBUFS +55 �� �������� ����� ��� ����� +$ EISCONN +56 ����� ��� ��������� +$ ENOTCONN +57 ����� �� ��������� +$ ESHUTDOWN +58 �� ���� ������� ����� �������� ������ +$ ETOOMANYREFS +59 ������� ����� ������: �� ���� ��������� +$ ETIMEDOUT +60 �������� ��������� ����� ������� +$ ECONNREFUSED +61 ����������� ���������� +$ ELOOP +62 ������� ����� ������� ���������� ������ +$ ENAMETOOLONG +63 ������� ������� ��� ����� +$ EHOSTDOWN +64 ���� �� �������� +$ EHOSTUNREACH +65 ��� �������� � ����� +$ ENOTEMPTY +66 ������� �� ���� +$ EPROCLIM +67 ������� ����� ��������� +$ EUSERS +68 ������� ����� ������������� +$ EDQUOT +69 ����������� �������� ����� +$ ESTALE +70 ���������� ��������� ����� NFS +$ EREMOTE +71 ������� ����� ������������� ��������� � ���� +$ EBADRPC +72 ������������ ��������� RPC +$ ERPCMISMATCH +73 �������� ������ RPC +$ EPROGUNAVAIL +74 ��������� RPC ���������� +$ EPROGMISMATCH +75 �������� ������ ��������� +$ EPROCUNAVAIL +76 ������������ ��������� ��� ��������� +$ ENOLCK +77 ���������� ���������� +$ ENOSYS +78 ������� �� ����������� +$ EFTYPE +79 ������������ ��� ��� ������ ����� +$ EAUTH +80 ������ �������������� +$ ENEEDAUTH +81 ���������� ������������� +$ EIDRM +82 ������������� ������ +$ ENOMSG +83 ��� ��������� ���������� ���� +$ EOVERFLOW +84 ������� ������� �������� ��� �������� � ��������� ���� ������ +$ ECANCELED +85 �������� �������� +$ EILSEQ +86 ������������ ������������������ ������ +$ ENOATTR +87 �������� �� ������ +$ EDOOFUS +88 ������ ��������������� +$ +$ strsignal() support catalog +$ +$set 2 +$ SIGHUP +$ XXX: ����������? +1 ������ ����� +$ SIGINT +2 ���������� �� ������� +$ SIGQUIT +3 ����� +$ SIGILL +4 ������������ ���������� +$ SIGTRAP +5 ������� �����������/����� �������� +$ SIGABRT +$ XXX: ��������� ���������� +6 ������� ���������� ����������� +$ SIGEMT +7 ������� EMT +$ SIGFPE +$ XXX: ������ �������� � ��������� ������? +8 ������ ��� ������ � ������������ ������ +$ SIGKILL +$ XXX: ���� +9 ������������� ��������� +$ SIGBUS +$ XXX: ������ ��������� �� ���� +10 ������ ���� +$ SIGSEGV +11 ������ ����������� +$ SIGSYS +12 ������������ ��������� ����� +$ SIGPIPE +13 ����� �������� +$ SIGALRM +14 �������� ������ +$ SIGTERM +15 �������� +$ SIGURG +16 ��������� ������� ����-����� +$ SIGSTOP +17 ������������ (������) +$ SIGTSTP +18 ������������ +$ SIGCONT +19 ����������� ������ +$ SIGCHLD +20 ��������� ������ ������������ �������� +$ SIGTTIN +21 ���������� (���� � ���������) +$ SIGTTOU +22 ���������� (����� �� ��������) +$ SIGIO +23 ����-����� �������� +$ SIGXCPU +24 ��������� ����������� ������������� ������� +$ SIGXFSZ +25 �������� ������������ ������ ����� +$ SIGVTALRM +26 ����� ����������� ������ +$ SIGPROF +27 ����� ������ �������������� +$ SIGWINCH +28 ��������� ������� ���� +$ SIGINFO +29 ������ ���������� +$ SIGUSR1 +30 ���������������� ������ 1 +$ SIGUSR2 +31 ���������������� ������ 2 diff --git a/lib/libc/posix1e/Makefile b/lib/libc/posix1e/Makefile new file mode 100644 index 0000000..0b709d8 --- /dev/null +++ b/lib/libc/posix1e/Makefile @@ -0,0 +1,35 @@ +# $Id: Makefile 89 2016-01-12 00:20:40Z reddawg $ +# The System Makefile (C) 2002 The UbixOS Project + +# Include Global 'Source' Options +include ../../../Makefile.incl +include ../../Makefile.incl +include ../Makefile.incl + +INCLUDES += -I../locale/ + +#Objects +OBJS = acl_calc_mask.o acl_copy.o acl_delete.o acl_delete_entry.o acl_entry.o acl_free.o acl_from_text.o acl_get.o acl_init.o acl_perm.o acl_set.o acl_size.o acl_support.o acl_to_text.o acl_valid.o extattr.o mac.o mac_exec.o mac_get.o mac_set.o + +all: $(OBJS) + +# Compile the source files +.cc.o: + $(CXX) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -c -o $@ $< + +.cc.s: + $(CXX) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -S -o $@ $< + +.c.o: + $(CC) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -c $< + +.c.s: + $(CC) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -S -o $@ $< + +.S.o: + $(CC) $(CFLAGS) -Wall -nostdlib -c -o $@ $< + +# Clean up the junk +clean: + $(REMOVE) $(OBJS) + diff --git a/lib/libc/posix1e/Makefile.incl b/lib/libc/posix1e/Makefile.incl new file mode 100644 index 0000000..b09921e --- /dev/null +++ b/lib/libc/posix1e/Makefile.incl @@ -0,0 +1,124 @@ +Makefile.incl 209147 2010-06-14 02:26:13Z kientzle $ + +.PATH: ${.CURDIR}/posix1e + +CFLAGS+=-D_ACL_PRIVATE + +# Copy kern/subr_acl_nfs4.c to the libc object directory. +subr_acl_nfs4.c: ${.CURDIR}/../../sys/kern/subr_acl_nfs4.c + cat ${.ALLSRC} > ${.TARGET} + +SRCS+= acl_branding.c \ + acl_calc_mask.c \ + acl_copy.c \ + acl_compat.c \ + acl_delete.c \ + acl_delete_entry.c \ + acl_entry.c \ + acl_flag.c \ + acl_free.c \ + acl_from_text.c \ + acl_from_text_nfs4.c \ + acl_get.c \ + acl_id_to_name.c \ + acl_init.c \ + acl_perm.c \ + acl_set.c \ + acl_strip.c \ + acl_support.c \ + acl_support_nfs4.c \ + acl_to_text.c \ + acl_to_text_nfs4.c \ + acl_valid.c \ + extattr.c \ + mac.c \ + mac_exec.c \ + mac_get.c \ + mac_set.c \ + subr_acl_nfs4.c + +SYM_MAPS+=${.CURDIR}/posix1e/Symbol.map + +MAN+= acl.3 \ + acl_add_flag_np.3 \ + acl_add_perm.3 \ + acl_calc_mask.3 \ + acl_clear_flags_np.3 \ + acl_clear_perms.3 \ + acl_copy_entry.3 \ + acl_create_entry.3 \ + acl_delete.3 \ + acl_delete_entry.3 \ + acl_delete_flag_np.3 \ + acl_delete_perm.3 \ + acl_dup.3 \ + acl_free.3 \ + acl_from_text.3 \ + acl_get.3 \ + acl_get_brand_np.3 \ + acl_get_entry.3 \ + acl_get_entry_type_np.3 \ + acl_get_flagset_np.3 \ + acl_get_flag_np.3 \ + acl_get_permset.3 \ + acl_get_perm_np.3 \ + acl_get_qualifier.3 \ + acl_get_tag_type.3 \ + acl_init.3 \ + acl_is_trivial_np.3 \ + acl_set.3 \ + acl_set_entry_type_np.3 \ + acl_set_flagset_np.3 \ + acl_set_permset.3 \ + acl_set_qualifier.3 \ + acl_set_tag_type.3 \ + acl_strip_np.3 \ + acl_to_text.3 \ + acl_valid.3 \ + extattr.3 \ + mac.3 \ + mac.conf.5 \ + mac_free.3 \ + mac_is_present.3 \ + mac_get.3 \ + mac_prepare.3 \ + mac_set.3 \ + mac_text.3 \ + posix1e.3 + +MLINKS+=acl_create_entry.3 acl_create_entry_np.3\ + acl_delete.3 acl_delete_def_file.3 \ + acl_delete.3 acl_delete_file_np.3 \ + acl_delete.3 acl_delete_fd_np.3 \ + acl_delete_entry.3 acl_delete_entry_np.3\ + acl_get.3 acl_get_file.3 \ + acl_get.3 acl_get_fd.3 \ + acl_get.3 acl_get_fd_np.3 \ + acl_get.3 acl_get_link_np.3 \ + acl_set.3 acl_set_file.3 \ + acl_set.3 acl_set_fd.3 \ + acl_set.3 acl_set_fd_np.3 \ + acl_set.3 acl_set_link_np.3 \ + acl_to_text.3 acl_to_text_np.3 \ + acl_valid.3 acl_valid_file_np.3 \ + acl_valid.3 acl_valid_fd_np.3 \ + extattr.3 extattr_namespace_to_string.3 \ + extattr.3 extattr_string_to_namespace.3 \ + mac_get.3 mac_get_fd.3 \ + mac_get.3 mac_get_file.3 \ + mac_get.3 mac_get_link.3 \ + mac_get.3 mac_get_peer.3 \ + mac_get.3 mac_get_pid.3 \ + mac_get.3 mac_get_proc.3 \ + mac_prepare.3 mac_prepare_file_label.3 \ + mac_prepare.3 mac_prepare_ifnet_label.3 \ + mac_prepare.3 mac_prepare_process_label.3 \ + mac_prepare.3 mac_prepare_type.3 \ + mac_set.3 mac_set_fd.3 \ + mac_set.3 mac_set_file.3 \ + mac_set.3 mac_set_link.3 \ + mac_set.3 mac_set_proc.3 \ + mac_text.3 mac_from_text.3 \ + mac_text.3 mac_to_text.3 + +CLEANFILES+= subr_acl_nfs4.c diff --git a/lib/libc/posix1e/Symbol.map b/lib/libc/posix1e/Symbol.map new file mode 100644 index 0000000..854e350 --- /dev/null +++ b/lib/libc/posix1e/Symbol.map @@ -0,0 +1,86 @@ +/* + * $FreeBSD: releng/10.2/lib/libc/posix1e/Symbol.map 194955 2009-06-25 12:46:59Z trasz $ + */ + +FBSD_1.0 { + acl_calc_mask; + acl_copy_entry; + acl_copy_ext; + acl_copy_int; + acl_delete_def_file; + acl_delete_def_link_np; + acl_delete_file_np; + acl_delete_link_np; + acl_delete_fd_np; + acl_delete_entry; + acl_create_entry; + acl_get_entry; + acl_free; + acl_from_text; + acl_get_file; + acl_get_link_np; + acl_get_fd; + acl_get_fd_np; + acl_get_permset; + acl_get_qualifier; + acl_get_tag_type; + acl_init; + acl_dup; + acl_clear_perms; + acl_set_file; + acl_set_link_np; + acl_set_fd; + acl_set_fd_np; + acl_set_permset; + acl_set_qualifier; + acl_set_tag_type; + acl_to_text; + acl_valid; + acl_valid_file_np; + acl_valid_link_np; + acl_valid_fd_np; + extattr_namespace_to_string; + extattr_string_to_namespace; + mac_reload; + mac_free; + mac_from_text; + mac_to_text; + mac_prepare; + mac_prepare_type; + mac_prepare_ifnet_label; + mac_prepare_file_label; + mac_prepare_packet_label; + mac_prepare_process_label; + mac_is_present; + mac_execve; + mac_get_fd; + mac_get_file; + mac_get_link; + mac_get_peer; + mac_get_pid; + mac_get_proc; + mac_set_fd; + mac_set_file; + mac_set_link; + mac_set_proc; +}; + +FBSD_1.1 { + acl_add_flag_np; + acl_add_perm; + acl_clear_flags_np; + acl_create_entry_np; + acl_delete_entry_np; + acl_delete_flag_np; + acl_delete_perm; + acl_get_brand_np; + acl_get_entry_type_np; + acl_get_flag_np; + acl_get_flagset_np; + acl_get_perm_np; + acl_is_trivial_np; + acl_set_entry_type_np; + acl_set_flagset_np; + acl_strip_np; + acl_to_text_np; +}; diff --git a/lib/libc/posix1e/acl.3 b/lib/libc/posix1e/acl.3 new file mode 100644 index 0000000..4490d10 --- /dev/null +++ b/lib/libc/posix1e/acl.3 @@ -0,0 +1,307 @@ +.\"- +.\" Copyright (c) 2000, 2001, 2002 Robert N. M. Watson +.\" All rights reserved. +.\" +.\" This software was developed by Robert Watson for the TrustedBSD Project. +.\" +.\" 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 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 AUTHOR 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. +.\" +.\" $FreeBSD: releng/10.2/lib/libc/posix1e/acl.3 275254 2014-11-29 15:51:48Z trasz $ +.\" +.Dd October 30, 2014 +.Dt ACL 3 +.Os +.Sh NAME +.Nm acl +.Nd introduction to the POSIX.1e/NFSv4 ACL security API +.Sh LIBRARY +.Lb libc +.Sh SYNOPSIS +.In sys/types.h +.In sys/acl.h +.Sh DESCRIPTION +.Fx +permits file systems to export Access Control Lists via the VFS, and +provides a library for userland access to and manipulation of these ACLs. +.Fx +supports POSIX.1e and NFSv4 ACLs, but +not all file systems provide support for ACLs, and some may require that +ACL support be explicitly enabled by the administrator. +The library calls include routines to allocate, duplicate, retrieve, set, +and validate ACLs associated with file objects. +As well as the POSIX.1e routines, there are a number of non-portable +extensions defined that allow for ACL semantics alternative to +POSIX.1e, such as NFSv4. +Where routines are non-standard, they are suffixed with _np to indicate that +they are not portable. +.Pp +POSIX.1e describes a set of ACL manipulation routines to manage the +contents of ACLs, as well as their relationships with files; almost +all of these support routines are implemented in +.Fx . +.Pp +Available functions, sorted by behavior, include: +.Bl -tag -width indent +.It Fn acl_add_flag_np +This function is described in +.Xr acl_add_flag_np 3 , +and may be used to add flags to a flagset. +.It Fn acl_add_perm +This function is described in +.Xr acl_add_perm 3 , +and may be used to add permissions to a permission set. +.It Fn acl_calc_mask +This function is described in +.Xr acl_calc_mask 3 , +and may be used to calculate and set the permissions associated with +the +.Dv ACL_MASK +entry. +.It Fn acl_clear_flags_np +This function is described in +.Xr acl_clear_flags_np 3 , +and may be used to clear all flags from a flagset. +.It Fn acl_clear_perms +This function is described in +.Xr acl_clear_perms 3 , +and may be used to clear all permissions from a permission set. +.It Fn acl_copy_entry +This function is described in +.Xr acl_copy_entry 3 , +and may be used to copy the contents of an ACL entry. +.It Xo +.Fn acl_create_entry , +.Fn acl_create_entry_np +.Xc +These functions are described in +.Xr acl_create_entry 3 , +and may be used to create an empty entry in an ACL. +.It Xo +.Fn acl_delete_def_file , +.Fn acl_delete_def_link_np , +.Fn acl_delete_fd_np , +.Fn acl_delete_file_np , +.Fn acl_delete_link_np +.Xc +These functions are described in +.Xr acl_delete 3 , +and may be used to delete ACLs from file system objects. +.It Xo +.Fn acl_delete_entry , +.Fn acl_delete_entry_np , +.Xc +This functions are described in +.Xr acl_delete_entry 3 , +and may be used to delete an entry from an ACL. +.It Fn acl_delete_flag_np +This function is described in +.Xr acl_delete_flag_np 3 , +and may be used to delete flags from a flagset. +.It Fn acl_delete_perm +This function is described in +.Xr acl_delete_perm 3 , +and may be used to delete permissions from a permset. +.It Fn acl_dup +This function is described in +.Xr acl_dup 3 , +and may be used to duplicate an ACL structure. +.It Fn acl_free +This function is described in +.Xr acl_free 3 , +and may be used to free userland working ACL storage. +.It Fn acl_from_text +This function is described in +.Xr acl_from_text 3 , +and may be used to convert a text-form ACL into working ACL state, if +the ACL has POSIX.1e or NFSv4 semantics. +.It Fn acl_get_brand_np +This function is described in +.Xr acl_get_brand_np 3 +and may be used to determine whether the ACL has POSIX.1e or NFSv4 semantics. +.It Fn acl_get_entry +This function is described in +.Xr acl_get_entry 3 , +and may be used to retrieve a designated ACL entry from an ACL. +.It Xo +.Fn acl_get_fd , +.Fn acl_get_fd_np , +.Fn acl_get_file , +.Fn acl_get_link_np +.Xc +These functions are described in +.Xr acl_get 3 , +and may be used to retrieve ACLs from file system objects. +.It Fn acl_get_entry_type_np +This function is described in +.Xr acl_get_entry_type_np 3 , +and may be used to retrieve an ACL type from an ACL entry. +.It Fn acl_get_flagset_np +This function is described in +.Xr acl_get_flagset_np 3 , +and may be used to retrieve a flagset from an ACL entry. +.It Fn acl_get_permset +This function is described in +.Xr acl_get_permset 3 , +and may be used to retrieve a permset from an ACL entry. +.It Fn acl_get_qualifier +This function is described in +.Xr acl_get_qualifier 3 , +and may be used to retrieve the qualifier from an ACL entry. +.It Fn acl_get_tag_type +This function is described in +.Xr acl_get_tag_type 3 , +and may be used to retrieve the tag type from an ACL entry. +.It Fn acl_init +This function is described in +.Xr acl_init 3 , +and may be used to allocate a fresh (empty) ACL structure. +.It Fn acl_is_trivial_np +This function is described in +.Xr acl_is_trivial_np 3 , +and may be used to find out whether ACL is trivial. +.It Xo +.Fn acl_set_fd , +.Fn acl_set_fd_np , +.Fn acl_set_file , +.Fn acl_set_link_np +.Xc +These functions are described in +.Xr acl_set 3 , +and may be used to assign an ACL to a file system object. +.It Fn acl_set_entry_type_np +This function is described in +.Xr acl_set_entry_type_np 3 , +and may be used to set the ACL type of an ACL entry. +.It Fn acl_set_flagset_np +This function is described in +.Xr acl_set_flagset_np 3 , +and may be used to set the flags of an ACL entry from a flagset. +.It Fn acl_set_permset +This function is described in +.Xr acl_set_permset 3 , +and may be used to set the permissions of an ACL entry from a permset. +.It Fn acl_set_qualifier +This function is described in +.Xr acl_set_qualifier 3 , +and may be used to set the qualifier of an ACL. +.It Fn acl_set_tag_type +This function is described in +.Xr acl_set_tag_type 3 , +and may be used to set the tag type of an ACL. +.It Fn acl_strip_np +This function is described in +.Xr acl-strip_np 3 , +and may be used to remove extended entries from an ACL. +.It Xo +.Fn acl_to_text , +.Fn acl_to_text_np +.Xc +These functions are described in +.Xr acl_to_text 3 , +and may be used to generate a text-form of a POSIX.1e or NFSv4 semantics ACL. +.It Xo +.Fn acl_valid , +.Fn acl_valid_fd_np , +.Fn acl_valid_file_np , +.Fn acl_valid_link_np +.Xc +These functions are described in +.Xr acl_valid 3 , +and may be used to validate an ACL as correct POSIX.1e-semantics, or +as appropriate for a particular file system object regardless of semantics. +.El +.Pp +Documentation of the internal kernel interfaces backing these calls may +be found in +.Xr acl 9 . +The syscalls between the internal interfaces and the public library +routines may change over time, and as such are not documented. +They are not intended to be called directly without going through the +library. +.Sh SEE ALSO +.Xr getfacl 1 , +.Xr setfacl 1 , +.Xr acl_add_flag_np 3 , +.Xr acl_add_perm 3 , +.Xr acl_calc_mask 3 , +.Xr acl_clear_flags_np 3 , +.Xr acl_clear_perms 3 , +.Xr acl_copy_entry 3 , +.Xr acl_create_entry 3 , +.Xr acl_delete_entry 3 , +.Xr acl_delete_flag_np 3 , +.Xr acl_delete_perm 3 , +.Xr acl_dup 3 , +.Xr acl_free 3 , +.Xr acl_from_text 3 , +.Xr acl_get 3 , +.Xr acl_get_brand_np 3 , +.Xr acl_get_entry_type_np 3 , +.Xr acl_get_flagset_np 3 , +.Xr acl_get_permset 3 , +.Xr acl_get_qualifier 3 , +.Xr acl_get_tag_type 3 , +.Xr acl_init 3 , +.Xr acl_is_trivial_np 3 , +.Xr acl_set 3 , +.Xr acl_set_entry_type_np 3 , +.Xr acl_set_flagset_np 3 , +.Xr acl_set_permset 3 , +.Xr acl_set_qualifier 3 , +.Xr acl_set_tag_type 3 , +.Xr acl_strip_np 3 , +.Xr acl_to_text 3 , +.Xr acl_valid 3 , +.Xr posix1e 3 , +.Xr acl 9 +.Sh STANDARDS +POSIX.1e assigns security labels to all objects, extending the security +functionality described in POSIX.1. +These additional labels provide fine-grained discretionary access control, +fine-grained capabilities, and labels necessary for mandatory access +control. +POSIX.2c describes a set of userland utilities for manipulating these +labels. +.Pp +POSIX.1e is described in IEEE POSIX.1e draft 17. +Discussion of the draft continues on the cross-platform POSIX.1e +implementation mailing list. +To join this list, see the +.Fx +POSIX.1e implementation page for more information. +.Sh HISTORY +POSIX.1e support was introduced in +.Fx 4.0 ; +.Fx 5.0 +was the first version to include a complete ACL implementation based +on extended attributes for the UFS and UFS2 file systems. +NFSv4 ACL support was introduced in +.Fx 8.0 . +.Pp +The +.Xr getfacl 1 +and +.Xr setfacl 1 +utilities describe the user tools that permit direct manipulation of complete +file ACLs. +.Sh AUTHORS +.An Robert N M Watson diff --git a/lib/libc/posix1e/acl_add_flag_np.3 b/lib/libc/posix1e/acl_add_flag_np.3 new file mode 100644 index 0000000..5c6d85b --- /dev/null +++ b/lib/libc/posix1e/acl_add_flag_np.3 @@ -0,0 +1,97 @@ +.\"- +.\" Copyright (c) 2008, 2009 Edward Tomasz Napierala +.\" 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 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 AUTHOR 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. +.\" +.\" $FreeBSD: releng/10.2/lib/libc/posix1e/acl_add_flag_np.3 275253 2014-11-29 15:50:13Z trasz $ +.\" +.Dd October 30, 2014 +.Dt ACL_ADD_FLAG_NP 3 +.Os +.Sh NAME +.Nm acl_add_flag_np +.Nd add flags to a flagset +.Sh LIBRARY +.Lb libc +.Sh SYNOPSIS +.In sys/types.h +.In sys/acl.h +.Ft int +.Fn acl_add_flag_np "acl_flagset_t flagset_d" "acl_flag_t flag" +.Sh DESCRIPTION +The +.Fn acl_add_flag_np +function +is a non-portable call that adds the NFSv4 ACL flags contained in +.Fa flags +to the flagset +.Fa flagset_d . +.Pp +Note: it is not considered an error to attempt to add flags +that already exist in the flagset. +.Pp +Valid values are: +.Bl -column -offset 3n "ACL_ENTRY_NO_PROPAGATE_INHERIT" +.It ACL_ENTRY_FILE_INHERIT Ta "Will be inherited by files." +.It ACL_ENTRY_DIRECTORY_INHERIT Ta "Will be inherited by directories." +.It ACL_ENTRY_NO_PROPAGATE_INHERIT Ta "Will not propagate." +.It ACL_ENTRY_INHERIT_ONLY Ta "Inherit-only." +.El +.Sh RETURN VALUES +.Rv -std acl_add_flag_np +.Sh ERRORS +The +.Fn acl_add_flag_np +function fails if: +.Bl -tag -width Er +.It Bq Er EINVAL +Argument +.Fa flagset_d +is not a valid descriptor for a flagset within an ACL entry. +Argument +.Fa flag +does not contain a valid +.Vt acl_flag_t +value. +.El +.Sh SEE ALSO +.Xr acl 3 , +.Xr acl_clear_flags_np 3 , +.Xr acl_delete_flag_np 3 , +.Xr acl_get_flagset_np 3 , +.Xr acl_set_flagset_np 3 , +.Xr posix1e 3 +.Sh STANDARDS +POSIX.1e is described in IEEE POSIX.1e draft 17. +.Sh HISTORY +POSIX.1e support was introduced in +.Fx 4.0 . +The +.Fn acl_add_flag_np +function was added in +.Fx 8.0 . +.Sh AUTHORS +The +.Fn acl_add_flag_np +function was written by +.An Edward Tomasz Napierala Aq trasz@FreeBSD.org . diff --git a/lib/libc/posix1e/acl_add_perm.3 b/lib/libc/posix1e/acl_add_perm.3 new file mode 100644 index 0000000..905c9e7 --- /dev/null +++ b/lib/libc/posix1e/acl_add_perm.3 @@ -0,0 +1,129 @@ +.\"- +.\" Copyright (c) 2001 Chris D. Faulhaber +.\" 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 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 AUTHOR 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. +.\" +.\" $FreeBSD: releng/10.2/lib/libc/posix1e/acl_add_perm.3 233665 2012-03-29 16:02:40Z joel $ +.\" +.Dd June 25, 2009 +.Dt ACL_ADD_PERM 3 +.Os +.Sh NAME +.Nm acl_add_perm +.Nd add permissions to a permission set +.Sh LIBRARY +.Lb libc +.Sh SYNOPSIS +.In sys/types.h +.In sys/acl.h +.Ft int +.Fn acl_add_perm "acl_permset_t permset_d" "acl_perm_t perm" +.Sh DESCRIPTION +The +.Fn acl_add_perm +function +is a POSIX.1e call that adds the permission contained in +.Fa perm +to the permission set +.Fa permset_d . +.Pp +Note: it is not considered an error to attempt to add permissions +that already exist in the permission set. +.Pp +For POSIX.1e ACLs, valid values are: +.Bl -column -offset 3n "ACL_WRITE_NAMED_ATTRS" +.It ACL_EXECUTE Execute permission +.It ACL_WRITE Write permission +.It ACL_READ Read permission +.El +.Pp +For NFSv4 ACLs, valid values are: +.Bl -column -offset 3n "ACL_WRITE_NAMED_ATTRS" +.It ACL_READ_DATA Ta "Read permission" +.It ACL_LIST_DIRECTORY Ta "Same as ACL_READ_DATA" +.It ACL_WRITE_DATA Ta "Write permission, or permission to create files" +.It ACL_ADD_FILE Ta "Same as ACL_READ_DATA" +.It ACL_APPEND_DATA Ta "Permission to create directories. Ignored for files" +.It ACL_ADD_SUBDIRECTORY Ta "Same as ACL_APPEND_DATA" +.It ACL_READ_NAMED_ATTRS Ta "Ignored" +.It ACL_WRITE_NAMED_ATTRS Ta "Ignored" +.It ACL_EXECUTE Ta "Execute permission" +.It ACL_DELETE_CHILD Ta "Permission to delete files and subdirectories" +.It ACL_READ_ATTRIBUTES Ta "Permission to read basic attributes" +.It ACL_WRITE_ATTRIBUTES Ta "Permission to change basic attributes" +.It ACL_DELETE Ta "Permission to delete the object this ACL is placed on" +.It ACL_READ_ACL Ta "Permission to read ACL" +.It ACL_WRITE_ACL Ta "Permission to change the ACL and file mode" +.It ACL_SYNCHRONIZE Ta "Ignored" +.El +.Pp +Calling +.Fn acl_add_perm +with +.Fa perm +equal to ACL_WRITE or ACL_READ brands the ACL as POSIX. +Calling it with ACL_READ_DATA, ACL_LIST_DIRECTORY, ACL_WRITE_DATA, +ACL_ADD_FILE, ACL_APPEND_DATA, ACL_ADD_SUBDIRECTORY, ACL_READ_NAMED_ATTRS, +ACL_WRITE_NAMED_ATTRS, ACL_DELETE_CHILD, ACL_READ_ATTRIBUTES, +ACL_WRITE_ATTRIBUTES, ACL_DELETE, ACL_READ_ACL, ACL_WRITE_ACL +or ACL_SYNCHRONIZE brands the ACL as NFSv4. +.Sh RETURN VALUES +.Rv -std acl_add_perm +.Sh ERRORS +The +.Fn acl_add_perm +function fails if: +.Bl -tag -width Er +.It Bq Er EINVAL +Argument +.Fa permset_d +is not a valid descriptor for a permission set within an ACL entry. +Argument +.Fa perm +does not contain a valid +.Vt acl_perm_t +value. +ACL is already branded differently. +.El +.Sh SEE ALSO +.Xr acl 3 , +.Xr acl_clear_perms 3 , +.Xr acl_delete_perm 3 , +.Xr acl_get_brand_np 3 , +.Xr acl_get_permset 3 , +.Xr acl_set_permset 3 , +.Xr posix1e 3 +.Sh STANDARDS +POSIX.1e is described in IEEE POSIX.1e draft 17. +.Sh HISTORY +POSIX.1e support was introduced in +.Fx 4.0 . +The +.Fn acl_add_perm +function was added in +.Fx 5.0 . +.Sh AUTHORS +The +.Fn acl_add_perm +function was written by +.An Chris D. Faulhaber Aq jedgar@fxp.org . diff --git a/lib/libc/posix1e/acl_branding.c b/lib/libc/posix1e/acl_branding.c new file mode 100644 index 0000000..f44a55d --- /dev/null +++ b/lib/libc/posix1e/acl_branding.c @@ -0,0 +1,169 @@ +/*- + * Copyright (c) 2008, 2009 Edward Tomasz Napierała + * 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 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 AUTHOR 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 +__FBSDID("$FreeBSD: releng/10.2/lib/libc/posix1e/acl_branding.c 208034 2010-05-13 16:44:27Z trasz $"); + +#include +#include +#include + +#include "acl_support.h" + +/* + * An ugly detail of the implementation - fortunately not visible + * to the API users - is the "branding": libc needs to keep track + * of what "brand" ACL is: NFSv4, POSIX.1e or unknown. It happens + * automatically - for example, during acl_get_file(3) ACL gets + * branded according to the "type" argument; during acl_set_permset + * ACL, if its brand is unknown it gets branded as NFSv4 if any of the + * NFSv4 permissions that are not valid for POSIX.1e ACL are set etc. + * Branding information is used for printing out the ACL (acl_to_text(3)), + * veryfying acl_set_whatever arguments (checking against setting + * bits that are valid only for NFSv4 in ACL branded as POSIX.1e) etc. + */ + +static acl_t +entry2acl(acl_entry_t entry) +{ + acl_t aclp; + + aclp = (acl_t)(((long)entry >> _ACL_T_ALIGNMENT_BITS) << _ACL_T_ALIGNMENT_BITS); + + return (aclp); +} + +/* + * Return brand of an ACL. + */ +int +_acl_brand(const acl_t acl) +{ + + return (acl->ats_brand); +} + +int +_entry_brand(const acl_entry_t entry) +{ + + return (_acl_brand(entry2acl(entry))); +} + +/* + * Return 1, iff branding ACL as "brand" is ok. + */ +int +_acl_brand_may_be(const acl_t acl, int brand) +{ + + if (_acl_brand(acl) == ACL_BRAND_UNKNOWN) + return (1); + + if (_acl_brand(acl) == brand) + return (1); + + return (0); +} + +int +_entry_brand_may_be(const acl_entry_t entry, int brand) +{ + + return (_acl_brand_may_be(entry2acl(entry), brand)); +} + +/* + * Brand ACL as "brand". + */ +void +_acl_brand_as(acl_t acl, int brand) +{ + + assert(_acl_brand_may_be(acl, brand)); + + acl->ats_brand = brand; +} + +void +_entry_brand_as(const acl_entry_t entry, int brand) +{ + + _acl_brand_as(entry2acl(entry), brand); +} + +int +_acl_type_not_valid_for_acl(const acl_t acl, acl_type_t type) +{ + + switch (_acl_brand(acl)) { + case ACL_BRAND_NFS4: + if (type == ACL_TYPE_NFS4) + return (0); + break; + + case ACL_BRAND_POSIX: + if (type == ACL_TYPE_ACCESS || type == ACL_TYPE_DEFAULT) + return (0); + break; + + case ACL_BRAND_UNKNOWN: + return (0); + } + + return (-1); +} + +void +_acl_brand_from_type(acl_t acl, acl_type_t type) +{ + + switch (type) { + case ACL_TYPE_NFS4: + _acl_brand_as(acl, ACL_BRAND_NFS4); + break; + case ACL_TYPE_ACCESS: + case ACL_TYPE_DEFAULT: + _acl_brand_as(acl, ACL_BRAND_POSIX); + break; + default: + /* XXX: What to do here? */ + break; + } +} + +int +acl_get_brand_np(acl_t acl, int *brand_p) +{ + + if (acl == NULL || brand_p == NULL) { + errno = EINVAL; + return (-1); + } + *brand_p = _acl_brand(acl); + + return (0); +} diff --git a/lib/libc/posix1e/acl_calc_mask.3 b/lib/libc/posix1e/acl_calc_mask.3 new file mode 100644 index 0000000..dba9334 --- /dev/null +++ b/lib/libc/posix1e/acl_calc_mask.3 @@ -0,0 +1,98 @@ +.\"- +.\" Copyright (c) 2001 Chris D. Faulhaber +.\" 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 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 AUTHOR 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. +.\" +.\" $FreeBSD: releng/10.2/lib/libc/posix1e/acl_calc_mask.3 184607 2008-11-04 00:20:43Z imp $ +.\" +.Dd March 10, 2001 +.Dt ACL_CALC_MASK 3 +.Os +.Sh NAME +.Nm acl_calc_mask +.Nd calculate and set ACL mask permissions +.Sh LIBRARY +.Lb libc +.Sh SYNOPSIS +.In sys/types.h +.In sys/acl.h +.Ft int +.Fn acl_calc_mask "acl_t *acl_p" +.Sh DESCRIPTION +The +.Fn acl_calc_mask +function +is a POSIX.1e call that calculates and set the permissions +associated with the +.Dv ACL_MASK +ACL entry of the ACL referred to by +.Fa acl_p . +.Pp +The value of new permissions are the union of the permissions +granted by the +.Dv ACL_GROUP , ACL_GROUP_OBJ , ACL_USER +tag types which +match processes in the file group class contained in the ACL +referred to by +.Fa acl_p . +.Pp +If the ACL referred to by +.Fa acl_p +already contains an +.Dv ACL_MASK +entry, its permissions shall be +overwritten; if it does not contain an +.Dv ACL_MASK +entry, one shall +be added. +.Sh RETURN VALUES +.Rv -std acl_calc_mask +.Sh ERRORS +The +.Fn acl_calc_mask +function fails if: +.Bl -tag -width Er +.It Bq Er EINVAL +Argument +.Fa acl_p +does not point to a pointer to a valid ACL. +.El +.Sh SEE ALSO +.Xr acl 3 , +.Xr acl_get_entry 3 , +.Xr acl_valid 3 , +.Xr posix1e 3 +.Sh STANDARDS +POSIX.1e is described in IEEE POSIX.1e draft 17. +.Sh HISTORY +POSIX.1e support was introduced in +.Fx 4.0 . +The +.Fn acl_calc_mask +function was added in +.Fx 5.0 . +.Sh AUTHORS +The +.Fn acl_calc_mask +function was written by +.An Chris D. Faulhaber Aq jedgar@fxp.org . diff --git a/lib/libc/posix1e/acl_calc_mask.c b/lib/libc/posix1e/acl_calc_mask.c new file mode 100644 index 0000000..f8a1c44 --- /dev/null +++ b/lib/libc/posix1e/acl_calc_mask.c @@ -0,0 +1,127 @@ +/* + * Copyright (c) 2001-2002 Chris D. Faulhaber + * 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 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 AUTHOR 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 + +#include +#include "namespace.h" +#include +#include "un-namespace.h" + +#include +#include + +#include "acl_support.h" + +/* + * acl_calc_mask() (23.4.2): calculate and set the permissions + * associated with the ACL_MASK ACL entry. If the ACL already + * contains an ACL_MASK entry, its permissions shall be + * overwritten; if not, one shall be added. + */ +int +acl_calc_mask(acl_t *acl_p) +{ + struct acl *acl_int, *acl_int_new; + acl_t acl_new; + int i, mask_mode, mask_num; + + /* + * (23.4.2.4) requires acl_p to point to a pointer to a valid ACL. + * Since one of the primary reasons to use this function would be + * to calculate the appropriate mask to obtain a valid ACL, we only + * perform sanity checks here and validate the ACL prior to + * returning. + */ + if (acl_p == NULL || *acl_p == NULL) { + errno = EINVAL; + return (-1); + } + + if (!_acl_brand_may_be(*acl_p, ACL_BRAND_POSIX)) { + errno = EINVAL; + return (-1); + } + _acl_brand_as(*acl_p, ACL_BRAND_POSIX); + + acl_int = &(*acl_p)->ats_acl; + if ((acl_int->acl_cnt < 3) || (acl_int->acl_cnt > ACL_MAX_ENTRIES)) { + errno = EINVAL; + return (-1); + } + + acl_new = acl_dup(*acl_p); + if (acl_new == NULL) + return (-1); + acl_int_new = &acl_new->ats_acl; + + mask_mode = 0; + mask_num = -1; + + /* gather permissions and find a mask entry */ + for (i = 0; i < acl_int_new->acl_cnt; i++) { + switch(acl_int_new->acl_entry[i].ae_tag) { + case ACL_USER: + case ACL_GROUP: + case ACL_GROUP_OBJ: + mask_mode |= + acl_int_new->acl_entry[i].ae_perm & ACL_PERM_BITS; + break; + case ACL_MASK: + mask_num = i; + break; + } + } + + /* if a mask entry already exists, overwrite the perms */ + if (mask_num != -1) + acl_int_new->acl_entry[mask_num].ae_perm = mask_mode; + else { + /* if no mask exists, check acl_cnt... */ + if (acl_int_new->acl_cnt == ACL_MAX_ENTRIES) { + errno = ENOMEM; + return (-1); + } + /* ...and add the mask entry */ + acl_int_new->acl_entry[acl_int_new->acl_cnt].ae_tag = ACL_MASK; + acl_int_new->acl_entry[acl_int_new->acl_cnt].ae_id = + ACL_UNDEFINED_ID; + acl_int_new->acl_entry[acl_int_new->acl_cnt].ae_perm = + mask_mode; + acl_int_new->acl_cnt++; + } + + if (acl_valid(acl_new) == -1) { + errno = EINVAL; + acl_free(acl_new); + return (-1); + } + + **acl_p = *acl_new; + acl_free(acl_new); + + return (0); +} diff --git a/lib/libc/posix1e/acl_clear_flags_np.3 b/lib/libc/posix1e/acl_clear_flags_np.3 new file mode 100644 index 0000000..f25a6ae --- /dev/null +++ b/lib/libc/posix1e/acl_clear_flags_np.3 @@ -0,0 +1,79 @@ +.\"- +.\" Copyright (c) 2008, 2009 Edward Tomasz Napierala +.\" 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 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 AUTHOR 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. +.\" +.\" $FreeBSD: releng/10.2/lib/libc/posix1e/acl_clear_flags_np.3 275253 2014-11-29 15:50:13Z trasz $ +.\" +.Dd October 30, 2014 +.Dt ACL_CLEAR_FLAGS_NP 3 +.Os +.Sh NAME +.Nm acl_clear_flags_np +.Nd clear flags from a flagset +.Sh LIBRARY +.Lb libc +.Sh SYNOPSIS +.In sys/types.h +.In sys/acl.h +.Ft int +.Fn acl_clear_flags_np "acl_flagset_t flagset_d" +.Sh DESCRIPTION +The +.Fn acl_clear_flags_np +function +is a non-portable call that clears all NFSv4 ACL flags from flagset +.Fa flagset_d . +.Sh RETURN VALUES +.Rv -std acl_clear_flags_np +.Sh ERRORS +The +.Fn acl_clear_flags_np +function fails if: +.Bl -tag -width Er +.It Bq Er EINVAL +Argument +.Fa flagset_d +is not a valid descriptor for a flagset. +.El +.Sh SEE ALSO +.Xr acl 3 , +.Xr acl_add_flag_np 3 , +.Xr acl_delete_flag_np 3 , +.Xr acl_get_flagset_np 3 , +.Xr acl_set_flagset_np 3 , +.Xr posix1e 3 +.Sh STANDARDS +POSIX.1e is described in IEEE POSIX.1e draft 17. +.Sh HISTORY +POSIX.1e support was introduced in +.Fx 4.0 . +The +.Fn acl_clear_flags_np +function was added in +.Fx 5.0 . +.Sh AUTHORS +The +.Fn acl_clear_flags_np +function was written by +.An Edward Tomasz Napierala Aq trasz@FreeBSD.org . diff --git a/lib/libc/posix1e/acl_clear_perms.3 b/lib/libc/posix1e/acl_clear_perms.3 new file mode 100644 index 0000000..e72806c --- /dev/null +++ b/lib/libc/posix1e/acl_clear_perms.3 @@ -0,0 +1,79 @@ +.\"- +.\" Copyright (c) 2001 Chris D. Faulhaber +.\" 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 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 AUTHOR 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. +.\" +.\" $FreeBSD: releng/10.2/lib/libc/posix1e/acl_clear_perms.3 184607 2008-11-04 00:20:43Z imp $ +.\" +.Dd March 10, 2001 +.Dt ACL_CLEAR_PERMS 3 +.Os +.Sh NAME +.Nm acl_clear_perms +.Nd clear permissions from a permission set +.Sh LIBRARY +.Lb libc +.Sh SYNOPSIS +.In sys/types.h +.In sys/acl.h +.Ft int +.Fn acl_clear_perms "acl_permset_t permset_d" +.Sh DESCRIPTION +The +.Fn acl_clear_perms +function +is a POSIX.1e call that clears all permissions from permissions set +.Fa permset_d . +.Sh RETURN VALUES +.Rv -std acl_clear_perms +.Sh ERRORS +The +.Fn acl_clear_perms +function fails if: +.Bl -tag -width Er +.It Bq Er EINVAL +Argument +.Fa permset_d +is not a valid descriptor for a permission set. +.El +.Sh SEE ALSO +.Xr acl 3 , +.Xr acl_add_perm 3 , +.Xr acl_delete_perm 3 , +.Xr acl_get_permset 3 , +.Xr acl_set_permset 3 , +.Xr posix1e 3 +.Sh STANDARDS +POSIX.1e is described in IEEE POSIX.1e draft 17. +.Sh HISTORY +POSIX.1e support was introduced in +.Fx 4.0 . +The +.Fn acl_clear_perms +function was added in +.Fx 5.0 . +.Sh AUTHORS +The +.Fn acl_clear_perms +function was written by +.An Chris D. Faulhaber Aq jedgar@fxp.org . diff --git a/lib/libc/posix1e/acl_compat.c b/lib/libc/posix1e/acl_compat.c new file mode 100644 index 0000000..65b88d4 --- /dev/null +++ b/lib/libc/posix1e/acl_compat.c @@ -0,0 +1,59 @@ +/*- + * Copyright (c) 2008 Edward Tomasz Napierała + * 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 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 AUTHOR 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 +__FBSDID("$FreeBSD: releng/10.2/lib/libc/posix1e/acl_compat.c 192804 2009-05-26 11:42:06Z trasz $"); + +#include + +/* + * Compatibility wrappers for applications compiled against libc from before + * NFSv4 ACLs were added. + */ +int +__oldacl_get_perm_np(acl_permset_t permset_d, oldacl_perm_t perm) +{ + + return (acl_get_perm_np(permset_d, perm)); +} + +int +__oldacl_add_perm(acl_permset_t permset_d, oldacl_perm_t perm) +{ + + return (acl_add_perm(permset_d, perm)); +} + +int +__oldacl_delete_perm(acl_permset_t permset_d, oldacl_perm_t perm) +{ + + return (acl_delete_perm(permset_d, perm)); +} + +__sym_compat(acl_get_perm_np, __oldacl_get_perm_np, FBSD_1.0); +__sym_compat(acl_add_perm, __oldacl_add_perm, FBSD_1.0); +__sym_compat(acl_delete_perm, __oldacl_delete_perm, FBSD_1.0); diff --git a/lib/libc/posix1e/acl_copy.c b/lib/libc/posix1e/acl_copy.c new file mode 100644 index 0000000..b82c951 --- /dev/null +++ b/lib/libc/posix1e/acl_copy.c @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2001-2002 Chris D. Faulhaber + * 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 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 AUTHOR 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 +__FBSDID("$FreeBSD: releng/10.2/lib/libc/posix1e/acl_copy.c 194955 2009-06-25 12:46:59Z trasz $"); + +#include +#include "namespace.h" +#include +#include "un-namespace.h" + +#include +#include + +#include "acl_support.h" + +/* + * acl_copy_entry() (23.4.4): copy the contents of ACL entry src_d to + * ACL entry dest_d + */ +int +acl_copy_entry(acl_entry_t dest_d, acl_entry_t src_d) +{ + + if (src_d == NULL || dest_d == NULL || src_d == dest_d) { + errno = EINVAL; + return (-1); + } + + /* + * Can we brand the new entry the same as the source entry? + */ + if (!_entry_brand_may_be(dest_d, _entry_brand(src_d))) { + errno = EINVAL; + return (-1); + } + + _entry_brand_as(dest_d, _entry_brand(src_d)); + + dest_d->ae_tag = src_d->ae_tag; + dest_d->ae_id = src_d->ae_id; + dest_d->ae_perm = src_d->ae_perm; + dest_d->ae_entry_type = src_d->ae_entry_type; + dest_d->ae_flags = src_d->ae_flags; + + return (0); +} + +ssize_t +acl_copy_ext(void *buf_p, acl_t acl, ssize_t size) +{ + + errno = ENOSYS; + return (-1); +} + +acl_t +acl_copy_int(const void *buf_p) +{ + + errno = ENOSYS; + return (NULL); +} diff --git a/lib/libc/posix1e/acl_copy_entry.3 b/lib/libc/posix1e/acl_copy_entry.3 new file mode 100644 index 0000000..200b733 --- /dev/null +++ b/lib/libc/posix1e/acl_copy_entry.3 @@ -0,0 +1,85 @@ +.\"- +.\" Copyright (c) 2001 Chris D. Faulhaber +.\" 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 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 AUTHOR 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. +.\" +.\" $FreeBSD: releng/10.2/lib/libc/posix1e/acl_copy_entry.3 184607 2008-11-04 00:20:43Z imp $ +.\" +.Dd March 10, 2001 +.Dt ACL_COPY_ENTRY 3 +.Os +.Sh NAME +.Nm acl_copy_entry +.Nd copy an ACL entry to another ACL entry +.Sh LIBRARY +.Lb libc +.Sh SYNOPSIS +.In sys/types.h +.In sys/acl.h +.Ft int +.Fn acl_copy_entry "acl_entry_t dest_d" "acl_entry_t src_d" +.Sh DESCRIPTION +The +.Fn acl_copy_entry +function +is a POSIX.1e call that copies the contents of ACL entry +.Fa src_d +to ACL entry +.Fa dest_d . +.Sh RETURN VALUES +.Rv -std acl_copy_entry +.Sh ERRORS +The +.Fn acl_copy_entry +function fails if: +.Bl -tag -width Er +.It Bq Er EINVAL +Argument +.Fa src_d +or +.Fa dest_d +is not a valid descriptor for an ACL entry, or +arguments +.Fa src_d +and +.Fa dest_d +reference the same ACL entry. +.El +.Sh SEE ALSO +.Xr acl 3 , +.Xr acl_get_entry 3 , +.Xr posix1e 3 +.Sh STANDARDS +POSIX.1e is described in IEEE POSIX.1e draft 17. +.Sh HISTORY +POSIX.1e support was introduced in +.Fx 4.0 . +The +.Fn acl_copy_entry +function was added in +.Fx 5.0 . +.Sh AUTHORS +The +.Fn acl_copy_entry +function was written by +.An Chris D. Faulhaber Aq jedgar@fxp.org . diff --git a/lib/libc/posix1e/acl_create_entry.3 b/lib/libc/posix1e/acl_create_entry.3 new file mode 100644 index 0000000..dcad1a1 --- /dev/null +++ b/lib/libc/posix1e/acl_create_entry.3 @@ -0,0 +1,98 @@ +.\"- +.\" Copyright (c) 2001 Chris D. Faulhaber +.\" 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 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 AUTHOR 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. +.\" +.\" $FreeBSD: releng/10.2/lib/libc/posix1e/acl_create_entry.3 233648 2012-03-29 05:02:12Z eadler $ +.\" +.Dd June 25, 2009 +.Dt ACL_CREATE_ENTRY 3 +.Os +.Sh NAME +.Nm acl_create_entry +.Nm acl_create_entry_np +.Nd create a new ACL entry +.Sh LIBRARY +.Lb libc +.Sh SYNOPSIS +.In sys/types.h +.In sys/acl.h +.Ft int +.Fn acl_create_entry "acl_t *acl_p" "acl_entry_t *entry_p" +.Ft int +.Fn acl_create_entry_np "acl_t *acl_p" "acl_entry_t *entry_p" "int index" +.Sh DESCRIPTION +The +.Fn acl_create_entry +function +is a POSIX.1e call that creates a new ACL entry in the ACL +pointed to by +.Fa acl_p . +The +.Fn acl_create_entry_np +function is a non-portable version that creates the ACL entry +at position +.Fa index . +Positions are numbered starting from zero, i.e. calling +.Fn acl_create_entry_np +with +.Fa index +argument equal to zero will prepend the entry to the ACL. +.Sh RETURN VALUES +.Rv -std acl_create_entry +.Sh ERRORS +The +.Fn acl_create_entry +function fails if: +.Bl -tag -width Er +.It Bq Er EINVAL +Argument +.Fa acl_p +does not point to a pointer to a valid ACL. +Argument +.Fa index +is out of bounds. +.It Bq Er ENOMEM +The ACL working storage requires more memory than is +allowed by the hardware or system-imposed memory +management constraints. +.El +.Sh SEE ALSO +.Xr acl 3 , +.Xr acl_delete_entry 3 , +.Xr acl_get_entry 3 , +.Xr posix1e 3 +.Sh STANDARDS +POSIX.1e is described in IEEE POSIX.1e draft 17. +.Sh HISTORY +POSIX.1e support was introduced in +.Fx 4.0 . +The +.Fn acl_create_entry +function was added in +.Fx 5.0 . +.Sh AUTHORS +The +.Fn acl_create_entry +function was written by +.An Chris D. Faulhaber Aq jedgar@fxp.org . diff --git a/lib/libc/posix1e/acl_delete.3 b/lib/libc/posix1e/acl_delete.3 new file mode 100644 index 0000000..535f577 --- /dev/null +++ b/lib/libc/posix1e/acl_delete.3 @@ -0,0 +1,140 @@ +.\"- +.\" Copyright (c) 2000, 2002 Robert N. M. Watson +.\" All rights reserved. +.\" +.\" This software was developed by Robert Watson for the TrustedBSD Project. +.\" +.\" 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 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 AUTHOR 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. +.\" +.\" $FreeBSD: releng/10.2/lib/libc/posix1e/acl_delete.3 131635 2004-07-05 17:12:53Z ru $ +.\" +.Dd December 29, 2002 +.Dt ACL_DELETE 3 +.Os +.Sh NAME +.Nm acl_delete_def_file , +.Nm acl_delete_def_link_np , +.Nm acl_delete_fd_np , +.Nm acl_delete_file_np , +.Nm acl_delete_link_np +.Nd delete an ACL from a file +.Sh LIBRARY +.Lb libc +.Sh SYNOPSIS +.In sys/types.h +.In sys/acl.h +.Ft int +.Fn acl_delete_def_file "const char *path_p" +.Ft int +.Fn acl_delete_def_link_np "const char *path_p" +.Ft int +.Fn acl_delete_fd_np "int filedes" "acl_type_t type" +.Ft int +.Fn acl_delete_file_np "const char *path_p" "acl_type_t type" +.Ft int +.Fn acl_delete_link_np "const char *path_p" "acl_type_t type" +.Sh DESCRIPTION +The +.Fn acl_delete_def_file , +.Fn acl_delete_def_link_np , +.Fn acl_delete_fd_np , +.Fn acl_delete_file_np , +and +.Fn acl_delete_link_np +each allow the deletion of an ACL from a file. +The +.Fn acl_delete_def_file +function +is a POSIX.1e call that deletes the default ACL from a file (normally a +directory) by name; the remainder of the calls are non-portable extensions +that permit the deletion of arbitrary ACL types from a file/directory +either by path name or file descriptor. +The +.Fn _file +variations follow a symlink if it occurs in the last segment of the +path name; the +.Fn _link +variations operate on the symlink itself. +.Sh IMPLEMENTATION NOTES +.Fx Ns 's +support for POSIX.1e interfaces and features is still under +development at this time. +.Sh RETURN VALUES +.Rv -std +.Sh ERRORS +If any of the following conditions occur, these functions shall return -1 +and set +.Va errno +to the corresponding value: +.Bl -tag -width Er +.It Bq Er EACCES +Search permission is denied for a component of the path prefix, or the +object exists and the process does not have appropriate access rights. +.It Bq Er EBADF +The +.Va fd +argument is not a valid file descriptor. +.It Bq Er EINVAL +The ACL type passed is invalid for this file object. +.It Bq Er ENAMETOOLONG +A component of a pathname exceeded 255 characters, or an +entire path name exceeded 1023 characters. +.It Bq Er ENOENT +The named object does not exist, or the +.Va path_p +argument points to an empty string. +.It Bq Er ENOMEM +Insufficient memory available to fulfill request. +.It Bq Er ENOTDIR +A component of the path prefix is not a directory. +.Pp +Argument +.Va path_p +must be a directory, and is not. +.It Bq Er EOPNOTSUPP +The file system does not support ACL deletion. +.It Bq Er EPERM +The process does not have appropriate privilege to perform the operation +to delete an ACL. +.It Bq Er EROFS +The file system is read-only. +.El +.Sh SEE ALSO +.Xr acl 3 , +.Xr acl_get 3 , +.Xr acl_set 3 , +.Xr posix1e 3 +.Sh STANDARDS +POSIX.1e is described in IEEE POSIX.1e draft 17. +Discussion +of the draft continues on the cross-platform POSIX.1e implementation +mailing list. +To join this list, see the +.Fx +POSIX.1e implementation +page for more information. +.Sh HISTORY +POSIX.1e support was introduced in +.Fx 4.0 , +and development continues. +.Sh AUTHORS +.An Robert N M Watson diff --git a/lib/libc/posix1e/acl_delete.c b/lib/libc/posix1e/acl_delete.c new file mode 100644 index 0000000..0ebc158 --- /dev/null +++ b/lib/libc/posix1e/acl_delete.c @@ -0,0 +1,79 @@ +/*- + * Copyright (c) 1999, 2000, 2001, 2002 Robert N. M. Watson + * All rights reserved. + * + * This software was developed by Robert Watson for the TrustedBSD Project. + * + * 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 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 AUTHOR 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. + */ +/* + * acl_delete_def_file -- remove a default acl from a file + */ + +#include +__FBSDID("$FreeBSD: releng/10.2/lib/libc/posix1e/acl_delete.c 192586 2009-05-22 15:56:43Z trasz $"); + +#include +#include "namespace.h" +#include +#include "un-namespace.h" +#include + +#include "acl_support.h" + +int +acl_delete_def_file(const char *path_p) +{ + + return (__acl_delete_file(path_p, ACL_TYPE_DEFAULT)); +} + +int +acl_delete_def_link_np(const char *path_p) +{ + + return (__acl_delete_link(path_p, ACL_TYPE_DEFAULT)); +} + +int +acl_delete_file_np(const char *path_p, acl_type_t type) +{ + + type = _acl_type_unold(type); + return (__acl_delete_file(path_p, type)); +} + +int +acl_delete_link_np(const char *path_p, acl_type_t type) +{ + + type = _acl_type_unold(type); + return (__acl_delete_link(path_p, type)); +} + +int +acl_delete_fd_np(int filedes, acl_type_t type) +{ + + type = _acl_type_unold(type); + return (___acl_delete_fd(filedes, type)); +} diff --git a/lib/libc/posix1e/acl_delete_entry.3 b/lib/libc/posix1e/acl_delete_entry.3 new file mode 100644 index 0000000..1fd3cf8 --- /dev/null +++ b/lib/libc/posix1e/acl_delete_entry.3 @@ -0,0 +1,101 @@ +.\"- +.\" Copyright (c) 2001 Chris D. Faulhaber +.\" 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 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 AUTHOR 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. +.\" +.\" $FreeBSD: releng/10.2/lib/libc/posix1e/acl_delete_entry.3 235286 2012-05-11 20:06:46Z gjb $ +.\" +.Dd June 25, 2009 +.Dt ACL_DELETE_ENTRY 3 +.Os +.Sh NAME +.Nm acl_delete_entry , +.Nm acl_delete_entry_np +.Nd delete an ACL entry from an ACL +.Sh LIBRARY +.Lb libc +.Sh SYNOPSIS +.In sys/types.h +.In sys/acl.h +.Ft int +.Fn acl_delete_entry "acl_t acl" "acl_entry_t entry_d" +.Ft int +.Fn acl_delete_entry_np "acl_t acl" "int index" +.Sh DESCRIPTION +The +.Fn acl_delete_entry +function +is a POSIX.1e call that removes the ACL entry +.Fa entry_d +from ACL +.Fa acl . +The +.Fn acl_delete_entry_np +function is a non-portable version that removes the ACL entry +at position +.Fa index +from ACL +.Fa acl . +Positions are numbered starting from zero, i.e. calling +.Fn acl_delete_entry_np +with +.Fa index +argument equal to zero will remove the first ACL entry. +.Sh RETURN VALUES +.Rv -std acl_delete_entry +.Sh ERRORS +The +.Fn acl_delete_entry +function fails if: +.Bl -tag -width Er +.It Bq Er EINVAL +Argument +.Fa acl +does not point to a valid ACL. +Argument +.Fa entry_d +is not a valid descriptor for an ACL entry in +.Fa acl . +Argument +.Fa index +is out of bounds. +.El +.Sh SEE ALSO +.Xr acl 3 , +.Xr acl_copy_entry 3 , +.Xr acl_get_entry 3 , +.Xr posix1e 3 +.Sh STANDARDS +POSIX.1e is described in IEEE POSIX.1e draft 17. +.Sh HISTORY +POSIX.1e support was introduced in +.Fx 4.0 . +The +.Fn acl_delete_entry +function was added in +.Fx 5.0 . +.Sh AUTHORS +The +.Fn acl_delete_entry +function was written by +.An Chris D. Faulhaber Aq jedgar@fxp.org . diff --git a/lib/libc/posix1e/acl_delete_entry.c b/lib/libc/posix1e/acl_delete_entry.c new file mode 100644 index 0000000..9f89acb --- /dev/null +++ b/lib/libc/posix1e/acl_delete_entry.c @@ -0,0 +1,162 @@ +/* + * Copyright (c) 2001-2002 Chris D. Faulhaber + * 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 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 AUTHOR 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 +__FBSDID("$FreeBSD: releng/10.2/lib/libc/posix1e/acl_delete_entry.c 200992 2009-12-25 18:05:06Z markus $"); + +#include +#include "namespace.h" +#include +#include "un-namespace.h" +#include +#include +#include + +#include "acl_support.h" + +static int +_entry_matches(const acl_entry_t a, const acl_entry_t b) +{ + /* + * There is a semantical difference here between NFSv4 and POSIX + * draft ACLs. In POSIX, there may be only one entry for the particular + * user or group. In NFSv4 ACL, there may be any number of them. We're + * trying to be more specific here in that case. + */ + switch (_entry_brand(a)) { + case ACL_BRAND_NFS4: + if (a->ae_tag != b->ae_tag || a->ae_entry_type != b->ae_entry_type) + return (0); + + /* If ae_ids matter, compare them as well. */ + if (a->ae_tag == ACL_USER || a->ae_tag == ACL_GROUP) { + if (a->ae_id != b->ae_id) + return (0); + } + + return (1); + + default: + if ((a->ae_tag == b->ae_tag) && (a->ae_id == b->ae_id)) + return (1); + } + + return (0); +} + +/* + * acl_delete_entry() (23.4.9): remove the ACL entry indicated by entry_d + * from acl. + */ +int +acl_delete_entry(acl_t acl, acl_entry_t entry_d) +{ + struct acl *acl_int; + struct acl_entry entry_int; + int i, j, found = 0; + + if (acl == NULL || entry_d == NULL) { + errno = EINVAL; + return (-1); + } + + acl_int = &acl->ats_acl; + + if (_entry_brand(entry_d) != _acl_brand(acl)) { + errno = EINVAL; + return (-1); + } + + if ((acl->ats_acl.acl_cnt < 1) || + (acl->ats_acl.acl_cnt > ACL_MAX_ENTRIES)) { + errno = EINVAL; + return (-1); + } + + /* Use a local copy to prevent deletion of more than this entry */ + entry_int = *entry_d; + + for (i = 0; i < acl->ats_acl.acl_cnt;) { + if (_entry_matches(&(acl->ats_acl.acl_entry[i]), &entry_int)) { + /* ...shift the remaining entries... */ + for (j = i; j < acl->ats_acl.acl_cnt - 1; ++j) + acl->ats_acl.acl_entry[j] = + acl->ats_acl.acl_entry[j+1]; + /* ...drop the count and zero the unused entry... */ + acl->ats_acl.acl_cnt--; + bzero(&acl->ats_acl.acl_entry[j], + sizeof(struct acl_entry)); + acl->ats_cur_entry = 0; + + /* Continue with the loop to remove all maching entries. */ + found = 1; + } else + i++; + } + + if (found) + return (0); + + errno = EINVAL; + return (-1); +} + +int +acl_delete_entry_np(acl_t acl, int offset) +{ + struct acl *acl_int; + int i; + + if (acl == NULL) { + errno = EINVAL; + return (-1); + } + + acl_int = &acl->ats_acl; + + if (offset < 0 || offset >= acl_int->acl_cnt) { + errno = EINVAL; + return (-1); + } + + if ((acl->ats_acl.acl_cnt < 1) || + (acl->ats_acl.acl_cnt > ACL_MAX_ENTRIES)) { + errno = EINVAL; + return (-1); + } + + /* ...shift the remaining entries... */ + for (i = offset; i < acl->ats_acl.acl_cnt - 1; ++i) + acl->ats_acl.acl_entry[i] = + acl->ats_acl.acl_entry[i+1]; + /* ...drop the count and zero the unused entry... */ + acl->ats_acl.acl_cnt--; + bzero(&acl->ats_acl.acl_entry[i], + sizeof(struct acl_entry)); + acl->ats_cur_entry = 0; + + return (0); +} diff --git a/lib/libc/posix1e/acl_delete_flag_np.3 b/lib/libc/posix1e/acl_delete_flag_np.3 new file mode 100644 index 0000000..7656c69 --- /dev/null +++ b/lib/libc/posix1e/acl_delete_flag_np.3 @@ -0,0 +1,84 @@ +.\"- +.\" Copyright (c) 2008, 2009 Edward Tomasz Napierala +.\" 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 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 AUTHOR 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. +.\" +.\" $FreeBSD: releng/10.2/lib/libc/posix1e/acl_delete_flag_np.3 275253 2014-11-29 15:50:13Z trasz $ +.\" +.Dd October 30, 2014 +.Dt ACL_DELETE_FLAG_NP 3 +.Os +.Sh NAME +.Nm acl_delete_flag_np +.Nd delete flags from a flagset +.Sh LIBRARY +.Lb libc +.Sh SYNOPSIS +.In sys/types.h +.In sys/acl.h +.Ft int +.Fn acl_delete_flag_np "acl_flagset_t flagset_d" "acl_flag_t flag" +.Sh DESCRIPTION +The +.Fn acl_delete_flag_np +function +is a non-portable call that removes specific NFSv4 ACL flags from flagset +.Fa flags . +.Sh RETURN VALUES +.Rv -std acl_delete_flag_np +.Sh ERRORS +The +.Fn acl_delete_flag_np +function fails if: +.Bl -tag -width Er +.It Bq Er EINVAL +Argument +.Fa flagset_d +is not a valid descriptor for a flagset. +Argument +.Fa flag +does not contain a valid +.Vt acl_flag_t +value. +.El +.Sh SEE ALSO +.Xr acl 3 , +.Xr acl_add_flag_np 3 , +.Xr acl_clear_flag_nps 3 , +.Xr acl_get_flagset_np 3 , +.Xr acl_set_flagset_np 3 , +.Xr posix1e 3 +.Sh STANDARDS +POSIX.1e is described in IEEE POSIX.1e draft 17. +.Sh HISTORY +POSIX.1e support was introduced in +.Fx 4.0 . +The +.Fn acl_delete_flag_np +function was added in +.Fx 8.0 . +.Sh AUTHORS +The +.Fn acl_delete_flag_np +function was written by +.An Edward Tomasz Napierala Aq trasz@FreeBSD.org . diff --git a/lib/libc/posix1e/acl_delete_perm.3 b/lib/libc/posix1e/acl_delete_perm.3 new file mode 100644 index 0000000..8ca839e --- /dev/null +++ b/lib/libc/posix1e/acl_delete_perm.3 @@ -0,0 +1,84 @@ +.\"- +.\" Copyright (c) 2001 Chris D. Faulhaber +.\" 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 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 AUTHOR 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. +.\" +.\" $FreeBSD: releng/10.2/lib/libc/posix1e/acl_delete_perm.3 184607 2008-11-04 00:20:43Z imp $ +.\" +.Dd March 10, 2001 +.Dt ACL_DELETE_PERM 3 +.Os +.Sh NAME +.Nm acl_delete_perm +.Nd delete permissions from a permission set +.Sh LIBRARY +.Lb libc +.Sh SYNOPSIS +.In sys/types.h +.In sys/acl.h +.Ft int +.Fn acl_delete_perm "acl_permset_t permset_d" "acl_perm_t perm" +.Sh DESCRIPTION +The +.Fn acl_delete_perm +function +is a POSIX.1e call that removes specific permissions from permissions set +.Fa perm . +.Sh RETURN VALUES +.Rv -std acl_delete_perm +.Sh ERRORS +The +.Fn acl_delete_perm +function fails if: +.Bl -tag -width Er +.It Bq Er EINVAL +Argument +.Fa permset_d +is not a valid descriptor for a permission set. +Argument +.Fa perm +does not contain a valid +.Vt acl_perm_t +value. +.El +.Sh SEE ALSO +.Xr acl 3 , +.Xr acl_add_perm 3 , +.Xr acl_clear_perms 3 , +.Xr acl_get_permset 3 , +.Xr acl_set_permset 3 , +.Xr posix1e 3 +.Sh STANDARDS +POSIX.1e is described in IEEE POSIX.1e draft 17. +.Sh HISTORY +POSIX.1e support was introduced in +.Fx 4.0 . +The +.Fn acl_delete_perm +function was added in +.Fx 5.0 . +.Sh AUTHORS +The +.Fn acl_delete_perm +function was written by +.An Chris D. Faulhaber Aq jedgar@fxp.org . diff --git a/lib/libc/posix1e/acl_dup.3 b/lib/libc/posix1e/acl_dup.3 new file mode 100644 index 0000000..69b841c --- /dev/null +++ b/lib/libc/posix1e/acl_dup.3 @@ -0,0 +1,110 @@ +.\"- +.\" Copyright (c) 2000, 2002 Robert N. M. Watson +.\" All rights reserved. +.\" +.\" This software was developed by Robert Watson for the TrustedBSD Project. +.\" +.\" 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 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 AUTHOR 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. +.\" +.\" $FreeBSD: releng/10.2/lib/libc/posix1e/acl_dup.3 131504 2004-07-02 23:52:20Z ru $ +.\" +.Dd January 28, 2000 +.Dt ACL_DUP 3 +.Os +.Sh NAME +.Nm acl_dup +.Nd duplicate an ACL +.Sh LIBRARY +.Lb libc +.Sh SYNOPSIS +.In sys/types.h +.In sys/acl.h +.Ft acl_t +.Fn acl_dup "acl_t acl" +.Sh DESCRIPTION +The +.Fn acl_dup +function returns a pointer to a copy of the ACL pointed to by the argument +.Va acl . +.Pp +This function may cause memory to be allocated. +The caller should free any +releasable memory, when the new ACL is no longer required, by calling +.Xr acl_free 3 +with the +.Va (void*)acl_t +as an argument. +.Pp +Any existing ACL pointers that refer to the ACL referred to by +.Va acl +shall continue to refer to the ACL. +.Sh IMPLEMENTATION NOTES +.Fx Ns 's +support for POSIX.1e interfaces and features is still under +development at this time. +.Sh RETURN VALUES +Upon successful completion, this function shall return a pointer to the +duplicate ACL. +Otherwise, a value of +.Va (acl_t)NULL +shall be returned, and +.Va errno +shall be set to indicate the error. +.Sh ERRORS +If any of the following conditions occur, the +.Fn acl_init +function shall return a value of +.Va (acl_t)NULL +and set +.Va errno +to the corresponding value: +.Bl -tag -width Er +.It Bq Er EINVAL +Argument +.Va acl +does not point to a valid ACL. +.It Bq Er ENOMEM +The +.Va acl_t +to be returned requires more memory than is allowed by the hardware or +system-imposed memory management constraints. +.El +.Sh SEE ALSO +.Xr acl 3 , +.Xr acl_free 3 , +.Xr acl_get 3 , +.Xr posix1e 3 +.Sh STANDARDS +POSIX.1e is described in IEEE POSIX.1e draft 17. +Discussion +of the draft continues on the cross-platform POSIX.1e implementation +mailing list. +To join this list, see the +.Fx +POSIX.1e implementation +page for more information. +.Sh HISTORY +POSIX.1e support was introduced in +.Fx 4.0 , +and development continues. +.Sh AUTHORS +.An Robert N M Watson diff --git a/lib/libc/posix1e/acl_entry.c b/lib/libc/posix1e/acl_entry.c new file mode 100644 index 0000000..0e92e32 --- /dev/null +++ b/lib/libc/posix1e/acl_entry.c @@ -0,0 +1,146 @@ +/* + * Copyright (c) 2001-2002 Chris D. Faulhaber + * 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 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 AUTHOR 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 +__FBSDID("$FreeBSD: releng/10.2/lib/libc/posix1e/acl_entry.c 208783 2010-06-03 14:16:58Z trasz $"); + +#include +#include "namespace.h" +#include +#include "un-namespace.h" + +#include +#include + +/* + * acl_create_entry() (23.4.7): create a new ACL entry in the ACL pointed + * to by acl_p. + */ +int +acl_create_entry(acl_t *acl_p, acl_entry_t *entry_p) +{ + struct acl *acl_int; + + if (acl_p == NULL) { + errno = EINVAL; + return (-1); + } + + acl_int = &(*acl_p)->ats_acl; + + /* + * +1, because we are checking if there is space left for one more + * entry. + */ + if (acl_int->acl_cnt + 1 >= ACL_MAX_ENTRIES) { + errno = EINVAL; + return (-1); + } + + *entry_p = &acl_int->acl_entry[acl_int->acl_cnt++]; + + (**entry_p).ae_tag = ACL_UNDEFINED_TAG; + (**entry_p).ae_id = ACL_UNDEFINED_ID; + (**entry_p).ae_perm = ACL_PERM_NONE; + (**entry_p).ae_entry_type = 0; + (**entry_p).ae_flags = 0; + + (*acl_p)->ats_cur_entry = 0; + + return (0); +} + +int +acl_create_entry_np(acl_t *acl_p, acl_entry_t *entry_p, int offset) +{ + int i; + struct acl *acl_int; + + if (acl_p == NULL) { + errno = EINVAL; + return (-1); + } + + acl_int = &(*acl_p)->ats_acl; + + if (acl_int->acl_cnt + 1 >= ACL_MAX_ENTRIES) { + errno = EINVAL; + return (-1); + } + + if (offset < 0 || offset >= acl_int->acl_cnt) { + errno = EINVAL; + return (-1); + } + + /* Make room for the new entry. */ + for (i = acl_int->acl_cnt; i > offset; i--) + acl_int->acl_entry[i] = acl_int->acl_entry[i - 1]; + + acl_int->acl_cnt++; + + *entry_p = &acl_int->acl_entry[offset]; + + (**entry_p).ae_tag = ACL_UNDEFINED_TAG; + (**entry_p).ae_id = ACL_UNDEFINED_ID; + (**entry_p).ae_perm = ACL_PERM_NONE; + (**entry_p).ae_entry_type = 0; + (**entry_p).ae_flags= 0; + + (*acl_p)->ats_cur_entry = 0; + + return (0); +} + +/* + * acl_get_entry() (23.4.14): returns an ACL entry from an ACL + * indicated by entry_id. + */ +int +acl_get_entry(acl_t acl, int entry_id, acl_entry_t *entry_p) +{ + struct acl *acl_int; + + if (acl == NULL) { + errno = EINVAL; + return (-1); + } + acl_int = &acl->ats_acl; + + switch(entry_id) { + case ACL_FIRST_ENTRY: + acl->ats_cur_entry = 0; + /* PASSTHROUGH */ + case ACL_NEXT_ENTRY: + if (acl->ats_cur_entry >= acl->ats_acl.acl_cnt) + return 0; + *entry_p = &acl_int->acl_entry[acl->ats_cur_entry++]; + return (1); + } + + errno = EINVAL; + return (-1); +} diff --git a/lib/libc/posix1e/acl_flag.c b/lib/libc/posix1e/acl_flag.c new file mode 100644 index 0000000..6e136a5 --- /dev/null +++ b/lib/libc/posix1e/acl_flag.c @@ -0,0 +1,155 @@ +/*- + * Copyright (c) 2008, 2009 Edward Tomasz Napierała + * 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 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 AUTHOR 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 +__FBSDID("$FreeBSD: releng/10.2/lib/libc/posix1e/acl_flag.c 194957 2009-06-25 13:08:02Z trasz $"); + +#include +#include +#include + +#include "acl_support.h" + +static int +_flag_is_invalid(acl_flag_t flag) +{ + + if ((flag & ACL_FLAGS_BITS) == flag) + return (0); + + errno = EINVAL; + + return (1); +} + +int +acl_add_flag_np(acl_flagset_t flagset_d, acl_flag_t flag) +{ + + if (flagset_d == NULL) { + errno = EINVAL; + return (-1); + } + + if (_flag_is_invalid(flag)) + return (-1); + + *flagset_d |= flag; + + return (0); +} + +int +acl_clear_flags_np(acl_flagset_t flagset_d) +{ + + if (flagset_d == NULL) { + errno = EINVAL; + return (-1); + } + + *flagset_d |= 0; + + return (0); +} + +int +acl_delete_flag_np(acl_flagset_t flagset_d, acl_flag_t flag) +{ + + if (flagset_d == NULL) { + errno = EINVAL; + return (-1); + } + + if (_flag_is_invalid(flag)) + return (-1); + + *flagset_d &= ~flag; + + return (0); +} + +int +acl_get_flag_np(acl_flagset_t flagset_d, acl_flag_t flag) +{ + + if (flagset_d == NULL) { + errno = EINVAL; + return (-1); + } + + if (_flag_is_invalid(flag)) + return (-1); + + if (*flagset_d & flag) + return (1); + + return (0); +} + +int +acl_get_flagset_np(acl_entry_t entry_d, acl_flagset_t *flagset_p) +{ + + if (entry_d == NULL || flagset_p == NULL) { + errno = EINVAL; + return (-1); + } + + if (!_entry_brand_may_be(entry_d, ACL_BRAND_NFS4)) { + errno = EINVAL; + return (-1); + } + + *flagset_p = &entry_d->ae_flags; + + return (0); +} + +int +acl_set_flagset_np(acl_entry_t entry_d, acl_flagset_t flagset_d) +{ + + if (entry_d == NULL) { + errno = EINVAL; + return (-1); + } + + if (!_entry_brand_may_be(entry_d, ACL_BRAND_NFS4)) { + errno = EINVAL; + return (-1); + } + + _entry_brand_as(entry_d, ACL_BRAND_NFS4); + + if (_flag_is_invalid(*flagset_d)) + return (-1); + + entry_d->ae_flags = *flagset_d; + + return (0); +} diff --git a/lib/libc/posix1e/acl_free.3 b/lib/libc/posix1e/acl_free.3 new file mode 100644 index 0000000..53d0364 --- /dev/null +++ b/lib/libc/posix1e/acl_free.3 @@ -0,0 +1,89 @@ +.\"- +.\" Copyright (c) 2000, 2002 Robert N. M. Watson +.\" All rights reserved. +.\" +.\" This software was developed by Robert Watson for the TrustedBSD Project. +.\" +.\" 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 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 AUTHOR 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. +.\" +.\" $FreeBSD: releng/10.2/lib/libc/posix1e/acl_free.3 131504 2004-07-02 23:52:20Z ru $ +.\" +.Dd January 28, 2000 +.Dt ACL_FREE 3 +.Os +.Sh NAME +.Nm acl_free +.Nd free ACL working state +.Sh LIBRARY +.Lb libc +.Sh SYNOPSIS +.In sys/types.h +.In sys/acl.h +.Ft int +.Fn acl_free "void *obj_p" +.Sh DESCRIPTION +The +.Fn acl_free +call allows the freeing of ACL working space, such as is allocated by +.Xr acl_dup 3 , +or +.Xr acl_from_text 3 . +.Sh IMPLEMENTATION NOTES +.Fx Ns 's +support for POSIX.1e interfaces and features is still under +development at this time. +.Sh RETURN VALUES +.Rv -std acl_free +.Sh ERRORS +If any of the following conditions occur, the +.Fn acl_free +function shall return -1 and set +.Va errno +to the corresponding value: +.Bl -tag -width Er +.It Bq Er EINVAL +The value of the +.Va obj_p +argument is invalid. +.El +.Sh SEE ALSO +.Xr acl 3 , +.Xr acl_dup 3 , +.Xr acl_from_text 3 , +.Xr acl_get 3 , +.Xr acl_init 3 , +.Xr posix1e 3 +.Sh STANDARDS +POSIX.1e is described in IEEE POSIX.1e draft 17. +Discussion +of the draft continues on the cross-platform POSIX.1e implementation +mailing list. +To join this list, see the +.Fx +POSIX.1e implementation +page for more information. +.Sh HISTORY +POSIX.1e support was introduced in +.Fx 4.0 , +and development continues. +.Sh AUTHORS +.An Robert N M Watson diff --git a/lib/libc/posix1e/acl_free.c b/lib/libc/posix1e/acl_free.c new file mode 100644 index 0000000..7dae1d1 --- /dev/null +++ b/lib/libc/posix1e/acl_free.c @@ -0,0 +1,54 @@ +/*- + * Copyright (c) 1999, 2000, 2001 Robert N. M. Watson + * 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 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 AUTHOR 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. + */ +/* + * acl_free -- free ACL objects from user memory + */ + +#include +__FBSDID("$FreeBSD: releng/10.2/lib/libc/posix1e/acl_free.c 92986 2002-03-22 21:53:29Z obrien $"); + +#include +#include "namespace.h" +#include +#include "un-namespace.h" +#include +#include + +/* + * acl_free() (23.4.12): free any releasable memory allocated to the + * ACL data object identified by obj_p. + */ +int +acl_free(void *obj_p) +{ + + if (obj_p) { + free(obj_p); + obj_p = NULL; + } + + return (0); +} diff --git a/lib/libc/posix1e/acl_from_text.3 b/lib/libc/posix1e/acl_from_text.3 new file mode 100644 index 0000000..dd304e0 --- /dev/null +++ b/lib/libc/posix1e/acl_from_text.3 @@ -0,0 +1,130 @@ +.\"- +.\" Copyright (c) 2000, 2002 Robert N. M. Watson +.\" All rights reserved. +.\" +.\" This software was developed by Robert Watson for the TrustedBSD Project. +.\" +.\" 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 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 AUTHOR 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. +.\" +.\" $FreeBSD: releng/10.2/lib/libc/posix1e/acl_from_text.3 131504 2004-07-02 23:52:20Z ru $ +.\" +.Dd January 28, 2000 +.Dt ACL_FROM_TEXT 3 +.Os +.Sh NAME +.Nm acl_from_text +.Nd create an ACL from text +.Sh LIBRARY +.Lb libc +.Sh SYNOPSIS +.In sys/types.h +.In sys/acl.h +.Ft acl_t +.Fn acl_from_text "const char *buf_p" +.Sh DESCRIPTION +The +.Fn acl_from_text +function converts the text form of an ACL referred to by +.Va buf_p +into the internal working structure for ACLs, appropriate for applying to +files or manipulating. +.Pp +This function may cause memory to be allocated. +The caller should free any +releasable memory, when the new ACL is no longer required, by calling +.Xr acl_free 3 +with the +.Va (void *)acl_t +as an argument. +.Sh IMPLEMENTATION NOTES +.Fx Ns 's +support for POSIX.1e interfaces and features is still under +development at this time. +.Sh RETURN VALUES +Upon successful completion, the function shall return a pointer to the +internal representation of the ACL in working storage. +Otherwise, a value +of +.Va (acl_t)NULL +shall be returned, and +.Va errno +shall be set to indicate the error. +.Sh ERRORS +If any of the following conditions occur, the +.Fn acl_from_text +function shall return a value of +.Va (acl_t)NULL +and set +.Va errno +to the corresponding value: +.Bl -tag -width Er +.It Bq Er EINVAL +Argument +.Va buf_p +cannot be translated into an ACL. +.It Bq Er ENOMEM +The ACL working storage requires more memory than is allowed by the +hardware or system-imposed memory management constraints. +.El +.Sh SEE ALSO +.Xr acl 3 , +.Xr acl_free 3 , +.Xr acl_get 3 , +.Xr acl_to_text 3 , +.Xr posix1e 3 +.Sh STANDARDS +POSIX.1e is described in IEEE POSIX.1e draft 17. +Discussion +of the draft continues on the cross-platform POSIX.1e implementation +mailing list. +To join this list, see the +.Fx +POSIX.1e implementation +page for more information. +.Sh HISTORY +POSIX.1e support was introduced in +.Fx 4.0 , +and development continues. +.Sh AUTHORS +.An Robert N M Watson +.Sh BUGS +The +.Fn acl_from_text +and +.Fn acl_to_text +functions +rely on the +.Xr getpwent 3 +library calls to manage username and uid mapping, as well as the +.Xr getgrent 3 +library calls to manage groupname and gid mapping. +These calls are not +thread safe, and so transitively, neither are +.Fn acl_from_text +and +.Fn acl_to_text . +These functions may also interfere with stateful +calls associated with the +.Fn getpwent +and +.Fn getgrent +calls. diff --git a/lib/libc/posix1e/acl_from_text.c b/lib/libc/posix1e/acl_from_text.c new file mode 100644 index 0000000..30dcded --- /dev/null +++ b/lib/libc/posix1e/acl_from_text.c @@ -0,0 +1,313 @@ +/*- + * Copyright (c) 1999, 2000, 2001 Robert N. M. Watson + * 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 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 AUTHOR 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. + */ +/* + * acl_from_text: Convert a text-form ACL from a string to an acl_t. + */ + +#include +__FBSDID("$FreeBSD: releng/10.2/lib/libc/posix1e/acl_from_text.c 209736 2010-07-06 17:20:08Z trasz $"); + +#include +#include "namespace.h" +#include +#include "un-namespace.h" +#include +#include +#include +#include +#include +#include +#include + +#include "acl_support.h" + +static acl_tag_t acl_string_to_tag(char *tag, char *qualifier); + +int _nfs4_acl_entry_from_text(acl_t aclp, char *entry); +int _text_could_be_nfs4_acl(const char *entry); + +static acl_tag_t +acl_string_to_tag(char *tag, char *qualifier) +{ + + if (*qualifier == '\0') { + if ((!strcmp(tag, "user")) || (!strcmp(tag, "u"))) { + return (ACL_USER_OBJ); + } else + if ((!strcmp(tag, "group")) || (!strcmp(tag, "g"))) { + return (ACL_GROUP_OBJ); + } else + if ((!strcmp(tag, "mask")) || (!strcmp(tag, "m"))) { + return (ACL_MASK); + } else + if ((!strcmp(tag, "other")) || (!strcmp(tag, "o"))) { + return (ACL_OTHER); + } else + return(-1); + } else { + if ((!strcmp(tag, "user")) || (!strcmp(tag, "u"))) { + return(ACL_USER); + } else + if ((!strcmp(tag, "group")) || (!strcmp(tag, "g"))) { + return(ACL_GROUP); + } else + return(-1); + } +} + +static int +_posix1e_acl_entry_from_text(acl_t aclp, char *entry) +{ + acl_tag_t t; + acl_perm_t p; + char *tag, *qualifier, *permission; + uid_t id; + int error; + + assert(_acl_brand(aclp) == ACL_BRAND_POSIX); + + /* Split into three ':' delimited fields. */ + tag = strsep(&entry, ":"); + if (tag == NULL) { + errno = EINVAL; + return (-1); + } + tag = string_skip_whitespace(tag); + if ((*tag == '\0') && (!entry)) { + /* + * Is an entirely comment line, skip to next + * comma. + */ + return (0); + } + string_trim_trailing_whitespace(tag); + + qualifier = strsep(&entry, ":"); + if (qualifier == NULL) { + errno = EINVAL; + return (-1); + } + qualifier = string_skip_whitespace(qualifier); + string_trim_trailing_whitespace(qualifier); + + permission = strsep(&entry, ":"); + if (permission == NULL || entry) { + errno = EINVAL; + return (-1); + } + permission = string_skip_whitespace(permission); + string_trim_trailing_whitespace(permission); + + t = acl_string_to_tag(tag, qualifier); + if (t == -1) { + errno = EINVAL; + return (-1); + } + + error = _posix1e_acl_string_to_perm(permission, &p); + if (error == -1) { + errno = EINVAL; + return (-1); + } + + switch(t) { + case ACL_USER_OBJ: + case ACL_GROUP_OBJ: + case ACL_MASK: + case ACL_OTHER: + if (*qualifier != '\0') { + errno = EINVAL; + return (-1); + } + id = 0; + break; + + case ACL_USER: + case ACL_GROUP: + error = _acl_name_to_id(t, qualifier, &id); + if (error == -1) + return (-1); + break; + + default: + errno = EINVAL; + return (-1); + } + + error = _posix1e_acl_add_entry(aclp, t, id, p); + if (error == -1) + return (-1); + + return (0); +} + +static int +_text_is_nfs4_entry(const char *entry) +{ + int count = 0; + + assert(strlen(entry) > 0); + + while (*entry != '\0') { + if (*entry == ':' || *entry == '@') + count++; + entry++; + } + + if (count <= 2) + return (0); + + return (1); +} + +/* + * acl_from_text -- Convert a string into an ACL. + * Postpone most validity checking until the end and call acl_valid() to do + * that. + */ +acl_t +acl_from_text(const char *buf_p) +{ + acl_t acl; + char *mybuf_p, *line, *cur, *notcomment, *comment, *entry; + int error; + + /* Local copy we can mess up. */ + mybuf_p = strdup(buf_p); + if (mybuf_p == NULL) + return(NULL); + + acl = acl_init(3); /* XXX: WTF, 3? */ + if (acl == NULL) { + free(mybuf_p); + return(NULL); + } + + /* Outer loop: delimit at \n boundaries. */ + cur = mybuf_p; + while ((line = strsep(&cur, "\n"))) { + /* Now split the line on the first # to strip out comments. */ + comment = line; + notcomment = strsep(&comment, "#"); + + /* Inner loop: delimit at ',' boundaries. */ + while ((entry = strsep(¬comment, ","))) { + + /* Skip empty lines. */ + if (strlen(string_skip_whitespace(entry)) == 0) + continue; + + if (_acl_brand(acl) == ACL_BRAND_UNKNOWN) { + if (_text_is_nfs4_entry(entry)) + _acl_brand_as(acl, ACL_BRAND_NFS4); + else + _acl_brand_as(acl, ACL_BRAND_POSIX); + } + + switch (_acl_brand(acl)) { + case ACL_BRAND_NFS4: + error = _nfs4_acl_entry_from_text(acl, entry); + break; + + case ACL_BRAND_POSIX: + error = _posix1e_acl_entry_from_text(acl, entry); + break; + + default: + error = EINVAL; + break; + } + + if (error) + goto error_label; + } + } + +#if 0 + /* XXX Should we only return ACLs valid according to acl_valid? */ + /* Verify validity of the ACL we read in. */ + if (acl_valid(acl) == -1) { + errno = EINVAL; + goto error_label; + } +#endif + + free(mybuf_p); + return(acl); + +error_label: + acl_free(acl); + free(mybuf_p); + return(NULL); +} + +/* + * Given a username/groupname from a text form of an ACL, return the uid/gid + * XXX NOT THREAD SAFE, RELIES ON GETPWNAM, GETGRNAM + * XXX USES *PW* AND *GR* WHICH ARE STATEFUL AND THEREFORE THIS ROUTINE + * MAY HAVE SIDE-EFFECTS + */ +int +_acl_name_to_id(acl_tag_t tag, char *name, uid_t *id) +{ + struct group *g; + struct passwd *p; + unsigned long l; + char *endp; + + switch(tag) { + case ACL_USER: + p = getpwnam(name); + if (p == NULL) { + l = strtoul(name, &endp, 0); + if (*endp != '\0' || l != (unsigned long)(uid_t)l) { + errno = EINVAL; + return (-1); + } + *id = (uid_t)l; + return (0); + } + *id = p->pw_uid; + return (0); + + case ACL_GROUP: + g = getgrnam(name); + if (g == NULL) { + l = strtoul(name, &endp, 0); + if (*endp != '\0' || l != (unsigned long)(gid_t)l) { + errno = EINVAL; + return (-1); + } + *id = (gid_t)l; + return (0); + } + *id = g->gr_gid; + return (0); + + default: + return (EINVAL); + } +} diff --git a/lib/libc/posix1e/acl_from_text_nfs4.c b/lib/libc/posix1e/acl_from_text_nfs4.c new file mode 100644 index 0000000..c80fb93 --- /dev/null +++ b/lib/libc/posix1e/acl_from_text_nfs4.c @@ -0,0 +1,283 @@ +/*- + * Copyright (c) 2008, 2009 Edward Tomasz Napierała + * 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 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 AUTHOR 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 +__FBSDID("$FreeBSD: releng/10.2/lib/libc/posix1e/acl_from_text_nfs4.c 209736 2010-07-06 17:20:08Z trasz $"); + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "acl_support.h" + +#define MAX_ENTRY_LENGTH 512 + +/* + * Parse the tag field of ACL entry passed as "str". If qualifier + * needs to follow, then the variable referenced by "need_qualifier" + * is set to 1, otherwise it's set to 0. + */ +static int +parse_tag(const char *str, acl_entry_t entry, int *need_qualifier) +{ + + assert(need_qualifier != NULL); + *need_qualifier = 0; + + if (strcmp(str, "owner@") == 0) + return (acl_set_tag_type(entry, ACL_USER_OBJ)); + if (strcmp(str, "group@") == 0) + return (acl_set_tag_type(entry, ACL_GROUP_OBJ)); + if (strcmp(str, "everyone@") == 0) + return (acl_set_tag_type(entry, ACL_EVERYONE)); + + *need_qualifier = 1; + + if (strcmp(str, "user") == 0 || strcmp(str, "u") == 0) + return (acl_set_tag_type(entry, ACL_USER)); + if (strcmp(str, "group") == 0 || strcmp(str, "g") == 0) + return (acl_set_tag_type(entry, ACL_GROUP)); + + warnx("malformed ACL: invalid \"tag\" field"); + + return (-1); +} + +/* + * Parse the qualifier field of ACL entry passed as "str". + * If user or group name cannot be resolved, then the variable + * referenced by "need_qualifier" is set to 1; it will be checked + * later to figure out whether the appended_id is required. + */ +static int +parse_qualifier(char *str, acl_entry_t entry, int *need_qualifier) +{ + int qualifier_length, error; + uid_t id; + acl_tag_t tag; + + assert(need_qualifier != NULL); + *need_qualifier = 0; + + qualifier_length = strlen(str); + + if (qualifier_length == 0) { + warnx("malformed ACL: empty \"qualifier\" field"); + return (-1); + } + + error = acl_get_tag_type(entry, &tag); + if (error) + return (error); + + error = _acl_name_to_id(tag, str, &id); + if (error) { + *need_qualifier = 1; + return (0); + } + + return (acl_set_qualifier(entry, &id)); +} + +static int +parse_access_mask(char *str, acl_entry_t entry) +{ + int error; + acl_perm_t perm; + + error = _nfs4_parse_access_mask(str, &perm); + if (error) + return (error); + + error = acl_set_permset(entry, &perm); + + return (error); +} + +static int +parse_flags(char *str, acl_entry_t entry) +{ + int error; + acl_flag_t flags; + + error = _nfs4_parse_flags(str, &flags); + if (error) + return (error); + + error = acl_set_flagset_np(entry, &flags); + + return (error); +} + +static int +parse_entry_type(const char *str, acl_entry_t entry) +{ + + if (strcmp(str, "allow") == 0) + return (acl_set_entry_type_np(entry, ACL_ENTRY_TYPE_ALLOW)); + if (strcmp(str, "deny") == 0) + return (acl_set_entry_type_np(entry, ACL_ENTRY_TYPE_DENY)); + if (strcmp(str, "audit") == 0) + return (acl_set_entry_type_np(entry, ACL_ENTRY_TYPE_AUDIT)); + if (strcmp(str, "alarm") == 0) + return (acl_set_entry_type_np(entry, ACL_ENTRY_TYPE_ALARM)); + + warnx("malformed ACL: invalid \"type\" field"); + + return (-1); +} + +static int +parse_appended_id(char *str, acl_entry_t entry) +{ + int qualifier_length; + char *end; + id_t id; + + qualifier_length = strlen(str); + if (qualifier_length == 0) { + warnx("malformed ACL: \"appended id\" field present, " + "but empty"); + return (-1); + } + + id = strtod(str, &end); + if (end - str != qualifier_length) { + warnx("malformed ACL: appended id is not a number"); + return (-1); + } + + return (acl_set_qualifier(entry, &id)); +} + +static int +number_of_colons(const char *str) +{ + int count = 0; + + while (*str != '\0') { + if (*str == ':') + count++; + + str++; + } + + return (count); +} + +int +_nfs4_acl_entry_from_text(acl_t aclp, char *str) +{ + int error, need_qualifier; + acl_entry_t entry; + char *field, *qualifier_field; + + error = acl_create_entry(&aclp, &entry); + if (error) + return (error); + + assert(_entry_brand(entry) == ACL_BRAND_NFS4); + + if (str == NULL) + goto truncated_entry; + field = strsep(&str, ":"); + + field = string_skip_whitespace(field); + if ((*field == '\0') && (!str)) { + /* + * Is an entirely comment line, skip to next + * comma. + */ + return (0); + } + + error = parse_tag(field, entry, &need_qualifier); + if (error) + goto malformed_field; + + if (need_qualifier) { + if (str == NULL) + goto truncated_entry; + qualifier_field = field = strsep(&str, ":"); + error = parse_qualifier(field, entry, &need_qualifier); + if (error) + goto malformed_field; + } + + if (str == NULL) + goto truncated_entry; + field = strsep(&str, ":"); + error = parse_access_mask(field, entry); + if (error) + goto malformed_field; + + if (str == NULL) + goto truncated_entry; + /* Do we have "flags" field? */ + if (number_of_colons(str) > 0) { + field = strsep(&str, ":"); + error = parse_flags(field, entry); + if (error) + goto malformed_field; + } + + if (str == NULL) + goto truncated_entry; + field = strsep(&str, ":"); + error = parse_entry_type(field, entry); + if (error) + goto malformed_field; + + if (need_qualifier) { + if (str == NULL) { + warnx("malformed ACL: unknown user or group name " + "\"%s\"", qualifier_field); + goto truncated_entry; + } + + error = parse_appended_id(str, entry); + if (error) + goto malformed_field; + } + + return (0); + +truncated_entry: +malformed_field: + acl_delete_entry(aclp, entry); + errno = EINVAL; + return (-1); +} diff --git a/lib/libc/posix1e/acl_get.3 b/lib/libc/posix1e/acl_get.3 new file mode 100644 index 0000000..bd1ca84 --- /dev/null +++ b/lib/libc/posix1e/acl_get.3 @@ -0,0 +1,168 @@ +.\"- +.\" Copyright (c) 2000, 2002 Robert N. M. Watson +.\" All rights reserved. +.\" +.\" This software was developed by Robert Watson for the TrustedBSD Project. +.\" +.\" 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 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 AUTHOR 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. +.\" +.\" $FreeBSD: releng/10.2/lib/libc/posix1e/acl_get.3 213573 2010-10-08 12:40:16Z uqs $ +.\" +.Dd June 25, 2009 +.Dt ACL_GET 3 +.Os +.Sh NAME +.Nm acl_get_fd , +.Nm acl_get_fd_np , +.Nm acl_get_file , +.Nm acl_get_link_np +.Nd get an ACL for a file +.Sh LIBRARY +.Lb libc +.Sh SYNOPSIS +.In sys/types.h +.In sys/acl.h +.Ft acl_t +.Fn acl_get_fd "int fd" +.Ft acl_t +.Fn acl_get_fd_np "int fd" "acl_type_t type" +.Ft acl_t +.Fn acl_get_file "const char *path_p" "acl_type_t type" +.Ft acl_t +.Fn acl_get_link_np "const char *path_p" "acl_type_t type" +.Sh DESCRIPTION +The +.Fn acl_get_fd , +.Fn acl_get_file , +.Fn acl_get_link_np , +and +.Fn acl_get_fd_np +each allow the retrieval of an ACL from a file. +The +.Fn acl_get_fd +is a POSIX.1e call that allows the retrieval of an ACL of type +ACL_TYPE_ACCESS +from a file descriptor. +The +.Fn acl_get_fd_np +function +is a non-portable form of +.Fn acl_get_fd +that allows the retrieval of any type of ACL from a file descriptor. +The +.Fn acl_get_file +function is a POSIX.1e call that allows the retrieval of a +specified type of ACL from a file by name; +.Fn acl_get_link_np +is a non-portable variation on +.Fn acl_get_file +which does not follow a symlink if the target of the call is a +symlink. +.Pp +These functions may cause memory to be allocated. +The caller should free +any releasable memory, when the new ACL is no longer required, by calling +.Xr acl_free 3 +with the +.Va (void *)acl_t +as an argument. +.Pp +The ACL in the working storage is an independent copy of the ACL associated +with the object referred to by +.Va fd . +The ACL in the working storage shall not participate in any access control +decisions. +.Pp +Valid values for the +.Va type +argument are: +.Bl -column -offset 3n "ACL_TYPE_DEFAULT" +.It ACL_TYPE_ACCESS POSIX.1e access ACL +.It ACL_TYPE_DEFAULT POSIX.1e default ACL +.It ACL_TYPE_NFS4 NFSv4 ACL +.El +.Pp +The ACL returned will be branded accordingly. +.Sh IMPLEMENTATION NOTES +.Fx Ns 's +support for POSIX.1e interfaces and features is still under +development at this time. +.Sh RETURN VALUES +Upon successful completion, the function shall return a pointer to the ACL +that was retrieved. +Otherwise, a value of +.Va (acl_t)NULL +shall be returned, and +.Va errno +shall be set to indicate the error. +.Sh ERRORS +If any of the following conditions occur, the +.Fn acl_get_fd +function shall return a value of +.Va (acl_t)NULL +and set +.Va errno +to the corresponding value: +.Bl -tag -width Er +.It Bq Er EACCES +Search permission is denied for a component of the path prefix, or the +object exists and the process does not have appropriate access rights. +.It Bq Er EBADF +The +.Va fd +argument is not a valid file descriptor. +.It Bq Er EINVAL +The ACL type passed is invalid for this file object. +.It Bq Er ENAMETOOLONG +A component of a pathname exceeded 255 characters, or an +entire path name exceeded 1023 characters. +.It Bq Er ENOENT +The named object does not exist, or the +.Va path_p +argument points to an empty string. +.It Bq Er ENOMEM +Insufficient memory available to fulfill request. +.It Bq Er EOPNOTSUPP +The file system does not support ACL retrieval. +.El +.Sh SEE ALSO +.Xr acl 3 , +.Xr acl_free 3 , +.Xr acl_get 3 , +.Xr acl_get_brand_np 3 , +.Xr acl_set 3 , +.Xr posix1e 3 +.Sh STANDARDS +POSIX.1e is described in IEEE POSIX.1e draft 17. +Discussion +of the draft continues on the cross-platform POSIX.1e implementation +mailing list. +To join this list, see the +.Fx +POSIX.1e implementation +page for more information. +.Sh HISTORY +POSIX.1e support was introduced in +.Fx 4.0 , +and development continues. +.Sh AUTHORS +.An Robert N M Watson diff --git a/lib/libc/posix1e/acl_get.c b/lib/libc/posix1e/acl_get.c new file mode 100644 index 0000000..fc712e2 --- /dev/null +++ b/lib/libc/posix1e/acl_get.c @@ -0,0 +1,216 @@ +/*- + * Copyright (c) 1999, 2000, 2001, 2002 Robert N. M. Watson + * All rights reserved. + * + * This software was developed by Robert Watson for the TrustedBSD Project. + * + * 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 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 AUTHOR 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. + */ +/* + * acl_get_fd - syscall wrapper for retrieving access ACL by fd + * acl_get_fd_np - syscall wrapper for retrieving ACL by fd (non-POSIX) + * acl_get_file - syscall wrapper for retrieving ACL by filename + * acl_get_link_np - syscall wrapper for retrieving ACL by filename (NOFOLLOW) + * (non-POSIX) + * acl_get_perm_np() checks if a permission is in the specified + * permset (non-POSIX) + * acl_get_permset() returns the permission set in the ACL entry + * acl_get_qualifier() retrieves the qualifier of the tag from the ACL entry + * acl_get_tag_type() returns the tag type for the ACL entry entry_d + */ + +#include +__FBSDID("$FreeBSD: releng/10.2/lib/libc/posix1e/acl_get.c 208437 2010-05-23 08:12:36Z trasz $"); + +#include +#include "namespace.h" +#include +#include "un-namespace.h" + +#include +#include +#include +#include +#include + +#include "acl_support.h" + +acl_t +acl_get_file(const char *path_p, acl_type_t type) +{ + acl_t aclp; + int error; + + aclp = acl_init(ACL_MAX_ENTRIES); + if (aclp == NULL) + return (NULL); + + type = _acl_type_unold(type); + error = __acl_get_file(path_p, type, &aclp->ats_acl); + if (error) { + acl_free(aclp); + return (NULL); + } + + aclp->ats_acl.acl_maxcnt = ACL_MAX_ENTRIES; + _acl_brand_from_type(aclp, type); + + return (aclp); +} + +acl_t +acl_get_link_np(const char *path_p, acl_type_t type) +{ + acl_t aclp; + int error; + + aclp = acl_init(ACL_MAX_ENTRIES); + if (aclp == NULL) + return (NULL); + + type = _acl_type_unold(type); + error = __acl_get_link(path_p, type, &aclp->ats_acl); + if (error) { + acl_free(aclp); + return (NULL); + } + + aclp->ats_acl.acl_maxcnt = ACL_MAX_ENTRIES; + _acl_brand_from_type(aclp, type); + + return (aclp); +} + +acl_t +acl_get_fd(int fd) +{ + if (fpathconf(fd, _PC_ACL_NFS4) == 1) + return (acl_get_fd_np(fd, ACL_TYPE_NFS4)); + + return (acl_get_fd_np(fd, ACL_TYPE_ACCESS)); +} + +acl_t +acl_get_fd_np(int fd, acl_type_t type) +{ + acl_t aclp; + int error; + + aclp = acl_init(ACL_MAX_ENTRIES); + if (aclp == NULL) + return (NULL); + + type = _acl_type_unold(type); + error = ___acl_get_fd(fd, type, &aclp->ats_acl); + if (error) { + acl_free(aclp); + return (NULL); + } + + aclp->ats_acl.acl_maxcnt = ACL_MAX_ENTRIES; + _acl_brand_from_type(aclp, type); + + return (aclp); +} + +/* + * acl_get_permset() (23.4.17): return via permset_p a descriptor to + * the permission set in the ACL entry entry_d. + */ +int +acl_get_permset(acl_entry_t entry_d, acl_permset_t *permset_p) +{ + + if (entry_d == NULL || permset_p == NULL) { + errno = EINVAL; + return (-1); + } + + *permset_p = &entry_d->ae_perm; + + return (0); +} + +/* + * acl_get_qualifier() (23.4.18): retrieve the qualifier of the tag + * for the ACL entry entry_d. + */ +void * +acl_get_qualifier(acl_entry_t entry_d) +{ + uid_t *retval; + + if (entry_d == NULL) { + errno = EINVAL; + return (NULL); + } + + switch(entry_d->ae_tag) { + case ACL_USER: + case ACL_GROUP: + retval = malloc(sizeof(uid_t)); + if (retval == NULL) + return (NULL); + *retval = entry_d->ae_id; + return (retval); + } + + errno = EINVAL; + return (NULL); +} + +/* + * acl_get_tag_type() (23.4.19): return the tag type for the ACL + * entry entry_p. + */ +int +acl_get_tag_type(acl_entry_t entry_d, acl_tag_t *tag_type_p) +{ + + if (entry_d == NULL || tag_type_p == NULL) { + errno = EINVAL; + return (-1); + } + + *tag_type_p = entry_d->ae_tag; + + return (0); +} + +int +acl_get_entry_type_np(acl_entry_t entry_d, acl_entry_type_t *entry_type_p) +{ + + if (entry_d == NULL || entry_type_p == NULL) { + errno = EINVAL; + return (-1); + } + + if (!_entry_brand_may_be(entry_d, ACL_BRAND_NFS4)) { + errno = EINVAL; + return (-1); + } + + *entry_type_p = entry_d->ae_entry_type; + + return (0); +} diff --git a/lib/libc/posix1e/acl_get_brand_np.3 b/lib/libc/posix1e/acl_get_brand_np.3 new file mode 100644 index 0000000..78b9b4b --- /dev/null +++ b/lib/libc/posix1e/acl_get_brand_np.3 @@ -0,0 +1,86 @@ +.\"- +.\" Copyright (c) 2008, 2009 Edward Tomasz Napierala +.\" 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 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 AUTHOR 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. +.\" +.\" $FreeBSD: releng/10.2/lib/libc/posix1e/acl_get_brand_np.3 204725 2010-03-04 19:38:24Z joel $ +.\" +.Dd June 25, 2009 +.Dt ACL_GET_BRAND_NP 3 +.Os +.Sh NAME +.Nm acl_get_brand_np +.Nd retrieve the ACL brand from an ACL entry +.Sh LIBRARY +.Lb libc +.Sh SYNOPSIS +.In sys/types.h +.In sys/acl.h +.Ft int +.Fn acl_get_brand_np "acl_t acl" "int *brand_p" +.Sh DESCRIPTION +The +.Fn acl_get_brand_np +function +is a non-portable call that returns the ACL brand for the ACL +.Fa acl . +Upon successful completion, the location referred to by the argument +.Fa brand_p +will be set to the ACL brand of the ACL +.Fa acl . +.Pp +Branding is an internal mechanism intended to prevent mixing POSIX.1e +and NFSv4 entries by mistake. +It's also used by the libc to determine how to print out the ACL. +The first call to function that is specific for one particular brand - POSIX.1e +or NFSv4 - "brands" the ACL. +After that, calling function specific to another brand will result in error. +.Sh RETURN VALUES +.Rv -std acl_get_brand_np +.Sh ERRORS +The +.Fn acl_get_brand_np +function fails if: +.Bl -tag -width Er +.It Bq Er EINVAL +Argument +.Fa acl +does not point to a valid ACL. +.El +.Sh SEE ALSO +.Xr acl 3 , +.Xr posix1e 3 +.Sh STANDARDS +POSIX.1e is described in IEEE POSIX.1e draft 17. +.Sh HISTORY +POSIX.1e support was introduced in +.Fx 4.0 . +The +.Fn acl_get_brand_np +function was added in +.Fx 8.0 . +.Sh AUTHORS +The +.Fn acl_get_brand_np +function was written by +.An Edward Tomasz Napierala Aq trasz@FreeBSD.org . diff --git a/lib/libc/posix1e/acl_get_entry.3 b/lib/libc/posix1e/acl_get_entry.3 new file mode 100644 index 0000000..67d6c14 --- /dev/null +++ b/lib/libc/posix1e/acl_get_entry.3 @@ -0,0 +1,145 @@ +.\"- +.\" Copyright (c) 2001 Chris D. Faulhaber +.\" 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 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 AUTHOR 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. +.\" +.\" $FreeBSD: releng/10.2/lib/libc/posix1e/acl_get_entry.3 184607 2008-11-04 00:20:43Z imp $ +.\" +.Dd April 13, 2001 +.Dt ACL_GET_ENTRY 3 +.Os +.Sh NAME +.Nm acl_get_entry +.Nd retrieve an ACL entry from an ACL +.Sh LIBRARY +.Lb libc +.Sh SYNOPSIS +.In sys/types.h +.In sys/acl.h +.Ft int +.Fn acl_get_entry "acl_t acl" "int entry_id" "acl_entry_t *entry_p" +.Sh DESCRIPTION +The +.Fn acl_get_entry +function +is a POSIX.1e call that retrieves a descriptor for an ACL entry +specified by the argument +.Fa entry_d +within the ACL indicated by the argument +.Fa acl . +.Pp +If the value of +.Fa entry_id +is +.Dv ACL_FIRST_ENTRY , +then the function will return in +.Fa entry_p +a descriptor for the first ACL entry within +.Fa acl . +If a call is made to +.Fn acl_get_entry +with +.Fa entry_id +set to +.Dv ACL_NEXT_ENTRY +when there has not been either an initial successful call to +.Fn acl_get_entry , +or a previous successful call to +.Fn acl_create_entry , +.Fn acl_delete_entry , +.Fn acl_dup , +.Fn acl_from_text , +.Fn acl_get_fd , +.Fn acl_get_file , +.Fn acl_set_fd , +.Fn acl_set_file , +or +.Fn acl_valid , +then the result is unspecified. +.Sh RETURN VALUES +If the +.Fn acl_get_entry +function successfully obtains an ACL entry, a value of 1 is returned. +If the ACL has no ACL entries, the +.Fn acl_get_entry +returns a value of 0. +If the value of +.Fa entry_id +is +.Dv ACL_NEXT_ENTRY +and the last ACL entry in the ACL has already been returned by a +previous call to +.Fn acl_get_entry , +a value of 0 will be returned until a successful call with +.Fa entry_id +of +.Dv ACL_FIRST_ENTRY +is made. +Otherwise, a value of -1 will be returned and +the global variable +.Va errno +will be set to indicate the error. +.Sh ERRORS +The +.Fn acl_get_entry +fails if: +.Bl -tag -width Er +.It Bq Er EINVAL +Argument +.Fa acl +does not point to a valid ACL. +Argument +.Fa entry_id +is neither +.Dv ACL_FIRST_ENTRY +nor +.Dv ACL_NEXT_ENTRY . +.El +.Sh SEE ALSO +.Xr acl 3 , +.Xr acl_calc_mask 3 , +.Xr acl_create_entry 3 , +.Xr acl_delete_entry 3 , +.Xr acl_dup 3 , +.Xr acl_from_text 3 , +.Xr acl_get_fd 3 , +.Xr acl_get_file 3 , +.Xr acl_init 3 , +.Xr acl_set_fd 3 , +.Xr acl_set_file 3 , +.Xr acl_valid 3 , +.Xr posix1e 3 +.Sh STANDARDS +POSIX.1e is described in IEEE POSIX.1e draft 17. +.Sh HISTORY +POSIX.1e support was introduced in +.Fx 4.0 . +The +.Fn acl_get_entry +function was added in +.Fx 5.0 . +.Sh AUTHORS +The +.Fn acl_get_entry +function was written by +.An Chris D. Faulhaber Aq jedgar@fxp.org . diff --git a/lib/libc/posix1e/acl_get_entry_type_np.3 b/lib/libc/posix1e/acl_get_entry_type_np.3 new file mode 100644 index 0000000..95e5345 --- /dev/null +++ b/lib/libc/posix1e/acl_get_entry_type_np.3 @@ -0,0 +1,80 @@ +.\"- +.\" Copyright (c) 2008, 2009 Edward Tomasz Napierala +.\" 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 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 AUTHOR 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. +.\" +.\" $FreeBSD: releng/10.2/lib/libc/posix1e/acl_get_entry_type_np.3 204725 2010-03-04 19:38:24Z joel $ +.\" +.Dd June 25, 2009 +.Dt ACL_GET_ENTRY_TYPE_NP 3 +.Os +.Sh NAME +.Nm acl_get_entry_type_np +.Nd retrieve the ACL type from an NFSv4 ACL entry +.Sh LIBRARY +.Lb libc +.Sh SYNOPSIS +.In sys/types.h +.In sys/acl.h +.Ft int +.Fn acl_get_entry_type_np "acl_entry_t entry_d" "acl_entry_type_t *entry_type_p" +.Sh DESCRIPTION +The +.Fn acl_get_entry_type_np +function +is a non-portable call that returns the ACL type for the NFSv4 ACL entry +.Fa entry_d . +Upon successful completion, the location referred to by the argument +.Fa entry_type_p +will be set to the ACL type of the ACL entry +.Fa entry_d . +.Sh RETURN VALUES +.Rv -std acl_get_entry_type_np +.Sh ERRORS +The +.Fn acl_get_entry_type_np +function fails if: +.Bl -tag -width Er +.It Bq Er EINVAL +Argument +.Fa entry_d +is not a valid descriptor for an NFSv4 ACL entry; +.El +.Sh SEE ALSO +.Xr acl 3 , +.Xr acl_set_entry_type_np 3 , +.Xr posix1e 3 +.Sh STANDARDS +POSIX.1e is described in IEEE POSIX.1e draft 17. +.Sh HISTORY +POSIX.1e support was introduced in +.Fx 4.0 . +The +.Fn acl_get_entry_type_np +function was added in +.Fx 8.0 . +.Sh AUTHORS +The +.Fn acl_get_entry_type_np +function was written by +.An Edward Tomasz Napierala Aq trasz@FreeBSD.org . diff --git a/lib/libc/posix1e/acl_get_flag_np.3 b/lib/libc/posix1e/acl_get_flag_np.3 new file mode 100644 index 0000000..9a06aed --- /dev/null +++ b/lib/libc/posix1e/acl_get_flag_np.3 @@ -0,0 +1,94 @@ +.\"- +.\" Copyright (c) 2008, 2009 Edward Tomasz Napierala +.\" 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 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 AUTHOR 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. +.\" +.\" $FreeBSD: releng/10.2/lib/libc/posix1e/acl_get_flag_np.3 275253 2014-11-29 15:50:13Z trasz $ +.\" +.Dd October 30, 2014 +.Dt ACL_GET_FLAG_NP 3 +.Os +.Sh NAME +.Nm acl_get_flag_np +.Nd check if a flag is set in a flagset +.Sh LIBRARY +.Lb libc +.Sh SYNOPSIS +.In sys/types.h +.In sys/acl.h +.Ft int +.Fn acl_get_flag_np "acl_flagset_t flagset_d" "acl_flag_t flag" +.Sh DESCRIPTION +The +.Fn acl_get_flag_np +function +is a non-portable function that checks if a NFSv4 ACL flag is set in +a flagset. +.Sh RETURN VALUES +If the flag in +.Fa flag +is set in the flagset +.Fa flagset_d , +a value of +1 +is returned, otherwise a value of +0 +is returned. +.Sh ERRORS +If any of the following conditions occur, the +.Fn acl_get_flag_np +function will return a value of +\-1 +and set global variable +.Va errno +to the corresponding value: +.Bl -tag -width Er +.It Bq Er EINVAL +Argument +.Fa flag +does not contain a valid ACL flag or argument +.Fa flagset_d +is not a valid ACL flagset. +.El +.Sh SEE ALSO +.Xr acl 3 , +.Xr acl_add_flag_np 3 , +.Xr acl_clear_flags_np 3 , +.Xr acl_delete_flag_np 3 , +.Xr acl_get_flagset_np 3 , +.Xr acl_set_flagset_np 3 , +.Xr posix1e 3 +.Sh STANDARDS +POSIX.1e is described in IEEE POSIX.1e draft 17. +.Sh HISTORY +POSIX.1e support was introduced in +.Fx 4.0 . +The +.Fn acl_get_flag_np +function was added in +.Fx 8.0 . +.Sh AUTHORS +The +.Fn acl_get_flag_np +function was written by +.An Edward Tomasz Napierala Aq trasz@FreeBSD.org . diff --git a/lib/libc/posix1e/acl_get_flagset_np.3 b/lib/libc/posix1e/acl_get_flagset_np.3 new file mode 100644 index 0000000..a25b738 --- /dev/null +++ b/lib/libc/posix1e/acl_get_flagset_np.3 @@ -0,0 +1,83 @@ +.\"- +.\" Copyright (c) 2008, 2009 Edward Tomasz Napierala +.\" 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 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 AUTHOR 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. +.\" +.\" $FreeBSD: releng/10.2/lib/libc/posix1e/acl_get_flagset_np.3 275253 2014-11-29 15:50:13Z trasz $ +.\" +.Dd October 30, 2014 +.Dt ACL_GET_FLAGSET_NP 3 +.Os +.Sh NAME +.Nm acl_get_flagset_np +.Nd retrieve flagset from an NFSv4 ACL entry +.Sh LIBRARY +.Lb libc +.Sh SYNOPSIS +.In sys/types.h +.In sys/acl.h +.Ft int +.Fn acl_get_flagset_np "acl_entry_t entry_d" "acl_flagset_t *flagset_p" +.Sh DESCRIPTION +The +.Fn acl_get_flagset_np +function +is a non-portable call that returns via +.Fa flagset_np_p +a descriptor to the flagset in the NFSv4 ACL entry +.Fa entry_d . +Subsequent operations using the returned flagset operate +on the flagset within the ACL entry. +.Sh RETURN VALUES +.Rv -std acl_get_flagset_np +.Sh ERRORS +The +.Fn acl_get_flagset_np +function fails if: +.Bl -tag -width Er +.It Bq Er EINVAL +Argument +.Fa entry_d +is not a valid descriptor for an ACL entry. +.El +.Sh SEE ALSO +.Xr acl 3 , +.Xr acl_add_flag_np 3 , +.Xr acl_clear_flags_np 3 , +.Xr acl_delete_flag_np 3 , +.Xr acl_set_flagset_np 3 , +.Xr posix1e 3 +.Sh STANDARDS +POSIX.1e is described in IEEE POSIX.1e draft 17. +.Sh HISTORY +POSIX.1e support was introduced in +.Fx 4.0 . +The +.Fn acl_get_flagset_np +function was added in +.Fx 8.0 . +.Sh AUTHORS +The +.Fn acl_get_flagset_np +function was written by +.An Edward Tomasz Napierala Aq trasz@FreeBSD.org . diff --git a/lib/libc/posix1e/acl_get_perm_np.3 b/lib/libc/posix1e/acl_get_perm_np.3 new file mode 100644 index 0000000..1fb007e --- /dev/null +++ b/lib/libc/posix1e/acl_get_perm_np.3 @@ -0,0 +1,94 @@ +.\"- +.\" Copyright (c) 2001 Chris D. Faulhaber +.\" 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 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 AUTHOR 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. +.\" +.\" $FreeBSD: releng/10.2/lib/libc/posix1e/acl_get_perm_np.3 184607 2008-11-04 00:20:43Z imp $ +.\" +.Dd April 10, 2001 +.Dt ACL_GET_PERM_NP 3 +.Os +.Sh NAME +.Nm acl_get_perm_np +.Nd "check if a permission is set in a permission set" +.Sh LIBRARY +.Lb libc +.Sh SYNOPSIS +.In sys/types.h +.In sys/acl.h +.Ft int +.Fn acl_get_perm_np "acl_permset_t permset_d" "acl_perm_t perm" +.Sh DESCRIPTION +The +.Fn acl_get_perm_np +function +is a non-portable function that checks if a permission is set in +a permission set. +.Sh RETURN VALUES +If the permission in +.Fa perm +is set in the permission set +.Fa permset_d , +a value of +1 +is returned, otherwise a value of +0 +is returned. +.Sh ERRORS +If any of the following conditions occur, the +.Fn acl_get_perm_np +function will return a value of +\-1 +and set global variable +.Va errno +to the corresponding value: +.Bl -tag -width Er +.It Bq Er EINVAL +Argument +.Fa perm +does not contain a valid ACL permission or argument +.Fa permset_d +is not a valid ACL permset. +.El +.Sh SEE ALSO +.Xr acl 3 , +.Xr acl_add_perm 3 , +.Xr acl_clear_perms 3 , +.Xr acl_delete_perm 3 , +.Xr acl_get_permset 3 , +.Xr acl_set_permset 3 , +.Xr posix1e 3 +.Sh STANDARDS +POSIX.1e is described in IEEE POSIX.1e draft 17. +.Sh HISTORY +POSIX.1e support was introduced in +.Fx 4.0 . +The +.Fn acl_get_perm_np +function was added in +.Fx 5.0 . +.Sh AUTHORS +The +.Fn acl_get_perm_np +function was written by +.An Chris D. Faulhaber Aq jedgar@fxp.org . diff --git a/lib/libc/posix1e/acl_get_permset.3 b/lib/libc/posix1e/acl_get_permset.3 new file mode 100644 index 0000000..0c84964 --- /dev/null +++ b/lib/libc/posix1e/acl_get_permset.3 @@ -0,0 +1,83 @@ +.\"- +.\" Copyright (c) 2001 Chris D. Faulhaber +.\" 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 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 AUTHOR 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. +.\" +.\" $FreeBSD: releng/10.2/lib/libc/posix1e/acl_get_permset.3 184607 2008-11-04 00:20:43Z imp $ +.\" +.Dd March 10, 2001 +.Dt ACL_GET_PERMSET 3 +.Os +.Sh NAME +.Nm acl_get_permset +.Nd retrieve permission set from an ACL entry +.Sh LIBRARY +.Lb libc +.Sh SYNOPSIS +.In sys/types.h +.In sys/acl.h +.Ft int +.Fn acl_get_permset "acl_entry_t entry_d" "acl_permset_t *permset_p" +.Sh DESCRIPTION +The +.Fn acl_get_permset +function +is a POSIX.1e call that returns via +.Fa permset_p +a descriptor to the permission set in the ACL entry +.Fa entry_d . +Subsequent operations using the returned permission set operate +on the permission set within the ACL entry. +.Sh RETURN VALUES +.Rv -std acl_get_permset +.Sh ERRORS +The +.Fn acl_get_permset +function fails if: +.Bl -tag -width Er +.It Bq Er EINVAL +Argument +.Fa entry_d +is not a valid descriptor for an ACL entry. +.El +.Sh SEE ALSO +.Xr acl 3 , +.Xr acl_add_perm 3 , +.Xr acl_clear_perms 3 , +.Xr acl_delete_perm 3 , +.Xr acl_set_permset 3 , +.Xr posix1e 3 +.Sh STANDARDS +POSIX.1e is described in IEEE POSIX.1e draft 17. +.Sh HISTORY +POSIX.1e support was introduced in +.Fx 4.0 . +The +.Fn acl_get_permset +function was added in +.Fx 5.0 . +.Sh AUTHORS +The +.Fn acl_get_permset +function was written by +.An Chris D. Faulhaber Aq jedgar@fxp.org . diff --git a/lib/libc/posix1e/acl_get_qualifier.3 b/lib/libc/posix1e/acl_get_qualifier.3 new file mode 100644 index 0000000..68b1494 --- /dev/null +++ b/lib/libc/posix1e/acl_get_qualifier.3 @@ -0,0 +1,140 @@ +.\"- +.\" Copyright (c) 2001 Chris D. Faulhaber +.\" 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 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 AUTHOR 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. +.\" +.\" $FreeBSD: releng/10.2/lib/libc/posix1e/acl_get_qualifier.3 184607 2008-11-04 00:20:43Z imp $ +.\" +.Dd March 13, 2001 +.Dt ACL_GET_QUALIFIER 3 +.Os +.Sh NAME +.Nm acl_get_qualifier +.Nd retrieve the qualifier from an ACL entry +.Sh LIBRARY +.Lb libc +.Sh SYNOPSIS +.In sys/types.h +.In sys/acl.h +.Ft void * +.Fn acl_get_qualifier "acl_entry_t entry_d" +.Sh DESCRIPTION +The +.Fn acl_get_qualifier +function +is a POSIX.1e call that retrieves the qualifier of the tag for +the ACL entry indicated by the argument +.Fa entry_d +into working storage and returns a pointer to that storage. +.Pp +If the value of the tag type in the ACL entry referred to by +.Fa entry_d +is +.Dv ACL_USER , +then the value returned by +.Fn acl_get_qualifier +will be a pointer to type +.Vt uid_t . +.Pp +If the value of the tag type in +the ACL entry referred to by +.Fa entry_d +is +.Dv ACL_GROUP , +then the value returned by +.Fn acl_get_qualifier +will be a pointer to type +.Vt gid_t . +.Pp +If the value of the tag type in the ACL entry referred to by +.Fa entry_d +is +.Dv ACL_UNDEFINED_TAG , ACL_USER_OBJ , ACL_GROUP_OBJ , +.Dv ACL_OTHER , ACL_MASK , +or an implementation-defined value for which a qualifier +is not supported, then +.Fn acl_get_qualifier +will return a value of +.Vt ( void * ) Ns Dv NULL +and the function will fail. +.Pp +This function may cause memory to be allocated. +The caller should +free any releasable memory, when the new qualifier is no longer +required, by calling +.Fn acl_free +with +.Vt void * +as the argument. +.Sh RETURN VALUES +The +.Fn acl_get_qualifier +function returns a pointer to the allocated storage if successful; +otherwise a +.Dv NULL +pointer is returned and the global variable +.Va errno +is set to indicate the error. +.Sh ERRORS +The +.Fn acl_get_qualifier +fails if: +.Bl -tag -width Er +.It Bq Er EINVAL +Argument +.Fa entry_d +does not point to a valid descriptor for an ACL entry. +The +value of the tag type in the ACL entry referenced by argument +.Fa entry_d +is not +.Dv ACL_USER +or +.Dv ACL_GROUP . +.It Bq Er ENOMEM +The value to be returned requires more memory than is allowed +by the hardware or system-imposed memory management constraints. +.El +.Sh SEE ALSO +.Xr acl 3 , +.Xr acl_create_entry 3 , +.Xr acl_free 3 , +.Xr acl_get_entry 3 , +.Xr acl_get_tag_type 3 , +.Xr acl_set_qualifier 3 , +.Xr acl_set_tag_type 3 , +.Xr posix1e 3 +.Sh STANDARDS +POSIX.1e is described in IEEE POSIX.1e draft 17. +.Sh HISTORY +POSIX.1e support was introduced in +.Fx 4.0 . +The +.Fn acl_get_qualifier +function was added in +.Fx 5.0 . +.Sh AUTHORS +The +.Fn acl_get_qualifier +function was written by +.An Chris D. Faulhaber Aq jedgar@fxp.org . diff --git a/lib/libc/posix1e/acl_get_tag_type.3 b/lib/libc/posix1e/acl_get_tag_type.3 new file mode 100644 index 0000000..37cf258 --- /dev/null +++ b/lib/libc/posix1e/acl_get_tag_type.3 @@ -0,0 +1,85 @@ +.\"- +.\" Copyright (c) 2001 Chris D. Faulhaber +.\" 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 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 AUTHOR 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. +.\" +.\" $FreeBSD: releng/10.2/lib/libc/posix1e/acl_get_tag_type.3 184607 2008-11-04 00:20:43Z imp $ +.\" +.Dd March 10, 2001 +.Dt ACL_GET_TAG_TYPE 3 +.Os +.Sh NAME +.Nm acl_get_tag_type +.Nd retrieve the tag type from an ACL entry +.Sh LIBRARY +.Lb libc +.Sh SYNOPSIS +.In sys/types.h +.In sys/acl.h +.Ft int +.Fn acl_get_tag_type "acl_entry_t entry_d" "acl_tag_t *tag_type_p" +.Sh DESCRIPTION +The +.Fn acl_get_tag_type +function +is a POSIX.1e call that returns the tag type for the ACL entry +.Fa entry_d . +Upon successful completion, the location referred to by the argument +.Fa tag_type_p +will be set to the tag type of the ACL entry +.Fa entry_d . +.Sh RETURN VALUES +.Rv -std acl_get_tag_type +.Sh ERRORS +The +.Fn acl_get_tag_type +function fails if: +.Bl -tag -width Er +.It Bq Er EINVAL +Argument +.Fa entry_d +is not a valid descriptor for an ACL entry; +.El +.Sh SEE ALSO +.Xr acl 3 , +.Xr acl_create_entry 3 , +.Xr acl_get_entry 3 , +.Xr acl_get_qualifier 3 , +.Xr acl_init 3 , +.Xr acl_set_qualifier 3 , +.Xr acl_set_tag_type 3 , +.Xr posix1e 3 +.Sh STANDARDS +POSIX.1e is described in IEEE POSIX.1e draft 17. +.Sh HISTORY +POSIX.1e support was introduced in +.Fx 4.0 . +The +.Fn acl_get_tag_type +function was added in +.Fx 5.0 . +.Sh AUTHORS +The +.Fn acl_get_tag_type +function was written by +.An Chris D. Faulhaber Aq jedgar@fxp.org . diff --git a/lib/libc/posix1e/acl_id_to_name.c b/lib/libc/posix1e/acl_id_to_name.c new file mode 100644 index 0000000..783b8a4 --- /dev/null +++ b/lib/libc/posix1e/acl_id_to_name.c @@ -0,0 +1,100 @@ +/*- + * Copyright (c) 1999-2001, 2008 Robert N. M. Watson + * 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 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 AUTHOR 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. + */ +/* + * Support functionality for the POSIX.1e ACL interface + * These calls are intended only to be called within the library. + */ + +#include +__FBSDID("$FreeBSD: releng/10.2/lib/libc/posix1e/acl_id_to_name.c 209147 2010-06-14 02:26:13Z kientzle $"); + +#include +#include "namespace.h" +#include +#include "un-namespace.h" +#include +#include +#include +#include +#include +#include +#include + +#include "acl_support.h" + +/* + * Given a uid/gid, return a username/groupname for the text form of an ACL. + * Note that we truncate user and group names, rather than error out, as + * this is consistent with other tools manipulating user and group names. + * XXX NOT THREAD SAFE, RELIES ON GETPWUID, GETGRGID + * XXX USES *PW* AND *GR* WHICH ARE STATEFUL AND THEREFORE THIS ROUTINE + * MAY HAVE SIDE-EFFECTS + */ +int +_posix1e_acl_id_to_name(acl_tag_t tag, uid_t id, ssize_t buf_len, char *buf, + int flags) +{ + struct group *g; + struct passwd *p; + int i; + + switch(tag) { + case ACL_USER: + if (flags & ACL_TEXT_NUMERIC_IDS) + p = NULL; + else + p = getpwuid(id); + if (!p) + i = snprintf(buf, buf_len, "%d", id); + else + i = snprintf(buf, buf_len, "%s", p->pw_name); + + if (i < 0) { + errno = ENOMEM; + return (-1); + } + return (0); + + case ACL_GROUP: + if (flags & ACL_TEXT_NUMERIC_IDS) + g = NULL; + else + g = getgrgid(id); + if (g == NULL) + i = snprintf(buf, buf_len, "%d", id); + else + i = snprintf(buf, buf_len, "%s", g->gr_name); + + if (i < 0) { + errno = ENOMEM; + return (-1); + } + return (0); + + default: + return (EINVAL); + } +} diff --git a/lib/libc/posix1e/acl_init.3 b/lib/libc/posix1e/acl_init.3 new file mode 100644 index 0000000..e298454 --- /dev/null +++ b/lib/libc/posix1e/acl_init.3 @@ -0,0 +1,111 @@ +.\"- +.\" Copyright (c) 2000, 2002 Robert N. M. Watson +.\" All rights reserved. +.\" +.\" This software was developed by Robert Watson for the TrustedBSD Project. +.\" +.\" 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 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 AUTHOR 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. +.\" +.\" $FreeBSD: releng/10.2/lib/libc/posix1e/acl_init.3 131504 2004-07-02 23:52:20Z ru $ +.\" +.Dd January 28, 2000 +.Dt ACL_INIT 3 +.Os +.Sh NAME +.Nm acl_init +.Nd initialize ACL working storage +.Sh LIBRARY +.Lb libc +.Sh SYNOPSIS +.In sys/types.h +.In sys/acl.h +.Ft acl_t +.Fn acl_init "int count" +.Sh DESCRIPTION +The +.Fn acl_init +function allocates and initializes the working storage for an ACL of at +least +.Va count +ACL entries. +A pointer to the working storage is returned. +The working +storage allocated to contain the ACL is freed by a call to +.Xr acl_free 3 . +When the area is first allocated, it shall contain an ACL that contains +no ACL entries. +.Pp +This function may cause memory to be allocated. +The caller should free any +releasable memory, when the new ACL is no longer required, by calling +.Xr acl_free 3 +with the +.Va (void*)acl_t +as an argument. +.Sh IMPLEMENTATION NOTES +.Fx Ns 's +support for POSIX.1e interfaces and features is still under +development at this time. +.Sh RETURN VALUES +Upon successful completion, this function shall return a pointer to the +working storage. +Otherwise, a value of +.Va (acl_t)NULL +shall be returned, and +.Va errno +shall be set to indicate the error. +.Sh ERRORS +If any of the following conditions occur, the +.Fn acl_init +function shall return a value of +.Va (acl_t)NULL +and set +.Va errno +to the corresponding value: +.Bl -tag -width Er +.It Bq Er EINVAL +The value of count is less than zero. +.It Bq Er ENOMEM +The +.Va acl_t +to be returned requires more memory than is allowed by the hardware or +system-imposed memory management constraints. +.El +.Sh SEE ALSO +.Xr acl 3 , +.Xr acl_free 3 , +.Xr posix1e 3 +.Sh STANDARDS +POSIX.1e is described in IEEE POSIX.1e draft 17. +Discussion +of the draft continues on the cross-platform POSIX.1e implementation +mailing list. +To join this list, see the +.Fx +POSIX.1e implementation +page for more information. +.Sh HISTORY +POSIX.1e support was introduced in +.Fx 4.0 , +and development continues. +.Sh AUTHORS +.An Robert N M Watson diff --git a/lib/libc/posix1e/acl_init.c b/lib/libc/posix1e/acl_init.c new file mode 100644 index 0000000..bc512d8 --- /dev/null +++ b/lib/libc/posix1e/acl_init.c @@ -0,0 +1,93 @@ +/*- + * Copyright (c) 1999, 2000, 2001 Robert N. M. Watson + * 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 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 AUTHOR 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. + */ +/* + * acl_init -- return a fresh acl structure + * acl_dup -- duplicate an acl and return the new copy + */ + +#include +__FBSDID("$FreeBSD: releng/10.2/lib/libc/posix1e/acl_init.c 194955 2009-06-25 12:46:59Z trasz $"); + +#include +#include "namespace.h" +#include +#include "un-namespace.h" +#include +#include +#include +#include + +#include "acl_support.h" + +#ifndef CTASSERT +#define CTASSERT(x) _CTASSERT(x, __LINE__) +#define _CTASSERT(x, y) __CTASSERT(x, y) +#define __CTASSERT(x, y) typedef char __assert_ ## y [(x) ? 1 : -1] +#endif + +CTASSERT(1 << _ACL_T_ALIGNMENT_BITS > sizeof(struct acl_t_struct)); + +acl_t +acl_init(int count) +{ + int error; + acl_t acl; + + if (count > ACL_MAX_ENTRIES) { + errno = ENOMEM; + return (NULL); + } + if (count < 0) { + errno = EINVAL; + return (NULL); + } + + error = posix_memalign((void *)&acl, 1 << _ACL_T_ALIGNMENT_BITS, + sizeof(struct acl_t_struct)); + if (error) + return (NULL); + + bzero(acl, sizeof(struct acl_t_struct)); + acl->ats_brand = ACL_BRAND_UNKNOWN; + acl->ats_acl.acl_maxcnt = ACL_MAX_ENTRIES; + + return (acl); +} + +acl_t +acl_dup(acl_t acl) +{ + acl_t acl_new; + + acl_new = acl_init(ACL_MAX_ENTRIES); + if (acl_new != NULL) { + *acl_new = *acl; + acl->ats_cur_entry = 0; + acl_new->ats_cur_entry = 0; + } + + return (acl_new); +} diff --git a/lib/libc/posix1e/acl_is_trivial_np.3 b/lib/libc/posix1e/acl_is_trivial_np.3 new file mode 100644 index 0000000..11d4299 --- /dev/null +++ b/lib/libc/posix1e/acl_is_trivial_np.3 @@ -0,0 +1,85 @@ +.\"- +.\" Copyright (c) 2008, 2009 Edward Tomasz Napierala +.\" All rights reserved. +.\" +.\" This software was developed by Robert Watson for the TrustedBSD Project. +.\" +.\" 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 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 AUTHOR 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. +.\" +.\" $FreeBSD: releng/10.2/lib/libc/posix1e/acl_is_trivial_np.3 258877 2013-12-03 18:28:18Z trasz $ +.\" +.Dd November 12, 2013 +.Dt ACL_STRIP_NP 3 +.Os +.Sh NAME +.Nm acl_is_trivial_np +.Nd determine whether ACL is trivial +.Sh LIBRARY +.Lb libc +.Sh SYNOPSIS +.In sys/types.h +.In sys/acl.h +.Ft int +.Fn acl_is_trivial_np "const acl_t aclp" "int *trivialp" +.Sh DESCRIPTION +The +.Fn acl_is_trivial +function determines whether the ACL pointed to by the argument +.Va acl +is trivial. +Upon successful completion, the location referred to by the argument +.Fa trivialp +will be set to 1, if the ACL +.Fa aclp +points to is trivial, or 0 if it's not. +.Pp +ACL is trivial if it can be fully expressed as a file mode without losing +any access rules. +For POSIX.1e ACLs, ACL is trivial if it has the three required entries, +one for owner, one for owning group, and one for other. +For NFSv4 ACLs, ACL is trivial if it is identical to the ACL generated by +.Fn acl_strip_np 3 . +Files that have non-trivial ACL have a plus sign appended after mode bits +in "ls -l" output. +.Sh RETURN VALUES +.Rv -std acl_get_tag_type +.Sh SEE ALSO +.Xr acl 3 , +.Xr posix1e 3 +.Sh STANDARDS +POSIX.1e is described in IEEE POSIX.1e draft 17. +Discussion +of the draft continues on the cross-platform POSIX.1e implementation +mailing list. +To join this list, see the +.Fx +POSIX.1e implementation +page for more information. +.Sh HISTORY +POSIX.1e support was introduced in +.Fx 4.0 . +The +.Fn acl_is_trivial_np +function was added in +.Fx 8.0 . +.Sh AUTHORS +.An Edward Tomasz Napierala Aq trasz@FreeBSD.org . diff --git a/lib/libc/posix1e/acl_perm.c b/lib/libc/posix1e/acl_perm.c new file mode 100644 index 0000000..ae60081 --- /dev/null +++ b/lib/libc/posix1e/acl_perm.c @@ -0,0 +1,128 @@ +/* + * Copyright (c) 2001-2002 Chris D. Faulhaber + * 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 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 AUTHOR 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 +__FBSDID("$FreeBSD: releng/10.2/lib/libc/posix1e/acl_perm.c 208437 2010-05-23 08:12:36Z trasz $"); + +#include +#include "namespace.h" +#include +#include "un-namespace.h" + +#include +#include + +static int +_perm_is_invalid(acl_perm_t perm) +{ + + /* Check if more than a single bit is set. */ + if ((perm & -perm) == perm && + (perm & (ACL_POSIX1E_BITS | ACL_NFS4_PERM_BITS)) == perm) + return (0); + + errno = EINVAL; + + return (1); +} + +/* + * acl_add_perm() (23.4.1): add the permission contained in perm to the + * permission set permset_d + */ +int +acl_add_perm(acl_permset_t permset_d, acl_perm_t perm) +{ + + if (permset_d == NULL) { + errno = EINVAL; + return (-1); + } + + if (_perm_is_invalid(perm)) + return (-1); + + *permset_d |= perm; + + return (0); +} + +/* + * acl_clear_perms() (23.4.3): clear all permisions from the permission + * set permset_d + */ +int +acl_clear_perms(acl_permset_t permset_d) +{ + + if (permset_d == NULL) { + errno = EINVAL; + return (-1); + } + + *permset_d = ACL_PERM_NONE; + + return (0); +} + +/* + * acl_delete_perm() (23.4.10): remove the permission in perm from the + * permission set permset_d + */ +int +acl_delete_perm(acl_permset_t permset_d, acl_perm_t perm) +{ + + if (permset_d == NULL) { + errno = EINVAL; + return (-1); + } + + if (_perm_is_invalid(perm)) + return (-1); + + *permset_d &= ~perm; + + return (0); +} + +int +acl_get_perm_np(acl_permset_t permset_d, acl_perm_t perm) +{ + + if (permset_d == NULL) { + errno = EINVAL; + return (-1); + } + + if (_perm_is_invalid(perm)) + return (-1); + + if (*permset_d & perm) + return (1); + + return (0); +} diff --git a/lib/libc/posix1e/acl_set.3 b/lib/libc/posix1e/acl_set.3 new file mode 100644 index 0000000..7a1e45d --- /dev/null +++ b/lib/libc/posix1e/acl_set.3 @@ -0,0 +1,157 @@ +.\"- +.\" Copyright (c) 2000, 2002 Robert N. M. Watson +.\" All rights reserved. +.\" +.\" This software was developed by Robert Watson for the TrustedBSD Project. +.\" +.\" 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 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 AUTHOR 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. +.\" +.\" $FreeBSD: releng/10.2/lib/libc/posix1e/acl_set.3 213573 2010-10-08 12:40:16Z uqs $ +.\" +.Dd June 25, 2009 +.Dt ACL_SET 3 +.Os +.Sh NAME +.Nm acl_set_fd , +.Nm acl_set_fd_np , +.Nm acl_set_file , +.Nm acl_set_link_np +.Nd set an ACL for a file +.Sh LIBRARY +.Lb libc +.Sh SYNOPSIS +.In sys/types.h +.In sys/acl.h +.Ft int +.Fn acl_set_fd "int fd" "acl_t acl" +.Ft int +.Fn acl_set_fd_np "int fd" "acl_t acl" "acl_type_t type" +.Ft int +.Fn acl_set_file "const char *path_p" "acl_type_t type" "acl_t acl" +.Ft int +.Fn acl_set_link_np "const char *path_p" "acl_type_t type" "acl_t acl" +.Sh DESCRIPTION +The +.Fn acl_set_fd , +.Fn acl_set_fd_np , +.Fn acl_set_file , +and +.Fn acl_set_link_np +each associate an ACL with an object referred to by +.Va fd +or +.Va path_p . +The +.Fn acl_set_fd_np +and +.Fn acl_set_link_np +functions are not POSIX.1e calls. +The +.Fn acl_set_fd +function allows only the setting of ACLs of type ACL_TYPE_ACCESS +where as +.Fn acl_set_fd_np +allows the setting of ACLs of any type. +The +.Fn acl_set_link_np +function acts on a symlink rather than its target, if the target of the +path is a symlink. +.Pp +Valid values for the +.Va type +argument are: +.Bl -column -offset 3n "ACL_TYPE_DEFAULT" +.It ACL_TYPE_ACCESS POSIX.1e access ACL +.It ACL_TYPE_DEFAULT POSIX.1e default ACL +.It ACL_TYPE_NFS4 NFSv4 ACL +.El +.Pp +Trying to set ACL_TYPE_NFS4 with +.Va acl +branded as POSIX.1e, or ACL_TYPE_ACCESS or ACL_TYPE_DEFAULT with ACL +branded as NFSv4, will result in error. +.Sh IMPLEMENTATION NOTES +.Fx Ns 's +support for POSIX.1e interfaces and features is still under +development at this time. +.Sh RETURN VALUES +.Rv -std +.Sh ERRORS +If any of the following conditions occur, these functions shall return +-1 and set +.Va errno +to the corresponding value: +.Bl -tag -width Er +.It Bq Er EACCES +Search permission is denied for a component of the path prefix, or the +object exists and the process does not have appropriate access rights. +.It Bq Er EBADF +The +.Va fd +argument is not a valid file descriptor. +.It Bq Er EINVAL +Argument +.Va acl +does not point to a valid ACL for this object, or the ACL type +specified in +.Va type +is invalid for this object, or there is branding mismatch. +.It Bq Er ENAMETOOLONG +A component of a pathname exceeded 255 characters, or an +entire path name exceeded 1023 characters. +.It Bq Er ENOENT +The named object does not exist, or the +.Va path_p +argument points to an empty string. +.It Bq Er ENOMEM +Insufficient memory available to fulfill request. +.It Bq Er ENOSPC +The directory or file system that would contain the new ACL cannot be +extended, or the file system is out of file allocation resources. +.It Bq Er EOPNOTSUPP +The file system does not support ACL retrieval. +.It Bq Er EROFS +This function requires modification of a file system which is currently +read-only. +.El +.Sh SEE ALSO +.Xr acl 3 , +.Xr acl_delete 3 , +.Xr acl_get 3 , +.Xr acl_get_brand_np 3 , +.Xr acl_valid 3 , +.Xr posix1e 3 +.Sh STANDARDS +POSIX.1e is described in IEEE POSIX.1e draft 17. +Discussion +of the draft continues on the cross-platform POSIX.1e implementation +mailing list. +To join this list, see the +.Fx +POSIX.1e implementation +page for more information. +.Sh HISTORY +POSIX.1e support was introduced in +.Fx 4.0 , +and development continues. +.Sh AUTHORS +.An Robert N M Watson diff --git a/lib/libc/posix1e/acl_set.c b/lib/libc/posix1e/acl_set.c new file mode 100644 index 0000000..00f959b --- /dev/null +++ b/lib/libc/posix1e/acl_set.c @@ -0,0 +1,253 @@ +/*- + * Copyright (c) 1999, 2000, 2001, 2002 Robert N. M. Watson + * All rights reserved. + * + * This software was developed by Robert Watson for the TrustedBSD Project. + * + * 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 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 AUTHOR 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. + */ +/* + * acl_set_file -- set a file/directory ACL by name + */ + +#include +__FBSDID("$FreeBSD: releng/10.2/lib/libc/posix1e/acl_set.c 208785 2010-06-03 14:29:17Z trasz $"); + +#include +#include "namespace.h" +#include +#include "un-namespace.h" + +#include +#include +#include +#include + +#include "acl_support.h" + +/* + * For POSIX.1e-semantic ACLs, do a presort so the kernel doesn't have to + * (the POSIX.1e semantic code will reject unsorted ACL submission). If it's + * not a semantic that the library knows about, just submit it flat and + * assume the caller knows what they're up to. + */ +int +acl_set_file(const char *path_p, acl_type_t type, acl_t acl) +{ + + if (acl == NULL || path_p == NULL) { + errno = EINVAL; + return (-1); + } + type = _acl_type_unold(type); + if (_acl_type_not_valid_for_acl(acl, type)) { + errno = EINVAL; + return (-1); + } + if (_posix1e_acl(acl, type)) + _posix1e_acl_sort(acl); + + acl->ats_cur_entry = 0; + + return (__acl_set_file(path_p, type, &acl->ats_acl)); +} + +int +acl_set_link_np(const char *path_p, acl_type_t type, acl_t acl) +{ + + if (acl == NULL || path_p == NULL) { + errno = EINVAL; + return (-1); + } + type = _acl_type_unold(type); + if (_acl_type_not_valid_for_acl(acl, type)) { + errno = EINVAL; + return (-1); + } + if (_posix1e_acl(acl, type)) + _posix1e_acl_sort(acl); + + acl->ats_cur_entry = 0; + + return (__acl_set_link(path_p, type, &acl->ats_acl)); +} + +int +acl_set_fd(int fd, acl_t acl) +{ + + if (fpathconf(fd, _PC_ACL_NFS4) == 1) + return (acl_set_fd_np(fd, acl, ACL_TYPE_NFS4)); + + return (acl_set_fd_np(fd, acl, ACL_TYPE_ACCESS)); +} + +int +acl_set_fd_np(int fd, acl_t acl, acl_type_t type) +{ + + if (acl == NULL) { + errno = EINVAL; + return (-1); + } + type = _acl_type_unold(type); + if (_acl_type_not_valid_for_acl(acl, type)) { + errno = EINVAL; + return (-1); + } + if (_posix1e_acl(acl, type)) + _posix1e_acl_sort(acl); + + acl->ats_cur_entry = 0; + + return (___acl_set_fd(fd, type, &acl->ats_acl)); +} + +/* + * acl_set_permset() (23.4.23): sets the permissions of ACL entry entry_d + * with the permissions in permset_d + */ +int +acl_set_permset(acl_entry_t entry_d, acl_permset_t permset_d) +{ + + if (!entry_d) { + errno = EINVAL; + return (-1); + } + + if ((*permset_d & ACL_POSIX1E_BITS) != *permset_d) { + if ((*permset_d & ACL_NFS4_PERM_BITS) != *permset_d) { + errno = EINVAL; + return (-1); + } + if (!_entry_brand_may_be(entry_d, ACL_BRAND_NFS4)) { + errno = EINVAL; + return (-1); + } + _entry_brand_as(entry_d, ACL_BRAND_NFS4); + } + + entry_d->ae_perm = *permset_d; + + return (0); +} + +/* + * acl_set_qualifier() sets the qualifier (ae_id) of the tag for + * ACL entry entry_d to the value referred to by tag_qualifier_p + */ +int +acl_set_qualifier(acl_entry_t entry_d, const void *tag_qualifier_p) +{ + + if (!entry_d || !tag_qualifier_p) { + errno = EINVAL; + return (-1); + } + switch(entry_d->ae_tag) { + case ACL_USER: + case ACL_GROUP: + entry_d->ae_id = *(uid_t *)tag_qualifier_p; + break; + default: + errno = EINVAL; + return (-1); + } + + return (0); +} + +/* + * acl_set_tag_type() sets the tag type for ACL entry entry_d to the + * value of tag_type + */ +int +acl_set_tag_type(acl_entry_t entry_d, acl_tag_t tag_type) +{ + + if (entry_d == NULL) { + errno = EINVAL; + return (-1); + } + + switch(tag_type) { + case ACL_OTHER: + case ACL_MASK: + if (!_entry_brand_may_be(entry_d, ACL_BRAND_POSIX)) { + errno = EINVAL; + return (-1); + } + _entry_brand_as(entry_d, ACL_BRAND_POSIX); + break; + case ACL_EVERYONE: + if (!_entry_brand_may_be(entry_d, ACL_BRAND_NFS4)) { + errno = EINVAL; + return (-1); + } + _entry_brand_as(entry_d, ACL_BRAND_NFS4); + break; + } + + switch(tag_type) { + case ACL_USER_OBJ: + case ACL_USER: + case ACL_GROUP_OBJ: + case ACL_GROUP: + case ACL_MASK: + case ACL_OTHER: + case ACL_EVERYONE: + entry_d->ae_tag = tag_type; + return (0); + } + + errno = EINVAL; + return (-1); +} + +int +acl_set_entry_type_np(acl_entry_t entry_d, acl_entry_type_t entry_type) +{ + + if (entry_d == NULL) { + errno = EINVAL; + return (-1); + } + if (!_entry_brand_may_be(entry_d, ACL_BRAND_NFS4)) { + errno = EINVAL; + return (-1); + } + _entry_brand_as(entry_d, ACL_BRAND_NFS4); + + switch (entry_type) { + case ACL_ENTRY_TYPE_ALLOW: + case ACL_ENTRY_TYPE_DENY: + case ACL_ENTRY_TYPE_AUDIT: + case ACL_ENTRY_TYPE_ALARM: + entry_d->ae_entry_type = entry_type; + return (0); + } + + errno = EINVAL; + return (-1); +} diff --git a/lib/libc/posix1e/acl_set_entry_type_np.3 b/lib/libc/posix1e/acl_set_entry_type_np.3 new file mode 100644 index 0000000..9adbdf9 --- /dev/null +++ b/lib/libc/posix1e/acl_set_entry_type_np.3 @@ -0,0 +1,94 @@ +.\"- +.\" Copyright (c) 2008, 2009 Edward Tomasz Napierala +.\" 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 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 AUTHOR 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. +.\" +.\" $FreeBSD: releng/10.2/lib/libc/posix1e/acl_set_entry_type_np.3 275253 2014-11-29 15:50:13Z trasz $ +.\" +.Dd October 30, 2014 +.Dt ACL_SET_ENTRY_TYPE_NP 3 +.Os +.Sh NAME +.Nm acl_set_entry_type_np +.Nd set NFSv4 ACL entry type +.Sh LIBRARY +.Lb libc +.Sh SYNOPSIS +.In sys/types.h +.In sys/acl.h +.Ft int +.Fn acl_set_entry_type_np "acl_entry_t entry_d" "acl_entry_type_t entry_type" +.Sh DESCRIPTION +The +.Fn acl_set_entry_type_np +function +is a non-portable call that sets the type of the NFSv4 ACL entry +.Fa entry_d +to the value referred to by +.Fa entry_type . +.Pp +Valid values are: +.Bl -column -offset 3n "ACL_ENTRY_TYPE_ALLOW" +.It ACL_ENTRY_TYPE_ALLOW Ta "allow" type entry +.It ACL_ENTRY_TYPE_DENY Ta "deny" type entry +.El +.Pp +This call brands the ACL as NFSv4. +.Sh RETURN VALUES +.Rv -std acl_set_entry_type_np +.Sh ERRORS +The +.Fn acl_set_entry_type_np +function fails if: +.Bl -tag -width Er +.It Bq Er EINVAL +Argument +.Fa entry_d +is not a valid descriptor for an ACL entry. +The value pointed to by +.Fa entry_type +is not valid. +ACL is already branded as POSIX.1e. +.It Bq Er ENOMEM +The value to be returned requires more memory than is allowed +by the hardware or system-imposed memory management constraints. +.El +.Sh SEE ALSO +.Xr acl 3 , +.Xr acl_get_brand_np 3 , +.Xr acl_get_entry_type_np 3 , +.Xr posix1e 3 +.Sh STANDARDS +POSIX.1e is described in IEEE POSIX.1e draft 17. +.Sh HISTORY +POSIX.1e support was introduced in +.Fx 4.0 . +The +.Fn acl_get_entry_type_np +function was added in +.Fx 8.0 . +.Sh AUTHORS +The +.Fn acl_get_entry_type_np +function was written by +.An Edward Tomasz Napierala Aq trasz@FreeBSD.org . diff --git a/lib/libc/posix1e/acl_set_flagset_np.3 b/lib/libc/posix1e/acl_set_flagset_np.3 new file mode 100644 index 0000000..4bc257a --- /dev/null +++ b/lib/libc/posix1e/acl_set_flagset_np.3 @@ -0,0 +1,85 @@ +.\"- +.\" Copyright (c) 2008, 2009 Edward Tomasz Napierala +.\" 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 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 AUTHOR 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. +.\" +.\" $FreeBSD: releng/10.2/lib/libc/posix1e/acl_set_flagset_np.3 275253 2014-11-29 15:50:13Z trasz $ +.\" +.Dd October 30, 2014 +.Dt ACL_SET_FLAGSET_NP 3 +.Os +.Sh NAME +.Nm acl_set_flagset_np +.Nd set the flags of an NFSv4 ACL entry +.Sh LIBRARY +.Lb libc +.Sh SYNOPSIS +.In sys/types.h +.In sys/acl.h +.Ft int +.Fn acl_set_flagset_np "acl_entry_t entry_d" "acl_flagset_t flagset_d" +.Sh DESCRIPTION +The +.Fn acl_set_flagset_np +function +is a non-portable call that sets the flags of NFSv4 ACL entry +.Fa entry_d +with the flags contained in +.Fa flagset_d . +.Pp +This call brands the ACL as NFSv4. +.Sh RETURN VALUES +.Rv -std acl_set_flagset_np +.Sh ERRORS +The +.Fn acl_set_flagset_np +function fails if: +.Bl -tag -width Er +.It Bq Er EINVAL +Argument +.Fa entry_d +is not a valid descriptor for an ACL entry. +ACL is already branded as POSIX.1e. +.El +.Sh SEE ALSO +.Xr acl 3 , +.Xr acl_add_flag_np 3 , +.Xr acl_get_brand_np 3 , +.Xr acl_clear_flags_np 3 , +.Xr acl_delete_flag_np 3 , +.Xr acl_get_flagset_np 3 , +.Xr posix1e 3 +.Sh STANDARDS +POSIX.1e is described in IEEE POSIX.1e draft 17. +.Sh HISTORY +POSIX.1e support was introduced in +.Fx 4.0 . +The +.Fn acl_set_flagset_np +function was added in +.Fx 8.0 . +.Sh AUTHORS +The +.Fn acl_set_flagset_np +function was written by +.An Edward Tomasz Napierala Aq trasz@FreeBSD.org . diff --git a/lib/libc/posix1e/acl_set_permset.3 b/lib/libc/posix1e/acl_set_permset.3 new file mode 100644 index 0000000..f8aa51b --- /dev/null +++ b/lib/libc/posix1e/acl_set_permset.3 @@ -0,0 +1,81 @@ +.\"- +.\" Copyright (c) 2001 Chris D. Faulhaber +.\" 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 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 AUTHOR 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. +.\" +.\" $FreeBSD: releng/10.2/lib/libc/posix1e/acl_set_permset.3 184607 2008-11-04 00:20:43Z imp $ +.\" +.Dd March 10, 2001 +.Dt ACL_SET_PERMSET 3 +.Os +.Sh NAME +.Nm acl_set_permset +.Nd set the permissions of an ACL entry +.Sh LIBRARY +.Lb libc +.Sh SYNOPSIS +.In sys/types.h +.In sys/acl.h +.Ft int +.Fn acl_set_permset "acl_entry_t entry_d" "acl_permset_t permset_d" +.Sh DESCRIPTION +The +.Fn acl_set_permset +function +is a POSIX.1e call that sets the permissions of ACL entry +.Fa entry_d +with the permissions contained in +.Fa permset_d . +.Sh RETURN VALUES +.Rv -std acl_set_permset +.Sh ERRORS +The +.Fn acl_set_permset +function fails if: +.Bl -tag -width Er +.It Bq Er EINVAL +Argument +.Fa entry_d +is not a valid descriptor for an ACL entry. +.El +.Sh SEE ALSO +.Xr acl 3 , +.Xr acl_add_perm 3 , +.Xr acl_clear_perms 3 , +.Xr acl_delete_perm 3 , +.Xr acl_get_permset 3 , +.Xr posix1e 3 +.Sh STANDARDS +POSIX.1e is described in IEEE POSIX.1e draft 17. +.Sh HISTORY +POSIX.1e support was introduced in +.Fx 4.0 . +The +.Fn acl_set_permset +function was added in +.Fx 5.0 . +.Sh AUTHORS +The +.Fn acl_set_permset +function was written by +.An Chris D. Faulhaber Aq jedgar@fxp.org . diff --git a/lib/libc/posix1e/acl_set_qualifier.3 b/lib/libc/posix1e/acl_set_qualifier.3 new file mode 100644 index 0000000..1556df5 --- /dev/null +++ b/lib/libc/posix1e/acl_set_qualifier.3 @@ -0,0 +1,91 @@ +.\"- +.\" Copyright (c) 2001 Chris D. Faulhaber +.\" 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 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 AUTHOR 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. +.\" +.\" $FreeBSD: releng/10.2/lib/libc/posix1e/acl_set_qualifier.3 191520 2009-04-26 10:12:20Z trasz $ +.\" +.Dd March 10, 2001 +.Dt ACL_SET_QUALIFIER 3 +.Os +.Sh NAME +.Nm acl_set_qualifier +.Nd set ACL tag qualifier +.Sh LIBRARY +.Lb libc +.Sh SYNOPSIS +.In sys/types.h +.In sys/acl.h +.Ft int +.Fn acl_set_qualifier "acl_entry_t entry_d" "const void *tag_qualifier_p" +.Sh DESCRIPTION +The +.Fn acl_set_qualifier +function +is a POSIX.1e call that sets the qualifier of the tag for the ACL entry +.Fa entry_d +to the value referred to by +.Fa tag_qualifier_p . +.Sh RETURN VALUES +.Rv -std acl_set_qualifier +.Sh ERRORS +The +.Fn acl_set_qualifier +function fails if: +.Bl -tag -width Er +.It Bq Er EINVAL +Argument +.Fa entry_d +is not a valid descriptor for an ACL entry. +The tag type of the +ACL entry +.Fa entry_d +is not +.Dv ACL_USER +or +.Dv ACL_GROUP . +The value pointed to by +.Fa tag_qualifier_p +is not valid. +.It Bq Er ENOMEM +The value to be returned requires more memory than is allowed +by the hardware or system-imposed memory management constraints. +.El +.Sh SEE ALSO +.Xr acl 3 , +.Xr acl_get_qualifier 3 , +.Xr posix1e 3 +.Sh STANDARDS +POSIX.1e is described in IEEE POSIX.1e draft 17. +.Sh HISTORY +POSIX.1e support was introduced in +.Fx 4.0 . +The +.Fn acl_get_qualifier +function was added in +.Fx 5.0 . +.Sh AUTHORS +The +.Fn acl_get_qualifier +function was written by +.An Chris D. Faulhaber Aq jedgar@fxp.org . diff --git a/lib/libc/posix1e/acl_set_tag_type.3 b/lib/libc/posix1e/acl_set_tag_type.3 new file mode 100644 index 0000000..127d3fb --- /dev/null +++ b/lib/libc/posix1e/acl_set_tag_type.3 @@ -0,0 +1,102 @@ +.\"- +.\" Copyright (c) 2001 Chris D. Faulhaber +.\" 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 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 AUTHOR 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. +.\" +.\" $FreeBSD: releng/10.2/lib/libc/posix1e/acl_set_tag_type.3 233665 2012-03-29 16:02:40Z joel $ +.\" +.Dd June 25, 2009 +.Dt ACL_SET_TAG_TYPE 3 +.Os +.Sh NAME +.Nm acl_set_tag_type +.Nd set the tag type of an ACL entry +.Sh LIBRARY +.Lb libc +.Sh SYNOPSIS +.In sys/types.h +.In sys/acl.h +.Ft int +.Fn acl_set_tag_type "acl_entry_t entry_d" "acl_tag_t tag_type" +.Sh DESCRIPTION +The +.Fn acl_set_tag_type +function +is a POSIX.1e call that sets the ACL tag type of ACL entry +.Fa entry_d +to the value of +.Fa tag_type . +.Pp +Valid values are: +.Bl -column -offset 3n "ACL_OTHER_OBJ" +.It ACL_USER_OBJ Ta "Permissions apply to file owner" +.It ACL_USER Ta "Permissions apply to additional user specified by qualifier" +.It ACL_GROUP_OBJ Ta "Permissions apply to file group" +.It ACL_GROUP Ta "Permissions apply to additional group specified by qualifier" +.It ACL_MASK Ta "Permissions specify mask" +.It ACL_OTHER Ta Permissions apply to "other" +.It ACL_OTHER_OBJ Ta "Same as ACL_OTHER" +.It ACL_EVERYONE Ta Permissions apply to "everyone@" +.El +.Pp +Calling +.Fn acl_set_tag_type +with +.Fa tag_type +equal to ACL_MASK, ACL_OTHER or ACL_OTHER_OBJ brands the ACL as POSIX.1e. +Calling it with ACL_EVERYONE brands the ACL as NFSv4. +.Sh RETURN VALUES +.Rv -std acl_set_tag_type +.Sh ERRORS +The +.Fn acl_set_tag_type +function fails if: +.Bl -tag -width Er +.It Bq Er EINVAL +Argument +.Fa entry_d +is not a valid descriptor for an ACL entry. +Argument +.Fa tag_type +is not a valid ACL tag type. +ACL is already branded differently. +.El +.Sh SEE ALSO +.Xr acl 3 , +.Xr acl_get_brand_np 3 , +.Xr acl_get_tag_type 3 , +.Xr posix1e 3 +.Sh STANDARDS +POSIX.1e is described in IEEE POSIX.1e draft 17. +.Sh HISTORY +POSIX.1e support was introduced in +.Fx 4.0 . +The +.Fn acl_set_tag_type +function was added in +.Fx 5.0 . +.Sh AUTHORS +The +.Fn acl_set_tag_type +function was written by +.An Chris D. Faulhaber Aq jedgar@fxp.org . diff --git a/lib/libc/posix1e/acl_size.c b/lib/libc/posix1e/acl_size.c new file mode 100644 index 0000000..a7a4e3c --- /dev/null +++ b/lib/libc/posix1e/acl_size.c @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2001-2002 Chris D. Faulhaber + * 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 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 AUTHOR OR THE VOICES IN HIS HEAD 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 +__FBSDID("$FreeBSD: src/lib/libc/posix1e/acl_size.c,v 1.4 2002/03/22 21:52:38 obrien Exp $"); + +#include +#include "namespace.h" +#include +#include "un-namespace.h" + +#include + +ssize_t +acl_size(acl_t acl) +{ + + errno = ENOSYS; + return (-1); +} diff --git a/lib/libc/posix1e/acl_strip.c b/lib/libc/posix1e/acl_strip.c new file mode 100644 index 0000000..096b643 --- /dev/null +++ b/lib/libc/posix1e/acl_strip.c @@ -0,0 +1,225 @@ +/*- + * Copyright (c) 2001 Chris D. Faulhaber + * 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 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 AUTHOR 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 +__FBSDID("$FreeBSD: releng/10.2/lib/libc/posix1e/acl_strip.c 219878 2011-03-22 17:44:07Z trasz $"); + +#include +#include +#include +#include +#include + +#include "acl_support.h" + +/* + * These routines from sys/kern/subr_acl_nfs4.c are used by both kernel + * and libc. + */ +void acl_nfs4_sync_mode_from_acl(mode_t *_mode, const struct acl *aclp); +void acl_nfs4_trivial_from_mode_libc(struct acl *aclp, int file_owner_id, + int canonical_six); + +static acl_t +_nfs4_acl_strip_np(const acl_t aclp, int canonical_six) +{ + acl_t newacl; + mode_t mode = 0; + + newacl = acl_init(ACL_MAX_ENTRIES); + if (newacl == NULL) { + errno = ENOMEM; + return (NULL); + } + + _acl_brand_as(newacl, ACL_BRAND_NFS4); + + acl_nfs4_sync_mode_from_acl(&mode, &(aclp->ats_acl)); + acl_nfs4_trivial_from_mode_libc(&(newacl->ats_acl), mode, canonical_six); + + return (newacl); +} + +static acl_t +_posix1e_acl_strip_np(const acl_t aclp, int recalculate_mask) +{ + acl_t acl_new, acl_old; + acl_entry_t entry, entry_new; + acl_permset_t perm; + acl_tag_t tag; + int entry_id, have_mask_entry; + + assert(_acl_brand(aclp) == ACL_BRAND_POSIX); + + acl_old = acl_dup(aclp); + if (acl_old == NULL) + return (NULL); + + assert(_acl_brand(acl_old) == ACL_BRAND_POSIX); + + have_mask_entry = 0; + acl_new = acl_init(ACL_MAX_ENTRIES); + if (acl_new == NULL) + return (NULL); + tag = ACL_UNDEFINED_TAG; + + /* only save the default user/group/other entries */ + entry_id = ACL_FIRST_ENTRY; + while (acl_get_entry(acl_old, entry_id, &entry) == 1) { + entry_id = ACL_NEXT_ENTRY; + + assert(_entry_brand(entry) == ACL_BRAND_POSIX); + + if (acl_get_tag_type(entry, &tag) == -1) + return (NULL); + + switch(tag) { + case ACL_USER_OBJ: + case ACL_GROUP_OBJ: + case ACL_OTHER: + if (acl_get_tag_type(entry, &tag) == -1) + return (NULL); + if (acl_get_permset(entry, &perm) == -1) + return (NULL); + if (acl_create_entry(&acl_new, &entry_new) == -1) + return (NULL); + if (acl_set_tag_type(entry_new, tag) == -1) + return (NULL); + if (acl_set_permset(entry_new, perm) == -1) + return (NULL); + if (acl_copy_entry(entry_new, entry) == -1) + return (NULL); + assert(_entry_brand(entry_new) == ACL_BRAND_POSIX); + break; + case ACL_MASK: + have_mask_entry = 1; + break; + default: + break; + } + } + + assert(_acl_brand(acl_new) == ACL_BRAND_POSIX); + + if (have_mask_entry && recalculate_mask) { + if (acl_calc_mask(&acl_new) == -1) + return (NULL); + } + + return (acl_new); +} + +acl_t +acl_strip_np(const acl_t aclp, int recalculate_mask) +{ + switch (_acl_brand(aclp)) { + case ACL_BRAND_NFS4: + return (_nfs4_acl_strip_np(aclp, 0)); + + case ACL_BRAND_POSIX: + return (_posix1e_acl_strip_np(aclp, recalculate_mask)); + + default: + errno = EINVAL; + return (NULL); + } +} + +/* + * Return 1, if ACL is trivial, 0 otherwise. + * + * ACL is trivial, iff its meaning could be fully expressed using just file + * mode. In other words, ACL is trivial iff it doesn't have "+" to the right + * of the mode bits in "ls -l" output ;-) + */ +int +acl_is_trivial_np(const acl_t aclp, int *trivialp) +{ + acl_t tmpacl; + int differs; + + if (aclp == NULL || trivialp == NULL) { + errno = EINVAL; + return (-1); + } + + switch (_acl_brand(aclp)) { + case ACL_BRAND_POSIX: + if (aclp->ats_acl.acl_cnt == 3) + *trivialp = 1; + else + *trivialp = 0; + + return (0); + + case ACL_BRAND_NFS4: + /* + * If the ACL has more than canonical six entries, + * it's non trivial by definition. + */ + if (aclp->ats_acl.acl_cnt > 6) { + *trivialp = 0; + return (0); + } + + /* + * Calculate trivial ACL - using acl_strip_np(3) - and compare + * with the original. + */ + tmpacl = _nfs4_acl_strip_np(aclp, 0); + if (tmpacl == NULL) + return (-1); + + differs = _acl_differs(aclp, tmpacl); + acl_free(tmpacl); + + if (differs == 0) { + *trivialp = 1; + return (0); + } + + /* + * Try again with an old-style, "canonical six" trivial ACL. + */ + tmpacl = _nfs4_acl_strip_np(aclp, 1); + if (tmpacl == NULL) + return (-1); + + differs = _acl_differs(aclp, tmpacl); + acl_free(tmpacl); + + if (differs) + *trivialp = 0; + else + *trivialp = 1; + + return (0); + + default: + errno = EINVAL; + return (-1); + } +} diff --git a/lib/libc/posix1e/acl_strip_np.3 b/lib/libc/posix1e/acl_strip_np.3 new file mode 100644 index 0000000..77c108e --- /dev/null +++ b/lib/libc/posix1e/acl_strip_np.3 @@ -0,0 +1,109 @@ +.\"- +.\" Copyright (c) 2008, 2009 Edward Tomasz Napierala +.\" All rights reserved. +.\" +.\" This software was developed by Robert Watson for the TrustedBSD Project. +.\" +.\" 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 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 AUTHOR 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. +.\" +.\" $FreeBSD: releng/10.2/lib/libc/posix1e/acl_strip_np.3 210772 2010-08-02 16:01:45Z joel $ +.\" +.Dd June 25, 2009 +.Dt ACL_STRIP_NP 3 +.Os +.Sh NAME +.Nm acl_strip_np +.Nd strip extended entries from an ACL +.Sh LIBRARY +.Lb libc +.Sh SYNOPSIS +.In sys/types.h +.In sys/acl.h +.Ft acl_t +.Fn acl_strip_np "const acl_t acl" "int recalculate_mask" +.Sh DESCRIPTION +The +.Fn acl_strip_np +function returns a pointer to a trivial ACL computed from the ACL pointed +to by the argument +.Va acl . +.Pp +This function may cause memory to be allocated. +The caller should free any +releasable memory, when the new ACL is no longer required, by calling +.Xr acl_free 3 +with the +.Va (void*)acl_t +as an argument. +.Pp +Any existing ACL pointers that refer to the ACL referred to by +.Va acl +shall continue to refer to the ACL. +.Sh RETURN VALUES +Upon successful completion, this function shall return a pointer to the +newly allocated ACL. +Otherwise, a value of +.Va (acl_t)NULL +shall be returned, and +.Va errno +shall be set to indicate the error. +.Sh ERRORS +If any of the following conditions occur, the +.Fn acl_init +function shall return a value of +.Va (acl_t)NULL +and set +.Va errno +to the corresponding value: +.Bl -tag -width Er +.It Bq Er EINVAL +Argument +.Va acl +does not point to a valid ACL. +.It Bq Er ENOMEM +The +.Va acl_t +to be returned requires more memory than is allowed by the hardware or +system-imposed memory management constraints. +.El +.Sh SEE ALSO +.Xr acl 3 , +.Xr acl_is_trivial_np 3 , +.Xr posix1e 3 +.Sh STANDARDS +POSIX.1e is described in IEEE POSIX.1e draft 17. +Discussion +of the draft continues on the cross-platform POSIX.1e implementation +mailing list. +To join this list, see the +.Fx +POSIX.1e implementation +page for more information. +.Sh HISTORY +POSIX.1e support was introduced in +.Fx 4.0 . +The +.Fn acl_strip_np +function was added in +.Fx 8.0 . +.Sh AUTHORS +.An Edward Tomasz Napierala Aq trasz@FreeBSD.org . diff --git a/lib/libc/posix1e/acl_support.c b/lib/libc/posix1e/acl_support.c new file mode 100644 index 0000000..b7dc1f7 --- /dev/null +++ b/lib/libc/posix1e/acl_support.c @@ -0,0 +1,418 @@ +/*- + * Copyright (c) 1999-2001, 2008 Robert N. M. Watson + * 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 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 AUTHOR 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. + */ +/* + * Support functionality for the POSIX.1e ACL interface + * These calls are intended only to be called within the library. + */ + +#include +__FBSDID("$FreeBSD: releng/10.2/lib/libc/posix1e/acl_support.c 209147 2010-06-14 02:26:13Z kientzle $"); + +#include +#include "namespace.h" +#include +#include "un-namespace.h" +#include +#include +#include +#include +#include +#include +#include + +#include "acl_support.h" + +#define ACL_STRING_PERM_WRITE 'w' +#define ACL_STRING_PERM_READ 'r' +#define ACL_STRING_PERM_EXEC 'x' +#define ACL_STRING_PERM_NONE '-' + +/* + * Return 0, if both ACLs are identical. + */ +int +_acl_differs(const acl_t a, const acl_t b) +{ + int i; + struct acl_entry *entrya, *entryb; + + assert(_acl_brand(a) == _acl_brand(b)); + assert(_acl_brand(a) != ACL_BRAND_UNKNOWN); + assert(_acl_brand(b) != ACL_BRAND_UNKNOWN); + + if (a->ats_acl.acl_cnt != b->ats_acl.acl_cnt) + return (1); + + for (i = 0; i < b->ats_acl.acl_cnt; i++) { + entrya = &(a->ats_acl.acl_entry[i]); + entryb = &(b->ats_acl.acl_entry[i]); + + if (entrya->ae_tag != entryb->ae_tag || + entrya->ae_id != entryb->ae_id || + entrya->ae_perm != entryb->ae_perm || + entrya->ae_entry_type != entryb->ae_entry_type || + entrya->ae_flags != entryb->ae_flags) + return (1); + } + + return (0); +} + +/* + * _posix1e_acl_entry_compare -- compare two acl_entry structures to + * determine the order they should appear in. Used by _posix1e_acl_sort to + * sort ACL entries into the kernel-desired order -- i.e., the order useful + * for evaluation and O(n) validity checking. Beter to have an O(nlogn) sort + * in userland and an O(n) in kernel than to have both in kernel. + */ +typedef int (*compare)(const void *, const void *); +static int +_posix1e_acl_entry_compare(struct acl_entry *a, struct acl_entry *b) +{ + + assert(_entry_brand(a) == ACL_BRAND_POSIX); + assert(_entry_brand(b) == ACL_BRAND_POSIX); + + /* + * First, sort between tags -- conveniently defined in the correct + * order for verification. + */ + if (a->ae_tag < b->ae_tag) + return (-1); + if (a->ae_tag > b->ae_tag) + return (1); + + /* + * Next compare uids/gids on appropriate types. + */ + + if (a->ae_tag == ACL_USER || a->ae_tag == ACL_GROUP) { + if (a->ae_id < b->ae_id) + return (-1); + if (a->ae_id > b->ae_id) + return (1); + + /* shouldn't be equal, fall through to the invalid case */ + } + + /* + * Don't know how to sort multiple entries of the rest--either it's + * a bad entry, or there shouldn't be more than one. Ignore and the + * validity checker can get it later. + */ + return (0); +} + +/* + * _posix1e_acl_sort -- sort ACL entries in POSIX.1e-formatted ACLs. + */ +void +_posix1e_acl_sort(acl_t acl) +{ + struct acl *acl_int; + + acl_int = &acl->ats_acl; + + qsort(&acl_int->acl_entry[0], acl_int->acl_cnt, + sizeof(struct acl_entry), (compare) _posix1e_acl_entry_compare); +} + +/* + * acl_posix1e -- in what situations should we acl_sort before submission? + * We apply posix1e ACL semantics for any ACL of type ACL_TYPE_ACCESS or + * ACL_TYPE_DEFAULT + */ +int +_posix1e_acl(acl_t acl, acl_type_t type) +{ + + if (_acl_brand(acl) != ACL_BRAND_POSIX) + return (0); + + return ((type == ACL_TYPE_ACCESS) || (type == ACL_TYPE_DEFAULT)); +} + +/* + * _posix1e_acl_check -- given an ACL, check its validity. This is mirrored + * from code in sys/kern/kern_acl.c, and if changes are made in one, they + * should be made in the other also. This copy of acl_check is made + * available * in userland for the benefit of processes wanting to check ACLs + * for validity before submitting them to the kernel, or for performing + * in userland file system checking. Needless to say, the kernel makes + * the real checks on calls to get/setacl. + * + * See the comments in kernel for explanation -- just briefly, it assumes + * an already sorted ACL, and checks based on that assumption. The + * POSIX.1e interface, acl_valid(), will perform the sort before calling + * this. Returns 0 on success, EINVAL on failure. + */ +int +_posix1e_acl_check(acl_t acl) +{ + struct acl *acl_int; + struct acl_entry *entry; /* current entry */ + uid_t highest_uid=0, highest_gid=0; + int stage = ACL_USER_OBJ; + int i = 0; + int count_user_obj=0, count_user=0, count_group_obj=0, + count_group=0, count_mask=0, count_other=0; + + acl_int = &acl->ats_acl; + + /* printf("_posix1e_acl_check: checking acl with %d entries\n", + acl->acl_cnt); */ + while (i < acl_int->acl_cnt) { + entry = &acl_int->acl_entry[i]; + + if ((entry->ae_perm | ACL_PERM_BITS) != ACL_PERM_BITS) + return (EINVAL); + + switch(entry->ae_tag) { + case ACL_USER_OBJ: + /* printf("_posix1e_acl_check: %d: ACL_USER_OBJ\n", + i); */ + if (stage > ACL_USER_OBJ) + return (EINVAL); + stage = ACL_USER; + count_user_obj++; + break; + + case ACL_USER: + /* printf("_posix1e_acl_check: %d: ACL_USER\n", i); */ + if (stage > ACL_USER) + return (EINVAL); + stage = ACL_USER; + if (count_user && (entry->ae_id <= highest_uid)) + return (EINVAL); + highest_uid = entry->ae_id; + count_user++; + break; + + case ACL_GROUP_OBJ: + /* printf("_posix1e_acl_check: %d: ACL_GROUP_OBJ\n", + i); */ + if (stage > ACL_GROUP_OBJ) + return (EINVAL); + stage = ACL_GROUP; + count_group_obj++; + break; + + case ACL_GROUP: + /* printf("_posix1e_acl_check: %d: ACL_GROUP\n", i); */ + if (stage > ACL_GROUP) + return (EINVAL); + stage = ACL_GROUP; + if (count_group && (entry->ae_id <= highest_gid)) + return (EINVAL); + highest_gid = entry->ae_id; + count_group++; + break; + + case ACL_MASK: + /* printf("_posix1e_acl_check: %d: ACL_MASK\n", i); */ + if (stage > ACL_MASK) + return (EINVAL); + stage = ACL_MASK; + count_mask++; + break; + + case ACL_OTHER: + /* printf("_posix1e_acl_check: %d: ACL_OTHER\n", i); */ + if (stage > ACL_OTHER) + return (EINVAL); + stage = ACL_OTHER; + count_other++; + break; + + default: + /* printf("_posix1e_acl_check: %d: INVALID\n", i); */ + return (EINVAL); + } + i++; + } + + if (count_user_obj != 1) + return (EINVAL); + + if (count_group_obj != 1) + return (EINVAL); + + if (count_mask != 0 && count_mask != 1) + return (EINVAL); + + if (count_other != 1) + return (EINVAL); + + return (0); +} + +/* + * Given a right-shifted permission (i.e., direct ACL_PERM_* mask), fill + * in a string describing the permissions. + */ +int +_posix1e_acl_perm_to_string(acl_perm_t perm, ssize_t buf_len, char *buf) +{ + + if (buf_len < _POSIX1E_ACL_STRING_PERM_MAXSIZE + 1) { + errno = ENOMEM; + return (-1); + } + + if ((perm | ACL_PERM_BITS) != ACL_PERM_BITS) { + errno = EINVAL; + return (-1); + } + + buf[3] = 0; /* null terminate */ + + if (perm & ACL_READ) + buf[0] = ACL_STRING_PERM_READ; + else + buf[0] = ACL_STRING_PERM_NONE; + + if (perm & ACL_WRITE) + buf[1] = ACL_STRING_PERM_WRITE; + else + buf[1] = ACL_STRING_PERM_NONE; + + if (perm & ACL_EXECUTE) + buf[2] = ACL_STRING_PERM_EXEC; + else + buf[2] = ACL_STRING_PERM_NONE; + + return (0); +} + +/* + * given a string, return a permission describing it + */ +int +_posix1e_acl_string_to_perm(char *string, acl_perm_t *perm) +{ + acl_perm_t myperm = ACL_PERM_NONE; + char *ch; + + ch = string; + while (*ch) { + switch(*ch) { + case ACL_STRING_PERM_READ: + myperm |= ACL_READ; + break; + case ACL_STRING_PERM_WRITE: + myperm |= ACL_WRITE; + break; + case ACL_STRING_PERM_EXEC: + myperm |= ACL_EXECUTE; + break; + case ACL_STRING_PERM_NONE: + break; + default: + return (EINVAL); + } + ch++; + } + + *perm = myperm; + return (0); +} + +/* + * Add an ACL entry without doing much checking, et al + */ +int +_posix1e_acl_add_entry(acl_t acl, acl_tag_t tag, uid_t id, acl_perm_t perm) +{ + struct acl *acl_int; + struct acl_entry *e; + + acl_int = &acl->ats_acl; + + if (acl_int->acl_cnt >= ACL_MAX_ENTRIES) { + errno = ENOMEM; + return (-1); + } + + e = &(acl_int->acl_entry[acl_int->acl_cnt]); + e->ae_perm = perm; + e->ae_tag = tag; + e->ae_id = id; + acl_int->acl_cnt++; + + return (0); +} + +/* + * Convert "old" type - ACL_TYPE_{ACCESS,DEFAULT}_OLD - into its "new" + * counterpart. It's neccessary for the old (pre-NFSv4 ACLs) binaries + * to work with new libc and kernel. Fixing 'type' for old binaries with + * old libc and new kernel is being done by kern/vfs_acl.c:type_unold(). + */ +int +_acl_type_unold(acl_type_t type) +{ + + switch (type) { + case ACL_TYPE_ACCESS_OLD: + return (ACL_TYPE_ACCESS); + case ACL_TYPE_DEFAULT_OLD: + return (ACL_TYPE_DEFAULT); + default: + return (type); + } +} + +char * +string_skip_whitespace(char *string) +{ + + while (*string && ((*string == ' ') || (*string == '\t'))) + string++; + + return (string); +} + +void +string_trim_trailing_whitespace(char *string) +{ + char *end; + + if (*string == '\0') + return; + + end = string + strlen(string) - 1; + + while (end != string) { + if ((*end == ' ') || (*end == '\t')) { + *end = '\0'; + end--; + } else { + return; + } + } + + return; +} diff --git a/lib/libc/posix1e/acl_support.h b/lib/libc/posix1e/acl_support.h new file mode 100644 index 0000000..d337c0f --- /dev/null +++ b/lib/libc/posix1e/acl_support.h @@ -0,0 +1,66 @@ +/*- + * Copyright (c) 1999, 2000, 2001 Robert N. M. Watson + * 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 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 AUTHOR 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. + * + * $FreeBSD: releng/10.2/lib/libc/posix1e/acl_support.h 209736 2010-07-06 17:20:08Z trasz $ + */ +/* + * Support functionality for the POSIX.1e ACL interface + * These calls are intended only to be called within the library. + */ +#ifndef _ACL_SUPPORT_H +#define _ACL_SUPPORT_H + +#define _POSIX1E_ACL_STRING_PERM_MAXSIZE 3 /* read, write, exec */ +#define _ACL_T_ALIGNMENT_BITS 13 + +int _acl_type_unold(acl_type_t type); +int _acl_differs(const acl_t a, const acl_t b); +int _acl_type_not_valid_for_acl(const acl_t acl, acl_type_t type); +void _acl_brand_from_type(acl_t acl, acl_type_t type); +int _acl_brand(const acl_t acl); +int _entry_brand(const acl_entry_t entry); +int _acl_brand_may_be(const acl_t acl, int brand); +int _entry_brand_may_be(const acl_entry_t entry, int brand); +void _acl_brand_as(acl_t acl, int brand); +void _entry_brand_as(const acl_entry_t entry, int brand); +int _nfs4_format_flags(char *str, size_t size, acl_flag_t var, int verbose); +int _nfs4_format_access_mask(char *str, size_t size, acl_perm_t var, int verbose); +int _nfs4_parse_flags(const char *str, acl_flag_t *var); +int _nfs4_parse_access_mask(const char *str, acl_perm_t *var); +int _posix1e_acl_check(acl_t acl); +void _posix1e_acl_sort(acl_t acl); +int _posix1e_acl(acl_t acl, acl_type_t type); +int _posix1e_acl_id_to_name(acl_tag_t tag, uid_t id, ssize_t buf_len, + char *buf, int flags); +int _posix1e_acl_perm_to_string(acl_perm_t perm, ssize_t buf_len, + char *buf); +int _posix1e_acl_string_to_perm(char *string, acl_perm_t *perm); +int _posix1e_acl_add_entry(acl_t acl, acl_tag_t tag, uid_t id, + acl_perm_t perm); +char *string_skip_whitespace(char *string); +void string_trim_trailing_whitespace(char *string); +int _acl_name_to_id(acl_tag_t tag, char *name, uid_t *id); + +#endif diff --git a/lib/libc/posix1e/acl_support_nfs4.c b/lib/libc/posix1e/acl_support_nfs4.c new file mode 100644 index 0000000..f3c7e05 --- /dev/null +++ b/lib/libc/posix1e/acl_support_nfs4.c @@ -0,0 +1,260 @@ +/*- + * Copyright (c) 2008, 2009 Edward Tomasz Napierała + * 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 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 AUTHOR 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 +__FBSDID("$FreeBSD: releng/10.2/lib/libc/posix1e/acl_support_nfs4.c 220465 2011-04-09 07:42:25Z trasz $"); + +#include +#include +#include +#include +#include +#include +#include "acl_support.h" + +struct flagnames_struct { + uint32_t flag; + const char *name; + char letter; +}; + +struct flagnames_struct a_flags[] = + {{ ACL_ENTRY_FILE_INHERIT, "file_inherit", 'f'}, + { ACL_ENTRY_DIRECTORY_INHERIT, "dir_inherit", 'd'}, + { ACL_ENTRY_INHERIT_ONLY, "inherit_only", 'i'}, + { ACL_ENTRY_NO_PROPAGATE_INHERIT, "no_propagate", 'n'}, + { ACL_ENTRY_SUCCESSFUL_ACCESS, "successfull_access", 'S'}, + { ACL_ENTRY_FAILED_ACCESS, "failed_access", 'F'}, + /* + * There is no ACE_IDENTIFIER_GROUP here - SunOS does not show it + * in the "flags" field. There is no ACE_OWNER, ACE_GROUP or + * ACE_EVERYONE either, for obvious reasons. + */ + { 0, 0, 0}}; + +struct flagnames_struct a_access_masks[] = + {{ ACL_READ_DATA, "read_data", 'r'}, + { ACL_WRITE_DATA, "write_data", 'w'}, + { ACL_EXECUTE, "execute", 'x'}, + { ACL_APPEND_DATA, "append_data", 'p'}, + { ACL_DELETE_CHILD, "delete_child", 'D'}, + { ACL_DELETE, "delete", 'd'}, + { ACL_READ_ATTRIBUTES, "read_attributes", 'a'}, + { ACL_WRITE_ATTRIBUTES, "write_attributes", 'A'}, + { ACL_READ_NAMED_ATTRS, "read_xattr", 'R'}, + { ACL_WRITE_NAMED_ATTRS, "write_xattr", 'W'}, + { ACL_READ_ACL, "read_acl", 'c'}, + { ACL_WRITE_ACL, "write_acl", 'C'}, + { ACL_WRITE_OWNER, "write_owner", 'o'}, + { ACL_SYNCHRONIZE, "synchronize", 's'}, + { ACL_FULL_SET, "full_set", '\0'}, + { ACL_MODIFY_SET, "modify_set", '\0'}, + { ACL_READ_SET, "read_set", '\0'}, + { ACL_WRITE_SET, "write_set", '\0'}, + { 0, 0, 0}}; + +static const char * +format_flag(uint32_t *var, const struct flagnames_struct *flags) +{ + + for (; flags->name != 0; flags++) { + if ((flags->flag & *var) == 0) + continue; + + *var &= ~flags->flag; + return (flags->name); + } + + return (NULL); +} + +static int +format_flags_verbose(char *str, size_t size, uint32_t var, + const struct flagnames_struct *flags) +{ + size_t off = 0; + const char *tmp; + + while ((tmp = format_flag(&var, flags)) != NULL) { + off += snprintf(str + off, size - off, "%s/", tmp); + assert (off < size); + } + + /* If there were any flags added... */ + if (off > 0) { + off--; + /* ... then remove the last slash. */ + assert(str[off] == '/'); + } + + str[off] = '\0'; + + return (0); +} + +static int +format_flags_compact(char *str, size_t size, uint32_t var, + const struct flagnames_struct *flags) +{ + size_t i; + + for (i = 0; flags[i].letter != '\0'; i++) { + assert(i < size); + if ((flags[i].flag & var) == 0) + str[i] = '-'; + else + str[i] = flags[i].letter; + } + + str[i] = '\0'; + + return (0); +} + +static int +parse_flags_verbose(const char *strp, uint32_t *var, + const struct flagnames_struct *flags, const char *flags_name, + int *try_compact) +{ + int i, found, ever_found = 0; + char *str, *flag; + + str = strdup(strp); + *try_compact = 0; + *var = 0; + + while (str != NULL) { + flag = strsep(&str, "/:"); + + found = 0; + for (i = 0; flags[i].name != NULL; i++) { + if (strcmp(flags[i].name, flag) == 0) { + *var |= flags[i].flag; + found = 1; + ever_found = 1; + } + } + + if (!found) { + if (ever_found) + warnx("malformed ACL: \"%s\" field contains " + "invalid flag \"%s\"", flags_name, flag); + else + *try_compact = 1; + free(str); + return (-1); + } + } + + free(str); + return (0); +} + +static int +parse_flags_compact(const char *str, uint32_t *var, + const struct flagnames_struct *flags, const char *flags_name) +{ + int i, j, found; + + *var = 0; + + for (i = 0;; i++) { + if (str[i] == '\0') + return (0); + + /* Ignore minus signs. */ + if (str[i] == '-') + continue; + + found = 0; + + for (j = 0; flags[j].name != NULL; j++) { + if (flags[j].letter == str[i]) { + *var |= flags[j].flag; + found = 1; + break; + } + } + + if (!found) { + warnx("malformed ACL: \"%s\" field contains " + "invalid flag \"%c\"", flags_name, str[i]); + return (-1); + } + } +} + +int +_nfs4_format_flags(char *str, size_t size, acl_flag_t var, int verbose) +{ + + if (verbose) + return (format_flags_verbose(str, size, var, a_flags)); + + return (format_flags_compact(str, size, var, a_flags)); +} + +int +_nfs4_format_access_mask(char *str, size_t size, acl_perm_t var, int verbose) +{ + + if (verbose) + return (format_flags_verbose(str, size, var, a_access_masks)); + + return (format_flags_compact(str, size, var, a_access_masks)); +} + +int +_nfs4_parse_flags(const char *str, acl_flag_t *flags) +{ + int error, try_compact; + int tmpflags; + + error = parse_flags_verbose(str, &tmpflags, a_flags, "flags", &try_compact); + if (error && try_compact) + error = parse_flags_compact(str, &tmpflags, a_flags, "flags"); + + *flags = tmpflags; + + return (error); +} + +int +_nfs4_parse_access_mask(const char *str, acl_perm_t *perms) +{ + int error, try_compact; + int tmpperms; + + error = parse_flags_verbose(str, &tmpperms, a_access_masks, + "access permissions", &try_compact); + if (error && try_compact) + error = parse_flags_compact(str, &tmpperms, + a_access_masks, "access permissions"); + + *perms = tmpperms; + + return (error); +} diff --git a/lib/libc/posix1e/acl_to_text.3 b/lib/libc/posix1e/acl_to_text.3 new file mode 100644 index 0000000..f3ec3b6 --- /dev/null +++ b/lib/libc/posix1e/acl_to_text.3 @@ -0,0 +1,158 @@ +.\"- +.\" Copyright (c) 2000, 2002 Robert N. M. Watson +.\" All rights reserved. +.\" +.\" This software was developed by Robert Watson for the TrustedBSD Project. +.\" +.\" 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 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 AUTHOR 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. +.\" +.\" $FreeBSD: releng/10.2/lib/libc/posix1e/acl_to_text.3 233665 2012-03-29 16:02:40Z joel $ +.\" +.Dd June 25, 2009 +.Dt ACL_TO_TEXT 3 +.Os +.Sh NAME +.Nm acl_to_text , +.Nm acl_to_text_np +.Nd convert an ACL to text +.Sh LIBRARY +.Lb libc +.Sh SYNOPSIS +.In sys/types.h +.In sys/acl.h +.Ft char * +.Fn acl_to_text "acl_t acl" "ssize_t *len_p" +.Ft char * +.Fn acl_to_text_np "acl_t acl" "ssize_t *len_p" "int flags" +.Sh DESCRIPTION +The +.Fn acl_to_text +and +.Fn acl_to_text_np +functions translate the ACL pointed to by argument +.Va acl +into a NULL terminated character string. +If the pointer +.Va len_p +is not NULL, then the function shall return the length of the string (not +including the NULL terminator) in the location pointed to by +.Va len_p . +If the ACL is POSIX.1e, the format of the text string returned by +.Fn acl_to_text +shall be the POSIX.1e long ACL form. If the ACL is NFSv4, the format +of the text string shall be the compact form, unless the +.Va ACL_TEXT_VERBOSE +flag is given. +.Pp +The flags specified are formed by +.Em or Ns 'ing +the following values +.Bl -column -offset 3n "ACL_TEXT_NUMERIC_IDS" +.It ACL_TEXT_VERBOSE Ta "Format ACL using verbose form" +.It ACL_TEXT_NUMERIC_IDS Ta "Do not resolve IDs into user or group names" +.It ACL_TEXT_APPEND_ID Ta "In addition to user and group names, append numeric IDs" +.El +.Pp +This function allocates any memory necessary to contain the string and +returns a pointer to the string. +The caller should free any releasable +memory, when the new string is no longer required, by calling +.Xr acl_free 3 +with the +.Va (void*)char +as an argument. +.Sh IMPLEMENTATION NOTES +.Fx Ns 's +support for POSIX.1e interfaces and features is still under +development at this time. +.Sh RETURN VALUES +Upon successful completion, the function shall return a pointer to the +long text form of an ACL. +Otherwise, a value of +.Va (char*)NULL +shall be returned and +.Va errno +shall be set to indicate the error. +.Sh ERRORS +If any of the following conditions occur, the +.Fn acl_to_text +function shall return a value of +.Va (acl_t)NULL +and set +.Va errno +to the corresponding value: +.Bl -tag -width Er +.It Bq Er EINVAL +Argument +.Va acl +does not point to a valid ACL. +.Pp +The ACL denoted by +.Va acl +contains one or more improperly formed ACL entries, or for some other +reason cannot be translated into a text form of an ACL. +.It Bq Er ENOMEM +The character string to be returned requires more memory than is allowed +by the hardware or software-imposed memory management constraints. +.El +.Sh SEE ALSO +.Xr acl 3 , +.Xr acl_free 3 , +.Xr acl_from_text 3 , +.Xr posix1e 3 +.Sh STANDARDS +POSIX.1e is described in IEEE POSIX.1e draft 17. +Discussion +of the draft continues on the cross-platform POSIX.1e implementation +mailing list. +To join this list, see the +.Fx +POSIX.1e implementation +page for more information. +.Sh HISTORY +POSIX.1e support was introduced in +.Fx 4.0 , +and development continues. +.Sh AUTHORS +.An Robert N M Watson +.Sh BUGS +The +.Fn acl_from_text +and +.Fn acl_to_text +functions +rely on the +.Xr getpwent 3 +library calls to manage username and uid mapping, as well as the +.Xr getgrent 3 +library calls to manage groupname and gid mapping. +These calls are not +thread safe, and so transitively, neither are +.Fn acl_from_text +and +.Fn acl_to_text . +These functions may also interfere with stateful +calls associated with the +.Fn getpwent +and +.Fn getgrent +calls. diff --git a/lib/libc/posix1e/acl_to_text.c b/lib/libc/posix1e/acl_to_text.c new file mode 100644 index 0000000..825600e --- /dev/null +++ b/lib/libc/posix1e/acl_to_text.c @@ -0,0 +1,261 @@ +/*- + * Copyright (c) 1999-2002 Robert N. M. Watson + * 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 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 AUTHOR 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. + */ +/* + * acl_to_text - return a text string with a text representation of the acl + * in it. + */ + +#include +__FBSDID("$FreeBSD: releng/10.2/lib/libc/posix1e/acl_to_text.c 200142 2009-12-05 19:04:21Z ed $"); + +#include +#include "namespace.h" +#include +#include "un-namespace.h" +#include +#include +#include +#include + +#include "acl_support.h" + +/* + * acl_to_text - generate a text form of an acl + * spec says nothing about output ordering, so leave in acl order + * + * This function will not produce nice results if it is called with + * a non-POSIX.1e semantics ACL. + */ + +char *_nfs4_acl_to_text_np(const acl_t acl, ssize_t *len_p, int flags); + +static char * +_posix1e_acl_to_text(acl_t acl, ssize_t *len_p, int flags) +{ + struct acl *acl_int; + char *buf, *tmpbuf; + char name_buf[MAXLOGNAME]; + char perm_buf[_POSIX1E_ACL_STRING_PERM_MAXSIZE+1], + effective_perm_buf[_POSIX1E_ACL_STRING_PERM_MAXSIZE+1]; + int i, error, len; + uid_t ae_id; + acl_tag_t ae_tag; + acl_perm_t ae_perm, effective_perm, mask_perm; + + buf = strdup(""); + if (buf == NULL) + return(NULL); + + acl_int = &acl->ats_acl; + + mask_perm = ACL_PERM_BITS; /* effective is regular if no mask */ + for (i = 0; i < acl_int->acl_cnt; i++) + if (acl_int->acl_entry[i].ae_tag == ACL_MASK) + mask_perm = acl_int->acl_entry[i].ae_perm; + + for (i = 0; i < acl_int->acl_cnt; i++) { + ae_tag = acl_int->acl_entry[i].ae_tag; + ae_id = acl_int->acl_entry[i].ae_id; + ae_perm = acl_int->acl_entry[i].ae_perm; + + switch(ae_tag) { + case ACL_USER_OBJ: + error = _posix1e_acl_perm_to_string(ae_perm, + _POSIX1E_ACL_STRING_PERM_MAXSIZE+1, perm_buf); + if (error) + goto error_label; + len = asprintf(&tmpbuf, "%suser::%s\n", buf, + perm_buf); + if (len == -1) + goto error_label; + free(buf); + buf = tmpbuf; + break; + + case ACL_USER: + error = _posix1e_acl_perm_to_string(ae_perm, + _POSIX1E_ACL_STRING_PERM_MAXSIZE+1, perm_buf); + if (error) + goto error_label; + + error = _posix1e_acl_id_to_name(ae_tag, ae_id, + MAXLOGNAME, name_buf, flags); + if (error) + goto error_label; + + effective_perm = ae_perm & mask_perm; + if (effective_perm != ae_perm) { + error = _posix1e_acl_perm_to_string( + effective_perm, + _POSIX1E_ACL_STRING_PERM_MAXSIZE+1, + effective_perm_buf); + if (error) + goto error_label; + len = asprintf(&tmpbuf, "%suser:%s:%s\t\t# " + "effective: %s\n", + buf, name_buf, perm_buf, + effective_perm_buf); + } else { + len = asprintf(&tmpbuf, "%suser:%s:%s\n", buf, + name_buf, perm_buf); + } + if (len == -1) + goto error_label; + free(buf); + buf = tmpbuf; + break; + + case ACL_GROUP_OBJ: + error = _posix1e_acl_perm_to_string(ae_perm, + _POSIX1E_ACL_STRING_PERM_MAXSIZE+1, perm_buf); + if (error) + goto error_label; + + effective_perm = ae_perm & mask_perm; + if (effective_perm != ae_perm) { + error = _posix1e_acl_perm_to_string( + effective_perm, + _POSIX1E_ACL_STRING_PERM_MAXSIZE+1, + effective_perm_buf); + if (error) + goto error_label; + len = asprintf(&tmpbuf, "%sgroup::%s\t\t# " + "effective: %s\n", + buf, perm_buf, effective_perm_buf); + } else { + len = asprintf(&tmpbuf, "%sgroup::%s\n", buf, + perm_buf); + } + if (len == -1) + goto error_label; + free(buf); + buf = tmpbuf; + break; + + case ACL_GROUP: + error = _posix1e_acl_perm_to_string(ae_perm, + _POSIX1E_ACL_STRING_PERM_MAXSIZE+1, perm_buf); + if (error) + goto error_label; + + error = _posix1e_acl_id_to_name(ae_tag, ae_id, + MAXLOGNAME, name_buf, flags); + if (error) + goto error_label; + + effective_perm = ae_perm & mask_perm; + if (effective_perm != ae_perm) { + error = _posix1e_acl_perm_to_string( + effective_perm, + _POSIX1E_ACL_STRING_PERM_MAXSIZE+1, + effective_perm_buf); + if (error) + goto error_label; + len = asprintf(&tmpbuf, "%sgroup:%s:%s\t\t# " + "effective: %s\n", + buf, name_buf, perm_buf, + effective_perm_buf); + } else { + len = asprintf(&tmpbuf, "%sgroup:%s:%s\n", buf, + name_buf, perm_buf); + } + if (len == -1) + goto error_label; + free(buf); + buf = tmpbuf; + break; + + case ACL_MASK: + error = _posix1e_acl_perm_to_string(ae_perm, + _POSIX1E_ACL_STRING_PERM_MAXSIZE+1, perm_buf); + if (error) + goto error_label; + + len = asprintf(&tmpbuf, "%smask::%s\n", buf, + perm_buf); + if (len == -1) + goto error_label; + free(buf); + buf = tmpbuf; + break; + + case ACL_OTHER: + error = _posix1e_acl_perm_to_string(ae_perm, + _POSIX1E_ACL_STRING_PERM_MAXSIZE+1, perm_buf); + if (error) + goto error_label; + + len = asprintf(&tmpbuf, "%sother::%s\n", buf, + perm_buf); + if (len == -1) + goto error_label; + free(buf); + buf = tmpbuf; + break; + + default: + errno = EINVAL; + goto error_label; + } + } + + if (len_p) { + *len_p = strlen(buf); + } + return (buf); + +error_label: + /* jump to here sets errno already, we just clean up */ + if (buf) free(buf); + return (NULL); +} + +char * +acl_to_text_np(acl_t acl, ssize_t *len_p, int flags) +{ + + if (acl == NULL) { + errno = EINVAL; + return(NULL); + } + + switch (_acl_brand(acl)) { + case ACL_BRAND_POSIX: + return (_posix1e_acl_to_text(acl, len_p, flags)); + case ACL_BRAND_NFS4: + return (_nfs4_acl_to_text_np(acl, len_p, flags)); + default: + errno = EINVAL; + return (NULL); + } +} + +char * +acl_to_text(acl_t acl, ssize_t *len_p) +{ + + return (acl_to_text_np(acl, len_p, 0)); +} diff --git a/lib/libc/posix1e/acl_to_text_nfs4.c b/lib/libc/posix1e/acl_to_text_nfs4.c new file mode 100644 index 0000000..49d983a --- /dev/null +++ b/lib/libc/posix1e/acl_to_text_nfs4.c @@ -0,0 +1,264 @@ +/*- + * Copyright (c) 2008, 2009 Edward Tomasz Napierała + * 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 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 AUTHOR 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 +__FBSDID("$FreeBSD: releng/10.2/lib/libc/posix1e/acl_to_text_nfs4.c 208811 2010-06-05 07:40:32Z trasz $"); + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "acl_support.h" + +#define MAX_ENTRY_LENGTH 512 + +static int +format_who(char *str, size_t size, const acl_entry_t entry, int numeric) +{ + int error; + acl_tag_t tag; + struct passwd *pwd; + struct group *grp; + uid_t *id; + + error = acl_get_tag_type(entry, &tag); + if (error) + return (error); + + switch (tag) { + case ACL_USER_OBJ: + snprintf(str, size, "owner@"); + break; + + case ACL_USER: + id = (uid_t *)acl_get_qualifier(entry); + if (id == NULL) + return (-1); + /* XXX: Thread-unsafe. */ + if (!numeric) + pwd = getpwuid(*id); + else + pwd = NULL; + if (pwd == NULL) + snprintf(str, size, "user:%d", (unsigned int)*id); + else + snprintf(str, size, "user:%s", pwd->pw_name); + break; + + case ACL_GROUP_OBJ: + snprintf(str, size, "group@"); + break; + + case ACL_GROUP: + id = (uid_t *)acl_get_qualifier(entry); + if (id == NULL) + return (-1); + /* XXX: Thread-unsafe. */ + if (!numeric) + grp = getgrgid(*id); + else + grp = NULL; + if (grp == NULL) + snprintf(str, size, "group:%d", (unsigned int)*id); + else + snprintf(str, size, "group:%s", grp->gr_name); + break; + + case ACL_EVERYONE: + snprintf(str, size, "everyone@"); + break; + + default: + return (-1); + } + + return (0); +} + +static int +format_entry_type(char *str, size_t size, const acl_entry_t entry) +{ + int error; + acl_entry_type_t entry_type; + + error = acl_get_entry_type_np(entry, &entry_type); + if (error) + return (error); + + switch (entry_type) { + case ACL_ENTRY_TYPE_ALLOW: + snprintf(str, size, "allow"); + break; + case ACL_ENTRY_TYPE_DENY: + snprintf(str, size, "deny"); + break; + case ACL_ENTRY_TYPE_AUDIT: + snprintf(str, size, "audit"); + break; + case ACL_ENTRY_TYPE_ALARM: + snprintf(str, size, "alarm"); + break; + default: + return (-1); + } + + return (0); +} + +static int +format_additional_id(char *str, size_t size, const acl_entry_t entry) +{ + int error; + acl_tag_t tag; + uid_t *id; + + error = acl_get_tag_type(entry, &tag); + if (error) + return (error); + + switch (tag) { + case ACL_USER_OBJ: + case ACL_GROUP_OBJ: + case ACL_EVERYONE: + str[0] = '\0'; + break; + + default: + id = (uid_t *)acl_get_qualifier(entry); + if (id == NULL) + return (-1); + snprintf(str, size, ":%d", (unsigned int)*id); + } + + return (0); +} + +static int +format_entry(char *str, size_t size, const acl_entry_t entry, int flags) +{ + size_t off = 0, min_who_field_length = 18; + acl_permset_t permset; + acl_flagset_t flagset; + int error, len; + char buf[MAX_ENTRY_LENGTH + 1]; + + assert(_entry_brand(entry) == ACL_BRAND_NFS4); + + error = acl_get_flagset_np(entry, &flagset); + if (error) + return (error); + + error = acl_get_permset(entry, &permset); + if (error) + return (error); + + error = format_who(buf, sizeof(buf), entry, + flags & ACL_TEXT_NUMERIC_IDS); + if (error) + return (error); + len = strlen(buf); + if (len < min_who_field_length) + len = min_who_field_length; + off += snprintf(str + off, size - off, "%*s:", len, buf); + + error = _nfs4_format_access_mask(buf, sizeof(buf), *permset, + flags & ACL_TEXT_VERBOSE); + if (error) + return (error); + off += snprintf(str + off, size - off, "%s:", buf); + + error = _nfs4_format_flags(buf, sizeof(buf), *flagset, + flags & ACL_TEXT_VERBOSE); + if (error) + return (error); + off += snprintf(str + off, size - off, "%s:", buf); + + error = format_entry_type(buf, sizeof(buf), entry); + if (error) + return (error); + off += snprintf(str + off, size - off, "%s", buf); + + if (flags & ACL_TEXT_APPEND_ID) { + error = format_additional_id(buf, sizeof(buf), entry); + if (error) + return (error); + off += snprintf(str + off, size - off, "%s", buf); + } + + off += snprintf(str + off, size - off, "\n"); + + /* Make sure we didn't truncate anything. */ + assert (off < size); + + return (0); +} + +char * +_nfs4_acl_to_text_np(const acl_t aclp, ssize_t *len_p, int flags) +{ + int error, off = 0, size, entry_id = ACL_FIRST_ENTRY; + char *str; + acl_entry_t entry; + + if (aclp->ats_acl.acl_cnt == 0) + return strdup(""); + + size = aclp->ats_acl.acl_cnt * MAX_ENTRY_LENGTH; + str = malloc(size); + if (str == NULL) + return (NULL); + + while (acl_get_entry(aclp, entry_id, &entry) == 1) { + entry_id = ACL_NEXT_ENTRY; + + assert(off < size); + + error = format_entry(str + off, size - off, entry, flags); + if (error) { + free(str); + errno = EINVAL; + return (NULL); + } + + off = strlen(str); + } + + assert(off < size); + str[off] = '\0'; + + if (len_p != NULL) + *len_p = off; + + return (str); +} diff --git a/lib/libc/posix1e/acl_valid.3 b/lib/libc/posix1e/acl_valid.3 new file mode 100644 index 0000000..c524df0 --- /dev/null +++ b/lib/libc/posix1e/acl_valid.3 @@ -0,0 +1,170 @@ +.\"- +.\" Copyright (c) 2000, 2002 Robert N. M. Watson +.\" All rights reserved. +.\" +.\" This software was developed by Robert Watson for the TrustedBSD Project. +.\" +.\" 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 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 AUTHOR 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. +.\" +.\" $FreeBSD: releng/10.2/lib/libc/posix1e/acl_valid.3 140288 2005-01-15 12:21:03Z ru $ +.\" +.Dd December 29, 2002 +.Dt ACL_VALID 3 +.Os +.Sh NAME +.Nm acl_valid , +.Nm acl_valid_fd_np , +.Nm acl_valid_file_np , +.Nm acl_valid_link_np +.Nd validate an ACL +.Sh LIBRARY +.Lb libc +.Sh SYNOPSIS +.In sys/types.h +.In sys/acl.h +.Ft int +.Fn acl_valid "acl_t acl" +.Ft int +.Fn acl_valid_fd_np "int fd" "acl_type_t type" "acl_t acl" +.Ft int +.Fn acl_valid_file_np "const char *path_p" "acl_type_t type" "acl_t acl" +.Ft int +.Fn acl_valid_link_np "const char *path_p" "acl_type_t type" "acl_t acl" +.Sh DESCRIPTION +These functions check that the ACL referred to by the argument +.Va acl +is valid. +The POSIX.1e routine, +.Fn acl_valid , +checks this validity only with POSIX.1e ACL semantics, and irrespective +of the context in which the ACL is to be used. +The non-portable forms, +.Fn acl_valid_fd_np , +.Fn acl_valid_file_np , +and +.Fn acl_valid_link_np +allow an ACL to be checked in the context of a specific acl type, +.Va type , +and file system object. +In environments where additional ACL types are +supported than just POSIX.1e, this makes more sense. +Whereas +.Fn acl_valid_file_np +will follow the symlink if the specified path is to a symlink, +.Fn acl_valid_link_np +will not. +.Pp +For POSIX.1e semantics, the checks include: +.Bl -bullet +.It +The three required entries +.Dv ( ACL_USER_OBJ , ACL_GROUP_OBJ , +and +.Dv ACL_OTHER ) +shall exist exactly once in the ACL. +If the ACL contains any +.Dv ACL_USER , ACL_GROUP , +or any other +implementation-defined entries in the file group class +then one +.Dv ACL_MASK +entry shall also be required. +The ACL shall contain at most one +.Dv ACL_MASK +entry. +.It +The qualifier field shall be unique among all entries of +the same POSIX.1e ACL facility defined tag type. +The +tag type field shall contain valid values including any +implementation-defined values. +Validation of the values +of the qualifier field is implementation-defined. +.El +.Pp +The POSIX.1e +.Fn acl_valid +function may reorder the ACL for the purposes of verification; the +non-portable validation functions will not. +.Sh IMPLEMENTATION NOTES +.Fx Ns 's +support for POSIX.1e interfaces and features is still under +development at this time. +.Sh RETURN VALUES +.Rv -std +.Sh ERRORS +If any of the following conditions occur, these functions shall return +-1 and set +.Va errno +to the corresponding value: +.Bl -tag -width Er +.It Bq Er EACCES +Search permission is denied for a component of the path prefix, or the +object exists and the process does not have appropriate access rights. +.It Bq Er EBADF +The +.Va fd +argument is not a valid file descriptor. +.It Bq Er EINVAL +Argument +.Va acl +does not point to a valid ACL. +.Pp +One or more of the required ACL entries is not present in +.Va acl . +.Pp +The ACL contains entries that are not unique. +.Pp +The file system rejects the ACL based on fs-specific semantics issues. +.It Bq Er ENAMETOOLONG +A component of a pathname exceeded 255 characters, or an +entire path name exceeded 1023 characters. +.It Bq Er ENOENT +The named object does not exist, or the +.Va path_p +argument points to an empty string. +.It Bq Er ENOMEM +Insufficient memory available to fulfill request. +.It Bq Er EOPNOTSUPP +The file system does not support ACL retrieval. +.El +.Sh SEE ALSO +.Xr acl 3 , +.Xr acl_get 3 , +.Xr acl_init 3 , +.Xr acl_set 3 , +.Xr posix1e 3 +.Sh STANDARDS +POSIX.1e is described in IEEE POSIX.1e draft 17. +Discussion +of the draft continues on the cross-platform POSIX.1e implementation +mailing list. +To join this list, see the +.Fx +POSIX.1e implementation +page for more information. +.Sh HISTORY +POSIX.1e support was introduced in +.Fx 4.0 , +and development continues. +.Sh AUTHORS +.An Robert N M Watson diff --git a/lib/libc/posix1e/acl_valid.c b/lib/libc/posix1e/acl_valid.c new file mode 100644 index 0000000..070a3ae --- /dev/null +++ b/lib/libc/posix1e/acl_valid.c @@ -0,0 +1,124 @@ +/*- + * Copyright (c) 1999, 2000, 2001, 2002 Robert N. M. Watson + * All rights reserved. + * + * This software was developed by Robert Watson for the TrustedBSD Project. + * + * 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 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 AUTHOR 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. + */ +/* + * acl_valid -- POSIX.1e ACL check routine + */ + +#include +__FBSDID("$FreeBSD: releng/10.2/lib/libc/posix1e/acl_valid.c 208785 2010-06-03 14:29:17Z trasz $"); + +#include +#include "namespace.h" +#include +#include "un-namespace.h" +#include +#include + +#include "acl_support.h" + +/* + * acl_valid: accepts an ACL, returns 0 on valid ACL, -1 for invalid, + * and errno set to EINVAL. + * + * Implemented by calling the acl_check routine in acl_support, which + * requires ordering. We call acl_support's _posix1e_acl_sort to make this + * true. POSIX.1e allows acl_valid() to reorder the ACL as it sees fit. + * + * This call is deprecated, as it doesn't ask whether the ACL is valid + * for a particular target. However, this call is standardized, unlike + * the other two forms. + */ +int +acl_valid(acl_t acl) +{ + int error; + + if (acl == NULL) { + errno = EINVAL; + return (-1); + } + if (!_acl_brand_may_be(acl, ACL_BRAND_POSIX)) { + errno = EINVAL; + return (-1); + } + _posix1e_acl_sort(acl); + error = _posix1e_acl_check(acl); + if (error) { + errno = error; + return (-1); + } else { + return (0); + } +} + +int +acl_valid_file_np(const char *pathp, acl_type_t type, acl_t acl) +{ + + if (pathp == NULL || acl == NULL) { + errno = EINVAL; + return (-1); + } + type = _acl_type_unold(type); + if (_posix1e_acl(acl, type)) + _posix1e_acl_sort(acl); + + return (__acl_aclcheck_file(pathp, type, &acl->ats_acl)); +} + +int +acl_valid_link_np(const char *pathp, acl_type_t type, acl_t acl) +{ + + if (pathp == NULL || acl == NULL) { + errno = EINVAL; + return (-1); + } + type = _acl_type_unold(type); + if (_posix1e_acl(acl, type)) + _posix1e_acl_sort(acl); + + return (__acl_aclcheck_link(pathp, type, &acl->ats_acl)); +} + +int +acl_valid_fd_np(int fd, acl_type_t type, acl_t acl) +{ + + if (acl == NULL) { + errno = EINVAL; + return (-1); + } + type = _acl_type_unold(type); + if (_posix1e_acl(acl, type)) + _posix1e_acl_sort(acl); + + acl->ats_cur_entry = 0; + + return (___acl_aclcheck_fd(fd, type, &acl->ats_acl)); +} diff --git a/lib/libc/posix1e/extattr.3 b/lib/libc/posix1e/extattr.3 new file mode 100644 index 0000000..4be28d7 --- /dev/null +++ b/lib/libc/posix1e/extattr.3 @@ -0,0 +1,100 @@ +.\" +.\" Copyright (c) 2001 Dima Dorfman +.\" 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 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 AUTHOR 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. +.\" +.\" $FreeBSD: releng/10.2/lib/libc/posix1e/extattr.3 107788 2002-12-12 17:26:04Z ru $ +.\" +.Dd June 24, 2001 +.Dt EXTATTR 3 +.Os +.Sh NAME +.Nm extattr_namespace_to_string , +.Nm extattr_string_to_namespace +.Nd convert an extended attribute namespace identifier to a string and +vice versa +.Sh LIBRARY +.Lb libutil +.Sh SYNOPSIS +.In sys/extattr.h +.In libutil.h +.Ft int +.Fn extattr_namespace_to_string "int attrnamespace" "char **string" +.Ft int +.Fn extattr_string_to_namespace "const char *string" "int *attrnamespace" +.Sh DESCRIPTION +The +.Fn extattr_namespace_to_string +function converts a VFS extended attribute identifier to a human-readable +string; +the +.Fn extattr_string_to_namespace +function undoes the aforementioned operation, +and converts a human-readable string representing a namespace to a +namespace identifier. +Although a file system may implement arbitrary namespaces, +these functions only support the +.Dv EXTATTR_NAMESPACE_USER +.Pq Dq user +and +.Dv EXTATTR_NAMESPACE_SYSTEM +.Pq Dq system +namespaces, +which are defined in +.Xr extattr 9 . +.Pp +These functions are meant to be used in error reporting and other +interactive tasks. +For example, +instead of printing the integer identifying an extended attribute in +an error message, +a program might use +.Fn extattr_namespace_to_string +to obtain a human-readable representation. +Likewise, +instead of requiring a user to enter the integer representing a namespace, +an interactive program might ask for a name and use +.Fn extattr_string_to_namespace +to get the desired identifier. +.Sh RETURN VALUES +If any of the calls are unsuccessful, the value \-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 requested namespace could not be identified. +.El +.Sh SEE ALSO +.Xr extattr 2 , +.Xr getextattr 8 , +.Xr setextattr 8 , +.Xr extattr 9 +.Sh HISTORY +Extended attribute support was developed as part of the +.Tn TrustedBSD +Project, and introduced in +.Fx 5.0 . +It was developed to support security extensions requiring additional labels +to be associated with each file or directory. diff --git a/lib/libc/posix1e/extattr.c b/lib/libc/posix1e/extattr.c new file mode 100644 index 0000000..90801fc --- /dev/null +++ b/lib/libc/posix1e/extattr.c @@ -0,0 +1,77 @@ +/*- + * Copyright (c) 2001 Robert N. M. Watson + * 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 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 AUTHOR 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. + */ +/* + * TrustedBSD: Utility functions for extended attributes. + */ + +#include +__FBSDID("$FreeBSD: releng/10.2/lib/libc/posix1e/extattr.c 150065 2005-09-12 19:52:42Z stefanf $"); + +#include +#include + +#include +#include +#include + +int +extattr_namespace_to_string(int attrnamespace, char **string) +{ + + switch(attrnamespace) { + case EXTATTR_NAMESPACE_USER: + if (string != NULL) + *string = strdup(EXTATTR_NAMESPACE_USER_STRING); + return (0); + + case EXTATTR_NAMESPACE_SYSTEM: + if (string != NULL) + *string = strdup(EXTATTR_NAMESPACE_SYSTEM_STRING); + return (0); + + default: + errno = EINVAL; + return (-1); + } +} + +int +extattr_string_to_namespace(const char *string, int *attrnamespace) +{ + + if (!strcmp(string, EXTATTR_NAMESPACE_USER_STRING)) { + if (attrnamespace != NULL) + *attrnamespace = EXTATTR_NAMESPACE_USER; + return (0); + } else if (!strcmp(string, EXTATTR_NAMESPACE_SYSTEM_STRING)) { + if (attrnamespace != NULL) + *attrnamespace = EXTATTR_NAMESPACE_SYSTEM; + return (0); + } else { + errno = EINVAL; + return (-1); + } +} diff --git a/lib/libc/posix1e/mac.3 b/lib/libc/posix1e/mac.3 new file mode 100644 index 0000000..2d77759 --- /dev/null +++ b/lib/libc/posix1e/mac.3 @@ -0,0 +1,176 @@ +.\" Copyright (c) 2001, 2003 Networks Associates Technology, Inc. +.\" Copyright (c) 2009 Robert N. M. Watson +.\" All rights reserved. +.\" +.\" This software was developed for the FreeBSD Project by Chris +.\" Costello at Safeport Network Services and Network Associates +.\" Laboratories, the Security Research Division of Network Associates, +.\" Inc. under DARPA/SPAWAR contract N66001-01-C-8035 ("CBOSS"), as part +.\" of the DARPA CHATS research program. +.\" +.\" 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 AUTHORS 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 AUTHORS 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. +.\" +.\" $FreeBSD: releng/10.2/lib/libc/posix1e/mac.3 210772 2010-08-02 16:01:45Z joel $ +.\" +.Dd August 7, 2009 +.Dt MAC 3 +.Os +.Sh NAME +.Nm mac +.Nd introduction to the MAC security API +.Sh LIBRARY +.Lb libc +.Sh SYNOPSIS +.In sys/mac.h +.Pp +In the kernel configuration file: +.Cd "options MAC" +.Sh DESCRIPTION +Mandatory Access Control labels describe confidentiality, integrity, and +other security attributes of operating system objects, overriding +discretionary access control. +Not all system objects support MAC labeling, and MAC policies must be +explicitly enabled by the administrator. +This API, based on POSIX.1e, includes routines to retrieve, manipulate, set, +and convert to and from text the MAC labels on files and processes. +.Pp +MAC labels consist of a set of (name, value) tuples, representing security +attributes from MAC policies. +For example, this label contains security labels defined by two policies, +.Xr mac_biba 4 +and +.Xr mac_mls 4 : +.Bd -literal -offset indent +biba/low,mls/low +.Ed +.Pp +Further syntax and semantics of MAC labels may be found in +.Xr maclabel 7 . +.Pp +Applications operate on labels stored in +.Vt mac_t , +but can convert between this internal format and a text format for the +purposes of presentation to uses or external storage. +When querying a label on an object, a +.Vt mac_t +must first be prepared using the interfaces described in +.Xr mac_prepare 3 , +allowing the application to declare which policies it wishes to interrogate. +The application writer can also rely on default label names declared in +.Xr mac.conf 5 . +.Pp +When finished with a +.Vt mac_t , +the application must call +.Xr mac_free 3 +to release its storage. +.Pp +The following functions are defined: +.Bl -tag -width indent +.It Fn mac_is_present +This function, described in +.Xr mac_is_present 3 , +allows applications to test whether MAC is configured, as well as whether +specific policies are configured. +.It Fn mac_get_fd , Fn mac_get_file , Fn mac_get_link , Fn mac_get_peer +These functions, described in +.Xr mac_get 3 , +retrieve the MAC labels associated with file descriptors, files, and socket +peers. +.It Fn mac_get_pid , Fn mac_get_proc +These functions, described in +.Xr mac_get 3 , +retrieve the MAC labels associated with processes. +.It Fn mac_set_fd , Fn mac_set_file , Fn mac_set_link +These functions, described in +.Xr mac_set 3 , +set the MAC labels associated with file descriptors and files. +.It Fn mac_set_proc +This function, described in +.Xr mac_set 3 , +sets the MAC label associated with the current process. +.It Fn mac_free +This function, described in +.Xr mac_free 3 , +frees working MAC label storage. +.It Fn mac_from_text +This function, described in +.Xr mac_text 3 , +converts a text-form MAC label into working MAC label storage, +.Vt mac_t . +.It Fn mac_prepare , Fn mac_prepare_file_label , Fn mac_prepare_ifnet_label , Fn mac_prepare_process_label , Fn mac_prepare_type +These functions, described in +.Xr mac_prepare 3 , +allocate working storage for MAC label operations. +.Xr mac_prepare 3 +prepares a label based on caller-specified label names; the other calls +rely on the default configuration specified in +.Xr mac.conf 5 . +.It Fn mac_to_text +This function is described in +.Xr mac_text 3 , +and may be used to convert a +.Vt mac_t +into a text-form MAC label. +.El +.Sh FILES +.Bl -tag -width ".Pa /etc/mac.conf" -compact +.It Pa /etc/mac.conf +MAC library configuration file, documented in +.Xr mac.conf 5 . +Provides default behavior for applications aware of MAC labels on +system objects, but without policy-specific knowledge. +.El +.Sh SEE ALSO +.Xr mac_free 3 , +.Xr mac_get 3 , +.Xr mac_is_present 3 , +.Xr mac_prepare 3 , +.Xr mac_set 3 , +.Xr mac_text 3 , +.Xr posix1e 3 , +.Xr mac 4 , +.Xr mac.conf 5 , +.Xr mac 9 +.Sh STANDARDS +These APIs are loosely based on the APIs described in POSIX.1e, as described +in IEEE POSIX.1e draft 17. +However, the resemblance of these APIs to the POSIX APIs is loose, as the +POSIX APIs were unable to express some notions required for flexible and +extensible access control. +.Sh HISTORY +Support for Mandatory Access Control was introduced in +.Fx 5.0 +as part of the +.Tn TrustedBSD +Project. +.Sh BUGS +The +.Tn TrustedBSD +MAC Framework and associated policies, interfaces, and +applications are considered to be an experimental feature in +.Fx . +Sites considering production deployment should keep the experimental +status of these services in mind during any deployment process. +See also +.Xr mac 9 +for related considerations regarding the kernel framework. diff --git a/lib/libc/posix1e/mac.c b/lib/libc/posix1e/mac.c new file mode 100644 index 0000000..10bae79 --- /dev/null +++ b/lib/libc/posix1e/mac.c @@ -0,0 +1,449 @@ +/* + * Copyright (c) 1999, 2000, 2001, 2002 Robert N. M. Watson + * Copyright (c) 2002, 2003 Networks Associates Technology, Inc. + * All rights reserved. + * + * This software was developed by Robert Watson for the TrustedBSD Project. + * + * This software was developed for the FreeBSD Project in part by Network + * Associates Laboratories, the Security Research Division of Network + * Associates, Inc. under DARPA/SPAWAR contract N66001-01-C-8035 ("CBOSS"), + * as part of the DARPA CHATS research program. + * + * 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 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 AUTHOR 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 +__FBSDID("$FreeBSD: releng/10.2/lib/libc/posix1e/mac.c 254700 2013-08-23 13:59:47Z jilles $"); + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include + +static int internal_initialized; + +/* + * Maintain a list of default label preparations for various object + * types. Each name will appear only once in the list. + * + * XXXMAC: Not thread-safe. + */ +static LIST_HEAD(, label_default) label_default_head; +struct label_default { + char *ld_name; + char *ld_labels; + LIST_ENTRY(label_default) ld_entries; +}; + +static void +mac_destroy_labels(void) +{ + struct label_default *ld; + + while ((ld = LIST_FIRST(&label_default_head))) { + free(ld->ld_name); + free(ld->ld_labels); + LIST_REMOVE(ld, ld_entries); + free(ld); + } +} + +static void +mac_destroy_internal(void) +{ + + mac_destroy_labels(); + + internal_initialized = 0; +} + +static int +mac_add_type(const char *name, const char *labels) +{ + struct label_default *ld, *ld_new; + char *name_dup, *labels_dup; + + /* + * Speculatively allocate all the memory now to avoid allocating + * later when we will someday hold a mutex. + */ + name_dup = strdup(name); + if (name_dup == NULL) { + errno = ENOMEM; + return (-1); + } + labels_dup = strdup(labels); + if (labels_dup == NULL) { + free(name_dup); + errno = ENOMEM; + return (-1); + } + ld_new = malloc(sizeof(*ld)); + if (ld_new == NULL) { + free(name_dup); + free(labels_dup); + errno = ENOMEM; + return (-1); + } + + /* + * If the type is already present, replace the current entry + * rather than add a new instance. + */ + for (ld = LIST_FIRST(&label_default_head); ld != NULL; + ld = LIST_NEXT(ld, ld_entries)) { + if (strcmp(name, ld->ld_name) == 0) + break; + } + + if (ld != NULL) { + free(ld->ld_labels); + ld->ld_labels = labels_dup; + labels_dup = NULL; + } else { + ld = ld_new; + ld->ld_name = name_dup; + ld->ld_labels = labels_dup; + + ld_new = NULL; + name_dup = NULL; + labels_dup = NULL; + + LIST_INSERT_HEAD(&label_default_head, ld, ld_entries); + } + + if (name_dup != NULL) + free(name_dup); + if (labels_dup != NULL) + free(labels_dup); + if (ld_new != NULL) + free(ld_new); + + return (0); +} + +static char * +next_token(char **string) +{ + char *token; + + token = strsep(string, " \t"); + while (token != NULL && *token == '\0') + token = strsep(string, " \t"); + + return (token); +} + +static int +mac_init_internal(int ignore_errors) +{ + const char *filename; + char line[LINE_MAX]; + FILE *file; + int error; + + error = 0; + + LIST_INIT(&label_default_head); + + if (!issetugid() && getenv("MAC_CONFFILE") != NULL) + filename = getenv("MAC_CONFFILE"); + else + filename = MAC_CONFFILE; + file = fopen(filename, "re"); + if (file == NULL) + return (0); + + while (fgets(line, LINE_MAX, file)) { + char *comment, *parse, *statement; + + if (line[strlen(line)-1] == '\n') + line[strlen(line)-1] = '\0'; + else { + if (ignore_errors) + continue; + fclose(file); + error = EINVAL; + goto just_return; + } + + /* Remove any comment. */ + comment = line; + parse = strsep(&comment, "#"); + + /* Blank lines OK. */ + statement = next_token(&parse); + if (statement == NULL) + continue; + + if (strcmp(statement, "default_labels") == 0) { + char *name, *labels; + + name = next_token(&parse); + labels = next_token(&parse); + if (name == NULL || labels == NULL || + next_token(&parse) != NULL) { + if (ignore_errors) + continue; + error = EINVAL; + fclose(file); + goto just_return; + } + + if (mac_add_type(name, labels) == -1) { + if (ignore_errors) + continue; + fclose(file); + goto just_return; + } + } else if (strcmp(statement, "default_ifnet_labels") == 0 || + strcmp(statement, "default_file_labels") == 0 || + strcmp(statement, "default_process_labels") == 0) { + char *labels, *type; + + if (strcmp(statement, "default_ifnet_labels") == 0) + type = "ifnet"; + else if (strcmp(statement, "default_file_labels") == 0) + type = "file"; + else if (strcmp(statement, "default_process_labels") == + 0) + type = "process"; + + labels = next_token(&parse); + if (labels == NULL || next_token(&parse) != NULL) { + if (ignore_errors) + continue; + error = EINVAL; + fclose(file); + goto just_return; + } + + if (mac_add_type(type, labels) == -1) { + if (ignore_errors) + continue; + fclose(file); + goto just_return; + } + } else { + if (ignore_errors) + continue; + fclose(file); + error = EINVAL; + goto just_return; + } + } + + fclose(file); + + internal_initialized = 1; + +just_return: + if (error != 0) + mac_destroy_internal(); + return (error); +} + +static int +mac_maybe_init_internal(void) +{ + + if (!internal_initialized) + return (mac_init_internal(1)); + else + return (0); +} + +int +mac_reload(void) +{ + + if (internal_initialized) + mac_destroy_internal(); + return (mac_init_internal(0)); +} + +int +mac_free(struct mac *mac) +{ + + if (mac->m_string != NULL) + free(mac->m_string); + free(mac); + + return (0); +} + +int +mac_from_text(struct mac **mac, const char *text) +{ + + *mac = (struct mac *) malloc(sizeof(**mac)); + if (*mac == NULL) + return (ENOMEM); + + (*mac)->m_string = strdup(text); + if ((*mac)->m_string == NULL) { + free(*mac); + *mac = NULL; + return (ENOMEM); + } + + (*mac)->m_buflen = strlen((*mac)->m_string)+1; + + return (0); +} + +int +mac_to_text(struct mac *mac, char **text) +{ + + *text = strdup(mac->m_string); + if (*text == NULL) + return (ENOMEM); + return (0); +} + +int +mac_prepare(struct mac **mac, const char *elements) +{ + + if (strlen(elements) >= MAC_MAX_LABEL_BUF_LEN) + return (EINVAL); + + *mac = (struct mac *) malloc(sizeof(**mac)); + if (*mac == NULL) + return (ENOMEM); + + (*mac)->m_string = malloc(MAC_MAX_LABEL_BUF_LEN); + if ((*mac)->m_string == NULL) { + free(*mac); + *mac = NULL; + return (ENOMEM); + } + + strcpy((*mac)->m_string, elements); + (*mac)->m_buflen = MAC_MAX_LABEL_BUF_LEN; + + return (0); +} + +int +mac_prepare_type(struct mac **mac, const char *name) +{ + struct label_default *ld; + int error; + + error = mac_maybe_init_internal(); + if (error != 0) + return (error); + + for (ld = LIST_FIRST(&label_default_head); ld != NULL; + ld = LIST_NEXT(ld, ld_entries)) { + if (strcmp(name, ld->ld_name) == 0) + return (mac_prepare(mac, ld->ld_labels)); + } + + errno = ENOENT; + return (-1); /* XXXMAC: ENOLABEL */ +} + +int +mac_prepare_ifnet_label(struct mac **mac) +{ + + return (mac_prepare_type(mac, "ifnet")); +} + +int +mac_prepare_file_label(struct mac **mac) +{ + + return (mac_prepare_type(mac, "file")); +} + +int +mac_prepare_packet_label(struct mac **mac) +{ + + return (mac_prepare_type(mac, "packet")); +} + +int +mac_prepare_process_label(struct mac **mac) +{ + + return (mac_prepare_type(mac, "process")); +} + +/* + * Simply test whether the TrustedBSD/MAC MIB tree is present; if so, + * return 1 to indicate that the system has MAC enabled overall or for + * a given policy. + */ +int +mac_is_present(const char *policyname) +{ + int mib[5]; + size_t siz; + char *mibname; + int error; + + if (policyname != NULL) { + if (policyname[strcspn(policyname, ".=")] != '\0') { + errno = EINVAL; + return (-1); + } + mibname = malloc(sizeof("security.mac.") - 1 + + strlen(policyname) + sizeof(".enabled")); + if (mibname == NULL) + return (-1); + strcpy(mibname, "security.mac."); + strcat(mibname, policyname); + strcat(mibname, ".enabled"); + siz = 5; + error = sysctlnametomib(mibname, mib, &siz); + free(mibname); + } else { + siz = 3; + error = sysctlnametomib("security.mac", mib, &siz); + } + if (error == -1) { + switch (errno) { + case ENOTDIR: + case ENOENT: + return (0); + default: + return (error); + } + } + return (1); +} diff --git a/lib/libc/posix1e/mac.conf.5 b/lib/libc/posix1e/mac.conf.5 new file mode 100644 index 0000000..0badcda --- /dev/null +++ b/lib/libc/posix1e/mac.conf.5 @@ -0,0 +1,123 @@ +.\" Copyright (c) 2003 Networks Associates Technology, Inc. +.\" All rights reserved. +.\" +.\" This software was developed for the FreeBSD Project in part by Network +.\" Associates Laboratories, the Security Research Division of Network +.\" Associates, Inc. under DARPA/SPAWAR contract N66001-01-C-8035 ("CBOSS"), +.\" as part of the DARPA CHATS research program. +.\" +.\" 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 AUTHORS 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 AUTHORS 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. +.\" +.\" $FreeBSD: releng/10.2/lib/libc/posix1e/mac.conf.5 140505 2005-01-20 09:17:07Z ru $ +.\" +.Dd April 19, 2003 +.Dt MAC.CONF 5 +.Os +.Sh NAME +.Nm mac.conf +.Nd format of the MAC library configuration file +.Sh DESCRIPTION +The +.Nm +file configures the default label elements to be used by policy-agnostic +applications that operate on MAC labels. +A file contains a series of default label sets specified by object class, +in addition to blank lines and comments preceded by a +.Ql # +symbol. +.Pp +Currently, the implementation supports two syntax styles for label +element declaration. +The old (deprecated) syntax consists of a +single line with two fields separated by white space: the object +class name, and a list of label elements as used by the +.Xr mac_prepare 3 +library calls prior to an application invocation of a function from +.Xr mac_get 3 . +.Pp +The newer more preferred syntax consists of three fields separated by +white space: the label group, object class name and a list of +label elements. +.Pp +Label element names may optionally begin with a +.Ql \&? +symbol to indicate that a failure to retrieve the label element for +an object should be silently ignored, and improves usability if the +set of MAC policies may change over time. +.Sh FILES +.Bl -tag -width ".Pa /etc/mac.conf" -compact +.It Pa /etc/mac.conf +MAC library configuration file. +.El +.Sh EXAMPLES +The following example configures user applications to operate with +four MAC policies: +.Xr mac_biba 4 , +.Xr mac_mls 4 , +SEBSD, +and +.Xr mac_partition 4 . +.Bd -literal -offset indent +# +# Default label set to be used by simple MAC applications + +default_labels file ?biba,?lomac,?mls,?sebsd +default_labels ifnet ?biba,?lomac,?mls,?sebsd +default_labels process ?biba,?lomac,?mls,?partition,?sebsd +default_labels socket ?biba,?lomac,?mls + +# +# Deprecated (old) syntax + +default_file_labels ?biba,?mls,?sebsd +default_ifnet_labels ?biba,?mls,?sebsd +default_process_labels ?biba,?mls,partition,?sebsd +.Ed +.Pp +In this example, userland applications will attempt to retrieve Biba, +MLS, and SEBSD labels for all object classes; for processes, they will +additionally attempt to retrieve a Partition identifier. +In all cases except the Partition identifier, failure to retrieve a +label due to the respective policy not being present will be ignored. +.Sh SEE ALSO +.Xr mac 3 , +.Xr mac_get 3 , +.Xr mac_prepare 3 , +.Xr mac 4 , +.Xr mac 9 +.Sh HISTORY +Support for Mandatory Access Control was introduced in +.Fx 5.0 +as part of the +.Tn TrustedBSD +Project. +.Sh BUGS +The +.Tn TrustedBSD +MAC Framework and associated policies, interfaces, and +applications are considered to be an experimental feature in +.Fx . +Sites considering production deployment should keep the experimental +status of these services in mind during any deployment process. +See also +.Xr mac 9 +for related considerations regarding the kernel framework. diff --git a/lib/libc/posix1e/mac_exec.c b/lib/libc/posix1e/mac_exec.c new file mode 100644 index 0000000..cd2ad17 --- /dev/null +++ b/lib/libc/posix1e/mac_exec.c @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2002 Networks Associates Technology, Inc. + * All rights reserved. + * + * This software was developed for the FreeBSD Project in part by Network + * Associates Laboratories, the Security Research Division of Network + * Associates, Inc. under DARPA/SPAWAR contract N66001-01-C-8035 ("CBOSS"), + * as part of the DARPA CHATS research program. + * + * 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 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 AUTHOR 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 +__FBSDID("$FreeBSD: releng/10.2/lib/libc/posix1e/mac_exec.c 176901 2008-03-07 15:25:56Z rwatson $"); + +#include +#include + +extern int __mac_execve(char *fname, char **argv, char **envv, + struct mac *mac_p); + +int +mac_execve(char *fname, char **argv, char **envv, struct mac *label) +{ + + return (__mac_execve(fname, argv, envv, label)); +} diff --git a/lib/libc/posix1e/mac_free.3 b/lib/libc/posix1e/mac_free.3 new file mode 100644 index 0000000..fed6447 --- /dev/null +++ b/lib/libc/posix1e/mac_free.3 @@ -0,0 +1,99 @@ +.\" Copyright (c) 2001, 2002 Networks Associates Technology, Inc. +.\" All rights reserved. +.\" +.\" This software was developed for the FreeBSD Project by Chris +.\" Costello at Safeport Network Services and NAI Labs, the Security +.\" Research Division of Network Associates, Inc. under DARPA/SPAWAR +.\" contract N66001-01-C-8035 ("CBOSS"), as part of the DARPA CHATS +.\" research program. +.\" +.\" 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 not be used to endorse or promote +.\" products derived from this software without specific prior written +.\" permission. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS 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 AUTHORS 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. +.\" +.\" $FreeBSD: releng/10.2/lib/libc/posix1e/mac_free.3 196123 2009-08-12 10:46:48Z rwatson $ +.\" +.Dd December 21, 2001 +.Dt MAC_FREE 3 +.Os +.Sh NAME +.Nm mac_free +.Nd free MAC label +.Sh LIBRARY +.Lb libc +.Sh SYNOPSIS +.In sys/mac.h +.Ft int +.Fn mac_free "mac_t label" +.Sh DESCRIPTION +The +.Fn mac_free +function frees the storage allocated to contain a +.Vt mac_t . +.Sh RETURN VALUES +The +.Fn mac_free +function always returns 0. +WARNING: see the notes in the +.Sx BUGS +section regarding the use of this +function. +.Sh SEE ALSO +.Xr mac 3 , +.Xr mac_get 3 , +.Xr mac_prepare 3 , +.Xr mac_set 3 , +.Xr mac_text 3 , +.Xr posix1e 3 , +.Xr mac 4 , +.Xr mac 9 +.Sh STANDARDS +POSIX.1e is described in IEEE POSIX.1e draft 17. +Discussion of the draft +continues on the cross-platform POSIX.1e implementation mailing list. +To join this list, see the +.Fx +POSIX.1e implementation page +for more information. +.Sh HISTORY +Support for Mandatory Access Control was introduced in +.Fx 5.0 +as part of the +.Tn TrustedBSD +Project. +.Sh BUGS +POSIX.1e specifies that +.Fn mac_free +will be used to free text strings created using +.Xr mac_to_text 3 . +Because +.Vt mac_t +is a complex structure in the +.Tn TrustedBSD +implementation, +.Fn mac_free +is specific to +.Vt mac_3 , +and must not be used to free the character strings returned from +.Fn mac_to_text . +Doing so may result in undefined behavior. diff --git a/lib/libc/posix1e/mac_get.3 b/lib/libc/posix1e/mac_get.3 new file mode 100644 index 0000000..13b247b --- /dev/null +++ b/lib/libc/posix1e/mac_get.3 @@ -0,0 +1,152 @@ +.\" Copyright (c) 2001, 2004 Networks Associates Technology, Inc. +.\" All rights reserved. +.\" +.\" This software was developed for the FreeBSD Project by Chris +.\" Costello at Safeport Network Services and NAI Labs, the Security +.\" Research Division of Network Associates, Inc. under DARPA/SPAWAR +.\" contract N66001-01-C-8035 ("CBOSS"), as part of the DARPA CHATS +.\" research program. +.\" +.\" 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 AUTHORS 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 AUTHORS 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. +.\" +.\" $FreeBSD: releng/10.2/lib/libc/posix1e/mac_get.3 196123 2009-08-12 10:46:48Z rwatson $ +.\" +.Dd December 21, 2001 +.Dt MAC_GET 3 +.Os +.Sh NAME +.Nm mac_get_file , +.Nm mac_get_link , +.Nm mac_get_fd , +.Nm mac_get_peer , +.Nm mac_get_pid , +.Nm mac_get_proc +.Nd get the label of a file, socket, socket peer or process +.Sh LIBRARY +.Lb libc +.Sh SYNOPSIS +.In sys/mac.h +.Ft int +.Fn mac_get_file "const char *path" "mac_t label" +.Ft int +.Fn mac_get_link "const char *path" "mac_t label" +.Ft int +.Fn mac_get_fd "int fd" "mac_t label" +.Ft int +.Fn mac_get_peer "int fd" "mac_t label" +.Ft int +.Fn mac_get_pid "pid_t pid" "mac_t label" +.Ft int +.Fn mac_get_proc "mac_t label" +.Sh DESCRIPTION +The +.Fn mac_get_file +system call returns the label associated with a file specified by +pathname. +The +.Fn mac_get_link +function is the same as +.Fn mac_get_file , +except that it does not follow symlinks. +.Pp +The +.Fn mac_get_fd +system call returns the label associated with an object referenced by +the specified file descriptor. +Note that in the case of a file system socket, the label returned will +be the socket label, which may be different from the label of the +on-disk node acting as a rendezvous for the socket. +The +.Fn mac_get_peer +system call returns the label associated with the remote endpoint of +a socket; the exact semantics of this call will depend on the protocol +domain, communications type, and endpoint; typically this label will +be cached when a connection-oriented protocol instance is first set up, +and is undefined for datagram protocols. +.Pp +The +.Fn mac_get_pid +and +.Fn mac_get_proc +system calls return the process label associated with an arbitrary +process ID, or the current process. +.Pp +Label storage for use with these calls must first be allocated and +prepared using the +.Xr mac_prepare 3 +functions. +When an application is done using a label, the memory may be returned +using +.Xr mac_free 3 . +.Sh ERRORS +.Bl -tag -width Er +.It Bq Er EACCES +A component of +.Fa path +is not searchable, +or MAC read access to the file +is denied. +.It Bq Er EINVAL +The requested label operation is not valid for the object referenced by +.Fa fd . +.It Bq Er ENAMETOOLONG +The pathname pointed to by +.Fa path +exceeds +.Dv PATH_MAX , +or a component of the pathname exceeds +.Dv NAME_MAX . +.It Bq Er ENOENT +A component of +.Fa path +does not exist. +.It Bq Er ENOMEM +Insufficient memory is available +to allocate a new MAC label structure. +.It Bq Er ENOTDIR +A component of +.Fa path +is not a directory. +.El +.Sh SEE ALSO +.Xr mac 3 , +.Xr mac_free 3 , +.Xr mac_prepare 3 , +.Xr mac_set 3 , +.Xr mac_text 3 , +.Xr posix1e 3 , +.Xr mac 4 , +.Xr mac 9 +.Sh STANDARDS +POSIX.1e is described in IEEE POSIX.1e draft 17. +Discussion of the draft +continues on the cross-platform POSIX.1e implementation mailing list. +To join this list, see the +.Fx +POSIX.1e implementation page +for more information. +.Sh HISTORY +Support for Mandatory Access Control was introduced in +.Fx 5.0 +as part of the +.Tn TrustedBSD +Project. diff --git a/lib/libc/posix1e/mac_get.c b/lib/libc/posix1e/mac_get.c new file mode 100644 index 0000000..20fa55f --- /dev/null +++ b/lib/libc/posix1e/mac_get.c @@ -0,0 +1,87 @@ +/* + * Copyright (c) 1999, 2000, 2001, 2002 Robert N. M. Watson + * All rights reserved. + * + * This software was developed by Robert Watson for the TrustedBSD Project. + * + * 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 names of the authors 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 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 AUTHOR 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 +__FBSDID("$FreeBSD: releng/10.2/lib/libc/posix1e/mac_get.c 176901 2008-03-07 15:25:56Z rwatson $"); + +#include +#include +#include + +extern int __mac_get_fd(int fd, struct mac *mac_p); +extern int __mac_get_file(const char *path_p, struct mac *mac_p); +extern int __mac_get_link(const char *path_p, struct mac *mac_p); +extern int __mac_get_pid(pid_t pid, struct mac *mac_p); +extern int __mac_get_proc(struct mac *mac_p); + +int +mac_get_fd(int fd, struct mac *label) +{ + + return (__mac_get_fd(fd, label)); +} + +int +mac_get_file(const char *path, struct mac *label) +{ + + return (__mac_get_file(path, label)); +} + +int +mac_get_link(const char *path, struct mac *label) +{ + + return (__mac_get_link(path, label)); +} + +int +mac_get_peer(int fd, struct mac *label) +{ + socklen_t len; + + len = sizeof(*label); + return (getsockopt(fd, SOL_SOCKET, SO_PEERLABEL, label, &len)); +} + +int +mac_get_pid(pid_t pid, struct mac *label) +{ + + return (__mac_get_pid(pid, label)); +} + +int +mac_get_proc(struct mac *label) +{ + + return (__mac_get_proc(label)); +} diff --git a/lib/libc/posix1e/mac_is_present.3 b/lib/libc/posix1e/mac_is_present.3 new file mode 100644 index 0000000..1f6d6a1 --- /dev/null +++ b/lib/libc/posix1e/mac_is_present.3 @@ -0,0 +1,87 @@ +.\" Copyright (c) 2002 Networks Associates Technology, Inc. +.\" All rights reserved. +.\" +.\" This software was developed for the FreeBSD Project by Chris +.\" Costello at Safeport Network Services and NAI Labs, the Security +.\" Research Division of Network Associates, Inc. under DARPA/SPAWAR +.\" contract N66001-01-C-8035 ("CBOSS"), as part of the DARPA CHATS +.\" research program. +.\" +.\" 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 AUTHORS 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 AUTHORS 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. +.\" +.\" $FreeBSD: releng/10.2/lib/libc/posix1e/mac_is_present.3 162841 2006-09-30 10:34:13Z ru $ +.\" +.Dd July 7, 2006 +.Dt MAC_IS_PRESENT 3 +.Os +.Sh NAME +.Nm mac_is_present +.Nd report whether the running system has MAC support +.Sh LIBRARY +.Lb libc +.Sh SYNOPSIS +.In sys/mac.h +.Ft int +.Fn mac_is_present "const char *policyname" +.Sh DESCRIPTION +The +.Fn mac_is_present +function determines whether the currently-running kernel supports MAC for +a given policy or not. +If +.Fa policyname +is +.Pf non- Dv NULL , +the presence of the named policy +(e.g.\& +.Dq Li biba , +.Dq Li mls , +.Dq Li te ) +is checked, otherwise the presence of any MAC policies at all is checked. +.Sh RETURN VALUES +If the system supports the given MAC policy, the value 1 is returned. +If the specified MAC policy is not supported, the value 0 is returned. +If an error occurs, the value \-1 is returned. +.Sh ERRORS +.Bl -tag -width Er +.It Bq Er EINVAL +The value of +.Fa policyname +is not valid. +.It Bq Er ENOMEM +Insufficient memory was available to allocate internal storage. +.El +.Sh SEE ALSO +.Xr mac 3 , +.Xr mac_free 3 , +.Xr mac_get 3 , +.Xr mac_prepare 3 , +.Xr mac_set 3 , +.Xr mac_text 3 , +.Xr mac 4 , +.Xr mac 9 +.Sh HISTORY +Support for Mandatory Access Control was introduced in +.Fx 5.0 +as part of the +.Tn TrustedBSD +Project. diff --git a/lib/libc/posix1e/mac_prepare.3 b/lib/libc/posix1e/mac_prepare.3 new file mode 100644 index 0000000..3e2c3ee --- /dev/null +++ b/lib/libc/posix1e/mac_prepare.3 @@ -0,0 +1,126 @@ +.\" Copyright (c) 2002, 2003 Networks Associates Technology, Inc. +.\" All rights reserved. +.\" +.\" This software was developed for the FreeBSD Project by Chris +.\" Costello at Safeport Network Services and Network Associates Labs, +.\" the Security Research Division of Network Associates, Inc. under +.\" DARPA/SPAWAR contract N66001-01-C-8035 ("CBOSS"), as part of the +.\" DARPA CHATS research program. +.\" +.\" 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 AUTHORS 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 AUTHORS 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. +.\" +.\" $FreeBSD: releng/10.2/lib/libc/posix1e/mac_prepare.3 235400 2012-05-13 14:16:04Z joel $ +.\" +.Dd August 22, 2003 +.Dt MAC_PREPARE 3 +.Os +.Sh NAME +.Nm mac_prepare , mac_prepare_type , mac_prepare_file_label , +.Nm mac_prepare_ifnet_label , mac_prepare_process_label +.Nd allocate appropriate storage for +.Vt mac_t +.Sh SYNOPSIS +.In sys/mac.h +.Ft int +.Fn mac_prepare "mac_t *mac" "const char *elements" +.Ft int +.Fn mac_prepare_type "mac_t *mac" "const char *name" +.Ft int +.Fn mac_prepare_file_label "mac_t *mac" +.Ft int +.Fn mac_prepare_ifnet_label "mac_t *mac" +.Ft int +.Fn mac_prepare_process_label "mac_t *mac" +.Sh DESCRIPTION +The +.Nm +family of functions allocates the appropriate amount of storage and initializes +.Fa *mac +for use by +.Xr mac_get 3 . +When the resulting label is passed into the +.Xr mac_get 3 +functions, the kernel will attempt to fill in the label elements specified +when the label was prepared. +Elements are specified in a nul-terminated string, using commas to +delimit fields. +Element names may be prefixed with the +.Ql \&? +character to indicate that a failure by the kernel to retrieve that +element should not be considered fatal. +.Pp +The +.Fn mac_prepare +function accepts a list of policy names as a parameter, and allocates the +storage to fit those label elements accordingly. +The remaining functions in the family make use of system defaults defined +in +.Xr mac.conf 5 +instead of an explicit +.Va elements +argument, deriving the default from the specified object type. +.Pp +.Fn mac_prepare_type +allocates the storage to fit an object label of the type specified by +the +.Va name +argument. +The +.Fn mac_prepare_file_label , +.Fn mac_prepare_ifnet_label , +and +.Fn mac_prepare_process_label +functions are equivalent to invocations of +.Fn mac_prepare_type +with arguments of +.Qq file , +.Qq ifnet , +and +.Qq process +respectively. +.Sh RETURN VALUES +.Rv -std +.Sh SEE ALSO +.Xr mac 3 , +.Xr mac_free 3 , +.Xr mac_get 3 , +.Xr mac_is_present 3 , +.Xr mac_set 3 , +.Xr mac 4 , +.Xr mac.conf 5 , +.Xr maclabel 7 +.Sh STANDARDS +POSIX.1e is described in IEEE POSIX.1e draft 17. +Discussion of the draft +continues on the cross-platform POSIX.1e implementation mailing list. +To join this list, see the +.Fx +POSIX.1e implementation page +for more information. +.Sh HISTORY +Support for Mandatory Access Control was introduced in +.Fx 5.0 +as part of the +.Tn TrustedBSD +Project. +Support for generic object types first appeared in +.Fx 5.2 . diff --git a/lib/libc/posix1e/mac_set.3 b/lib/libc/posix1e/mac_set.3 new file mode 100644 index 0000000..aaf0454 --- /dev/null +++ b/lib/libc/posix1e/mac_set.3 @@ -0,0 +1,149 @@ +.\" Copyright (c) 2001 Networks Associates Technology, Inc. +.\" All rights reserved. +.\" +.\" This software was developed for the FreeBSD Project by Chris +.\" Costello at Safeport Network Services and NAI Labs, the Security +.\" Research Division of Network Associates, Inc. under DARPA/SPAWAR +.\" contract N66001-01-C-8035 ("CBOSS"), as part of the DARPA CHATS +.\" research program. +.\" +.\" 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 AUTHORS 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 AUTHORS 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. +.\" +.\" $FreeBSD: releng/10.2/lib/libc/posix1e/mac_set.3 196123 2009-08-12 10:46:48Z rwatson $ +.\" +.Dd January 14, 2003 +.Dt MAC_SET 3 +.Os +.Sh NAME +.Nm mac_set_file , +.Nm mac_set_fd , +.Nm mac_set_proc +.Nd set the MAC label for a file or process +.Sh LIBRARY +.Lb libc +.Sh SYNOPSIS +.In sys/mac.h +.Ft int +.Fn mac_set_file "const char *path" "mac_t label" +.Ft int +.Fn mac_set_link "const char *path" "mac_t label" +.Ft int +.Fn mac_set_fd "int fd" "mac_t label" +.Ft int +.Fn mac_set_proc "mac_t label" +.Sh DESCRIPTION +The +.Fn mac_set_file +and +.Fn mac_set_fd +functions associate a MAC label +specified by +.Fa label +to the file referenced to by +.Fa path_p , +or to the file descriptor +.Fa fd , +respectively. +Note that when a file descriptor references a socket, label operations +on the file descriptor act on the socket, not on the file that may +have been used as a rendezvous when binding the socket. +The +.Fn mac_set_link +function is the same as +.Fn mac_set_file , +except that it does not follow symlinks. +.Pp +The +.Fn mac_set_proc +function associates the MAC label +specified by +.Fa label +to the calling process. +.Pp +A process is allowed to set a label for a file +only if it has MAC write access to the file, +and its effective user ID is equal to +the owner of the file, +or has appropriate privileges. +.Sh RETURN VALUES +.Rv -std mac_set_fd mac_set_file mac_set_link mac_set_proc +.Sh ERRORS +.Bl -tag -width Er +.It Bq Er EACCES +MAC write access to the file is denied. +.It Bq Er EBADF +The +.Fa fd +argument +is not a valid file descriptor. +.It Bq Er EINVAL +The +.Fa label +argument +is not a valid MAC label, or the object referenced by +.Fa fd +is not appropriate for label operations. +.It Bq Er EOPNOTSUPP +Setting MAC labels is not supported +by the file referenced by +.Fa fd . +.It Bq Er EPERM +The calling process had insufficient privilege +to change the MAC label. +.It Bq Er EROFS +File system for the object being modified +is read only. +.It Bq Er ENAMETOOLONG +.\" XXX POSIX_NO_TRUNC? +The length of the pathname in +.Fa path_p +exceeds +.Dv PATH_MAX , +or a component of the pathname +is longer than +.Dv NAME_MAX . +.It Bq Er ENOENT +The file referenced by +.Fa path_p +does not exist. +.It Bq Er ENOTDIR +A component of the pathname +referenced by +.Fa path_p +is not a directory. +.El +.Sh SEE ALSO +.Xr mac 3 , +.Xr mac_free 3 , +.Xr mac_get 3 , +.Xr mac_is_present 3 , +.Xr mac_prepare 3 , +.Xr mac_text 3 , +.Xr posix1e 3 , +.Xr mac 4 , +.Xr mac 9 +.Sh HISTORY +Support for Mandatory Access Control was introduced in +.Fx 5.0 +as part of the +.Tn TrustedBSD +Project. diff --git a/lib/libc/posix1e/mac_set.c b/lib/libc/posix1e/mac_set.c new file mode 100644 index 0000000..0aaf8b1 --- /dev/null +++ b/lib/libc/posix1e/mac_set.c @@ -0,0 +1,69 @@ +/* + * Copyright (c) 1999, 2000, 2001, 2002 Robert N. M. Watson + * All rights reserved. + * + * This software was developed by Robert Watson for the TrustedBSD Project. + * + * 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 names of the authors 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 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 AUTHOR 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 +__FBSDID("$FreeBSD: releng/10.2/lib/libc/posix1e/mac_set.c 176901 2008-03-07 15:25:56Z rwatson $"); + +#include +#include + +extern int __mac_set_fd(int fd, struct mac *mac_p); +extern int __mac_set_file(const char *path_p, struct mac *mac_p); +extern int __mac_set_link(const char *path_p, struct mac *mac_p); +extern int __mac_set_proc(struct mac *mac_p); + +int +mac_set_fd(int fd, struct mac *label) +{ + + return (__mac_set_fd(fd, label)); +} + +int +mac_set_file(const char *path, struct mac *label) +{ + + return (__mac_set_file(path, label)); +} + +int +mac_set_link(const char *path, struct mac *label) +{ + + return (__mac_set_link(path, label)); +} + +int +mac_set_proc(struct mac *label) +{ + + return (__mac_set_proc(label)); +} diff --git a/lib/libc/posix1e/mac_text.3 b/lib/libc/posix1e/mac_text.3 new file mode 100644 index 0000000..64805eb --- /dev/null +++ b/lib/libc/posix1e/mac_text.3 @@ -0,0 +1,117 @@ +.\" Copyright (c) 2001 Networks Associates Technology, Inc. +.\" All rights reserved. +.\" +.\" This software was developed for the FreeBSD Project by Chris +.\" Costello at Safeport Network Services and NAI Labs, the Security +.\" Research Division of Network Associates, Inc. under DARPA/SPAWAR +.\" contract N66001-01-C-8035 ("CBOSS"), as part of the DARPA CHATS +.\" research program. +.\" +.\" 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 AUTHORS 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 AUTHORS 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. +.\" +.\" $FreeBSD: releng/10.2/lib/libc/posix1e/mac_text.3 196123 2009-08-12 10:46:48Z rwatson $ +.\" +.Dd December 21, 2001 +.Dt MAC_TEXT 3 +.Os +.Sh NAME +.Nm mac_from_text , +.Nm mac_to_text +.Nd convert MAC label to/from text representation +.Sh LIBRARY +.Lb libc +.Sh SYNOPSIS +.In sys/mac.h +.Ft int +.Fn mac_from_text "mac_t *mac" "const char *text" +.Ft int +.Fn mac_to_text "mac_t label" "char **text" +.Sh DESCRIPTION +The +.Fn mac_from_text +function converts the text representation of a label +into the internal policy label format +.Pq Vt mac_t +and places it in +.Fa *mac , +which must later be freed with +.Xr free 3 . +.Pp +The +.Fn mac_to_text +function allocates storage for +.Fa *text , +which will be set to the text representation of +.Fa label . +.Pp +Refer to +.Xr maclabel 7 +for the MAC label format. +.Sh RETURN VALUES +.Rv -std mac_from_text mac_to_text +.Sh COMPATIBILITY +POSIX.1e does not define +a format for text representations +of MAC labels. +.Pp +POSIX.1e requires that text strings allocated using +.Fn mac_to_text +be freed using +.Xr mac_free 3 ; +in the +.Fx +implementation, they must be freed using +.Xr free 3 , +as +.Xr mac_free 3 +is used only to free memory used for type +.Vt mac_t . +.Sh ERRORS +.Bl -tag -width Er +.It Bq Er ENOMEM +Insufficient memory was available +to allocate internal storage. +.El +.Sh SEE ALSO +.Xr free 3 , +.Xr mac 3 , +.Xr mac_get 3 , +.Xr mac_is_present 3 , +.Xr mac_prepare 3 , +.Xr mac_set 3 , +.Xr posix1e 3 , +.Xr mac 4 , +.Xr maclabel 7 +.Sh STANDARDS +POSIX.1e is described in IEEE POSIX.1e draft 17. +Discussion of the draft +continues on the cross-platform POSIX.1e implementation mailing list. +To join this list, see the +.Fx +POSIX.1e implementation page +for more information. +.Sh HISTORY +Support for Mandatory Access Control was introduced in +.Fx 5.0 +as part of the +.Tn TrustedBSD +Project. diff --git a/lib/libc/posix1e/posix1e.3 b/lib/libc/posix1e/posix1e.3 new file mode 100644 index 0000000..c28f00c --- /dev/null +++ b/lib/libc/posix1e/posix1e.3 @@ -0,0 +1,118 @@ +.\"- +.\" Copyright (c) 2000, 2009 Robert N. M. Watson +.\" 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 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 AUTHOR 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. +.\" +.\" $FreeBSD: releng/10.2/lib/libc/posix1e/posix1e.3 264818 2014-04-23 12:11:14Z brueffer $ +.\" +.Dd April 15, 2014 +.Dt POSIX1E 3 +.Os +.Sh NAME +.Nm posix1e +.Nd introduction to the POSIX.1e security API +.Sh LIBRARY +.Lb libc +.Sh SYNOPSIS +.In sys/types.h +.In sys/acl.h +.In sys/mac.h +.Sh DESCRIPTION +POSIX.1e describes five security extensions to the POSIX.1 API: Access +Control Lists (ACLs), Auditing, Capabilities, Mandatory Access Control, and +Information Flow Labels. +While IEEE POSIX.1e D17 specification has not been standardized, several of +its interfaces are widely used. +.Pp +.Fx +implements POSIX.1e interface for access control lists, described in +.Xr acl 3 , +and supports ACLs on the +.Xr ffs 7 +file system; ACLs must be administratively enabled using +.Xr tunefs 8 . +.Pp +.Fx +implements a POSIX.1e-like mandatory access control interface, described in +.Xr mac 3 , +although with a number of extensions and important semantic differences. +.Pp +.Fx +does not implement the POSIX.1e audit, privilege (capability), or information +flow label APIs. +However, +.Fx +does implement the +.Xr libbsm +audit API. +It also provides +.Xr capsicum 4 , +a lightweight OS capability and sandbox framework implementing a +hybrid capability system model. +.Sh ENVIRONMENT +POSIX.1e assigns security attributes to all objects, extending the security +functionality described in POSIX.1. +These additional attributes store fine-grained discretionary access control +information and mandatory access control labels; for files, they are stored +in extended attributes, described in +.Xr extattr 3 . +.Pp +POSIX.2c describes +a set of userland utilities for manipulating these attributes, including +.Xr getfacl 1 +and +.Xr setfacl 1 +for access control lists, and +.Xr getfmac 8 +and +.Xr setfmac 8 +for mandatory access control labels. +.Sh SEE ALSO +.Xr getfacl 1 , +.Xr setfacl 1 , +.Xr extattr 2 , +.Xr acl 3 , +.Xr extattr 3 , +.Xr libcapsicum 3 , +.Xr libbsm 3 , +.Xr mac 3 , +.Xr capsicum 4 , +.Xr ffs 7 , +.Xr getfmac 8 , +.Xr setfmac 8 , +.Xr tunefs 8 , +.Xr acl 9 , +.Xr extattr 9 , +.Xr mac 9 +.Sh STANDARDS +POSIX.1e is described in IEEE POSIX.1e draft 17. +.Sh HISTORY +POSIX.1e support was introduced in +.Fx 4.0 ; +most features were available as of +.Fx 5.0 . +.Sh AUTHORS +.An Robert N M Watson +.An Chris D. Faulhaber +.An Thomas Moestl +.An Ilmar S Habibulin diff --git a/lib/libc/quad/Makefile b/lib/libc/quad/Makefile new file mode 100644 index 0000000..c8c97c2 --- /dev/null +++ b/lib/libc/quad/Makefile @@ -0,0 +1,34 @@ +# $Id: Makefile 89 2016-01-12 00:20:40Z reddawg $ +# The System Makefile (C) 2002 The UbixOS Project + +# Include Global 'Source' Options +include ../../../Makefile.incl +include ../../Makefile.incl +include ../Makefile.incl + +#Objects +#OBJS = anddi3.o adddi3.o qdivrem.o umoddi3.o udivdi3.o divdi3.o +OBJS = adddi3.o anddi3.o ashldi3.o ashrdi3.o cmpdi2.o divdi3.o fixdfdi.o fixsfdi.o fixunsdfdi.o fixunssfdi.o floatdidf.o floatdisf.o floatunsdidf.o iordi3.o lshldi3.o lshrdi3.o moddi3.o muldi3.o negdi2.o notdi2.o qdivrem.o subdi3.o ucmpdi2.o udivdi3.o umoddi3.o xordi3.o + +all: $(OBJS) + +# Compile the source files +.cc.o: + $(CXX) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -c -o $@ $< + +.cc.s: + $(CXX) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -S -o $@ $< + +.c.o: + $(CC) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -c $< + +.c.s: + $(CC) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -S -o $@ $< + +.S.o: + $(CC) $(CFLAGS) -Wall -nostdlib -c -o $@ $< + +# Clean up the junk +clean: + $(REMOVE) $(OBJS) + diff --git a/lib/libc/quad/adddi3.c b/lib/libc/quad/adddi3.c new file mode 100644 index 0000000..d97059e --- /dev/null +++ b/lib/libc/quad/adddi3.c @@ -0,0 +1,62 @@ +/*- + * Copyright (c) 1992, 1993 + * The Regents of the University of California. All rights reserved. + * + * This software was developed by the Computer Systems Engineering group + * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and + * contributed to Berkeley. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)adddi3.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/quad/adddi3.c,v 1.2 2002/03/22 21:52:42 obrien Exp $"); + +#include "quad.h" + +/* + * Add two quads. This is trivial since a one-bit carry from a single + * u_long addition x+y occurs if and only if the sum x+y is less than + * either x or y (the choice to compare with x or y is arbitrary). + */ +quad_t +__adddi3(a, b) + quad_t a, b; +{ + union uu aa, bb, sum; + + aa.q = a; + bb.q = b; + sum.ul[L] = aa.ul[L] + bb.ul[L]; + sum.ul[H] = aa.ul[H] + bb.ul[H] + (sum.ul[L] < bb.ul[L]); + return (sum.q); +} diff --git a/lib/libc/quad/anddi3.c b/lib/libc/quad/anddi3.c new file mode 100644 index 0000000..7d58cf1 --- /dev/null +++ b/lib/libc/quad/anddi3.c @@ -0,0 +1,60 @@ +/*- + * Copyright (c) 1992, 1993 + * The Regents of the University of California. All rights reserved. + * + * This software was developed by the Computer Systems Engineering group + * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and + * contributed to Berkeley. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)anddi3.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/quad/anddi3.c,v 1.2 2002/03/22 21:52:42 obrien Exp $"); + +#include "quad.h" + +/* + * Return a & b, in quad. + */ +quad_t +__anddi3(a, b) + quad_t a, b; +{ + union uu aa, bb; + + aa.q = a; + bb.q = b; + aa.ul[0] &= bb.ul[0]; + aa.ul[1] &= bb.ul[1]; + return (aa.q); +} diff --git a/lib/libc/quad/ashldi3.c b/lib/libc/quad/ashldi3.c new file mode 100644 index 0000000..6e9d493 --- /dev/null +++ b/lib/libc/quad/ashldi3.c @@ -0,0 +1,68 @@ +/*- + * Copyright (c) 1992, 1993 + * The Regents of the University of California. All rights reserved. + * + * This software was developed by the Computer Systems Engineering group + * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and + * contributed to Berkeley. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)ashldi3.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/quad/ashldi3.c,v 1.2 2002/03/22 21:52:42 obrien Exp $"); + +#include "quad.h" + +/* + * Shift a (signed) quad value left (arithmetic shift left). + * This is the same as logical shift left! + */ +quad_t +__ashldi3(a, shift) + quad_t a; + qshift_t shift; +{ + union uu aa; + + aa.q = a; + if (shift >= LONG_BITS) { + aa.ul[H] = shift >= QUAD_BITS ? 0 : + aa.ul[L] << (shift - LONG_BITS); + aa.ul[L] = 0; + } else if (shift > 0) { + aa.ul[H] = (aa.ul[H] << shift) | + (aa.ul[L] >> (LONG_BITS - shift)); + aa.ul[L] <<= shift; + } + return (aa.q); +} diff --git a/lib/libc/quad/ashrdi3.c b/lib/libc/quad/ashrdi3.c new file mode 100644 index 0000000..0d57b20 --- /dev/null +++ b/lib/libc/quad/ashrdi3.c @@ -0,0 +1,77 @@ +/*- + * Copyright (c) 1992, 1993 + * The Regents of the University of California. All rights reserved. + * + * This software was developed by the Computer Systems Engineering group + * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and + * contributed to Berkeley. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)ashrdi3.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/quad/ashrdi3.c,v 1.2 2002/03/22 21:52:42 obrien Exp $"); + +#include "quad.h" + +/* + * Shift a (signed) quad value right (arithmetic shift right). + */ +quad_t +__ashrdi3(a, shift) + quad_t a; + qshift_t shift; +{ + union uu aa; + + aa.q = a; + if (shift >= LONG_BITS) { + long s; + + /* + * Smear bits rightward using the machine's right-shift + * method, whether that is sign extension or zero fill, + * to get the `sign word' s. Note that shifting by + * LONG_BITS is undefined, so we shift (LONG_BITS-1), + * then 1 more, to get our answer. + */ + s = (aa.sl[H] >> (LONG_BITS - 1)) >> 1; + aa.ul[L] = shift >= QUAD_BITS ? s : + aa.sl[H] >> (shift - LONG_BITS); + aa.ul[H] = s; + } else if (shift > 0) { + aa.ul[L] = (aa.ul[L] >> shift) | + (aa.ul[H] << (LONG_BITS - shift)); + aa.sl[H] >>= shift; + } + return (aa.q); +} diff --git a/lib/libc/quad/cmpdi2.c b/lib/libc/quad/cmpdi2.c new file mode 100644 index 0000000..495a8ee --- /dev/null +++ b/lib/libc/quad/cmpdi2.c @@ -0,0 +1,61 @@ +/*- + * Copyright (c) 1992, 1993 + * The Regents of the University of California. All rights reserved. + * + * This software was developed by the Computer Systems Engineering group + * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and + * contributed to Berkeley. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)cmpdi2.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/quad/cmpdi2.c,v 1.2 2002/03/22 21:52:42 obrien Exp $"); + +#include "quad.h" + +/* + * Return 0, 1, or 2 as a <, =, > b respectively. + * Both a and b are considered signed---which means only the high word is + * signed. + */ +int +__cmpdi2(a, b) + quad_t a, b; +{ + union uu aa, bb; + + aa.q = a; + bb.q = b; + return (aa.sl[H] < bb.sl[H] ? 0 : aa.sl[H] > bb.sl[H] ? 2 : + aa.ul[L] < bb.ul[L] ? 0 : aa.ul[L] > bb.ul[L] ? 2 : 1); +} diff --git a/lib/libc/quad/divdi3.c b/lib/libc/quad/divdi3.c new file mode 100644 index 0000000..a8290d8 --- /dev/null +++ b/lib/libc/quad/divdi3.c @@ -0,0 +1,67 @@ +/*- + * Copyright (c) 1992, 1993 + * The Regents of the University of California. All rights reserved. + * + * This software was developed by the Computer Systems Engineering group + * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and + * contributed to Berkeley. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)divdi3.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/quad/divdi3.c,v 1.2 2002/03/22 21:52:43 obrien Exp $"); + +#include "quad.h" + +/* + * Divide two signed quads. + * ??? if -1/2 should produce -1 on this machine, this code is wrong + */ +quad_t +__divdi3(a, b) + quad_t a, b; +{ + u_quad_t ua, ub, uq; + int neg; + + if (a < 0) + ua = -(u_quad_t)a, neg = 1; + else + ua = a, neg = 0; + if (b < 0) + ub = -(u_quad_t)b, neg ^= 1; + else + ub = b; + uq = __qdivrem(ua, ub, (u_quad_t *)0); + return (neg ? -uq : uq); +} diff --git a/lib/libc/quad/fixdfdi.c b/lib/libc/quad/fixdfdi.c new file mode 100644 index 0000000..10c2d51 --- /dev/null +++ b/lib/libc/quad/fixdfdi.c @@ -0,0 +1,64 @@ +/*- + * Copyright (c) 1992, 1993 + * The Regents of the University of California. All rights reserved. + * + * This software was developed by the Computer Systems Engineering group + * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and + * contributed to Berkeley. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)fixdfdi.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/quad/fixdfdi.c,v 1.2 2002/03/22 21:52:43 obrien Exp $"); + +#include "quad.h" + +/* + * Convert double to (signed) quad. + * We clamp anything that is out of range. + */ +quad_t +__fixdfdi(x) + double x; +{ + if (x < 0) + if (x <= QUAD_MIN) + return (QUAD_MIN); + else + return ((quad_t)-(u_quad_t)-x); + else + if (x >= QUAD_MAX) + return (QUAD_MAX); + else + return ((quad_t)(u_quad_t)x); +} diff --git a/lib/libc/quad/fixsfdi.c b/lib/libc/quad/fixsfdi.c new file mode 100644 index 0000000..647a4a1 --- /dev/null +++ b/lib/libc/quad/fixsfdi.c @@ -0,0 +1,65 @@ +/*- + * Copyright (c) 1992 The Regents of the University of California. + * All rights reserved. + * + * This software was developed by the Computer Systems Engineering group + * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and + * contributed to Berkeley. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)fixsfdi.c 5.1 (Berkeley) 7/7/92"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/quad/fixsfdi.c,v 1.2 2002/03/22 21:52:43 obrien Exp $"); + +#include "quad.h" + +/* + * Convert float to (signed) quad. + * We clamp anything that is out of range. + * + * N.B.: must use new ANSI syntax (sorry). + */ +long long +__fixsfdi(float x) +{ + if (x < 0) + if (x <= QUAD_MIN) + return (QUAD_MIN); + else + return ((quad_t)-(u_quad_t)-x); + else + if (x >= QUAD_MAX) + return (QUAD_MAX); + else + return ((quad_t)(u_quad_t)x); +} diff --git a/lib/libc/quad/fixunsdfdi.c b/lib/libc/quad/fixunsdfdi.c new file mode 100644 index 0000000..694cd62 --- /dev/null +++ b/lib/libc/quad/fixunsdfdi.c @@ -0,0 +1,98 @@ +/*- + * Copyright (c) 1992, 1993 + * The Regents of the University of California. All rights reserved. + * + * This software was developed by the Computer Systems Engineering group + * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and + * contributed to Berkeley. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)fixunsdfdi.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/quad/fixunsdfdi.c,v 1.2 2002/03/22 21:52:43 obrien Exp $"); + +#include "quad.h" + +#define ONE_FOURTH (1 << (LONG_BITS - 2)) +#define ONE_HALF (ONE_FOURTH * 2.0) +#define ONE (ONE_FOURTH * 4.0) + +/* + * Convert double to (unsigned) quad. + * Not sure what to do with negative numbers---for now, anything out + * of range becomes UQUAD_MAX. + */ +u_quad_t +__fixunsdfdi(x) + double x; +{ + double toppart; + union uu t; + + if (x < 0) + return (UQUAD_MAX); /* ??? should be 0? ERANGE??? */ +#ifdef notdef /* this falls afoul of a GCC bug */ + if (x >= UQUAD_MAX) + return (UQUAD_MAX); +#else /* so we wire in 2^64-1 instead */ + if (x >= 18446744073709551615.0) + return (UQUAD_MAX); +#endif + /* + * Get the upper part of the result. Note that the divide + * may round up; we want to avoid this if possible, so we + * subtract `1/2' first. + */ + toppart = (x - ONE_HALF) / ONE; + /* + * Now build a u_quad_t out of the top part. The difference + * between x and this is the bottom part (this may introduce + * a few fuzzy bits, but what the heck). With any luck this + * difference will be nonnegative: x should wind up in the + * range [0..ULONG_MAX]. For paranoia, we assume [LONG_MIN.. + * 2*ULONG_MAX] instead. + */ + t.ul[H] = (unsigned long)toppart; + t.ul[L] = 0; + x -= (double)t.uq; + if (x < 0) { + t.ul[H]--; + x += ULONG_MAX; + } + if (x > ULONG_MAX) { + t.ul[H]++; + x -= ULONG_MAX; + } + t.ul[L] = (u_long)x; + return (t.uq); +} diff --git a/lib/libc/quad/fixunssfdi.c b/lib/libc/quad/fixunssfdi.c new file mode 100644 index 0000000..1263fee --- /dev/null +++ b/lib/libc/quad/fixunssfdi.c @@ -0,0 +1,102 @@ +/*- + * Copyright (c) 1992, 1993 + * The Regents of the University of California. All rights reserved. + * + * This software was developed by the Computer Systems Engineering group + * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and + * contributed to Berkeley. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)fixunssfdi.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/quad/fixunssfdi.c,v 1.2 2002/03/22 21:52:43 obrien Exp $"); + +#include "quad.h" + +#define ONE_FOURTH (1 << (LONG_BITS - 2)) +#define ONE_HALF (ONE_FOURTH * 2.0) +#define ONE (ONE_FOURTH * 4.0) + +/* + * Convert float to (unsigned) quad. We do most of our work in double, + * out of sheer paranoia. + * + * Not sure what to do with negative numbers---for now, anything out + * of range becomes UQUAD_MAX. + * + * N.B.: must use new ANSI syntax (sorry). + */ +u_quad_t +__fixunssfdi(float f) +{ + double x, toppart; + union uu t; + + if (f < 0) + return (UQUAD_MAX); /* ??? should be 0? ERANGE??? */ +#ifdef notdef /* this falls afoul of a GCC bug */ + if (f >= UQUAD_MAX) + return (UQUAD_MAX); +#else /* so we wire in 2^64-1 instead */ + if (f >= 18446744073709551615.0) + return (UQUAD_MAX); +#endif + x = f; + /* + * Get the upper part of the result. Note that the divide + * may round up; we want to avoid this if possible, so we + * subtract `1/2' first. + */ + toppart = (x - ONE_HALF) / ONE; + /* + * Now build a u_quad_t out of the top part. The difference + * between x and this is the bottom part (this may introduce + * a few fuzzy bits, but what the heck). With any luck this + * difference will be nonnegative: x should wind up in the + * range [0..ULONG_MAX]. For paranoia, we assume [LONG_MIN.. + * 2*ULONG_MAX] instead. + */ + t.ul[H] = (unsigned long)toppart; + t.ul[L] = 0; + x -= (double)t.uq; + if (x < 0) { + t.ul[H]--; + x += ULONG_MAX; + } + if (x > ULONG_MAX) { + t.ul[H]++; + x -= ULONG_MAX; + } + t.ul[L] = (u_long)x; + return (t.uq); +} diff --git a/lib/libc/quad/floatdidf.c b/lib/libc/quad/floatdidf.c new file mode 100644 index 0000000..ba0b6a7 --- /dev/null +++ b/lib/libc/quad/floatdidf.c @@ -0,0 +1,76 @@ +/*- + * Copyright (c) 1992, 1993 + * The Regents of the University of California. All rights reserved. + * + * This software was developed by the Computer Systems Engineering group + * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and + * contributed to Berkeley. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)floatdidf.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/quad/floatdidf.c,v 1.2 2002/03/22 21:52:43 obrien Exp $"); + +#include "quad.h" + +/* + * Convert (signed) quad to double. + */ +double +__floatdidf(x) + quad_t x; +{ + double d; + union uu u; + int neg; + + /* + * Get an unsigned number first, by negating if necessary. + */ + if (x < 0) + u.q = -x, neg = 1; + else + u.q = x, neg = 0; + + /* + * Now u.ul[H] has the factor of 2^32 (or whatever) and u.ul[L] + * has the units. Ideally we could just set d, add LONG_BITS to + * its exponent, and then add the units, but this is portable + * code and does not know how to get at an exponent. Machine- + * specific code may be able to do this more efficiently. + */ + d = (double)u.ul[H] * ((1 << (LONG_BITS - 2)) * 4.0); + d += u.ul[L]; + + return (neg ? -d : d); +} diff --git a/lib/libc/quad/floatdisf.c b/lib/libc/quad/floatdisf.c new file mode 100644 index 0000000..bac96c2 --- /dev/null +++ b/lib/libc/quad/floatdisf.c @@ -0,0 +1,78 @@ +/*- + * Copyright (c) 1992, 1993 + * The Regents of the University of California. All rights reserved. + * + * This software was developed by the Computer Systems Engineering group + * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and + * contributed to Berkeley. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)floatdisf.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/quad/floatdisf.c,v 1.2 2002/03/22 21:52:43 obrien Exp $"); + +#include "quad.h" + +/* + * Convert (signed) quad to float. + */ +float +__floatdisf(x) + quad_t x; +{ + float f; + union uu u; + int neg; + + /* + * Get an unsigned number first, by negating if necessary. + */ + if (x < 0) + u.q = -x, neg = 1; + else + u.q = x, neg = 0; + + /* + * Now u.ul[H] has the factor of 2^32 (or whatever) and u.ul[L] + * has the units. Ideally we could just set f, add LONG_BITS to + * its exponent, and then add the units, but this is portable + * code and does not know how to get at an exponent. Machine- + * specific code may be able to do this more efficiently. + * + * Using double here may be excessive paranoia. + */ + f = (double)u.ul[H] * ((1 << (LONG_BITS - 2)) * 4.0); + f += u.ul[L]; + + return (neg ? -f : f); +} diff --git a/lib/libc/quad/floatunsdidf.c b/lib/libc/quad/floatunsdidf.c new file mode 100644 index 0000000..66bf63b --- /dev/null +++ b/lib/libc/quad/floatunsdidf.c @@ -0,0 +1,61 @@ +/*- + * Copyright (c) 1992, 1993 + * The Regents of the University of California. All rights reserved. + * + * This software was developed by the Computer Systems Engineering group + * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and + * contributed to Berkeley. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)floatunsdidf.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/quad/floatunsdidf.c,v 1.2 2002/03/22 21:52:43 obrien Exp $"); + +#include "quad.h" + +/* + * Convert (unsigned) quad to double. + * This is exactly like floatdidf.c except that negatives never occur. + */ +double +__floatunsdidf(x) + u_quad_t x; +{ + double d; + union uu u; + + u.uq = x; + d = (double)u.ul[H] * ((1 << (LONG_BITS - 2)) * 4.0); + d += u.ul[L]; + return (d); +} diff --git a/lib/libc/quad/iordi3.c b/lib/libc/quad/iordi3.c new file mode 100644 index 0000000..be16676 --- /dev/null +++ b/lib/libc/quad/iordi3.c @@ -0,0 +1,60 @@ +/*- + * Copyright (c) 1992, 1993 + * The Regents of the University of California. All rights reserved. + * + * This software was developed by the Computer Systems Engineering group + * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and + * contributed to Berkeley. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)iordi3.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/quad/iordi3.c,v 1.2 2002/03/22 21:52:43 obrien Exp $"); + +#include "quad.h" + +/* + * Return a | b, in quad. + */ +quad_t +__iordi3(a, b) + quad_t a, b; +{ + union uu aa, bb; + + aa.q = a; + bb.q = b; + aa.ul[0] |= bb.ul[0]; + aa.ul[1] |= bb.ul[1]; + return (aa.q); +} diff --git a/lib/libc/quad/lshldi3.c b/lib/libc/quad/lshldi3.c new file mode 100644 index 0000000..261f4b0 --- /dev/null +++ b/lib/libc/quad/lshldi3.c @@ -0,0 +1,68 @@ +/*- + * Copyright (c) 1992, 1993 + * The Regents of the University of California. All rights reserved. + * + * This software was developed by the Computer Systems Engineering group + * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and + * contributed to Berkeley. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)lshldi3.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/quad/lshldi3.c,v 1.2 2002/03/22 21:52:43 obrien Exp $"); + +#include "quad.h" + +/* + * Shift an (unsigned) quad value left (logical shift left). + * This is the same as arithmetic shift left! + */ +quad_t +__lshldi3(a, shift) + quad_t a; + qshift_t shift; +{ + union uu aa; + + aa.q = a; + if (shift >= LONG_BITS) { + aa.ul[H] = shift >= QUAD_BITS ? 0 : + aa.ul[L] << (shift - LONG_BITS); + aa.ul[L] = 0; + } else if (shift > 0) { + aa.ul[H] = (aa.ul[H] << shift) | + (aa.ul[L] >> (LONG_BITS - shift)); + aa.ul[L] <<= shift; + } + return (aa.q); +} diff --git a/lib/libc/quad/lshrdi3.c b/lib/libc/quad/lshrdi3.c new file mode 100644 index 0000000..9f35ed6 --- /dev/null +++ b/lib/libc/quad/lshrdi3.c @@ -0,0 +1,67 @@ +/*- + * Copyright (c) 1992, 1993 + * The Regents of the University of California. All rights reserved. + * + * This software was developed by the Computer Systems Engineering group + * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and + * contributed to Berkeley. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)lshrdi3.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/quad/lshrdi3.c,v 1.2 2002/03/22 21:52:43 obrien Exp $"); + +#include "quad.h" + +/* + * Shift an (unsigned) quad value right (logical shift right). + */ +quad_t +__lshrdi3(a, shift) + quad_t a; + qshift_t shift; +{ + union uu aa; + + aa.q = a; + if (shift >= LONG_BITS) { + aa.ul[L] = shift >= QUAD_BITS ? 0 : + aa.ul[H] >> (shift - LONG_BITS); + aa.ul[H] = 0; + } else if (shift > 0) { + aa.ul[L] = (aa.ul[L] >> shift) | + (aa.ul[H] << (LONG_BITS - shift)); + aa.ul[H] >>= shift; + } + return (aa.q); +} diff --git a/lib/libc/quad/moddi3.c b/lib/libc/quad/moddi3.c new file mode 100644 index 0000000..7a51dd3 --- /dev/null +++ b/lib/libc/quad/moddi3.c @@ -0,0 +1,69 @@ +/*- + * Copyright (c) 1992, 1993 + * The Regents of the University of California. All rights reserved. + * + * This software was developed by the Computer Systems Engineering group + * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and + * contributed to Berkeley. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)moddi3.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/quad/moddi3.c,v 1.3 2002/03/22 21:52:43 obrien Exp $"); + +#include "quad.h" + +/* + * Return remainder after dividing two signed quads. + * + * XXX + * If -1/2 should produce -1 on this machine, this code is wrong. + */ +quad_t +__moddi3(a, b) + quad_t a, b; +{ + u_quad_t ua, ub, ur; + int neg; + + if (a < 0) + ua = -(u_quad_t)a, neg = 1; + else + ua = a, neg = 0; + if (b < 0) + ub = -(u_quad_t)b; + else + ub = b; + (void)__qdivrem(ua, ub, &ur); + return (neg ? -ur : ur); +} diff --git a/lib/libc/quad/muldi3.c b/lib/libc/quad/muldi3.c new file mode 100644 index 0000000..cc0c887 --- /dev/null +++ b/lib/libc/quad/muldi3.c @@ -0,0 +1,248 @@ +/*- + * Copyright (c) 1992, 1993 + * The Regents of the University of California. All rights reserved. + * + * This software was developed by the Computer Systems Engineering group + * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and + * contributed to Berkeley. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)muldi3.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/quad/muldi3.c,v 1.3 2002/03/21 18:40:57 obrien Exp $"); + +#include "quad.h" + +/* + * Multiply two quads. + * + * Our algorithm is based on the following. Split incoming quad values + * u and v (where u,v >= 0) into + * + * u = 2^n u1 * u0 (n = number of bits in `u_long', usu. 32) + * + * and + * + * v = 2^n v1 * v0 + * + * Then + * + * uv = 2^2n u1 v1 + 2^n u1 v0 + 2^n v1 u0 + u0 v0 + * = 2^2n u1 v1 + 2^n (u1 v0 + v1 u0) + u0 v0 + * + * Now add 2^n u1 v1 to the first term and subtract it from the middle, + * and add 2^n u0 v0 to the last term and subtract it from the middle. + * This gives: + * + * uv = (2^2n + 2^n) (u1 v1) + + * (2^n) (u1 v0 - u1 v1 + u0 v1 - u0 v0) + + * (2^n + 1) (u0 v0) + * + * Factoring the middle a bit gives us: + * + * uv = (2^2n + 2^n) (u1 v1) + [u1v1 = high] + * (2^n) (u1 - u0) (v0 - v1) + [(u1-u0)... = mid] + * (2^n + 1) (u0 v0) [u0v0 = low] + * + * The terms (u1 v1), (u1 - u0) (v0 - v1), and (u0 v0) can all be done + * in just half the precision of the original. (Note that either or both + * of (u1 - u0) or (v0 - v1) may be negative.) + * + * This algorithm is from Knuth vol. 2 (2nd ed), section 4.3.3, p. 278. + * + * Since C does not give us a `long * long = quad' operator, we split + * our input quads into two longs, then split the two longs into two + * shorts. We can then calculate `short * short = long' in native + * arithmetic. + * + * Our product should, strictly speaking, be a `long quad', with 128 + * bits, but we are going to discard the upper 64. In other words, + * we are not interested in uv, but rather in (uv mod 2^2n). This + * makes some of the terms above vanish, and we get: + * + * (2^n)(high) + (2^n)(mid) + (2^n + 1)(low) + * + * or + * + * (2^n)(high + mid + low) + low + * + * Furthermore, `high' and `mid' can be computed mod 2^n, as any factor + * of 2^n in either one will also vanish. Only `low' need be computed + * mod 2^2n, and only because of the final term above. + */ +static quad_t __lmulq(u_long, u_long); + +quad_t +__muldi3(a, b) + quad_t a, b; +{ + union uu u, v, low, prod; + u_long high, mid, udiff, vdiff; + int negall, negmid; +#define u1 u.ul[H] +#define u0 u.ul[L] +#define v1 v.ul[H] +#define v0 v.ul[L] + + /* + * Get u and v such that u, v >= 0. When this is finished, + * u1, u0, v1, and v0 will be directly accessible through the + * longword fields. + */ + if (a >= 0) + u.q = a, negall = 0; + else + u.q = -a, negall = 1; + if (b >= 0) + v.q = b; + else + v.q = -b, negall ^= 1; + + if (u1 == 0 && v1 == 0) { + /* + * An (I hope) important optimization occurs when u1 and v1 + * are both 0. This should be common since most numbers + * are small. Here the product is just u0*v0. + */ + prod.q = __lmulq(u0, v0); + } else { + /* + * Compute the three intermediate products, remembering + * whether the middle term is negative. We can discard + * any upper bits in high and mid, so we can use native + * u_long * u_long => u_long arithmetic. + */ + low.q = __lmulq(u0, v0); + + if (u1 >= u0) + negmid = 0, udiff = u1 - u0; + else + negmid = 1, udiff = u0 - u1; + if (v0 >= v1) + vdiff = v0 - v1; + else + vdiff = v1 - v0, negmid ^= 1; + mid = udiff * vdiff; + + high = u1 * v1; + + /* + * Assemble the final product. + */ + prod.ul[H] = high + (negmid ? -mid : mid) + low.ul[L] + + low.ul[H]; + prod.ul[L] = low.ul[L]; + } + return (negall ? -prod.q : prod.q); +#undef u1 +#undef u0 +#undef v1 +#undef v0 +} + +/* + * Multiply two 2N-bit longs to produce a 4N-bit quad, where N is half + * the number of bits in a long (whatever that is---the code below + * does not care as long as quad.h does its part of the bargain---but + * typically N==16). + * + * We use the same algorithm from Knuth, but this time the modulo refinement + * does not apply. On the other hand, since N is half the size of a long, + * we can get away with native multiplication---none of our input terms + * exceeds (ULONG_MAX >> 1). + * + * Note that, for u_long l, the quad-precision result + * + * l << N + * + * splits into high and low longs as HHALF(l) and LHUP(l) respectively. + */ +static quad_t +__lmulq(u_long u, u_long v) +{ + u_long u1, u0, v1, v0, udiff, vdiff, high, mid, low; + u_long prodh, prodl, was; + union uu prod; + int neg; + + u1 = HHALF(u); + u0 = LHALF(u); + v1 = HHALF(v); + v0 = LHALF(v); + + low = u0 * v0; + + /* This is the same small-number optimization as before. */ + if (u1 == 0 && v1 == 0) + return (low); + + if (u1 >= u0) + udiff = u1 - u0, neg = 0; + else + udiff = u0 - u1, neg = 1; + if (v0 >= v1) + vdiff = v0 - v1; + else + vdiff = v1 - v0, neg ^= 1; + mid = udiff * vdiff; + + high = u1 * v1; + + /* prod = (high << 2N) + (high << N); */ + prodh = high + HHALF(high); + prodl = LHUP(high); + + /* if (neg) prod -= mid << N; else prod += mid << N; */ + if (neg) { + was = prodl; + prodl -= LHUP(mid); + prodh -= HHALF(mid) + (prodl > was); + } else { + was = prodl; + prodl += LHUP(mid); + prodh += HHALF(mid) + (prodl < was); + } + + /* prod += low << N */ + was = prodl; + prodl += LHUP(low); + prodh += HHALF(low) + (prodl < was); + /* ... + low; */ + if ((prodl += low) < low) + prodh++; + + /* return 4N-bit product */ + prod.ul[H] = prodh; + prod.ul[L] = prodl; + return (prod.q); +} diff --git a/lib/libc/quad/negdi2.c b/lib/libc/quad/negdi2.c new file mode 100644 index 0000000..f1de706 --- /dev/null +++ b/lib/libc/quad/negdi2.c @@ -0,0 +1,59 @@ +/*- + * Copyright (c) 1992, 1993 + * The Regents of the University of California. All rights reserved. + * + * This software was developed by the Computer Systems Engineering group + * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and + * contributed to Berkeley. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)negdi2.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/quad/negdi2.c,v 1.2 2002/03/22 21:52:43 obrien Exp $"); + +#include "quad.h" + +/* + * Return -a (or, equivalently, 0 - a), in quad. See subdi3.c. + */ +quad_t +__negdi2(a) + quad_t a; +{ + union uu aa, res; + + aa.q = a; + res.ul[L] = -aa.ul[L]; + res.ul[H] = -aa.ul[H] - (res.ul[L] > 0); + return (res.q); +} diff --git a/lib/libc/quad/notdi2.c b/lib/libc/quad/notdi2.c new file mode 100644 index 0000000..354abe5 --- /dev/null +++ b/lib/libc/quad/notdi2.c @@ -0,0 +1,60 @@ +/*- + * Copyright (c) 1992, 1993 + * The Regents of the University of California. All rights reserved. + * + * This software was developed by the Computer Systems Engineering group + * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and + * contributed to Berkeley. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)notdi2.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/quad/notdi2.c,v 1.2 2002/03/22 21:52:43 obrien Exp $"); + +#include "quad.h" + +/* + * Return ~a. For some reason gcc calls this `one's complement' rather + * than `not'. + */ +quad_t +__one_cmpldi2(a) + quad_t a; +{ + union uu aa; + + aa.q = a; + aa.ul[0] = ~aa.ul[0]; + aa.ul[1] = ~aa.ul[1]; + return (aa.q); +} diff --git a/lib/libc/quad/qdivrem.c b/lib/libc/quad/qdivrem.c new file mode 100644 index 0000000..b57077a --- /dev/null +++ b/lib/libc/quad/qdivrem.c @@ -0,0 +1,281 @@ +/*- + * Copyright (c) 1992, 1993 + * The Regents of the University of California. All rights reserved. + * + * This software was developed by the Computer Systems Engineering group + * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and + * contributed to Berkeley. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)qdivrem.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/quad/qdivrem.c,v 1.3 2002/03/21 18:40:57 obrien Exp $"); + +/* + * Multiprecision divide. This algorithm is from Knuth vol. 2 (2nd ed), + * section 4.3.1, pp. 257--259. + */ + +#include "quad.h" + +#define B (1 << HALF_BITS) /* digit base */ + +/* Combine two `digits' to make a single two-digit number. */ +#define COMBINE(a, b) (((u_long)(a) << HALF_BITS) | (b)) + +/* select a type for digits in base B: use unsigned short if they fit */ +#if ULONG_MAX == 0xffffffff && USHRT_MAX >= 0xffff +typedef unsigned short digit; +#else +typedef u_long digit; +#endif + +/* + * Shift p[0]..p[len] left `sh' bits, ignoring any bits that + * `fall out' the left (there never will be any such anyway). + * We may assume len >= 0. NOTE THAT THIS WRITES len+1 DIGITS. + */ +static void +shl(digit *p, int len, int sh) +{ + int i; + + for (i = 0; i < len; i++) + p[i] = LHALF(p[i] << sh) | (p[i + 1] >> (HALF_BITS - sh)); + p[i] = LHALF(p[i] << sh); +} + +/* + * __qdivrem(u, v, rem) returns u/v and, optionally, sets *rem to u%v. + * + * We do this in base 2-sup-HALF_BITS, so that all intermediate products + * fit within u_long. As a consequence, the maximum length dividend and + * divisor are 4 `digits' in this base (they are shorter if they have + * leading zeros). + */ +u_quad_t +__qdivrem(uq, vq, arq) + u_quad_t uq, vq, *arq; +{ + union uu tmp; + digit *u, *v, *q; + digit v1, v2; + u_long qhat, rhat, t; + int m, n, d, j, i; + digit uspace[5], vspace[5], qspace[5]; + + /* + * Take care of special cases: divide by zero, and u < v. + */ + if (vq == 0) { + /* divide by zero. */ + static volatile const unsigned int zero = 0; + + tmp.ul[H] = tmp.ul[L] = 1 / zero; + if (arq) + *arq = uq; + return (tmp.q); + } + if (uq < vq) { + if (arq) + *arq = uq; + return (0); + } + u = &uspace[0]; + v = &vspace[0]; + q = &qspace[0]; + + /* + * Break dividend and divisor into digits in base B, then + * count leading zeros to determine m and n. When done, we + * will have: + * u = (u[1]u[2]...u[m+n]) sub B + * v = (v[1]v[2]...v[n]) sub B + * v[1] != 0 + * 1 < n <= 4 (if n = 1, we use a different division algorithm) + * m >= 0 (otherwise u < v, which we already checked) + * m + n = 4 + * and thus + * m = 4 - n <= 2 + */ + tmp.uq = uq; + u[0] = 0; + u[1] = HHALF(tmp.ul[H]); + u[2] = LHALF(tmp.ul[H]); + u[3] = HHALF(tmp.ul[L]); + u[4] = LHALF(tmp.ul[L]); + tmp.uq = vq; + v[1] = HHALF(tmp.ul[H]); + v[2] = LHALF(tmp.ul[H]); + v[3] = HHALF(tmp.ul[L]); + v[4] = LHALF(tmp.ul[L]); + for (n = 4; v[1] == 0; v++) { + if (--n == 1) { + u_long rbj; /* r*B+u[j] (not root boy jim) */ + digit q1, q2, q3, q4; + + /* + * Change of plan, per exercise 16. + * r = 0; + * for j = 1..4: + * q[j] = floor((r*B + u[j]) / v), + * r = (r*B + u[j]) % v; + * We unroll this completely here. + */ + t = v[2]; /* nonzero, by definition */ + q1 = u[1] / t; + rbj = COMBINE(u[1] % t, u[2]); + q2 = rbj / t; + rbj = COMBINE(rbj % t, u[3]); + q3 = rbj / t; + rbj = COMBINE(rbj % t, u[4]); + q4 = rbj / t; + if (arq) + *arq = rbj % t; + tmp.ul[H] = COMBINE(q1, q2); + tmp.ul[L] = COMBINE(q3, q4); + return (tmp.q); + } + } + + /* + * By adjusting q once we determine m, we can guarantee that + * there is a complete four-digit quotient at &qspace[1] when + * we finally stop. + */ + for (m = 4 - n; u[1] == 0; u++) + m--; + for (i = 4 - m; --i >= 0;) + q[i] = 0; + q += 4 - m; + + /* + * Here we run Program D, translated from MIX to C and acquiring + * a few minor changes. + * + * D1: choose multiplier 1 << d to ensure v[1] >= B/2. + */ + d = 0; + for (t = v[1]; t < B / 2; t <<= 1) + d++; + if (d > 0) { + shl(&u[0], m + n, d); /* u <<= d */ + shl(&v[1], n - 1, d); /* v <<= d */ + } + /* + * D2: j = 0. + */ + j = 0; + v1 = v[1]; /* for D3 -- note that v[1..n] are constant */ + v2 = v[2]; /* for D3 */ + do { + digit uj0, uj1, uj2; + + /* + * D3: Calculate qhat (\^q, in TeX notation). + * Let qhat = min((u[j]*B + u[j+1])/v[1], B-1), and + * let rhat = (u[j]*B + u[j+1]) mod v[1]. + * While rhat < B and v[2]*qhat > rhat*B+u[j+2], + * decrement qhat and increase rhat correspondingly. + * Note that if rhat >= B, v[2]*qhat < rhat*B. + */ + uj0 = u[j + 0]; /* for D3 only -- note that u[j+...] change */ + uj1 = u[j + 1]; /* for D3 only */ + uj2 = u[j + 2]; /* for D3 only */ + if (uj0 == v1) { + qhat = B; + rhat = uj1; + goto qhat_too_big; + } else { + u_long n = COMBINE(uj0, uj1); + qhat = n / v1; + rhat = n % v1; + } + while (v2 * qhat > COMBINE(rhat, uj2)) { + qhat_too_big: + qhat--; + if ((rhat += v1) >= B) + break; + } + /* + * D4: Multiply and subtract. + * The variable `t' holds any borrows across the loop. + * We split this up so that we do not require v[0] = 0, + * and to eliminate a final special case. + */ + for (t = 0, i = n; i > 0; i--) { + t = u[i + j] - v[i] * qhat - t; + u[i + j] = LHALF(t); + t = (B - HHALF(t)) & (B - 1); + } + t = u[j] - t; + u[j] = LHALF(t); + /* + * D5: test remainder. + * There is a borrow if and only if HHALF(t) is nonzero; + * in that (rare) case, qhat was too large (by exactly 1). + * Fix it by adding v[1..n] to u[j..j+n]. + */ + if (HHALF(t)) { + qhat--; + for (t = 0, i = n; i > 0; i--) { /* D6: add back. */ + t += u[i + j] + v[i]; + u[i + j] = LHALF(t); + t = HHALF(t); + } + u[j] = LHALF(u[j] + t); + } + q[j] = qhat; + } while (++j <= m); /* D7: loop on j. */ + + /* + * If caller wants the remainder, we have to calculate it as + * u[m..m+n] >> d (this is at most n digits and thus fits in + * u[m+1..m+n], but we may need more source digits). + */ + if (arq) { + if (d) { + for (i = m + n; i > m; --i) + u[i] = (u[i] >> d) | + LHALF(u[i - 1] << (HALF_BITS - d)); + u[i] = 0; + } + tmp.ul[H] = COMBINE(uspace[1], uspace[2]); + tmp.ul[L] = COMBINE(uspace[3], uspace[4]); + *arq = tmp.q; + } + + tmp.ul[H] = COMBINE(qspace[1], qspace[2]); + tmp.ul[L] = COMBINE(qspace[3], qspace[4]); + return (tmp.q); +} diff --git a/lib/libc/quad/quad.h b/lib/libc/quad/quad.h new file mode 100644 index 0000000..60a2ffb --- /dev/null +++ b/lib/libc/quad/quad.h @@ -0,0 +1,115 @@ +/*- + * Copyright (c) 1992, 1993 + * The Regents of the University of California. All rights reserved. + * + * This software was developed by the Computer Systems Engineering group + * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and + * contributed to Berkeley. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * @(#)quad.h 8.1 (Berkeley) 6/4/93 + * $FreeBSD: src/lib/libc/quad/quad.h,v 1.6 2002/03/21 22:47:55 obrien Exp $ + */ + +/* + * Quad arithmetic. + * + * This library makes the following assumptions: + * + * - The type long long (aka quad_t) exists. + * + * - A quad variable is exactly twice as long as `long'. + * + * - The machine's arithmetic is two's complement. + * + * This library can provide 128-bit arithmetic on a machine with 128-bit + * quads and 64-bit longs, for instance, or 96-bit arithmetic on machines + * with 48-bit longs. + */ + +#include +#include + +/* + * Depending on the desired operation, we view a `long long' (aka quad_t) in + * one or more of the following formats. + */ +union uu { + quad_t q; /* as a (signed) quad */ + quad_t uq; /* as an unsigned quad */ + long sl[2]; /* as two signed longs */ + u_long ul[2]; /* as two unsigned longs */ +}; + +/* + * Define high and low longwords. + */ +#define H _QUAD_HIGHWORD +#define L _QUAD_LOWWORD + +/* + * Total number of bits in a quad_t and in the pieces that make it up. + * These are used for shifting, and also below for halfword extraction + * and assembly. + */ +#define QUAD_BITS (sizeof(quad_t) * CHAR_BIT) +#define LONG_BITS (sizeof(long) * CHAR_BIT) +#define HALF_BITS (sizeof(long) * CHAR_BIT / 2) + +/* + * Extract high and low shortwords from longword, and move low shortword of + * longword to upper half of long, i.e., produce the upper longword of + * ((quad_t)(x) << (number_of_bits_in_long/2)). (`x' must actually be u_long.) + * + * These are used in the multiply code, to split a longword into upper + * and lower halves, and to reassemble a product as a quad_t, shifted left + * (sizeof(long)*CHAR_BIT/2). + */ +#define HHALF(x) ((x) >> HALF_BITS) +#define LHALF(x) ((x) & ((1 << HALF_BITS) - 1)) +#define LHUP(x) ((x) << HALF_BITS) + +quad_t __divdi3(quad_t a, quad_t b); +quad_t __moddi3(quad_t a, quad_t b); +u_quad_t __qdivrem(u_quad_t u, u_quad_t v, u_quad_t *rem); +u_quad_t __udivdi3(u_quad_t a, u_quad_t b); +u_quad_t __umoddi3(u_quad_t a, u_quad_t b); + +/* + * XXX + * Compensate for gcc 1 vs gcc 2. Gcc 1 defines ?sh?di3's second argument + * as u_quad_t, while gcc 2 correctly uses int. Unfortunately, we still use + * both compilers. + */ +#if __GNUC__ >= 2 +typedef unsigned int qshift_t; +#else +typedef u_quad_t qshift_t; +#endif diff --git a/lib/libc/quad/subdi3.c b/lib/libc/quad/subdi3.c new file mode 100644 index 0000000..64adfda --- /dev/null +++ b/lib/libc/quad/subdi3.c @@ -0,0 +1,61 @@ +/*- + * Copyright (c) 1992, 1993 + * The Regents of the University of California. All rights reserved. + * + * This software was developed by the Computer Systems Engineering group + * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and + * contributed to Berkeley. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)subdi3.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/quad/subdi3.c,v 1.2 2002/03/22 21:52:43 obrien Exp $"); + +#include "quad.h" + +/* + * Subtract two quad values. This is trivial since a one-bit carry + * from a single u_long difference x-y occurs if and only if (x-y) > x. + */ +quad_t +__subdi3(a, b) + quad_t a, b; +{ + union uu aa, bb, diff; + + aa.q = a; + bb.q = b; + diff.ul[L] = aa.ul[L] - bb.ul[L]; + diff.ul[H] = aa.ul[H] - bb.ul[H] - (diff.ul[L] > aa.ul[L]); + return (diff.q); +} diff --git a/lib/libc/quad/ucmpdi2.c b/lib/libc/quad/ucmpdi2.c new file mode 100644 index 0000000..d5958ba --- /dev/null +++ b/lib/libc/quad/ucmpdi2.c @@ -0,0 +1,60 @@ +/*- + * Copyright (c) 1992, 1993 + * The Regents of the University of California. All rights reserved. + * + * This software was developed by the Computer Systems Engineering group + * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and + * contributed to Berkeley. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)ucmpdi2.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/quad/ucmpdi2.c,v 1.2 2002/03/22 21:52:43 obrien Exp $"); + +#include "quad.h" + +/* + * Return 0, 1, or 2 as a <, =, > b respectively. + * Neither a nor b are considered signed. + */ +int +__ucmpdi2(a, b) + u_quad_t a, b; +{ + union uu aa, bb; + + aa.uq = a; + bb.uq = b; + return (aa.ul[H] < bb.ul[H] ? 0 : aa.ul[H] > bb.ul[H] ? 2 : + aa.ul[L] < bb.ul[L] ? 0 : aa.ul[L] > bb.ul[L] ? 2 : 1); +} diff --git a/lib/libc/quad/udivdi3.c b/lib/libc/quad/udivdi3.c new file mode 100644 index 0000000..f7ce83a --- /dev/null +++ b/lib/libc/quad/udivdi3.c @@ -0,0 +1,55 @@ +/*- + * Copyright (c) 1992, 1993 + * The Regents of the University of California. All rights reserved. + * + * This software was developed by the Computer Systems Engineering group + * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and + * contributed to Berkeley. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)udivdi3.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/quad/udivdi3.c,v 1.2 2002/03/22 21:52:43 obrien Exp $"); + +#include "quad.h" + +/* + * Divide two unsigned quads. + */ +u_quad_t +__udivdi3(a, b) + u_quad_t a, b; +{ + + return (__qdivrem(a, b, (u_quad_t *)0)); +} diff --git a/lib/libc/quad/umoddi3.c b/lib/libc/quad/umoddi3.c new file mode 100644 index 0000000..12703c7 --- /dev/null +++ b/lib/libc/quad/umoddi3.c @@ -0,0 +1,57 @@ +/*- + * Copyright (c) 1992, 1993 + * The Regents of the University of California. All rights reserved. + * + * This software was developed by the Computer Systems Engineering group + * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and + * contributed to Berkeley. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)umoddi3.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/quad/umoddi3.c,v 1.2 2002/03/22 21:52:43 obrien Exp $"); + +#include "quad.h" + +/* + * Return remainder after dividing two unsigned quads. + */ +u_quad_t +__umoddi3(a, b) + u_quad_t a, b; +{ + u_quad_t r; + + (void)__qdivrem(a, b, &r); + return (r); +} diff --git a/lib/libc/quad/xordi3.c b/lib/libc/quad/xordi3.c new file mode 100644 index 0000000..73594de --- /dev/null +++ b/lib/libc/quad/xordi3.c @@ -0,0 +1,60 @@ +/*- + * Copyright (c) 1992, 1993 + * The Regents of the University of California. All rights reserved. + * + * This software was developed by the Computer Systems Engineering group + * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and + * contributed to Berkeley. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)xordi3.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/quad/xordi3.c,v 1.2 2002/03/22 21:52:43 obrien Exp $"); + +#include "quad.h" + +/* + * Return a ^ b, in quad. + */ +quad_t +__xordi3(a, b) + quad_t a, b; +{ + union uu aa, bb; + + aa.q = a; + bb.q = b; + aa.ul[0] ^= bb.ul[0]; + aa.ul[1] ^= bb.ul[1]; + return (aa.q); +} diff --git a/lib/libc/regex/COPYRIGHT b/lib/libc/regex/COPYRIGHT new file mode 100644 index 0000000..574f6bc --- /dev/null +++ b/lib/libc/regex/COPYRIGHT @@ -0,0 +1,56 @@ +Copyright 1992, 1993, 1994 Henry Spencer. All rights reserved. +This software is not subject to any license of the American Telephone +and Telegraph Company or of the Regents of the University of California. + +Permission is granted to anyone to use this software for any purpose on +any computer system, and to alter it and redistribute it, subject +to the following restrictions: + +1. The author is not responsible for the consequences of use of this + software, no matter how awful, even if they arise from flaws in it. + +2. The origin of this software must not be misrepresented, either by + explicit claim or by omission. Since few users ever read sources, + credits must appear in the documentation. + +3. Altered versions must be plainly marked as such, and must not be + misrepresented as being the original software. Since few users + ever read sources, credits must appear in the documentation. + +4. This notice may not be removed or altered. + +=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +/*- + * Copyright (c) 1994 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * @(#)COPYRIGHT 8.1 (Berkeley) 3/16/94 + */ diff --git a/lib/libc/regex/Makefile b/lib/libc/regex/Makefile new file mode 100644 index 0000000..a9b742b --- /dev/null +++ b/lib/libc/regex/Makefile @@ -0,0 +1,35 @@ +# $Id: Makefile 89 2016-01-12 00:20:40Z reddawg $ +# The System Makefile (C) 2002 The UbixOS Project + +# Include Global 'Source' Options +include ../../../Makefile.incl +include ../../Makefile.incl +include ../Makefile.incl + +INCLUDES += -I../locale/ + +#Objects +OBJS = regcomp.o regerror.o regexec.o regfree.o + +all: $(OBJS) + +# Compile the source files +.cc.o: + $(CXX) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -c -o $@ $< + +.cc.s: + $(CXX) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -S -o $@ $< + +.c.o: + $(CC) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -c $< + +.c.s: + $(CC) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -S -o $@ $< + +.S.o: + $(CC) $(CFLAGS) -Wall -nostdlib -c -o $@ $< + +# Clean up the junk +clean: + $(REMOVE) $(OBJS) + diff --git a/lib/libc/regex/cname.h b/lib/libc/regex/cname.h new file mode 100644 index 0000000..4f0d583 --- /dev/null +++ b/lib/libc/regex/cname.h @@ -0,0 +1,142 @@ +/*- + * Copyright (c) 1992, 1993, 1994 Henry Spencer. + * Copyright (c) 1992, 1993, 1994 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * Henry Spencer. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * @(#)cname.h 8.3 (Berkeley) 3/20/94 + * $FreeBSD: src/lib/libc/regex/cname.h,v 1.3 2002/03/22 23:41:56 obrien Exp $ + */ + +/* character-name table */ +static struct cname { + char *name; + char code; +} cnames[] = { + {"NUL", '\0'}, + {"SOH", '\001'}, + {"STX", '\002'}, + {"ETX", '\003'}, + {"EOT", '\004'}, + {"ENQ", '\005'}, + {"ACK", '\006'}, + {"BEL", '\007'}, + {"alert", '\007'}, + {"BS", '\010'}, + {"backspace", '\b'}, + {"HT", '\011'}, + {"tab", '\t'}, + {"LF", '\012'}, + {"newline", '\n'}, + {"VT", '\013'}, + {"vertical-tab", '\v'}, + {"FF", '\014'}, + {"form-feed", '\f'}, + {"CR", '\015'}, + {"carriage-return", '\r'}, + {"SO", '\016'}, + {"SI", '\017'}, + {"DLE", '\020'}, + {"DC1", '\021'}, + {"DC2", '\022'}, + {"DC3", '\023'}, + {"DC4", '\024'}, + {"NAK", '\025'}, + {"SYN", '\026'}, + {"ETB", '\027'}, + {"CAN", '\030'}, + {"EM", '\031'}, + {"SUB", '\032'}, + {"ESC", '\033'}, + {"IS4", '\034'}, + {"FS", '\034'}, + {"IS3", '\035'}, + {"GS", '\035'}, + {"IS2", '\036'}, + {"RS", '\036'}, + {"IS1", '\037'}, + {"US", '\037'}, + {"space", ' '}, + {"exclamation-mark", '!'}, + {"quotation-mark", '"'}, + {"number-sign", '#'}, + {"dollar-sign", '$'}, + {"percent-sign", '%'}, + {"ampersand", '&'}, + {"apostrophe", '\''}, + {"left-parenthesis", '('}, + {"right-parenthesis", ')'}, + {"asterisk", '*'}, + {"plus-sign", '+'}, + {"comma", ','}, + {"hyphen", '-'}, + {"hyphen-minus", '-'}, + {"period", '.'}, + {"full-stop", '.'}, + {"slash", '/'}, + {"solidus", '/'}, + {"zero", '0'}, + {"one", '1'}, + {"two", '2'}, + {"three", '3'}, + {"four", '4'}, + {"five", '5'}, + {"six", '6'}, + {"seven", '7'}, + {"eight", '8'}, + {"nine", '9'}, + {"colon", ':'}, + {"semicolon", ';'}, + {"less-than-sign", '<'}, + {"equals-sign", '='}, + {"greater-than-sign", '>'}, + {"question-mark", '?'}, + {"commercial-at", '@'}, + {"left-square-bracket", '['}, + {"backslash", '\\'}, + {"reverse-solidus", '\\'}, + {"right-square-bracket",']'}, + {"circumflex", '^'}, + {"circumflex-accent", '^'}, + {"underscore", '_'}, + {"low-line", '_'}, + {"grave-accent", '`'}, + {"left-brace", '{'}, + {"left-curly-bracket", '{'}, + {"vertical-line", '|'}, + {"right-brace", '}'}, + {"right-curly-bracket", '}'}, + {"tilde", '~'}, + {"DEL", '\177'}, + {NULL, 0} +}; diff --git a/lib/libc/regex/engine.c b/lib/libc/regex/engine.c new file mode 100644 index 0000000..cb48cfc --- /dev/null +++ b/lib/libc/regex/engine.c @@ -0,0 +1,1196 @@ +/*- + * Copyright (c) 1992, 1993, 1994 Henry Spencer. + * Copyright (c) 1992, 1993, 1994 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * Henry Spencer. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * @(#)engine.c 8.5 (Berkeley) 3/20/94 + */ + +#include +__FBSDID("$FreeBSD: src/lib/libc/regex/engine.c,v 1.16 2004/12/30 14:27:57 dds Exp $"); + +/* + * The matching engine and friends. This file is #included by regexec.c + * after suitable #defines of a variety of macros used herein, so that + * different state representations can be used without duplicating masses + * of code. + */ + +#ifdef SNAMES +#define matcher smatcher +#define fast sfast +#define slow sslow +#define dissect sdissect +#define backref sbackref +#define step sstep +#define print sprint +#define at sat +#define match smat +#endif +#ifdef LNAMES +#define matcher lmatcher +#define fast lfast +#define slow lslow +#define dissect ldissect +#define backref lbackref +#define step lstep +#define print lprint +#define at lat +#define match lmat +#endif +#ifdef MNAMES +#define matcher mmatcher +#define fast mfast +#define slow mslow +#define dissect mdissect +#define backref mbackref +#define step mstep +#define print mprint +#define at mat +#define match mmat +#endif + +/* another structure passed up and down to avoid zillions of parameters */ +struct match { + struct re_guts *g; + int eflags; + regmatch_t *pmatch; /* [nsub+1] (0 element unused) */ + char *offp; /* offsets work from here */ + char *beginp; /* start of string -- virtual NUL precedes */ + char *endp; /* end of string -- virtual NUL here */ + char *coldp; /* can be no match starting before here */ + char **lastpos; /* [nplus+1] */ + STATEVARS; + states st; /* current states */ + states fresh; /* states for a fresh start */ + states tmp; /* temporary */ + states empty; /* empty set of states */ + mbstate_t mbs; /* multibyte conversion state */ +}; + +/* ========= begin header generated by ./mkh ========= */ +#ifdef __cplusplus +extern "C" { +#endif + +/* === engine.c === */ +static int matcher(struct re_guts *g, char *string, size_t nmatch, regmatch_t pmatch[], int eflags); +static char *dissect(struct match *m, char *start, char *stop, sopno startst, sopno stopst); +static char *backref(struct match *m, char *start, char *stop, sopno startst, sopno stopst, sopno lev); +static char *fast(struct match *m, char *start, char *stop, sopno startst, sopno stopst); +static char *slow(struct match *m, char *start, char *stop, sopno startst, sopno stopst); +static states step(struct re_guts *g, sopno start, sopno stop, states bef, wint_t ch, states aft); +#define BOL (OUT-1) +#define EOL (BOL-1) +#define BOLEOL (BOL-2) +#define NOTHING (BOL-3) +#define BOW (BOL-4) +#define EOW (BOL-5) +#define BADCHAR (BOL-6) +#define NONCHAR(c) ((c) <= OUT) +#ifdef REDEBUG +static void print(struct match *m, char *caption, states st, int ch, FILE *d); +#endif +#ifdef REDEBUG +static void at(struct match *m, char *title, char *start, char *stop, sopno startst, sopno stopst); +#endif +#ifdef REDEBUG +static char *pchar(int ch); +#endif + +#ifdef __cplusplus +} +#endif +/* ========= end header generated by ./mkh ========= */ + +#ifdef REDEBUG +#define SP(t, s, c) print(m, t, s, c, stdout) +#define AT(t, p1, p2, s1, s2) at(m, t, p1, p2, s1, s2) +#define NOTE(str) { if (m->eflags®_TRACE) printf("=%s\n", (str)); } +#else +#define SP(t, s, c) /* nothing */ +#define AT(t, p1, p2, s1, s2) /* nothing */ +#define NOTE(s) /* nothing */ +#endif + +/* + - matcher - the actual matching engine + == static int matcher(struct re_guts *g, char *string, \ + == size_t nmatch, regmatch_t pmatch[], int eflags); + */ +static int /* 0 success, REG_NOMATCH failure */ +matcher(g, string, nmatch, pmatch, eflags) +struct re_guts *g; +char *string; +size_t nmatch; +regmatch_t pmatch[]; +int eflags; +{ + char *endp; + int i; + struct match mv; + struct match *m = &mv; + char *dp; + const sopno gf = g->firststate+1; /* +1 for OEND */ + const sopno gl = g->laststate; + char *start; + char *stop; + /* Boyer-Moore algorithms variables */ + char *pp; + int cj, mj; + char *mustfirst; + char *mustlast; + int *matchjump; + int *charjump; + + /* simplify the situation where possible */ + if (g->cflags®_NOSUB) + nmatch = 0; + if (eflags®_STARTEND) { + start = string + pmatch[0].rm_so; + stop = string + pmatch[0].rm_eo; + } else { + start = string; + stop = start + strlen(start); + } + if (stop < start) + return(REG_INVARG); + + /* prescreening; this does wonders for this rather slow code */ + if (g->must != NULL) { + if (g->charjump != NULL && g->matchjump != NULL) { + mustfirst = g->must; + mustlast = g->must + g->mlen - 1; + charjump = g->charjump; + matchjump = g->matchjump; + pp = mustlast; + for (dp = start+g->mlen-1; dp < stop;) { + /* Fast skip non-matches */ + while (dp < stop && charjump[(int)*dp]) + dp += charjump[(int)*dp]; + + if (dp >= stop) + break; + + /* Greedy matcher */ + /* We depend on not being used for + * for strings of length 1 + */ + while (*--dp == *--pp && pp != mustfirst); + + if (*dp == *pp) + break; + + /* Jump to next possible match */ + mj = matchjump[pp - mustfirst]; + cj = charjump[(int)*dp]; + dp += (cj < mj ? mj : cj); + pp = mustlast; + } + if (pp != mustfirst) + return(REG_NOMATCH); + } else { + for (dp = start; dp < stop; dp++) + if (*dp == g->must[0] && + stop - dp >= g->mlen && + memcmp(dp, g->must, (size_t)g->mlen) == 0) + break; + if (dp == stop) /* we didn't find g->must */ + return(REG_NOMATCH); + } + } + + /* match struct setup */ + m->g = g; + m->eflags = eflags; + m->pmatch = NULL; + m->lastpos = NULL; + m->offp = string; + m->beginp = start; + m->endp = stop; + STATESETUP(m, 4); + SETUP(m->st); + SETUP(m->fresh); + SETUP(m->tmp); + SETUP(m->empty); + CLEAR(m->empty); + ZAPSTATE(&m->mbs); + + /* Adjust start according to moffset, to speed things up */ + if (g->moffset > -1) + start = ((dp - g->moffset) < start) ? start : dp - g->moffset; + + /* this loop does only one repetition except for backrefs */ + for (;;) { + endp = fast(m, start, stop, gf, gl); + if (endp == NULL) { /* a miss */ + if (m->pmatch != NULL) + free((char *)m->pmatch); + if (m->lastpos != NULL) + free((char *)m->lastpos); + STATETEARDOWN(m); + return(REG_NOMATCH); + } + if (nmatch == 0 && !g->backrefs) + break; /* no further info needed */ + + /* where? */ + assert(m->coldp != NULL); + for (;;) { + NOTE("finding start"); + endp = slow(m, m->coldp, stop, gf, gl); + if (endp != NULL) + break; + assert(m->coldp < m->endp); + m->coldp += XMBRTOWC(NULL, m->coldp, + m->endp - m->coldp, &m->mbs, 0); + } + if (nmatch == 1 && !g->backrefs) + break; /* no further info needed */ + + /* oh my, he wants the subexpressions... */ + if (m->pmatch == NULL) + m->pmatch = (regmatch_t *)malloc((m->g->nsub + 1) * + sizeof(regmatch_t)); + if (m->pmatch == NULL) { + STATETEARDOWN(m); + return(REG_ESPACE); + } + for (i = 1; i <= m->g->nsub; i++) + m->pmatch[i].rm_so = m->pmatch[i].rm_eo = -1; + if (!g->backrefs && !(m->eflags®_BACKR)) { + NOTE("dissecting"); + dp = dissect(m, m->coldp, endp, gf, gl); + } else { + if (g->nplus > 0 && m->lastpos == NULL) + m->lastpos = (char **)malloc((g->nplus+1) * + sizeof(char *)); + if (g->nplus > 0 && m->lastpos == NULL) { + free(m->pmatch); + STATETEARDOWN(m); + return(REG_ESPACE); + } + NOTE("backref dissect"); + dp = backref(m, m->coldp, endp, gf, gl, (sopno)0); + } + if (dp != NULL) + break; + + /* uh-oh... we couldn't find a subexpression-level match */ + assert(g->backrefs); /* must be back references doing it */ + assert(g->nplus == 0 || m->lastpos != NULL); + for (;;) { + if (dp != NULL || endp <= m->coldp) + break; /* defeat */ + NOTE("backoff"); + endp = slow(m, m->coldp, endp-1, gf, gl); + if (endp == NULL) + break; /* defeat */ + /* try it on a shorter possibility */ +#ifndef NDEBUG + for (i = 1; i <= m->g->nsub; i++) { + assert(m->pmatch[i].rm_so == -1); + assert(m->pmatch[i].rm_eo == -1); + } +#endif + NOTE("backoff dissect"); + dp = backref(m, m->coldp, endp, gf, gl, (sopno)0); + } + assert(dp == NULL || dp == endp); + if (dp != NULL) /* found a shorter one */ + break; + + /* despite initial appearances, there is no match here */ + NOTE("false alarm"); + /* recycle starting later */ + start = m->coldp + XMBRTOWC(NULL, m->coldp, + stop - m->coldp, &m->mbs, 0); + assert(start <= stop); + } + + /* fill in the details if requested */ + if (nmatch > 0) { + pmatch[0].rm_so = m->coldp - m->offp; + pmatch[0].rm_eo = endp - m->offp; + } + if (nmatch > 1) { + assert(m->pmatch != NULL); + for (i = 1; i < nmatch; i++) + if (i <= m->g->nsub) + pmatch[i] = m->pmatch[i]; + else { + pmatch[i].rm_so = -1; + pmatch[i].rm_eo = -1; + } + } + + if (m->pmatch != NULL) + free((char *)m->pmatch); + if (m->lastpos != NULL) + free((char *)m->lastpos); + STATETEARDOWN(m); + return(0); +} + +/* + - dissect - figure out what matched what, no back references + == static char *dissect(struct match *m, char *start, \ + == char *stop, sopno startst, sopno stopst); + */ +static char * /* == stop (success) always */ +dissect(m, start, stop, startst, stopst) +struct match *m; +char *start; +char *stop; +sopno startst; +sopno stopst; +{ + int i; + sopno ss; /* start sop of current subRE */ + sopno es; /* end sop of current subRE */ + char *sp; /* start of string matched by it */ + char *stp; /* string matched by it cannot pass here */ + char *rest; /* start of rest of string */ + char *tail; /* string unmatched by rest of RE */ + sopno ssub; /* start sop of subsubRE */ + sopno esub; /* end sop of subsubRE */ + char *ssp; /* start of string matched by subsubRE */ + char *sep; /* end of string matched by subsubRE */ + char *oldssp; /* previous ssp */ + char *dp; + + AT("diss", start, stop, startst, stopst); + sp = start; + for (ss = startst; ss < stopst; ss = es) { + /* identify end of subRE */ + es = ss; + switch (OP(m->g->strip[es])) { + case OPLUS_: + case OQUEST_: + es += OPND(m->g->strip[es]); + break; + case OCH_: + while (OP(m->g->strip[es]) != O_CH) + es += OPND(m->g->strip[es]); + break; + } + es++; + + /* figure out what it matched */ + switch (OP(m->g->strip[ss])) { + case OEND: + assert(nope); + break; + case OCHAR: + sp += XMBRTOWC(NULL, sp, stop - start, &m->mbs, 0); + break; + case OBOL: + case OEOL: + case OBOW: + case OEOW: + break; + case OANY: + case OANYOF: + sp += XMBRTOWC(NULL, sp, stop - start, &m->mbs, 0); + break; + case OBACK_: + case O_BACK: + assert(nope); + break; + /* cases where length of match is hard to find */ + case OQUEST_: + stp = stop; + for (;;) { + /* how long could this one be? */ + rest = slow(m, sp, stp, ss, es); + assert(rest != NULL); /* it did match */ + /* could the rest match the rest? */ + tail = slow(m, rest, stop, es, stopst); + if (tail == stop) + break; /* yes! */ + /* no -- try a shorter match for this one */ + stp = rest - 1; + assert(stp >= sp); /* it did work */ + } + ssub = ss + 1; + esub = es - 1; + /* did innards match? */ + if (slow(m, sp, rest, ssub, esub) != NULL) { + dp = dissect(m, sp, rest, ssub, esub); + assert(dp == rest); + } else /* no */ + assert(sp == rest); + sp = rest; + break; + case OPLUS_: + stp = stop; + for (;;) { + /* how long could this one be? */ + rest = slow(m, sp, stp, ss, es); + assert(rest != NULL); /* it did match */ + /* could the rest match the rest? */ + tail = slow(m, rest, stop, es, stopst); + if (tail == stop) + break; /* yes! */ + /* no -- try a shorter match for this one */ + stp = rest - 1; + assert(stp >= sp); /* it did work */ + } + ssub = ss + 1; + esub = es - 1; + ssp = sp; + oldssp = ssp; + for (;;) { /* find last match of innards */ + sep = slow(m, ssp, rest, ssub, esub); + if (sep == NULL || sep == ssp) + break; /* failed or matched null */ + oldssp = ssp; /* on to next try */ + ssp = sep; + } + if (sep == NULL) { + /* last successful match */ + sep = ssp; + ssp = oldssp; + } + assert(sep == rest); /* must exhaust substring */ + assert(slow(m, ssp, sep, ssub, esub) == rest); + dp = dissect(m, ssp, sep, ssub, esub); + assert(dp == sep); + sp = rest; + break; + case OCH_: + stp = stop; + for (;;) { + /* how long could this one be? */ + rest = slow(m, sp, stp, ss, es); + assert(rest != NULL); /* it did match */ + /* could the rest match the rest? */ + tail = slow(m, rest, stop, es, stopst); + if (tail == stop) + break; /* yes! */ + /* no -- try a shorter match for this one */ + stp = rest - 1; + assert(stp >= sp); /* it did work */ + } + ssub = ss + 1; + esub = ss + OPND(m->g->strip[ss]) - 1; + assert(OP(m->g->strip[esub]) == OOR1); + for (;;) { /* find first matching branch */ + if (slow(m, sp, rest, ssub, esub) == rest) + break; /* it matched all of it */ + /* that one missed, try next one */ + assert(OP(m->g->strip[esub]) == OOR1); + esub++; + assert(OP(m->g->strip[esub]) == OOR2); + ssub = esub + 1; + esub += OPND(m->g->strip[esub]); + if (OP(m->g->strip[esub]) == OOR2) + esub--; + else + assert(OP(m->g->strip[esub]) == O_CH); + } + dp = dissect(m, sp, rest, ssub, esub); + assert(dp == rest); + sp = rest; + break; + case O_PLUS: + case O_QUEST: + case OOR1: + case OOR2: + case O_CH: + assert(nope); + break; + case OLPAREN: + i = OPND(m->g->strip[ss]); + assert(0 < i && i <= m->g->nsub); + m->pmatch[i].rm_so = sp - m->offp; + break; + case ORPAREN: + i = OPND(m->g->strip[ss]); + assert(0 < i && i <= m->g->nsub); + m->pmatch[i].rm_eo = sp - m->offp; + break; + default: /* uh oh */ + assert(nope); + break; + } + } + + assert(sp == stop); + return(sp); +} + +/* + - backref - figure out what matched what, figuring in back references + == static char *backref(struct match *m, char *start, \ + == char *stop, sopno startst, sopno stopst, sopno lev); + */ +static char * /* == stop (success) or NULL (failure) */ +backref(m, start, stop, startst, stopst, lev) +struct match *m; +char *start; +char *stop; +sopno startst; +sopno stopst; +sopno lev; /* PLUS nesting level */ +{ + int i; + sopno ss; /* start sop of current subRE */ + char *sp; /* start of string matched by it */ + sopno ssub; /* start sop of subsubRE */ + sopno esub; /* end sop of subsubRE */ + char *ssp; /* start of string matched by subsubRE */ + char *dp; + size_t len; + int hard; + sop s; + regoff_t offsave; + cset *cs; + wint_t wc; + + AT("back", start, stop, startst, stopst); + sp = start; + + /* get as far as we can with easy stuff */ + hard = 0; + for (ss = startst; !hard && ss < stopst; ss++) + switch (OP(s = m->g->strip[ss])) { + case OCHAR: + if (sp == stop) + return(NULL); + sp += XMBRTOWC(&wc, sp, stop - sp, &m->mbs, BADCHAR); + if (wc != OPND(s)) + return(NULL); + break; + case OANY: + if (sp == stop) + return(NULL); + sp += XMBRTOWC(&wc, sp, stop - sp, &m->mbs, BADCHAR); + if (wc == BADCHAR) + return (NULL); + break; + case OANYOF: + if (sp == stop) + return (NULL); + cs = &m->g->sets[OPND(s)]; + sp += XMBRTOWC(&wc, sp, stop - sp, &m->mbs, BADCHAR); + if (wc == BADCHAR || !CHIN(cs, wc)) + return(NULL); + break; + case OBOL: + if ( (sp == m->beginp && !(m->eflags®_NOTBOL)) || + (sp < m->endp && *(sp-1) == '\n' && + (m->g->cflags®_NEWLINE)) ) + { /* yes */ } + else + return(NULL); + break; + case OEOL: + if ( (sp == m->endp && !(m->eflags®_NOTEOL)) || + (sp < m->endp && *sp == '\n' && + (m->g->cflags®_NEWLINE)) ) + { /* yes */ } + else + return(NULL); + break; + case OBOW: + if (( (sp == m->beginp && !(m->eflags®_NOTBOL)) || + (sp < m->endp && *(sp-1) == '\n' && + (m->g->cflags®_NEWLINE)) || + (sp > m->beginp && + !ISWORD(*(sp-1))) ) && + (sp < m->endp && ISWORD(*sp)) ) + { /* yes */ } + else + return(NULL); + break; + case OEOW: + if (( (sp == m->endp && !(m->eflags®_NOTEOL)) || + (sp < m->endp && *sp == '\n' && + (m->g->cflags®_NEWLINE)) || + (sp < m->endp && !ISWORD(*sp)) ) && + (sp > m->beginp && ISWORD(*(sp-1))) ) + { /* yes */ } + else + return(NULL); + break; + case O_QUEST: + break; + case OOR1: /* matches null but needs to skip */ + ss++; + s = m->g->strip[ss]; + do { + assert(OP(s) == OOR2); + ss += OPND(s); + } while (OP(s = m->g->strip[ss]) != O_CH); + /* note that the ss++ gets us past the O_CH */ + break; + default: /* have to make a choice */ + hard = 1; + break; + } + if (!hard) { /* that was it! */ + if (sp != stop) + return(NULL); + return(sp); + } + ss--; /* adjust for the for's final increment */ + + /* the hard stuff */ + AT("hard", sp, stop, ss, stopst); + s = m->g->strip[ss]; + switch (OP(s)) { + case OBACK_: /* the vilest depths */ + i = OPND(s); + assert(0 < i && i <= m->g->nsub); + if (m->pmatch[i].rm_eo == -1) + return(NULL); + assert(m->pmatch[i].rm_so != -1); + len = m->pmatch[i].rm_eo - m->pmatch[i].rm_so; + assert(stop - m->beginp >= len); + if (sp > stop - len) + return(NULL); /* not enough left to match */ + ssp = m->offp + m->pmatch[i].rm_so; + if (memcmp(sp, ssp, len) != 0) + return(NULL); + while (m->g->strip[ss] != SOP(O_BACK, i)) + ss++; + return(backref(m, sp+len, stop, ss+1, stopst, lev)); + break; + case OQUEST_: /* to null or not */ + dp = backref(m, sp, stop, ss+1, stopst, lev); + if (dp != NULL) + return(dp); /* not */ + return(backref(m, sp, stop, ss+OPND(s)+1, stopst, lev)); + break; + case OPLUS_: + assert(m->lastpos != NULL); + assert(lev+1 <= m->g->nplus); + m->lastpos[lev+1] = sp; + return(backref(m, sp, stop, ss+1, stopst, lev+1)); + break; + case O_PLUS: + if (sp == m->lastpos[lev]) /* last pass matched null */ + return(backref(m, sp, stop, ss+1, stopst, lev-1)); + /* try another pass */ + m->lastpos[lev] = sp; + dp = backref(m, sp, stop, ss-OPND(s)+1, stopst, lev); + if (dp == NULL) + return(backref(m, sp, stop, ss+1, stopst, lev-1)); + else + return(dp); + break; + case OCH_: /* find the right one, if any */ + ssub = ss + 1; + esub = ss + OPND(s) - 1; + assert(OP(m->g->strip[esub]) == OOR1); + for (;;) { /* find first matching branch */ + dp = backref(m, sp, stop, ssub, esub, lev); + if (dp != NULL) + return(dp); + /* that one missed, try next one */ + if (OP(m->g->strip[esub]) == O_CH) + return(NULL); /* there is none */ + esub++; + assert(OP(m->g->strip[esub]) == OOR2); + ssub = esub + 1; + esub += OPND(m->g->strip[esub]); + if (OP(m->g->strip[esub]) == OOR2) + esub--; + else + assert(OP(m->g->strip[esub]) == O_CH); + } + break; + case OLPAREN: /* must undo assignment if rest fails */ + i = OPND(s); + assert(0 < i && i <= m->g->nsub); + offsave = m->pmatch[i].rm_so; + m->pmatch[i].rm_so = sp - m->offp; + dp = backref(m, sp, stop, ss+1, stopst, lev); + if (dp != NULL) + return(dp); + m->pmatch[i].rm_so = offsave; + return(NULL); + break; + case ORPAREN: /* must undo assignment if rest fails */ + i = OPND(s); + assert(0 < i && i <= m->g->nsub); + offsave = m->pmatch[i].rm_eo; + m->pmatch[i].rm_eo = sp - m->offp; + dp = backref(m, sp, stop, ss+1, stopst, lev); + if (dp != NULL) + return(dp); + m->pmatch[i].rm_eo = offsave; + return(NULL); + break; + default: /* uh oh */ + assert(nope); + break; + } + + /* "can't happen" */ + assert(nope); + /* NOTREACHED */ + return "shut up gcc"; +} + +/* + - fast - step through the string at top speed + == static char *fast(struct match *m, char *start, \ + == char *stop, sopno startst, sopno stopst); + */ +static char * /* where tentative match ended, or NULL */ +fast(m, start, stop, startst, stopst) +struct match *m; +char *start; +char *stop; +sopno startst; +sopno stopst; +{ + states st = m->st; + states fresh = m->fresh; + states tmp = m->tmp; + char *p = start; + wint_t c; + wint_t lastc; /* previous c */ + wint_t flagch; + int i; + char *coldp; /* last p after which no match was underway */ + size_t clen; + + CLEAR(st); + SET1(st, startst); + st = step(m->g, startst, stopst, st, NOTHING, st); + ASSIGN(fresh, st); + SP("start", st, *p); + coldp = NULL; + if (start == m->beginp) + c = OUT; + else { + /* + * XXX Wrong if the previous character was multi-byte. + * Newline never is (in encodings supported by FreeBSD), + * so this only breaks the ISWORD tests below. + */ + c = (uch)*(start - 1); + } + for (;;) { + /* next character */ + lastc = c; + if (p == m->endp) + c = OUT; + else + clen = XMBRTOWC(&c, p, stop - p, &m->mbs, BADCHAR); + if (EQ(st, fresh)) + coldp = p; + + /* is there an EOL and/or BOL between lastc and c? */ + flagch = '\0'; + i = 0; + if ( (lastc == '\n' && m->g->cflags®_NEWLINE) || + (lastc == OUT && !(m->eflags®_NOTBOL)) ) { + flagch = BOL; + i = m->g->nbol; + } + if ( (c == '\n' && m->g->cflags®_NEWLINE) || + (c == OUT && !(m->eflags®_NOTEOL)) ) { + flagch = (flagch == BOL) ? BOLEOL : EOL; + i += m->g->neol; + } + if (i != 0) { + for (; i > 0; i--) + st = step(m->g, startst, stopst, st, flagch, st); + SP("boleol", st, c); + } + + /* how about a word boundary? */ + if ( (flagch == BOL || (lastc != OUT && !ISWORD(lastc))) && + (c != OUT && ISWORD(c)) ) { + flagch = BOW; + } + if ( (lastc != OUT && ISWORD(lastc)) && + (flagch == EOL || (c != OUT && !ISWORD(c))) ) { + flagch = EOW; + } + if (flagch == BOW || flagch == EOW) { + st = step(m->g, startst, stopst, st, flagch, st); + SP("boweow", st, c); + } + + /* are we done? */ + if (ISSET(st, stopst) || p == stop) + break; /* NOTE BREAK OUT */ + + /* no, we must deal with this character */ + ASSIGN(tmp, st); + ASSIGN(st, fresh); + assert(c != OUT); + st = step(m->g, startst, stopst, tmp, c, st); + SP("aft", st, c); + assert(EQ(step(m->g, startst, stopst, st, NOTHING, st), st)); + p += clen; + } + + assert(coldp != NULL); + m->coldp = coldp; + if (ISSET(st, stopst)) + return(p+XMBRTOWC(NULL, p, stop - p, &m->mbs, 0)); + else + return(NULL); +} + +/* + - slow - step through the string more deliberately + == static char *slow(struct match *m, char *start, \ + == char *stop, sopno startst, sopno stopst); + */ +static char * /* where it ended */ +slow(m, start, stop, startst, stopst) +struct match *m; +char *start; +char *stop; +sopno startst; +sopno stopst; +{ + states st = m->st; + states empty = m->empty; + states tmp = m->tmp; + char *p = start; + wint_t c; + wint_t lastc; /* previous c */ + wint_t flagch; + int i; + char *matchp; /* last p at which a match ended */ + size_t clen; + + AT("slow", start, stop, startst, stopst); + CLEAR(st); + SET1(st, startst); + SP("sstart", st, *p); + st = step(m->g, startst, stopst, st, NOTHING, st); + matchp = NULL; + if (start == m->beginp) + c = OUT; + else { + /* + * XXX Wrong if the previous character was multi-byte. + * Newline never is (in encodings supported by FreeBSD), + * so this only breaks the ISWORD tests below. + */ + c = (uch)*(start - 1); + } + for (;;) { + /* next character */ + lastc = c; + if (p == m->endp) { + c = OUT; + clen = 0; + } else + clen = XMBRTOWC(&c, p, stop - p, &m->mbs, BADCHAR); + + /* is there an EOL and/or BOL between lastc and c? */ + flagch = '\0'; + i = 0; + if ( (lastc == '\n' && m->g->cflags®_NEWLINE) || + (lastc == OUT && !(m->eflags®_NOTBOL)) ) { + flagch = BOL; + i = m->g->nbol; + } + if ( (c == '\n' && m->g->cflags®_NEWLINE) || + (c == OUT && !(m->eflags®_NOTEOL)) ) { + flagch = (flagch == BOL) ? BOLEOL : EOL; + i += m->g->neol; + } + if (i != 0) { + for (; i > 0; i--) + st = step(m->g, startst, stopst, st, flagch, st); + SP("sboleol", st, c); + } + + /* how about a word boundary? */ + if ( (flagch == BOL || (lastc != OUT && !ISWORD(lastc))) && + (c != OUT && ISWORD(c)) ) { + flagch = BOW; + } + if ( (lastc != OUT && ISWORD(lastc)) && + (flagch == EOL || (c != OUT && !ISWORD(c))) ) { + flagch = EOW; + } + if (flagch == BOW || flagch == EOW) { + st = step(m->g, startst, stopst, st, flagch, st); + SP("sboweow", st, c); + } + + /* are we done? */ + if (ISSET(st, stopst)) + matchp = p; + if (EQ(st, empty) || p == stop) + break; /* NOTE BREAK OUT */ + + /* no, we must deal with this character */ + ASSIGN(tmp, st); + ASSIGN(st, empty); + assert(c != OUT); + st = step(m->g, startst, stopst, tmp, c, st); + SP("saft", st, c); + assert(EQ(step(m->g, startst, stopst, st, NOTHING, st), st)); + p += clen; + } + + return(matchp); +} + + +/* + - step - map set of states reachable before char to set reachable after + == static states step(struct re_guts *g, sopno start, sopno stop, \ + == states bef, int ch, states aft); + == #define BOL (OUT-1) + == #define EOL (BOL-1) + == #define BOLEOL (BOL-2) + == #define NOTHING (BOL-3) + == #define BOW (BOL-4) + == #define EOW (BOL-5) + == #define BADCHAR (BOL-6) + == #define NONCHAR(c) ((c) <= OUT) + */ +static states +step(g, start, stop, bef, ch, aft) +struct re_guts *g; +sopno start; /* start state within strip */ +sopno stop; /* state after stop state within strip */ +states bef; /* states reachable before */ +wint_t ch; /* character or NONCHAR code */ +states aft; /* states already known reachable after */ +{ + cset *cs; + sop s; + sopno pc; + onestate here; /* note, macros know this name */ + sopno look; + int i; + + for (pc = start, INIT(here, pc); pc != stop; pc++, INC(here)) { + s = g->strip[pc]; + switch (OP(s)) { + case OEND: + assert(pc == stop-1); + break; + case OCHAR: + /* only characters can match */ + assert(!NONCHAR(ch) || ch != OPND(s)); + if (ch == OPND(s)) + FWD(aft, bef, 1); + break; + case OBOL: + if (ch == BOL || ch == BOLEOL) + FWD(aft, bef, 1); + break; + case OEOL: + if (ch == EOL || ch == BOLEOL) + FWD(aft, bef, 1); + break; + case OBOW: + if (ch == BOW) + FWD(aft, bef, 1); + break; + case OEOW: + if (ch == EOW) + FWD(aft, bef, 1); + break; + case OANY: + if (!NONCHAR(ch)) + FWD(aft, bef, 1); + break; + case OANYOF: + cs = &g->sets[OPND(s)]; + if (!NONCHAR(ch) && CHIN(cs, ch)) + FWD(aft, bef, 1); + break; + case OBACK_: /* ignored here */ + case O_BACK: + FWD(aft, aft, 1); + break; + case OPLUS_: /* forward, this is just an empty */ + FWD(aft, aft, 1); + break; + case O_PLUS: /* both forward and back */ + FWD(aft, aft, 1); + i = ISSETBACK(aft, OPND(s)); + BACK(aft, aft, OPND(s)); + if (!i && ISSETBACK(aft, OPND(s))) { + /* oho, must reconsider loop body */ + pc -= OPND(s) + 1; + INIT(here, pc); + } + break; + case OQUEST_: /* two branches, both forward */ + FWD(aft, aft, 1); + FWD(aft, aft, OPND(s)); + break; + case O_QUEST: /* just an empty */ + FWD(aft, aft, 1); + break; + case OLPAREN: /* not significant here */ + case ORPAREN: + FWD(aft, aft, 1); + break; + case OCH_: /* mark the first two branches */ + FWD(aft, aft, 1); + assert(OP(g->strip[pc+OPND(s)]) == OOR2); + FWD(aft, aft, OPND(s)); + break; + case OOR1: /* done a branch, find the O_CH */ + if (ISSTATEIN(aft, here)) { + for (look = 1; + OP(s = g->strip[pc+look]) != O_CH; + look += OPND(s)) + assert(OP(s) == OOR2); + FWD(aft, aft, look); + } + break; + case OOR2: /* propagate OCH_'s marking */ + FWD(aft, aft, 1); + if (OP(g->strip[pc+OPND(s)]) != O_CH) { + assert(OP(g->strip[pc+OPND(s)]) == OOR2); + FWD(aft, aft, OPND(s)); + } + break; + case O_CH: /* just empty */ + FWD(aft, aft, 1); + break; + default: /* ooooops... */ + assert(nope); + break; + } + } + + return(aft); +} + +#ifdef REDEBUG +/* + - print - print a set of states + == #ifdef REDEBUG + == static void print(struct match *m, char *caption, states st, \ + == int ch, FILE *d); + == #endif + */ +static void +print(m, caption, st, ch, d) +struct match *m; +char *caption; +states st; +int ch; +FILE *d; +{ + struct re_guts *g = m->g; + int i; + int first = 1; + + if (!(m->eflags®_TRACE)) + return; + + fprintf(d, "%s", caption); + if (ch != '\0') + fprintf(d, " %s", pchar(ch)); + for (i = 0; i < g->nstates; i++) + if (ISSET(st, i)) { + fprintf(d, "%s%d", (first) ? "\t" : ", ", i); + first = 0; + } + fprintf(d, "\n"); +} + +/* + - at - print current situation + == #ifdef REDEBUG + == static void at(struct match *m, char *title, char *start, char *stop, \ + == sopno startst, sopno stopst); + == #endif + */ +static void +at(m, title, start, stop, startst, stopst) +struct match *m; +char *title; +char *start; +char *stop; +sopno startst; +sopno stopst; +{ + if (!(m->eflags®_TRACE)) + return; + + printf("%s %s-", title, pchar(*start)); + printf("%s ", pchar(*stop)); + printf("%ld-%ld\n", (long)startst, (long)stopst); +} + +#ifndef PCHARDONE +#define PCHARDONE /* never again */ +/* + - pchar - make a character printable + == #ifdef REDEBUG + == static char *pchar(int ch); + == #endif + * + * Is this identical to regchar() over in debug.c? Well, yes. But a + * duplicate here avoids having a debugging-capable regexec.o tied to + * a matching debug.o, and this is convenient. It all disappears in + * the non-debug compilation anyway, so it doesn't matter much. + */ +static char * /* -> representation */ +pchar(ch) +int ch; +{ + static char pbuf[10]; + + if (isprint((uch)ch) || ch == ' ') + sprintf(pbuf, "%c", ch); + else + sprintf(pbuf, "\\%o", ch); + return(pbuf); +} +#endif +#endif + +#undef matcher +#undef fast +#undef slow +#undef dissect +#undef backref +#undef step +#undef print +#undef at +#undef match diff --git a/lib/libc/regex/regcomp.c b/lib/libc/regex/regcomp.c new file mode 100644 index 0000000..268a579 --- /dev/null +++ b/lib/libc/regex/regcomp.c @@ -0,0 +1,1844 @@ +/*- + * Copyright (c) 1992, 1993, 1994 Henry Spencer. + * Copyright (c) 1992, 1993, 1994 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * Henry Spencer. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * @(#)regcomp.c 8.5 (Berkeley) 3/20/94 + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)regcomp.c 8.5 (Berkeley) 3/20/94"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/regex/regcomp.c,v 1.34 2004/10/03 15:42:59 stefanf Exp $"); + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "collate.h" + +#include "utils.h" +#include "regex2.h" + +#include "cname.h" + +/* + * parse structure, passed up and down to avoid global variables and + * other clumsinesses + */ +struct parse { + char *next; /* next character in RE */ + char *end; /* end of string (-> NUL normally) */ + int error; /* has an error been seen? */ + sop *strip; /* malloced strip */ + sopno ssize; /* malloced strip size (allocated) */ + sopno slen; /* malloced strip length (used) */ + int ncsalloc; /* number of csets allocated */ + struct re_guts *g; +# define NPAREN 10 /* we need to remember () 1-9 for back refs */ + sopno pbegin[NPAREN]; /* -> ( ([0] unused) */ + sopno pend[NPAREN]; /* -> ) ([0] unused) */ +}; + +/* ========= begin header generated by ./mkh ========= */ +#ifdef __cplusplus +extern "C" { +#endif + +/* === regcomp.c === */ +static void p_ere(struct parse *p, wint_t stop); +static void p_ere_exp(struct parse *p); +static void p_str(struct parse *p); +static void p_bre(struct parse *p, wint_t end1, wint_t end2); +static int p_simp_re(struct parse *p, int starordinary); +static int p_count(struct parse *p); +static void p_bracket(struct parse *p); +static void p_b_term(struct parse *p, cset *cs); +static void p_b_cclass(struct parse *p, cset *cs); +static void p_b_eclass(struct parse *p, cset *cs); +static wint_t p_b_symbol(struct parse *p); +static wint_t p_b_coll_elem(struct parse *p, wint_t endc); +static wint_t othercase(wint_t ch); +static void bothcases(struct parse *p, wint_t ch); +static void ordinary(struct parse *p, wint_t ch); +static void nonnewline(struct parse *p); +static void repeat(struct parse *p, sopno start, int from, int to); +static int seterr(struct parse *p, int e); +static cset *allocset(struct parse *p); +static void freeset(struct parse *p, cset *cs); +static void CHadd(struct parse *p, cset *cs, wint_t ch); +static void CHaddrange(struct parse *p, cset *cs, wint_t min, wint_t max); +static void CHaddtype(struct parse *p, cset *cs, wctype_t wct); +static wint_t singleton(cset *cs); +static sopno dupl(struct parse *p, sopno start, sopno finish); +static void doemit(struct parse *p, sop op, size_t opnd); +static void doinsert(struct parse *p, sop op, size_t opnd, sopno pos); +static void dofwd(struct parse *p, sopno pos, sop value); +static void enlarge(struct parse *p, sopno size); +static void stripsnug(struct parse *p, struct re_guts *g); +static void findmust(struct parse *p, struct re_guts *g); +static int altoffset(sop *scan, int offset); +static void computejumps(struct parse *p, struct re_guts *g); +static void computematchjumps(struct parse *p, struct re_guts *g); +static sopno pluscount(struct parse *p, struct re_guts *g); +static wint_t wgetnext(struct parse *p); + +#ifdef __cplusplus +} +#endif +/* ========= end header generated by ./mkh ========= */ + +static char nuls[10]; /* place to point scanner in event of error */ + +/* + * macros for use with parse structure + * BEWARE: these know that the parse structure is named `p' !!! + */ +#define PEEK() (*p->next) +#define PEEK2() (*(p->next+1)) +#define MORE() (p->next < p->end) +#define MORE2() (p->next+1 < p->end) +#define SEE(c) (MORE() && PEEK() == (c)) +#define SEETWO(a, b) (MORE() && MORE2() && PEEK() == (a) && PEEK2() == (b)) +#define EAT(c) ((SEE(c)) ? (NEXT(), 1) : 0) +#define EATTWO(a, b) ((SEETWO(a, b)) ? (NEXT2(), 1) : 0) +#define NEXT() (p->next++) +#define NEXT2() (p->next += 2) +#define NEXTn(n) (p->next += (n)) +#define GETNEXT() (*p->next++) +#define WGETNEXT() wgetnext(p) +#define SETERROR(e) seterr(p, (e)) +#define REQUIRE(co, e) ((co) || SETERROR(e)) +#define MUSTSEE(c, e) (REQUIRE(MORE() && PEEK() == (c), e)) +#define MUSTEAT(c, e) (REQUIRE(MORE() && GETNEXT() == (c), e)) +#define MUSTNOTSEE(c, e) (REQUIRE(!MORE() || PEEK() != (c), e)) +#define EMIT(op, sopnd) doemit(p, (sop)(op), (size_t)(sopnd)) +#define INSERT(op, pos) doinsert(p, (sop)(op), HERE()-(pos)+1, pos) +#define AHEAD(pos) dofwd(p, pos, HERE()-(pos)) +#define ASTERN(sop, pos) EMIT(sop, HERE()-pos) +#define HERE() (p->slen) +#define THERE() (p->slen - 1) +#define THERETHERE() (p->slen - 2) +#define DROP(n) (p->slen -= (n)) + +#ifndef NDEBUG +static int never = 0; /* for use in asserts; shuts lint up */ +#else +#define never 0 /* some s have bugs too */ +#endif + +/* Macro used by computejump()/computematchjump() */ +#define MIN(a,b) ((a)<(b)?(a):(b)) + +/* + - regcomp - interface for parser and compilation + = extern int regcomp(regex_t *, const char *, int); + = #define REG_BASIC 0000 + = #define REG_EXTENDED 0001 + = #define REG_ICASE 0002 + = #define REG_NOSUB 0004 + = #define REG_NEWLINE 0010 + = #define REG_NOSPEC 0020 + = #define REG_PEND 0040 + = #define REG_DUMP 0200 + */ +int /* 0 success, otherwise REG_something */ +regcomp(preg, pattern, cflags) +regex_t * __restrict preg; +const char * __restrict pattern; +int cflags; +{ + struct parse pa; + struct re_guts *g; + struct parse *p = &pa; + int i; + size_t len; +#ifdef REDEBUG +# define GOODFLAGS(f) (f) +#else +# define GOODFLAGS(f) ((f)&~REG_DUMP) +#endif + + cflags = GOODFLAGS(cflags); + if ((cflags®_EXTENDED) && (cflags®_NOSPEC)) + return(REG_INVARG); + + if (cflags®_PEND) { + if (preg->re_endp < pattern) + return(REG_INVARG); + len = preg->re_endp - pattern; + } else + len = strlen((char *)pattern); + + /* do the mallocs early so failure handling is easy */ + g = (struct re_guts *)malloc(sizeof(struct re_guts)); + if (g == NULL) + return(REG_ESPACE); + p->ssize = len/(size_t)2*(size_t)3 + (size_t)1; /* ugh */ + p->strip = (sop *)malloc(p->ssize * sizeof(sop)); + p->slen = 0; + if (p->strip == NULL) { + free((char *)g); + return(REG_ESPACE); + } + + /* set things up */ + p->g = g; + p->next = (char *)pattern; /* convenience; we do not modify it */ + p->end = p->next + len; + p->error = 0; + p->ncsalloc = 0; + for (i = 0; i < NPAREN; i++) { + p->pbegin[i] = 0; + p->pend[i] = 0; + } + g->sets = NULL; + g->ncsets = 0; + g->cflags = cflags; + g->iflags = 0; + g->nbol = 0; + g->neol = 0; + g->must = NULL; + g->moffset = -1; + g->charjump = NULL; + g->matchjump = NULL; + g->mlen = 0; + g->nsub = 0; + g->backrefs = 0; + + /* do it */ + EMIT(OEND, 0); + g->firststate = THERE(); + if (cflags®_EXTENDED) + p_ere(p, OUT); + else if (cflags®_NOSPEC) + p_str(p); + else + p_bre(p, OUT, OUT); + EMIT(OEND, 0); + g->laststate = THERE(); + + /* tidy up loose ends and fill things in */ + stripsnug(p, g); + findmust(p, g); + /* only use Boyer-Moore algorithm if the pattern is bigger + * than three characters + */ + if(g->mlen > 3) { + computejumps(p, g); + computematchjumps(p, g); + if(g->matchjump == NULL && g->charjump != NULL) { + free(g->charjump); + g->charjump = NULL; + } + } + g->nplus = pluscount(p, g); + g->magic = MAGIC2; + preg->re_nsub = g->nsub; + preg->re_g = g; + preg->re_magic = MAGIC1; +#ifndef REDEBUG + /* not debugging, so can't rely on the assert() in regexec() */ + if (g->iflags&BAD) + SETERROR(REG_ASSERT); +#endif + + /* win or lose, we're done */ + if (p->error != 0) /* lose */ + regfree(preg); + return(p->error); +} + +/* + - p_ere - ERE parser top level, concatenation and alternation + == static void p_ere(struct parse *p, int stop); + */ +static void +p_ere(p, stop) +struct parse *p; +int stop; /* character this ERE should end at */ +{ + char c; + sopno prevback; + sopno prevfwd; + sopno conc; + int first = 1; /* is this the first alternative? */ + + for (;;) { + /* do a bunch of concatenated expressions */ + conc = HERE(); + while (MORE() && (c = PEEK()) != '|' && c != stop) + p_ere_exp(p); + (void)REQUIRE(HERE() != conc, REG_EMPTY); /* require nonempty */ + + if (!EAT('|')) + break; /* NOTE BREAK OUT */ + + if (first) { + INSERT(OCH_, conc); /* offset is wrong */ + prevfwd = conc; + prevback = conc; + first = 0; + } + ASTERN(OOR1, prevback); + prevback = THERE(); + AHEAD(prevfwd); /* fix previous offset */ + prevfwd = HERE(); + EMIT(OOR2, 0); /* offset is very wrong */ + } + + if (!first) { /* tail-end fixups */ + AHEAD(prevfwd); + ASTERN(O_CH, prevback); + } + + assert(!MORE() || SEE(stop)); +} + +/* + - p_ere_exp - parse one subERE, an atom possibly followed by a repetition op + == static void p_ere_exp(struct parse *p); + */ +static void +p_ere_exp(p) +struct parse *p; +{ + char c; + wint_t wc; + sopno pos; + int count; + int count2; + sopno subno; + int wascaret = 0; + + assert(MORE()); /* caller should have ensured this */ + c = GETNEXT(); + + pos = HERE(); + switch (c) { + case '(': + (void)REQUIRE(MORE(), REG_EPAREN); + p->g->nsub++; + subno = p->g->nsub; + if (subno < NPAREN) + p->pbegin[subno] = HERE(); + EMIT(OLPAREN, subno); + if (!SEE(')')) + p_ere(p, ')'); + if (subno < NPAREN) { + p->pend[subno] = HERE(); + assert(p->pend[subno] != 0); + } + EMIT(ORPAREN, subno); + (void)MUSTEAT(')', REG_EPAREN); + break; +#ifndef POSIX_MISTAKE + case ')': /* happens only if no current unmatched ( */ + /* + * You may ask, why the ifndef? Because I didn't notice + * this until slightly too late for 1003.2, and none of the + * other 1003.2 regular-expression reviewers noticed it at + * all. So an unmatched ) is legal POSIX, at least until + * we can get it fixed. + */ + SETERROR(REG_EPAREN); + break; +#endif + case '^': + EMIT(OBOL, 0); + p->g->iflags |= USEBOL; + p->g->nbol++; + wascaret = 1; + break; + case '$': + EMIT(OEOL, 0); + p->g->iflags |= USEEOL; + p->g->neol++; + break; + case '|': + SETERROR(REG_EMPTY); + break; + case '*': + case '+': + case '?': + SETERROR(REG_BADRPT); + break; + case '.': + if (p->g->cflags®_NEWLINE) + nonnewline(p); + else + EMIT(OANY, 0); + break; + case '[': + p_bracket(p); + break; + case '\\': + (void)REQUIRE(MORE(), REG_EESCAPE); + wc = WGETNEXT(); + ordinary(p, wc); + break; + case '{': /* okay as ordinary except if digit follows */ + (void)REQUIRE(!MORE() || !isdigit((uch)PEEK()), REG_BADRPT); + /* FALLTHROUGH */ + default: + p->next--; + wc = WGETNEXT(); + ordinary(p, wc); + break; + } + + if (!MORE()) + return; + c = PEEK(); + /* we call { a repetition if followed by a digit */ + if (!( c == '*' || c == '+' || c == '?' || + (c == '{' && MORE2() && isdigit((uch)PEEK2())) )) + return; /* no repetition, we're done */ + NEXT(); + + (void)REQUIRE(!wascaret, REG_BADRPT); + switch (c) { + case '*': /* implemented as +? */ + /* this case does not require the (y|) trick, noKLUDGE */ + INSERT(OPLUS_, pos); + ASTERN(O_PLUS, pos); + INSERT(OQUEST_, pos); + ASTERN(O_QUEST, pos); + break; + case '+': + INSERT(OPLUS_, pos); + ASTERN(O_PLUS, pos); + break; + case '?': + /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */ + INSERT(OCH_, pos); /* offset slightly wrong */ + ASTERN(OOR1, pos); /* this one's right */ + AHEAD(pos); /* fix the OCH_ */ + EMIT(OOR2, 0); /* offset very wrong... */ + AHEAD(THERE()); /* ...so fix it */ + ASTERN(O_CH, THERETHERE()); + break; + case '{': + count = p_count(p); + if (EAT(',')) { + if (isdigit((uch)PEEK())) { + count2 = p_count(p); + (void)REQUIRE(count <= count2, REG_BADBR); + } else /* single number with comma */ + count2 = INFINITY; + } else /* just a single number */ + count2 = count; + repeat(p, pos, count, count2); + if (!EAT('}')) { /* error heuristics */ + while (MORE() && PEEK() != '}') + NEXT(); + (void)REQUIRE(MORE(), REG_EBRACE); + SETERROR(REG_BADBR); + } + break; + } + + if (!MORE()) + return; + c = PEEK(); + if (!( c == '*' || c == '+' || c == '?' || + (c == '{' && MORE2() && isdigit((uch)PEEK2())) ) ) + return; + SETERROR(REG_BADRPT); +} + +/* + - p_str - string (no metacharacters) "parser" + == static void p_str(struct parse *p); + */ +static void +p_str(p) +struct parse *p; +{ + (void)REQUIRE(MORE(), REG_EMPTY); + while (MORE()) + ordinary(p, WGETNEXT()); +} + +/* + - p_bre - BRE parser top level, anchoring and concatenation + == static void p_bre(struct parse *p, int end1, \ + == int end2); + * Giving end1 as OUT essentially eliminates the end1/end2 check. + * + * This implementation is a bit of a kludge, in that a trailing $ is first + * taken as an ordinary character and then revised to be an anchor. + * The amount of lookahead needed to avoid this kludge is excessive. + */ +static void +p_bre(p, end1, end2) +struct parse *p; +int end1; /* first terminating character */ +int end2; /* second terminating character */ +{ + sopno start = HERE(); + int first = 1; /* first subexpression? */ + int wasdollar = 0; + + if (EAT('^')) { + EMIT(OBOL, 0); + p->g->iflags |= USEBOL; + p->g->nbol++; + } + while (MORE() && !SEETWO(end1, end2)) { + wasdollar = p_simp_re(p, first); + first = 0; + } + if (wasdollar) { /* oops, that was a trailing anchor */ + DROP(1); + EMIT(OEOL, 0); + p->g->iflags |= USEEOL; + p->g->neol++; + } + + (void)REQUIRE(HERE() != start, REG_EMPTY); /* require nonempty */ +} + +/* + - p_simp_re - parse a simple RE, an atom possibly followed by a repetition + == static int p_simp_re(struct parse *p, int starordinary); + */ +static int /* was the simple RE an unbackslashed $? */ +p_simp_re(p, starordinary) +struct parse *p; +int starordinary; /* is a leading * an ordinary character? */ +{ + int c; + int count; + int count2; + sopno pos; + int i; + wint_t wc; + sopno subno; +# define BACKSL (1<g->cflags®_NEWLINE) + nonnewline(p); + else + EMIT(OANY, 0); + break; + case '[': + p_bracket(p); + break; + case BACKSL|'{': + SETERROR(REG_BADRPT); + break; + case BACKSL|'(': + p->g->nsub++; + subno = p->g->nsub; + if (subno < NPAREN) + p->pbegin[subno] = HERE(); + EMIT(OLPAREN, subno); + /* the MORE here is an error heuristic */ + if (MORE() && !SEETWO('\\', ')')) + p_bre(p, '\\', ')'); + if (subno < NPAREN) { + p->pend[subno] = HERE(); + assert(p->pend[subno] != 0); + } + EMIT(ORPAREN, subno); + (void)REQUIRE(EATTWO('\\', ')'), REG_EPAREN); + break; + case BACKSL|')': /* should not get here -- must be user */ + case BACKSL|'}': + SETERROR(REG_EPAREN); + break; + case BACKSL|'1': + case BACKSL|'2': + case BACKSL|'3': + case BACKSL|'4': + case BACKSL|'5': + case BACKSL|'6': + case BACKSL|'7': + case BACKSL|'8': + case BACKSL|'9': + i = (c&~BACKSL) - '0'; + assert(i < NPAREN); + if (p->pend[i] != 0) { + assert(i <= p->g->nsub); + EMIT(OBACK_, i); + assert(p->pbegin[i] != 0); + assert(OP(p->strip[p->pbegin[i]]) == OLPAREN); + assert(OP(p->strip[p->pend[i]]) == ORPAREN); + (void) dupl(p, p->pbegin[i]+1, p->pend[i]); + EMIT(O_BACK, i); + } else + SETERROR(REG_ESUBREG); + p->g->backrefs = 1; + break; + case '*': + (void)REQUIRE(starordinary, REG_BADRPT); + /* FALLTHROUGH */ + default: + p->next--; + wc = WGETNEXT(); + ordinary(p, wc); + break; + } + + if (EAT('*')) { /* implemented as +? */ + /* this case does not require the (y|) trick, noKLUDGE */ + INSERT(OPLUS_, pos); + ASTERN(O_PLUS, pos); + INSERT(OQUEST_, pos); + ASTERN(O_QUEST, pos); + } else if (EATTWO('\\', '{')) { + count = p_count(p); + if (EAT(',')) { + if (MORE() && isdigit((uch)PEEK())) { + count2 = p_count(p); + (void)REQUIRE(count <= count2, REG_BADBR); + } else /* single number with comma */ + count2 = INFINITY; + } else /* just a single number */ + count2 = count; + repeat(p, pos, count, count2); + if (!EATTWO('\\', '}')) { /* error heuristics */ + while (MORE() && !SEETWO('\\', '}')) + NEXT(); + (void)REQUIRE(MORE(), REG_EBRACE); + SETERROR(REG_BADBR); + } + } else if (c == '$') /* $ (but not \$) ends it */ + return(1); + + return(0); +} + +/* + - p_count - parse a repetition count + == static int p_count(struct parse *p); + */ +static int /* the value */ +p_count(p) +struct parse *p; +{ + int count = 0; + int ndigits = 0; + + while (MORE() && isdigit((uch)PEEK()) && count <= DUPMAX) { + count = count*10 + (GETNEXT() - '0'); + ndigits++; + } + + (void)REQUIRE(ndigits > 0 && count <= DUPMAX, REG_BADBR); + return(count); +} + +/* + - p_bracket - parse a bracketed character list + == static void p_bracket(struct parse *p); + */ +static void +p_bracket(p) +struct parse *p; +{ + cset *cs; + wint_t ch; + + /* Dept of Truly Sickening Special-Case Kludges */ + if (p->next + 5 < p->end && strncmp(p->next, "[:<:]]", 6) == 0) { + EMIT(OBOW, 0); + NEXTn(6); + return; + } + if (p->next + 5 < p->end && strncmp(p->next, "[:>:]]", 6) == 0) { + EMIT(OEOW, 0); + NEXTn(6); + return; + } + + if ((cs = allocset(p)) == NULL) + return; + + if (p->g->cflags®_ICASE) + cs->icase = 1; + if (EAT('^')) + cs->invert = 1; + if (EAT(']')) + CHadd(p, cs, ']'); + else if (EAT('-')) + CHadd(p, cs, '-'); + while (MORE() && PEEK() != ']' && !SEETWO('-', ']')) + p_b_term(p, cs); + if (EAT('-')) + CHadd(p, cs, '-'); + (void)MUSTEAT(']', REG_EBRACK); + + if (p->error != 0) /* don't mess things up further */ + return; + + if (cs->invert && p->g->cflags®_NEWLINE) + cs->bmp['\n' >> 3] |= 1 << ('\n' & 7); + + if ((ch = singleton(cs)) != OUT) { /* optimize singleton sets */ + ordinary(p, ch); + freeset(p, cs); + } else + EMIT(OANYOF, (int)(cs - p->g->sets)); +} + +/* + - p_b_term - parse one term of a bracketed character list + == static void p_b_term(struct parse *p, cset *cs); + */ +static void +p_b_term(p, cs) +struct parse *p; +cset *cs; +{ + char c; + wint_t start, finish; + wint_t i; + + /* classify what we've got */ + switch ((MORE()) ? PEEK() : '\0') { + case '[': + c = (MORE2()) ? PEEK2() : '\0'; + break; + case '-': + SETERROR(REG_ERANGE); + return; /* NOTE RETURN */ + break; + default: + c = '\0'; + break; + } + + switch (c) { + case ':': /* character class */ + NEXT2(); + (void)REQUIRE(MORE(), REG_EBRACK); + c = PEEK(); + (void)REQUIRE(c != '-' && c != ']', REG_ECTYPE); + p_b_cclass(p, cs); + (void)REQUIRE(MORE(), REG_EBRACK); + (void)REQUIRE(EATTWO(':', ']'), REG_ECTYPE); + break; + case '=': /* equivalence class */ + NEXT2(); + (void)REQUIRE(MORE(), REG_EBRACK); + c = PEEK(); + (void)REQUIRE(c != '-' && c != ']', REG_ECOLLATE); + p_b_eclass(p, cs); + (void)REQUIRE(MORE(), REG_EBRACK); + (void)REQUIRE(EATTWO('=', ']'), REG_ECOLLATE); + break; + default: /* symbol, ordinary character, or range */ + start = p_b_symbol(p); + if (SEE('-') && MORE2() && PEEK2() != ']') { + /* range */ + NEXT(); + if (EAT('-')) + finish = '-'; + else + finish = p_b_symbol(p); + } else + finish = start; + if (start == finish) + CHadd(p, cs, start); + else { + if (__collate_load_error) { + (void)REQUIRE((uch)start <= (uch)finish, REG_ERANGE); + CHaddrange(p, cs, start, finish); + } else { + (void)REQUIRE(__collate_range_cmp(start, finish) <= 0, REG_ERANGE); + for (i = 0; i <= UCHAR_MAX; i++) { + if ( __collate_range_cmp(start, i) <= 0 + && __collate_range_cmp(i, finish) <= 0 + ) + CHadd(p, cs, i); + } + } + } + break; + } +} + +/* + - p_b_cclass - parse a character-class name and deal with it + == static void p_b_cclass(struct parse *p, cset *cs); + */ +static void +p_b_cclass(p, cs) +struct parse *p; +cset *cs; +{ + char *sp = p->next; + size_t len; + wctype_t wct; + char clname[16]; + + while (MORE() && isalpha((uch)PEEK())) + NEXT(); + len = p->next - sp; + if (len >= sizeof(clname) - 1) { + SETERROR(REG_ECTYPE); + return; + } + memcpy(clname, sp, len); + clname[len] = '\0'; + if ((wct = wctype(clname)) == 0) { + SETERROR(REG_ECTYPE); + return; + } + CHaddtype(p, cs, wct); +} + +/* + - p_b_eclass - parse an equivalence-class name and deal with it + == static void p_b_eclass(struct parse *p, cset *cs); + * + * This implementation is incomplete. xxx + */ +static void +p_b_eclass(p, cs) +struct parse *p; +cset *cs; +{ + wint_t c; + + c = p_b_coll_elem(p, '='); + CHadd(p, cs, c); +} + +/* + - p_b_symbol - parse a character or [..]ed multicharacter collating symbol + == static char p_b_symbol(struct parse *p); + */ +static wint_t /* value of symbol */ +p_b_symbol(p) +struct parse *p; +{ + wint_t value; + + (void)REQUIRE(MORE(), REG_EBRACK); + if (!EATTWO('[', '.')) + return(WGETNEXT()); + + /* collating symbol */ + value = p_b_coll_elem(p, '.'); + (void)REQUIRE(EATTWO('.', ']'), REG_ECOLLATE); + return(value); +} + +/* + - p_b_coll_elem - parse a collating-element name and look it up + == static char p_b_coll_elem(struct parse *p, int endc); + */ +static wint_t /* value of collating element */ +p_b_coll_elem(p, endc) +struct parse *p; +wint_t endc; /* name ended by endc,']' */ +{ + char *sp = p->next; + struct cname *cp; + int len; + mbstate_t mbs; + wchar_t wc; + size_t clen; + + while (MORE() && !SEETWO(endc, ']')) + NEXT(); + if (!MORE()) { + SETERROR(REG_EBRACK); + return(0); + } + len = p->next - sp; + for (cp = cnames; cp->name != NULL; cp++) + if (strncmp(cp->name, sp, len) == 0 && cp->name[len] == '\0') + return(cp->code); /* known name */ + memset(&mbs, 0, sizeof(mbs)); + if ((clen = mbrtowc(&wc, sp, len, &mbs)) == len) + return (wc); /* single character */ + else if (clen == (size_t)-1 || clen == (size_t)-2) + SETERROR(REG_ILLSEQ); + else + SETERROR(REG_ECOLLATE); /* neither */ + return(0); +} + +/* + - othercase - return the case counterpart of an alphabetic + == static char othercase(int ch); + */ +static wint_t /* if no counterpart, return ch */ +othercase(ch) +wint_t ch; +{ + assert(iswalpha(ch)); + if (iswupper(ch)) + return(towlower(ch)); + else if (iswlower(ch)) + return(towupper(ch)); + else /* peculiar, but could happen */ + return(ch); +} + +/* + - bothcases - emit a dualcase version of a two-case character + == static void bothcases(struct parse *p, int ch); + * + * Boy, is this implementation ever a kludge... + */ +static void +bothcases(p, ch) +struct parse *p; +wint_t ch; +{ + char *oldnext = p->next; + char *oldend = p->end; + char bracket[3 + MB_LEN_MAX]; + size_t n; + mbstate_t mbs; + + assert(othercase(ch) != ch); /* p_bracket() would recurse */ + p->next = bracket; + memset(&mbs, 0, sizeof(mbs)); + n = wcrtomb(bracket, ch, &mbs); + assert(n != (size_t)-1); + bracket[n] = ']'; + bracket[n + 1] = '\0'; + p->end = bracket+n+1; + p_bracket(p); + assert(p->next == p->end); + p->next = oldnext; + p->end = oldend; +} + +/* + - ordinary - emit an ordinary character + == static void ordinary(struct parse *p, int ch); + */ +static void +ordinary(p, ch) +struct parse *p; +wint_t ch; +{ + cset *cs; + + if ((p->g->cflags®_ICASE) && iswalpha(ch) && othercase(ch) != ch) + bothcases(p, ch); + else if ((ch & OPDMASK) == ch) + EMIT(OCHAR, ch); + else { + /* + * Kludge: character is too big to fit into an OCHAR operand. + * Emit a singleton set. + */ + if ((cs = allocset(p)) == NULL) + return; + CHadd(p, cs, ch); + EMIT(OANYOF, (int)(cs - p->g->sets)); + } +} + +/* + - nonnewline - emit REG_NEWLINE version of OANY + == static void nonnewline(struct parse *p); + * + * Boy, is this implementation ever a kludge... + */ +static void +nonnewline(p) +struct parse *p; +{ + char *oldnext = p->next; + char *oldend = p->end; + char bracket[4]; + + p->next = bracket; + p->end = bracket+3; + bracket[0] = '^'; + bracket[1] = '\n'; + bracket[2] = ']'; + bracket[3] = '\0'; + p_bracket(p); + assert(p->next == bracket+3); + p->next = oldnext; + p->end = oldend; +} + +/* + - repeat - generate code for a bounded repetition, recursively if needed + == static void repeat(struct parse *p, sopno start, int from, int to); + */ +static void +repeat(p, start, from, to) +struct parse *p; +sopno start; /* operand from here to end of strip */ +int from; /* repeated from this number */ +int to; /* to this number of times (maybe INFINITY) */ +{ + sopno finish = HERE(); +# define N 2 +# define INF 3 +# define REP(f, t) ((f)*8 + (t)) +# define MAP(n) (((n) <= 1) ? (n) : ((n) == INFINITY) ? INF : N) + sopno copy; + + if (p->error != 0) /* head off possible runaway recursion */ + return; + + assert(from <= to); + + switch (REP(MAP(from), MAP(to))) { + case REP(0, 0): /* must be user doing this */ + DROP(finish-start); /* drop the operand */ + break; + case REP(0, 1): /* as x{1,1}? */ + case REP(0, N): /* as x{1,n}? */ + case REP(0, INF): /* as x{1,}? */ + /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */ + INSERT(OCH_, start); /* offset is wrong... */ + repeat(p, start+1, 1, to); + ASTERN(OOR1, start); + AHEAD(start); /* ... fix it */ + EMIT(OOR2, 0); + AHEAD(THERE()); + ASTERN(O_CH, THERETHERE()); + break; + case REP(1, 1): /* trivial case */ + /* done */ + break; + case REP(1, N): /* as x?x{1,n-1} */ + /* KLUDGE: emit y? as (y|) until subtle bug gets fixed */ + INSERT(OCH_, start); + ASTERN(OOR1, start); + AHEAD(start); + EMIT(OOR2, 0); /* offset very wrong... */ + AHEAD(THERE()); /* ...so fix it */ + ASTERN(O_CH, THERETHERE()); + copy = dupl(p, start+1, finish+1); + assert(copy == finish+4); + repeat(p, copy, 1, to-1); + break; + case REP(1, INF): /* as x+ */ + INSERT(OPLUS_, start); + ASTERN(O_PLUS, start); + break; + case REP(N, N): /* as xx{m-1,n-1} */ + copy = dupl(p, start, finish); + repeat(p, copy, from-1, to-1); + break; + case REP(N, INF): /* as xx{n-1,INF} */ + copy = dupl(p, start, finish); + repeat(p, copy, from-1, to); + break; + default: /* "can't happen" */ + SETERROR(REG_ASSERT); /* just in case */ + break; + } +} + +/* + - wgetnext - helper function for WGETNEXT() macro. Gets the next wide + - character from the parse struct, signals a REG_ILLSEQ error if the + - character can't be converted. Returns the number of bytes consumed. + */ +static wint_t +wgetnext(p) +struct parse *p; +{ + mbstate_t mbs; + wchar_t wc; + size_t n; + + memset(&mbs, 0, sizeof(mbs)); + n = mbrtowc(&wc, p->next, p->end - p->next, &mbs); + if (n == (size_t)-1 || n == (size_t)-2) { + SETERROR(REG_ILLSEQ); + return (0); + } + if (n == 0) + n = 1; + p->next += n; + return (wc); +} + +/* + - seterr - set an error condition + == static int seterr(struct parse *p, int e); + */ +static int /* useless but makes type checking happy */ +seterr(p, e) +struct parse *p; +int e; +{ + if (p->error == 0) /* keep earliest error condition */ + p->error = e; + p->next = nuls; /* try to bring things to a halt */ + p->end = nuls; + return(0); /* make the return value well-defined */ +} + +/* + - allocset - allocate a set of characters for [] + == static cset *allocset(struct parse *p); + */ +static cset * +allocset(p) +struct parse *p; +{ + cset *cs, *ncs; + + ncs = realloc(p->g->sets, (p->g->ncsets + 1) * sizeof(*ncs)); + if (ncs == NULL) { + SETERROR(REG_ESPACE); + return (NULL); + } + p->g->sets = ncs; + cs = &p->g->sets[p->g->ncsets++]; + memset(cs, 0, sizeof(*cs)); + + return(cs); +} + +/* + - freeset - free a now-unused set + == static void freeset(struct parse *p, cset *cs); + */ +static void +freeset(p, cs) +struct parse *p; +cset *cs; +{ + cset *top = &p->g->sets[p->g->ncsets]; + + free(cs->wides); + free(cs->ranges); + free(cs->types); + memset(cs, 0, sizeof(*cs)); + if (cs == top-1) /* recover only the easy case */ + p->g->ncsets--; +} + +/* + - singleton - Determine whether a set contains only one character, + - returning it if so, otherwise returning OUT. + */ +static wint_t +singleton(cs) +cset *cs; +{ + wint_t i, s, n; + + for (i = n = 0; i < NC; i++) + if (CHIN(cs, i)) { + n++; + s = i; + } + if (n == 1) + return (s); + if (cs->nwides == 1 && cs->nranges == 0 && cs->ntypes == 0 && + cs->icase == 0) + return (cs->wides[0]); + /* Don't bother handling the other cases. */ + return (OUT); +} + +/* + - CHadd - add character to character set. + */ +static void +CHadd(p, cs, ch) +struct parse *p; +cset *cs; +wint_t ch; +{ + wint_t nch, *newwides; + assert(ch >= 0); + if (ch < NC) + cs->bmp[ch >> 3] |= 1 << (ch & 7); + else { + newwides = realloc(cs->wides, (cs->nwides + 1) * + sizeof(*cs->wides)); + if (newwides == NULL) { + SETERROR(REG_ESPACE); + return; + } + cs->wides = newwides; + cs->wides[cs->nwides++] = ch; + } + if (cs->icase) { + if ((nch = towlower(ch)) < NC) + cs->bmp[nch >> 3] |= 1 << (nch & 7); + if ((nch = towupper(ch)) < NC) + cs->bmp[nch >> 3] |= 1 << (nch & 7); + } +} + +/* + - CHaddrange - add all characters in the range [min,max] to a character set. + */ +static void +CHaddrange(p, cs, min, max) +struct parse *p; +cset *cs; +wint_t min, max; +{ + crange *newranges; + + for (; min < NC && min <= max; min++) + CHadd(p, cs, min); + if (min >= max) + return; + newranges = realloc(cs->ranges, (cs->nranges + 1) * + sizeof(*cs->ranges)); + if (newranges == NULL) { + SETERROR(REG_ESPACE); + return; + } + cs->ranges = newranges; + cs->ranges[cs->nranges].min = min; + cs->ranges[cs->nranges].min = max; + cs->nranges++; +} + +/* + - CHaddtype - add all characters of a certain type to a character set. + */ +static void +CHaddtype(p, cs, wct) +struct parse *p; +cset *cs; +wctype_t wct; +{ + wint_t i; + wctype_t *newtypes; + + for (i = 0; i < NC; i++) + if (iswctype(i, wct)) + CHadd(p, cs, i); + newtypes = realloc(cs->types, (cs->ntypes + 1) * + sizeof(*cs->types)); + if (newtypes == NULL) { + SETERROR(REG_ESPACE); + return; + } + cs->types = newtypes; + cs->types[cs->ntypes++] = wct; +} + +/* + - dupl - emit a duplicate of a bunch of sops + == static sopno dupl(struct parse *p, sopno start, sopno finish); + */ +static sopno /* start of duplicate */ +dupl(p, start, finish) +struct parse *p; +sopno start; /* from here */ +sopno finish; /* to this less one */ +{ + sopno ret = HERE(); + sopno len = finish - start; + + assert(finish >= start); + if (len == 0) + return(ret); + enlarge(p, p->ssize + len); /* this many unexpected additions */ + assert(p->ssize >= p->slen + len); + (void) memcpy((char *)(p->strip + p->slen), + (char *)(p->strip + start), (size_t)len*sizeof(sop)); + p->slen += len; + return(ret); +} + +/* + - doemit - emit a strip operator + == static void doemit(struct parse *p, sop op, size_t opnd); + * + * It might seem better to implement this as a macro with a function as + * hard-case backup, but it's just too big and messy unless there are + * some changes to the data structures. Maybe later. + */ +static void +doemit(p, op, opnd) +struct parse *p; +sop op; +size_t opnd; +{ + /* avoid making error situations worse */ + if (p->error != 0) + return; + + /* deal with oversize operands ("can't happen", more or less) */ + assert(opnd < 1<slen >= p->ssize) + enlarge(p, (p->ssize+1) / 2 * 3); /* +50% */ + assert(p->slen < p->ssize); + + /* finally, it's all reduced to the easy case */ + p->strip[p->slen++] = SOP(op, opnd); +} + +/* + - doinsert - insert a sop into the strip + == static void doinsert(struct parse *p, sop op, size_t opnd, sopno pos); + */ +static void +doinsert(p, op, opnd, pos) +struct parse *p; +sop op; +size_t opnd; +sopno pos; +{ + sopno sn; + sop s; + int i; + + /* avoid making error situations worse */ + if (p->error != 0) + return; + + sn = HERE(); + EMIT(op, opnd); /* do checks, ensure space */ + assert(HERE() == sn+1); + s = p->strip[sn]; + + /* adjust paren pointers */ + assert(pos > 0); + for (i = 1; i < NPAREN; i++) { + if (p->pbegin[i] >= pos) { + p->pbegin[i]++; + } + if (p->pend[i] >= pos) { + p->pend[i]++; + } + } + + memmove((char *)&p->strip[pos+1], (char *)&p->strip[pos], + (HERE()-pos-1)*sizeof(sop)); + p->strip[pos] = s; +} + +/* + - dofwd - complete a forward reference + == static void dofwd(struct parse *p, sopno pos, sop value); + */ +static void +dofwd(p, pos, value) +struct parse *p; +sopno pos; +sop value; +{ + /* avoid making error situations worse */ + if (p->error != 0) + return; + + assert(value < 1<strip[pos] = OP(p->strip[pos]) | value; +} + +/* + - enlarge - enlarge the strip + == static void enlarge(struct parse *p, sopno size); + */ +static void +enlarge(p, size) +struct parse *p; +sopno size; +{ + sop *sp; + + if (p->ssize >= size) + return; + + sp = (sop *)realloc(p->strip, size*sizeof(sop)); + if (sp == NULL) { + SETERROR(REG_ESPACE); + return; + } + p->strip = sp; + p->ssize = size; +} + +/* + - stripsnug - compact the strip + == static void stripsnug(struct parse *p, struct re_guts *g); + */ +static void +stripsnug(p, g) +struct parse *p; +struct re_guts *g; +{ + g->nstates = p->slen; + g->strip = (sop *)realloc((char *)p->strip, p->slen * sizeof(sop)); + if (g->strip == NULL) { + SETERROR(REG_ESPACE); + g->strip = p->strip; + } +} + +/* + - findmust - fill in must and mlen with longest mandatory literal string + == static void findmust(struct parse *p, struct re_guts *g); + * + * This algorithm could do fancy things like analyzing the operands of | + * for common subsequences. Someday. This code is simple and finds most + * of the interesting cases. + * + * Note that must and mlen got initialized during setup. + */ +static void +findmust(p, g) +struct parse *p; +struct re_guts *g; +{ + sop *scan; + sop *start; + sop *newstart; + sopno newlen; + sop s; + char *cp; + int offset; + char buf[MB_LEN_MAX]; + size_t clen; + mbstate_t mbs; + + /* avoid making error situations worse */ + if (p->error != 0) + return; + + /* + * It's not generally safe to do a ``char'' substring search on + * multibyte character strings, but it's safe for at least + * UTF-8 (see RFC 3629). + */ + if (MB_CUR_MAX > 1 && + strcmp(_CurrentRuneLocale->__encoding, "UTF-8") != 0) + return; + + /* find the longest OCHAR sequence in strip */ + newlen = 0; + offset = 0; + g->moffset = 0; + scan = g->strip + 1; + do { + s = *scan++; + switch (OP(s)) { + case OCHAR: /* sequence member */ + if (newlen == 0) { /* new sequence */ + memset(&mbs, 0, sizeof(mbs)); + newstart = scan - 1; + } + clen = wcrtomb(buf, OPND(s), &mbs); + if (clen == (size_t)-1) + goto toohard; + newlen += clen; + break; + case OPLUS_: /* things that don't break one */ + case OLPAREN: + case ORPAREN: + break; + case OQUEST_: /* things that must be skipped */ + case OCH_: + offset = altoffset(scan, offset); + scan--; + do { + scan += OPND(s); + s = *scan; + /* assert() interferes w debug printouts */ + if (OP(s) != O_QUEST && OP(s) != O_CH && + OP(s) != OOR2) { + g->iflags |= BAD; + return; + } + } while (OP(s) != O_QUEST && OP(s) != O_CH); + /* FALLTHROUGH */ + case OBOW: /* things that break a sequence */ + case OEOW: + case OBOL: + case OEOL: + case O_QUEST: + case O_CH: + case OEND: + if (newlen > g->mlen) { /* ends one */ + start = newstart; + g->mlen = newlen; + if (offset > -1) { + g->moffset += offset; + offset = newlen; + } else + g->moffset = offset; + } else { + if (offset > -1) + offset += newlen; + } + newlen = 0; + break; + case OANY: + if (newlen > g->mlen) { /* ends one */ + start = newstart; + g->mlen = newlen; + if (offset > -1) { + g->moffset += offset; + offset = newlen; + } else + g->moffset = offset; + } else { + if (offset > -1) + offset += newlen; + } + if (offset > -1) + offset++; + newlen = 0; + break; + case OANYOF: /* may or may not invalidate offset */ + /* First, everything as OANY */ + if (newlen > g->mlen) { /* ends one */ + start = newstart; + g->mlen = newlen; + if (offset > -1) { + g->moffset += offset; + offset = newlen; + } else + g->moffset = offset; + } else { + if (offset > -1) + offset += newlen; + } + if (offset > -1) + offset++; + newlen = 0; + break; + toohard: + default: + /* Anything here makes it impossible or too hard + * to calculate the offset -- so we give up; + * save the last known good offset, in case the + * must sequence doesn't occur later. + */ + if (newlen > g->mlen) { /* ends one */ + start = newstart; + g->mlen = newlen; + if (offset > -1) + g->moffset += offset; + else + g->moffset = offset; + } + offset = -1; + newlen = 0; + break; + } + } while (OP(s) != OEND); + + if (g->mlen == 0) { /* there isn't one */ + g->moffset = -1; + return; + } + + /* turn it into a character string */ + g->must = malloc((size_t)g->mlen + 1); + if (g->must == NULL) { /* argh; just forget it */ + g->mlen = 0; + g->moffset = -1; + return; + } + cp = g->must; + scan = start; + memset(&mbs, 0, sizeof(mbs)); + while (cp < g->must + g->mlen) { + while (OP(s = *scan++) != OCHAR) + continue; + clen = wcrtomb(cp, OPND(s), &mbs); + assert(clen != (size_t)-1); + cp += clen; + } + assert(cp == g->must + g->mlen); + *cp++ = '\0'; /* just on general principles */ +} + +/* + - altoffset - choose biggest offset among multiple choices + == static int altoffset(sop *scan, int offset); + * + * Compute, recursively if necessary, the largest offset among multiple + * re paths. + */ +static int +altoffset(scan, offset) +sop *scan; +int offset; +{ + int largest; + int try; + sop s; + + /* If we gave up already on offsets, return */ + if (offset == -1) + return -1; + + largest = 0; + try = 0; + s = *scan++; + while (OP(s) != O_QUEST && OP(s) != O_CH) { + switch (OP(s)) { + case OOR1: + if (try > largest) + largest = try; + try = 0; + break; + case OQUEST_: + case OCH_: + try = altoffset(scan, try); + if (try == -1) + return -1; + scan--; + do { + scan += OPND(s); + s = *scan; + if (OP(s) != O_QUEST && OP(s) != O_CH && + OP(s) != OOR2) + return -1; + } while (OP(s) != O_QUEST && OP(s) != O_CH); + /* We must skip to the next position, or we'll + * leave altoffset() too early. + */ + scan++; + break; + case OANYOF: + case OCHAR: + case OANY: + try++; + case OBOW: + case OEOW: + case OLPAREN: + case ORPAREN: + case OOR2: + break; + default: + try = -1; + break; + } + if (try == -1) + return -1; + s = *scan++; + } + + if (try > largest) + largest = try; + + return largest+offset; +} + +/* + - computejumps - compute char jumps for BM scan + == static void computejumps(struct parse *p, struct re_guts *g); + * + * This algorithm assumes g->must exists and is has size greater than + * zero. It's based on the algorithm found on Computer Algorithms by + * Sara Baase. + * + * A char jump is the number of characters one needs to jump based on + * the value of the character from the text that was mismatched. + */ +static void +computejumps(p, g) +struct parse *p; +struct re_guts *g; +{ + int ch; + int mindex; + + /* Avoid making errors worse */ + if (p->error != 0) + return; + + g->charjump = (int*) malloc((NC + 1) * sizeof(int)); + if (g->charjump == NULL) /* Not a fatal error */ + return; + /* Adjust for signed chars, if necessary */ + g->charjump = &g->charjump[-(CHAR_MIN)]; + + /* If the character does not exist in the pattern, the jump + * is equal to the number of characters in the pattern. + */ + for (ch = CHAR_MIN; ch < (CHAR_MAX + 1); ch++) + g->charjump[ch] = g->mlen; + + /* If the character does exist, compute the jump that would + * take us to the last character in the pattern equal to it + * (notice that we match right to left, so that last character + * is the first one that would be matched). + */ + for (mindex = 0; mindex < g->mlen; mindex++) + g->charjump[(int)g->must[mindex]] = g->mlen - mindex - 1; +} + +/* + - computematchjumps - compute match jumps for BM scan + == static void computematchjumps(struct parse *p, struct re_guts *g); + * + * This algorithm assumes g->must exists and is has size greater than + * zero. It's based on the algorithm found on Computer Algorithms by + * Sara Baase. + * + * A match jump is the number of characters one needs to advance based + * on the already-matched suffix. + * Notice that all values here are minus (g->mlen-1), because of the way + * the search algorithm works. + */ +static void +computematchjumps(p, g) +struct parse *p; +struct re_guts *g; +{ + int mindex; /* General "must" iterator */ + int suffix; /* Keeps track of matching suffix */ + int ssuffix; /* Keeps track of suffixes' suffix */ + int* pmatches; /* pmatches[k] points to the next i + * such that i+1...mlen is a substring + * of k+1...k+mlen-i-1 + */ + + /* Avoid making errors worse */ + if (p->error != 0) + return; + + pmatches = (int*) malloc(g->mlen * sizeof(unsigned int)); + if (pmatches == NULL) { + g->matchjump = NULL; + return; + } + + g->matchjump = (int*) malloc(g->mlen * sizeof(unsigned int)); + if (g->matchjump == NULL) /* Not a fatal error */ + return; + + /* Set maximum possible jump for each character in the pattern */ + for (mindex = 0; mindex < g->mlen; mindex++) + g->matchjump[mindex] = 2*g->mlen - mindex - 1; + + /* Compute pmatches[] */ + for (mindex = g->mlen - 1, suffix = g->mlen; mindex >= 0; + mindex--, suffix--) { + pmatches[mindex] = suffix; + + /* If a mismatch is found, interrupting the substring, + * compute the matchjump for that position. If no + * mismatch is found, then a text substring mismatched + * against the suffix will also mismatch against the + * substring. + */ + while (suffix < g->mlen + && g->must[mindex] != g->must[suffix]) { + g->matchjump[suffix] = MIN(g->matchjump[suffix], + g->mlen - mindex - 1); + suffix = pmatches[suffix]; + } + } + + /* Compute the matchjump up to the last substring found to jump + * to the beginning of the largest must pattern prefix matching + * it's own suffix. + */ + for (mindex = 0; mindex <= suffix; mindex++) + g->matchjump[mindex] = MIN(g->matchjump[mindex], + g->mlen + suffix - mindex); + + ssuffix = pmatches[suffix]; + while (suffix < g->mlen) { + while (suffix <= ssuffix && suffix < g->mlen) { + g->matchjump[suffix] = MIN(g->matchjump[suffix], + g->mlen + ssuffix - suffix); + suffix++; + } + if (suffix < g->mlen) + ssuffix = pmatches[ssuffix]; + } + + free(pmatches); +} + +/* + - pluscount - count + nesting + == static sopno pluscount(struct parse *p, struct re_guts *g); + */ +static sopno /* nesting depth */ +pluscount(p, g) +struct parse *p; +struct re_guts *g; +{ + sop *scan; + sop s; + sopno plusnest = 0; + sopno maxnest = 0; + + if (p->error != 0) + return(0); /* there may not be an OEND */ + + scan = g->strip + 1; + do { + s = *scan++; + switch (OP(s)) { + case OPLUS_: + plusnest++; + break; + case O_PLUS: + if (plusnest > maxnest) + maxnest = plusnest; + plusnest--; + break; + } + } while (OP(s) != OEND); + if (plusnest != 0) + g->iflags |= BAD; + return(maxnest); +} diff --git a/lib/libc/regex/regerror.c b/lib/libc/regex/regerror.c new file mode 100644 index 0000000..4e43f3d --- /dev/null +++ b/lib/libc/regex/regerror.c @@ -0,0 +1,181 @@ +/*- + * Copyright (c) 1992, 1993, 1994 Henry Spencer. + * Copyright (c) 1992, 1993, 1994 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * Henry Spencer. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * @(#)regerror.c 8.4 (Berkeley) 3/20/94 + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)regerror.c 8.4 (Berkeley) 3/20/94"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/regex/regerror.c,v 1.9 2004/07/12 06:07:26 tjr Exp $"); + +#include +#include +#include +#include +#include +#include + +#include "utils.h" + +/* ========= begin header generated by ./mkh ========= */ +#ifdef __cplusplus +extern "C" { +#endif + +/* === regerror.c === */ +static char *regatoi(const regex_t *preg, char *localbuf); + +#ifdef __cplusplus +} +#endif +/* ========= end header generated by ./mkh ========= */ +/* + = #define REG_NOMATCH 1 + = #define REG_BADPAT 2 + = #define REG_ECOLLATE 3 + = #define REG_ECTYPE 4 + = #define REG_EESCAPE 5 + = #define REG_ESUBREG 6 + = #define REG_EBRACK 7 + = #define REG_EPAREN 8 + = #define REG_EBRACE 9 + = #define REG_BADBR 10 + = #define REG_ERANGE 11 + = #define REG_ESPACE 12 + = #define REG_BADRPT 13 + = #define REG_EMPTY 14 + = #define REG_ASSERT 15 + = #define REG_INVARG 16 + = #define REG_ILLSEQ 17 + = #define REG_ATOI 255 // convert name to number (!) + = #define REG_ITOA 0400 // convert number to name (!) + */ +static struct rerr { + int code; + char *name; + char *explain; +} rerrs[] = { + {REG_NOMATCH, "REG_NOMATCH", "regexec() failed to match"}, + {REG_BADPAT, "REG_BADPAT", "invalid regular expression"}, + {REG_ECOLLATE, "REG_ECOLLATE", "invalid collating element"}, + {REG_ECTYPE, "REG_ECTYPE", "invalid character class"}, + {REG_EESCAPE, "REG_EESCAPE", "trailing backslash (\\)"}, + {REG_ESUBREG, "REG_ESUBREG", "invalid backreference number"}, + {REG_EBRACK, "REG_EBRACK", "brackets ([ ]) not balanced"}, + {REG_EPAREN, "REG_EPAREN", "parentheses not balanced"}, + {REG_EBRACE, "REG_EBRACE", "braces not balanced"}, + {REG_BADBR, "REG_BADBR", "invalid repetition count(s)"}, + {REG_ERANGE, "REG_ERANGE", "invalid character range"}, + {REG_ESPACE, "REG_ESPACE", "out of memory"}, + {REG_BADRPT, "REG_BADRPT", "repetition-operator operand invalid"}, + {REG_EMPTY, "REG_EMPTY", "empty (sub)expression"}, + {REG_ASSERT, "REG_ASSERT", "\"can't happen\" -- you found a bug"}, + {REG_INVARG, "REG_INVARG", "invalid argument to regex routine"}, + {REG_ILLSEQ, "REG_ILLSEQ", "illegal byte sequence"}, + {0, "", "*** unknown regexp error code ***"} +}; + +/* + - regerror - the interface to error numbers + = extern size_t regerror(int, const regex_t *, char *, size_t); + */ +/* ARGSUSED */ +size_t +regerror(errcode, preg, errbuf, errbuf_size) +int errcode; +const regex_t * __restrict preg; +char * __restrict errbuf; +size_t errbuf_size; +{ + struct rerr *r; + size_t len; + int target = errcode &~ REG_ITOA; + char *s; + char convbuf[50]; + + if (errcode == REG_ATOI) + s = regatoi(preg, convbuf); + else { + for (r = rerrs; r->code != 0; r++) + if (r->code == target) + break; + + if (errcode®_ITOA) { + if (r->code != 0) + (void) strcpy(convbuf, r->name); + else + sprintf(convbuf, "REG_0x%x", target); + assert(strlen(convbuf) < sizeof(convbuf)); + s = convbuf; + } else + s = r->explain; + } + + len = strlen(s) + 1; + if (errbuf_size > 0) { + if (errbuf_size > len) + (void) strcpy(errbuf, s); + else { + (void) strncpy(errbuf, s, errbuf_size-1); + errbuf[errbuf_size-1] = '\0'; + } + } + + return(len); +} + +/* + - regatoi - internal routine to implement REG_ATOI + == static char *regatoi(const regex_t *preg, char *localbuf); + */ +static char * +regatoi(preg, localbuf) +const regex_t *preg; +char *localbuf; +{ + struct rerr *r; + + for (r = rerrs; r->code != 0; r++) + if (strcmp(r->name, preg->re_endp) == 0) + break; + if (r->code == 0) + return("0"); + + sprintf(localbuf, "%d", r->code); + return(localbuf); +} diff --git a/lib/libc/regex/regex2.h b/lib/libc/regex/regex2.h new file mode 100644 index 0000000..c971c9c --- /dev/null +++ b/lib/libc/regex/regex2.h @@ -0,0 +1,200 @@ +/*- + * Copyright (c) 1992, 1993, 1994 Henry Spencer. + * Copyright (c) 1992, 1993, 1994 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * Henry Spencer. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * @(#)regex2.h 8.4 (Berkeley) 3/20/94 + * $FreeBSD: src/lib/libc/regex/regex2.h,v 1.8 2004/07/12 07:35:59 tjr Exp $ + */ + +/* + * First, the stuff that ends up in the outside-world include file + = typedef off_t regoff_t; + = typedef struct { + = int re_magic; + = size_t re_nsub; // number of parenthesized subexpressions + = const char *re_endp; // end pointer for REG_PEND + = struct re_guts *re_g; // none of your business :-) + = } regex_t; + = typedef struct { + = regoff_t rm_so; // start of match + = regoff_t rm_eo; // end of match + = } regmatch_t; + */ +/* + * internals of regex_t + */ +#define MAGIC1 ((('r'^0200)<<8) | 'e') + +/* + * The internal representation is a *strip*, a sequence of + * operators ending with an endmarker. (Some terminology etc. is a + * historical relic of earlier versions which used multiple strips.) + * Certain oddities in the representation are there to permit running + * the machinery backwards; in particular, any deviation from sequential + * flow must be marked at both its source and its destination. Some + * fine points: + * + * - OPLUS_ and O_PLUS are *inside* the loop they create. + * - OQUEST_ and O_QUEST are *outside* the bypass they create. + * - OCH_ and O_CH are *outside* the multi-way branch they create, while + * OOR1 and OOR2 are respectively the end and the beginning of one of + * the branches. Note that there is an implicit OOR2 following OCH_ + * and an implicit OOR1 preceding O_CH. + * + * In state representations, an operator's bit is on to signify a state + * immediately *preceding* "execution" of that operator. + */ +typedef unsigned long sop; /* strip operator */ +typedef long sopno; +#define OPRMASK 0xf8000000L +#define OPDMASK 0x07ffffffL +#define OPSHIFT ((unsigned)27) +#define OP(n) ((n)&OPRMASK) +#define OPND(n) ((n)&OPDMASK) +#define SOP(op, opnd) ((op)|(opnd)) +/* operators meaning operand */ +/* (back, fwd are offsets) */ +#define OEND (1L<= 0); + if (ch < NC) + return (((cs->bmp[ch >> 3] & (1 << (ch & 7))) != 0) ^ + cs->invert); + for (i = 0; i < cs->nwides; i++) + if (ch == cs->wides[i]) + return (!cs->invert); + for (i = 0; i < cs->nranges; i++) + if (cs->ranges[i].min <= ch && ch <= cs->ranges[i].max) + return (!cs->invert); + for (i = 0; i < cs->ntypes; i++) + if (iswctype(ch, cs->types[i])) + return (!cs->invert); + return (cs->invert); +} + +static __inline int +CHIN(cs, ch) +cset *cs; +wint_t ch; +{ + + assert(ch >= 0); + if (ch < NC) + return (((cs->bmp[ch >> 3] & (1 << (ch & 7))) != 0) ^ + cs->invert); + else if (cs->icase) + return (CHIN1(cs, ch) || CHIN1(cs, towlower(ch)) || + CHIN1(cs, towupper(ch))); + else + return (CHIN1(cs, ch)); +} + +/* + * main compiled-expression structure + */ +struct re_guts { + int magic; +# define MAGIC2 ((('R'^0200)<<8)|'E') + sop *strip; /* malloced area for strip */ + int ncsets; /* number of csets in use */ + cset *sets; /* -> cset [ncsets] */ + int cflags; /* copy of regcomp() cflags argument */ + sopno nstates; /* = number of sops */ + sopno firststate; /* the initial OEND (normally 0) */ + sopno laststate; /* the final OEND */ + int iflags; /* internal flags */ +# define USEBOL 01 /* used ^ */ +# define USEEOL 02 /* used $ */ +# define BAD 04 /* something wrong */ + int nbol; /* number of ^ used */ + int neol; /* number of $ used */ + char *must; /* match must contain this string */ + int moffset; /* latest point at which must may be located */ + int *charjump; /* Boyer-Moore char jump table */ + int *matchjump; /* Boyer-Moore match jump table */ + int mlen; /* length of must */ + size_t nsub; /* copy of re_nsub */ + int backrefs; /* does it use back references? */ + sopno nplus; /* how deep does it nest +s? */ +}; + +/* misc utilities */ +#define OUT (-2) /* a non-character value */ +#define ISWORD(c) (iswalnum((uch)(c)) || (c) == '_') diff --git a/lib/libc/regex/regexec.c b/lib/libc/regex/regexec.c new file mode 100644 index 0000000..c570369 --- /dev/null +++ b/lib/libc/regex/regexec.c @@ -0,0 +1,244 @@ +/*- + * Copyright (c) 1992, 1993, 1994 Henry Spencer. + * Copyright (c) 1992, 1993, 1994 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * Henry Spencer. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * @(#)regexec.c 8.3 (Berkeley) 3/20/94 + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)regexec.c 8.3 (Berkeley) 3/20/94"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/regex/regexec.c,v 1.6 2004/07/12 07:35:59 tjr Exp $"); + +/* + * the outer shell of regexec() + * + * This file includes engine.c three times, after muchos fiddling with the + * macros that code uses. This lets the same code operate on two different + * representations for state sets and characters. + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "utils.h" +#include "regex2.h" + +static int nope __unused = 0; /* for use in asserts; shuts lint up */ + +static __inline size_t +xmbrtowc(wi, s, n, mbs, dummy) +wint_t *wi; +const char *s; +size_t n; +mbstate_t *mbs; +wint_t dummy; +{ + size_t nr; + wchar_t wc; + + nr = mbrtowc(&wc, s, n, mbs); + if (wi != NULL) + *wi = wc; + if (nr == 0) + return (1); + else if (nr == (size_t)-1 || nr == (size_t)-2) { + memset(mbs, 0, sizeof(*mbs)); + if (wi != NULL) + *wi = dummy; + return (1); + } else + return (nr); +} + +static __inline size_t +xmbrtowc_dummy(wi, s, n, mbs, dummy) +wint_t *wi; +const char *s; +size_t n __unused; +mbstate_t *mbs __unused; +wint_t dummy __unused; +{ + + if (wi != NULL) + *wi = (unsigned char)*s; + return (1); +} + +/* macros for manipulating states, small version */ +#define states long +#define states1 states /* for later use in regexec() decision */ +#define CLEAR(v) ((v) = 0) +#define SET0(v, n) ((v) &= ~((unsigned long)1 << (n))) +#define SET1(v, n) ((v) |= (unsigned long)1 << (n)) +#define ISSET(v, n) (((v) & ((unsigned long)1 << (n))) != 0) +#define ASSIGN(d, s) ((d) = (s)) +#define EQ(a, b) ((a) == (b)) +#define STATEVARS long dummy /* dummy version */ +#define STATESETUP(m, n) /* nothing */ +#define STATETEARDOWN(m) /* nothing */ +#define SETUP(v) ((v) = 0) +#define onestate long +#define INIT(o, n) ((o) = (unsigned long)1 << (n)) +#define INC(o) ((o) <<= 1) +#define ISSTATEIN(v, o) (((v) & (o)) != 0) +/* some abbreviations; note that some of these know variable names! */ +/* do "if I'm here, I can also be there" etc without branches */ +#define FWD(dst, src, n) ((dst) |= ((unsigned long)(src)&(here)) << (n)) +#define BACK(dst, src, n) ((dst) |= ((unsigned long)(src)&(here)) >> (n)) +#define ISSETBACK(v, n) (((v) & ((unsigned long)here >> (n))) != 0) +/* no multibyte support */ +#define XMBRTOWC xmbrtowc_dummy +#define ZAPSTATE(mbs) ((void)(mbs)) +/* function names */ +#define SNAMES /* engine.c looks after details */ + +#include "engine.c" + +/* now undo things */ +#undef states +#undef CLEAR +#undef SET0 +#undef SET1 +#undef ISSET +#undef ASSIGN +#undef EQ +#undef STATEVARS +#undef STATESETUP +#undef STATETEARDOWN +#undef SETUP +#undef onestate +#undef INIT +#undef INC +#undef ISSTATEIN +#undef FWD +#undef BACK +#undef ISSETBACK +#undef SNAMES +#undef XMBRTOWC +#undef ZAPSTATE + +/* macros for manipulating states, large version */ +#define states char * +#define CLEAR(v) memset(v, 0, m->g->nstates) +#define SET0(v, n) ((v)[n] = 0) +#define SET1(v, n) ((v)[n] = 1) +#define ISSET(v, n) ((v)[n]) +#define ASSIGN(d, s) memcpy(d, s, m->g->nstates) +#define EQ(a, b) (memcmp(a, b, m->g->nstates) == 0) +#define STATEVARS long vn; char *space +#define STATESETUP(m, nv) { (m)->space = malloc((nv)*(m)->g->nstates); \ + if ((m)->space == NULL) return(REG_ESPACE); \ + (m)->vn = 0; } +#define STATETEARDOWN(m) { free((m)->space); } +#define SETUP(v) ((v) = &m->space[m->vn++ * m->g->nstates]) +#define onestate long +#define INIT(o, n) ((o) = (n)) +#define INC(o) ((o)++) +#define ISSTATEIN(v, o) ((v)[o]) +/* some abbreviations; note that some of these know variable names! */ +/* do "if I'm here, I can also be there" etc without branches */ +#define FWD(dst, src, n) ((dst)[here+(n)] |= (src)[here]) +#define BACK(dst, src, n) ((dst)[here-(n)] |= (src)[here]) +#define ISSETBACK(v, n) ((v)[here - (n)]) +/* no multibyte support */ +#define XMBRTOWC xmbrtowc_dummy +#define ZAPSTATE(mbs) ((void)(mbs)) +/* function names */ +#define LNAMES /* flag */ + +#include "engine.c" + +/* multibyte character & large states version */ +#undef LNAMES +#undef XMBRTOWC +#undef ZAPSTATE +#define XMBRTOWC xmbrtowc +#define ZAPSTATE(mbs) memset((mbs), 0, sizeof(*(mbs))) +#define MNAMES + +#include "engine.c" + +/* + - regexec - interface for matching + = extern int regexec(const regex_t *, const char *, size_t, \ + = regmatch_t [], int); + = #define REG_NOTBOL 00001 + = #define REG_NOTEOL 00002 + = #define REG_STARTEND 00004 + = #define REG_TRACE 00400 // tracing of execution + = #define REG_LARGE 01000 // force large representation + = #define REG_BACKR 02000 // force use of backref code + * + * We put this here so we can exploit knowledge of the state representation + * when choosing which matcher to call. Also, by this point the matchers + * have been prototyped. + */ +int /* 0 success, REG_NOMATCH failure */ +regexec(preg, string, nmatch, pmatch, eflags) +const regex_t * __restrict preg; +const char * __restrict string; +size_t nmatch; +regmatch_t pmatch[__restrict]; +int eflags; +{ + struct re_guts *g = preg->re_g; +#ifdef REDEBUG +# define GOODFLAGS(f) (f) +#else +# define GOODFLAGS(f) ((f)&(REG_NOTBOL|REG_NOTEOL|REG_STARTEND)) +#endif + + if (preg->re_magic != MAGIC1 || g->magic != MAGIC2) + return(REG_BADPAT); + assert(!(g->iflags&BAD)); + if (g->iflags&BAD) /* backstop for no-debug case */ + return(REG_BADPAT); + eflags = GOODFLAGS(eflags); + + if (MB_CUR_MAX > 1) + return(mmatcher(g, (char *)string, nmatch, pmatch, eflags)); + else if (g->nstates <= CHAR_BIT*sizeof(states1) && !(eflags®_LARGE)) + return(smatcher(g, (char *)string, nmatch, pmatch, eflags)); + else + return(lmatcher(g, (char *)string, nmatch, pmatch, eflags)); +} diff --git a/lib/libc/regex/regfree.c b/lib/libc/regex/regfree.c new file mode 100644 index 0000000..110879e --- /dev/null +++ b/lib/libc/regex/regfree.c @@ -0,0 +1,94 @@ +/*- + * Copyright (c) 1992, 1993, 1994 Henry Spencer. + * Copyright (c) 1992, 1993, 1994 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * Henry Spencer. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * @(#)regfree.c 8.3 (Berkeley) 3/20/94 + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)regfree.c 8.3 (Berkeley) 3/20/94"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/regex/regfree.c,v 1.6 2004/07/12 07:35:59 tjr Exp $"); + +#include +#include +#include +#include +#include +#include +#include + +#include "utils.h" +#include "regex2.h" + +/* + - regfree - free everything + = extern void regfree(regex_t *); + */ +void +regfree(preg) +regex_t *preg; +{ + struct re_guts *g; + int i; + + if (preg->re_magic != MAGIC1) /* oops */ + return; /* nice to complain, but hard */ + + g = preg->re_g; + if (g == NULL || g->magic != MAGIC2) /* oops again */ + return; + preg->re_magic = 0; /* mark it invalid */ + g->magic = 0; /* mark it invalid */ + + if (g->strip != NULL) + free((char *)g->strip); + if (g->sets != NULL) { + for (i = 0; i < g->ncsets; i++) { + free(g->sets[i].ranges); + free(g->sets[i].wides); + free(g->sets[i].types); + } + free((char *)g->sets); + } + if (g->must != NULL) + free(g->must); + if (g->charjump != NULL) + free(&g->charjump[CHAR_MIN]); + if (g->matchjump != NULL) + free(g->matchjump); + free((char *)g); +} diff --git a/lib/libc/regex/utils.h b/lib/libc/regex/utils.h new file mode 100644 index 0000000..5439b6c --- /dev/null +++ b/lib/libc/regex/utils.h @@ -0,0 +1,58 @@ +/*- + * Copyright (c) 1992, 1993, 1994 Henry Spencer. + * Copyright (c) 1992, 1993, 1994 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * Henry Spencer. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * @(#)utils.h 8.3 (Berkeley) 3/20/94 + * $FreeBSD: src/lib/libc/regex/utils.h,v 1.2 2002/03/22 23:41:56 obrien Exp $ + */ + +/* utility definitions */ +#define DUPMAX _POSIX2_RE_DUP_MAX /* xxx is this right? */ +#define INFINITY (DUPMAX + 1) +#define NC (CHAR_MAX - CHAR_MIN + 1) +typedef unsigned char uch; + +/* switch off assertions (if not already off) if no REDEBUG */ +#ifndef REDEBUG +#ifndef NDEBUG +#define NDEBUG /* no assertions please */ +#endif +#endif +#include + +/* for old systems with bcopy() but no memmove() */ +#ifdef USEBCOPY +#define memmove(d, s, c) bcopy(s, d, c) +#endif diff --git a/lib/libc/resolv/Makefile b/lib/libc/resolv/Makefile new file mode 100644 index 0000000..f4377a1 --- /dev/null +++ b/lib/libc/resolv/Makefile @@ -0,0 +1,35 @@ +# $Id: Makefile 89 2016-01-12 00:20:40Z reddawg $ +# The System Makefile (C) 2002 The UbixOS Project + +# Include Global 'Source' Options +include ../../../Makefile.incl +include ../../Makefile.incl +include ../Makefile.incl + +INCLUDES += -I../locale/ + +#Objects +OBJS = h_errno.o herror.o mtctxres.o res_comp.o res_data.o res_debug.o res_init.o res_mkquery.o res_query.o res_send.o res_state.o + +all: $(OBJS) + +# Compile the source files +.cc.o: + $(CXX) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -c -o $@ $< + +.cc.s: + $(CXX) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -S -o $@ $< + +.c.o: + $(CC) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -c $< + +.c.s: + $(CC) $(CFLAGS) -Wall -nostdlib -O $(INCLUDES) -S -o $@ $< + +.S.o: + $(CC) $(CFLAGS) -Wall -nostdlib -c -o $@ $< + +# Clean up the junk +clean: + $(REMOVE) $(OBJS) + diff --git a/lib/libc/resolv/h_errno.c b/lib/libc/resolv/h_errno.c new file mode 100644 index 0000000..dcd240d --- /dev/null +++ b/lib/libc/resolv/h_errno.c @@ -0,0 +1,49 @@ +/*- + * Copyright (c) 2006 The FreeBSD Project. 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 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 AUTHOR 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. + * + * $FreeBSD: src/lib/libc/resolv/h_errno.c,v 1.2.2.1 2006/07/17 10:09:58 ume Exp $ + */ + +#include +#include +#include +#include + +#undef h_errno +extern int h_errno; + +int * +__h_errno(void) +{ + return (&__res_state()->res_h_errno); +} + +void +__h_errno_set(res_state res, int err) +{ + h_errno = res->res_h_errno = err; +} + +/* binary backward compatibility for FreeBSD 5.x and 6.x */ +__weak_reference(__h_errno, __h_error); diff --git a/lib/libc/resolv/herror.c b/lib/libc/resolv/herror.c new file mode 100644 index 0000000..cdc6b92 --- /dev/null +++ b/lib/libc/resolv/herror.c @@ -0,0 +1,128 @@ +/* + * 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. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +/* + * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC") + * Portions Copyright (c) 1996-1999 by Internet Software Consortium. + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT + * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static const char sccsid[] = "@(#)herror.c 8.1 (Berkeley) 6/4/93"; +static const char rcsid[] = "$Id: herror.c 89 2016-01-12 00:20:40Z reddawg $"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/resolv/herror.c,v 1.2.2.1 2006/07/17 10:09:58 ume Exp $"); + +#include "port_before.h" + +#include "namespace.h" +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include "un-namespace.h" + +#include "port_after.h" + +const char *h_errlist[] = { + "Resolver Error 0 (no error)", + "Unknown host", /* 1 HOST_NOT_FOUND */ + "Host name lookup failure", /* 2 TRY_AGAIN */ + "Unknown server error", /* 3 NO_RECOVERY */ + "No address associated with name", /* 4 NO_ADDRESS */ +}; +const int h_nerr = { sizeof h_errlist / sizeof h_errlist[0] }; + +#undef h_errno +int h_errno; + +/* + * herror -- + * print the error indicated by the h_errno value. + */ +void +herror(const char *s) { + struct iovec iov[4], *v = iov; + char *t; + + if (s != NULL && *s != '\0') { + DE_CONST(s, t); + v->iov_base = t; + v->iov_len = strlen(t); + v++; + DE_CONST(": ", t); + v->iov_base = t; + v->iov_len = 2; + v++; + } + DE_CONST(hstrerror(*__h_errno()), t); + v->iov_base = t; + v->iov_len = strlen(v->iov_base); + v++; + DE_CONST("\n", t); + v->iov_base = t; + v->iov_len = 1; + _writev(STDERR_FILENO, iov, (v - iov) + 1); +} + +/* + * hstrerror -- + * return the string associated with a given "host" errno value. + */ +const char * +hstrerror(int err) { + if (err < 0) + return ("Resolver internal error"); + else if (err < h_nerr) + return (h_errlist[err]); + return ("Unknown resolver error"); +} diff --git a/lib/libc/resolv/mtctxres.c b/lib/libc/resolv/mtctxres.c new file mode 100644 index 0000000..ccb7ad8 --- /dev/null +++ b/lib/libc/resolv/mtctxres.c @@ -0,0 +1,140 @@ +#include +__FBSDID("$FreeBSD: src/lib/libc/resolv/mtctxres.c,v 1.2.2.1 2006/07/17 10:09:58 ume Exp $"); + +#include +#ifdef DO_PTHREADS +#include +#ifdef _LIBC +#include +#endif +#endif +#include +#include +#include +#include +#include +#include + +#ifdef DO_PTHREADS +static pthread_key_t key; +static int mt_key_initialized = 0; + +static int __res_init_ctx(void); +static void __res_destroy_ctx(void *); + +#if defined(sun) && !defined(__GNUC__) +#pragma init (_mtctxres_init) +#endif +#endif + +static mtctxres_t sharedctx; + +#ifdef DO_PTHREADS +/* + * Initialize the TSD key. By doing this at library load time, we're + * implicitly running without interference from other threads, so there's + * no need for locking. + */ +static void +_mtctxres_init(void) { + int pthread_keycreate_ret; + + pthread_keycreate_ret = pthread_key_create(&key, __res_destroy_ctx); + if (pthread_keycreate_ret == 0) + mt_key_initialized = 1; +} +#endif + +#ifndef _LIBC +/* + * To support binaries that used the private MT-safe interface in + * Solaris 8, we still need to provide the __res_enable_mt() + * and __res_disable_mt() entry points. They're do-nothing routines. + */ +int +__res_enable_mt(void) { + return (-1); +} + +int +__res_disable_mt(void) { + return (0); +} +#endif + +#ifdef DO_PTHREADS +static int +__res_init_ctx(void) { + + mtctxres_t *mt; + int ret; + + + if (pthread_getspecific(key) != 0) { + /* Already exists */ + return (0); + } + + if ((mt = malloc(sizeof (mtctxres_t))) == 0) { + errno = ENOMEM; + return (-1); + } + + memset(mt, 0, sizeof (mtctxres_t)); + + if ((ret = pthread_setspecific(key, mt)) != 0) { + free(mt); + errno = ret; + return (-1); + } + + return (0); +} + +static void +__res_destroy_ctx(void *value) { + + mtctxres_t *mt = (mtctxres_t *)value; + + if (mt != 0) + free(mt); +} +#endif + +mtctxres_t * +___mtctxres(void) { +#ifdef DO_PTHREADS + mtctxres_t *mt; + +#ifdef _LIBC + if (pthread_main_np() != 0) + return (&sharedctx); +#endif + + /* + * This if clause should only be executed if we are linking + * statically. When linked dynamically _mtctxres_init() should + * be called at binding time due the #pragma above. + */ + if (!mt_key_initialized) { + static pthread_mutex_t keylock = PTHREAD_MUTEX_INITIALIZER; + pthread_mutex_lock(&keylock); + _mtctxres_init(); + pthread_mutex_unlock(&keylock); + } + + /* + * If we have already been called in this thread return the existing + * context. Otherwise recreat a new context and return it. If + * that fails return a global context. + */ + if (mt_key_initialized) { + if (((mt = pthread_getspecific(key)) != 0) || + (__res_init_ctx() == 0 && + (mt = pthread_getspecific(key)) != 0)) { + return (mt); + } + } +#endif + return (&sharedctx); +} diff --git a/lib/libc/resolv/res_comp.c b/lib/libc/resolv/res_comp.c new file mode 100644 index 0000000..509adcd --- /dev/null +++ b/lib/libc/resolv/res_comp.c @@ -0,0 +1,274 @@ +/* + * 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. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +/* + * Portions Copyright (c) 1993 by Digital Equipment Corporation. + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies, and that + * the name of Digital Equipment Corporation not be used in advertising or + * publicity pertaining to distribution of the document or software without + * specific, written prior permission. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL + * WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL DIGITAL EQUIPMENT + * CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL + * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR + * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS + * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS + * SOFTWARE. + */ + +/* + * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC") + * Portions Copyright (c) 1996-1999 by Internet Software Consortium. + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT + * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static const char sccsid[] = "@(#)res_comp.c 8.1 (Berkeley) 6/4/93"; +static const char rcsid[] = "$Id: res_comp.c 89 2016-01-12 00:20:40Z reddawg $"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/resolv/res_comp.c,v 1.2.2.1 2006/07/17 10:09:58 ume Exp $"); + +#include "port_before.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "port_after.h" + +/* + * Expand compressed domain name 'src' to full domain name. + * 'msg' is a pointer to the begining of the message, + * 'eom' points to the first location after the message, + * 'dst' is a pointer to a buffer of size 'dstsiz' for the result. + * Return size of compressed name or -1 if there was an error. + */ +int +dn_expand(const u_char *msg, const u_char *eom, const u_char *src, + char *dst, int dstsiz) +{ + int n = ns_name_uncompress(msg, eom, src, dst, (size_t)dstsiz); + + if (n > 0 && dst[0] == '.') + dst[0] = '\0'; + return (n); +} + +/* + * Pack domain name 'exp_dn' in presentation form into 'comp_dn'. + * Return the size of the compressed name or -1. + * 'length' is the size of the array pointed to by 'comp_dn'. + */ +int +dn_comp(const char *src, u_char *dst, int dstsiz, + u_char **dnptrs, u_char **lastdnptr) +{ + return (ns_name_compress(src, dst, (size_t)dstsiz, + (const u_char **)dnptrs, + (const u_char **)lastdnptr)); +} + +/* + * Skip over a compressed domain name. Return the size or -1. + */ +int +dn_skipname(const u_char *ptr, const u_char *eom) { + const u_char *saveptr = ptr; + + if (ns_name_skip(&ptr, eom) == -1) + return (-1); + return (ptr - saveptr); +} + +/* + * Verify that a domain name uses an acceptable character set. + */ + +/* + * Note the conspicuous absence of ctype macros in these definitions. On + * non-ASCII hosts, we can't depend on string literals or ctype macros to + * tell us anything about network-format data. The rest of the BIND system + * is not careful about this, but for some reason, we're doing it right here. + */ +#define PERIOD 0x2e +#define hyphenchar(c) ((c) == 0x2d) +#define bslashchar(c) ((c) == 0x5c) +#define periodchar(c) ((c) == PERIOD) +#define asterchar(c) ((c) == 0x2a) +#define alphachar(c) (((c) >= 0x41 && (c) <= 0x5a) \ + || ((c) >= 0x61 && (c) <= 0x7a)) +#define digitchar(c) ((c) >= 0x30 && (c) <= 0x39) + +#define borderchar(c) (alphachar(c) || digitchar(c)) +#define middlechar(c) (borderchar(c) || hyphenchar(c)) +#define domainchar(c) ((c) > 0x20 && (c) < 0x7f) + +int +res_hnok(const char *dn) { + int pch = PERIOD, ch = *dn++; + + while (ch != '\0') { + int nch = *dn++; + + if (periodchar(ch)) { + (void)NULL; + } else if (periodchar(pch)) { + if (!borderchar(ch)) + return (0); + } else if (periodchar(nch) || nch == '\0') { + if (!borderchar(ch)) + return (0); + } else { + if (!middlechar(ch)) + return (0); + } + pch = ch, ch = nch; + } + return (1); +} + +/* + * hostname-like (A, MX, WKS) owners can have "*" as their first label + * but must otherwise be as a host name. + */ +int +res_ownok(const char *dn) { + if (asterchar(dn[0])) { + if (periodchar(dn[1])) + return (res_hnok(dn+2)); + if (dn[1] == '\0') + return (1); + } + return (res_hnok(dn)); +} + +/* + * SOA RNAMEs and RP RNAMEs can have any printable character in their first + * label, but the rest of the name has to look like a host name. + */ +int +res_mailok(const char *dn) { + int ch, escaped = 0; + + /* "." is a valid missing representation */ + if (*dn == '\0') + return (1); + + /* otherwise