diff --git a/.cvsignore b/.cvsignore new file mode 100644 index 0000000..7d91f2e --- /dev/null +++ b/.cvsignore @@ -0,0 +1,3 @@ +ne2k-tx.log +ne2k-txdump.txt +snapshot.txt diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..2358625 --- /dev/null +++ b/Makefile @@ -0,0 +1,40 @@ +# $Id$ +# The System Makefile (C) 2002 The UbixOS Project + +all: tools kernel libc ubix objgfx40 libcpp bin +# depend kernel tools + +libc: src + (cd src/lib/libc;make) + +objgfx40: src + (cd src/lib/objgfx40;make) + +ubix: src + (cd src/lib/ubix;make) + +libcpp: src + (cd src/lib/libcpp;make) + +depend: src + (cd src/lib/ubix;make) + +bin: src + (cd src/bin;make) + +kernel: src + (cd src/sys;make) + +tools: src + (cd src/tools;make) + +install: + (cd src/sys;make install) + +clean: + (cd src/sys;make clean) + (cd src/lib/libc;make clean) + (cd src/bin;make clean) + (cd src/lib/ubix;make clean) + (cd src/lib/objgfx40;make clean) + (cd src/lib/libcpp;make clean) diff --git a/README b/README new file mode 100644 index 0000000..9d9dddc --- /dev/null +++ b/README @@ -0,0 +1 @@ +NO README Yet diff --git a/doc/vmm.txt b/doc/vmm.txt new file mode 100644 index 0000000..debb245 --- /dev/null +++ b/doc/vmm.txt @@ -0,0 +1,34 @@ +This document goes over the UbixOS VMM + + +1. Memory Layout - + + Each application has its own private 4gb memory area the first 1mb is mapped 1:1 against the systems memory and is shared between all of the proccess + on the system it include bios information video buffers and the kernel code. + + From 0x100000 - 3gb this memory region is available for the task itself for its code data and anything else it may need it for + + The top 1gb is reserved and shared across every application this is the os memory region not readable by the application unless it is in a syscall + + at 0x100000 the applications page directory is stored and page 0x768 is all the pagetable listed in the page dir specified at 0x100000 + +2. Functions - + + vmmInit: + This function initializes our memory map and paging system if either fail this returns a failure. + + vmmMemMapInit: + This initializes our memory map, it is a linked list of available pages it keeps track of COW (copy on write) as well as ownership and status + + vmmPagingInit: + This initializes our paging system sets up default memory area for kernel and remaps the memory map into the top 1GB this builds the memory foundation + for each application to follow + + vmmCreateVirtualSpace: + This creates a new virtual space for a process it takes on arg pidType pid and returns the base address of the new page directory + This has the shared lower 1 mb and top 1GB everything inbetween is available for the process + + vmmCopyVirtualSpace: + This copies the current virtual space for the process specified by the arg pidType pid passed in. This copy sets all the pages for 2mb -3gb COW and no + memory is physically copied when the program attempts to write to this region a page fault happens then the memory is physically copied + diff --git a/src/Makefile.inc b/src/Makefile.inc new file mode 100644 index 0000000..8a14d34 --- /dev/null +++ b/src/Makefile.inc @@ -0,0 +1,10 @@ +# $Id$ +# Global 'Source' Options + +# allow you to change your default compiler without affecting your other work +CC = gcc295 +CXX = g++295 +LD = ld +AR = ar +REMOVE = rm -rf + diff --git a/src/bin/Makefile b/src/bin/Makefile new file mode 100644 index 0000000..e6a4bda --- /dev/null +++ b/src/bin/Makefile @@ -0,0 +1,63 @@ +# $Id$ +# The System Makefile (C) 2002 The UbixOS Project + +all: init-bin login-bin shell-bin ls-bin clock-bin muffin-bin cp-bin #fdisk-bin +# test-bin pwd-bin cat-bin ld-dyn-bin de-bin goofball-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-dyn-bin: ld-dyn + (cd ld-dyn;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) + +clean: + (cd cp;make clean) + (cd fdisk;make clean) + (cd init;make clean) + (cd shell;make clean) + #(cd test;make clean) + (cd ls;make clean) + #(cd pwd;make clean) + (cd login;make clean) + (cd clock;make clean) + #(cd cat;make clean) + #(cd ld-dyn;make clean) + #(cd de;make clean) + (cd muffin;make clean) + #(cd goofball;make clean) diff --git a/src/bin/Makefile.inc b/src/bin/Makefile.inc new file mode 100644 index 0000000..2dcd501 --- /dev/null +++ b/src/bin/Makefile.inc @@ -0,0 +1,5 @@ +# 'bin' options + +CFLAGS = -fno-builtin -I../../include #-I../../lib/libc/include -fno-builtin + +LIBRARIES = ../../lib/libc/math/*.o ../../lib/libc/quad/*.o ../../lib/libc/stdio/*.o ../../lib/libc/stdlib/*.o ../../lib/libc/sys/*.o ../../lib/libc/string/*.o ../../lib/libc/locale/*.o ../../lib/libc/gen/*.o ../../lib/libc/generic/*.o diff --git a/src/bin/clock/Makefile b/src/bin/clock/Makefile new file mode 100644 index 0000000..bdfc00d --- /dev/null +++ b/src/bin/clock/Makefile @@ -0,0 +1,51 @@ +# $Id$ +# Application Makefile (C) 2002 The UbixOS Project + +# Include Global 'Source' Options +include ../../Makefile.inc + +#Compiler Flags +CFLAGS = -I../../include -fno-builtin + +#Linker +LD = ld + +#Binary File Name +BINARY = clock + +#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 + +#Startup File +STARTUP = ../../lib/ubix/startup.o + +# Link The Binary +$(BINARY) : $(OBJS) + $(CC) -nostdlib -o $@ $(STARTUP) $(LIBRARIES) $(OBJS) + +# 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) $(BINARY) diff --git a/src/bin/clock/main.c b/src/bin/clock/main.c new file mode 100644 index 0000000..9804603 --- /dev/null +++ b/src/bin/clock/main.c @@ -0,0 +1,130 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#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) { + char time[10]; + int sysTime = 0x0; + int offset = 0x0; + int i = 0x0; + + int year = 0x0; + int month = 0x0; + int day = 0x0; + int hour = 0x0; + int min = 0x0; + int sec = 0x0; + + if (argv[1] != 0x0) { + offset = atoi(argv[1]); + } + while (1) { + + while (sysTime == gettime()) + sched_yield(); + + 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; + + sprintf(time,"[%02d/%02d/%i, %02d:%02d.%02d]",month,day,year,hour,min,sec); + print2(time,offset,0xFA); + sysTime = gettime(); + } + return(0); + } + +void print2(char *string,int cv_pos,int printColor) +{ + char *scrnBuf = (char *)0xB8000; + int i = 0; + + while ('\0' != string[i]) { + switch (string[i]) { + case '\t': + cv_pos += 3; + break; + case '\b': + if (cv_pos != 0) { + cv_pos -= 2; + scrnBuf[((cv_pos + 1) << 1)] = ' '; + } /* if */ + break; + case '\n': + cv_pos = cv_pos - (cv_pos % 80) + 79; + break; + default: + scrnBuf[(cv_pos << 1)] = string[i]; + scrnBuf[(cv_pos << 1) | 0x1] = (printColor & 0xFF); + break; + } /* switch */ + + cv_pos++; + i++; + } + } diff --git a/src/bin/cp/Makefile b/src/bin/cp/Makefile new file mode 100644 index 0000000..fdd54f4 --- /dev/null +++ b/src/bin/cp/Makefile @@ -0,0 +1,39 @@ +# $Id$ +# Application Makefile (C) 2002 The UbixOS Project + +# Include Global 'Source' Options +include ../../Makefile.inc +include ../Makefile.inc + +#Binary File Name +BINARY = cp + +#Objects +OBJS = main.o + +#Startup File +STARTUP = ../../lib/ubix/startup.o + +# Link The Binary +$(BINARY) : $(OBJS) + $(CC) -nostdlib -o $@ $(STARTUP) $(LIBRARIES) $(OBJS) + +# 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) $(BINARY) diff --git a/src/bin/cp/main.c b/src/bin/cp/main.c new file mode 100644 index 0000000..64deac3 --- /dev/null +++ b/src/bin/cp/main.c @@ -0,0 +1,48 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#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); + } + +/*** + END + ***/ + diff --git a/src/bin/fdisk/Makefile b/src/bin/fdisk/Makefile new file mode 100644 index 0000000..cc698d4 --- /dev/null +++ b/src/bin/fdisk/Makefile @@ -0,0 +1,48 @@ +# $Id$ +# Application Makefile (C) 2002 The UbixOS Project + +# Include Global 'Source' Options +include ../../Makefile.inc +include ../Makefile.inc + +#Compiler Flags +CFLAGS = -I../../include -I../../lib/libc/include -fno-builtin + +#Linker +LD = ld + +#Binary File Name +BINARY = fdisk + +#Delete Program +REMOVE = rm -f + +#Objects +OBJS = fdisk.o + +#Startup File +STARTUP = ../../lib/ubix/startup.o + +# Link The Binary +$(BINARY) : $(OBJS) + $(CC) -nostdlib -o $@ $(STARTUP) $(LIBRARIES) $(OBJS) + +# 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) $(BINARY) diff --git a/src/bin/fdisk/fdisk.c b/src/bin/fdisk/fdisk.c new file mode 100644 index 0000000..7d81f74 --- /dev/null +++ b/src/bin/fdisk/fdisk.c @@ -0,0 +1,1397 @@ +/* + * Mach Operating System + * Copyright (c) 1992 Carnegie Mellon University + * All Rights Reserved. + * + * Permission to use, copy, modify and distribute this software and its + * documentation is hereby granted, provided that both the copyright + * notice and this permission notice appear in all copies of the + * software, derivative works or modified versions, and any portions + * thereof, and that both notices appear in supporting documentation. + * + * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS" + * CONDITION. CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND FOR + * ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE. + * + * Carnegie Mellon requests users of this software to return to + * + * Software Distribution Coordinator or Software.Distribution@CS.CMU.EDU + * School of Computer Science + * Carnegie Mellon University + * Pittsburgh PA 15213-3890 + * + * any improvements or extensions that they make and grant Carnegie Mellon + * the rights to redistribute these changes. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* +#include +*/ + +int iotest; + +#define LBUF 100 +static char lbuf[LBUF]; + +#define MBRSIGOFF 510 + +/* + * + * Ported to 386bsd by Julian Elischer Thu Oct 15 20:26:46 PDT 1992 + * + * 14-Dec-89 Robert Baron (rvb) at Carnegie-Mellon University + * Copyright (c) 1989 Robert. V. Baron + * Created. + */ + +#define Decimal(str, ans, tmp) if (decimal(str, &tmp, ans)) ans = tmp + +#define RoundCyl(x) ((((x) + cylsecs - 1) / cylsecs) * cylsecs) + +#define MAX_SEC_SIZE 2048 /* maximum section size that is supported */ +#define MIN_SEC_SIZE 512 /* the sector size to start sensing at */ +static int secsize = 0; /* the sensed sector size */ + +static char *disk; + +static int cyls, sectors, heads, cylsecs, disksecs; + +struct mboot { + unsigned char padding[2]; /* force the longs to be long aligned */ + unsigned char *bootinst; /* boot code */ + off_t bootinst_size; + struct dos_partition parts[NDOSPART]; +}; + +static struct mboot mboot; +static int fd, fdw; + + +#define ACTIVE 0x80 + +static uInt32 dos_cyls; +static uInt32 dos_heads; +static uInt32 dos_sectors; +static uInt32 dos_cylsecs; + +#define DOSSECT(s,c) ((s & 0x3f) | ((c >> 2) & 0xc0)) +#define DOSCYL(c) (c & 0xff) + +#define MAX_ARGS 10 + +static int current_line_number; + +static int geom_processed = 0; +static int part_processed = 0; +static int active_processed = 0; + +typedef struct cmd { + char cmd; + int n_args; + struct arg { + char argtype; + int arg_val; + } args[MAX_ARGS]; +} CMD; + +static int B_flag = 0; /* replace boot code */ +static int I_flag = 0; /* use entire disk for FreeBSD */ +static int a_flag = 0; /* set active partition */ +static char *b_flag = NULL; /* path to boot code */ +static int i_flag = 0; /* replace partition data */ +static int u_flag = 0; /* update partition data */ +static int s_flag = 0; /* Print a summary and exit */ +static int t_flag = 0; /* test only */ +static char *f_flag = NULL; /* Read config info from file */ +static int v_flag = 0; /* Be verbose */ + +static struct part_type +{ + unsigned char type; + const char *name; +} part_types[] = { + {0x00, "unused"} + ,{0x01, "Primary DOS with 12 bit FAT"} + ,{0x02, "XENIX / file system"} + ,{0x03, "XENIX /usr file system"} + ,{0x04, "Primary DOS with 16 bit FAT (< 32MB)"} + ,{0x05, "Extended DOS"} + ,{0x06, "Primary 'big' DOS (>= 32MB)"} + ,{0x07, "OS/2 HPFS, NTFS, QNX-2 (16 bit) or Advanced UNIX"} + ,{0x08, "AIX file system or SplitDrive"} + ,{0x09, "AIX boot partition or Coherent"} + ,{0x0A, "OS/2 Boot Manager, OPUS or Coherent swap"} + ,{0x0B, "DOS or Windows 95 with 32 bit FAT"} + ,{0x0C, "DOS or Windows 95 with 32 bit FAT (LBA)"} + ,{0x0E, "Primary 'big' DOS (>= 32MB, LBA)"} + ,{0x0F, "Extended DOS (LBA)"} + ,{0x10, "OPUS"} + ,{0x11, "OS/2 BM: hidden DOS with 12-bit FAT"} + ,{0x12, "Compaq diagnostics"} + ,{0x14, "OS/2 BM: hidden DOS with 16-bit FAT (< 32MB)"} + ,{0x16, "OS/2 BM: hidden DOS with 16-bit FAT (>= 32MB)"} + ,{0x17, "OS/2 BM: hidden IFS (e.g. HPFS)"} + ,{0x18, "AST Windows swapfile"} + ,{0x24, "NEC DOS"} + ,{0x3C, "PartitionMagic recovery"} + ,{0x39, "plan9"} + ,{0x40, "VENIX 286"} + ,{0x41, "Linux/MINIX (sharing disk with DRDOS)"} + ,{0x42, "SFS or Linux swap (sharing disk with DRDOS)"} + ,{0x43, "Linux native (sharing disk with DRDOS)"} + ,{0x4D, "QNX 4.2 Primary"} + ,{0x4E, "QNX 4.2 Secondary"} + ,{0x4F, "QNX 4.2 Tertiary"} + ,{0x50, "DM (disk manager)"} + ,{0x51, "DM6 Aux1 (or Novell)"} + ,{0x52, "CP/M or Microport SysV/AT"} + ,{0x53, "DM6 Aux3"} + ,{0x54, "DM6"} + ,{0x55, "EZ-Drive (disk manager)"} + ,{0x56, "Golden Bow (disk manager)"} + ,{0x5c, "Priam Edisk (disk manager)"} /* according to S. Widlake */ + ,{0x61, "SpeedStor"} + ,{0x63, "System V/386 (such as ISC UNIX), GNU HURD or Mach"} + ,{0x64, "Novell Netware/286 2.xx"} + ,{0x65, "Novell Netware/386 3.xx"} + ,{0x70, "DiskSecure Multi-Boot"} + ,{0x75, "PCIX"} + ,{0x77, "QNX4.x"} + ,{0x78, "QNX4.x 2nd part"} + ,{0x79, "QNX4.x 3rd part"} + ,{0x80, "Minix until 1.4a"} + ,{0x81, "Minix since 1.4b, early Linux partition or Mitac disk manager"} + ,{0x82, "Linux swap or Solaris x86"} + ,{0x83, "Linux native"} + ,{0x84, "OS/2 hidden C: drive"} + ,{0x85, "Linux extended"} + ,{0x86, "NTFS volume set??"} + ,{0x87, "NTFS volume set??"} + ,{0x93, "Amoeba file system"} + ,{0x94, "Amoeba bad block table"} + ,{0x9F, "BSD/OS"} + ,{0xA0, "Suspend to Disk"} + ,{0xA5, "FreeBSD/NetBSD/386BSD"} + ,{0xA6, "OpenBSD"} + ,{0xA7, "NeXTSTEP"} + ,{0xA9, "NetBSD"} + ,{0xAC, "IBM JFS"} + ,{0xB7, "BSDI BSD/386 file system"} + ,{0xB8, "BSDI BSD/386 swap"} + ,{0xBE, "Solaris x86 boot"} + ,{0xC1, "DRDOS/sec with 12-bit FAT"} + ,{0xC4, "DRDOS/sec with 16-bit FAT (< 32MB)"} + ,{0xC6, "DRDOS/sec with 16-bit FAT (>= 32MB)"} + ,{0xC7, "Syrinx"} + ,{0xDB, "CP/M, Concurrent CP/M, Concurrent DOS or CTOS"} + ,{0xE1, "DOS access or SpeedStor with 12-bit FAT extended partition"} + ,{0xE3, "DOS R/O or SpeedStor"} + ,{0xE4, "SpeedStor with 16-bit FAT extended partition < 1024 cyl."} + ,{0xEB, "BeOS file system"} + ,{0xEE, "EFI GPT"} + ,{0xEF, "EFI System Partition"} + ,{0xF1, "SpeedStor"} + ,{0xF2, "DOS 3.3+ Secondary"} + ,{0xF4, "SpeedStor large partition"} + ,{0xFE, "SpeedStor >1024 cyl. or LANstep"} + ,{0xFF, "Xenix bad blocks table"} +}; + +static void print_s0(int which); +static void print_part(int i); +static void init_sector0(unsigned long start); +static void init_boot(void); +static void change_part(int i); +static void print_params(void); +static void change_active(int which); +static void change_code(void); +static void get_params_to_use(void); +static char *get_rootdisk(void); +static void dos(struct dos_partition *partp); +static int open_disk(int flag); +static ssize_t read_disk(off_t sector, void *buf); +static ssize_t write_disk(off_t sector, void *buf); +static int get_params(void); +static int read_s0(void); +static int write_s0(void); +static int ok(const char *str); +static int decimal(const char *str, int *num, int deflt); +static const char *get_type(int type); +static int read_config(char *config_file); +static void reset_boot(void); +static int sanitize_partition(struct dos_partition *); +static void usage(void); + +int +main(int argc, char *argv[]) +{ + struct stat sb; + int c, i; + int partition = -1; + struct dos_partition *partp; + + while ((c = getopt(argc, argv, "BIab:f:istuv1234")) != -1) + switch (c) { + case 'B': + B_flag = 1; + break; + case 'I': + I_flag = 1; + break; + case 'a': + a_flag = 1; + break; + case 'b': + b_flag = optarg; + break; + case 'f': + f_flag = optarg; + break; + case 'i': + i_flag = 1; + break; + case 's': + s_flag = 1; + break; + case 't': + t_flag = 1; + break; + case 'u': + u_flag = 1; + break; + case 'v': + v_flag = 1; + break; + case '1': + case '2': + case '3': + case '4': + partition = c - '0'; + break; + default: + usage(); + } + if (f_flag || i_flag) + u_flag = 1; + if (t_flag) + v_flag = 1; + argc -= optind; + argv += optind; + + if (argc == 0) { + disk = get_rootdisk(); + } else { + if (stat(argv[0], &sb) == 0) { + /* OK, full pathname given */ + disk = argv[0]; + } else if (errno == ENOENT) { + /* Try prepending "/dev" */ + asprintf(&disk, "%s%s", _PATH_DEV, argv[0]); + if (disk == NULL) + errx(1, "out of memory"); + } else { + /* other stat error, let it fail below */ + disk = argv[0]; + } + } + if (open_disk(u_flag) < 0) + err(1, "cannot open disk %s", disk); + + /* (abu)use mboot.bootinst to probe for the sector size */ + if ((mboot.bootinst = malloc(MAX_SEC_SIZE)) == NULL) + err(1, "cannot allocate buffer to determine disk sector size"); + read_disk(0, mboot.bootinst); + free(mboot.bootinst); + mboot.bootinst = NULL; + + if (s_flag) { + if (read_s0()) + err(1, "read_s0"); + printf("%s: %d cyl %d hd %d sec\n", disk, dos_cyls, dos_heads, + dos_sectors); + printf("Part %11s %11s Type Flags\n", "Start", "Size"); + for (i = 0; i < NDOSPART; i++) { + partp = ((struct dos_partition *) &mboot.parts) + i; + if (partp->dp_start == 0 && partp->dp_size == 0) + continue; + printf("%4d: %11lu %11lu 0x%02x 0x%02x\n", i + 1, + (uInt32) partp->dp_start, + (uInt32) partp->dp_size, partp->dp_typ, + partp->dp_flag); + } + exit(0); + } + + printf("******* Working on device %s *******\n",disk); + + if (I_flag) { + read_s0(); + reset_boot(); + partp = (struct dos_partition *) (&mboot.parts[0]); + partp->dp_typ = DOSPTYP_386BSD; + partp->dp_flag = ACTIVE; + partp->dp_start = dos_sectors; + partp->dp_size = (disksecs / dos_cylsecs) * dos_cylsecs - + dos_sectors; + dos(partp); + if (v_flag) + print_s0(-1); + if (!t_flag) + write_s0(); + exit(0); + } + if (f_flag) { + if (read_s0() || i_flag) + reset_boot(); + if (!read_config(f_flag)) + exit(1); + if (v_flag) + print_s0(-1); + if (!t_flag) + write_s0(); + } else { + if(u_flag) + get_params_to_use(); + else + print_params(); + + if (read_s0()) + init_sector0(dos_sectors); + + printf("Media sector size is %d\n", secsize); + printf("Warning: BIOS sector numbering starts with sector 1\n"); + printf("Information from DOS bootblock is:\n"); + if (partition == -1) + for (i = 1; i <= NDOSPART; i++) + change_part(i); + else + change_part(partition); + + if (u_flag || a_flag) + change_active(partition); + + if (B_flag) + change_code(); + + if (u_flag || a_flag || B_flag) { + if (!t_flag) { + printf("\nWe haven't changed the partition table yet. "); + printf("This is your last chance.\n"); + } + print_s0(-1); + if (!t_flag) { + if (ok("Should we write new partition table?")) + write_s0(); + } else { + printf("\n-t flag specified -- partition table not written.\n"); + } + } + } + + exit(0); +} + +static void +usage() +{ + fprintf(stderr, "%s%s", + "usage: fdisk [-BIaistu] [-b bootcode] [-1234] [disk]\n", + " fdisk -f configfile [-itv] [disk]\n"); + exit(1); +} + +static void +print_s0(int which) +{ + int i; + + print_params(); + printf("Information from DOS bootblock is:\n"); + if (which == -1) + for (i = 1; i <= NDOSPART; i++) + printf("%d: ", i), print_part(i); + else + print_part(which); +} + +static struct dos_partition mtpart; + +static void +print_part(int i) +{ + struct dos_partition *partp; + uInt64 part_mb; + + partp = ((struct dos_partition *) &mboot.parts) + i - 1; + + if (!bcmp(partp, &mtpart, sizeof (struct dos_partition))) { + printf("\n"); + return; + } + /* + * Be careful not to overflow. + */ + part_mb = partp->dp_size; + part_mb *= secsize; + part_mb /= (1024 * 1024); + printf("sysid %d (%#04x),(%s)\n", partp->dp_typ, partp->dp_typ, + get_type(partp->dp_typ)); + printf(" start %lu, size %lu (%ju Meg), flag %x%s\n", + (uInt32)partp->dp_start, + (uInt32)partp->dp_size, + (uintmax_t)part_mb, + partp->dp_flag, + partp->dp_flag == ACTIVE ? " (active)" : ""); + printf("\tbeg: cyl %d/ head %d/ sector %d;\n\tend: cyl %d/ head %d/ sector %d\n" + ,DPCYL(partp->dp_scyl, partp->dp_ssect) + ,partp->dp_shd + ,DPSECT(partp->dp_ssect) + ,DPCYL(partp->dp_ecyl, partp->dp_esect) + ,partp->dp_ehd + ,DPSECT(partp->dp_esect)); +} + + +static void +init_boot(void) +{ +#ifndef __ia64__ + const char *fname; + int fdesc, n; + struct stat sb; + + fname = b_flag ? b_flag : "/boot/mbr"; + if ((fdesc = open(fname, O_RDONLY)) == -1 || + fstat(fdesc, &sb) == -1) + err(1, "%s", fname); + if ((mboot.bootinst_size = sb.st_size) % secsize != 0) + errx(1, "%s: length must be a multiple of sector size", fname); + if (mboot.bootinst != NULL) + free(mboot.bootinst); + if ((mboot.bootinst = malloc(mboot.bootinst_size = sb.st_size)) == NULL) + errx(1, "%s: unable to allocate read buffer", fname); + if ((n = read(fdesc, mboot.bootinst, mboot.bootinst_size)) == -1 || + close(fdesc)) + err(1, "%s", fname); + if (n != mboot.bootinst_size) + errx(1, "%s: short read", fname); +#else + if (mboot.bootinst != NULL) + free(mboot.bootinst); + mboot.bootinst_size = secsize; + if ((mboot.bootinst = malloc(mboot.bootinst_size)) == NULL) + errx(1, "unable to allocate boot block buffer"); + memset(mboot.bootinst, 0, mboot.bootinst_size); + le16enc(&mboot.bootinst[DOSMAGICOFFSET], DOSMAGIC); +#endif +} + + +static void +init_sector0(unsigned long start) +{ + struct dos_partition *partp = (struct dos_partition *) (&mboot.parts[3]); + + init_boot(); + + partp->dp_typ = DOSPTYP_386BSD; + partp->dp_flag = ACTIVE; + start = ((start + dos_sectors - 1) / dos_sectors) * dos_sectors; + if(start == 0) + start = dos_sectors; + partp->dp_start = start; + partp->dp_size = (disksecs / dos_cylsecs) * dos_cylsecs - start; + + dos(partp); +} + +static void +change_part(int i) +{ + struct dos_partition *partp = ((struct dos_partition *) &mboot.parts) + i - 1; + + printf("The data for partition %d is:\n", i); + print_part(i); + + if (u_flag && ok("Do you want to change it?")) { + int tmp; + + if (i_flag) { + bzero((char *)partp, sizeof (struct dos_partition)); + if (i == 4) { + init_sector0(1); + printf("\nThe static data for the DOS partition 4 has been reinitialized to:\n"); + print_part(i); + } + } + + do { + Decimal("sysid (165=FreeBSD)", partp->dp_typ, tmp); + Decimal("start", partp->dp_start, tmp); + Decimal("size", partp->dp_size, tmp); + if (!sanitize_partition(partp)) { + warnx("ERROR: failed to adjust; setting sysid to 0"); + partp->dp_typ = 0; + } + + if (ok("Explicitly specify beg/end address ?")) + { + int tsec,tcyl,thd; + tcyl = DPCYL(partp->dp_scyl,partp->dp_ssect); + thd = partp->dp_shd; + tsec = DPSECT(partp->dp_ssect); + Decimal("beginning cylinder", tcyl, tmp); + Decimal("beginning head", thd, tmp); + Decimal("beginning sector", tsec, tmp); + partp->dp_scyl = DOSCYL(tcyl); + partp->dp_ssect = DOSSECT(tsec,tcyl); + partp->dp_shd = thd; + + tcyl = DPCYL(partp->dp_ecyl,partp->dp_esect); + thd = partp->dp_ehd; + tsec = DPSECT(partp->dp_esect); + Decimal("ending cylinder", tcyl, tmp); + Decimal("ending head", thd, tmp); + Decimal("ending sector", tsec, tmp); + partp->dp_ecyl = DOSCYL(tcyl); + partp->dp_esect = DOSSECT(tsec,tcyl); + partp->dp_ehd = thd; + } else + dos(partp); + + print_part(i); + } while (!ok("Are we happy with this entry?")); + } + } + +static void +print_params() +{ + printf("parameters extracted from in-core disklabel are:\n"); + printf("cylinders=%d heads=%d sectors/track=%d (%d blks/cyl)\n\n" + ,cyls,heads,sectors,cylsecs); + if((dos_sectors > 63) || (dos_cyls > 1023) || (dos_heads > 255)) + printf("Figures below won't work with BIOS for partitions not in cyl 1\n"); + printf("parameters to be used for BIOS calculations are:\n"); + printf("cylinders=%d heads=%d sectors/track=%d (%d blks/cyl)\n\n" + ,dos_cyls,dos_heads,dos_sectors,dos_cylsecs); +} + +static void +change_active(int which) +{ + struct dos_partition *partp = &mboot.parts[0]; + int active, i, new, tmp; + + active = -1; + for (i = 0; i < NDOSPART; i++) { + if ((partp[i].dp_flag & ACTIVE) == 0) + continue; + printf("Partition %d is marked active\n", i + 1); + if (active == -1) + active = i + 1; + } + if (a_flag && which != -1) + active = which; + else if (active == -1) + active = 1; + + if (!ok("Do you want to change the active partition?")) + return; +setactive: + do { + new = active; + Decimal("active partition", new, tmp); + if (new < 1 || new > 4) { + printf("Active partition number must be in range 1-4." + " Try again.\n"); + goto setactive; + } + active = new; + } while (!ok("Are you happy with this choice")); + for (i = 0; i < NDOSPART; i++) + partp[i].dp_flag = 0; + if (active > 0 && active <= NDOSPART) + partp[active-1].dp_flag = ACTIVE; +} + +static void +change_code() +{ + if (ok("Do you want to change the boot code?")) + init_boot(); +} + +void +get_params_to_use() +{ + int tmp; + print_params(); + if (ok("Do you want to change our idea of what BIOS thinks ?")) + { + do + { + Decimal("BIOS's idea of #cylinders", dos_cyls, tmp); + Decimal("BIOS's idea of #heads", dos_heads, tmp); + Decimal("BIOS's idea of #sectors", dos_sectors, tmp); + dos_cylsecs = dos_heads * dos_sectors; + print_params(); + } + while(!ok("Are you happy with this choice")); + } +} + + +/***********************************************\ +* Change real numbers into strange dos numbers * +\***********************************************/ +static void +dos(struct dos_partition *partp) +{ + int cy, sec; + uInt32 end; + + if (partp->dp_typ == 0 && partp->dp_start == 0 && partp->dp_size == 0) { + memcpy(partp, &mtpart, sizeof(*partp)); + return; + } + + /* Start c/h/s. */ + partp->dp_shd = partp->dp_start % dos_cylsecs / dos_sectors; + cy = partp->dp_start / dos_cylsecs; + sec = partp->dp_start % dos_sectors + 1; + partp->dp_scyl = DOSCYL(cy); + partp->dp_ssect = DOSSECT(sec, cy); + + /* End c/h/s. */ + end = partp->dp_start + partp->dp_size - 1; + partp->dp_ehd = end % dos_cylsecs / dos_sectors; + cy = end / dos_cylsecs; + sec = end % dos_sectors + 1; + partp->dp_ecyl = DOSCYL(cy); + partp->dp_esect = DOSSECT(sec, cy); +} + +static int +open_disk(int flag) +{ + struct stat st; + int rwmode, p; + char *s; + + fdw = -1; + if (stat(disk, &st) == -1) { + if (errno == ENOENT) + return -2; + warnx("can't get file status of %s", disk); + return -1; + } + if ( !(st.st_mode & S_IFCHR) ) + warnx("device %s is not character special", disk); + rwmode = a_flag || I_flag || B_flag || flag ? O_RDWR : O_RDONLY; + fd = open(disk, rwmode); + if (fd == -1 && errno == ENXIO) + return -2; + if (fd == -1 && errno == EPERM && rwmode == O_RDWR) { + fd = open(disk, O_RDONLY); + if (fd == -1) + return -3; + for (p = 1; p < 5; p++) { + asprintf(&s, "%ss%d", disk, p); + fdw = open(s, O_RDONLY); + free(s); + if (fdw == -1) + continue; + break; + } + if (fdw == -1) + return -4; + } + if (fd == -1) { + warnx("can't open device %s", disk); + return -1; + } + if (get_params() == -1) { + warnx("can't get disk parameters on %s", disk); + return -1; + } + return fd; +} + +static ssize_t +read_disk(off_t sector, void *buf) +{ + lseek(fd,(sector * 512), 0); + if( secsize == 0 ) + for( secsize = MIN_SEC_SIZE; secsize <= MAX_SEC_SIZE; secsize *= 2 ) + { + /* try the read */ + int size = read(fd, buf, secsize); + if( size == secsize ) + /* it worked so return */ + return secsize; + } + else + return read( fd, buf, secsize ); + + /* we failed to read at any of the sizes */ + return -1; +} + +static ssize_t +write_disk(off_t sector, void *buf) +{ + + if (fdw != -1) { + return ioctl(fdw, DIOCSMBR, buf); + } else { + lseek(fd,(sector * 512), 0); + /* write out in the size that the read_disk found worked */ + return write(fd, buf, secsize); + } +} + +static int +get_params() +{ + int error; + uInt32 u; + off_t o; + + error = ioctl(fd, DIOCGFWSECTORS, &u); + if (error == 0) + sectors = dos_sectors = u; + else + sectors = dos_sectors = 63; + + error = ioctl(fd, DIOCGFWHEADS, &u); + if (error == 0) + heads = dos_heads = u; + else + heads = dos_heads = 255; + + dos_cylsecs = cylsecs = heads * sectors; + disksecs = cyls * heads * sectors; + + error = ioctl(fd, DIOCGSECTORSIZE, &u); + if (error != 0 || u == 0) + u = 512; + + error = ioctl(fd, DIOCGMEDIASIZE, &o); + if (error == 0) { + disksecs = o / u; + cyls = dos_cyls = o / (u * dos_heads * dos_sectors); + } + + return (disksecs); +} + + +static int +read_s0() +{ + int i; + + mboot.bootinst_size = secsize; + if (mboot.bootinst != NULL) + free(mboot.bootinst); + if ((mboot.bootinst = malloc(mboot.bootinst_size)) == NULL) { + warnx("unable to allocate buffer to read fdisk " + "partition table"); + return -1; + } + if (read_disk(0, mboot.bootinst) == -1) { + warnx("can't read fdisk partition table"); + return -1; + } + if (le16dec(&mboot.bootinst[DOSMAGICOFFSET]) != DOSMAGIC) { + warnx("invalid fdisk partition table found"); + /* So should we initialize things */ + return -1; + } + for (i = 0; i < NDOSPART; i++) + dos_partition_dec( + &mboot.bootinst[DOSPARTOFF + i * DOSPARTSIZE], + &mboot.parts[i]); + return 0; +} + +static int +write_s0() +{ + int sector, i; + + if (iotest) { + print_s0(-1); + return 0; + } + for(i = 0; i < NDOSPART; i++) + dos_partition_enc(&mboot.bootinst[DOSPARTOFF + i * DOSPARTSIZE], + &mboot.parts[i]); + le16enc(&mboot.bootinst[DOSMAGICOFFSET], DOSMAGIC); + for(sector = 0; sector < mboot.bootinst_size / secsize; sector++) + if (write_disk(sector, + &mboot.bootinst[sector * secsize]) == -1) { + warn("can't write fdisk partition table"); + return -1; + } + return(0); +} + + +static int +ok(const char *str) +{ + printf("%s [n] ", str); + fflush(stdout); + if (fgets(lbuf, LBUF, stdin) == NULL) + exit(1); + lbuf[strlen(lbuf)-1] = 0; + + if (*lbuf && + (!strcmp(lbuf, "yes") || !strcmp(lbuf, "YES") || + !strcmp(lbuf, "y") || !strcmp(lbuf, "Y"))) + return 1; + else + return 0; +} + +static int +decimal(const char *str, int *num, int deflt) +{ + int acc = 0, c; + char *cp; + + while (1) { + printf("Supply a decimal value for \"%s\" [%d] ", str, deflt); + fflush(stdout); + if (fgets(lbuf, LBUF, stdin) == NULL) + exit(1); + lbuf[strlen(lbuf)-1] = 0; + + if (!*lbuf) + return 0; + + cp = lbuf; + while ((c = *cp) && (c == ' ' || c == '\t')) cp++; + if (!c) + return 0; + while ((c = *cp++)) { + if (c <= '9' && c >= '0') + acc = acc * 10 + c - '0'; + else + break; + } + if (c == ' ' || c == '\t') + while ((c = *cp) && (c == ' ' || c == '\t')) cp++; + if (!c) { + *num = acc; + return 1; + } else + printf("%s is an invalid decimal number. Try again.\n", + lbuf); + } + +} + +static const char * +get_type(int type) +{ + int numentries = (sizeof(part_types)/sizeof(struct part_type)); + int counter = 0; + struct part_type *ptr = part_types; + + + while(counter < numentries) { + if(ptr->type == type) + return(ptr->name); + ptr++; + counter++; + } + return("unknown"); +} + + +static void +parse_config_line(char *line, CMD *command) +{ + char *cp, *end; + + cp = line; + while (1) { + memset(command, 0, sizeof(*command)); + + while (isspace(*cp)) ++cp; + if (*cp == '\0' || *cp == '#') + break; + command->cmd = *cp++; + + /* + * Parse args + */ + while (1) { + while (isspace(*cp)) ++cp; + if (*cp == '#') + break; /* found comment */ + if (isalpha(*cp)) + command->args[command->n_args].argtype = *cp++; + if (!isdigit(*cp)) + break; /* assume end of line */ + end = NULL; + command->args[command->n_args].arg_val = strtol(cp, &end, 0); + if (cp == end) + break; /* couldn't parse number */ + cp = end; + command->n_args++; + } + break; + } +} + + +static int +process_geometry(CMD *command) +{ + int status = 1, i; + + while (1) { + geom_processed = 1; + if (part_processed) { + warnx( + "ERROR line %d: the geometry specification line must occur before\n\ + all partition specifications", + current_line_number); + status = 0; + break; + } + if (command->n_args != 3) { + warnx("ERROR line %d: incorrect number of geometry args", + current_line_number); + status = 0; + break; + } + dos_cyls = 0; + dos_heads = 0; + dos_sectors = 0; + for (i = 0; i < 3; ++i) { + switch (command->args[i].argtype) { + case 'c': + dos_cyls = command->args[i].arg_val; + break; + case 'h': + dos_heads = command->args[i].arg_val; + break; + case 's': + dos_sectors = command->args[i].arg_val; + break; + default: + warnx( + "ERROR line %d: unknown geometry arg type: '%c' (0x%02x)", + current_line_number, command->args[i].argtype, + command->args[i].argtype); + status = 0; + break; + } + } + if (status == 0) + break; + + dos_cylsecs = dos_heads * dos_sectors; + + /* + * Do sanity checks on parameter values + */ + if (dos_cyls == 0) { + warnx("ERROR line %d: number of cylinders not specified", + current_line_number); + status = 0; + } + if (dos_cyls > 1024) { + warnx( + "WARNING line %d: number of cylinders (%d) may be out-of-range\n\ + (must be within 1-1024 for normal BIOS operation, unless the entire disk\n\ + is dedicated to FreeBSD)", + current_line_number, dos_cyls); + } + + if (dos_heads == 0) { + warnx("ERROR line %d: number of heads not specified", + current_line_number); + status = 0; + } else if (dos_heads > 256) { + warnx("ERROR line %d: number of heads must be within (1-256)", + current_line_number); + status = 0; + } + + if (dos_sectors == 0) { + warnx("ERROR line %d: number of sectors not specified", + current_line_number); + status = 0; + } else if (dos_sectors > 63) { + warnx("ERROR line %d: number of sectors must be within (1-63)", + current_line_number); + status = 0; + } + + break; + } + return (status); +} + + +static int +process_partition(CMD *command) +{ + int status = 0, partition; + uInt32 prev_head_boundary, prev_cyl_boundary; + uInt32 adj_size, max_end; + struct dos_partition *partp; + + while (1) { + part_processed = 1; + if (command->n_args != 4) { + warnx("ERROR line %d: incorrect number of partition args", + current_line_number); + break; + } + partition = command->args[0].arg_val; + if (partition < 1 || partition > 4) { + warnx("ERROR line %d: invalid partition number %d", + current_line_number, partition); + break; + } + partp = ((struct dos_partition *) &mboot.parts) + partition - 1; + bzero((char *)partp, sizeof (struct dos_partition)); + partp->dp_typ = command->args[1].arg_val; + partp->dp_start = command->args[2].arg_val; + partp->dp_size = command->args[3].arg_val; + max_end = partp->dp_start + partp->dp_size; + + if (partp->dp_typ == 0) { + /* + * Get out, the partition is marked as unused. + */ + /* + * Insure that it's unused. + */ + bzero((char *)partp, sizeof (struct dos_partition)); + status = 1; + break; + } + + /* + * Adjust start upwards, if necessary, to fall on a head boundary. + */ + if (partp->dp_start % dos_sectors != 0) { + prev_head_boundary = partp->dp_start / dos_sectors * dos_sectors; + if (max_end < dos_sectors || + prev_head_boundary > max_end - dos_sectors) { + /* + * Can't go past end of partition + */ + warnx( + "ERROR line %d: unable to adjust start of partition %d to fall on\n\ + a head boundary", + current_line_number, partition); + break; + } + warnx( + "WARNING: adjusting start offset of partition %d\n\ + from %u to %u, to fall on a head boundary", + partition, (uInt32)partp->dp_start, + (uInt32)(prev_head_boundary + dos_sectors)); + partp->dp_start = prev_head_boundary + dos_sectors; + } + + /* + * Adjust size downwards, if necessary, to fall on a cylinder + * boundary. + */ + prev_cyl_boundary = + ((partp->dp_start + partp->dp_size) / dos_cylsecs) * dos_cylsecs; + if (prev_cyl_boundary > partp->dp_start) + adj_size = prev_cyl_boundary - partp->dp_start; + else { + warnx( + "ERROR: could not adjust partition to start on a head boundary\n\ + and end on a cylinder boundary."); + return (0); + } + if (adj_size != partp->dp_size) { + warnx( + "WARNING: adjusting size of partition %d from %u to %u\n\ + to end on a cylinder boundary", + partition, (uInt32)partp->dp_size, (uInt32)adj_size); + partp->dp_size = adj_size; + } + if (partp->dp_size == 0) { + warnx("ERROR line %d: size of partition %d is zero", + current_line_number, partition); + break; + } + + dos(partp); + status = 1; + break; + } + return (status); +} + + +static int +process_active(CMD *command) +{ + int status = 0, partition, i; + struct dos_partition *partp; + + while (1) { + active_processed = 1; + if (command->n_args != 1) { + warnx("ERROR line %d: incorrect number of active args", + current_line_number); + status = 0; + break; + } + partition = command->args[0].arg_val; + if (partition < 1 || partition > 4) { + warnx("ERROR line %d: invalid partition number %d", + current_line_number, partition); + break; + } + /* + * Reset active partition + */ + partp = ((struct dos_partition *) &mboot.parts); + for (i = 0; i < NDOSPART; i++) + partp[i].dp_flag = 0; + partp[partition-1].dp_flag = ACTIVE; + + status = 1; + break; + } + return (status); +} + + +static int +process_line(char *line) +{ + CMD command; + int status = 1; + + while (1) { + parse_config_line(line, &command); + switch (command.cmd) { + case 0: + /* + * Comment or blank line + */ + break; + case 'g': + /* + * Set geometry + */ + status = process_geometry(&command); + break; + case 'p': + status = process_partition(&command); + break; + case 'a': + status = process_active(&command); + break; + default: + status = 0; + break; + } + break; + } + return (status); +} + + +static int +read_config(char *config_file) +{ + FILE *fp = NULL; + int status = 1; + char buf[1010]; + + while (1) { + if (strcmp(config_file, "-") != 0) { + /* + * We're not reading from stdin + */ + if ((fp = fopen(config_file, "r")) == NULL) { + status = 0; + break; + } + } else { + fp = stdin; + } + current_line_number = 0; + while (!feof(fp)) { + if (fgets(buf, sizeof(buf), fp) == NULL) + break; + ++current_line_number; + status = process_line(buf); + if (status == 0) + break; + } + break; + } + if (fp) { + /* + * It doesn't matter if we're reading from stdin, as we've reached EOF + */ + fclose(fp); + } + return (status); +} + + +static void +reset_boot(void) +{ + int i; + struct dos_partition *partp; + + init_boot(); + for (i = 0; i < 4; ++i) { + partp = ((struct dos_partition *) &mboot.parts) + i; + bzero((char *)partp, sizeof (struct dos_partition)); + } +} + +static int +sanitize_partition(struct dos_partition *partp) +{ + uInt32 prev_head_boundary, prev_cyl_boundary; + uInt32 max_end, size, start; + + start = partp->dp_start; + size = partp->dp_size; + max_end = start + size; + /* Only allow a zero size if the partition is being marked unused. */ + if (size == 0) { + if (start == 0 && partp->dp_typ == 0) + return (1); + warnx("ERROR: size of partition is zero"); + return (0); + } + /* Return if no adjustment is necessary. */ + if (start % dos_sectors == 0 && (start + size) % dos_sectors == 0) + return (1); + + if (start == 0) { + warnx("WARNING: partition overlaps with partition table"); + if (ok("Correct this automatically?")) + start = dos_sectors; + } + if (start % dos_sectors != 0) + warnx("WARNING: partition does not start on a head boundary"); + if ((start +size) % dos_sectors != 0) + warnx("WARNING: partition does not end on a cylinder boundary"); + warnx("WARNING: this may confuse the BIOS or some operating systems"); + if (!ok("Correct this automatically?")) + return (1); + + /* + * Adjust start upwards, if necessary, to fall on a head boundary. + */ + if (start % dos_sectors != 0) { + prev_head_boundary = start / dos_sectors * dos_sectors; + if (max_end < dos_sectors || + prev_head_boundary >= max_end - dos_sectors) { + /* + * Can't go past end of partition + */ + warnx( + "ERROR: unable to adjust start of partition to fall on a head boundary"); + return (0); + } + start = prev_head_boundary + dos_sectors; + } + + /* + * Adjust size downwards, if necessary, to fall on a cylinder + * boundary. + */ + prev_cyl_boundary = ((start + size) / dos_cylsecs) * dos_cylsecs; + if (prev_cyl_boundary > start) + size = prev_cyl_boundary - start; + else { + warnx("ERROR: could not adjust partition to start on a head boundary\n\ + and end on a cylinder boundary."); + return (0); + } + + /* Finally, commit any changes to partp and return. */ + if (start != partp->dp_start) { + warnx("WARNING: adjusting start offset of partition to %u", + (uInt32)start); + partp->dp_start = start; + } + if (size != partp->dp_size) { + warnx("WARNING: adjusting size of partition to %u", (uInt32)size); + partp->dp_size = size; + } + + return (1); +} + +/* + * Try figuring out the root device's canonical disk name. + * The following choices are considered: + * /dev/ad0s1a => /dev/ad0 + * /dev/da0a => /dev/da0 + * /dev/vinum/root => /dev/vinum/root + */ +static char * +get_rootdisk(void) +{ + struct statfs rootfs; + regex_t re; +#define NMATCHES 2 + regmatch_t rm[NMATCHES]; + char *s; + int rv; + + if (statfs("/", &rootfs) == -1) + err(1, "statfs(\"/\")"); + + if ((rv = regcomp(&re, "^(/dev/[a-z]+[0-9]+)([sp][0-9]+)?[a-h]?$", + REG_EXTENDED)) != 0) + errx(1, "regcomp() failed (%d)", rv); + if ((rv = regexec(&re, rootfs.f_mntfromname, NMATCHES, rm, 0)) != 0) + errx(1, +"mounted root fs resource doesn't match expectations (regexec returned %d)", + rv); + if ((s = malloc(rm[1].rm_eo - rm[1].rm_so + 1)) == NULL) + errx(1, "out of memory"); + memcpy(s, rootfs.f_mntfromname + rm[1].rm_so, + rm[1].rm_eo - rm[1].rm_so); + s[rm[1].rm_eo - rm[1].rm_so] = 0; + + return s; +} diff --git a/src/bin/init/Makefile b/src/bin/init/Makefile new file mode 100644 index 0000000..0a76efe --- /dev/null +++ b/src/bin/init/Makefile @@ -0,0 +1,39 @@ +# $Id$ +# Application Makefile (C) 2002 The UbixOS Project + +# Include Global 'Source' Options +include ../../Makefile.inc +include ../Makefile.inc + +#Binary File Name +BINARY = init + +#Objects +OBJS = main.o + +#Startup File +STARTUP = ../../lib/ubix/startup.o + +# Link The Binary +$(BINARY) : $(OBJS) + $(CC) -nostdlib -o $@ $(STARTUP) $(LIBRARIES) $(OBJS) + +# 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 ${CFLAGS} $@ $< + +# Clean Up The junk +clean: + $(REMOVE) $(OBJS) $(BINARY) diff --git a/src/bin/init/main.c b/src/bin/init/main.c new file mode 100644 index 0000000..9cda1e7 --- /dev/null +++ b/src/bin/init/main.c @@ -0,0 +1,56 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#include +#include +#include +#include +#include + +int main(int argc,char **argv) { + int i=0; + startSDE(); + if (getpid() != 1) { + printf("Sorry This Program Must Be Started By The Kernel!!!!\n"); +// exit(1); + } + if ((getuid() != 0) && (getgid() != 0)) { + printf("Sorry The System Must Start This As Root.\n"); + exit(1); + } + printf("Initializing System.\n"); + startup: + i = fork(); + if (0 == i) { + printf("Starting Login Daemon.\n"); + exec("login@sys",0x0,0x0); + printf("Error Starting System\n"); + exit(0); + } + else { + while (pidStatus(i) > 0x0) + sched_yield(); + goto startup; + } + return(0); + } diff --git a/src/bin/launcher/Makefile b/src/bin/launcher/Makefile new file mode 100644 index 0000000..17c0346 --- /dev/null +++ b/src/bin/launcher/Makefile @@ -0,0 +1,55 @@ +# $Id$ +# Application Makefile (C) 2002 The UbixOS Project + +# Include Global 'Source' Options +include ../../Makefile.inc +include ../Makefile.inc + +#Compiler Flags +CFLAGS = -DNOBOOL -fno-builtin -fno-rtti -fno-exceptions + +#Linker +LD = ld + +#Binary File Name +BINARY = launcher + +#Delete Program +REMOVE = rm -f + +#Objects +OBJS = launcher.o + +#Libraries +LIBRARIES2 = ../../lib/objgfx40/*.o ../../lib/libcpp/*.o ../../lib/views/sunlight/*.o + +#Include +INCLUDE = -I../../lib/libc/include -I../../lib/libcpp/include -I../../lib/objgfx40 + +#Startup File +STARTUP = ../../lib/ubix/startup.o + +# Link The Binary +$(BINARY) : $(OBJS) + #$(CC) -nostdlib -o $@ $(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) $(BINARY) diff --git a/src/bin/launcher/launcher.cpp b/src/bin/launcher/launcher.cpp new file mode 100644 index 0000000..f3fb855 --- /dev/null +++ b/src/bin/launcher/launcher.cpp @@ -0,0 +1,4 @@ + +int main(void) { + return 0; +} diff --git a/src/bin/login/Makefile b/src/bin/login/Makefile new file mode 100644 index 0000000..5543379 --- /dev/null +++ b/src/bin/login/Makefile @@ -0,0 +1,39 @@ +# $Id$ +# Application Makefile (C) 2002 The UbixOS Project + +# Include Global 'Source' Options +include ../../Makefile.inc +include ../Makefile.inc + +#Binary File Name +BINARY = login + +#Objects +OBJS = main.o + +#Startup File +STARTUP = ../../lib/ubix/startup.o + +# Link The Binary +$(BINARY) : $(OBJS) + $(CC) -nostdlib -o $@ $(STARTUP) $(LIBRARIES) $(OBJS) + +# 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) $(BINARY) diff --git a/src/bin/login/main.c b/src/bin/login/main.c new file mode 100644 index 0000000..07e838e --- /dev/null +++ b/src/bin/login/main.c @@ -0,0 +1,124 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#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() != 0) && (getgid() != 0)) { + printf("This Application Must Be Run As Root.\n"); + exit(1); + } + data = (struct passwd *)malloc(4096); + if (!(fd = fopen("userdb@sys","r"))) { + printf("Error Opening File"); + memcpy(data[0].username,"root",4); + memcpy(data[0].password,"user",4); + memcpy(data[0].shell,"shell@sys", 10); + } + else { + fread(data,4096,1,fd); + fclose(fd); + } + data2 = (char *)malloc(256); + 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 == memcmp(userName,data[i].username,4)) { + if (0x0 == memcmp(passWord,data[i].password,4)) { + shellPid = fork(); + if (!shellPid) { + if (setuid(data[i].uid) != 0x0) { + printf("Set UID Failed\n"); + } + if (setgid(data[i].gid) != 0x0) { + printf("Set GID Failed\n"); + } + if ((fd = fopen("motd@sys","r")) == 0x0) { + printf("No MOTD"); + } + else { + fread(data2,256,1,fd); + printf("%s\n",data2); + } + fclose(fd); + chdir(data[i].path); + exec(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; + exit(1); + } + diff --git a/src/bin/ls/Makefile b/src/bin/ls/Makefile new file mode 100644 index 0000000..eb1967a --- /dev/null +++ b/src/bin/ls/Makefile @@ -0,0 +1,48 @@ +# $Id$ +# Application Makefile (C) 2002 The UbixOS Project + +# Include Global 'Source' Options +include ../../Makefile.inc +include ../Makefile.inc + +#Compiler Flags +CFLAGS = -I../../include -fno-builtin + +#Linker +LD = ld + +#Binary File Name +BINARY = ls + +#Delete Program +REMOVE = rm -f + +#Objects +OBJS = main.o + +#Startup File +STARTUP = ../../lib/ubix/startup.o + +# Link The Binary +$(BINARY) : $(OBJS) + $(CC) -nostdlib -o $@ $(STARTUP) $(LIBRARIES) $(OBJS) + +# 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) $(BINARY) diff --git a/src/bin/ls/main.c b/src/bin/ls/main.c new file mode 100644 index 0000000..c0f9111 --- /dev/null +++ b/src/bin/ls/main.c @@ -0,0 +1,122 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#include +#include + +#define permRead 0x8 +#define permWrite 0x4 +#define permExecute 0x2 +#define permHidden 0x1 + + +//UbixFS Directory Entry +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 + }; + +#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 = (char *)malloc(256); + char *permsData = (char *)malloc(13); + FILE *fd; + struct directoryEntry *dirEntry = 0x0; + if (argv[1] == 0x0) { + if ((fd = fopen(":","rb")) == 0x0) { + printf("Error: Reading Directory\n"); + exit(1); + } + } + else { + 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); + if (!fclose(fd)) { + printf("Error Closing Directory\n"); + } + pwd[0] = '/'; + for (i=0;i<(fd->size/sizeof(struct directoryEntry));i++) { + 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: + } + } + /* + for (i=0;i +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/src/bin/shell/Makefile b/src/bin/shell/Makefile new file mode 100644 index 0000000..17f11a7 --- /dev/null +++ b/src/bin/shell/Makefile @@ -0,0 +1,48 @@ +# $Id$ +# Application Makefile (C) 2002 The UbixOS Project + +# Include Global 'Source' Options +include ../../Makefile.inc +include ../Makefile.inc + +#Compiler Flags +CFLAGS = -I../../include -fno-builtin + +#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 + +#Startup File +STARTUP = ../../lib/ubix/startup.o + +# Link The Binary +$(BINARY) : $(OBJS) + $(CC) -nostdlib -o $@ $(STARTUP) $(LIBRARIES) $(OBJS) + +# 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) $(BINARY) diff --git a/src/bin/shell/commands.c b/src/bin/shell/commands.c new file mode 100644 index 0000000..a4c89f1 --- /dev/null +++ b/src/bin/shell/commands.c @@ -0,0 +1,90 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#include +#include +#include +#include +#include +#include "shell.h" + +int commands(inputBuffer *data) { + int cPid = 0x0,i = 0x0; + 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) { + while (1) { + cPid = fork(); + printf("Pid: [%i]\n",cPid); + if (!cPid) { + exec("test",data->argc,data->argv); + exit(1); + } + else { + while (pidStatus(cPid)); + } + + } + } + else if (memcmp(data->args->arg,"echo",4) == 0) { + for (i=1;iargc;i++) { + printf("%s ",data->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 (data->argv[1]) { + chdir(data->argv[1]); + getcwd(cwd,1024); + } + } + else if (memcmp(data->args->arg,"unlink",6) == 0) { + if (data->argv[1]) { + unlink(data->argv[1]); + } + } + /* + else if (memcmp(data->args->arg,"mkdir",5) == 0x0) { + if (data->argv[1]) { + mkdir(data->argv[1]); + } + } + */ + else { + return(0); + } + return(1); + } diff --git a/src/bin/shell/error.c b/src/bin/shell/error.c new file mode 100644 index 0000000..7b97f1b --- /dev/null +++ b/src/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$ + +**************************************************************************************/ + +#include +#include + +void error(int errorCode,char *errorMsg) { + printf("ERROR: #%i Message: %s\n", errorCode, errorMsg); + exit(errorCode); + } diff --git a/src/bin/shell/exec.c b/src/bin/shell/exec.c new file mode 100644 index 0000000..c583f5b --- /dev/null +++ b/src/bin/shell/exec.c @@ -0,0 +1,46 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#include +#include +#include +#include +#include "shell.h" + +void sched_yield(); + +void execProgram(inputBuffer *data) { + int cPid = 0x0; + cPid = fork(); + if (!cPid) { + exec(data->argv[0],data->argc,data->argv); + printf("%s: Command Not Found.\n",data->argv[0]); + exit(1); + } + else { + if (data->bg == 0x0) { + while (pidStatus(cPid) > 0) + sched_yield(); + } + } + } diff --git a/src/bin/shell/input.c b/src/bin/shell/input.c new file mode 100644 index 0000000..da3815e --- /dev/null +++ b/src/bin/shell/input.c @@ -0,0 +1,66 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#include +#include +#include +#include "shell.h" + +void parseInput(inputBuffer *buffer,char *data) { + int i = 0x0; + char *arg = 0x0; + struct argsStruct *tmpArgs = 0x0; + + while (data[0] == ' ') { + data++; + } + buffer->args = (struct argsStruct *)malloc(sizeof(struct argsStruct)); + //printf("args: [0x%X]\n",buffer->args); + tmpArgs = buffer->args; + while(data != 0x0) { + arg = strtok(data," "); + data = strtok(NULL,"\n"); + if (arg[0] == '&') { + buffer->bg = 0x1; + } + else { + buffer->argc++; + tmpArgs->arg = arg; + if (data != 0x0) { + tmpArgs->next = (struct argsStruct *)malloc(sizeof(struct argsStruct)); + //printf("args: [0x%X]\n",tmpArgs->next); + } + tmpArgs = tmpArgs->next; + } + } + buffer->argv = (char **)malloc(4*buffer->argc); + //printf("argv: [0x%X]\n",buffer->argv); + tmpArgs = buffer->args; + for (i=0;iargc;i++) { + buffer->argv[i] = tmpArgs->arg; + tmpArgs = tmpArgs->next; + } + } + +void freeArgs(inputBuffer *ptr) { + } diff --git a/src/bin/shell/main.c b/src/bin/shell/main.c new file mode 100644 index 0000000..01a980f --- /dev/null +++ b/src/bin/shell/main.c @@ -0,0 +1,61 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#include +#include +#include +#include +#include +#include "shell.h" + +char *machine = 0x0; +char *cwd = 0x0; +char *cwc = 0x0; + +int main() { + unsigned char buffer[256],*data; + inputBuffer *inBuf = (inputBuffer *)malloc(sizeof(inputBuffer)); + + machine = (char *)malloc(8); + cwd = (char *)malloc(1024); + cwc = (char *)malloc(3); + + sprintf(machine,"uBixCube"); + getcwd(cwd,1024); + sprintf(cwc,"sys"); + + while (1) { + printf("%s:%s@%s> ",machine,cwd,cwc); + gets((char *)&buffer); + data = (uInt8 *)&buffer; + parseInput(inBuf,data); + if (inBuf->args->arg != 0x0) { + if (!commands(inBuf)) execProgram(inBuf); + } + freeArgs(inBuf); + inBuf->argc = 0x0; + inBuf->args = 0x0; + inBuf->bg = 0x0; + } + exit(0); + } diff --git a/src/bin/shell/shell.h b/src/bin/shell/shell.h new file mode 100644 index 0000000..47f0a8a --- /dev/null +++ b/src/bin/shell/shell.h @@ -0,0 +1,19 @@ +#include + +extern char *cwd; + +struct argsStruct { + struct argsStruct *next; + char *arg; + }; + +typedef struct { + int argc; + char **argv; + uInt8 bg; + struct argsStruct *args; + } inputBuffer; + +void parseInput(inputBuffer *,char *); +int commands(inputBuffer *); +void execProgram(inputBuffer *); diff --git a/src/bin/views/Makefile b/src/bin/views/Makefile new file mode 100644 index 0000000..ba3707e --- /dev/null +++ b/src/bin/views/Makefile @@ -0,0 +1,51 @@ +# $Id$ +# Application Makefile (C) 2002 The UbixOS Project + +# Include Global 'Source' Options +include ../../Makefile.inc + +#Compiler Flags +CFLAGS = -I../../lib/libc/include -fno-builtin + +#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 + +#Startup File +STARTUP = ../../lib/ubix/startup.o + +# Link The Binary +$(BINARY) : $(OBJS) + $(CC) -nostdlib -o $@ $(STARTUP) $(LIBRARIES) $(OBJS) + +# 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) $(BINARY) diff --git a/src/bin/views/main.c b/src/bin/views/main.c new file mode 100644 index 0000000..e86deaa --- /dev/null +++ b/src/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$ + +**************************************************************************************/ + +#include +#include + +int main(int argc,char **argv) { + return(0); + } + +/*** + END + ***/ + diff --git a/src/include/ctype.h b/src/include/ctype.h new file mode 100644 index 0000000..ece6382 --- /dev/null +++ b/src/include/ctype.h @@ -0,0 +1,228 @@ +/* + * 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. + * + * @(#)ctype.h 8.4 (Berkeley) 1/21/94 + * $FreeBSD: src/include/ctype.h,v 1.24 2002/09/09 05:38:05 mike Exp $ + */ + +#ifndef _CTYPE_H_ +#define _CTYPE_H_ + +#include +#include + +#define _CTYPE_A 0x00000100L /* Alpha */ +#define _CTYPE_C 0x00000200L /* Control */ +#define _CTYPE_D 0x00000400L /* Digit */ +#define _CTYPE_G 0x00000800L /* Graph */ +#define _CTYPE_L 0x00001000L /* Lower */ +#define _CTYPE_P 0x00002000L /* Punct */ +#define _CTYPE_S 0x00004000L /* Space */ +#define _CTYPE_U 0x00008000L /* Upper */ +#define _CTYPE_X 0x00010000L /* X digit */ +#define _CTYPE_B 0x00020000L /* Blank */ +#define _CTYPE_R 0x00040000L /* Print */ +#define _CTYPE_I 0x00080000L /* Ideogram */ +#define _CTYPE_T 0x00100000L /* Special */ +#define _CTYPE_Q 0x00200000L /* Phonogram */ +#define _CTYPE_SW0 0x20000000L /* 0 width character */ +#define _CTYPE_SW1 0x40000000L /* 1 width character */ +#define _CTYPE_SW2 0x80000000L /* 2 width character */ +#define _CTYPE_SW3 0xc0000000L /* 3 width character */ + +__BEGIN_DECLS +int isalnum(int); +int isalpha(int); +int iscntrl(int); +int isdigit(int); +int isgraph(int); +int islower(int); +int isprint(int); +int ispunct(int); +int isspace(int); +int isupper(int); +int isxdigit(int); +int tolower(int); +int toupper(int); + +#if __XSI_VISIBLE +int _tolower(int); +int _toupper(int); +int isascii(int); +int toascii(int); +#endif + +#if __BSD_VISIBLE +int digittoint(int); +int isblank(int); +int ishexnumber(int); +int isideogram(int); +int isnumber(int); +int isphonogram(int); +int isrune(int); +int isspecial(int); +#endif +__END_DECLS + +#define isalnum(c) __istype((c), _CTYPE_A|_CTYPE_D) +#define isalpha(c) __istype((c), _CTYPE_A) +#define iscntrl(c) __istype((c), _CTYPE_C) +#define isdigit(c) __isctype((c), _CTYPE_D) /* ANSI -- locale independent */ +#define isgraph(c) __istype((c), _CTYPE_G) +#define islower(c) __istype((c), _CTYPE_L) +#define isprint(c) __istype((c), _CTYPE_R) +#define ispunct(c) __istype((c), _CTYPE_P) +#define isspace(c) __istype((c), _CTYPE_S) +#define isupper(c) __istype((c), _CTYPE_U) +#define isxdigit(c) __isctype((c), _CTYPE_X) /* ANSI -- locale independent */ +#define tolower(c) __tolower(c) +#define toupper(c) __toupper(c) + +#if __XSI_VISIBLE +/* + * POSIX.1-2001 specifies _tolower() and _toupper() to be macros equivalent to + * tolower() and toupper() respectively, minus extra checking to ensure that + * the argument is a lower or uppercase letter respectively. We've chosen to + * implement these macros with the same error checking as tolower() and + * toupper() since this doesn't violate the specification itself, only its + * intent. We purposely leave _tolower() and _toupper() undocumented to + * discourage their use. + * + * XXX isascii() and toascii() should similarly be undocumented. + */ +#define _tolower(c) __tolower(c) +#define _toupper(c) __toupper(c) +#define isascii(c) (((c) & ~0x7F) == 0) +#define toascii(c) ((c) & 0x7F) +#endif + +#if __BSD_VISIBLE +#define digittoint(c) __maskrune((c), 0xFF) +#define isblank(c) __istype((c), _CTYPE_B) +#define ishexnumber(c) __istype((c), _CTYPE_X) +#define isideogram(c) __istype((c), _CTYPE_I) +#define isnumber(c) __istype((c), _CTYPE_D) +#define isphonogram(c) __istype((c), _CTYPE_Q) +#define isrune(c) __istype((c), 0xFFFFFF00L) +#define isspecial(c) __istype((c), _CTYPE_T) +#endif + +/* See comments in about __ct_rune_t. */ +__BEGIN_DECLS +unsigned long ___runetype(__ct_rune_t); +__ct_rune_t ___tolower(__ct_rune_t); +__ct_rune_t ___toupper(__ct_rune_t); +__END_DECLS + +/* + * _EXTERNALIZE_CTYPE_INLINES_ is defined in locale/nomacros.c to tell us + * to generate code for extern versions of all our inline functions. + */ +#ifdef _EXTERNALIZE_CTYPE_INLINES_ +#define _USE_CTYPE_INLINE_ +#define static +#define __inline +#endif + +/* + * brings namespace pollution (struct member names). This prevents + * us from using the inline optimizations in the more strict __POSIX_VISIBLE and + * __XSI_VISIBLE namespaces. To fix this properly would require that we rename + * member names of long-standing structs, or something equally evil. + */ +#if !__BSD_VISIBLE && !defined(_USE_CTYPE_INLINE_) && \ + !defined(_DONT_USE_CTYPE_INLINE_) +#define _DONT_USE_CTYPE_INLINE_ +#endif + +/* + * Use inline functions if we are allowed to and the compiler supports them. + */ +#if !defined(_DONT_USE_CTYPE_INLINE_) && \ + (defined(_USE_CTYPE_INLINE_) || defined(__GNUC__) || defined(__cplusplus)) + +#include + +static __inline int +__maskrune(__ct_rune_t _c, unsigned long _f) +{ + return ((_c < 0 || _c >= _CACHED_RUNES) ? ___runetype(_c) : + _CurrentRuneLocale->runetype[_c]) & _f; +} + +static __inline int +__istype(__ct_rune_t _c, unsigned long _f) +{ + return (!!__maskrune(_c, _f)); +} + +static __inline int +__isctype(__ct_rune_t _c, unsigned long _f) +{ + return (_c < 0 || _c >= _CACHED_RUNES) ? 0 : + !!(_DefaultRuneLocale.runetype[_c] & _f); +} + +static __inline __ct_rune_t +__toupper(__ct_rune_t _c) +{ + return (_c < 0 || _c >= _CACHED_RUNES) ? ___toupper(_c) : + _CurrentRuneLocale->mapupper[_c]; +} + +static __inline __ct_rune_t +__tolower(__ct_rune_t _c) +{ + return (_c < 0 || _c >= _CACHED_RUNES) ? ___tolower(_c) : + _CurrentRuneLocale->maplower[_c]; +} + +#else /* not using inlines */ + +__BEGIN_DECLS +int __maskrune(__ct_rune_t, unsigned long); +int __istype(__ct_rune_t, unsigned long); +int __isctype(__ct_rune_t, unsigned long); +__ct_rune_t __toupper(__ct_rune_t); +__ct_rune_t __tolower(__ct_rune_t); +__END_DECLS +#endif /* using inlines */ + +#endif /* !_CTYPE_H_ */ diff --git a/src/include/ctypes.h b/src/include/ctypes.h new file mode 100644 index 0000000..b817f43 --- /dev/null +++ b/src/include/ctypes.h @@ -0,0 +1,25 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +int toupper(int c); +int tolower(int c); \ No newline at end of file diff --git a/src/include/err.h b/src/include/err.h new file mode 100644 index 0000000..a3c04cf --- /dev/null +++ b/src/include/err.h @@ -0,0 +1,68 @@ +/*- + * Copyright (c) 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * @(#)err.h 8.1 (Berkeley) 6/2/93 + * $FreeBSD: src/include/err.h,v 1.11 2002/08/21 16:19:55 mike Exp $ + */ + +#ifndef _ERR_H_ +#define _ERR_H_ + +/* + * Don't use va_list in the err/warn prototypes. Va_list is typedef'd in two + * places ( and ), so if we include one + * of them here we may collide with the utility's includes. It's unreasonable + * for utilities to have to include one of them to include err.h, so we get + * __va_list from and use it. + */ +#include +#include + +__BEGIN_DECLS +void err(int, const char *, ...) __dead2 __printf0like(2, 3); +void verr(int, const char *, __va_list) __dead2 __printf0like(2, 0); +void errc(int, int, const char *, ...) __dead2 __printf0like(3, 4); +void verrc(int, int, const char *, __va_list) __dead2 + __printf0like(3, 0); +void errx(int, const char *, ...) __dead2 __printf0like(2, 3); +void verrx(int, const char *, __va_list) __dead2 __printf0like(2, 0); +void warn(const char *, ...) __printf0like(1, 2); +void vwarn(const char *, __va_list) __printf0like(1, 0); +void warnc(int, const char *, ...) __printf0like(2, 3); +void vwarnc(int, const char *, __va_list) __printf0like(2, 0); +void warnx(const char *, ...) __printflike(1, 2); +void vwarnx(const char *, __va_list) __printflike(1, 0); +void err_set_file(void *); +void err_set_exit(void (*)(int)); +__END_DECLS + +#endif /* !_ERR_H_ */ diff --git a/src/include/errno.h b/src/include/errno.h new file mode 100644 index 0000000..524b156 --- /dev/null +++ b/src/include/errno.h @@ -0,0 +1,186 @@ +/* + * Copyright (c) 1982, 1986, 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. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * @(#)errno.h 8.5 (Berkeley) 1/21/94 + * $FreeBSD: src/sys/sys/errno.h,v 1.25 2002/10/07 06:25:23 phk Exp $ + */ + +#ifndef _SYS_ERRNO_H_ +#define _SYS_ERRNO_H_ + +#ifndef _KERNEL +#include +__BEGIN_DECLS +int * __error(void); +__END_DECLS +#define errno (* __error()) +#endif + +#define EPERM 1 /* Operation not permitted */ +#define ENOENT 2 /* No such file or directory */ +#define ESRCH 3 /* No such process */ +#define EINTR 4 /* Interrupted system call */ +#define EIO 5 /* Input/output error */ +#define ENXIO 6 /* Device not configured */ +#define E2BIG 7 /* Argument list too long */ +#define ENOEXEC 8 /* Exec format error */ +#define EBADF 9 /* Bad file descriptor */ +#define ECHILD 10 /* No child processes */ +#define EDEADLK 11 /* Resource deadlock avoided */ + /* 11 was EAGAIN */ +#define ENOMEM 12 /* Cannot allocate memory */ +#define EACCES 13 /* Permission denied */ +#define EFAULT 14 /* Bad address */ +#ifndef _POSIX_SOURCE +#define ENOTBLK 15 /* Block device required */ +#endif +#define EBUSY 16 /* Device busy */ +#define EEXIST 17 /* File exists */ +#define EXDEV 18 /* Cross-device link */ +#define ENODEV 19 /* Operation not supported by device */ +#define ENOTDIR 20 /* Not a directory */ +#define EISDIR 21 /* Is a directory */ +#define EINVAL 22 /* Invalid argument */ +#define ENFILE 23 /* Too many open files in system */ +#define EMFILE 24 /* Too many open files */ +#define ENOTTY 25 /* Inappropriate ioctl for device */ +#ifndef _POSIX_SOURCE +#define ETXTBSY 26 /* Text file busy */ +#endif +#define EFBIG 27 /* File too large */ +#define ENOSPC 28 /* No space left on device */ +#define ESPIPE 29 /* Illegal seek */ +#define EROFS 30 /* Read-only filesystem */ +#define EMLINK 31 /* Too many links */ +#define EPIPE 32 /* Broken pipe */ + +/* math software */ +#define EDOM 33 /* Numerical argument out of domain */ +#define ERANGE 34 /* Result too large */ + +/* non-blocking and interrupt i/o */ +#define EAGAIN 35 /* Resource temporarily unavailable */ +#ifndef _POSIX_SOURCE +#define EWOULDBLOCK EAGAIN /* Operation would block */ +#define EINPROGRESS 36 /* Operation now in progress */ +#define EALREADY 37 /* Operation already in progress */ + +/* ipc/network software -- argument errors */ +#define ENOTSOCK 38 /* Socket operation on non-socket */ +#define EDESTADDRREQ 39 /* Destination address required */ +#define EMSGSIZE 40 /* Message too long */ +#define EPROTOTYPE 41 /* Protocol wrong type for socket */ +#define ENOPROTOOPT 42 /* Protocol not available */ +#define EPROTONOSUPPORT 43 /* Protocol not supported */ +#define ESOCKTNOSUPPORT 44 /* Socket type not supported */ +#define EOPNOTSUPP 45 /* Operation not supported */ +#define ENOTSUP EOPNOTSUPP /* Operation not supported */ +#define EPFNOSUPPORT 46 /* Protocol family not supported */ +#define EAFNOSUPPORT 47 /* Address family not supported by protocol family */ +#define EADDRINUSE 48 /* Address already in use */ +#define EADDRNOTAVAIL 49 /* Can't assign requested address */ + +/* ipc/network software -- operational errors */ +#define ENETDOWN 50 /* Network is down */ +#define ENETUNREACH 51 /* Network is unreachable */ +#define ENETRESET 52 /* Network dropped connection on reset */ +#define ECONNABORTED 53 /* Software caused connection abort */ +#define ECONNRESET 54 /* Connection reset by peer */ +#define ENOBUFS 55 /* No buffer space available */ +#define EISCONN 56 /* Socket is already connected */ +#define ENOTCONN 57 /* Socket is not connected */ +#define ESHUTDOWN 58 /* Can't send after socket shutdown */ +#define ETOOMANYREFS 59 /* Too many references: can't splice */ +#define ETIMEDOUT 60 /* Operation timed out */ +#define ECONNREFUSED 61 /* Connection refused */ + +#define ELOOP 62 /* Too many levels of symbolic links */ +#endif /* _POSIX_SOURCE */ +#define ENAMETOOLONG 63 /* File name too long */ + +/* should be rearranged */ +#ifndef _POSIX_SOURCE +#define EHOSTDOWN 64 /* Host is down */ +#define EHOSTUNREACH 65 /* No route to host */ +#endif /* _POSIX_SOURCE */ +#define ENOTEMPTY 66 /* Directory not empty */ + +/* quotas & mush */ +#ifndef _POSIX_SOURCE +#define EPROCLIM 67 /* Too many processes */ +#define EUSERS 68 /* Too many users */ +#define EDQUOT 69 /* Disc quota exceeded */ + +/* Network File System */ +#define ESTALE 70 /* Stale NFS file handle */ +#define EREMOTE 71 /* Too many levels of remote in path */ +#define EBADRPC 72 /* RPC struct is bad */ +#define ERPCMISMATCH 73 /* RPC version wrong */ +#define EPROGUNAVAIL 74 /* RPC prog. not avail */ +#define EPROGMISMATCH 75 /* Program version wrong */ +#define EPROCUNAVAIL 76 /* Bad procedure for program */ +#endif /* _POSIX_SOURCE */ + +#define ENOLCK 77 /* No locks available */ +#define ENOSYS 78 /* Function not implemented */ + +#ifndef _POSIX_SOURCE +#define EFTYPE 79 /* Inappropriate file type or format */ +#define EAUTH 80 /* Authentication error */ +#define ENEEDAUTH 81 /* Need authenticator */ +#define EIDRM 82 /* Identifier removed */ +#define ENOMSG 83 /* No message of desired type */ +#define EOVERFLOW 84 /* Value too large to be stored in data type */ +#define ECANCELED 85 /* Operation canceled */ +#define EILSEQ 86 /* Illegal byte sequence */ +#define ENOATTR 87 /* Attribute not found */ + +#define EDOOFUS 88 /* Programming error */ + +#define ELAST 88 /* Must be equal largest errno */ + +#endif /* _POSIX_SOURCE */ + +#ifdef _KERNEL +/* pseudo-errors returned inside kernel to modify return to process */ +#define ERESTART (-1) /* restart syscall */ +#define EJUSTRETURN (-2) /* don't modify regs, just return */ +#define ENOIOCTL (-3) /* ioctl not handled by this layer */ +#define EDIRIOCTL (-4) /* do direct ioctl in GEOM */ +#endif + +#endif diff --git a/src/include/fcntl.h b/src/include/fcntl.h new file mode 100644 index 0000000..520391c --- /dev/null +++ b/src/include/fcntl.h @@ -0,0 +1,233 @@ +/*- + * Copyright (c) 1983, 1990, 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. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * @(#)fcntl.h 8.3 (Berkeley) 1/21/94 + * $FreeBSD: src/sys/sys/fcntl.h,v 1.15 2003/06/20 07:59:59 phk Exp $ + */ + +#ifndef _SYS_FCNTL_H_ +#define _SYS_FCNTL_H_ + +/* + * This file includes the definitions for open and fcntl + * described by POSIX for ; it also includes + * related kernel definitions. + */ + +#include +#include + +#ifndef _MODE_T_DECLARED +typedef __mode_t mode_t; +#define _MODE_T_DECLARED +#endif + +#ifndef _OFF_T_DECLARED +typedef __off_t off_t; +#define _OFF_T_DECLARED +#endif + +#ifndef _PID_T_DECLARED +typedef __pid_t pid_t; +#define _PID_T_DECLARED +#endif + +/* + * File status flags: these are used by open(2), fcntl(2). + * They are also used (indirectly) in the kernel file structure f_flags, + * which is a superset of the open/fcntl flags. Open flags and f_flags + * are inter-convertible using OFLAGS(fflags) and FFLAGS(oflags). + * Open/fcntl flags begin with O_; kernel-internal flags begin with F. + */ +/* open-only flags */ +#define O_RDONLY 0x0000 /* open for reading only */ +#define O_WRONLY 0x0001 /* open for writing only */ +#define O_RDWR 0x0002 /* open for reading and writing */ +#define O_ACCMODE 0x0003 /* mask for above modes */ + +/* + * Kernel encoding of open mode; separate read and write bits that are + * independently testable: 1 greater than the above. + * + * XXX + * FREAD and FWRITE are excluded from the #ifdef _KERNEL so that TIOCFLUSH, + * which was documented to use FREAD/FWRITE, continues to work. + */ +#if __BSD_VISIBLE +#define FREAD 0x0001 +#define FWRITE 0x0002 +#endif +#define O_NONBLOCK 0x0004 /* no delay */ +#define O_APPEND 0x0008 /* set append mode */ +#if __BSD_VISIBLE +#define O_SHLOCK 0x0010 /* open with shared file lock */ +#define O_EXLOCK 0x0020 /* open with exclusive file lock */ +#define O_ASYNC 0x0040 /* signal pgrp when data ready */ +#define O_FSYNC 0x0080 /* synchronous writes */ +#endif +#define O_SYNC 0x0080 /* POSIX synonym for O_FSYNC */ +#if __BSD_VISIBLE +#define O_NOFOLLOW 0x0100 /* don't follow symlinks */ +#endif +#define O_CREAT 0x0200 /* create if nonexistent */ +#define O_TRUNC 0x0400 /* truncate to zero length */ +#define O_EXCL 0x0800 /* error if already exists */ +#ifdef _KERNEL +#define FHASLOCK 0x4000 /* descriptor holds advisory lock */ +#endif + +/* Defined by POSIX 1003.1; BSD default, but must be distinct from O_RDONLY. */ +#define O_NOCTTY 0x8000 /* don't assign controlling terminal */ + +#if __BSD_VISIBLE +/* Attempt to bypass buffer cache */ +#define O_DIRECT 0x00010000 +#endif + +/* + * XXX missing O_DSYNC, O_RSYNC. + */ + +#ifdef _KERNEL +/* convert from open() flags to/from fflags; convert O_RD/WR to FREAD/FWRITE */ +#define FFLAGS(oflags) ((oflags) + 1) +#define OFLAGS(fflags) ((fflags) - 1) + +/* bits to save after open */ +#define FMASK (FREAD|FWRITE|FAPPEND|FASYNC|FFSYNC|FNONBLOCK|O_DIRECT) +/* bits settable by fcntl(F_SETFL, ...) */ +#define FCNTLFLAGS (FAPPEND|FASYNC|FFSYNC|FNONBLOCK|FPOSIXSHM|O_DIRECT) +#endif + +/* + * The O_* flags used to have only F* names, which were used in the kernel + * and by fcntl. We retain the F* names for the kernel f_flag field + * and for backward compatibility for fcntl. These flags are deprecated. + */ +#if __BSD_VISIBLE +#define FAPPEND O_APPEND /* kernel/compat */ +#define FASYNC O_ASYNC /* kernel/compat */ +#define FFSYNC O_FSYNC /* kernel */ +#define FNONBLOCK O_NONBLOCK /* kernel */ +#define FNDELAY O_NONBLOCK /* compat */ +#define O_NDELAY O_NONBLOCK /* compat */ +#endif + +/* + * We are out of bits in f_flag (which is a short). However, + * the flag bits not set in FMASK are only meaningful in the + * initial open syscall. Those bits can thus be given a + * different meaning for fcntl(2). + */ +#if __BSD_VISIBLE + +/* + * Set by shm_open(3) to get automatic MAP_ASYNC behavior + * for POSIX shared memory objects (which are otherwise + * implemented as plain files). + */ +#define FPOSIXSHM O_NOFOLLOW +#endif + +/* + * Constants used for fcntl(2) + */ + +/* command values */ +#define F_DUPFD 0 /* duplicate file descriptor */ +#define F_GETFD 1 /* get file descriptor flags */ +#define F_SETFD 2 /* set file descriptor flags */ +#define F_GETFL 3 /* get file status flags */ +#define F_SETFL 4 /* set file status flags */ +#if __BSD_VISIBLE || __XSI_VISIBLE || __POSIX_VISIBLE >= 200112 +#define F_GETOWN 5 /* get SIGIO/SIGURG proc/pgrp */ +#define F_SETOWN 6 /* set SIGIO/SIGURG proc/pgrp */ +#endif +#define F_GETLK 7 /* get record locking information */ +#define F_SETLK 8 /* set record locking information */ +#define F_SETLKW 9 /* F_SETLK; wait if blocked */ + +/* file descriptor flags (F_GETFD, F_SETFD) */ +#define FD_CLOEXEC 1 /* close-on-exec flag */ + +/* record locking flags (F_GETLK, F_SETLK, F_SETLKW) */ +#define F_RDLCK 1 /* shared or read lock */ +#define F_UNLCK 2 /* unlock */ +#define F_WRLCK 3 /* exclusive or write lock */ +#ifdef _KERNEL +#define F_WAIT 0x010 /* Wait until lock is granted */ +#define F_FLOCK 0x020 /* Use flock(2) semantics for lock */ +#define F_POSIX 0x040 /* Use POSIX semantics for lock */ +#endif + +/* + * Advisory file segment locking data type - + * information passed to system by user + */ +struct flock { + off_t l_start; /* starting offset */ + off_t l_len; /* len = 0 means until end of file */ + pid_t l_pid; /* lock owner */ + short l_type; /* lock type: read/write, etc. */ + short l_whence; /* type of l_start */ +}; + + +#if __BSD_VISIBLE +/* lock operations for flock(2) */ +#define LOCK_SH 0x01 /* shared file lock */ +#define LOCK_EX 0x02 /* exclusive file lock */ +#define LOCK_NB 0x04 /* don't block when locking */ +#define LOCK_UN 0x08 /* unlock file */ +#endif + +/* + * XXX missing posix_fadvise() and posix_fallocate(), and POSIX_FADV_* macros. + */ + +#ifndef _KERNEL +__BEGIN_DECLS +int open(const char *, int, ...); +int creat(const char *, mode_t); +int fcntl(int, int, ...); +#if __BSD_VISIBLE +int flock(int, int); +#endif +__END_DECLS +#endif + +#endif /* !_SYS_FCNTL_H_ */ diff --git a/src/include/limits.h b/src/include/limits.h new file mode 100644 index 0000000..587f01f --- /dev/null +++ b/src/include/limits.h @@ -0,0 +1,134 @@ +/*- + * 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. + * + * @(#)limits.h 8.2 (Berkeley) 1/4/94 + * $FreeBSD: src/include/limits.h,v 1.16 2003/04/29 13:35:58 kan Exp $ + */ + +#ifndef _LIMITS_H_ +#define _LIMITS_H_ + +#include + +#if __POSIX_VISIBLE +#define _POSIX_ARG_MAX 4096 +#define _POSIX_CHILD_MAX 25 +#define _POSIX_LINK_MAX 8 +#define _POSIX_MAX_CANON 255 +#define _POSIX_MAX_INPUT 255 +#define _POSIX_NAME_MAX 14 +#define _POSIX_NGROUPS_MAX 8 +#define _POSIX_OPEN_MAX 20 +#define _POSIX_PATH_MAX 256 +#define _POSIX_PIPE_BUF 512 +#define _POSIX_SSIZE_MAX 32767 +#define _POSIX_STREAM_MAX 8 +#define _POSIX_TZNAME_MAX 6 + +#define BC_BASE_MAX 99 /* max ibase/obase values in bc(1) */ +#define BC_DIM_MAX 2048 /* max array elements in bc(1) */ +#define BC_SCALE_MAX 99 /* max scale value in bc(1) */ +#define BC_STRING_MAX 1000 /* max const string length in bc(1) */ +#define COLL_WEIGHTS_MAX 0 /* max weights for order keyword */ +#define EXPR_NEST_MAX 32 /* max expressions nested in expr(1) */ +#define LINE_MAX 2048 /* max bytes in an input line */ +#define RE_DUP_MAX 255 /* max RE's in interval notation */ + +#define _POSIX2_BC_BASE_MAX 99 +#define _POSIX2_BC_DIM_MAX 2048 +#define _POSIX2_BC_SCALE_MAX 99 +#define _POSIX2_BC_STRING_MAX 1000 +#define _POSIX2_EQUIV_CLASS_MAX 2 +#define _POSIX2_EXPR_NEST_MAX 32 +#define _POSIX2_LINE_MAX 2048 +#define _POSIX2_RE_DUP_MAX 255 +#endif + +#if __POSIX_VISIBLE >= 199309 +#define _POSIX_AIO_LISTIO_MAX 16 +#define _POSIX_AIO_MAX 1 +#define _POSIX_DELAYTIMER_MAX 32 +#define _POSIX_MQ_OPEN_MAX 8 +#define _POSIX_MQ_PRIO_MAX 32 +#define _POSIX_RTSIG_MAX 8 +#define _POSIX_SEM_NSEMS_MAX 256 +#define _POSIX_SEM_VALUE_MAX 32767 +#define _POSIX_SIGQUEUE_MAX 32 +#define _POSIX_TIMER_MAX 32 +#endif + +#if __POSIX_VISIBLE >= 199506 +#define _POSIX_THREAD_DESTRUCTOR_ITERATIONS 4 +#define _POSIX_THREAD_KEYS_MAX 128 +#define _POSIX_THREAD_THREADS_MAX 64 +#endif + +#if __POSIX_VISIBLE >= 200112 +#define _POSIX_HOST_NAME_MAX 255 +#define _POSIX_LOGIN_NAME_MAX 9 +#define _POSIX_SS_REPL_MAX 4 +#define _POSIX_SYMLINK_MAX 255 +#define _POSIX_SYMLOOP_MAX 8 +#define _POSIX_TRACE_EVENT_NAME_MAX 30 +#define _POSIX_TRACE_NAME_MAX 8 +#define _POSIX_TRACE_SYS_MAX 8 +#define _POSIX_TRACE_USER_EVENT_MAX 32 +#define _POSIX_TTY_NAME_MAX 9 +#define _POSIX2_CHARCLASS_NAME_MAX 14 +#define _POSIX2_COLL_WEIGHTS_MAX 2 + +#define _POSIX_RE_DUP_MAX _POSIX2_RE_DUP_MAX +#endif + +#if __XSI_VISIBLE +#define _XOPEN_IOV_MAX 16 +#define _XOPEN_NAME_MAX 255 +#define _XOPEN_PATH_MAX 1024 +#define PASS_MAX 128 /* _PASSWORD_LEN from */ + +#define NL_ARGMAX 99 /* max # of position args for printf */ +#define NL_LANGMAX 31 /* max LANG name length */ +#define NL_MSGMAX 32767 +#define NL_NMAX 1 +#define NL_SETMAX 255 +#define NL_TEXTMAX 2048 +#endif + +#define MB_LEN_MAX 6 /* 31-bit UTF-8 */ + +#include + +#if __POSIX_VISIBLE +#include +#endif + +#endif /* !_LIMITS_H_ */ diff --git a/src/include/machine/_limits.h b/src/include/machine/_limits.h new file mode 100644 index 0000000..5be49ff --- /dev/null +++ b/src/include/machine/_limits.h @@ -0,0 +1,101 @@ +/* + * 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. + * + * @(#)limits.h 8.3 (Berkeley) 1/4/94 + * $FreeBSD: src/sys/i386/include/_limits.h,v 1.25 2003/05/19 20:29:06 kan Exp $ + */ + +#ifndef _MACHINE__LIMITS_H_ +#define _MACHINE__LIMITS_H_ + +/* + * According to ANSI (section 2.2.4.2), the values below must be usable by + * #if preprocessing directives. Additionally, the expression must have the + * same type as would an expression that is an object of the corresponding + * type converted according to the integral promotions. The subtraction for + * INT_MIN, etc., is so the value is not unsigned; e.g., 0x80000000 is an + * unsigned int for 32-bit two's complement ANSI compilers (section 3.1.3.2). + * These numbers are for the default configuration of gcc. They work for + * some other compilers as well, but this should not be depended on. + */ + +#define __CHAR_BIT 8 /* number of bits in a char */ + +#define __SCHAR_MAX 0x7f /* max value for a signed char */ +#define __SCHAR_MIN (-0x7f - 1) /* min value for a signed char */ + +#define __UCHAR_MAX 0xff /* max value for an unsigned char */ + +#define __USHRT_MAX 0xffff /* max value for an unsigned short */ +#define __SHRT_MAX 0x7fff /* max value for a short */ +#define __SHRT_MIN (-0x7fff - 1) /* min value for a short */ + +#define __UINT_MAX 0xffffffffU /* max value for an unsigned int */ +#define __INT_MAX 0x7fffffff /* max value for an int */ +#define __INT_MIN (-0x7fffffff - 1) /* min value for an int */ + +/* Bad hack for gcc configured to give 64-bit longs. */ +#ifdef _LARGE_LONG +#define __ULONG_MAX 0xffffffffffffffffUL +#define __LONG_MAX 0x7fffffffffffffffL +#define __LONG_MIN (-0x7fffffffffffffffL - 1) +#else +#define __ULONG_MAX 0xffffffffUL /* max value for an unsigned long */ +#define __LONG_MAX 0x7fffffffL /* max value for a long */ +#define __LONG_MIN (-0x7fffffffL - 1) /* min value for a long */ +#endif + + /* max value for an unsigned long long */ +#define __ULLONG_MAX 0xffffffffffffffffULL +#define __LLONG_MAX 0x7fffffffffffffffLL /* max value for a long long */ +#define __LLONG_MIN (-0x7fffffffffffffffLL - 1) /* min for a long long */ + +#define __SSIZE_MAX __INT_MAX /* max value for a ssize_t */ + +#define __SIZE_T_MAX __UINT_MAX /* max value for a size_t */ + +#define __OFF_MAX __LLONG_MAX /* max value for an off_t */ +#define __OFF_MIN __LLONG_MIN /* min value for an off_t */ + +/* Quads and long longs are the same size. Ensure they stay in sync. */ +#define __UQUAD_MAX __ULLONG_MAX /* max value for a uquad_t */ +#define __QUAD_MAX __LLONG_MAX /* max value for a quad_t */ +#define __QUAD_MIN __LLONG_MIN /* min value for a quad_t */ + +#ifdef _LARGE_LONG +#define __LONG_BIT 64 +#else +#define __LONG_BIT 32 +#endif +#define __WORD_BIT 32 + +#endif /* !_MACHINE__LIMITS_H_ */ diff --git a/src/include/machine/_stdint.h b/src/include/machine/_stdint.h new file mode 100644 index 0000000..fbd3ced --- /dev/null +++ b/src/include/machine/_stdint.h @@ -0,0 +1,171 @@ +/*- + * Copyright (c) 2001, 2002 Mike Barcroft + * Copyright (c) 2001 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. + * + * $FreeBSD: src/sys/i386/include/_stdint.h,v 1.1 2002/07/29 17:41:07 mike Exp $ + */ + +#ifndef _MACHINE__STDINT_H_ +#define _MACHINE__STDINT_H_ + +#if !defined(__cplusplus) || defined(__STDC_CONSTANT_MACROS) + +#define INT8_C(c) (c) +#define INT16_C(c) (c) +#define INT32_C(c) (c) +#define INT64_C(c) (c ## LL) + +#define UINT8_C(c) (c) +#define UINT16_C(c) (c) +#define UINT32_C(c) (c ## U) +#define UINT64_C(c) (c ## ULL) + +#define INTMAX_C(c) (c ## LL) +#define UINTMAX_C(c) (c ## ULL) + +#endif /* !defined(__cplusplus) || defined(__STDC_CONSTANT_MACROS) */ + +#if !defined(__cplusplus) || defined(__STDC_LIMIT_MACROS) + +/* + * ISO/IEC 9899:1999 + * 7.18.2.1 Limits of exact-width integer types + */ +/* Minimum values of exact-width signed integer types. */ +#define INT8_MIN (-0x7f-1) +#define INT16_MIN (-0x7fff-1) +#define INT32_MIN (-0x7fffffff-1) +#define INT64_MIN (-0x7fffffffffffffffLL-1) + +/* Maximum values of exact-width signed integer types. */ +#define INT8_MAX 0x7f +#define INT16_MAX 0x7fff +#define INT32_MAX 0x7fffffff +#define INT64_MAX 0x7fffffffffffffffLL + +/* Maximum values of exact-width unsigned integer types. */ +#define UINT8_MAX 0xff +#define UINT16_MAX 0xffff +#define UINT32_MAX 0xffffffffU +#define UINT64_MAX 0xffffffffffffffffULL + +/* + * ISO/IEC 9899:1999 + * 7.18.2.2 Limits of minimum-width integer types + */ +/* Minimum values of minimum-width signed integer types. */ +#define INT_LEAST8_MIN INT8_MIN +#define INT_LEAST16_MIN INT16_MIN +#define INT_LEAST32_MIN INT32_MIN +#define INT_LEAST64_MIN INT64_MIN + +/* Maximum values of minimum-width signed integer types. */ +#define INT_LEAST8_MAX INT8_MAX +#define INT_LEAST16_MAX INT16_MAX +#define INT_LEAST32_MAX INT32_MAX +#define INT_LEAST64_MAX INT64_MAX + +/* Maximum values of minimum-width unsigned integer types. */ +#define UINT_LEAST8_MAX UINT8_MAX +#define UINT_LEAST16_MAX UINT16_MAX +#define UINT_LEAST32_MAX UINT32_MAX +#define UINT_LEAST64_MAX UINT64_MAX + +/* + * ISO/IEC 9899:1999 + * 7.18.2.3 Limits of fastest minimum-width integer types + */ +/* Minimum values of fastest minimum-width signed integer types. */ +#define INT_FAST8_MIN INT32_MIN +#define INT_FAST16_MIN INT32_MIN +#define INT_FAST32_MIN INT32_MIN +#define INT_FAST64_MIN INT64_MIN + +/* Maximum values of fastest minimum-width signed integer types. */ +#define INT_FAST8_MAX INT32_MAX +#define INT_FAST16_MAX INT32_MAX +#define INT_FAST32_MAX INT32_MAX +#define INT_FAST64_MAX INT64_MAX + +/* Maximum values of fastest minimum-width unsigned integer types. */ +#define UINT_FAST8_MAX UINT32_MAX +#define UINT_FAST16_MAX UINT32_MAX +#define UINT_FAST32_MAX UINT32_MAX +#define UINT_FAST64_MAX UINT64_MAX + +/* + * ISO/IEC 9899:1999 + * 7.18.2.4 Limits of integer types capable of holding object pointers + */ +#define INTPTR_MIN INT32_MIN +#define INTPTR_MAX INT32_MAX +#define UINTPTR_MAX UINT32_MAX + +/* + * ISO/IEC 9899:1999 + * 7.18.2.5 Limits of greatest-width integer types + */ +#define INTMAX_MIN INT64_MIN +#define INTMAX_MAX INT64_MAX +#define UINTMAX_MAX UINT64_MAX + +/* + * ISO/IEC 9899:1999 + * 7.18.3 Limits of other integer types + */ +/* Limits of ptrdiff_t. */ +#define PTRDIFF_MIN INT32_MIN +#define PTRDIFF_MAX INT32_MAX + +/* Limits of sig_atomic_t. */ +#define SIG_ATOMIC_MIN INT32_MIN +#define SIG_ATOMIC_MAX INT32_MAX + +/* Limit of size_t. */ +#define SIZE_MAX UINT32_MAX + +#ifndef WCHAR_MIN /* Also possibly defined in */ +/* Limits of wchar_t. */ +#define WCHAR_MIN INT32_MIN +#define WCHAR_MAX INT32_MAX + +/* Limits of wint_t. */ +#define WINT_MIN INT32_MIN +#define WINT_MAX INT32_MAX +#endif + +#endif /* !defined(__cplusplus) || defined(__STDC_LIMIT_MACROS) */ + +#endif /* !_MACHINE__STDINT_H_ */ diff --git a/src/include/machine/_types.h b/src/include/machine/_types.h new file mode 100644 index 0000000..d57eb23 --- /dev/null +++ b/src/include/machine/_types.h @@ -0,0 +1,126 @@ +/*- + * Copyright (c) 2002 Mike Barcroft + * 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. + * + * From: @(#)ansi.h 8.2 (Berkeley) 1/4/94 + * From: @(#)types.h 8.3 (Berkeley) 1/5/94 + * $FreeBSD: src/sys/i386/include/_types.h,v 1.7 2003/03/30 05:24:52 jake Exp $ + */ + +#ifndef _MACHINE__TYPES_H_ +#define _MACHINE__TYPES_H_ + +/* + * Basic types upon which most other types are built. + */ +typedef __signed char __int8_t; +typedef unsigned char __uint8_t; +typedef short __int16_t; +typedef unsigned short __uint16_t; +typedef int __int32_t; +typedef unsigned int __uint32_t; + +#if defined(lint) +/* LONGLONG */ +typedef long long __int64_t; +/* LONGLONG */ +typedef unsigned long long __uint64_t; +#elif defined(__GNUC__) +typedef int __attribute__((__mode__(__DI__))) __int64_t; +typedef unsigned int __attribute__((__mode__(__DI__))) __uint64_t; +#else +/* LONGLONG */ +typedef long long __int64_t; +/* LONGLONG */ +typedef unsigned long long __uint64_t; +#endif + +/* + * Standard type definitions. + */ +typedef unsigned long __clock_t; /* clock()... */ +typedef __int32_t __critical_t; +typedef double __double_t; +typedef double __float_t; +typedef __int32_t __intfptr_t; +typedef __int64_t __intmax_t; +typedef __int32_t __intptr_t; +typedef __int32_t __int_fast8_t; +typedef __int32_t __int_fast16_t; +typedef __int32_t __int_fast32_t; +typedef __int64_t __int_fast64_t; +typedef __int8_t __int_least8_t; +typedef __int16_t __int_least16_t; +typedef __int32_t __int_least32_t; +typedef __int64_t __int_least64_t; +typedef __int32_t __ptrdiff_t; /* ptr1 - ptr2 */ +typedef __int32_t __register_t; +typedef __int32_t __segsz_t; /* segment size (in pages) */ +typedef __uint32_t __size_t; /* sizeof() */ +typedef __int32_t __ssize_t; /* byte count or error */ +typedef __int32_t __time_t; /* time()... */ +typedef __uint32_t __uintfptr_t; +typedef __uint64_t __uintmax_t; +typedef __uint32_t __uintptr_t; +typedef __uint32_t __uint_fast8_t; +typedef __uint32_t __uint_fast16_t; +typedef __uint32_t __uint_fast32_t; +typedef __uint64_t __uint_fast64_t; +typedef __uint8_t __uint_least8_t; +typedef __uint16_t __uint_least16_t; +typedef __uint32_t __uint_least32_t; +typedef __uint64_t __uint_least64_t; +typedef __uint32_t __u_register_t; +typedef __uint32_t __vm_offset_t; +typedef __int64_t __vm_ooffset_t; +#ifdef PAE +typedef __uint64_t __vm_paddr_t; +#else +typedef __uint32_t __vm_paddr_t; +#endif +typedef __uint64_t __vm_pindex_t; +typedef __uint32_t __vm_size_t; + +/* + * Unusual type definitions. + */ +#if defined(__GNUC__) && (__GNUC__ == 2 && __GNUC_MINOR__ > 95 || __GNUC__ >= 3) +typedef __builtin_va_list __va_list; /* internally known to gcc */ +#else +typedef char * __va_list; +#endif /* post GCC 2.95 */ +#if defined __GNUC__ && !defined(__GNUC_VA_LIST) && !defined(__NO_GNUC_VA_LIST) +#define __GNUC_VA_LIST +typedef __va_list __gnuc_va_list; /* compatibility w/GNU headers*/ +#endif + +#endif /* !_MACHINE__TYPES_H_ */ diff --git a/src/include/machine/endian.h b/src/include/machine/endian.h new file mode 100644 index 0000000..ca63ae7 --- /dev/null +++ b/src/include/machine/endian.h @@ -0,0 +1,182 @@ +/*- + * Copyright (c) 1987, 1991 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. + * + * @(#)endian.h 7.8 (Berkeley) 4/3/91 + * $FreeBSD: src/sys/i386/include/endian.h,v 1.37 2003/09/22 21:46:47 peter Exp $ + */ + +#ifndef _MACHINE_ENDIAN_H_ +#define _MACHINE_ENDIAN_H_ + +#include +#include + +/* + * Define the order of 32-bit words in 64-bit words. + */ +#define _QUAD_HIGHWORD 1 +#define _QUAD_LOWWORD 0 + +/* + * Definitions for byte order, according to byte significance from low + * address to high. + */ +#define _LITTLE_ENDIAN 1234 /* LSB first: i386, vax */ +#define _BIG_ENDIAN 4321 /* MSB first: 68000, ibm, net */ +#define _PDP_ENDIAN 3412 /* LSB first in word, MSW first in long */ + +#define _BYTE_ORDER _LITTLE_ENDIAN + +/* + * Deprecated variants that don't have enough underscores to be useful in more + * strict namespaces. + */ +#if __BSD_VISIBLE +#define LITTLE_ENDIAN _LITTLE_ENDIAN +#define BIG_ENDIAN _BIG_ENDIAN +#define PDP_ENDIAN _PDP_ENDIAN +#define BYTE_ORDER _BYTE_ORDER +#endif + +#ifdef __GNUC__ + +#define __word_swap_int_var(x) \ +__extension__ ({ register __uint32_t __X = (x); \ + __asm ("rorl $16, %0" : "+r" (__X)); \ + __X; }) + +#ifdef __OPTIMIZE__ + +#define __word_swap_int_const(x) \ + ((((x) & 0xffff0000) >> 16) | \ + (((x) & 0x0000ffff) << 16)) +#define __word_swap_int(x) (__builtin_constant_p(x) ? \ + __word_swap_int_const(x) : __word_swap_int_var(x)) + +#else /* __OPTIMIZE__ */ + +#define __word_swap_int(x) __word_swap_int_var(x) + +#endif /* __OPTIMIZE__ */ + +#if defined(_KERNEL) && (defined(I486_CPU) || defined(I586_CPU) || defined(I686_CPU)) && !defined(I386_CPU) + +#define __byte_swap_int_var(x) \ +__extension__ ({ register __uint32_t __X = (x); \ + __asm ("bswap %0" : "+r" (__X)); \ + __X; }) +#else + +#define __byte_swap_int_var(x) \ +__extension__ ({ register __uint32_t __X = (x); \ + __asm ("xchgb %h0, %b0\n\trorl $16, %0\n\txchgb %h0, %b0" \ + : "+q" (__X)); \ + __X; }) +#endif + +#ifdef __OPTIMIZE__ + +#define __byte_swap_int_const(x) \ + ((((x) & 0xff000000) >> 24) | \ + (((x) & 0x00ff0000) >> 8) | \ + (((x) & 0x0000ff00) << 8) | \ + (((x) & 0x000000ff) << 24)) +#define __byte_swap_int(x) (__builtin_constant_p(x) ? \ + __byte_swap_int_const(x) : __byte_swap_int_var(x)) + +#else /* __OPTIMIZE__ */ + +#define __byte_swap_int(x) __byte_swap_int_var(x) + +#endif /* __OPTIMIZE__ */ + +#define __byte_swap_word_var(x) \ +__extension__ ({ register __uint16_t __X = (x); \ + __asm ("xchgb %h0, %b0" : "+q" (__X)); \ + __X; }) + +#ifdef __OPTIMIZE__ + +#define __byte_swap_word_const(x) \ + ((((x) & 0xff00) >> 8) | \ + (((x) & 0x00ff) << 8)) + +#define __byte_swap_word(x) (__builtin_constant_p(x) ? \ + __byte_swap_word_const(x) : __byte_swap_word_var(x)) + +#else /* __OPTIMIZE__ */ + +#define __byte_swap_word(x) __byte_swap_word_var(x) + +#endif /* __OPTIMIZE__ */ + +static __inline __uint64_t +__bswap64(__uint64_t _x) +{ + + return ((_x >> 56) | ((_x >> 40) & 0xff00) | ((_x >> 24) & 0xff0000) | + ((_x >> 8) & 0xff000000) | ((_x << 8) & ((__uint64_t)0xff << 32)) | + ((_x << 24) & ((__uint64_t)0xff << 40)) | + ((_x << 40) & ((__uint64_t)0xff << 48)) | ((_x << 56))); +} + +static __inline __uint32_t +__bswap32(__uint32_t _x) +{ + + return (__byte_swap_int(_x)); +} + +static __inline __uint16_t +__bswap16(__uint16_t _x) +{ + + return (__byte_swap_word(_x)); +} + +#define __htonl(x) __bswap32(x) +#define __htons(x) __bswap16(x) +#define __ntohl(x) __bswap32(x) +#define __ntohs(x) __bswap16(x) + +#else /* !__GNUC__ */ + +/* + * No optimizations are available for this compiler. Fall back to + * non-optimized functions by defining the constant usually used to prevent + * redefinition. + */ +#define _BYTEORDER_FUNC_DEFINED + +#endif /* __GNUC__ */ + +#endif /* !_MACHINE_ENDIAN_H_ */ diff --git a/src/include/machine/param.h b/src/include/machine/param.h new file mode 100644 index 0000000..68f8020 --- /dev/null +++ b/src/include/machine/param.h @@ -0,0 +1,146 @@ +/*- + * 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. + * + * from: @(#)param.h 5.8 (Berkeley) 6/28/91 + * $FreeBSD: src/sys/i386/include/param.h,v 1.69 2003/06/14 23:23:53 alc Exp $ + */ + +/* + * Machine dependent constants for Intel 386. + */ + +/* + * Round p (pointer or byte index) up to a correctly-aligned value + * for all data types (int, long, ...). The result is unsigned int + * and must be cast to any desired pointer type. + */ +#ifndef _ALIGNBYTES +#define _ALIGNBYTES (sizeof(int) - 1) +#endif +#ifndef _ALIGN +#define _ALIGN(p) (((unsigned)(p) + _ALIGNBYTES) & ~_ALIGNBYTES) +#endif + +#ifndef _MACHINE +#define _MACHINE i386 +#endif +#ifndef _MACHINE_ARCH +#define _MACHINE_ARCH i386 +#endif + +#ifndef _NO_NAMESPACE_POLLUTION + +#ifndef _MACHINE_PARAM_H_ +#define _MACHINE_PARAM_H_ + +#ifndef MACHINE +#define MACHINE "i386" +#endif +#ifndef MACHINE_ARCH +#define MACHINE_ARCH "i386" +#endif +#define MID_MACHINE MID_I386 + +#ifdef SMP +#define MAXCPU 16 +#else +#define MAXCPU 1 +#endif /* SMP */ + +#define ALIGNBYTES _ALIGNBYTES +#define ALIGN(p) _ALIGN(p) + +#define PAGE_SHIFT 12 /* LOG2(PAGE_SIZE) */ +#define PAGE_SIZE (1<> PAGE_SHIFT) +#define ptoa(x) ((x) << PAGE_SHIFT) + +#define i386_btop(x) ((x) >> PAGE_SHIFT) +#define i386_ptob(x) ((x) << PAGE_SHIFT) + +#define pgtok(x) ((x) * (PAGE_SIZE / 1024)) + +#endif /* !_MACHINE_PARAM_H_ */ +#endif /* !_NO_NAMESPACE_POLLUTION */ diff --git a/src/include/machine/signal.h b/src/include/machine/signal.h new file mode 100644 index 0000000..0009d76 --- /dev/null +++ b/src/include/machine/signal.h @@ -0,0 +1,142 @@ +/* + * Copyright (c) 1986, 1989, 1991, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * @(#)signal.h 8.1 (Berkeley) 6/11/93 + * $FreeBSD: src/sys/i386/include/signal.h,v 1.20 2002/12/02 19:58:55 deischen Exp $ + */ + +#ifndef _MACHINE_SIGNAL_H_ +#define _MACHINE_SIGNAL_H_ + +#include +#include + +/* + * Machine-dependent signal definitions + */ + +typedef int sig_atomic_t; + +#if __XSI_VISIBLE +/* + * Minimum signal stack size. The current signal frame + * for i386 is 408 bytes large. + */ +#define MINSIGSTKSZ (512 * 4) +#endif + +#if __BSD_VISIBLE +#include /* codes for SIGILL, SIGFPE */ + +/* + * Only the kernel should need these old type definitions. + */ +#if defined(_KERNEL) && defined(COMPAT_43) +/* + * Information pushed on stack when a signal is delivered. + * This is used by the kernel to restore state following + * execution of the signal handler. It is also made available + * to the handler to allow it to restore state properly if + * a non-standard exit is performed. + */ +struct osigcontext { + int sc_onstack; /* sigstack state to restore */ + osigset_t sc_mask; /* signal mask to restore */ + int sc_esp; /* machine state follows: */ + int sc_ebp; + int sc_isp; + int sc_eip; + int sc_efl; + int sc_es; + int sc_ds; + int sc_cs; + int sc_ss; + int sc_edi; + int sc_esi; + int sc_ebx; + int sc_edx; + int sc_ecx; + int sc_eax; + int sc_gs; + int sc_fs; + int sc_trapno; + int sc_err; +}; +#endif + +/* + * The sequence of the fields/registers in struct sigcontext should match + * those in mcontext_t. + */ +struct sigcontext { + struct __sigset sc_mask; /* signal mask to restore */ + int sc_onstack; /* sigstack state to restore */ + int sc_gs; /* machine state (struct trapframe) */ + int sc_fs; + int sc_es; + int sc_ds; + int sc_edi; + int sc_esi; + int sc_ebp; + int sc_isp; + int sc_ebx; + int sc_edx; + int sc_ecx; + int sc_eax; + int sc_trapno; + int sc_err; + int sc_eip; + int sc_cs; + int sc_efl; + int sc_esp; + int sc_ss; + int sc_len; /* sizeof(mcontext_t) */ + /* + * XXX - See and for + * the following fields. + */ + int sc_fpformat; + int sc_ownedfp; + int sc_spare1[1]; + int sc_fpstate[128] __aligned(16); + int sc_spare2[8]; +}; + +#define sc_sp sc_esp +#define sc_fp sc_ebp +#define sc_pc sc_eip +#define sc_ps sc_efl +#define sc_eflags sc_efl + +#endif /* __BSD_VISIBLE */ + +#endif /* !_MACHINE_SIGNAL_H_ */ diff --git a/src/include/machine/trap.h b/src/include/machine/trap.h new file mode 100644 index 0000000..c32c70b --- /dev/null +++ b/src/include/machine/trap.h @@ -0,0 +1,107 @@ +/*- + * 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. + * + * from: @(#)trap.h 5.4 (Berkeley) 5/9/91 + * $FreeBSD: src/sys/i386/include/trap.h,v 1.13 2001/07/12 06:32:51 peter Exp $ + */ + +#ifndef _MACHINE_TRAP_H_ +#define _MACHINE_TRAP_H_ + +/* + * Trap type values + * also known in trap.c for name strings + */ + +#define T_PRIVINFLT 1 /* privileged instruction */ +#define T_BPTFLT 3 /* breakpoint instruction */ +#define T_ARITHTRAP 6 /* arithmetic trap */ +#define T_PROTFLT 9 /* protection fault */ +#define T_TRCTRAP 10 /* debug exception (sic) */ +#define T_PAGEFLT 12 /* page fault */ +#define T_ALIGNFLT 14 /* alignment fault */ + +#define T_DIVIDE 18 /* integer divide fault */ +#define T_NMI 19 /* non-maskable trap */ +#define T_OFLOW 20 /* overflow trap */ +#define T_BOUND 21 /* bound instruction fault */ +#define T_DNA 22 /* device not available fault */ +#define T_DOUBLEFLT 23 /* double fault */ +#define T_FPOPFLT 24 /* fp coprocessor operand fetch fault */ +#define T_TSSFLT 25 /* invalid tss fault */ +#define T_SEGNPFLT 26 /* segment not present fault */ +#define T_STKFLT 27 /* stack fault */ +#define T_MCHK 28 /* machine check trap */ +#define T_XMMFLT 29 /* SIMD floating-point exception */ +#define T_RESERVED 30 /* reserved (unknown) */ + +/* XXX most of the following codes aren't used, but could be. */ + +/* definitions for */ +#define ILL_RESAD_FAULT T_RESADFLT +#define ILL_PRIVIN_FAULT T_PRIVINFLT +#define ILL_RESOP_FAULT T_RESOPFLT +#define ILL_ALIGN_FAULT T_ALIGNFLT +#define ILL_FPOP_FAULT T_FPOPFLT /* coprocessor operand fault */ + +/* portable macros for SIGFPE/ARITHTRAP */ +#define FPE_INTOVF 1 /* integer overflow */ +#define FPE_INTDIV 2 /* integer divide by zero */ +#define FPE_FLTDIV 3 /* floating point divide by zero */ +#define FPE_FLTOVF 4 /* floating point overflow */ +#define FPE_FLTUND 5 /* floating point underflow */ +#define FPE_FLTRES 6 /* floating point inexact result */ +#define FPE_FLTINV 7 /* invalid floating point operation */ +#define FPE_FLTSUB 8 /* subscript out of range */ + +/* old FreeBSD macros, deprecated */ +#define FPE_INTOVF_TRAP 0x1 /* integer overflow */ +#define FPE_INTDIV_TRAP 0x2 /* integer divide by zero */ +#define FPE_FLTDIV_TRAP 0x3 /* floating/decimal divide by zero */ +#define FPE_FLTOVF_TRAP 0x4 /* floating overflow */ +#define FPE_FLTUND_TRAP 0x5 /* floating underflow */ +#define FPE_FPU_NP_TRAP 0x6 /* floating point unit not present */ +#define FPE_SUBRNG_TRAP 0x7 /* subrange out of bounds */ + +/* codes for SIGBUS */ +#define BUS_PAGE_FAULT T_PAGEFLT /* page fault protection base */ +#define BUS_SEGNP_FAULT T_SEGNPFLT /* segment not present */ +#define BUS_STK_FAULT T_STKFLT /* stack segment */ +#define BUS_SEGM_FAULT T_RESERVED /* segment protection base */ + +/* Trap's coming from user mode */ +#define T_USER 0x100 + +#endif /* !_MACHINE_TRAP_H_ */ diff --git a/src/include/math.h b/src/include/math.h new file mode 100644 index 0000000..2435391 --- /dev/null +++ b/src/include/math.h @@ -0,0 +1,2 @@ +double sqrt(double val); +double atan(double val); diff --git a/src/include/paths.h b/src/include/paths.h new file mode 100644 index 0000000..952a3ae --- /dev/null +++ b/src/include/paths.h @@ -0,0 +1,139 @@ +/* + * 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. + * + * @(#)paths.h 8.1 (Berkeley) 6/2/93 + * $FreeBSD: src/include/paths.h,v 1.25 2004/01/04 17:17:46 iedowse Exp $ + */ + +#ifndef _PATHS_H_ +#define _PATHS_H_ + +#include + +/* Default search path. */ +#define _PATH_DEFPATH "/usr/bin:/bin" +/* All standard utilities path. */ +#define _PATH_STDPATH \ + "/usr/bin:/bin:/usr/sbin:/sbin:" +/* Locate system binaries */ +#define _PATH_SYSPATH \ + "/sbin:/usr/sbin" + +#define _PATH_AUTHCONF "/etc/auth.conf" +#define _PATH_BSHELL "/bin/sh" +#define _PATH_CAPABILITY "/etc/capability" +#define _PATH_CAPABILITY_DB "/etc/capability.db" +#define _PATH_CONSOLE "/dev/console" +#define _PATH_CP "/bin/cp" +#define _PATH_CSHELL "/bin/csh" +#define _PATH_DEFTAPE "/dev/sa0" +#define _PATH_DEVNULL "/dev/null" +#define _PATH_DEVZERO "/dev/zero" +#define _PATH_DRUM "/dev/drum" +#define _PATH_ETC "/etc" +#define _PATH_FTPUSERS "/etc/ftpusers" +#define _PATH_HALT "/sbin/halt" +#define _PATH_IFCONFIG "/sbin/ifconfig" +#define _PATH_KMEM "/dev/kmem" +#define _PATH_LIBMAP_CONF "/etc/libmap.conf" +#define _PATH_LOCALE "/usr/share/locale" +#define _PATH_LOGIN "/usr/bin/login" +#define _PATH_MAILDIR "/var/mail" +#define _PATH_MAN "/usr/share/man" +#define _PATH_MDCONFIG "/sbin/mdconfig" +#define _PATH_MEM "/dev/mem" +#define _PATH_MKSNAP_FFS "/sbin/mksnap_ffs" +#define _PATH_MOUNT "/sbin/mount" +#define _PATH_NEWFS "/sbin/newfs" +#define _PATH_NOLOGIN "/var/run/nologin" +#define _PATH_RCP "/bin/rcp" +#define _PATH_REBOOT "/sbin/reboot" +#define _PATH_RLOGIN "/usr/bin/rlogin" +#define _PATH_RM "/bin/rm" +#define _PATH_RSH "/usr/bin/rsh" +#define _PATH_SENDMAIL "/usr/sbin/sendmail" +#define _PATH_SHELLS "/etc/shells" +#define _PATH_TTY "/dev/tty" +#define _PATH_UNIX "don't use _PATH_UNIX" +#define _PATH_VI "/usr/bin/vi" +#define _PATH_WALL "/usr/bin/wall" + +/* Provide trailing slash, since mostly used for building pathnames. */ +#define _PATH_DEV "/dev/" +#define _PATH_TMP "/tmp/" +#define _PATH_VARDB "/var/db/" +#define _PATH_VARRUN "/var/run/" +#define _PATH_VARTMP "/var/tmp/" +#define _PATH_YP "/var/yp/" +#define _PATH_UUCPLOCK "/var/spool/lock/" + +/* How to get the correct name of the kernel. */ +__BEGIN_DECLS +const char *getbootfile(void); +__END_DECLS + +#ifdef RESCUE +#undef _PATH_DEFPATH +#define _PATH_DEFPATH "/rescue:/usr/bin:/bin" +#undef _PATH_STDPATH +#define _PATH_STDPATH "/rescue:/usr/bin:/bin:/usr/sbin:/sbin" +#undef _PATH_SYSPATH +#define _PATH_SYSPATH "/rescue:/sbin:/usr/sbin" +#undef _PATH_BSHELL +#define _PATH_BSHELL "/rescue/sh" +#undef _PATH_CP +#define _PATH_CP "/rescue/cp" +#undef _PATH_CSHELL +#define _PATH_CSHELL "/rescue/csh" +#undef _PATH_HALT +#define _PATH_HALT "/rescue/halt" +#undef _PATH_IFCONFIG +#define _PATH_IFCONFIG "/rescue/ifconfig" +#undef _PATH_MDCONFIG +#define _PATH_MDCONFIG "/rescue/mdconfig" +#undef _PATH_MOUNT +#define _PATH_MOUNT "/rescue/mount" +#undef _PATH_NEWFS +#define _PATH_NEWFS "/rescue/newfs" +#undef _PATH_RCP +#define _PATH_RCP "/rescue/rcp" +#undef _PATH_REBOOT +#define _PATH_REBOOT "/rescue/reboot" +#undef _PATH_RM +#define _PATH_RM "/rescue/rm" +#undef _PATH_VI +#define _PATH_VI "/rescue/vi" +#undef _PATH_WALL +#define _PATH_WALL "/rescue/wall" +#endif /* RESCUE */ + +#endif /* !_PATHS_H_ */ diff --git a/src/include/quad.h b/src/include/quad.h new file mode 100644 index 0000000..4f65864 --- /dev/null +++ b/src/include/quad.h @@ -0,0 +1,4 @@ +#include + +quad_t __divdi3(quad_t a,quad_t b); +u_quad_t __udivdi3(u_quad_t a,u_quad_t b); diff --git a/src/include/regex.h b/src/include/regex.h new file mode 100644 index 0000000..a58db6f --- /dev/null +++ b/src/include/regex.h @@ -0,0 +1,119 @@ +/*- + * Copyright (c) 1992 Henry Spencer. + * Copyright (c) 1992, 1993 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * Henry Spencer of the University of Toronto. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * @(#)regex.h 8.2 (Berkeley) 1/3/94 + * $FreeBSD: src/include/regex.h,v 1.10 2003/12/18 10:41:39 jkh Exp $ + */ + +#ifndef _REGEX_H_ +#define _REGEX_H_ + +#include +#include + +/* types */ +typedef __off_t regoff_t; + +#ifndef _SIZE_T_DECLARED +typedef __size_t size_t; +#define _SIZE_T_DECLARED +#endif + +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; + +/* regcomp() flags */ +#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 + +/* regerror() flags */ +#define REG_ENOSYS (-1) +#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_ATOI 255 /* convert name to number (!) */ +#define REG_ITOA 0400 /* convert number to name (!) */ + +/* regexec() flags */ +#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 */ + +__BEGIN_DECLS +int regcomp(regex_t * __restrict, const char * __restrict, int); +size_t regerror(int, const regex_t * __restrict, char * __restrict, size_t); +/* + * XXX forth parameter should be `regmatch_t [__restrict]', but isn't because + * of a bug in GCC 3.2 (when -std=c99 is specified) which perceives this as a + * syntax error. + */ +int regexec(const regex_t * __restrict, const char * __restrict, size_t, + regmatch_t * __restrict, int); +void regfree(regex_t *); +__END_DECLS + +#endif /* !_REGEX_H_ */ diff --git a/src/include/rune.h b/src/include/rune.h new file mode 100644 index 0000000..b1e6115 --- /dev/null +++ b/src/include/rune.h @@ -0,0 +1,70 @@ +/*- + * 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. + * + * @(#)rune.h 8.1 (Berkeley) 6/27/93 + * $FreeBSD: src/include/rune.h,v 1.4 2003/06/25 22:28:33 phantom Exp $ + */ + +#ifndef _RUNE_H_ +#define _RUNE_H_ + +#include +#include + +#ifndef _RUNE_T_DECLARED +#define _RUNE_T_DECLARED +typedef __rune_t rune_t; +#endif + +#define _INVALID_RUNE _CurrentRuneLocale->invalid_rune + +#define __sgetrune _CurrentRuneLocale->sgetrune +#define __sputrune _CurrentRuneLocale->sputrune + +#define sgetrune(s, n, r) (*__sgetrune)((s), (n), (r)) +#define sputrune(c, s, n, r) (*__sputrune)((c), (s), (n), (r)) + +__BEGIN_DECLS +char *mbrune(const char *, rune_t); +char *mbrrune(const char *, rune_t); +char *mbmb(const char *, char *); +long fgetrune(FILE *); +int fputrune(rune_t, FILE *); +int fungetrune(rune_t, FILE *); +int setrunelocale(char *); +void setinvalidrune(rune_t); +__END_DECLS + +#endif /*! _RUNE_H_ */ diff --git a/src/include/runetype.h b/src/include/runetype.h new file mode 100644 index 0000000..d7001f0 --- /dev/null +++ b/src/include/runetype.h @@ -0,0 +1,94 @@ +/*- + * 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. + * + * @(#)runetype.h 8.1 (Berkeley) 6/2/93 + * $FreeBSD: src/include/runetype.h,v 1.8 2002/09/06 04:22:54 mike Exp $ + */ + +#ifndef _RUNETYPE_H_ +#define _RUNETYPE_H_ + +#include +#include + +#define _CACHED_RUNES (1 <<8 ) /* Must be a power of 2 */ +#define _CRMASK (~(_CACHED_RUNES - 1)) + +/* + * The lower 8 bits of runetype[] contain the digit value of the rune. + */ +typedef struct { + __rune_t min; /* First rune of the range */ + __rune_t max; /* Last rune (inclusive) of the range */ + __rune_t map; /* What first maps to in maps */ + unsigned long *types; /* Array of types in range */ +} _RuneEntry; + +typedef struct { + int nranges; /* Number of ranges stored */ + _RuneEntry *ranges; /* Pointer to the ranges */ +} _RuneRange; + +typedef struct { + char magic[8]; /* Magic saying what version we are */ + char encoding[32]; /* ASCII name of this encoding */ + + __rune_t (*sgetrune)(const char *, __size_t, char const **); + int (*sputrune)(__rune_t, char *, __size_t, char **); + __rune_t invalid_rune; + + unsigned long runetype[_CACHED_RUNES]; + __rune_t maplower[_CACHED_RUNES]; + __rune_t mapupper[_CACHED_RUNES]; + + /* + * The following are to deal with Runes larger than _CACHED_RUNES - 1. + * Their data is actually contiguous with this structure so as to make + * it easier to read/write from/to disk. + */ + _RuneRange runetype_ext; + _RuneRange maplower_ext; + _RuneRange mapupper_ext; + + void *variable; /* Data which depends on the encoding */ + int variable_len; /* how long that data is */ +} _RuneLocale; + +#define _RUNE_MAGIC_1 "RuneMagi" /* Indicates version 0 of RuneLocale */ + +extern _RuneLocale _DefaultRuneLocale; +extern _RuneLocale *_CurrentRuneLocale; + +#endif /* !_RUNETYPE_H_ */ diff --git a/src/include/stdarg.h b/src/include/stdarg.h new file mode 100644 index 0000000..a1e1e4b --- /dev/null +++ b/src/include/stdarg.h @@ -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$ + +**************************************************************************************/ + +#ifndef _STDARG_H +#define _STDARG_H + +typedef char *vaList; + +#define _vaSize(TYPE) (((sizeof(TYPE) + sizeof(int) -1) / sizeof(int)) * sizeof(int)) +#define vaStart(AP, LASTARG) (AP=((vaList)&(LASTARG) + _vaSize(LASTARG))) +#define vaEnd(AP) +#define vaArg(AP, TYPE) (AP += _vaSize(TYPE), *((TYPE *)(AP - _vaSize(TYPE)))) + +#endif diff --git a/src/include/stddef.h b/src/include/stddef.h new file mode 100644 index 0000000..a331305 --- /dev/null +++ b/src/include/stddef.h @@ -0,0 +1,68 @@ +/*- + * 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. + * + * @(#)stddef.h 8.1 (Berkeley) 6/2/93 + * + * $FreeBSD: src/include/stddef.h,v 1.10 2003/12/07 21:10:06 marcel Exp $ + */ + +#ifndef _STDDEF_H_ +#define _STDDEF_H_ + +#include +#include +#include + +typedef __ptrdiff_t ptrdiff_t; + +#if __BSD_VISIBLE +#ifndef _RUNE_T_DECLARED +typedef __rune_t rune_t; +#define _RUNE_T_DECLARED +#endif +#endif + +#ifndef _SIZE_T_DECLARED +typedef __size_t size_t; +#define _SIZE_T_DECLARED +#endif + +#ifndef __cplusplus +#ifndef _WCHAR_T_DECLARED +typedef __wchar_t wchar_t; +#define _WCHAR_T_DECLARED +#endif +#endif + +#define offsetof(type, member) __offsetof(type, member) + +#endif /* _STDDEF_H_ */ diff --git a/src/include/stdint.h b/src/include/stdint.h new file mode 100644 index 0000000..b0d6632 --- /dev/null +++ b/src/include/stdint.h @@ -0,0 +1,106 @@ +/*- + * Copyright (c) 2001 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. + * + * $FreeBSD: src/sys/sys/stdint.h,v 1.4 2002/08/21 16:20:01 mike Exp $ + */ + +#ifndef _SYS_STDINT_H_ +#define _SYS_STDINT_H_ + +#include +#include + +#include + +#ifndef _INT8_T_DECLARED +typedef __int8_t int8_t; +#define _INT8_T_DECLARED +#endif + +#ifndef _INT16_T_DECLARED +typedef __int16_t int16_t; +#define _INT16_T_DECLARED +#endif + +#ifndef _INT32_T_DECLARED +typedef __int32_t int32_t; +#define _INT32_T_DECLARED +#endif + +#ifndef _INT64_T_DECLARED +typedef __int64_t int64_t; +#define _INT64_T_DECLARED +#endif + +#ifndef _UINT8_T_DECLARED +typedef __uint8_t uint8_t; +#define _UINT8_T_DECLARED +#endif + +#ifndef _UINT16_T_DECLARED +typedef __uint16_t uint16_t; +#define _UINT16_T_DECLARED +#endif + +#ifndef _UINT32_T_DECLARED +typedef __uint32_t uint32_t; +#define _UINT32_T_DECLARED +#endif + +#ifndef _UINT64_T_DECLARED +typedef __uint64_t uint64_t; +#define _UINT64_T_DECLARED +#endif + +typedef __int_least8_t int_least8_t; +typedef __int_least16_t int_least16_t; +typedef __int_least32_t int_least32_t; +typedef __int_least64_t int_least64_t; + +typedef __uint_least8_t uint_least8_t; +typedef __uint_least16_t uint_least16_t; +typedef __uint_least32_t uint_least32_t; +typedef __uint_least64_t uint_least64_t; + +typedef __int_fast8_t int_fast8_t; +typedef __int_fast16_t int_fast16_t; +typedef __int_fast32_t int_fast32_t; +typedef __int_fast64_t int_fast64_t; + +typedef __uint_fast8_t uint_fast8_t; +typedef __uint_fast16_t uint_fast16_t; +typedef __uint_fast32_t uint_fast32_t; +typedef __uint_fast64_t uint_fast64_t; + +typedef __intmax_t intmax_t; +typedef __uintmax_t uintmax_t; + +#ifndef _INTPTR_T_DECLARED +typedef __intptr_t intptr_t; +typedef __uintptr_t uintptr_t; +#define _INTPTR_T_DECLARED +#endif + +#endif /* !_SYS_STDINT_H_ */ diff --git a/src/include/stdio.h b/src/include/stdio.h new file mode 100644 index 0000000..5de3754 --- /dev/null +++ b/src/include/stdio.h @@ -0,0 +1,81 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#ifndef _STDIO_H +#define _STDIO_H + +#include +#include +#include + +/* Type Definitions */ + +typedef struct fileDescriptor { + uLong fd; + uInt32 size; + } FILE; + +/* Definitions */ + +extern FILE fdTable[]; + +#define stdin (&fdTable[0]) +#define stdout (&fdTable[1]) +#define stderr (&fdTable[2]) + +#define SEEK_SET 0 + +#define EOF (-1) + +/* Functions Definitions */ + +int fprintf(FILE *, const char *,...); +int printf(const char *, ...); +int vfprintf(FILE *,const char *,vaList args); +int vsprintf(char *buf,const char *fmt,vaList args); +FILE *fopen(const char *,const char *); +int fwrite(const void *ptr,int size,int nmemb,FILE *fd); +int fgetc(FILE *fd); + +//New Functions Listed From Here On Till I'm Done Writing A libc +int sprintf(char *string, const char *format, ...); +char *gets(char *string); +size_t fread(void *pointer,size_t size,size_t count, FILE *stream); +int fclose(FILE *fp); +int fseek(FILE *,long offset,int whence); + + +/**** Proper LIBC Stuff ****/ + +extern __const int sys_nerr; +extern __const char *__const sys_errlist[]; + + +int asprintf(char **, const char *, ...) __printflike(2, 3); +int feof(FILE *); +char *fgets(char * __restrict, int, FILE * __restrict); +int fflush(FILE *); +/**** END ****/ + +#endif + diff --git a/src/include/stdlib.h b/src/include/stdlib.h new file mode 100644 index 0000000..77ce5c9 --- /dev/null +++ b/src/include/stdlib.h @@ -0,0 +1,39 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#ifndef _STDLIB_H +#define _STDLIB_H + +#include + +extern int __mb_cur_max; +#define MB_CUR_MAX __mb_cur_max + +void exit(int); +void *malloc(uInt len); +void free(void *); +int abs(int val); +int atoi(const char *str); +long strtol(const char * __restrict nptr, char ** __restrict endptr, int base); + +#endif diff --git a/src/include/string.h b/src/include/string.h new file mode 100644 index 0000000..942444d --- /dev/null +++ b/src/include/string.h @@ -0,0 +1,48 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#ifndef _STRING_H +#define _STRING_H + +#include +#include + +extern void * memcpy(void *, const void *, size_t); +extern void * memset(void *, int, size_t); +extern int memcmp(const void *, const void *, size_t); + +extern int strlen(const char *); + +char *strtok(char *str, const char *sep); +char *strtok_r(char *str, const char *sep, char **last); + +int strcmp(const char *s1, const char *s2); + + +/**** NEW ****/ +size_t strlcat(char *, const char *, size_t); +size_t strlcpy(char *, const char *, size_t); +int bcmp(const void *, const void *, size_t); /* LEGACY */ +/**** END ****/ + +#endif diff --git a/src/include/sys/_null.h b/src/include/sys/_null.h new file mode 100644 index 0000000..359eed0 --- /dev/null +++ b/src/include/sys/_null.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2003 Marcel Moolenaar + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must 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/sys/sys/_null.h,v 1.5 2003/12/26 06:11:43 obrien Exp $ + */ + +#ifndef NULL + +#ifdef _KERNEL +#define NULL (void *)0 +#else +#if defined(__LP64__) +#define NULL 0L +#else +#define NULL 0 +#endif +#endif /* _KERNEL */ + +#endif diff --git a/src/include/sys/_sigset.h b/src/include/sys/_sigset.h new file mode 100644 index 0000000..bae3341 --- /dev/null +++ b/src/include/sys/_sigset.h @@ -0,0 +1,63 @@ +/* + * Copyright (c) 1982, 1986, 1989, 1991, 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. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * @(#)signal.h 8.4 (Berkeley) 5/4/95 + * $FreeBSD: src/sys/sys/_sigset.h,v 1.34 2002/10/25 19:10:58 peter Exp $ + */ + +#ifndef _SYS__SIGSET_H_ +#define _SYS__SIGSET_H_ + +/* + * sigset_t macros. + */ +#define _SIG_WORDS 4 +#define _SIG_MAXSIG 128 +#define _SIG_IDX(sig) ((sig) - 1) +#define _SIG_WORD(sig) (_SIG_IDX(sig) >> 5) +#define _SIG_BIT(sig) (1 << (_SIG_IDX(sig) & 31)) +#define _SIG_VALID(sig) ((sig) <= _SIG_MAXSIG && (sig) > 0) + +typedef struct __sigset { + __uint32_t __bits[_SIG_WORDS]; +} __sigset_t; + +#if defined(_KERNEL) && defined(COMPAT_43) +typedef unsigned int osigset_t; +#endif + +#endif /* !_SYS__SIGSET_H_ */ diff --git a/src/include/sys/_timeval.h b/src/include/sys/_timeval.h new file mode 100644 index 0000000..9784bcf --- /dev/null +++ b/src/include/sys/_timeval.h @@ -0,0 +1,52 @@ +/*- + * 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. + * + * $FreeBSD: src/sys/sys/_timeval.h,v 1.1 2002/12/31 04:08:41 mike Exp $ + */ + +#ifndef _SYS__TIMEVAL_H_ +#define _SYS__TIMEVAL_H_ + +#include + +#ifndef _SUSECONDS_T_DECLARED +typedef __suseconds_t suseconds_t; +#define _SUSECONDS_T_DECLARED +#endif + +#ifndef _TIME_T_DECLARED +typedef __time_t time_t; +#define _TIME_T_DECLARED +#endif + +/* + * Structure returned by gettimeofday(2) system call, and used in other calls. + */ +struct timeval { + long tv_sec; /* seconds (XXX should be time_t) */ + suseconds_t tv_usec; /* and microseconds */ +}; + +#endif /* !_SYS__TIMEVAL_H_ */ diff --git a/src/include/sys/_types.h b/src/include/sys/_types.h new file mode 100644 index 0000000..85a8322 --- /dev/null +++ b/src/include/sys/_types.h @@ -0,0 +1,102 @@ +/*- + * 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. + * + * $FreeBSD: src/sys/sys/_types.h,v 1.14 2003/03/28 15:27:30 mike Exp $ + */ + +#ifndef _SYS__TYPES_H_ +#define _SYS__TYPES_H_ + +#include +#include + +/* + * Standard type definitions. + */ +typedef __int32_t __clockid_t; /* clock_gettime()... */ +typedef __uint32_t __fflags_t; /* file flags */ +typedef __uint64_t __fsblkcnt_t; +typedef __uint64_t __fsfilcnt_t; +typedef __uint32_t __gid_t; +typedef __int64_t __id_t; /* can hold a gid_t, pid_t, or uid_t */ +typedef __uint32_t __ino_t; /* inode number */ +typedef long __key_t; /* IPC key (for Sys V IPC) */ +typedef __uint16_t __mode_t; /* permissions */ +typedef int __nl_item; +typedef __uint16_t __nlink_t; /* link count */ +typedef __int64_t __off_t; /* file offset */ +typedef __int32_t __pid_t; /* process [group] */ +typedef __int64_t __rlim_t; /* resource limit (XXX not unsigned) */ +typedef __uint8_t __sa_family_t; +typedef __uint32_t __socklen_t; +typedef long __suseconds_t; /* microseconds (signed) */ +typedef __int32_t __timer_t; /* timer_gettime()... */ +typedef __uint32_t __udev_t; /* device number */ +typedef __uint32_t __uid_t; +typedef unsigned int __useconds_t; /* microseconds (unsigned) */ + +/* + * Unusual type definitions. + */ +/* + * rune_t is declared to be an ``int'' instead of the more natural + * ``unsigned long'' or ``long''. Two things are happening here. It is not + * unsigned so that EOF (-1) can be naturally assigned to it and used. Also, + * it looks like 10646 will be a 31 bit standard. This means that if your + * ints cannot hold 32 bits, you will be in trouble. The reason an int was + * chosen over a long is that the is*() and to*() routines take ints (says + * ANSI C), but they use __ct_rune_t instead of int. + * + * NOTE: rune_t is not covered by ANSI nor other standards, and should not + * be instantiated outside of lib/libc/locale. Use wchar_t. wchar_t and + * rune_t must be the same type. Also, wint_t must be no narrower than + * wchar_t, and should be able to hold all members of the largest + * character set plus one extra value (WEOF), and must be at least 16 bits. + */ +typedef int __ct_rune_t; +typedef __ct_rune_t __wchar_t; +typedef __ct_rune_t __rune_t; +typedef __ct_rune_t __wint_t; + +/* + * dev_t has differing meanings in userland and the kernel. + */ +#ifdef _KERNEL +struct cdev; +typedef struct cdev *__dev_t; +#else +typedef __udev_t __dev_t; /* device number */ +#endif + +/* + * mbstate_t is an opaque object to keep conversion state during multibyte + * stream conversions. + */ +typedef union { + char __mbstate8[128]; + __int64_t _mbstateL; /* for alignment */ +} __mbstate_t; + +#endif /* !_SYS__TYPES_H_ */ diff --git a/src/include/sys/cdefs.h b/src/include/sys/cdefs.h new file mode 100644 index 0000000..b2fd8af --- /dev/null +++ b/src/include/sys/cdefs.h @@ -0,0 +1,454 @@ +/* + * Copyright (c) 1991, 1993 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * Berkeley Software Design, 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. + * + * @(#)cdefs.h 8.8 (Berkeley) 1/9/95 + * $FreeBSD: src/sys/sys/cdefs.h,v 1.79 2003/10/31 05:42:53 peter Exp $ + */ + +#ifndef _SYS_CDEFS_H_ +#define _SYS_CDEFS_H_ + +#if defined(__cplusplus) +#define __BEGIN_DECLS extern "C" { +#define __END_DECLS } +#else +#define __BEGIN_DECLS +#define __END_DECLS +#endif + +/* + * Macro to test if we're using a specific version of gcc or later. + */ +#ifdef __GNUC__ +#define __GNUC_PREREQ__(ma, mi) \ + (__GNUC__ > (ma) || __GNUC__ == (ma) && __GNUC_MINOR__ >= (mi)) +#else +#define __GNUC_PREREQ__(ma, mi) 0 +#endif + +/* + * The __CONCAT macro is used to concatenate parts of symbol names, e.g. + * with "#define OLD(foo) __CONCAT(old,foo)", OLD(foo) produces oldfoo. + * The __CONCAT macro is a bit tricky to use if it must work in non-ANSI + * mode -- there must be no spaces between its arguments, and for nested + * __CONCAT's, all the __CONCAT's must be at the left. __CONCAT can also + * concatenate double-quoted strings produced by the __STRING macro, but + * this only works with ANSI C. + * + * __XSTRING is like __STRING, but it expands any macros in its argument + * first. It is only available with ANSI C. + */ +#if defined(__STDC__) || defined(__cplusplus) +#define __P(protos) protos /* full-blown ANSI C */ +#define __CONCAT1(x,y) x ## y +#define __CONCAT(x,y) __CONCAT1(x,y) +#define __STRING(x) #x /* stringify without expanding x */ +#define __XSTRING(x) __STRING(x) /* expand x, then stringify */ + +#define __const const /* define reserved names to standard */ +#define __signed signed +#define __volatile volatile +#if defined(__cplusplus) +#define __inline inline /* convert to C++ keyword */ +#else +#ifndef __GNUC__ +#define __inline /* delete GCC keyword */ +#endif /* !__GNUC__ */ +#endif /* !__cplusplus */ + +#else /* !(__STDC__ || __cplusplus) */ +#define __P(protos) () /* traditional C preprocessor */ +#define __CONCAT(x,y) x/**/y +#define __STRING(x) "x" + +#ifndef __GNUC__ +#define __const /* delete pseudo-ANSI C keywords */ +#define __inline +#define __signed +#define __volatile +/* + * In non-ANSI C environments, new programs will want ANSI-only C keywords + * deleted from the program and old programs will want them left alone. + * When using a compiler other than gcc, programs using the ANSI C keywords + * const, inline etc. as normal identifiers should define -DNO_ANSI_KEYWORDS. + * When using "gcc -traditional", we assume that this is the intent; if + * __GNUC__ is defined but __STDC__ is not, we leave the new keywords alone. + */ +#ifndef NO_ANSI_KEYWORDS +#define const /* delete ANSI C keywords */ +#define inline +#define signed +#define volatile +#endif /* !NO_ANSI_KEYWORDS */ +#endif /* !__GNUC__ */ +#endif /* !(__STDC__ || __cplusplus) */ + +/* + * Compiler-dependent macros to help declare dead (non-returning) and + * pure (no side effects) functions, and unused variables. They are + * null except for versions of gcc that are known to support the features + * properly (old versions of gcc-2 supported the dead and pure features + * in a different (wrong) way). If we do not provide an implementation + * for a given compiler, let the compile fail if it is told to use + * a feature that we cannot live without. + */ +#ifdef lint +#define __dead2 +#define __pure2 +#define __unused +#define __packed +#define __aligned(x) +#define __section(x) +#else +#if !__GNUC_PREREQ__(2, 5) +#define __dead2 +#define __pure2 +#define __unused +#endif +#if __GNUC__ == 2 && __GNUC_MINOR__ >= 5 && __GNUC_MINOR__ < 7 +#define __dead2 __attribute__((__noreturn__)) +#define __pure2 __attribute__((__const__)) +#define __unused +/* XXX Find out what to do for __packed, __aligned and __section */ +#endif +#if __GNUC_PREREQ__(2, 7) +#define __dead2 __attribute__((__noreturn__)) +#define __pure2 __attribute__((__const__)) +#define __unused __attribute__((__unused__)) +#define __packed __attribute__((__packed__)) +#define __aligned(x) __attribute__((__aligned__(x))) +#define __section(x) __attribute__((__section__(x))) +#endif +#endif + +#if __GNUC_PREREQ__(3, 1) +#define __always_inline __attribute__((__always_inline__)) +#else +#define __always_inline +#endif + +#if __GNUC_PREREQ__(3, 3) +#define __nonnull(x) __attribute__((__nonnull__(x))) +#else +#define __nonnull(x) +#endif + +/* XXX: should use `#if __STDC_VERSION__ < 199901'. */ +#if !__GNUC_PREREQ__(2, 7) +#define __func__ NULL +#endif + +#if __GNUC__ >= 2 && !defined(__STRICT_ANSI__) || __STDC_VERSION__ >= 199901 +#define __LONG_LONG_SUPPORTED +#endif + +/* + * GCC 2.95 provides `__restrict' as an extension to C90 to support the + * C99-specific `restrict' type qualifier. We happen to use `__restrict' as + * a way to define the `restrict' type qualifier without disturbing older + * software that is unaware of C99 keywords. + */ +#if !(__GNUC__ == 2 && __GNUC_MINOR__ == 95) +#if !defined(__STDC_VERSION__) || __STDC_VERSION__ < 199901 +#define __restrict +#else +#define __restrict restrict +#endif +#endif + +/* + * GNU C version 2.96 adds explicit branch prediction so that + * the CPU back-end can hint the processor and also so that + * code blocks can be reordered such that the predicted path + * sees a more linear flow, thus improving cache behavior, etc. + * + * The following two macros provide us with a way to utilize this + * compiler feature. Use __predict_true() if you expect the expression + * to evaluate to true, and __predict_false() if you expect the + * expression to evaluate to false. + * + * A few notes about usage: + * + * * Generally, __predict_false() error condition checks (unless + * you have some _strong_ reason to do otherwise, in which case + * document it), and/or __predict_true() `no-error' condition + * checks, assuming you want to optimize for the no-error case. + * + * * Other than that, if you don't know the likelihood of a test + * succeeding from empirical or other `hard' evidence, don't + * make predictions. + * + * * These are meant to be used in places that are run `a lot'. + * It is wasteful to make predictions in code that is run + * seldomly (e.g. at subsystem initialization time) as the + * basic block reordering that this affects can often generate + * larger code. + */ +#if __GNUC_PREREQ__(2, 96) +#define __predict_true(exp) __builtin_expect((exp), 1) +#define __predict_false(exp) __builtin_expect((exp), 0) +#else +#define __predict_true(exp) (exp) +#define __predict_false(exp) (exp) +#endif + +/* + * We define this here since , , and + * require it. + */ +#define __offsetof(type, field) ((size_t)(&((type *)0)->field)) + +/* + * Compiler-dependent macros to declare that functions take printf-like + * or scanf-like arguments. They are null except for versions of gcc + * that are known to support the features properly (old versions of gcc-2 + * didn't permit keeping the keywords out of the application namespace). + */ +#if !__GNUC_PREREQ__(2, 7) +#define __printflike(fmtarg, firstvararg) +#define __scanflike(fmtarg, firstvararg) +#else +#define __printflike(fmtarg, firstvararg) \ + __attribute__((__format__ (__printf__, fmtarg, firstvararg))) +#define __scanflike(fmtarg, firstvararg) \ + __attribute__((__format__ (__scanf__, fmtarg, firstvararg))) +#endif + +/* Compiler-dependent macros that rely on FreeBSD-specific extensions. */ +#if __FreeBSD_cc_version >= 300001 +#define __printf0like(fmtarg, firstvararg) \ + __attribute__((__format__ (__printf0__, fmtarg, firstvararg))) +#else +#define __printf0like(fmtarg, firstvararg) +#endif + +#ifdef __GNUC__ +#define __strong_reference(sym,aliassym) \ + extern __typeof (sym) aliassym __attribute__ ((__alias__ (#sym))); +#ifdef __STDC__ +#define __weak_reference(sym,alias) \ + __asm__(".weak " #alias); \ + __asm__(".equ " #alias ", " #sym) +#define __warn_references(sym,msg) \ + __asm__(".section .gnu.warning." #sym); \ + __asm__(".asciz \"" msg "\""); \ + __asm__(".previous") +#else +#define __weak_reference(sym,alias) \ + __asm__(".weak alias"); \ + __asm__(".equ alias, sym") +#define __warn_references(sym,msg) \ + __asm__(".section .gnu.warning.sym"); \ + __asm__(".asciz \"msg\""); \ + __asm__(".previous") +#endif /* __STDC__ */ +#endif /* __GNUC__ */ + +#ifdef __GNUC__ +#define __IDSTRING(name,string) __asm__(".ident\t\"" string "\"") +#else +/* + * The following definition might not work well if used in header files, + * but it should be better than nothing. If you want a "do nothing" + * version, then it should generate some harmless declaration, such as: + * #define __IDSTRING(name,string) struct __hack + */ +#define __IDSTRING(name,string) static const char name[] __unused = string +#endif + +/* + * Embed the rcs id of a source file in the resulting library. Note that in + * more recent ELF binutils, we use .ident allowing the ID to be stripped. + * Usage: + * __FBSDID("$FreeBSD: src/sys/sys/cdefs.h,v 1.79 2003/10/31 05:42:53 peter Exp $"); + */ +#ifndef __FBSDID +#if !defined(lint) && !defined(STRIP_FBSDID) +#define __FBSDID(s) __IDSTRING(__CONCAT(__rcsid_,__LINE__),s) +#else +#define __FBSDID(s) struct __hack +#endif +#endif + +#ifndef __RCSID +#ifndef NO__RCSID +#define __RCSID(s) __IDSTRING(__CONCAT(__rcsid_,__LINE__),s) +#else +#define __RCSID(s) struct __hack +#endif +#endif + +#ifndef __RCSID_SOURCE +#ifndef NO__RCSID_SOURCE +#define __RCSID_SOURCE(s) __IDSTRING(__CONCAT(__rcsid_source_,__LINE__),s) +#else +#define __RCSID_SOURCE(s) struct __hack +#endif +#endif + +#ifndef __SCCSID +#ifndef NO__SCCSID +#define __SCCSID(s) __IDSTRING(__CONCAT(__sccsid_,__LINE__),s) +#else +#define __SCCSID(s) struct __hack +#endif +#endif + +#ifndef __COPYRIGHT +#ifndef NO__COPYRIGHT +#define __COPYRIGHT(s) __IDSTRING(__CONCAT(__copyright_,__LINE__),s) +#else +#define __COPYRIGHT(s) struct __hack +#endif +#endif + +#ifndef __DECONST +#define __DECONST(type, var) ((type)(uintptr_t)(const void *)(var)) +#endif + +#ifndef __DEVOLATILE +#define __DEVOLATILE(type, var) ((type)(uintptr_t)(volatile void *)(var)) +#endif + +#ifndef __DEQUALIFY +#define __DEQUALIFY(type, var) ((type)(uintptr_t)(const volatile void *)(var)) +#endif + +/*- + * The following definitions are an extension of the behavior originally + * implemented in , but with a different level of granularity. + * POSIX.1 requires that the macros we test be defined before any standard + * header file is included. + * + * Here's a quick run-down of the versions: + * defined(_POSIX_SOURCE) 1003.1-1988 + * _POSIX_C_SOURCE == 1 1003.1-1990 + * _POSIX_C_SOURCE == 2 1003.2-1992 C Language Binding Option + * _POSIX_C_SOURCE == 199309 1003.1b-1993 + * _POSIX_C_SOURCE == 199506 1003.1c-1995, 1003.1i-1995, + * and the omnibus ISO/IEC 9945-1: 1996 + * _POSIX_C_SOURCE == 200112 1003.1-2001 + * + * In addition, the X/Open Portability Guide, which is now the Single UNIX + * Specification, defines a feature-test macro which indicates the version of + * that specification, and which subsumes _POSIX_C_SOURCE. + * + * Our macros begin with two underscores to avoid namespace screwage. + */ + +/* Deal with IEEE Std. 1003.1-1990, in which _POSIX_C_SOURCE == 1. */ +#if defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE == 1 +#undef _POSIX_C_SOURCE /* Probably illegal, but beyond caring now. */ +#define _POSIX_C_SOURCE 199009 +#endif + +/* Deal with IEEE Std. 1003.2-1992, in which _POSIX_C_SOURCE == 2. */ +#if defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE == 2 +#undef _POSIX_C_SOURCE +#define _POSIX_C_SOURCE 199209 +#endif + +/* Deal with various X/Open Portability Guides and Single UNIX Spec. */ +#ifdef _XOPEN_SOURCE +#if _XOPEN_SOURCE - 0 >= 600 +#define __XSI_VISIBLE 600 +#undef _POSIX_C_SOURCE +#define _POSIX_C_SOURCE 200112 +#elif _XOPEN_SOURCE - 0 >= 500 +#define __XSI_VISIBLE 500 +#undef _POSIX_C_SOURCE +#define _POSIX_C_SOURCE 199506 +#endif +#endif + +/* + * Deal with all versions of POSIX. The ordering relative to the tests above is + * important. + */ +#if defined(_POSIX_SOURCE) && !defined(_POSIX_C_SOURCE) +#define _POSIX_C_SOURCE 198808 +#endif +#ifdef _POSIX_C_SOURCE +#if _POSIX_C_SOURCE >= 200112 +#define __POSIX_VISIBLE 200112 +#define __ISO_C_VISIBLE 1999 +#elif _POSIX_C_SOURCE >= 199506 +#define __POSIX_VISIBLE 199506 +#define __ISO_C_VISIBLE 1990 +#elif _POSIX_C_SOURCE >= 199309 +#define __POSIX_VISIBLE 199309 +#define __ISO_C_VISIBLE 1990 +#elif _POSIX_C_SOURCE >= 199209 +#define __POSIX_VISIBLE 199209 +#define __ISO_C_VISIBLE 1990 +#elif _POSIX_C_SOURCE >= 199009 +#define __POSIX_VISIBLE 199009 +#define __ISO_C_VISIBLE 1990 +#else +#define __POSIX_VISIBLE 198808 +#define __ISO_C_VISIBLE 0 +#endif /* _POSIX_C_SOURCE */ +#else +/*- + * Deal with _ANSI_SOURCE: + * If it is defined, and no other compilation environment is explicitly + * requested, then define our internal feature-test macros to zero. This + * makes no difference to the preprocessor (undefined symbols in preprocessing + * expressions are defined to have value zero), but makes it more convenient for + * a test program to print out the values. + * + * If a program mistakenly defines _ANSI_SOURCE and some other macro such as + * _POSIX_C_SOURCE, we will assume that it wants the broader compilation + * environment (and in fact we will never get here). + */ +#if defined(_ANSI_SOURCE) /* Hide almost everything. */ +#define __POSIX_VISIBLE 0 +#define __XSI_VISIBLE 0 +#define __BSD_VISIBLE 0 +#define __ISO_C_VISIBLE 1990 +#elif defined(_C99_SOURCE) /* Localism to specify strict C99 env. */ +#define __POSIX_VISIBLE 0 +#define __XSI_VISIBLE 0 +#define __BSD_VISIBLE 0 +#define __ISO_C_VISIBLE 1999 +#else /* Default environment: show everything. */ +#define __POSIX_VISIBLE 200112 +#define __XSI_VISIBLE 600 +#define __BSD_VISIBLE 1 +#define __ISO_C_VISIBLE 1999 +#endif +#endif + +#endif /* !_SYS_CDEFS_H_ */ diff --git a/src/include/sys/disk.h b/src/include/sys/disk.h new file mode 100644 index 0000000..5070a51 --- /dev/null +++ b/src/include/sys/disk.h @@ -0,0 +1,71 @@ +/* + * ---------------------------------------------------------------------------- + * "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 + * ---------------------------------------------------------------------------- + * + * $FreeBSD: src/sys/sys/disk.h,v 1.39 2003/04/01 18:55:04 phk Exp $ + * + */ + +#ifndef _SYS_DISK_H_ +#define _SYS_DISK_H_ + +#include + +#ifdef _KERNEL + +#ifndef _SYS_CONF_H_ +#include /* XXX: temporary to avoid breakage */ +#endif + +struct disk; +struct disk *disk_enumerate(struct disk *disk); +void disk_err(struct bio *bp, const char *what, int blkdone, int nl); + +#endif + +#define DIOCGSECTORSIZE _IOR('d', 128, uInt32) + /*- + * Get the sectorsize of the device in bytes. The sectorsize is the + * smallest unit of data which can be transfered from this device. + * Usually this is a power of two but it may not be. (ie: CDROM audio) + */ + +#define DIOCGMEDIASIZE _IOR('d', 129, off_t) /* Get media size in bytes */ + /*- + * Get the size of the entire device in bytes. This should be a + * multiple of the sectorsize. + */ + +#define DIOCGFWSECTORS _IOR('d', 130, uInt32) /* Get firmware sectorcount */ + /*- + * Get the firmwares notion of number of sectors per track. This + * value is mostly used for compatibility with various ill designed + * disk label formats. Don't use it unless you have to. + */ + +#define DIOCGFWHEADS _IOR('d', 131, uInt32) /* Get firmware headcount */ + /*- + * Get the firmwares notion of number of heads per cylinder. This + * value is mostly used for compatibility with various ill designed + * disk label formats. Don't use it unless you have to. + */ + +#define DIOCSKERNELDUMP _IOW('d', 133, uInt32) /* Set/Clear kernel dumps */ + /*- + * Enable/Disable (the argument is boolean) the device for kernel + * core dumps. + */ + +#define DIOCGFRONTSTUFF _IOR('d', 134, off_t) + /*- + * Many disk formats have some amount of space reserved at the + * start of the disk to hold bootblocks, various disklabels and + * similar stuff. This ioctl returns the number of such bytes + * which may apply to the device. + */ + +#endif /* _SYS_DISK_H_ */ diff --git a/src/include/sys/diskmbr.h b/src/include/sys/diskmbr.h new file mode 100644 index 0000000..54d49c6 --- /dev/null +++ b/src/include/sys/diskmbr.h @@ -0,0 +1,81 @@ +/* + * Copyright (c) 1987, 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. + * + * @(#)disklabel.h 8.2 (Berkeley) 7/10/94 + * $FreeBSD: src/sys/sys/diskmbr.h,v 1.98 2003/04/13 21:52:22 phk Exp $ + */ + +#ifndef _SYS_DISKMBR_H_ +#define _SYS_DISKMBR_H_ + +#include + +#define DOSBBSECTOR 0 /* DOS boot block relative sector number */ +#define DOSPARTOFF 446 +#define DOSPARTSIZE 16 +#define NDOSPART 4 +#define NEXTDOSPART 32 +#define DOSMAGICOFFSET 510 +#define DOSMAGIC 0xAA55 + +#define DOSPTYP_386BSD 0xa5 /* 386BSD partition type */ +#define DOSPTYP_LINSWP 0x82 /* Linux swap partition */ +#define DOSPTYP_LINUX 0x83 /* Linux partition */ +#define DOSPTYP_PMBR 0xee /* GPT Protective MBR */ +#define DOSPTYP_EXT 5 /* DOS extended partition */ +#define DOSPTYP_EXTLBA 15 /* DOS extended partition */ + +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_typ; /* 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 */ +}; +#ifdef CTASSERT +CTASSERT(sizeof (struct dos_partition) == DOSPARTSIZE); +#endif + +void dos_partition_dec(void const *pp, struct dos_partition *d); +void dos_partition_enc(void *pp, struct dos_partition *d); + +#define DPSECT(s) ((s) & 0x3f) /* isolate relevant bits of sector */ +#define DPCYL(c, s) ((c) + (((s) & 0xc0)<<2)) /* and those that are cylinder */ + +#define DIOCSMBR _IOW('M', 129, uInt8[512]) + +#endif /* !_SYS_DISKMBR_H_ */ diff --git a/src/include/sys/endian.h b/src/include/sys/endian.h new file mode 100644 index 0000000..f01c874 --- /dev/null +++ b/src/include/sys/endian.h @@ -0,0 +1,200 @@ +/*- + * Copyright (c) 2002 Thomas Moestl + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must 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/sys/sys/endian.h,v 1.6 2003/10/15 20:05:57 obrien Exp $ + */ + +#ifndef _SYS_ENDIAN_H_ +#define _SYS_ENDIAN_H_ + +#include +#include +#include + +#ifndef _UINT16_T_DECLARED +typedef __uInt16 uInt16; +#define _UINT16_T_DECLARED +#endif + +#ifndef _UINT32_T_DECLARED +typedef __uInt32 uInt32; +#define _UINT32_T_DECLARED +#endif + +#ifndef _UINT64_T_DECLARED +typedef __uInt64 uInt64; +#define _UINT64_T_DECLARED +#endif + +/* + * General byte order swapping functions. + */ +#define bswap16(x) __bswap16(x) +#define bswap32(x) __bswap32(x) +#define bswap64(x) __bswap64(x) + +/* + * Host to big endian, host to little endian, big endian to host, and little + * endian to host byte order functions as detailed in byteorder(9). + */ +#if _BYTE_ORDER == _LITTLE_ENDIAN +#define htobe16(x) bswap16((x)) +#define htobe32(x) bswap32((x)) +#define htobe64(x) bswap64((x)) +#define htole16(x) ((uInt16)(x)) +#define htole32(x) ((uInt32)(x)) +#define htole64(x) ((uInt64)(x)) + +#define be16toh(x) bswap16((x)) +#define be32toh(x) bswap32((x)) +#define be64toh(x) bswap64((x)) +#define le16toh(x) ((uInt16)(x)) +#define le32toh(x) ((uInt32)(x)) +#define le64toh(x) ((uInt64)(x)) +#else /* _BYTE_ORDER != _LITTLE_ENDIAN */ +#define htobe16(x) ((uInt16)(x)) +#define htobe32(x) ((uInt32)(x)) +#define htobe64(x) ((uInt64)(x)) +#define htole16(x) bswap16((x)) +#define htole32(x) bswap32((x)) +#define htole64(x) bswap64((x)) + +#define be16toh(x) ((uInt16)(x)) +#define be32toh(x) ((uInt32)(x)) +#define be64toh(x) ((uInt64)(x)) +#define le16toh(x) bswap16((x)) +#define le32toh(x) bswap32((x)) +#define le64toh(x) bswap64((x)) +#endif /* _BYTE_ORDER == _LITTLE_ENDIAN */ + +/* Alignment-agnostic encode/decode bytestream to/from little/big endian. */ + +static __inline uInt16 +be16dec(const void *pp) +{ + unsigned char const *p = (unsigned char const *)pp; + + return ((p[0] << 8) | p[1]); +} + +static __inline uInt32 +be32dec(const void *pp) +{ + unsigned char const *p = (unsigned char const *)pp; + + return ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); +} + +static __inline uInt64 +be64dec(const void *pp) +{ + unsigned char const *p = (unsigned char const *)pp; + + return (((uInt64)be32dec(p) << 32) | be32dec(p + 4)); +} + +static __inline uInt16 +le16dec(const void *pp) +{ + unsigned char const *p = (unsigned char const *)pp; + + return ((p[1] << 8) | p[0]); +} + +static __inline uInt32 +le32dec(const void *pp) +{ + unsigned char const *p = (unsigned char const *)pp; + + return ((p[3] << 24) | (p[2] << 16) | (p[1] << 8) | p[0]); +} + +static __inline uInt64 +le64dec(const void *pp) +{ + unsigned char const *p = (unsigned char const *)pp; + + return (((uInt64)le32dec(p + 4) << 32) | le32dec(p)); +} + +static __inline void +be16enc(void *pp, uInt16 u) +{ + unsigned char *p = (unsigned char *)pp; + + p[0] = (u >> 8) & 0xff; + p[1] = u & 0xff; +} + +static __inline void +be32enc(void *pp, uInt32 u) +{ + unsigned char *p = (unsigned char *)pp; + + p[0] = (u >> 24) & 0xff; + p[1] = (u >> 16) & 0xff; + p[2] = (u >> 8) & 0xff; + p[3] = u & 0xff; +} + +static __inline void +be64enc(void *pp, uInt64 u) +{ + unsigned char *p = (unsigned char *)pp; + + be32enc(p, u >> 32); + be32enc(p + 4, u & 0xffffffff); +} + +static __inline void +le16enc(void *pp, uInt16 u) +{ + unsigned char *p = (unsigned char *)pp; + + p[0] = u & 0xff; + p[1] = (u >> 8) & 0xff; +} + +static __inline void +le32enc(void *pp, uInt32 u) +{ + unsigned char *p = (unsigned char *)pp; + + p[0] = u & 0xff; + p[1] = (u >> 8) & 0xff; + p[2] = (u >> 16) & 0xff; + p[3] = (u >> 24) & 0xff; +} + +static __inline void +le64enc(void *pp, uInt64 u) +{ + unsigned char *p = (unsigned char *)pp; + + le32enc(p, u & 0xffffffff); + le32enc(p + 4, u >> 32); +} + +#endif /* _SYS_ENDIAN_H_ */ diff --git a/src/include/sys/ioccom.h b/src/include/sys/ioccom.h new file mode 100644 index 0000000..4a063e9 --- /dev/null +++ b/src/include/sys/ioccom.h @@ -0,0 +1,75 @@ +/*- + * Copyright (c) 1982, 1986, 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. + * + * @(#)ioccom.h 8.2 (Berkeley) 3/28/94 + * $FreeBSD: src/sys/sys/ioccom.h,v 1.14 2002/04/10 04:53:37 imp Exp $ + */ + +#ifndef _SYS_IOCCOM_H_ +#define _SYS_IOCCOM_H_ + +/* + * Ioctl's have the command encoded in the lower word, and the size of + * any in or out parameters in the upper word. The high 3 bits of the + * upper word are used to encode the in/out status of the parameter. + */ +#define IOCPARM_MASK 0x1fff /* parameter length, at most 13 bits */ +#define IOCPARM_LEN(x) (((x) >> 16) & IOCPARM_MASK) +#define IOCBASECMD(x) ((x) & ~(IOCPARM_MASK << 16)) +#define IOCGROUP(x) (((x) >> 8) & 0xff) + +#define IOCPARM_MAX PAGE_SIZE /* max size of ioctl, mult. of PAGE_SIZE */ +#define IOC_VOID 0x20000000 /* no parameters */ +#define IOC_OUT 0x40000000 /* copy out parameters */ +#define IOC_IN 0x80000000 /* copy in parameters */ +#define IOC_INOUT (IOC_IN|IOC_OUT) +#define IOC_DIRMASK 0xe0000000 /* mask for IN/OUT/VOID */ + +#define _IOC(inout,group,num,len) \ + ((unsigned long)(inout | ((len & IOCPARM_MASK) << 16) | ((group) << 8) | (num))) +#define _IO(g,n) _IOC(IOC_VOID, (g), (n), 0) +#define _IOR(g,n,t) _IOC(IOC_OUT, (g), (n), sizeof(t)) +#define _IOW(g,n,t) _IOC(IOC_IN, (g), (n), sizeof(t)) +/* this should be _IORW, but stdio got there first */ +#define _IOWR(g,n,t) _IOC(IOC_INOUT, (g), (n), sizeof(t)) + +#ifndef _KERNEL + +#include + +__BEGIN_DECLS +int ioctl(int, unsigned long, ...); +__END_DECLS + +#endif + +#endif /* !_SYS_IOCCOM_H_ */ diff --git a/src/include/sys/limits.h b/src/include/sys/limits.h new file mode 100644 index 0000000..20f2f74 --- /dev/null +++ b/src/include/sys/limits.h @@ -0,0 +1,100 @@ +/* + * 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. + * + * $FreeBSD: src/sys/sys/limits.h,v 1.6 2004/02/26 03:53:54 mlaier Exp $ + */ + +#ifndef _SYS_LIMITS_H_ +#define _SYS_LIMITS_H_ + +#include +#include + +#define CHAR_BIT __CHAR_BIT /* number of bits in a char */ + +#define SCHAR_MAX __SCHAR_MAX /* max value for a signed char */ +#define SCHAR_MIN __SCHAR_MIN /* min value for a signed char */ + +#define UCHAR_MAX __UCHAR_MAX /* max value for an unsigned char */ + +#ifdef __CHAR_UNSIGNED__ +#define CHAR_MAX UCHAR_MAX /* max value for a char */ +#define CHAR_MIN 0 /* min value for a char */ +#else +#define CHAR_MAX SCHAR_MAX +#define CHAR_MIN SCHAR_MIN +#endif + +#define USHRT_MAX __USHRT_MAX /* max value for an unsigned short */ +#define SHRT_MAX __SHRT_MAX /* max value for a short */ +#define SHRT_MIN __SHRT_MIN /* min value for a short */ + +#define UINT_MAX __UINT_MAX /* max value for an unsigned int */ +#define INT_MAX __INT_MAX /* max value for an int */ +#define INT_MIN __INT_MIN /* min value for an int */ + +#define ULONG_MAX __ULONG_MAX /* max for an unsigned long */ +#define LONG_MAX __LONG_MAX /* max for a long */ +#define LONG_MIN __LONG_MIN /* min for a long */ + +#define UID_MAX UINT_MAX /* max value for a uid_t */ +#define GID_MAX UINT_MAX /* max value for a gid_t */ + +#ifdef __LONG_LONG_SUPPORTED +#define ULLONG_MAX __ULLONG_MAX /* max for an unsigned long long */ +#define LLONG_MAX __LLONG_MAX /* max for a long long */ +#define LLONG_MIN __LLONG_MIN /* min for a long long */ +#endif + +#if __POSIX_VISIBLE || __XSI_VISIBLE +#define SSIZE_MAX __SSIZE_MAX /* max value for an ssize_t */ +#endif + +#if __POSIX_VISIBLE >= 200112 || __XSI_VISIBLE +#define SIZE_T_MAX __SIZE_T_MAX /* max value for a size_t */ + +#define OFF_MAX __OFF_MAX /* max value for an off_t */ +#define OFF_MIN __OFF_MIN /* min value for an off_t */ +#endif + +#if __BSD_VISIBLE +#define UQUAD_MAX (__UQUAD_MAX) /* max value for a uquad_t */ +#define QUAD_MAX (__QUAD_MAX) /* max value for a quad_t */ +#define QUAD_MIN (__QUAD_MIN) /* min value for a quad_t */ +#endif + +#if __XSI_VISIBLE +#define LONG_BIT __LONG_BIT +#define WORD_BIT __WORD_BIT +#endif + +#endif /* !_SYS_LIMITS_H_ */ diff --git a/src/include/sys/mman.h b/src/include/sys/mman.h new file mode 100644 index 0000000..a8130c5 --- /dev/null +++ b/src/include/sys/mman.h @@ -0,0 +1,36 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#ifndef _MMAN_H +#define _MMAN_H + +#include + +void *mmap(void *, size_t, int, int, int, off_t); + +#endif + +/*** + END + ***/ + diff --git a/src/include/sys/mount.h b/src/include/sys/mount.h new file mode 100644 index 0000000..93e6182 --- /dev/null +++ b/src/include/sys/mount.h @@ -0,0 +1,577 @@ +/* + * Copyright (c) 1989, 1991, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * @(#)mount.h 8.21 (Berkeley) 5/20/95 + * $FreeBSD: src/sys/sys/mount.h,v 1.153 2004/02/02 18:24:29 pjd Exp $ + */ + +#ifndef _SYS_MOUNT_H_ +#define _SYS_MOUNT_H_ + +#include +#include +#ifdef _KERNEL +#include +#include +#include +#endif + +typedef struct fsid { int32_t val[2]; } fsid_t; /* filesystem id type */ + +/* + * File identifier. + * These are unique per filesystem on a single machine. + */ +#define MAXFIDSZ 16 + +struct fid { + uInt16 fid_len; /* length of data in bytes */ + uInt16 fid_reserved; /* force longword alignment */ + char fid_data[MAXFIDSZ]; /* data (variable length) */ +}; + +/* + * filesystem statistics + */ +#define MFSNAMELEN 16 /* length of type name including null */ +#define MNAMELEN 88 /* size of on/from name bufs */ +#define STATFS_VERSION 0x20030518 /* current version number */ +struct statfs { + uInt32 f_version; /* structure version number */ + uInt32 f_type; /* type of filesystem */ + uInt64 f_flags; /* copy of mount exported flags */ + uInt64 f_bsize; /* filesystem fragment size */ + uInt64 f_iosize; /* optimal transfer block size */ + uInt64 f_blocks; /* total data blocks in filesystem */ + uInt64 f_bfree; /* free blocks in filesystem */ + int64_t f_bavail; /* free blocks avail to non-superuser */ + uInt64 f_files; /* total file nodes in filesystem */ + int64_t f_ffree; /* free nodes avail to non-superuser */ + uInt64 f_syncwrites; /* count of sync writes since mount */ + uInt64 f_asyncwrites; /* count of async writes since mount */ + uInt64 f_syncreads; /* count of sync reads since mount */ + uInt64 f_asyncreads; /* count of async reads since mount */ + uInt64 f_spare[10]; /* unused spare */ + uInt32 f_namemax; /* maximum filename length */ + uid_t f_owner; /* user that mounted the filesystem */ + fsid_t f_fsid; /* filesystem id */ + char f_charspare[80]; /* spare string space */ + char f_fstypename[MFSNAMELEN]; /* filesystem type name */ + char f_mntfromname[MNAMELEN]; /* mounted filesystem */ + char f_mntonname[MNAMELEN]; /* directory on which mounted */ +}; + +#ifdef _KERNEL +#define OMFSNAMELEN 16 /* length of fs type name, including null */ +#define OMNAMELEN (88 - 2 * sizeof(long)) /* size of on/from name bufs */ + +/* XXX getfsstat.2 is out of date with write and read counter changes here. */ +/* XXX statfs.2 is out of date with read counter changes here. */ +struct ostatfs { + long f_spare2; /* placeholder */ + long f_bsize; /* fundamental filesystem block size */ + long f_iosize; /* optimal transfer block size */ + long f_blocks; /* total data blocks in filesystem */ + long f_bfree; /* free blocks in fs */ + long f_bavail; /* free blocks avail to non-superuser */ + long f_files; /* total file nodes in filesystem */ + long f_ffree; /* free file nodes in fs */ + fsid_t f_fsid; /* filesystem id */ + uid_t f_owner; /* user that mounted the filesystem */ + int f_type; /* type of filesystem */ + int f_flags; /* copy of mount exported flags */ + long f_syncwrites; /* count of sync writes since mount */ + long f_asyncwrites; /* count of async writes since mount */ + char f_fstypename[OMFSNAMELEN]; /* fs type name */ + char f_mntonname[OMNAMELEN]; /* directory on which mounted */ + long f_syncreads; /* count of sync reads since mount */ + long f_asyncreads; /* count of async reads since mount */ + short f_spares1; /* unused spare */ + char f_mntfromname[OMNAMELEN];/* mounted filesystem */ + short f_spares2; /* unused spare */ + /* + * XXX on machines where longs are aligned to 8-byte boundaries, there + * is an unnamed int32_t here. This spare was after the apparent end + * of the struct until we bit off the read counters from f_mntonname. + */ + long f_spare[2]; /* unused spare */ +}; + +#define MMAXOPTIONLEN 65536 /* maximum length of a mount option */ + +TAILQ_HEAD(vnodelst, vnode); +TAILQ_HEAD(vfsoptlist, vfsopt); +struct vfsopt { + TAILQ_ENTRY(vfsopt) link; + char *name; + void *value; + int len; +}; + +/* + * Structure per mounted filesystem. Each mounted filesystem has an + * array of operations and an instance record. The filesystems are + * put on a doubly linked list. + * + * NOTE: mnt_nvnodelist and mnt_reservedvnlist. At the moment vnodes + * are linked into mnt_nvnodelist. At some point in the near future the + * vnode list will be split into a 'dirty' and 'clean' list. mnt_nvnodelist + * will become the dirty list and mnt_reservedvnlist will become the 'clean' + * list. Filesystem kld's syncing code should remain compatible since + * they only need to scan the dirty vnode list (nvnodelist -> dirtyvnodelist). + */ +struct mount { + TAILQ_ENTRY(mount) mnt_list; /* mount list */ + struct vfsops *mnt_op; /* operations on fs */ + struct vfsconf *mnt_vfc; /* configuration info */ + struct vnode *mnt_vnodecovered; /* vnode we mounted on */ + struct vnode *mnt_syncer; /* syncer vnode */ + struct vnodelst mnt_nvnodelist; /* list of vnodes this mount */ + struct vnodelst mnt_reservedvnlist; /* (future) dirty vnode list */ + struct lock mnt_lock; /* mount structure lock */ + struct mtx mnt_mtx; /* mount structure interlock */ + int mnt_writeopcount; /* write syscalls in progress */ + int mnt_flag; /* flags shared with user */ + struct vfsoptlist *mnt_opt; /* current mount options */ + struct vfsoptlist *mnt_optnew; /* new options passed to fs */ + int mnt_kern_flag; /* kernel only flags */ + int mnt_maxsymlinklen; /* max size of short symlink */ + struct statfs mnt_stat; /* cache of filesystem stats */ + struct ucred *mnt_cred; /* credentials of mounter */ + qaddr_t mnt_data; /* private data */ + time_t mnt_time; /* last time written*/ + int mnt_iosize_max; /* max size for clusters, etc */ + struct netexport *mnt_export; /* export list */ + struct label *mnt_mntlabel; /* MAC label for the mount */ + struct label *mnt_fslabel; /* MAC label for the fs */ + int mnt_nvnodelistsize; /* # of vnodes on this mount */ +}; + + +#define MNT_ILOCK(mp) mtx_lock(&(mp)->mnt_mtx) +#define MNT_IUNLOCK(mp) mtx_unlock(&(mp)->mnt_mtx) + +#endif /* _KERNEL */ + +/* + * User specifiable flags. + */ +#define MNT_RDONLY 0x00000001 /* read only filesystem */ +#define MNT_SYNCHRONOUS 0x00000002 /* filesystem written synchronously */ +#define MNT_NOEXEC 0x00000004 /* can't exec from filesystem */ +#define MNT_NOSUID 0x00000008 /* don't honor setuid bits on fs */ +#define MNT_NODEV 0x00000010 /* don't interpret special files */ +#define MNT_UNION 0x00000020 /* union with underlying filesystem */ +#define MNT_ASYNC 0x00000040 /* filesystem written asynchronously */ +#define MNT_SUIDDIR 0x00100000 /* special handling of SUID on dirs */ +#define MNT_SOFTDEP 0x00200000 /* soft updates being done */ +#define MNT_NOSYMFOLLOW 0x00400000 /* do not follow symlinks */ +#define MNT_JAILDEVFS 0x02000000 /* jail-friendly DEVFS behaviour */ +#define MNT_MULTILABEL 0x04000000 /* MAC support for individual objects */ +#define MNT_ACLS 0x08000000 /* ACL support enabled */ +#define MNT_NOATIME 0x10000000 /* disable update of file access time */ +#define MNT_NOCLUSTERR 0x40000000 /* disable cluster read */ +#define MNT_NOCLUSTERW 0x80000000 /* disable cluster write */ + +/* + * NFS export related mount flags. + */ +#define MNT_EXRDONLY 0x00000080 /* exported read only */ +#define MNT_EXPORTED 0x00000100 /* filesystem is exported */ +#define MNT_DEFEXPORTED 0x00000200 /* exported to the world */ +#define MNT_EXPORTANON 0x00000400 /* use anon uid mapping for everyone */ +#define MNT_EXKERB 0x00000800 /* exported with Kerberos uid mapping */ +#define MNT_EXPUBLIC 0x20000000 /* public export (WebNFS) */ + +/* + * Flags set by internal operations, + * but visible to the user. + * XXX some of these are not quite right.. (I've never seen the root flag set) + */ +#define MNT_LOCAL 0x00001000 /* filesystem is stored locally */ +#define MNT_QUOTA 0x00002000 /* quotas are enabled on filesystem */ +#define MNT_ROOTFS 0x00004000 /* identifies the root filesystem */ +#define MNT_USER 0x00008000 /* mounted by a user */ +#define MNT_IGNORE 0x00800000 /* do not show entry in df */ + +/* + * Mask of flags that are visible to statfs(). + * XXX I think that this could now become (~(MNT_CMDFLAGS)) + * but the 'mount' program may need changing to handle this. + */ +#define MNT_VISFLAGMASK (MNT_RDONLY | MNT_SYNCHRONOUS | MNT_NOEXEC | \ + MNT_NOSUID | MNT_NODEV | MNT_UNION | \ + MNT_ASYNC | MNT_EXRDONLY | MNT_EXPORTED | \ + MNT_DEFEXPORTED | MNT_EXPORTANON| MNT_EXKERB | \ + MNT_LOCAL | MNT_USER | MNT_QUOTA | \ + MNT_ROOTFS | MNT_NOATIME | MNT_NOCLUSTERR| \ + MNT_NOCLUSTERW | MNT_SUIDDIR | MNT_SOFTDEP | \ + MNT_IGNORE | MNT_EXPUBLIC | MNT_NOSYMFOLLOW | \ + MNT_JAILDEVFS | MNT_MULTILABEL | MNT_ACLS) + +/* Mask of flags that can be updated. */ +#define MNT_UPDATEMASK (MNT_NOSUID | MNT_NOEXEC | MNT_NODEV | \ + MNT_SYNCHRONOUS | MNT_UNION | MNT_ASYNC | \ + MNT_NOATIME | \ + MNT_NOSYMFOLLOW | MNT_IGNORE | MNT_JAILDEVFS | \ + MNT_NOCLUSTERR | MNT_NOCLUSTERW | MNT_SUIDDIR | \ + MNT_ACLS | MNT_USER) + +/* + * External filesystem command modifier flags. + * Unmount can use the MNT_FORCE flag. + * XXX These are not STATES and really should be somewhere else. + */ +#define MNT_UPDATE 0x00010000 /* not a real mount, just an update */ +#define MNT_DELEXPORT 0x00020000 /* delete export host lists */ +#define MNT_RELOAD 0x00040000 /* reload filesystem data */ +#define MNT_FORCE 0x00080000 /* force unmount or readonly change */ +#define MNT_SNAPSHOT 0x01000000 /* snapshot the filesystem */ +#define MNT_BYFSID 0x08000000 /* specify filesystem by ID. */ +#define MNT_CMDFLAGS (MNT_UPDATE | MNT_DELEXPORT | MNT_RELOAD | \ + MNT_FORCE | MNT_SNAPSHOT | MNT_BYFSID) +/* + * Internal filesystem control flags stored in mnt_kern_flag. + * + * MNTK_UNMOUNT locks the mount entry so that name lookup cannot proceed + * past the mount point. This keeps the subtree stable during mounts + * and unmounts. + * + * MNTK_UNMOUNTF permits filesystems to detect a forced unmount while + * dounmount() is still waiting to lock the mountpoint. This allows + * the filesystem to cancel operations that might otherwise deadlock + * with the unmount attempt (used by NFS). + */ +#define MNTK_UNMOUNTF 0x00000001 /* forced unmount in progress */ +#define MNTK_UNMOUNT 0x01000000 /* unmount in progress */ +#define MNTK_MWAIT 0x02000000 /* waiting for unmount to finish */ +#define MNTK_WANTRDWR 0x04000000 /* upgrade to read/write requested */ +#define MNTK_SUSPEND 0x08000000 /* request write suspension */ +#define MNTK_SUSPENDED 0x10000000 /* write operations are suspended */ + +/* + * Sysctl CTL_VFS definitions. + * + * Second level identifier specifies which filesystem. Second level + * identifier VFS_VFSCONF returns information about all filesystems. + * Second level identifier VFS_GENERIC is non-terminal. + */ +#define VFS_VFSCONF 0 /* get configured filesystems */ +#define VFS_GENERIC 0 /* generic filesystem information */ +/* + * Third level identifiers for VFS_GENERIC are given below; third + * level identifiers for specific filesystems are given in their + * mount specific header files. + */ +#define VFS_MAXTYPENUM 1 /* int: highest defined filesystem type */ +#define VFS_CONF 2 /* struct: vfsconf for filesystem given + as next argument */ + +/* + * Flags for various system call interfaces. + * + * waitfor flags to vfs_sync() and getfsstat() + */ +#define MNT_WAIT 1 /* synchronously wait for I/O to complete */ +#define MNT_NOWAIT 2 /* start all I/O, but do not wait for it */ +#define MNT_LAZY 3 /* push data not written by filesystem syncer */ + +/* + * Generic file handle + */ +struct fhandle { + fsid_t fh_fsid; /* Filesystem id of mount point */ + struct fid fh_fid; /* Filesys specific id */ +}; +typedef struct fhandle fhandle_t; + +/* + * Export arguments for local filesystem mount calls. + */ +struct export_args { + int ex_flags; /* export related flags */ + uid_t ex_root; /* mapping for root uid */ + struct xucred ex_anon; /* mapping for anonymous user */ + struct sockaddr *ex_addr; /* net address to which exported */ + uInt8 ex_addrlen; /* and the net address length */ + struct sockaddr *ex_mask; /* mask of valid bits in saddr */ + uInt8 ex_masklen; /* and the smask length */ + char *ex_indexfile; /* index file for WebNFS URLs */ +}; + +/* + * Structure holding information for a publicly exported filesystem + * (WebNFS). Currently the specs allow just for one such filesystem. + */ +struct nfs_public { + int np_valid; /* Do we hold valid information */ + fhandle_t np_handle; /* Filehandle for pub fs (internal) */ + struct mount *np_mount; /* Mountpoint of exported fs */ + char *np_index; /* Index file */ +}; + +/* + * Filesystem configuration information. One of these exists for each + * type of filesystem supported by the kernel. These are searched at + * mount time to identify the requested filesystem. + */ +struct vfsconf { + struct vfsops *vfc_vfsops; /* filesystem operations vector */ + char vfc_name[MFSNAMELEN]; /* filesystem type name */ + int vfc_typenum; /* historic filesystem type number */ + int vfc_refcount; /* number mounted of this type */ + int vfc_flags; /* permanent flags */ + struct vfsoptdecl *vfc_opts; /* mount options */ + struct vfsconf *vfc_next; /* next in list */ +}; + +/* Userland version of the struct vfsconf. */ +struct xvfsconf { + struct vfsops *vfc_vfsops; /* filesystem operations vector */ + char vfc_name[MFSNAMELEN]; /* filesystem type name */ + int vfc_typenum; /* historic filesystem type number */ + int vfc_refcount; /* number mounted of this type */ + int vfc_flags; /* permanent flags */ + struct vfsconf *vfc_next; /* next in list */ +}; + +struct ovfsconf { + void *vfc_vfsops; + char vfc_name[32]; + int vfc_index; + int vfc_refcount; + int vfc_flags; +}; + +/* + * NB: these flags refer to IMPLEMENTATION properties, not properties of + * any actual mounts; i.e., it does not make sense to change the flags. + */ +#define VFCF_STATIC 0x00010000 /* statically compiled into kernel */ +#define VFCF_NETWORK 0x00020000 /* may get data over the network */ +#define VFCF_READONLY 0x00040000 /* writes are not implemented */ +#define VFCF_SYNTHETIC 0x00080000 /* data does not represent real files */ +#define VFCF_LOOPBACK 0x00100000 /* aliases some other mounted FS */ +#define VFCF_UNICODE 0x00200000 /* stores file names as Unicode*/ + +struct iovec; +struct uio; + +#ifdef _KERNEL + +#ifdef MALLOC_DECLARE +MALLOC_DECLARE(M_MOUNT); +#endif +extern int maxvfsconf; /* highest defined filesystem type */ +extern int nfs_mount_type; /* vfc_typenum for nfs, or -1 */ +extern struct vfsconf *vfsconf; /* head of list of filesystem types */ + +/* + * Operations supported on mounted filesystem. + */ +struct mount_args; +struct nameidata; + +typedef int vfs_mount_t(struct mount *mp, char *path, caddr_t data, + struct nameidata *ndp, struct thread *td); +typedef int vfs_start_t(struct mount *mp, int flags, struct thread *td); +typedef int vfs_unmount_t(struct mount *mp, int mntflags, struct thread *td); +typedef int vfs_root_t(struct mount *mp, struct vnode **vpp); +typedef int vfs_quotactl_t(struct mount *mp, int cmds, uid_t uid, + caddr_t arg, struct thread *td); +typedef int vfs_statfs_t(struct mount *mp, struct statfs *sbp, + struct thread *td); +typedef int vfs_sync_t(struct mount *mp, int waitfor, struct ucred *cred, + struct thread *td); +typedef int vfs_vget_t(struct mount *mp, ino_t ino, int flags, + struct vnode **vpp); +typedef int vfs_fhtovp_t(struct mount *mp, struct fid *fhp, struct vnode **vpp); +typedef int vfs_checkexp_t(struct mount *mp, struct sockaddr *nam, + int *extflagsp, struct ucred **credanonp); +typedef int vfs_vptofh_t(struct vnode *vp, struct fid *fhp); +typedef int vfs_init_t(struct vfsconf *); +typedef int vfs_uninit_t(struct vfsconf *); +typedef int vfs_extattrctl_t(struct mount *mp, int cmd, + struct vnode *filename_vp, int attrnamespace, + const char *attrname, struct thread *td); +typedef int vfs_nmount_t(struct mount *mp, struct nameidata *ndp, + struct thread *td); + +struct vfsops { + vfs_mount_t *vfs_mount; + vfs_start_t *vfs_start; + vfs_unmount_t *vfs_unmount; + vfs_root_t *vfs_root; + vfs_quotactl_t *vfs_quotactl; + vfs_statfs_t *vfs_statfs; + vfs_sync_t *vfs_sync; + vfs_vget_t *vfs_vget; + vfs_fhtovp_t *vfs_fhtovp; + vfs_checkexp_t *vfs_checkexp; + vfs_vptofh_t *vfs_vptofh; + vfs_init_t *vfs_init; + vfs_uninit_t *vfs_uninit; + vfs_extattrctl_t *vfs_extattrctl; + /* Additions below are not binary compatible with 5.0 and below. */ + vfs_nmount_t *vfs_nmount; +}; + +#define VFS_NMOUNT(MP, NDP, P) (*(MP)->mnt_op->vfs_nmount)(MP, NDP, P) +#define VFS_MOUNT(MP, PATH, DATA, NDP, P) \ + (*(MP)->mnt_op->vfs_mount)(MP, PATH, DATA, NDP, P) +#define VFS_START(MP, FLAGS, P) (*(MP)->mnt_op->vfs_start)(MP, FLAGS, P) +#define VFS_UNMOUNT(MP, FORCE, P) (*(MP)->mnt_op->vfs_unmount)(MP, FORCE, P) +#define VFS_ROOT(MP, VPP) (*(MP)->mnt_op->vfs_root)(MP, VPP) +#define VFS_QUOTACTL(MP,C,U,A,P) (*(MP)->mnt_op->vfs_quotactl)(MP, C, U, A, P) +#define VFS_STATFS(MP, SBP, P) (*(MP)->mnt_op->vfs_statfs)(MP, SBP, P) +#define VFS_SYNC(MP, WAIT, C, P) (*(MP)->mnt_op->vfs_sync)(MP, WAIT, C, P) +#define VFS_VGET(MP, INO, FLAGS, VPP) \ + (*(MP)->mnt_op->vfs_vget)(MP, INO, FLAGS, VPP) +#define VFS_FHTOVP(MP, FIDP, VPP) \ + (*(MP)->mnt_op->vfs_fhtovp)(MP, FIDP, VPP) +#define VFS_VPTOFH(VP, FIDP) (*(VP)->v_mount->mnt_op->vfs_vptofh)(VP, FIDP) +#define VFS_CHECKEXP(MP, NAM, EXFLG, CRED) \ + (*(MP)->mnt_op->vfs_checkexp)(MP, NAM, EXFLG, CRED) +#define VFS_EXTATTRCTL(MP, C, FN, NS, N, P) \ + (*(MP)->mnt_op->vfs_extattrctl)(MP, C, FN, NS, N, P) + +#include + +#define VFS_SET(vfsops, fsname, flags) \ + static struct vfsconf fsname ## _vfsconf = { \ + &vfsops, \ + #fsname, \ + -1, \ + 0, \ + flags \ + }; \ + static moduledata_t fsname ## _mod = { \ + #fsname, \ + vfs_modevent, \ + & fsname ## _vfsconf \ + }; \ + DECLARE_MODULE(fsname, fsname ## _mod, SI_SUB_VFS, SI_ORDER_MIDDLE) + +extern char *mountrootfsname; + +/* + * exported vnode operations + */ +int dounmount(struct mount *, int, struct thread *td); +int kernel_mount(struct iovec *iovp, unsigned int iovcnt, int flags); +int kernel_vmount(int flags, ...); +int vfs_getopt(struct vfsoptlist *, const char *, void **, int *); +int vfs_copyopt(struct vfsoptlist *, const char *, void *, int); +int vfs_mount(struct thread *td, const char *type, char *path, + int flags, void *data); +int vfs_setpublicfs /* set publicly exported fs */ + (struct mount *, struct netexport *, struct export_args *); +int vfs_lock(struct mount *); /* lock a vfs */ +void vfs_msync(struct mount *, int); +void vfs_unlock(struct mount *); /* unlock a vfs */ +int vfs_busy(struct mount *, int, struct mtx *, struct thread *td); +int vfs_export /* process mount export info */ + (struct mount *, struct export_args *); +struct netcred *vfs_export_lookup /* lookup host in fs export list */ + (struct mount *, struct sockaddr *); +int vfs_allocate_syncvnode(struct mount *); +void vfs_getnewfsid(struct mount *); +dev_t vfs_getrootfsid(struct mount *); +struct mount *vfs_getvfs(fsid_t *); /* return vfs given fsid */ +int vfs_modevent(module_t, int, void *); +int vfs_mountedon(struct vnode *); /* is a vfs mounted on vp */ +void vfs_mountroot(void); /* mount our root filesystem */ +int vfs_rootmountalloc(char *, char *, struct mount **); +void vfs_mount_destroy(struct mount *, struct thread *); +void vfs_unbusy(struct mount *, struct thread *td); +void vfs_unmountall(void); +int vfs_register(struct vfsconf *); +int vfs_unregister(struct vfsconf *); +extern TAILQ_HEAD(mntlist, mount) mountlist; /* mounted filesystem list */ +extern struct mtx mountlist_mtx; +extern struct nfs_public nfs_pub; + +/* + * Declarations for these vfs default operations are located in + * kern/vfs_default.c, they should be used instead of making "dummy" + * functions or casting entries in the VFS op table to "enopnotsupp()". + */ +vfs_start_t vfs_stdstart; +vfs_root_t vfs_stdroot; +vfs_quotactl_t vfs_stdquotactl; +vfs_statfs_t vfs_stdstatfs; +vfs_sync_t vfs_stdsync; +vfs_sync_t vfs_stdnosync; +vfs_vget_t vfs_stdvget; +vfs_fhtovp_t vfs_stdfhtovp; +vfs_checkexp_t vfs_stdcheckexp; +vfs_vptofh_t vfs_stdvptofh; +vfs_init_t vfs_stdinit; +vfs_uninit_t vfs_stduninit; +vfs_extattrctl_t vfs_stdextattrctl; + +/* XXX - these should be indirect functions!!! */ +int softdep_fsync(struct vnode *); +int softdep_process_worklist(struct mount *); + +#else /* !_KERNEL */ + +#include + +struct stat; + +__BEGIN_DECLS +int fhopen(const struct fhandle *, int); +int fhstat(const struct fhandle *, struct stat *); +int fhstatfs(const struct fhandle *, struct statfs *); +int fstatfs(int, struct statfs *); +int getfh(const char *, fhandle_t *); +int getfsstat(struct statfs *, long, int); +int getmntinfo(struct statfs **, int); +int mount(const char *, const char *, int, void *); +int nmount(struct iovec *, uInt32, int); +int statfs(const char *, struct statfs *); +int unmount(const char *, int); + +/* C library stuff */ +void endvfsent(void); +struct ovfsconf *getvfsbytype(int); +struct ovfsconf *getvfsent(void); +int getvfsbyname(const char *, struct xvfsconf *); +void setvfsent(int); +int vfsisloadable(const char *); +int vfsload(const char *); +__END_DECLS + +#endif /* _KERNEL */ + +#endif /* !_SYS_MOUNT_H_ */ diff --git a/src/include/sys/param.h b/src/include/sys/param.h new file mode 100644 index 0000000..711abe3 --- /dev/null +++ b/src/include/sys/param.h @@ -0,0 +1,331 @@ +/*- + * Copyright (c) 1982, 1986, 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. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * @(#)param.h 8.3 (Berkeley) 4/4/95 + * $FreeBSD: src/sys/sys/param.h,v 1.181 2004/02/25 01:27:32 ache Exp $ + */ + +#ifndef _SYS_PARAM_H_ +#define _SYS_PARAM_H_ + +#include + +#define BSD 199506 /* System version (year & month). */ +#define BSD4_3 1 +#define BSD4_4 1 + +/* + * __FreeBSD_version numbers are documented in the Porter's Handbook. + * If you bump the version for any reason, you should update the documentation + * there. + * Currently this lives here: + * + * doc/en_US.ISO8859-1/books/porters-handbook/book.sgml + * + * scheme is: <0 if release branch, otherwise 1>xx + */ +#undef __FreeBSD_version +#define __FreeBSD_version 502104 /* Master, propagated to newvers */ + +#ifndef LOCORE +#include +#endif + +/* + * Machine-independent constants (some used in following include files). + * Redefined constants are from POSIX 1003.1 limits file. + * + * MAXCOMLEN should be >= sizeof(ac_comm) (see ) + * MAXLOGNAME should be == UT_NAMESIZE+1 (see ) + */ +#include + +#define MAXCOMLEN 19 /* max command name remembered */ +#define MAXINTERP 32 /* max interpreter file name length */ +#define MAXLOGNAME 17 /* max login name length (incl. NUL) */ +#define MAXUPRC CHILD_MAX /* max simultaneous processes */ +#define NCARGS ARG_MAX /* max bytes for an exec function */ +#define NGROUPS NGROUPS_MAX /* max number groups */ +#define NOFILE OPEN_MAX /* max open files per process */ +#define NOGROUP 65535 /* marker for empty group set member */ +#define MAXHOSTNAMELEN 256 /* max hostname size */ +#define SPECNAMELEN 63 /* max length of devicename */ + +/* More types and definitions used throughout the kernel. */ +#ifdef _KERNEL +#if (defined(BURN_BRIDGES) || __FreeBSD_version >= 600000) \ + && defined(OBSOLETE_IN_6) +#error "This file contains obsolete code to be removed in 6.0-current" +#endif +#include +#include +#include +#include + +#define FALSE 0 +#define TRUE 1 +#endif + +#ifndef _KERNEL +/* Signals. */ +#include +#endif + +/* Machine type dependent parameters. */ +#include +#ifndef _KERNEL +#include +#endif + +#ifndef _NO_NAMESPACE_POLLUTION + +#ifndef DEV_BSHIFT +#define DEV_BSHIFT 9 /* log2(DEV_BSIZE) */ +#endif +#define DEV_BSIZE (1<>PAGE_SHIFT) +#endif + +/* + * btodb() is messy and perhaps slow because `bytes' may be an off_t. We + * want to shift an unsigned type to avoid sign extension and we don't + * want to widen `bytes' unnecessarily. Assume that the result fits in + * a daddr_t. + */ +#ifndef btodb +#define btodb(bytes) /* calculates (bytes / DEV_BSIZE) */ \ + (sizeof (bytes) > sizeof(long) \ + ? (daddr_t)((unsigned long long)(bytes) >> DEV_BSHIFT) \ + : (daddr_t)((unsigned long)(bytes) >> DEV_BSHIFT)) +#endif + +#ifndef dbtob +#define dbtob(db) /* calculates (db * DEV_BSIZE) */ \ + ((off_t)(db) << DEV_BSHIFT) +#endif + +#endif /* _NO_NAMESPACE_POLLUTION */ + +#define PRIMASK 0x0ff +#define PCATCH 0x100 /* OR'd with pri for tsleep to check signals */ +#define PDROP 0x200 /* OR'd with pri to stop re-entry of interlock mutex */ + +#define NZERO 0 /* default "nice" */ + +#define NBBY 8 /* number of bits in a byte */ +#define NBPW sizeof(int) /* number of bytes per word (integer) */ + +#define CMASK 022 /* default file mask: S_IWGRP|S_IWOTH */ +#ifdef _KERNEL +#define NOUDEV (udev_t)(-1) /* non-existent device */ +#define NOMAJ 256 /* non-existent device */ +#define NODEV NULL /* non-existent device */ +#else +#define NODEV (dev_t)(-1) /* non-existent device */ +#endif + +#define CBLOCK 128 /* Clist block size, must be a power of 2. */ +#define CBQSIZE (CBLOCK/NBBY) /* Quote bytes/cblock - can do better. */ + /* Data chars/clist. */ +#define CBSIZE (CBLOCK - sizeof(struct cblock *) - CBQSIZE) +#define CROUND (CBLOCK - 1) /* Clist rounding. */ + +/* + * File system parameters and macros. + * + * MAXBSIZE - Filesystems are made out of blocks of at most MAXBSIZE bytes + * per block. MAXBSIZE may be made larger without effecting + * any existing filesystems as long as it does not exceed MAXPHYS, + * and may be made smaller at the risk of not being able to use + * filesystems which require a block size exceeding MAXBSIZE. + * + * BKVASIZE - Nominal buffer space per buffer, in bytes. BKVASIZE is the + * minimum KVM memory reservation the kernel is willing to make. + * Filesystems can of course request smaller chunks. Actual + * backing memory uses a chunk size of a page (PAGE_SIZE). + * + * If you make BKVASIZE too small you risk seriously fragmenting + * the buffer KVM map which may slow things down a bit. If you + * make it too big the kernel will not be able to optimally use + * the KVM memory reserved for the buffer cache and will wind + * up with too-few buffers. + * + * The default is 16384, roughly 2x the block size used by a + * normal UFS filesystem. + */ +#define MAXBSIZE 65536 /* must be power of 2 */ +#define BKVASIZE 16384 /* must be power of 2 */ +#define BKVAMASK (BKVASIZE-1) + +/* + * MAXPATHLEN defines the longest permissible path length after expanding + * symbolic links. It is used to allocate a temporary buffer from the buffer + * pool in which to do the name expansion, hence should be a power of two, + * and must be less than or equal to MAXBSIZE. MAXSYMLINKS defines the + * maximum number of symbolic links that may be expanded in a path name. + * It should be set high enough to allow all legitimate uses, but halt + * infinite loops reasonably quickly. + */ +#define MAXPATHLEN PATH_MAX +#define MAXSYMLINKS 32 + +/* Bit map related macros. */ +#define setbit(a,i) ((a)[(i)/NBBY] |= 1<<((i)%NBBY)) +#define clrbit(a,i) ((a)[(i)/NBBY] &= ~(1<<((i)%NBBY))) +#define isset(a,i) ((a)[(i)/NBBY] & (1<<((i)%NBBY))) +#define isclr(a,i) (((a)[(i)/NBBY] & (1<<((i)%NBBY))) == 0) + +/* Macros for counting and rounding. */ +#ifndef howmany +#define howmany(x, y) (((x)+((y)-1))/(y)) +#endif +#define rounddown(x, y) (((x)/(y))*(y)) +#define roundup(x, y) ((((x)+((y)-1))/(y))*(y)) /* to any y */ +#define roundup2(x, y) (((x)+((y)-1))&(~((y)-1))) /* if y is powers of two */ +#define powerof2(x) ((((x)-1)&(x))==0) + +/* Macros for min/max. */ +#define MIN(a,b) (((a)<(b))?(a):(b)) +#define MAX(a,b) (((a)>(b))?(a):(b)) + +#ifdef _KERNEL +/* + * Basic byte order function prototypes for non-inline functions. + */ +#ifndef _BYTEORDER_PROTOTYPED +#define _BYTEORDER_PROTOTYPED +__BEGIN_DECLS +__uint32_t htonl(__uint32_t); +__uint16_t htons(__uint16_t); +__uint32_t ntohl(__uint32_t); +__uint16_t ntohs(__uint16_t); +__END_DECLS +#endif + +#ifndef lint +#ifndef _BYTEORDER_FUNC_DEFINED +#define _BYTEORDER_FUNC_DEFINED +#define htonl(x) __htonl(x) +#define htons(x) __htons(x) +#define ntohl(x) __ntohl(x) +#define ntohs(x) __ntohs(x) +#endif /* !_BYTEORDER_FUNC_DEFINED */ +#endif /* lint */ +#endif /* _KERNEL */ + +/* + * Constants for setting the parameters of the kernel memory allocator. + * + * 2 ** MINBUCKET is the smallest unit of memory that will be + * allocated. It must be at least large enough to hold a pointer. + * + * Units of memory less or equal to MAXALLOCSAVE will permanently + * allocate physical memory; requests for these size pieces of + * memory are quite fast. Allocations greater than MAXALLOCSAVE must + * always allocate and free physical memory; requests for these + * size allocations should be done infrequently as they will be slow. + * + * Constraints: PAGE_SIZE <= MAXALLOCSAVE <= 2 ** (MINBUCKET + 14), and + * MAXALLOCSIZE must be a power of two. + */ +#if defined(__alpha__) || defined(__ia64__) || defined(__sparc64__) +#define MINBUCKET 5 /* 5 => min allocation of 32 bytes */ +#else +#define MINBUCKET 4 /* 4 => min allocation of 16 bytes */ +#endif +#define MAXALLOCSAVE (2 * PAGE_SIZE) + +/* + * Scale factor for scaled integers used to count %cpu time and load avgs. + * + * The number of CPU `tick's that map to a unique `%age' can be expressed + * by the formula (1 / (2 ^ (FSHIFT - 11))). The maximum load average that + * can be calculated (assuming 32 bits) can be closely approximated using + * the formula (2 ^ (2 * (16 - FSHIFT))) for (FSHIFT < 15). + * + * For the scheduler to maintain a 1:1 mapping of CPU `tick' to `%age', + * FSHIFT must be at least 11; this gives us a maximum load avg of ~1024. + */ +#define FSHIFT 11 /* bits to right of fixed binary point */ +#define FSCALE (1<> (PAGE_SHIFT - DEV_BSHIFT)) + +#define ctodb(db) /* calculates pages to devblks */ \ + ((db) << (PAGE_SHIFT - DEV_BSHIFT)) + +#endif /* _SYS_PARAM_H_ */ diff --git a/src/include/sys/queue.h b/src/include/sys/queue.h new file mode 100644 index 0000000..b93015e --- /dev/null +++ b/src/include/sys/queue.h @@ -0,0 +1,557 @@ +/* + * 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. + * + * @(#)queue.h 8.5 (Berkeley) 8/20/94 + * $FreeBSD: src/sys/sys/queue.h,v 1.56 2003/08/14 14:49:26 kan Exp $ + */ + +#ifndef _SYS_QUEUE_H_ +#define _SYS_QUEUE_H_ + +#include + +/* + * This file defines four types of data structures: singly-linked lists, + * singly-linked tail queues, lists and tail queues. + * + * A singly-linked list is headed by a single forward pointer. The elements + * are singly linked for minimum space and pointer manipulation overhead at + * the expense of O(n) removal for arbitrary elements. New elements can be + * added to the list after an existing element or at the head of the list. + * Elements being removed from the head of the list should use the explicit + * macro for this purpose for optimum efficiency. A singly-linked list may + * only be traversed in the forward direction. Singly-linked lists are ideal + * for applications with large datasets and few or no removals or for + * implementing a LIFO queue. + * + * A singly-linked tail queue is headed by a pair of pointers, one to the + * head of the list and the other to the tail of the list. The elements are + * singly linked for minimum space and pointer manipulation overhead at the + * expense of O(n) removal for arbitrary elements. New elements can be added + * to the list after an existing element, at the head of the list, or at the + * end of the list. Elements being removed from the head of the tail queue + * should use the explicit macro for this purpose for optimum efficiency. + * A singly-linked tail queue may only be traversed in the forward direction. + * Singly-linked tail queues are ideal for applications with large datasets + * and few or no removals or for implementing a FIFO queue. + * + * A list is headed by a single forward pointer (or an array of forward + * pointers for a hash table header). The elements are doubly linked + * so that an arbitrary element can be removed without a need to + * traverse the list. New elements can be added to the list before + * or after an existing element or at the head of the list. A list + * may only be traversed in the forward direction. + * + * A tail queue is headed by a pair of pointers, one to the head of the + * list and the other to the tail of the list. The elements are doubly + * linked so that an arbitrary element can be removed without a need to + * traverse the list. New elements can be added to the list before or + * after an existing element, at the head of the list, or at the end of + * the list. A tail queue may be traversed in either direction. + * + * For details on the use of these macros, see the queue(3) manual page. + * + * + * SLIST LIST STAILQ TAILQ + * _HEAD + + + + + * _HEAD_INITIALIZER + + + + + * _ENTRY + + + + + * _INIT + + + + + * _EMPTY + + + + + * _FIRST + + + + + * _NEXT + + + + + * _PREV - - - + + * _LAST - - + + + * _FOREACH + + + + + * _FOREACH_SAFE + + + + + * _FOREACH_REVERSE - - - + + * _FOREACH_REVERSE_SAFE - - - + + * _INSERT_HEAD + + + + + * _INSERT_BEFORE - + - + + * _INSERT_AFTER + + + + + * _INSERT_TAIL - - + + + * _CONCAT - - + + + * _REMOVE_HEAD + - + - + * _REMOVE + + + + + * + */ +#define QUEUE_MACRO_DEBUG 0 +#if QUEUE_MACRO_DEBUG +/* Store the last 2 places the queue element or head was altered */ +struct qm_trace { + char * lastfile; + int lastline; + char * prevfile; + int prevline; +}; + +#define TRACEBUF struct qm_trace trace; +#define TRASHIT(x) do {(x) = (void *)-1;} while (0) + +#define QMD_TRACE_HEAD(head) do { \ + (head)->trace.prevline = (head)->trace.lastline; \ + (head)->trace.prevfile = (head)->trace.lastfile; \ + (head)->trace.lastline = __LINE__; \ + (head)->trace.lastfile = __FILE__; \ +} while (0) + +#define QMD_TRACE_ELEM(elem) do { \ + (elem)->trace.prevline = (elem)->trace.lastline; \ + (elem)->trace.prevfile = (elem)->trace.lastfile; \ + (elem)->trace.lastline = __LINE__; \ + (elem)->trace.lastfile = __FILE__; \ +} while (0) + +#else +#define QMD_TRACE_ELEM(elem) +#define QMD_TRACE_HEAD(head) +#define TRACEBUF +#define TRASHIT(x) +#endif /* QUEUE_MACRO_DEBUG */ + +/* + * Singly-linked List declarations. + */ +#define SLIST_HEAD(name, type) \ +struct name { \ + struct type *slh_first; /* first element */ \ +} + +#define SLIST_HEAD_INITIALIZER(head) \ + { NULL } + +#define SLIST_ENTRY(type) \ +struct { \ + struct type *sle_next; /* next element */ \ +} + +/* + * Singly-linked List functions. + */ +#define SLIST_EMPTY(head) ((head)->slh_first == NULL) + +#define SLIST_FIRST(head) ((head)->slh_first) + +#define SLIST_FOREACH(var, head, field) \ + for ((var) = SLIST_FIRST((head)); \ + (var); \ + (var) = SLIST_NEXT((var), field)) + +#define SLIST_FOREACH_SAFE(var, head, field, tvar) \ + for ((var) = SLIST_FIRST((head)); \ + (var) && ((tvar) = SLIST_NEXT((var), field), 1); \ + (var) = (tvar)) + +#define SLIST_FOREACH_PREVPTR(var, varp, head, field) \ + for ((varp) = &SLIST_FIRST((head)); \ + ((var) = *(varp)) != NULL; \ + (varp) = &SLIST_NEXT((var), field)) + +#define SLIST_INIT(head) do { \ + SLIST_FIRST((head)) = NULL; \ +} while (0) + +#define SLIST_INSERT_AFTER(slistelm, elm, field) do { \ + SLIST_NEXT((elm), field) = SLIST_NEXT((slistelm), field); \ + SLIST_NEXT((slistelm), field) = (elm); \ +} while (0) + +#define SLIST_INSERT_HEAD(head, elm, field) do { \ + SLIST_NEXT((elm), field) = SLIST_FIRST((head)); \ + SLIST_FIRST((head)) = (elm); \ +} while (0) + +#define SLIST_NEXT(elm, field) ((elm)->field.sle_next) + +#define SLIST_REMOVE(head, elm, type, field) do { \ + if (SLIST_FIRST((head)) == (elm)) { \ + SLIST_REMOVE_HEAD((head), field); \ + } \ + else { \ + struct type *curelm = SLIST_FIRST((head)); \ + while (SLIST_NEXT(curelm, field) != (elm)) \ + curelm = SLIST_NEXT(curelm, field); \ + SLIST_NEXT(curelm, field) = \ + SLIST_NEXT(SLIST_NEXT(curelm, field), field); \ + } \ +} while (0) + +#define SLIST_REMOVE_HEAD(head, field) do { \ + SLIST_FIRST((head)) = SLIST_NEXT(SLIST_FIRST((head)), field); \ +} while (0) + +/* + * Singly-linked Tail queue declarations. + */ +#define STAILQ_HEAD(name, type) \ +struct name { \ + struct type *stqh_first;/* first element */ \ + struct type **stqh_last;/* addr of last next element */ \ +} + +#define STAILQ_HEAD_INITIALIZER(head) \ + { NULL, &(head).stqh_first } + +#define STAILQ_ENTRY(type) \ +struct { \ + struct type *stqe_next; /* next element */ \ +} + +/* + * Singly-linked Tail queue functions. + */ +#define STAILQ_CONCAT(head1, head2) do { \ + if (!STAILQ_EMPTY((head2))) { \ + *(head1)->stqh_last = (head2)->stqh_first; \ + (head1)->stqh_last = (head2)->stqh_last; \ + STAILQ_INIT((head2)); \ + } \ +} while (0) + +#define STAILQ_EMPTY(head) ((head)->stqh_first == NULL) + +#define STAILQ_FIRST(head) ((head)->stqh_first) + +#define STAILQ_FOREACH(var, head, field) \ + for((var) = STAILQ_FIRST((head)); \ + (var); \ + (var) = STAILQ_NEXT((var), field)) + + +#define STAILQ_FOREACH_SAFE(var, head, field, tvar) \ + for ((var) = STAILQ_FIRST((head)); \ + (var) && ((tvar) = STAILQ_NEXT((var), field), 1); \ + (var) = (tvar)) + +#define STAILQ_INIT(head) do { \ + STAILQ_FIRST((head)) = NULL; \ + (head)->stqh_last = &STAILQ_FIRST((head)); \ +} while (0) + +#define STAILQ_INSERT_AFTER(head, tqelm, elm, field) do { \ + if ((STAILQ_NEXT((elm), field) = STAILQ_NEXT((tqelm), field)) == NULL)\ + (head)->stqh_last = &STAILQ_NEXT((elm), field); \ + STAILQ_NEXT((tqelm), field) = (elm); \ +} while (0) + +#define STAILQ_INSERT_HEAD(head, elm, field) do { \ + if ((STAILQ_NEXT((elm), field) = STAILQ_FIRST((head))) == NULL) \ + (head)->stqh_last = &STAILQ_NEXT((elm), field); \ + STAILQ_FIRST((head)) = (elm); \ +} while (0) + +#define STAILQ_INSERT_TAIL(head, elm, field) do { \ + STAILQ_NEXT((elm), field) = NULL; \ + *(head)->stqh_last = (elm); \ + (head)->stqh_last = &STAILQ_NEXT((elm), field); \ +} while (0) + +#define STAILQ_LAST(head, type, field) \ + (STAILQ_EMPTY((head)) ? \ + NULL : \ + ((struct type *) \ + ((char *)((head)->stqh_last) - __offsetof(struct type, field)))) + +#define STAILQ_NEXT(elm, field) ((elm)->field.stqe_next) + +#define STAILQ_REMOVE(head, elm, type, field) do { \ + if (STAILQ_FIRST((head)) == (elm)) { \ + STAILQ_REMOVE_HEAD((head), field); \ + } \ + else { \ + struct type *curelm = STAILQ_FIRST((head)); \ + while (STAILQ_NEXT(curelm, field) != (elm)) \ + curelm = STAILQ_NEXT(curelm, field); \ + if ((STAILQ_NEXT(curelm, field) = \ + STAILQ_NEXT(STAILQ_NEXT(curelm, field), field)) == NULL)\ + (head)->stqh_last = &STAILQ_NEXT((curelm), field);\ + } \ +} while (0) + +#define STAILQ_REMOVE_HEAD(head, field) do { \ + if ((STAILQ_FIRST((head)) = \ + STAILQ_NEXT(STAILQ_FIRST((head)), field)) == NULL) \ + (head)->stqh_last = &STAILQ_FIRST((head)); \ +} while (0) + +#define STAILQ_REMOVE_HEAD_UNTIL(head, elm, field) do { \ + if ((STAILQ_FIRST((head)) = STAILQ_NEXT((elm), field)) == NULL) \ + (head)->stqh_last = &STAILQ_FIRST((head)); \ +} while (0) + +/* + * List declarations. + */ +#define LIST_HEAD(name, type) \ +struct name { \ + struct type *lh_first; /* first element */ \ +} + +#define LIST_HEAD_INITIALIZER(head) \ + { NULL } + +#define LIST_ENTRY(type) \ +struct { \ + struct type *le_next; /* next element */ \ + struct type **le_prev; /* address of previous next element */ \ +} + +/* + * List functions. + */ + +#define LIST_EMPTY(head) ((head)->lh_first == NULL) + +#define LIST_FIRST(head) ((head)->lh_first) + +#define LIST_FOREACH(var, head, field) \ + for ((var) = LIST_FIRST((head)); \ + (var); \ + (var) = LIST_NEXT((var), field)) + +#define LIST_FOREACH_SAFE(var, head, field, tvar) \ + for ((var) = LIST_FIRST((head)); \ + (var) && ((tvar) = LIST_NEXT((var), field), 1); \ + (var) = (tvar)) + +#define LIST_INIT(head) do { \ + LIST_FIRST((head)) = NULL; \ +} while (0) + +#define LIST_INSERT_AFTER(listelm, elm, field) do { \ + if ((LIST_NEXT((elm), field) = LIST_NEXT((listelm), field)) != NULL)\ + LIST_NEXT((listelm), field)->field.le_prev = \ + &LIST_NEXT((elm), field); \ + LIST_NEXT((listelm), field) = (elm); \ + (elm)->field.le_prev = &LIST_NEXT((listelm), field); \ +} while (0) + +#define LIST_INSERT_BEFORE(listelm, elm, field) do { \ + (elm)->field.le_prev = (listelm)->field.le_prev; \ + LIST_NEXT((elm), field) = (listelm); \ + *(listelm)->field.le_prev = (elm); \ + (listelm)->field.le_prev = &LIST_NEXT((elm), field); \ +} while (0) + +#define LIST_INSERT_HEAD(head, elm, field) do { \ + if ((LIST_NEXT((elm), field) = LIST_FIRST((head))) != NULL) \ + LIST_FIRST((head))->field.le_prev = &LIST_NEXT((elm), field);\ + LIST_FIRST((head)) = (elm); \ + (elm)->field.le_prev = &LIST_FIRST((head)); \ +} while (0) + +#define LIST_NEXT(elm, field) ((elm)->field.le_next) + +#define LIST_REMOVE(elm, field) do { \ + if (LIST_NEXT((elm), field) != NULL) \ + LIST_NEXT((elm), field)->field.le_prev = \ + (elm)->field.le_prev; \ + *(elm)->field.le_prev = LIST_NEXT((elm), field); \ +} while (0) + +/* + * Tail queue declarations. + */ +#define TAILQ_HEAD(name, type) \ +struct name { \ + struct type *tqh_first; /* first element */ \ + struct type **tqh_last; /* addr of last next element */ \ + TRACEBUF \ +} + +#define TAILQ_HEAD_INITIALIZER(head) \ + { NULL, &(head).tqh_first } + +#define TAILQ_ENTRY(type) \ +struct { \ + struct type *tqe_next; /* next element */ \ + struct type **tqe_prev; /* address of previous next element */ \ + TRACEBUF \ +} + +/* + * Tail queue functions. + */ +#define TAILQ_CONCAT(head1, head2, field) do { \ + if (!TAILQ_EMPTY(head2)) { \ + *(head1)->tqh_last = (head2)->tqh_first; \ + (head2)->tqh_first->field.tqe_prev = (head1)->tqh_last; \ + (head1)->tqh_last = (head2)->tqh_last; \ + TAILQ_INIT((head2)); \ + QMD_TRACE_HEAD(head); \ + QMD_TRACE_HEAD(head2); \ + } \ +} while (0) + +#define TAILQ_EMPTY(head) ((head)->tqh_first == NULL) + +#define TAILQ_FIRST(head) ((head)->tqh_first) + +#define TAILQ_FOREACH(var, head, field) \ + for ((var) = TAILQ_FIRST((head)); \ + (var); \ + (var) = TAILQ_NEXT((var), field)) + +#define TAILQ_FOREACH_SAFE(var, head, field, tvar) \ + for ((var) = TAILQ_FIRST((head)); \ + (var) && ((tvar) = TAILQ_NEXT((var), field), 1); \ + (var) = (tvar)) + +#define TAILQ_FOREACH_REVERSE(var, head, headname, field) \ + for ((var) = TAILQ_LAST((head), headname); \ + (var); \ + (var) = TAILQ_PREV((var), headname, field)) + +#define TAILQ_FOREACH_REVERSE_SAFE(var, head, headname, field, tvar) \ + for ((var) = TAILQ_LAST((head), headname); \ + (var) && ((tvar) = TAILQ_PREV((var), headname, field), 1); \ + (var) = (tvar)) + +#define TAILQ_INIT(head) do { \ + TAILQ_FIRST((head)) = NULL; \ + (head)->tqh_last = &TAILQ_FIRST((head)); \ + QMD_TRACE_HEAD(head); \ +} while (0) + +#define TAILQ_INSERT_AFTER(head, listelm, elm, field) do { \ + if ((TAILQ_NEXT((elm), field) = TAILQ_NEXT((listelm), field)) != NULL)\ + TAILQ_NEXT((elm), field)->field.tqe_prev = \ + &TAILQ_NEXT((elm), field); \ + else { \ + (head)->tqh_last = &TAILQ_NEXT((elm), field); \ + QMD_TRACE_HEAD(head); \ + } \ + TAILQ_NEXT((listelm), field) = (elm); \ + (elm)->field.tqe_prev = &TAILQ_NEXT((listelm), field); \ + QMD_TRACE_ELEM(&(elm)->field); \ + QMD_TRACE_ELEM(&listelm->field); \ +} while (0) + +#define TAILQ_INSERT_BEFORE(listelm, elm, field) do { \ + (elm)->field.tqe_prev = (listelm)->field.tqe_prev; \ + TAILQ_NEXT((elm), field) = (listelm); \ + *(listelm)->field.tqe_prev = (elm); \ + (listelm)->field.tqe_prev = &TAILQ_NEXT((elm), field); \ + QMD_TRACE_ELEM(&(elm)->field); \ + QMD_TRACE_ELEM(&listelm->field); \ +} while (0) + +#define TAILQ_INSERT_HEAD(head, elm, field) do { \ + if ((TAILQ_NEXT((elm), field) = TAILQ_FIRST((head))) != NULL) \ + TAILQ_FIRST((head))->field.tqe_prev = \ + &TAILQ_NEXT((elm), field); \ + else \ + (head)->tqh_last = &TAILQ_NEXT((elm), field); \ + TAILQ_FIRST((head)) = (elm); \ + (elm)->field.tqe_prev = &TAILQ_FIRST((head)); \ + QMD_TRACE_HEAD(head); \ + QMD_TRACE_ELEM(&(elm)->field); \ +} while (0) + +#define TAILQ_INSERT_TAIL(head, elm, field) do { \ + TAILQ_NEXT((elm), field) = NULL; \ + (elm)->field.tqe_prev = (head)->tqh_last; \ + *(head)->tqh_last = (elm); \ + (head)->tqh_last = &TAILQ_NEXT((elm), field); \ + QMD_TRACE_HEAD(head); \ + QMD_TRACE_ELEM(&(elm)->field); \ +} while (0) + +#define TAILQ_LAST(head, headname) \ + (*(((struct headname *)((head)->tqh_last))->tqh_last)) + +#define TAILQ_NEXT(elm, field) ((elm)->field.tqe_next) + +#define TAILQ_PREV(elm, headname, field) \ + (*(((struct headname *)((elm)->field.tqe_prev))->tqh_last)) + +#define TAILQ_REMOVE(head, elm, field) do { \ + if ((TAILQ_NEXT((elm), field)) != NULL) \ + TAILQ_NEXT((elm), field)->field.tqe_prev = \ + (elm)->field.tqe_prev; \ + else { \ + (head)->tqh_last = (elm)->field.tqe_prev; \ + QMD_TRACE_HEAD(head); \ + } \ + *(elm)->field.tqe_prev = TAILQ_NEXT((elm), field); \ + TRASHIT((elm)->field.tqe_next); \ + TRASHIT((elm)->field.tqe_prev); \ + QMD_TRACE_ELEM(&(elm)->field); \ +} while (0) + + +#ifdef _KERNEL + +/* + * XXX insque() and remque() are an old way of handling certain queues. + * They bogusly assumes that all queue heads look alike. + */ + +struct quehead { + struct quehead *qh_link; + struct quehead *qh_rlink; +}; + +#ifdef __GNUC__ + +static __inline void +insque(void *a, void *b) +{ + struct quehead *element = (struct quehead *)a, + *head = (struct quehead *)b; + + element->qh_link = head->qh_link; + element->qh_rlink = head; + head->qh_link = element; + element->qh_link->qh_rlink = element; +} + +static __inline void +remque(void *a) +{ + struct quehead *element = (struct quehead *)a; + + element->qh_link->qh_rlink = element->qh_rlink; + element->qh_rlink->qh_link = element->qh_link; + element->qh_rlink = 0; +} + +#else /* !__GNUC__ */ + +void insque(void *a, void *b); +void remque(void *a); + +#endif /* __GNUC__ */ + +#endif /* _KERNEL */ + +#endif /* !_SYS_QUEUE_H_ */ diff --git a/src/include/sys/sched.h b/src/include/sys/sched.h new file mode 100644 index 0000000..5e85737 --- /dev/null +++ b/src/include/sys/sched.h @@ -0,0 +1,7 @@ +#ifndef _SCHED_H +#define _SCHED_H + +int sched_yield(); + +#endif + diff --git a/src/include/sys/signal.h b/src/include/sys/signal.h new file mode 100644 index 0000000..862f204 --- /dev/null +++ b/src/include/sys/signal.h @@ -0,0 +1,358 @@ +/*- + * Copyright (c) 1982, 1986, 1989, 1991, 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. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * @(#)signal.h 8.4 (Berkeley) 5/4/95 + * $FreeBSD: src/sys/sys/signal.h,v 1.42 2003/03/31 23:31:50 jeff Exp $ + */ + +#ifndef _SYS_SIGNAL_H_ +#define _SYS_SIGNAL_H_ + +#include +#include +#include + +#include /* sig_atomic_t; trap codes; sigcontext */ + +/* + * System defined signals. + */ +#if __POSIX_VISIBLE || __XSI_VISIBLE +#define SIGHUP 1 /* hangup */ +#endif +#define SIGINT 2 /* interrupt */ +#if __POSIX_VISIBLE || __XSI_VISIBLE +#define SIGQUIT 3 /* quit */ +#endif +#define SIGILL 4 /* illegal instr. (not reset when caught) */ +#if __XSI_VISIBLE +#define SIGTRAP 5 /* trace trap (not reset when caught) */ +#endif +#define SIGABRT 6 /* abort() */ +#if __BSD_VISIBLE +#define SIGIOT SIGABRT /* compatibility */ +#define SIGEMT 7 /* EMT instruction */ +#endif +#define SIGFPE 8 /* floating point exception */ +#if __POSIX_VISIBLE || __XSI_VISIBLE +#define SIGKILL 9 /* kill (cannot be caught or ignored) */ +#endif +#if __POSIX_VISIBLE >= 200112 || __XSI_VISIBLE +#define SIGBUS 10 /* bus error */ +#endif +#define SIGSEGV 11 /* segmentation violation */ +#if __BSD_VISIBLE +#define SIGSYS 12 /* non-existent system call invoked */ +#endif +#if __POSIX_VISIBLE || __XSI_VISIBLE +#define SIGPIPE 13 /* write on a pipe with no one to read it */ +#define SIGALRM 14 /* alarm clock */ +#endif +#define SIGTERM 15 /* software termination signal from kill */ +#if __POSIX_VISIBLE >= 200112 || __XSI_VISIBLE +#define SIGURG 16 /* urgent condition on IO channel */ +#endif +#if __POSIX_VISIBLE || __XSI_VISIBLE +#define SIGSTOP 17 /* sendable stop signal not from tty */ +#define SIGTSTP 18 /* stop signal from tty */ +#define SIGCONT 19 /* continue a stopped process */ +#define SIGCHLD 20 /* to parent on child stop or exit */ +#define SIGTTIN 21 /* to readers pgrp upon background tty read */ +#define SIGTTOU 22 /* like TTIN if (tp->t_local<OSTOP) */ +#endif +#if __BSD_VISIBLE +#define SIGIO 23 /* input/output possible signal */ +#endif +#if __XSI_VISIBLE +#define SIGXCPU 24 /* exceeded CPU time limit */ +#define SIGXFSZ 25 /* exceeded file size limit */ +#define SIGVTALRM 26 /* virtual time alarm */ +#define SIGPROF 27 /* profiling time alarm */ +#endif +#if __BSD_VISIBLE +#define SIGWINCH 28 /* window size changes */ +#define SIGINFO 29 /* information request */ +#endif +#if __POSIX_VISIBLE || __XSI_VISIBLE +#define SIGUSR1 30 /* user defined signal 1 */ +#define SIGUSR2 31 /* user defined signal 2 */ +#endif +#if __BSD_VISIBLE +#define SIGTHR 32 /* Thread interrupt. */ +#endif +/* + * XXX missing SIGRTMIN, SIGRTMAX. + */ + +#define SIG_DFL ((__sighandler_t *)0) +#define SIG_IGN ((__sighandler_t *)1) +#define SIG_ERR ((__sighandler_t *)-1) +/* + * XXX missing SIG_HOLD. + */ + +/*- + * Type of a signal handling function. + * + * Language spec sez signal handlers take exactly one arg, even though we + * actually supply three. Ugh! + * + * We don't try to hide the difference by leaving out the args because + * that would cause warnings about conformant programs. Nonconformant + * programs can avoid the warnings by casting to (__sighandler_t *) or + * sig_t before calling signal() or assigning to sa_handler or sv_handler. + * + * The kernel should reverse the cast before calling the function. It + * has no way to do this, but on most machines 1-arg and 3-arg functions + * have the same calling protocol so there is no problem in practice. + * A bit in sa_flags could be used to specify the number of args. + */ +typedef void __sighandler_t(int); + +#if __POSIX_VISIBLE || __XSI_VISIBLE +#ifndef _SIGSET_T_DECLARED +#define _SIGSET_T_DECLARED +typedef __sigset_t sigset_t; +#endif +#endif + +#if __POSIX_VISIBLE >= 199309 || __XSI_VISIBLE >= 500 +union sigval { + /* Members as suggested by Annex C of POSIX 1003.1b. */ + int sigval_int; + void *sigval_ptr; +}; +#endif + +#if __POSIX_VISIBLE >= 199309 +struct sigevent { + int sigev_notify; /* Notification type */ + union { + int __sigev_signo; /* Signal number */ + int __sigev_notify_kqueue; + } __sigev_u; + union sigval sigev_value; /* Signal value */ +/* + * XXX missing sigev_notify_function, sigev_notify_attributes. + */ +}; +#define sigev_signo __sigev_u.__sigev_signo +#if __BSD_VISIBLE +#define sigev_notify_kqueue __sigev_u.__sigev_notify_kqueue +#endif + +#define SIGEV_NONE 0 /* No async notification */ +#define SIGEV_SIGNAL 1 /* Generate a queued signal */ +#if __BSD_VISIBLE +#define SIGEV_KEVENT 3 /* Generate a kevent */ +#endif +/* + * XXX missing SIGEV_THREAD. + */ +#endif /* __POSIX_VISIBLE >= 199309 */ + +#if __POSIX_VISIBLE >= 199309 || __XSI_VISIBLE +typedef struct __siginfo { + int si_signo; /* signal number */ + int si_errno; /* errno association */ + /* + * Cause of signal, one of the SI_ macros or signal-specific + * values, i.e. one of the FPE_... values for SIGFPE. This + * value is equivalent to the second argument to an old-style + * FreeBSD signal handler. + */ + int si_code; /* signal code */ + __pid_t si_pid; /* sending process */ + __uid_t si_uid; /* sender's ruid */ + int si_status; /* exit value */ + void *si_addr; /* faulting instruction */ + union sigval si_value; /* signal value */ + long si_band; /* band event for SIGPOLL */ + int __spare__[7]; /* gimme some slack */ +} siginfo_t; +#endif + +#if __POSIX_VISIBLE || __XSI_VISIBLE +struct __siginfo; + +/* + * Signal vector "template" used in sigaction call. + */ +struct sigaction { + union { + void (*__sa_handler)(int); + void (*__sa_sigaction)(int, struct __siginfo *, void *); + } __sigaction_u; /* signal handler */ + int sa_flags; /* see signal options below */ + sigset_t sa_mask; /* signal mask to apply */ +}; + +#define sa_handler __sigaction_u.__sa_handler +#endif + +#if __XSI_VISIBLE +/* If SA_SIGINFO is set, sa_sigaction must be used instead of sa_handler. */ +#define sa_sigaction __sigaction_u.__sa_sigaction +#endif + +#if __POSIX_VISIBLE || __XSI_VISIBLE +#define SA_NOCLDSTOP 0x0008 /* do not generate SIGCHLD on child stop */ +#endif /* __POSIX_VISIBLE || __XSI_VISIBLE */ + +#if __XSI_VISIBLE +#define SA_ONSTACK 0x0001 /* take signal on signal stack */ +#define SA_RESTART 0x0002 /* restart system call on signal return */ +#define SA_RESETHAND 0x0004 /* reset to SIG_DFL when taking signal */ +#define SA_NODEFER 0x0010 /* don't mask the signal we're delivering */ +#define SA_NOCLDWAIT 0x0020 /* don't keep zombies around */ +#define SA_SIGINFO 0x0040 /* signal handler with SA_SIGINFO args */ +#endif +#if __BSD_VISIBLE +/* XXX dubious. */ +#ifdef COMPAT_SUNOS +#define SA_USERTRAMP 0x0100 /* do not bounce off kernel's sigtramp */ +#endif +#endif + +#if __BSD_VISIBLE +#define NSIG 32 /* number of old signals (counting 0) */ +#endif + +#if __POSIX_VISIBLE || __XSI_VISIBLE +#define SI_USER 0x10001 +#define SI_QUEUE 0x10002 +#define SI_TIMER 0x10003 +#define SI_ASYNCIO 0x10004 +#define SI_MESGQ 0x10005 +#endif +#if __BSD_VISIBLE +#define SI_UNDEFINED 0 +#endif + +#if __BSD_VISIBLE +typedef __sighandler_t *sig_t; /* type of pointer to a signal function */ +typedef void __siginfohandler_t(int, struct __siginfo *, void *); +#endif + +#if __XSI_VISIBLE +/* + * Structure used in sigaltstack call. + */ +#if __BSD_VISIBLE +typedef struct sigaltstack { +#else +typedef struct { +#endif + char *ss_sp; /* signal stack base */ + __size_t ss_size; /* signal stack length */ + int ss_flags; /* SS_DISABLE and/or SS_ONSTACK */ +} stack_t; + +#define SS_ONSTACK 0x0001 /* take signal on alternate stack */ +#define SS_DISABLE 0x0004 /* disable taking signals on alternate stack */ +#define SIGSTKSZ (MINSIGSTKSZ + 32768) /* recommended stack size */ +#endif + +#if __BSD_VISIBLE +/* + * 4.3 compatibility: + * Signal vector "template" used in sigvec call. + */ +struct sigvec { + __sighandler_t *sv_handler; /* signal handler */ + int sv_mask; /* signal mask to apply */ + int sv_flags; /* see signal options below */ +}; + +#define SV_ONSTACK SA_ONSTACK +#define SV_INTERRUPT SA_RESTART /* same bit, opposite sense */ +#define SV_RESETHAND SA_RESETHAND +#define SV_NODEFER SA_NODEFER +#define SV_NOCLDSTOP SA_NOCLDSTOP +#define SV_SIGINFO SA_SIGINFO +#define sv_onstack sv_flags /* isn't compatibility wonderful! */ +#endif + +/* Keep this in one place only */ +#if defined(_KERNEL) && defined(COMPAT_43) && \ + !defined(__i386__) && !defined(__alpha__) +struct osigcontext { + int _not_used; +}; +#endif + +#if __XSI_VISIBLE +/* + * Structure used in sigstack call. + */ +struct sigstack { + /* XXX ss_sp's type should be `void *'. */ + char *ss_sp; /* signal stack pointer */ + int ss_onstack; /* current status */ +}; +#endif + +#if __BSD_VISIBLE || __POSIX_VISIBLE > 0 && __POSIX_VISIBLE <= 200112 +/* + * Macro for converting signal number to a mask suitable for + * sigblock(). + */ +#define sigmask(m) (1 << ((m)-1)) +#endif + +#if __BSD_VISIBLE +#define BADSIG SIG_ERR +#endif + +#if __POSIX_VISIBLE || __XSI_VISIBLE +/* + * Flags for sigprocmask: + */ +#define SIG_BLOCK 1 /* block specified signal set */ +#define SIG_UNBLOCK 2 /* unblock specified signal set */ +#define SIG_SETMASK 3 /* set specified signal set */ +#endif + +/* + * For historical reasons; programs expect signal's return value to be + * defined by . + */ +__BEGIN_DECLS +__sighandler_t *signal(int, __sighandler_t *); +__END_DECLS + +#endif /* !_SYS_SIGNAL_H_ */ diff --git a/src/include/sys/stat.h b/src/include/sys/stat.h new file mode 100644 index 0000000..585ccd3 --- /dev/null +++ b/src/include/sys/stat.h @@ -0,0 +1,328 @@ +/*- + * Copyright (c) 1982, 1986, 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. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * @(#)stat.h 8.12 (Berkeley) 6/16/95 + * $FreeBSD: src/sys/sys/stat.h,v 1.37 2003/05/22 17:07:57 mike Exp $ + */ + +#ifndef _SYS_STAT_H_ +#define _SYS_STAT_H_ + +#include +#include + +/* XXX missing blkcnt_t, blksize_t. */ + +#ifndef _DEV_T_DECLARED +typedef __dev_t dev_t; +#define _DEV_T_DECLARED +#endif + +#ifndef _FFLAGS_T_DECLARED +typedef __fflags_t fflags_t; +#define _FFLAGS_T_DECLARED +#endif + +#ifndef _GID_T_DECLARED +typedef __gid_t gid_t; +#define _GID_T_DECLARED +#endif + +#ifndef _INO_T_DECLARED +typedef __ino_t ino_t; +#define _INO_T_DECLARED +#endif + +#ifndef _MODE_T_DECLARED +typedef __mode_t mode_t; +#define _MODE_T_DECLARED +#endif + +#ifndef _NLINK_T_DECLARED +typedef __nlink_t nlink_t; +#define _NLINK_T_DECLARED +#endif + +#ifndef _OFF_T_DECLARED +typedef __off_t off_t; +#define _OFF_T_DECLARED +#endif + +#ifndef _TIME_T_DECLARED +typedef __time_t time_t; +#define _TIME_T_DECLARED +#endif + +#ifndef _UID_T_DECLARED +typedef __uid_t uid_t; +#define _UID_T_DECLARED +#endif + +#if !defined(_KERNEL) && __BSD_VISIBLE +/* + * XXX we need this for struct timespec. We get miscellaneous namespace + * pollution with it. + */ +#include +#endif + +#if !__BSD_VISIBLE +#include +#endif + +#if __BSD_VISIBLE +struct ostat { + __uint16_t st_dev; /* inode's device */ + ino_t st_ino; /* inode's number */ + mode_t st_mode; /* inode protection mode */ + nlink_t st_nlink; /* number of hard links */ + __uint16_t st_uid; /* user ID of the file's owner */ + __uint16_t st_gid; /* group ID of the file's group */ + __uint16_t st_rdev; /* device type */ + __int32_t st_size; /* file size, in bytes */ + struct timespec st_atimespec; /* time of last access */ + struct timespec st_mtimespec; /* time of last data modification */ + struct timespec st_ctimespec; /* time of last file status change */ + __int32_t st_blksize; /* optimal blocksize for I/O */ + __int32_t st_blocks; /* blocks allocated for file */ + fflags_t st_flags; /* user defined flags for file */ + __uint32_t st_gen; /* file generation number */ +}; +#endif /* __BSD_VISIBLE */ + +struct stat { + __udev_t st_dev; /* inode's device */ + ino_t st_ino; /* inode's number */ + mode_t st_mode; /* inode protection mode */ + nlink_t st_nlink; /* number of hard links */ + uid_t st_uid; /* user ID of the file's owner */ + gid_t st_gid; /* group ID of the file's group */ + __udev_t st_rdev; /* device type */ +#if __BSD_VISIBLE + struct timespec st_atimespec; /* time of last access */ + struct timespec st_mtimespec; /* time of last data modification */ + struct timespec st_ctimespec; /* time of last file status change */ +#else + time_t st_atime; /* time of last access */ + long st_atimensec; /* nsec of last access */ + time_t st_mtime; /* time of last data modification */ + long st_mtimensec; /* nsec of last data modification */ + time_t st_ctime; /* time of last file status change */ + long st_ctimensec; /* nsec of last file status change */ +#endif + off_t st_size; /* file size, in bytes */ + __int64_t st_blocks; /* blocks allocated for file */ + __uint32_t st_blksize; /* optimal blocksize for I/O */ + fflags_t st_flags; /* user defined flags for file */ + __uint32_t st_gen; /* file generation number */ + __int32_t st_lspare; +#if __BSD_VISIBLE + struct timespec st_birthtimespec; /* time of file creation */ + /* + * Explicitly pad st_birthtimespec to 16 bytes so that the size of + * struct stat is backwards compatible. We use bitfields instead + * of an array of chars so that this doesn't require a C99 compiler + * to compile if the size of the padding is 0. We use 2 bitfields + * to cover up to 64 bits on 32-bit machines. We assume that + * CHAR_BIT is 8... + */ + unsigned int :(8 / 2) * (16 - (int)sizeof(struct timespec)); + unsigned int :(8 / 2) * (16 - (int)sizeof(struct timespec)); +#else + time_t st_birthtime; /* time of file creation */ + long st_birthtimensec; /* nsec of file creation */ + unsigned int :(8 / 2) * (16 - (int)sizeof(struct __timespec)); + unsigned int :(8 / 2) * (16 - (int)sizeof(struct __timespec)); +#endif +}; + +#if __BSD_VISIBLE +struct nstat { + __udev_t st_dev; /* inode's device */ + ino_t st_ino; /* inode's number */ + __uint32_t st_mode; /* inode protection mode */ + __uint32_t st_nlink; /* number of hard links */ + uid_t st_uid; /* user ID of the file's owner */ + gid_t st_gid; /* group ID of the file's group */ + __udev_t st_rdev; /* device type */ + struct timespec st_atimespec; /* time of last access */ + struct timespec st_mtimespec; /* time of last data modification */ + struct timespec st_ctimespec; /* time of last file status change */ + off_t st_size; /* file size, in bytes */ + __int64_t st_blocks; /* blocks allocated for file */ + __uint32_t st_blksize; /* optimal blocksize for I/O */ + fflags_t st_flags; /* user defined flags for file */ + __uint32_t st_gen; /* file generation number */ + struct timespec st_birthtimespec; /* time of file creation */ + /* + * See above about the following padding. + */ + unsigned int :(8 / 2) * (16 - (int)sizeof(struct timespec)); + unsigned int :(8 / 2) * (16 - (int)sizeof(struct timespec)); +}; +#endif + +#if __BSD_VISIBLE +#define st_atime st_atimespec.tv_sec +#define st_mtime st_mtimespec.tv_sec +#define st_ctime st_ctimespec.tv_sec +#define st_birthtime st_birthtimespec.tv_sec +#endif + +#define S_ISUID 0004000 /* set user id on execution */ +#define S_ISGID 0002000 /* set group id on execution */ +#if __BSD_VISIBLE +#define S_ISTXT 0001000 /* sticky bit */ +#endif + +#define S_IRWXU 0000700 /* RWX mask for owner */ +#define S_IRUSR 0000400 /* R for owner */ +#define S_IWUSR 0000200 /* W for owner */ +#define S_IXUSR 0000100 /* X for owner */ + +#if __BSD_VISIBLE +#define S_IREAD S_IRUSR +#define S_IWRITE S_IWUSR +#define S_IEXEC S_IXUSR +#endif + +#define S_IRWXG 0000070 /* RWX mask for group */ +#define S_IRGRP 0000040 /* R for group */ +#define S_IWGRP 0000020 /* W for group */ +#define S_IXGRP 0000010 /* X for group */ + +#define S_IRWXO 0000007 /* RWX mask for other */ +#define S_IROTH 0000004 /* R for other */ +#define S_IWOTH 0000002 /* W for other */ +#define S_IXOTH 0000001 /* X for other */ + +#if __XSI_VISIBLE +#define S_IFMT 0170000 /* type of file mask */ +#define S_IFIFO 0010000 /* named pipe (fifo) */ +#define S_IFCHR 0020000 /* character special */ +#define S_IFDIR 0040000 /* directory */ +#define S_IFBLK 0060000 /* block special */ +#define S_IFREG 0100000 /* regular */ +#define S_IFLNK 0120000 /* symbolic link */ +#define S_IFSOCK 0140000 /* socket */ +#define S_ISVTX 0001000 /* save swapped text even after use */ +#endif +#if __BSD_VISIBLE +#define S_IFWHT 0160000 /* whiteout */ +#endif + +#define S_ISDIR(m) (((m) & 0170000) == 0040000) /* directory */ +#define S_ISCHR(m) (((m) & 0170000) == 0020000) /* char special */ +#define S_ISBLK(m) (((m) & 0170000) == 0060000) /* block special */ +#define S_ISREG(m) (((m) & 0170000) == 0100000) /* regular file */ +#define S_ISFIFO(m) (((m) & 0170000) == 0010000) /* fifo or socket */ +#if __POSIX_VISIBLE >= 200112 +#define S_ISLNK(m) (((m) & 0170000) == 0120000) /* symbolic link */ +#define S_ISSOCK(m) (((m) & 0170000) == 0140000) /* socket */ +#endif +#if __XSI_VISIBLE +#define S_ISWHT(m) (((m) & 0170000) == 0160000) /* whiteout */ +#endif + +#if __BSD_VISIBLE +#define ACCESSPERMS (S_IRWXU|S_IRWXG|S_IRWXO) /* 0777 */ + /* 7777 */ +#define ALLPERMS (S_ISUID|S_ISGID|S_ISTXT|S_IRWXU|S_IRWXG|S_IRWXO) + /* 0666 */ +#define DEFFILEMODE (S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH) + +#define S_BLKSIZE 512 /* block size used in the stat struct */ + +/* + * Definitions of flags stored in file flags word. + * + * Super-user and owner changeable flags. + */ +#define UF_SETTABLE 0x0000ffff /* mask of owner changeable flags */ +#define UF_NODUMP 0x00000001 /* do not dump file */ +#define UF_IMMUTABLE 0x00000002 /* file may not be changed */ +#define UF_APPEND 0x00000004 /* writes to file may only append */ +#define UF_OPAQUE 0x00000008 /* directory is opaque wrt. union */ +#define UF_NOUNLINK 0x00000010 /* file may not be removed or renamed */ +/* + * Super-user changeable flags. + */ +#define SF_SETTABLE 0xffff0000 /* mask of superuser changeable flags */ +#define SF_ARCHIVED 0x00010000 /* file is archived */ +#define SF_IMMUTABLE 0x00020000 /* file may not be changed */ +#define SF_APPEND 0x00040000 /* writes to file may only append */ +#define SF_NOUNLINK 0x00100000 /* file may not be removed or renamed */ +#define SF_SNAPSHOT 0x00200000 /* snapshot inode */ + +#ifdef _KERNEL +/* + * Shorthand abbreviations of above. + */ +#define OPAQUE (UF_OPAQUE) +#define APPEND (UF_APPEND | SF_APPEND) +#define IMMUTABLE (UF_IMMUTABLE | SF_IMMUTABLE) +#define NOUNLINK (UF_NOUNLINK | SF_NOUNLINK) +#endif + +#endif /* __BSD_VISIBLE */ + +#ifndef _KERNEL +__BEGIN_DECLS +#if __BSD_VISIBLE +int chflags(const char *, unsigned long); +#endif +int chmod(const char *, mode_t); +#if __BSD_VISIBLE +int fchflags(int, unsigned long); +int fchmod(int, mode_t); +#endif +int fstat(int, struct stat *); +#if __BSD_VISIBLE +int lchflags(const char *, int); +int lchmod(const char *, mode_t); +#endif +#if __POSIX_VISIBLE >= 200112 +int lstat(const char *, struct stat *); +#endif +int mkdir(const char *, mode_t); +int mkfifo(const char *, mode_t); +int stat(const char *, struct stat *); +mode_t umask(mode_t); +__END_DECLS +#endif /* !_KERNEL */ + +#endif /* !_SYS_STAT_H_ */ diff --git a/src/include/sys/sys.h b/src/include/sys/sys.h new file mode 100644 index 0000000..19ee01f --- /dev/null +++ b/src/include/sys/sys.h @@ -0,0 +1,35 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#ifndef _SYS_H +#define _SYS_H + +int exec(char *,int argc,char **argv); +int pidStatus(int pid); +void *getPage(int count); +void *getDrives(); +int getuptime(); +int gettime(); +int startSDE(); + +#endif diff --git a/src/include/sys/syslimits.h b/src/include/sys/syslimits.h new file mode 100644 index 0000000..03cf0ee --- /dev/null +++ b/src/include/sys/syslimits.h @@ -0,0 +1,75 @@ +/* + * 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. + * + * @(#)syslimits.h 8.1 (Berkeley) 6/2/93 + * $FreeBSD: src/sys/sys/syslimits.h,v 1.16 2003/09/10 19:08:16 obrien Exp $ + */ + +#ifndef _SYS_SYSLIMITS_H_ +#define _SYS_SYSLIMITS_H_ + +#if !defined(_KERNEL) && !defined(_LIMITS_H_) && !defined(_SYS_PARAM_H_) +#if __GNUC__ +#warning "No user-serviceable parts inside." +#endif +#endif + +/* + * Do not add any new variables here. (See the comment at the end of + * the file for why.) + */ +#define ARG_MAX 65536 /* max bytes for an exec function */ +#ifndef CHILD_MAX +#define CHILD_MAX 40 /* max simultaneous processes */ +#endif +#define LINK_MAX 32767 /* max file link count */ +#define MAX_CANON 255 /* max bytes in term canon input line */ +#define MAX_INPUT 255 /* max bytes in terminal input */ +#define NAME_MAX 255 /* max bytes in a file name */ +#define NGROUPS_MAX 16 /* max supplemental group id's */ +#ifndef OPEN_MAX +#define OPEN_MAX 64 /* max open files per process */ +#endif +#define PATH_MAX 1024 /* max bytes in pathname */ +#define PIPE_BUF 512 /* max bytes for atomic pipe writes */ +#define IOV_MAX 1024 /* max elements in i/o vector */ + +/* + * We leave the following values undefined to force applications to either + * assume conservative values or call sysconf() to get the current value. + * + * HOST_NAME_MAX + * + * (We should do this for most of the values currently defined here, + * but many programs are not prepared to deal with this yet.) + */ +#endif diff --git a/src/include/sys/time.h b/src/include/sys/time.h new file mode 100644 index 0000000..1b15b48 --- /dev/null +++ b/src/include/sys/time.h @@ -0,0 +1,322 @@ +/* + * Copyright (c) 1982, 1986, 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. + * + * @(#)time.h 8.5 (Berkeley) 5/4/95 + * $FreeBSD: src/sys/sys/time.h,v 1.64 2004/02/29 10:55:15 phk Exp $ + */ + +#ifndef _SYS_TIME_H_ +#define _SYS_TIME_H_ + +#include +#include +#include + +struct timezone { + int tz_minuteswest; /* minutes west of Greenwich */ + int tz_dsttime; /* type of dst correction */ +}; +#define DST_NONE 0 /* not on dst */ +#define DST_USA 1 /* USA style dst */ +#define DST_AUST 2 /* Australian style dst */ +#define DST_WET 3 /* Western European dst */ +#define DST_MET 4 /* Middle European dst */ +#define DST_EET 5 /* Eastern European dst */ +#define DST_CAN 6 /* Canada */ + +#if __BSD_VISIBLE +struct bintime { + time_t sec; + uInt64 frac; +}; + +static __inline void +bintime_addx(struct bintime *bt, uInt64 x) +{ + uInt64 u; + + u = bt->frac; + bt->frac += x; + if (u > bt->frac) + bt->sec++; +} + +static __inline void +bintime_add(struct bintime *bt, const struct bintime *bt2) +{ + uInt64 u; + + u = bt->frac; + bt->frac += bt2->frac; + if (u > bt->frac) + bt->sec++; + bt->sec += bt2->sec; +} + +static __inline void +bintime_sub(struct bintime *bt, const struct bintime *bt2) +{ + uInt64 u; + + u = bt->frac; + bt->frac -= bt2->frac; + if (u < bt->frac) + bt->sec--; + bt->sec -= bt2->sec; +} + +/*- + * Background information: + * + * When converting between timestamps on parallel timescales of differing + * resolutions it is historical and scientific practice to round down rather + * than doing 4/5 rounding. + * + * The date changes at midnight, not at noon. + * + * Even at 15:59:59.999999999 it's not four'o'clock. + * + * time_second ticks after N.999999999 not after N.4999999999 + */ + +static __inline void +bintime2timespec(const struct bintime *bt, struct timespec *ts) +{ + + ts->tv_sec = bt->sec; + ts->tv_nsec = ((uInt64)1000000000 * (uInt32)(bt->frac >> 32)) >> 32; +} + +static __inline void +timespec2bintime(const struct timespec *ts, struct bintime *bt) +{ + + bt->sec = ts->tv_sec; + /* 18446744073 = int(2^64 / 1000000000) */ + bt->frac = ts->tv_nsec * (uInt64)18446744073LL; +} + +static __inline void +bintime2timeval(const struct bintime *bt, struct timeval *tv) +{ + + tv->tv_sec = bt->sec; + tv->tv_usec = ((uInt64)1000000 * (uInt32)(bt->frac >> 32)) >> 32; +} + +static __inline void +timeval2bintime(const struct timeval *tv, struct bintime *bt) +{ + + bt->sec = tv->tv_sec; + /* 18446744073709 = int(2^64 / 1000000) */ + bt->frac = tv->tv_usec * (uInt64)18446744073709LL; +} +#endif /* __BSD_VISIBLE */ + +#ifdef _KERNEL + +/* Operations on timespecs */ +#define timespecclear(tvp) ((tvp)->tv_sec = (tvp)->tv_nsec = 0) +#define timespecisset(tvp) ((tvp)->tv_sec || (tvp)->tv_nsec) +#define timespeccmp(tvp, uvp, cmp) \ + (((tvp)->tv_sec == (uvp)->tv_sec) ? \ + ((tvp)->tv_nsec cmp (uvp)->tv_nsec) : \ + ((tvp)->tv_sec cmp (uvp)->tv_sec)) +#define timespecadd(vvp, uvp) \ + do { \ + (vvp)->tv_sec += (uvp)->tv_sec; \ + (vvp)->tv_nsec += (uvp)->tv_nsec; \ + if ((vvp)->tv_nsec >= 1000000000) { \ + (vvp)->tv_sec++; \ + (vvp)->tv_nsec -= 1000000000; \ + } \ + } while (0) +#define timespecsub(vvp, uvp) \ + do { \ + (vvp)->tv_sec -= (uvp)->tv_sec; \ + (vvp)->tv_nsec -= (uvp)->tv_nsec; \ + if ((vvp)->tv_nsec < 0) { \ + (vvp)->tv_sec--; \ + (vvp)->tv_nsec += 1000000000; \ + } \ + } while (0) + +/* Operations on timevals. */ + +#define timevalclear(tvp) ((tvp)->tv_sec = (tvp)->tv_usec = 0) +#define timevalisset(tvp) ((tvp)->tv_sec || (tvp)->tv_usec) +#define timevalcmp(tvp, uvp, cmp) \ + (((tvp)->tv_sec == (uvp)->tv_sec) ? \ + ((tvp)->tv_usec cmp (uvp)->tv_usec) : \ + ((tvp)->tv_sec cmp (uvp)->tv_sec)) + +/* timevaladd and timevalsub are not inlined */ + +#endif /* _KERNEL */ + +#ifndef _KERNEL /* NetBSD/OpenBSD compatible interfaces */ + +#define timerclear(tvp) ((tvp)->tv_sec = (tvp)->tv_usec = 0) +#define timerisset(tvp) ((tvp)->tv_sec || (tvp)->tv_usec) +#define timercmp(tvp, uvp, cmp) \ + (((tvp)->tv_sec == (uvp)->tv_sec) ? \ + ((tvp)->tv_usec cmp (uvp)->tv_usec) : \ + ((tvp)->tv_sec cmp (uvp)->tv_sec)) +#define timeradd(tvp, uvp, vvp) \ + do { \ + (vvp)->tv_sec = (tvp)->tv_sec + (uvp)->tv_sec; \ + (vvp)->tv_usec = (tvp)->tv_usec + (uvp)->tv_usec; \ + if ((vvp)->tv_usec >= 1000000) { \ + (vvp)->tv_sec++; \ + (vvp)->tv_usec -= 1000000; \ + } \ + } while (0) +#define timersub(tvp, uvp, vvp) \ + do { \ + (vvp)->tv_sec = (tvp)->tv_sec - (uvp)->tv_sec; \ + (vvp)->tv_usec = (tvp)->tv_usec - (uvp)->tv_usec; \ + if ((vvp)->tv_usec < 0) { \ + (vvp)->tv_sec--; \ + (vvp)->tv_usec += 1000000; \ + } \ + } while (0) +#endif + +/* + * Names of the interval timers, and structure + * defining a timer setting. + */ +#define ITIMER_REAL 0 +#define ITIMER_VIRTUAL 1 +#define ITIMER_PROF 2 + +struct itimerval { + struct timeval it_interval; /* timer interval */ + struct timeval it_value; /* current value */ +}; + +/* + * Getkerninfo clock information structure + */ +struct clockinfo { + int hz; /* clock frequency */ + int tick; /* micro-seconds per hz tick */ + int spare; + int stathz; /* statistics clock frequency */ + int profhz; /* profiling clock frequency */ +}; + +/* CLOCK_REALTIME and TIMER_ABSTIME are supposed to be in time.h */ + +#ifndef CLOCK_REALTIME +#define CLOCK_REALTIME 0 +#endif +#define CLOCK_VIRTUAL 1 +#define CLOCK_PROF 2 +#define CLOCK_MONOTONIC 4 + +#define TIMER_RELTIME 0x0 /* relative timer */ +#ifndef TIMER_ABSTIME +#define TIMER_ABSTIME 0x1 /* absolute timer */ +#endif + +#ifdef _KERNEL +extern time_t time_second; +extern time_t time_uptime; +extern struct timeval boottime; + +/* + * Functions for looking at our clock: [get]{bin,nano,micro}[up]time() + * + * Functions without the "get" prefix returns the best timestamp + * we can produce in the given format. + * + * "bin" == struct bintime == seconds + 64 bit fraction of seconds. + * "nano" == struct timespec == seconds + nanoseconds. + * "micro" == struct timeval == seconds + microseconds. + * + * Functions containing "up" returns time relative to boot and + * should be used for calculating time intervals. + * + * Functions without "up" returns GMT time. + * + * Functions with the "get" prefix returns a less precise result + * much faster than the functions without "get" prefix and should + * be used where a precision of 10 msec is acceptable or where + * performance is priority. (NB: "precision", _not_ "resolution" !) + * + */ + +void binuptime(struct bintime *bt); +void nanouptime(struct timespec *tsp); +void microuptime(struct timeval *tvp); + +void bintime(struct bintime *bt); +void nanotime(struct timespec *tsp); +void microtime(struct timeval *tvp); + +void getbinuptime(struct bintime *bt); +void getnanouptime(struct timespec *tsp); +void getmicrouptime(struct timeval *tvp); + +void getbintime(struct bintime *bt); +void getnanotime(struct timespec *tsp); +void getmicrotime(struct timeval *tvp); + +/* Other functions */ +int itimerdecr(struct itimerval *itp, int usec); +int itimerfix(struct timeval *tv); +int ppsratecheck(struct timeval *, int *, int); +int ratecheck(struct timeval *, const struct timeval *); +void timevaladd(struct timeval *t1, const struct timeval *t2); +void timevalsub(struct timeval *t1, const struct timeval *t2); +int tvtohz(struct timeval *tv); +#else /* !_KERNEL */ +#include + +#include + +__BEGIN_DECLS +int adjtime(const struct timeval *, struct timeval *); +int futimes(int, const struct timeval *); +int getitimer(int, struct itimerval *); +int gettimeofday(struct timeval *, struct timezone *); +int lutimes(const char *, const struct timeval *); +int setitimer(int, const struct itimerval *, struct itimerval *); +int settimeofday(const struct timeval *, const struct timezone *); +int utimes(const char *, const struct timeval *); +__END_DECLS + +#endif /* !_KERNEL */ + +#endif /* !_SYS_TIME_H_ */ diff --git a/src/include/sys/timespec.h b/src/include/sys/timespec.h new file mode 100644 index 0000000..0cc0212 --- /dev/null +++ b/src/include/sys/timespec.h @@ -0,0 +1,69 @@ +/* + * Copyright (c) 1982, 1986, 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. + * + * @(#)time.h 8.5 (Berkeley) 5/4/95 + * from: FreeBSD: src/sys/sys/time.h,v 1.43 2000/03/20 14:09:05 phk Exp + * $FreeBSD: src/sys/sys/timespec.h,v 1.2 2002/08/21 16:20:01 mike Exp $ + */ + +/* + * Prerequisites: , + */ + +#ifndef _SYS_TIMESPEC_H_ +#define _SYS_TIMESPEC_H_ + +#ifndef _TIME_T_DECLARED +typedef __time_t time_t; +#define _TIME_T_DECLARED +#endif + +struct timespec { + time_t tv_sec; /* seconds */ + long tv_nsec; /* and nanoseconds */ +}; + +#if __BSD_VISIBLE +#define TIMEVAL_TO_TIMESPEC(tv, ts) \ + do { \ + (ts)->tv_sec = (tv)->tv_sec; \ + (ts)->tv_nsec = (tv)->tv_usec * 1000; \ + } while (0) +#define TIMESPEC_TO_TIMEVAL(tv, ts) \ + do { \ + (tv)->tv_sec = (ts)->tv_sec; \ + (tv)->tv_usec = (ts)->tv_nsec / 1000; \ + } while (0) + +#endif /* __BSD_VISIBLE */ + +#endif /* _SYS_TIMESPEC_H_ */ diff --git a/src/include/sys/types.h b/src/include/sys/types.h new file mode 100644 index 0000000..6180110 --- /dev/null +++ b/src/include/sys/types.h @@ -0,0 +1,78 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#ifndef _TYPES_H +#define _TYPES_H + +#include + +/**** NEW TYPEDEFS ****/ +#ifndef _OFF_T_DECLARED +typedef __off_t off_t; +#define _OFF_T_DECLARED +#endif + +#ifndef _SSIZE_T_DECLARED +typedef __ssize_t ssize_t; +#define _SSIZE_T_DECLARED +#endif + +#ifndef _UINT64_T_DECLARED +typedef __uint64_t uInt64; +#define _UINT64_T_DECLARED +#endif + +#ifndef _INT32_T_DECLARED +typedef __int32_t int32_t; +#define _INT32_T_DECLARED +#endif + +#ifndef _INT64_T_DECLARED +typedef __int64_t int64_t; +#define _INT64_T_DECLARED +#endif + + +/**** END ****/ + +typedef unsigned short uShort; +typedef unsigned long uLong; +typedef unsigned char uChar; +typedef unsigned int uInt; + +typedef unsigned char uInt8; +typedef unsigned short uInt16; +typedef unsigned int uInt32; + +typedef long long int quad_t; +typedef unsigned long long int u_quad_t; + +#ifndef NULL +#define NULL 0x0 +#endif + +#ifndef NOBOOL +typedef enum { FALSE=0,TRUE=1 } bool; +#endif + +#endif diff --git a/src/include/sys/ucred.h b/src/include/sys/ucred.h new file mode 100644 index 0000000..b8c1a6b --- /dev/null +++ b/src/include/sys/ucred.h @@ -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. + * + * @(#)ucred.h 8.4 (Berkeley) 1/9/95 + * $FreeBSD: src/sys/sys/ucred.h,v 1.48 2003/11/12 15:07:18 bde Exp $ + */ + +#ifndef _SYS_UCRED_H_ +#define _SYS_UCRED_H_ + +/* + * Credentials. + * + * Please do not inspect cr_uid directly to determine superuserness. + * Only the suser() or suser_cred() function should be used for this. + */ +#if defined(_KERNEL) || defined(_WANT_UCRED) +struct ucred { + uInt32 cr_ref; /* reference count */ +#define cr_startcopy cr_uid + uid_t cr_uid; /* effective user id */ + uid_t cr_ruid; /* real user id */ + uid_t cr_svuid; /* saved user id */ + short cr_ngroups; /* number of groups */ + gid_t cr_groups[NGROUPS]; /* groups */ + gid_t cr_rgid; /* real group id */ + gid_t cr_svgid; /* saved user id */ + struct uidinfo *cr_uidinfo; /* per euid resource consumption */ + struct uidinfo *cr_ruidinfo; /* per ruid resource consumption */ + struct prison *cr_prison; /* jail(2) */ +#define cr_endcopy cr_label + struct label *cr_label; /* MAC label */ + struct mtx *cr_mtxp; /* protect refcount */ +}; +#define NOCRED ((struct ucred *)0) /* no credential available */ +#define FSCRED ((struct ucred *)-1) /* filesystem credential */ +#endif /* _KERNEL || _WANT_UCRED */ + +/* + * This is the external representation of struct ucred. + */ +struct xucred { + uInt32 cr_version; /* structure layout version */ + uid_t cr_uid; /* effective user id */ + short cr_ngroups; /* number of groups */ + gid_t cr_groups[NGROUPS]; /* groups */ + void *_cr_unused1; /* compatibility with old ucred */ +}; +#define XUCRED_VERSION 0 + +/* This can be used for both ucred and xucred structures. */ +#define cr_gid cr_groups[0] + +#ifdef _KERNEL +struct thread; + +void change_egid(struct ucred *newcred, gid_t egid); +void change_euid(struct ucred *newcred, struct uidinfo *euip); +void change_rgid(struct ucred *newcred, gid_t rgid); +void change_ruid(struct ucred *newcred, struct uidinfo *ruip); +void change_svgid(struct ucred *newcred, gid_t svgid); +void change_svuid(struct ucred *newcred, uid_t svuid); +void crcopy(struct ucred *dest, struct ucred *src); +struct ucred *crdup(struct ucred *cr); +#ifdef DIAGNOSTIC +void cred_free_thread(struct thread *td); +#endif +void cred_update_thread(struct thread *td); +void crfree(struct ucred *cr); +struct ucred *crget(void); +struct ucred *crhold(struct ucred *cr); +int crshared(struct ucred *cr); +void cru2x(struct ucred *cr, struct xucred *xcr); +int groupmember(gid_t gid, struct ucred *cred); +#endif /* _KERNEL */ + +#endif /* !_SYS_UCRED_H_ */ diff --git a/src/include/time.h b/src/include/time.h new file mode 100644 index 0000000..2b05e1b --- /dev/null +++ b/src/include/time.h @@ -0,0 +1,156 @@ +/* + * 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. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * @(#)time.h 8.3 (Berkeley) 1/21/94 + */ + +/* + * $FreeBSD: src/include/time.h,v 1.31 2003/12/07 21:10:06 marcel Exp $ + */ + +#ifndef _TIME_H_ +#define _TIME_H_ + +#include +#include +#include + +#if __POSIX_VISIBLE > 0 && __POSIX_VISIBLE < 200112 || __BSD_VISIBLE +/* + * Frequency of the clock ticks reported by times(). Deprecated - use + * sysconf(_SC_CLK_TCK) instead. (Removed in 1003.1-2001.) + */ +#define CLK_TCK 128 +#endif + +/* Frequency of the clock ticks reported by clock(). */ +#define CLOCKS_PER_SEC 128 + +#ifndef _CLOCK_T_DECLARED +typedef __clock_t clock_t; +#define _CLOCK_T_DECLARED +#endif + +#ifndef _TIME_T_DECLARED +typedef __time_t time_t; +#define _TIME_T_DECLARED +#endif + +#ifndef _SIZE_T_DECLARED +typedef __size_t size_t; +#define _SIZE_T_DECLARED +#endif + +#if __POSIX_VISIBLE >= 199309 +/* + * New in POSIX 1003.1b-1993. + */ +#ifndef _CLOCKID_T_DECLARED +typedef __clockid_t clockid_t; +#define _CLOCKID_T_DECLARED +#endif + +#ifndef _TIMER_T_DECLARED +typedef __timer_t timer_t; +#define _TIMER_T_DECLARED +#endif + +#include +#endif /* __POSIX_VISIBLE >= 199309 */ + +struct tm { + int tm_sec; /* seconds after the minute [0-60] */ + int tm_min; /* minutes after the hour [0-59] */ + int tm_hour; /* hours since midnight [0-23] */ + int tm_mday; /* day of the month [1-31] */ + int tm_mon; /* months since January [0-11] */ + int tm_year; /* years since 1900 */ + int tm_wday; /* days since Sunday [0-6] */ + int tm_yday; /* days since January 1 [0-365] */ + int tm_isdst; /* Daylight Savings Time flag */ + long tm_gmtoff; /* offset from UTC in seconds */ + char *tm_zone; /* timezone abbreviation */ +}; + +#if __POSIX_VISIBLE +extern char *tzname[]; +#endif + +__BEGIN_DECLS +char *asctime(const struct tm *); +clock_t clock(void); +char *ctime(const time_t *); +double difftime(time_t, time_t); +struct tm *gmtime(const time_t *); +struct tm *localtime(const time_t *); +time_t mktime(struct tm *); +size_t strftime(char * __restrict, size_t, const char * __restrict, + const struct tm * __restrict); +time_t time(time_t *); + +#if __POSIX_VISIBLE +void tzset(void); +#endif + +#if __POSIX_VISIBLE >= 199309 +int clock_getres(clockid_t, struct timespec *); +int clock_gettime(clockid_t, struct timespec *); +int clock_settime(clockid_t, const struct timespec *); +int nanosleep(const struct timespec *, struct timespec *); +#endif /* __POSIX_VISIBLE >= 199309 */ + +#if __POSIX_VISIBLE >= 199506 +char *asctime_r(const struct tm *, char *); +char *ctime_r(const time_t *, char *); +struct tm *gmtime_r(const time_t *, struct tm *); +struct tm *localtime_r(const time_t *, struct tm *); +#endif + +#if __XSI_VISIBLE +char *strptime(const char * __restrict, const char * __restrict, + struct tm * __restrict); +#endif + +#if __BSD_VISIBLE +char *timezone(int, int); +void tzsetwall(void); +time_t timelocal(struct tm * const); +time_t timegm(struct tm * const); +#endif /* __BSD_VISIBLE */ +__END_DECLS + +#endif /* !_TIME_H_ */ diff --git a/src/include/unistd.h b/src/include/unistd.h new file mode 100644 index 0000000..857b1c3 --- /dev/null +++ b/src/include/unistd.h @@ -0,0 +1,56 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#ifndef _UNISTD_H +#define _UNISTD_H + +#include +#include + +#ifndef _GETOPT_DECLARED +#define _GETOPT_DECLARED +int getopt(int, char * const [], const char *); +extern char *optarg; /* getopt(3) external variables */ +extern int optind, opterr, optopt; +#endif /* _GETOPT_DECLARED */ + +ssize_t write(int, const void *, size_t); +off_t lseek(int, off_t, int); + + +/**** END ****/ + + +uShort getpid(void); +pid_t fork(); + +//New Functions Added Belong Under Here +char *getcwd(char *buffer,uInt32 size); +int setuid(int); +int setgid(int); +int getuid(void); +int getgid(void); +int chdir(const char *path); +int unlink(const char *path); + +#endif diff --git a/src/include/wchar.h b/src/include/wchar.h new file mode 100644 index 0000000..cc1bbce --- /dev/null +++ b/src/include/wchar.h @@ -0,0 +1,204 @@ +/*- + * Copyright (c)1999 Citrus 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/include/wchar.h,v 1.36 2003/12/07 21:10:06 marcel Exp $ + */ + +/*- + * Copyright (c) 1999, 2000 The NetBSD Foundation, Inc. + * All rights reserved. + * + * This code is derived from software contributed to The NetBSD Foundation + * by Julian Coleman. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the 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: wchar.h,v 1.8 2000/12/22 05:31:42 itojun Exp $ + */ + +#ifndef _WCHAR_H_ +#define _WCHAR_H_ + +#include +#include +#include +#include + +#ifndef _MBSTATE_T_DECLARED +typedef __mbstate_t mbstate_t; +#define _MBSTATE_T_DECLARED +#endif + +#ifndef _SIZE_T_DECLARED +typedef __size_t size_t; +#define _SIZE_T_DECLARED +#endif + +#ifndef __cplusplus +#ifndef _WCHAR_T_DECLARED +typedef __wchar_t wchar_t; +#define _WCHAR_T_DECLARED +#endif +#endif + +#ifndef _WINT_T_DECLARED +typedef __wint_t wint_t; +#define _WINT_T_DECLARED +#endif + +#ifndef WCHAR_MIN +#define WCHAR_MIN __INT_MIN +#define WCHAR_MAX __INT_MAX +#endif + +#ifndef WEOF +#define WEOF ((wint_t)-1) +#endif + +struct __sFILE; +struct tm; + +__BEGIN_DECLS +wint_t btowc(int); +wint_t fgetwc(struct __sFILE *); +wchar_t * + fgetws(wchar_t * __restrict, int, struct __sFILE * __restrict); +wint_t fputwc(wchar_t, struct __sFILE *); +int fputws(const wchar_t * __restrict, struct __sFILE * __restrict); +int fwide(struct __sFILE *, int); +int fwprintf(struct __sFILE * __restrict, const wchar_t * __restrict, ...); +int fwscanf(struct __sFILE * __restrict, const wchar_t * __restrict, ...); +wint_t getwc(struct __sFILE *); +wint_t getwchar(void); +size_t mbrlen(const char * __restrict, size_t, mbstate_t * __restrict); +size_t mbrtowc(wchar_t * __restrict, const char * __restrict, size_t, + mbstate_t * __restrict); +int mbsinit(const mbstate_t *); +size_t mbsrtowcs(wchar_t * __restrict, const char ** __restrict, size_t, + mbstate_t * __restrict); +wint_t putwc(wchar_t, struct __sFILE *); +wint_t putwchar(wchar_t); +int swprintf(wchar_t * __restrict, size_t n, const wchar_t * __restrict, + ...); +int swscanf(const wchar_t * __restrict, const wchar_t * __restrict, ...); +wint_t ungetwc(wint_t, struct __sFILE *); +int vfwprintf(struct __sFILE * __restrict, const wchar_t * __restrict, + __va_list); +int vswprintf(wchar_t * __restrict, size_t n, const wchar_t * __restrict, + __va_list); +int vwprintf(const wchar_t * __restrict, __va_list); +size_t wcrtomb(char * __restrict, wchar_t, mbstate_t * __restrict); +wchar_t *wcscat(wchar_t * __restrict, const wchar_t * __restrict); +wchar_t *wcschr(const wchar_t *, wchar_t); +int wcscmp(const wchar_t *, const wchar_t *); +int wcscoll(const wchar_t *, const wchar_t *); +wchar_t *wcscpy(wchar_t * __restrict, const wchar_t * __restrict); +size_t wcscspn(const wchar_t *, const wchar_t *); +size_t wcsftime(wchar_t * __restrict, size_t, const wchar_t * __restrict, + const struct tm * __restrict); +size_t wcslen(const wchar_t *); +wchar_t *wcsncat(wchar_t * __restrict, const wchar_t * __restrict, + size_t); +int wcsncmp(const wchar_t *, const wchar_t *, size_t); +wchar_t *wcsncpy(wchar_t * __restrict , const wchar_t * __restrict, size_t); +wchar_t *wcspbrk(const wchar_t *, const wchar_t *); +wchar_t *wcsrchr(const wchar_t *, wchar_t); +size_t wcsrtombs(char * __restrict, const wchar_t ** __restrict, size_t, + mbstate_t * __restrict); +size_t wcsspn(const wchar_t *, const wchar_t *); +wchar_t *wcsstr(const wchar_t * __restrict, const wchar_t * __restrict); +size_t wcsxfrm(wchar_t * __restrict, const wchar_t * __restrict, size_t); +int wctob(wint_t); +double wcstod(const wchar_t * __restrict, wchar_t ** __restrict); +wchar_t *wcstok(wchar_t * __restrict, const wchar_t * __restrict, + wchar_t ** __restrict); +long wcstol(const wchar_t * __restrict, wchar_t ** __restrict, int); +unsigned long + wcstoul(const wchar_t * __restrict, wchar_t ** __restrict, int); +wchar_t *wmemchr(const wchar_t *, wchar_t, size_t); +int wmemcmp(const wchar_t *, const wchar_t *, size_t); +wchar_t *wmemcpy(wchar_t * __restrict, const wchar_t * __restrict, size_t); +wchar_t *wmemmove(wchar_t *, const wchar_t *, size_t); +wchar_t *wmemset(wchar_t *, wchar_t, size_t); +int wprintf(const wchar_t * __restrict, ...); +int wscanf(const wchar_t * __restrict, ...); + +#if __ISO_C_VISIBLE >= 1999 +int vfwscanf(struct __sFILE * __restrict, const wchar_t * __restrict, + __va_list); +int vswscanf(const wchar_t * __restrict, const wchar_t * __restrict, + __va_list); +int vwscanf(const wchar_t * __restrict, __va_list); +float wcstof(const wchar_t * __restrict, wchar_t ** __restrict); +long double + wcstold(const wchar_t * __restrict, wchar_t ** __restrict); +#ifdef __LONG_LONG_SUPPORTED +/* LONGLONG */ +long long + wcstoll(const wchar_t * __restrict, wchar_t ** __restrict, int); +/* LONGLONG */ +unsigned long long + wcstoull(const wchar_t * __restrict, wchar_t ** __restrict, int); +#endif +#endif /* __ISO_C_VISIBLE >= 1999 */ + +#if __XSI_VISIBLE +int wcswidth(const wchar_t *, size_t); +int wcwidth(wchar_t); +#endif + +#if __BSD_VISIBLE +size_t wcslcat(wchar_t *, const wchar_t *, size_t); +size_t wcslcpy(wchar_t *, const wchar_t *, size_t); +#endif +__END_DECLS + +#endif /* !_WCHAR_H_ */ diff --git a/src/lib/Makefile.inc b/src/lib/Makefile.inc new file mode 100644 index 0000000..b3cb8c4 --- /dev/null +++ b/src/lib/Makefile.inc @@ -0,0 +1,5 @@ +# $Id$ +# 'lib' options + +LDFLAGS = -Bshareable +CFLAGS = -fno-builtin diff --git a/src/lib/libc_old/Makefile b/src/lib/libc_old/Makefile new file mode 100644 index 0000000..71e83e6 --- /dev/null +++ b/src/lib/libc_old/Makefile @@ -0,0 +1,57 @@ +# $Id$ +# The System Makefile (C) 2002 The UbixOS Project + +# Include Global 'Source' Options +include ../../Makefile.inc +include ../Makefile.inc + +#Objects +OBJS = + +#Sub Sections +SUBS = ./stdio/*.o ./sys/*.o ./string/*.o ./stdlib/*.o ./math/*.o ./quad/*.o ./generic/*.o ./locale/*.o ./gen/*.o + +#Output +OUTPUT = libc.so + +lib.so: $(OBJS) + (cd stdio;make) + (cd stdlib;make) + (cd math;make) + (cd locale;make) + (cd quad;make) + (cd sys;make) + (cd string;make) + (cd generic;make) + (cd gen;make) +# $(LD) $(LDFLAGS) -o $(OUTPUT) $(OBJS) ./stdio/*.o ./sys/*.o ./string/*.o ./stdlib/*.o + $(CC) -nostdlib -shared -Wl,-soname,libc.so -o $(OUTPUT) $(OBJS) $(SUBS) + +# 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 stdio;make clean) + (cd sys;make clean) + (cd stdlib;make clean) + (cd locale;make clean) + (cd generic;make clean) + (cd string;make clean) + (cd math;make clean) + (cd quad;make clean) + (cd gen;make clean) diff --git a/src/lib/libc_old/gen/Makefile b/src/lib/libc_old/gen/Makefile new file mode 100644 index 0000000..4aab894 --- /dev/null +++ b/src/lib/libc_old/gen/Makefile @@ -0,0 +1,34 @@ +# $Id$ +# The System Makefile (C) 2002 The UbixOS Project + +# Include Global 'Source' Options +include ../../../Makefile.inc +include ../../Makefile.inc + +#Objects +OBJS = setprogname.o getprogname.o errlst.o err.o + +#Output +OUTPUT = libc.so + +$(OUTPUT): $(OBJS) + +# Compile the source files +.cc.o: + $(CXX) $(CFLAGS) -Wall -nostdlib -O -I../../../include -c -o $@ $< + +.cc.s: + $(CXX) $(CFLAGS) -Wall -nostdlib -O -I../../../include -S -o $@ $< + +.c.o: + $(CC) $(CFLAGS) -Wall -nostdlib -O -I. -I../../../include -c $< + +.c.s: + $(CC) $(CFLAGS) -Wall -nostdlib -O -I../../../include -S -o $@ $< + +.S.o: + $(CC) $(CFLAGS) -Wall -nostdlib -c -o $@ $< + +# Clean up the junk +clean: + $(REMOVE) $(OBJS) $(OUTPUT) diff --git a/src/lib/libc_old/gen/err.c b/src/lib/libc_old/gen/err.c new file mode 100644 index 0000000..5ae43f3 --- /dev/null +++ b/src/lib/libc_old/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, ...) +{ + vaList ap; + vaStart(ap, fmt); + verrc(eval, errno, fmt, ap); + vaEnd(ap); +} + +void +verr(eval, fmt, ap) + int eval; + const char *fmt; + vaList ap; +{ + verrc(eval, errno, fmt, ap); +} + +void +errc(int eval, int code, const char *fmt, ...) +{ + vaList ap; + vaStart(ap, fmt); + verrc(eval, code, fmt, ap); + vaEnd(ap); +} + +void +verrc(eval, code, fmt, ap) + int eval; + int code; + const char *fmt; + vaList 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, ...) +{ + vaList ap; + vaStart(ap, fmt); + verrx(eval, fmt, ap); + vaEnd(ap); +} + +void +verrx(eval, fmt, ap) + int eval; + const char *fmt; + vaList 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, ...) +{ + vaList ap; + vaStart(ap, fmt); + vwarnc(errno, fmt, ap); + vaEnd(ap); +} + +void +vwarn(fmt, ap) + const char *fmt; + vaList ap; +{ + vwarnc(errno, fmt, ap); +} + +void +warnc(int code, const char *fmt, ...) +{ + vaList ap; + vaStart(ap, fmt); + vwarnc(code, fmt, ap); + vaEnd(ap); +} + +void +vwarnc(code, fmt, ap) + int code; + const char *fmt; + vaList 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, ...) +{ + vaList ap; + vaStart(ap, fmt); + vwarnx(fmt, ap); + vaEnd(ap); +} + +void +vwarnx(fmt, ap) + const char *fmt; + vaList 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/src/lib/libc_old/gen/errlst.c b/src/lib/libc_old/gen/errlst.c new file mode 100644 index 0000000..5207748 --- /dev/null +++ b/src/lib/libc_old/gen/errlst.c @@ -0,0 +1,153 @@ +/* + * 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.7 2002/10/09 08:04:24 peter 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 */ +}; +const int sys_nerr = sizeof(sys_errlist) / sizeof(sys_errlist[0]); diff --git a/src/lib/libc_old/gen/getprogname.c b/src/lib/libc_old/gen/getprogname.c new file mode 100644 index 0000000..4be82e3 --- /dev/null +++ b/src/lib/libc_old/gen/getprogname.c @@ -0,0 +1,17 @@ +#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/src/lib/libc_old/gen/libc_private.h b/src/lib/libc_old/gen/libc_private.h new file mode 100644 index 0000000..63f8610 --- /dev/null +++ b/src/lib/libc_old/gen/libc_private.h @@ -0,0 +1,129 @@ +/* + * 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. + * + * $FreeBSD: src/lib/libc/include/libc_private.h,v 1.11 2003/11/05 18:17:30 deischen Exp $ + * + * 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 + + +/* + * 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/src/lib/libc_old/gen/namespace.h b/src/lib/libc_old/gen/namespace.h new file mode 100644 index 0000000..1e59c6c --- /dev/null +++ b/src/lib/libc_old/gen/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. + * + * $FreeBSD: src/lib/libc/include/namespace.h,v 1.16 2003/05/01 19:03:13 nectar Exp $ + */ + +#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 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/src/lib/libc_old/gen/setprogname.c b/src/lib/libc_old/gen/setprogname.c new file mode 100644 index 0000000..654bef4 --- /dev/null +++ b/src/lib/libc_old/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/src/lib/libc_old/gen/un-namespace.h b/src/lib/libc_old/gen/un-namespace.h new file mode 100644 index 0000000..067e22d --- /dev/null +++ b/src/lib/libc_old/gen/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. + * + * $FreeBSD: src/lib/libc/include/un-namespace.h,v 1.13 2003/05/01 19:03:13 nectar Exp $ + */ + +#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 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/src/lib/libc_old/generic/Makefile b/src/lib/libc_old/generic/Makefile new file mode 100644 index 0000000..f76f39f --- /dev/null +++ b/src/lib/libc_old/generic/Makefile @@ -0,0 +1,33 @@ +# $Id$ +# The System Makefile (C) 2002 The UbixOS Project + +# Include Global 'Source' Options +include ../../../Makefile.inc +include ../../Makefile.inc + +#Objects +OBJS = unlink.o getcwd.o mkdir.o chdir.o +#Output +OUTPUT = libc.so + +$(OUTPUT): $(OBJS) + +# Compile the source files +.cc.o: + $(CXX) $(CFLAGS) -Wall -nostdlib -O -I../include -c -o $@ $< + +.cc.s: + $(CXX) $(CFLAGS) -Wall -nostdlib -O -I../include -S -o $@ $< + +.c.o: + $(CC) $(CFLAGS) -Wall -nostdlib -O -I../include -I../../../include -c $< + +.c.s: + $(CC) $(CFLAGS) -Wall -nostdlib -O -I../include -S -o $@ $< + +.S.o: + $(CC) $(CFLAGS) -Wall -nostdlib -c -o $@ $< + +# Clean up the junk +clean: + $(REMOVE) $(OBJS) $(OUTPUT) diff --git a/src/lib/libc_old/generic/chdir.c b/src/lib/libc_old/generic/chdir.c new file mode 100644 index 0000000..b1f7be4 --- /dev/null +++ b/src/lib/libc_old/generic/chdir.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$ + +**************************************************************************************/ + +int chdir(const char *path) { + asm( + "int %0\n" + : : "i" (0x80),"a" (28),"b" (path) + ); + return(0x0); + } \ No newline at end of file diff --git a/src/lib/libc_old/generic/getcwd.c b/src/lib/libc_old/generic/getcwd.c new file mode 100644 index 0000000..5c03359 --- /dev/null +++ b/src/lib/libc_old/generic/getcwd.c @@ -0,0 +1,32 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#include + +char *getcwd(char *cwd,uInt32 len) { + asm( + "int %0\n" + : : "i" (0x80),"a" (26),"b" (cwd) + ); + return(cwd); + } diff --git a/src/lib/libc_old/generic/mkdir.c b/src/lib/libc_old/generic/mkdir.c new file mode 100644 index 0000000..3f58803 --- /dev/null +++ b/src/lib/libc_old/generic/mkdir.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$ + +**************************************************************************************/ + +int mkdir(const char *path) { + asm( + "int %0\n" + : : "i" (0x80),"a" (29),"b" (path) + ); + return(0x0); + } diff --git a/src/lib/libc_old/generic/unlink.c b/src/lib/libc_old/generic/unlink.c new file mode 100644 index 0000000..ef248e7 --- /dev/null +++ b/src/lib/libc_old/generic/unlink.c @@ -0,0 +1,31 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +int unlink(const char *path) { + int retVal = 0x0; + asm( + "int %0\n" + : : "i" (0x80),"a" (30),"b" (path),"c" (&retVal) + ); + return(retVal); + } diff --git a/src/lib/libc_old/locale/Makefile b/src/lib/libc_old/locale/Makefile new file mode 100644 index 0000000..2354356 --- /dev/null +++ b/src/lib/libc_old/locale/Makefile @@ -0,0 +1,34 @@ +# $Id$ +# The System Makefile (C) 2002 The UbixOS Project + +# Include Global 'Source' Options +include ../../../Makefile.inc +include ../../Makefile.inc + +#Objects +OBJS = mbrtowc.o srune.o none.o wcrtomb.o table.o runetype.o toupper.o tolower.o + +#Output +OUTPUT = libc.so + +$(OUTPUT): $(OBJS) + +# Compile the source files +.cc.o: + $(CXX) $(CFLAGS) -Wall -nostdlib -O -I../include -c -o $@ $< + +.cc.s: + $(CXX) $(CFLAGS) -Wall -nostdlib -O -I../include -S -o $@ $< + +.c.o: + $(CC) $(CFLAGS) -Wall -nostdlib -O -I../include -I../../../include -c $< + +.c.s: + $(CC) $(CFLAGS) -Wall -nostdlib -O -I../include -S -o $@ $< + +.S.o: + $(CC) $(CFLAGS) -Wall -nostdlib -c -o $@ $< + +# Clean up the junk +clean: + $(REMOVE) $(OBJS) $(OUTPUT) diff --git a/src/lib/libc_old/locale/mbrtowc.c b/src/lib/libc_old/locale/mbrtowc.c new file mode 100644 index 0000000..e45dd95 --- /dev/null +++ b/src/lib/libc_old/locale/mbrtowc.c @@ -0,0 +1,90 @@ +/*- + * 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/mbrtowc.c,v 1.4 2003/11/01 05:13:13 tjr Exp $"); + +#include +#include +#include +#include + +extern size_t (*__mbrtowc)(wchar_t * __restrict, const char * __restrict, + size_t, mbstate_t * __restrict); + +size_t +mbrtowc(wchar_t * __restrict pwc, const char * __restrict s, + size_t n, mbstate_t * __restrict ps) +{ + + return (__mbrtowc(pwc, s, n, ps)); +} + +/* + * Emulate the ISO C mbrtowc() function in terms of the deprecated + * 4.4BSD sgetrune() function. + */ +size_t +__emulated_mbrtowc(wchar_t * __restrict pwc, const char * __restrict s, + size_t n, mbstate_t * __restrict ps __unused) +{ + const char *e; + rune_t r; + + if (s == NULL) { + pwc = NULL; + s = ""; + n = 1; + } + + if ((r = sgetrune(s, n, &e)) == _INVALID_RUNE) { + /* + * The design of sgetrune() doesn't give us any way to tell + * between incomplete and invalid multibyte sequences. + */ + + if (n >= (size_t)MB_CUR_MAX) { + /* + * If we have been supplied with at least MB_CUR_MAX + * bytes and still cannot find a valid character, the + * data must be invalid. + */ + errno = EILSEQ; + return ((size_t)-1); + } + + /* + * .. otherwise, it's an incomplete character or an invalid + * character we cannot detect yet. + */ + return ((size_t)-2); + } + + if (pwc != NULL) + *pwc = (wchar_t)r; + + return (r != 0 ? (size_t)(e - s) : 0); +} diff --git a/src/lib/libc_old/locale/none.c b/src/lib/libc_old/locale/none.c new file mode 100644 index 0000000..e891c13 --- /dev/null +++ b/src/lib/libc_old/locale/none.c @@ -0,0 +1,102 @@ +/*- + * Copyright (c) 2002, 2003 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.7 2003/11/01 05:13:13 tjr Exp $"); + +#include +#include +#include +#include +#include +#include +#include + +extern size_t (*__mbrtowc)(wchar_t * __restrict, const char * __restrict, + size_t, mbstate_t * __restrict); +extern size_t (*__wcrtomb)(char * __restrict, wchar_t, mbstate_t * __restrict); + +int _none_init(_RuneLocale *); +size_t _none_mbrtowc(wchar_t * __restrict, const char * __restrict, size_t, + mbstate_t * __restrict); +size_t _none_wcrtomb(char * __restrict, wchar_t, mbstate_t * __restrict); + +int +_none_init(_RuneLocale *rl) +{ + + __mbrtowc = _none_mbrtowc; + __wcrtomb = _none_wcrtomb; + _CurrentRuneLocale = rl; + __mb_cur_max = 1; + return(0); +} + +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); +} + +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); +} diff --git a/src/lib/libc_old/locale/runetype.c b/src/lib/libc_old/locale/runetype.c new file mode 100644 index 0000000..e843637 --- /dev/null +++ b/src/lib/libc_old/locale/runetype.c @@ -0,0 +1,66 @@ +/*- + * 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.8 2002/08/21 16:19:56 mike Exp $"); + +#include +#include + +unsigned long +___runetype(c) + __ct_rune_t c; +{ + int x; + _RuneRange *rr = &_CurrentRuneLocale->runetype_ext; + _RuneEntry *re = rr->ranges; + + if (c < 0 || c == EOF) + return(0L); + + for (x = 0; x < rr->nranges; ++x, ++re) { + if (c < re->min) + return(0L); + if (c <= re->max) { + if (re->types) + return(re->types[c - re->min]); + else + return(re->map); + } + } + + return(0L); +} diff --git a/src/lib/libc_old/locale/srune.c b/src/lib/libc_old/locale/srune.c new file mode 100644 index 0000000..c986053 --- /dev/null +++ b/src/lib/libc_old/locale/srune.c @@ -0,0 +1,95 @@ +/*- + * 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/locale/srune.c,v 1.2 2004/01/06 18:26:14 nectar Exp $"); + +#include +#include +#include +#include + +/* + * Emulate the deprecated 4.4BSD sgetrune() function in terms of + * the ISO C mbrtowc() function. + */ +rune_t +__emulated_sgetrune(const char *string, size_t n, const char **result) +{ + wchar_t wc; + size_t nconv; + + /* + * Pass a NULL conversion state to mbrtowc() since multibyte + * conversion states are not supported. + */ + nconv = mbrtowc(&wc, string, n, NULL); + if (nconv == (size_t)-2) { + if (result != NULL) + *result = string; + return (_INVALID_RUNE); + } + if (nconv == (size_t)-1) { + if (result != NULL) + *result = string + 1; + return (_INVALID_RUNE); + } + if (nconv == 0) + nconv = 1; + if (result != NULL) + *result = string + nconv; + return ((rune_t)wc); +} + +/* + * Emulate the deprecated 4.4BSD sputrune() function in terms of + * the ISO C wcrtomb() function. + */ +int +__emulated_sputrune(rune_t rune, char *string, size_t n, char **result) +{ + char buf[MB_LEN_MAX]; + size_t nconv; + + nconv = wcrtomb(buf, (wchar_t)rune, NULL); + if (nconv == (size_t)-1) { + if (result != NULL) + *result = NULL; + return (0); + } + if (string == NULL) { + if (result != NULL) + *result = (char *)0 + nconv; + } else if (n >= nconv) { + memcpy(string, buf, nconv); + if (result != NULL) + *result = string + nconv; + } else { + if (result != NULL) + *result = NULL; + } + return (nconv); +} diff --git a/src/lib/libc_old/locale/table.c b/src/lib/libc_old/locale/table.c new file mode 100644 index 0000000..e9feeda --- /dev/null +++ b/src/lib/libc_old/locale/table.c @@ -0,0 +1,268 @@ +/*- + * 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.19 2003/11/01 05:13:13 tjr Exp $"); + +#include +#include +#include + +extern size_t _none_mbrtowc(wchar_t * __restrict, const char * __restrict, size_t, + mbstate_t * __restrict); +extern size_t _none_wcrtomb(char * __restrict, wchar_t, mbstate_t * __restrict); +extern size_t __emulated_mbrtowc(wchar_t * __restrict, + const char * __restrict, size_t, + mbstate_t * __restrict ps); +extern size_t __emulated_wcrtomb(char * __restrict, wchar_t, + mbstate_t * __restrict ps); +extern rune_t __emulated_sgetrune(const char *, size_t, const char **); +extern int __emulated_sputrune(rune_t, char *, size_t, char **); + +_RuneLocale _DefaultRuneLocale = { + _RUNE_MAGIC_1, + "NONE", + __emulated_sgetrune, + __emulated_sputrune, + 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; + +int __mb_cur_max = 1; +size_t (*__mbrtowc)(wchar_t * __restrict, const char * __restrict, size_t, + mbstate_t * __restrict) = _none_mbrtowc; +size_t (*__wcrtomb)(char * __restrict, wchar_t, mbstate_t * __restrict) = + _none_wcrtomb; diff --git a/src/lib/libc_old/locale/tolower.c b/src/lib/libc_old/locale/tolower.c new file mode 100644 index 0000000..72888c6 --- /dev/null +++ b/src/lib/libc_old/locale/tolower.c @@ -0,0 +1,26 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ +int tolower (int c) { + if (c >= 'A' && c <= 'Z') c += ('a' - 'A'); + return c; +} diff --git a/src/lib/libc_old/locale/toupper.c b/src/lib/libc_old/locale/toupper.c new file mode 100644 index 0000000..dc784de --- /dev/null +++ b/src/lib/libc_old/locale/toupper.c @@ -0,0 +1,27 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +int toupper(int c) { +if (c >= 'a' && c <= 'z') c += ('A' - 'a'); + return c; +} \ No newline at end of file diff --git a/src/lib/libc_old/locale/wcrtomb.c b/src/lib/libc_old/locale/wcrtomb.c new file mode 100644 index 0000000..1f2e150 --- /dev/null +++ b/src/lib/libc_old/locale/wcrtomb.c @@ -0,0 +1,66 @@ +/*- + * 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/wcrtomb.c,v 1.5 2003/11/01 05:13:13 tjr Exp $"); + +#include +#include +#include +#include +#include + +extern size_t (*__wcrtomb)(char * __restrict, wchar_t, mbstate_t * __restrict); + +size_t +wcrtomb(char * __restrict s, wchar_t wc, mbstate_t * __restrict ps) +{ + + return (__wcrtomb(s, wc, ps)); +} + +/* + * Emulate the ISO C wcrtomb() function in terms of the deprecated + * 4.4BSD sputrune() function. + */ +size_t +__emulated_wcrtomb(char * __restrict s, wchar_t wc, + mbstate_t * __restrict ps __unused) +{ + char *e; + char buf[MB_LEN_MAX]; + + if (s == NULL) { + s = buf; + wc = L'\0'; + } + sputrune(wc, s, MB_CUR_MAX, &e); + if (e == NULL) { + errno = EILSEQ; + return ((size_t)-1); + } + return ((size_t)(e - s)); +} diff --git a/src/lib/libc_old/math/Makefile b/src/lib/libc_old/math/Makefile new file mode 100644 index 0000000..1b73391 --- /dev/null +++ b/src/lib/libc_old/math/Makefile @@ -0,0 +1,34 @@ +# $Id$ +# The System Makefile (C) 2002 The UbixOS Project + +# Include Global 'Source' Options +include ../../../Makefile.inc +include ../../Makefile.inc + +#Objects +OBJS = atan.o sqrt.o + +#Output +OUTPUT = libc.so + +$(OUTPUT): $(OBJS) + +# Compile the source files +.cc.o: + $(CXX) $(CFLAGS) -Wall -nostdlib -O -I../include -c -o $@ $< + +.cc.s: + $(CXX) $(CFLAGS) -Wall -nostdlib -O -I../include -S -o $@ $< + +.c.o: + $(CC) $(CFLAGS) -Wall -nostdlib -O -I../include -c $< + +.c.s: + $(CC) $(CFLAGS) -Wall -nostdlib -O -I../include -S -o $@ $< + +.S.o: + $(CC) $(CFLAGS) -Wall -nostdlib -c -o $@ $< + +# Clean up the junk +clean: + $(REMOVE) $(OBJS) $(OUTPUT) diff --git a/src/lib/libc_old/math/atan.c b/src/lib/libc_old/math/atan.c new file mode 100644 index 0000000..ee59158 --- /dev/null +++ b/src/lib/libc_old/math/atan.c @@ -0,0 +1,5 @@ +#include + +double atan(double val) { + return(val); + } diff --git a/src/lib/libc_old/math/sqrt.c b/src/lib/libc_old/math/sqrt.c new file mode 100644 index 0000000..581e032 --- /dev/null +++ b/src/lib/libc_old/math/sqrt.c @@ -0,0 +1,5 @@ +#include + +double sqrt(double val) { + return(val); + } diff --git a/src/lib/libc_old/quad/Makefile b/src/lib/libc_old/quad/Makefile new file mode 100644 index 0000000..82ed23e --- /dev/null +++ b/src/lib/libc_old/quad/Makefile @@ -0,0 +1,33 @@ +# $Id$ +# The System Makefile (C) 2002 The UbixOS Project + +# Include Global 'Source' Options +include ../../../Makefile.inc +include ../../Makefile.inc + +#Objects +OBJS = udivdi3.o divdi3.o +#Output +OUTPUT = libc.so + +$(OUTPUT): $(OBJS) + +# Compile the source files +.cc.o: + $(CXX) $(CFLAGS) -Wall -nostdlib -O -I../../../include -c -o $@ $< + +.cc.s: + $(CXX) $(CFLAGS) -Wall -nostdlib -O -I../include -S -o $@ $< + +.c.o: + $(CC) $(CFLAGS) -Wall -nostdlib -O -I../../../include -c $< + +.c.s: + $(CC) $(CFLAGS) -Wall -nostdlib -O -I../include -S -o $@ $< + +.S.o: + $(CC) $(CFLAGS) -Wall -nostdlib -c -o $@ $< + +# Clean up the junk +clean: + $(REMOVE) $(OBJS) $(OUTPUT) diff --git a/src/lib/libc_old/quad/divdi3.c b/src/lib/libc_old/quad/divdi3.c new file mode 100644 index 0000000..914b0be --- /dev/null +++ b/src/lib/libc_old/quad/divdi3.c @@ -0,0 +1,17 @@ +#include + +quad_t __divdi3(quad_t a,quad_t b) { + u_quad_t ua = 0x0, ub = 0x0, uq = 0x0; + 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/src/lib/libc_old/quad/qdivrem.c b/src/lib/libc_old/quad/qdivrem.c new file mode 100644 index 0000000..0fa5cb8 --- /dev/null +++ b/src/lib/libc_old/quad/qdivrem.c @@ -0,0 +1,199 @@ +#include + +u_quad_t +__qdivrem(uq, vq, arq) + u_quad_t uq, vq, *arq; +{ + union uu tmp; + digit *u, *v, *q; + register 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 { + register 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/src/lib/libc_old/quad/udivdi3.c b/src/lib/libc_old/quad/udivdi3.c new file mode 100644 index 0000000..4c9908d --- /dev/null +++ b/src/lib/libc_old/quad/udivdi3.c @@ -0,0 +1,7 @@ +#include + +u_quad_t __udivdi3(u_quad_t a,u_quad_t b) { + + //return (__qdivrem(a, b, (u_quad_t *)0)); + return(0); +} diff --git a/src/lib/libc_old/stdio/Makefile b/src/lib/libc_old/stdio/Makefile new file mode 100644 index 0000000..592bc8e --- /dev/null +++ b/src/lib/libc_old/stdio/Makefile @@ -0,0 +1,34 @@ +# $Id$ +# The System Makefile (C) 2002 The UbixOS Project + +# Include Global 'Source' Options +include ../../../Makefile.inc +include ../../Makefile.inc + +#Objects +OBJS = fprintf.o fseek.o printf.o vsprintf.o fd.o vfprintf.o fopen.o fread.o fwrite.o fgetc.o sprintf.o gets.o fclose.o + +#Output +OUTPUT = libc.so + +$(OUTPUT): $(OBJS) + +# Compile the source files +.cc.o: + $(CXX) $(CFLAGS) -Wall -nostdlib -O -I../include -c -o $@ $< + +.cc.s: + $(CXX) $(CFLAGS) -Wall -nostdlib -O -I../include -S -o $@ $< + +.c.o: + $(CC) $(CFLAGS) -Wall -nostdlib -O -I../include -I../../../include -c $< + +.c.s: + $(CC) $(CFLAGS) -Wall -nostdlib -O -I../include -S -o $@ $< + +.S.o: + $(CC) $(CFLAGS) -Wall -nostdlib -c -o $@ $< + +# Clean up the junk +clean: + $(REMOVE) $(OBJS) $(OUTPUT) diff --git a/src/lib/libc_old/stdio/fclose.c b/src/lib/libc_old/stdio/fclose.c new file mode 100644 index 0000000..6ee582a --- /dev/null +++ b/src/lib/libc_old/stdio/fclose.c @@ -0,0 +1,35 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#include +#include + +int fclose(FILE *fp) { + int status = 0x0; + asm( + "int %0\n" + : : "i" (0x80),"a" (10),"b" (fp),"c" (&status) + ); + return(status); + } + diff --git a/src/lib/libc_old/stdio/fd.c b/src/lib/libc_old/stdio/fd.c new file mode 100644 index 0000000..57563f5 --- /dev/null +++ b/src/lib/libc_old/stdio/fd.c @@ -0,0 +1,32 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#include + +FILE fdTable[3] = { + {0x0}, /* stdin */ + {0x1}, /* stdout */ + {0x2} /* stderr */ + }; + + diff --git a/src/lib/libc_old/stdio/fgetc.c b/src/lib/libc_old/stdio/fgetc.c new file mode 100644 index 0000000..bd562a0 --- /dev/null +++ b/src/lib/libc_old/stdio/fgetc.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$ + +**************************************************************************************/ + +#include + +int fgetc(FILE *fd) { + volatile int ch = 0; + asm( + "int %0" + : + : "i" (0x80),"a" (5),"b" (&ch),"c" (fd) + ); + return(ch); + } diff --git a/src/lib/libc_old/stdio/fopen.c b/src/lib/libc_old/stdio/fopen.c new file mode 100644 index 0000000..507fef1 --- /dev/null +++ b/src/lib/libc_old/stdio/fopen.c @@ -0,0 +1,36 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#include +#include + +FILE *fopen(const char *file,const char *mode) { + FILE *fp = malloc(sizeof(FILE)); + fp->fd = -1; + asm( + "int %0\n" + : : "i" (0x80),"a" (8),"b" (file),"c" (mode),"d" (fp) + ); + //printf("\0",fp->fd); + return((FILE *)fp); + } diff --git a/src/lib/libc_old/stdio/fprintf.c b/src/lib/libc_old/stdio/fprintf.c new file mode 100644 index 0000000..f1b6c32 --- /dev/null +++ b/src/lib/libc_old/stdio/fprintf.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$ + +**************************************************************************************/ + +#include +#include + +int fprintf(FILE *fp,const char *fmt, ...) { + int retVal; + vaList ap; + vaStart(ap, fmt); + retVal = vfprintf(fp, fmt, ap); + vaEnd(ap); + return(retVal); + } diff --git a/src/lib/libc_old/stdio/fread.c b/src/lib/libc_old/stdio/fread.c new file mode 100644 index 0000000..50ac13c --- /dev/null +++ b/src/lib/libc_old/stdio/fread.c @@ -0,0 +1,33 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#include + +size_t fread(void *pointer,size_t size,size_t count, FILE *stream) { + asm( + "int %0\n" + : : "i" (0x80),"a" (22),"b" (pointer),"c" (size * count),"d" (stream) + ); + return(count); + } + diff --git a/src/lib/libc_old/stdio/fseek.c b/src/lib/libc_old/stdio/fseek.c new file mode 100644 index 0000000..12542cb --- /dev/null +++ b/src/lib/libc_old/stdio/fseek.c @@ -0,0 +1,32 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#include + +int fseek(FILE *fd,long offset,int whence) { + asm( + "int %0\n" + : : "i" (0x80),"a" (27),"b" (fd),"c" (offset),"d" (whence) + ); + return(offset+whence); + } diff --git a/src/lib/libc_old/stdio/fwrite.c b/src/lib/libc_old/stdio/fwrite.c new file mode 100644 index 0000000..8fca2cc --- /dev/null +++ b/src/lib/libc_old/stdio/fwrite.c @@ -0,0 +1,35 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#include + +int fwrite(const void *ptr,int size,int nmemb,FILE *fd) { + int retVal = size; + asm( + "int %0" + : + : "i" (0x80),"a" (23),"b" (ptr),"c" (size*nmemb),"d" (fd) + ); + return(retVal); + } + diff --git a/src/lib/libc_old/stdio/gets.c b/src/lib/libc_old/stdio/gets.c new file mode 100644 index 0000000..f9b7f30 --- /dev/null +++ b/src/lib/libc_old/stdio/gets.c @@ -0,0 +1,43 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#include + +char *gets(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("%c",ch); + count ++; + } + string[count] = '\0'; + return(string); + } + diff --git a/src/lib/libc_old/stdio/printf.c b/src/lib/libc_old/stdio/printf.c new file mode 100644 index 0000000..4db8494 --- /dev/null +++ b/src/lib/libc_old/stdio/printf.c @@ -0,0 +1,36 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#include +#include + +int printf(char const *fmt, ...) { + int retVal; + vaList ap; + vaStart(ap, fmt); + retVal = vfprintf(stdin, fmt, ap); + vaEnd(ap); + return(retVal); + } + + diff --git a/src/lib/libc_old/stdio/sprintf.c b/src/lib/libc_old/stdio/sprintf.c new file mode 100644 index 0000000..6fc3aa6 --- /dev/null +++ b/src/lib/libc_old/stdio/sprintf.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$ + +**************************************************************************************/ + +#include + +int sprintf(char *string, const char *format, ...) { + vaList args; + int retVal = 0x0; + vaStart(args, format); + retVal = vsprintf(string,format,args); + vaEnd(args); + return(retVal); + } + diff --git a/src/lib/libc_old/stdio/vfprintf.c b/src/lib/libc_old/stdio/vfprintf.c new file mode 100644 index 0000000..9409d9c --- /dev/null +++ b/src/lib/libc_old/stdio/vfprintf.c @@ -0,0 +1,37 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#include +#include + +int vfprintf(FILE *fd,const char *fmt,vaList args) { + int retVal = 0; + char data[512]; + retVal = vsprintf(data,fmt,args); + asm volatile( + "int %0" + : + : "i" (0x80),"a" (23),"b" (&data),"c" (retVal),"d" (fd) + ); + return(retVal); + } diff --git a/src/lib/libc_old/stdio/vsprintf.c b/src/lib/libc_old/stdio/vsprintf.c new file mode 100644 index 0000000..6a1055f --- /dev/null +++ b/src/lib/libc_old/stdio/vsprintf.c @@ -0,0 +1,241 @@ +/************************************************************************************** + Copyright (c) 2002 The UbixOS Project + All rights reserved. + + Redistribution and use in source and binary forms, with or without modification, + are prohibited. + + $Id$ + +**************************************************************************************/ + +/* vsprintf.c -- Lars Wirzenius & Linus Torvalds. */ +/* + * Wirzenius wrote this portably, Torvalds fucked it up :-) + */ + +#include +#include + +/* we use this so that we can do without the ctype library */ +#define is_digit(c) ((c) >= '0' && (c) <= '9') + +static int skip_atoi(const char **s) +{ + int i=0; + + while (is_digit(**s)) + i = i*10 + *((*s)++) - '0'; + return i; +} + +#define ZEROPAD 1 /* pad with zero */ +#define SIGN 2 /* unsigned/signed long */ +#define PLUS 4 /* show plus */ +#define SPACE 8 /* space if plus */ +#define LEFT 16 /* left justified */ +#define SPECIAL 32 /* 0x */ +#define SMALL 64 /* use 'abcdef' instead of 'ABCDEF' */ + +#define do_div(n,base) ({ \ +int __res; \ +__asm__("divl %4":"=a" (n),"=d" (__res):"0" (n),"1" (0),"r" (base)); \ +__res; }) + +static char * number(char * str, int num, int base, int size, int precision + ,int type) +{ + char c,sign,tmp[36]; + const char *digits="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + int i; + + if (type&SMALL) digits="0123456789abcdefghijklmnopqrstuvwxyz"; + if (type&LEFT) type &= ~ZEROPAD; + if (base<2 || base>36) + return 0; + c = (type & ZEROPAD) ? '0' : ' ' ; + if (type&SIGN && num<0) { + sign='-'; + num = -num; + } else + sign=(type&PLUS) ? '+' : ((type&SPACE) ? ' ' : 0); + if (sign) size--; + if (type&SPECIAL) { + if (base==16) { size -= 2; } + else if (base==8) { size--; } + } + i=0; + if (num==0) + tmp[i++]='0'; + else while (num!=0) + tmp[i++]=digits[do_div(num,base)]; + if (i>precision) precision=i; + size -= precision; + if (!(type&(ZEROPAD+LEFT))) + while(size-->0) + *str++ = ' '; + if (sign) + *str++ = sign; + if (type&SPECIAL) { + if (base==8) { + *str++ = '0'; + } + else if (base==16) { + *str++ = '0'; + *str++ = digits[33]; + } + } + if (!(type&LEFT)) + while(size-->0) + *str++ = c; + while(i0) + *str++ = tmp[i]; + while(size-->0) + *str++ = ' '; + return str; +} + +int vsprintf(char *buf, const char *fmt, vaList args) +{ + int len; + int i; + char * str; + char *s; + int *ip; + + int flags; /* flags to number() */ + + int field_width; /* width of output field */ + int precision; /* min. # of digits for integers; max + number of chars for from string */ + int qualifier; /* 'h', 'l', or 'L' for integer fields */ + + for (str=buf ; *fmt ; ++fmt) { + if (*fmt != '%') { + *str++ = *fmt; + continue; + } + + /* process flags */ + flags = 0; + repeat: + ++fmt; /* this also skips first '%' */ + switch (*fmt) { + case '-': flags |= LEFT; goto repeat; + case '+': flags |= PLUS; goto repeat; + case ' ': flags |= SPACE; goto repeat; + case '#': flags |= SPECIAL; goto repeat; + case '0': flags |= ZEROPAD; goto repeat; + } + + /* get field width */ + field_width = -1; + if (is_digit(*fmt)) + field_width = skip_atoi(&fmt); + else if (*fmt == '*') { + /* it's the next argument */ + field_width = vaArg(args, int); + if (field_width < 0) { + field_width = -field_width; + flags |= LEFT; + } + } + + /* get the precision */ + precision = -1; + if (*fmt == '.') { + ++fmt; + if (is_digit(*fmt)) + precision = skip_atoi(&fmt); + else if (*fmt == '*') { + /* it's the next argument */ + precision = vaArg(args, int); + } + if (precision < 0) + precision = 0; + } + + /* get the conversion qualifier */ + qualifier = -1; + if (*fmt == 'h' || *fmt == 'l' || *fmt == 'L') { + qualifier = *fmt; + ++fmt; + } + + switch (*fmt) { + case 'c': + if (!(flags & LEFT)) + while (--field_width > 0) + *str++ = ' '; + *str++ = (unsigned char) vaArg(args, int); + while (--field_width > 0) + *str++ = ' '; + break; + + case 's': + s = vaArg(args, char *); + len = strlen(s); + if (precision < 0) + precision = len; + else if (len > precision) + len = precision; + + if (!(flags & LEFT)) + while (len < field_width--) + *str++ = ' '; + for (i = 0; i < len; ++i) + *str++ = *s++; + while (len < field_width--) + *str++ = ' '; + break; + + case 'o': + str = number(str, vaArg(args, unsigned long), 8, + field_width, precision, flags); + break; + + case 'p': + if (field_width == -1) { + field_width = 8; + flags |= ZEROPAD; + } + str = number(str, + (unsigned long) vaArg(args, void *), 16, + field_width, precision, flags); + break; + + case 'x': + flags |= SMALL; + case 'X': + str = number(str, vaArg(args, unsigned long), 16, + field_width, precision, flags); + break; + + case 'd': + case 'i': + flags |= SIGN; + case 'u': + str = number(str, vaArg(args, unsigned long), 10, + field_width, precision, flags); + break; + + case 'n': + ip = vaArg(args, int *); + *ip = (str - buf); + break; + + default: + if (*fmt != '%') + *str++ = '%'; + if (*fmt) + *str++ = *fmt; + else + --fmt; + break; + } + } + *str = '\0'; + return str-buf; +} diff --git a/src/lib/libc_old/stdlib/Makefile b/src/lib/libc_old/stdlib/Makefile new file mode 100644 index 0000000..db318b8 --- /dev/null +++ b/src/lib/libc_old/stdlib/Makefile @@ -0,0 +1,34 @@ +# $Id$ +# The System Makefile (C) 2002 The UbixOS Project + +# Include Global 'Source' Options +include ../../../Makefile.inc +include ../../Makefile.inc + +#Objects +OBJS = strtol.o atoi.o abs.o exit.o malloc.o rand.o + +#Output +OUTPUT = libc.so + +$(OUTPUT): $(OBJS) + +# Compile the source files +.cc.o: + $(CXX) -Wall ${CFLAGS} -nostdinc -O -I../include -c -o $@ $< + +.cc.s: + $(CXX) -Wall ${CFLAGS} -nostdinc -O -I../include -S -o $@ $< + +.c.o: + $(CC) -Wall ${CFLAGS} -nostdinc -O -I../include -I../../../include -c $< + +.c.s: + $(CC) -Wall ${CFLAGS} -nostdinc -O -I../include -S -o $@ $< + +.S.o: + $(CC) -Wall ${CFLAGS} -nostdinc -c -o $@ $< + +# Clean up the junk +clean: + $(REMOVE) $(OBJS) $(OUTPUT) diff --git a/src/lib/libc_old/stdlib/abs.c b/src/lib/libc_old/stdlib/abs.c new file mode 100644 index 0000000..a008c42 --- /dev/null +++ b/src/lib/libc_old/stdlib/abs.c @@ -0,0 +1,5 @@ +#include + +int abs(int val) { + return(val>0?val:-val); + } diff --git a/src/lib/libc_old/stdlib/atoi.c b/src/lib/libc_old/stdlib/atoi.c new file mode 100644 index 0000000..6f0327b --- /dev/null +++ b/src/lib/libc_old/stdlib/atoi.c @@ -0,0 +1,5 @@ +#include + +int atoi(const char *str) { + return (int)strtol(str, (char **)NULL, 10); + } diff --git a/src/lib/libc_old/stdlib/exit.c b/src/lib/libc_old/stdlib/exit.c new file mode 100644 index 0000000..6d09554 --- /dev/null +++ b/src/lib/libc_old/stdlib/exit.c @@ -0,0 +1,31 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#include + +void exit(int status) { + asm( + "int %0\n" + : : "i" (0x80),"a" (2),"b" (status) + ); + } diff --git a/src/lib/libc_old/stdlib/malloc.c b/src/lib/libc_old/stdlib/malloc.c new file mode 100644 index 0000000..ca564d9 --- /dev/null +++ b/src/lib/libc_old/stdlib/malloc.c @@ -0,0 +1,203 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#include +#include +#include + +struct memDescriptor { + struct memDescriptor *prev; //4 + struct memDescriptor *next; //4 + void *baseAddr; //4 + unsigned long limit; //4 + unsigned char status; //1 + char reserved[15]; //15 + }; + +struct memDescriptor *kernDesc = 0x0; +struct memDescriptor *freeKernDesc = 0x0; +struct memDescriptor *emptyKernDesc = 0x0; + +void insertFreeDesc(struct memDescriptor *freeDesc); + +void initMalloc() { + int i=0; + struct memDescriptor *tmpDesc1 = 0x0; + struct memDescriptor *tmpDesc2 = 0x0; + emptyKernDesc = (struct memDescriptor *)getPage(1); + tmpDesc1 = emptyKernDesc; + tmpDesc1->prev = 0x0; + for (i=1;i<((4096/sizeof(struct memDescriptor)));i++) { + tmpDesc2 = &emptyKernDesc[i]; + tmpDesc2->prev = tmpDesc1; + tmpDesc1->next = tmpDesc2; + tmpDesc1 = tmpDesc2; + } + tmpDesc1->next = 0x0; + //Return + return; + } + +void *getEmptyDesc() { + struct memDescriptor *tmpDesc = emptyKernDesc; + if (tmpDesc != 0x0) { + emptyKernDesc = tmpDesc->next; + emptyKernDesc->prev = 0x0; + tmpDesc->next = 0x0; + tmpDesc->prev = 0x0; + return(tmpDesc); + } + printf("Error Finding Empty Descriptor!\n"); + return(0x0); + } + +void *malloc(uInt len) { + struct memDescriptor *tmpDesc1 = 0x0; + struct memDescriptor *tmpDesc2 = 0x0; + //If Kernel Descriptor Is NULL Initialize Malloc + if (emptyKernDesc == 0x0) { + initMalloc(); + } + len = (len + 15) & 0xFFFFFFF0; + for (tmpDesc1 = freeKernDesc;tmpDesc1;tmpDesc1=tmpDesc1->next) { + if (tmpDesc1->limit >= len) { + tmpDesc1->status = 0x1; + if (tmpDesc1->prev != 0x0) { + tmpDesc1->prev->next = tmpDesc1->next; + tmpDesc1->next->prev = tmpDesc1->prev; + } + else { + freeKernDesc = tmpDesc1->next; + freeKernDesc->prev = 0x0; + } + tmpDesc1->prev = 0x0; + tmpDesc1->next = kernDesc; + kernDesc->prev = tmpDesc1; + kernDesc = tmpDesc1; + if (tmpDesc1->limit > (len + 16)) { + tmpDesc2 = getEmptyDesc(); + tmpDesc2->limit = tmpDesc1->limit - len; + tmpDesc1->limit = len; + tmpDesc2->baseAddr = tmpDesc1->baseAddr + len; + tmpDesc2->status = 0x0; + insertFreeDesc(tmpDesc2); + } + return(tmpDesc1->baseAddr); + } + } + tmpDesc1 = getEmptyDesc(); + if (tmpDesc1 != 0x0) { + tmpDesc1->baseAddr = (struct memDescriptor *)getPage((len+4095)/4096); + tmpDesc1->limit = len; + tmpDesc1->status = 0x1; + tmpDesc1->next = kernDesc; + tmpDesc1->prev = 0x0; + if (kernDesc != 0x0) { + kernDesc->prev = tmpDesc1; + } + kernDesc = tmpDesc1; + if ((len/4096) > 0) { + tmpDesc2 = getEmptyDesc(); + tmpDesc2->status = 0x0; + tmpDesc2->baseAddr = tmpDesc1->baseAddr + tmpDesc1->limit; + tmpDesc2->limit = ((len + 4095)/4096)*4096 - tmpDesc1->limit; + insertFreeDesc(tmpDesc2); + } + /* + printf("[0x"); + printf("%X",tmpDesc1->baseAddr); + printf("]\n"); + */ + return(tmpDesc1->baseAddr); + } + //Return Null If Unable To Malloc + return(0x0); + } + +void free(void *baseAddr) { + long *data = 0x0; + long i = 0x0; + struct memDescriptor *tmpDesc1 = 0x0; + struct memDescriptor *tmpDesc2 = 0x0; + + if (baseAddr == 0x0) { + return; + } + for (tmpDesc1=kernDesc;tmpDesc1;tmpDesc1=tmpDesc1->next) { + if (tmpDesc1->baseAddr == baseAddr) { + tmpDesc1->status = 0x0; + if (tmpDesc1->prev) { + tmpDesc2 = tmpDesc1->prev; + tmpDesc2->next = tmpDesc1->next; + } + if (tmpDesc1->next) { + tmpDesc2 = tmpDesc1->next; + if (tmpDesc2) { + tmpDesc2->prev = tmpDesc1->prev; + } + } + if ((kernDesc == tmpDesc1) && (tmpDesc1->prev)) { + kernDesc = tmpDesc1->prev; + } + else { + kernDesc = tmpDesc1->next; + } + insertFreeDesc(tmpDesc1); + data = baseAddr; + for (i=0;i < (tmpDesc1->limit/4);i++) { + data[i] = 0x0; + } + return; + } + } + printf("Error Freeing User Descriptor! [0x%X]\n",(unsigned int) baseAddr); + return; + } + +void insertFreeDesc(struct memDescriptor *freeDesc) { + struct memDescriptor *tmpDesc; + freeDesc->status = 0x0; + if (freeKernDesc != 0x0) { + for (tmpDesc=freeKernDesc;tmpDesc;tmpDesc=tmpDesc->next) { + if ((freeDesc->limit >= tmpDesc->limit) && (!tmpDesc->next)) { + tmpDesc->next = freeDesc; + freeDesc->prev = tmpDesc; + freeDesc->next = 0x0; + return; + } + else if ((freeDesc->limit >= tmpDesc->limit) && (freeDesc->limit <= tmpDesc->next->limit)) { + freeDesc->next = tmpDesc->next; + freeDesc->prev = tmpDesc; + tmpDesc->next->prev = freeDesc; + tmpDesc->next = freeDesc; + return; + } + } + } + else { + freeDesc->prev = 0x0; + freeDesc->next = 0x0; + freeKernDesc = freeDesc; + } + return; + } \ No newline at end of file diff --git a/src/lib/libc_old/stdlib/rand.c b/src/lib/libc_old/stdlib/rand.c new file mode 100644 index 0000000..bc37554 --- /dev/null +++ b/src/lib/libc_old/stdlib/rand.c @@ -0,0 +1,65 @@ + /************************************************************************************** + 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: + +**************************************************************************************/ + +static long holdrand = 1L; + +/*** +*void srand(seed) - seed the random number generator +* +*Purpose: +* Seeds the random number generator with the int given. Adapted from the +* BASIC random number generator. +* +*Entry: +* unsigned seed - seed to seed rand # generator with +* +*Exit: +* None. +* +*Exceptions: +* +**************************************************************************/ + +void srand(unsigned int seed) { + holdrand = (long)seed; +} + +/*** +*int rand() - returns a random number +* +*Purpose: +* returns a pseudo-random number 0 through 32767. +* +*Entry: +* None. +* +*Exit: +* Returns a pseudo-random number 0 through 32767. +* +*Exceptions: +* +*******************************************************************************/ + +int rand(void) { + return(((holdrand = holdrand * 214013L + 2531011L) >> 16) & 0x7fff); +} \ No newline at end of file diff --git a/src/lib/libc_old/stdlib/strtol.c b/src/lib/libc_old/stdlib/strtol.c new file mode 100644 index 0000000..75caf0e --- /dev/null +++ b/src/lib/libc_old/stdlib/strtol.c @@ -0,0 +1,96 @@ +#include +#include +#include +#include + + +long +strtol(const char * __restrict nptr, char ** __restrict endptr, int base) +{ + const char *s; + unsigned long acc; + char c; + unsigned long cutoff; + int neg, any, cutlim; + + /* + * Skip white space and pick up leading +/- sign if any. + * If base is 0, allow 0x for hex and 0 for octal, else + * assume decimal; if base is already 16, allow 0x. + */ + s = nptr; + do { + c = *s++; + } while (isspace((unsigned char)c)); + if (c == '-') { + neg = 1; + c = *s++; + } else { + neg = 0; + if (c == '+') + c = *s++; + } + if ((base == 0 || base == 16) && + c == '0' && (*s == 'x' || *s == 'X')) { + c = s[1]; + s += 2; + base = 16; + } + if (base == 0) + base = c == '0' ? 8 : 10; + acc = any = 0; + if (base < 2 || base > 36) + goto noconv; + + /* + * Compute the cutoff value between legal numbers and illegal + * numbers. That is the largest legal value, divided by the + * base. An input number that is greater than this value, if + * followed by a legal input character, is too big. One that + * is equal to this value may be valid or not; the limit + * between valid and invalid numbers is then based on the last + * digit. For instance, if the range for longs is + * [-2147483648..2147483647] and the input base is 10, + * cutoff will be set to 214748364 and cutlim to either + * 7 (neg==0) or 8 (neg==1), meaning that if we have accumulated + * a value > 214748364, or equal but the next digit is > 7 (or 8), + * the number is too big, and we will return a range error. + * + * Set 'any' if any `digits' consumed; make it negative to indicate + * overflow. + */ + cutoff = neg ? (unsigned long)-(LONG_MIN + LONG_MAX) + LONG_MAX + : LONG_MAX; + cutlim = cutoff % base; + cutoff /= base; + for ( ; ; c = *s++) { + if (c >= '0' && c <= '9') + c -= '0'; + else if (c >= 'A' && c <= 'Z') + c -= 'A' - 10; + else if (c >= 'a' && c <= 'z') + c -= '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 = (char *)(any ? s - 1 : nptr); + return (acc); +} diff --git a/src/lib/libc_old/string/Makefile b/src/lib/libc_old/string/Makefile new file mode 100644 index 0000000..5843e57 --- /dev/null +++ b/src/lib/libc_old/string/Makefile @@ -0,0 +1,33 @@ +# $Id$ +# The System Makefile (C) 2002 The UbixOS Project + +# Include Global 'Source' Options +include ../../../Makefile.inc +include ../../Makefile.inc +#Objects +OBJS = strrchr.o strlcat.o strlcpy.o strerror.o strtok.o memcpy.o memset.o memcmp.o strlen.o strcmp.o + +#Output +OUTPUT = libc.so + +$(OUTPUT): $(OBJS) + +# Compile the source files +.cc.o: + $(CXX) $(CFLAGS) -Wall -nostdinc -O -I../include -c -o $@ $< + +.cc.s: + $(CXX) $(CFLAGS) -Wall -nostdinc -O -I../include -S -o $@ $< + +.c.o: + $(CC) $(CFLAGS) -Wall -nostdinc -O -I../include -I../../../include -c $< + +.c.s: + $(CC) $(CFLAGS) -Wall -nostdinc -O -I../include -S -o $@ $< + +.S.o: + $(CC) $(CFLAGS) -Wall -nostdinc -c -o $@ $< + +# Clean up the junk +clean: + $(REMOVE) $(OBJS) $(OUTPUT) diff --git a/src/lib/libc_old/string/memcmp.c b/src/lib/libc_old/string/memcmp.c new file mode 100644 index 0000000..266e2c2 --- /dev/null +++ b/src/lib/libc_old/string/memcmp.c @@ -0,0 +1,28 @@ +#include +#include + +int memcmp(const void * dst, const void * src, size_t length) +{ + size_t x = length >> 2; + size_t y = length & 0xf; + size_t i; + + for (i = 0; i < x; i++) + { + if (((unsigned long *)dst)[i] > ((unsigned long *)src)[i]) + return 1; + if (((unsigned long *)dst)[i] < ((unsigned long *)src)[i]) + return -1; + } + + for (i = 0; i < y; i++) + { + if (((char *) dst)[length-y+i] > ((char *) src)[length-y+i]) + return 1; + if (((char *) dst)[length-y+i] < ((char *) src)[length-y+i]) + return -1; + } + + return 0; +} + diff --git a/src/lib/libc_old/string/memcpy.c b/src/lib/libc_old/string/memcpy.c new file mode 100644 index 0000000..e57ba1b --- /dev/null +++ b/src/lib/libc_old/string/memcpy.c @@ -0,0 +1,18 @@ +#include +#include + +void * memcpy(void * dst, const void * src, size_t length) +{ + size_t x = length >> 2; + size_t y = length & 0xf; + size_t i; + + for (i = 0; i < x; i++) + ((unsigned long *)dst)[i] = ((unsigned long *)src)[i]; + + for (i = 0; i < y; i++) + ((char *) dst)[length-y+i] = ((char *) src)[length-y+i]; + + return dst; +} + diff --git a/src/lib/libc_old/string/memset.c b/src/lib/libc_old/string/memset.c new file mode 100644 index 0000000..1acfbd6 --- /dev/null +++ b/src/lib/libc_old/string/memset.c @@ -0,0 +1,20 @@ +#include +#include + +void * memset(void * dst, int c, size_t length) +{ + size_t x = length >> 2; + size_t y = length & 0xf; + size_t i; + + unsigned int newC = (c << 24) | (c << 16) | (c << 8) | (c); + + for (i = 0; i < x; i++) + ((unsigned long *)dst)[i] = newC; + + for (i = 0; i < y; i++) + ((char *) dst)[length-y+i] = c; + + return dst; +} + diff --git a/src/lib/libc_old/string/rindex.c b/src/lib/libc_old/string/rindex.c new file mode 100644 index 0000000..697b69a --- /dev/null +++ b/src/lib/libc_old/string/rindex.c @@ -0,0 +1,66 @@ +/* + * 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[] = "@(#)rindex.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/string/rindex.c,v 1.7 2003/12/18 07:44:53 jkh Exp $"); + +#include + +#ifdef STRRCHR +#include + +char * +strrchr +#else +#include + +char * +rindex +#endif +(const char *p, int ch) +{ + char *save; + char c; + + c = ch; + for (save = NULL;; ++p) { + if (*p == c) + save = (char *)p; + if (*p == '\0') + return (save); + } + /* NOTREACHED */ +} diff --git a/src/lib/libc_old/string/strcmp.c b/src/lib/libc_old/string/strcmp.c new file mode 100644 index 0000000..334afba --- /dev/null +++ b/src/lib/libc_old/string/strcmp.c @@ -0,0 +1,49 @@ +/*- + * Copyright (c) 1990, 1993 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * Chris Torek. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#include +#include + +/* + * Compare strings. + */ + +int strcmp(const char *s1, const char *s2) { + while (*s1 == *s2++) + if (*s1++ == 0) + return (0); + return (*(const unsigned char *)s1 - *(const unsigned char *)(s2 - 1)); +} diff --git a/src/lib/libc_old/string/strcpy.c b/src/lib/libc_old/string/strcpy.c new file mode 100644 index 0000000..1a9d0cd --- /dev/null +++ b/src/lib/libc_old/string/strcpy.c @@ -0,0 +1,9 @@ +#include"string.h" +char*strcpy(char*restrict dst,const char*restrict src) +{ + char*ret=dst; + + do *dst++=*src; while(*src++); + + return ret; +} diff --git a/src/lib/libc_old/string/strerror.c b/src/lib/libc_old/string/strerror.c new file mode 100644 index 0000000..b1c4913 --- /dev/null +++ b/src/lib/libc_old/string/strerror.c @@ -0,0 +1,99 @@ +/*- + * 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[] = "@(#)strerror.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/string/strerror.c,v 1.13 2003/05/01 19:03:14 nectar Exp $"); + +#include +#include +#include + +#define UPREFIX "Unknown error: " + +/* + * Define a buffer size big enough to describe a 64-bit signed integer + * converted to ASCII decimal (19 bytes), with an optional leading sign + * (1 byte); finally, we get the prefix and a trailing NUL from UPREFIX. + */ +#define EBUFSIZE (20 + sizeof(UPREFIX)) + +/* + * Doing this by hand instead of linking with stdio(3) avoids bloat for + * statically linked binaries. + */ +static void +errstr(int num, char *buf, size_t len) +{ + char *t; + unsigned int uerr; + char tmp[EBUFSIZE]; + + t = tmp + sizeof(tmp); + *--t = '\0'; + uerr = (num >= 0) ? num : -num; + do { + *--t = "0123456789"[uerr % 10]; + } while (uerr /= 10); + if (num < 0) + *--t = '-'; + strlcpy(buf, UPREFIX, len); + strlcat(buf, t, len); +} + +int +strerror_r(int errnum, char *strerrbuf, size_t buflen) +{ + + if (errnum < 1 || errnum >= sys_nerr) { + errstr(errnum, strerrbuf, buflen); + return (EINVAL); + } + if (strlcpy(strerrbuf, sys_errlist[errnum], buflen) >= buflen) + return (ERANGE); + return (0); +} + +char * +strerror(int num) +{ + static char ebuf[EBUFSIZE]; + + if (num > 0 && num < sys_nerr) + return ((char *)sys_errlist[num]); + errno = EINVAL; + errstr(num, ebuf, sizeof(ebuf)); + return (ebuf); +} diff --git a/src/lib/libc_old/string/strlcat.c b/src/lib/libc_old/string/strlcat.c new file mode 100644 index 0000000..19924e5 --- /dev/null +++ b/src/lib/libc_old/string/strlcat.c @@ -0,0 +1,75 @@ +/* $OpenBSD: strlcat.c,v 1.2 1999/06/17 16:28:58 millert Exp $ */ + +/* + * Copyright (c) 1998 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 char *rcsid = "$OpenBSD: strlcat.c,v 1.2 1999/06/17 16:28:58 millert Exp $"); +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/string/strlcat.c,v 1.9 2003/05/01 19:03:14 nectar Exp $"); + +#include +#include + +/* + * Appends src to string dst of size siz (unlike strncat, siz is the + * full size of dst, not space left). At most siz-1 characters + * will be copied. Always NUL terminates (unless siz <= strlen(dst)). + * Returns strlen(src) + MIN(siz, strlen(initial dst)). + * If retval >= siz, truncation occurred. + */ +size_t +strlcat(dst, src, siz) + char *dst; + const char *src; + size_t siz; +{ + char *d = dst; + const char *s = src; + size_t n = siz; + size_t dlen; + + /* Find the end of dst and adjust bytes left but don't go past end */ + while (n-- != 0 && *d != '\0') + d++; + dlen = d - dst; + n = siz - dlen; + + if (n == 0) + return(dlen + strlen(s)); + while (*s != '\0') { + if (n != 1) { + *d++ = *s; + n--; + } + s++; + } + *d = '\0'; + + return(dlen + (s - src)); /* count does not include NUL */ +} diff --git a/src/lib/libc_old/string/strlcpy.c b/src/lib/libc_old/string/strlcpy.c new file mode 100644 index 0000000..eedb6a9 --- /dev/null +++ b/src/lib/libc_old/string/strlcpy.c @@ -0,0 +1,70 @@ +/* $OpenBSD: strlcpy.c,v 1.4 1999/05/01 18:56:41 millert Exp $ */ + +/* + * Copyright (c) 1998 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 char *rcsid = "$OpenBSD: strlcpy.c,v 1.4 1999/05/01 18:56:41 millert Exp $"); +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: src/lib/libc/string/strlcpy.c,v 1.7 2003/05/01 19:03:14 nectar Exp $"); + +#include +#include + +/* + * Copy src to string dst of size siz. At most siz-1 characters + * will be copied. Always NUL terminates (unless siz == 0). + * Returns strlen(src); if retval >= siz, truncation occurred. + */ +size_t strlcpy(dst, src, siz) + char *dst; + const char *src; + size_t siz; +{ + char *d = dst; + const char *s = src; + size_t n = siz; + + /* Copy as many bytes as will fit */ + if (n != 0 && --n != 0) { + do { + if ((*d++ = *s++) == 0) + break; + } while (--n != 0); + } + + /* Not enough room in dst, add NUL and traverse rest of src */ + if (n == 0) { + if (siz != 0) + *d = '\0'; /* NUL-terminate dst */ + while (*s++) + ; + } + + return(s - src - 1); /* count does not include NUL */ +} diff --git a/src/lib/libc_old/string/strlen.c b/src/lib/libc_old/string/strlen.c new file mode 100644 index 0000000..4febfa7 --- /dev/null +++ b/src/lib/libc_old/string/strlen.c @@ -0,0 +1,16 @@ +#include +#include + +int strlen(const char * string) +{ + int i = 0; + + while (1) + { + if (string[i] == '\0') + return i; + i++; + } + + return 0; +} diff --git a/src/lib/libc_old/string/strncpy.c b/src/lib/libc_old/string/strncpy.c new file mode 100644 index 0000000..4e172fb --- /dev/null +++ b/src/lib/libc_old/string/strncpy.c @@ -0,0 +1,13 @@ +#include"string.h" +char*strncpy(char*restrict dst,const char*restrict src,size_t n) +{ + register size_t i=0; + char*ret=dst; + + do *dst++=*src; while(*src++ && ++i +__FBSDID("$FreeBSD: src/lib/libc/string/strrchr.c,v 1.2 2002/03/22 21:53:19 obrien Exp $"); + +#define STRRCHR +#include "rindex.c" diff --git a/src/lib/libc_old/string/strtok.c b/src/lib/libc_old/string/strtok.c new file mode 100644 index 0000000..89a1a21 --- /dev/null +++ b/src/lib/libc_old/string/strtok.c @@ -0,0 +1,71 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#include +#include + +char *strtok_r(char *s, const char *delim, char **last) { + char *spanp; + int c, sc; + char *tok; + + if ((s == NULL) && ((s = *last) == NULL)) { + return(NULL); + } + +cont: + c = *s++; + for (spanp = (char *)delim; (sc = *spanp++) != 0; ) { + if (c == sc) { + goto cont; + } + } + if (c == 0) { + *last = NULL; + return(NULL); + } + tok = s - 1; + + for (;;) { + c = *s++; + spanp = (char *)delim; + do { + if ((sc = *spanp++) == c) { + if (c == 0) { + s = NULL; + } + else { + char *w = s - 1; + *w = '\0'; + } + *last = s; + return(tok); + } + } while (sc != 0); + } + } + +char *strtok(char *s, const char *delim) { + static char *last; + return (strtok_r(s, delim, &last)); + } \ No newline at end of file diff --git a/src/lib/libc_old/sys/Makefile b/src/lib/libc_old/sys/Makefile new file mode 100644 index 0000000..079d52f --- /dev/null +++ b/src/lib/libc_old/sys/Makefile @@ -0,0 +1,34 @@ +# $Id$ +# The System Makefile (C) 2002 The UbixOS Project + +# Include Global 'Source' Options +include ../../../Makefile.inc +include ../../Makefile.inc + +#Objects +OBJS = startsde.o mmap.o error.o getuptime.o gettime.o getdrives.o setuid.o setgid.o getuid.o getgid.o exec.o getpid.o fork.o pidstatus.o getpage.o sched.o + +#Output +OUTPUT = sys.so + +$(OUTPUT): $(OBJS) + +# Compile the source files +.cc.o: + $(CXX) ${CFLAGS} -Wall -nostdinc -O -I../include -c -o $@ $< + +.cc.s: + $(CXX) ${CFLAGS} -Wall -nostdinc -O -I../include -S -o $@ $< + +.c.o: + $(CC) ${CFLAGS} -Wall -nostdinc -O -I../include -I../../../include -c $< + +.c.s: + $(CC) ${CFLAGS} -Wall -nostdinc -O -I../include -S -o $@ $< + +.S.o: + $(CC) ${CFLAGS} -Wall -nostdinc -c -o $@ $< + +# Clean up the junk +clean: + $(REMOVE) $(OBJS) $(OUTPUT) diff --git a/src/lib/libc_old/sys/error.c b/src/lib/libc_old/sys/error.c new file mode 100644 index 0000000..d4489c8 --- /dev/null +++ b/src/lib/libc_old/sys/error.c @@ -0,0 +1,3 @@ +int * __error(void) { + return(0x0); + } diff --git a/src/lib/libc_old/sys/exec.c b/src/lib/libc_old/sys/exec.c new file mode 100644 index 0000000..5e1e933 --- /dev/null +++ b/src/lib/libc_old/sys/exec.c @@ -0,0 +1,31 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +int exec(char *file,int argc,char **argv) { + int status = 0x1; + asm( + "int %0 \n" + : : "i" (0x80),"a" (3),"b" (file),"c" (argc),"d" (argv) + ); + return(status); + } diff --git a/src/lib/libc_old/sys/fork.c b/src/lib/libc_old/sys/fork.c new file mode 100644 index 0000000..5b1b6c5 --- /dev/null +++ b/src/lib/libc_old/sys/fork.c @@ -0,0 +1,47 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#include +#include + +pid_t fork() { + pid_t pid = 0x0; + asm( + "pushl %%eax\n" + "pushl %%ecx\n" + "movl $4,%%eax\n" + "push %%ss\n" + "movl %%esp,%%ecx\n" + "sub $4,%%ecx\n" + "pushl %%ecx\n" + "int $0x80 \n" + "popl %%esp\n" + "pop %%ax\n" + "popl %%ecx\n" + "popl %%eax\n" + : + : "b" (&pid) + ); + return(pid); + } + diff --git a/src/lib/libc_old/sys/getdrives.c b/src/lib/libc_old/sys/getdrives.c new file mode 100644 index 0000000..76ed8e4 --- /dev/null +++ b/src/lib/libc_old/sys/getdrives.c @@ -0,0 +1,11 @@ +#include + + +void *getDrives() { + uInt32 ptr = 0x0; + asm( + "int %0\n" + : : "i" (0x80),"a" (45),"b" (&ptr) + ); + return((void *)ptr); + } \ No newline at end of file diff --git a/src/lib/libc_old/sys/getgid.c b/src/lib/libc_old/sys/getgid.c new file mode 100644 index 0000000..c37c63c --- /dev/null +++ b/src/lib/libc_old/sys/getgid.c @@ -0,0 +1,33 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#include + +int getgid(void) { + int gid = 0x0; + asm( + "int %0\n" + : : "i" (0x80),"a" (32),"b" (&gid) + ); + return(gid); + } \ No newline at end of file diff --git a/src/lib/libc_old/sys/getpage.c b/src/lib/libc_old/sys/getpage.c new file mode 100644 index 0000000..73cdae0 --- /dev/null +++ b/src/lib/libc_old/sys/getpage.c @@ -0,0 +1,31 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +void *getPage(int count) { + long pageAddr = 0x0; + asm( + "int %0\n" + : : "i" (0x80),"a" (7),"b" (&pageAddr),"c" (count) + ); + return((void *)pageAddr); + } diff --git a/src/lib/libc_old/sys/getpid.c b/src/lib/libc_old/sys/getpid.c new file mode 100644 index 0000000..0bbfbbd --- /dev/null +++ b/src/lib/libc_old/sys/getpid.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$ + +**************************************************************************************/ + +#include + +int getpid(void) { + int pid = 0x0; + asm( + "int %0\n" + : : "i" (0x80),"a" (1),"b" (&pid) + ); + return(pid); + } + diff --git a/src/lib/libc_old/sys/gettime.c b/src/lib/libc_old/sys/gettime.c new file mode 100644 index 0000000..8a753bc --- /dev/null +++ b/src/lib/libc_old/sys/gettime.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$ + +**************************************************************************************/ + +#include + +int gettime(void) { + int time = 0x0; + asm( + "int %0\n" + : : "i" (0x80),"a" (47),"b" (&time) + ); + return(time); + } + diff --git a/src/lib/libc_old/sys/getuid.c b/src/lib/libc_old/sys/getuid.c new file mode 100644 index 0000000..6153b64 --- /dev/null +++ b/src/lib/libc_old/sys/getuid.c @@ -0,0 +1,33 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#include + +int getuid(void) { + int uid = 0x0; + asm( + "int %0\n" + : : "i" (0x80),"a" (31),"b" (&uid) + ); + return(uid); + } \ No newline at end of file diff --git a/src/lib/libc_old/sys/getuptime.c b/src/lib/libc_old/sys/getuptime.c new file mode 100644 index 0000000..bf536cf --- /dev/null +++ b/src/lib/libc_old/sys/getuptime.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$ + +**************************************************************************************/ + +#include + +int getuptime(void) { + int uptime = 0x0; + asm( + "int %0\n" + : : "i" (0x80),"a" (46),"b" (&uptime) + ); + return(uptime); + } + diff --git a/src/lib/libc_old/sys/mmap.c b/src/lib/libc_old/sys/mmap.c new file mode 100644 index 0000000..a3fb470 --- /dev/null +++ b/src/lib/libc_old/sys/mmap.c @@ -0,0 +1,43 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + + +#include + +void *mmap(void *addr, size_t len, int prot, int flags, int fd, off_t offset) { +/* + asm( + "pushl %%eax \n" + "movl $4,%%eax\n" + "int $0x69 \n" + "popl %%eax \n" + ); +*/ + + return(0x0); + } + +/*** + END + ***/ + diff --git a/src/lib/libc_old/sys/pidstatus.c b/src/lib/libc_old/sys/pidstatus.c new file mode 100644 index 0000000..acbb836 --- /dev/null +++ b/src/lib/libc_old/sys/pidstatus.c @@ -0,0 +1,33 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#include + +int pidStatus(int pid) { + int status = 0x0; + asm( + "int %0\n" + : : "i" (0x80),"a" (6),"b" (pid),"c" (&status) + ); + return(status); + } diff --git a/src/lib/libc_old/sys/sched.c b/src/lib/libc_old/sys/sched.c new file mode 100644 index 0000000..7e53359 --- /dev/null +++ b/src/lib/libc_old/sys/sched.c @@ -0,0 +1,13 @@ + +#include + +int sched_yield(void) +{ + int return_val = 0; + asm( + "int %0\n" + : : "i" (0x80),"a" (11) + ); + return return_val; +} + diff --git a/src/lib/libc_old/sys/setgid.c b/src/lib/libc_old/sys/setgid.c new file mode 100644 index 0000000..6014b59 --- /dev/null +++ b/src/lib/libc_old/sys/setgid.c @@ -0,0 +1,33 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#include + +int setgid(int gid) { + int status = 0x0; + asm( + "int %0\n" + : : "i" (0x80),"a" (34),"b" (gid),"c" (&status) + ); + return(status); + } \ No newline at end of file diff --git a/src/lib/libc_old/sys/setuid.c b/src/lib/libc_old/sys/setuid.c new file mode 100644 index 0000000..1fe8c07 --- /dev/null +++ b/src/lib/libc_old/sys/setuid.c @@ -0,0 +1,33 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#include + +int setuid(int uid) { + int status = 0x0; + asm( + "int %0\n" + : : "i" (0x80),"a" (33),"b" (uid),"c" (&status) + ); + return(status); + } \ No newline at end of file diff --git a/src/lib/libc_old/sys/startsde.c b/src/lib/libc_old/sys/startsde.c new file mode 100644 index 0000000..dc922e9 --- /dev/null +++ b/src/lib/libc_old/sys/startsde.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$ + +**************************************************************************************/ + +#include + +int startSDE(void) { + int time = 0x0; + asm( + "int %0\n" + : : "i" (0x80),"a" (48) + ); + return(time); + } + diff --git a/src/lib/libcpp/Makefile b/src/lib/libcpp/Makefile new file mode 100644 index 0000000..2d97ece --- /dev/null +++ b/src/lib/libcpp/Makefile @@ -0,0 +1,32 @@ +# (C) 2002 The UbixOS Project +# $Id$ + +# Include Global 'Source' Options +include ../../Makefile.inc +include ../Makefile.inc +# Objects +OBJS = libcpp.o + +#Include + +INCLUDE = -I./include -I../libc/include + +all: $(OBJS) + +# Compile Types +.cpp.o: + $(CXX) ${CFLAGS} -Wall -DNOBOOL -fno-rtti -fno-exceptions -g -c $(INCLUDE) -o $@ $< +.cc.o: + $(CXX) ${CFLAGS} -Wall -DNOBOOL -fno-builtin -fno-rtti -fno-exceptions -fomit-frame-pointer -O $(INCLUDE) -c -o $@ $< +.cc.s: + $(CXX) ${CFLAGS} -Wall -fomit-frame-pointer -O $(INCLUDE) -S -o $@ $< +.c.o: + $(CC) ${CFLAGS} -Wall -fomit-frame-pointer -O $(INCLUDE) -c -o $@ $< +.c.s: + $(CC) ${CFLAGS} -Wall -fomit-frame-pointer -O $(INCLUDE) -S -o $@ $< +.S.o: + $(CC) ${CFLAGS} -Wall -fomit-frame-pointer -c -o $@ $< + +# Clean up the junk +clean: + $(REMOVE) $(OBJS) diff --git a/src/lib/libcpp/include/libcpp.h b/src/lib/libcpp/include/libcpp.h new file mode 100644 index 0000000..78f02c8 --- /dev/null +++ b/src/lib/libcpp/include/libcpp.h @@ -0,0 +1,9 @@ +#ifndef __LIBCPP_H +#define __LIBCPP_H + +void * operator new(unsigned size); +void operator delete(void * ptr); +void * operator new[](unsigned size); +void operator delete[](void * ptr); + +#endif diff --git a/src/lib/libcpp/libcpp.cc b/src/lib/libcpp/libcpp.cc new file mode 100644 index 0000000..b5084a9 --- /dev/null +++ b/src/lib/libcpp/libcpp.cc @@ -0,0 +1,33 @@ +extern "C" +{ +#include +void __pure_virtual() { while(1); } +void __cxa_pure_virtual() { while(1); } +} + +#include + +void * operator new[](unsigned size) +{ + return malloc(size); +} + +void operator delete[](void * ptr) +{ + free(ptr); + + return; +} + +void * operator new(unsigned size) +{ + return malloc(size); +} + +void operator delete(void * ptr) +{ + free(ptr); + + return; +} + diff --git a/src/lib/objgfx40/1.DPF b/src/lib/objgfx40/1.DPF new file mode 100644 index 0000000..a02b207 --- /dev/null +++ b/src/lib/objgfx40/1.DPF Binary files differ diff --git a/src/lib/objgfx40/6X6.DPF b/src/lib/objgfx40/6X6.DPF new file mode 100644 index 0000000..bf94b27 --- /dev/null +++ b/src/lib/objgfx40/6X6.DPF Binary files differ diff --git a/src/lib/objgfx40/BLOCK.DPF b/src/lib/objgfx40/BLOCK.DPF new file mode 100644 index 0000000..12f39f7 --- /dev/null +++ b/src/lib/objgfx40/BLOCK.DPF Binary files differ diff --git a/src/lib/objgfx40/BOLD.DPF b/src/lib/objgfx40/BOLD.DPF new file mode 100644 index 0000000..20800b5 --- /dev/null +++ b/src/lib/objgfx40/BOLD.DPF Binary files differ diff --git a/src/lib/objgfx40/Makefile b/src/lib/objgfx40/Makefile new file mode 100644 index 0000000..dc4c1d2 --- /dev/null +++ b/src/lib/objgfx40/Makefile @@ -0,0 +1,40 @@ +# $Id$ +# Kernel Makefile (C) 2002 The UbixOS Project + +include ../../Makefile.inc +include ../Makefile.inc + +#Delete Program +REMOVE = rm -f + +#Objects +OBJS = vWidget.o vWindow.o objgfx40.o ogFont.o ogSprite.o ogBlit.o ogPixCon.o + +#Include +INCLUDE = -I./ -I../../lib/libc/include -I../../lib/libcpp/include + +#Output +OUTPUT = objgfx40.so + +$(OUTPUT): $(OBJS) + $(CC) -nostdlib -shared -Wl,-soname,$(OUTPUT) -o $(OUTPUT) $(OBJS) + +# Compile the source files +.cpp.o: + $(CXX) -Wall -g -fno-builtin -fno-rtti -fno-exceptions -DNOBOOL $(INCLUDE) -c -o $@ $< + +.cc.o: + $(CXX) -Wall -fomit-frame-pointer -O -nobuilting -I../../lib/libc/include -I./include -S -o $@ $< + +.c.o: + $(CC) -Wall -O -I../../lib/libc/include -c -o $@ $< + +.c.s: + $(CC) -Wall -fomit-frame-pointer -O -I../../lib/libc/include -S -o $@ $< + +.S.o: + $(CC) -Wall -fomit-frame-pointer -c -o $@ $< + +# Clean up the junk +clean: + $(REMOVE) $(OBJS) $(BINARY) $(OUTPUT) *.core diff --git a/src/lib/objgfx40/OLDENG.DPF b/src/lib/objgfx40/OLDENG.DPF new file mode 100644 index 0000000..e542aca --- /dev/null +++ b/src/lib/objgfx40/OLDENG.DPF Binary files differ diff --git a/src/lib/objgfx40/PACMAN.DPF b/src/lib/objgfx40/PACMAN.DPF new file mode 100644 index 0000000..4db8522 --- /dev/null +++ b/src/lib/objgfx40/PACMAN.DPF Binary files differ diff --git a/src/lib/objgfx40/ROM8X8.DPF b/src/lib/objgfx40/ROM8X8.DPF new file mode 100644 index 0000000..b65b08d --- /dev/null +++ b/src/lib/objgfx40/ROM8X8.DPF Binary files differ diff --git a/src/lib/objgfx40/ROMAN1.DPF b/src/lib/objgfx40/ROMAN1.DPF new file mode 100755 index 0000000..19dc135 --- /dev/null +++ b/src/lib/objgfx40/ROMAN1.DPF Binary files differ diff --git a/src/lib/objgfx40/SCRIPT.DPF b/src/lib/objgfx40/SCRIPT.DPF new file mode 100755 index 0000000..8adf710 --- /dev/null +++ b/src/lib/objgfx40/SCRIPT.DPF Binary files differ diff --git a/src/lib/objgfx40/include/ogDisplay_VESA.h b/src/lib/objgfx40/include/ogDisplay_VESA.h new file mode 100644 index 0000000..bf713eb --- /dev/null +++ b/src/lib/objgfx40/include/ogDisplay_VESA.h @@ -0,0 +1,100 @@ +#ifndef OGDISPLAY_VESA_H +#define OGDISPLAY_VESA_H + +#include "objgfx40.h" + +struct ogModeInfo { + uInt16 modeAttributes __attribute__((packed)); + uInt8 windowAFlags __attribute__((packed)); + uInt8 windowBFlags __attribute__((packed)); + uInt16 granularity __attribute__((packed)); + uInt16 windowSize __attribute__((packed)); + uInt16 windowASeg __attribute__((packed)); + uInt16 windowBSeg __attribute__((packed)); + void* bankSwitch __attribute__((packed)); + uInt16 bytesPerLine __attribute__((packed)); + uInt16 xRes __attribute__((packed)); + uInt16 yRes __attribute__((packed)); + uInt8 charWidth __attribute__((packed)); + uInt8 charHeight __attribute__((packed)); + uInt8 numBitPlanes __attribute__((packed)); + uInt8 bitsPerPixel __attribute__((packed)); + uInt8 numberOfBanks __attribute__((packed)); + uInt8 memoryModel __attribute__((packed)); + uInt8 bankSize __attribute__((packed)); + uInt8 numOfImagePages __attribute__((packed)); + uInt8 reserved __attribute__((packed)); + // Direct colour fields (required for Direct/6 and YUV/7 memory models + uInt8 redMaskSize __attribute__((packed)); + uInt8 redFieldPosition __attribute__((packed)); + uInt8 greenMaskSize __attribute__((packed)); + uInt8 greenFieldPosition __attribute__((packed)); + uInt8 blueMaskSize __attribute__((packed)); + uInt8 blueFieldPosition __attribute__((packed)); + uInt8 alphaMaskSize __attribute__((packed)); + uInt8 alphaFieldPosition __attribute__((packed)); + uInt8 directColourMode __attribute__((packed)); + // VESA 2.0 specific fields + uInt32 physBasePtr __attribute__((packed)); + void* offScreenMemOffset __attribute__((packed)); + uInt16 offScreenMemSize __attribute__((packed)); + uInt8 paddington[461] __attribute__((packed)); +}; + +struct ogVESAInfo { + char VBESignature[4] __attribute__((packed)); + uInt8 minVersion __attribute__((packed)); + uInt8 majVersion __attribute__((packed)); + uInt32 OEMStringPtr __attribute__((packed)); + uInt32 capabilities __attribute__((packed)); + uInt32 videoModePtr __attribute__((packed)); + uInt16 totalMemory __attribute__((packed)); + // VESA 2.0 specific fields + uInt16 OEMSoftwareRev __attribute__((packed)); + uInt32 OEMVendorNamePtr __attribute__((packed)); + uInt32 OEMProductNamePtr __attribute__((packed)); + uInt32 OEMProductRevPtr __attribute__((packed)); + uInt8 paddington[474] __attribute__((packed)); +}; + +class ogDisplay_VESA : public ogSurface { + protected: + void * pages[2]; + uInt32 activePage; + uInt32 visualPage; + uInt16 screenSelector; + ogVESAInfo * VESAInfo; + ogModeInfo * modeInfo; + bool inGraphics; + uInt16 FindMode(uInt32, uInt32, uInt32); + void GetModeInfo(uInt16); + void GetVESAInfo(void); + void SetMode(uInt16); + virtual uInt32 RawGetPixel(uInt32, uInt32); + virtual void RawSetPixel(uInt32, uInt32, uInt32); + virtual void RawSetPixel(uInt32, uInt32, uInt8, uInt8, uInt8, uInt8); + void SetPal(void); + public: + ogDisplay_VESA(void); + virtual bool Alias(ogSurface&, uInt32, uInt32, uInt32, uInt32); + virtual bool Avail(void); + virtual void Clear(uInt32); + virtual bool Clone(ogSurface&); + virtual void CopyLineTo(uInt32, uInt32, const void *, uInt32); + virtual void CopyLineFrom(uInt32, uInt32, void *, uInt32); + virtual void CopyPalette(ogSurface&); + virtual bool Create(uInt32, uInt32, ogPixelFmt); + virtual uInt32 GetPixel(int32, int32); + virtual void * GetPtr(uInt32, uInt32); + virtual void HLine(int32, int32, int32, uInt32); + virtual bool LoadPalette(const char *); + virtual void SetPalette(const ogRGBA8[]); + virtual void SetPixel(int32, int32, uInt32); + virtual void SetPalette(uInt8, uInt8, uInt8, uInt8); + virtual void SetPalette(uInt8, uInt8, uInt8, uInt8, uInt8); + virtual void VFlip(void); + virtual void VLine(int32, int32, int32, uInt32); + virtual ~ogDisplay_VESA(void); +}; // ogDisplay_VESA + +#endif diff --git a/src/lib/objgfx40/main.cpp b/src/lib/objgfx40/main.cpp new file mode 100644 index 0000000..f0b450d --- /dev/null +++ b/src/lib/objgfx40/main.cpp @@ -0,0 +1,610 @@ +/********************************************************************** +will add copyright bs later + +$Id$ +**********************************************************************/ + +#include "ogPixCon.h" +#include "objgfx40.h" +#include "ogFont.h" +#include "ogSprite.h" +#include "ogBlit.h" +#ifdef __DJGPP__ +#include "ogDisplay_VESA.h" +#endif +#include +#include +#include +#include + +using namespace std; + +void +testPixCon(void) { + ogSurface * buf1 = new ogSurface(); + ogSurface * buf2 = new ogSurface(); + ogPixCon * pixCon = new ogPixCon(OG_PIXFMT_32BPP, OG_PIXFMT_16BPP); + uInt8 r, g, b; + + buf1->Create(100, 100, OG_PIXFMT_32BPP); + buf2->Create(100, 200, OG_PIXFMT_16BPP); + + buf1->SetPixel(0, 0, buf1->Pack(128, 42, 69)); + buf2->SetPixel(0, 0, pixCon->ConvPix(buf1->GetPixel(0, 0))); + + buf2->Unpack(buf2->GetPixel(0, 0), r, g, b); +// cout << "r: " << (uInt32)r << endl; +// cout << "g: " << (uInt32)g << endl; +// cout << "b: " << (uInt32)b << endl; + return; +}; // textPixCon + +void testSetPixel(ogSurface& buf) { + uInt32 xx,yy; + buf.Clear(buf.Pack(0,255,0)); + for (yy = 0; yy<=buf.GetMaxY(); yy++) + for (xx = 0; xx<=buf.GetMaxX(); xx++) + buf.SetPixel(xx,yy,xx*yy); + getc(stdin); + return; +} // testSetPixel + +void testRect(ogSurface& buf) { + uInt32 count; + if (buf.GetBPP()==8) + for (count=0; count<1000; count++) + buf.Rect(buf.GetMaxX() / 2 - count, buf.GetMaxY() / 2 - count, + buf.GetMaxX() / 2 + count, buf.GetMaxY() / 2 + count, + count); + else + for (count=0; count<1000; count++) + buf.Rect(buf.GetMaxX() / 2 - count, buf.GetMaxY() / 2 - count, + buf.GetMaxX() / 2 + count, buf.GetMaxY() / 2 + count, + buf.Pack(count,count,count)); + getc(stdin); + return; +} // testRect + +void testLine(ogSurface & buf) { + uInt32 count; + uInt32 colour; + buf.Clear(buf.Pack(0, 0, 0)); + for (count = 150; count > 0; count--) { + buf.Line(buf.GetMaxX() / 2, buf.GetMaxY() / 2, + buf.GetMaxX(), count*4, buf.Pack(192, 192, 192)); + } // for count + getc(stdin); + if (buf.GetBPP()==8) + for (count=0; count<(buf.GetMaxX()+1); count+=2) { + buf.Line(count-10,-10,buf.GetMaxX()-count+10,buf.GetMaxY()+10,count); + } // for + else { + colour = 255; + for (count = 0; count < (buf.GetMaxX()+1)/2; count+=4) { + buf.Line(buf.GetMaxX()/2, buf.GetMaxY()/2, + buf.GetMaxX()/2-count,buf.GetMaxY(), + buf.Pack(colour,colour,colour)); + buf.Line(buf.GetMaxX()/2, buf.GetMaxY()/2, + buf.GetMaxX()/2+count,buf.GetMaxY(), + buf.Pack(colour,colour,colour)); + buf.Line(buf.GetMaxX()/2, buf.GetMaxY()/2, + buf.GetMaxX()/2-count,0, + buf.Pack(0,colour,0)); + buf.Line(buf.GetMaxX()/2, buf.GetMaxY()/2, + buf.GetMaxX()/2+count,0, + buf.Pack(0,colour,0)); + + --colour; + } // for + + colour = 255; + for (count = 0; count < (buf.GetMaxY()+1)/2; count+=4) { + buf.Line(buf.GetMaxX()/2, buf.GetMaxY()/2, + 0, buf.GetMaxY()/2-count, + buf.Pack(colour,0,0)); + buf.Line(buf.GetMaxX()/2, buf.GetMaxY()/2, + 0, buf.GetMaxY()/2+count, + buf.Pack(colour,0,0)); + buf.Line(buf.GetMaxX()/2, buf.GetMaxY()/2, + buf.GetMaxX(), buf.GetMaxY()/2-count, + buf.Pack(0,0,colour)); + buf.Line(buf.GetMaxX()/2, buf.GetMaxY()/2, + buf.GetMaxX(), buf.GetMaxY()/2+count, + buf.Pack(0,0,colour)); + --colour; + } // for + } // else + getc(stdin); + return; +} // testLine + +void testClear(ogSurface & buf) { + uInt32 count; + if (buf.GetBPP()==8) + for (count=0; count<256; count++) + buf.Clear(count); + else { + for (count=0; count<256; count+=8) + buf.Clear(buf.Pack(count,0,0)); + for (count=0; count<256; count+=8) + buf.Clear(buf.Pack(0,count,0)); + for (count=0; count<256; count+=8) + buf.Clear(buf.Pack(0,0,count)); + for (count=0; count<256; count+=8) + buf.Clear(buf.Pack(count,count,count)); + } // else + getc(stdin); + return; +} // testClear + +void testCircle(ogSurface & buf) { + uInt32 count; + if (buf.GetBPP()==8) + for (count=0; count<1000; count++) + buf.Circle(buf.GetMaxX()/2,buf.GetMaxY()/2, count, count); + else + for (count=0; count<1000; count++) + buf.Circle(buf.GetMaxX()/2,buf.GetMaxY()/2,count,buf.Pack(count,0,count)); + getc(stdin); +} // testCircle + +void testVFlip(ogSurface & buf) { + buf.VFlip(); + getc(stdin); + return; +} // testVFlip + +void testHFlip(ogSurface & buf) { + buf.HFlip(); + getc(stdin); + return; +} // testHFlip + +void testArc(ogSurface & buf) { + uInt32 radius; + uInt32 mid_x, mid_y; + mid_x = buf.GetMaxX()/2; + mid_y = buf.GetMaxY()/2; + if (buf.GetBPP()==8) { + for (radius = 1; radius <9; radius++) { + buf.Arc(mid_x, mid_y, radius*10, 0, 90, radius*15); + buf.Arc(mid_x, mid_y, radius*10, 180,270, 249-(radius-1)*16); + } // for + } else { + for (radius = 1; radius <255; radius++) { + buf.Arc(mid_x, mid_y, radius, 0, 90, buf.Pack(radius,radius,0)); + buf.Arc(mid_x, mid_y, radius, 180,270,buf.Pack(0,255-radius,255-radius)); + } // for + } // else + getchar(); + return; +} // testArc + +void testCubicBezierCurve(ogSurface & buf) { + buf.CubicBezierCurve(100, 100, + 300,50, + 400,120, + 350,300, + 25, buf.Pack(255,255,255)); + getchar(); + return; +} // testCubicBezierCurve + +void testCurve(ogSurface & buf) { + buf.Curve(10,10,100,30,35,160,20,buf.Pack(255,255,255)); + getchar(); + return; +} // testCurve +void testSprite(ogSurface & buf) { + uInt32 count; + uInt32 w,h; + ogSprite * sprite = NULL; + sprite = new ogSprite(); + + buf.Clear(buf.Pack(0, 0, 0)); + testLine(buf); + if (buf.GetBPP()==8) + sprite->Get(buf, + buf.GetMaxX()/2-80,buf.GetMaxY()/2-80, + buf.GetMaxX()/2+80,buf.GetMaxY()/2+80); + else + sprite->Get(buf, + buf.GetMaxX()/2-150,buf.GetMaxY()/2-150, + buf.GetMaxX()/2+150,buf.GetMaxY()/2+150); + + sprite->Save("test.spr"); + delete sprite; + sprite = new ogSprite(); + sprite->Load("test.spr"); + w = sprite->GetWidth()/2; + h = sprite->GetHeight()/2; + buf.Clear(buf.Pack(0, 0, 0)); + sprite->Put(buf,-10000,-10000); // test *really* off the screen + sprite->Put(buf,10000,10000); // test *really* off the screen + + sprite->Put(buf,buf.GetMaxX()/2-w,buf.GetMaxY()/2-h); + sprite->Put(buf,-w,-h); + sprite->Put(buf,buf.GetMaxX()/2-w,-h); + sprite->Put(buf,buf.GetMaxX()-w,-h); + sprite->Put(buf,-w,buf.GetMaxY()/2-h); + sprite->Put(buf,buf.GetMaxX()-w,buf.GetMaxY()/2-h); + sprite->Put(buf,-w,buf.GetMaxY()-h); + sprite->Put(buf,buf.GetMaxX()/2-w,buf.GetMaxY()-h); + sprite->Put(buf,buf.GetMaxX()-w,buf.GetMaxY()-h); + getc(stdin); + for (count = 0; count < 256; count++) { + sprite->Put(buf,random() % (buf.GetMaxX()+sprite->GetWidth()) - sprite->GetWidth(), + random() % (buf.GetMaxY()+sprite->GetHeight()) - sprite->GetHeight()); + } // for + delete sprite; + getc(stdin); + return; +} // testSprite + +void testBlit(ogSurface & buf) { + int32 xx, yy, count; + ogBlit * blit = NULL; + ogBlit * blit2 = NULL; + + blit = new ogBlit(); + + buf.Clear(buf.Pack(0, 0, 0)); + for (xx= 0; xx<= 20; xx++) { + buf.Line(128,0,128-xx*6,255,buf.Pack(255,255,255)); + buf.Line(128,0,128+xx*6,255,buf.Pack(255,255,255)); + buf.Line(128,255,128-xx*6,0,buf.Pack(255,255,255)); + buf.Line(128,255,128+xx*6,0,buf.Pack(255,255,255)); + } // for + + buf.FillCircle(128,128,60,buf.Pack(255,255,255)); + blit->Get(buf,0,0,255,255); + for (yy = 0; yy<=(int32)buf.GetMaxY(); yy++) + for (xx = 0; xx<=(int32)buf.GetMaxX(); xx++) + buf.SetPixel(xx,yy,xx*yy); + blit->Save("test.blt"); + blit2 = new ogBlit(*blit, true); + + delete blit; + blit2->Save("test2.blt"); + blit = new ogBlit(); + blit->Load("test.blt"); + + blit->Put(buf,-10000,-10000); // test *really* off the screen + blit->Put(buf,10000,10000); // test *really* off the screen + + blit->Put(buf,-128,-128); + blit->Put(buf,buf.GetMaxX()/2-128,-128); + blit->Put(buf,buf.GetMaxX()-128,-128); + blit->Put(buf,-128,buf.GetMaxY()/2-128); + blit->Put(buf,buf.GetMaxX()/2-128,buf.GetMaxY()/2-128); + blit->Put(buf,buf.GetMaxX()-128,buf.GetMaxY()/2-128); + blit->Put(buf,-128,buf.GetMaxY()-128); + blit->Put(buf,buf.GetMaxX()/2-128,buf.GetMaxY()-128); + blit->Put(buf,buf.GetMaxX()-128,buf.GetMaxY()-128); + + getc(stdin); + buf.Clear(buf.Pack(0, 0, 0)); + for (yy = 0; yy<=(int32)buf.GetMaxY(); yy++) + for (xx = 0; xx<=(int32)buf.GetMaxX(); xx++) + buf.SetPixel(xx,yy,xx*yy); + blit->GetBlitWithMask(buf, + buf.GetMaxX()/2-blit->GetWidth(), + buf.GetMaxY()/2-blit->GetHeight()); + buf.Clear(buf.Pack(0, 0, 0)); + blit->Put(buf,-10000,-10000); // test *really* off the screen + blit->Put(buf,10000,10000); // test *really* off the screen + + blit->Put(buf,-128,-128); + blit->Put(buf,buf.GetMaxX()/2-128,-128); + blit->Put(buf,buf.GetMaxX()-128,-128); + blit->Put(buf,-128,buf.GetMaxY()/2-128); + blit->Put(buf,buf.GetMaxX()/2-128,buf.GetMaxY()/2-128); + blit->Put(buf,buf.GetMaxX()-128,buf.GetMaxY()/2-128); + blit->Put(buf,-128,buf.GetMaxY()-128); + blit->Put(buf,buf.GetMaxX()/2-128,buf.GetMaxY()-128); + blit->Put(buf,buf.GetMaxX()-128,buf.GetMaxY()-128); + + getc(stdin); + for (count = 0; count < 1000; count++) { + blit->Put(buf,random() % (buf.GetMaxX()+blit->GetWidth()) - blit->GetWidth(), + random() % (buf.GetMaxY()+blit->GetHeight()) - blit->GetHeight()); + } // for + getc(stdin); + for (yy = 0; yy<=(int32)buf.GetMaxY(); yy++) + for (xx = 0; xx<=(int32)buf.GetMaxX(); xx++) + buf.SetPixel(xx,yy,xx*yy); + + blit->GetBlitWithMask(buf,buf.GetMaxX()/2,buf.GetMaxY()-128); + buf.Clear(buf.Pack(128,128,128)); + blit->Put(buf,buf.GetMaxX()/2-128,buf.GetMaxY()/2-128); + getc(stdin); + delete blit; + delete blit2; + + return; +} // testBlit + +void +testBlit2(ogSurface & buf) { + ogBlit * blit = new ogBlit(); + ogSurface * buf2 = new ogSurface(); + ogSurface * blitsource = new ogSurface(); + uInt32 xx,yy,count,colour; + buf.Clear(buf.Pack(0, 0, 0)); + if (!buf2->Clone(buf)) cout << "Clone failed!!!" << endl; + if (!blitsource->Clone(buf)) cout << "Clone failed!!" << endl; + + colour = 255; + for (count = 0; count < (buf2->GetMaxX()+1)/2; count+=4) { + buf2->Line(buf2->GetMaxX()/2, buf2->GetMaxY()/2, + buf2->GetMaxX()/2-count,buf2->GetMaxY(), + buf2->Pack(colour,colour,colour)); + buf2->Line(buf2->GetMaxX()/2, buf2->GetMaxY()/2, + buf2->GetMaxX()/2+count,buf2->GetMaxY(), + buf2->Pack(colour,colour,colour)); + buf2->Line(buf2->GetMaxX()/2, buf2->GetMaxY()/2, + buf2->GetMaxX()/2-count,0, + buf2->Pack(0,colour,0)); + buf2->Line(buf2->GetMaxX()/2, buf2->GetMaxY()/2, + buf2->GetMaxX()/2+count,0, + buf2->Pack(0,colour,0)); + --colour; + } // for + + colour = 255; + for (count = 0; count < (buf.GetMaxY()+1)/2; count+=4) { + buf2->Line(buf2->GetMaxX()/2, buf2->GetMaxY()/2, + 0, buf2->GetMaxY()/2-count, + buf2->Pack(colour,0,0)); + buf2->Line(buf2->GetMaxX()/2, buf2->GetMaxY()/2, + 0, buf2->GetMaxY()/2+count, + buf2->Pack(colour,0,0)); + buf2->Line(buf2->GetMaxX()/2, buf2->GetMaxY()/2, + buf2->GetMaxX(), buf2->GetMaxY()/2-count, + buf2->Pack(0,0,colour)); + buf2->Line(buf2->GetMaxX()/2, buf2->GetMaxY()/2, + buf2->GetMaxX(), buf2->GetMaxY()/2+count, + buf2->Pack(0,0,colour)); + --colour; + } // for + for (yy = 0; yy<=buf2->GetMaxY(); yy++) + for (xx = 0; xx<=buf2->GetMaxX(); xx++) + buf2->SetPixel(xx,yy, xx*yy); + for (count = 0; count<200; count++) + blitsource->FillCircle(random() % blitsource->GetMaxX(), random() % blitsource->GetMaxY(), + random() % 35+1,blitsource->Pack(255,255,255)); + + blit->Get(*blitsource,0,0,blitsource->GetMaxX(),blitsource->GetMaxY()); + blit->Save("bigblit.blt"); + delete blit; + blit = new ogBlit; + blit->Load("bigblit.blt"); + for (count = 0; count<=256; count+=4) { + for (yy = 0; yy<=buf2->GetMaxY(); yy++) + for (xx = 0; xx<=buf2->GetMaxX(); xx++) + buf2->SetPixel(xx,yy,xx*yy*count); + + blit->GetBlitWithMask(*buf2,0,0); + blit->Put(buf,0,0); + } // for + + getc(stdin); + delete blitsource; + delete buf2; + delete blit; + return; +} // testBlit2 + +void +testBlit3(ogSurface & buf) { + int32 count; + ogBlit * blit = NULL; + ogSurface * buf2 = NULL; + buf2 = new ogSurface(); + blit = new ogBlit(); + buf.Clear(buf.Pack(0, 0, 0)); + buf.FillCircle(buf.GetMaxX()/2,buf.GetMaxY()/2,14,buf.Pack(255,255,255)); + blit->Get(buf,buf.GetMaxX()/2-20,buf.GetMaxY()/2-20, + buf.GetMaxX()/2+20,buf.GetMaxY()/2+20); + blit->Put(buf,0,0); + for (count=0; count<(int32)buf.GetMaxX(); count++) + buf.Line(count,0,count,buf.GetMaxY(),count); + buf2->Clone(buf); + blit->GetBlitWithMask(*buf2,10,10); + buf.Clear(buf.Pack(63,63,63)); + for (count=-40; count<(int32)buf.GetMaxX()+10; count++) { + blit->GetBlitWithMask(*buf2,count,buf2->GetMaxY()/2-20); + blit->Put(buf,count,buf.GetMaxY()/2-20); + blit->GetBlitWithMask(*buf2,buf2->GetMaxX()/2-20,count); + blit->Put(buf,buf.GetMaxX()/2-20,count); + } + getc(stdin); + delete blit; + return; +} // testBlit3 + +void +testSaveLoadPal(ogSurface & buf) { + uInt32 count; + testRect(buf); + for (count=0; count<256; count++) + buf.SetPalette(count,count,count,count); + if (buf.SavePalette("test.pal")==false) cout << "SavePal() failed" << endl; + for (count=0; count<256; count++) + buf.SetPalette(count,0,0,0); + if (buf.LoadPalette("test.pal")==false) cout << "LoadPal() failed" << endl; + testRect(buf); +} // testSaveLoadPal + +void +testPolygon(ogSurface & buf) { + ogPoint2d points[16]; + uInt32 count; + buf.Clear(buf.Pack(0, 0, 0)); + for (count=0; count<16; count++) { + points[count].x = random() % buf.GetMaxX(); + points[count].y = random() % buf.GetMaxY(); + } // for + buf.FillPolygon(16, points, buf.Pack(random() & 255,random() & 255,random() & 255)); + getc(stdin); + return; +} // testPolygon + +void +testSpline(ogSurface & buf) { + ogPoint2d points[8]; + uInt32 i; + for (i=0; i<8; i++) { + points[i].x = random() % buf.GetMaxX(); + points[i].y = random() % buf.GetMaxY(); + } // for + buf.Clear(buf.Pack(0, 0, 0)); + buf.Polygon(8, points, buf.Pack(22,229,52)); + buf.Spline(8, points, 24, buf.Pack(64,64,255)); + buf.BSpline(8, points, 24, buf.Pack(255,128,128)); + getchar(); + return; +} // testSpline + +void +testFont(ogSurface & buf) { + uInt32 xx, yy; + ogBitFont * font = new ogBitFont(); + font->Load("SCRIPT.DPF", 0); + font->SetFGColor(255, 255, 255, 255); + font->SetBGColor(0, 0, 0, 255); + + font->PutString(buf, 0, 0, "abAByzYZ"); + + for (yy = 0; yyGetHeight(); yy++) { + for (xx = 0; xx<79; xx++) + if ((buf.GetPixel(xx, yy) & buf.GetAlphaMasker()) == 0) + cout << " "; + else + cout << "*"; + cout << endl; + } + + delete font; + return; +} // testFont + +void +testGouraud(ogSurface & buf) { + uInt8 r, g, b; + ogPoint2d points[4]; + ogRGBA8 colours[4]; + r = g = b = 0; + + points[0].x = buf.GetMaxX() - 150; + points[0].y = 0; + points[1].x = buf.GetMaxX(); + points[1].y = 0; + points[2].x = buf.GetMaxX(); + points[2].y = 150; + points[3].x = buf.GetMaxX() - 250; + points[3].y = 250; + colours[0].red = 255; + colours[0].green = 0; + colours[0].blue = 0; + colours[0].alpha = 255; + colours[1].red = 0; + colours[1].green = 255; + colours[1].blue = 128; + colours[1].alpha = 255; + colours[2].red = 128; + colours[2].green = 255; + colours[2].blue = 128; + colours[2].alpha = 255; + colours[3].red = 63; + colours[3].green = 63; + colours[3].blue = 63; + colours[3].alpha = 255; + buf.FillGouraudPolygon(4, points, colours); + getc(stdin); + return; +} // testGouraud + +void +testCopyBuf(ogSurface & buf) { + ogSurface * buf2 = new ogSurface(); + ogPixelFmt pixFmt; + buf.GetPixFmt(pixFmt); + buf2->Create(400, 400, OG_PIXFMT_32BPP); + buf2->Clear(buf2->Pack(255, 128, 255)); + buf.CopyBuf(0, 0, *buf2, 0, 0, buf2->GetMaxX(), buf2->GetMaxY()); + delete buf2; + getc(stdin); + return; +} + +void +testFillRect(ogSurface & buf) { + uInt32 count; + for (count = 100; count > 0; count--) { + buf.FillRect(count, count, 0, 0, buf.Pack(count*2, count*2, count*2)); + } + getc(stdin); + + return; +} // testFillRect() +int main() { + ogSurface* buf = NULL; + +#ifdef __DJGPP__ + buf = new ogDisplay_VESA(); + buf->Create(800, 600, OG_PIXFMT_16BPP); +#else + buf = new ogSurface(); + if (buf->Create(1024, 768, OG_PIXFMT_16BPP)==false) exit(1); +#endif + srandom(time(NULL)); + +// buf->SetBlending(true); +// buf->SetAlpha(127); + buf->SetAntiAliasing(true); + +//cout << "testPixCon()" << endl; +// testPixCon(); + cout << "testFillRect()" << endl; + testFillRect(*buf); + cout << "testCopyBuf()" << endl; + testCopyBuf(*buf); + cout << "testGouraud()" << endl; + testGouraud(*buf); + cout << "testFont()" << endl; + testFont(*buf); + cout << "TestRect()" << endl; + testRect(*buf); + cout << "testCircle()" << endl; + testCircle(*buf); + cout << "TestLine()" << endl; + testLine(*buf); +cout << "TestVFlip()" << endl; + testVFlip(*buf); +cout << "TestHFlip()" << endl; + testHFlip(*buf); +cout << "TestArc()" << endl; + testArc(*buf); +cout << "TestSetPixel()" << endl; + testSetPixel(*buf); +cout << "TestClear()" << endl; + testClear(*buf); +cout << "TestSprite()" << endl; + testSprite(*buf); +cout << "TestBlit()" << endl; + testBlit(*buf); +cout << "TestBlit2()" << endl; + testBlit2(*buf); +// testBlit3(*buf); // special test for 320x200x8bpp +// testSaveLoadPal(*buf); // use an 8bpp mode +cout << "TestPolygon()" << endl; + testPolygon(*buf); +cout << "TestCurve()" << endl; + testCurve(*buf); +cout << "TestSpline()" << endl; + testSpline(*buf); + delete buf; +// buf->SetPixel(0, 0, buf->Pack(0, 0, 0)); + return(0); +} diff --git a/src/lib/objgfx40/objgfx40.cpp b/src/lib/objgfx40/objgfx40.cpp new file mode 100644 index 0000000..53e87e5 --- /dev/null +++ b/src/lib/objgfx40/objgfx40.cpp @@ -0,0 +1,4145 @@ +/******************************************************* +$Id$ +*******************************************************/ + +#ifndef __UBIXOS_KERNEL__ +extern "C" { + #include + #include + #include + #include + } +#endif + +#ifdef __UBIXOS_KERNEL__ +extern "C" { + #include + #include + #include + #include + #include + } + +#define abs(a) (((a) < 0) ? -(a) : (a)) +#endif + +#include +#include +#include +#ifdef __UBIXOS__ +#include +#endif + +const + uInt32 OG_MASKS[32] = { + 0, + 1, + 3, + 7, + 15, + 31, + 63, + 127, + 255, + 511, + 1023, + 2047, + 4095, + 8191, + 16383, + 32767, + 65535, + 131071, + 262143, + 524287, + 1048575, + 2097151, + 4194303, + 8388607, + 16777215, + 33554431, + 67108863, + 134217727, + 268435455, + 536870911, + 1073741823, + 2147483647 + }; // OG_MASKS[] + +const + float INTENSITIES[32] = { + 1.0, // 0 + 0.984250984251, // 1 + 0.968245836552, // 2 + 0.951971638233, // 3 + 0.935414346693, // 4 + 0.938558653544, // 5 + 0.901387818866, // 6 + 0.883883476483, // 7 + 0.866025403784, // 8 + 0.847791247891, // 9 + 0.829156197589, // 10 + 0.810092587301, // 11 + 0.790569415042, // 12 + 0.770551750371, // 13 + 0.75, // 14 + 0.728868986856, // 15 + 0.707106781187, // 16 + 0.684653196881, // 17 + 0.661437827766, // 18 + 0.637377439199, // 19 + 0.612372435696, // 20 + 0.586301969978, // 21 + 0.559016994375, // 22 + 0.53033008589, // 23 + 0.5, // 24 + 0.467707173347, // 25 + 0.433012701892, // 26 + 0.395284707521, // 27 + 0.353553390593, // 28 + 0.306186217848, // 29 + 0.25, // 30 + 0.176776695297 // 31 + }; // INTENSITIES[] + +// #include "../ubixos-home/src/sys/include/ubixos/types.h" + +// #define ROUND(f) (int)((f) + ((f) > 0 ? 0.5 : -0.5)) + +struct ogHLine { + int32 xStart; + int32 xEnd; +}; + +struct ogHLineList { + int32 length; + int32 yStart; + int32 * xLeft; + int32 * xRight; +}; + +struct ogPointListHeader { + int32 length; + ogPoint2d * PointPtr; +}; + +struct ogEdgeState { + ogEdgeState* nextEdge; + int32 x; + int32 startY; + int32 wholePixelXMove; + int32 xDirection; + int32 errorTerm; + int32 errorTermAdjUp; + int32 errorTermAdjDown; + int32 count; + ogRGBA8 colour; + int32 rStepY; + int32 gStepY; + int32 bStepY; + int32 aStepY; + int32 rIncY; + int32 gIncY; + int32 bIncY; + int32 aIncY; +}; + +class ogEdgeTable { + public: + ogEdgeState * globalEdges; + ogEdgeState * activeEdges; + ogEdgeTable(void) { globalEdges = activeEdges = NULL; return; } + void AdvanceAET(void); + void BuildGET(uInt32 numPoints, ogPoint2d * polyPoints); + void BuildGET_G(uInt32 numPoints, ogPoint2d * polyPoints, ogRGBA8 * colours); + void MoveXSortedToAET(int32 yToMove); + void ScanOutAET(ogSurface & destObject, int32 yToScan, uInt32 colour); + void ScanOutAET_G(ogSurface & destObject, int32 yToScan); + void XSortAET(void); + ~ogEdgeTable(void); +}; // ogEdgeState + +void +ogEdgeTable::AdvanceAET(void) { + ogEdgeState * currentEdge; + ogEdgeState ** currentEdgePtr; + + currentEdgePtr = &activeEdges; + currentEdge = activeEdges; + while (currentEdge!=NULL) { + --currentEdge->count; + if (0 == currentEdge->count) { + // this edge is finished, so remove it from the AET + *currentEdgePtr = currentEdge->nextEdge; + // I'm thinking I should dispose currentEdge here!? + } else { + // advance the edge's x coord by minimum move + currentEdge->x += currentEdge->wholePixelXMove; + // determine whether it's time for X to advance one extra + currentEdge->errorTerm += currentEdge->errorTermAdjUp; + if (currentEdge->errorTerm > 0) { + currentEdge->x += currentEdge->xDirection; + currentEdge->errorTerm -= currentEdge->errorTermAdjDown; + } // if + currentEdgePtr = ¤tEdge->nextEdge; + } // else + currentEdge = *currentEdgePtr; + } // while + return; +} // ogEdgeTable::AdvanceAET + +void +ogEdgeTable::BuildGET(uInt32 numPoints, ogPoint2d * polyPoints) { + int32 i, x1, y1, x2, y2, deltaX, deltaY, width, tmp; + ogEdgeState * newEdgePtr; + ogEdgeState * followingEdge; + ogEdgeState ** followingEdgeLink; + + /* + * Creates a GET in the buffer pointed to by NextFreeEdgeStruc from + * the vertex list. Edge endpoints are flipped, if necessary, to + * guarantee all edges go top to bottom. The GET is sorted primarily + * by ascending Y start coordinate, and secondarily by ascending X + * start coordinate within edges with common Y coordinates } + */ + + // Scan through the vertex list and put all non-0-height edges into + // the GET, sorted by increasing Y start coordinate} + + for (i = 0; i < (int32)numPoints; i++) { + // calculate the edge height and width + x1 = polyPoints[i].x; + y1 = polyPoints[i].y; + + if (0 == i) { + // wrap back around to the end of the list + x2 = polyPoints[numPoints-1].x; + y2 = polyPoints[numPoints-1].y; + } else { + x2 = polyPoints[i-1].x; + y2 = polyPoints[i-1].y; + } // else i!=0 + + if (y1 > y2) { + tmp = x1; + x1 = x2; + x2 = tmp; + + tmp = y1; + y1 = y2; + y2 = tmp; + } // if y1>y2 + + // skip if this can't ever be an active edge (has 0 height) + deltaY = y2-y1; + if (deltaY != 0) { + newEdgePtr = new ogEdgeState; + newEdgePtr->xDirection = ((deltaX = x2-x1) > 0) ? 1 : -1; + width = abs(deltaX); + newEdgePtr->x = x1; + newEdgePtr->startY = y1; + newEdgePtr->count = newEdgePtr->errorTermAdjDown = deltaY; + newEdgePtr->errorTerm = (deltaX >= 0) ? 0 : 1-deltaY; + + if (deltaY >= width) { + newEdgePtr->wholePixelXMove = 0; + newEdgePtr->errorTermAdjUp = width; + } else { + newEdgePtr->wholePixelXMove = (width / deltaY) * newEdgePtr->xDirection; + newEdgePtr->errorTermAdjUp = width % deltaY; + } // else + + followingEdgeLink = &globalEdges; + while (true) { + followingEdge = *followingEdgeLink; + if ((followingEdge == NULL) || + (followingEdge->startY > y1) || + ((followingEdge->startY == y1) && + (followingEdge->x>=x1))) { + newEdgePtr->nextEdge = followingEdge; + *followingEdgeLink = newEdgePtr; + break; + } // if + followingEdgeLink = &followingEdge->nextEdge; + } // while + } // if deltaY!=0 + } // for + return; +} // ogEdgeTable::BuildGET + +void +ogEdgeTable::BuildGET_G(uInt32 numPoints, ogPoint2d * polyPoints, ogRGBA8 * colours) { + + int32 i, x1, y1, x2, y2, deltaX, deltaY, width, tmp; + ogEdgeState * newEdgePtr; + ogEdgeState * followingEdge; + ogEdgeState ** followingEdgeLink; + ogRGBA8 c1, c2, cTmp; + + /* + * Creates a GET in the buffer pointed to by NextFreeEdgeStruc from + * the vertex list. Edge endpoints are flipped, if necessary, to + * guarantee all edges go top to bottom. The GET is sorted primarily + * by ascending Y start coordinate, and secondarily by ascending X + * start coordinate within edges with common Y coordinates } + */ + + // Scan through the vertex list and put all non-0-height edges into + // the GET, sorted by increasing Y start coordinate} + + for (i = 0; i < (int32)numPoints; i++) { + // calculate the edge height and width + x1 = polyPoints[i].x; + y1 = polyPoints[i].y; + c1 = colours[i]; + + if (0 == i) { + // wrap back around to the end of the list + x2 = polyPoints[numPoints-1].x; + y2 = polyPoints[numPoints-1].y; + c2 = colours[numPoints-1]; + } else { + x2 = polyPoints[i-1].x; + y2 = polyPoints[i-1].y; + c2 = colours[i-1]; + } // else i!=0 + + if (y1 > y2) { + tmp = x1; + x1 = x2; + x2 = tmp; + + tmp = y1; + y1 = y2; + y2 = tmp; + + cTmp = c1; + c1 = c2; + c2 = cTmp; + } // if y1>y2 + + // skip if this can't ever be an active edge (has 0 height) + deltaY = y2-y1; + if (deltaY != 0) { + newEdgePtr = new ogEdgeState; + newEdgePtr->colour = c1; + newEdgePtr->xDirection = ((deltaX = x2-x1) > 0) ? 1 : -1; + + newEdgePtr -> rStepY = ((c2.red - c1.red +1) << 16) / deltaY; + newEdgePtr -> rIncY = 0; + newEdgePtr -> gStepY = ((c2.green - c1.green +1) << 16) / deltaY; + newEdgePtr -> gIncY = 0; + newEdgePtr -> bStepY = ((c2.blue - c1.blue +1) << 16) / deltaY; + newEdgePtr -> bIncY = 0; + newEdgePtr -> aStepY = ((c2.alpha - c1.alpha +1) << 16) / deltaY; + newEdgePtr -> aIncY = 0; + + width = abs(deltaX); + newEdgePtr->x = x1; + newEdgePtr->startY = y1; + newEdgePtr->count = newEdgePtr->errorTermAdjDown = deltaY; + newEdgePtr->errorTerm = (deltaX >= 0) ? 0 : 1-deltaY; + + if (deltaY >= width) { + newEdgePtr->wholePixelXMove = 0; + newEdgePtr->errorTermAdjUp = width; + } else { + newEdgePtr->wholePixelXMove = (width / deltaY) * newEdgePtr->xDirection; + newEdgePtr->errorTermAdjUp = width % deltaY; + } // else + + followingEdgeLink = &globalEdges; + while (true) { + followingEdge = *followingEdgeLink; + if ((followingEdge == NULL) || + (followingEdge->startY > y1) || + ((followingEdge->startY == y1) && + (followingEdge->x>=x1))) { + newEdgePtr->nextEdge = followingEdge; + *followingEdgeLink = newEdgePtr; + break; + } // if + followingEdgeLink = &followingEdge->nextEdge; + } // while + } // if deltaY!=0 + } // for + return; +} // ogEdgeTable::BuildGET_G + +void +ogEdgeTable::MoveXSortedToAET(int32 yToMove) { + ogEdgeState * AETEdge; + ogEdgeState * tempEdge; + ogEdgeState ** AETEdgePtr; + int32 currentX; + + /* The GET is Y sorted. Any edges that start at the desired Y + * coordinate will be first in the GET, so we'll move edges from + * the GET to AET until the first edge left in the GET is no + * longer at the desired Y coordinate. Also, the GET is X sorted + * within each Y cordinate, so each successive edge we add to the + * AET is guaranteed to belong later in the AET than the one just + * added. + */ + AETEdgePtr = &activeEdges; + while ((globalEdges != NULL) && (globalEdges->startY == yToMove)) { + currentX = globalEdges->x; + // link the new edge into the AET so that the AET is still + // sorted by X coordinate + while (true) { + AETEdge = *AETEdgePtr; + if ((AETEdge == NULL) || (AETEdge->x >= currentX)) { + tempEdge = globalEdges->nextEdge; + *AETEdgePtr = globalEdges; + globalEdges->nextEdge = AETEdge; + AETEdgePtr = &globalEdges->nextEdge; + globalEdges = tempEdge; + break; + } else AETEdgePtr = &AETEdge->nextEdge; + } // while true + } // while globalEdges!=NULL and globalEdges->startY==yToMove + return; +} // ogEdgeTable::MoveXSortedToAET + +void +ogEdgeTable::ScanOutAET(ogSurface & destObject, int32 yToScan, uInt32 colour) { + ogEdgeState * currentEdge; + int32 leftX; + + /* Scan through the AET, drawing line segments as each pair of edge + * crossings is encountered. The nearest pixel on or to the right + * of the left edges is drawn, and the nearest pixel to the left + * of but not on right edges is drawn + */ + currentEdge = activeEdges; + + while (currentEdge != NULL) { + leftX = currentEdge->x; + currentEdge = currentEdge->nextEdge; + + if (currentEdge != NULL) { + if (currentEdge->x > leftX) + destObject.HLine(leftX, currentEdge->x-1, yToScan, colour); + currentEdge = currentEdge->nextEdge; + } // if currentEdge != NULL + } // while + + return; +} // ogEdgeTable::ScanOutAET + +void +ogEdgeTable::ScanOutAET_G(ogSurface & destObject, int32 yToScan) { + ogEdgeState * currentEdge; + int32 leftX, count; + int32 rStepX, gStepX, bStepX, aStepX; + int32 rIncX, gIncX, bIncX, aIncX; + int32 lR, lG, lB, lA; + int32 rR, rG, rB, rA; + int32 dR, dG, dB, dA; + int32 dist; + + /* Scan through the AET, drawing line segments as each pair of edge + * crossings is encountered. The nearest pixel on or to the right + * of the left edges is drawn, and the nearest pixel to the left + * of but not on right edges is drawn + */ + currentEdge = activeEdges; + + while (currentEdge != NULL) { + leftX = currentEdge->x; + + lR = currentEdge->colour.red; + lG = currentEdge->colour.green; + lB = currentEdge->colour.blue; + lA = currentEdge->colour.alpha; + + lR += currentEdge->rIncY >> 16; + lG += currentEdge->gIncY >> 16; + lB += currentEdge->bIncY >> 16; + lA += currentEdge->aIncY >> 16; + + currentEdge->rIncY += currentEdge->rStepY; + currentEdge->gIncY += currentEdge->gStepY; + currentEdge->bIncY += currentEdge->bStepY; + currentEdge->aIncY += currentEdge->aStepY; + + + currentEdge = currentEdge->nextEdge; + + if (currentEdge != NULL) { + if (leftX != currentEdge->x) { + rR = currentEdge->colour.red; + rG = currentEdge->colour.green; + rB = currentEdge->colour.blue; + rA = currentEdge->colour.alpha; + + rR += currentEdge->rIncY >> 16; + rG += currentEdge->gIncY >> 16; + rB += currentEdge->bIncY >> 16; + rA += currentEdge->aIncY >> 16; + + currentEdge->rIncY += currentEdge->rStepY; + currentEdge->gIncY += currentEdge->gStepY; + currentEdge->bIncY += currentEdge->bStepY; + currentEdge->aIncY += currentEdge->aStepY; + + dR = rR - lR; + dG = rG - lG; + dB = rB - lB; + dA = rA - lA; + + dist = currentEdge->x - leftX; + + rStepX = (dR << 16) / dist; + rIncX = 0; + gStepX = (dG << 16) / dist; + gIncX = 0; + bStepX = (dB << 16) / dist; + bIncX = 0; + aStepX = (dA << 16) / dist; + aIncX = 0; + + for (count = leftX; count < currentEdge->x; count++) { + destObject.SetPixel(count, yToScan, + lR + (rIncX >> 16), + lG + (gIncX >> 16), + lB + (bIncX >> 16), + lA + (aIncX >> 16) ); + rIncX += rStepX; + gIncX += gStepX; + bIncX += bStepX; + aIncX += aStepX; + } // for + } + currentEdge = currentEdge->nextEdge; + } // if currentEdge != NULL + } // while + + return; +} // ogEdgeTable::ScanOutAET_G + +void +ogEdgeTable::XSortAET(void) { + ogEdgeState * currentEdge; + ogEdgeState * tempEdge; + ogEdgeState ** currentEdgePtr; + bool swapOccurred; + + if (activeEdges == NULL) return; + + do { + swapOccurred = false; + currentEdgePtr = &activeEdges; + currentEdge = activeEdges; + while (currentEdge->nextEdge!=NULL) { + if (currentEdge->x > currentEdge->nextEdge->x) { + // the second edge has a lower x than the first + // swap them in the AET + tempEdge = currentEdge->nextEdge->nextEdge; + *currentEdgePtr = currentEdge->nextEdge; + currentEdge->nextEdge->nextEdge = currentEdge; + currentEdge->nextEdge = tempEdge; + swapOccurred = true; + } // if + currentEdgePtr = &((*currentEdgePtr)->nextEdge); + currentEdge = *currentEdgePtr; + } // while + } while (swapOccurred); + return; +} // ogEdgeTable::XSortAET + +ogEdgeTable::~ogEdgeTable(void) { + ogEdgeState * edge; + ogEdgeState * tmpEdge; + tmpEdge = globalEdges; + // first walk the global edges and delete any non-null nodes + while (tmpEdge!=NULL) { + edge = tmpEdge; + tmpEdge = edge->nextEdge; + delete edge; + } // while + tmpEdge = activeEdges; + // next walk the activeEdges and delete any non-null nodes. Note that this should + // always be null + while (tmpEdge!=NULL) { + edge = tmpEdge; + tmpEdge = edge->nextEdge; + delete edge; + } // while + return; +} // ogEdgeTable::~ogEdgeTable + +static bool +fileExists(const char *file) +{ +#ifdef __UBIXOS_KERNEL__ + fileDescriptor *f = fopen(file, "rb"); +#else + FILE *f = fopen(file, "rb"); +#endif + + if (!f) + return false; + fclose(f); + return true; +} + +static int32 calculate(float mu, int32 p0, int32 p1, int32 p2, int32 p3); + +// ogSurface constructor +ogSurface::ogSurface(void) { + version = ogVERSION; + + dataState = ogNone; + buffer = NULL; + lineOfs = NULL; + pal = NULL; + attributes = NULL; + xRes = 0; + yRes = 0; + maxX = 0; + maxY = 0; + bSize = 0; + lSize = 0; + BPP = 0; + bytesPerPix = 0; + pixFmtID = 0; + redShifter = 0; + greenShifter = 0; + blueShifter = 0; + alphaShifter = 0; + redFieldPosition = 0; + greenFieldPosition = 0; + blueFieldPosition = 0; + alphaFieldPosition = 0; + alphaMasker = 0; + lastError = ogOK; + return; +} // ogSurface::ogSurface + +void +ogSurface::AARawLine(uInt32 x1, uInt32 y1, uInt32 x2, uInt32 y2, uInt32 colour) { + /* + * aaRawLine + * + * private method + * + * draws an unclipped anti-aliased line from (x1,y1) to (x2,y2) using colour + * + */ + uInt32 erradj, erracc; + uInt32 erracctmp, intshift, wgt, wgtCompMask; + int32 dx, dy, tmp, xDir, i; + uInt8 r, g, b, a; + uInt32 alphas[32]; + bool oldBlending; + + if (y1 > y2) { + tmp= y1; + y1 = y2; + y2 = tmp; + + tmp= x1; + x1 = x2; + x2 = tmp; + } // if + + dx = (x2-x1); + if (dx>=0) xDir=1; else { dx = -dx; xDir=-1; } +// dx = abs(dx); + dy = (y2 - y1); + + if (0 == dy) { + HLine(x1, x2, y1, colour); + return; + } + + if (0 == dx) { + VLine(x1, y1, y2, colour); + return; + } + + Unpack(colour, r, g, b, a); + + if (!IsBlending()) a = 255; + + for (i = 0; i < 32; i++) { + alphas[i] = static_cast(INTENSITIES[i]*a + 0.5f); + } // for + + oldBlending = SetBlending(true); + + RawSetPixel(x1, y1, r, g, b, a); + + // this is incomplete.. diagonal lines don't travel through the + // center of pixels exactly + + do { + + if (dx == dy) { + for (; dy != 0; dy--) { + x1 += xDir; + ++y1; + RawSetPixel(x1, y1, r, g, b, a); + } // for + break; // pop out to the bottom and restore the old blending state + } // if dx==dy + + erracc = 0; + intshift = 32-5; + wgt = 12; + wgtCompMask = 31; + + if (dy > dx) { + /* y-major. Calculate 32-bit fixed point fractional part of a pixel that + * X advances every time Y advances 1 pixel, truncating the result so that + * we won't overrun the endpoint along the X axis + */ +// erradj = ((uInt64) dx << 32) / (uInt64)dy; + __asm__ __volatile__ ( + " xor %%eax, %%eax \n" + " div %1 \n" + " mov %%eax, %2 \n" + : + : "d" (dx), "b" (dy), "m" (erradj) + ); + + while (--dy) { + erracctmp = erracc; + erracc += erradj; + if (erracc <= erracctmp) x1 += xDir; + y1++; // y-major so always advance Y + /* the nbits most significant bits of erracc give us the intensity + * weighting for this pixel, and the complement of the weighting for + * the paired pixel. + */ + wgt = erracc >> intshift; + SetPixel(x1, y1, r, g, b, alphas[wgt]); + SetPixel(x1+xDir, y1, r, g, b, alphas[wgt ^ wgtCompMask]); + } // while + + } else { + + /* x-major line. Calculate 32-bit fixed-point fractional part of a pixel + * that Y advances each time X advances 1 pixel, truncating the result so + * that we won't overrun the endpoint along the X axis. + */ +// erradj = ((uInt64)dy << 32) / (uInt64)dx; + __asm__ __volatile__ ( + " xor %%eax, %%eax \n" + " div %1 \n" + " mov %%eax, %2 \n" + : + : "d" (dy), "b" (dx), "m" (erradj) + ); + + // draw all pixels other than the first and last + while (--dx) { + erracctmp = erracc; + erracc += erradj; + if (erracc <= erracctmp) y1++; + x1 += xDir; // x-major so always advance X + /* the nbits most significant bits of erracc give us the intensity + * weighting for this pixel, and the complement of the weighting for + * the paired pixel. + */ + wgt = erracc >> intshift; + SetPixel(x1, y1, r, g, b, alphas[wgt]); + SetPixel(x1, y1+1, r, g, b, alphas[wgt ^ wgtCompMask]); + } // while + } // else + RawSetPixel(x2, y2, r, g, b, alphas[wgt]); + + } while (false); + + SetBlending(oldBlending); + return; +} // ogSurface::AARawLine + +uInt32 +ogSurface::RawGetPixel(uInt32 x, uInt32 y) { + uInt32 result; + switch (bytesPerPix) { + case 4: + __asm__ __volatile__( + " shl $2, %%ecx \n" // shl ecx, 2 {adjust for pixel size} + " add %%esi, %%edi \n" // add edi, esi + " add %%ecx, %%edi \n" // add edi, ecx + " mov (%%edi),%%eax \n" // eax,word ptr [edi] + " mov %%eax, %3 \n" // mov result, eax + : + : "D" (buffer), "S" (lineOfs[y]), // %0, %1 + "c" (x), "m" (result) // %2, %3 + ); + break; + case 3: + __asm__ __volatile__( + " mov %%ecx, %%eax \n" // mov eax, ecx - adjust for pixel size + " add %%ecx, %%ecx \n" // add ecx, ecx - adjust for pixel size + " add %%eax, %%ecx \n" // add ecx, eax - adjust for pixel size + " add %%esi, %%edi \n" // add edi, esi + " add %%ecx, %%edi \n" // add edi, ecx + " movzwl (%%edi),%%eax \n" // edx,word ptr [edi] + " xor %%eax, %%eax \n" + " mov 2(%%edi), %%al \n" // mov al, [edi+2] + " shl $16, %%eax \n" // shl eax, 16 + " mov (%%edi), %%ax \n" // mov ax, [edi] + " mov %%eax, %3 \n" // mov result, eax + : + : "D" (buffer), "S" (lineOfs[y]), // %0, %1 + "c" (x), "m" (result) // %2, %3 + ); + break; + case 2: + __asm__ __volatile__( + " add %%esi, %%edi \n" // add edi, esi + " add %%ecx, %%ecx \n" // add ecx, ecx {adjust for pixel size} + " add %%ecx, %%edi \n" // add edi, ecx + " movzwl (%%edi),%%eax \n" // movzx edx,word ptr [edi] + " mov %%eax, %0 \n" // mov result, eax + : "=m" (result) + : "D" (buffer), "S" (lineOfs[y]), // %0, %1 + "c" (x) // , "m" (result) // %2, %3 + ); + break; + case 1: + __asm__ __volatile__( + " add %%esi, %%edi \n" // add edi, esi + " add %%ecx, %%edi \n" // add edi, ecx + " movzbl (%%edi),%%eax \n" // movzx edx,byte ptr [edi] + " mov %%eax, %3 \n" // mov result, eax + : + : "D" (buffer), "S" (lineOfs[y]), // %0, %1 + "c" (x), "m" (result) // %2, %3 + ); + break; + } // switch + return result; +} // ogSurface::RawGetPixel + +void +ogSurface::RawSetPixel(uInt32 x, uInt32 y, uInt32 colour) { + uInt32 newR, newG, newB, inverseA; + uInt8 sR, sG, sB, sA; + uInt8 dR, dG, dB; + + do { + if (IsBlending()) { + Unpack(colour, sR, sG, sB, sA); + if (0 == sA) return; + if (255 == sA) break; + inverseA = 255 - sA; + Unpack(RawGetPixel(x, y), dR, dG, dB); + newR = (dR * inverseA + sR * sA) >> 8; + newG = (dG * inverseA + sG * sA) >> 8; + newB = (dB * inverseA + sB * sA) >> 8; + colour = Pack(newR, newG, newB, inverseA); + } // if + } while (false); + + switch (bytesPerPix) { + case 4: + __asm__ __volatile__( + // { Calculate offset, prepare the pixel to be drawn } + " shl $2, %%ecx \n" // shl eax, 2 {adjust for pixel size} + " add %%esi, %%edi \n" // add edi, esi + " add %%ecx, %%edi \n" // add edi, ecx + // { Draw the pixel } + " mov %%eax, (%%edi) \n" // mov [edi], eax + : + : "D" (buffer), "S" (lineOfs[y]), // %0, %1 + "c" (x), "a" (colour) // %2, %3 + ); + break; + case 3: + __asm__ __volatile__( + // Calculate offset, prepare the pixel to be drawn + " leal (%%ecx, %%ecx, 2), %%ecx \n" // lea ecx, [ecx + ecx*2] + " add %%esi, %%edi \n" // add edi, esi + " add %%ecx, %%edi \n" // add edi, ecx + // { Draw the pixel } + " mov %%ax, (%%edi) \n" // mov [edi], ax + " shr $16, %%eax \n" // shr eax, 16 + " mov %%al, 2(%%edi)\n" // mov [edi+2],al + : + : "D" (buffer), "S" (lineOfs[y]), // %0, %1 + "c" (x), "a" (colour) // %2, %3 + ); + break; + case 2: + __asm__ __volatile__( + // { Calculate offset, prepare the pixel to be drawn } + " add %%ecx, %%ecx \n" // add ecx, ecx {adjust for pixel size} + " add %%esi, %%edi \n" // add edi, esi + // " mov %3, %%eax \n" // mov eax, colour + " add %%ecx, %%edi \n" // add edi, ecx + // { Draw the pixel } + " mov %%ax, (%%edi) \n" // mov [edi], ax + : + : "D" (buffer), "S" (lineOfs[y]), // %0, %1 + "c" (x), "a" (colour) // %2, %3 + ); + break; + case 1: + __asm__ __volatile__( + // { Calculate offset, prepare the pixel to be drawn } + // " add (%%esi,%%ebx,4), %%edi \n" // add edi, [esi + ebx * 4] + " add %%esi, %%edi \n" // add edi, esi + " add %%ecx, %%edi \n" // add edi, ecx + // { Draw the pixel } + " mov %%al, (%%edi) \n" // mov [edi], al + : + : "D" (buffer), "S" (lineOfs[y]), // %0, %1 + "c" (x), "a" (colour) // %2, %3 + ); + break; + } // switch + return; +} // ogSurface::RawSetPixel + +void +ogSurface::RawSetPixel(uInt32 x, uInt32 y, uInt8 r, uInt8 g, uInt8 b, uInt8 a) { + uInt32 newR, newG, newB, inverseA; + uInt8 dR, dG, dB; + uInt32 colour; + + do { + if (IsBlending()) { + if (0 == a) return; + if (255 == a) { + colour = Pack(r, g, b, a); + break; + } // if a == 255 + + inverseA = 255 - a; + Unpack(RawGetPixel(x, y), dR, dG, dB); + newR = (dR * inverseA + r * a) >> 8; + newG = (dG * inverseA + g * a) >> 8; + newB = (dB * inverseA + b * a) >> 8; + colour = Pack(newR, newG, newB, inverseA); + } else colour = Pack(r, g, b, a); + } while (false); + + switch (bytesPerPix) { + case 4: + __asm__ __volatile__( + // { Calculate offset, prepare the pixel to be drawn } + " shl $2, %%ecx \n" // shl eax, 2 {adjust for pixel size} + " add %%esi, %%edi \n" // add edi, esi + " add %%ecx, %%edi \n" // add edi, ecx + // { Draw the pixel } + " mov %%eax, (%%edi) \n" // mov [edi], eax + : + : "D" (buffer), "S" (lineOfs[y]), // %0, %1 + "c" (x), "a" (colour) // %2, %3 + ); + break; + case 3: + __asm__ __volatile__( + // Calculate offset, prepare the pixel to be drawn + " leal (%%ecx, %%ecx, 2), %%ecx \n" // lea ecx, [ecx + ecx*2] + " add %%esi, %%edi \n" // add edi, esi + " add %%ecx, %%edi \n" // add edi, ecx + // { Draw the pixel } + " mov %%ax, (%%edi) \n" // mov [edi], ax + " shr $16, %%eax \n" // shr eax, 16 + " mov %%al, 2(%%edi)\n" // mov [edi+2],al + : + : "D" (buffer), "S" (lineOfs[y]), // %0, %1 + "c" (x), "a" (colour) // %2, %3 + ); + break; + case 2: + __asm__ __volatile__( + // { Calculate offset, prepare the pixel to be drawn } + " add %%ecx, %%ecx \n" // add ecx, ecx {adjust for pixel size} + " add %%esi, %%edi \n" // add edi, esi + // " mov %3, %%eax \n" // mov eax, colour + " add %%ecx, %%edi \n" // add edi, ecx + // { Draw the pixel } + " mov %%ax, (%%edi) \n" // mov [edi], ax + : + : "D" (buffer), "S" (lineOfs[y]), // %0, %1 + "c" (x), "a" (colour) // %2, %3 + ); + break; + case 1: + __asm__ __volatile__( + // { Calculate offset, prepare the pixel to be drawn } + // " add (%%esi,%%ebx,4), %%edi \n" // add edi, [esi + ebx * 4] + " add %%esi, %%edi \n" // add edi, esi + " add %%ecx, %%edi \n" // add edi, ecx + // { Draw the pixel } + " mov %%al, (%%edi) \n" // mov [edi], al + : + : "D" (buffer), "S" (lineOfs[y]), // %0, %1 + "c" (x), "a" (colour) // %2, %3 + ); + break; + } // switch + return; +} // ogSurface::RawSetPixel + +bool +ogSurface::ClipLine(int32& x1, int32& y1, int32& x2, int32& y2) { + /* + * clipLine() + * + * private method + * + * clips a line to (0,0),(maxX,maxY); returns true if + * the line segment is in bounds, false if none of the line segment is + * on the screen. Uses HJI's line clipping algorithm. + */ + + int32 tx1, ty1, tx2, ty2; + int32 OutCode; + uInt32 AndResult, OrResult; + AndResult = 15; + OrResult = 0; + OutCode = 0; + if (x1<0) OutCode+=8; + if (x1>(int32)maxX) OutCode+=4; + if (y1<0) OutCode+=2; + if (y1>(int32)maxY) OutCode++; + + AndResult &= OutCode; + OrResult |= OutCode; + OutCode = 0; + + if (x2<0) OutCode+=8; + if (x2>(int32)maxX) OutCode+=4; + if (y2<0) OutCode+=2; + if (y2>(int32)maxY) OutCode++; + + AndResult &= OutCode; + OrResult |= OutCode; + + if (AndResult>0) return false; + if (OrResult==0) return true; + + // some clipping is required here. + + tx1 = x1; + ty1 = y1; + tx2 = x2; + ty2 = y2; + + if (x1<0) { + ty1 = (x2*y1-x1*y2) / (x2-x1); + tx1 = 0; + } // if + else + if (x2<0) { + ty2 = (x2*y1-x1*y2) / (x2-x1); + tx2 = 0; + } // elseif + + if (x1>(int32)maxX) { + ty1 = (y1*(x2-maxX)+y2*(maxX-x1)) / (x2-x1); + tx1 = maxX; + } // if + else + if (x2>(int32)maxX) { + ty2 = (y1*(x2-maxX)+y2*(maxX-x1)) / (x2-x1); + tx2 = maxX; + } // elseif + + if (((ty1<0) && (ty2<0)) || + ((ty1>(int32)maxY) && (ty2>(int32)maxY))) return false; + + if (ty1<0) { + tx1 = (x1*y2-x2*y1) / (y2-y1); + ty1 = 0; + } // if + else + if (ty2<0) { + tx2 = (x1*y2-x2*y1) / (y2-y1); + ty2 = 0; + } // elseif + + if (ty1>(int32)maxY) { + tx1 = (x1*(y2-maxY)+x2*(maxY-y1)) / (y2-y1); + ty1 = maxY; + } // if + else + if (ty2>(int32)maxY) { + tx2 = (x1*(y2-maxY)+x2*(maxY-y1)) / (y2-y1); + ty2 = maxY; + } // elseif + + if (((uInt32)tx1>maxX) || ((uInt32)tx2>maxX)) return false; + + x1 = tx1; + y1 = ty1; + x2 = tx2; + y2 = ty2; + + return true; +} // ogSurface::ClipLine + +// wu's double step line algorithm blatently borrowed from: +// http://www.edepot.com/linewu.html + +void ogSurface::RawLine(uInt32 x1, uInt32 y1, uInt32 x2, uInt32 y2, uInt32 colour) { + int32 dy = y2 - y1; + int32 dx = x2 - x1; + int32 stepx, stepy; + + if (dy < 0) { dy = -dy; stepy = -1; } else { stepy = 1; } + if (dx < 0) { dx = -dx; stepx = -1; } else { stepx = 1; } + + RawSetPixel(x1, y1, colour); + RawSetPixel(x2, y2, colour); + + if (dx > dy) { + int32 length = (dx - 1) >> 2; + int32 extras = (dx - 1) & 3; + int32 incr2 = (dy << 2) - (dx << 1); + + if (incr2 < 0) { + int32 c = dy << 1; + int32 incr1 = c << 1; + int32 d = incr1 - dx; + + for (int32 i = 0; i < length; i++) { + x1 += stepx; + x2 -= stepx; + + if (d < 0) { // Pattern: + RawSetPixel(x1, y1, colour); // + RawSetPixel(x1 += stepx, y1, colour); // x o o + RawSetPixel(x2, y2, colour); // + RawSetPixel(x2 -= stepx, y2, colour); + + d += incr1; + } else { + + if (d < c) { // Pattern: + RawSetPixel(x1, y1, colour); // o + RawSetPixel(x1 += stepx, y1 += stepy, colour); // x o + RawSetPixel(x2, y2, colour); // + RawSetPixel(x2 -= stepx, y2 -= stepy, colour); + } else { + RawSetPixel(x1, y1 += stepy, colour); // Pattern: + RawSetPixel(x1 += stepx, y1, colour); // o o + RawSetPixel(x2, y2 -= stepy, colour); // x + RawSetPixel(x2 -= stepx, y2, colour); // + } // else + + d += incr2; + } // else + } // for i + + if (extras > 0) { + + if (d < 0) { + RawSetPixel(x1 += stepx, y1, colour); + if (extras > 1) RawSetPixel(x1 += stepx, y1, colour); + if (extras > 2) RawSetPixel(x2 -= stepx, y2, colour); + } else + if (d < c) { + RawSetPixel(x1 += stepx, y1, colour); + if (extras > 1) RawSetPixel(x1 += stepx, y1 += stepy, colour); + if (extras > 2) RawSetPixel(x2 -= stepx, y2, colour); + } else { + RawSetPixel(x1 += stepx, y1 += stepy, colour); + if (extras > 1) RawSetPixel(x1 += stepx, y1, colour); + if (extras > 2) RawSetPixel(x2 -= stepx, y2 -= stepy, colour); + } + } // if extras > 0 + } else { + int32 c = (dy - dx) << 1; + int32 incr1 = c << 1; + int32 d = incr1 + dx; + + for (int32 i = 0; i < length; i++) { + x1 += stepx; + x2 -= stepx; + + if (d > 0) { + RawSetPixel(x1, y1 += stepy, colour); // Pattern: + RawSetPixel(x1 += stepx, y1 += stepy, colour); // o + RawSetPixel(x2, y2 -= stepy, colour); // o + RawSetPixel(x2 -= stepx, y2 -= stepy, colour); // x + d += incr1; + } else { + if (d < c) { + RawSetPixel(x1, y1, colour); // Pattern: + RawSetPixel(x1 += stepx, y1 += stepy, colour); // o + RawSetPixel(x2, y2, colour); // x o + RawSetPixel(x2 -= stepx, y2 -= stepy, colour); // + } else { + RawSetPixel(x1, y1 += stepy, colour); // Pattern: + RawSetPixel(x1 += stepx, y1, colour); // o o + RawSetPixel(x2, y2 -= stepy, colour); // x + RawSetPixel(x2 -= stepx, y2, colour); // + } + + d += incr2; + } // else + } // for i + + if (extras > 0) { + if (d > 0) { + RawSetPixel(x1 += stepx, y1 += stepy, colour); + if (extras > 1) RawSetPixel(x1 += stepx, y1 += stepy, colour); + if (extras > 2) RawSetPixel(x2 -= stepx, y2 -= stepy, colour); + } else + if (d < c) { + RawSetPixel(x1 += stepx, y1, colour); + if (extras > 1) RawSetPixel(x1 += stepx, y1 += stepy, colour); + if (extras > 2) RawSetPixel(x2 -= stepx, y2, colour); + } else { + + RawSetPixel(x1 += stepx, y1 += stepy, colour); + + if (extras > 1) RawSetPixel(x1 += stepx, y1, colour); + if (extras > 2) { + if (d > c) + RawSetPixel(x2 -= stepx, y2 -= stepy, colour); + else + RawSetPixel(x2 -= stepx, y2, colour); + } // if extras > 2 + + } // else + } // if extras > 0 + } // else + + } else { + + int32 length = (dy - 1) >> 2; + int32 extras = (dy - 1) & 3; + int32 incr2 = (dx << 2) - (dy << 1); + + if (incr2 < 0) { + int32 c = dx << 1; + int32 incr1 = c << 1; + int32 d = incr1 - dy; + + for (int32 i = 0; i < length; i++) { + y1 += stepy; + y2 -= stepy; + + if (d < 0) { + RawSetPixel(x1, y1, colour); + RawSetPixel(x1, y1 += stepy, colour); + RawSetPixel(x2, y2, colour); + RawSetPixel(x2, y2 -= stepy, colour); + + d += incr1; + } else { + + if (d < c) { + RawSetPixel(x1, y1, colour); + RawSetPixel(x1 += stepx, y1 += stepy, colour); + RawSetPixel(x2, y2, colour); + RawSetPixel(x2 -= stepx, y2 -= stepy, colour); + } else { + RawSetPixel(x1 += stepx, y1, colour); + RawSetPixel(x1, y1 += stepy, colour); + RawSetPixel(x2 -= stepx, y2, colour); + RawSetPixel(x2, y2 -= stepy, colour); + } // else + + d += incr2; + } // else + } // for i + + if (extras > 0) { + if (d < 0) { + RawSetPixel(x1, y1 += stepy, colour); + if (extras > 1) RawSetPixel(x1, y1 += stepy, colour); + if (extras > 2) RawSetPixel(x2, y2 -= stepy, colour); + } else + if (d < c) { + RawSetPixel(x1, y1 += stepy, colour); + if (extras > 1) RawSetPixel(x1 += stepx, y1 += stepy, colour); + if (extras > 2) RawSetPixel(x2, y2 -= stepy, colour); + } else { + RawSetPixel(x1 += stepx, y1 += stepy, colour); + if (extras > 1) RawSetPixel(x1, y1 += stepy, colour); + if (extras > 2) RawSetPixel(x2 -= stepx, y2 -= stepy, colour); + } // else + } // if extras > 0 + } else { + int32 c = (dx - dy) << 1; + int32 incr1 = c << 1; + int32 d = incr1 + dy; + + for (int32 i = 0; i < length; i++) { + y1 += stepy; + y2 -= stepy; + + if (d > 0) { + RawSetPixel(x1 += stepx, y1, colour); + RawSetPixel(x1 += stepx, y1 += stepy, colour); + RawSetPixel(x2 -= stepx, y2, colour); + RawSetPixel(x2 -= stepx, y2 -= stepy, colour); + d += incr1; + } else { + if (d < c) { + RawSetPixel(x1, y1, colour); + RawSetPixel(x1 += stepx, y1 += stepy, colour); + RawSetPixel(x2, y2, colour); + RawSetPixel(x2 -= stepx, y2 -= stepy, colour); + } else { + RawSetPixel(x1 += stepx, y1, colour); + RawSetPixel(x1, y1 += stepy, colour); + RawSetPixel(x2 -= stepx, y2, colour); + RawSetPixel(x2, y2 -= stepy, colour); + } // else + d += incr2; + } // else + } // for + + if (extras > 0) { + if (d > 0) { + RawSetPixel(x1 += stepx, y1 += stepy, colour); + if (extras > 1) RawSetPixel(x1 += stepx, y1 += stepy, colour); + if (extras > 2) RawSetPixel(x2 -= stepx, y2 -= stepy, colour); + } else + if (d < c) { + RawSetPixel(x1, y1 += stepy, colour); + if (extras > 1) RawSetPixel(x1 += stepx, y1 += stepy, colour); + if (extras > 2) RawSetPixel(x2, y2 -= stepy, colour); + } else { + RawSetPixel(x1 += stepx, y1 += stepy, colour); + if (extras > 1) RawSetPixel(x1, y1 += stepy, colour); + if (extras > 2) { + if (d > c) + RawSetPixel(x2 -= stepx, y2 -= stepy, colour); + else + RawSetPixel(x2, y2 -= stepy, colour); + } // if extras > 2 + } // else + } // if extras > 0 + } // else + } // else +} // ogSurface::RawLine + +#if 0 +void +ogSurface::RawLine(uInt32 x1, uInt32 y1, uInt32 x2, uInt32 y2, uInt32 colour) { + /* + * ogSurface::RawLine() + * + * private method; draws an unclipped line from (x1,y1) to (x2,y2) + * + */ + int32 tc; + if (!Avail()) return; + switch (BPP) { + case 8: + __asm__ __volatile__( + " mov $1, %%ecx \n" // mov ecx, 1 + " bt $15, %%eax \n" // bt eax, 15 + " jnc rlxPositive8 \n" + " or $-1, %%ecx \n" // or ecx, -1 + " neg %%eax \n" // neg eax +"rlxPositive8: \n" + " add %%eax, %%eax \n" // add eax, eax + " bt $15, %%ebx \n" // bt ebx, 15 + " jnc rlyPositive8 \n" + " neg %%edx \n" // neg edx + " neg %%ebx \n" // neg ebx +"rlyPositive8: \n" + " add %%ebx, %%ebx \n" // add ebx, ebx + + " cmp %%ebx, %%eax \n" // cmp eax, ebx + " jle rlyGreater8 \n" + " push %%ecx \n" // push ecx + " mov %%eax, %%ecx \n" // mov ecx, eax + " mov %%ebx, %6 \n" // mov tc, ebx + " shr $1, %%ecx \n" // shr ecx, 1 + " sub %%ecx, %6 \n" // sub tc, ecx + " pop %%ecx \n" // pop ecx +"rlxTop8: \n" + " push %%eax \n" // push eax + " mov %5, %%eax \n" // mov eax, colour + " mov %%al, (%%edi) \n" // mov [edi], al + " pop %%eax \n" // pop eax + " cmp %%edi, %%esi \n" // cmp esi, edi + " je rlDone8 \n" + " cmp $0, %6 \n" // cmp tc, 0 + " jl rlNoAddY8 \n" + " add %%edx, %%edi \n" // add edi, edx + " sub %%eax, %6 \n" // sub tc, eax +"rlNoAddY8: \n" + " add %%ecx, %%edi \n" // add edi, ecx + " add %%ebx, %6 \n" // add tc, ebx + " jmp rlxTop8 \n" + +"rlyGreater8: \n" + " push %%ecx \n" // push ecx + " mov %%ebx, %%ecx \n" // mov ecx, ebx + " mov %%eax, %6 \n" // mov tc, eax + " shr $1, %%ecx \n" // shr ecx, 1 + " sub %%ecx, %6 \n" // sub tc, ecx + " pop %%ecx \n" +"rlyTop8: \n" + " push %%eax \n" // push eax + " mov %5, %%eax \n" // mov eax, colour + " mov %%al, (%%edi) \n" // mov [edi], al + " pop %%eax \n" // pop eax + " cmp %%edi, %%esi \n" // cmp esi, edi + " je rlDone8 \n" + " cmp $0, %6 \n" // cmp tc, 0 + " jl rlNoAddX8 \n" + " add %%ecx, %%edi \n" // add edi, ecx + " sub %%ebx, %6 \n" // sub tc, ebx +"rlNoAddX8: \n" + " add %%edx, %%edi \n" // add edi, edx + " add %%eax, %6 \n" // add tc, eax + " jmp rlyTop8 \n" +"rlDone8: \n" + : + : "D" ((uInt8 *)buffer+lineOfs[y1]+x1), // %0 + "S" ((uInt8 *)buffer+lineOfs[y2]+x2), // %1 + "a" (x2-x1), "b" (y2-y1), // %2, %3 + "d" (xRes), "m" (colour), // %4, %5 + "m" (tc) // %6 + ); + break; + case 15: + case 16: + __asm__ __volatile__( + " mov $1, %%ecx \n" // mov ecx, 1 + " bt $15, %%eax \n" // bt eax, 15 + " jnc rlxPositive16 \n" + " or $-1, %%ecx \n" // or ecx, -1 + " neg %%eax \n" // neg eax +"rlxPositive16: \n" + " add %%eax, %%eax \n" // add eax, eax + " bt $15, %%ebx \n" // bt ebx, 15 + " jnc rlyPositive16 \n" + " neg %%edx \n" // neg edx + " neg %%ebx \n" // neg ebx +"rlyPositive16: \n" + " add %%ebx, %%ebx \n" // add ebx, ebx + + " cmp %%ebx, %%eax \n" // cmp eax, ebx + " jle rlyGreater16 \n" + " push %%ecx \n" // push ecx + " mov %%eax, %%ecx \n" // mov ecx, eax + " mov %%ebx, %6 \n" // mov tc, ebx + " shr $1, %%ecx \n" // shr ecx, 1 + " sub %%ecx, %6 \n" // sub tc, ecx + " pop %%ecx \n" // pop ecx +"rlxTop16: \n" + " push %%eax \n" // push eax + " mov %5, %%eax \n" // mov eax, colour + " mov %%ax, (%%edi) \n" // mov [edi], ax + " pop %%eax \n" // pop eax + " cmp %%edi, %%esi \n" // cmp esi, edi + " je rlDone16 \n" + " cmp $0, %6 \n" // cmp tc, 0 + " jl rlNoAddY16 \n" + " add %%edx, %%edi \n" // add edi, edx + " sub %%eax, %6 \n" // sub tc, eax +"rlNoAddY16: \n" + " add %%ecx, %%edi \n" // add edi, ecx + " add %%ecx, %%edi \n" // add edi, ecx - pix size + " add %%ebx, %6 \n" // add tc, ebx + " jmp rlxTop16 \n" + +"rlyGreater16: \n" + " push %%ecx \n" // push ecx + " mov %%ebx, %%ecx \n" // mov ecx, ebx + " mov %%eax, %6 \n" // mov tc, eax + " shr $1, %%ecx \n" // shr ecx, 1 + " sub %%ecx, %6 \n" // sub tc, ecx + " pop %%ecx \n" +"rlyTop16: \n" + " push %%eax \n" // push eax + " mov %5, %%eax \n" // mov eax, colour + " mov %%ax, (%%edi) \n" // mov [edi], ax + " pop %%eax \n" // pop eax + " cmp %%edi, %%esi \n" // cmp esi, edi + " je rlDone16 \n" + " cmp $0, %6 \n" // cmp tc, 0 + " jl rlNoAddX16 \n" + " add %%ecx, %%edi \n" // add edi, ecx + " add %%ecx, %%edi \n" // add edi, ecx - pix size + " sub %%ebx, %6 \n" // sub tc, ebx +"rlNoAddX16: \n" + " add %%edx, %%edi \n" // add edi, edx + " add %%eax, %6 \n" // add tc, eax + " jmp rlyTop16 \n" +"rlDone16: \n" + : + : "D" ((uInt8 *)buffer+lineOfs[y1]+(x1 << 1)), // %0 + "S" ((uInt8 *)buffer+lineOfs[y2]+(x2 << 1)), // %1 + "a" (x2-x1), "b" (y2-y1), // %2, %3 + "d" (xRes), "m" (colour), // %4, %5 + "m" (tc) // %6 + ); + break; + case 24: + __asm__ __volatile__( + " mov $1, %%ecx \n" // mov ecx, 1 + " bt $15, %%eax \n" // bt eax, 15 + " jnc rlxPositive24 \n" + " or $-1, %%ecx \n" // or ecx, -1 + " neg %%eax \n" // neg eax +"rlxPositive24: \n" + " add %%eax, %%eax \n" // add eax, eax + " bt $15, %%ebx \n" // bt ebx, 15 + " jnc rlyPositive24 \n" + " neg %%edx \n" // neg edx + " neg %%ebx \n" // neg ebx +"rlyPositive24: \n" + " add %%ebx, %%ebx \n" // add ebx, ebx + + " cmp %%ebx, %%eax \n" // cmp eax, ebx + " jle rlyGreater24 \n" + " push %%ecx \n" // push ecx + " mov %%eax, %%ecx \n" // mov ecx, eax + " mov %%ebx, %6 \n" // mov tc, ebx + " shr $1, %%ecx \n" // shr ecx, 1 + " sub %%ecx, %6 \n" // sub tc, ecx + " pop %%ecx \n" // pop ecx +"rlxTop24: \n" + " push %%eax \n" // push eax + " mov %5, %%eax \n" // mov eax, colour + " mov %%ax, (%%edi) \n" // mov [edi], ax + " shr $16, %%eax \n" // shr eax, 16 + " mov %%al, 2(%%edi)\n" // mov [edi+2],al + " pop %%eax \n" // pop eax + " cmp %%edi, %%esi \n" // cmp esi, edi + " je rlDone24 \n" + " cmp $0, %6 \n" // cmp tc, 0 + " jl rlNoAddY24 \n" + " add %%edx, %%edi \n" // add edi, edx + " sub %%eax, %6 \n" // sub tc, eax +"rlNoAddY24: \n" + " add %%ecx, %%edi \n" // add edi, ecx + " add %%ecx, %%edi \n" // add edi, ecx - pix size + " add %%ecx, %%edi \n" // add edi, ecx + " add %%ebx, %6 \n" // add tc, ebx + " jmp rlxTop24 \n" + +"rlyGreater24: \n" + " push %%ecx \n" // push ecx + " mov %%ebx, %%ecx \n" // mov ecx, ebx + " mov %%eax, %6 \n" // mov tc, eax + " shr $1, %%ecx \n" // shr ecx, 1 + " sub %%ecx, %6 \n" // sub tc, ecx + " pop %%ecx \n" +"rlyTop24: \n" + " push %%eax \n" // push eax + " mov %5, %%eax \n" // mov eax, colour + " mov %%ax, (%%edi) \n" // mov [edi], ax + " shr $16, %%eax \n" // shr eax, 16 + " mov %%al, 2(%%edi)\n" // mov [edi+2],al + " pop %%eax \n" // pop eax + " cmp %%edi, %%esi \n" // cmp esi, edi + " je rlDone24 \n" + " cmp $0, %6 \n" // cmp tc, 0 + " jl rlNoAddX24 \n" + " add %%ecx, %%edi \n" // add edi, ecx + " add %%ecx, %%edi \n" // add edi, ecx - pix size + " add %%ecx, %%edi \n" // add edi, ecx + " sub %%ebx, %6 \n" // sub tc, ebx +"rlNoAddX24: \n" + " add %%edx, %%edi \n" // add edi, edx + " add %%eax, %6 \n" // add tc, eax + " jmp rlyTop24 \n" +"rlDone24: \n" + : + : "D" ((uInt8 *)buffer+lineOfs[y1]+(x1*3)), // %0 + "S" ((uInt8 *)buffer+lineOfs[y2]+(x2*3)), // %1 + "a" (x2-x1), "b" (y2-y1), // %2, %3 + "d" (xRes), "m" (colour), // %4, %5 + "m" (tc) // %6 + ); + break; + case 32: + __asm__ __volatile__( + " mov $1, %%ecx \n" // mov ecx, 1 + " bt $15, %%eax \n" // bt eax, 15 + " jnc rlxPositive32 \n" + " or $-1, %%ecx \n" // or ecx, -1 + " neg %%eax \n" // neg eax +"rlxPositive32: \n" + " add %%eax, %%eax \n" // add eax, eax + " bt $15, %%ebx \n" // bt ebx, 15 + " jnc rlyPositive32 \n" + " neg %%edx \n" // neg edx + " neg %%ebx \n" // neg ebx +"rlyPositive32: \n" + " add %%ebx, %%ebx \n" // add ebx, ebx + + " cmp %%ebx, %%eax \n" // cmp eax, ebx + " jle rlyGreater32 \n" + " push %%ecx \n" // push ecx + " mov %%eax, %%ecx \n" // mov ecx, eax + " mov %%ebx, %6 \n" // mov tc, ebx + " shr $1, %%ecx \n" // shr ecx, 1 + " sub %%ecx, %6 \n" // sub tc, ecx + " pop %%ecx \n" // pop ecx +"rlxTop32: \n" + " push %%eax \n" // push eax + " mov %5, %%eax \n" // mov eax, colour + " mov %%eax, (%%edi)\n" // mov [edi], eax + " pop %%eax \n" // pop eax + " cmp %%edi, %%esi \n" // cmp esi, edi + " je rlDone32 \n" + " cmp $0, %6 \n" // cmp tc, 0 + " jl rlNoAddY32 \n" + " add %%edx, %%edi \n" // add edi, edx + " sub %%eax, %6 \n" // sub tc, eax +"rlNoAddY32: \n" + " add %%ecx, %%edi \n" // add edi, ecx + " add %%ecx, %%edi \n" // add edi, ecx - pix size + " add %%ecx, %%edi \n" // add edi, ecx + " add %%ecx, %%edi \n" // add edi, ecx - pix size + " add %%ebx, %6 \n" // add tc, ebx + " jmp rlxTop32 \n" + +"rlyGreater32: \n" + " push %%ecx \n" // push ecx + " mov %%ebx, %%ecx \n" // mov ecx, ebx + " mov %%eax, %6 \n" // mov tc, eax + " shr $1, %%ecx \n" // shr ecx, 1 + " sub %%ecx, %6 \n" // sub tc, ecx + " pop %%ecx \n" +"rlyTop32: \n" + " push %%eax \n" // push eax + " mov %5, %%eax \n" // mov eax, colour + " mov %%eax, (%%edi)\n" // mov [edi], eax + " pop %%eax \n" // pop eax + " cmp %%edi, %%esi \n" // cmp esi, edi + " je rlDone32 \n" + " cmp $0, %6 \n" // cmp tc, 0 + " jl rlNoAddX32 \n" + " add %%ecx, %%edi \n" // add edi, ecx - pix size + " add %%ecx, %%edi \n" // add edi, ecx + " add %%ecx, %%edi \n" // add edi, ecx - pix size + " add %%ecx, %%edi \n" // add edi, ecx + " sub %%ebx, %6 \n" // sub tc, ebx +"rlNoAddX32: \n" + " add %%edx, %%edi \n" // add edi, edx + " add %%eax, %6 \n" // add tc, eax + " jmp rlyTop32 \n" +"rlDone32: \n" + : + : "D" ((uInt8 *)buffer+lineOfs[y1]+(x1 << 2)), // %0 + "S" ((uInt8 *)buffer+lineOfs[y2]+(x2 << 2)), // %1 + "a" (x2-x1), "b" (y2-y1), // %2, %3 + "d" (xRes), "m" (colour), // %4, %5 + "m" (tc) // %6 + ); + break; + } // switch + return; +} // ogSurface::RawLine +#endif + +bool +ogSurface::Alias(ogSurface& src, uInt32 x1, uInt32 y1, uInt32 x2, uInt32 y2) { + uInt32 tmp; + + if (ogOwner == dataState) { + SetLastError(ogAlreadyOwner); + return false; + } // if + + if (x2 eAngle) { + tmp = sAngle; + sAngle = eAngle; + eAngle = tmp; + } // if + + x = 0; + y = radius; + p = 3-2*radius; + + while (x<=y) { + alpha = (180.0/3.14159265358979)*atan((double)x/(double)y); + + if ((alpha >= sAngle) && (alpha <= eAngle)) + SetPixel(xCenter-x, yCenter-y, colour); + + if ((90-alpha >= sAngle) && (90-alpha <= eAngle)) + SetPixel(xCenter-y, yCenter-x, colour); + + if ((90+alpha >= sAngle) && (90+alpha <= eAngle)) + SetPixel(xCenter-y, yCenter+x, colour); + + if ((180-alpha >= sAngle) && (180-alpha <= eAngle)) + SetPixel(xCenter-x, yCenter+y, colour); + + if ((180+alpha >= sAngle) && (180+alpha <= eAngle)) + SetPixel(xCenter+x, yCenter+y, colour); + + if ((270-alpha >= sAngle) && (270-alpha <= eAngle)) + SetPixel(xCenter+y, yCenter+x, colour); + + if ((270+alpha >= sAngle) && (270+alpha <= eAngle)) + SetPixel(xCenter+y, yCenter-x, colour); + + if ((360-alpha >= sAngle) && (360-alpha <= eAngle)) + SetPixel(xCenter+x, yCenter-y, colour); + + if (p < 0) + p += 4*x+6; + else { + p += 4*(x-y)+10; + --y; + } // else + ++x; + } // while + return; +} // ogSurface::Arc + +bool +ogSurface::Avail(void) { + return ((buffer!=NULL) && (lineOfs!=NULL)); +} // ogSurface::Avail + +static int32 +calculate(float mu, int32 p0, int32 p1, int32 p2, int32 p3) { + float mu2, mu3; + mu2 = mu*mu; + mu3 = mu2*mu; + return (int32)(0.5f+(1.0/6.0)*(mu3*(-p0+3.0*p1-3.0*p2+p3)+ + mu2*(3.0*p0-6.0*p1+3.0*p2)+ + mu*(-3.0*p0+3.0*p2)+(p0+4.0*p1+p2))); +} // calculate + + +void +ogSurface::BSpline(uInt32 numPoints, ogPoint2d* points, uInt32 segments, + uInt32 colour) { + float mu, mudelta; + int32 x1, y1, x2, y2; + uInt32 n, h; + + if (NULL == points) return; + + if ((numPoints < 4) || (numPoints > 255) || (0 == segments)) return; + + mudelta = 1.0/segments; + for (n=3; n= 0) { + SetPixel(xCenter+x, yCenter+y, colour); + SetPixel(xCenter+x, yCenter-y, colour); + SetPixel(xCenter-x, yCenter+y, colour); + SetPixel(xCenter-x, yCenter-y, colour); + + if (d + y > 0) { + y--; + d -= 2*y+1; + } // if + + if (x > d) { + x++; + d += 2*x+1; + } // if + } // while + return; +} // ogSurface::Circle + +void +ogSurface::Clear(uInt32 colour) { + uInt32 height = 0; + uInt32 xx, yy; + uInt8 r, g, b, a; + if (!Avail()) return; + + do { + if (IsBlending()) { + Unpack(colour, r, g, b, a); + if (0 == a) return; + if (255 == a) break; + for (yy = 0; yy <= maxY; yy++) + for (xx = 0; xx <= maxX; xx++) + RawSetPixel(xx, yy, r, g, b, a); + } // if + } while (false); + + __asm__ __volatile__("cld\n"); + switch (bytesPerPix) { + case 4: + __asm__ __volatile__( + + " add (%%esi), %%edi \n" // add edi, [esi] + " mov %%ecx, %%esi \n" // mov esi, ecx + " inc %%edx \n" // inc edx (maxX) + " inc %%ebx \n" // inc ebx (maxY) + " mov %%edx, %%ecx \n" // mov ecx, edx + " shl $2, %%ecx \n" // shl ecx, 2 + " sub %%ecx, %%esi \n" // sub esi, ecx // adjust for pix size + "loop32: \n" + " mov %%edx, %%ecx \n" // mov ecx, edx + " rep \n" + " stosl \n" + " add %%esi, %%edi \n" // add edi, esi + " dec %%ebx \n" + " jnz loop32 \n" + + : + : "D" (buffer), "S" (lineOfs), // %0, %1 + "a" (colour), "b" (maxY), // %2, %3 + "c" (xRes), "d" (maxX) // %4, %5 + ); + break; + case 3: + __asm__ __volatile__( + " add (%%esi), %%edi \n" // add edi, [esi] + " mov %%ecx, %%esi \n" // mov esi, ecx + " inc %%edx \n" // inc edx (maxX) + " inc %%ebx \n" // inc ebx (maxY) + " sub %%edx, %%esi \n" // sub esi, edx // adjust for pix size + " mov %%ebx, %6 \n" // mov height, ebx + " sub %%edx, %%esi \n" // sub esi, edx // adjust for pix size + " mov %%eax, %%ebx \n" // mov ebx, eax + " sub %%edx, %%esi \n" // sub esi, edx // adjust for pix size + " shr $16, %%ebx \n" // shr ebx, 16 + "oloop24: \n" + " mov %%edx, %%ecx \n" // mov ecx, edx + "iloop24: \n" + " mov %%ax,(%%edi) \n" // mov [edi],ax + " movb %%bl,2(%%edi) \n" // mov [edi+2],bl + " add $3, %%edi \n" // add edi, 3 + " dec %%ecx \n" // dec ecx + " jnz iloop24 \n" + " add %%esi, %%edi \n" // add edi, esi + " decl %6 \n" // dec height + " jnz oloop24 \n" + : + : "D" (buffer), "S" (lineOfs), // %0, %1 + "a" (colour), "b" (maxY), // %2, %3 + "c" (xRes), "d" (maxX), // %4, %5 + "m" (height) // %6 + ); + break; + case 2: + __asm__ __volatile__( + " add (%%esi), %%edi \n" // add edi, [esi] + " mov %%ecx, %%esi \n" // mov esi, ecx + " inc %%edx \n" // inc edx (maxX) + " inc %%ebx \n" // inc ebx (maxY) + " sub %%edx, %%esi \n" // sub esi, edx + " sub %%edx, %%esi \n" // sub esi, edx // adjust for pix size + " mov %%ax, %%cx \n" // mov cx, ax + " shl $16, %%eax \n" // shl eax, 16 + " mov %%cx, %%ax \n" // mov ax, cx + "loop16: \n" + " mov %%edx, %%ecx \n" // mov ecx, edx + " shr $1, %%ecx \n" // shr ecx, 1 + " rep \n" + " stosl \n" + " jnc noc16 \n" + " stosw \n" + "noc16: \n" + " add %%esi, %%edi \n" // add edi, esi + " dec %%ebx \n" + " jnz loop16 \n" + : + : "D" (buffer), "S" (lineOfs), // %0, %1 + "a" (colour), "b" (maxY), // %2, %3 + "c" (xRes), "d" (maxX) // %4, %5 + ); + break; + case 1: + __asm__ __volatile__( + " add (%%esi), %%edi \n" // add edi, [esi] + " mov %%ecx, %%esi \n" // mov esi, ecx + " inc %%edx \n" // inc edx (maxY) + " inc %%ebx \n" // inc ebx (maxX) + " sub %%edx, %%esi \n" // sub esi, edx + " mov %%al, %%ah \n" // mov ah, al + " mov %%ax, %%cx \n" // mov cx, ax + " shl $16, %%eax \n" // shl eax, 16 + " mov %%cx, %%ax \n" // mov ax, cx + "loop8: \n" + " push %%edx \n" + " mov %%edx, %%ecx \n" // mov ecx, edx + " and $3, %%edx \n" // and edx, 3 + " shr $2, %%ecx \n" // shr ecx, 2 + " rep \n" + " stosl \n" + " mov %%edx, %%ecx \n" // mov ecx, edx + " rep \n" + " stosb \n" + " pop %%edx \n" + " add %%esi, %%edi \n" // add edi, esi + " dec %%ebx \n" + " jnz loop8 \n" + : + : "D" (buffer), "S" (lineOfs), // %0, %1 + "a" (colour), "b" (maxY), // %2, %3 + "c" (xRes), "d" (maxX) // %4, %5 + ); + break; + } // switch + return; +} // ogSurface::Clear + +bool +ogSurface::Clone(ogSurface& src) { + bool created; + ogPixelFmt pixFmt; + + if (ogNone == src.dataState) { + SetLastError(ogNoSurface); + return false; + } // if + + src.GetPixFmt(pixFmt); + created = Create(src.maxX+1, src.maxY+1, pixFmt); + if (!created) return false; + + *attributes = *src.attributes; + + CopyPalette(src); + Copy(src); + return true; +} // ogSurface::Clone + +void +ogSurface::Copy(ogSurface& src) { + uInt32 pixMap[256]; + uInt32 count, xCount, yCount; + uInt32 xx, yy; + uInt8 r, g, b, a; + void * srcPtr; + + if (!Avail()) return; + if (!src.Avail()) return; + + xCount = src.maxX+1; + if (xCount>maxX+1) xCount=maxX+1; + yCount = src.maxY+1; + if (yCount>maxY+1) yCount=maxY+1; + + if (IsBlending()) { + + for (yy = 0; yy < yCount; yy++) + for (xx = 0; xx < xCount; xx++) { + src.Unpack(src.RawGetPixel(xx, yy), r, g, b, a); + RawSetPixel(xx, yy, r, g, b, a); + } // for xx + + return; + } // if blending + + if (pixFmtID != src.pixFmtID) { + if (src.bytesPerPix == 1) { + for (xx = 0; xx < 256; xx++) + pixMap[xx] = Pack(src.pal[xx].red, + src.pal[xx].green, + src.pal[xx].blue, + src.pal[xx].alpha); + + for (yy = 0; yy < yCount; yy++) + for (xx = 0; xx < xCount; xx++) + RawSetPixel(xx, yy, pixMap[src.RawGetPixel(xx, yy)]); + + } else { // if src.bytesPerPix == 1 + ogPixelFmt srcPixFmt, dstPixFmt; + src.GetPixFmt(srcPixFmt); + GetPixFmt(dstPixFmt); + ogPixCon * pc = new ogPixCon(srcPixFmt, dstPixFmt); + + for (yy = 0; yy < yCount; yy++) + for (xx = 0; xx < xCount; xx++) + RawSetPixel(xx, yy, pc->ConvPix(src.RawGetPixel(xx, yy))); + + delete pc; + } // else + } else { + + xCount *= bytesPerPix; + + for (count = 0; count < yCount; count++) + if ((srcPtr = src.GetPtr(0, count)) == NULL) { + /* + * if we are here then we couldn't get a direct memory pointer + * from the source object. This means that it is not a normal + * "memory" buffer and we have to use the implementation inspecific + * interface. We let the source buffer fill a "temporary" buffer + * and then we copy it to where it needs to go. + */ +#ifdef __UBIXOS_KERNEL__ + srcPtr = kmalloc(xCount,sysID); // allocate space +#else + srcPtr = malloc(xCount); // allocate space +#endif + if (srcPtr != NULL) { + src.CopyLineFrom(0, count, srcPtr, xCount); + CopyLineTo(0, count, srcPtr, xCount); +#ifdef __UBIXOS_KERNEL__ + kfree(srcPtr); +#else + free(srcPtr); +#endif + } // if srcPtr!=NULL + } else CopyLineTo(0, count, srcPtr, xCount); + } // else +} // ogSurface::Copy + +void +ogSurface::CopyBuf(int32 dX1, int32 dY1, + ogSurface& src, int32 sX1, int32 sY1, int32 sX2, int32 sY2) { + uInt32 pixMap[256]; + int32 xx, yy, count, xCount, yCount; + uInt8 r, g, b, a; + void *srcPtr; + ogPixCon * pc; + ogPixelFmt srcPixFmt, dstPixFmt; + + if (!Avail()) return; + if (!src.Avail()) return; + + if ((dX1>(int32)maxX) || (dY1>(int32)maxY)) return; + + // if any of the source buffer is out of bounds then do nothing + if (( (uInt32)sX1>src.maxX) || ((uInt32)sX2>src.maxX) || + ( (uInt32)sY1>src.maxY) || ((uInt32)sY2>src.maxY)) return; + + if (sX1 > sX2) { + xx = sX1; + sX1= sX2; + sX2= xx; + } // if + + if (sY1 > sY2) { + yy = sY1; + sY1= sY2; + sY2= yy; + } // if + + xCount = abs(sX2-sX1)+1; + yCount = abs(sY2-sY1)+1; + + if (dX1+xCount > (int32)maxX+1) xCount = maxX-dX1+1; + if (dY1+yCount > (int32)maxY+1) yCount = maxY-dY1+1; + + if (dX1 < 0) { + xCount += dX1; + sX1 -= dX1; + dX1 = 0; + } // if + + if (dY1 < 0) { + yCount += dY1; + sY1 -= dY1; + dY1 = 0; + } // if + + if ((dX1+xCount<0) || (dY1+yCount<0)) return; + + if (IsBlending()) { + for (yy = 0; yy < yCount; yy++) + for (xx = 0; xx < xCount; xx++) { + src.Unpack(src.RawGetPixel(sX1+xx, sY1+yy), r, g, b, a); + RawSetPixel(dX1+xx, dY1+yy, r, g, b, a); + } // for xx + } // if IsBlending + + if (pixFmtID != src.pixFmtID) { + + if (1 == src.bytesPerPix) { + for (xx=0; xx<256; xx++) + pixMap[xx] = Pack(src.pal[xx].red, + src.pal[xx].green, + src.pal[xx].blue, + src.pal[xx].alpha); + + for (yy = 0; yy < yCount; yy++) + for (xx = 0; xx < xCount; xx++) + RawSetPixel(dX1+xx,dY1+yy, + pixMap[src.GetPixel(sX1+xx,sY1+yy)]); + } else { + + src.GetPixFmt(srcPixFmt); + GetPixFmt(dstPixFmt); + pc = new ogPixCon(srcPixFmt, dstPixFmt); // allocate the pixel converter + if (NULL == pc) return; + + for (yy = 0; yy < yCount; yy++) + for (xx = 0; xx < xCount; xx++) { + RawSetPixel(dX1+xx, dY1+yy, + pc->ConvPix(src.RawGetPixel(sX1+xx, sY1+yy))); + } // for xx + + delete pc; // destroy the pixel converter + + } // else + } else { + xCount *= bytesPerPix; + + for (count = 0; count < yCount; count++) + if ((srcPtr = src.GetPtr(sX1, sY1+count)) == NULL) { + // if we are here then we couldn't get a direct memory pointer + // from the source object. This means that it is not a normal + // "memory" buffer and we have to use the implementation inspecific + // interface. We let the source buffer fill a "temporary" buffer + // and then we copy it to where it needs to go. + +#ifdef __UBIXOS_KERNEL__ + srcPtr = kmalloc(xCount,sysID); // allocate space +#else + srcPtr = malloc(xCount); // allocate space +#endif + if (srcPtr != NULL) { + src.CopyLineFrom(sX1, sY1+count, srcPtr, xCount); + CopyLineTo(dX1, dY1+count, srcPtr, xCount); +#ifdef __UBIXOS_KERNEL__ + kfree(srcPtr); +#else + free(srcPtr); +#endif + } // if srcPtr!=NULL + } else CopyLineTo(dX1,dY1+count,srcPtr,xCount); + } // else +} // ogSurface::CopyBuf + +void +ogSurface::CopyLineTo(uInt32 dx, uInt32 dy, const void * src, uInt32 size) { + /* + * CopyLineTo() + * + * Inputs: + * + * dx - Destination X of the target buffer + * dy - Destination Y of the target buffer + * src - buffer to copy + * size - size in bytes *NOT* pixels + * + * Copies a run of pixels (of the same format) to (x,y) of a buffer + * + * This method is required because of the different implementations of + * copying a run of pixels to a buffer + * + * WARNING!!! This does *NO* error checking. It is assumed that you've + * done all of that. CopyLineTo and CopyLineFrom are the only + * methods that don't check to make sure you're hosing things. Don't + * use this method unless YOU KNOW WHAT YOU'RE DOING!!!!!!!!! + */ + +#ifdef __UBIXOS_KERNEL__ + kmemcpy( (uInt8*)buffer+lineOfs[dy]+dx*bytesPerPix, // dest + src, // src + size); // size +#else + memcpy( (uInt8*)buffer+lineOfs[dy]+dx*bytesPerPix, // dest + src, // src + size); // size +#endif + + return; +} // ogSurface::CopyLineTo + +void +ogSurface::CopyLineFrom(uInt32 sx, uInt32 sy, void * dst, uInt32 size) { + /* + * CopyLineFrom() + * + * Inputs: + * + * sx - Source X of the target buffer + * sy - Source Y of the target buffer + * dest - where to put it + * size - size in bytes *NOT* pixels + * + * Copies a run of pixels (of the same format) to (x,y) of a buffer + * + * This method is required because of the different implementations of + * copying a run of pixels to a buffer + * + * WARNING!!! This does *NO* error checking. It is assumed that you've + * done all of that. CopyLineTo and CopyLineFrom are the only + * methods that don't check to make sure you're hosing things. Don't + * use this method unless YOU KNOW WHAT YOU'RE DOING!!!!!!!!! + */ + +#ifdef __UBIXOS_KERNEL__ + kmemcpy( dst, // dest + (uInt8*)buffer+lineOfs[sy]+sx*bytesPerPix, // src + size); // size +#else + memcpy( dst, // dest + (uInt8*)buffer+lineOfs[sy]+sx*bytesPerPix, // src + size); // size +#endif + + return; +} // ogSurface::CopyLineFrom + +void +ogSurface::CopyPalette(ogSurface& src) { + if (NULL == src.pal) return; + if (NULL == pal) pal = new ogRGBA8[256]; + if (NULL == pal) return; + src.GetPalette(pal); + // memcpy(pal, src.pal, sizeof(ogRGBA8)*256); + return; +} // ogSurface::CopyPalette + +bool +ogSurface::Create(uInt32 _xRes, uInt32 _yRes, ogPixelFmt _pixFormat) { + /* + * ogSurface::Create() + * Allocates memory for a buffer of size _xRes by _yRes with + * the pixel format defined in _pixformat. Allocates memory + * for pal and lineOfs. + */ + void * newBuffer = NULL; + uInt32 * newLineOfs = NULL; + ogRGBA8 * newPal = NULL; + ogAttributes* newAttributes = NULL; + + uInt32 newBSize; + uInt32 newLSize; + uInt32 yy; + + bool status = false; + + switch (_pixFormat.BPP) { + case 8: + case 15: + case 16: + case 24: + case 32: + break; + default: + SetLastError(ogBadBPP); + return false; + } // switch + + newBSize = _xRes * _yRes * ((_pixFormat.BPP + 7) >> 3); + newLSize = _yRes * sizeof(uInt32); // number of scan lines * sizeof(uInt32) + +#ifdef __UBIXOS_KERNEL__ + newBuffer = kmalloc(newBSize,sysID); +#else + newBuffer = malloc(newBSize); +#endif + newLineOfs = new uInt32[_yRes]; + newPal = new ogRGBA8[256]; + newAttributes = new ogAttributes(); + + do { + + if ((NULL == newBuffer) || (NULL == newLineOfs) || + (NULL == newPal) || (NULL == newAttributes)) { + SetLastError(ogMemAllocFail); + break; // break out of do {...} while(false) + } // if + + // check to see if we have already allocated memory .. if so, free it + + if (ogOwner == dataState) { +#ifdef __UBIXOS_KERNEL__ + kfree(buffer); +#else + free(buffer); +#endif + delete [] lineOfs; + delete [] pal; + delete attributes; + } // if dataState + + buffer = newBuffer; + lineOfs = newLineOfs; + pal = newPal; + attributes = newAttributes; + bSize = newBSize; + lSize = newLSize; + + newBuffer = NULL; + newLineOfs = NULL; + newPal = NULL; + newAttributes = NULL; + + BPP = _pixFormat.BPP; + bytesPerPix = (BPP + 7) >> 3; + + SetPalette(DEFAULT_PALETTE); + // memcpy(pal, DEFAULT_PALETTE, sizeof(ogRGBA8)*256); + + maxX = _xRes -1; + xRes = _xRes * bytesPerPix; + maxY = _yRes -1; + yRes = _yRes; + + // in the pascal version we go from 1 to maxY .. here we use yy < yRes + // (which is the same) + + lineOfs[0] = 0; + for (yy = 1; yy < yRes; yy++) + lineOfs[yy] = lineOfs[yy-1]+xRes; + + dataState = ogOwner; + + // For 8bpp modes the next part doesn't matter + + redFieldPosition = _pixFormat.redFieldPosition; + greenFieldPosition = _pixFormat.greenFieldPosition; + blueFieldPosition = _pixFormat.blueFieldPosition; + alphaFieldPosition = _pixFormat.alphaFieldPosition; + // The next part is only used by 15/16hpp + redShifter = 8-_pixFormat.redMaskSize; + greenShifter = 8-_pixFormat.greenMaskSize; + blueShifter = 8-_pixFormat.blueMaskSize; + alphaShifter = 8-_pixFormat.alphaMaskSize; + + if (_pixFormat.alphaMaskSize != 0) + alphaMasker = ~(OG_MASKS[_pixFormat.alphaMaskSize] << alphaFieldPosition); + else + alphaMasker = ~0; + + if (1 == bytesPerPix) { + pixFmtID = 0x08080808; + // turn anti aliasing off by default for 8bpp modes + SetAntiAliasing(false); + } else { + pixFmtID = (redFieldPosition) | + (greenFieldPosition << 8) | + (blueFieldPosition << 16) | + (alphaFieldPosition << 24); + SetAntiAliasing(true); + } // else + + Clear(Pack(0, 0, 0)); + + owner = this; + status = true; + } while(false); + +#ifdef __UBIXOS_KERNEL__ + if (newBuffer) kfree(newBuffer); +#else + if (newBuffer) free(newBuffer); +#endif + if (newLineOfs) delete [] newLineOfs; + if (newPal) delete [] newPal; + if (newAttributes) delete newAttributes; + + return status; +} // ogSurface::Create + +void +ogSurface::CubicBezierCurve(int32 x1, int32 y1, int32 x2, int32 y2, + int32 x3, int32 y3, int32 x4, int32 y4, + uInt32 segments, uInt32 colour) { + float tX1, tY1, tX2, tY2, tX3, tY3, mu, mu2, mu3, mudelta; + int32 xStart, yStart, xEnd, yEnd; + uInt32 n; + if (segments<1) return; + if (segments>128) segments=128; + + mudelta = 1.0/segments; + mu = mudelta; + tX1 =-x1+3*x2-3*x3+x4; + tY1 =-y1+3*y2-3*y3+y4; + tX2 =3*x1-6*x2+3*x3; + tY2 =3*y1-6*y2+3*y3; + tX3 =-3*x1+3*x2; + tY3 =-3*y1+3*y2; + + xStart = x1; + yStart = y1; + + for (n=1; n(mu3*tX1+mu2*tX2+mu*tX3+x1 +0.5f); + yEnd = static_cast(mu3*tY1+mu2*tY2+mu*tY3+y1 +0.5f); + Line(xStart, yStart, xEnd, yEnd, colour); + mu += mudelta; + xStart = xEnd; + yStart = yEnd; + } // for + return; +} // ogSurface::CubicBezierCurve + +void +ogSurface::Curve(int32 x1, int32 y1, int32 x2, int32 y2, int32 x3, int32 y3, + uInt32 segments, uInt32 colour) { + int64 ex, ey, fx, fy; + int64 t1, t2; + + if (segments<2) segments=2; else if (segments>128) segments=128; + x2 = (x2*2)-((x1+x3)/2); + y2 = (y2*2)-((y1+y3)/2); + + ex = ((int64)(x2-x1) << 17) / segments; + ey = ((int64)(y2-y1) << 17) / (int64)segments; + fx = ((int64)(x3-(2*x2)+x1) << 16) / (segments*segments); + fy = ((int64)(y3-(2*y2)+y1) << 16) / (int64)(segments*segments); + + while (--segments>0) { + t1=x3; + t2=y3; + x3=((int64)((fx*segments+ex)*segments) / 65536L)+x1; + y3=((int64)((fy*segments+ey)*segments) / 65536L)+y1; + Line(t1, t2, x3, y3, colour); + } // while + Line(x3,y3,x1,y1,colour); + return; + +} // ogSurface::Curve + +void +ogSurface::FillCircle(int32 xCenter, int32 yCenter, + uInt32 radius, uInt32 colour) { + int32 x, y, d; + x = 0; + y = radius; + d = 4*(1-radius); + + while (y >= 0) { + if (d + y > 0) { + HLine(xCenter-x, xCenter+x, yCenter-y, colour); + if (y != 0) HLine(xCenter-x, xCenter+x, yCenter+y, colour); + + --y; + d -= 4*y+1; + } // if + + + if (x > d) { + ++x; + d += 4*x+1; + } // if + } // while + return; +} // ogSurface::FillCircle + +#if 0 +!-/* Scan converts an edge from (X1,Y1) to (X2,Y2), not including the +!- * point at (X2,Y2). This avoids overlapping the end of one line with +!- * the start of the next, and causes the bottom scan line of the +!- * polygon not to be drawn. If SkipFirst != 0, the point at (X1,Y1) +!- * isn't drawn. For each scan line, the pixel closest to the scanned +!- * line without being to the left of the scanned line is chosen +!- */ +!-static void index_forward(int32 & index, uInt32 numPoints) { +!- index = (index + 1) % numPoints; +!- return; +!-} // index_forward +!- +!-static void index_backward(int32 & index, uInt32 numPoints) { +!- index = (index - 1 + numPoints) % numPoints; +!- return; +!-} // index_forward +!- +!-static void index_move(int32 & index, uInt32 numPoints, int32 direction) { +!- if (direction > 0) +!- index_forward(index, numPoints); +!- else +!- index_backward(index, numPoints); +!- return; +!-} // index_move +!- +!-static void scanEdge(int32 x1, int32 y1, int32 x2, int32 y2, +!- uInt32 & eIdx, int32 * xList) { +!- int32 y, deltaX, deltaY; +!- float inverseSlope; +!- +!- deltaX = x2 - x1; +!- deltaY = y2 - y1; +!- if (deltaY <= 0) return; +!- inverseSlope = deltaX / deltaY; +!- +!- // Store the X coordinate of the pixel closest to but not to the +!- // left of the line for each Y coordinate between Y1 and Y2, not +!- // including Y2 +!- y = y1; +!- do { +!- xList[eIdx] = x1+ (int32)(0.5f+((y-y1)*inverseSlope)); +!- y++; +!- eIdx++; +!- } while (y maxPointY) { +!- maxIndex = i; +!- maxPointY = polyPoints[i].y; // new bottom +!- } // else if +!- } // for +!- +!- if (minPointY == maxPointY) return; +!- +!- // scan in ascending order to find the last top-edge point +!- minIndexR = minIndexL; +!- while (polyPoints[minIndexR].y == minPointY) index_forward(minIndexR, numPoints); +!- index_backward(minIndexR, numPoints); // back up to last top-edge point +!- +!- // now scan in descending order to find the first top-edge point +!- while (polyPoints[minIndexL].y == minPointY) index_backward(minIndexL, numPoints); +!- index_forward(minIndexL, numPoints); +!- +!- // figure out which direction through the vertex list from the top +!- // vertex is the left edge and which is the right +!- leftEdgeDir = -1; +!- +!- topIsFlat = (polyPoints[minIndexL].x==polyPoints[minIndexR].x) ? 0 : 1; +!- if (topIsFlat==1) { +!- if (polyPoints[minIndexL].x > polyPoints[minIndexR].x) { +!- leftEdgeDir = 1; +!- temp = minIndexL; +!- minIndexL = minIndexR; +!- minIndexR = temp; +!- } +!- } else { +!- // Point to the downward end of the first line of each of the +!- // two edges down from the top +!- nextIndex = minIndexR; +!- index_forward(nextIndex, numPoints); +!- prevIndex = minIndexL; +!- index_forward(prevIndex, numPoints); +!- +!- deltaXN = polyPoints[nextIndex].x - polyPoints[minIndexL].x; +!- deltaYN = polyPoints[nextIndex].y - polyPoints[minIndexL].y; +!- deltaXP = polyPoints[prevIndex].x - polyPoints[minIndexL].x; +!- deltaYP = polyPoints[prevIndex].y - polyPoints[minIndexL].y; +!- if (deltaXN * deltaYP - deltaYN * deltaXP < 0) { +!- leftEdgeDir = 1; +!- temp = minIndexL; +!- minIndexL = minIndexR; +!- minIndexR = temp; +!- } // if +!- } // else +!- +!- /* Set the # of scan lines in the polygon, skipping the bottom edge +!- * and also skipping the top vertex if the top isn't flat because +!- * in that case the top vertex has a right edge component, and set +!- * the top scan line to draw, which is likewise the second line of +!- * the polygon unles the top if flat +!- */ +!- +!- workingHLineList.length = maxPointY - minPointY; +!- if (workingHLineList.length <= 0) return; +!- workingHLineList.yStart = minPointY; +!- +!- // get memory in which to srote the line list we generate +!- workingHLineList.xLeft = workingHLineList.xRight = NULL; +!- if ((workingHLineList.xLeft = new int32[workingHLineList.length]) == NULL) return; +!- if ((workingHLineList.xRight = new int32[workingHLineList.length]) == NULL) { +!- delete workingHLineList.xLeft; +!- return; +!- } +!- memset(workingHLineList.xLeft,0,workingHLineList.length*sizeof(int32)); +!- memset(workingHLineList.xRight,0,workingHLineList.length*sizeof(int32)); +!- +!- // scan the left edge and store the boundary points int he list +!- // Initial pointer for storing scan converted left-edge coords +!- edgePointIdx = 0; +!- +!- // start from the top of the left edge +!- curIndex = prevIndex = minIndexL; +!- +!- do { +!- index_move(curIndex, numPoints, leftEdgeDir); +!- scanEdge(polyPoints[prevIndex].x, +!- polyPoints[prevIndex].y, +!- polyPoints[curIndex].x, +!- polyPoints[curIndex].y, +!- edgePointIdx, +!- workingHLineList.xLeft); +!- prevIndex = curIndex; +!- } while (curIndex != maxIndex); +!- +!- edgePointIdx = 0; +!- curIndex = prevIndex = minIndexR; +!- // Scan convert the right edge, top to bottom. X coordinates are +!- // adjusted 1 to the left, effectively causing scan conversion of +!- // the nearest points to the left of but not exactly on the edge } +!- do { +!- index_move(curIndex, numPoints, -leftEdgeDir); +!- scanEdge(polyPoints[prevIndex].x, +!- polyPoints[prevIndex].y, +!- polyPoints[curIndex].x, +!- polyPoints[curIndex].y, +!- edgePointIdx, +!- workingHLineList.xRight); +!- prevIndex = curIndex; +!- } while (curIndex != maxIndex); +!- +!- ogPolygon(numPoints, polyPoints, colour); +!- +!- for (i = 0; i < workingHLineList.length; i++) { +!- HLine(workingHLineList.xLeft[i], workingHLineList.xRight[i], +!- workingHLineList.yStart+i, colour); +!- } // for +!- +!- ogPolygon(numPoints, polyPoints, colour); +!- +!- delete workingHLineList.xLeft; +!- delete workingHLineList.xRight; +!- +!- return; +!-} // ogSurface::FillConvexPolygon +#endif + +void +ogSurface::FillGouraudPolygon(uInt32 numPoints, ogPoint2d* polyPoints, ogRGBA8 * colours) { + + ogEdgeTable * edges; + int32 currentY = ~0; + + if (numPoints < 3) return; + + edges = new ogEdgeTable(); + + if (NULL == edges) return; // sanity check + + edges->BuildGET_G(numPoints, polyPoints, colours); + + if (edges->globalEdges != NULL) + currentY = edges->globalEdges->startY; + + while ((edges->globalEdges != NULL) || (edges->activeEdges != NULL)) { + edges->MoveXSortedToAET(currentY); + edges->ScanOutAET_G(*this, currentY); + edges->AdvanceAET(); + edges->XSortAET(); + ++currentY; + if (currentY>(int32)maxY) break; // if we've gone past the bottom, stop + } // while + + delete edges; + return; +} // ogSurface::FillGouraudPolygon + +void +ogSurface::FillPolygon(uInt32 numPoints, ogPoint2d* polyPoints, uInt32 colour) { + ogEdgeTable * edges; + int32 currentY = ~0; + + if (numPoints<3) return; + + if (!IsBlending()) Polygon(numPoints, polyPoints, colour); + + edges = new ogEdgeTable(); + + if (NULL == edges) return; // sanity check + + edges->BuildGET(numPoints, polyPoints); + + if (edges->globalEdges != NULL) + currentY = edges->globalEdges->startY; + + while ((edges->globalEdges != NULL) || (edges->activeEdges != NULL)) { + edges->MoveXSortedToAET(currentY); + edges->ScanOutAET(*this, currentY, colour); + edges->AdvanceAET(); + edges->XSortAET(); + currentY++; + if (currentY>(int32)maxY) break; // if we've gone past the bottom, stop + } // while + delete edges; + return; +} // ogSurface::FillPolygon + +void +ogSurface::FillRect(int32 x1, int32 y1, int32 x2, int32 y2, uInt32 colour) { + int32 yy, tmp; + + if (x2 < x1) { + tmp= x2; + x2 = x1; + x1 = tmp; + } // if + + if (y2 < y1) { + tmp= y2; + y2 = y1; + y1 = tmp; + } // if + + if ((y2 < 0) || (y1 > (int32)maxY)) return; + if (y1 < 0) y1=0; + if (y2 > (int32)maxY) y2=maxY; + for (yy = y1; yy <= y2; yy++) + HLine(x1, x2, yy, colour); +} // ogSurface::FillRect + +void ogSurface::FillTriangle(int32 x1, int32 y1, int32 x2, int32 y2, + int32 x3, int32 y3, uInt32 colour) { + ogPoint2d points[3]; + points[0].x = x1; + points[0].y = y1; + points[1].x = x2; + points[1].y = y2; + points[2].x = x3; + points[2].y = y3; + + FillPolygon(3, points, colour); + + return; +} // ogSurface::FillTriangle + +uInt32 +ogSurface::GetAlpha(void) { + if (attributes != NULL) + return attributes->defaultAlpha; + else + return 255L; +} // ogSurface::GetAlpha + +ogErrorCode +ogSurface::GetLastError(void) { + ogErrorCode tmp = lastError; + lastError = ogOK; + return tmp; +} // ogSurface::GetLastError + +void +ogSurface::GetPalette(ogRGBA8 _pal[256]) { +#ifdef __UBIXOS_KERNEL__ + kmemcpy(_pal, pal, sizeof(_pal)); +#else + memcpy(_pal, pal, sizeof(_pal)); +#endif + return; +} // ogSurface::GetPalette + +void +ogSurface::GetPixFmt(ogPixelFmt& pixfmt) { + pixfmt.BPP = BPP; + pixfmt.redFieldPosition = redFieldPosition; + pixfmt.greenFieldPosition = greenFieldPosition; + pixfmt.blueFieldPosition = blueFieldPosition; + pixfmt.alphaFieldPosition = alphaFieldPosition; + pixfmt.redMaskSize = 8-redShifter; + pixfmt.greenMaskSize = 8-greenShifter; + pixfmt.blueMaskSize = 8-blueShifter; + pixfmt.alphaMaskSize = 8-alphaShifter; + return; +} // ogSurface::GetPixFmt + +uInt32 +ogSurface::GetPixel(int32 x, int32 y) { + uInt32 result; + if (!Avail()) return GetTransparentColor(); + + if (((uInt32)x>maxX) || ((uInt32)y>maxY)) return GetTransparentColor(); + + switch (bytesPerPix) { + case 4: + __asm__ __volatile__( + " shl $2, %%ecx \n" // shl ecx, 2 {adjust for pixel size} + " add %%esi, %%edi \n" // add edi, esi + " add %%ecx, %%edi \n" // add edi, ecx + " mov (%%edi),%%eax \n" // eax,word ptr [edi] + " mov %%eax, %3 \n" // mov result, eax + : + : "D" (buffer), "S" (lineOfs[y]), // %0, %1 + "c" (x), "m" (result) // %2, %3 + ); + break; + case 3: + __asm__ __volatile__( + " leal (%%ecx, %%ecx, 2), %%ecx \n" // lea ecx, [ecx + ecx*2] +// " mov %%ecx, %%eax \n" // mov eax, ecx - adjust for pixel size +// " add %%ecx, %%ecx \n" // add ecx, ecx - adjust for pixel size +// " add %%eax, %%ecx \n" // add ecx, eax - adjust for pixel size + " add %%esi, %%edi \n" // add edi, esi + " add %%ecx, %%edi \n" // add edi, ecx + " movzwl (%%edi),%%eax \n" // edx,word ptr [edi] + " xor %%eax, %%eax \n" + " mov 2(%%edi), %%al \n" // mov al, [edi+2] + " shl $16, %%eax \n" // shl eax, 16 + " mov (%%edi), %%ax \n" // mov ax, [edi] + " mov %%eax, %3 \n" // mov result, eax + : + : "D" (buffer), "S" (lineOfs[y]), // %0, %1 + "c" (x), "m" (result) // %2, %3 + ); + break; + case 2: + __asm__ __volatile__( + " add %%esi, %%edi \n" // add edi, esi + " add %%ecx, %%ecx \n" // add ecx, ecx {adjust for pixel size} + " add %%ecx, %%edi \n" // add edi, ecx + " movzwl (%%edi),%%eax \n" // movzx edx,word ptr [edi] + " mov %%eax, %0 \n" // mov result, eax + : "=m" (result) + : "D" (buffer), "S" (lineOfs[y]), // %0, %1 + "c" (x) // , "m" (result) // %2, %3 + ); + break; + case 1: + __asm__ __volatile__( + " add %%esi, %%edi \n" // add edi, esi + " add %%ecx, %%edi \n" // add edi, ecx + " movzbl (%%edi),%%eax \n" // movzx edx,byte ptr [edi] + " mov %%eax, %3 \n" // mov result, eax + : + : "D" (buffer), "S" (lineOfs[y]), // %0, %1 + "c" (x), "m" (result) // %2, %3 + ); + break; + } // switch + return result; +} // ogSurface::GetPixel + +void * +ogSurface::GetPtr(uInt32 x, uInt32 y) { +// return (Avail() ? ( (uInt8*)buffer+(lineOfs[y]+x*((BPP+7) >> 3)) ) : NULL ); + return ((uInt8*)buffer+(lineOfs[y]+x*bytesPerPix)); +} // ogSurface::GetPtr + +uInt32 +ogSurface::GetTransparentColor(void) { + if (attributes) + return attributes->transparentColor; + else + return 0; +} // ogSurface::GetTransparentColor + +void +ogSurface::HFlip(void) { + void * tmpBuf1; + void * tmpBuf2; + uInt32 xWidth, count; + + if (!Avail()) return; + + xWidth = (maxX+1)*bytesPerPix; + +#ifdef __UBIXOS_KERNEL__ + tmpBuf1 = kmalloc(xWidth,sysID); + tmpBuf2 = kmalloc(xWidth,sysID); +#else + tmpBuf1 = malloc(xWidth); + tmpBuf2 = malloc(xWidth); +#endif + + if ((tmpBuf1 != NULL) && (tmpBuf2 != NULL)) + for (count = 0; count <= (maxY/2); count++) { + CopyLineFrom(0, count, tmpBuf1, xWidth); + CopyLineFrom(0, maxY-count,tmpBuf2, xWidth); + CopyLineTo(0, maxY-count,tmpBuf1, xWidth); + CopyLineTo(0, count, tmpBuf2, xWidth); + } // for count + +#ifdef __UBIXOS_KERNEL__ + kfree(tmpBuf2); + kfree(tmpBuf1); +#else + free(tmpBuf2); + free(tmpBuf1); +#endif + + return; +} // ogSurface::HFlip + +void +ogSurface::HLine(int32 x1, int32 x2, int32 y, uInt32 colour) { + int32 tmp; + uInt8 r, g, b, a; + + if (!Avail()) return; + if ((uInt32)y>maxY) return; + + if (x1 > x2) { + tmp= x1; + x1 = x2; + x2 = tmp; + } // if + + if (x1 < 0) x1 = 0; + if (x2 > (int32)maxX) x2 = maxX; + if (x2 < x1) return; + + if (IsBlending()) { + Unpack(colour, r, g, b, a); + if (0 == a) return; + if (255 == a) { + for (tmp = x1; tmp <= x2; tmp++) + RawSetPixel(tmp, y, r, g, b, a); + return; + } // if a == 255 + } // if blending + + __asm__ __volatile__("cld \n"); + switch (bytesPerPix) { + case 4: + __asm__ __volatile__( + " sub %%ebx, %%ecx \n" // sub ecx, ebx + " add %%esi, %%edi \n" // add edi, esi + " inc %%ecx \n" + " shl $2, %%ebx \n" // shl ebx, 2 + " add %%ebx, %%edi \n" // add edi, ebx + " rep \n" + " stosl \n" + : + : "D" (buffer), "S" (lineOfs[y]), // %0, %1 + "a" (colour), "b" (x1), // %2, %3 + "c" (x2) // %4 + ); + break; + case 3: + __asm__ __volatile__( + " sub %%ebx, %%ecx \n" // sub ecx, ebx + " add %%esi, %%edi \n" // add edi, esi + " add %%ebx, %%ebx \n" // add ebx, ebx - pix size + " inc %%ecx \n" // inc ecx + " add %%edx, %%ebx \n" // add ebx, edx - pix size + " add %%ebx, %%edi \n" // add edi, ebx + " mov %%eax, %%ebx \n" // mov ebx, eax + " shr $16, %%ebx \n" // shr ebx, 16 + "hLlop24: \n" + " mov %%ax, (%%edi) \n" // mov [edi], ax + " mov %%bl, 2(%%edi)\n" // mov [edi+2], bl + " add $3, %%edi \n" // add edi, 3 + " dec %%ecx \n" // dec ecx + " jnz hLlop24 \n" + : + : "D" (buffer), "S" (lineOfs[y]), // %0, %1 + "a" (colour), "b" (x1), // %2, %3 + "c" (x2), "d" (x1) // %4, %5 + ); + break; + case 2: + __asm__ __volatile__( + " sub %%ebx, %%ecx \n" // sub ecx, ebx + " add %%ebx, %%ebx \n" // add ebx, ebx - pix size + " inc %%ecx \n" // inc ecx + " add %%ebx, %%edi \n" // add edi, ebx + " add %%esi, %%edi \n" // add edi, esi + " xor %%edx, %%edx \n" // xor edx, edx + " mov %%ax, %%dx \n" // mov dx, ax + " shl $16, %%eax \n" // shl eax, 16 + " add %%edx, %%eax \n" // add eax, edx + + " shr $1, %%ecx \n" // shr ecx, 1 + " rep \n" + " stosl \n" + " jnc hLnoc16 \n" + " stosw \n" + "hLnoc16: \n" + : + : "D" (buffer), "S" (lineOfs[y]), // %0, %1 + "a" (colour), "b" (x1), // %2, %3 + "c" (x2) // %4 + ); + break; + case 1: + __asm__ __volatile__( + " add %%ebx, %%edi \n" // add edi, ebx + " add %%esi, %%edi \n" // add edi, esi + " and $0xff, %%eax \n" // and eax, 0ffh + " sub %%ebx, %%ecx \n" // sub ecx, ebx + " mov %%al, %%ah \n" // mov ah, al + " inc %%ecx \n" // inc ecx + " mov %%eax, %%ebx \n" // mov ebx, eax + " shl $16, %%ebx \n" // shl ebx, 16 + " add %%ebx, %%eax \n" // add eax, ebx + + " mov %%ecx, %%edx \n" // mov edx, ecx + " mov $4, %%ecx \n" // mov ecx, 4 + " sub %%edi, %%ecx \n" // sub ecx, edi + " and $3, %%ecx \n" // and ecx, 3 + " sub %%ecx, %%edx \n" // sub edx, ecx + " jle LEndBytes \n" + " rep \n" + " stosb \n" + " mov %%edx, %%ecx \n" // mov ecx, edx + " and $3, %%edx \n" // and edx, 3 + " shr $2, %%ecx \n" // shr ecx, 2 + " rep \n" + " stosl \n" + "LEndBytes: \n" + " add %%edx, %%ecx \n" // add ecx, edx + " rep \n" + " stosb \n" + : + : "D" (buffer), "S" (lineOfs[y]), // %0, %1 + "a" (colour), "b" (x1), // %2, %3 + "c" (x2) + ); + break; + } // switch + return; +} // ogSurface::HLine + +bool +ogSurface::IsAntiAliasing(void) { + if (attributes) + return attributes->antiAlias; + else + return false; +} // ogSurface::IsAntiAliasing + +bool +ogSurface::IsBlending(void) { + if (attributes) + return attributes->blending; + else + return false; +} // ogSurface::IsBlending + +void +ogSurface::Line(int32 x1, int32 y1, int32 x2, int32 y2, uInt32 colour) { + if (ClipLine(x1,y1,x2,y2)) { + if (IsAntiAliasing()) + AARawLine(x1, y1, x2, y2, colour); + else + RawLine(x1, y1, x2, y2, colour); + } // if clipLine + return; +} // ogSurface::Line + +bool +ogSurface::LoadPalette(const char *palfile) { + ogRGBA8 oldPalette[256]; +#ifdef __UBIXOS_KERNEL__ + fileDescriptor *f; +#else + FILE *f; +#endif + uInt32 lresult; + bool result; + + if (!fileExists(palfile)) { + SetLastError(ogFileNotFound); + return false; + } // if + + if (NULL == pal) { + pal = new ogRGBA8[256]; + if (NULL == pal) { + SetLastError(ogMemAllocFail); + return false; + } // if + SetPalette(DEFAULT_PALETTE); + // memcpy(pal, DEFAULT_PALETTE, sizeof(ogRGBA8)*256); + } // if + + GetPalette(oldPalette); + // memcpy(&oldPalette, pal, sizeof(ogRGBA8)*256); + + if ((f = fopen(palfile, "rb"))==NULL) return false; + + lresult = fread(pal, sizeof(ogRGBA8), 256, f); + result = (256 == lresult); + + if (!result) { + SetLastError(ogFileReadError); + SetPalette(oldPalette); + // memcpy(pal, &oldPalette, sizeof(ogRGBA8)*256); + } // if + + fclose(f); + return result; +} // ogSurface::LoadPalette + +void +ogSurface::Polygon(uInt32 numPoints, ogPoint2d* polyPoints, uInt32 colour) { + uInt32 count; + + if (1 == numPoints) + SetPixel(polyPoints[0].x, polyPoints[0].y, colour); + else + for (count = 0; count < numPoints; count++) + Line(polyPoints[count].x, polyPoints[count].y, + polyPoints[(count+1) % numPoints].x, + polyPoints[(count+1) % numPoints].y, + colour); + return; +} // ogSurface::Polygon + +void +ogSurface::Rect(int32 x1, int32 y1, int32 x2, int32 y2, uInt32 colour) { + int32 tmp; + + if ((x1 == x2) || (y1 == y2)) { + + if ((x1 == x2) && (y1 == y2)) + SetPixel(x1, y1, colour); + else + Line(x1, y1, x2, y2, colour); + + } else { + + if (y1 > y2) { + tmp= y1; + y1 = y2; + y2 = tmp; + } // if + + HLine(x1, x2, y1, colour); // Horizline has built in clipping + VLine(x1, y1+1, y2-1, colour); // vertline has built in clipping too + VLine(x2, y1+1, y2-1, colour); + HLine(x1, x2, y2, colour); + + } // else + + return; +} // ogSurface::Rect + +uInt32 +ogSurface::Pack(uInt8 red, uInt8 green, uInt8 blue) { + uInt32 idx, colour; + uInt32 rd, gd, bd, dist, newdist; + + colour = 0; + switch (bytesPerPix) { + case 4: + colour = ( (red << redFieldPosition) | + (green << greenFieldPosition) | + (blue << blueFieldPosition) | + (GetAlpha() << alphaFieldPosition) ); + break; + case 3: + colour = ( (red << redFieldPosition) | + (green << greenFieldPosition) | + (blue << blueFieldPosition) ); + break; + case 2: + colour = ((red >> redShifter) << redFieldPosition) | + ((green >> greenShifter) << greenFieldPosition) | + ((blue >> blueShifter) << blueFieldPosition) | + ((GetAlpha() >> alphaShifter) << alphaFieldPosition); + break; + case 1: + colour = 0; + dist = 255+255+255; + for (idx = 0; idx <= 255; idx++) { + rd = abs(red-pal[idx].red); + gd = abs(green-pal[idx].green); + bd = abs(blue-pal[idx].blue); + newdist = rd + gd + bd; + + if (newdist < dist) { + dist = newdist; + colour = idx; + } // if + } // for + break; + } // switch + + return colour; + +} // ogSurface::RGB + +uInt32 +ogSurface::Pack(uInt8 red, uInt8 green, uInt8 blue, uInt8 alpha) { + uInt32 idx, colour; + uInt32 rd, gd, bd, dist, newdist; + + colour = 0; + switch (bytesPerPix) { + case 4: + colour = ( (red << redFieldPosition) | + (green << greenFieldPosition) | + (blue << blueFieldPosition) | + (alpha << alphaFieldPosition) ); + break; + case 3: + colour = ( (red << redFieldPosition) | + (green << greenFieldPosition) | + (blue << blueFieldPosition) ); + break; + case 2: + colour = ((red >> redShifter) << redFieldPosition) | + ((green >> greenShifter) << greenFieldPosition) | + ((blue >> blueShifter) << blueFieldPosition) | + ((alpha >> alphaShifter) << alphaFieldPosition); + break; + case 1: + colour = 0; + dist = 255+255+255; + for (idx = 0; idx <= 255; idx++) { + rd = abs(red-pal[idx].red); + gd = abs(green-pal[idx].green); + bd = abs(blue-pal[idx].blue); + newdist = rd + gd + bd; + + if (newdist < dist) { + dist = newdist; + colour = idx; + } // if + } // for + break; + } // switch + + return colour; +} // ogSurface::Pack + +bool +ogSurface::SavePalette(const char *palfile) { +#ifdef __UBIXOS_KERNEL__ + fileDescriptor *f; +#else + FILE * f; +#endif + uInt32 lresult; + + if (NULL == pal) { + SetLastError(ogNoPalette); + return false; + } + + if ((f = fopen(palfile, "wb"))==NULL) return false; + lresult = fwrite(pal,sizeof(ogRGBA8),256,f); + fclose(f); + + if (256 == lresult) + return true; + else { + SetLastError(ogFileWriteError); + return false; + } // else + +} // ogSurface::SavePal + +void +ogSurface::Scale(ogSurface& src) { + ScaleBuf(0, 0, maxX, maxY, src, 0, 0, src.maxX, src.maxY); + return; +} // ogSurface::Scale + +void +ogSurface::ScaleBuf(int32 dX1, int32 dY1, int32 dX2, int32 dY2, + ogSurface& src, + int32 sX1, int32 sY1, int32 sX2, int32 sY2) { + + uInt32 sWidth, dWidth; + uInt32 sHeight, dHeight; + int32 sx, sy, xx, yy; + uInt32 xInc, yInc; + uInt32 origdX1, origdY1; + ogPixelFmt pixFmt; + ogSurface * tmpBuf; + ogSurface * sBuf; + ogSurface * dBuf; + bool doCopyBuf; + + origdX1 = origdY1 = 0; // to keep the compiler from generating a warning + + if (!Avail()) return; + if (!src.Avail()) return; + + if (sX1 > sX2) { + xx = sX1; + sX1= sX2; + sX2= xx; + } + + if (sY1 > sY2) { + yy = sY1; + sY1= sY2; + sY2= yy; + } + + // if any part of the source falls outside the buffer then don't do anything + + if (((uInt32)sX1>src.maxX) || ((uInt32)sX2>src.maxX) || + ((uInt32)sY1>src.maxY) || ((uInt32)sY2>src.maxY)) return; + + if (dX1 > dX2) { + xx = dX1; + dX1= dX1; + dX2= xx; + } + + if (dY1 > dY2) { + yy = dY1; + dY1= dY2; + dY2= yy; + } + + dWidth = (dX2-dX1)+1; + if (dWidth <= 0) return; + + dHeight = (dY2-dY1)+1; + if (dHeight <= 0) return; + + sWidth = (sX2-sX1)+1; + sHeight = (sY2-sY1)+1; + + // convert into 16:16 fixed point ratio + xInc = (sWidth << 16) / dWidth; + yInc = (sHeight << 16) / dHeight; + + if (dX2 > (int32)maxX) { + xx = (xInc*(dX1-maxX)) >> 16; + sX1 -= xx; + sWidth -= xx; + dWidth -= (dX1-maxX); + dX1 = maxX; + } + + if (dY2 > (int32)maxY) { + yy = (yInc*(dY2-maxY)) >> 16; + sY2 -= yy; + sHeight -= yy; + dHeight -= (dY2-maxY); + dY2 = maxY; + } + + if (dX1 < 0) { + xx = (xInc*(-dX1)) >> 16; + sX1 += xx; + sWidth -= xx; + dWidth += dX1; + dX1 = 0; + } + + if (dY1<0) { + yy = (yInc*(-dY1)) >> 16; + sY1 += yy; + sHeight -= yy; + dHeight += dY1; + dY1 = 0; + } + + if ((dWidth <= 0) || (dHeight <= 0)) return; + if ((sWidth <= 0) || (sHeight <= 0)) return; + + // Do a quick check to see if the scale is 1:1 .. in that case just copy + // the image + + if ((dWidth == sWidth) && (dHeight == sHeight)) { + CopyBuf(dX1, dY1, src,sX1,sY1,sX2,sY2); + return; + } + + tmpBuf = NULL; + + /* + * Alright.. this is how we're going to optimize the case of different + * pixel formats. We are going to use copyBuf() to automagically do + * the conversion for us using tmpBuf. Here's how it works: + * If the source buffer is smaller than the dest buffer (ie, we're making + * something bigger) we will convert the source buffer first into the dest + * buffer's pixel format. Then we do the scaling. + * If the source buffer is larger than the dest buffer (ie, we're making + * something smaller) we will scale first and then use copyBuf to do + * the conversion. + * This method puts the onus of conversion on the copyBuf() function which, + * while not excessively fast, does the job. + * The case in which the source and dest are the same size is handled above. + * + */ + if (pixFmtID != src.pixFmtID) { + + tmpBuf = new ogSurface(); + if (tmpBuf==NULL) return; + if (sWidth*sHeight*src.bytesPerPix <= dWidth*dHeight*bytesPerPix) { + // if the number of pixels in the source buffer is less than the + // number of pixels in the dest buffer then... + GetPixFmt(pixFmt); + if (!tmpBuf->Create(sWidth, sHeight, pixFmt)) return; + tmpBuf->CopyPalette(src); + tmpBuf->CopyBuf(0, 0, src, sX1, sY1, sX2, sY2); + sX2 -= sX1; + sY2 -= sY1; + sX1 = 0; + sY1 = 0; + sBuf = tmpBuf; + dBuf = this; + doCopyBuf = false; // do we do a copyBuf later? + } else { + src.GetPixFmt(pixFmt); + if (!tmpBuf->Create(dWidth,dHeight,pixFmt)) return; + tmpBuf->CopyPalette(*this); + origdX1 = dX1; + origdY1 = dY1; + dX1 = 0; + dY1 = 0; + dX2 = tmpBuf->maxX; + dY2 = tmpBuf->maxY; + sBuf = &src; + dBuf = tmpBuf; + doCopyBuf = true; + } // else + } else { + // pixel formats are identical + sBuf = &src; + dBuf = this; + doCopyBuf = false; + } // else + + sy = sY1 << 16; + + for (yy = dY1; yy <= dY2; yy++) { + sx = 0; + for (xx = dX1; xx <= dX2; xx++) { + dBuf->RawSetPixel(xx, yy, + sBuf->RawGetPixel(sX1+(sx >> 16),(sy>>16))); + sx += xInc; + } // for xx + sy += yInc; + } // for yy + + if ((doCopyBuf) && (tmpBuf != NULL)) + CopyBuf(origdX1, origdY1, *tmpBuf, 0, 0, tmpBuf->maxX, tmpBuf->maxY); + + delete tmpBuf; + return; +} // ogSurface::ScaleBuf + +uInt32 +ogSurface::SetAlpha(uInt32 _newAlpha) { + uInt32 tmp; + + if (attributes) { + tmp = attributes->defaultAlpha; + attributes->defaultAlpha = _newAlpha; + return tmp; + } else return _newAlpha; +} // ogSurface::SetAlpha + +bool +ogSurface::SetAntiAliasing(bool _antiAliasing) { + bool tmp; + + if (attributes) { + tmp = attributes->antiAlias; + attributes->antiAlias = _antiAliasing; + return tmp; + } else return _antiAliasing; +} // ogSurface::SetAntiAliasing + +bool +ogSurface::SetBlending(bool _blending) { + bool tmp; + + if (attributes) { + tmp = attributes->blending; + attributes->blending = _blending; + return tmp; + } else return _blending; + +} // ogSurface::SetBlending; + +ogErrorCode +ogSurface::SetLastError(ogErrorCode latestError) { + ogErrorCode tmp = lastError; + lastError = latestError; + return tmp; +} // ogSurface::SetLastError + +void +ogSurface::SetPalette(const ogRGBA8 newPal[256]) { + if (NULL == pal) return; +#ifdef __UBIXOS_KERNEL__ + kmemcpy(pal, newPal, sizeof(pal)); +#else + memcpy(pal, newPal, sizeof(pal)); +#endif + return; +} // ogSurface::SetPalette + +void +ogSurface::SetPixel(int32 x, int32 y, uInt32 colour) { + uInt32 newR, newG, newB, inverseA; + uInt8 sR, sG, sB, sA; + uInt8 dR, dG, dB; + + if (!Avail()) return; + + if (((uInt32)x>maxX) || ((uInt32)y>maxY)) return; + + do { + if (IsBlending()) { + Unpack(colour, sR, sG, sB, sA); + if (0 == sA) return; + if (255 == sA) break; + inverseA = 255 - sA; + Unpack(RawGetPixel(x, y), dR, dG, dB); + newR = (dR * inverseA + sR * sA) >> 8; + newG = (dG * inverseA + sG * sA) >> 8; + newB = (dB * inverseA + sB * sA) >> 8; + colour = Pack(newR, newG, newB, inverseA); + } // if + } while (false); + + switch (bytesPerPix) { + case 4: + __asm__ __volatile__( + // { Calculate offset, prepare the pixel to be drawn } + " shl $2, %%ecx \n" // shl eax, 2 {adjust for pixel size} + " add %%esi, %%edi \n" // add edi, esi + " add %%ecx, %%edi \n" // add edi, ecx + // { Draw the pixel } + " mov %%eax, (%%edi) \n" // mov [edi], eax + : + : "D" (buffer), "S" (lineOfs[y]), // %0, %1 + "c" (x), "a" (colour) // %2, %3 + ); + break; + case 3: + __asm__ __volatile__( + // Calculate offset, prepare the pixel to be drawn + " leal (%%ecx, %%ecx, 2), %%ecx \n" // lea ecx, [ecx + ecx*2] + " add %%esi, %%edi \n" // add edi, esi + " add %%ecx, %%edi \n" // add edi, ecx + // { Draw the pixel } + " mov %%ax, (%%edi) \n" // mov [edi], ax + " shr $16, %%eax \n" // shr eax, 16 + " mov %%al, 2(%%edi)\n" // mov [edi+2],al + : + : "D" (buffer), "S" (lineOfs[y]), // %0, %1 + "c" (x), "a" (colour) // %2, %3 + ); + break; + case 2: + __asm__ __volatile__( + // { Calculate offset, prepare the pixel to be drawn } + " add %%ecx, %%ecx \n" // add ecx, ecx {adjust for pixel size} + " add %%esi, %%edi \n" // add edi, esi + // " mov %3, %%eax \n" // mov eax, colour + " add %%ecx, %%edi \n" // add edi, ecx + // { Draw the pixel } + " mov %%ax, (%%edi) \n" // mov [edi], ax + : + : "D" (buffer), "S" (lineOfs[y]), // %0, %1 + "c" (x), "a" (colour) // %2, %3 + ); + break; + case 1: + __asm__ __volatile__( + // { Calculate offset, prepare the pixel to be drawn } + // " add (%%esi,%%ebx,4), %%edi \n" // add edi, [esi + ebx * 4] + " add %%esi, %%edi \n" // add edi, esi + " add %%ecx, %%edi \n" // add edi, ecx + // { Draw the pixel } + " mov %%al, (%%edi) \n" // mov [edi], al + : + : "D" (buffer), "S" (lineOfs[y]), // %0, %1 + "c" (x), "a" (colour) // %2, %3 + ); + break; + } // switch + return; +} // ogSurface::SetPixel + +void +ogSurface::SetPixel(int32 x, int32 y, uInt8 r, uInt8 g, uInt8 b, uInt8 a) { + if (!Avail()) return; + if (((uInt32)x>maxX) || ((uInt32)y>maxY)) return; + RawSetPixel(x, y, r, g, b, a); + return; +} // ogSurface::SetPixel + +void +ogSurface::SetPalette(uInt8 colour, uInt8 red, uInt8 green, uInt8 blue, uInt8 alpha) { + if (NULL == pal) return; + pal[colour].red = red; + pal[colour].green = green; + pal[colour].blue = blue; + pal[colour].alpha = alpha; + return; +} // ogSurface::SetPalette + +void +ogSurface::SetPalette(uInt8 colour, uInt8 red, uInt8 green, uInt8 blue) { + if (NULL == pal) return; + pal[colour].red = red; + pal[colour].green = green; + pal[colour].blue = blue; + pal[colour].alpha = GetAlpha(); + return; +} // ogSurface::SetPalette + +uInt32 +ogSurface::SetTransparentColor(uInt32 colour) { + uInt32 tmp = 0; + + if (attributes) { + tmp = attributes->transparentColor & GetAlphaMasker(); + attributes->transparentColor = colour & GetAlphaMasker(); + } // if + + return tmp; +} // ogSurface::SetTransparentColor + +static double f(double g) { return g*g*g-g; } + +void +ogSurface::Spline(uInt32 numPoints, ogPoint2d* points, uInt32 segments, + uInt32 colour) { + int32 i, oldY, oldX, x, y, j; + float part, t, xx, yy, tmp; + float * zc; + float * dx; + float * dy; + float * u; + float * wndX1; + float * wndY1; + float * px; + float * py; + + bool runOnce; + + if ((numPoints < 2) || (NULL == points)) return; + + zc = new float[numPoints]; + dx = new float[numPoints]; + dy = new float[numPoints]; + u = new float[numPoints]; + wndX1 = new float[numPoints]; + wndY1 = new float[numPoints]; + px = new float[numPoints]; + py = new float[numPoints]; + + do { + if (NULL == zc) break; + if (NULL == dx) break; + if (NULL == dy) break; + if (NULL == wndX1) break; + if (NULL == wndY1) break; + if (NULL == px) break; + if (NULL == py) break; + + for (i = 0; (uInt32)i < numPoints; i++) { + zc[i] = dx[i] = dy[i] = u[i] = wndX1[i] = wndY1[i] = px[i] = py[i] = 0.0f; + } + + runOnce = false; + oldX = oldY = 0; + + x = points[0].x; + y = points[0].y; + + for (i = 1; (uInt32)i < numPoints; i++) { + xx = points[i-1].x - points[i].x; + yy = points[i-1].y - points[i].y; + t = sqrt(xx*xx + yy*yy); + zc[i] = zc[i-1]+t; + } // for + + u[0] = zc[1] - zc[0] +1; + for (i = 1; (uInt32)i < numPoints-1; i++) { + u[i] = zc[i+1]-zc[i]+1; + tmp = 2*(zc[i+1]-zc[i-1]); + dx[i] = tmp; + dy[i] = tmp; + wndY1[i] = 6.0f*((points[i+1].y-points[i].y)/u[i]- + (points[i].y-points[i-1].y)/u[i-1]); + wndX1[i] = 6.0f*((points[i+1].x-points[i].x)/u[i]- + (points[i].x-points[i-1].x)/u[i-1]); + } // for + + for (i = 1; (uInt32)i < numPoints-2; i++) { + wndY1[i+1] = wndY1[i+1]-wndY1[i]*u[i]/dy[i]; + dy[i+1] = dy[i+1]-u[i]*u[i]/dy[i]; + wndX1[i+1] = wndX1[i+1]-wndX1[i]*u[i]/dx[i]; + dx[i+1] = dx[i+1]-u[i]*u[i]/dx[i]; + } // for + + for (i = numPoints-2; i > 0; i--) { + py[i] = (wndY1[i]-u[i]*py[i+1])/dy[i]; + px[i] = (wndX1[i]-u[i]*px[i+1])/dx[i]; + } // for + + for (i = 0; (uInt32)i < numPoints-1; i++) { + for (j = 0; (uInt32)j <= segments; j++) { + part = zc[i]-(((zc[i]-zc[i+1])/segments)*j); + t = (part-zc[i])/u[i]; + part = t * points[i+1].y + + (1.0-t)*points[i].y + + u[i] * u[i] * ( f(t) * py[i+1] + f(1.0-t) * py[i]) /6.0; +// y = Round(part); + y = static_cast(part+0.5f); + part = zc[i]-(((zc[i]-zc[i+1])/segments)*j); + t = (part-zc[i])/u[i]; + part = t*points[i+1].x+(1.0-t)*points[i].x+u[i]*u[i]*(f(t)*px[i+1]+ + f(1.0-t)*px[i])/6.0; + +// x = Round(part); + x = static_cast(part+0.5f); + if (runOnce) Line(oldX, oldY, x, y, colour); else runOnce = true; + oldX = x; + oldY = y; + } // for j + } // for i + } while (false); + + delete [] py; + delete [] px; + delete [] wndY1; + delete [] wndX1; + delete [] u; + delete [] dy; + delete [] dx; + delete [] zc; + + return; +} // ogSurface::Spline + + +void +ogSurface::Triangle(int32 x1, int32 y1, int32 x2, int32 y2, int32 x3, + int32 y3, uInt32 colour) { + + Line(x1, y1, x2, y2,colour); + Line(x2, y2, x3, y3,colour); + Line(x3, y3, x1, y1,colour); + return; +} // ogSurface::Triangle + +void +ogSurface::Unpack(uInt32 colour, uInt8& red, uInt8& green, uInt8& blue) { + + switch (bytesPerPix) { + case 4: + case 3: + red = colour >> redFieldPosition; + green = colour >> greenFieldPosition; + blue = colour >> blueFieldPosition; + break; + case 2: + red = ((colour >> redFieldPosition) << redShifter); + green = ((colour >> greenFieldPosition) << greenShifter); + blue = ((colour >> blueFieldPosition) << blueShifter); + if (red != 0) red += OG_MASKS[redShifter]; + if (green != 0) green += OG_MASKS[greenShifter]; + if (blue != 0) blue += OG_MASKS[blueShifter]; + break; + case 1: + + if (NULL == pal) { + red = 0; + green = 0; + blue = 0; + return; + } // if pal == null + + if (colour>255) colour &= 255; + red = pal[colour].red; + green = pal[colour].green; + blue = pal[colour].blue; + break; + default: + red = 0; + green = 0; + blue = 0; + } // switch + + return; +} // ogSurface::Unpack + +void +ogSurface::Unpack(uInt32 colour, uInt8& red, uInt8& green, uInt8& blue, uInt8& alpha) { + + switch (bytesPerPix) { + case 4: + red = colour >> redFieldPosition; + green = colour >> greenFieldPosition; + blue = colour >> blueFieldPosition; + alpha = colour >> alphaFieldPosition; + break; + case 3: + red = colour >> redFieldPosition; + green = colour >> greenFieldPosition; + blue = colour >> blueFieldPosition; + alpha = GetAlpha(); + break; + case 2: + red = ((colour >> redFieldPosition) << redShifter); + green = ((colour >> greenFieldPosition) << greenShifter); + blue = ((colour >> blueFieldPosition) << blueShifter); + if (red != 0) red += OG_MASKS[redShifter]; + if (green != 0) green += OG_MASKS[greenShifter]; + if (blue != 0) blue += OG_MASKS[blueShifter]; + + if (alphaShifter != 8) { + alpha = (colour >> alphaFieldPosition) << alphaShifter; + if (alpha != 0) alpha += OG_MASKS[alphaShifter]; + } else alpha = GetAlpha(); + + break; + case 1: + + if (NULL == pal) { + red = green = blue = alpha = 0; + return; + } // if pal == null + + if (colour>255) colour &= 255; + red = pal[colour].red; + green = pal[colour].green; + blue = pal[colour].blue; + alpha = pal[colour].alpha; + break; + default: + red = green = blue = alpha = 0; + } // switch + + return; +} // ogSurface::Unpack + +void +ogSurface::VFlip(void) { + uInt32 height; + + if (!Avail()) return; + + switch (bytesPerPix) { + case 4: + __asm__ __volatile__( + " add %%edi, %%esi \n" // add esi, edi + "vf32lop: \n" + " push %%esi \n" // push esi + " push %%edi \n" // push edi + "vf32lop2: \n" + " mov (%%edi),%%eax \n" // mov eax, [edi] + " mov (%%esi),%%ecx \n" // mov ecx, [esi] + " mov %%eax,(%%esi) \n" // mov [esi], eax + " mov %%ecx,(%%edi) \n" // mov [edi], ecx + " add $4, %%edi \n" // add edi, 4 + " sub $4, %%esi \n" // sub esi, 4 + " cmp %%esi, %%edi \n" // cmp edi, esi + " jbe vf32lop2 \n" + " pop %%edi \n" // pop edi + " pop %%esi \n" // pop esi + " add %%ebx, %%esi \n" // add esi, ebx + " add %%ebx, %%edi \n" // add edi, ebx + " dec %%edx \n" + " jnz vf32lop \n" + : + : "D" ((char *)buffer+lineOfs[0]), "S" (maxX*4), // %0, %1 + "b" (xRes), "d" (maxY+1) // %2, %3 + ); + break; + case 3: + height = maxY + 1; + __asm__ __volatile__( + " add %%edi, %%esi \n" // add esi, edi + "vf24lop: \n" + " push %%esi \n" // push esi + " push %%edi \n" // push edi + "vf24lop2: \n" + " mov (%%edi),%%ax \n" // mov ax, [edi] + " mov 2(%%edi),%%dl \n" // mov dl, [edi+2] + " mov (%%esi),%%cx \n" // mov cx, [esi] + " mov 2(%%esi),%%dh \n" // mov dh, [esi+2] + " mov %%ax,(%%esi) \n" // mov [esi], ax + " mov %%dl,2(%%esi) \n" // mov [esi+2], dl + " mov %%cx,(%%edi) \n" // mov [edi], cx + " mov %%dh,2(%%edi) \n" // mov [edi+2], dh + " add $3, %%edi \n" // add edi, 3 + " sub $3, %%esi \n" // sub esi, 3 + " cmp %%esi, %%edi \n" // cmp edi, esi + " jbe vf24lop2 \n" + " pop %%edi \n" // pop edi + " pop %%esi \n" // pop esi + " add %%ebx, %%esi \n" // add esi, ebx + " add %%ebx, %%edi \n" // add edi, ebx + " decl %3 \n" // dec height + " jnz vf24lop \n" + : + : "D" ((char *)buffer+lineOfs[0]), "S" (maxX*3), // %0, %1 + "b" (xRes), "m" (height) // %2, %3 + ); + break; + case 2: + __asm__ __volatile__( + " add %%edi, %%esi \n" // add esi, edi + "vf16lop: \n" + " push %%esi \n" // push esi + " push %%edi \n" // push edi + "vf16lop2: \n" + " mov (%%edi),%%ax \n" // mov ax, [edi] + " mov (%%esi),%%cx \n" // mov cx, [esi] + " mov %%ax,(%%esi) \n" // mov [esi], ax + " mov %%cx,(%%edi) \n" // mov [edi], cx + " add $2, %%edi \n" // add edi, 2 + " sub $2, %%esi \n" // sub esi, 2 + " cmp %%esi, %%edi \n" // cmp edi, esi + " jbe vf16lop2 \n" + " pop %%edi \n" // pop edi + " pop %%esi \n" // pop esi + " add %%ebx, %%esi \n" // add esi, ebx + " add %%ebx, %%edi \n" // add edi, ebx + " dec %%edx \n" + " jnz vf16lop \n" + : + : "D" ((char *)buffer+lineOfs[0]), "S" (maxX*2), // %0, %1 + "b" (xRes), "d" (maxY+1) // %2, %3 + ); + break; + case 1: + __asm__ __volatile__( + " add %%edi, %%esi \n" // add esi, edi + "vf8lop: \n" + " push %%esi \n" // push esi + " push %%edi \n" // push edi + "vf8lop2: \n" + " mov (%%edi),%%al \n" // mov al, [edi] + " mov (%%esi),%%ah \n" // mov ah, [esi] + " mov %%al,(%%esi) \n" // mov [esi], al + " mov %%ah,(%%edi) \n" // mov [edi], ah + " inc %%edi \n" // inc edi + " dec %%esi \n" // dec esi + " cmp %%esi, %%edi \n" // cmp edi, esi + " jbe vf8lop2 \n" + " pop %%edi \n" // pop edi + " pop %%esi \n" // pop esi + " add %%ebx, %%esi \n" // add esi, ebx + " add %%ebx, %%edi \n" // add edi, ebx + " dec %%edx \n" + " jnz vf8lop \n" + : + : "D" ((char *)buffer+lineOfs[0]), "S" (maxX), // %0, %1 + "b" (xRes), "d" (maxY+1) // %2, %3 + ); + break; + } // switch + return; +} // ogSurface::VFlip + +void +ogSurface::VLine(int32 x, int32 y1, int32 y2, uInt32 colour) { + int32 tmp; + uInt8 r, g, b, a; + + if (!Avail()) return; + if ((uInt32)x > maxX) return; + + if (y1 > y2) { + tmp= y1; + y1 = y2; + y2 = tmp; + } // if + + if (y1 < 0) y1 = 0; + if (y2 > (int32)maxY) y2 = maxY; + if (y2 < y1) return; + + if (IsBlending()) { + + Unpack(colour, r, g, b, a); + + if (0 == a) return; + + if (255 != a) { + for (tmp = y1; tmp <= y2; tmp++) + RawSetPixel(x, tmp, r, g, b, a); + return; + } // if + + } // if blending + + switch (bytesPerPix) { + case 4: + __asm__ __volatile__( + " add %%esi, %%edi \n" // add edi, esi + " shl $2, %%ebx \n" // shl ebx, 2 - pix size + " mov %6, %%esi \n" // mov esi, y1 + " sub %%esi, %%ecx \n" // sub ecx, esi + " add %%ebx, %%edi \n" // add edi, ebx + " inc %%ecx \n" // inc ecx + "vLlop32: \n" + " mov %%eax, (%%edi)\n" // mov [edi], eax + " add %%edx, %%edi \n" // add edi, edx + " dec %%ecx \n" // dec ecx + " jnz vLlop32 \n" + : + : "D" (buffer), "S" (lineOfs[y1]), // %0, %1 + "a" (colour), "b" (x), // %2, %3 + "c" (y2), "d" (xRes), // %4, %5 + "m" (y1) // %6 + ); + break; + case 3: + __asm__ __volatile__( + " add %%esi, %%edi \n" // add edi, esi + " mov %%ebx, %%esi \n" // mov esi, ebx - pix size + " add %%ebx, %%ebx \n" // add ebx, ebx - pix size + " add %%esi, %%ebx \n" // add ebx, esi - pix size + " mov %6, %%esi \n" // mov esi, y1 + " sub %%esi, %%ecx \n" // sub ecx, esi + " add %%ebx, %%edi \n" // add edi, ebx + " inc %%ecx \n" // inc ecx + " mov %%eax, %%ebx \n" // mov ebx, eax + " shr $16, %%ebx \n" // shr ebx, 16 + "vLlop24: \n" + " mov %%ax, (%%edi) \n" // mov [edi], eax + " mov %%bl, 2(%%edi)\n" // mov [edi+2], bl + " add %%edx, %%edi \n" // add edi, edx + " dec %%ecx \n" // dec ecx + " jnz vLlop24 \n" + : + : "D" (buffer), "S" (lineOfs[y1]), // %0, %1 + "a" (colour), "b" (x), // %2, %3 + "c" (y2), "d" (xRes), // %4, %5 + "m" (y1) // %6 + ); + break; + case 2: + __asm__ __volatile__( + " add %%esi, %%edi \n" // add edi, esi + " add %%ebx, %%ebx \n" // add ebx, ebx - pix size + " mov %6, %%esi \n" // mov esi, y1 + " sub %%esi, %%ecx \n" // sub ecx, esi + " add %%ebx, %%edi \n" // add edi, ebx + " inc %%ecx \n" // inc ecx + "vLlop16: \n" + " mov %%ax, (%%edi) \n" // mov [edi], ax + " add %%edx, %%edi \n" // add edi, edx + " dec %%ecx \n" // dec ecx + " jnz vLlop16 \n" + : + : "D" (buffer), "S" (lineOfs[y1]), // %0, %1 + "a" (colour), "b" (x), // %2, %3 + "c" (y2), "d" (xRes), // %4, %5 + "m" (y1) // %6 + ); + break; + case 1: + __asm__ __volatile__( + " add %%esi, %%edi \n" // add edi, esi + " mov %6, %%esi \n" // mov esi, y1 + " sub %%esi, %%ecx \n" // sub ecx, esi + " add %%ebx, %%edi \n" // add edi, ebx + " inc %%ecx \n" // inc ecx + "vLlop8: \n" + " mov %%al, (%%edi) \n" // mov [edi], al + " add %%edx, %%edi \n" // add edi, edx + " dec %%ecx \n" // dec ecx + " jnz vLlop8 \n" + : + : "D" (buffer), "S" (lineOfs[y1]), // %0, %1 + "a" (colour), "b" (x), // %2, %3 + "c" (y2), "d" (xRes), // %4, %5 + "m" (y1) // %6 + ); + break; + } // switch + return; +} // ogSurface::VLine + +ogSurface::~ogSurface(void) { + + if (dataState == ogOwner) { + delete [] pal; + delete [] lineOfs; + delete attributes; +#ifdef __UBIXOS_KERNEL__ + kfree(buffer); +#else + free(buffer); +#endif + } // if datastate + + pal = NULL; + lineOfs= NULL; + buffer = NULL; + attributes = NULL; + bSize = 0; + lSize = 0; + dataState = ogNone; + return; +} // ogSurface::~ogSurface + + diff --git a/src/lib/objgfx40/objgfx40/defpal.inc b/src/lib/objgfx40/objgfx40/defpal.inc new file mode 100644 index 0000000..da73f83 --- /dev/null +++ b/src/lib/objgfx40/objgfx40/defpal.inc @@ -0,0 +1,259 @@ +const + ogRGBA8 DEFAULT_PALETTE[256] = + {{0, 0, 0, 255}, // 0 + {0, 0, 170, 255}, + {0, 170, 0, 255}, + {0, 170, 170, 255}, // 3 + {170, 0, 0, 255}, + {170, 0, 170, 255}, + {170, 85, 0, 255}, + {170, 170, 170, 255}, // 7 + {85, 85, 85, 255}, + {85, 85, 255, 255}, + {85, 255, 85, 255}, + {85, 255, 255, 255}, // 11 + {255, 85, 85, 255}, + {255, 85, 255, 255}, + {255, 255, 85, 255}, + {255, 255, 255, 255}, //15 + {16, 16, 16, 255}, // 16 + {32, 32, 32, 255}, + {48, 48, 48, 255}, + {64, 64, 64, 255}, + {80, 80, 80, 255}, + {96, 96, 96, 255}, + {112, 112, 112, 255}, + {128, 128, 128, 255}, + {144, 144, 144, 255}, + {160, 160, 160, 255}, + {176, 176, 176, 255}, + {192, 192, 192, 255}, + {208, 208, 208, 255}, + {224, 224, 224, 255}, + {240, 240, 240, 255}, + {255, 255, 255, 255}, //31 + {59, 0, 0, 255}, // 32 + {79, 0, 0, 255}, + {103, 0, 0, 255}, + {123, 0, 0, 255}, + {143, 7, 7, 255}, + {167, 7, 7, 255}, + {187, 11, 11, 255}, + {211, 15, 15, 255}, + {231, 19, 19, 255}, + {255, 27, 27, 255}, + {255, 59, 59, 255}, + {255, 91, 91, 255}, + {255, 119, 119, 255}, + {255, 151, 151, 255}, + {255, 183, 183, 255}, + {255, 215, 215, 255}, + {55, 55, 0, 255}, // 48 + {71, 71, 0, 255}, + {87, 87, 0, 255}, + {103, 103, 7, 255}, + {119, 119, 7, 255}, + {135, 135, 11, 255}, + {155, 155, 19, 255}, + {171, 171, 23, 255}, + {187, 187, 31, 255}, + {203, 203, 35, 255}, + {219, 219, 43, 255}, + {239, 239, 59, 255}, + {255, 255, 63, 255}, + {255, 255, 127, 255}, + {255, 255, 187, 255}, + {255, 255, 255, 255}, + {0, 43, 0, 255}, // 64 + {0, 63, 0, 255}, + {0, 83, 0, 255}, + {0, 103, 0, 255}, + {7, 127, 7, 255}, + {7, 147, 7, 255}, + {11, 167, 11, 255}, + {15, 187, 15, 255}, + {19, 211, 19, 255}, + {27, 231, 27, 255}, + {59, 235, 59, 255}, + {91, 239, 91, 255}, + {127, 239, 127, 255}, + {159, 243, 159, 255}, + {195, 247, 195, 255}, + {231, 251, 231, 255}, + {0, 55, 55, 255}, // 80 + {0, 71, 71, 255}, + {0, 87, 87, 255}, + {7, 103, 103, 255}, + {7, 119, 119, 255}, + {11, 135, 135, 255}, + {19, 155, 155, 255}, + {23, 171, 171, 255}, + {31, 187, 187, 255}, + {35, 203, 203, 255}, + {43, 219, 219, 255}, + {51, 235, 235, 255}, + {63, 255, 255, 255}, + {127, 255, 255, 255}, + {187, 255, 255, 255}, + {255, 255, 255, 255}, + {15, 15, 55, 255}, // 96 + {19, 19, 79, 255}, + {27, 27, 103, 255}, + {31, 31, 127, 255}, + {35, 35, 155, 255}, + {39, 39, 179, 255}, + {43, 43, 203, 255}, + {47, 47, 227, 255}, + {51, 51, 255, 255}, + {71, 71, 255, 255}, + {91, 91, 255, 255}, + {111, 111, 255, 255}, + {131, 131, 255, 255}, + {151, 151, 255, 255}, + {175, 175, 255, 255}, + {195, 195, 255, 255}, + {59, 51, 59, 255}, // 112 + {79, 63, 79, 255}, + {103, 71, 103, 255}, + {123, 75, 123, 255}, + {143, 75, 143, 255}, + {167, 71, 167, 255}, + {187, 67, 187, 255}, + {211, 55, 211, 255}, + {231, 43, 231, 255}, + {255, 27, 255, 255}, + {255, 59, 255, 255}, + {255, 91, 255, 255}, + {255, 119, 255, 255}, + {255, 151, 255, 255}, + {255, 183, 255, 255}, + {255, 215, 255, 255}, + {59, 51, 59, 255}, // 128 + {71, 59, 71, 255}, + {83, 71, 83, 255}, + {95, 83, 95, 255}, + {111, 95, 111, 255}, + {123, 103, 123, 255}, + {135, 115, 135, 255}, + {147, 127, 147, 255}, + {163, 139, 163, 255}, + {175, 151, 175, 255}, + {187, 159, 187, 255}, + {203, 171, 203, 255}, + {215, 183, 215, 255}, + {227, 191, 227, 255}, + {239, 203, 239, 255}, + {255, 215, 255, 255}, + {55, 27, 27, 255}, // 144 + {71, 35, 35, 255}, + {91, 43, 43, 255}, + {107, 55, 55, 255}, + {127, 67, 67, 255}, + {143, 75, 75, 255}, + {163, 87, 87, 255}, + {179, 99, 99, 255}, + {199, 111, 111, 255}, + {203, 127, 127, 255}, + {211, 139, 139, 255}, + {219, 159, 159, 255}, + {223, 175, 175, 255}, + {231, 191, 191, 255}, + {239, 211, 211, 255}, + {247, 231, 231, 255}, + {91, 63, 27, 255}, // 160 + {111, 75, 31, 255}, + {127, 87, 39, 255}, + {147, 103, 43, 255}, + {167, 115, 51, 255}, + {187, 127, 55, 255}, + {207, 139, 63, 255}, + {227, 155, 67, 255}, + {247, 167, 75, 255}, + {247, 175, 95, 255}, + {247, 183, 119, 255}, + {247, 195, 139, 255}, + {247, 203, 159, 255}, + {247, 215, 183, 255}, + {247, 227, 203, 255}, + {251, 239, 227, 255}, + {63, 63, 31, 255}, // 176 + {75, 75, 35, 255}, + {87, 87, 43, 255}, + {99, 99, 51, 255}, + {115, 115, 55, 255}, + {127, 127, 63, 255}, + {139, 139, 67, 255}, + {151, 151, 75, 255}, + {167, 167, 83, 255}, + {175, 175, 95, 255}, + {183, 183, 107, 255}, + {191, 191, 123, 255}, + {203, 203, 139, 255}, + {211, 211, 159, 255}, + {219, 219, 175, 255}, + {231, 231, 195, 255}, + {27, 59, 47, 255}, // 192 + {31, 75, 59, 255}, + {39, 87, 67, 255}, + {47, 103, 79, 255}, + {55, 119, 91, 255}, + {59, 135, 99, 255}, + {67, 151, 111, 255}, + {71, 167, 119, 255}, + {79, 183, 127, 255}, + {87, 199, 139, 255}, + {91, 215, 147, 255}, + {99, 231, 155, 255}, + {127, 235, 183, 255}, + {163, 239, 211, 255}, + {195, 243, 231, 255}, + {231, 251, 247, 255}, + {23, 55, 55, 255}, // 208 + {31, 71, 71, 255}, + {39, 87, 87, 255}, + {47, 103, 103, 255}, + {55, 119, 119, 255}, + {67, 139, 139, 255}, + {75, 155, 155, 255}, + {87, 171, 171, 255}, + {99, 187, 187, 255}, + {111, 203, 203, 255}, + {123, 223, 223, 255}, + {143, 227, 227, 255}, + {163, 231, 231, 255}, + {183, 235, 235, 255}, + {203, 239, 239, 255}, + {227, 247, 247, 255}, + {39, 39, 79, 255}, // 224 + {47, 47, 91, 255}, + {55, 55, 107, 255}, + {63, 63, 123, 255}, + {71, 71, 139, 255}, + {79, 79, 151, 255}, + {87, 87, 167, 255}, + {99, 99, 183, 255}, + {107, 107, 199, 255}, + {123, 123, 203, 255}, + {139, 139, 211, 255}, + {155, 155, 219, 255}, + {171, 171, 223, 255}, + {187, 187, 231, 255}, + {207, 207, 239, 255}, + {227, 227, 247, 255}, + {63, 27, 63, 255}, // 240 + {75, 31, 75, 255}, + {91, 39, 91, 255}, + {103, 47, 103, 255}, + {119, 51, 119, 255}, + {131, 59, 131, 255}, + {147, 67, 147, 255}, + {163, 75, 163, 255}, + {175, 83, 175, 255}, + {191, 91, 191, 255}, + {199, 107, 199, 255}, + {207, 127, 207, 255}, + {215, 147, 215, 255}, + {223, 171, 223, 255}, + {231, 195, 231, 255}, + {243, 219, 243, 255}}; + diff --git a/src/lib/objgfx40/objgfx40/objgfx40.h b/src/lib/objgfx40/objgfx40/objgfx40.h new file mode 100644 index 0000000..11a3bc0 --- /dev/null +++ b/src/lib/objgfx40/objgfx40/objgfx40.h @@ -0,0 +1,243 @@ +/************************************************************** +$Id$ +**************************************************************/ + +#ifndef OBJGFX40_H +#define OBJGFX40_H + +#ifndef __UBIXOS_KERNEL__ +#include // for NULL, true, false +#endif + +#define ogVERSION 4.0; + +typedef signed char int8; +typedef signed short int int16; +typedef signed long int int32; +typedef signed long long int int64; +typedef unsigned char uInt8; +typedef unsigned short int uInt16; +typedef unsigned long int uInt32; +typedef unsigned long long int uInt64; + +extern const uInt32 OG_MASKS[32]; + +enum ogDataState { ogNone, ogOwner, ogAliasing }; + +enum ogErrorCode { + ogOK, + ogMemAllocFail, + ogAlreadyOwner, + ogNoSurface, + ogNoPalette, + ogBadBPP, + ogSourceOutOfBounds, + ogDestOutOfBounds, + ogFileNotFound, + ogFileReadError, + ogFileWriteError, + ogNoCloning, + ogNoAliasing, + ogNoModeSupport +}; // ogErrorCode + +struct ogRGB8 { + uInt8 red; + uInt8 green; + uInt8 blue; +}; + +struct ogRGBA8 { + uInt8 red; + uInt8 green; + uInt8 blue; + uInt8 alpha; +}; + +struct ogRGB32 { + uInt32 red; + uInt32 green; + uInt32 blue; +}; + +struct ogRGBA32 { + uInt32 red; + uInt32 green; + uInt32 blue; + uInt32 alpha; +}; + +struct ogPoint2d { + int32 x; + int32 y; +}; + +struct ogPoint3d { + int32 x; + int32 y; + int32 z; +}; + +typedef + struct ogPixelFmt { + uInt8 BPP; + uInt8 redFieldPosition; + uInt8 greenFieldPosition; + uInt8 blueFieldPosition; + uInt8 alphaFieldPosition; + uInt8 redMaskSize; + uInt8 greenMaskSize; + uInt8 blueMaskSize; + uInt8 alphaMaskSize; + uInt8 reserved[7]; + }; + +// Default pixel formats + +const ogPixelFmt OG_NULL_PIXFMT = { 0, 0,0,0,0,0,0,0,0, {0,0,0,0,0,0}}; +const ogPixelFmt OG_PIXFMT_8BPP = { 8, 0,0,0,0,0,0,0,0, {0,0,0,0,0,0}}; +const ogPixelFmt OG_PIXFMT_15BPP = {15, 10,5,0,15,5,5,5,1, {0,0,0,0,0,0}}; +const ogPixelFmt OG_PIXFMT_16BPP = {16, 11,5,0,0,5,6,5,0, {0,0,0,0,0,0}}; +const ogPixelFmt OG_PIXFMT_24BPP = {24, 16,8,0,0,8,8,8,0, {0,0,0,0,0,0}}; +const ogPixelFmt OG_PIXFMT_32BPP = {32, 16,8,0,24,8,8,8,8, {0,0,0,0,0,0}}; +const ogPixelFmt OG_MAC_PIXFMT_16BPP = {16, 8,4,0,12,4,4,4,4, {0,0,0,0,0,0}}; +#if 0 +class + ogAttributes(uInt32 transparentColour = 0, + uInt32 defaultAlpha = 255, + bool antiAlias = true, + bool blending = false); +#endif + +class ogAttributes { + public: + uInt32 transparentColor; + uInt32 defaultAlpha; + bool antiAlias; + bool blending; + ogAttributes():transparentColor(0), + defaultAlpha(255), + antiAlias(true), + blending(false) { } + ogAttributes & operator=( ogAttributes const & copy ) { + transparentColor = copy.transparentColor; + defaultAlpha = copy.defaultAlpha; + antiAlias = copy.antiAlias; + blending = copy.blending; + return * this; + } // operator = +}; // ogAttributes + +class ogSurface { +#ifdef __UBIXOS_KERNEL__ + public: +#else + protected: +#endif + float version; + void * buffer; + ogSurface * owner; + uInt32 * lineOfs; + ogRGBA8 * pal; + ogAttributes*attributes; + + uInt32 xRes, yRes; + uInt32 maxX, maxY; + uInt32 bSize; // buffer size (in bytes) + uInt32 lSize; // LineOfs size (in bytes) + + uInt32 BPP; // bits per pixel + uInt32 bytesPerPix; + uInt32 pixFmtID; + + uInt32 redFieldPosition; + uInt32 greenFieldPosition; + uInt32 blueFieldPosition; + uInt32 alphaFieldPosition; + + uInt32 redShifter; + uInt32 greenShifter; + uInt32 blueShifter; + uInt32 alphaShifter; + uInt32 alphaMasker; + ogErrorCode lastError; + ogDataState dataState; + + bool ClipLine(int32&, int32&, int32&, int32&); + void RawLine(uInt32, uInt32, uInt32, uInt32, uInt32); + virtual uInt32 RawGetPixel(uInt32, uInt32); + virtual void RawSetPixel(uInt32, uInt32, uInt32); + virtual void RawSetPixel(uInt32, uInt32, uInt8, uInt8, uInt8, uInt8); + void AARawLine(uInt32, uInt32, uInt32, uInt32, uInt32); + public: + ogSurface(void); + virtual bool Alias(ogSurface&, uInt32, uInt32, uInt32, uInt32); + virtual bool Avail(void); + void Arc(int32, int32, uInt32, uInt32, uInt32, uInt32); + void BSpline(uInt32, ogPoint2d*, uInt32, uInt32); + void Circle(int32, int32, uInt32, uInt32); + virtual void Clear(uInt32); + virtual bool Clone(ogSurface&); + void Copy(ogSurface&); + void CopyBuf(int32, int32, + ogSurface&, int32, int32, int32, int32); + virtual void CopyLineTo(uInt32, uInt32, const void *, uInt32); + virtual void CopyLineFrom(uInt32, uInt32, void *, uInt32); + virtual void CopyPalette(ogSurface&); + virtual bool Create(uInt32, uInt32, ogPixelFmt); + void CubicBezierCurve(int32, int32, int32, int32, + int32, int32, int32, int32, uInt32, uInt32); + void Curve(int32,int32, int32,int32, int32,int32, uInt32, uInt32); + void FillCircle(int32, int32, uInt32, uInt32); + void FillGouraudPolygon(uInt32, ogPoint2d*, ogRGBA8 *); + void FillPolygon(uInt32, ogPoint2d*, uInt32); + void FillRect(int32, int32, int32, int32, uInt32); + void FillTriangle(int32,int32, int32,int32, int32,int32, uInt32); + uInt32 GetAlpha(void); + uInt32 GetAlphaMasker(void) const { return alphaMasker; } + uInt32 GetBPP(void) const { return BPP; } + uInt32 GetBytesPerPix(void) const { return bytesPerPix; } + ogDataState GetDataState(void) const { return dataState; } + ogErrorCode GetLastError(void); + uInt32 GetMaxX(void) const { return maxX; } + uInt32 GetMaxY(void) const { return maxY; } + void GetPalette(ogRGBA8[]); + void GetPixFmt(ogPixelFmt&); + uInt32 GetPixFmtID(void) const { return pixFmtID; } + virtual uInt32 GetPixel(int32, int32); + virtual void * GetPtr(uInt32, uInt32); + uInt32 GetTransparentColor(void); + void HFlip(void); + virtual void HLine(int32, int32, int32, uInt32); + bool IsAntiAliasing(void); + bool IsBlending(void); + void Line(int32, int32, int32, int32, uInt32); + virtual bool LoadPalette(const char *); + void Polygon(uInt32, ogPoint2d*, uInt32); + void Rect(int32, int32, int32, int32, uInt32); + uInt32 Pack(uInt8, uInt8, uInt8); + uInt32 Pack(uInt8, uInt8, uInt8, uInt8); + bool SavePalette(const char *); + void Scale(ogSurface&); + void ScaleBuf(int32, int32, int32, int32, + ogSurface&, int32, int32, int32, int32); + uInt32 SetAlpha(uInt32); + bool SetAntiAliasing(bool); + bool SetBlending(bool); + virtual ogErrorCode SetLastError(ogErrorCode); + virtual void SetPixel(int32, int32, uInt32); + virtual void SetPixel(int32, int32, uInt8, uInt8, uInt8, uInt8); + virtual void SetPalette(const ogRGBA8[]); + virtual void SetPalette(uInt8, uInt8, uInt8, uInt8, uInt8); + virtual void SetPalette(uInt8, uInt8, uInt8, uInt8); + uInt32 SetTransparentColor(uInt32); + void Spline(uInt32, ogPoint2d*, uInt32, uInt32); + void Triangle(int32, int32, int32, int32, int32, int32, uInt32); + void Unpack(uInt32, uInt8&, uInt8&, uInt8&); + void Unpack(uInt32, uInt8&, uInt8&, uInt8&, uInt8&); + virtual void VFlip(void); + virtual void VLine(int32, int32, int32, uInt32); + virtual ~ogSurface(void); +}; // ogSurface + +#endif diff --git a/src/lib/objgfx40/objgfx40/ogBlit.h b/src/lib/objgfx40/objgfx40/ogBlit.h new file mode 100644 index 0000000..5d4604d --- /dev/null +++ b/src/lib/objgfx40/objgfx40/ogBlit.h @@ -0,0 +1,29 @@ +#ifndef OGBLIT_H +#define OGBLIT_H + +#include "ogSprite.h" + +class ogBlit: public ogSprite { + protected: + uInt8 * blitMask; + uInt32 blitMaskSize; + uInt32 totalPixCount; + int32 startX, startY; + int32 endX, endY; + + void BlitSize(ogSurface&, int32, int32, int32, int32); + public: + ogBlit(void); + ogBlit(const ogBlit &, bool); + virtual void Get(ogSurface&, int32, int32, int32, int32); + void GetBlitMask(ogSurface &, int32, int32, int32, int32); + uInt32 GetBlitMaskSize(void) const { return blitMaskSize; } + void GetBlitWithMask(ogSurface&, int32, int32); + virtual uInt32 GetSize(void); + virtual bool LoadFrom(const char *, uInt32); + virtual void Put(ogSurface&, int32, int32); + virtual bool SaveTo(const char *, int32); + virtual ~ogBlit(void); +}; // ogBlit + +#endif diff --git a/src/lib/objgfx40/objgfx40/ogFont.h b/src/lib/objgfx40/objgfx40/ogFont.h new file mode 100644 index 0000000..28a53c3 --- /dev/null +++ b/src/lib/objgfx40/objgfx40/ogFont.h @@ -0,0 +1,45 @@ +#ifndef OGFONT_H +#define OGFONT_H + +#include "objgfx40.h" + +enum + ogTextAlign { + leftText, + bottomText = leftText, + centerText, + rightText, + topText = rightText + }; // textAlign + +class + ogBitFont { + protected: + uInt32 fontDataIdx[256]; + uInt32 charWidthTable[256]; + uInt32 charHeightTable[256]; + uInt8 * fontData; + uInt32 fontDataSize; + ogRGBA8 BGColour; + ogRGBA8 FGColour; + uInt16 numOfChars; + uInt8 width, height; + uInt8 startingChar; + public: + ogBitFont(); + void CenterTextX(ogSurface&, int32, const char *); + uInt32 GetWidth(void) const { return width; } + uInt32 GetHeight(void) const { return height; } + void JustifyText(ogSurface&, ogTextAlign, ogTextAlign, const char *); + bool Load(const char *, uInt32); + void PutChar(ogSurface&, int32, int32, const char); + void PutString(ogSurface&, int32, int32, const char *); +// bool Save(const char *); + void SetBGColor(uInt32, uInt32, uInt32, uInt32); + void SetFGColor(uInt32, uInt32, uInt32, uInt32); + uInt32 TextHeight(const char *); + uInt32 TextWidth(const char *); + ~ogBitFont(); +}; // ogBitFont + +#endif diff --git a/src/lib/objgfx40/objgfx40/ogPixCon.h b/src/lib/objgfx40/objgfx40/ogPixCon.h new file mode 100644 index 0000000..eb794e8 --- /dev/null +++ b/src/lib/objgfx40/objgfx40/ogPixCon.h @@ -0,0 +1,16 @@ +#ifndef OGPIXCON_H +#define OGPIXCON_H + +#include "objgfx40.h" + +class ogPixCon { + protected: + uInt32 srcMasker; + uInt32 srcShifter; + uInt32 dstShifter; + public: + ogPixCon(ogPixelFmt, ogPixelFmt); + uInt32 ConvPix(uInt32); +}; // ogPixCon + +#endif diff --git a/src/lib/objgfx40/objgfx40/ogSprite.h b/src/lib/objgfx40/objgfx40/ogSprite.h new file mode 100644 index 0000000..0767f40 --- /dev/null +++ b/src/lib/objgfx40/objgfx40/ogSprite.h @@ -0,0 +1,44 @@ +#ifndef OGSPRITE_H +#define OGSPRITE_H + +#include "objgfx40.h" + +class ogSprite { + protected: + void * image; // image data + uInt32 imageSize; // memory size of the image pointer + ogRGBA8 * pal; // palette (used for 8bpp sprites) + uInt32 width, height; // width and height (in pixels) + uInt32 bitDepth; // make this 32-bit just for alignment purposes + uInt32 RFP; // red field position + uInt32 GFP; // green field position + uInt32 BFP; // blue field position + uInt32 AFP; // alpha field position + uInt32 rShift; // red shifter + uInt32 gShift; // green shifter + uInt32 bShift; // blue shifter + uInt32 aShift; // alpha shifter + uInt32 tColour; // original transparent colour + uInt32 pixelFmtID; // pixel format id + uInt32 bytesPerPixel; // bytes per pixel + uInt32 dAlpha; // default alpha + uInt32 GetPixel(void *); + void SetPixel(void *, uInt32); + void Unpack(uInt32, uInt8&, uInt8&, uInt8&, uInt8&); + public: + ogSprite & operator=(ogSprite const &); + ogSprite(void); + ogSprite(const ogSprite &); + void Get(ogSurface&, int32, int32, int32, int32); + uInt32 GetHeight(void) { return height; } + uInt32 GetSize(void); + uInt32 GetWidth(void) { return width; } + bool Load(const char *); + virtual bool LoadFrom(const char *, uInt32); + virtual void Put(ogSurface&, int32, int32); + bool Save(const char *); + virtual bool SaveTo(const char *, int32); + virtual ~ogSprite(void); + +}; // ogSprite +#endif diff --git a/src/lib/objgfx40/objgfx40/vWidget.h b/src/lib/objgfx40/objgfx40/vWidget.h new file mode 100644 index 0000000..26dcada --- /dev/null +++ b/src/lib/objgfx40/objgfx40/vWidget.h @@ -0,0 +1,17 @@ +#ifndef VWIDGET_H +#define VWIDGET_H + +#include + +class vWidget : public ogSurface { + protected: + bool active; + public: + vWidget(void) { active = true; } + virtual void vDraw(void) = 0; + virtual bool vGetActive(void) const { return active; } + virtual bool vSetActive(bool); + virtual bool vCreate(void) = 0; +}; + +#endif diff --git a/src/lib/objgfx40/objgfx40/vWindow.h b/src/lib/objgfx40/objgfx40/vWindow.h new file mode 100644 index 0000000..3865603 --- /dev/null +++ b/src/lib/objgfx40/objgfx40/vWindow.h @@ -0,0 +1,19 @@ +#ifndef VWINDOW_H +#define VWINDOW_H + +#include +#include +#include + +class vWindow : public vWidget { + protected: + ogSurface * realWindow; + ogBitFont * titleFont; + public: + vWindow(void); + virtual void vDraw(void) { return; } + virtual bool vCreate(void); + void vSDECommand(uInt32); + virtual ~vWindow(void); +}; +#endif diff --git a/src/lib/objgfx40/ogBlit.cpp b/src/lib/objgfx40/ogBlit.cpp new file mode 100644 index 0000000..2c19286 --- /dev/null +++ b/src/lib/objgfx40/ogBlit.cpp @@ -0,0 +1,850 @@ +extern "C" { + #include + #include + #include + } +#include +#include + +using namespace std; + +static bool +fileExists(const char *file) +{ + FILE *f = fopen(file, "rb"); + if (!f) + return false; + fclose(f); + return true; +} + +ogBlit::ogBlit(ogBlit const & srcBlit, bool doFullCopy = false) : ogSprite() { + + // horrible horrible hack. This is required because I can't have + // two constructors with the same parameter list like I can in pascal. + + // -- begin hack -- + if (doFullCopy) ogSprite::operator=(srcBlit); + // -- end hack -- + + startX = srcBlit.startX; + startY = srcBlit.startY; + endX = srcBlit.endX; + endY = srcBlit.endY; + + totalPixCount = srcBlit.totalPixCount; + blitMaskSize = srcBlit.blitMaskSize; + + blitMask = NULL; + + if (blitMaskSize != 0) { + blitMask = new uInt8[blitMaskSize]; + if ((blitMask != NULL) && (srcBlit.blitMask != NULL)) + memcpy(blitMask, srcBlit.blitMask, blitMaskSize); + } // if + return; +} // ogBlit::ogBlit + +ogBlit::ogBlit(void) : ogSprite() { + blitMask = NULL; + blitMaskSize = 0; + totalPixCount = 0; + startX = 0; + startY = 0; + endX = 0; + endY = 0; + return; +} // ogBlit::ogBlit + +void +ogBlit::BlitSize(ogSurface& src, int32 x1, int32 y1, int32 x2, int32 y2) { + uInt32 aMask; + int32 x,y; + uInt8 zerocount; + uInt8 pixcount; + + bool inZeros; + bool found; + + // first free the image data or the blitMask data if we already have some + + free(image); + delete [] blitMask; + + image = NULL; + blitMask = NULL; + imageSize = 0; + blitMaskSize = 0; + + aMask = src.GetAlphaMasker(); + tColour = src.GetTransparentColor(); + + startX = x1; + startY = y1; + endX = x2; + endY = y2; + + // start by locating the left-most non-transparent pixel in the region defined + // by (x1,y1) to (x2,y2) + + found = false; + while ((!found) && (startX <= x2)) { + for (y = y1; y <= y2; y++) + found |= ((src.GetPixel(startX, y) & aMask) != tColour); + if (!found) ++startX; + } // while + + // now we look for the top-most non-transparent pixel in the regsion + // defined by (startX,y1) to (x2,y2) + + found = false; + while ((!found) && (startY <= y2)) { + for (x = startX; x <= x2; x++) + found |= ((src.GetPixel(x,startY) & aMask) != tColour); + if (!found) ++startY; + } // while + + found = false; + while ((!found) && (endX >= startX)) { + for (y = startY; y <= y2; y++) + found |= ((src.GetPixel(endX,y) & aMask) != tColour); + if (!found) --endX; + } // while + + found = false; + while ((!found) && (endY >= startY)) { + for (x = startX; x <= endX; x++) + found |= ((src.GetPixel(x,endY) & aMask) != tColour); + if (!found) --endY; + } // while + + for (y = startY; y <= endY; y++) { + zerocount = 0; + blitMaskSize++; // save room for xlcount + x = startX; + inZeros = ((src.GetPixel(x,y) & aMask) == tColour); + + while (x <= endX) { + switch (inZeros) { + case true: + zerocount = 0; // How many zeros? + + while ((x <= endX) && ((src.GetPixel(x,y) & aMask) == tColour)) { + ++x; + + if (255 == zerocount) { + zerocount = 0; + blitMaskSize += 2; + } else ++zerocount; + } // while + + inZeros = false; + break; // case true + + case false: + pixcount = 0; + blitMaskSize += 2; + do { + ++x; + + if (255 == pixcount) { + blitMaskSize += 2; + pixcount = 0; + } else ++pixcount; + + ++totalPixCount; + //mjikaboom imageSize += bm; + } while ((x <= endX) && ((src.GetPixel(x,y) & aMask) != tColour)); + inZeros = true; + break; // case false + } // switch + } // while + } // for + + startX -= x1; + startY -= y1; + endX -= x1; + endY -= y1; + + blitMask = new uInt8[blitMaskSize]; //(uInt8 *)malloc(blitMaskSize); +// memset(blitMask,0,blitMaskSize); + return; +} // ogBlit::BlitSize + +void +ogBlit::GetBlitMask(ogSurface& src, int32 x1, int32 y1, + int32 x2, int32 y2) { + + uInt8 * blitMaskPtr; + uInt8 * lineCountPtr; + int32 x, y; + bool inZeros; + uInt8 pixCount, zeroCount; + uInt32 aMask; + uInt32 tmp; + + if (x1 > x2) { + tmp = x1; + x1 = x2; + x2 = tmp; + } // if + + if (y1 > y2) { + tmp = y1; + y1 = y2; + y2 = tmp; + } // if + + // calculate the width/height + + width = (x2 - x1)+1; + height = (y2 - y1)+1; + + bytesPerPixel = src.GetBytesPerPix(); + + if (1 == bytesPerPixel) { + if (pal != NULL) pal = new ogRGBA8[256]; + // note that tPal will check for null, so this check may be unnecessary + if (pal != NULL) src.GetPalette(pal); +/* for (tmp = 0; tmp < 256; tmp++) + src.Unpack(tmp, + pal[tmp].red, + pal[tmp].green, + pal[tmp].blue, + pal[tmp].alpha); */ + } // if + + // compute the size of the blit mask and allocate memory for it + + BlitSize(src, x1, y1, x2, y2); + + if (NULL == blitMask) return; + + blitMaskPtr = blitMask; + aMask = src.GetAlphaMasker(); + tColour = src.GetTransparentColor(); + + for (y = y1+startY; y <= y1+endY; y++) { + zeroCount = 0; + lineCountPtr = blitMaskPtr; + *lineCountPtr = 0; + ++blitMaskPtr; + x = x1+startX; + inZeros = ((src.GetPixel(x,y) & aMask) == tColour); + + while (x <= x1+endX) { + switch (inZeros) { + case true: + zeroCount = 0; + while ((x <= x1+endX) && ((src.GetPixel(x,y) & aMask) == tColour)) { + ++x; + if (255 == zeroCount) { + ++(*lineCountPtr); + *blitMaskPtr = 255; // offset + ++blitMaskPtr; // increment to next byte + *blitMaskPtr = 0; // runcount + ++blitMaskPtr; // increment to next byte + *blitMaskPtr = 0; // offset + zeroCount = 0; + } else ++zeroCount; + } // while + + inZeros = false; // we are no longer in zeros + break; // case true + + case false: + ++(*lineCountPtr); + *blitMaskPtr = zeroCount; + ++blitMaskPtr; + *blitMaskPtr = 0; + pixCount = 0; + + do { + ++x; + + if (255 == pixCount) { + ++(*lineCountPtr); + *blitMaskPtr = 255; // runcount + ++blitMaskPtr; // advance pointer + *blitMaskPtr = 0; // offset to next run + ++blitMaskPtr; // advance pointer + *blitMaskPtr = 0; // next run count (incremented below) + pixCount = 0; + } else ++pixCount; + + ++(*blitMaskPtr); + + } while ((x <= (x1+endX)) && + ((src.GetPixel(x,y) & aMask)!=tColour)); + ++blitMaskPtr; + inZeros = true; // set inZeros to true to toggle + break; // case false + } // switch + } // while + } // for y + return; +} // ogBlit::GetBlitMask + +void +ogBlit::Get(ogSurface& src, int32 x1, int32 y1, int32 x2, int32 y2) { + int32 tmp; + + if (x1 > x2) { + tmp = x1; + x1 = x2; + x2 = tmp; + } // if + + if (y1 > y2) { + tmp = y1; + y1 = y2; + y2 = tmp; + } // if + + // get the blit mask + GetBlitMask(src, x1, y1, x2, y2); + + // now get the actual blit using the blit mask + GetBlitWithMask(src, x1, y1); + + return; +} // ogBlit::Get + +void +ogBlit::GetBlitWithMask(ogSurface & src, int32 x, int32 y) { + /* + * getBlitWithMask + * + * Retrieves the data portion of a blit using a predefined mask and + * stores the data in the image pointer. If the source buffer is + * a different pixel format, we will adjust the image pointer + * to accommodate the new data and update the pixel format. The put() + * function will adjust the pixels to the dest buffer as needed. + * Before calling this routine, you must call getBlitMask. + */ + + int32 sx, sy; + uInt8 lineCount, offset, pixCount; + uInt32 nsy, ney; + uInt8 *blitMaskPtr; + void *imagePtr; + uInt32 distToEdge, xRight, count; + ogPixelFmt pixFmt; + + if (NULL == blitMask) return; + + if ( (x + startX > (int32)src.GetMaxX()) || (x + endX < 0) || + (y + startY > (int32)src.GetMaxY()) || (y + endY < 0)) return; + + blitMaskPtr = blitMask; + + // First check to see if the pixel format we got the blitmask from + // is different than what we're dealing with now + // note that the first time through pixelFmtID will be 0, so this + // will get that information + + if (src.GetPixFmtID() != pixelFmtID) { + free(image); + image = NULL; + imageSize = 0; + + src.GetPixFmt(pixFmt); + + bitDepth = pixFmt.BPP; + RFP = pixFmt.redFieldPosition; + GFP = pixFmt.greenFieldPosition; + BFP = pixFmt.blueFieldPosition; + AFP = pixFmt.alphaFieldPosition; + rShift = 8-pixFmt.redMaskSize; + gShift = 8-pixFmt.greenMaskSize; + bShift = 8-pixFmt.blueMaskSize; + aShift = 8-pixFmt.alphaMaskSize; + + bytesPerPixel = src.GetBytesPerPix(); + pixelFmtID = src.GetPixFmtID(); + dAlpha = src.GetAlpha(); + // tColour = src.GetTransparentColor(); // done elsewhere + + } // if + + if (NULL == image) { + imageSize = totalPixCount * bytesPerPixel; + image = malloc(imageSize); + } // if + + imagePtr = image; + // If any part of the blit data is out of bounds, we need to fill it with the + // transparent colour + if ( (x + startX < 0) || (x + endX > (int32)src.GetMaxX()) || + (y + startY < 0) || (y + endY > (int32)src.GetMaxY())) { + for (count = 0; count < totalPixCount; count++) { + SetPixel(imagePtr, tColour); + (uInt8 *)imagePtr += bytesPerPixel; + } // for count + imagePtr = image; // reset the image pointer + } // if + + // first do clipping on the top edge + nsy = startY; + if (y+startY < 0) { + /* + * If we're here then part of the blit is above the top edge of the + * buffer. The distance to the top of the buffer is abs(y+startY). + * So, we need to loop through the blit geometry and advance the + * relative pointers (BlitMaskPtr and ImagePtr) + */ + for (sy = (y+startY); sy<0; sy++) { + ++nsy; + lineCount = *blitMaskPtr; + ++blitMaskPtr; + while (lineCount>0) { + ++blitMaskPtr; + pixCount = *blitMaskPtr; + ++blitMaskPtr; + if (pixCount > 0) (uInt8 *)imagePtr += pixCount*bytesPerPixel; + --lineCount; + } // while + } // for sy + } // if + + // Now do clipping on the bottom edge. This is easy. + if (y+endY > (int32)src.GetMaxY()) + ney = (src.GetMaxY()-y); + else + ney = endY; + + for (sy = nsy; (uInt32)sy <= ney; sy++) { + sx = x+startX; + lineCount = *blitMaskPtr; + ++blitMaskPtr; + + while (lineCount > 0) { + offset = *blitMaskPtr; + ++blitMaskPtr; + sx += offset; + pixCount = *blitMaskPtr; + ++blitMaskPtr; + + if (pixCount > 0) { + if (sx <= (int32)src.GetMaxX()) { + if ((sx < 0) && (sx+pixCount > 0)) { + pixCount += sx; // remember, sx is negative + (uInt8*)imagePtr -= sx*bytesPerPixel; // remember, sx is negative + sx = 0; + } // if sx<0 && sx+pixcount>0 + + if (sx+pixCount > (int32)src.GetMaxX()+1) { + distToEdge = (src.GetMaxX()-sx)+1; + xRight = (pixCount - distToEdge)*bytesPerPixel; + pixCount = distToEdge; + } else xRight = 0; // if sx+pixCount>MaxX + + if (sx >= 0) + src.CopyLineFrom(sx, y+sy, imagePtr,pixCount*bytesPerPixel); + + (uInt8*)imagePtr += xRight; // get any remainter from right edge clip + } // if sx <= MaxX + + sx += pixCount; + (uInt8*)imagePtr += pixCount*bytesPerPixel; + + } // if pixCount>0 + --lineCount; + } // while + } // for + + return; +} // ogBlit::GetBlitWithMask + +uInt32 +ogBlit::GetSize(void) { + return ogSprite::GetSize() + + sizeof(totalPixCount) + + sizeof(blitMaskSize) + + blitMaskSize + + sizeof(startX) + + sizeof(startY) + + sizeof(endX) + + sizeof(endY); +} // ogBlit::GetSize + +bool +ogBlit::LoadFrom(const char * filename, uInt32 offset) { + FILE * infile; + uInt32 lresult, tresult, totSize; + uInt32 tmpSize; + char headerIdent[4]; + + if (fileExists(filename)==false) return false; + if ((infile = fopen(filename,"rb"))==NULL) return false; + fseek(infile, offset, SEEK_SET); + + // for now just free up the previous image. This will be changed + // later so it doesn't affect the current image (if any) if there + // is a failure loading + + free(image); + delete [] pal; + delete [] blitMask; + imageSize = 0; + blitMaskSize = 0; + + tresult = 0; // total bytes we've read in so far + + lresult = fread(headerIdent, sizeof(headerIdent), 1, infile); + tresult += lresult*sizeof(headerIdent); + if ((headerIdent[0]!='B') || + (headerIdent[1]!='L') || + (headerIdent[2]!='T') || + (headerIdent[3]!=(char)0x1A)) { + fclose(infile); + return false; + } + lresult = fread(&totSize, sizeof(totSize), 1, infile); + tresult += lresult*sizeof(totSize); + + lresult = fread(&width, sizeof(width), 1, infile); + tresult += lresult*sizeof(width); + + lresult = fread(&height, sizeof(height), 1, infile); + tresult += lresult*sizeof(height); + + lresult = fread(&bitDepth, sizeof(bitDepth), 1, infile); + tresult += lresult*sizeof(bitDepth); + + lresult = fread(&RFP, sizeof(RFP), 1, infile); + tresult += lresult*sizeof(RFP); + + lresult = fread(&GFP, sizeof(GFP), 1, infile); + tresult += lresult*sizeof(GFP); + + lresult = fread(&BFP, sizeof(BFP), 1, infile); + tresult += lresult*sizeof(BFP); + + lresult = fread(&AFP, sizeof(AFP), 1, infile); + tresult += lresult*sizeof(AFP); + + lresult = fread(&rShift, sizeof(rShift), 1, infile); + tresult += lresult*sizeof(rShift); + + lresult = fread(&gShift, sizeof(gShift), 1, infile); + tresult += lresult*sizeof(gShift); + + lresult = fread(&bShift, sizeof(bShift), 1, infile); + tresult += lresult*sizeof(bShift); + + lresult = fread(&aShift, sizeof(aShift), 1, infile); + tresult += lresult*sizeof(aShift); + + lresult = fread(&tColour, sizeof(tColour), 1, infile); + tresult += lresult*sizeof(tColour); + + lresult = fread(&pixelFmtID, sizeof(pixelFmtID), 1, infile); + tresult += lresult*sizeof(pixelFmtID); + + lresult = fread(&bytesPerPixel, sizeof(bytesPerPixel), 1, infile); + tresult += lresult*sizeof(bytesPerPixel); + + lresult = fread(&dAlpha, sizeof(dAlpha), 1, infile); + tresult += lresult*sizeof(dAlpha); + + lresult = fread(&totalPixCount, sizeof(totalPixCount), 1, infile); + tresult += lresult*sizeof(totalPixCount); + + lresult = fread(&startX, sizeof(startX), 1, infile); + tresult += lresult*sizeof(startX); + + lresult = fread(&startY, sizeof(startY), 1, infile); + tresult += lresult*sizeof(startY); + + lresult = fread(&endX, sizeof(endX), 1, infile); + tresult += lresult*sizeof(endX); + + lresult = fread(&endY, sizeof(endY), 1, infile); + tresult += lresult*sizeof(endY); + + lresult = fread(&blitMaskSize, sizeof(blitMaskSize), 1, infile); + tresult += lresult*sizeof(blitMaskSize); + + lresult = fread(&imageSize, sizeof(imageSize), 1, infile); + tresult += lresult*sizeof(imageSize); + + blitMask = new uInt8[blitMaskSize]; + if (blitMask == NULL) { + fclose(infile); + return false; + } + + image = malloc(imageSize); + if (image == NULL) { + fclose(infile); + return false; + } + + // read in the blit mask + lresult = fread(blitMask, blitMaskSize, 1, infile); + tresult += lresult*blitMaskSize; + + // read in the image data + // it's possible that if we start saving only blit masks this section will be + // blank + lresult = fread(image, 1, imageSize, infile); + tresult += lresult; + + if (bitDepth==8) { + // 8bpp sprites have palettes + if (pal==NULL) pal = new ogRGBA8[256]; + if (pal==NULL) { + fclose(infile); + return false; + } // if pal==NULL + lresult = fread(&tmpSize, sizeof(tmpSize), 1, infile); + tresult += lresult*sizeof(tmpSize); + if (tmpSize>sizeof(ogRGBA8)*256) { + fclose(infile); + return false; + } + lresult = fread(pal, tmpSize, 1, infile); + tresult += lresult*tmpSize; + } // if bitDepth == 8 + + fclose(infile); + return (tresult == totSize); +} // ogBlit::LoadFrom + +void +ogBlit::Put(ogSurface& dest, int32 x, int32 y) { + int32 sx, sy; + uInt32 nsy, ney; + uInt8 lineCount, offset, pixCount; + uInt8* blitMaskPtr; + void * imagePtr; + uInt32 distToEdge, xRight, xx; + uInt8 r, g, b, a; + ogPixelFmt pixFmt; + + // can we draw anything? + if ((NULL == blitMask) || (NULL == image)) return; + + if (!dest.Avail()) return; + + // see if the blit is oustide the buffer + if ( ((x+startX) > (int32)dest.GetMaxX()) || ((x + endX) < 0) || + ((y+startY) > (int32)dest.GetMaxY()) || ((y + endY) < 0) ) return; + + blitMaskPtr = blitMask; + imagePtr = image; + + // first do clipping on the top edge + nsy = startY; + if (y+startY < 0) { + /* + * If we're here then part of the blit is above the top edge of the + * buffer. The distance to the top of the buffer is abs(y+startY). + * So, we need to loop through the blit geometry and advance the + * relative pointers (blitMaskPtr and imagePtr) + */ + for (sy = (y+startY); sy < 0; sy++) { + ++nsy; + lineCount = *blitMaskPtr; + ++blitMaskPtr; + + while (lineCount > 0) { + ++blitMaskPtr; + pixCount = *blitMaskPtr; + ++blitMaskPtr; + if (pixCount > 0) (uInt8 *)imagePtr += pixCount*bytesPerPixel; + --lineCount; + } // while + } // for sy + } // if + + // Now do clipping on the bottom edge. This is easy + // y is guaranteed to be >=0 + // I'm going to contradict myself and say that I don't think y is + // guaranteed to be >= 0. + + if (y+endY > (int32)dest.GetMaxY()) + ney = (dest.GetMaxY()-y); + else + ney = endY; + + dest.GetPixFmt(pixFmt); + + if ((dest.GetPixFmtID() != pixelFmtID) || (dest.IsBlending())) { + for (sy = nsy; (uInt32)sy <= ney; sy++) { + sx = x+startX; + lineCount = *blitMaskPtr; + ++blitMaskPtr; + while (lineCount > 0) { + offset = *blitMaskPtr; + ++blitMaskPtr; + sx += offset; + pixCount = *blitMaskPtr; + ++blitMaskPtr; + + if (pixCount > 0) { + if (sx <= (int32)dest.GetMaxX()) { + + if ((sx < 0) && (sx+(int32)pixCount > 0)) { + pixCount += sx; // remember, sx is negative + (uInt8*)imagePtr -= sx*bytesPerPixel; // remember, sx is negative + sx = 0; + } // if sx<0 && sx+pixCount>0 + + if (sx+pixCount > (int32)dest.GetMaxX()) { + distToEdge = (dest.GetMaxX()-sx)+1; + xRight = (pixCount-distToEdge)*bytesPerPixel; + pixCount = distToEdge; + } else xRight = 0; // if sx+pixCount>MaxX + + if (sx >= 0) + for (xx = 0; xx < pixCount; xx++) { + Unpack(GetPixel((uInt8*)imagePtr+(xx*bytesPerPixel)), + r, g, b, a); + dest.SetPixel(sx+xx, sy+y, r, g, b, a); + } // for + (uInt8*)imagePtr += xRight; + } // if sx <= maxX + sx += pixCount; + (uInt8*)imagePtr += pixCount*bytesPerPixel; + } // if pixCount != 0 + --lineCount; + } // while + } // for + } else { + for (sy = nsy; (uInt32)sy <= ney; sy++) { + sx = x+startX; + lineCount = *blitMaskPtr; + ++blitMaskPtr; + + while (lineCount > 0) { + offset = *blitMaskPtr; + ++blitMaskPtr; + sx += offset; + pixCount = *blitMaskPtr; + ++blitMaskPtr; + + if (pixCount > 0) { + if (sx <= (int32)dest.GetMaxX()) { + if ((sx < 0) && (sx+pixCount > 0)) { + pixCount += sx; // remember, sx is negative + (uInt8*)imagePtr -= sx*bytesPerPixel; // remember, sx is negative + sx = 0; + } // if sx<0 && sx+pixCount>0 + + if (sx+pixCount>(int32)dest.GetMaxX()+1) { + distToEdge = (dest.GetMaxX()-sx)+1; + xRight = (pixCount - distToEdge)*bytesPerPixel; + pixCount = distToEdge; + } else xRight = 0; // if sx+pixCount>MaxX + + if (sx >= 0) + dest.CopyLineTo(sx, y+sy, imagePtr, pixCount*bytesPerPixel); + (uInt8*)imagePtr += xRight; + } // if sx <= MaxX + sx += pixCount; + (uInt8*)imagePtr += pixCount*bytesPerPixel; + } // if pixCount>0 + --lineCount; + } // while + } // for + } // else + + return; +} // ogBlit::Put + +bool +ogBlit::SaveTo(const char * filename, int32 offset) { + /* + * saveTo + * + * saves a blit to disk. If the file doesn't exit then we will create + * a new one (doing this will ignore any specified offset). If the file + * exists, we will seek to the specified offset and place the bitmap there. + * If offset is -1, then we seek to the end of the file. + * + * This function will fail on files larger than 2GB. + * + */ + FILE * outfile = NULL; + char headerIdent[4]; + uInt32 tmpSize; + + if (image==NULL) return false; + if ((bitDepth==8) && (pal==NULL)) return false; + + if (fileExists(filename)==false) { // file doesn't exist + if ((outfile = fopen(filename,"wb")) == NULL) return false; + } else { + // file exists. Now we check to see where we put it + if (offset==-1) { + if ((outfile = fopen(filename, "ab")) == NULL) return false; + } else { + // we have an existing file and an offset to place the data + if ((outfile = fopen(filename, "wb")) == NULL) return false; + if (offset!=0) fseek(outfile, offset, SEEK_SET); + } // else + } // else + + tmpSize = GetSize(); + + headerIdent[0] = 'B'; + headerIdent[1] = 'L'; + headerIdent[2] = 'T'; + headerIdent[3] = (char)0x1A; // EOF marker + + // we store exactly how bit this sucker is inside the header. This includes + // the header information before it, and the size itself + fwrite(headerIdent, sizeof(headerIdent), 1, outfile); + + fwrite(&tmpSize, sizeof(tmpSize), 1, outfile); + fwrite(&width, sizeof(width), 1, outfile); + fwrite(&height, sizeof(height), 1, outfile); + fwrite(&bitDepth, sizeof(bitDepth), 1, outfile); + + fwrite(&RFP, sizeof(RFP), 1, outfile); + fwrite(&GFP, sizeof(GFP), 1, outfile); + fwrite(&BFP, sizeof(BFP), 1, outfile); + fwrite(&AFP, sizeof(AFP), 1, outfile); + + fwrite(&rShift, sizeof(rShift), 1, outfile); + fwrite(&gShift, sizeof(gShift), 1, outfile); + fwrite(&bShift, sizeof(bShift), 1, outfile); + fwrite(&aShift, sizeof(aShift), 1, outfile); + + fwrite(&tColour, sizeof(tColour), 1, outfile); + fwrite(&pixelFmtID, sizeof(pixelFmtID), 1, outfile); + fwrite(&bytesPerPixel, sizeof(bytesPerPixel), 1, outfile); + fwrite(&dAlpha, sizeof(dAlpha), 1, outfile); + + fwrite(&totalPixCount, sizeof(totalPixCount), 1, outfile); + + fwrite(&startX, sizeof(startX), 1, outfile); + fwrite(&startY, sizeof(startY), 1, outfile); + fwrite(&endX, sizeof(endX), 1, outfile); + fwrite(&endY, sizeof(endY), 1, outfile); + + fwrite(&blitMaskSize, sizeof(blitMaskSize), 1, outfile); + fwrite(&imageSize, sizeof(imageSize), 1, outfile); + + fwrite(blitMask, blitMaskSize, 1, outfile); + fwrite(image, 1, imageSize, outfile); + + if (bitDepth == 8) { + tmpSize = sizeof(ogRGBA8)*256; + fwrite(&tmpSize, sizeof(tmpSize), 1, outfile); + fwrite(pal, sizeof(ogRGBA8), 256, outfile); + } // if bitDepth == 8 + + fclose(outfile); + return true; +} // ogBlit::SaveTo + +ogBlit::~ogBlit(void) { + delete [] blitMask; + blitMask = NULL; + blitMaskSize = 0; + return; +} // ogBlit::~ogBlit + diff --git a/src/lib/objgfx40/ogDisplay_UbixOS.cc b/src/lib/objgfx40/ogDisplay_UbixOS.cc new file mode 100755 index 0000000..4cc578c --- /dev/null +++ b/src/lib/objgfx40/ogDisplay_UbixOS.cc @@ -0,0 +1,270 @@ +#include +#include +#include + +extern "C" { + #include + #include + #include + #include + #include + #include + } + +/* + * + * ogDisplay methods + * + */ + +void +initVESAMode(uInt16 mode) { + kprintf("Pre-initVESAMode\n"); + biosCall(0x10,0x4F02,mode,0x0,0x0,0x0,0x0,0x0,0x0); + kprintf("Post-initVESAMode\n"); + return; +} + +ogDisplay_UbixOS::ogDisplay_UbixOS(void) { + pages[0] = pages[1] = NULL; + activePage = visualPage = 0; + pal = new ogRGBA8[256]; + attributes = new ogAttributes(); + + VESAInfo = (ogVESAInfo *)0x11000; + modeInfo = (ogModeInfo *)0x11200; + + getVESAInfo(); + return; +} // ogDisplay_UbixOS::ogDisplay_UbixOS + +void +ogDisplay_UbixOS::GetModeInfo(uInt16 mode) { + kprintf("Pre-getModeInfo\n"); + biosCall(0x10,0x4F01,0x0,mode,0x0,0x0,0x0,0x1120,0x0); + kprintf("Post-getModeInfo\n"); + return; +} // ogDisplay_UbixOS::GetModeInfo + +void +ogDisplay_UbixOS::GetVESAInfo(void) { + VESAInfo->VBESignature[0] = 'V'; // First off initialize the structure. + VESAInfo->VBESignature[1] = 'B'; + VESAInfo->VBESignature[2] = 'E'; + VESAInfo->VBESignature[3] = '2'; + kprintf("Pre-getVESAInfo\n"); + biosCall(0x10,0x4F00,0x0,0x0,0x0,0x0,0x0,0x1100,0x0); + kprintf("Post-getVESAInfo\n"); + return; + } // ogDisplay_UbixOS::GetVESAInfo + +uInt16 +ogDisplay_UbixOS::FindMode(uInt32 _xRes, uInt32 _yRes, uInt32 _BPP) { + uInt16 mode; + + if ((320 == _xRes) && (200 == _yRes) && (8 == _BPP)) return 0x13; + +// if ((VESAInfo==NULL) || (VESAInfo->videoModePtr==NULL)) return 0; + if (NULL == modeInfo) return 0; + + for (mode = 0x100; mode < 0x1FF; mode++) { + getModeInfo(mode); + if ((modeInfo->xRes >= _xRes) && (modeInfo->yRes >= _yRes) && + (modeInfo->bitsPerPixel == _BPP)) + return mode; + } + + return 0; +} // ogDisplay_UbixOS::FindMode + +void ogDisplay_UbixOS::SetMode(uInt16 mode) { + + uInt32 size = 0x0, count = 0x0, i = 0x0; + + if (mode==0x13) { + + xRes = 320; + yRes = 200; + maxX = 319; + maxY = 199; + BPP = 8; + bytesPerPix = 1; + + redFieldPosition = 0; + greenFieldPosition = 0; + blueFieldPosition = 0; + alphaFieldPosition = 0; + + redShifter = 0; + greenShifter = 0; + blueShifter = 0; + alphaFieldPosition = 0; + + // UBU, THIS IS NULL BECAUSE WE DON'T EVER USE 320x200x256c! + // THIS COMMENT WILL COME BACK TO BITE YOU ON THE ASS + buffer = NULL; + + } else { + buffer = NULL; + mode |= 0x4000; // attempt lfb + getModeInfo(mode); + if (modeInfo->physBasePtr == 0) return; + buffer = (void *)modeInfo->physBasePtr; + size = modeInfo->yRes*modeInfo->bytesPerLine; + + xRes = modeInfo->bytesPerLine; + yRes = modeInfo->yRes; + maxX = modeInfo->xRes-1; + maxY = yRes-1; + + BPP = modeInfo->bitsPerPixel; + bytesPerPix = (BPP + 7) >> 3; + + redFieldPosition = modeInfo->redFieldPosition; + greenFieldPosition = modeInfo->greenFieldPosition; + blueFieldPosition = modeInfo->blueFieldPosition; + alphaFieldPosition = modeInfo->alphaFieldPosition; + + if (4 == bytesPerPix) { + modeInfo->alphaMaskSize = 8; + while ((alphaFieldPosition == redFieldPosition) || + (alphaFieldPosition == greenFieldPosition) || + (alphaFieldPosition == blueFieldPosition)) + alphaFieldPosition += 8; + } // if + + redShifter = 8-modeInfo->redMaskSize; + greenShifter = 8-modeInfo->greenMaskSize; + blueShifter = 8-modeInfo->blueMaskSize; + alphaShifter = 8-modeInfo->alphaMaskSize; + + if (modeInfo->alphaMaskSize != 0) + alphaMasker = ~(OG_MASKS[modeInfo->alphaMaskSize] << alphaFieldPosition); + else + alphaMasker = ~0; + + } // else not mode 0x13 + + owner = this; + dataState = ogAliasing; + + if ((lineOfs!=NULL) && (lSize!=0)) delete [] lineOfs; + lSize = yRes*sizeof(uInt32); + lineOfs = new uInt32[yRes];; + if (NULL == lineOfs) return; + + lineOfs[0] = 0; + for (count = 1; count < yRes; count++) + lineOfs[count] = lineOfs[count-1]+xRes; + + initVESAMode(mode); + + SetAntiAliasing(BPP > 8); + if (NULL == pal) pal = new ogRGBA8[256]; + SetPalette(DEFAULT_PALETTE); + + if (1 == bytesPerPix) { + pixFmtID = 0x08080808; + } else { + pixFmtID = (redFieldPosition) | + (greenFieldPosition << 8) | + (blueFieldPosition << 16) | + (alphaFieldPosition << 24); + } // else + + printOff = 0; + for (i = 0x0; i < ((size)/4096); i++) { + vmmRemapPage(modeInfo->physBasePtr + (i * 0x1000), + modeInfo->physBasePtr + (i * 0x1000)); + } // for i + return; +} // ogDisplay_UbixOS::SetMode + +void ogDisplay_UbixOS::SetPal(void) { + if (bytesPerPix != 1) return; + outportb(0x3c8,0); + for (uInt32 c = 0; c < 256; c++) { + outportb(0x3c9, pal[c].red >> 2); + outportb(0x3c9, pal[c].green >> 2); + outportb(0x3c9, pal[c].blue >> 2); + } // for + return; +} // ogDisplay_UbixOS::SetPal + +bool +ogDisplay_UbixOS::Alias(ogSurface& SrcObject, uInt32 x1, + uInt32 y1, uInt32 x2, uInt32 y2) { + SetLastError(ogNoAliasing); + return false; +} // ogDisplay_UbixOS::Alias + +bool +ogDisplay_UbixOS::Create(uInt32 _xRes, uInt32 _yRes,ogPixelFmt _pixFormat) { + uInt16 mode; + mode = 0x111; + setMode(mode); + /* + mode = findMode(_xRes, _yRes, _pixFormat.BPP); + if ((mode == 0) && ((_pixFormat.BPP==24) || (_pixFormat.BPP==32))) { + if (_pixFormat.BPP==24) _pixFormat.BPP=32; else _pixFormat.BPP=24; + mode=findMode(_xRes,_yRes,_pixFormat.BPP); + } // if + if (mode!=0) setMode(mode); + */ + return (mode!=0); +} // ogDisplay_UbixOS::Create + +bool +ogDisplay_UbixOS::Clone(ogSurface& SrcObject) { + SetLastError(ogNoCloning); + return false; +} // ogDisplay_UbixOS::Clone + +void +ogDisplay_UbixOS::CopyPal(ogSurface& SrcObject) { + ogSurface::CopyPal(SrcObject); + SetPal(); + return; +} // ogDisplay_UbixOS::CopyPal + +bool +ogDisplay_UbixOS::LoadPalette(const char *palfile) { + bool result; + if ((result = ogSurface::LoadPalette(palfile))==true) SetPal(); + return result; +} // ogDisplay_UbixOS::LoadPalette + +void +ogDisplay_UbixOS::SetPalette(uInt8 colour, uInt8 red, uInt8 green, uInt8 b +lue) { + if (NULL == pal) return; + ogSurface::SetRGBPalette(colour, red, green, blue); + outportb(0x3c8, colour); + outportb(0x3c9, red >> 2); + outportb(0x3c9, green >> 2); + outportb(0x3c9, blue >> 2); + + return; +} // ogDisplay_UbixOS::SetPalette + +void +ogDisplay_UbixOS::SetPalette(uInt8 colour, uInt8 red, uInt8 green, + uInt8 blue, uInt8 alpha) { + if (NULL == pal) return; + ogSurface::SetPalette(colour, red, green, blue, alpha); + outportb(0x3c8, colour); + outportb(0x3c9, red >> 2); + outportb(0x3c9, green >> 2); + outportb(0x3c9, blue >> 2); + + return; +} // ogDisplay_UbixOS::SetPalette + +ogDisplay_UbixOS::~ogDisplay_UbixOS(void) { + delete attributes; + delete pal; +//mji delete VESAInfo; +//mji delete modeInfo; + return; +} // ogDisplay_UbixOS::~ogDisplay_UbixOS + diff --git a/src/lib/objgfx40/ogDisplay_VESA.cpp b/src/lib/objgfx40/ogDisplay_VESA.cpp new file mode 100644 index 0000000..38c9ed2 --- /dev/null +++ b/src/lib/objgfx40/ogDisplay_VESA.cpp @@ -0,0 +1,1450 @@ +#include "objgfx40.h" +#include "defpal.inc" +#include "ogDisplay_VESA.h" +#include // for __tb +#include +#include +#include +#include +#include + +/* + * + * ogDisplay methods + * + */ + +void +initVESAMode(uInt16 mode) { + __dpmi_regs regs; + regs.x.ax = 0x4f02; + regs.x.bx = mode; + __dpmi_int(0x10, ®s); + return; +} + +ogDisplay_VESA::ogDisplay_VESA(void) : ogSurface() { + pages[0] = pages[1] = NULL; + activePage = visualPage = 0; + inGraphics = false; + VESAInfo = new ogVESAInfo; + modeInfo = new ogModeInfo; + pal = new ogRGBA8[256]; + attributes = new ogAttributes(); + + GetVESAInfo(); + + screenSelector = __dpmi_allocate_ldt_descriptors(1); + + return; +} // ogDisplay_VESA::ogDisplay_VESA + +uInt32 +ogDisplay_VESA::RawGetPixel(uInt32 x, uInt32 y) { + uInt32 result; + switch (bytesPerPix) { + case 4: + __asm__ __volatile__( + " push %%ds \n" // push ds + " mov %%ax, %%ds \n" // mov ds, ax (screenSelector) + " shl $2, %%ecx \n" // shl ecx, 2 {adjust for pixel size} + // " add (%%esi,%%ebx,4), %%edi \n" // add edi, [esi + ebx*4] + " add %%esi, %%edi \n" // add edi, esi + " add %%ecx, %%edi \n" // add edi, ecx + " mov (%%edi),%%eax \n" // eax,word ptr [edi] + " mov %%eax, %4 \n" // mov result, eax + " pop %%ds \n" // pop ds + : + : "D" (buffer), "S" (lineOfs[y]), // %0, %1 + "a" (screenSelector), "c" (x), "m" (result) // %2, %3, %4 + ); + break; + case 3: + __asm__ __volatile__( + " push %%ds \n" // push ds + " mov %%ax, %%ds \n" // mov ds, ax (screenSelector) + " mov %%ecx, %%eax \n" // mov eax, ecx - adjust for pixel size + " add %%ecx, %%ecx \n" // add ecx, ecx - adjust for pixel size + " add %%eax, %%ecx \n" // add ecx, eax - adjust for pixel size + " add %%esi, %%edi \n" // add edi, esi + // " add (%%esi,%%ebx,4), %%edi \n" // add edi, [esi + ebx*4] + " add %%ecx, %%edi \n" // add edi, ecx + " movzwl (%%edi),%%eax \n" // movzx edx,word ptr [edi] + " xor %%eax, %%eax \n" + " mov 2(%%edi), %%al \n" // mov al, [edi+2] + " shl $16, %%eax \n" // shl eax, 16 + " mov (%%edi), %%ax \n" // mov ax, [edi] + " mov %%eax, %4 \n" // mov result, eax + " pop %%ds \n" // pop ds + : + : "D" (buffer), "S" (lineOfs[y]), // %0, %1 + "a" (screenSelector), "c" (x), "m" (result) // %2, %3, %4 + ); + break; + case 2: + __asm__ __volatile__( + " push %%ds \n" // push ds + " mov %%ax, %%ds \n" // mov ds, ax (screenSelector) + " add %%esi, %%edi \n" // add edi, esi + " add %%ecx, %%ecx \n" // add ecx, ecx {adjust for pixel size} + " add %%ecx, %%edi \n" // add edi, ecx + " movzwl (%%edi),%%eax \n" // movzx edx,word ptr [edi] + " mov %%eax, %4 \n" // mov result, eax + " pop %%ds \n" // pop ds + : + : "D" (buffer), "S" (lineOfs[y]), // %0, %1 + "a" (screenSelector), "c" (x), "m" (result) // %2, %3, %4 + ); + break; + case 1: + __asm__ __volatile__( + " push %%ds \n" // push ds + " mov %%ax, %%ds \n" // mov ds, ax (screenSelector) + " add %%esi, %%edi \n" // add edi, esi + " add %%ecx, %%edi \n" // add edi, ecx + " movzbl (%%edi),%%eax \n" // movzx edx,byte ptr [edi] + " mov %%eax, %4 \n" // mov result, eax + " pop %%ds \n" // pop ds + : + : "D" (buffer), "S" (lineOfs[y]), // %0, %1 + "a" (screenSelector), "c" (x), "m" (result) // %2, %3, %4 + ); + break; + } // switch + return result; +} // ogDisplay_VESA::RawGetPixel + +void +ogDisplay_VESA::RawSetPixel(uInt32 x, uInt32 y, uInt32 colour) { + uInt32 newR, newG, newB, inverseA; + uInt8 sR, sG, sB, sA; + uInt8 dR, dG, dB; + + do { + if (IsBlending()) { + Unpack(colour, sR, sG, sB, sA); + if (0 == sA) return; + if (255 == sA) break; + inverseA = 255 - sA; + Unpack(RawGetPixel(x, y), dR, dG, dB); + newR = (dR * inverseA + sR * sA) >> 8; + newG = (dG * inverseA + sG * sA) >> 8; + newB = (dB * inverseA + sB * sA) >> 8; + colour = Pack(newR, newG, newB, inverseA); + } // if + } while (false); + + switch (bytesPerPix) { + case 4: + __asm__ __volatile__( + // { Calculate offset, prepare the pixel to be drawn } + " push %%ds \n" // push ds + " mov %%dx, %%ds \n" // mov ds, dx + + " shl $2, %%ecx \n" // shl eax, 2 {adjust for pixel size} + " add %%esi, %%edi \n" // add edi, esi + " add %%ecx, %%edi \n" // add edi, ecx + // { Draw the pixel } + " mov %%eax, (%%edi) \n" // mov [edi], eax + " pop %%ds \n" // pop ds + : + : "D" (buffer), "S" (lineOfs[y]), // %0, %1 + "c" (x), "a" (colour), // %2, %3 + "d" (screenSelector) // %4 + ); + break; + case 3: + __asm__ __volatile__( + // { Calculate offset, prepare the pixel to be drawn } + // " add (%%esi,%%ebx,4),%%edi \n" // add edi, [esi + ebx * 4] + " push %%ds \n" // push ds + " mov %%dx, %%ds \n" // mov ds, dx + " add %%esi, %%edi \n" // add edi, esi + " add %%ecx, %%edi \n" // add edi, ecx + " add %%ecx, %%edi \n" // add edi, ecx {adjust for pixel size} + " add %%ecx, %%edi \n" // add edi, ecx {adjust for pixel size} + // { Draw the pixel } + " mov %%ax, (%%edi) \n" // mov [edi], ax + " shr $16, %%eax \n" // shr eax, 16 + " mov %%al, 2(%%edi)\n" // mov [edi+2],al + " pop %%ds \n" // pop ds + : + : "D" (buffer), "S" (lineOfs[y]), // %0, %1 + "c" (x), "a" (colour), // %2, %3 + "d" (screenSelector) // %4 + ); + break; + case 2: + __asm__ __volatile__( + // { Calculate offset, prepare the pixel to be drawn } + " push %%ds \n" // push ds + " mov %%dx, %%ds \n" // mov ds, dx + " add %%ecx, %%ecx \n" // add ecx, ecx {adjust for pixel size} + " add %%esi, %%edi \n" // add edi, esi + " add %%ecx, %%edi \n" // add edi, ecx + // { Draw the pixel } + " mov %%ax, (%%edi) \n" // mov [edi], al + " pop %%ds \n" // pop ds + : + : "D" (buffer), "S" (lineOfs[y]), // %0, %1 + "c" (x), "a" (colour), // %2, %3 + "d" (screenSelector) // %4 + ); + break; + case 1: + __asm__ __volatile__( + // { Calculate offset, prepare the pixel to be drawn } + // " add (%%esi,%%ebx,4), %%edi \n" // add edi, [esi + ebx * 4] + " push %%ds \n" // push ds + " mov %%dx, %%ds \n" // mov ds, dx + " add %%esi, %%edi \n" // add edi, esi + " add %%ecx, %%edi \n" // add edi, ecx + // { Draw the pixel } + " mov %%al, (%%edi) \n" // mov [edi], al + " pop %%ds \n" // pop ds + : + : "D" (buffer), "S" (lineOfs[y]), // %0, %1 + "c" (x), "a" (colour), // %2, %3 + "d" (screenSelector) // %4 + ); + break; + } // switch + return; +} // ogDisplay_VESA::RawSetPixel + +void +ogDisplay_VESA::RawSetPixel(uInt32 x, uInt32 y, uInt8 r, uInt8 g, uInt8 b, uInt8 a) { + uInt32 newR, newG, newB, inverseA; + uInt8 dR, dG, dB; + uInt32 colour; + + do { + if (IsBlending()) { + if (0 == a) return; + if (255 == a) { + colour = Pack(r, g, b, a); + break; + } // if a == 255 + + inverseA = 255 - a; + Unpack(RawGetPixel(x, y), dR, dG, dB); + newR = (dR * inverseA + r * a) >> 8; + newG = (dG * inverseA + g * a) >> 8; + newB = (dB * inverseA + b * a) >> 8; + colour = Pack(newR, newG, newB, inverseA); + } else colour = Pack(r, g, b, a); + } while (false); + switch (bytesPerPix) { + case 4: + __asm__ __volatile__( + // { Calculate offset, prepare the pixel to be drawn } + " push %%ds \n" // push ds + " mov %%dx, %%ds \n" // mov ds, dx + + " shl $2, %%ecx \n" // shl eax, 2 {adjust for pixel size} + " add %%esi, %%edi \n" // add edi, esi + " add %%ecx, %%edi \n" // add edi, ecx + // { Draw the pixel } + " mov %%eax, (%%edi) \n" // mov [edi], eax + " pop %%ds \n" // pop ds + : + : "D" (buffer), "S" (lineOfs[y]), // %0, %1 + "c" (x), "a" (colour), // %2, %3 + "d" (screenSelector) // %4 + ); + break; + case 3: + __asm__ __volatile__( + // { Calculate offset, prepare the pixel to be drawn } + // " add (%%esi,%%ebx,4),%%edi \n" // add edi, [esi + ebx * 4] + " push %%ds \n" // push ds + " mov %%dx, %%ds \n" // mov ds, dx + " add %%esi, %%edi \n" // add edi, esi + " add %%ecx, %%edi \n" // add edi, ecx + " add %%ecx, %%edi \n" // add edi, ecx {adjust for pixel size} + " add %%ecx, %%edi \n" // add edi, ecx {adjust for pixel size} + // { Draw the pixel } + " mov %%ax, (%%edi) \n" // mov [edi], ax + " shr $16, %%eax \n" // shr eax, 16 + " mov %%al, 2(%%edi)\n" // mov [edi+2],al + " pop %%ds \n" // pop ds + : + : "D" (buffer), "S" (lineOfs[y]), // %0, %1 + "c" (x), "a" (colour), // %2, %3 + "d" (screenSelector) // %4 + ); + break; + case 2: + __asm__ __volatile__( + // { Calculate offset, prepare the pixel to be drawn } + " push %%ds \n" // push ds + " mov %%dx, %%ds \n" // mov ds, dx + " add %%ecx, %%ecx \n" // add ecx, ecx {adjust for pixel size} + " add %%esi, %%edi \n" // add edi, esi + " add %%ecx, %%edi \n" // add edi, ecx + // { Draw the pixel } + " mov %%ax, (%%edi) \n" // mov [edi], al + " pop %%ds \n" // pop ds + : + : "D" (buffer), "S" (lineOfs[y]), // %0, %1 + "c" (x), "a" (colour), // %2, %3 + "d" (screenSelector) // %4 + ); + break; + case 1: + __asm__ __volatile__( + // { Calculate offset, prepare the pixel to be drawn } + // " add (%%esi,%%ebx,4), %%edi \n" // add edi, [esi + ebx * 4] + " push %%ds \n" // push ds + " mov %%dx, %%ds \n" // mov ds, dx + " add %%esi, %%edi \n" // add edi, esi + " add %%ecx, %%edi \n" // add edi, ecx + // { Draw the pixel } + " mov %%al, (%%edi) \n" // mov [edi], al + " pop %%ds \n" // pop ds + : + : "D" (buffer), "S" (lineOfs[y]), // %0, %1 + "c" (x), "a" (colour), // %2, %3 + "d" (screenSelector) // %4 + ); + break; + } // switch + return; +} // ogDisplay_VESA::RawSetPixel + +bool +ogDisplay_VESA::Avail(void) { + return ( ((screenSelector != 0) || (buffer != NULL)) && (lineOfs != NULL)); +} // ogDisplay_VESA::Avail + +void +ogDisplay_VESA::GetModeInfo(uInt16 mode) { + __dpmi_regs regs; + memset(modeInfo, 0, sizeof(struct ogModeInfo)); + memset(®s, 0, sizeof(regs)); + dosmemput(modeInfo, sizeof(struct ogModeInfo), __tb); + + int ofs, seg; + + seg = __tb; // __tb is a buffer located in "dos memory". This buffer + ofs = __tb; // is used because the vesa driver cannot acces memory + // above 1 MB (your program is most likely to be located above 1MB). + + ofs &= 0xffff; // Make a real pointer (segment:offse = 16:16) + seg &= 0xffff0000; // from the address of the buffer. + seg >>= 4; + + regs.x.ax = 0x4f01; // Get the modeinfo of a certain vesa video mode, + // this is a structure which contains. + regs.x.cx = mode; // information needed by other functions below. + regs.x.es = seg; + regs.x.di = ofs; + __dpmi_int(0x10, ®s); + + /* This info is located in dos memory, so it has to be moved to your + * program's address space. + */ + dosmemget(__tb, sizeof(struct ogModeInfo), modeInfo); + return; + +} // ogDisplay_VESA::GetModeInfo + +void +ogDisplay_VESA::GetVESAInfo(void) { + unsigned int seg, ofs; + __dpmi_regs regs; + if (NULL == VESAInfo) VESAInfo = new ogVESAInfo; + if (NULL == VESAInfo) return; + + memset(VESAInfo, 0, sizeof(struct ogVESAInfo)); + memset(®s, 0, sizeof(regs)); + VESAInfo->VBESignature[0] = 'V'; // First off initialize the structure. + VESAInfo->VBESignature[1] = 'B'; + VESAInfo->VBESignature[2] = 'E'; + VESAInfo->VBESignature[3] = '2'; + + /* + + Because VBE funtions operate in real mode, we first have to move the + initialized structure to real-mode address space, so the structure can + be filled by the vesa function in real mode. + + */ + dosmemput(VESAInfo, sizeof(struct ogVESAInfo), __tb); + + + seg = __tb; // Calculate real mode address of the buffer. + ofs = __tb; + ofs &= 0xffff; + seg &= 0xffff0000; + seg >>= 4; + + regs.x.ax = 0x4F00; + regs.x.es = seg; + regs.x.di = ofs; + + __dpmi_int(0x10, ®s); // Get vesa info. + + // Move the structure back to + dosmemget(__tb, sizeof(struct ogVESAInfo), VESAInfo); + + VESAInfo->OEMStringPtr = (VESAInfo->OEMStringPtr & 0xFFFF) + + ((VESAInfo->OEMStringPtr & 0xFFFF0000) >> 12); + + VESAInfo->OEMVendorNamePtr= (VESAInfo->OEMVendorNamePtr& 0xFFFF) + + ((VESAInfo->OEMVendorNamePtr& 0xFFFF0000) >> 12); + + VESAInfo->OEMProductNamePtr= (VESAInfo->OEMProductNamePtr& 0xFFFF) + + ((VESAInfo->OEMProductNamePtr& 0xFFFF0000) >> 12); + + VESAInfo->OEMProductRevPtr= (VESAInfo->OEMProductRevPtr& 0xFFFF) + + ((VESAInfo->OEMProductRevPtr& 0xFFFF0000) >> 12); + + VESAInfo->videoModePtr = ((VESAInfo->videoModePtr & 0xFFFF0000) >> 12) + + (VESAInfo->videoModePtr & 0xFFFF); + + return; +} // ogDisplay_VESA::GetVESAInfo + +uInt16 +ogDisplay_VESA::FindMode(uInt32 _xRes, uInt32 _yRes, uInt32 _BPP) { + uInt16 mode; + + if ((320 == _xRes) && (200 == _yRes) && (8 == _BPP)) return 0x13; + +// if ((VESAInfo==NULL) || (VESAInfo->videoModePtr==NULL)) return 0; + if (NULL == modeInfo) return 0; + + for (mode = 0x100; mode < 0x1FF; mode++) { + GetModeInfo(mode); + if ((modeInfo->xRes >= _xRes) && (modeInfo->yRes >= _yRes) && + (modeInfo->bitsPerPixel == _BPP)) + return mode; + } + + return 0; +} // ogDisplay_VESA::FindMode + +void +ogDisplay_VESA::SetMode(uInt16 mode) { + uInt32 size, count; + __dpmi_meminfo mem_info; + + if (0x13 == mode) { + + xRes = 320; + yRes = 200; + maxX = 319; + maxY = 199; + BPP = 8; + bytesPerPix = 1; + + redFieldPosition = 0; + greenFieldPosition = 0; + blueFieldPosition = 0; + alphaFieldPosition = 0; + + redShifter = 0; + greenShifter = 0; + blueShifter = 0; + alphaFieldPosition = 0; + + mem_info.address = 0xA0000; + mem_info.size = 64000; + size = 63999; + buffer = NULL; + __dpmi_physical_address_mapping(&mem_info); + __dpmi_set_segment_base_address(screenSelector, mem_info.address); + __dpmi_set_segment_limit(screenSelector, size); + __dpmi_set_descriptor_access_rights(screenSelector, 0x40F3); + + } else { + buffer = NULL; + mode |= 0x4000; // attempt lfb + GetModeInfo(mode); + if (modeInfo->physBasePtr == 0) return; + size = modeInfo->yRes*modeInfo->bytesPerLine; + + xRes = modeInfo->bytesPerLine; + yRes = modeInfo->yRes; + maxX = modeInfo->xRes-1; + maxY = yRes-1; + + BPP = modeInfo->bitsPerPixel; + bytesPerPix = (BPP + 7) >> 3; + + redFieldPosition = modeInfo->redFieldPosition; + greenFieldPosition = modeInfo->greenFieldPosition; + blueFieldPosition = modeInfo->blueFieldPosition; + alphaFieldPosition = modeInfo->alphaFieldPosition; + + if (4 == bytesPerPix) { + modeInfo->alphaMaskSize = 8; + while ((alphaFieldPosition == redFieldPosition) || + (alphaFieldPosition == greenFieldPosition) || + (alphaFieldPosition == blueFieldPosition)) + alphaFieldPosition += 8; + } // if + + redShifter = 8-modeInfo->redMaskSize; + greenShifter = 8-modeInfo->greenMaskSize; + blueShifter = 8-modeInfo->blueMaskSize; + alphaShifter = 8-modeInfo->alphaMaskSize; + + if (modeInfo->alphaMaskSize != 0) + alphaMasker = ~(OG_MASKS[modeInfo->alphaMaskSize] << alphaFieldPosition); + else + alphaMasker = ~0; + + + mem_info.address = modeInfo->physBasePtr; + mem_info.size = size; + size = ((size+4095) >> 12); + __dpmi_physical_address_mapping(&mem_info); + __dpmi_set_segment_base_address(screenSelector, mem_info.address); + __dpmi_set_segment_limit(screenSelector,size); + __dpmi_set_descriptor_access_rights(screenSelector, 0xC0F3); + } // else + + owner = this; + dataState = ogAliasing; + inGraphics = true; + + if ((lineOfs!=NULL) && (lSize!=0)) delete [] lineOfs; + lSize = yRes*sizeof(uInt32); + lineOfs = new uInt32[yRes];; + if (lineOfs == NULL) return; + lineOfs[0] = 0; + for (count=1; count 8); +// antiAlias=(BPP>8); + if (8 == BPP) SetPal(); + Clear(Pack(0, 0, 0)); + return; +} // ogDisplay_VESA::SetMode + +void +ogDisplay_VESA::SetPal(void) { + if (bytesPerPix != 1) return; + outportb(0x3c8,0); + for (uInt32 c = 0; c < 256; c++) { + outportb(0x3c9, pal[c].red >> 2); + outportb(0x3c9, pal[c].green >> 2); + outportb(0x3c9, pal[c].blue >> 2); + } // for + return; +} // ogDisplay_VESA::SetPal + +void +ogDisplay_VESA::SetPalette(const ogRGBA8 newPal[256]) { + ogSurface::SetPalette(newPal); + SetPal(); + return; +} // ogDisplay_VESA::SetPalette; + +bool +ogDisplay_VESA::Alias(ogSurface& src, uInt32 x1, uInt32 y1, + uInt32 x2, uInt32 y2) { + + SetLastError(ogNoAliasing); + return false; +} // ogDisplay_VESA::Alias + +void +ogDisplay_VESA::Clear(uInt32 colour) { + uInt32 height = 0; + uInt32 xx, yy; + uInt8 r, g, b, a; + + if (!Avail()) return; + + do { + if (IsBlending()) { + Unpack(colour, r, g, b, a); + if (0 == a) return; + if (255 == a) break; + for (yy = 0; yy <= maxY; yy++) + for (xx = 0; xx <= maxX; xx++) + RawSetPixel(xx, yy, r, g, b, a); + } // if + } while (false); + + __asm__ __volatile__("cld\n"); + switch (bytesPerPix) { + case 4: + __asm__ __volatile__( + " push %%es \n" // push es + " mov %6, %%ax \n" // mov ax, screenSelector + " mov %%ax, %%es \n" // mov es, ax + " add (%%esi), %%edi \n" // add edi, [esi] + " mov %%ecx, %%esi \n" // mov esi, ecx + " inc %%edx \n" // inc edx (maxX) + " inc %%ebx \n" // inc ebx (maxY) + " mov %5, %%eax \n" // mov eax, colour + " mov %%edx, %%ecx \n" // mov ecx, edx + " shl $2, %%ecx \n" // shl ecx, 2 + " sub %%ecx, %%esi \n" // sub esi, ecx // adjust for pix size + "loop32: \n" + " mov %%edx, %%ecx \n" // mov ecx, edx + " rep \n" + " stosl \n" + " add %%esi, %%edi \n" // add edi, esi + " dec %%ebx \n" + " jnz loop32 \n" + " pop %%es \n" // pop es + : + : "D" (buffer), "S" (lineOfs), // %0, %1 + "b" (maxY), "c" (xRes), "d" (maxX), // %2, %3, %4 + "m" (colour), "m" (screenSelector) // %5, %6 + ); + break; + case 3: + __asm__ __volatile__( + " push %%es \n" // push es + " mov %7, %%ax \n" // mov ax, screenSelector + " mov %%ax, %%es \n" // mov es, ax + " add (%%esi), %%edi \n" // add edi, [esi] + " mov %%ecx, %%esi \n" // mov esi, ecx + " inc %%edx \n" // inc edx (maxX) + " inc %%ebx \n" // inc ebx (maxY) + " mov %5, %%eax \n" // mov eax, colour + " sub %%edx, %%esi \n" // sub esi, edx // adjust for pix size + " mov %%ebx, %6 \n" // mov height, ebx + " sub %%edx, %%esi \n" // sub esi, edx // adjust for pix size + " mov %%eax, %%ebx \n" // mov ebx, eax + " sub %%edx, %%esi \n" // sub esi, edx // adjust for pix size + " shr $16, %%ebx \n" // shr ebx, 16 + "oloop24: \n" + " mov %%edx, %%ecx \n" // mov ecx, edx + "iloop24: \n" + " mov %%ax,(%%edi) \n" // mov [edi],ax + " movb %%bl,2(%%edi) \n" // mov [edi+2],bl + " add $3, %%edi \n" // add edi, 3 + " dec %%ecx \n" // dec ecx + " jnz iloop24 \n" + " add %%esi, %%edi \n" // add edi, esi + " decl %6 \n" // dec height + " jnz oloop24 \n" + " pop %%es \n" // pop es + : + : "D" (buffer), "S" (lineOfs), // %0, %1 + "b" (maxY), "c" (xRes), "d" (maxX), // %2, %3, %4 + "m" (colour), "m" (height), // %5, %6 + "m" (screenSelector) // %7 + ); + break; + case 2: + __asm__ __volatile__( + " push %%es \n" // push es + " mov %6, %%ax \n" // mov ax, screenSelector + " mov %%ax, %%es \n" // mov es, ax + " add (%%esi), %%edi \n" // add edi, [esi] + " mov %%ecx, %%esi \n" // mov esi, ecx + " inc %%edx \n" // inc edx (maxX) + " inc %%ebx \n" // inc ebx (maxY) + " sub %%edx, %%esi \n" // sub esi, edx + " mov %5, %%eax \n" // mov eax, colour + " sub %%edx, %%esi \n" // sub esi, edx // adjust for pix size + " mov %%ax, %%cx \n" // mov cx, ax + " shl $16, %%eax \n" // shl eax, 16 + " mov %%cx, %%ax \n" // mov ax, cx + "loop16: \n" + " mov %%edx, %%ecx \n" // mov ecx, edx + " shr $1, %%ecx \n" // shr ecx, 1 + " rep \n" + " stosl \n" + " jnc noc16 \n" + " stosw \n" + "noc16: \n" + " add %%esi, %%edi \n" // add edi, esi + " dec %%ebx \n" + " jnz loop16 \n" + " pop %%es \n" + : + : "D" (buffer), "S" (lineOfs), // %0, %1 + "b" (maxY), "c" (xRes), "d" (maxX), // %2, %3, %4 + "m" (colour), "m" (screenSelector) // %5, %6 + ); + break; + + case 1: + __asm__ __volatile__( + " push %%es \n" // push es + " mov %6, %%ax \n" // mov ax, screenSelector + " mov %%ax, %%es \n" // mov es, ax + " add (%%esi), %%edi \n" // add edi, [esi] + " mov %%ecx, %%esi \n" // mov esi, ecx + " inc %%edx \n" // inc edx (maxY) + " inc %%ebx \n" // inc ebx (maxX) + " mov %5, %%eax \n" // mov eax, colour + " sub %%edx, %%esi \n" // sub esi, edx + " mov %%al, %%ah \n" // mov ah, al + " mov %%ax, %%cx \n" // mov cx, ax + " shl $16, %%eax \n" // shl eax, 16 + " mov %%cx, %%ax \n" // mov ax, cx + "loop8: \n" + " push %%edx \n" + " mov %%edx, %%ecx \n" // mov ecx, edx + " and $3, %%edx \n" // and edx, 3 + " shr $2, %%ecx \n" // shr ecx, 2 + " rep \n" + " stosl \n" + " mov %%edx, %%ecx \n" // mov ecx, edx + " rep \n" + " stosb \n" + " pop %%edx \n" + " add %%esi, %%edi \n" // add edi, esi + " dec %%ebx \n" + " jnz loop8 \n" + " pop %%es \n" // pop es + : + : "D" (buffer), "S" (lineOfs), // %0, %1 + "b" (maxY), "c" (xRes), "d" (maxX), // %2, %3, %4 + "m" (colour), "m" (screenSelector) // %5, %6 + ); + break; + } // switch + return; +} // ogDisplay_VESA::Clear + +void +ogDisplay_VESA::CopyLineTo(uInt32 dx, uInt32 dy, const void * src, + uInt32 size) { + /* + * CopyLineTo() + * + * Inputs: + * + * dx - Destination X of the target buffer + * dy - Destination Y of the target buffer + * src - buffer to copy + * size - size in bytes *NOT* pixels + * + * Copies a run of pixels (of the same format) to (x,y) of a buffer + * + * This method is required because of the different implementations of + * copying a run of pixels to a buffer + * + * WARNING!!! This does *NO* error checking. It is assumed that you've + * done all of that. CopyLineTo and CopyLineFrom are the only + * methods that don't check to make sure you're hosing things. Don't + * use this method unless YOU KNOW WHAT YOU'RE DOING!!!!!!!!! + */ + movedata(_my_ds(),(uInt32)src, + screenSelector,(uInt32)((uInt8*)buffer+(lineOfs[dy]+dx*bytesPerPix) ), + size); + + return; +} // ogSurface::CopyLineTo + +void +ogDisplay_VESA::CopyLineFrom(uInt32 sx, uInt32 sy, void * dest, uInt32 size) { + /* + * CopyLineFrom() + * + * Inputs: + * + * sx - Source X of the target buffer + * sy - Source Y of the target buffer + * dest - where to put it + * size - size in bytes *NOT* pixels + * + * Copies a run of pixels (of the same format) to (x,y) of a buffer + * + * This method is required because of the different implementations of + * copying a run of pixels to a buffer + * + * WARNING!!! This does *NO* error checking. It is assumed that you've + * done all of that. CopyLineTo and CopyLineFrom are the only + * methods that don't check to make sure you're hosing things. Don't + * use this method unless YOU KNOW WHAT YOU'RE DOING!!!!!!!!! + */ + movedata(screenSelector,(uInt32)((uInt8*)buffer+(lineOfs[sy]+sx*bytesPerPix ) ), + _my_ds(),(uInt32)dest, + size); + + return; +} // ogDisplay_VESA::CopyLineFrom + +bool +ogDisplay_VESA::Create(uInt32 _xRes, uInt32 _yRes, ogPixelFmt _pixFormat) { + uInt16 mode; + mode = FindMode(_xRes, _yRes, _pixFormat.BPP); + if ((mode == 0) && ((_pixFormat.BPP==24) || (_pixFormat.BPP==32))) { + if (_pixFormat.BPP==24) _pixFormat.BPP=32; else _pixFormat.BPP=24; + mode = FindMode(_xRes,_yRes,_pixFormat.BPP); + } // if + if (mode!=0) SetMode(mode); + return (mode!=0); +} // ogDisplay_VESA::Create + +bool +ogDisplay_VESA::Clone(ogSurface& src) { + SetLastError(ogNoCloning); + return false; +} // ogDisplay_VESA::Clone + +void +ogDisplay_VESA::CopyPalette(ogSurface& src) { + ogSurface::CopyPalette(src); + SetPal(); + return; +} // ogDisplay_VESA::CopyPalette + +uInt32 +ogDisplay_VESA::GetPixel(int32 x, int32 y) { + uInt32 result; + if (!Avail()) return GetTransparentColor(); + if (((uInt32)x>maxX) || ((uInt32)y>maxY)) + return GetTransparentColor(); + switch (bytesPerPix) { + case 4: + __asm__ __volatile__( + " push %%ds \n" // push ds + " mov %%ax, %%ds \n" // mov ds, ax (screenSelector) + " shl $2, %%ecx \n" // shl ecx, 2 {adjust for pixel size} + // " add (%%esi,%%ebx,4), %%edi \n" // add edi, [esi + ebx*4] + " add %%esi, %%edi \n" // add edi, esi + " add %%ecx, %%edi \n" // add edi, ecx + " mov (%%edi),%%eax \n" // eax, dword ptr [edi] + " mov %%eax, %4 \n" // mov result, eax + " pop %%ds \n" // pop ds + : + : "D" (buffer), "S" (lineOfs[y]), // %0, %1 + "a" (screenSelector), "c" (x), "m" (result) // %2, %3, %4 + ); + break; + case 3: + __asm__ __volatile__( + " push %%ds \n" // push ds + " mov %%ax, %%ds \n" // mov ds, ax (screenSelector) + " mov %%ecx, %%eax \n" // mov eax, ecx - adjust for pixel size + " add %%ecx, %%ecx \n" // add ecx, ecx - adjust for pixel size + " add %%eax, %%ecx \n" // add ecx, eax - adjust for pixel size + " add %%esi, %%edi \n" // add edi, esi + // " add (%%esi,%%ebx,4), %%edi \n" // add edi, [esi + ebx*4] + " add %%ecx, %%edi \n" // add edi, ecx + " movzwl (%%edi),%%eax \n" // movzx edx,word ptr [edi] + " xor %%eax, %%eax \n" + " mov 2(%%edi), %%al \n" // mov al, [edi+2] + " shl $16, %%eax \n" // shl eax, 16 + " mov (%%edi), %%ax \n" // mov ax, [edi] + " mov %%eax, %4 \n" // mov result, eax + " pop %%ds \n" // pop ds + : + : "D" (buffer), "S" (lineOfs[y]), // %0, %1 + "a" (screenSelector), "c" (x), "m" (result) // %2, %3, %4 + ); + break; + case 2: + __asm__ __volatile__( + " push %%ds \n" // push ds + " mov %%ax, %%ds \n" // mov ds, ax (screenSelector) + " add %%esi, %%edi \n" // add edi, esi + " add %%ecx, %%ecx \n" // add ecx, ecx {adjust for pixel size} + " add %%ecx, %%edi \n" // add edi, ecx + " movzwl (%%edi),%%eax \n" // movzx edx,word ptr [edi] + " mov %%eax, %4 \n" // mov result, eax + " pop %%ds \n" // pop ds + : + : "D" (buffer), "S" (lineOfs[y]), // %0, %1 + "a" (screenSelector), "c" (x), "m" (result) // %2, %3, %4 + ); + break; + case 1: + __asm__ __volatile__( + " push %%ds \n" // push ds + " mov %%ax, %%ds \n" // mov ds, ax (screenSelector) + " add %%esi, %%edi \n" // add edi, esi + " add %%ecx, %%edi \n" // add edi, ecx + " movzbl (%%edi),%%eax \n" // movzx edx,byte ptr [edi] + " mov %%eax, %4 \n" // mov result, eax + " pop %%ds \n" // pop ds + : + : "D" (buffer), "S" (lineOfs[y]), // %0, %1 + "a" (screenSelector), "c" (x), "m" (result) // %2, %3, %4 + ); + break; + } // switch + return result; +} // ogDisplay_VESA::GetPixel + +void * +ogDisplay_VESA::GetPtr(uInt32 x, uInt32 y) { + return NULL; +} // ogDisplay_VESA::GetPtr + +void +ogDisplay_VESA::HLine(int32 x1, int32 x2, int32 y, uInt32 colour) { + int32 tmp; + uInt8 r, g, b, a; + + if (!Avail()) return; + if ((uInt32)y>maxY) return; + if (x1 > x2) { + tmp= x1; + x1 = x2; + x2 = tmp; + } // if + if (x1 < 0) x1 = 0; + if (x2 > (int32)maxX) x2 = maxX; + if (x2 < x1) return; + + if (IsBlending()) { + Unpack(colour, r, g, b, a); + if (0 == a) return; + if (255 == a) { + for (tmp = x1; tmp <= x2; tmp++) + RawSetPixel(tmp, y, r, g, b, a); + return; + } // if a == 255 + } // if blending + + __asm__ __volatile__("cld \n"); + switch (bytesPerPix) { + case 4: + __asm__ __volatile__( + " push %%es \n" // push es + " mov %%dx, %%es \n" // mov es, dx + " sub %%ebx, %%ecx \n" // sub ecx, ebx + " add %%esi, %%edi \n" // add edi, esi + " inc %%ecx \n" + " shl $2, %%ebx \n" // shl ebx, 2 + " add %%ebx, %%edi \n" // add edi, ebx + " rep \n" + " stosl \n" + " pop %%es \n" // pop es + : + : "D" (buffer), "S" (lineOfs[y]), // %0, %1 + "a" (colour), "b" (x1), // %2, %3 + "c" (x2), "d" (screenSelector) // %4, %5 + ); + break; + case 3: + __asm__ __volatile__( + " push %%es \n" // push es + " mov %%ax, %%es \n" // mov es, ax + " mov %2, %%eax \n" + " sub %%ebx, %%ecx \n" // sub ecx, ebx + " add %%esi, %%edi \n" // add edi, esi + " add %%ebx, %%ebx \n" // add ebx, ebx - pix size + " inc %%ecx \n" // inc ecx + " add %%edx, %%ebx \n" // add ebx, edx - pix size + " add %%ebx, %%edi \n" // add edi, ebx + " mov %%eax, %%ebx \n" // mov ebx, eax + " shr $16, %%ebx \n" // shr ebx, 16 + "hLlop24: \n" + " mov %%ax, (%%edi) \n" // mov [edi], ax + " mov %%bl, 2(%%edi)\n" // mov [edi+2], bl + " add $3, %%edi \n" // add edi, 3 + " dec %%ecx \n" // dec ecx + " jnz hLlop24 \n" + " pop %%es \n" // pop es + + : + : "D" (buffer), "S" (lineOfs[y]), // %0, %1 + "m" (colour), "b" (x1), // %2, %3 + "c" (x2), "d" (x1), "a" (screenSelector) // %4, %5 + ); + break; + case 2: + __asm__ __volatile__( + " push %%es \n" + " mov %%dx, %%es \n" // mov es, dx + " sub %%ebx, %%ecx \n" // sub ecx, ebx + " add %%ebx, %%ebx \n" // add ebx, ebx - pix size + " inc %%ecx \n" // inc ecx + " add %%ebx, %%edi \n" // add edi, ebx + " add %%esi, %%edi \n" // add edi, esi + " xor %%edx, %%edx \n" // xor edx, edx + " mov %%ax, %%dx \n" // mov dx, ax + " shl $16, %%eax \n" // shl eax, 16 + " add %%edx, %%eax \n" // add eax, edx + + " shr $1, %%ecx \n" // shr ecx, 1 + " rep \n" + " stosl \n" + " jnc hLnoc16 \n" + " stosw \n" + "hLnoc16: \n" + " pop %%es \n" + : + : "D" (buffer), "S" (lineOfs[y]), // %0, %1 + "a" (colour), "b" (x1), // %2, %3 + "c" (x2), "d" (screenSelector) + ); + break; + case 1: + __asm__ __volatile__( + " push %%es \n" // push es + " mov %%dx, %%es \n" // mov es, dx + " add %%ebx, %%edi \n" // add edi, ebx + " add %%esi, %%edi \n" // add edi, esi + " and $0xff, %%eax \n" // and eax, 0ffh + " sub %%ebx, %%ecx \n" // sub ecx, ebx + " mov %%al, %%ah \n" // mov ah, al + " inc %%ecx \n" // inc ecx + " mov %%eax, %%ebx \n" // mov ebx, eax + " shl $16, %%ebx \n" // shl ebx, 16 + " add %%ebx, %%eax \n" // add eax, ebx + + " mov %%ecx, %%edx \n" // mov edx, ecx + " mov $4, %%ecx \n" // mov ecx, 4 + " sub %%edi, %%ecx \n" // sub ecx, edi + " and $3, %%ecx \n" // and ecx, 3 + " sub %%ecx, %%edx \n" // sub edx, ecx + " jle LEndBytes \n" + " rep \n" + " stosb \n" + " mov %%edx, %%ecx \n" // mov ecx, edx + " and $3, %%edx \n" // and edx, 3 + " shr $2, %%ecx \n" // shr ecx, 2 + " rep \n" + " stosl \n" + "LEndBytes: \n" + " add %%edx, %%ecx \n" // add ecx, edx + " rep \n" + " stosb \n" + " pop %%es \n" + : + : "D" (buffer), "S" (lineOfs[y]), // %0, %1 + "a" (colour), "b" (x1), // %2, %3 + "c" (x2), "d" (screenSelector) + ); + break; + } // switch + return; +} // ogDisplay_VESA::HLine + +bool +ogDisplay_VESA::LoadPalette(const char *palfile) { + bool result; + if ((result = ogSurface::LoadPalette(palfile))==true) SetPal(); + return result; +} // ogDisplay_VESA::LoadPalette + +void +ogDisplay_VESA::SetPixel(int32 x, int32 y, uInt32 colour) { + uInt32 newR, newG, newB, inverseA; + uInt8 sR, sG, sB, sA; + uInt8 dR, dG, dB; + + if (!Avail()) return; + if (((uInt32)x > maxX) || ((uInt32)y > maxY)) return; + + do { + if (IsBlending()) { + Unpack(colour, sR, sG, sB, sA); + if (0 == sA) return; + if (255 == sA) break; + inverseA = 255 - sA; + Unpack(RawGetPixel(x, y), dR, dG, dB); + newR = (dR * inverseA + sR * sA) >> 8; + newG = (dG * inverseA + sG * sA) >> 8; + newB = (dB * inverseA + sB * sA) >> 8; + colour = Pack(newR, newG, newB, inverseA); + } // if + } while (false); + + switch (bytesPerPix) { + case 4: + __asm__ __volatile__( + // { Calculate offset, prepare the pixel to be drawn } + " push %%ds \n" // push ds + " mov %4, %%dx \n" // mov dx, screenSelector + " mov %%dx, %%ds \n" // mov ds, dx + " shl $2, %%ecx \n" // shl eax, 2 {adjust for pixel size} + " add %%esi, %%edi \n" // add edi, esi + " add %%ecx, %%edi \n" // add edi, ecx + // { Draw the pixel } + " mov %%eax, (%%edi)\n" // mov [edi], eax + " pop %%ds \n" // pop ds + : + : "D" (buffer), "S" (lineOfs[y]), // %0, %1 + "c" (x), "a" (colour), "m" (screenSelector) // %2, %3, %4 + ); + break; + case 3: + __asm__ __volatile__( + // { Calculate offset, prepare the pixel to be drawn } + " push %%ds \n" // push ds + " mov %4, %%dx \n" // mov dx, screenSelector + " mov %%dx, %%ds \n" // mov ds, dx + " add %%esi, %%edi \n" // add edi, esi + " add %%ecx, %%edi \n" // add edi, ecx + " add %%ecx, %%edi \n" // add edi, ecx {adjust for pixel size} + " add %%ecx, %%edi \n" // add edi, ecx {adjust for pixel size} + // { Draw the pixel } + " mov %%ax, (%%edi) \n" // mov [edi], ax + " shr $16, %%eax \n" // shr eax, 16 + " mov %%al, 2(%%edi)\n" // mov [edi+2],al + " pop %%ds \n" // pop ds + : + : "D" (buffer), "S" (lineOfs[y]), // %0, %1 + "c" (x), "a" (colour), "m" (screenSelector) // %2, %3, %4 + ); + break; + case 2: + __asm__ __volatile__( + // { Calculate offset, prepare the pixel to be drawn } + " push %%ds \n" + " mov %4, %%dx \n" + " mov %%dx, %%ds \n" + + " add %%ecx, %%ecx \n" // add ecx, ecx {adjust for pixel size} + " add %%esi, %%edi \n" // add edi, esi + " mov %3, %%eax \n" // mov eax, colour + " add %%ecx, %%edi \n" // add edi, ecx + // { Draw the pixel } + " mov %%ax, (%%edi) \n" // mov [edi], al + " pop %%ds\n" + + : + : "D" (buffer), "S" (lineOfs[y]), // %0, %1 + "c" (x), "a" (colour), "m" (screenSelector) // %2, %3, %4 + ); + break; + + case 1: + __asm__ __volatile__( + // { Calculate offset, prepare the pixel to be drawn } + " push %%ds \n" + " mov %4, %%dx \n" + " mov %%dx, %%ds \n" + " add %%esi, %%edi \n" // add edi, esi + " add %%ecx, %%edi \n" // add edi, ecx + // { Draw the pixel } + " mov %%al, (%%edi) \n" // mov [edi], al + " pop %%ds\n" + : + : "D" (buffer), "S" (lineOfs[y]), // %0, %1 + "c" (x), "a" (colour), "m" (screenSelector) // %2, %3, %4 + ); + break; + } // switch + return; +} // ogDisplay_VESA::SetPixel + +void +ogDisplay_VESA::SetPalette(uInt8 colour, uInt8 red, uInt8 green, uInt8 blue) { + if (NULL == pal) return; + ogSurface::SetPalette(colour,red,green,blue); + outportb(0x3c8, colour); + outportb(0x3c9, red >> 2); + outportb(0x3c9, green >> 2); + outportb(0x3c9, blue >> 2); + + return; +} // ogDisplay_VESA::SetPalette + +void +ogDisplay_VESA::SetPalette(uInt8 colour, uInt8 red, uInt8 green, + uInt8 blue, uInt8 alpha) { + if (NULL == pal) return; + ogSurface::SetPalette(colour, red, green, blue, alpha); + outportb(0x3c8, colour); + outportb(0x3c9, red >> 2); + outportb(0x3c9, green >> 2); + outportb(0x3c9, blue >> 2); + + return; +} // ogDisplay_VESA::SetPalette + +void +ogDisplay_VESA::VFlip(void) { + if (!Avail()) return; + + switch (bytesPerPix) { + case 4: + __asm__ __volatile__( + " push %%ds \n" // push ds + " mov %%ax, %%ds \n" // mov ds, ax + " add %%edi, %%esi \n" // add esi, edi + "vf32lop: \n" + " push %%esi \n" // push esi + " push %%edi \n" // push edi + "vf32lop2: \n" + " mov (%%edi),%%eax \n" // mov eax, [edi] + " mov (%%esi),%%ecx \n" // mov ecx, [esi] + " mov %%eax,(%%esi) \n" // mov [esi], eax + " mov %%ecx,(%%edi) \n" // mov [edi], ecx + " add $4, %%edi \n" // add edi, 4 + " sub $4, %%esi \n" // sub esi, 4 + " cmp %%esi, %%edi \n" // cmp edi, esi + " jbe vf32lop2 \n" + " pop %%edi \n" // pop edi + " pop %%esi \n" // pop esi + " add %%ebx, %%esi \n" // add esi, ebx + " add %%ebx, %%edi \n" // add edi, ebx + " dec %%edx \n" + " jnz vf32lop \n" + " pop %%ds \n" // pop ds + : + : "D" ((char *)buffer+lineOfs[0]), "S" (maxX*4), // %0, %1 + "b" (xRes), "d" (maxY+1), "a" (screenSelector) // %2, %3, %4 + ); + break; + case 3: + __asm__ __volatile__( + " push %%ds \n" // push ds + " mov %%ax, %%ds \n" // mov ds, ax + " add %%edi, %%esi \n" // add esi, edi + "vf24lop: \n" + " push %%esi \n" // push esi + " push %%edi \n" // push edi + "vf24lop2: \n" + " mov (%%edi),%%ax \n" // mov ax, [edi] + " mov 2(%%edi),%%dl \n" // mov dl, [edi+2] + " mov (%%esi),%%cx \n" // mov cx, [esi] + " mov 2(%%esi),%%dh \n" // mov dh, [esi+2] + " mov %%ax,(%%esi) \n" // mov [esi], ax + " mov %%dl,2(%%esi) \n" // mov [esi+2], dl + " mov %%cx,(%%edi) \n" // mov [edi], cx + " mov %%dh,2(%%edi) \n" // mov [edi+2], dh + " add $3, %%edi \n" // add edi, 3 + " sub $3, %%esi \n" // sub esi, 3 + " cmp %%esi, %%edi \n" // cmp edi, esi + " jbe vf24lop2 \n" + " pop %%edi \n" // pop edi + " pop %%esi \n" // pop esi + " add %%ebx, %%esi \n" // add esi, ebx + " add %%ebx, %%edi \n" // add edi, ebx + " decl %3 \n" // dec height + " jnz vf24lop \n" + " pop %%ds \n" // pop ds + : + : "D" ((char *)buffer+lineOfs[0]), "S" (maxX*3), // %0, %1 + "b" (xRes), "d" (maxY+1), "a" (screenSelector) // %2, %3, %4 + ); + break; + case 2: + __asm__ __volatile__( + " push %%ds \n" // push ds + " mov %%ax, %%ds \n" // mov ds, ax + " add %%edi, %%esi \n" // add esi, edi + "vf16lop: \n" + " push %%esi \n" // push esi + " push %%edi \n" // push edi + "vf16lop2: \n" + " mov (%%edi),%%ax \n" // mov ax, [edi] + " mov (%%esi),%%cx \n" // mov cx, [esi] + " mov %%ax,(%%esi) \n" // mov [esi], ax + " mov %%cx,(%%edi) \n" // mov [edi], cx + " add $2, %%edi \n" // add edi, 2 + " sub $2, %%esi \n" // sub esi, 2 + " cmp %%esi, %%edi \n" // cmp edi, esi + " jbe vf16lop2 \n" + " pop %%edi \n" // pop edi + " pop %%esi \n" // pop esi + " add %%ebx, %%esi \n" // add esi, ebx + " add %%ebx, %%edi \n" // add edi, ebx + " dec %%edx \n" + " jnz vf16lop \n" + " pop %%ds \n" // pop ds + : + : "D" ((char *)buffer+lineOfs[0]), "S" (maxX*2), // %0, %1 + "b" (xRes), "d" (maxY+1), "a" (screenSelector) // %2, %3, %4 + ); + break; + case 1: + __asm__ __volatile__( + " push %%ds \n" // push ds + " mov %%ax, %%ds \n" // mov ds, ax + " add %%edi, %%esi \n" // add esi, edi + "vf8lop: \n" + " push %%esi \n" // push esi + " push %%edi \n" // push edi + "vf8lop2: \n" + " mov (%%edi),%%al \n" // mov al, [edi] + " mov (%%esi),%%ah \n" // mov ah, [esi] + " mov %%al,(%%esi) \n" // mov [esi], al + " mov %%ah,(%%edi) \n" // mov [edi], ah + " inc %%edi \n" // inc edi + " dec %%esi \n" // dec esi + " cmp %%esi, %%edi \n" // cmp edi, esi + " jbe vf8lop2 \n" + " pop %%edi \n" // pop edi + " pop %%esi \n" // pop esi + " add %%ebx, %%esi \n" // add esi, ebx + " add %%ebx, %%edi \n" // add edi, ebx + " dec %%edx \n" + " jnz vf8lop \n" + " pop %%ds \n" // pop ds + : + : "D" ((char *)buffer+lineOfs[0]), "S" (maxX), // %0, %1 + "b" (xRes), "d" (maxY+1), "a" (screenSelector) // %2, %3, %4 + ); + break; + } // switch + return; +} // ogDisplay_VESA::VFlip + +void +ogDisplay_VESA::VLine(int32 x, int32 y1, int32 y2, uInt32 colour) { + int32 tmp; + uInt8 r, g, b, a; + + if (!Avail()) return; + if ((uInt32)x > maxX) return; + + if (y1>y2) { + tmp= y1; + y1 = y2; + y2 = tmp; + } // if + + if (y1 < 0) y1 = 0; + if (y2 > (int32)maxY) y2 = maxY; + if (y2 < y1) return; + + if (IsBlending()) { + + Unpack(colour, r, g, b, a); + + if (0 == a) return; + + if (255 != a) { + for (tmp = y1; tmp <= y2; tmp++) + RawSetPixel(x, tmp, r, g, b, a); + return; + } // if + + } // if blending + + switch (bytesPerPix) { + case 4: + __asm__ __volatile__( + " push %%ds \n" // push ds + " add %%esi, %%edi \n" // add edi, esi + " shl $2, %%ebx \n" // shl ebx, 2 - pix size + " mov %7, %%si \n" // mov si, screenSelector + " mov %%si, %%ds \n" // mov ds, si + " mov %6, %%esi \n" // mov esi, y1 + " sub %%esi, %%ecx \n" // sub ecx, esi + " add %%ebx, %%edi \n" // add edi, ebx + " mov %2, %%eax \n" // mov eax, colour + " inc %%ecx \n" // inc ecx + "vLlop32: \n" + " mov %%eax, (%%edi)\n" // mov [edi], eax + " add %%edx, %%edi \n" // add edi, edx + " dec %%ecx \n" // dec ecx + " jnz vLlop32 \n" + " pop %%ds \n" // pop ds + : + : "D" (buffer), "S" (lineOfs[y1]), // %0, %1 + "m" (colour), "b" (x), // %2, %3 + "c" (y2), "d" (xRes), // %4, %5 + "m" (y1), "m" (screenSelector) // %6, %7 + ); + break; + case 3: + __asm__ __volatile__( + " push %%ds \n" // push ds + " add %%esi, %%edi \n" // add edi, esi + " mov %%ebx, %%esi \n" // mov esi, ebx - pix size + " add %%ebx, %%ebx \n" // add ebx, ebx - pix size + " add %%esi, %%ebx \n" // add ebx, esi - pix size + " mov %7, %%si \n" // mov si, screenSelector + " mov %%si, %%ds \n" // mov ds, si + " mov %6, %%esi \n" // mov esi, y1 + " sub %%esi, %%ecx \n" // sub ecx, esi + " add %%ebx, %%edi \n" // add edi, ebx + " mov %2, %%eax \n" // mov eax, colour + " inc %%ecx \n" // inc ecx + " mov %%eax, %%ebx \n" // mov ebx, eax + " shr $16, %%ebx \n" // shr ebx, 16 + "vLlop24: \n" + " mov %%ax, (%%edi) \n" // mov [edi], eax + " mov %%bl, 2(%%edi)\n" // mov [edi+2], bl + " add %%edx, %%edi \n" // add edi, edx + " dec %%ecx \n" // dec ecx + " jnz vLlop24 \n" + " pop %%ds \n" // pop ds + : + : "D" (buffer), "S" (lineOfs[y1]), // %0, %1 + "m" (colour), "b" (x), // %2, %3 + "c" (y2), "d" (xRes), // %4, %5 + "m" (y1), "m" (screenSelector) // %6, %7 + ); + break; + case 2: + __asm__ __volatile__( + " push %%ds \n" // push ds + " add %%esi, %%edi \n" // add edi, esi + " add %%ebx, %%ebx \n" // add ebx, ebx - pix size + " mov %7, %%si \n" // mov si, screenSelector + " mov %%si, %%ds \n" // mov ds, si + " mov %6, %%esi \n" // mov esi, y1 + " sub %%esi, %%ecx \n" // sub ecx, esi + " add %%ebx, %%edi \n" // add edi, ebx + " mov %2, %%eax \n" // mov eax, colour + " inc %%ecx \n" // inc ecx + "vLlop16: \n" + " mov %%ax, (%%edi) \n" // mov [edi], ax + " add %%edx, %%edi \n" // add edi, edx + " dec %%ecx \n" // dec ecx + " jnz vLlop16 \n" + " pop %%ds \n" // pop ds + : + : "D" (buffer), "S" (lineOfs[y1]), // %0, %1 + "m" (colour), "b" (x), // %2, %3 + "c" (y2), "d" (xRes), // %4, %5 + "m" (y1), "m" (screenSelector) // %6, %7 + ); + break; + case 1: + __asm__ __volatile__( + " push %%ds \n" // push ds + " add %%esi, %%edi \n" // add edi, esi + " mov %7, %%si \n" // mov si, screenSelector + " mov %%si, %%ds \n" // mov ds, si + " mov %6, %%esi \n" // mov esi, y1 + " sub %%esi, %%ecx \n" // sub ecx, esi + " add %%ebx, %%edi \n" // add edi, ebx + " mov %2, %%eax \n" // mov eax, colour + " inc %%ecx \n" // inc ecx + "vLlop8: \n" + " mov %%al, (%%edi) \n" // mov [edi], al + " add %%edx, %%edi \n" // add edi, edx + " dec %%ecx \n" // dec ecx + " jnz vLlop8 \n" + " pop %%ds \n" // pop ds + : + : "D" (buffer), "S" (lineOfs[y1]), // %0, %1 + "m" (colour), "b" (x), // %2, %3 + "c" (y2), "d" (xRes), // %4, %5 + "m" (y1), "m" (screenSelector) // %6, %7 + ); + break; + + } // switch + return; +} // ogDisplay_VESA::VLine + +ogDisplay_VESA::~ogDisplay_VESA(void) { + __dpmi_regs regs; + if (VESAInfo != NULL) delete VESAInfo; + if (modeInfo != NULL) delete modeInfo; + if (attributes != NULL) delete attributes; + if (inGraphics) { + regs.x.ax = 3; + __dpmi_int(0x10, ®s); + } // if inGraphics + + return; +} diff --git a/src/lib/objgfx40/ogFont.cpp b/src/lib/objgfx40/ogFont.cpp new file mode 100644 index 0000000..d28e252 --- /dev/null +++ b/src/lib/objgfx40/ogFont.cpp @@ -0,0 +1,319 @@ +#include +#include + +extern "C" { + #include +#ifdef __UBIXOS_KERNEL__ + #include +#else + #include + #include +#endif + } + +using namespace std; +typedef + struct { + char ID[3]; + uInt8 version; + uInt8 width, height; + uInt8 numOfChars; + uInt8 startingChar; + uInt8 colourType; + uInt8 paddington[7]; + } ogDPFHeader; + +static +bool +fileExists(const char *file) +{ +#ifdef __UBIXOS_KERNEL__ + fileDescriptor *f = fopen(file, "rb"); +#else + FILE *f = fopen(file, "rb"); +#endif + if (!f) + return false; + fclose(f); + return true; +} + +ogBitFont::ogBitFont(void) { +#ifdef __UBIXOS_KERNEL__ + kmemset(fontDataIdx, 0, sizeof(fontDataIdx)); + kmemset(charWidthTable, 0, sizeof(charWidthTable)); + kmemset(charHeightTable, 0, sizeof(charHeightTable)); +#else + memset(fontDataIdx, 0, sizeof(fontDataIdx)); + memset(charWidthTable, 0, sizeof(charWidthTable)); + memset(charHeightTable, 0, sizeof(charHeightTable)); +#endif + + fontData = NULL; + fontDataSize = 0; + numOfChars = 0; + width = height = startingChar = 0; + + BGColour.red = 0; + BGColour.green = 0; + BGColour.blue = 0; + BGColour.alpha = 0; + + FGColour.red = 255; + FGColour.green = 255; + FGColour.blue = 255; + FGColour.alpha = 255; + + return; +} // ogBitFont::ogBitFont + +void +ogBitFont::SetBGColor(uInt32 red, uInt32 green, uInt32 blue, uInt32 alpha) { + BGColour.red = red; + BGColour.green = green; + BGColour.blue = blue; + BGColour.alpha = alpha; + return; +} // ogBitFont::SetBGColor + +void +ogBitFont::SetFGColor(uInt32 red, uInt32 green, uInt32 blue, uInt32 alpha) { + FGColour.red = red; + FGColour.green = green; + FGColour.blue = blue; + FGColour.alpha = alpha; + return; +} // ogBitFont::SetFGColor + +ogBitFont::~ogBitFont(void) { +#ifdef __UBIXOS_KERNEL__ + kmemset(fontDataIdx, 0, sizeof(fontDataIdx)); + kmemset(charWidthTable, 0, sizeof(charWidthTable)); + kmemset(charHeightTable, 0, sizeof(charHeightTable)); +#else + memset(fontDataIdx, 0, sizeof(fontDataIdx)); + memset(charWidthTable, 0, sizeof(charWidthTable)); + memset(charHeightTable, 0, sizeof(charHeightTable)); +#endif + delete [] fontData; + fontData = NULL; + fontDataSize = 0; + width = height = startingChar = 0; + return; +} // ogBitFont::~ogBitFont; + +void +ogBitFont::CenterTextX(ogSurface& dest, int32 y, const char * textString) { + int32 x; + x = ((dest.GetMaxX()+1) - TextWidth(textString)) / 2; + PutString(dest, x, y, textString); + return; +} // ogBitFont::CenterTextX + +void +ogBitFont::JustifyText(ogSurface& dest, ogTextAlign horiz, ogTextAlign vert, + const char * textString) { + uInt32 x, y; + + switch (horiz) { + case leftText: + x = 0; + break; + case centerText: + x = ((dest.GetMaxX())-TextWidth(textString)) / 2; + break; + case rightText: + x = (dest.GetMaxX())-TextWidth(textString); + break; + default: + return; + } // switch + + switch (vert) { + case topText: + y = 0; + break; + case centerText: + y = ((dest.GetMaxY())-TextHeight(textString)) / 2; + break; + case bottomText: + y = (dest.GetMaxY())-TextHeight(textString); + default: + return; + } // switch + + PutString(dest, x, y, textString); + return; +} // ogBitFont::JustifyText + +bool +ogBitFont::Load(const char* fontFile, uInt32 offset = 0) { +#ifdef __UBIXOS_KERNEL__ + fileDescriptor * infile; +#else + FILE * infile; +#endif + ogDPFHeader header; + uInt32 lresult, size; + + if (!fileExists(fontFile)) return false; + + delete [] fontData; + + infile = fopen(fontFile, "rb"); + fseek(infile, offset, SEEK_SET); + lresult = fread(&header, sizeof(header), 1, infile); + width = header.width; + height = header.height; + numOfChars = header.numOfChars; + if (0 == numOfChars) numOfChars = 256; + startingChar = header.startingChar; + +#ifdef __UBIXOS_KERNEL__ + kmemset(fontDataIdx, 0, sizeof(fontDataIdx)); + kmemset(charWidthTable, 0, sizeof(charWidthTable)); + kmemset(charHeightTable, 0, sizeof(charHeightTable)); +#else + memset(fontDataIdx, 0, sizeof(fontDataIdx)); + memset(charWidthTable, 0, sizeof(charWidthTable)); + memset(charHeightTable, 0, sizeof(charHeightTable)); +#endif + + size = (((uInt32)width+7) / 8)*(uInt32)height; + fontDataSize = size* (uInt32)numOfChars; + + for (int32 tmp = startingChar; tmp <= startingChar+numOfChars-1; tmp++) { + charWidthTable[tmp] = width; + charHeightTable[tmp] = height; + fontDataIdx[tmp] = (size*(tmp-startingChar)); + } // for tmp + + fontData = new uInt8[fontDataSize]; + + lresult = fread(fontData, 1, fontDataSize, infile); + + fclose(infile); + return true; +} // ogBitFont::Load + +/* +bool +ogFont::LoadFrom(const char* FontFile, uInt32 Offset) { + return true; +} // ogFont::LoadFrom + + +bool +ogFont::Save(const char* FontFile) { + return saveTo(FontFile,0); +} // ogFont::Save +*/ + +uInt32 +ogBitFont::TextHeight(const char * textString) { + uInt32 size, tmpsize; + size = 0; + const unsigned char * text = (const unsigned char *)textString; + + if (text != NULL) + while (*text) { + tmpsize = charHeightTable[*text++]; + if (tmpsize>size) size = tmpsize; + } // while + + return size; +} // ogBitFont::TextHeight + +uInt32 +ogBitFont::TextWidth(const char * textString) { + uInt32 size = 0; + const unsigned char * text = (const unsigned char *)textString; + + if (text != NULL) + while (*text) + size += charWidthTable[*text++]; + return size; +} // ogBitFont::TextWidth + +/* +bool +ogBitFont::SaveTo(const char * fontFile, int32 offset) { + return true; +} // TDPFont::SaveTo +*/ + +void +ogBitFont::PutChar(ogSurface& dest, int32 x, int32 y, const char ch) { + + uInt32 xx, xCount, yCount; + uInt32 BGC, FGC, tColour; + uInt8 * offset; + uInt8 bits = 0; + const unsigned char c = (const unsigned char)ch; + + if (NULL == fontData) return; + if (!dest.Avail()) return; + + if (charWidthTable[c] != 0) { + BGC = dest.Pack(BGColour.red, + BGColour.green, + BGColour.blue, + BGColour.alpha); + + BGC &= dest.GetAlphaMasker(); + + tColour = dest.GetTransparentColor(); + + FGC = dest.Pack(FGColour.red, + FGColour.green, + FGColour.blue, + FGColour.alpha); + + offset = fontData; + offset += fontDataIdx[c]; + + for (yCount = 0; yCount < height; yCount++) { + xCount = charWidthTable[c]; + xx = 0; + + do { + if (0 == (xx & 7)) bits = *(offset++); + if ((bits & 128) != 0) + dest.SetPixel(x + xx, y+yCount , FGColour.red, FGColour.green, + FGColour.blue, FGColour.alpha); + else + if (BGC != tColour) + dest.SetPixel(x + xx, y+yCount, BGC); + + bits += bits; + ++xx; + } while (--xCount); + } // for yCount + } // if + return; +} // ogBitFont::PutChar + +void +ogBitFont::PutString(ogSurface& dest, int32 x, int32 y, + const char *textString) { + + const unsigned char *text; + unsigned char ch; + + if (NULL == textString) return; +#ifdef __UBIXOS_KERNEL__ + if (0 == kstrlen(textString)) return; +#else + if (0 == strlen(textString)) return; +#endif + if (!dest.Avail()) return; + + text = (const unsigned char *)textString; + + while ((ch = *text++) != 0) { + PutChar(dest, x, y, ch); + x += charWidthTable[ch]; + } // while + + return; +} // ogBitFont::PutString diff --git a/src/lib/objgfx40/ogPixCon.cpp b/src/lib/objgfx40/ogPixCon.cpp new file mode 100644 index 0000000..0e0473b --- /dev/null +++ b/src/lib/objgfx40/ogPixCon.cpp @@ -0,0 +1,143 @@ +#include +#include + +// ogPixCon constructor +ogPixCon::ogPixCon(ogPixelFmt srcPixFmt, ogPixelFmt dstPixFmt) { + uInt8 channelIdx[4]; + uInt8 srcFieldSize[4]; + uInt8 srcFieldPos[4]; + uInt8 dstShifters[4]; + + uInt8 tmpb; + int32 i, j; + + channelIdx[0] = 0; + channelIdx[1] = 1; + channelIdx[2] = 2; + channelIdx[3] = 3; + + srcFieldSize[0] = srcPixFmt.alphaMaskSize; + srcFieldSize[1] = srcPixFmt.redMaskSize; + srcFieldSize[2] = srcPixFmt.greenMaskSize; + srcFieldSize[3] = srcPixFmt.blueMaskSize; + + srcFieldPos[0] = srcPixFmt.alphaFieldPosition; + srcFieldPos[1] = srcPixFmt.redFieldPosition; + srcFieldPos[2] = srcPixFmt.greenFieldPosition; + srcFieldPos[3] = srcPixFmt.blueFieldPosition; + + /* + * The dest shifters are 32-(fieldPosition+fieldSize). For things like + * 24bpp where there is no alpha, the field position will be 0, and the + * field size will be 0. 32-(0+0) is 32.. and when the shift takes place + * the 32 will turn into a 0 and the shift will do nothing + */ + + dstShifters[0] = 32-(dstPixFmt.alphaFieldPosition+dstPixFmt.alphaMaskSize); + dstShifters[1] = 32-(dstPixFmt.redFieldPosition+dstPixFmt.redMaskSize); + dstShifters[2] = 32-(dstPixFmt.greenFieldPosition+dstPixFmt.greenMaskSize); + dstShifters[3] = 32-(dstPixFmt.blueFieldPosition+dstPixFmt.blueMaskSize); + + i = srcPixFmt.redMaskSize - dstPixFmt.redMaskSize; + if (i>0) + srcMasker = OG_MASKS[dstPixFmt.redMaskSize] << (srcPixFmt.redFieldPosition+i); + else + srcMasker = OG_MASKS[srcPixFmt.redMaskSize] << srcPixFmt.redFieldPosition; + + i = srcPixFmt.greenMaskSize - dstPixFmt.greenMaskSize; + if (i>0) + srcMasker+= OG_MASKS[dstPixFmt.greenMaskSize] << (srcPixFmt.greenFieldPosition+i); + else + srcMasker+= OG_MASKS[srcPixFmt.greenMaskSize] << srcPixFmt.greenFieldPosition; + + i = srcPixFmt.blueMaskSize - dstPixFmt.blueMaskSize; + if (i>0) + srcMasker+= OG_MASKS[dstPixFmt.blueMaskSize] << (srcPixFmt.blueFieldPosition+i); + else + srcMasker+= OG_MASKS[srcPixFmt.blueMaskSize] << srcPixFmt.blueFieldPosition; + + i = srcPixFmt.alphaMaskSize - dstPixFmt.alphaMaskSize; + if (i>0) + srcMasker+= OG_MASKS[dstPixFmt.alphaMaskSize] << (srcPixFmt.alphaFieldPosition+i); + else + srcMasker+= OG_MASKS[srcPixFmt.alphaMaskSize] << srcPixFmt.alphaFieldPosition; + + /* + * sort in descending order based on srcFieldPos (oth field will hold + * highest position value) + */ + + for (i = 1; i < 4; i++ ) + for (j = 0; j < i; j++) { + if (srcFieldPos[j] < srcFieldPos[i]) { + tmpb = srcFieldPos[j]; + srcFieldPos[j] = srcFieldPos[i]; + srcFieldPos[i] = tmpb; + + tmpb = srcFieldSize[j]; + srcFieldSize[j] = srcFieldSize[i]; + srcFieldSize[i] = tmpb; + + tmpb = channelIdx[j]; + channelIdx[j] = channelIdx[i]; + channelIdx[i] = tmpb; + } // if + } // for j + + srcShifter = ((srcFieldSize[0] << 24) | + (srcFieldSize[1] << 16) | + (srcFieldSize[2] << 8) | + (srcFieldSize[3])); + + dstShifter = ((dstShifters[channelIdx[0]] << 24) | + (dstShifters[channelIdx[1]] << 16) | + (dstShifters[channelIdx[2]] << 8) | + (dstShifters[channelIdx[3]])); + return; +} // ogPixCon::ogPixCon + +uInt32 +ogPixCon::ConvPix(uInt32 pixel) { + __asm__ __volatile__( + " xor %%ebx, %%ebx \n" // xor ebx, ebx + " xor %%edi, %%edi \n" // xor edi, edi + " \n" + " push %%eax \n" // push eax + " \n" + " and %%edx, %%esi \n" // and esi, edx + " xor %%eax, %%eax \n" // xor eax, eax + " xor %%edx, %%edx \n" // xor edx, edx + " \n" + " shrdl %%cl, %%esi, %%eax \n" // shrd eax, esi, cl + " shr %%cl, %%esi \n" // shr esi, cl + " mov %%ch, %%cl \n" // mov cl, ch + " shrdl %%cl, %%esi, %%ebx \n" // shrd ebx, esi, cl + " shr %%cl, %%esi \n" // shr esi, cl + " shr $16, %%ecx \n" // shr ecx, 16 + " shrdl %%cl, %%esi, %%edx \n" // shrd edx, esi, cl + " shr %%cl, %%esi \n" // shr esi, cl + " mov %%ch, %%cl \n" // mov cl, ch + " shrdl %%cl, %%esi, %%edi \n" // shrd edi, esi, cl + " \n" + " pop %%ecx \n" // pop ecx + " \n" + " shr %%cl, %%eax \n" // shr eax, cl + " shr $8, %%ecx \n" // shr ecx, 8 + " shr %%cl, %%ebx \n" // shr ebx, cl + " shr $8, %%ecx \n" // shr ecx, 8 + " shr %%cl, %%edx \n" // shr edx, cl + " shr $8, %%ecx \n" // shr ecx, 8 + " shr %%cl, %%edi \n" // shr edi, cl + " \n" + " or %%ebx, %%eax \n" // or eax, ebx + " or %%edi, %%edx \n" // or edx, edi + " nop \n" // nop + " or %%edx, %%eax \n" // or eax, edx + + : "=a" (pixel) // %0 + : "S" (pixel), "d" (srcMasker), // %1, %2 + "c" (srcShifter), "a" (dstShifter) // %3, %4 + // "ecx" (srcShifter), "eax" (dstShifter) // %2, %3 + ); + return pixel; +}; // ogPixCon::ConvPix diff --git a/src/lib/objgfx40/ogSprite.cpp b/src/lib/objgfx40/ogSprite.cpp new file mode 100644 index 0000000..7381123 --- /dev/null +++ b/src/lib/objgfx40/ogSprite.cpp @@ -0,0 +1,701 @@ +extern "C" { + #include + #include + #include + } +#include +#include + +static bool +fileExists(const char *file) +{ + FILE *f = fopen(file, "rb"); + if (!f) + return false; + fclose(f); + return true; +} + +ogSprite::ogSprite(const ogSprite& srcSprite) { + image = NULL; + pal = NULL; + imageSize = 0; + width = 0; + height = 0; + bitDepth = 0; + RFP = 0; + GFP = 0; + BFP = 0; + AFP = 0; + rShift = 0; + gShift = 0; + bShift = 0; + aShift = 0; + tColour = 0; + pixelFmtID = 0; + bytesPerPixel = 0; + dAlpha = 0; + + if ((NULL == srcSprite.image) || (0 == srcSprite.imageSize)) return; + + // allocate space for the sprite + image = malloc(srcSprite.imageSize); + if (NULL == image) return; + + // copy the image size + imageSize = srcSprite.imageSize; + + if (srcSprite.pal != NULL) { + pal = new ogRGBA8[256]; + if (pal != NULL) memcpy(srcSprite.pal, pal, sizeof(ogRGBA8) * 256); + } // if + + width = srcSprite.width; + height = srcSprite.height; + bitDepth = srcSprite.bitDepth; + RFP = srcSprite.RFP; + GFP = srcSprite.GFP; + BFP = srcSprite.BFP; + AFP = srcSprite.AFP; + rShift = srcSprite.rShift; + gShift = srcSprite.gShift; + bShift = srcSprite.bShift; + aShift = srcSprite.aShift; + tColour = srcSprite.tColour; + pixelFmtID = srcSprite.bytesPerPixel; + dAlpha = srcSprite.dAlpha; + + return; +} // ogSprite::ogSprite + +ogSprite::ogSprite(void) { + image = NULL; + pal = NULL; + imageSize = 0; + width = 0; + height = 0; + bitDepth = 0; + RFP = 0; + GFP = 0; + BFP = 0; + AFP = 0; + rShift = 0; + gShift = 0; + bShift = 0; + aShift = 0; + tColour = 0; + pixelFmtID = 0; + bytesPerPixel = 0; + dAlpha = 0; + return; +} // ogSprite::ogSprite + +ogSprite & +ogSprite::operator=(ogSprite const & srcSprite) { + + if ((NULL == srcSprite.image) || (0 == srcSprite.imageSize)) return *this; + + free(image); + delete [] pal; + + // allocate space for the sprite + image = malloc(srcSprite.imageSize); + + // this is such a bad case it should probably throw an exception + if (NULL == image) return *this; + + // copy the image size + imageSize = srcSprite.imageSize; + + if (srcSprite.pal != NULL) { + pal = new ogRGBA8[256]; + if (pal != NULL) memcpy(srcSprite.pal, pal, sizeof(ogRGBA8) * 256); + } // if + + width = srcSprite.width; + height = srcSprite.height; + bitDepth = srcSprite.bitDepth; + RFP = srcSprite.RFP; + GFP = srcSprite.GFP; + BFP = srcSprite.BFP; + AFP = srcSprite.AFP; + rShift = srcSprite.rShift; + gShift = srcSprite.gShift; + bShift = srcSprite.bShift; + aShift = srcSprite.aShift; + tColour = srcSprite.tColour; + pixelFmtID = srcSprite.bytesPerPixel; + dAlpha = srcSprite.dAlpha; + + return *this; +} +void +ogSprite::Get(ogSurface& srcObject, int32 x1, int32 y1, int32 x2, int32 y2) { + ogPixelFmt pixfmt; + uInt32 xx, yy, xOfs, yOfs; + uInt32 rx1, ry1, rx2, ry2; + uInt32 xCount, yCount, count; + void *p; + uInt32 maxX, maxY; + + if (!srcObject.Avail()) return; + + free(image); + free(pal); + + maxX = srcObject.GetMaxX(); + maxY = srcObject.GetMaxY(); + + srcObject.GetPixFmt(pixfmt); + + bitDepth = pixfmt.BPP; + RFP = pixfmt.redFieldPosition; + GFP = pixfmt.greenFieldPosition; + BFP = pixfmt.blueFieldPosition; + AFP = pixfmt.alphaFieldPosition; + rShift = 8-pixfmt.redMaskSize; + gShift = 8-pixfmt.greenMaskSize; + bShift = 8-pixfmt.blueMaskSize; + aShift = 8-pixfmt.alphaMaskSize; + + pixelFmtID = srcObject.GetPixFmtID(); + + dAlpha = srcObject.GetAlpha(); + tColour = srcObject.GetTransparentColor(); + + bytesPerPixel = srcObject.GetBytesPerPix(); + + if (1 == bytesPerPixel) { + if (NULL == pal) pal = new ogRGBA8[256]; + if (NULL == pal) return; + srcObject.GetPalette(pal); + /* for (count = 0; count < 256; count++) + srcObject.Unpack(count, + pal[count].red, + pal[count].green, + pal[count].blue, + pal[count].alpha); */ + +// memcpy(pal, srcObject.pal, sizeof(ogRGBA8)*256); + } // if + + if (x1 > x2) { + xx = x1; + x1 = x2; + x2 = xx; + } // if + + if (y1 > y2) { + yy = y1; + y1 = y2; + y2 = yy; + } // if + + xCount = abs(x2-x1)+1; + yCount = abs(y2-y1)+1; + width = xCount; + height = yCount; + imageSize = xCount*yCount*bytesPerPixel; + + image = malloc(imageSize); + p = image; + + if ( ((uInt32)x1 > maxX) || ((uInt32)y1 > maxY) || + ((uInt32)x2 > maxX) || ((uInt32)y2 > maxY) ) { + + for (count = 0; count < (xCount*yCount); count++) { + SetPixel(p, tColour); + (uInt8 *)p += bytesPerPixel; + } // for + p = image; // reset the pointer; + } // if + + xOfs = 0; + yOfs = 0; + + if (y1 < 0) { + yCount += y1; + ry1 = 0; + yOfs = xCount*abs(y1); + } else ry1 = y1; + + if (x1 < 0) { + xCount += x1; + rx1 = 0; + xOfs = abs(x1); + } else rx1 = x1; + + if (x2 > (int32)maxX) { + xCount -= maxX-x2+1; + rx2 = maxX; + } else rx2 = x2; + + if (y2 > (int32)maxY) { + yCount -= maxY-y2+1; + ry2 = maxY; + } else ry2 = y2; + + xCount *= bytesPerPixel; + + for (yy = 0; yy < yCount; yy++) { + ( (uInt8 *)p ) += xOfs; + srcObject.CopyLineFrom(rx1, ry1+yy, p, xCount); + ( (uInt8 *)p ) += xCount; + } + return; +} // ogSprite::Get + +uInt32 +ogSprite::GetPixel(void * p) { + uInt32 result; + switch (bytesPerPixel) { + case 4: + return *(uInt32 *)p; + break; + case 3: + asm( + " xor %%eax, %%eax \n" // xor eax, eax + " mov 2(%%edi),%%al \n" // mov al, [edi+2] + " shl $16, %%eax \n" // shl eax, 16 + " mov (%%edi), %%ax \n" // mov ax, [edi] + " mov %%eax, %1 \n" // mov result, eax + : + : "D" (p), "m" (result) + ); + return result; + break; + case 2: + return *(uInt16 *)p; + break; + case 1: + return *(uInt8 *)p; + break; + default: + return 0; + break; + } // switch +} // ogSprite::GetPixel + +void +ogSprite::SetPixel(void * p, uInt32 colour) { + + switch (bytesPerPixel) { + case 4: + *(uInt32 *)p = colour; + break; + case 3: + asm( + " mov %%ax, (%%edi) \n" // mov [edi], ax + " shr $16, %%eax \n" // shr eax, 16 + " mov %%al, 2(%%edi)\n" // mov [edi+2],al + : + : "D" (p), "a" (colour) + ); + break; + case 2: + *(uInt16 *)p = (uInt16)colour; + break; + case 1: + *(uInt8 *)p = (uInt8)colour; + break; + } // switch + return; +} // ogSprite::SetPixel + +uInt32 +ogSprite::GetSize(void) { + /* + * getSize + * + * returns the size of the image as it would take on disk. This includes + * all header related information (width/height, bitdepth, pixel format, + * etc) along with an extra sizeof(uInt32) + * for storing the complete size. This allows easy indexing of images, + * since you can figure out exactly how much the image will take up on + * disk. This function computes the size in the exact order it is on disk. + * If the image is 8bpp, then there is a 768 byte palette stored after the + * image data along with an extra sizeof(uInt32) for the palette size in + * bytes. Currently we store the entire palette, but later I expect we + * will add the ability to optimize the palette so only used entries are + * stored. + * + * If you were to store a single sprite in a file, getSize would equal the + * filesize. + */ + uInt32 tmpsize; + char headerIdent[4]; + + tmpsize = sizeof(headerIdent)+ + sizeof(uInt32)+ // total size + sizeof(width)+sizeof(height)+ // width/height + sizeof(bitDepth)+ // bitDepth + sizeof(RFP)+sizeof(GFP)+sizeof(BFP)+sizeof(AFP)+ // field positions + sizeof(rShift)+sizeof(gShift)+sizeof(bShift)+sizeof(aShift)+ // shifters + sizeof(tColour)+ // tColour + sizeof(bytesPerPixel)+ // bytes per pixel + sizeof(pixelFmtID)+ // pixel format ID + sizeof(dAlpha)+ // default alpha + sizeof(imageSize)+ // image size in bytes + imageSize; // actual image area in bytes + if (1 == bytesPerPixel) tmpsize += sizeof(uInt32)+sizeof(ogRGBA8)*256; + return tmpsize; +} // ogSprite::GetSize + +bool +ogSprite::Load(const char * filename) { + return LoadFrom(filename,0); +} // ogSprite::Load + +bool +ogSprite::LoadFrom(const char * filename, uInt32 offset) { + FILE * infile; + uInt32 lresult, tresult, totSize; + uInt32 tmpSize; + char headerIdent[4]; + + if (!fileExists(filename)) return false; + if (NULL == (infile = fopen(filename,"rb"))) return false; + fseek(infile, offset, SEEK_SET); + + // for now just free up the previous image. This will be changed + // later so it doesn't affect the current image (if any) if there + // is a failure loading + + free(image); + free(pal); + + image = NULL; + imageSize = 0; + pal = NULL; + + tresult = 0; // total bytes we've read in so far + + lresult = fread(&headerIdent, sizeof(headerIdent), 1, infile); + tresult += lresult*sizeof(headerIdent); + if ((headerIdent[0] != 'S') || + (headerIdent[1] != 'P') || + (headerIdent[2] != 'R') || + (headerIdent[3] != (char)0x1A)) { + fclose(infile); + return false; + } + + lresult = fread(&totSize, sizeof(totSize), 1, infile); + tresult += lresult*sizeof(totSize); + + lresult = fread(&width, sizeof(width), 1, infile); + tresult += lresult*sizeof(width); + + lresult = fread(&height, sizeof(height), 1, infile); + tresult += lresult*sizeof(height); + + lresult = fread(&bitDepth, sizeof(bitDepth), 1, infile); + tresult += lresult*sizeof(bitDepth); + + lresult = fread(&RFP, sizeof(RFP), 1, infile); + tresult += lresult*sizeof(RFP); + + lresult = fread(&GFP, sizeof(GFP), 1, infile); + tresult += lresult*sizeof(GFP); + + lresult = fread(&BFP, sizeof(BFP), 1, infile); + tresult += lresult*sizeof(BFP); + + lresult = fread(&AFP, sizeof(AFP), 1, infile); + tresult += lresult*sizeof(AFP); + + lresult = fread(&rShift, sizeof(rShift), 1, infile); + tresult += lresult*sizeof(rShift); + + lresult = fread(&gShift, sizeof(gShift), 1, infile); + tresult += lresult*sizeof(gShift); + + lresult = fread(&bShift, sizeof(bShift), 1, infile); + tresult += lresult*sizeof(bShift); + + lresult = fread(&aShift, sizeof(aShift), 1, infile); + tresult += lresult*sizeof(aShift); + + lresult = fread(&tColour, sizeof(tColour), 1, infile); + tresult += lresult*sizeof(tColour); + + lresult = fread(&pixelFmtID, sizeof(pixelFmtID), 1, infile); + tresult += lresult*sizeof(pixelFmtID); + + lresult = fread(&bytesPerPixel, sizeof(bytesPerPixel), 1, infile); + tresult += lresult*sizeof(bytesPerPixel); + + lresult = fread(&dAlpha, sizeof(dAlpha), 1, infile); + tresult += lresult*sizeof(dAlpha); + + lresult = fread(&imageSize, sizeof(imageSize), 1, infile); + tresult += lresult*sizeof(imageSize); + + image = malloc(imageSize); + if (NULL == image) { + fclose(infile); + return false; + } + + // I suppose we could interchange the imageSize and record count to produce + // the number of bytes we read it... we'll try it this way for now. + lresult = fread(image, imageSize, 1, infile); + tresult += lresult*imageSize; + + if (1 == bytesPerPixel) { + // 8bpp sprites have palettes + if (NULL == pal) pal = new ogRGBA8[256]; + if (NULL == pal) { + fclose(infile); + return false; + } // if pal==NULL + + lresult = fread(&tmpSize, sizeof(tmpSize), 1, infile); + tresult += lresult*sizeof(tmpSize); + + if (tmpSize > sizeof(ogRGBA8)*256) { + fclose(infile); + return false; + } // if + + lresult = fread(pal, tmpSize, 1, infile); + tresult += lresult*tmpSize; + } // if bytesPerPixel == 1 + + fclose(infile); + return (tresult == totSize); +} // ogSprite::LoadFrom; + +void +ogSprite::Put(ogSurface& destObject, int32 x, int32 y) { + uInt32 xx, yy; + int32 xCount, yCount; + uInt32 yOfs; + uInt32 xLeft, xRight; + int32 maxX, maxY; + void * p; + uInt8 r, g, b, a; + ogPixelFmt pixfmt; + + if (NULL == image) return; + if (!destObject.Avail()) return; + + maxX = destObject.GetMaxX(); + maxY = destObject.GetMaxY(); + + xCount = width; + yCount = height; + + // check to see if the image is totally off the screen + if ((x+xCount<0) || (y+yCount<0) || (x>(int32)maxX) || (y>(int32)maxY)) return; + + p = image; + + if (y < 0) { + yOfs = abs(y)*xCount*bytesPerPixel; + yCount += y; + y = 0; + } else yOfs = 0; + + if (x < 0) { + xLeft = abs(x)*bytesPerPixel; + xCount += x; + x = 0; + } else xLeft = 0; + + if (x+xCount > maxX) { + xRight = (xCount - (maxX-x+1))*bytesPerPixel; + xCount = (maxX-x)+1; + } else xRight = 0; + + if ((y+yCount) > maxY) yCount = (maxY-y)+1; + + destObject.GetPixFmt(pixfmt); + + (uInt8 *)p += yOfs; + + if ((destObject.GetPixFmtID() != pixelFmtID) || (destObject.IsBlending())) { + + for (yy = 0; yy < (uInt32)yCount; yy++) { + (uInt8 *)p += xLeft; + + for (xx = 0; xx < (uInt32)xCount; xx++) { + Unpack(GetPixel(p), r, g, b, a); + (uInt8 *)p += bytesPerPixel; + // this could probably be rawSetPixelRGBA instead + destObject.SetPixel(x+xx, y+yy, r, g, b, a); + } // for + + (uInt8 *)p += xRight; + } // for yy + + } else { // pixel formats match + xCount *= bytesPerPixel; + + for (yy = 0; yy < (uInt32)yCount; yy++) { + (uInt8 *)p += xLeft; + destObject.CopyLineTo(x, y+yy, p, xCount); + (uInt8 *)p += xCount; + (uInt8 *)p += xRight; + } // for + + } // else + return; +} // ogSurface::Put + +bool +ogSprite::Save(const char * filename) { + return SaveTo(filename,0); +} // ogSprite::Save + +bool +ogSprite::SaveTo(const char * filename, int32 offset) { + /* + * saveTo + * + * saves a bitmap to disk. If the file doesn't exit then we will create + * a new one (doing this will ignore any specified offset). If the file + * exists, we will seek to the specified offset and place the bitmap there. + * If offset is -1, then we seek to the end of the file. + * + * This function will fail on files larger than 2GB. + * + */ + FILE * outfile = NULL; + char headerIdent[4]; + uInt32 tmpSize; + + if (NULL == image) return false; + if ((1 == bytesPerPixel) && (NULL == pal)) return false; + + if (!fileExists(filename)) { // file doesn't exist + if ((outfile = fopen(filename,"wb")) == NULL) return false; + } else { + // file exists. Now we check to see where we put it + if (offset==-1) { + if ((outfile = fopen(filename, "ab")) == NULL) return false; + } else { + // we have an existing file and an offset to place the data + if ((outfile = fopen(filename, "wb")) == NULL) return false; + if (offset!=0) fseek(outfile, offset, SEEK_SET); + } // else + } // else + + headerIdent[0] = 'S'; + headerIdent[1] = 'P'; + headerIdent[2] = 'R'; + headerIdent[3] = (char)0x1A; // EOF marker + + // we store exactly how bit this sucker is inside the header. This includes + // the header information before it, and the size itself + tmpSize = GetSize(); + fwrite(headerIdent, sizeof(headerIdent), 1, outfile); + + fwrite(&tmpSize, sizeof(tmpSize), 1, outfile); + fwrite(&width, sizeof(width), 1, outfile); + fwrite(&height, sizeof(height), 1, outfile); + fwrite(&bitDepth, sizeof(bitDepth), 1, outfile); + + fwrite(&RFP, sizeof(RFP), 1, outfile); + fwrite(&GFP, sizeof(GFP), 1, outfile); + fwrite(&BFP, sizeof(BFP), 1, outfile); + fwrite(&AFP, sizeof(AFP), 1, outfile); + + fwrite(&rShift, sizeof(rShift), 1, outfile); + fwrite(&gShift, sizeof(gShift), 1, outfile); + fwrite(&bShift, sizeof(bShift), 1, outfile); + fwrite(&aShift, sizeof(aShift), 1, outfile); + + fwrite(&tColour, sizeof(tColour), 1, outfile); + fwrite(&pixelFmtID, sizeof(pixelFmtID), 1, outfile); + fwrite(&bytesPerPixel, sizeof(bytesPerPixel), 1, outfile); + fwrite(&dAlpha, sizeof(dAlpha), 1, outfile); + + fwrite(&imageSize, sizeof(imageSize), 1, outfile); + fwrite(image, imageSize, 1, outfile); + + if (1 == bytesPerPixel) { + tmpSize = sizeof(ogRGBA8)*256; + fwrite(&tmpSize, sizeof(tmpSize), 1, outfile); + fwrite(pal, sizeof(ogRGBA8), 256, outfile); + } // if bytesPerPixel == 1 + + fclose(outfile); + return true; +} // ogSprite::SaveTo + +void +ogSprite::Unpack(uInt32 colour, uInt8& red, uInt8& green, uInt8& blue, + uInt8& alpha) { + switch (bytesPerPixel) { + case 4: + red = (uInt8)(colour >> RFP); + green = (uInt8)(colour >> GFP); + blue = (uInt8)(colour >> BFP); + alpha = (uInt8)(colour >> AFP); + break; + case 3: + red = (uInt8)(colour >> RFP); + green = (uInt8)(colour >> GFP); + blue = (uInt8)(colour >> BFP); + alpha = dAlpha; + break; + case 2: + red = (uInt8)(colour >> RFP) << rShift; + green = (uInt8)(colour >> GFP) << gShift; + blue = (uInt8)(colour >> BFP) << bShift; + if (red != 0) red += OG_MASKS[rShift]; + if (green != 0) green += OG_MASKS[gShift]; + if (blue != 0) blue += OG_MASKS[bShift]; + + if (aShift != 8) { + alpha = (uInt8)(colour >> AFP) << aShift; + if (alpha != 0) alpha += OG_MASKS[aShift]; + } else alpha = dAlpha; + + break; + case 1: + + if (NULL == pal) { + red = green = blue = alpha = 0; + return; + } // if + + if (colour > 255) colour &= 255; + red = pal[colour].red; + green = pal[colour].green; + blue = pal[colour].blue; + alpha = pal[colour].alpha; + break; + default: + red = green = blue = alpha = 0; + break; + } // switch + return; +} // ogSprite::Unpack + +ogSprite::~ogSprite(void) { + free(image); + delete [] pal; + image = NULL; + pal = NULL; + imageSize = 0; + width = 0; + height = 0; + bitDepth = 0; + RFP = 0; + GFP = 0; + BFP = 0; + AFP = 0; + rShift = 0; + gShift = 0; + bShift = 0; + aShift = 0; + tColour = 0; + pixelFmtID= 0; + bytesPerPixel = 0; + dAlpha = 0; + return; +} // ogSprite::~ogSprite + + diff --git a/src/lib/objgfx40/rh_opt.gdt b/src/lib/objgfx40/rh_opt.gdt new file mode 100644 index 0000000..325a7f1 --- /dev/null +++ b/src/lib/objgfx40/rh_opt.gdt Binary files differ diff --git a/src/lib/objgfx40/rh_opt.gpr b/src/lib/objgfx40/rh_opt.gpr new file mode 100644 index 0000000..f3883ae --- /dev/null +++ b/src/lib/objgfx40/rh_opt.gpr Binary files differ diff --git a/src/lib/objgfx40/rh_opt.mak b/src/lib/objgfx40/rh_opt.mak new file mode 100644 index 0000000..1d41e21 --- /dev/null +++ b/src/lib/objgfx40/rh_opt.mak @@ -0,0 +1,356 @@ +# This file is automatically generated by RHIDE 1.4.9 +# created from within RHIDE +FLAGS_FOR_SUBPROJECTS=RHIDE_OS_="$(RHIDE_OS_)" CFLAGS="$(CFLAGS)"\ + CXXFLAGS="$(CXXFLAGS)" LDFLAGS="$(LDFLAGS)" CPPFLAGS="$(CPPFLAGS)" +RHIDE_OS=$(RHIDE_OS_) +ifeq ($(strip $(RHIDE_OS)),) +ifneq ($(strip $(DJDIR)),) +RHIDE_OS_:=DJGPP +else +RHIDE_OS_:=$(patsubst CYGWIN%,CYGWIN,$(shell uname)) +endif +endif + +INCLUDE_DIRS= +LIB_DIRS= +C_DEBUG_FLAGS= +C_OPT_FLAGS=-O4 +C_WARN_FLAGS=-pedantic -Wmain -Wparentheses -Wreturn-type -Wuninitialized\ + -Wall -W -Wpointer-arith -Wmissing-prototypes -Wredundant-decls +C_C_LANG_FLAGS= +C_CXX_LANG_FLAGS= +C_P_LANG_FLAGS= +C_FPC_LANG_FLAGS= +C_F_LANG_FLAGS= +C_ADA_LANG_FLAGS= +LIBS= +LD_EXTRA_FLAGS=-g +C_EXTRA_FLAGS=-Wno-long-long +LOCAL_OPT=$(subst ___~~~___, ,$(subst $(notdir $<)___,,$(filter $(notdir\ + $<)___%,$(LOCAL_OPTIONS)))) + +OBJFILES=main.o objgfx30.o ogBlit.o ogDisplay_VESA.o ogFont.o ogSprite.o +ALL_OBJFILES=main.o objgfx30.o ogBlit.o ogDisplay_VESA.o ogFont.o\ + ogSprite.o +LIBRARIES= +SOURCE_NAME=$< +OUTFILE=$@ +SPECIAL_CFLAGS= +SPECIAL_LDFLAGS= +PROG_ARGS= +SRC_DIRS= +WUC= +EDITORS= +MAIN_TARGET=objgfx.exe +PROJECT_ITEMS=main.cpp objgfx30.cpp ogBlit.cpp ogDisplay_VESA.cpp\ + ogFont.cpp ogSprite.cpp +DEFAULT_MASK=*.cpp +RHIDE_BIN_DIR=c:/djgpp/bin +PASCAL_TYPE=GPC +GET_HOME=$(HOME) +CLEAN_FILES=$(MAIN_TARGET) $(OBJFILES) +RHIDE_GCC=gcc +RHIDE_AS=gcc +RHIDE_GXX=gcc +RHIDE_GPC=gpc +RHIDE_FPC=ppc386 +RHIDE_AR=ar +RHIDE_LD=gcc +RHIDE_G77=g77 +RHIDE_NASM=nasm +RHIDE_LD_PASCAL=gpc +RHIDE_LD_FPC=$(RHIDE_FPC) -E+ +RHIDE_GNATBIND=gnatbind +RHIDE_RM=rm +RHIDE_ARFLAGS=rcs +RHIDE_TYPED_LIBS.f=g2c m +RHIDE_TYPED_LIBS.for=$(RHIDE_TYPED_LIBS.f) +RHIDE_TYPED_LIBS.F=$(RHIDE_TYPED_LIBS.f) +RHIDE_TYPED_LIBS.fpp=$(RHIDE_TYPED_LIBS.f) +RHIDE_TYPED_LIBS_GPC=gpc m +RHIDE_TYPED_LIBS_FPC=fpc +RHIDE_TYPED_LIBS.p=$(RHIDE_TYPED_LIBS_$(PASCAL_TYPE)) +RHIDE_TYPED_LIBS.pas=$(RHIDE_TYPED_LIBS.p) +RHIDE_TYPED_LIBS.pp=$(RHIDE_TYPED_LIBS_FPC) +RHIDE_TYPED_LIBS_$(RHIDE_OS).cc=stdc++ +RHIDE_TYPED_LIBS_DJGPP.cc=stdcxx m +RHIDE_TYPED_LIBS_DJGPP.cc=stdcxx m +RHIDE_TYPED_LIBS.cc=$(RHIDE_TYPED_LIBS_$(RHIDE_OS).cc) +RHIDE_TYPED_LIBS.cpp=$(RHIDE_TYPED_LIBS.cc) +RHIDE_TYPED_LIBS.cxx=$(RHIDE_TYPED_LIBS.cc) +RHIDE_TYPED_LIBS.C=$(RHIDE_TYPED_LIBS.cc) +RHIDE_TYPED_LIBS.ii=$(RHIDE_TYPED_LIBS.cc) +RHIDE_TYPED_LIBS.l=fl +RHIDE_TYPED_LIBS.m=objc +RHIDE_TYPED_LIBS.adb=gnat +RHIDE_TYPED_LIBS_SUFFIXES=$(sort $(foreach item,$(PROJECT_ITEMS),$(suffix\ + $(item)))) +RHIDE_TYPED_LIBS=$(foreach\ + suff,$(RHIDE_TYPED_LIBS_SUFFIXES),$(RHIDE_TYPED_LIBS$(suff))) +RHIDE_INCLUDES=$(SPECIAL_CFLAGS) $(addprefix -I,$(INCLUDE_DIRS)) +RHIDE_LIBDIRS=$(addprefix -L,$(LIB_DIRS)) +RHIDE_LIBS=$(addprefix -l,$(LIBS) $(RHIDE_TYPED_LIBS) $(RHIDE_OS_LIBS)) +RHIDE_LDFLAGS=$(SPECIAL_LDFLAGS) $(addprefix -Xlinker ,$(LD_EXTRA_FLAGS)) +RHIDE_NASM_TARGET_DJGPP=coff +RHIDE_NASM_TARGET_Linux=elf +RHIDE_NASM_TARGET=$(RHIDE_NASM_TARGET_$(RHIDE_OS)) +RHIDE_COMPILE_NASM=$(RHIDE_NASM) -f $(RHIDE_NASM_TARGET) $(LOCAL_OPT) -o\ + $(OUTFILE) $(SOURCE_NAME) +RHIDE_COMPILE_FORTRAN=$(RHIDE_G77) $(RHIDE_INCLUDES) $(C_DEBUG_FLAGS)\ + $(C_OPT_FLAGS) $(C_WARN_FLAGS) $(C_F_LANG_FLAGS) $(C_EXTRA_FLAGS)\ + $(LOCAL_OPT) -c $(SOURCE_NAME) -o $(OUTFILE) +RHIDE_COMPILE_FORTRAN_FORCE=$(RHIDE_G77) $(RHIDE_INCLUDES) $(C_DEBUG_FLAGS)\ + $(C_OPT_FLAGS) $(C_WARN_FLAGS) $(C_F_LANG_FLAGS) $(C_EXTRA_FLAGS)\ + -x f77 $(LOCAL_OPT) -c $(SOURCE_NAME) -o $(OUTFILE) +RHIDE_COMPILE_C=$(RHIDE_GCC) $(RHIDE_INCLUDES) $(C_DEBUG_FLAGS)\ + $(C_OPT_FLAGS) $(C_WARN_FLAGS) $(C_C_LANG_FLAGS) $(C_EXTRA_FLAGS)\ + $(RHIDE_OS_CFLAGS) $(CPPFLAGS) $(CFLAGS) $(LOCAL_OPT) -c\ + $(SOURCE_NAME) -o $(OUTFILE) +RHIDE_COMPILE_C_FORCE=$(RHIDE_GCC) $(RHIDE_INCLUDES) $(C_DEBUG_FLAGS)\ + $(C_OPT_FLAGS) $(C_WARN_FLAGS) $(C_C_LANG_FLAGS) $(C_EXTRA_FLAGS)\ + -x c $(RHIDE_OS_CFLAGS) $(CPPFLAGS) $(CFLAGS) $(LOCAL_OPT) -c\ + $(SOURCE_NAME) -o $(OUTFILE) +RHIDE_COMPILE_CC=$(RHIDE_GXX) $(RHIDE_INCLUDES) $(C_DEBUG_FLAGS)\ + $(C_OPT_FLAGS) $(C_WARN_FLAGS) $(C_C_LANG_FLAGS)\ + $(C_CXX_LANG_FLAGS) $(C_EXTRA_FLAGS) $(RHIDE_OS_CXXFLAGS)\ + $(CPPFLAGS) $(CXXFLAGS) $(LOCAL_OPT) -c $(SOURCE_NAME) -o\ + $(OUTFILE) +RHIDE_COMPILE_CC_FORCE=$(RHIDE_GXX) $(RHIDE_INCLUDES) $(C_DEBUG_FLAGS)\ + $(C_OPT_FLAGS) $(C_WARN_FLAGS) $(C_C_LANG_FLAGS)\ + $(C_CXX_LANG_FLAGS) $(C_EXTRA_FLAGS) $(RHIDE_OS_CXXFLAGS)\ + $(CPPFLAGS) $(CXXFLAGS) -x c++ $(LOCAL_OPT) -c $(SOURCE_NAME) -o\ + $(OUTFILE) +RHIDE_COMPILE_ASM=$(RHIDE_AS) $(RHIDE_INCLUDES) $(C_DEBUG_FLAGS)\ + $(C_OPT_FLAGS) $(C_WARN_FLAGS) $(C_EXTRA_FLAGS) $(LOCAL_OPT) -c\ + $(SOURCE_NAME) -o $(OUTFILE) +RHIDE_COMPILE_ASM_FORCE=$(RHIDE_AS) $(RHIDE_INCLUDES) $(C_DEBUG_FLAGS)\ + $(C_OPT_FLAGS) $(C_WARN_FLAGS) $(C_EXTRA_FLAGS) -x assembler\ + $(LOCAL_OPT) -c $(SOURCE_NAME) -o $(OUTFILE) +RHIDE_GPC_FLAGS=$(RHIDE_INCLUDES) $(C_DEBUG_FLAGS) $(C_OPT_FLAGS)\ + $(C_WARN_FLAGS) $(C_P_LANG_FLAGS) $(C_EXTRA_FLAGS) +RHIDE_COMPILE_GPC=$(RHIDE_GPC) $(RHIDE_GPC_FLAGS) $(LOCAL_OPT) -c\ + $(SOURCE_NAME) -o $(OUTFILE) +RHIDE_COMPILE_GPC_FORCE=$(RHIDE_GPC) $(RHIDE_GPC_FLAGS) -x pascal\ + $(LOCAL_OPT) -c $(SOURCE_NAME) -o $(OUTFILE) +RHIDE_FPC_FLAGS=$(C_FPC_LANG_FLAGS) $(LOCAL_OPT) $(addprefix\ + -Up,$(INCLUDE_DIRS)) $(C_EXTRA_FLAGS) +RHIDE_COMPILE_FPC=$(RHIDE_FPC) $(RHIDE_FPC_FLAGS) -E- $(SOURCE_NAME) +RHIDE_COMPILE_FPC_FORCE=$(RHIDE_FPC) $(RHIDE_FPC_FLAGS) -B -E-\ + $(SOURCE_NAME) +RHIDE_COMPILE_LINK=$(RHIDE_LD) $(RHIDE_LIBDIRS) $(C_EXTRA_FLAGS) -o\ + $(OUTFILE) $(OBJFILES) $(LIBRARIES) $(LDFLAGS) $(RHIDE_LDFLAGS)\ + $(RHIDE_LIBS) +RHIDE_COMPILE_LINK_GPC=$(RHIDE_LD_PASCAL) $(RHIDE_LIBDIRS) $(C_EXTRA_FLAGS)\ + -o $(OUTFILE) $(OBJFILES) $(LIBRARIES) $(RHIDE_LDFLAGS) $(LDFLAGS)\ + $(RHIDE_LIBS) +RHIDE_COMPILE_LINK_GPC_AUTOMAKE=$(RHIDE_LD_PASCAL) $(RHIDE_LIBDIRS) -o\ + $(OUTFILE) --automake $(RHIDE_GPC_FLAGS) $(SOURCE_NAME)\ + $(LIBRARIES) $(LDFLAGS) $(RHIDE_LDFLAGS) $(RHIDE_LIBS) +RHIDE_COMPILE_PASCAL=$(RHIDE_COMPILE_$(PASCAL_TYPE)) +RHIDE_COMPILE_PASCAL_FORCE=$(RHIDE_COMPILE_$(PASCAL_TYPE)_FORCE) +RHIDE_COMPILE_LINK_PASCAL_AUTOMAKE=$(RHIDE_COMPILE_LINK_$(PASCAL_TYPE)_AUTOMAKE) +RHIDE_COMPILE_LINK_PASCAL=$(RHIDE_COMPILE_LINK_$(PASCAL_TYPE)) +RHIDE_FPC_LIBDIRS_$(RHIDE_OS)=/usr/local/lib /usr/lib /lib +RHIDE_FPC_LIBDIRS_DJGPP=/usr/local/lib /usr/lib /lib +RHIDE_FPC_LIBDIRS_DJGPP=$(DJDIR)/lib +RHIDE_FPC_LIBDIRS=$(RHIDE_FPC_LIBDIRS_$(RHIDE_OS)) +RHIDE_FPC_LINK_FLAGS_$(RHIDE_OS)=$(RHIDE_LIBDIRS) $(addprefix\ + -L,$(RHIDE_FPC_LIBDIRS)) +RHIDE_FPC_LINK_FLAGS_DJGPP=$(RHIDE_LIBDIRS) $(addprefix\ + -L,$(RHIDE_FPC_LIBDIRS)) +RHIDE_FPC_LINK_FLAGS_DJGPP=-O coff-go32-exe $(RHIDE_LIBDIRS) $(addprefix\ + -L,$(RHIDE_FPC_LIBDIRS)) +RHIDE_FPC_LINK_FLAGS=$(RHIDE_FPC_LINK_FLAGS_$(RHIDE_OS)) +RHIDE_COMPILE_LINK_FPC=echo 'separate linking for FPK is not supported.\ + Please define a main source file in Project/Primary file.' 1>&2 +RHIDE_COMPILE_LINK_FPC_AUTOMAKE=$(RHIDE_FPC) -o$(OUTFILE) $(SOURCE_NAME)\ + $(RHIDE_FPC_FLAGS) -E+ +RHIDE_COMPILE_ARCHIVE=$(RHIDE_AR) $(RHIDE_ARFLAGS) $(OUTFILE)\ + $(ALL_OBJFILES) +RHIDE_COMPILE_ADA=$(RHIDE_GCC) $(RHIDE_INCLUDES) $(C_DEBUG_FLAGS)\ + $(C_OPT_FLAGS) $(C_WARN_FLAGS) $(C_C_LANG_FLAGS) $(C_EXTRA_FLAGS)\ + $(LOCAL_OPT) $(C_ADA_LANG_FLAGS) $(RHIDE_OS_CFLAGS) $(CPPFLAGS)\ + $(CFLAGS) -c $(SOURCE_NAME) -o $(OUTFILE) +RHIDE_ADA_BIND_FILE=$(addprefix _,$(setsuffix .c,$(OUTFILE))) +RHIDE_COMPILE_LINK_ADA_BIND=$(RHIDE_GNATBIND) -o $(RHIDE_ADA_BIND_FILE)\ + $(setsuffix .ali,$(OUTFILE)) +RHIDE_COMPILE_LINK_ADA_LINK=$(RHIDE_LD) $(RHIDE_LIBDIRS) $(C_EXTRA_FLAGS) -o\ + $(OUTFILE) $(RHIDE_ADA_BIND_FILE) $(OBJFILES) $(LIBRARIES)\ + $(LDFLAGS) $(RHIDE_LDFLAGS) $(RHIDE_LIBS) +_RHIDE_COMPILE_LINK_ADA=$(RHIDE_COMPILE_LINK_ADA_BIND);\ + $(RHIDE_COMPILE_LINK_ADA_LINK); $(RHIDE_RM)\ + $(RHIDE_ADA_BIND_FILE) +RHIDE_COMPILE_LINK_ADA=gnatbl $(RHIDE_LIBDIRS) $(C_EXTRA_FLAGS) -o\ + $(OUTFILE) $(setsuffix .ali,$(OUTFILE)) $(LIBRARIES) $(LDFLAGS) \ + $(RHIDE_LDFLAGS) $(RHIDE_LIBS) +RHIDE_COMPILE.c.o=$(RHIDE_COMPILE_C) +RHIDE_COMPILE.cc.o=$(RHIDE_COMPILE_CC) +RHIDE_COMPILE.p.o=$(RHIDE_COMPILE_PASCAL) +RHIDE_COMPILE.pas.o=$(RHIDE_COMPILE.p.o) +RHIDE_COMPILE.pp.o=$(RHIDE_COMPILE_FPC) +RHIDE_COMPILE.pas.s.GPC=$(subst -c $(SOURCE_NAME),-S\ + $(SOURCE_NAME),$(RHIDE_COMPILE_GPC)) +RHIDE_COMPILE.pas.s.FPC=$(RHIDE_COMPILE_FPC) -a -s +RHIDE_COMPILE.pas.s=$(RHIDE_COMPILE.pas.s.$(PASCAL_TYPE)) +RHIDE_COMPILE.f.o=$(RHIDE_COMPILE_FORTRAN) +RHIDE_COMPILE.nsm.o=$(RHIDE_COMPILE_NASM) +RHIDE_COMPILE.s.o=$(RHIDE_COMPILE_ASM) +RHIDE_COMPILE.c.s=$(subst -c $(SOURCE_NAME),-S\ + $(SOURCE_NAME),$(RHIDE_COMPILE_C)) +RHIDE_COMPILE.c.i=$(subst -c $(SOURCE_NAME),-E\ + $(SOURCE_NAME),$(RHIDE_COMPILE_C)) +RHIDE_COMPILE.i.s=$(RHIDE_COMPILE.c.s) +RHIDE_COMPILE.cc.s=$(subst -c $(SOURCE_NAME),-S\ + $(SOURCE_NAME),$(RHIDE_COMPILE_CC)) +RHIDE_COMPILE.cc.ii=$(subst -c $(SOURCE_NAME),-E\ + $(SOURCE_NAME),$(RHIDE_COMPILE_CC)) +RHIDE_COMPILE.ii.s=$(RHIDE_COMPILE.cc.s) +RHIDE_COMPILE.cpp.o=$(RHIDE_COMPILE.cc.o) +RHIDE_COMPILE.cxx.o=$(RHIDE_COMPILE.cc.o) +RHIDE_COMPILE.C.o=$(RHIDE_COMPILE.cc.o) +RHIDE_COMPILE.pas.o=$(RHIDE_COMPILE.p.o) +RHIDE_COMPILE.for.o=$(RHIDE_COMPILE.f.o) +RHIDE_COMPILE.F.o=$(RHIDE_COMPILE.f.o) +RHIDE_COMPILE.fpp.o=$(RHIDE_COMPILE.f.o) +RHIDE_COMPILE.asm.o=$(RHIDE_COMPILE.nsm.o) +RHIDE_COMPILE.cpp.s=$(RHIDE_COMPILE.cc.s) +RHIDE_COMPILE.cxx.s=$(RHIDE_COMPILE.cc.s) +RHIDE_COMPILE.C.s=$(RHIDE_COMPILE.cc.s) +RHIDE_COMPILE.cpp.ii=$(RHIDE_COMPILE.cc.ii) +RHIDE_COMPILE.cxx.ii=$(RHIDE_COMPILE.cc.ii) +RHIDE_COMPILE.C.ii=$(RHIDE_COMPILE.cc.ii) +RHIDE_COMPILE.adb.o=$(RHIDE_COMPILE_ADA) +RHIDE_FSDB=fsdb $(OUTFILE) $(addprefix -p ,$(SRC_DIRS)) $(PROG_ARGS) +RHIDE_GDB=gdb $(OUTFILE) $(addprefix -d ,$(SRC_DIRS)) +DEFAULT_GREP_MASK=*.[cfhmnps]* +RHIDE_GREP=grep -n $(prompt arguments for GREP,$(WUC) $(DEFAULT_GREP_MASK)) +RHIDE_GPROF=gprof $(OUTFILE) +RHIDE_RLOG=$(shell rlog -R $(rlog_arg)) +RHIDE_CO=$(shell co -q $(co_arg)) +RHIDE_STANDARD_INCLUDES_$(RHIDE_OS)=$(addprefix /usr/,include include/sys\ + include/g++ include/g++/std) +RHIDE_STANDARD_INCLUDES_DJGPP=$(addprefix /usr/,include include/sys\ + include/g++ include/g++/std) +RHIDE_STANDARD_INCLUDES_DJGPP=$(addprefix $(DJDIR)/,include include/sys\ + lang/cxx lang/cxx/std) +RHIDE_STANDARD_INCLUDES=$(RHIDE_STANDARD_INCLUDES_$(RHIDE_OS)) +RHIDE_CONFIG_DIRS_$(RHIDE_OS)=/usr/local/share/rhide /usr/share/rhide \ + /local/share/rhide /share/rhide +RHIDE_CONFIG_DIRS_DJGPP=/usr/local/share/rhide /usr/share/rhide \ + /local/share/rhide /share/rhide +RHIDE_CONFIG_DIRS_DJGPP=$(DJDIR)/share/rhide +RHIDE_CONFIG_DIRS_COMMON=$(RHIDE_CONFIG_DIRS_$(RHIDE_OS))\ + $(RHIDE_BIN_DIR)/../share/rhide +RHIDE_CONFIG_DIRS=. $(RHIDE_SHARE) $(GET_HOME) $(RHIDE_CONFIG_DIRS_COMMON)\ + $(addsuffix /SET,$(RHIDE_CONFIG_DIRS_COMMON)) $(SET_FILES) +RHIDE_PATH_SEPARATOR_$(RHIDE_OS)=: +RHIDE_PATH_SEPARATOR_DJGPP=: +RHIDE_PATH_SEPARATOR_DJGPP=; +RHIDE_PATH_SEPARATOR=$(RHIDE_PATH_SEPARATOR_$(RHIDE_OS)) +RHIDE_EMPTY= +RHIDE_SPACE=$(RHIDE_EMPTY) $(RHIDE_EMPTY) +RHIDE_TYPED_LIBS_DJGPP.cc=stdcxx m +RHIDE_TYPED_LIBS_DJGPP.cxx=stdcxx m +RHIDE_TYPED_LIBS_DJGPP.cpp=stdcxx m +RHIDE_TYPED_LIBS.f=g2c m +%.o: %.c + $(RHIDE_COMPILE.c.o) +%.o: %.i + $(RHIDE_COMPILE_C) +%.o: %.cc + $(RHIDE_COMPILE.cc.o) +%.o: %.cpp + $(RHIDE_COMPILE.cpp.o) +%.o: %.cxx + $(RHIDE_COMPILE.cxx.o) +%.o: %.C + $(RHIDE_COMPILE.C.o) +%.o: %.ii + $(RHIDE_COMPILE_CC) +%.o: %.s + $(RHIDE_COMPILE.s.o) +%.o: %.S + $(RHIDE_COMPILE_ASM) +%.s: %.c + $(RHIDE_COMPILE.c.s) +%.s: %.i + $(RHIDE_COMPILE.i.s) +%.s: %.cc + $(RHIDE_COMPILE.cc.s) +%.s: %.cpp + $(RHIDE_COMPILE.cpp.s) +%.s: %.cxx + $(RHIDE_COMPILE.cxx.s) +%.s: %.C + $(RHIDE_COMPILE.C.s) +%.o: %.pas + $(RHIDE_COMPILE.pas.o) +%.o: %.p + $(RHIDE_COMPILE.p.o) +%.o: %.pp + $(RHIDE_COMPILE.pp.o) +%.s: %.pas + $(RHIDE_COMPILE.pas.s) +%.o: %.m + $(RHIDE_COMPILE_OBJC) +%.o: %.f + $(RHIDE_COMPILE.f.o) +%.o: %.for + $(RHIDE_COMPILE.for.o) +%.o: %.F + $(RHIDE_COMPILE.F.o) +%.o: %.fpp + $(RHIDE_COMPILE.fpp.o) +%.o: %.asm + $(RHIDE_COMPILE.asm.o) +%.o: %.nsm + $(RHIDE_COMPILE.nsm.o) +%.o: %.adb + $(RHIDE_COMPILE.adb.o) +%.i: %.c + $(RHIDE_COMPILE.c.i) +%.s: %.c + $(RHIDE_COMPILE.c.s) +%.ii: %.cc + $(RHIDE_COMPILE.cc.ii) +%.s: %.cc + $(RHIDE_COMPILE.cc.s) +%.ii: %.cpp + $(RHIDE_COMPILE.cpp.ii) +%.s: %.cpp + $(RHIDE_COMPILE.cpp.s) +%.ii: %.cxx + $(RHIDE_COMPILE.cxx.ii) +%.s: %.cxx + $(RHIDE_COMPILE.cxx.s) +%.ii: %.C + $(RHIDE_COMPILE.C.ii) +%.s: %.C + $(RHIDE_COMPILE.C.s) +clean:: + rm -f $(CLEAN_FILES) +DEPS_0= main.o objgfx30.o ogBlit.o ogDisplay_VESA.o ogFont.o ogSprite.o +NO_LINK= +LINK_FILES=$(filter-out $(NO_LINK),$(DEPS_0)) +objgfx.exe:: $(DEPS_0) + $(RHIDE_COMPILE_LINK) +DEPS_1=main.cpp +main.o:: $(DEPS_1) + $(RHIDE_COMPILE.cpp.o) +DEPS_2=objgfx30.cpp +objgfx30.o:: $(DEPS_2) + $(RHIDE_COMPILE.cpp.o) +DEPS_3=ogBlit.cpp +ogBlit.o:: $(DEPS_3) + $(RHIDE_COMPILE.cpp.o) +DEPS_4=ogDisplay_VESA.cpp +ogDisplay_VESA.o:: $(DEPS_4) + $(RHIDE_COMPILE.cpp.o) +DEPS_5=ogFont.cpp +ogFont.o:: $(DEPS_5) + $(RHIDE_COMPILE.cpp.o) +DEPS_6=ogSprite.cpp +ogSprite.o:: $(DEPS_6) + $(RHIDE_COMPILE.cpp.o) +all:: objgfx.exe + \ No newline at end of file diff --git a/src/lib/objgfx40/vWidget.cpp b/src/lib/objgfx40/vWidget.cpp new file mode 100644 index 0000000..a528250 --- /dev/null +++ b/src/lib/objgfx40/vWidget.cpp @@ -0,0 +1,9 @@ +#include + +bool +vWidget::vSetActive(bool _active) { + bool result = active; + active = _active; + return result; +} // vWidget::vSetActive + diff --git a/src/lib/objgfx40/vWindow.cpp b/src/lib/objgfx40/vWindow.cpp new file mode 100644 index 0000000..5e4da43 --- /dev/null +++ b/src/lib/objgfx40/vWindow.cpp @@ -0,0 +1,44 @@ +extern "C" { + #include + } +#include + +vWindow::vWindow(void) { + realWindow = new ogSurface(); + titleFont = new ogBitFont(); + return; +} // vWindow::vWindow + +bool +vWindow::vCreate(void) { + if (realWindow->Create(400,400,OG_PIXFMT_16BPP) == false) return false; + if (Alias(*realWindow, // window + 0, 0, // [x1, y1] + realWindow->GetMaxX(), realWindow->GetMaxY()) // [x2, y2] + == false) return false; + return true; +} // vWindow::vCreate + +void +vWindow::vSDECommand(uInt32 command) { + asm( + "int %0" + : + : "i" (0x80),"a" (40),"b" (command),"c" (realWindow) + ); + return; +} // vWindow::vSDECommand + +vWindow::~vWindow() { + delete realWindow; + delete titleFont; + return; +} // vWindow::~vWindow + +/* +ogSurface -> vWidget -> vWindow + | \------> vButton + | + | + -- ogDisplay_UbixOS -> SDE +*/ diff --git a/src/lib/ubix/Makefile b/src/lib/ubix/Makefile new file mode 100644 index 0000000..1f49f18 --- /dev/null +++ b/src/lib/ubix/Makefile @@ -0,0 +1,35 @@ +# $Id$ +# Kernel Makefile (C) 2002 The UbixOS Project + +# Include Global 'Source' Options +include ../../Makefile.inc +include ../Makefile.inc + +#Binary File Name +BINARY = none + +#Objects +OBJS = startup.o + +# Make the Binary +$(BINARY) : $(OBJS) + +# Compile the source files +.cc.o: + $(CXX) -Wall -fomit-frame-pointer -O -I../libc/include -c -o $@ $< + +.cc.s: + $(CXX) -Wall -fomit-frame-pointer -O -I../libc/include -S -o $@ $< + +.c.o: + $(CC) -Wall -O -I../libc/include -c -o $@ $< + +.c.s: + $(CC) -Wall -fomit-frame-pointer -O -I../libc/include -S -o $@ $< + +.S.o: + $(CC) -Wall -fomit-frame-pointer -c -o $@ $< + +# Clean up the junk +clean: + $(REMOVE) $(OBJS) $(BINARY) diff --git a/src/lib/ubix/startup.c b/src/lib/ubix/startup.c new file mode 100644 index 0000000..3ced2f5 --- /dev/null +++ b/src/lib/ubix/startup.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$ + +**************************************************************************************/ + +#include +#include +#include + +extern int main(int,char **); +const char *__progname = ""; + +void _start(int argc,char **argv) { + //__progname = argv[0]; + exit(main(argc,argv)); + } diff --git a/src/lib/views/sunlight/Makefile b/src/lib/views/sunlight/Makefile new file mode 100644 index 0000000..fee3837 --- /dev/null +++ b/src/lib/views/sunlight/Makefile @@ -0,0 +1,36 @@ +# $Id$ +# Kernel Makefile (C) 2002 The UbixOS Project + +include ../../../Makefile.inc + +#Objects +OBJS = sStyle.o vContext.o vButton.o vMenuBar.o vView.o vCanvas.o vDesktop.o + +#Include +INCLUDE = -I./ -I../../..lib/libc/include -I../../../lib/libcpp/include -I../../objgfx40/objgfx40 -I./include + +#Output +OUTPUT = views.so + +$(OUTPUT): $(OBJS) + $(CC) -nostdlib -shared -Wl,-soname,$(OUTPUT) -o $(OUTPUT) $(OBJS) + +# Compile the source files +.cpp.o: + $(CXX) -Wall -g -fno-builtin -fno-rtti -fno-exceptions -DNOBOOL $(INCLUDE) -c -o $@ $< + +.cc.o: + $(CXX) -Wall -fomit-frame-pointer -O -nobuilting -I../../lib/libc/include -I./include -S -o $@ $< + +.c.o: + $(CC) -Wall -O -I../../../lib/libc/include -c -o $@ $< + +.c.s: + $(CC) -Wall -fomit-frame-pointer -O -I../../../lib/libc/include -S -o $@ $< + +.S.o: + $(CC) -Wall -fomit-frame-pointer -c -o $@ $< + +# Clean up the junk +clean: + $(REMOVE) $(OBJS) $(BINARY) *.core diff --git a/src/lib/views/sunlight/include/sStyle.h b/src/lib/views/sunlight/include/sStyle.h new file mode 100644 index 0000000..18f15d0 --- /dev/null +++ b/src/lib/views/sunlight/include/sStyle.h @@ -0,0 +1,9 @@ +#ifndef SSTYLE_H +#define SSTYLE_H + +class sStyle { + protected: + public: + virtual ~sStyle(void); +}; // sStyle +#endif diff --git a/src/lib/views/sunlight/include/vButton.h b/src/lib/views/sunlight/include/vButton.h new file mode 100644 index 0000000..fa63da0 --- /dev/null +++ b/src/lib/views/sunlight/include/vButton.h @@ -0,0 +1,12 @@ +#ifndef VBUTTON_H +#define VBUTTON_H + +#include "vContext.h" + +class vButton : public vContext { + protected: + public: + vButton(vContext *); + virtual ~vButton(); +}; // vButton +#endif diff --git a/src/lib/views/sunlight/include/vCanvas.h b/src/lib/views/sunlight/include/vCanvas.h new file mode 100644 index 0000000..f6ce306 --- /dev/null +++ b/src/lib/views/sunlight/include/vCanvas.h @@ -0,0 +1,12 @@ +#ifndef VCANVAS_H +#define VCANVAS_H + +#include + +class vCanvas : public vContext { + protected: + public: + vCanvas(vContext *); + virtual ~vCanvas(void); +}; // vCanvas +#endif diff --git a/src/lib/views/sunlight/include/vContext.h b/src/lib/views/sunlight/include/vContext.h new file mode 100644 index 0000000..2c0fe26 --- /dev/null +++ b/src/lib/views/sunlight/include/vContext.h @@ -0,0 +1,35 @@ +#ifndef VCONTEXT_H +#define VCONTEXT_H + +#include +#include +#include +#include +#include + +class vContext : public ogSurface { + protected: + std::map styles; + std::list cContexts; // child contexts + vContext * pContext; // parent context + + ogSurface * realView; + int32 curX, curY; + uInt32 width, height; + bool attached; + public: + vContext(vContext *); + virtual vContext * Attach(vContext *); + virtual void DeleteAllStyles(void) { styles.clear(); }; + virtual bool DeleteStyle(const std::string); + virtual void Draw(void); + virtual vContext * Detach(vContext *); + virtual sStyle * GetStyle(const std::string); + virtual void SetPos(int32, int32); + virtual void SetSize(uInt32, uInt32); + virtual void SetStyle(const std::string, sStyle *); + virtual ~vContext(); + +}; // vContext + +#endif diff --git a/src/lib/views/sunlight/include/vDesktop.h b/src/lib/views/sunlight/include/vDesktop.h new file mode 100644 index 0000000..18aac66 --- /dev/null +++ b/src/lib/views/sunlight/include/vDesktop.h @@ -0,0 +1,18 @@ +#ifndef VDESKTOP_H +#define VDESKTOP_H + +#include + +class vDesktop : public vContext { + protected: + public: + vDesktop(vContext *); + virtual void DeleteAllStyles(void); + virtual bool DeleteStyle(const std::string); + virtual sStyle * GetStyle(const std::string); + virtual void SetPos(int32, int32); + virtual void SetStyle(const std::string, sStyle *); + + virtual ~vDesktop(void); +}; // vDesktop +#endif diff --git a/src/lib/views/sunlight/include/vMenuBar.h b/src/lib/views/sunlight/include/vMenuBar.h new file mode 100644 index 0000000..6e834f7 --- /dev/null +++ b/src/lib/views/sunlight/include/vMenuBar.h @@ -0,0 +1,13 @@ +#ifndef VMENUBAR_H +#define VMENUBAR_H + +#include + +class vMenuBar : public vContext { + protected: + public: + vMenuBar(vContext *); + virtual ~vMenuBar(); +}; // vMenuBar + +#endif diff --git a/src/lib/views/sunlight/include/vTitleTab.h b/src/lib/views/sunlight/include/vTitleTab.h new file mode 100644 index 0000000..17030e3 --- /dev/null +++ b/src/lib/views/sunlight/include/vTitleTab.h @@ -0,0 +1,18 @@ +#ifndef VTITLETAB_H +#define VTITLETAB_H + +#include +#include +#include + +class vTitleTab : public vContext { + protected: + ogBitFont * font; + std::string title; + public: + vTitleTab(vContext *); + void SetTitle(const std::string); + virtual ~vTitleTab(void); +}; // vTitleTab + +#endif diff --git a/src/lib/views/sunlight/include/vView.h b/src/lib/views/sunlight/include/vView.h new file mode 100644 index 0000000..ce48f85 --- /dev/null +++ b/src/lib/views/sunlight/include/vView.h @@ -0,0 +1,15 @@ +#ifndef VVIEW_H +#define VVIEW_H + +#include +#include +#include + +class vView : public vTitleTab, public vCanvas { + protected: + public: + vView(vContext *); + virtual ~vView(void); +}; // vView + +#endif diff --git a/src/lib/views/sunlight/sStyle.cpp b/src/lib/views/sunlight/sStyle.cpp new file mode 100644 index 0000000..a3e0645 --- /dev/null +++ b/src/lib/views/sunlight/sStyle.cpp @@ -0,0 +1,5 @@ +#include + +sStyle::~sStyle(void) { + return; +} // sStyle::~sStyle diff --git a/src/lib/views/sunlight/vButton.cpp b/src/lib/views/sunlight/vButton.cpp new file mode 100644 index 0000000..e3b816f --- /dev/null +++ b/src/lib/views/sunlight/vButton.cpp @@ -0,0 +1,12 @@ +#include +#include +#include + +vButton::vButton(vContext * parent) : vContext(parent) { + + return; +} // vButton::vButton + +vButton::~vButton(void) { + return; +} // vButton::~vButton diff --git a/src/lib/views/sunlight/vCanvas.cpp b/src/lib/views/sunlight/vCanvas.cpp new file mode 100644 index 0000000..c967aac --- /dev/null +++ b/src/lib/views/sunlight/vCanvas.cpp @@ -0,0 +1,10 @@ +#include +#include + +vCanvas::vCanvas(vContext * parent) : vContext(parent) { + return; +} + +vCanvas::~vCanvas(void) { + return; +} diff --git a/src/lib/views/sunlight/vContext.cpp b/src/lib/views/sunlight/vContext.cpp new file mode 100644 index 0000000..e041dda --- /dev/null +++ b/src/lib/views/sunlight/vContext.cpp @@ -0,0 +1,98 @@ +#include +#include +#include +#include +#include + +vContext::vContext(vContext * parent) { + pContext = parent; + realView = new ogSurface(); + curX = curY = width = height = 0; + attached = false; + return; +} // vContext::vContext + +vContext * +vContext::Attach(vContext * context) { + cContexts.push_back(context); + return context; +} // vContext::Attach + +bool +vContext::DeleteStyle(const std::string styleKey) { + /* + * vContext::DeleteStyle() + * returns true if style existed and was deleted + * returns false if style didn't exist (or wasn't deleted) + */ + + sStyle * tmpStyle = styles[styleKey]; + styles.erase(styleKey); + delete tmpStyle; + return (NULL == tmpStyle) ? false : true; +} // vContext::DeleteStyle + +vContext * +vContext::Detach(vContext * context) { + cContexts.remove(context); + return context; +} // vContext::Detach + +void +vContext::Draw(void) { + return; +} // vContext::Draw + +sStyle * +vContext::GetStyle(const std::string styleKey) { + /* + * GetStyle() + * retreives a style out of the style map using the styleKey string + * If no style is present in this node, check the parent + */ + sStyle * tmpStyle = styles[styleKey]; + + if ((NULL == tmpStyle) && (NULL != pContext)) { + return pContext->GetStyle(styleKey); + } // if + + return tmpStyle; +} // vContext::GetStyle + +void +vContext::SetPos(int32 newX, int32 newY) { + /* + * vContext::SetPos() + * Sets new position relative to parent's upper left corner + */ + + // I really should detach from the parent here + curX = newX; + curY = newY; + // and reattach to parent here + return; +} // vContext::SetPos + +void +vContext::SetSize(uInt32 newWidth, uInt32 newHeight) { + width = newWidth; + height = newHeight; +} // vContext::SetSize + +void +vContext::SetStyle(const std::string styleKey, sStyle * style) { + // I probably should check to see if a style exists before setting it + + // if the style is null, then just exit out without setting it + if (NULL == style) return; + + // set the new style + styles[styleKey] = style; +} // vContext::SetStyle + +vContext::~vContext(void) { + delete realView; + pContext = NULL; + curX = curY = 0; + return; +} // vContext::~vContext diff --git a/src/lib/views/sunlight/vDesktop.cpp b/src/lib/views/sunlight/vDesktop.cpp new file mode 100644 index 0000000..b48181e --- /dev/null +++ b/src/lib/views/sunlight/vDesktop.cpp @@ -0,0 +1,40 @@ +#include +#include + +vDesktop::vDesktop(vContext * parent) : vContext(parent) { + return; +} // vDesktop::vDesktop + +void +vDesktop::DeleteAllStyles(void) { + return; +} + +bool +vDesktop::DeleteStyle(const std::string styleName) { + return false; +} + +sStyle * +vDesktop::GetStyle(const std::string styleName) { + /* + * vDesktop::GetStyle + * This will have to send a message to the Launcher to get the actual + * style. For now use NULL + */ + return NULL; +} // vDesktop::GetStyle + +void +vDesktop::SetPos(int32 newX, int32 newY) { + return; +} // vDesktop::SetPos + +void +vDesktop::SetStyle(const std::string nameStyle, sStyle * style) { + return; +} // vDesktop::SetStyle + +vDesktop::~vDesktop(void) { + return; +} // vDesktop::~vDesktop diff --git a/src/lib/views/sunlight/vMenuBar.cpp b/src/lib/views/sunlight/vMenuBar.cpp new file mode 100644 index 0000000..a4e24f4 --- /dev/null +++ b/src/lib/views/sunlight/vMenuBar.cpp @@ -0,0 +1,10 @@ +#include +#include + +vMenuBar::vMenuBar(vContext * parent) : vContext(parent) { + return; +} // vMenuBar::vMenuBar + +vMenuBar::~vMenuBar(void) { + return; +} // vMenuBar::~vMenuBar diff --git a/src/lib/views/sunlight/vTitleTab.cpp b/src/lib/views/sunlight/vTitleTab.cpp new file mode 100644 index 0000000..d191bd0 --- /dev/null +++ b/src/lib/views/sunlight/vTitleTab.cpp @@ -0,0 +1,22 @@ +#include +#include +#include + +vTitleTab::vTitleTab(vContext * parent) : vContext(parent) { + font = new ogBitFont(); + title = ""; + + return; +} // vTitleTab::vTitleTab + +void +vTitleTab::SetTitle(const std::string newTitle) { + title = newTitle; + return; +} // vTitleTab::SetTitle + +vTitleTab::~vTitleTab(void) { + delete font; + font = NULL; + return; +} // vTitleTab::~vTitleTab diff --git a/src/lib/views/sunlight/vView.cpp b/src/lib/views/sunlight/vView.cpp new file mode 100644 index 0000000..34b586b --- /dev/null +++ b/src/lib/views/sunlight/vView.cpp @@ -0,0 +1,11 @@ +#include +#include +#include + +vView::vView(vContext * parent) : vTitleTab(parent), vCanvas(parent) { + return; +} // vView::vView + +vView::~vView(void) { + return; +} diff --git a/src/sys/Makefile b/src/sys/Makefile new file mode 100644 index 0000000..9b92f1f --- /dev/null +++ b/src/sys/Makefile @@ -0,0 +1,77 @@ +# $Id$ +# Kernel Makefile (C) 2002 The UbixOS Project + +all: net-code sde-code pci-code ubixfs-code vfs-code isa-code kernel-code lib-code vmm-code sys-code boot-code init-code devfs-code kernel-img + +boot-code: boot + (cd boot;make) + +init-code: init + (cd init;make) + +kernel-code: kernel + (cd kernel;make) + +isa-code: isa + (cd isa;make) + +pci-code: pci + (cd pci;make) + +sys-code: sys + (cd sys;make) + +vmm-code: vmm + (cd vmm;make) + +ubixfs-code: ubixfs + (cd ubixfs;make) + +devfs-code: devfs + (cd devfs;make) + +graphics-code: graphics + (cd graphics;make) + +ld-code: ld + (cd ld;make) + +lib-code: lib + (cd lib;make) + +sde-code: sde + (cd sde;make) + +vfs-code: vfs + (cd vfs;make) + +net-code: net + (cd net;make) + +kernel-img: compile + (/bin/echo "/* " > ./compile/null.c) + (date >> ./compile/null.c) + (echo $user >> ./compile/null.c) + (/bin/echo " */" >> ./compile/null.c) + (cd compile;make) + +install: + (cd boot;make install) + (cd ../tools/;make format-dsk) + +clean: + (cd boot;make clean) + (cd init;make clean) + (cd compile;make clean) + (cd sys;make clean) + (cd vmm;make clean) + (cd lib;make clean) + (cd kernel;make clean) + (cd isa;make clean) + (cd vfs;make clean) + (cd ubixfs;make clean) + (cd pci;make clean) + (cd sde;make clean) + (cd devfs;make clean) + (cd net;make clean) + (cd ../tools/;make clean) diff --git a/src/sys/Makefile.inc b/src/sys/Makefile.inc new file mode 100644 index 0000000..d5729ab --- /dev/null +++ b/src/sys/Makefile.inc @@ -0,0 +1,5 @@ +# $Id: +# global 'sys' options + +CFLAGS = -fno-builtin +KERNEL = ubix.elf diff --git a/src/sys/boot/Makefile b/src/sys/boot/Makefile new file mode 100644 index 0000000..eef8f5a --- /dev/null +++ b/src/sys/boot/Makefile @@ -0,0 +1,14 @@ +# $Id$ + +FDDEVICE = "/dev/fd0" +#FDDEVICE = /dev/fd1 +all: + (cd mbr;make) + +install: + +clean: + (rm -f writeimg format bootsec *.core boot2/test) + (cd btx;make clean) + (cd boot2;make clean) + (cd mbr;make clean) diff --git a/src/sys/boot/Makefile.inc b/src/sys/boot/Makefile.inc new file mode 100644 index 0000000..65ce9b5 --- /dev/null +++ b/src/sys/boot/Makefile.inc @@ -0,0 +1,7 @@ +# Common defines for all of /sys/boot/i386/ +# +# $FreeBSD: src/sys/boot/i386/Makefile.inc,v 1.1.2.2 2000/12/28 12:04:04 ps Exp $ + +LOADER_ADDRESS?= 0x200000 +CFLAGS+= -mpreferred-stack-boundary=2 +CC = gcc diff --git a/src/sys/boot/boot2/Makefile b/src/sys/boot/boot2/Makefile new file mode 100644 index 0000000..cd404d1 --- /dev/null +++ b/src/sys/boot/boot2/Makefile @@ -0,0 +1,87 @@ +# $FreeBSD: src/sys/boot/i386/boot2/Makefile,v 1.16.2.5 2002/08/07 16:31:53 ru Exp $ + +PROG= boot2 +NOMAN= +STRIP= +BINDIR?= /boot +BINMODE= 444 +CLEANFILES+= boot1 boot1.out boot1.o \ + boot2.ldr boot2.bin boot2.ld boot2.out boot2.o boot2.h \ + sio.o + +NM?= nm + +# A value of 0x80 enables LBA support. +B1FLAGS= 0x80 + +BOOT_COMCONSOLE_PORT?= 0x3f8 +BOOT_COMCONSOLE_SPEED?= 9600 +B2SIOFMT?= 0x3 + +.if exists(${.OBJDIR}/../btx) +BTX= ${.OBJDIR}/../btx +.else +BTX= ${.CURDIR}/../btx +.endif + +ORG1= 0x7c00 +ORG2= 0x1000 + +CFLAGS= -elf -I${.CURDIR}/../btx/lib -I. \ + -Os -fno-builtin -fforce-addr -fdata-sections \ + -malign-functions=0 -malign-jumps=0 -malign-loops=0 -mrtd \ + -mpreferred-stack-boundary=2 \ + -Wall -Waggregate-return -Wbad-function-cast -Wcast-align \ + -Wmissing-declarations -Wmissing-prototypes -Wnested-externs \ + -Wpointer-arith -Wshadow -Wstrict-prototypes -Wwrite-strings + +LDFLAGS=-nostdlib -static -N + +all: boot1 boot2 + +boot1: boot1.out + objcopy -S -O binary boot1.out ${.TARGET} + +boot1.out: boot1.o + ${LD} ${LDFLAGS} -e start -Ttext ${ORG1} -o ${.TARGET} boot1.o + +boot1.o: boot1.s + ${AS} ${AFLAGS} --defsym FLAGS=${B1FLAGS} ${.IMPSRC} -o ${.TARGET} + +boot2.h: boot1.out + ${NM} -t d ${.ALLSRC} | awk '/([0-9])+ T xread/ \ + { x = $$1 - ORG1; printf("#define XREADORG 0x7%x\n", x) }' \ + ORG1=`printf "%d" ${ORG1}` > boot2.h + +boot2: boot2.ldr boot2.bin ${BTX}/btx/btx + btxld -v -E ${ORG2} -f bin -b ${BTX}/btx/btx -l boot2.ldr \ + -o boot2.ld -P 1 boot2.bin + @ls -l boot2.ld | awk '{ x = 7680 - $$5; \ + print x " bytes available"; if (x < 0) exit 1 }' + dd if=boot2.ld of=${.TARGET} obs=7680 conv=osync 2>/dev/null + +boot2.ldr: + dd if=/dev/zero of=${.TARGET} bs=512 count=1 2>/dev/null + +boot2.bin: boot2.out + objcopy -S -O binary boot2.out ${.TARGET} + +boot2.out: boot2.o sio.o + ${LD} ${LDFLAGS} -Ttext ${ORG2} -o ${.TARGET} \ + ${BTX}/lib/crt0.o boot2.o sio.o + +boot2.o: boot2.h + +sio.o: sio.s + ${AS} ${AFLAGS} --defsym SIOPRT=${BOOT_COMCONSOLE_PORT} \ + --defsym SIOFMT=${B2SIOFMT} \ + --defsym SIOSPD=${BOOT_COMCONSOLE_SPEED} \ + ${.IMPSRC} -o ${.TARGET} + +install: + ${INSTALL} -o ${BINOWN} -g ${BINGRP} -m ${BINMODE} \ + boot1 ${DESTDIR}${BINDIR}/boot1 + ${INSTALL} -o ${BINOWN} -g ${BINGRP} -m ${BINMODE} \ + boot2 ${DESTDIR}${BINDIR}/boot2 + +.include diff --git a/src/sys/boot/boot2/boot1.s b/src/sys/boot/boot2/boot1.s new file mode 100644 index 0000000..6cda6a2 --- /dev/null +++ b/src/sys/boot/boot2/boot1.s @@ -0,0 +1,364 @@ +# +# Copyright (c) 1998 Robert Nordier +# All rights reserved. +# +# Redistribution and use in source and binary forms are freely +# permitted provided that the above copyright notice and this +# paragraph and the following disclaimer are duplicated in all +# such forms. +# +# This software is provided "AS IS" and without any express or +# implied warranties, including, without limitation, the implied +# warranties of merchantability and fitness for a particular +# purpose. +# + +# $Id$ + +# Memory Locations + .set MEM_REL,0x700 # Relocation address + .set MEM_ARG,0x900 # Arguments + .set MEM_ORG,0x7c00 # Origin + .set MEM_BUF,0x8c00 # Load area + .set MEM_BTX,0x9000 # BTX start + .set MEM_JMP,0x9010 # BTX entry point + .set MEM_USR,0xa000 # Client start + .set BDA_BOOT,0x472 # Boot howto flag + +# Partition Constants + .set PRT_OFF,0x1be # Partition offset + .set PRT_NUM,0x4 # Partitions + .set PRT_UBX,0x2A # Partition type + +# Flag Bits + .set FL_PACKET,0x80 # Packet mode + +# Misc. Constants + .set SIZ_PAG,0x1000 # Page size + .set SIZ_SEC,0x200 # Sector size + + .globl start + .globl xread + .code16 + +start: jmp main # Start recognizably + +# This is the start of a standard BIOS Parameter Block (BPB). Most bootable +# FAT disks have this at the start of their MBR. While normal BIOS's will +# work fine without this section, IBM's El Torito emulation "fixes" up the +# BPB by writing into the memory copy of the MBR. Rather than have data +# written into our xread routine, we'll define a BPB to work around it. +# The data marked with (T) indicates a field required for a ThinkPad to +# recognize the disk and (W) indicates fields written from IBM BIOS code. +# The use of the BPB is based on what OpenBSD and NetBSD implemented in +# their boot code but the required fields were determined by trial and error. +# +# Note: If additional space is needed in boot1, one solution would be to +# move the "prompt" message data (below) to replace the OEM ID. + + .org 0x03, 0x00 +oemid: .space 0x08, 0x00 # OEM ID + + .org 0x0b, 0x00 +bpb: .word 512 # sector size (T) + .byte 0 # sectors/clustor + .word 0 # reserved sectors + .byte 0 # number of FATs + .word 0 # root entries + .word 0 # small sectors + .byte 0 # media type (W) + .word 0 # sectors/fat + .word 18 # sectors per track (T) + .word 2 # number of heads (T) + .long 0 # hidden sectors (W) + .long 0 # large sectors + + .org 0x24, 0x00 +ebpb: .byte 0 # BIOS physical drive number (W) + + .org 0x25,0x90 +# +# Trampoline used by boot2 to call read to read data from the disk via +# the BIOS. Call with: +# +# %cx:%ax - long - LBA to read in +# %es:(%bx) - caddr_t - buffer to read data into +# %dl - byte - drive to read from +# %dh - byte - num sectors to read +# + +xread: push %ss # Address + pop %ds # data +# +# Setup an EDD disk packet and pass it to read +# +xread.1: # Starting + pushl $0x0 # absolute + push %cx # block + push %ax # number + push %es # Address of + push %bx # transfer buffer + xor %ax,%ax # Number of + movb %dh,%al # blocks to + push %ax # transfer + push $0x10 # Size of packet + mov %sp,%bp # Packet pointer + callw read # Read from disk + lea 0x10(%bp),%sp # Clear stack + lret # To far caller +# +# Load the rest of boot2 and BTX up, copy the parts to the right locations, +# and start it all up. +# + +# +# Setup the segment registers to flat addressing (segment 0) and setup the +# stack to end just below the start of our code. +# +main: +#mov $0x4f02,%ax +#mov $0x4103,%bx +#int $0x10 + cld # String ops inc + xor %cx,%cx # Zero + mov %cx,%es # Address + mov %cx,%ds # data + mov %cx,%ss # Set up + mov $start,%sp # stack +# +# Relocate ourself to MEM_REL. Since %cx == 0, the inc %ch sets +# %cx == 0x100. +# + mov %sp,%si # Source + mov $MEM_REL,%di # Destination + incb %ch # Word count + rep # Copy + movsw # code +# +# If we are on a hard drive, then load the MBR and look for the first +# UbixOS slice. We use the fake partition entry below that points to +# the MBR when we call nread. The first pass looks for the first active +# UbixOS slice. The second pass looks for the first non-active UbixOS +# slice if the first one fails. +# + mov $part4,%si # Partition + cmpb $0x80,%dl # Hard drive? + jb main.4 # No + movb $0x1,%dh # Block count + callw nread # Read MBR + mov $0x1,%cx # Two passes +main.1: mov $MEM_BUF+PRT_OFF,%si # Partition table + movb $0x1,%dh # Partition +main.2: cmpb $PRT_UBX,0x4(%si) # Our partition type? + jne main.3 # No + jcxz main.5 # If second pass + testb $0x80,(%si) # Active? + jnz main.5 # Yes +main.3: add $0x10,%si # Next entry + incb %dh # Partition + cmpb $0x1+PRT_NUM,%dh # In table? + jb main.2 # Yes + dec %cx # Do two + jcxz main.1 # passes +# +# If we get here, we didn't find any UbixOS slices at all, so print an +# error message and die. +# +#Ubu mov $msg_part,%si # Message + jmp error # Error +# +# Floppies use partition 0 of drive 0. +# +main.4: xor %dx,%dx # Partition:drive +# +# Ok, we have a slice and drive in %dx now, so use that to locate and load +# boot2. %si references the start of the slice we are looking for, so go +# ahead and load up the first 16 sectors (boot1 + boot2) from that. When +# we read it in, we conveniently use 0x8c00 as our transfer buffer. Thus, +# boot1 ends up at 0x8c00, and boot2 starts at 0x8c00 + 0x200 = 0x8e00. +# The first part of boot2 is the disklabel, which is 0x200 bytes long. +# The second part is BTX, which is thus loaded into 0x9000, which is where +# it also runs from. The boot2.bin binary starts right after the end of +# BTX, so we have to figure out where the start of it is and then move the +# binary to 0xb000. Normally, BTX clients start at MEM_USR, or 0xa000, but +# when we use btxld create boot2, we use an entry point of 0x1000. That +# entry point is relative to MEM_USR; thus boot2.bin starts at 0xb000. +# +main.5: mov %dx,MEM_ARG # Save args + movb $0x10,%dh # Sector count + callw nread # Read disk + mov $MEM_BTX,%bx # BTX + mov 0xa(%bx),%si # Get BTX length and set + add %bx,%si # %si to start of boot2.bin + mov $MEM_USR+SIZ_PAG,%di # Client page 1 + mov $MEM_BTX+0xe*SIZ_SEC,%cx # Byte + sub %si,%cx # count + rep # Relocate + movsb # client + sub %di,%cx # Byte count + xorb %al,%al # Zero assumed bss from + rep # the end of boot2.bin + stosb # up to 0x10000 + callw seta20 # Enable A20 + jmp start+MEM_JMP-MEM_ORG # Start BTX +# +# Enable A20 so we can access memory above 1 meg. +# +seta20: cli # Disable interrupts +seta20.1: inb $0x64,%al # Get status + testb $0x2,%al # Busy? + jnz seta20.1 # Yes + movb $0xd1,%al # Command: Write + outb %al,$0x64 # output port +seta20.2: inb $0x64,%al # Get status + testb $0x2,%al # Busy? + jnz seta20.2 # Yes + movb $0xdf,%al # Enable + outb %al,$0x60 # A20 + sti # Enable interrupts + retw # To caller +# +# Trampoline used to call read from within boot1. +# +nread: mov $MEM_BUF,%bx # Transfer buffer + mov 0x8(%si),%ax # Get + mov 0xa(%si),%cx # LBA + push %cs # Read from + callw xread.1 # disk + jnc return # If success, return + mov $msg_read,%si # Otherwise, set the error + # message and fall through to + # the error routine +# +# Print out the error message pointed to by %ds:(%si) followed +# by a prompt, wait for a keypress, and then reboot the machine. +# +error: callw putstr # Display message +# UBU mov $prompt,%si # Display + callw putstr # prompt + xorb %ah,%ah # BIOS: Get + int $0x16 # keypress + movw $0x1234, BDA_BOOT # Do a warm boot + ljmp $0xffff,$0x0 # reboot the machine +# +# Display a null-terminated string using the BIOS output. +# +putstr.0: mov $0x7,%bx # Page:attribute + movb $0xe,%ah # BIOS: Display + int $0x10 # character +putstr: lodsb # Get char + testb %al,%al # End of string? + jne putstr.0 # No + +# +# Overused return code. ereturn is used to return an error from the +# read function. Since we assume putstr succeeds, we (ab)use the +# same code when we return from putstr. +# +ereturn: movb $0x1,%ah # Invalid + stc # argument +return: retw # To caller +# +# Reads sectors from the disk. If EDD is enabled, then check if it is +# installed and use it if it is. If it is not installed or not enabled, then +# fall back to using CHS. Since we use a LBA, if we are using CHS, we have to +# fetch the drive parameters from the BIOS and divide it out ourselves. +# Call with: +# +# %dl - byte - drive number +# stack - 10 bytes - EDD Packet +# +read: push %dx # Save + movb $0x8,%ah # BIOS: Get drive + int $0x13 # parameters + movb %dh,%ch # Max head number + pop %dx # Restore + jc return # If error + andb $0x3f,%cl # Sectors per track + jz ereturn # If zero + cli # Disable interrupts + mov 0x8(%bp),%eax # Get LBA + push %dx # Save + movzbl %cl,%ebx # Divide by + xor %edx,%edx # sectors + div %ebx # per track + movb %ch,%bl # Max head number + movb %dl,%ch # Sector number + inc %bx # Divide by + xorb %dl,%dl # number + div %ebx # of heads + movb %dl,%bh # Head number + pop %dx # Restore + cmpl $0x3ff,%eax # Cylinder number supportable? + sti # Enable interrupts + ja read.7 # No, try EDD + xchgb %al,%ah # Set up cylinder + rorb $0x2,%al # number + orb %ch,%al # Merge + inc %ax # sector + xchg %ax,%cx # number + movb %bh,%dh # Head number + subb %ah,%al # Sectors this track + mov 0x2(%bp),%ah # Blocks to read + cmpb %ah,%al # To read + jb read.2 # this + movb %ah,%al # track +read.2: mov $0x5,%di # Try count +read.3: les 0x4(%bp),%bx # Transfer buffer + push %ax # Save + movb $0x2,%ah # BIOS: Read + int $0x13 # from disk + pop %bx # Restore + jnc read.4 # If success + dec %di # Retry? + jz read.6 # No + xorb %ah,%ah # BIOS: Reset + int $0x13 # disk system + xchg %bx,%ax # Block count + jmp read.3 # Continue +read.4: movzbw %bl,%ax # Sectors read + add %ax,0x8(%bp) # Adjust + jnc read.5 # LBA, + incw 0xa(%bp) # transfer +read.5: shlb %bl # buffer + add %bl,0x5(%bp) # pointer, + sub %al,0x2(%bp) # block count + ja read # If not done +read.6: retw # To caller +read.7: testb $FL_PACKET,%cs:MEM_REL+flags-start # LBA support enabled? + jz ereturn # No, so return an error + mov $0xbeba,%bx # Magic + push %dx # Save + movb $0x41,%ah # BIOS: Check + int $0x13 # extensions present + pop %dx # Restore + jc return # If error, return an error + cmp $0xbabe,%bx # Magic? + jne ereturn # No, so return an error + testb $0x1,%cl # Packet interface? + jz ereturn # No, so return an error + mov %bp,%si # Disk packet + movb $0x42,%ah # BIOS: Extended + int $0x13 # read + retw # To caller + +# Messages + +msg_read: .asciz "Read" +msg_part: .asciz "Boot" + +prompt: .asciz " error\r\n" + +flags: .byte FLAGS # Flags + + .org PRT_OFF,0x90 + +# Partition table + + .fill 0x30,0x1,0x0 +part4: .byte 0x80, 0x00, 0x01, 0x00 + .byte 0x2A, 0xff, 0xff, 0xff + .byte 0x00, 0x00, 0x00, 0x00 + .byte 0x50, 0xc3, 0x00, 0x00 # 50000 sectors long, bleh + + .word 0xbabe # Magic number diff --git a/src/sys/boot/boot2/boot2.c b/src/sys/boot/boot2/boot2.c new file mode 100644 index 0000000..e3a97d9 --- /dev/null +++ b/src/sys/boot/boot2/boot2.c @@ -0,0 +1,833 @@ +/* + * Copyright (c) 1998 Robert Nordier + * All rights reserved. + * + * Redistribution and use in source and binary forms are freely + * permitted provided that the above copyright notice and this + * paragraph and the following disclaimer are duplicated in all + * such forms. + * + * This software is provided "AS IS" and without any express or + * implied warranties, including, without limitation, the implied + * warranties of merchantability and fitness for a particular + * purpose. + */ + +/* + * $ID: src/sys/boot/i386/boot2/boot2.c,v 1.28.2.6 2002/03/31 18:12:50 pb Exp $ + */ + + +#include +#include +#include "diskslice.h" +#include "disklabel.h" +#include +#include +#include + +#include + +#include + +#include + +#include "boot2.h" +#include "lib.h" +#include "ubixfs.h" + +#define RBX_ASKNAME 0x0 /* -a */ +#define RBX_SINGLE 0x1 /* -s */ +#define RBX_DFLTROOT 0x5 /* -r */ +#define RBX_KDB 0x6 /* -d */ +#define RBX_CONFIG 0xa /* -c */ +#define RBX_VERBOSE 0xb /* -v */ +#define RBX_SERIAL 0xc /* -h */ +#define RBX_CDROM 0xd /* -C */ +#define RBX_GDB 0xf /* -g */ +#define RBX_DUAL 0x1d /* -D */ +#define RBX_PROBEKBD 0x1e /* -P */ +#define RBX_NOINTR 0x1f /* -n */ + +#define RBX_MASK 0xffff + +#define PATH_CONFIG "/boot.config" +#define PATH_BOOT3 "/ubix.elf" +#define PATH_KERNEL "/ubix.elf" + +#define ARGS 0x900 +#define NOPT 12 +#define BSIZEMAX 16384 +#define NDEV 5 +#define MEM_BASE 0x12 +#define MEM_EXT 0x15 +#define V86_CY(x) ((x) & 1) +#define V86_ZR(x) ((x) & 0x40) + +#define DRV_HARD 0x80 +#define DRV_MASK 0x7f + +#define TYPE_AD 0 +#define TYPE_WD 1 +#define TYPE_WFD 2 +#define TYPE_FD 3 +#define TYPE_DA 4 + +extern uint32_t _end; + +struct blockAllocationTableEntry *BAT = 0x0; +struct directoryEntry *rootDir = 0x0; + +static const char optstr[NOPT] = "DhaCcdgnPrsv"; +static const unsigned char flags[NOPT] = { + RBX_DUAL, + RBX_SERIAL, + RBX_ASKNAME, + RBX_CDROM, + RBX_CONFIG, + RBX_KDB, + RBX_GDB, + RBX_NOINTR, + RBX_PROBEKBD, + RBX_DFLTROOT, + RBX_SINGLE, + RBX_VERBOSE +}; + +static const char *const dev_nm[] = {"ad", "wd", " ", "fd", "da"}; +static const unsigned dev_maj[] = {30, 0, 1, 2, 4}; + +static struct dsk { + unsigned drive; + unsigned type; + unsigned unit; + unsigned slice; + unsigned part; + unsigned start; + int init; + int meta; +} dsk; +static char cmd[512]; +static char kname[1024]; +static uint32_t opts; +static struct bootinfo bootinfo; +static int ls; +static uint32_t fs_off; +static uint8_t ioctrl = 0x1; + +void exit(int); +static void load(const char *); +static int parse(char *); +static int xfsread(const char *, void *, size_t); +static ssize_t fsread(const char *, void *, size_t); +static int dskread(void *, unsigned, unsigned); +static int printf(const char *,...); +static int putchar(int); +static void *memcpy(void *, const void *, size_t); +static void *malloc(size_t); +static uint32_t memsize(int); +static int drvread(void *, unsigned, unsigned); +static int keyhit(unsigned); +static int xputc(int); +static int xgetc(int); +static int getc(int); + +/* My Functions */ +static void initUbixFS(void); + +static inline void readfile(const char *fname, void *buf, size_t size) { + fs_off = 0; + fsread(fname,buf,size); + } + +static inline int +strcmp(const char *s1, const char *s2) +{ + for (; *s1 == *s2 && *s1; s1++, s2++); + return (u_char)*s1 - (u_char)*s2; +} + +static inline int +fsfind(const char *name, ino_t * ino) +{ + char buf[DEV_BSIZE]; + struct dirent *d; + char *s; + ssize_t n; + fs_off = 0; + while ((n = fsread(name, buf, DEV_BSIZE)) > 0) + for (s = buf; s < buf + DEV_BSIZE;) { + d = (void *)s; + if (ls) + printf("%s ", d->d_name); + else if (!strcmp(name, d->d_name)) { + *ino = d->d_fileno; + return d->d_type; + } + s += d->d_reclen; + } + if (n != -1 && ls) + putchar('\n'); + return 0; +} + +static inline int +getchar(void) +{ + int c; + + c = xgetc(0); + if (c == '\r') + c = '\n'; + return c; +} + +static inline void +getstr(char *str, int size) +{ + char *s; + int c; + + s = str; + do { + switch (c = getchar()) { + case 0: + break; + case '\b': + case '\177': + if (s > str) { + s--; + putchar('\b'); + putchar(' '); + } else + c = 0; + break; + case '\n': + *s = 0; + break; + default: + if (s - str < size - 1) + *s++ = c; + } + if (c) + putchar(c); + } while (c != '\n'); +} + +static inline uint32_t +drvinfo(int drive) +{ + v86.addr = 0x13; + v86.eax = 0x800; + v86.edx = DRV_HARD + drive; + v86int(); + if (V86_CY(v86.efl)) + return 0x4f010f; + return ((v86.ecx & 0xc0) << 18) | ((v86.ecx & 0xff00) << 8) | + (v86.edx & 0xff00) | (v86.ecx & 0x3f); +} + +static inline void +putc(int c) +{ + v86.addr = 0x10; + v86.eax = 0xe00 | (c & 0xff); + v86.ebx = 0x7; + v86int(); +} + +static void initUbixFS() { + BAT = (struct blockAllocationTableEntry *)malloc(4096); + rootDir = (struct directoryEntry *)malloc(4096); + dskread(BAT,0,8); + dskread(rootDir,8,8); + } + +int +main(void) +{ + int autoboot, i; + + v86.ctl = V86_FLAGS; + dsk.drive = *(uint8_t *)PTOV(ARGS); + dsk.type = dsk.drive & DRV_HARD ? TYPE_AD : TYPE_FD; + dsk.unit = dsk.drive & DRV_MASK; + dsk.slice = *(uint8_t *)PTOV(ARGS + 1) + 1; + bootinfo.bi_version = BOOTINFO_VERSION; + bootinfo.bi_size = sizeof(bootinfo); + bootinfo.bi_basemem = memsize(MEM_BASE); + bootinfo.bi_extmem = memsize(MEM_EXT); + bootinfo.bi_memsizes_valid++; + for (i = 0; i < N_BIOS_GEOM; i++) + bootinfo.bi_bios_geom[i] = drvinfo(i); + autoboot = 2; + + /* Initialize UbixFS */ + initUbixFS(); + + readfile(PATH_CONFIG, cmd, sizeof(cmd)); + if (*cmd) { + printf("%s: %s", PATH_CONFIG, cmd); + if (parse(cmd)) + autoboot = 0; + *cmd = 0; + } + if (autoboot && !*kname) { + if (autoboot == 2) { + memcpy(kname, PATH_BOOT3, sizeof(PATH_BOOT3)); + if (!keyhit(0x37)) { + load(kname); + autoboot = 1; + } + } + if (autoboot == 1) + memcpy(kname, PATH_KERNEL, sizeof(PATH_KERNEL)); + } + for (;;) { + printf(" \n>> UbixOS/i386 uBoot\n" + "Default: %u:%s(%u,%c)%s\n" + "boot: ", + dsk.drive & DRV_MASK, dev_nm[dsk.type], dsk.unit, + 'a' + dsk.part, kname); + if (ioctrl & 0x2) + sio_flush(); + if (!autoboot || keyhit(0x5a)) + getstr(cmd, sizeof(cmd)); + else + putchar('\n'); + autoboot = 0; + if (parse(cmd)) + putchar('\a'); + else + load(kname); + } +} + +/* XXX - Needed for btxld to link the boot2 binary; do not remove. */ +void +exit(int x) +{ +} + +static void +load(const char *fname) +{ + union { + struct exec ex; + Elf32_Ehdr eh; + } hdr; + Elf32_Phdr ep[2]; + Elf32_Shdr es[2]; + caddr_t p; + uint32_t addr, x; + int fmt, i, j; + fs_off = 0; + if (xfsread(fname, &hdr, sizeof(hdr))) + return; + if (N_GETMAGIC(hdr.ex) == ZMAGIC) + fmt = 0; + else if (IS_ELF(hdr.eh)) + fmt = 1; + else { + printf("Invalid %s\n", "format"); + return; + } + if (fmt == 0) { + addr = hdr.ex.a_entry & 0xffffff; + p = PTOV(addr); + fs_off = PAGE_SIZE; + if (xfsread(fname, p, hdr.ex.a_text)) + return; + p += roundup2(hdr.ex.a_text, PAGE_SIZE); + if (xfsread(fname, p, hdr.ex.a_data)) + return; + p += hdr.ex.a_data + roundup2(hdr.ex.a_bss, PAGE_SIZE); + bootinfo.bi_symtab = VTOP(p); + memcpy(p, &hdr.ex.a_syms, sizeof(hdr.ex.a_syms)); + p += sizeof(hdr.ex.a_syms); + if (hdr.ex.a_syms) { + if (xfsread(fname, p, hdr.ex.a_syms)) + return; + p += hdr.ex.a_syms; + if (xfsread(fname, p, sizeof(int))) + return; + x = *(uint32_t *)p; + p += sizeof(int); + x -= sizeof(int); + if (xfsread(fname, p, x)) + return; + p += x; + } + } else { + fs_off = hdr.eh.e_phoff; + for (j = i = 0; i < hdr.eh.e_phnum && j < 2; i++) { + if (xfsread(fname, ep + j, sizeof(ep[0]))) + return; + if (ep[j].p_type == PT_LOAD) + j++; + } + for (i = 0; i < 2; i++) { + p = PTOV(ep[i].p_paddr & 0xffffff); + fs_off = ep[i].p_offset; + if (xfsread(fname, p, ep[i].p_filesz)) + return; + } + p += roundup2(ep[1].p_memsz, PAGE_SIZE); + bootinfo.bi_symtab = VTOP(p); + if (hdr.eh.e_shnum == hdr.eh.e_shstrndx + 3) { + fs_off = hdr.eh.e_shoff + sizeof(es[0]) * + (hdr.eh.e_shstrndx + 1); + if (xfsread(fname, &es, sizeof(es))) + return; + for (i = 0; i < 2; i++) { + memcpy(p, &es[i].sh_size, sizeof(es[i].sh_size)); + p += sizeof(es[i].sh_size); + fs_off = es[i].sh_offset; + if (xfsread(fname, p, es[i].sh_size)) + return; + p += es[i].sh_size; + } + } + addr = hdr.eh.e_entry & 0xffffff; + } + bootinfo.bi_esymtab = VTOP(p); + bootinfo.bi_kernelname = VTOP(fname); + bootinfo.bi_bios_dev = dsk.drive; + __exec((caddr_t)addr, RB_BOOTINFO | (opts & RBX_MASK), + MAKEBOOTDEV(dev_maj[dsk.type], 0, dsk.slice, dsk.unit, dsk.part), + 0, 0, 0, VTOP(&bootinfo)); +} + +static int +parse(char *arg) +{ + char *p, *q; + int drv, c, i; + + while ((c = *arg++)) { + if (c == ' ' || c == '\t' || c == '\n') + continue; + for (p = arg; *p && *p != '\n' && *p != ' ' && *p != '\t'; p++); + if (*p) + *p++ = 0; + if (c == '-') { + while ((c = *arg++)) { + for (i = 0; c != optstr[i]; i++) + if (i == NOPT - 1) + return -1; + opts ^= 1 << flags[i]; + } + if (opts & 1 << RBX_PROBEKBD) { + i = *(uint8_t *)PTOV(0x496) & 0x10; + printf("Keyboard: %s\n", i ? "yes" : "no"); + if (!i) + opts |= 1 << RBX_DUAL | 1 << RBX_SERIAL; + opts &= ~(1 << RBX_PROBEKBD); + } + ioctrl = opts & 1 << RBX_DUAL ? 0x3 : + opts & 1 << RBX_SERIAL ? 0x2 : 0x1; + if (ioctrl & 0x2) + sio_init(); + } else { + for (q = arg--; *q && *q != '('; q++); + if (*q) { + drv = -1; + if (arg[1] == ':') { + if (*arg < '0' || *arg > '9') + return -1; + drv = *arg - '0'; + arg += 2; + } + if (q - arg != 2) + return -1; + for (i = 0; arg[0] != dev_nm[i][0] || + arg[1] != dev_nm[i][1]; i++) + if (i == NDEV - 1) + return -1; + dsk.type = i; + arg += 3; + if (arg[1] != ',' || *arg < '0' || *arg > '9') + return -1; + dsk.unit = *arg - '0'; + arg += 2; + dsk.slice = WHOLE_DISK_SLICE; + if (arg[1] == ',') { + if (*arg < '0' || *arg > '0' + NDOSPART) + return -1; + if ((dsk.slice = *arg - '0')) + dsk.slice++; + arg += 2; + } + if (arg[1] != ')' || *arg < 'a' || *arg > 'p') + return -1; + dsk.part = *arg - 'a'; + arg += 2; + if (drv == -1) + drv = dsk.unit; + dsk.drive = (dsk.type == TYPE_WD || + dsk.type == TYPE_AD || + dsk.type == TYPE_DA ? DRV_HARD : 0) + drv; + dsk.meta = 0; + fsread(0, NULL, 0); + } + if ((i = p - arg - !*(p - 1))) { + if (i >= sizeof(kname)) + return -1; + memcpy(kname, arg, i + 1); + } + } + arg = p; + } + return 0; +} + +static int +xfsread(const char *fname, void *buf, size_t nbyte) +{ + if (fsread(fname, buf, nbyte) != nbyte) { +/* printf("Invalid %s\n", "format"); */ + return -1; + } + return 0; +} + +/* FSREAD */ +static ssize_t fsread(const char *fname, void *buf, size_t nbyte) { + int i = 0x0,x = 0x0,block = 0x0,bOffset = 0x0,offset = 0x0,lb = -1; + int fBlock = -1; + char *buffer = 0x0; + char *buffer2 = 0x0; + struct directoryEntry *tmpDir = 0x0; + tmpDir = rootDir; + if (*fname == '/') { fname++; } + for (i=0;i<=(4096/sizeof(struct directoryEntry));i++) { + if (!strcmp(tmpDir[i].fileName,fname)) { + fBlock = tmpDir[i].startCluster; + break; + } + } + if (fBlock == -1) { + nbyte = 0; + return(nbyte); + } + buffer = malloc(4096); + buffer2 = buf; + offset = fs_off; + if (offset < 0) { + printf("Error!!!\n"); + offset = 0; + } + for (i=0;i> DEV_BSHIFT; + dsk.meta++; + } + if (!inode) + return 0; + if (inomap != inode) { + if (dskread(blkbuf, fsbtodb(&fs, ino_to_fsba(&fs, inode)), + fsblks)) + return -1; + din = ((struct dinode *)blkbuf)[inode % INOPB(&fs)]; + inomap = inode; + fs_off = 0; + blkmap = indmap = 0; + } + s = buf; + if (nbyte > (n = din.di_size - fs_off)) + nbyte = n; + nb = nbyte; + while (nb) { + lbn = lblkno(&fs, fs_off); + if (lbn < NDADDR) + addr = din.di_db[lbn]; + else { + if (indmap != din.di_ib[0]) { + if (!indbuf) + indbuf = malloc(BSIZEMAX); + if (dskread(indbuf, fsbtodb(&fs, din.di_ib[0]), + fsblks)) + return -1; + indmap = din.di_ib[0]; + } + addr = indbuf[(lbn - NDADDR) % NINDIR(&fs)]; + } + n = dblksize(&fs, &din, lbn); + if (blkmap != addr) { + if (dskread(blkbuf, fsbtodb(&fs, addr), n >> DEV_BSHIFT)) + return -1; + blkmap = addr; + } + off = blkoff(&fs, fs_off); + n -= off; + if (n > nb) + n = nb; + memcpy(s, blkbuf + off, n); + s += n; + fs_off += n; + nb -= n; + } + return nbyte; +} +*/ + +static int +dskread(void *buf, unsigned lba, unsigned nblk) +{ + static char *sec; + struct dos_partition *dp; + struct ubixDiskLabel *d; + unsigned sl, i; + + if (!dsk.meta) { + if (!sec) + sec = malloc(DEV_BSIZE); + dsk.start = 0; + if (drvread(sec, DOSBBSECTOR, 1)) + return -1; + dp = (void *)(sec + DOSPARTOFF); + sl = dsk.slice; + if (sl < BASE_SLICE) { + for (i = 0; i < NDOSPART; i++) + if (dp[i].dp_typ == DOSPTYP_UBX && + (dp[i].dp_flag & 0x80 || sl < BASE_SLICE)) { + sl = BASE_SLICE + i; + if (dp[i].dp_flag & 0x80 || + dsk.slice == COMPATIBILITY_SLICE) + break; + } + if (dsk.slice == WHOLE_DISK_SLICE) + dsk.slice = sl; + } + if (sl != WHOLE_DISK_SLICE) { + if (sl != COMPATIBILITY_SLICE) + dp += sl - BASE_SLICE; + if (dp->dp_typ != DOSPTYP_UBX) { + printf("Invalid %s\n", "slice"); + return -1; + } + dsk.start = dp->dp_start; + } + if (drvread(sec, dsk.start + LABELSECTOR, 1)) + return -1; + d = (void *)(sec + LABELOFFSET); + if (d->magicNum != UBIXDISKMAGIC || d->magicNum2 != UBIXDISKMAGIC) { + if (dsk.part != RAW_PART) { + printf("Invalid %s\n", "label"); + return -1; + } + } else { + if (!dsk.init) { + if (d->driveType == DTYPE_SCSI) + dsk.type = TYPE_DA; + dsk.init++; + } + if (dsk.part >= d->numPartitions || + !d->partitions[dsk.part].p_size) { + printf("Invalid %s\n", "partition"); + return -1; + } + dsk.start = d->partitions[dsk.part].p_offset; + } + } + return drvread(buf, dsk.start + lba, nblk); +} + +static int +printf(const char *fmt,...) +{ + static const char digits[16] = "0123456789abcdef"; + va_list ap; + char buf[10]; + char *s; + unsigned r, u; + int c; + + va_start(ap, fmt); + while ((c = *fmt++)) { + if (c == '%') { + c = *fmt++; + switch (c) { + case 'c': + putchar(va_arg(ap, int)); + continue; + case 's': + for (s = va_arg(ap, char *); *s; s++) + putchar(*s); + continue; + case 'u': + case 'x': + r = c == 'u' ? 10U : 16U; + u = va_arg(ap, unsigned); + s = buf; + do + *s++ = digits[u % r]; + while (u /= r); + while (--s >= buf) + putchar(*s); + continue; + } + } + putchar(c); + } + va_end(ap); + return 0; +} + +static int +putchar(int c) +{ + if (c == '\n') + xputc('\r'); + return xputc(c); +} + +static void * +memcpy(void *dst, const void *src, size_t size) +{ + const char *s; + char *d; + + for (d = dst, s = src; size; size--) + *d++ = *s++; + return dst; +} + +static void * +malloc(size_t size) +{ + static uint32_t next; + void *p; + + if (!next) + next = roundup2(__base + _end, 0x10000) - __base; + p = (void *)next; + next += size; + return p; +} + +static uint32_t +memsize(int type) +{ + v86.addr = type; + v86.eax = 0x8800; + v86int(); + return v86.eax; +} + +static int +drvread(void *buf, unsigned lba, unsigned nblk) +{ + static unsigned c = 0x2d5c7c2f; + + printf("%c\b", c = c << 8 | c >> 24); + v86.ctl = V86_ADDR | V86_CALLF | V86_FLAGS; + v86.addr = XREADORG; /* call to xread in boot1 */ + v86.es = VTOPSEG(buf); + v86.eax = lba; + v86.ebx = VTOPOFF(buf); + v86.ecx = lba >> 16; + v86.edx = nblk << 8 | dsk.drive; + v86int(); + v86.ctl = V86_FLAGS; + if (V86_CY(v86.efl)) { + printf("Disk error 0x%x (lba=0x%x)\n", v86.eax >> 8 & 0xff, + lba); + return -1; + } + return 0; +} + +static int +keyhit(unsigned ticks) +{ + uint32_t t0, t1; + + if (opts & 1 << RBX_NOINTR) + return 0; + t0 = 0; + for (;;) { + if (xgetc(1)) + return 1; + t1 = *(uint32_t *)PTOV(0x46c); + if (!t0) + t0 = t1; + if (t1 < t0 || t1 >= t0 + ticks) + return 0; + } +} + +static int +xputc(int c) +{ + if (ioctrl & 0x1) + putc(c); + if (ioctrl & 0x2) + sio_putc(c); + return c; +} + +static int +xgetc(int fn) +{ + if (opts & 1 << RBX_NOINTR) + return 0; + for (;;) { + if (ioctrl & 0x1 && getc(1)) + return fn ? 1 : getc(0); + if (ioctrl & 0x2 && sio_ischar()) + return fn ? 1 : sio_getc(); + if (fn) + return 0; + } +} + +static int +getc(int fn) +{ + v86.addr = 0x16; + v86.eax = fn << 8; + v86int(); + return fn == 0 ? v86.eax & 0xff : !V86_ZR(v86.efl); +} diff --git a/src/sys/boot/boot2/disklabel.h b/src/sys/boot/boot2/disklabel.h new file mode 100644 index 0000000..b646693 --- /dev/null +++ b/src/sys/boot/boot2/disklabel.h @@ -0,0 +1,489 @@ +/* + * Copyright (c) 1987, 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. + * + * @(#)disklabel.h 8.2 (Berkeley) 7/10/94 + * $FreeBSD: src/sys/sys/disklabel.h,v 1.49.2.7 2001/05/27 05:58:26 jkh Exp $ + */ + +#ifndef _SYS_DISKLABEL_H_ +#define _SYS_DISKLABEL_H_ + +#ifndef _KERNEL +#include +#endif +#include + +/* + * Disk description table, see disktab(5) + */ +#define _PATH_DISKTAB "/etc/disktab" +#define DISKTAB "/etc/disktab" /* deprecated */ + +/* + * Each disk has a label which includes information about the hardware + * disk geometry, filesystem partitions, and drive specific information. + * The label is in block 0 or 1, possibly offset from the beginning + * to leave room for a bootstrap, etc. + */ + +/* XXX these should be defined per controller (or drive) elsewhere, not here! */ +#ifdef __i386__ +#define LABELSECTOR 1 /* sector containing label */ +#define LABELOFFSET 0 /* offset of label in sector */ +#endif + +#ifdef __alpha__ +#define LABELSECTOR 0 +#define LABELOFFSET 64 +#endif + +#ifndef LABELSECTOR +#define LABELSECTOR 0 /* sector containing label */ +#endif + +#ifndef LABELOFFSET +#define LABELOFFSET 64 /* offset of label in sector */ +#endif + +#define DISKMAGIC ((u_int32_t)0x82564557) /* The disk magic number */ +#ifndef MAXPARTITIONS +#define MAXPARTITIONS 8 +#endif + +#define LABEL_PART 2 /* partition containing label */ +#define RAW_PART 2 /* partition containing whole disk */ +#define SWAP_PART 1 /* partition normally containing swap */ + +#ifndef LOCORE +struct disklabel { + u_int32_t d_magic; /* the magic number */ + u_int16_t d_type; /* drive type */ + u_int16_t d_subtype; /* controller/d_type specific */ + char d_typename[16]; /* type name, e.g. "eagle" */ + + /* + * d_packname contains the pack identifier and is returned when + * the disklabel is read off the disk or in-core copy. + * d_boot0 and d_boot1 are the (optional) names of the + * primary (block 0) and secondary (block 1-15) bootstraps + * as found in /boot. These are returned when using + * getdiskbyname(3) to retrieve the values from /etc/disktab. + */ + union { + char un_d_packname[16]; /* pack identifier */ + struct { + char *un_d_boot0; /* primary bootstrap name */ + char *un_d_boot1; /* secondary bootstrap name */ + } un_b; + } d_un; +#define d_packname d_un.un_d_packname +#define d_boot0 d_un.un_b.un_d_boot0 +#define d_boot1 d_un.un_b.un_d_boot1 + + /* disk geometry: */ + u_int32_t d_secsize; /* # of bytes per sector */ + u_int32_t d_nsectors; /* # of data sectors per track */ + u_int32_t d_ntracks; /* # of tracks per cylinder */ + u_int32_t d_ncylinders; /* # of data cylinders per unit */ + u_int32_t d_secpercyl; /* # of data sectors per cylinder */ + u_int32_t d_secperunit; /* # of data sectors per unit */ + + /* + * Spares (bad sector replacements) below are not counted in + * d_nsectors or d_secpercyl. Spare sectors are assumed to + * be physical sectors which occupy space at the end of each + * track and/or cylinder. + */ + u_int16_t d_sparespertrack; /* # of spare sectors per track */ + u_int16_t d_sparespercyl; /* # of spare sectors per cylinder */ + /* + * Alternate cylinders include maintenance, replacement, configuration + * description areas, etc. + */ + u_int32_t d_acylinders; /* # of alt. cylinders per unit */ + + /* hardware characteristics: */ + /* + * d_interleave, d_trackskew and d_cylskew describe perturbations + * in the media format used to compensate for a slow controller. + * Interleave is physical sector interleave, set up by the + * formatter or controller when formatting. When interleaving is + * in use, logically adjacent sectors are not physically + * contiguous, but instead are separated by some number of + * sectors. It is specified as the ratio of physical sectors + * traversed per logical sector. Thus an interleave of 1:1 + * implies contiguous layout, while 2:1 implies that logical + * sector 0 is separated by one sector from logical sector 1. + * d_trackskew is the offset of sector 0 on track N relative to + * sector 0 on track N-1 on the same cylinder. Finally, d_cylskew + * is the offset of sector 0 on cylinder N relative to sector 0 + * on cylinder N-1. + */ + u_int16_t d_rpm; /* rotational speed */ + u_int16_t d_interleave; /* hardware sector interleave */ + u_int16_t d_trackskew; /* sector 0 skew, per track */ + u_int16_t d_cylskew; /* sector 0 skew, per cylinder */ + u_int32_t d_headswitch; /* head switch time, usec */ + u_int32_t d_trkseek; /* track-to-track seek, usec */ + u_int32_t d_flags; /* generic flags */ +#define NDDATA 5 + u_int32_t d_drivedata[NDDATA]; /* drive-type specific information */ +#define NSPARE 5 + u_int32_t d_spare[NSPARE]; /* reserved for future use */ + u_int32_t d_magic2; /* the magic number (again) */ + u_int16_t d_checksum; /* xor of data incl. partitions */ + + /* filesystem and partition information: */ + u_int16_t d_npartitions; /* number of partitions in following */ + u_int32_t d_bbsize; /* size of boot area at sn0, bytes */ + u_int32_t d_sbsize; /* max size of fs superblock, bytes */ + struct partition { /* the partition table */ + u_int32_t p_size; /* number of sectors in partition */ + u_int32_t p_offset; /* starting sector */ + u_int32_t p_fsize; /* filesystem basic fragment size */ + u_int8_t p_fstype; /* filesystem type, see below */ + u_int8_t p_frag; /* filesystem fragments per block */ + union { + u_int16_t cpg; /* UFS: FS cylinders per group */ + u_int16_t sgs; /* LFS: FS segment shift */ + } __partition_u1; +#define p_cpg __partition_u1.cpg +#define p_sgs __partition_u1.sgs + } d_partitions[MAXPARTITIONS]; /* actually may be more */ +}; + +static u_int16_t dkcksum(struct disklabel *lp); + +static __inline u_int16_t +dkcksum(struct disklabel *lp) +{ + u_int16_t *start, *end; + u_int16_t sum = 0; + + start = (u_int16_t *)lp; + end = (u_int16_t *)&lp->d_partitions[lp->d_npartitions]; + while (start < end) + sum ^= *start++; + return (sum); +} + +#else /* LOCORE */ + /* + * offsets for asm boot files. + */ + .set d_secsize,40 + .set d_nsectors,44 + .set d_ntracks,48 + .set d_ncylinders,52 + .set d_secpercyl,56 + .set d_secperunit,60 + .set d_end_,276 /* size of disk label */ +#endif /* LOCORE */ + +/* d_type values: */ +#define DTYPE_SMD 1 /* SMD, XSMD; VAX hp/up */ +#define DTYPE_MSCP 2 /* MSCP */ +#define DTYPE_DEC 3 /* other DEC (rk, rl) */ +#define DTYPE_SCSI 4 /* SCSI */ +#define DTYPE_ESDI 5 /* ESDI interface */ +#define DTYPE_ST506 6 /* ST506 etc. */ +#define DTYPE_HPIB 7 /* CS/80 on HP-IB */ +#define DTYPE_HPFL 8 /* HP Fiber-link */ +#define DTYPE_FLOPPY 10 /* floppy */ +#define DTYPE_CCD 11 /* concatenated disk */ +#define DTYPE_VINUM 12 /* vinum volume */ +#define DTYPE_DOC2K 13 /* Msys DiskOnChip */ + +#if defined(PC98) && !defined(PC98_ATCOMPAT) +#define DSTYPE_SEC256 0x80 /* physical sector size=256 */ +#endif + +#ifdef DKTYPENAMES +static char *dktypenames[] = { + "unknown", + "SMD", + "MSCP", + "old DEC", + "SCSI", + "ESDI", + "ST506", + "HP-IB", + "HP-FL", + "type 9", + "floppy", + "CCD", + "Vinum", + "DOC2K", + NULL +}; +#define DKMAXTYPES (sizeof(dktypenames) / sizeof(dktypenames[0]) - 1) +#endif + +/* + * Filesystem type and version. + * Used to interpret other filesystem-specific + * per-partition information. + */ +#define FS_UNUSED 0 /* unused */ +#define FS_SWAP 1 /* swap */ +#define FS_V6 2 /* Sixth Edition */ +#define FS_V7 3 /* Seventh Edition */ +#define FS_SYSV 4 /* System V */ +#define FS_V71K 5 /* V7 with 1K blocks (4.1, 2.9) */ +#define FS_V8 6 /* Eighth Edition, 4K blocks */ +#define FS_BSDFFS 7 /* 4.2BSD fast file system */ +#define FS_MSDOS 8 /* MSDOS file system */ +#define FS_BSDLFS 9 /* 4.4BSD log-structured file system */ +#define FS_OTHER 10 /* in use, but unknown/unsupported */ +#define FS_HPFS 11 /* OS/2 high-performance file system */ +#define FS_ISO9660 12 /* ISO 9660, normally CD-ROM */ +#define FS_BOOT 13 /* partition contains bootstrap */ +#define FS_VINUM 14 /* Vinum drive */ + +#ifdef DKTYPENAMES +static char *fstypenames[] = { + "unused", + "swap", + "Version 6", + "Version 7", + "System V", + "4.1BSD", + "Eighth Edition", + "4.2BSD", + "MSDOS", + "4.4LFS", + "unknown", + "HPFS", + "ISO9660", + "boot", + "vinum", + NULL +}; +#define FSMAXTYPES (sizeof(fstypenames) / sizeof(fstypenames[0]) - 1) +#endif + +/* + * flags shared by various drives: + */ +#define D_REMOVABLE 0x01 /* removable media */ +#define D_ECC 0x02 /* supports ECC */ +#define D_BADSECT 0x04 /* supports bad sector forw. */ +#define D_RAMDISK 0x08 /* disk emulator */ +#define D_CHAIN 0x10 /* can do back-back transfers */ + +/* + * Drive data for SMD. + */ +#define d_smdflags d_drivedata[0] +#define D_SSE 0x1 /* supports skip sectoring */ +#define d_mindist d_drivedata[1] +#define d_maxdist d_drivedata[2] +#define d_sdist d_drivedata[3] + +/* + * Drive data for ST506. + */ +#define d_precompcyl d_drivedata[0] +#define d_gap3 d_drivedata[1] /* used only when formatting */ + +/* + * Drive data for SCSI. + */ +#define d_blind d_drivedata[0] + +#ifndef LOCORE +/* + * Structure used to perform a format or other raw operation, returning + * data and/or register values. Register identification and format + * are device- and driver-dependent. + */ +struct format_op { + char *df_buf; + int df_count; /* value-result */ + daddr_t df_startblk; + int df_reg[8]; /* result */ +}; + +/* + * Structure used internally to retrieve information about a partition + * on a disk. + */ +struct partinfo { + struct disklabel *disklab; + struct partition *part; +}; + +/* DOS partition table -- located in boot block */ + +#if defined(PC98) && !defined(PC98_ATCOMPAT) +#define DOSBBSECTOR 0 /* DOS boot block relative sector number */ +#define DOSLABELSECTOR 1 /* 0: 256b/s, 1: 512b/s */ +#define DOSPARTOFF 0 +#define NDOSPART 16 +#define DOSPTYP_386BSD 0x94 /* 386BSD partition type */ +#define MBR_PTYPE_FreeBSD 0x94 /* FreeBSD partition type */ + +struct dos_partition { + unsigned char dp_mid; +#define DOSMID_386BSD (0x14|0x80) /* 386bsd|bootable */ + unsigned char dp_sid; +#define DOSSID_386BSD (0x44|0x80) /* 386bsd|active */ + unsigned char dp_dum1; + unsigned char dp_dum2; + unsigned char dp_ipl_sct; + unsigned char dp_ipl_head; + unsigned short dp_ipl_cyl; + unsigned char dp_ssect; /* starting sector */ + unsigned char dp_shd; /* starting head */ + unsigned short dp_scyl; /* starting cylinder */ + unsigned char dp_esect; /* end sector */ + unsigned char dp_ehd; /* end head */ + unsigned short dp_ecyl; /* end cylinder */ + unsigned char dp_name[16]; +}; + +#else /* IBMPC */ +#define DOSBBSECTOR 0 /* DOS boot block relative sector number */ +#define DOSPARTOFF 446 +#define NDOSPART 4 +#define DOSPTYP_386BSD 0xa5 /* 386BSD partition type */ +#define DOSPTYP_LINSWP 0x82 /* Linux swap partition */ +#define DOSPTYP_LINUX 0x83 /* Linux partition */ +#define DOSPTYP_EXT 5 /* DOS extended partition */ + +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_typ; /* partition type */ + unsigned char dp_ehd; /* end head */ + unsigned char dp_esect; /* end sector */ + unsigned char dp_ecyl; /* end cylinder */ + u_int32_t dp_start; /* absolute starting sector number */ + u_int32_t dp_size; /* partition size in sectors */ +}; +#endif + +#define DPSECT(s) ((s) & 0x3f) /* isolate relevant bits of sector */ +#define DPCYL(c, s) ((c) + (((s) & 0xc0)<<2)) /* and those that are cylinder */ + +/* + * Disk-specific ioctls. + */ + /* get and set disklabel; DIOCGPART used internally */ +#define DIOCGDINFO _IOR('d', 101, struct disklabel)/* get */ +#define DIOCSDINFO _IOW('d', 102, struct disklabel)/* set */ +#define DIOCWDINFO _IOW('d', 103, struct disklabel)/* set, update disk */ +#define DIOCGPART _IOW('d', 104, struct partinfo) /* get partition */ +#define DIOCGDVIRGIN _IOR('d', 105, struct disklabel) /* get virgin label */ + +#define DIOCWLABEL _IOW('d', 109, int) /* write en/disable label */ + +#ifdef _KERNEL + +/* + * XXX encoding of disk minor numbers, should be elsewhere. + * + * See for a possibly better encoding. + * + * "cpio -H newc" can be used to back up device files with large minor + * numbers (but not ones >= 2^31). Old cpio formats and all tar formats + * don't have enough bits, and cpio and tar don't notice the lossage. + * There are also some sign extension bugs. + */ + +/* + 3 2 1 0 + 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 + _________________________________________________________________ + | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | + ----------------------------------------------------------------- + | TYPE |UNIT_2 | SLICE | MAJOR? | UNIT |PART | + ----------------------------------------------------------------- +*/ + +#define DKMAXUNIT 0x1ff /* Highest disk unit number */ + +#define dkmakeminor(unit, slice, part) \ + (((slice) << 16) | (((unit) & 0x1e0) << 16) | \ + (((unit) & 0x1f) << 3) | (part)) +static __inline dev_t +dkmodpart(dev_t dev, int part) +{ + return (makedev(major(dev), (minor(dev) & ~7) | part)); +} + +static __inline dev_t +dkmodslice(dev_t dev, int slice) +{ + return (makedev(major(dev), (minor(dev) & ~0x1f0000) | (slice << 16))); +} + +#define dkpart(dev) (minor(dev) & 7) +#define dkslice(dev) ((minor(dev) >> 16) & 0x1f) +#define dktype(dev) ((minor(dev) >> 25) & 0x7f) + +static __inline u_int +dkunit(dev_t dev) +{ + return (((minor(dev) >> 16) & 0x1e0) | ((minor(dev) >> 3) & 0x1f)); +} + +struct buf; +struct buf_queue_head; + +int bounds_check_with_label __P((struct buf *bp, struct disklabel *lp, + int wlabel)); +void diskerr __P((struct buf *bp, char *what, int pri, int blkdone, + struct disklabel *lp)); +void disksort __P((struct buf *ap, struct buf *bp)); +char *readdisklabel __P((dev_t dev, struct disklabel *lp)); +void bufqdisksort __P((struct buf_queue_head *ap, struct buf *bp)); +int setdisklabel __P((struct disklabel *olp, struct disklabel *nlp, + u_long openmask)); +int writedisklabel __P((dev_t dev, struct disklabel *lp)); +#ifdef __alpha__ +void alpha_fix_srm_checksum __P((struct buf *bp)); +#endif + +#endif /* _KERNEL */ + +#endif /* LOCORE */ + +#ifndef _KERNEL +__BEGIN_DECLS +struct disklabel *getdiskbyname __P((const char *)); +__END_DECLS +#endif + +#endif /* !_SYS_DISKLABEL_H_ */ diff --git a/src/sys/boot/boot2/diskslice.h b/src/sys/boot/boot2/diskslice.h new file mode 100644 index 0000000..c5d50bb --- /dev/null +++ b/src/sys/boot/boot2/diskslice.h @@ -0,0 +1,107 @@ +/*- + * Copyright (c) 1994 Bruce D. 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, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must 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/sys/sys/diskslice.h,v 1.36.2.1 2001/01/29 01:50:50 ken Exp $ + */ + +#ifndef _SYS_DISKSLICE_H_ +#define _SYS_DISKSLICE_H_ + +#ifndef _KERNEL +#include +#endif +#include + +#define BASE_SLICE 2 +#define COMPATIBILITY_SLICE 0 +#define DIOCGSLICEINFO _IOR('d', 111, struct diskslices) +#define DIOCSYNCSLICEINFO _IOW('d', 112, int) +#define MAX_SLICES 32 +#define WHOLE_DISK_SLICE 1 + +struct diskslice { + u_long ds_offset; /* starting sector */ + u_long ds_size; /* number of sectors */ + int ds_type; /* (foreign) slice type */ +#ifdef PC98 + int ds_subtype; /* sub slice type */ + u_char ds_name[16]; /* slice name */ +#endif + struct disklabel *ds_label; /* BSD label, if any */ + void *ds_dev; /* devfs token for raw whole slice */ +#ifdef MAXPARTITIONS /* XXX don't depend on disklabel.h */ +#if MAXPARTITIONS != 8 /* but check consistency if possible */ +#error "inconsistent MAXPARTITIONS" +#endif +#else +#define MAXPARTITIONS 8 +#endif + void *ds_devs[MAXPARTITIONS]; /* XXX s.b. in label */ + u_char ds_openmask; /* devs open */ + u_char ds_wlabel; /* nonzero if label is writable */ +}; + +struct diskslices { + struct cdevsw *dss_cdevsw; /* for containing device */ + int dss_first_bsd_slice; /* COMPATIBILITY_SLICE is mapped here */ + u_int dss_nslices; /* actual dimension of dss_slices[] */ + u_int dss_oflags; /* copy of flags for "first" open */ + int dss_secmult; /* block to sector multiplier */ + int dss_secshift; /* block to sector shift (or -1) */ + int dss_secsize; /* sector size */ + struct diskslice + dss_slices[MAX_SLICES]; /* actually usually less */ +}; + +#ifdef _KERNEL + +/* Flags for dsopen(). */ +#define DSO_NOLABELS 1 +#define DSO_ONESLICE 2 +#define DSO_COMPATLABEL 4 + +#define dsgetlabel(dev, ssp) (ssp->dss_slices[dkslice(dev)].ds_label) + +struct buf; +struct disklabel; + +int dscheck __P((struct buf *bp, struct diskslices *ssp)); +void dsclose __P((dev_t dev, int mode, struct diskslices *ssp)); +void dsgone __P((struct diskslices **sspp)); +int dsinit __P((dev_t dev, struct disklabel *lp, + struct diskslices **sspp)); +int dsioctl __P((dev_t dev, u_long cmd, caddr_t data, + int flags, struct diskslices **sspp)); +int dsisopen __P((struct diskslices *ssp)); +struct diskslices *dsmakeslicestruct __P((int nslices, struct disklabel *lp)); +char *dsname __P((dev_t dev, int unit, int slice, int part, + char *partname)); +int dsopen __P((dev_t dev, int mode, u_int flags, + struct diskslices **sspp, struct disklabel *lp)); +int dssize __P((dev_t dev, struct diskslices **sspp)); + +#endif /* _KERNEL */ + +#endif /* !_SYS_DISKSLICE_H_ */ diff --git a/src/sys/boot/boot2/lib.h b/src/sys/boot/boot2/lib.h new file mode 100644 index 0000000..44d1f10 --- /dev/null +++ b/src/sys/boot/boot2/lib.h @@ -0,0 +1,24 @@ +/* + * Copyright (c) 1998 Robert Nordier + * All rights reserved. + * + * Redistribution and use in source and binary forms are freely + * permitted provided that the above copyright notice and this + * paragraph and the following disclaimer are duplicated in all + * such forms. + * + * This software is provided "AS IS" and without any express or + * implied warranties, including, without limitation, the implied + * warranties of merchantability and fitness for a particular + * purpose. + */ + +/* + * $FreeBSD: src/sys/boot/i386/boot2/lib.h,v 1.2 1999/08/28 00:40:02 peter Exp $ + */ + +void sio_init(void); +void sio_flush(void); +void sio_putc(int); +int sio_getc(void); +int sio_ischar(void); diff --git a/src/sys/boot/boot2/sio.s b/src/sys/boot/boot2/sio.s new file mode 100644 index 0000000..1e8da20 --- /dev/null +++ b/src/sys/boot/boot2/sio.s @@ -0,0 +1,80 @@ +# +# Copyright (c) 1998 Robert Nordier +# All rights reserved. +# +# Redistribution and use in source and binary forms are freely +# permitted provided that the above copyright notice and this +# paragraph and the following disclaimer are duplicated in all +# such forms. +# +# This software is provided "AS IS" and without any express or +# implied warranties, including, without limitation, the implied +# warranties of merchantability and fitness for a particular +# purpose. +# + +# $FreeBSD: src/sys/boot/i386/boot2/sio.s,v 1.4 1999/08/28 00:40:02 peter Exp $ + + .set SIO_PRT,SIOPRT # Base port + .set SIO_FMT,SIOFMT # 8N1 + .set SIO_DIV,(115200/SIOSPD) # 115200 / SPD + + .globl sio_init + .globl sio_flush + .globl sio_putc + .globl sio_getc + .globl sio_ischar + +# void sio_init(void) + +sio_init: movw $SIO_PRT+0x3,%dx # Data format reg + movb $SIO_FMT|0x80,%al # Set format + outb %al,(%dx) # and DLAB + pushl %edx # Save + subb $0x3,%dl # Divisor latch reg + movw $SIO_DIV,%ax # Set + outw %ax,(%dx) # BPS + popl %edx # Restore + movb $SIO_FMT,%al # Clear + outb %al,(%dx) # DLAB + incl %edx # Modem control reg + movb $0x3,%al # Set RTS, + outb %al,(%dx) # DTR + incl %edx # Line status reg + +# void sio_flush(void) + +sio_flush.0: call sio_getc.1 # Get character +sio_flush: call sio_ischar # Check for character + jnz sio_flush.0 # Till none + ret # To caller + +# void sio_putc(int c) + +sio_putc: movw $SIO_PRT+0x5,%dx # Line status reg + xor %ecx,%ecx # Timeout + movb $0x40,%ch # counter +sio_putc.1: inb (%dx),%al # Transmitter + testb $0x20,%al # buffer empty? + loopz sio_putc.1 # No + jz sio_putc.2 # If timeout + movb 0x4(%esp,1),%al # Get character + subb $0x5,%dl # Transmitter hold reg + outb %al,(%dx) # Write character +sio_putc.2: ret $0x4 # To caller + +# int sio_getc(void) + +sio_getc: call sio_ischar # Character available? + jz sio_getc # No +sio_getc.1: subb $0x5,%dl # Receiver buffer reg + inb (%dx),%al # Read character + ret # To caller + +# int sio_ischar(void) + +sio_ischar: movw $SIO_PRT+0x5,%dx # Line status register + xorl %eax,%eax # Zero + inb (%dx),%al # Received data + andb $0x1,%al # ready? + ret # To caller diff --git a/src/sys/boot/boot2/test.c b/src/sys/boot/boot2/test.c new file mode 100644 index 0000000..258a705 --- /dev/null +++ b/src/sys/boot/boot2/test.c @@ -0,0 +1,24 @@ +#include +#include + +#include "ubixfs.h" + +int main(int argc,char **argv) { + FILE *fd; + struct ubixDiskLabel *d = (struct ubixDiskLabel *)malloc(512); + printf("Building Disk Label\n"); + d->magicNum = UBIXDISKMAGIC; + d->magicNum2 = UBIXDISKMAGIC; + d->numPartitions = 2; + d->partitions[0].p_size = 2000; + d->partitions[0].p_offset = 50; + d->partitions[0].p_fstype = 0x24; + d->partitions[0].p_bsize = 0x8; + d->partitions[1].p_size = 2000; + d->partitions[1].p_offset = 1000; + d->partitions[1].p_fstype = 0x24; + d->partitions[1].p_bsize = 0x8; + fd = fopen(argv[1],"wb"); + fseek(fd,512 * (atoi(argv[2])),0); + fwrite(d,512,1,fd); + } diff --git a/src/sys/boot/boot2/ubixfs.h b/src/sys/boot/boot2/ubixfs.h new file mode 100644 index 0000000..4c558d1 --- /dev/null +++ b/src/sys/boot/boot2/ubixfs.h @@ -0,0 +1,44 @@ +#define DOSPTYP_UBX 0x2A /* UbixFS partition type */ +#define UBIXDISKMAGIC ((u_int32_t)0x45) /* The disk magic number */ +#define MAXUBIXPARTITIONS 16 +#define UBIXFSMAGIC ((u_int32_t)0x69) /* The File System Magic Number */ + +typedef unsigned long uLong; +typedef unsigned short uShort; + + +struct ubixDiskLabel { + u_int32_t magicNum; + u_int32_t magicNum2; + u_int16_t driveType; + u_int16_t numPartitions; + struct ubixPartitions { /* the partition table */ + u_int32_t p_size; /* number of sectors in partition */ + u_int32_t p_offset; /* starting sector */ + u_int32_t p_fsize; /* filesystem basic fragment size */ + u_int32_t p_bsize; /* BAT size */ + u_int8_t p_fstype; /* filesystem type, see below */ + u_int8_t 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 { + uLong startCluster; //Starting Cluster Of File + uLong size; //Size Of File + uLong creationDate; //Date Created + uLong lastModified; //Date Last Modified + uLong uid; //UID Of Owner + uLong gid; //GID Of Owner + uShort attributes; //Files Attributes + uShort permissions; //Files Permissions + char fileName[256]; //File Name + }; diff --git a/src/sys/boot/btx/Makefile b/src/sys/boot/btx/Makefile new file mode 100644 index 0000000..9a65f19 --- /dev/null +++ b/src/sys/boot/btx/Makefile @@ -0,0 +1,5 @@ +# $FreeBSD: src/sys/boot/i386/btx/Makefile,v 1.6 1999/08/28 00:40:03 peter Exp $ + +SUBDIR= btx btxldr lib + +.include diff --git a/src/sys/boot/btx/btx/Makefile b/src/sys/boot/btx/btx/Makefile new file mode 100644 index 0000000..cdefb50 --- /dev/null +++ b/src/sys/boot/btx/btx/Makefile @@ -0,0 +1,36 @@ +# $FreeBSD: src/sys/boot/i386/btx/btx/Makefile,v 1.7.2.2 2000/12/28 12:08:22 ps Exp $ + +M4?= m4 + +.if defined(PAGING) +M4FLAGS+= -DPAGING +.endif + +.if defined(BOOT_BTX_NOHANG) +BOOT_BTX_FLAGS=0x1 +.else +BOOT_BTX_FLAGS=0x0 +.endif + +AFLAGS+= --defsym BTX_FLAGS=${BOOT_BTX_FLAGS} + +ORG= 0x9000 + +all: btx + +btx: btx.o +.if ${OBJFORMAT} == aout + ${LD} -nostdlib -N -s -T ${ORG} -o btx.out btx.o + dd if=btx.out of=${.TARGET} ibs=32 skip=1 +.else + ${LD} -N -e start -Ttext ${ORG} -o btx.out btx.o + objcopy -S -O binary btx.out ${.TARGET} +.endif + +btx.o: btx.s + (cd ${.CURDIR}; ${M4} ${M4FLAGS} btx.s) | \ + ${AS} ${AFLAGS} -o ${.TARGET} + +CLEANFILES+= btx btx.out btx.o + +.include diff --git a/src/sys/boot/btx/btx/btx.s b/src/sys/boot/btx/btx/btx.s new file mode 100644 index 0000000..0bcf0a9 --- /dev/null +++ b/src/sys/boot/btx/btx/btx.s @@ -0,0 +1,1080 @@ +# +# Copyright (c) 1998 Robert Nordier +# All rights reserved. +# +# Redistribution and use in source and binary forms are freely +# permitted provided that the above copyright notice and this +# paragraph and the following disclaimer are duplicated in all +# such forms. +# +# This software is provided "AS IS" and without any express or +# implied warranties, including, without limitation, the implied +# warranties of merchantability and fitness for a particular +# purpose. +# + +# $FreeBSD: src/sys/boot/i386/btx/btx/btx.s,v 1.15.2.4 2000/12/28 12:08:22 ps Exp $ + +# +# Memory layout. +# + .set MEM_BTX,0x1000 # Start of BTX memory + .set MEM_ESP0,0x1800 # Supervisor stack + .set MEM_BUF,0x1800 # Scratch buffer + .set MEM_ESP1,0x1e00 # Link stack + .set MEM_IDT,0x1e00 # IDT + .set MEM_TSS,0x1f98 # TSS + .set MEM_MAP,0x2000 # I/O bit map + .set MEM_DIR,0x4000 # Page directory + .set MEM_TBL,0x5000 # Page tables + .set MEM_ORG,0x9000 # BTX code + .set MEM_USR,0xa000 # Start of user memory +# +# Paging control. +# + .set PAG_SIZ,0x1000 # Page size + .set PAG_CNT,0x1000 # Pages to map +# +# Segment selectors. +# + .set SEL_SCODE,0x8 # Supervisor code + .set SEL_SDATA,0x10 # Supervisor data + .set SEL_RCODE,0x18 # Real mode code + .set SEL_RDATA,0x20 # Real mode data + .set SEL_UCODE,0x28|3 # User code + .set SEL_UDATA,0x30|3 # User data + .set SEL_TSS,0x38 # TSS +# +# Task state segment fields. +# + .set TSS_ESP0,0x4 # PL 0 ESP + .set TSS_SS0,0x8 # PL 0 SS + .set TSS_ESP1,0xc # PL 1 ESP + .set TSS_MAP,0x66 # I/O bit map base +# +# System calls. +# + .set SYS_EXIT,0x0 # Exit + .set SYS_EXEC,0x1 # Exec +# +# V86 constants. +# + .set V86_FLG,0x208eff # V86 flag mask + .set V86_STK,0x400 # V86 stack allowance +# +# Dump format control bytes. +# + .set DMP_X16,0x1 # Word + .set DMP_X32,0x2 # Long + .set DMP_MEM,0x4 # Memory + .set DMP_EOL,0x8 # End of line +# +# Screen defaults and assumptions. +# + .set SCR_MAT,0x7 # Mode/attribute + .set SCR_COL,0x50 # Columns per row + .set SCR_ROW,0x19 # Rows per screen +# +# BIOS Data Area locations. +# + .set BDA_MEM,0x413 # Free memory + .set BDA_KEYFLAGS,0x417 # Keyboard shift-state flags + .set BDA_SCR,0x449 # Video mode + .set BDA_POS,0x450 # Cursor position + .set BDA_BOOT,0x472 # Boot howto flag +# +# Derivations, for brevity. +# + .set _ESP0H,MEM_ESP0>>0x8 # Byte 1 of ESP0 + .set _ESP1H,MEM_ESP1>>0x8 # Byte 1 of ESP1 + .set _TSSIO,MEM_MAP-MEM_TSS # TSS I/O base + .set _TSSLM,MEM_DIR-MEM_TSS-1 # TSS limit + .set _IDTLM,MEM_TSS-MEM_IDT-1 # IDT limit +# +# Code segment. +# + .globl start + .code16 +start: # Start of code +# +# BTX header. +# +btx_hdr: .byte 0xeb # Machine ID + .byte 0xe # Header size + .ascii "BTX" # Magic + .byte 0x1 # Major version + .byte 0x1 # Minor version + .byte BTX_FLAGS # Flags + .word PAG_CNT-MEM_ORG>>0xc # Paging control + .word break-start # Text size + .long 0x0 # Entry address +# +# Initialization routine. +# +init: cli # Disable interrupts + xor %ax,%ax # Zero/segment + mov %ax,%ss # Set up + mov $MEM_ESP0,%sp # stack + mov %ax,%es # Address + mov %ax,%ds # data + pushl $0x2 # Clear + popfl # flags +# +# Initialize memory. +# + mov $MEM_IDT,%di # Memory to initialize + mov $(MEM_ORG-MEM_IDT)/2,%cx # Words to zero + push %di # Save + rep # Zero-fill + stosw # memory + pop %di # Restore +# +# Create IDT. +# + mov $idtctl,%si # Control string +init.1: lodsb # Get entry + cbw # count + xchg %ax,%cx # as word + jcxz init.4 # If done + lodsb # Get segment + xchg %ax,%dx # P:DPL:type + lodsw # Get control + xchg %ax,%bx # set + lodsw # Get handler offset + mov $SEL_SCODE,%dh # Segment selector +init.2: shr %bx # Handle this int? + jnc init.3 # No + mov %ax,(%di) # Set handler offset + mov %dh,0x2(%di) # and selector + mov %dl,0x5(%di) # Set P:DPL:type + add $0x4,%ax # Next handler +init.3: lea 0x8(%di),%di # Next entry + loop init.2 # Till set done + jmp init.1 # Continue +# +# Initialize TSS. +# +init.4: movb $_ESP0H,TSS_ESP0+1(%di) # Set ESP0 + movb $SEL_SDATA,TSS_SS0(%di) # Set SS0 + movb $_ESP1H,TSS_ESP1+1(%di) # Set ESP1 + movb $_TSSIO,TSS_MAP(%di) # Set I/O bit map base +ifdef(`PAGING',` +# +# Create page directory. +# + xor %edx,%edx # Page + mov $PAG_SIZ>>0x8,%dh # size + xor %eax,%eax # Zero + mov $MEM_DIR,%di # Page directory + mov $PAG_CNT>>0xa,%cl # Entries + mov $MEM_TBL|0x7,%ax # First entry +init.5: stosl # Write entry + add %dx,%ax # To next + loop init.5 # Till done +# +# Create page tables. +# + mov $MEM_TBL,%di # Page table + mov $PAG_CNT>>0x8,%ch # Entries + xor %ax,%ax # Start address +init.6: mov $0x7,%al # Set U:W:P flags + cmp btx_hdr+0x8,%cx # Standard user page? + jb init.7 # Yes + cmp $PAG_CNT-MEM_BTX>>0xc,%cx # BTX memory? + jae init.7 # No or first page + and $~0x2,%al # Clear W flag + cmp $PAG_CNT-MEM_USR>>0xc,%cx # User page zero? + jne init.7 # No + testb $0x80,btx_hdr+0x7 # Unmap it? + jz init.7 # No + and $~0x1,%al # Clear P flag +init.7: stosl # Set entry + add %edx,%eax # Next address + loop init.6 # Till done +') +# +# Bring up the system. +# + mov $0x2820,%bx # Set protected mode + callw setpic # IRQ offsets + lidt idtdesc # Set IDT +ifdef(`PAGING',` + xor %eax,%eax # Set base + mov $MEM_DIR>>0x8,%ah # of page + mov %eax,%cr3 # directory +') + lgdt gdtdesc # Set GDT + mov %cr0,%eax # Switch to protected +ifdef(`PAGING',` + or $0x80000001,%eax # mode and enable paging +',` + or $0x01,%eax # mode +') + mov %eax,%cr0 # + ljmp $SEL_SCODE,$init.8 # To 32-bit code + .code32 +init.8: xorl %ecx,%ecx # Zero + movb $SEL_SDATA,%cl # To 32-bit + movw %cx,%ss # stack +# +# Launch user task. +# + movb $SEL_TSS,%cl # Set task + ltr %cx # register + movl $MEM_USR,%edx # User base address + movzwl %ss:BDA_MEM,%eax # Get free memory + shll $0xa,%eax # To bytes + subl $0x1000,%eax # Less arg space + subl %edx,%eax # Less base + movb $SEL_UDATA,%cl # User data selector + pushl %ecx # Set SS + pushl %eax # Set ESP + push $0x202 # Set flags (IF set) + push $SEL_UCODE # Set CS + pushl btx_hdr+0xc # Set EIP + pushl %ecx # Set GS + pushl %ecx # Set FS + pushl %ecx # Set DS + pushl %ecx # Set ES + pushl %edx # Set EAX + movb $0x7,%cl # Set remaining +init.9: push $0x0 # general + loop init.9 # registers + popa # and initialize + popl %es # Initialize + popl %ds # user + popl %fs # segment + popl %gs # registers + iret # To user mode +# +# Exit routine. +# +exit: cli # Disable interrupts + movl $MEM_ESP0,%esp # Clear stack +# +# Turn off paging. +# + movl %cr0,%eax # Get CR0 +ifdef(`PAGING',` + andl $~0x80000000,%eax # Disable + movl %eax,%cr0 # paging +') + xorl %ecx,%ecx # Zero +ifdef(`PAGING',` + movl %ecx,%cr3 # Flush TLB +') +# +# To 16 bits. +# + ljmpw $SEL_RCODE,$exit.1 # Reload CS + .code16 +exit.1: mov $SEL_RDATA,%cl # 16-bit selector + mov %cx,%ss # Reload SS + mov %cx,%ds # Load + mov %cx,%es # remaining + mov %cx,%fs # segment + mov %cx,%gs # registers +# +# To real-address mode. +# + dec %ax # Switch to + mov %eax,%cr0 # real mode + ljmp $0x0,$exit.2 # Reload CS +exit.2: xor %ax,%ax # Real mode segment + mov %ax,%ss # Reload SS + mov %ax,%ds # Address data + mov $0x7008,%bx # Set real mode + callw setpic # IRQ offsets + lidt ivtdesc # Set IVT +# +# Reboot or await reset. +# + sti # Enable interrupts + testb $0x1,btx_hdr+0x7 # Reboot? +exit.3: jz exit.3 # No + movw $0x1234, BDA_BOOT # Do a warm boot + ljmp $0xffff,$0x0 # reboot the machine +# +# Set IRQ offsets by reprogramming 8259A PICs. +# +setpic: in $0x21,%al # Save master + push %ax # IMR + in $0xa1,%al # Save slave + push %ax # IMR + movb $0x11,%al # ICW1 to + outb %al,$0x20 # master, + outb %al,$0xa0 # slave + movb %bl,%al # ICW2 to + outb %al,$0x21 # master + movb %bh,%al # ICW2 to + outb %al,$0xa1 # slave + movb $0x4,%al # ICW3 to + outb %al,$0x21 # master + movb $0x2,%al # ICW3 to + outb %al,$0xa1 # slave + movb $0x1,%al # ICW4 to + outb %al,$0x21 # master, + outb %al,$0xa1 # slave + pop %ax # Restore slave + outb %al,$0xa1 # IMR + pop %ax # Restore master + outb %al,$0x21 # IMR + retw # To caller + .code32 +# +# Initiate return from V86 mode to user mode. +# +inthlt: hlt # To supervisor mode +# +# Exception jump table. +# +intx00: push $0x0 # Int 0x0: #DE + jmp ex_noc # Divide error + push $0x1 # Int 0x1: #DB + jmp ex_noc # Debug + push $0x3 # Int 0x3: #BP + jmp ex_noc # Breakpoint + push $0x4 # Int 0x4: #OF + jmp ex_noc # Overflow + push $0x5 # Int 0x5: #BR + jmp ex_noc # BOUND range exceeded + push $0x6 # Int 0x6: #UD + jmp ex_noc # Invalid opcode + push $0x7 # Int 0x7: #NM + jmp ex_noc # Device not available + push $0x8 # Int 0x8: #DF + jmp except # Double fault + push $0xa # Int 0xa: #TS + jmp except # Invalid TSS + push $0xb # Int 0xb: #NP + jmp except # Segment not present + push $0xc # Int 0xc: #SS + jmp except # Stack segment fault + push $0xd # Int 0xd: #GP + jmp ex_v86 # General protection + push $0xe # Int 0xe: #PF + jmp except # Page fault +intx10: push $0x10 # Int 0x10: #MF + jmp ex_noc # Floating-point error +# +# Handle #GP exception. +# +ex_v86: testb $0x2,0x12(%esp,1) # V86 mode? + jz except # No + jmp v86mon # To monitor +# +# Save a zero error code. +# +ex_noc: pushl (%esp,1) # Duplicate int no + movb $0x0,0x4(%esp,1) # Fake error code +# +# Handle exception. +# +except: cld # String ops inc + pushl %ds # Save + pushl %es # most + pusha # registers + movb $0x6,%al # Push loop count + testb $0x2,0x3a(%esp,1) # V86 mode? + jnz except.1 # Yes + pushl %gs # Set GS + pushl %fs # Set FS + pushl %ds # Set DS + pushl %es # Set ES + movb $0x2,%al # Push loop count + cmpw $SEL_SCODE,0x44(%esp,1) # Supervisor mode? + jne except.1 # No + pushl %ss # Set SS + leal 0x50(%esp,1),%eax # Set + pushl %eax # ESP + jmp except.2 # Join common code +except.1: pushl 0x50(%esp,1) # Set GS, FS, DS, ES + decb %al # (if V86 mode), and + jne except.1 # SS, ESP +except.2: push $SEL_SDATA # Set up + popl %ds # to + pushl %ds # address + popl %es # data + movl %esp,%ebx # Stack frame + movl $dmpfmt,%esi # Dump format string + movl $MEM_BUF,%edi # Buffer + pushl %edi # Dump to + call dump # buffer + popl %esi # and + call putstr # display + leal 0x18(%esp,1),%esp # Discard frame + popa # Restore + popl %es # registers + popl %ds # saved + cmpb $0x3,(%esp,1) # Breakpoint? + je except.3 # Yes + jmp exit # Exit +except.3: leal 0x8(%esp,1),%esp # Discard err, int no + iret # From interrupt +# +# Return to user mode from V86 mode. +# +intrtn: cld # String ops inc + pushl %ds # Address + popl %es # data + leal 0x3c(%ebp),%edx # V86 Segment registers + movl MEM_TSS+TSS_ESP1,%esi # Link stack pointer + lodsl # INT_V86 args pointer + movl %esi,%ebx # Saved exception frame + testl %eax,%eax # INT_V86 args? + jz intrtn.2 # No + movl $MEM_USR,%edi # User base + movl 0x1c(%esi),%ebx # User ESP + movl %eax,(%edi,%ebx,1) # Restore to user stack + leal 0x8(%edi,%eax,1),%edi # Arg segment registers + testb $0x4,-0x6(%edi) # Return flags? + jz intrtn.1 # No + movl 0x30(%ebp),%eax # Get V86 flags + movw %ax,0x18(%esi) # Set user flags +intrtn.1: leal 0x10(%esi),%ebx # Saved exception frame + xchgl %edx,%esi # Segment registers + movb $0x4,%cl # Update seg regs + rep # in INT_V86 + movsl # args +intrtn.2: movl %edx,%esi # Segment registers + leal 0x28(%ebp),%edi # Set up seg + movb $0x4,%cl # regs for + rep # later + movsl # pop + movl %ebx,%esi # Restore exception + movb $0x5,%cl # frame to + rep # supervisor + movsl # stack + movl %esi,MEM_TSS+TSS_ESP1 # Link stack pointer + popa # Restore + leal 0x8(%esp,1),%esp # Discard err, int no + popl %es # Restore + popl %ds # user + popl %fs # segment + popl %gs # registers + iret # To user mode +# +# V86 monitor. +# +v86mon: cld # String ops inc + pushl $SEL_SDATA # Set up for + popl %ds # flat addressing + pusha # Save registers + movl %esp,%ebp # Address stack frame + movzwl 0x2c(%ebp),%edi # Load V86 CS + shll $0x4,%edi # To linear + movl 0x28(%ebp),%esi # Load V86 IP + addl %edi,%esi # Code pointer + xorl %ecx,%ecx # Zero + movb $0x2,%cl # 16-bit operands + xorl %eax,%eax # Zero +v86mon.1: lodsb # Get opcode + cmpb $0x66,%al # Operand size prefix? + jne v86mon.2 # No + movb $0x4,%cl # 32-bit operands + jmp v86mon.1 # Continue +v86mon.2: cmpb $0xf4,%al # HLT? + jne v86mon.3 # No + cmpl $inthlt+0x1,%esi # Is inthlt? + jne v86mon.7 # No (ignore) + jmp intrtn # Return to user mode +v86mon.3: cmpb $0xf,%al # Prefixed instruction? + jne v86mon.4 # No + cmpb $0x09,(%esi) # Is it a WBINVD? + je v86wbinvd # Yes + cmpb $0x30,(%esi) # Is it a WRMSR? + je v86wrmsr # Yes + cmpb $0x32,(%esi) # Is it a RDMSR? + je v86rdmsr # Yes + cmpb $0x20,(%esi) # Is this a + jne v86mon.4 # MOV EAX,CR0 + cmpb $0xc0,0x1(%esi) # instruction? + je v86mov # Yes +v86mon.4: cmpb $0xfa,%al # CLI? + je v86cli # Yes + cmpb $0xfb,%al # STI? + je v86sti # Yes + movzwl 0x38(%ebp),%ebx # Load V86 SS + shll $0x4,%ebx # To offset + pushl %ebx # Save + addl 0x34(%ebp),%ebx # Add V86 SP + movl 0x30(%ebp),%edx # Load V86 flags + cmpb $0x9c,%al # PUSHF/PUSHFD? + je v86pushf # Yes + cmpb $0x9d,%al # POPF/POPFD? + je v86popf # Yes + cmpb $0xcd,%al # INT imm8? + je v86intn # Yes + cmpb $0xcf,%al # IRET/IRETD? + je v86iret # Yes + popl %ebx # Restore + popa # Restore + jmp except # Handle exception +v86mon.5: movl %edx,0x30(%ebp) # Save V86 flags +v86mon.6: popl %edx # V86 SS adjustment + subl %edx,%ebx # Save V86 + movl %ebx,0x34(%ebp) # SP +v86mon.7: subl %edi,%esi # From linear + movl %esi,0x28(%ebp) # Save V86 IP + popa # Restore + leal 0x8(%esp,1),%esp # Discard int no, error + iret # To V86 mode +# +# Emulate MOV EAX,CR0. +# +v86mov: movl %cr0,%eax # CR0 to + movl %eax,0x1c(%ebp) # saved EAX + incl %esi # Adjust IP +# +# Return from emulating a 0x0f prefixed instruction +# +v86preret: incl %esi # Adjust IP + jmp v86mon.7 # Finish up +# +# Emulate WBINVD +# +v86wbinvd: wbinvd # Write back and invalidate + # cache + jmp v86preret # Finish up +# +# Emulate WRMSR +# +v86wrmsr: movl 0x18(%ebp),%ecx # Get user's %ecx (MSR to write) + movl 0x14(%ebp),%edx # Load the value + movl 0x1c(%ebp),%eax # to write + wrmsr # Write MSR + jmp v86preret # Finish up +# +# Emulate RDMSR +# +v86rdmsr: movl 0x18(%ebp),%ecx # MSR to read + rdmsr # Read the MSR + movl %eax,0x1c(%ebp) # Return the value of + movl %edx,0x14(%ebp) # the MSR to the user + jmp v86preret # Finish up +# +# Emulate CLI. +# +v86cli: andb $~0x2,0x31(%ebp) # Clear IF + jmp v86mon.7 # Finish up +# +# Emulate STI. +# +v86sti: orb $0x2,0x31(%ebp) # Set IF + jmp v86mon.7 # Finish up +# +# Emulate PUSHF/PUSHFD. +# +v86pushf: subl %ecx,%ebx # Adjust SP + cmpb $0x4,%cl # 32-bit + je v86pushf.1 # Yes + data16 # 16-bit +v86pushf.1: movl %edx,(%ebx) # Save flags + jmp v86mon.6 # Finish up +# +# Emulate IRET/IRETD. +# +v86iret: movzwl (%ebx),%esi # Load V86 IP + movzwl 0x2(%ebx),%edi # Load V86 CS + leal 0x4(%ebx),%ebx # Adjust SP + movl %edi,0x2c(%ebp) # Save V86 CS + xorl %edi,%edi # No ESI adjustment +# +# Emulate POPF/POPFD (and remainder of IRET/IRETD). +# +v86popf: cmpb $0x4,%cl # 32-bit? + je v86popf.1 # Yes + movl %edx,%eax # Initialize + data16 # 16-bit +v86popf.1: movl (%ebx),%eax # Load flags + addl %ecx,%ebx # Adjust SP + andl $V86_FLG,%eax # Merge + andl $~V86_FLG,%edx # the + orl %eax,%edx # flags + jmp v86mon.5 # Finish up +# +# trap int 15, function 87 +# reads %es:%si from saved registers on stack to find a GDT containing +# source and destination locations +# reads count of words from saved %cx +# returns success by setting %ah to 0 +# +int15_87: pushl %eax # Save + pushl %ebx # some information + pushl %esi # onto the stack. + pushl %edi + xorl %eax,%eax # clean EAX + xorl %ebx,%ebx # clean EBX + movl 0x4(%ebp),%esi # Get user's ESI + movl 0x3C(%ebp),%ebx # store ES + movw %si,%ax # store SI + shll $0x4,%ebx # Make it a seg. + addl %eax,%ebx # ebx=(es<<4)+si + movb 0x14(%ebx),%al # Grab the + movb 0x17(%ebx),%ah # necessary + shll $0x10,%eax # information + movw 0x12(%ebx),%ax # from + movl %eax,%esi # the + movb 0x1c(%ebx),%al # GDT in order to + movb 0x1f(%ebx),%ah # have %esi offset + shll $0x10,%eax # of source and %edi + movw 0x1a(%ebx),%ax # of destination. + movl %eax,%edi + pushl %ds # Make: + popl %es # es = ds + pushl %ecx # stash ECX + xorl %ecx,%ecx # highw of ECX is clear + movw 0x18(%ebp),%cx # Get user's ECX + shll $0x1,%ecx # Convert from num words to num + # bytes + rep # repeat... + movsb # perform copy. + popl %ecx # Restore + popl %edi + popl %esi # previous + popl %ebx # register + popl %eax # values. + movb $0x0,0x1d(%ebp) # set ah = 0 to indicate + # success + andb $0xfe,%dl # clear CF + jmp v86mon.5 # Finish up + +# +# Reboot the machine by setting the reboot flag and exiting +# +reboot: orb $0x1,btx_hdr+0x7 # Set the reboot flag + jmp exit # Terminate BTX and reboot + +# +# Emulate INT imm8... also make sure to check if it's int 15/87 +# +v86intn: lodsb # Get int no + cmpb $0x19,%al # is it int 19? + je reboot # yes, reboot the machine + cmpb $0x15,%al # is it int 15? + jne v86intn.3 # no, skip parse + pushl %eax # stash EAX + movl 0x1c(%ebp),%eax # user's saved EAX + cmpb $0x87,%ah # is it the memcpy subfunction? + jne v86intn.1 # no, keep checking + popl %eax # get the stack straight + jmp int15_87 # it's our cue +v86intn.1: cmpw $0x4f53,%ax # is it the delete key callout? + jne v86intn.2 # no, handle the int normally + movb BDA_KEYFLAGS,%al # get the shift key state + andb $0xc,%al # mask off just Ctrl and Alt + cmpb $0xc,%al # are both Ctrl and Alt down? + jne v86intn.2 # no, handle the int normally + popl %eax # restore EAX + jmp reboot # reboot the machine +v86intn.2: popl %eax # restore EAX +v86intn.3: subl %edi,%esi # From + shrl $0x4,%edi # linear + movw %dx,-0x2(%ebx) # Save flags + movw %di,-0x4(%ebx) # Save CS + leal -0x6(%ebx),%ebx # Adjust SP + movw %si,(%ebx) # Save IP + shll $0x2,%eax # Scale + movzwl (%eax),%esi # Load IP + movzwl 0x2(%eax),%edi # Load CS + movl %edi,0x2c(%ebp) # Save CS + xorl %edi,%edi # No ESI adjustment + andb $~0x1,%dh # Clear TF + jmp v86mon.5 # Finish up +# +# Hardware interrupt jump table. +# +intx20: push $0x8 # Int 0x20: IRQ0 + jmp int_hw # V86 int 0x8 + push $0x9 # Int 0x21: IRQ1 + jmp int_hw # V86 int 0x9 + push $0xa # Int 0x22: IRQ2 + jmp int_hw # V86 int 0xa + push $0xb # Int 0x23: IRQ3 + jmp int_hw # V86 int 0xb + push $0xc # Int 0x24: IRQ4 + jmp int_hw # V86 int 0xc + push $0xd # Int 0x25: IRQ5 + jmp int_hw # V86 int 0xd + push $0xe # Int 0x26: IRQ6 + jmp int_hw # V86 int 0xe + push $0xf # Int 0x27: IRQ7 + jmp int_hw # V86 int 0xf + push $0x70 # Int 0x28: IRQ8 + jmp int_hw # V86 int 0x70 + push $0x71 # Int 0x29: IRQ9 + jmp int_hw # V86 int 0x71 + push $0x72 # Int 0x2a: IRQ10 + jmp int_hw # V86 int 0x72 + push $0x73 # Int 0x2b: IRQ11 + jmp int_hw # V86 int 0x73 + push $0x74 # Int 0x2c: IRQ12 + jmp int_hw # V86 int 0x74 + push $0x75 # Int 0x2d: IRQ13 + jmp int_hw # V86 int 0x75 + push $0x76 # Int 0x2e: IRQ14 + jmp int_hw # V86 int 0x76 + push $0x77 # Int 0x2f: IRQ15 + jmp int_hw # V86 int 0x77 +# +# Reflect hardware interrupts. +# +int_hw: testb $0x2,0xe(%esp,1) # V86 mode? + jz intusr # No + pushl $SEL_SDATA # Address + popl %ds # data + xchgl %eax,(%esp,1) # Swap EAX, int no + pushl %ebp # Address + movl %esp,%ebp # stack frame + pushl %ebx # Save + shll $0x2,%eax # Get int + movl (%eax),%eax # vector + subl $0x6,0x14(%ebp) # Adjust V86 ESP + movzwl 0x18(%ebp),%ebx # V86 SS + shll $0x4,%ebx # * 0x10 + addl 0x14(%ebp),%ebx # + V86 ESP + xchgw %ax,0x8(%ebp) # Swap V86 IP + rorl $0x10,%eax # Swap words + xchgw %ax,0xc(%ebp) # Swap V86 CS + roll $0x10,%eax # Swap words + movl %eax,(%ebx) # CS:IP for IRET + movl 0x10(%ebp),%eax # V86 flags + movw %ax,0x4(%ebx) # Flags for IRET + andb $~0x3,0x11(%ebp) # Clear IF, TF + popl %ebx # Restore + popl %ebp # saved + popl %eax # registers + iret # To V86 mode +# +# Invoke V86 interrupt from user mode, with arguments. +# +intx31: stc # Have btx_v86 + pushl %eax # Missing int no +# +# Invoke V86 interrupt from user mode. +# +intusr: std # String ops dec + pushl %eax # Expand + pushl %eax # stack + pushl %eax # frame + pusha # Save + pushl %gs # Save + movl %esp,%eax # seg regs + pushl %fs # and + pushl %ds # point + pushl %es # to them + push $SEL_SDATA # Set up + popl %ds # to + pushl %ds # address + popl %es # data + movl $MEM_USR,%ebx # User base + movl %ebx,%edx # address + jc intusr.1 # If btx_v86 + xorl %edx,%edx # Control flags + xorl %ebp,%ebp # btx_v86 pointer +intusr.1: leal 0x50(%esp,1),%esi # Base of frame + pushl %esi # Save + addl -0x4(%esi),%ebx # User ESP + movl MEM_TSS+TSS_ESP1,%edi # Link stack pointer + leal -0x4(%edi),%edi # Adjust for push + xorl %ecx,%ecx # Zero + movb $0x5,%cl # Push exception + rep # frame on + movsl # link stack + xchgl %eax,%esi # Saved seg regs + movl 0x40(%esp,1),%eax # Get int no + testl %edx,%edx # Have btx_v86? + jz intusr.2 # No + movl (%ebx),%ebp # btx_v86 pointer + movb $0x4,%cl # Count + addl %ecx,%ebx # Adjust for pop + rep # Push saved seg regs + movsl # on link stack + addl %ebp,%edx # Flatten btx_v86 ptr + leal 0x14(%edx),%esi # Seg regs pointer + movl 0x4(%edx),%eax # Get int no/address + movzwl 0x2(%edx),%edx # Get control flags +intusr.2: movl %ebp,(%edi) # Push btx_v86 and + movl %edi,MEM_TSS+TSS_ESP1 # save link stack ptr + popl %edi # Base of frame + xchgl %eax,%ebp # Save intno/address + movl 0x48(%esp,1),%eax # Get flags + testb $0x2,%dl # Simulate CALLF? + jnz intusr.3 # Yes + decl %ebx # Push flags + decl %ebx # on V86 + movw %ax,(%ebx) # stack +intusr.3: movb $0x4,%cl # Count + subl %ecx,%ebx # Push return address + movl $inthlt,(%ebx) # on V86 stack + rep # Copy seg regs to + movsl # exception frame + xchgl %eax,%ecx # Save flags + movl %ebx,%eax # User ESP + subl $V86_STK,%eax # Less bytes + ja intusr.4 # to + xorl %eax,%eax # keep +intusr.4: shrl $0x4,%eax # Gives segment + stosl # Set SS + shll $0x4,%eax # To bytes + xchgl %eax,%ebx # Swap + subl %ebx,%eax # Gives offset + stosl # Set ESP + xchgl %eax,%ecx # Get flags + btsl $0x11,%eax # Set VM + andb $~0x1,%ah # Clear TF + stosl # Set EFL + xchgl %eax,%ebp # Get int no/address + testb $0x1,%dl # Address? + jnz intusr.5 # Yes + shll $0x2,%eax # Scale + movl (%eax),%eax # Load int vector +intusr.5: movl %eax,%ecx # Save + shrl $0x10,%eax # Gives segment + stosl # Set CS + movw %cx,%ax # Restore + stosl # Set EIP + leal 0x10(%esp,1),%esp # Discard seg regs + popa # Restore + iret # To V86 mode +# +# System Call. +# +intx30: cmpl $SYS_EXEC,%eax # Exec system call? + jne intx30.1 # No + pushl %ss # Set up + popl %es # all + pushl %es # segment + popl %ds # registers + pushl %ds # for the + popl %fs # program + pushl %fs # we're + popl %gs # invoking + movl $MEM_USR,%eax # User base address + addl 0xc(%esp,1),%eax # Change to user + leal 0x4(%eax),%esp # stack +ifdef(`PAGING',` + movl %cr0,%eax # Turn + andl $~0x80000000,%eax # off + movl %eax,%cr0 # paging + xorl %eax,%eax # Flush + movl %eax,%cr3 # TLB +') + popl %eax # Call + call *%eax # program +intx30.1: incb %ss:btx_hdr+0x7 # Flag reboot + jmp exit # Exit +# +# Dump structure [EBX] to [EDI], using format string [ESI]. +# +dump.0: stosb # Save char +dump: lodsb # Load char + testb %al,%al # End of string? + jz dump.10 # Yes + testb $0x80,%al # Control? + jz dump.0 # No + movb %al,%ch # Save control + movb $'=',%al # Append + stosb # '=' + lodsb # Get offset + pushl %esi # Save + movsbl %al,%esi # To + addl %ebx,%esi # pointer + testb $DMP_X16,%ch # Dump word? + jz dump.1 # No + lodsw # Get and + call hex16 # dump it +dump.1: testb $DMP_X32,%ch # Dump long? + jz dump.2 # No + lodsl # Get and + call hex32 # dump it +dump.2: testb $DMP_MEM,%ch # Dump memory? + jz dump.8 # No + pushl %ds # Save + testb $0x2,0x52(%ebx) # V86 mode? + jnz dump.3 # Yes + verr 0x4(%esi) # Readable selector? + jnz dump.3 # No + ldsl (%esi),%esi # Load pointer + jmp dump.4 # Join common code +dump.3: lodsl # Set offset + xchgl %eax,%edx # Save + lodsl # Get segment + shll $0x4,%eax # * 0x10 + addl %edx,%eax # + offset + xchgl %eax,%esi # Set pointer +dump.4: movb $0x10,%cl # Bytes to dump +dump.5: lodsb # Get byte and + call hex8 # dump it + decb %cl # Keep count + jz dump.7 # If done + movb $'-',%al # Separator + cmpb $0x8,%cl # Half way? + je dump.6 # Yes + movb $' ',%al # Use space +dump.6: stosb # Save separator + jmp dump.5 # Continue +dump.7: popl %ds # Restore +dump.8: popl %esi # Restore + movb $0xa,%al # Line feed + testb $DMP_EOL,%ch # End of line? + jnz dump.9 # Yes + movb $' ',%al # Use spaces + stosb # Save one +dump.9: jmp dump.0 # Continue +dump.10: stosb # Terminate string + ret # To caller +# +# Convert EAX, AX, or AL to hex, saving the result to [EDI]. +# +hex32: pushl %eax # Save + shrl $0x10,%eax # Do upper + call hex16 # 16 + popl %eax # Restore +hex16: call hex16.1 # Do upper 8 +hex16.1: xchgb %ah,%al # Save/restore +hex8: pushl %eax # Save + shrb $0x4,%al # Do upper + call hex8.1 # 4 + popl %eax # Restore +hex8.1: andb $0xf,%al # Get lower 4 + cmpb $0xa,%al # Convert + sbbb $0x69,%al # to hex + das # digit + orb $0x20,%al # To lower case + stosb # Save char + ret # (Recursive) +# +# Output zero-terminated string [ESI] to the console. +# +putstr.0: call putchr # Output char +putstr: lodsb # Load char + testb %al,%al # End of string? + jnz putstr.0 # No + ret # To caller +# +# Output character AL to the console. +# +putchr: pusha # Save + xorl %ecx,%ecx # Zero for loops + movb $SCR_MAT,%ah # Mode/attribute + movl $BDA_POS,%ebx # BDA pointer + movw (%ebx),%dx # Cursor position + movl $0xb8000,%edi # Regen buffer (color) + cmpb %ah,BDA_SCR-BDA_POS(%ebx) # Mono mode? + jne putchr.1 # No + xorw %di,%di # Regen buffer (mono) +putchr.1: cmpb $0xa,%al # New line? + je putchr.2 # Yes + xchgl %eax,%ecx # Save char + movb $SCR_COL,%al # Columns per row + mulb %dh # * row position + addb %dl,%al # + column + adcb $0x0,%ah # position + shll %eax # * 2 + xchgl %eax,%ecx # Swap char, offset + movw %ax,(%edi,%ecx,1) # Write attr:char + incl %edx # Bump cursor + cmpb $SCR_COL,%dl # Beyond row? + jb putchr.3 # No +putchr.2: xorb %dl,%dl # Zero column + incb %dh # Bump row +putchr.3: cmpb $SCR_ROW,%dh # Beyond screen? + jb putchr.4 # No + leal 2*SCR_COL(%edi),%esi # New top line + movw $(SCR_ROW-1)*SCR_COL/2,%cx # Words to move + rep # Scroll + movsl # screen + movb $' ',%al # Space + movb $SCR_COL,%cl # Columns to clear + rep # Clear + stosw # line + movb $SCR_ROW-1,%dh # Bottom line +putchr.4: movw %dx,(%ebx) # Update position + popa # Restore + ret # To caller + + .p2align 4 +# +# Global descriptor table. +# +gdt: .word 0x0,0x0,0x0,0x0 # Null entry + .word 0xffff,0x0,0x9a00,0xcf # SEL_SCODE + .word 0xffff,0x0,0x9200,0xcf # SEL_SDATA + .word 0xffff,0x0,0x9a00,0x0 # SEL_RCODE + .word 0xffff,0x0,0x9200,0x0 # SEL_RDATA + .word 0xffff,MEM_USR,0xfa00,0xcf# SEL_UCODE + .word 0xffff,MEM_USR,0xf200,0xcf# SEL_UDATA + .word _TSSLM,MEM_TSS,0x8900,0x0 # SEL_TSS +gdt.1: +# +# Pseudo-descriptors. +# +gdtdesc: .word gdt.1-gdt-1,gdt,0x0 # GDT +idtdesc: .word _IDTLM,MEM_IDT,0x0 # IDT +ivtdesc: .word 0x400-0x0-1,0x0,0x0 # IVT +# +# IDT construction control string. +# +idtctl: .byte 0x10, 0x8e # Int 0x0-0xf + .word 0x7dfb,intx00 # (exceptions) + .byte 0x10, 0x8e # Int 0x10 + .word 0x1, intx10 # (exception) + .byte 0x10, 0x8e # Int 0x20-0x2f + .word 0xffff,intx20 # (hardware) + .byte 0x1, 0xee # int 0x30 + .word 0x1, intx30 # (system call) + .byte 0x2, 0xee # Int 0x31-0x32 + .word 0x1, intx31 # (V86, null) + .byte 0x0 # End of string +# +# Dump format string. +# +dmpfmt: .byte '\n' # "\n" + .ascii "int" # "int=" + .byte 0x80|DMP_X32, 0x40 # "00000000 " + .ascii "err" # "err=" + .byte 0x80|DMP_X32, 0x44 # "00000000 " + .ascii "efl" # "efl=" + .byte 0x80|DMP_X32, 0x50 # "00000000 " + .ascii "eip" # "eip=" + .byte 0x80|DMP_X32|DMP_EOL,0x48 # "00000000\n" + .ascii "eax" # "eax=" + .byte 0x80|DMP_X32, 0x34 # "00000000 " + .ascii "ebx" # "ebx=" + .byte 0x80|DMP_X32, 0x28 # "00000000 " + .ascii "ecx" # "ecx=" + .byte 0x80|DMP_X32, 0x30 # "00000000 " + .ascii "edx" # "edx=" + .byte 0x80|DMP_X32|DMP_EOL,0x2c # "00000000\n" + .ascii "esi" # "esi=" + .byte 0x80|DMP_X32, 0x1c # "00000000 " + .ascii "edi" # "edi=" + .byte 0x80|DMP_X32, 0x18 # "00000000 " + .ascii "ebp" # "ebp=" + .byte 0x80|DMP_X32, 0x20 # "00000000 " + .ascii "esp" # "esp=" + .byte 0x80|DMP_X32|DMP_EOL,0x0 # "00000000\n" + .ascii "cs" # "cs=" + .byte 0x80|DMP_X16, 0x4c # "0000 " + .ascii "ds" # "ds=" + .byte 0x80|DMP_X16, 0xc # "0000 " + .ascii "es" # "es=" + .byte 0x80|DMP_X16, 0x8 # "0000 " + .ascii " " # " " + .ascii "fs" # "fs=" + .byte 0x80|DMP_X16, 0x10 # "0000 " + .ascii "gs" # "gs=" + .byte 0x80|DMP_X16, 0x14 # "0000 " + .ascii "ss" # "ss=" + .byte 0x80|DMP_X16|DMP_EOL,0x4 # "0000\n" + .ascii "cs:eip" # "cs:eip=" + .byte 0x80|DMP_MEM|DMP_EOL,0x48 # "00 00 ... 00 00\n" + .ascii "ss:esp" # "ss:esp=" + .byte 0x80|DMP_MEM|DMP_EOL,0x0 # "00 00 ... 00 00\n" + .asciz "BTX halted" # End +# +# End of BTX memory. +# + .p2align 4 +break: diff --git a/src/sys/boot/btx/btxldr/Makefile b/src/sys/boot/btx/btxldr/Makefile new file mode 100644 index 0000000..d421cd5 --- /dev/null +++ b/src/sys/boot/btx/btxldr/Makefile @@ -0,0 +1,28 @@ +# $FreeBSD: src/sys/boot/i386/btx/btxldr/Makefile,v 1.7.2.1 2000/04/15 03:09:41 ps Exp $ + +M4?= m4 +M4FLAGS+= -DLOADER_ADDRESS=${LOADER_ADDRESS} + +.if defined(BTXLDR_VERBOSE) +M4FLAGS+= -DBTXLDR_VERBOSE +.endif + +all: btxldr + +btxldr: btxldr.o +.if ${OBJFORMAT} == aout + ${LD} -nostdlib -N -s -T ${LOADER_ADDRESS} -o btxldr.out btxldr.o + dd if=btxldr.out of=${.TARGET} ibs=32 skip=1 +.else + ${LD} -N -e start -Ttext ${LOADER_ADDRESS} -o btxldr.out btxldr.o + objcopy -S -O binary btxldr.out ${.TARGET} +.endif + +btxldr.o: btxldr.s + (cd ${.CURDIR}; ${M4} ${M4FLAGS} btxldr.s ) | \ + ${AS} ${AFLAGS} -o ${.TARGET} + +CLEANFILES+= btxldr btxldr.out btxldr.o + +.include <${.CURDIR}/../../Makefile.inc> +.include diff --git a/src/sys/boot/btx/btxldr/btxldr.s b/src/sys/boot/btx/btxldr/btxldr.s new file mode 100644 index 0000000..3604c5d --- /dev/null +++ b/src/sys/boot/btx/btxldr/btxldr.s @@ -0,0 +1,396 @@ +# +# Copyright (c) 1998 Robert Nordier +# All rights reserved. +# +# Redistribution and use in source and binary forms are freely +# permitted provided that the above copyright notice and this +# paragraph and the following disclaimer are duplicated in all +# such forms. +# +# This software is provided "AS IS" and without any express or +# implied warranties, including, without limitation, the implied +# warranties of merchantability and fitness for a particular +# purpose. +# + +# $FreeBSD: src/sys/boot/i386/btx/btxldr/btxldr.s,v 1.8.2.2 2000/07/06 23:04:29 obrien Exp $ + +# +# Prototype BTX loader program, written in a couple of hours. The +# real thing should probably be more flexible, and in C. +# + +# +# Memory locations. +# + .set MEM_STUB,0x600 # Real mode stub + .set MEM_ESP,0x1000 # New stack pointer + .set MEM_TBL,0x5000 # BTX page tables + .set MEM_ENTRY,0x9010 # BTX entry point + .set MEM_DATA,start+0x1000 # Data segment +# +# Segment selectors. +# + .set SEL_SCODE,0x8 # 4GB code + .set SEL_SDATA,0x10 # 4GB data + .set SEL_RCODE,0x18 # 64K code + .set SEL_RDATA,0x20 # 64K data +# +# Paging constants. +# + .set PAG_SIZ,0x1000 # Page size + .set PAG_ENT,0x4 # Page entry size +# +# Screen constants. +# + .set SCR_MAT,0x7 # Mode/attribute + .set SCR_COL,0x50 # Columns per row + .set SCR_ROW,0x19 # Rows per screen +# +# BIOS Data Area locations. +# + .set BDA_MEM,0x413 # Free memory + .set BDA_SCR,0x449 # Video mode + .set BDA_POS,0x450 # Cursor position +# +# Required by aout gas inadequacy. +# + .set SIZ_STUB,0x1a # Size of stub +# +# We expect to be loaded by boot2 at the origin defined in ./Makefile. +# + .globl start +# +# BTX program loader for ELF clients. +# +start: cld # String ops inc + movl $m_logo,%esi # Identify + call putstr # ourselves + movzwl BDA_MEM,%eax # Get base memory + shll $0xa,%eax # in bytes + movl %eax,%ebp # Base of user stack +ifdef(`BTXLDR_VERBOSE',` + movl $m_mem,%esi # Display + call hexout # amount of + call putstr # base memory +') + lgdt gdtdesc # Load new GDT +# +# Relocate caller's arguments. +# +ifdef('BTXLDR_VERBOSE',` + movl $m_esp,%esi # Display + movl %esp,%eax # caller + call hexout # stack + call putstr # pointer + movl $m_args,%esi # Format string + leal 0x4(%esp,1),%ebx # First argument + movl $0x6,%ecx # Count +start.1: movl (%ebx),%eax # Get argument and + addl $0x4,%ebx # bump pointer + call hexout # Display it + loop start.1 # Till done + call putstr # End message +') + movl $0x48,%ecx # Allocate space + subl %ecx,%ebp # for bootinfo + movl 0x18(%esp,1),%esi # Source: bootinfo + cmpl $0x0, %esi # If the bootinfo pointer + je start_null_bi # is null, don't copy it + movl %ebp,%edi # Destination + rep # Copy + movsb # it + movl %ebp,0x18(%esp,1) # Update pointer +ifdef(`BTXLDR_VERBOSE',` + movl $m_rel_bi,%esi # Display + movl %ebp,%eax # bootinfo + call hexout # relocation + call putstr # message +') +start_null_bi: movl $0x18,%ecx # Allocate space + subl %ecx,%ebp # for arguments + leal 0x4(%esp,1),%esi # Source + movl %ebp,%edi # Destination + rep # Copy + movsb # them +ifdef(`BTXLDR_VERBOSE',` + movl $m_rel_args,%esi # Display + movl %ebp,%eax # argument + call hexout # relocation + call putstr # message +') +# +# Set up BTX kernel. +# + movl $MEM_ESP,%esp # Set up new stack + movl $MEM_DATA,%ebx # Data segment + movl $m_vers,%esi # Display BTX + call putstr # version message + movb 0x5(%ebx),%al # Get major version + addb $'0',%al # Display + call putchr # it + movb $'.',%al # And a + call putchr # dot + movb 0x6(%ebx),%al # Get minor + xorb %ah,%ah # version + movb $0xa,%dl # Divide + divb %dl,%al # by 10 + addb $'0',%al # Display + call putchr # tens + movb %ah,%al # Get units + addb $'0',%al # Display + call putchr # units + call putstr # End message + movl %ebx,%esi # BTX image + movzwl 0x8(%ebx),%edi # Compute + orl $PAG_SIZ/PAG_ENT-1,%edi # the + incl %edi # BTX + shll $0x2,%edi # load + addl $MEM_TBL,%edi # address + pushl %edi # Save load address + movzwl 0xa(%ebx),%ecx # Image size +ifdef(`BTXLDR_VERBOSE',` + pushl %ecx # Save image size +') + rep # Relocate + movsb # BTX + movl %esi,%ebx # Keep place +ifdef(`BTXLDR_VERBOSE',` + movl $m_rel_btx,%esi # Restore + popl %eax # parameters + call hexout # and +') + popl %ebp # display +ifdef(`BTXLDR_VERBOSE',` + movl %ebp,%eax # the + call hexout # relocation + call putstr # message +') + addl $PAG_SIZ,%ebp # Display +ifdef(`BTXLDR_VERBOSE',` + movl $m_base,%esi # the + movl %ebp,%eax # user + call hexout # base + call putstr # address +') +# +# Set up ELF-format client program. +# + cmpl $0x464c457f,(%ebx) # ELF magic number? + je start.3 # Yes + movl $e_fmt,%esi # Display error + call putstr # message +start.2: jmp start.2 # Hang +start.3: +ifdef(`BTXLDR_VERBOSE',` + movl $m_elf,%esi # Display ELF + call putstr # message + movl $m_segs,%esi # Format string +') + movl $0x2,%edi # Segment count + movl 0x1c(%ebx),%edx # Get e_phoff + addl %ebx,%edx # To pointer + movzwl 0x2c(%ebx),%ecx # Get e_phnum +start.4: cmpl $0x1,(%edx) # Is p_type PT_LOAD? + jne start.6 # No +ifdef(`BTXLDR_VERBOSE',` + movl 0x4(%edx),%eax # Display + call hexout # p_offset + movl 0x8(%edx),%eax # Display + call hexout # p_vaddr + movl 0x10(%edx),%eax # Display + call hexout # p_filesz + movl 0x14(%edx),%eax # Display + call hexout # p_memsz + call putstr # End message +') + pushl %esi # Save + pushl %edi # working + pushl %ecx # registers + movl 0x4(%edx),%esi # Get p_offset + addl %ebx,%esi # as pointer + movl 0x8(%edx),%edi # Get p_vaddr + addl %ebp,%edi # as pointer + movl 0x10(%edx),%ecx # Get p_filesz + rep # Set up + movsb # segment + movl 0x14(%edx),%ecx # Any bytes + subl 0x10(%edx),%ecx # to zero? + jz start.5 # No + xorb %al,%al # Then + rep # zero + stosb # them +start.5: popl %ecx # Restore + popl %edi # working + popl %esi # registers + decl %edi # Segments to do + je start.7 # If none +start.6: addl $0x20,%edx # To next entry + loop start.4 # Till done +start.7: +ifdef(`BTXLDR_VERBOSE',` + movl $m_done,%esi # Display done + call putstr # message +') + movl $start.8,%esi # Real mode stub + movl $MEM_STUB,%edi # Destination + movl $start.9-start.8,%ecx # Size + rep # Relocate + movsb # it + ljmp $SEL_RCODE,$MEM_STUB # To 16-bit code + .code16 +start.8: xorw %ax,%ax # Data + movb $SEL_RDATA,%al # selector + movw %ax,%ss # Reload SS + movw %ax,%ds # Reset + movw %ax,%es # other + movw %ax,%fs # segment + movw %ax,%gs # limits + movl %cr0,%eax # Switch to + decw %ax # real + movl %eax,%cr0 # mode + ljmp $0,$MEM_ENTRY # Jump to BTX entry point +start.9: + .code32 +# +# Output message [ESI] followed by EAX in hex. +# +hexout: pushl %eax # Save + call putstr # Display message + popl %eax # Restore + pushl %esi # Save + pushl %edi # caller's + movl $buf,%edi # Buffer + pushl %edi # Save + call hex32 # To hex + xorb %al,%al # Terminate + stosb # string + popl %esi # Restore +hexout.1: lodsb # Get a char + cmpb $'0',%al # Leading zero? + je hexout.1 # Yes + testb %al,%al # End of string? + jne hexout.2 # No + decl %esi # Undo +hexout.2: decl %esi # Adjust for inc + call putstr # Display hex + popl %edi # Restore + popl %esi # caller's + ret # To caller +# +# Output zero-terminated string [ESI] to the console. +# +putstr.0: call putchr # Output char +putstr: lodsb # Load char + testb %al,%al # End of string? + jne putstr.0 # No + ret # To caller +# +# Output character AL to the console. +# +putchr: pusha # Save + xorl %ecx,%ecx # Zero for loops + movb $SCR_MAT,%ah # Mode/attribute + movl $BDA_POS,%ebx # BDA pointer + movw (%ebx),%dx # Cursor position + movl $0xb8000,%edi # Regen buffer (color) + cmpb %ah,BDA_SCR-BDA_POS(%ebx) # Mono mode? + jne putchr.1 # No + xorw %di,%di # Regen buffer (mono) +putchr.1: cmpb $0xa,%al # New line? + je putchr.2 # Yes + xchgl %eax,%ecx # Save char + movb $SCR_COL,%al # Columns per row + mulb %dh # * row position + addb %dl,%al # + column + adcb $0x0,%ah # position + shll %eax # * 2 + xchgl %eax,%ecx # Swap char, offset + movw %ax,(%edi,%ecx,1) # Write attr:char + incl %edx # Bump cursor + cmpb $SCR_COL,%dl # Beyond row? + jb putchr.3 # No +putchr.2: xorb %dl,%dl # Zero column + incb %dh # Bump row +putchr.3: cmpb $SCR_ROW,%dh # Beyond screen? + jb putchr.4 # No + leal 2*SCR_COL(%edi),%esi # New top line + movw $(SCR_ROW-1)*SCR_COL/2,%cx # Words to move + rep # Scroll + movsl # screen + movb $' ',%al # Space + movb $SCR_COL,%cl # Columns to clear + rep # Clear + stosw # line + movb $SCR_ROW-1,%dh # Bottom line +putchr.4: movw %dx,(%ebx) # Update position + popa # Restore + ret # To caller +# +# Convert EAX, AX, or AL to hex, saving the result to [EDI]. +# +hex32: pushl %eax # Save + shrl $0x10,%eax # Do upper + call hex16 # 16 + popl %eax # Restore +hex16: call hex16.1 # Do upper 8 +hex16.1: xchgb %ah,%al # Save/restore +hex8: pushl %eax # Save + shrb $0x4,%al # Do upper + call hex8.1 # 4 + popl %eax # Restore +hex8.1: andb $0xf,%al # Get lower 4 + cmpb $0xa,%al # Convert + sbbb $0x69,%al # to hex + das # digit + orb $0x20,%al # To lower case + stosb # Save char + ret # (Recursive) + + .data + .p2align 4 +# +# Global descriptor table. +# +gdt: .word 0x0,0x0,0x0,0x0 # Null entry + .word 0xffff,0x0,0x9a00,0xcf # SEL_SCODE + .word 0xffff,0x0,0x9200,0xcf # SEL_SDATA + .word 0xffff,0x0,0x9a00,0x0 # SEL_RCODE + .word 0xffff,0x0,0x9200,0x0 # SEL_RDATA +gdt.1: +gdtdesc: .word gdt.1-gdt-1 # Limit + .long gdt # Base +# +# Messages. +# +m_logo: .asciz " \nBTX loader 1.00 " +m_vers: .asciz "BTX version is \0\n" +e_fmt: .asciz "Error: Client format not supported\n" +ifdef(`BTXLDR_VERBOSE',` +m_mem: .asciz "Starting in protected mode (base mem=\0)\n" +m_esp: .asciz "Arguments passed (esp=\0):\n" +m_args: .asciz"\n" +m_rel_bi: .asciz "Relocated bootinfo (size=48) to \0\n" +m_rel_args: .asciz "Relocated arguments (size=18) to \0\n" +m_rel_btx: .asciz "Relocated kernel (size=\0) to \0\n" +m_base: .asciz "Client base address is \0\n" +m_elf: .asciz "Client format is ELF\n" +m_segs: .asciz "text segment: offset=" + .asciz " vaddr=" + .asciz " filesz=" + .asciz " memsz=\0\n" + .asciz "data segment: offset=" + .asciz " vaddr=" + .asciz " filesz=" + .asciz " memsz=\0\n" +m_done: .asciz "Loading complete\n" +') +# +# Uninitialized data area. +# +buf: # Scratch buffer diff --git a/src/sys/boot/btx/lib/Makefile b/src/sys/boot/btx/lib/Makefile new file mode 100644 index 0000000..b2e47b8 --- /dev/null +++ b/src/sys/boot/btx/lib/Makefile @@ -0,0 +1,16 @@ +# $FreeBSD: src/sys/boot/i386/btx/lib/Makefile,v 1.3.2.1 2002/07/19 18:46:28 ru Exp $ + +OBJS= btxcsu.o btxsys.o btxv86.o +AFLAGS+= #-elf +LDFLAGS+= #-elf +CLEANFILES+= crt0.o ${OBJS} + +all: crt0.o + +crt0.o: ${OBJS} + ${LD} ${LDFLAGS} -i -o ${.TARGET} ${OBJS} + +.include + +.s.o: + ${AS} ${AFLAGS} -o ${.TARGET} ${.IMPSRC} diff --git a/src/sys/boot/btx/lib/btxcsu.s b/src/sys/boot/btx/lib/btxcsu.s new file mode 100644 index 0000000..119fda6 --- /dev/null +++ b/src/sys/boot/btx/lib/btxcsu.s @@ -0,0 +1,43 @@ +# +# Copyright (c) 1998 Robert Nordier +# All rights reserved. +# +# Redistribution and use in source and binary forms are freely +# permitted provided that the above copyright notice and this +# paragraph and the following disclaimer are duplicated in all +# such forms. +# +# This software is provided "AS IS" and without any express or +# implied warranties, including, without limitation, the implied +# warranties of merchantability and fitness for a particular +# purpose. +# + +# $FreeBSD: src/sys/boot/i386/btx/lib/btxcsu.s,v 1.3 1999/08/28 00:40:07 peter Exp $ + +# +# BTX C startup code (ELF). +# + +# +# Globals. +# + .global _start +# +# Constants. +# + .set ARGADJ,0xfa0 # Argument adjustment +# +# Client entry point. +# +_start: movl %eax,__base # Set base address + movl %esp,%eax # Set + addl $ARGADJ,%eax # argument + movl %eax,__args # pointer + call main # Invoke client main() + call exit # Invoke client exit() +# +# Data. +# + .comm __base,4 # Client base address + .comm __args,4 # Client arguments diff --git a/src/sys/boot/btx/lib/btxsys.s b/src/sys/boot/btx/lib/btxsys.s new file mode 100644 index 0000000..6bca740 --- /dev/null +++ b/src/sys/boot/btx/lib/btxsys.s @@ -0,0 +1,40 @@ +# +# Copyright (c) 1998 Robert Nordier +# All rights reserved. +# +# Redistribution and use in source and binary forms are freely +# permitted provided that the above copyright notice and this +# paragraph and the following disclaimer are duplicated in all +# such forms. +# +# This software is provided "AS IS" and without any express or +# implied warranties, including, without limitation, the implied +# warranties of merchantability and fitness for a particular +# purpose. +# + +# $FreeBSD: src/sys/boot/i386/btx/lib/btxsys.s,v 1.2 1999/08/28 00:40:07 peter Exp $ + +# +# BTX system calls. +# + +# +# Globals. +# + .global __exit + .global __exec +# +# Constants. +# + .set INT_SYS,0x30 # Interrupt number +# +# System call: exit +# +__exit: xorl %eax,%eax # BTX system + int $INT_SYS # call 0x0 +# +# System call: exec +# +__exec: movl $0x1,%eax # BTX system + int $INT_SYS # call 0x1 diff --git a/src/sys/boot/btx/lib/btxv86.h b/src/sys/boot/btx/lib/btxv86.h new file mode 100644 index 0000000..1ef0712 --- /dev/null +++ b/src/sys/boot/btx/lib/btxv86.h @@ -0,0 +1,63 @@ +/* + * Copyright (c) 1998 Robert Nordier + * All rights reserved. + * + * Redistribution and use in source and binary forms are freely + * permitted provided that the above copyright notice and this + * paragraph and the following disclaimer are duplicated in all + * such forms. + * + * This software is provided "AS IS" and without any express or + * implied warranties, including, without limitation, the implied + * warranties of merchantability and fitness for a particular + * purpose. + */ + +/* + * $FreeBSD: src/sys/boot/i386/btx/lib/btxv86.h,v 1.5 1999/08/28 00:40:08 peter Exp $ + */ + +#ifndef _BTXV86_H_ +#define _BTXV86_H_ + +#include + +#define V86_ADDR 0x10000 /* Segment:offset address */ +#define V86_CALLF 0x20000 /* Emulate far call */ +#define V86_FLAGS 0x40000 /* Return flags */ + +struct __v86 { + uint32_t ctl; /* Control flags */ + uint32_t addr; /* Interrupt number or address */ + uint32_t es; /* V86 ES register */ + uint32_t ds; /* V86 DS register */ + uint32_t fs; /* V86 FS register */ + uint32_t gs; /* V86 GS register */ + uint32_t eax; /* V86 EAX register */ + uint32_t ecx; /* V86 ECX register */ + uint32_t edx; /* V86 EDX register */ + uint32_t ebx; /* V86 EBX register */ + uint32_t efl; /* V86 eflags register */ + uint32_t ebp; /* V86 EBP register */ + uint32_t esi; /* V86 ESI register */ + uint32_t edi; /* V86 EDI register */ +}; + +extern struct __v86 __v86; /* V86 interface structure */ +void __v86int(void); + +#define v86 __v86 +#define v86int __v86int + +extern u_int32_t __base; +extern u_int32_t __args; + +#define PTOV(pa) ((caddr_t)(pa) - __base) +#define VTOP(va) ((vm_offset_t)(va) + __base) +#define VTOPSEG(va) (u_int16_t)(VTOP((caddr_t)va) >> 4) +#define VTOPOFF(va) (u_int16_t)(VTOP((caddr_t)va) & 0xf) + +void __exit(int) __attribute__((__noreturn__)); +void __exec(caddr_t, ...); + +#endif /* !_BTXV86_H_ */ diff --git a/src/sys/boot/btx/lib/btxv86.s b/src/sys/boot/btx/lib/btxv86.s new file mode 100644 index 0000000..6d6af19 --- /dev/null +++ b/src/sys/boot/btx/lib/btxv86.s @@ -0,0 +1,85 @@ +# +# Copyright (c) 1998 Robert Nordier +# All rights reserved. +# +# Redistribution and use in source and binary forms are freely +# permitted provided that the above copyright notice and this +# paragraph and the following disclaimer are duplicated in all +# such forms. +# +# This software is provided "AS IS" and without any express or +# implied warranties, including, without limitation, the implied +# warranties of merchantability and fitness for a particular +# purpose. +# + +# $FreeBSD: src/sys/boot/i386/btx/lib/btxv86.s,v 1.3 1999/08/28 00:40:08 peter Exp $ + +# +# BTX V86 interface. +# + +# +# Globals. +# + .global __v86int +# +# Fields in V86 interface structure. +# + .set V86_CTL,0x0 # Control flags + .set V86_ADDR,0x4 # Int number/address + .set V86_ES,0x8 # V86 ES + .set V86_DS,0xc # V86 DS + .set V86_FS,0x10 # V86 FS + .set V86_GS,0x14 # V86 GS + .set V86_EAX,0x18 # V86 EAX + .set V86_ECX,0x1c # V86 ECX + .set V86_EDX,0x20 # V86 EDX + .set V86_EBX,0x24 # V86 EBX + .set V86_EFL,0x28 # V86 eflags + .set V86_EBP,0x2c # V86 EBP + .set V86_ESI,0x30 # V86 ESI + .set V86_EDI,0x34 # V86 EDI +# +# Other constants. +# + .set INT_V86,0x31 # Interrupt number + .set SIZ_V86,0x38 # Size of V86 structure +# +# V86 interface function. +# +__v86int: popl __v86ret # Save return address + pushl $__v86 # Push pointer + call __v86_swap # Load V86 registers + int $INT_V86 # To BTX + call __v86_swap # Load user registers + addl $0x4,%esp # Discard pointer + pushl __v86ret # Restore return address + ret # To user +# +# Swap V86 and user registers. +# +__v86_swap: xchgl %ebp,0x4(%esp,1) # Swap pointer, EBP + xchgl %eax,V86_EAX(%ebp) # Swap EAX + xchgl %ecx,V86_ECX(%ebp) # Swap ECX + xchgl %edx,V86_EDX(%ebp) # Swap EDX + xchgl %ebx,V86_EBX(%ebp) # Swap EBX + pushl %eax # Save + pushf # Put eflags + popl %eax # in EAX + xchgl %eax,V86_EFL(%ebp) # Swap + pushl %eax # Put EAX + popf # in eflags + movl 0x8(%esp,1),%eax # Load EBP + xchgl %eax,V86_EBP(%ebp) # Swap + movl %eax,0x8(%esp,1) # Save EBP + popl %eax # Restore + xchgl %esi,V86_ESI(%ebp) # Swap ESI + xchgl %edi,V86_EDI(%ebp) # Swap EDI + xchgl %ebp,0x4(%esp,1) # Swap pointer, EBP + ret # To caller +# +# V86 interface structure. +# + .comm __v86,SIZ_V86 + .comm __v86ret,4 diff --git a/src/sys/boot/mbr/Makefile b/src/sys/boot/mbr/Makefile new file mode 100644 index 0000000..2645ba9 --- /dev/null +++ b/src/sys/boot/mbr/Makefile @@ -0,0 +1,51 @@ +# $Id$ +# Application Makefile (C) 2002 The UbixOS Project + +# Include Global 'Source' Options +include ../../Makefile.inc +include ../Makefile.inc + +#Compiler Flags +CFLAGS = -I../../include -fno-builtin + +#Linker +LD = ld + +#Binary File Name +BINARY = mbr + +#Delete Program +REMOVE = rm -f + +#Objects +OBJS = mbr.o +ORG = 0x600 + +#Startup File +#STARTUP = ../../../lib/ubix/startup.o + +# Link The Binary +$(BINARY) : $(OBJS) +# $(CC) -O -pipe -ffreestanding -mpreferred-stack-boundary=2 -N -e start -Ttext $(ORG) -nostdlib -o $(BINARY).out $(OBJS) + $(CC) -O -pipe -ffreestanding -mpreferred-stack-boundary=2 -N -e start -Wl,-Ttext,$(ORG) -nostdlib -o $(BINARY).out $(OBJS) + objcopy -S -O binary $(BINARY).out $(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) $(BINARY) $(BINARY).out diff --git a/src/sys/boot/mbr/mbr.s b/src/sys/boot/mbr/mbr.s new file mode 100644 index 0000000..bd75853 --- /dev/null +++ b/src/sys/boot/mbr/mbr.s @@ -0,0 +1,157 @@ +# +# Copyright (c) 1999 Robert Nordier +# All rights reserved. +# +# Redistribution and use in source and binary forms are freely +# permitted provided that the above copyright notice and this +# paragraph and the following disclaimer are duplicated in all +# such forms. +# +# This software is provided "AS IS" and without any express or +# implied warranties, including, without limitation, the implied +# warranties of merchantability and fitness for a particular +# purpose. +# + +# $FreeBSD: src/sys/boot/i386/mbr/mbr.s,v 1.6 2000/06/27 20:04:10 jhb Exp $ + +# A 512 byte MBR boot manager that simply boots the active partition. + + .set LOAD,0x7c00 # Load address + .set EXEC,0x600 # Execution address + .set PT_OFF,0x1be # Partition table + .set MAGIC,0x45 # Magic: bootable + + .set NHRDRV,0x475 # Number of hard drives + + .globl start # Entry point + .code16 + +# +# Setup the segment registers for flat addressing and setup the stack. +# +start: cld # String ops inc + xorw %ax,%ax # Zero + movw %ax,%es # Address + movw %ax,%ds # data + movw %ax,%ss # Set up + movw $LOAD,%sp # stack +# +# Relocate ourself to a lower address so that we are out of the way when +# we load in the bootstrap from the partition to boot. +# + movw $main-EXEC+LOAD,%si # Source + movw $main,%di # Destination + movw $0x200-(main-start),%cx # Byte count + rep # Relocate + movsb # code +# +# Jump to the relocated code. +# + jmp main-LOAD+EXEC # To relocated code +# +# Scan the partition table looking for an active entry. Note that %ch is +# zero from the repeated string instruction above. We save the offset of +# the active partition in %si and scan the entire table to ensure that only +# one partition is marked active. +# +main: xorw %si,%si # No active partition + movw $partbl,%bx # Partition table + movb $0x4,%cl # Number of entries +main.1: cmpb %ch,(%bx) # Null entry? + je main.2 # Yes + jg err_pt # If 0x1..0x7f + testw %si,%si # Active already found? + jnz err_pt # Yes + movw %bx,%si # Point to active +main.2: addb $0x10,%bl # Till + loop main.1 # done + testw %si,%si # Active found? + jnz main.3 # Yes + int $0x18 # BIOS: Diskless boot +# +# Ok, we've found a possible active partition. Check to see that the drive +# is a valid hard drive number. +# +main.3: cmpb $0x80,%dl # Drive valid? + jb main.4 # No + movb NHRDRV,%dh # Calculate the highest + addb $0x80,%dh # drive number available + cmpb %dh,%dl # Within range? + jb main.5 # Yes +main.4: movb (%si),%dl # Load drive +# +# Ok, now that we have a valid drive and partition entry, load the CHS from +# the partition entry and read the sector from the disk. +# +main.5: movw %sp,%di # Save stack pointer + movb 0x1(%si),%dh # Load head + movw 0x2(%si),%cx # Load cylinder:sector + movw $LOAD,%bx # Transfer buffer + cmpb $0xff,%dh # Might we need to use LBA? + jnz main.7 # No. + cmpw $0xffff,%cx # Do we need to use LBA? + jnz main.7 # No. + pushw %cx # Save %cx + pushw %bx # Save %bx + movw $0x55aa,%bx # Magic + movb $0x41,%ah # BIOS: EDD extensions + int $0x13 # present? + jc main.6 # No. + cmpw $0xaa55,%bx # Magic ok? + jne main.6 # No. + testb $0x1,%cl # Packet mode present? + jz main.6 # No. + popw %bx # Restore %bx + pushl $0x0 # Set the LBA + pushl 0x8(%si) # address + pushw %es # Set the address of + pushw %bx # the transfer buffer + pushw $0x1 # Read 1 sector + pushw $0x10 # Packet length + movw %sp,%si # Packer pointer + movw $0x4200,%ax # BIOS: LBA Read from disk + jmp main.8 # Skip the CHS setup +main.6: popw %bx # Restore %bx + popw %cx # Restore %cx +main.7: movw $0x201,%ax # BIOS: Read from disk +main.8: int $0x13 # Call the BIOS + movw %di,%sp # Restore stack + jc err_rd # If error +# +# Now that we've loaded the bootstrap, check for the 0xaa55 signature. If it +# is present, execute the bootstrap we just loaded. +# + cmpw $MAGIC,0x1fe(%bx) # Bootable? + jne err_os # No + jmp *%bx # Invoke bootstrap +# +# Various error message entry points. +# +err_pt: movw $msg_pt,%si # "Invalid partition + jmp putstr # table" + +err_rd: movw $msg_rd,%si # "Error loading + jmp putstr # operating system" + +err_os: movw $msg_os,%si # "Missing operating + jmp putstr # system" +# +# Output an ASCIZ string to the console via the BIOS. +# +putstr.0: movw $0x7,%bx # Page:attribute + movb $0xe,%ah # BIOS: Display + int $0x10 # character +putstr: lodsb # Get character + testb %al,%al # End of string? + jnz putstr.0 # No +putstr.1: jmp putstr.1 # Await reset + +msg_pt: .asciz "Invalid partition table" +msg_rd: .asciz "Error loading operating system" +msg_os: .asciz "Missing operating system" + + .org PT_OFF + +partbl: .fill 0x10,0x4,0x0 # Partition table + .word MAGIC # Magic number diff --git a/src/sys/compile/Makefile b/src/sys/compile/Makefile new file mode 100644 index 0000000..cd5bdc9 --- /dev/null +++ b/src/sys/compile/Makefile @@ -0,0 +1,38 @@ +# $Id$ +# Kernel Makefile (C) 2002 The UbixOS Project + +# Include Global 'Source' Options +include ../../Makefile.inc +include ../Makefile.inc + +#Objects +OBJS = null.o + +#Kernel Parts +KPARTS = ../init/*.o ../sys/*.o ../vmm/*.o ../lib/*.o ../kernel/*.o ../isa/*.o ../vfs/*.o ../ubixfs/*.o ../pci/*.o ../sde/*.o ../devfs/*.o ../net/core/*.o ../net/net/*.o ../net/api/*.o ../net/netif/*.o +#../graphics/*.o ../ld/*.o -Ttext 0x30000 -Tdata 0x34000 + +# Link the kernel statically with fixed text+data address @1M +$(KERNEL) : $(OBJS) + $(LD) -nobuiltin -o $@ $(OBJS) $(KPARTS) -Ttext 0x30000 + /usr/bin/strip $@ + +# Compile the source files +.cc.o: + $(CXX) ${CFLAGS} -Wall -fomit-frame-pointer -O -I../include -c -o $@ $< + +.cc.s: + $(CXX) ${CFLAGS} -Wall -fomit-frame-pointer -O -I../include -S -o $@ $< + +.c.o: + $(CC) ${CFLAGS} -Wall -O -I../include -c -o $@ $< + +.c.s: + $(CC) ${CFLAGS} -Wall -fomit-frame-pointer -O -I../include -S -o $@ $< + +.S.o: + $(CC) ${CFLAGS} -Wall -fomit-frame-pointer -c -o $@ $< + +# Clean up the junk +clean: + $(REMOVE) $(OBJS) $(KERNEL) null.c diff --git a/src/sys/devfs/Makefile b/src/sys/devfs/Makefile new file mode 100644 index 0000000..c94fb69 --- /dev/null +++ b/src/sys/devfs/Makefile @@ -0,0 +1,34 @@ +# (C) 2002 The UbixOS Project +# $Id$ + +# Include Global 'Source' Options +include ../../Makefile.inc + +CFLAGS = -fno-builtin + +# Linker +LINKER = ld + +# Remove +REMOVE = rm -fr + +# Objects +OBJS = devfs.o + +all: $(OBJS) + +# Compile Types +.cc.o: + $(CXX) ${CFLAGS} -Wall -fomit-frame-pointer -O -I../include -c -o $@ $< +.cc.s: + $(CXX) ${CFLAGS} -Wall -fomit-frame-pointer -O -I../include -S -o $@ $< +.c.o: + $(CC) ${CFLAGS} -Wall -fomit-frame-pointer -O -I../include -c -o $@ $< +.c.s: + $(CC) ${CFLAGS} -Wall -fomit-frame-pointer -O -I../include -S -o $@ $< +.S.o: + $(CC) ${CFLAGS} -Wall -fomit-frame-pointer -c -o $@ $< + +# Clean up the junk +clean: + $(REMOVE) $(OBJS) diff --git a/src/sys/devfs/devfs.c b/src/sys/devfs/devfs.c new file mode 100644 index 0000000..1992eda --- /dev/null +++ b/src/sys/devfs/devfs.c @@ -0,0 +1,199 @@ +/***************************************************************************************** + 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. + + $Log$ + Revision 1.3 2004/04/13 16:36:33 reddawg + Changed our copyright, it is all now under a BSD-Style license + + + + $Id$ + +*****************************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include +#include + + +int devFSEnable() { + //Add DevFS i will + if (vfsRegisterFS(1,devFSInit,devFSRead,devFSWrite,devFSOpen,0x0,0x0,0x0,0x0) != 0x0) { + //sysErr(systemErr,"Unable To Enable DevFS"); + return(0x1); + } + //Return + mount(0x0,0x0,0x1,"devfs","rw"); // Mount Device File System + return(0x0); + } + +void devFSInit(struct mountPoints *mp) { + struct devFsInfo *fsInfo = 0x0; + mp->fsInfo = (struct devFsInfo *)kmalloc(sizeof(struct devFsInfo),-2); + + fsInfo = mp->fsInfo; + fsInfo->deviceList = 0x0; + + kprintf("DevFS Initialized\n"); + //Return + return; + } + +int devFSOpen(char *file,fileDescriptor *fd) { + struct devFsInfo *fsInfo = fd->mp->fsInfo; + struct devFsDevices *tmpDev = 0x0; + kprintf("Opening DevFS File [0x%X]\n",fsInfo->deviceList); + for (tmpDev = fsInfo->deviceList;tmpDev != 0x0;tmpDev = tmpDev->next) { + kprintf("[%s][%s]\n",tmpDev->devName,file); + if (kstrcmp(tmpDev->devName,file) == 0x0) { + kprintf("fd->mode: %i\n",(fd->mode & 0x3)); + switch ((fd->mode & 0x3)) { + case 0: + case 1: + kprintf("Opened Device: [%s]\n",tmpDev->devName); + (void *)fd->start = tmpDev; + (void *)fd->size = 4096; + break; + default: + kprintf("Invalid File Mode\n"); + return(0x0); + break; + } + return(0x1); + } + } + return(0x0); + } + +/************************************************************************ + +Function: int readDevFS(fileDescriptor *fd,char *data,long offset,long size) +Description: Read File Into Data +Notes: + +************************************************************************/ +int devFSRead(fileDescriptor *fd,char *data,long offset,long size) { + int i = 0x0,x = 0x0; + uInt32 sectors = 0x0; + uInt16 diff = 0x0; + struct driveDriver *drive = 0x0; + struct devFsDevices *tmpDev = (void *)fd->start; + + kprintf("[0x%X]\n",tmpDev->devMajor); + drive = findDrive(tmpDev->devMajor); + kprintf("[0x%X][0x%X]\n",drive,drive->driveInfoStruct); + + + kprintf("Reading From Device: [%s]\n",fd->fileName); + + sectors = ((size+511)/512); + diff = (offset - ((offset/512)*512)); + + kprintf("Sectors: [%i:%i]\n",sectors,diff); + + for (i=0x0;iread(drive->driveInfoStruct,i + (offset/512),1,fd->buffer); + for (x=0x0;x<(size - (i*512));x++) { + if (diff > 0) { + data[x] = fd->buffer[x + diff]; + } + else { + data[x] = fd->buffer[x]; + } + } + diff = 0x0; + data += 512; + } + + return(size); + } + +/************************************************************************ + +Function: int writeDevFS(fileDescriptor *fd,char *data,long offset,long size) +Description: Write Data Into File +Notes: + +************************************************************************/ +int devFSWrite(fileDescriptor *fd,char *data,long offset,long size) { + int i = 0x0,x = 0x0; + struct driveDriver *drive = 0x0; + struct devFsDevices *tmpDev = (void *)fd->start; + + kprintf("[0x%X]\n",tmpDev->devMajor); + drive = findDrive(tmpDev->devMajor); + kprintf("[0x%X][0x%X]\n",drive,drive->driveInfoStruct); + + kprintf("Writing To Device: [%s]\n",fd->fileName); + for (i=0x0;i<((size+511)/512);i++) { + drive->read(drive->driveInfoStruct,i + (offset/512),1,fd->buffer); + for (x=0x0;((x < 512) && ((x + (i * 512)) < size));x++) { + fd->buffer[x] = data[x]; + } + drive->write(drive->driveInfoStruct,i + (offset/512),1,fd->buffer); + data += 512; + } + return(size); + } + + +int devFsMkNod(char *name,uInt8 type,uInt16 major,uInt16 minor) { + struct mountPoints *mp = 0x0; + struct devFsInfo *fsInfo = 0x0; + struct devFsDevices *tmpDev = 0x0; + + mp = findMount("devfs"); + + if (mp == 0x0) { + kprintf("Error: Can't Find Mount Point\n"); + return(0x0); + } + + fsInfo = mp->fsInfo; + + tmpDev = (struct devFsDevices *)kmalloc(sizeof(struct devFsDevices),-2); + + tmpDev->devType = type; + tmpDev->devMajor = major; + tmpDev->devMinor = minor; + sprintf(tmpDev->devName,name); + kprintf("tmpDev->devName: [%s]\n",tmpDev->devName); + + tmpDev->next = fsInfo->deviceList; + tmpDev->prev = 0x0; + if (fsInfo->deviceList != 0x0) { + fsInfo->deviceList->prev = tmpDev; + } + + fsInfo->deviceList = tmpDev; + + return(0x1); + } + diff --git a/src/sys/include/devfs/devfs.h b/src/sys/include/devfs/devfs.h new file mode 100644 index 0000000..dd00da6 --- /dev/null +++ b/src/sys/include/devfs/devfs.h @@ -0,0 +1,51 @@ +/************************************************************************************** + Copyright (c) 2002 The DevOS 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 DevOS 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$ + +**************************************************************************************/ + +#ifndef _DEVFS_H +#define _DEVFS_H + +#include +#include +#include + +struct devFsDevices { + struct devFsDevices *next; + struct devFsDevices *prev; + uInt8 devType; + uInt16 devMajor; + uInt16 devMinor; + char devName[32]; + }; + +struct devFsInfo { + struct devFsDevices *deviceList; + }; + +int devFSOpen(char *file,fileDescriptor *fd); +void devFSInit(struct mountPoints *mp); +int devFSEnable(); +int devFSRead(fileDescriptor *fd,char *data,long offset,long size); +int devFSWrite(fileDescriptor *fd,char *data,long offset,long size); +int devFsMkNod(char *name,uInt8 type,uInt16 major,uInt16 minor); + +#endif diff --git a/src/sys/include/isa/8259.h b/src/sys/include/isa/8259.h new file mode 100644 index 0000000..2afdcaf --- /dev/null +++ b/src/sys/include/isa/8259.h @@ -0,0 +1,46 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#ifndef _8259_H +#define _8259_H + +#include + +#define mPic 0x20 // I/O for master PIC +#define mImr 0x21 // I/O for master IMR +#define sPic 0xA0 // I/O for slave PIC +#define sImr 0xA1 // I/O for slace IMR +#define eoi 0x20 // EOI command +#define icw1 0x11 // Cascade, Edge triggered +#define icw4 0x01 // 8088 mode +#define mVec 0x68 // Vector for master +#define sVec 0x70 // Vector for slave +#define ocw3Irr 0x0A // Read IRR +#define ocw3Isr 0x0B // Read ISR + +int init8259(); +void irqEnable(uInt16 irqNo); +void irqDisable(uInt16 irqNo); + +#endif + diff --git a/src/sys/include/isa/atkbd.h b/src/sys/include/isa/atkbd.h new file mode 100644 index 0000000..34355e1 --- /dev/null +++ b/src/sys/include/isa/atkbd.h @@ -0,0 +1,40 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#ifndef _KEYBOARD_H +#define _KEYBOARD_H + +#define shiftKey 1 +#define controlKey 2 +#define altKey 4 +#define ledNumlock 2 +#define ledScrolllock 1 +#define ledCapslock 4 + +int keyboardInit(); +void keyboardISR(); +void keyboardHandler(); +void setLED(); + +#endif + diff --git a/src/sys/include/isa/fdc.h b/src/sys/include/isa/fdc.h new file mode 100644 index 0000000..a036bc9 --- /dev/null +++ b/src/sys/include/isa/fdc.h @@ -0,0 +1,79 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#ifndef _FDC_H +#define _FDC_H + +#include + +typedef struct DrvGeom { + byte heads; + byte tracks; + byte spt; +} drvGeom; + + +#define fdcMsr (0x3f4) +#define fdcData (0x3f5) +#define fdcDir (0x3f7) +#define fdcCcr (0x3f7) +#define fdcDor (0x3f2) +#define fdcDrs (0x3f4) + +#define cmdWrite (0xc5) +#define cmdRead (0xe6) +#define cmdSeek (0x0f) +#define cmdSensei (0x08) +#define cmdRecal (0x07) +#define cmdSpecify (0x03) + +#define dg144Heads 2 /* heads per drive (1.44M) */ +#define dg144Tracks 80 +#define dg144Spt 18 +#define dg144Gap3rw 0x1b +#define dg168Gap3rw 0x1c + + + +void fdcInit(); +void floppyIsr(); +void floppyIsrhndlr(); +void sendByte(int byte); +int getByte(); +bool fdcRw(int block,byte *blockBuffer,bool read,unsigned long numSectors); +void block2Hts(int block,int *head,int *track,int *sector); +void motorOn(void); +void motorOff(void); +bool seek(int track); +bool waitFdc(bool sensei); +int getByte(); +void sendByte(int byte); +void recalibrate(void); +void reset(void); +bool writeBlock(int block,byte *blockBuffer, unsigned long numSectors); +bool readBlock(int block,byte *blockBuffer, unsigned long numSectors); +void fdcWrite(void *info,long startSector,long sectorCount,void *baseAddr); +void fdcRead(void *info,long startSector,long sectorCount,void *baseAddr); + +#endif + diff --git a/src/sys/include/isa/ne2k.h b/src/sys/include/isa/ne2k.h new file mode 100644 index 0000000..354d35d --- /dev/null +++ b/src/sys/include/isa/ne2k.h @@ -0,0 +1,163 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#ifndef _NE2K_H +#define _NE2K_H + +#include +#include + +#define ether_addr ether_addr_t +typedef struct dp_rcvhdr +{ + uInt8 dr_status; /* Copy of rsr */ + uInt8 dr_next; /* Pointer to next packet */ + uInt8 dr_rbcl; /* Receive Byte Count Low */ + uInt8 dr_rbch; /* Receive Byte Count High */ +} dp_rcvhdr_t; + +typedef union etheraddr { + unsigned char bytes[6]; /* byteorder safe initialization */ + unsigned short shorts[3]; /* force 2-byte alignment */ +} ether_addr; + +#define RSR_FO 0x08 +#define RSR_PRX 0x01 +#define DEF_ENABLED 0x200 + +#define OK 0 + + +#define startPage 0x4C +#define stopPage 0x80 + + +#define NE_CMD 0x00 +#define NE_PSTART 0x01 +#define NE_PSTOP 0x02 +#define NE_BNRY 0x03 +#define NE_TPSR 0x04 +#define NE_ISR 0x07 +#define NE_CURRENT 0x07 +#define NE_RBCR0 0x0A +#define NE_RBCR1 0x0B +#define NE_RCR 0x0C +#define NE_TCR 0x0D +#define NE_DCR 0x0E +#define NE_IMR 0x0F + + +#define NE_DCR_WTS 0x01 +#define NE_DCR_LS 0x08 +#define NE_DCR_AR 0x10 +#define NE_DCR_FT1 0x40 +#define NE_DCR_FT0 0x20 + + + +#define E8390_STOP 0x01 +#define E8390_NODMA 0x20 +#define E8390_PAGE0 0x00 +#define E8390_PAGE1 0x40 +#define E8390_CMD 0x00 +#define E8390_START 0x02 +#define E8390_RREAD 0x08 +#define E8390_RWRITE 0x10 +#define E8390_RXOFF 0x20 +#define E8390_TXOFF 0x00 +#define E8390_RXCONFIG 0x04 +#define E8390_TXCONFIG 0x00 + +#define EN0_COUNTER0 0x0d +#define EN0_DCFG 0x0e +#define EN0_RCNTLO 0x0a +#define EN0_RCNTHI 0x0b +#define EN0_ISR 0x07 +#define EN0_IMR 0x0f +#define EN0_RSARLO 0x08 +#define EN0_RSARHI 0x09 +#define EN0_TPSR 0x04 +#define EN0_RXCR 0x0c +#define EN0_TXCR 0x0D +#define EN0_STARTPG 0x01 +#define EN0_STOPPG 0x02 +#define EN0_BOUNDARY 0x03 + +#define EN1_PHYS 0x01 +#define EN1_CURPAG 0x07 +#define EN1_MULT 0x08 + +#define NE1SM_START_PG 0x20 +#define NE1SM_STOP_PG 0x40 +#define NESM_START_PG 0x40 +#define NESM_STOP_PG 0x80 + +#define ENISR_ALL 0x3f + +#define ENDCFG_WTS 0x01 + +#define NE_DATAPORT 0x10 + +#define TX_2X_PAGES 12 +#define TX_1X_PAGES 6 +#define TX_PAGES (dev->priv->pingPong ? TX_2X_PAGES : TX_1X_PAGES) + + +#define DP_CURR 0x7 /* Current Page Register */ +#define DP_MAR0 0x8 /* Multicast Address Register 0 */ +#define DP_MAR1 0x9 /* Multicast Address Register 1 */ +#define DP_MAR2 0xA /* Multicast Address Register 2 */ +#define DP_MAR3 0xB /* Multicast Address Register 3 */ +#define DP_MAR4 0xC /* Multicast Address Register 4 */ +#define DP_MAR5 0xD /* Multicast Address Register 5 */ +#define DP_MAR6 0xE /* Multicast Address Register 6 */ +#define DP_MAR7 0xF /* Multicast Address Register 7 */ + +#define DP_CNTR0 0xD /* Tally Counter 0 */ +#define DP_CNTR1 0xE /* Tally Counter 1 */ +#define DP_CNTR2 0xF /* Tally Counter 2 */ + + +#define DP_PAGESIZE 256 + +extern char *nicPacket; +extern uInt32 packetLength; + + +int ne2kInit(uInt32); +int ne2kProbe(int,struct device *); +int ne2kDevInit(struct device *); +void NS8390_init(struct device *dev,int startp); + +void ne2kISR(); +void ne2kHandler(); + +int NICtoPC(struct device *dev,void *packet,int length,int nic_addr); +int PCtoNIC(struct device *dev,void *packet,int length); + +#endif + +/*** + END + ***/ + diff --git a/src/sys/include/isa/pit.h b/src/sys/include/isa/pit.h new file mode 100644 index 0000000..dfb1272 --- /dev/null +++ b/src/sys/include/isa/pit.h @@ -0,0 +1 @@ +int pitInit(int); diff --git a/src/sys/include/lib/bioscall.h b/src/sys/include/lib/bioscall.h new file mode 100644 index 0000000..bb8c40f --- /dev/null +++ b/src/sys/include/lib/bioscall.h @@ -0,0 +1,9 @@ +#include + +#define EFLAG_TF 0x100 +#define EFLAG_IF 0x200 +#define EFLAG_IOPL3 0x3000 +#define EFLAG_VM 0x20000 + +void biosCall(int biosInt,int eax,int ebx,int ecx,int edx,int esi,int edi,int es,int ds); +void bios16Code(); diff --git a/src/sys/include/lib/kmalloc.h b/src/sys/include/lib/kmalloc.h new file mode 100644 index 0000000..907793a --- /dev/null +++ b/src/sys/include/lib/kmalloc.h @@ -0,0 +1,65 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#ifndef _KMALLOC_H +#define _KMALLOC_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#define sysMalloc -2 +#define sysID -2 + +struct memDescriptor { + struct memDescriptor *prev; //4 + struct memDescriptor *next; //4 + void *baseAddr; //4 + uInt32 limit; //4 + uInt8 status; //1 + pidType pid; //4 + char reserved[11]; //11 + }; + +void kfree(void *baseAddr); +void *kmalloc(uInt32 len,pidType pid); +void initMalloc(pidType pid); +void *getEmptyDesc(); +void insertFreeDesc(struct memDescriptor *freeDesc); +void mergeMemBlocks(); +void kfreeProcess(pidType pid); + +extern struct memDescriptor *kernDesc; +extern struct memDescriptor *freeKernDesc; +extern struct memDescriptor *emptyKernDesc; + +extern int mallocLock; + +#ifdef __cplusplus +} +#endif + +#endif + diff --git a/src/sys/include/lib/kprint.h b/src/sys/include/lib/kprint.h new file mode 100644 index 0000000..9b40cc5 --- /dev/null +++ b/src/sys/include/lib/kprint.h @@ -0,0 +1,31 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#ifndef _KPRINT_H +#define _KPRINT_H + +int kprintf(const char *fmt, ...); + +extern int printOff; + +#endif diff --git a/src/sys/include/lib/kprintf.h b/src/sys/include/lib/kprintf.h new file mode 100644 index 0000000..55a7b19 --- /dev/null +++ b/src/sys/include/lib/kprintf.h @@ -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$ + +**************************************************************************************/ + +#ifndef _KPRINTF_H +#define _KPRINTF_H + +int kprintf(const char *fmt, ...); +int ogPrintf(char *); + +extern int printOff; +extern int ogprintOff; + +#endif + diff --git a/src/sys/include/lib/libcpp.h b/src/sys/include/lib/libcpp.h new file mode 100644 index 0000000..78f02c8 --- /dev/null +++ b/src/sys/include/lib/libcpp.h @@ -0,0 +1,9 @@ +#ifndef __LIBCPP_H +#define __LIBCPP_H + +void * operator new(unsigned size); +void operator delete(void * ptr); +void * operator new[](unsigned size); +void operator delete[](void * ptr); + +#endif diff --git a/src/sys/include/lib/string.h b/src/sys/include/lib/string.h new file mode 100644 index 0000000..472277e --- /dev/null +++ b/src/sys/include/lib/string.h @@ -0,0 +1,49 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#ifndef _STRING_H +#define _STRING_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +int kstrcmp(char *str1, char *str2); +int kstrncmp(const char * a, const char * b, size_t c); +void *kmemcpy(const void *dst, const void * src, size_t length); +void *kmemset(void * dst, int c, size_t length); +int kstrlen(const char * string); +int kmemcmp(const void * dst, const void * src, size_t length); +void kstrncpy(char * dest, const char * src, size_t size); +char *strtok(char *str, const char *sep); +char *strtok_r(char *str, const char *sep, char **last); + +int sprintf(char *buf,const char *fmt, ...); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/sys/include/math.h b/src/sys/include/math.h new file mode 100644 index 0000000..49afd00 --- /dev/null +++ b/src/sys/include/math.h @@ -0,0 +1,12 @@ +#ifndef __MATH_H +#define __MATH_H + +typedef long long int quad_t; +typedef unsigned long long int u_quad_t; + +double atan(double x); +double sqrt(double x); +u_quad_t __udivdi3(u_quad_t a,u_quad_t b); +quad_t __divdi3(quad_t a,quad_t b); + +#endif diff --git a/src/sys/include/net/api.h b/src/sys/include/net/api.h new file mode 100644 index 0000000..1d97411 --- /dev/null +++ b/src/sys/include/net/api.h @@ -0,0 +1,142 @@ +/* + * Copyright (c) 2001, Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce 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 Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (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 file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + * $Id$ + */ +#ifndef __LWIP_API_H__ +#define __LWIP_API_H__ + +#include "net/opt.h" +#include "net/pbuf.h" +#include "net/sys.h" + +#include "net/ipv4/ip.h" + +#include "net/udp.h" +#include "net/tcp.h" + +#include "net/err.h" + +#define NETCONN_NOCOPY 0x00 +#define NETCONN_COPY 0x01 + +enum netconn_type { + NETCONN_TCP, + NETCONN_UDP, + NETCONN_UDPLITE, + NETCONN_UDPNOCHKSUM +}; + +enum netconn_state { + NETCONN_NONE, + NETCONN_WRITE, + NETCONN_ACCEPT, + NETCONN_RECV, + NETCONN_CONNECT, + NETCONN_CLOSE +}; + +struct netbuf { + struct pbuf *p, *ptr; + struct ip_addr *fromaddr; + uInt16 fromport; + err_t err; +}; + +struct netconn { + enum netconn_type type; + enum netconn_state state; + union { + struct tcp_pcb *tcp; + struct udp_pcb *udp; + } pcb; + err_t err; + sys_mbox_t mbox; + sys_mbox_t recvmbox; + sys_mbox_t acceptmbox; + sys_sem_t sem; +}; + +/* Network buffer functions: */ +struct netbuf * netbuf_new (void); +void netbuf_delete (struct netbuf *buf); +void * netbuf_alloc (struct netbuf *buf, uInt16 size); +void netbuf_free (struct netbuf *buf); +void netbuf_ref (struct netbuf *buf, + void *dataptr, uInt16 size); +void netbuf_chain (struct netbuf *head, + struct netbuf *tail); + +uInt16 netbuf_len (struct netbuf *buf); +err_t netbuf_data (struct netbuf *buf, + void **dataptr, uInt16 *len); +Int8 netbuf_next (struct netbuf *buf); +void netbuf_first (struct netbuf *buf); + +void netbuf_copy (struct netbuf *buf, + void *dataptr, uInt16 len); +struct ip_addr * netbuf_fromaddr (struct netbuf *buf); +uInt16 netbuf_fromport (struct netbuf *buf); + +/* Network connection functions: */ +struct netconn * netconn_new (enum netconn_type type); +err_t netconn_delete (struct netconn *conn); +enum netconn_type netconn_type (struct netconn *conn); +err_t netconn_peer (struct netconn *conn, + struct ip_addr **addr, + uInt16 *port); +err_t netconn_addr (struct netconn *conn, + struct ip_addr **addr, + uInt16 *port); +err_t netconn_bind (struct netconn *conn, + struct ip_addr *addr, + uInt16 port); +err_t netconn_connect (struct netconn *conn, + struct ip_addr *addr, + uInt16 port); +err_t netconn_listen (struct netconn *conn); +struct netconn * netconn_accept (struct netconn *conn); +struct netbuf * netconn_recv (struct netconn *conn); +err_t netconn_send (struct netconn *conn, + struct netbuf *buf); +err_t netconn_write (struct netconn *conn, + void *dataptr, uInt16 size, + uInt8 copy); +err_t netconn_close (struct netconn *conn); + +err_t netconn_err (struct netconn *conn); + +void netbuf_copy_partial(struct netbuf *buf, void *dataptr, uInt16 len, uInt16 offset); + +#endif /* __LWIP_API_H__ */ + + diff --git a/src/sys/include/net/api_msg.h b/src/sys/include/net/api_msg.h new file mode 100644 index 0000000..2728f5f --- /dev/null +++ b/src/sys/include/net/api_msg.h @@ -0,0 +1,96 @@ +/* + * Copyright (c) 2001, Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce 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 Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (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 file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + * $Id$ + */ +#ifndef __LWIP_API_MSG_H__ +#define __LWIP_API_MSG_H__ + +#include "net/opt.h" +#include "net/pbuf.h" +#include "net/sys.h" + +#include "net/ipv4/ip.h" + +#include "net/udp.h" +#include "net/tcp.h" + +#include "net/api.h" + +enum api_msg_type { + API_MSG_NEWCONN, + API_MSG_DELCONN, + + API_MSG_BIND, + API_MSG_CONNECT, + + API_MSG_LISTEN, + API_MSG_ACCEPT, + + API_MSG_SEND, + API_MSG_RECV, + API_MSG_WRITE, + + API_MSG_CLOSE, + + API_MSG_MAX +}; + +struct api_msg_msg { + struct netconn *conn; + enum netconn_type conntype; + union { + struct pbuf *p; + struct { + struct ip_addr *ipaddr; + uInt16 port; + } bc; + struct { + void *dataptr; + uInt16 len; + unsigned char copy; + } w; + sys_mbox_t mbox; + uInt16 len; + } msg; +}; + +struct api_msg { + enum api_msg_type type; + struct api_msg_msg msg; +}; + +void api_msg_input(struct api_msg *msg); +void api_msg_post(struct api_msg *msg); + +#endif /* __LWIP_API_MSG_H__ */ + diff --git a/src/sys/include/net/arch.h b/src/sys/include/net/arch.h new file mode 100644 index 0000000..8be38c0 --- /dev/null +++ b/src/sys/include/net/arch.h @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2001, Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce 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 Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (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 file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + * $Id$ + */ +#ifndef __LWIP_ARCH_H__ +#define __LWIP_ARCH_H__ + +#ifndef LITTLE_ENDIAN +#define LITTLE_ENDIAN 1234 +#endif + +#ifndef BIG_ENDIAN +#define BIG_ENDIAN 4321 +#endif + +#include "arch/cpu.h" +#include "arch/cc.h" + +#ifndef PACK_STRUCT_BEGIN +#define PACK_STRUCT_BEGIN +#endif /* PACK_STRUCT_BEGIN */ + +#ifndef PACK_STRUCT_END +#define PACK_STRUCT_END +#endif /* PACK_STRUCT_END */ + +#ifndef PACK_STRUCT_FIELD +#define PACK_STRUCT_FIELD(x) x +#endif /* PACK_STRUCT_FIELD */ + +#endif /* __LWIP_ARCH_H__ */ diff --git a/src/sys/include/net/arch/cc.h b/src/sys/include/net/arch/cc.h new file mode 100644 index 0000000..a2f83a5 --- /dev/null +++ b/src/sys/include/net/arch/cc.h @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2001, Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce 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 Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (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 file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + * $Id$ + */ +#ifndef __ARCH_CC_H__ +#define __ARCH_CC_H__ + +#define PACK_STRUCT_FIELD(x) x __attribute__((packed)) +#define PACK_STRUCT_STRUCT __attribute__((packed)) +#define PACK_STRUCT_BEGIN +#define PACK_STRUCT_END + +#endif /* __ARCH_CC_H__ */ diff --git a/src/sys/include/net/arch/cpu.h b/src/sys/include/net/arch/cpu.h new file mode 100644 index 0000000..0a6d531 --- /dev/null +++ b/src/sys/include/net/arch/cpu.h @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2001, Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce 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 Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (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 file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + * $Id$ + */ +#ifndef __ARCH_CPU_H__ +#define __ARCH_CPU_H__ + +#ifndef BYTE_ORDER +#define BYTE_ORDER LITTLE_ENDIAN +#endif /* BYTE_ORDER */ + +#endif /* __ARCH_CPU_H__ */ diff --git a/src/sys/include/net/arch/init.h b/src/sys/include/net/arch/init.h new file mode 100644 index 0000000..0b5409d --- /dev/null +++ b/src/sys/include/net/arch/init.h @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2001, Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce 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 Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (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 file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + * $Id$ + */ +#ifndef __ARCH_INIT_H__ +#define __ARCH_INIT_H__ + +#define TCPIP_INIT_DONE(arg) sys_sem_signal(*(sys_sem_t *)arg) + +#endif /* __ARCH_INIT_H__ */ + + + + diff --git a/src/sys/include/net/arch/lib.h b/src/sys/include/net/arch/lib.h new file mode 100644 index 0000000..13d5446 --- /dev/null +++ b/src/sys/include/net/arch/lib.h @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2001, Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce 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 Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (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 file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + * $Id$ + */ +#ifndef __ARCH_LIB_H__ +#define __ARCH_LIB_H__ + +#ifndef _STRING_H_ +#ifndef _STRING_H +int strlen(const char *str); +int strncmp(const char *str1, const char *str2, int len); +void bcopy(const void *src, void *dest, int len); +void bzero(void *data, int n); +#endif /* _STRING_H */ +#endif /* _STRING_H_ */ + +#endif /* __ARCH_LIB_H__ */ diff --git a/src/sys/include/net/arch/perf.h b/src/sys/include/net/arch/perf.h new file mode 100644 index 0000000..9b47e5b --- /dev/null +++ b/src/sys/include/net/arch/perf.h @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2001, Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce 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 Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (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 file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + * $Id$ + */ +#ifndef __ARCH_PERF_H__ +#define __ARCH_PERF_H__ + +#include + +#ifdef PERF +#define PERF_START { \ + unsigned long __c1l, __c1h, __c2l, __c2h; \ + __asm__(".byte 0x0f, 0x31" : "=a" (__c1l), "=d" (__c1h)) +#define PERF_STOP(x) __asm__(".byte 0x0f, 0x31" : "=a" (__c2l), "=d" (__c2h)); \ + perf_print(__c1l, __c1h, __c2l, __c2h, x);} + +/*#define PERF_START do { \ + struct tms __perf_start, __perf_end; \ + times(&__perf_start) +#define PERF_STOP(x) times(&__perf_end); \ + perf_print_times(&__perf_start, &__perf_end, x);\ + } while(0)*/ +#else /* PERF */ +#define PERF_START /* null definition */ +#define PERF_STOP(x) /* null definition */ +#endif /* PERF */ + +void perf_print(unsigned long c1l, unsigned long c1h, + unsigned long c2l, unsigned long c2h, + char *key); + +void perf_print_times(struct tms *start, struct tms *end, char *key); + +void perf_init(char *fname); + +#endif /* __ARCH_PERF_H__ */ diff --git a/src/sys/include/net/arch/sys_arch.h b/src/sys/include/net/arch/sys_arch.h new file mode 100644 index 0000000..9ef598f --- /dev/null +++ b/src/sys/include/net/arch/sys_arch.h @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2001, Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce 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 Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (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 file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + * $Id$ + */ +#ifndef __ARCH_SYS_ARCH_H__ +#define __ARCH_SYS_ARCH_H__ + +#define SYS_MBOX_NULL NULL +#define SYS_SEM_NULL NULL + +struct sys_sem; +typedef struct sys_sem * sys_sem_t; + +struct sys_mbox; +typedef struct sys_mbox *sys_mbox_t; + +struct sys_thread; +typedef struct sys_thread * sys_thread_t; + +#endif /* __ARCH_SYS_ARCH_H__ */ + diff --git a/src/sys/include/net/debug.h b/src/sys/include/net/debug.h new file mode 100644 index 0000000..3d9899f --- /dev/null +++ b/src/sys/include/net/debug.h @@ -0,0 +1,139 @@ +/* + * Copyright (c) 2001, Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce 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 Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (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 file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + * $Id$ + */ +#ifndef __LWIP_DEBUG_H__ +#define __LWIP_DEBUG_H__ + +#ifdef LWIP_DEBUG + +#define ASSERT(x,y) if(!(y)) {printf("Assertion \"%s\" failed at line %d in %s\n", \ + x, __LINE__, __FILE__); fflush(NULL); abort();} + +/* These defines control the amount of debugging output: */ +#define MEM_TRACKING + +#define DEMO_DEBUG 1 + +#define ARP_DEBUG 0 + +#define NETIF_DEBUG 1 +#define PBUF_DEBUG 0 +#define DELIF_DEBUG 0 +#define DROPIF_DEBUG 0 +#define TUNIF_DEBUG 0 +#define UNIXIF_DEBUG 0 +#define TAPIF_DEBUG 0 + +#define API_LIB_DEBUG 0 +#define API_MSG_DEBUG 0 +#define SOCKETS_DEBUG 1 +#define ICMP_DEBUG 0 +#define INET_DEBUG 0 +#define IP_DEBUG 0 +#define IP_REASS_DEBUG 1 +#define MEM_DEBUG 0 +#define MEMP_DEBUG 0 +#define SYS_DEBUG 0 +#define TCP_DEBUG 0 +#define TCP_INPUT_DEBUG 0 +#define TCP_FR_DEBUG 0 +#define TCP_RTO_DEBUG 0 +#define TCP_REXMIT_DEBUG 0 +#define TCP_CWND_DEBUG 0 +#define TCP_WND_DEBUG 0 +#define TCP_OUTPUT_DEBUG 0 +#define TCP_RST_DEBUG 0 +#define TCP_QLEN_DEBUG 0 +#define UDP_DEBUG 0 +#define TCPIP_DEBUG 0 +#define TCPDUMP_DEBUG 0 +#define DHCP_DEBUG 1 + +#include +#define DEBUGF(debug, x) do { if(debug){ printf x; } } while(0) + + +#else /* LWIP_DEBUG */ + +/* DEBUG is not defined, so we define null macros for ASSERT and DEBUGF */ + +#define ASSERT(x,y) +#define DEBUGF(debug, x) + +/* And we define those to be zero: */ + +#define DEMO_DEBUG 0 +#define ARP_DEBUG 0 +#define NETIF_DEBUG 0 +#define PBUF_DEBUG 0 +#define DELIF_DEBUG 0 +#define DROPIF_DEBUG 0 +#define TUNIF_DEBUG 0 +#define UNIXIF_DEBUG 0 +#define TAPIF_DEBUG 0 +#define API_LIB_DEBUG 0 +#define API_MSG_DEBUG 0 +#define SOCKETS_DEBUG 0 +#define ICMP_DEBUG 0 +#define INET_DEBUG 0 +#define IP_DEBUG 0 +#define IP_REASS_DEBUG 0 +#define MEM_DEBUG 0 +#define MEMP_DEBUG 0 +#define SYS_DEBUG 0 +#define TCP_DEBUG 0 +#define TCP_INPUT_DEBUG 0 +#define TCP_FR_DEBUG 0 +#define TCP_RTO_DEBUG 0 +#define TCP_REXMIT_DEBUG 0 +#define TCP_CWND_DEBUG 0 +#define TCP_WND_DEBUG 0 +#define TCP_OUTPUT_DEBUG 0 +#define TCP_RST_DEBUG 0 +#define TCP_QLEN_DEBUG 0 +#define UDP_DEBUG 0 +#define TCPIP_DEBUG 0 +#define TCPDUMP_DEBUG 0 +#define DHCP_DEBUG 0 + +#endif /* LWIP_DEBUG */ + + +#endif /* __LWIP_DEBUG_H__ */ + + + + + + diff --git a/src/sys/include/net/def.h b/src/sys/include/net/def.h new file mode 100644 index 0000000..19e2289 --- /dev/null +++ b/src/sys/include/net/def.h @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2001, Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce 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 Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (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 file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + * $Id$ + */ +#ifndef __LWIP_DEF_H__ +#define __LWIP_DEF_H__ + +#define UMAX(a, b) ((a) > (b) ? (a) : (b)) + +#ifndef NULL +#define NULL ((void *)0) +#endif + +#include "arch/lib.h" + +#endif /* __LWIP_DEF_H__ */ + diff --git a/src/sys/include/net/err.h b/src/sys/include/net/err.h new file mode 100644 index 0000000..ddaba06 --- /dev/null +++ b/src/sys/include/net/err.h @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2001, Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce 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 Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (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 file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + * $Id$ + */ +#ifndef __LWIP_ERR_H__ +#define __LWIP_ERR_H__ + +#include + +#include "net/debug.h" + +#include "net/arch/cc.h" + +typedef Int8 err_t; + +/* Definitions for error constants. */ + +#define ERR_OK 0 /* No error, everything OK. */ +#define ERR_MEM -1 /* Out of memory error. */ +#define ERR_BUF -2 /* Buffer error. */ + + +#define ERR_ABRT -3 /* Connection aborted. */ +#define ERR_RST -4 /* Connection reset. */ +#define ERR_CLSD -5 /* Connection closed. */ +#define ERR_CONN -6 /* Not connected. */ + +#define ERR_VAL -7 /* Illegal value. */ + +#define ERR_ARG -8 /* Illegal argument. */ + +#define ERR_RTE -9 /* Routing problem. */ + +#define ERR_USE -10 /* Address in use. */ + + + +#ifdef LWIP_DEBUG +extern char *lwip_strerr(err_t err); +#else +#define lwip_strerr(x) "" +#endif /* LWIP_DEBUG */ +#endif /* __LWIP_ERR_H__ */ diff --git a/src/sys/include/net/ipv4/icmp.h b/src/sys/include/net/ipv4/icmp.h new file mode 100644 index 0000000..0a12aeb --- /dev/null +++ b/src/sys/include/net/ipv4/icmp.h @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2001, Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce 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 Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (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 file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + * $Id$ + */ +#ifndef __LWIP_ICMP_H__ +#define __LWIP_ICMP_H__ + +#include "net/arch.h" + +#include "net/opt.h" +#include "net/pbuf.h" + +#include "net/netif.h" + +#define ICMP_ER 0 /* echo reply */ +#define ICMP_DUR 3 /* destination unreachable */ +#define ICMP_SQ 4 /* source quench */ +#define ICMP_RD 5 /* redirect */ +#define ICMP_ECHO 8 /* echo */ +#define ICMP_TE 11 /* time exceeded */ +#define ICMP_PP 12 /* parameter problem */ +#define ICMP_TS 13 /* timestamp */ +#define ICMP_TSR 14 /* timestamp reply */ +#define ICMP_IRQ 15 /* information request */ +#define ICMP_IR 16 /* information reply */ + +enum icmp_dur_type { + ICMP_DUR_NET = 0, /* net unreachable */ + ICMP_DUR_HOST = 1, /* host unreachable */ + ICMP_DUR_PROTO = 2, /* protocol unreachable */ + ICMP_DUR_PORT = 3, /* port unreachable */ + ICMP_DUR_FRAG = 4, /* fragmentation needed and DF set */ + ICMP_DUR_SR = 5 /* source route failed */ +}; + +enum icmp_te_type { + ICMP_TE_TTL = 0, /* time to live exceeded in transit */ + ICMP_TE_FRAG = 1 /* fragment reassembly time exceeded */ +}; + +void icmp_input(struct pbuf *p, struct netif *inp); + +void icmp_dest_unreach(struct pbuf *p, enum icmp_dur_type t); +void icmp_time_exceeded(struct pbuf *p, enum icmp_te_type t); + +struct icmp_echo_hdr { + PACK_STRUCT_FIELD(uInt16 _type_code); + PACK_STRUCT_FIELD(uInt16 chksum); + PACK_STRUCT_FIELD(uInt16 id); + PACK_STRUCT_FIELD(uInt16 seqno); +} PACK_STRUCT_STRUCT; + + + +struct icmp_dur_hdr { + PACK_STRUCT_FIELD(uInt16 _type_code); + PACK_STRUCT_FIELD(uInt16 chksum); + PACK_STRUCT_FIELD(uInt32 unused); +} PACK_STRUCT_STRUCT; + +struct icmp_te_hdr { + PACK_STRUCT_FIELD(uInt16 _type_code); + PACK_STRUCT_FIELD(uInt16 chksum); + PACK_STRUCT_FIELD(uInt32 unused); +} PACK_STRUCT_STRUCT; + +#define ICMPH_TYPE(hdr) (NTOHS((hdr)->_type_code) >> 8) +#define ICMPH_CODE(hdr) (NTOHS((hdr)->_type_code) & 0xff) + +#define ICMPH_TYPE_SET(hdr, type) ((hdr)->_type_code = HTONS(ICMPH_CODE(hdr) | ((type) << 8))) +#define ICMPH_CODE_SET(hdr, code) ((hdr)->_type_code = HTONS((code) | (ICMPH_TYPE(hdr) << 8))) + +#endif /* __LWIP_ICMP_H__ */ + diff --git a/src/sys/include/net/ipv4/inet.h b/src/sys/include/net/ipv4/inet.h new file mode 100644 index 0000000..7752f4e --- /dev/null +++ b/src/sys/include/net/ipv4/inet.h @@ -0,0 +1,122 @@ +/* + * Copyright (c) 2001, Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce 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 Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (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 file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + * $Id$ + */ +#ifndef __LWIP_INET_H__ +#define __LWIP_INET_H__ + +#include "net/arch.h" + +#include "net/opt.h" +#include "net/pbuf.h" +#include "net/ipv4/ip_addr.h" + +uInt16 inet_chksum(void *dataptr, uInt16 len); +uInt16 inet_chksum_pbuf(struct pbuf *p); +uInt16 inet_chksum_pseudo(struct pbuf *p, + struct ip_addr *src, struct ip_addr *dest, + uInt8 proto, uInt16 proto_len); + +#ifdef HTONS +#undef HTONS +#endif /* HTONS */ +#ifdef NTOHS +#undef NTOHS +#endif /* NTOHS */ +#ifdef HTONL +#undef HTONL +#endif /* HTONL */ +#ifdef NTOHL +#undef NTOHL +#endif /* NTOHL */ + +#ifndef HTONS +# if BYTE_ORDER == BIG_ENDIAN +# define HTONS(n) (n) +# define htons(n) HTONS(n) +# else /* BYTE_ORDER == BIG_ENDIAN */ +# define HTONS(n) (((((uInt16)(n) & 0xff)) << 8) | (((uInt16)(n) & 0xff00) >> 8)) +# endif /* BYTE_ORDER == BIG_ENDIAN */ +#endif /* HTONS */ + +#ifdef NTOHS +#undef NTOHS +#endif /* NTOHS */ + +#ifdef ntohs +#undef ntohs +#endif /* ntohs */ + +#define NTOHS HTONS +#define ntohs htons + + +#ifndef HTONL +# if BYTE_ORDER == BIG_ENDIAN +# define HTONL(n) (n) +# define htonl(n) HTONL(n) +# else /* BYTE_ORDER == BIG_ENDIAN */ +# define HTONL(n) (((((uInt32)(n) & 0xff)) << 24) | \ + ((((uInt32)(n) & 0xff00)) << 8) | \ + ((((uInt32)(n) & 0xff0000)) >> 8) | \ + ((((uInt32)(n) & 0xff000000)) >> 24)) +# endif /* BYTE_ORDER == BIG_ENDIAN */ +#endif /* HTONL */ + +#ifdef ntohl +#undef ntohl +#endif /* ntohl */ + +#ifdef NTOHL +#undef NTOHL +#endif /* NTOHL */ + +#define NTOHL HTONL +#define ntohl htonl + +#ifndef _MACHINE_ENDIAN_H_ +#ifndef _NETINET_IN_H +#ifndef _LINUX_BYTEORDER_GENERIC_H + +#if BYTE_ORDER == LITTLE_ENDIAN +uInt16 htons(uInt16 n); +uInt32 htonl(uInt32 n); +#else +#endif /* BYTE_ORDER == LITTLE_ENDIAN */ + +#endif /* _LINUX_BYTEORDER_GENERIC_H */ +#endif /* _NETINET_IN_H */ +#endif /* _MACHINE_ENDIAN_H_ */ + +#endif /* __LWIP_INET_H__ */ + diff --git a/src/sys/include/net/ipv4/ip.h b/src/sys/include/net/ipv4/ip.h new file mode 100644 index 0000000..fcef881 --- /dev/null +++ b/src/sys/include/net/ipv4/ip.h @@ -0,0 +1,120 @@ +/* + * Copyright (c) 2001, Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce 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 Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (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 file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + * $Id$ + */ +#ifndef __LWIP_IP_H__ +#define __LWIP_IP_H__ + +#include "net/arch.h" + +#include "net/def.h" +#include "net/pbuf.h" +#include "net/ipv4/ip_addr.h" +#include "net/netif.h" + +#include "net/err.h" + +void ip_init(void); +uInt8 ip_lookup(void *header, struct netif *inp); +struct netif *ip_route(struct ip_addr *dest); +err_t ip_input(struct pbuf *p, struct netif *inp); +err_t ip_output(struct pbuf *p, struct ip_addr *src, struct ip_addr *dest, + uInt8 ttl, uInt8 proto); +err_t ip_output_if(struct pbuf *p, struct ip_addr *src, struct ip_addr *dest, + uInt8 ttl, uInt8 proto, + struct netif *netif); + +#define IP_HLEN 20 + +#define IP_PROTO_ICMP 1 +#define IP_PROTO_UDP 17 +#define IP_PROTO_UDPLITE 170 +#define IP_PROTO_TCP 6 + +/* This is passed as the destination address to ip_output_if (not + to ip_output), meaning that an IP header already is constructed + in the pbuf. This is used when TCP retransmits. */ +#ifdef IP_HDRINCL +#undef IP_HDRINCL +#endif /* IP_HDRINCL */ +#define IP_HDRINCL NULL + +struct ip_hdr { + /* version / header length / type of service */ + PACK_STRUCT_FIELD(uInt16 _v_hl_tos); + /* total length */ + PACK_STRUCT_FIELD(uInt16 _len); + /* identification */ + PACK_STRUCT_FIELD(uInt16 _id); + /* fragment offset field */ + PACK_STRUCT_FIELD(uInt16 _offset); +#define IP_RF 0x8000 /* reserved fragment flag */ +#define IP_DF 0x4000 /* dont fragment flag */ +#define IP_MF 0x2000 /* more fragments flag */ +#define IP_OFFMASK 0x1fff /* mask for fragmenting bits */ + /* time to live / protocol*/ + PACK_STRUCT_FIELD(uInt16 _ttl_proto); + /* checksum */ + PACK_STRUCT_FIELD(uInt16 _chksum); + /* source and destination IP addresses */ + PACK_STRUCT_FIELD(struct ip_addr src); + PACK_STRUCT_FIELD(struct ip_addr dest); +} PACK_STRUCT_STRUCT; + +#define IPH_V(hdr) (NTOHS((hdr)->_v_hl_tos) >> 12) +#define IPH_HL(hdr) ((NTOHS((hdr)->_v_hl_tos) >> 8) & 0x0f) +#define IPH_TOS(hdr) HTONS((NTOHS((hdr)->_v_hl_tos) & 0xff)) +#define IPH_LEN(hdr) ((hdr)->_len) +#define IPH_ID(hdr) ((hdr)->_id) +#define IPH_OFFSET(hdr) ((hdr)->_offset) +#define IPH_TTL(hdr) (NTOHS((hdr)->_ttl_proto) >> 8) +#define IPH_PROTO(hdr) (NTOHS((hdr)->_ttl_proto) & 0xff) +#define IPH_CHKSUM(hdr) ((hdr)->_chksum) + +#define IPH_VHLTOS_SET(hdr, v, hl, tos) (hdr)->_v_hl_tos = HTONS(((v) << 12) | ((hl) << 8) | (tos)) +#define IPH_LEN_SET(hdr, len) (hdr)->_len = (len) +#define IPH_ID_SET(hdr, id) (hdr)->_id = (id) +#define IPH_OFFSET_SET(hdr, off) (hdr)->_offset = (off) +#define IPH_TTL_SET(hdr, ttl) (hdr)->_ttl_proto = HTONS(IPH_PROTO(hdr) | ((ttl) << 8)) +#define IPH_PROTO_SET(hdr, proto) (hdr)->_ttl_proto = HTONS((proto) | (IPH_TTL(hdr) << 8)) +#define IPH_CHKSUM_SET(hdr, chksum) (hdr)->_chksum = (chksum) + + + +#if IP_DEBUG +void ip_debug_print(struct pbuf *p); +#endif /* IP_DEBUG */ + +#endif /* __LWIP_IP_H__ */ + + diff --git a/src/sys/include/net/ipv4/ip_addr.h b/src/sys/include/net/ipv4/ip_addr.h new file mode 100644 index 0000000..2fb5168 --- /dev/null +++ b/src/sys/include/net/ipv4/ip_addr.h @@ -0,0 +1,92 @@ +/* + * Copyright (c) 2001, Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce 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 Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (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 file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + * $Id$ + */ +#ifndef __LWIP_IP_ADDR_H__ +#define __LWIP_IP_ADDR_H__ + +#include "net/arch.h" + +#define IP_ADDR_ANY 0 + +#define IP_ADDR_BROADCAST (&ip_addr_broadcast) + +PACK_STRUCT_BEGIN +struct ip_addr { + PACK_STRUCT_FIELD(uInt32 addr); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END + +extern struct ip_addr ip_addr_broadcast; + +#define IP4_ADDR(ipaddr, a,b,c,d) (ipaddr)->addr = htonl(((uInt32)(a & 0xff) << 24) | ((uInt32)(b & 0xff) << 16) | \ + ((uInt32)(c & 0xff) << 8) | (uInt32)(d & 0xff)) + +#define ip_addr_set(dest, src) (dest)->addr = \ + ((src) == IP_ADDR_ANY? IP_ADDR_ANY:\ + ((struct ip_addr *)src)->addr) +#define ip_addr_maskcmp(addr1, addr2, mask) (((addr1)->addr & \ + (mask)->addr) == \ + ((addr2)->addr & \ + (mask)->addr)) +#define ip_addr_cmp(addr1, addr2) ((addr1)->addr == (addr2)->addr) + +#define ip_addr_isany(addr1) ((addr1) == NULL || (addr1)->addr == 0) + +#define ip_addr_isbroadcast(addr1, mask) (((((addr1)->addr) & ~((mask)->addr)) == \ + (0xffffffff & ~((mask)->addr))) || \ + ((addr1)->addr == 0xffffffff) || \ + ((addr1)->addr == 0x00000000)) + + +#define ip_addr_ismulticast(addr1) (((addr1)->addr & ntohl(0xf0000000)) == ntohl(0xe0000000)) + + +#define ip_addr_debug_print(ipaddr) kprintf("%d.%d.%d.%d", \ + (uInt8)(ntohl((ipaddr)->addr) >> 24) & 0xff, \ + (uInt8)(ntohl((ipaddr)->addr) >> 16) & 0xff, \ + (uInt8)(ntohl((ipaddr)->addr) >> 8) & 0xff, \ + (uInt8)ntohl((ipaddr)->addr) & 0xff) + + +#define ip4_addr1(ipaddr) ((uInt8)(ntohl((ipaddr)->addr) >> 24) & 0xff) +#define ip4_addr2(ipaddr) ((uInt8)(ntohl((ipaddr)->addr) >> 16) & 0xff) +#define ip4_addr3(ipaddr) ((uInt8)(ntohl((ipaddr)->addr) >> 8) & 0xff) +#define ip4_addr4(ipaddr) ((uInt8)(ntohl((ipaddr)->addr)) & 0xff) +#endif /* __LWIP_IP_ADDR_H__ */ + + + + + + diff --git a/src/sys/include/net/ipv6/icmp.h b/src/sys/include/net/ipv6/icmp.h new file mode 100644 index 0000000..ac428e9 --- /dev/null +++ b/src/sys/include/net/ipv6/icmp.h @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2001, Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce 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 Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (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 file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + * $Id$ + */ +#ifndef __LWIP_ICMP_H__ +#define __LWIP_ICMP_H__ + +#include "lwip/arch.h" + +#include "lwip/opt.h" +#include "lwip/pbuf.h" + +#include "lwip/netif.h" + +#define ICMP6_DUR 1 +#define ICMP6_TE 3 +#define ICMP6_ECHO 128 /* echo */ +#define ICMP6_ER 129 /* echo reply */ + + +enum icmp_dur_type { + ICMP_DUR_NET = 0, /* net unreachable */ + ICMP_DUR_HOST = 1, /* host unreachable */ + ICMP_DUR_PROTO = 2, /* protocol unreachable */ + ICMP_DUR_PORT = 3, /* port unreachable */ + ICMP_DUR_FRAG = 4, /* fragmentation needed and DF set */ + ICMP_DUR_SR = 5 /* source route failed */ +}; + +enum icmp_te_type { + ICMP_TE_TTL = 0, /* time to live exceeded in transit */ + ICMP_TE_FRAG = 1 /* fragment reassembly time exceeded */ +}; + +void icmp_input(struct pbuf *p, struct netif *inp); + +void icmp_dest_unreach(struct pbuf *p, enum icmp_dur_type t); +void icmp_time_exceeded(struct pbuf *p, enum icmp_te_type t); + +struct icmp_echo_hdr { + u8_t type; + u8_t icode; + u16_t chksum; + u16_t id; + u16_t seqno; +}; + +struct icmp_dur_hdr { + u8_t type; + u8_t icode; + u16_t chksum; + u32_t unused; +}; + +struct icmp_te_hdr { + u8_t type; + u8_t icode; + u16_t chksum; + u32_t unused; +}; + +#endif /* __LWIP_ICMP_H__ */ + diff --git a/src/sys/include/net/ipv6/inet.h b/src/sys/include/net/ipv6/inet.h new file mode 100644 index 0000000..8f1f203 --- /dev/null +++ b/src/sys/include/net/ipv6/inet.h @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2001, Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce 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 Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (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 file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + * $Id$ + */ +#ifndef __LWIP_INET_H__ +#define __LWIP_INET_H__ + +#include "net/arch.h" + +#include "net/opt.h" +#include "net/pbuf.h" +#include "net/ipv6/ip_addr.h" + +u16_t inet_chksum(void *data, u16_t len); +u16_t inet_chksum_pbuf(struct pbuf *p); +u16_t inet_chksum_pseudo(struct pbuf *p, + struct ip_addr *src, struct ip_addr *dest, + u8_t proto, u32_t proto_len); + + +#ifndef _MACHINE_ENDIAN_H_ +#ifndef _NETINET_IN_H +#ifndef _LINUX_BYTEORDER_GENERIC_H +u16_t htons(u16_t n); +u16_t ntohs(u16_t n); +u32_t htonl(u32_t n); +u32_t ntohl(u32_t n); +#endif /* _LINUX_BYTEORDER_GENERIC_H */ +#endif /* _NETINET_IN_H */ +#endif /* _MACHINE_ENDIAN_H_ */ + +#endif /* __LWIP_INET_H__ */ + diff --git a/src/sys/include/net/ipv6/ip.h b/src/sys/include/net/ipv6/ip.h new file mode 100644 index 0000000..82ca272 --- /dev/null +++ b/src/sys/include/net/ipv6/ip.h @@ -0,0 +1,99 @@ +/* + * Copyright (c) 2001, Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce 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 Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (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 file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + * $Id$ + */ +#ifndef __LWIP_IP_H__ +#define __LWIP_IP_H__ + +#include "lwip/debug.h" +#include "lwip/def.h" +#include "lwip/pbuf.h" +#include "lwip/ip_addr.h" + +#include "lwip/err.h" + +#define IP_HLEN 40 + +#define IP_PROTO_ICMP 58 +#define IP_PROTO_UDP 17 +#define IP_PROTO_UDPLITE 170 +#define IP_PROTO_TCP 6 + +/* This is passed as the destination address to ip_output_if (not + to ip_output), meaning that an IP header already is constructed + in the pbuf. This is used when TCP retransmits. */ +#ifdef IP_HDRINCL +#undef IP_HDRINCL +#endif /* IP_HDRINCL */ +#define IP_HDRINCL NULL + + +/* The IPv6 header. */ +struct ip_hdr { +#if BYTE_ORDER == LITTLE_ENDIAN + u8_t tclass1:4, v:4; + u8_t flow1:4, tclass2:4; +#else + u8_t v:4, tclass1:4; + u8_t tclass2:8, flow1:4; +#endif + u16_t flow2; + u16_t len; /* payload length */ + u8_t nexthdr; /* next header */ + u8_t hoplim; /* hop limit (TTL) */ + struct ip_addr src, dest; /* source and destination IP addresses */ +}; + +void ip_init(void); + +#include "lwip/netif.h" + +struct netif *ip_route(struct ip_addr *dest); + +void ip_input(struct pbuf *p, struct netif *inp); + +/* source and destination addresses in network byte order, please */ +err_t ip_output(struct pbuf *p, struct ip_addr *src, struct ip_addr *dest, + unsigned char ttl, unsigned char proto); + +err_t ip_output_if(struct pbuf *p, struct ip_addr *src, struct ip_addr *dest, + unsigned char ttl, unsigned char proto, + struct netif *netif); + +#if IP_DEBUG +void ip_debug_print(struct pbuf *p); +#endif /* IP_DEBUG */ + +#endif /* __LWIP_IP_H__ */ + + diff --git a/src/sys/include/net/ipv6/ip_addr.h b/src/sys/include/net/ipv6/ip_addr.h new file mode 100644 index 0000000..a082805 --- /dev/null +++ b/src/sys/include/net/ipv6/ip_addr.h @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2001, Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce 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 Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (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 file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + * $Id$ + */ +#ifndef __LWIP_IP_ADDR_H__ +#define __LWIP_IP_ADDR_H__ + +#include "net/arch.h" + +#define IP_ADDR_ANY 0 + +struct ip_addr { + u32_t addr[4]; +}; + +#define IP6_ADDR(ipaddr, a,b,c,d,e,f,g,h) do { (ipaddr)->addr[0] = htonl((u32_t)((a & 0xffff) << 16) | (b & 0xffff)); \ + (ipaddr)->addr[1] = htonl(((c & 0xffff) << 16) | (d & 0xffff)); \ + (ipaddr)->addr[2] = htonl(((e & 0xffff) << 16) | (f & 0xffff)); \ + (ipaddr)->addr[3] = htonl(((g & 0xffff) << 16) | (h & 0xffff)); } while(0) + +int ip_addr_maskcmp(struct ip_addr *addr1, struct ip_addr *addr2, + struct ip_addr *mask); +int ip_addr_cmp(struct ip_addr *addr1, struct ip_addr *addr2); +void ip_addr_set(struct ip_addr *dest, struct ip_addr *src); +int ip_addr_isany(struct ip_addr *addr); + + +#if IP_DEBUG +void ip_addr_debug_print(struct ip_addr *addr); +#endif /* IP_DEBUG */ + +#endif /* __LWIP_IP_ADDR_H__ */ diff --git a/src/sys/include/net/list.h b/src/sys/include/net/list.h new file mode 100644 index 0000000..f2afc5f --- /dev/null +++ b/src/sys/include/net/list.h @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2001, Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce 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 Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (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 file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + * $Id$ + */ +#ifndef __LWIP_LIST_H__ +#define __LWIP_LIST_H__ + +struct list; + +struct list *list_new(int size); +int list_push(struct list *list, void *elem); +void *list_pop(struct list *list); +int list_remove(struct list *list, void *elem); +void *list_first(struct list *list); +int list_elems(struct list *list); +void list_delete(struct list *list); + +void list_map(struct list *list, void (* func)(void *arg)); + +#endif /* __LWIP_LIST_H__ */ diff --git a/src/sys/include/net/lwipopts.h b/src/sys/include/net/lwipopts.h new file mode 100644 index 0000000..1499b27 --- /dev/null +++ b/src/sys/include/net/lwipopts.h @@ -0,0 +1,174 @@ +/* + * Copyright (c) 2001, Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce 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 Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (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 file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + * $Id$ + */ +#ifndef __LWIPOPTS_H__ +#define __LWIPOPTS_H__ + +/* ---------- Memory options ---------- */ +/* MEM_ALIGNMENT: should be set to the alignment of the CPU for which + lwIP is compiled. 4 byte alignment -> define MEM_ALIGNMENT to 4, 2 + byte alignment -> define MEM_ALIGNMENT to 2. */ +#define MEM_ALIGNMENT 2 + +/* MEM_SIZE: the size of the heap memory. If the application will send +a lot of data that needs to be copied, this should be set high. */ +#define MEM_SIZE 1000 + +/* MEMP_NUM_PBUF: the number of memp struct pbufs. If the application + sends a lot of data out of ROM (or other static memory), this + should be set high. */ +#define MEMP_NUM_PBUF 8 +/* MEMP_NUM_UDP_PCB: the number of UDP protocol control blocks. One + per active UDP "connection". */ +#define MEMP_NUM_UDP_PCB 4 +/* MEMP_NUM_TCP_PCB: the number of simulatenously active TCP + connections. */ +#define MEMP_NUM_TCP_PCB 5 +/* MEMP_NUM_TCP_PCB_LISTEN: the number of listening TCP + connections. */ +#define MEMP_NUM_TCP_PCB_LISTEN 8 +/* MEMP_NUM_TCP_SEG: the number of simultaneously queued TCP + segments. */ +#define MEMP_NUM_TCP_SEG 8 +/* MEMP_NUM_SYS_TIMEOUT: the number of simulateously active + timeouts. */ +#define MEMP_NUM_SYS_TIMEOUT 3 + + +/* The following four are used only with the sequential API and can be + set to 0 if the application only will use the raw API. */ +/* MEMP_NUM_NETBUF: the number of struct netbufs. */ +#define MEMP_NUM_NETBUF 2 +/* MEMP_NUM_NETCONN: the number of struct netconns. */ +#define MEMP_NUM_NETCONN 4 +/* MEMP_NUM_APIMSG: the number of struct api_msg, used for + communication between the TCP/IP stack and the sequential + programs. */ +#define MEMP_NUM_API_MSG 8 +/* MEMP_NUM_TCPIPMSG: the number of struct tcpip_msg, which is used + for sequential API communication and incoming packets. Used in + src/api/tcpip.c. */ +#define MEMP_NUM_TCPIP_MSG 8 + +/* These two control is reclaimer functions should be compiled + in. Should always be turned on (1). */ +#define MEM_RECLAIM 1 +#define MEMP_RECLAIM 1 + +/* ---------- Pbuf options ---------- */ +/* PBUF_POOL_SIZE: the number of buffers in the pbuf pool. */ +#define PBUF_POOL_SIZE 6 + +/* PBUF_POOL_BUFSIZE: the size of each pbuf in the pbuf pool. */ +#define PBUF_POOL_BUFSIZE 128 + +/* PBUF_LINK_HLEN: the number of bytes that should be allocated for a + link level header. */ +#define PBUF_LINK_HLEN 16 + +/* ---------- TCP options ---------- */ +#define LWIP_TCP 1 +#define TCP_TTL 255 + +/* Controls if TCP should queue segments that arrive out of + order. Define to 0 if your device is low on memory. */ +#define TCP_QUEUE_OOSEQ 1 + +/* TCP Maximum segment size. */ +#define TCP_MSS 128 + +/* TCP sender buffer space (bytes). */ +#define TCP_SND_BUF 256 + +/* TCP sender buffer space (pbufs). This must be at least = 2 * + TCP_SND_BUF/TCP_MSS for things to work. */ +#define TCP_SND_QUEUELEN 4 * TCP_SND_BUF/TCP_MSS + +/* TCP receive window. */ +#define TCP_WND 1024 + +/* Maximum number of retransmissions of data segments. */ +#define TCP_MAXRTX 12 + +/* Maximum number of retransmissions of SYN segments. */ +#define TCP_SYNMAXRTX 4 + +/* ---------- ARP options ---------- */ +#define ARP_TABLE_SIZE 10 + +/* ---------- IP options ---------- */ +/* Define IP_FORWARD to 1 if you wish to have the ability to forward + IP packets across network interfaces. If you are going to run lwIP + on a device with only one network interface, define this to 0. */ +#define IP_FORWARD 1 + +/* If defined to 1, IP options are allowed (but not parsed). If + defined to 0, all packets with IP options are dropped. */ +#define IP_OPTIONS 1 + +/* ---------- ICMP options ---------- */ +#define ICMP_TTL 255 + + +/* ---------- DHCP options ---------- */ +/* Define LWIP_DHCP to 1 if you want DHCP configuration of + interfaces. DHCP is not implemented in lwIP 0.5.1, however, so + turning this on does currently not work. */ +#define LWIP_DHCP 0 + +/* 1 if you want to do an ARP check on the offered address + (recommended). */ +#define DHCP_DOES_ARP_CHECK 1 + +/* ---------- UDP options ---------- */ +#define LWIP_UDP 1 +#define UDP_TTL 255 + + +/* ---------- Statistics options ---------- */ +#define STATS + +#ifdef STATS +#define LINK_STATS +#define IP_STATS +#define ICMP_STATS +#define UDP_STATS +#define TCP_STATS +#define MEM_STATS +#define MEMP_STATS +#define PBUF_STATS +#define SYS_STATS +#endif /* STATS */ + +#endif /* __LWIPOPTS_H__ */ diff --git a/src/sys/include/net/mem.h b/src/sys/include/net/mem.h new file mode 100644 index 0000000..c8a17eb --- /dev/null +++ b/src/sys/include/net/mem.h @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2001, Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce 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 Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (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 file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + * $Id$ + */ +#ifndef __LWIP_MEM_H__ +#define __LWIP_MEM_H__ + +#include + +#include "net/debug.h" +#include "net/opt.h" +#include "net/arch.h" + +#if MEM_SIZE > 64000l +typedef uInt32 mem_size_t; +#else +typedef uInt16 mem_size_t; +#endif /* MEM_SIZE > 64000 */ + + +void mem_init(void); + +void *mem_malloc(mem_size_t size); +void *mem_malloc2(mem_size_t size); +void mem_free(void *mem); +void *mem_realloc(void *mem, mem_size_t size); +void *mem_reallocm(void *mem, mem_size_t size); + +#ifdef MEM_PERF +void mem_perf_start(void); +void mem_perf_init(char *fname); +#endif /* MEM_PERF */ + +#ifdef MEM_RECLAIM +typedef mem_size_t (*mem_reclaim_func)(void *arg, mem_size_t size); +void mem_register_reclaim(mem_reclaim_func f, void *arg); +void mem_reclaim(unsigned int size); +#else +#define mem_register_reclaim(f, arg) +#endif /* MEM_RECLAIM */ + + +#define MEM_ALIGN_SIZE(size) (size + \ + ((((size) % MEM_ALIGNMENT) == 0)? 0 : \ + (MEM_ALIGNMENT - ((size) % MEM_ALIGNMENT)))) + +#define MEM_ALIGN(addr) (void *)MEM_ALIGN_SIZE((uInt32)addr) + +#endif /* __LWIP_MEM_H__ */ + diff --git a/src/sys/include/net/memp.h b/src/sys/include/net/memp.h new file mode 100644 index 0000000..3e0b849 --- /dev/null +++ b/src/sys/include/net/memp.h @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2001, Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce 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 Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (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 file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + * $Id$ + */ + +#ifndef __LWIP_MEMP_H__ +#define __LWIP_MEMP_H__ + +#include + +#include "net/debug.h" +#include "net/arch/cc.h" +#include "net/lwipopts.h" + +typedef enum { + MEMP_PBUF, + MEMP_UDP_PCB, + MEMP_TCP_PCB, + MEMP_TCP_PCB_LISTEN, + MEMP_TCP_SEG, + + MEMP_NETBUF, + MEMP_NETCONN, + MEMP_API_MSG, + MEMP_TCPIP_MSG, + + MEMP_SYS_TIMEOUT, + + MEMP_MAX +} memp_t; + +void memp_init(void); + +void *memp_malloc(memp_t type); +void *memp_mallocp(memp_t type); +void *memp_malloc2(memp_t type); +void *memp_realloc(memp_t fromtype, memp_t totype, void *mem); +void memp_free(memp_t type, void *mem); +void memp_freep(memp_t type, void *mem); + +#if MEMP_RECLAIM +typedef uInt8 (*memp_reclaim_func)(void *arg, memp_t type); +void memp_register_reclaim(memp_t type, memp_reclaim_func f, void *arg); +#else +#define memp_register_reclaim(t, f, arg) +#endif /* MEMP_RECLAIM */ + +#endif /* __LWIP_MEMP_H__ */ + diff --git a/src/sys/include/net/netif.h b/src/sys/include/net/netif.h new file mode 100644 index 0000000..545ec7e --- /dev/null +++ b/src/sys/include/net/netif.h @@ -0,0 +1,99 @@ +/* + * Copyright (c) 2001, Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce 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 Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (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 file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + * $Id$ + */ +#ifndef __LWIP_NETIF_H__ +#define __LWIP_NETIF_H__ + +#include "net/opt.h" + +#include "net/err.h" + +#include "net/ipv4/ip_addr.h" +#include "net/ipv4/inet.h" + +#include "net/pbuf.h" + + +struct netif { + struct netif *next; + uInt8 num; + struct ip_addr ip_addr; + struct ip_addr netmask; /* netmask in network byte order */ + struct ip_addr gw; + char hwaddr[6]; + + /* This function is called by the network device driver + when it wants to pass a packet to the TCP/IP stack. */ + err_t (* input)(struct pbuf *p, struct netif *inp); + + /* The following two fields should be filled in by the + initialization function for the device driver. */ + + char name[2]; + /* This function is called by the IP module when it wants + to send a packet on the interface. */ + err_t (* output)(struct netif *netif, struct pbuf *p, struct ip_addr *ipaddr); + err_t (* linkoutput)(struct netif *netif, struct pbuf *p); + + /* This field can be set bu the device driver and could point + to state information for the device. */ + void *state; +}; + +/* The list of network interfaces. */ +extern struct netif *netif_list; +extern struct netif *netif_default; + + +/* netif_init() must be called first. */ +void netif_init(); + +struct netif *netif_add(struct ip_addr *ipaddr, struct ip_addr *netmask, + struct ip_addr *gw, + void (* init)(struct netif *netif), + err_t (* input)(struct pbuf *p, struct netif *netif)); + +/* Returns a network interface given its name. The name is of the form + "et0", where the first two letters are the "name" field in the + netif structure, and the digit is in the num field in the same + structure. */ +struct netif *netif_find(char *name); + +void netif_set_default(struct netif *netif); + +void netif_set_ipaddr(struct netif *netif, struct ip_addr *ipaddr); +void netif_set_netmask(struct netif *netif, struct ip_addr *netmast); +void netif_set_gw(struct netif *netif, struct ip_addr *gw); + +#endif /* __LWIP_NETIF_H__ */ diff --git a/src/sys/include/net/opt.h b/src/sys/include/net/opt.h new file mode 100644 index 0000000..71d42c3 --- /dev/null +++ b/src/sys/include/net/opt.h @@ -0,0 +1,97 @@ +/* + * Copyright (c) 2001, Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce 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 Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (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 file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + * $Id$ + */ +#ifndef __LWIP_OPT_H__ +#define __LWIP_OPT_H__ + +#include "net/lwipopts.h" + +/* Define some handy default values for configuration parameters. */ + +#ifndef ICMP_TTL +#define ICMP_TTL 255 +#endif + +#ifndef UDP_TTL +#define UDP_TTL 255 +#endif + +#ifndef TCP_TTL +#define TCP_TTL 255 +#endif + +#ifndef TCP_MSS +#define TCP_MSS 128 /* A *very* conservative default. */ +#endif + +#ifndef TCP_WND +#define TCP_WND 2048 +#endif + +#ifndef TCP_MAXRTX +#define TCP_MAXRTX 12 +#endif + +#ifndef TCP_SYNMAXRTX +#define TCP_SYNMAXRTX 6 +#endif + +#ifndef MEM_ALIGNMENT +#define MEM_ALIGNMENT 1 +#endif + +#ifndef PBUF_POOL_SIZE +#define PBUF_POOL_SIZE 16 +#endif + +#ifndef PBUF_POOL_BUFSIZE +#define PBUF_POOL_BUFSIZE 128 +#endif + +#ifndef PBUF_LINK_HLEN +#define PBUF_LINK_HLEN 0 +#endif + +#ifndef LWIP_UDP +#define LWIP_UDP 1 +#endif + +#ifndef LWIP_TCP +#define LWIP_TCP 1 +#endif + +#endif /* __LWIP_OPT_H__ */ + + + diff --git a/src/sys/include/net/pbuf.h b/src/sys/include/net/pbuf.h new file mode 100644 index 0000000..293ac35 --- /dev/null +++ b/src/sys/include/net/pbuf.h @@ -0,0 +1,152 @@ +/* + * Copyright (c) 2001, Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce 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 Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (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 file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + * $Id$ + */ +/*-----------------------------------------------------------------------------------*/ +#ifndef __LWIP_PBUF_H__ +#define __LWIP_PBUF_H__ + +#include "net/debug.h" +#include "net/arch.h" + + +#define PBUF_TRANSPORT_HLEN 20 +#define PBUF_IP_HLEN 20 + +typedef enum { + PBUF_TRANSPORT, + PBUF_IP, + PBUF_LINK, + PBUF_RAW +} pbuf_layer; + +typedef enum { + PBUF_RAM, + PBUF_ROM, + PBUF_POOL +} pbuf_flag; + +/* Definitions for the pbuf flag field (these are not the flags that + are passed to pbuf_alloc()). */ +#define PBUF_FLAG_RAM 0x00 /* Flags that pbuf data is stored in RAM. */ +#define PBUF_FLAG_ROM 0x01 /* Flags that pbuf data is stored in ROM. */ +#define PBUF_FLAG_POOL 0x02 /* Flags that the pbuf comes from the + pbuf pool. */ + +struct pbuf { + struct pbuf *next; + + /* high 4 bits, flags, low 4 bits reference count */ + uInt8 flags, ref; + void *payload; + + /* Total length of buffer + additionally chained buffers. */ + uInt16 tot_len; + /* Length of this buffer. */ + uInt16 len; + +}; + +/* pbuf_init(): + + Initializes the pbuf module. The num parameter determines how many + pbufs that should be allocated to the pbuf pool, and the size + parameter specifies the size of the data allocated to those. */ +void pbuf_init(void); + +/* pbuf_alloc(): + + Allocates a pbuf at protocol layer l. The actual memory allocated + for the pbuf is determined by the layer at which the pbuf is + allocated and the requested size (from the size parameter). The + flag parameter decides how and where the pbuf should be allocated + as follows: + + * PBUF_RAM: buffer memory for pbuf is allocated as one large + chunk. This includesprotocol headers as well. + + * RBUF_ROM: no buffer memory is allocated for the pbuf, even for + protocol headers. Additional headers must be + prepended by allocating another pbuf and chain in to + the front of the ROM pbuf. + + * PBUF_ROOL: the pbuf is allocated as a pbuf chain, with pbufs from + the pbuf pool that is allocated during pbuf_init(). */ +struct pbuf *pbuf_alloc(pbuf_layer l, uInt16 size, pbuf_flag flag); + +/* pbuf_realloc(): + + Shrinks the pbuf to the size given by the size parameter. + */ +void pbuf_realloc(struct pbuf *p, uInt16 size); + +/* pbuf_header(): + + Tries to move the p->payload pointer header_size number of bytes + upward within the pbuf. The return value is non-zero if it + fails. If so, an additional pbuf should be allocated for the header + and it should be chained to the front. */ +uInt8 pbuf_header(struct pbuf *p, Int16 header_size); + +/* pbuf_ref(): + + Increments the reference count of the pbuf p. + */ +void pbuf_ref(struct pbuf *p); + +/* pbuf_free(): + + Decrements the reference count and deallocates the pbuf if the + reference count is zero. If the pbuf is a chain all pbufs in the + chain are deallocated. */ +uInt8 pbuf_free(struct pbuf *p); + +/* pbuf_clen(): + + Returns the length of the pbuf chain. */ +uInt8 pbuf_clen(struct pbuf *p); + +/* pbuf_chain(): + + Chains pbuf t on the end of pbuf h. Pbuf h will have it's tot_len + field adjusted accordingly. Pbuf t should no be used any more after + a call to this function, since pbuf t is now a part of pbuf h. */ +void pbuf_chain(struct pbuf *h, struct pbuf *t); + +/* pbuf_dechain(): + + Picks off the first pbuf from the pbuf chain p. Returns the tail of + the pbuf chain or NULL if the pbuf p was not chained. */ +struct pbuf *pbuf_dechain(struct pbuf *p); + +#endif /* __LWIP_PBUF_H__ */ diff --git a/src/sys/include/net/sockets.h b/src/sys/include/net/sockets.h new file mode 100644 index 0000000..577a2eb --- /dev/null +++ b/src/sys/include/net/sockets.h @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2001, Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce 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 Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (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 file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + * $Id$ + */ + + +#ifndef __LWIP_SOCKETS_H__ +#define __LWIP_SOCKETS_H__ + +#include + +struct in_addr { + uInt32 s_addr; +}; + + +struct sockaddr_in { + uInt8 sin_len; + uInt8 sin_family; + uInt16 sin_port; + struct in_addr sin_addr; + char sin_zero[8]; +}; + +struct sockaddr { + uInt8 sa_len; + uInt8 sa_family; + char sa_data[14]; +}; + +#define SOCK_STREAM 1 +#define SOCK_DGRAM 2 + +#define AF_INET 2 +#define PF_INET AF_INET + +#define IPPROTO_TCP 6 +#define IPPROTO_UDP 17 + +#define INADDR_ANY 0 +#define INADDR_BROADCAST 0xffffffff + +int lwip_accept(int s, struct sockaddr *addr, int *addrlen); +int lwip_bind(int s, struct sockaddr *name, int namelen); +int lwip_close(int s); +int lwip_connect(int s, struct sockaddr *name, int namelen); +int lwip_listen(int s, int backlog); +int lwip_recv(int s, void *mem, int len, unsigned int flags); +int lwip_read(int s, void *mem, int len); +int lwip_recvfrom(int s, void *mem, int len, unsigned int flags, + struct sockaddr *from, int *fromlen); +int lwip_send(int s, void *dataptr, int size, unsigned int flags); +int lwip_sendto(int s, void *dataptr, int size, unsigned int flags, + struct sockaddr *to, int tolen); +int lwip_socket(int domain, int type, int protocol); +int lwip_write(int s, void *dataptr, int size); + +#ifdef LWIP_COMPAT_SOCKETS +#define accept(a,b,c) lwip_accept(a,b,c) +#define bind(a,b,c) lwip_bind(a,b,c) +#define close(s) lwip_close(s) +#define connect(a,b,c) lwip_connect(a,b,c) +#define listen(a,b) lwip_listen(a,b) +#define recv(a,b,c,d) lwip_recv(a,b,c,d) +#define read(a,b,c) lwip_read(a,b,c) +#define recvfrom(a,b,c,d,e,f) lwip_recvfrom(a,b,c,d,e,f) +#define send(a,b,c,d) lwip_send(a,b,c,d) +#define sendto(a,b,c,d,e,f) lwip_sendto(a,b,c,d,e,f) +#define socket(a,b,c) lwip_socket(a,b,c) +#define write(a,b,c) lwip_write(a,b,c) +#endif /* LWIP_NO_COMPAT_SOCKETS */ + +#endif /* __LWIP_SOCKETS_H__ */ + diff --git a/src/sys/include/net/stats.h b/src/sys/include/net/stats.h new file mode 100644 index 0000000..bea1a61 --- /dev/null +++ b/src/sys/include/net/stats.h @@ -0,0 +1,112 @@ +/* + * Copyright (c) 2001, Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce 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 Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (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 file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + * $Id$ + */ +#ifndef __LWIP_STATS_H__ +#define __LWIP_STATS_H__ + +#include "net/opt.h" +#include "net/arch/cc.h" + +#include "net/memp.h" + +#ifdef STATS + +struct stats_proto { + uInt16 xmit; /* Transmitted packets. */ + uInt16 rexmit; /* Retransmitted packets. */ + uInt16 recv; /* Received packets. */ + uInt16 fw; /* Forwarded packets. */ + uInt16 drop; /* Dropped packets. */ + uInt16 chkerr; /* Checksum error. */ + uInt16 lenerr; /* Invalid length error. */ + uInt16 memerr; /* Out of memory error. */ + uInt16 rterr; /* Routing error. */ + uInt16 proterr; /* Protocol error. */ + uInt16 opterr; /* Error in options. */ + uInt16 err; /* Misc error. */ + uInt16 cachehit; +}; + +struct stats_mem { + uInt16 avail; + uInt16 used; + uInt16 max; + uInt16 err; + uInt16 reclaimed; +}; + +struct stats_pbuf { + uInt16 avail; + uInt16 used; + uInt16 max; + uInt16 err; + uInt16 reclaimed; + + uInt16 alloc_locked; + uInt16 refresh_locked; +}; + +struct stats_syselem { + uInt16 used; + uInt16 max; + uInt16 err; +}; + +struct stats_sys { + struct stats_syselem sem; + struct stats_syselem mbox; +}; + +struct stats_ { + struct stats_proto link; + struct stats_proto ip; + struct stats_proto icmp; + struct stats_proto udp; + struct stats_proto tcp; + struct stats_pbuf pbuf; + struct stats_mem mem; + struct stats_mem memp[MEMP_MAX]; + struct stats_sys sys; +}; + +extern struct stats_ stats; + +#endif /* STATS */ + +void stats_init(void); +#endif /* __LWIP_STATS_H__ */ + + + + diff --git a/src/sys/include/net/sys.h b/src/sys/include/net/sys.h new file mode 100644 index 0000000..62302bf --- /dev/null +++ b/src/sys/include/net/sys.h @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2001, Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce 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 Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (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 file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + * $Id$ + */ +#ifndef __LWIP_SYS_H__ +#define __LWIP_SYS_H__ + +#include "arch/cc.h" +#include "arch/sys_arch.h" + +typedef void (* sys_timeout_handler)(void *arg); + +struct sys_timeout { + struct sys_timeout *next; + uInt16 time; + sys_timeout_handler h; + void *arg; +}; + +struct sys_timeouts { + struct sys_timeout *next; +}; + +/* sys_init() must be called before anthing else. */ +void sys_init(void); + +/* + * sys_timeout(): + * + * Schedule a timeout a specified amount of milliseconds in the + * future. When the timeout occurs, the specified timeout handler will + * be called. The handler will be passed the "arg" argument when + * called. + * + */ +void sys_timeout(uInt16 msecs, sys_timeout_handler h, void *arg); +struct sys_timeouts *sys_arch_timeouts(void); + +/* Semaphore functions. */ +sys_sem_t sys_sem_new(uInt8 count); +void sys_sem_signal(sys_sem_t sem); +uInt16 sys_arch_sem_wait(sys_sem_t sem, uInt16 timeout); +void sys_sem_free(sys_sem_t sem); + +void sys_sem_wait(sys_sem_t sem); + +/* Mailbox functions. */ +sys_mbox_t sys_mbox_new(void); +void sys_mbox_post(sys_mbox_t mbox, void *msg); +uInt16 sys_arch_mbox_fetch(sys_mbox_t mbox, void **msg, uInt16 timeout); +void sys_mbox_free(sys_mbox_t mbox); + +void sys_mbox_fetch(sys_mbox_t mbox, void **msg); + +/* Thread functions. */ +void sys_thread_new(void (* thread)(void *arg), void *arg); + +/* The following functions are used only in Unix code, and + can be omitted when porting the stack. */ +/* Returns the current time in microseconds. */ +unsigned long sys_now(void); + +#endif /* __LWIP_SYS_H__ */ diff --git a/src/sys/include/net/tcp.h b/src/sys/include/net/tcp.h new file mode 100644 index 0000000..ee58616 --- /dev/null +++ b/src/sys/include/net/tcp.h @@ -0,0 +1,401 @@ +/* + * Copyright (c) 2001, Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce 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 Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (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 file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + * $Id$ + */ +#ifndef __LWIP_TCP_H__ +#define __LWIP_TCP_H__ + +#include "net/sys.h" +#include "net/mem.h" + +#include "net/pbuf.h" +#include "net/opt.h" +//UBU +#include "net/ipv4/ip.h" +//UBU +#include "net/ipv4/icmp.h" + +#include "net/sys.h" + +#include "net/err.h" + +struct tcp_pcb; + +/* Functions for interfacing with TCP: */ + +/* Lower layer interface to TCP: */ +void tcp_init (void); /* Must be called first to + initialize TCP. */ +void tcp_tmr (void); /* Must be called every + TCP_TMR_INTERVAL + ms. (Typically 100 ms). */ +/* Application program's interface: */ +struct tcp_pcb * tcp_new (void); + +void tcp_arg (struct tcp_pcb *pcb, void *arg); +void tcp_accept (struct tcp_pcb *pcb, + err_t (* accept)(void *arg, struct tcp_pcb *newpcb, + err_t err)); +void tcp_recv (struct tcp_pcb *pcb, + err_t (* recv)(void *arg, struct tcp_pcb *tpcb, + struct pbuf *p, err_t err)); +void tcp_sent (struct tcp_pcb *pcb, + err_t (* sent)(void *arg, struct tcp_pcb *tpcb, + uInt16 len)); +void tcp_poll (struct tcp_pcb *pcb, + err_t (* poll)(void *arg, struct tcp_pcb *tpcb), + uInt8 interval); +void tcp_err (struct tcp_pcb *pcb, + void (* err)(void *arg, err_t err)); + +#define tcp_sndbuf(pcb) ((pcb)->snd_buf) + +void tcp_recved (struct tcp_pcb *pcb, uInt16 len); +err_t tcp_bind (struct tcp_pcb *pcb, struct ip_addr *ipaddr, + uInt16 port); +err_t tcp_connect (struct tcp_pcb *pcb, struct ip_addr *ipaddr, + uInt16 port, err_t (* connected)(void *arg, + struct tcp_pcb *tpcb, + err_t err)); +struct tcp_pcb * tcp_listen (struct tcp_pcb *pcb); +void tcp_abort (struct tcp_pcb *pcb); +err_t tcp_close (struct tcp_pcb *pcb); +err_t tcp_write (struct tcp_pcb *pcb, const void *dataptr, uInt16 len, + uInt8 copy); + +/* It is also possible to call these two functions at the right + intervals (instead of calling tcp_tmr()). */ +void tcp_slowtmr (void); +void tcp_fasttmr (void); + + +/* Only used by IP to pass a TCP segment to TCP: */ +void tcp_input (struct pbuf *p, struct netif *inp); +/* Used within the TCP code only: */ +err_t tcp_output (struct tcp_pcb *pcb); + + + + +#define TCP_SEQ_LT(a,b) ((Int32)((a)-(b)) < 0) +#define TCP_SEQ_LEQ(a,b) ((Int32)((a)-(b)) <= 0) +#define TCP_SEQ_GT(a,b) ((Int32)((a)-(b)) > 0) +#define TCP_SEQ_GEQ(a,b) ((Int32)((a)-(b)) >= 0) + +#define TCP_FIN 0x01 +#define TCP_SYN 0x02 +#define TCP_RST 0x04 +#define TCP_PSH 0x08 +#define TCP_ACK 0x10 +#define TCP_URG 0x20 + +/* Length of the TCP header, excluding options. */ +#define TCP_HLEN 20 + +#define TCP_TMR_INTERVAL 100 /* The TCP timer interval in + milliseconds. */ + +#define TCP_FAST_INTERVAL 200 /* the fine grained timeout in + milliseconds */ +#define TCP_SLOW_INTERVAL 500 /* the coarse grained timeout in + milliseconds */ +#define TCP_FIN_WAIT_TIMEOUT 20000 /* milliseconds */ +#define TCP_SYN_RCVD_TIMEOUT 20000 /* milliseconds */ + +#define TCP_OOSEQ_TIMEOUT 6 /* x RTO */ + +#define TCP_MSL 60000 /* The maximum segment lifetime in microseconds */ + +struct tcp_hdr { + PACK_STRUCT_FIELD(uInt16 src); + PACK_STRUCT_FIELD(uInt16 dest); + PACK_STRUCT_FIELD(uInt32 seqno); + PACK_STRUCT_FIELD(uInt32 ackno); + PACK_STRUCT_FIELD(uInt16 _offset_flags); + PACK_STRUCT_FIELD(uInt16 wnd); + PACK_STRUCT_FIELD(uInt16 chksum); + PACK_STRUCT_FIELD(uInt16 urgp); +} PACK_STRUCT_STRUCT; + +#define TCPH_OFFSET(hdr) (NTOHS((hdr)->_offset_flags) >> 8) +#define TCPH_FLAGS(hdr) (NTOHS((hdr)->_offset_flags) & 0xff) + +#define TCPH_OFFSET_SET(hdr, offset) (hdr)->_offset_flags = HTONS(((offset) << 8) | TCPH_FLAGS(hdr)) +#define TCPH_FLAGS_SET(hdr, flags) (hdr)->_offset_flags = HTONS((TCPH_OFFSET(hdr) << 8) | (flags)) + +#define TCP_TCPLEN(seg) ((seg)->len + ((TCPH_FLAGS((seg)->tcphdr) & TCP_FIN || \ + TCPH_FLAGS((seg)->tcphdr) & TCP_SYN)? 1: 0)) + +enum tcp_state { + CLOSED = 0, + LISTEN = 1, + SYN_SENT = 2, + SYN_RCVD = 3, + ESTABLISHED = 4, + FIN_WAIT_1 = 5, + FIN_WAIT_2 = 6, + CLOSE_WAIT = 7, + CLOSING = 8, + LAST_ACK = 9, + TIME_WAIT = 10 +}; + + +/* the TCP protocol control block */ +struct tcp_pcb { + struct tcp_pcb *next; /* for the linked list */ + + enum tcp_state state; /* TCP state */ + + void *callback_arg; + + /* Function to call when a listener has been connected. */ + err_t (* accept)(void *arg, struct tcp_pcb *newpcb, err_t err); + + struct ip_addr local_ip; + uInt16 local_port; + + struct ip_addr remote_ip; + uInt16 remote_port; + + /* receiver varables */ + uInt32 rcv_nxt; /* next seqno expected */ + uInt16 rcv_wnd; /* receiver window */ + + /* Timers */ + uInt16 tmr; + + /* Retransmission timer. */ + uInt8 rtime; + + uInt16 mss; /* maximum segment size */ + + uInt8 flags; +#define TF_ACK_DELAY 0x01 /* Delayed ACK. */ +#define TF_ACK_NOW 0x02 /* Immediate ACK. */ +#define TF_INFR 0x04 /* In fast recovery. */ +#define TF_RESET 0x08 /* Connection was reset. */ +#define TF_CLOSED 0x10 /* Connection was sucessfully closed. */ +#define TF_GOT_FIN 0x20 /* Connection was closed by the remote end. */ + + /* RTT estimation variables. */ + uInt16 rttest; /* RTT estimate in 500ms ticks */ + uInt32 rtseq; /* sequence number being timed */ + Int32 sa, sv; + + uInt16 rto; /* retransmission time-out */ + uInt8 nrtx; /* number of retransmissions */ + + /* fast retransmit/recovery */ + uInt32 lastack; /* Highest acknowledged seqno. */ + uInt8 dupacks; + + /* congestion avoidance/control variables */ + uInt16 cwnd; + uInt16 ssthresh; + + /* sender variables */ + uInt32 snd_nxt, /* next seqno to be sent */ + snd_max, /* Highest seqno sent. */ + snd_wnd, /* sender window */ + snd_wl1, snd_wl2, + snd_lbb; + + uInt16 snd_buf; /* Avaliable buffer space for sending. */ + uInt8 snd_queuelen; + + /* Function to be called when more send buffer space is avaliable. */ + err_t (* sent)(void *arg, struct tcp_pcb *pcb, uInt16 space); + uInt16 acked; + + /* Function to be called when (in-sequence) data has arrived. */ + err_t (* recv)(void *arg, struct tcp_pcb *pcb, struct pbuf *p, err_t err); + struct pbuf *recv_data; + + /* Function to be called when a connection has been set up. */ + err_t (* connected)(void *arg, struct tcp_pcb *pcb, err_t err); + + /* Function which is called periodically. */ + err_t (* poll)(void *arg, struct tcp_pcb *pcb); + + /* Function to be called whenever a fatal error occurs. */ + void (* errf)(void *arg, err_t err); + + uInt8 polltmr, pollinterval; + + /* These are ordered by sequence number: */ + struct tcp_seg *unsent; /* Unsent (queued) segments. */ + struct tcp_seg *unacked; /* Sent but unacknowledged segments. */ +#if TCP_QUEUE_OOSEQ + struct tcp_seg *ooseq; /* Received out of sequence segments. */ +#endif /* TCP_QUEUE_OOSEQ */ + +}; + +struct tcp_pcb_listen { + struct tcp_pcb_listen *next; /* for the linked list */ + + enum tcp_state state; /* TCP state */ + + void *callback_arg; + + /* Function to call when a listener has been connected. */ + void (* accept)(void *arg, struct tcp_pcb *newpcb); + + struct ip_addr local_ip; + uInt16 local_port; +}; + +/* This structure is used to repressent TCP segments. */ +struct tcp_seg { + struct tcp_seg *next; /* used when putting segements on a queue */ + struct pbuf *p; /* buffer containing data + TCP header */ + void *dataptr; /* pointer to the TCP data in the pbuf */ + uInt16 len; /* the TCP length of this segment */ + struct tcp_hdr *tcphdr; /* the TCP header */ +}; + +/* Internal functions and global variables: */ +struct tcp_pcb *tcp_pcb_copy(struct tcp_pcb *pcb); +void tcp_pcb_purge(struct tcp_pcb *pcb); +void tcp_pcb_remove(struct tcp_pcb **pcblist, struct tcp_pcb *pcb); + +uInt8 tcp_segs_free(struct tcp_seg *seg); +uInt8 tcp_seg_free(struct tcp_seg *seg); +struct tcp_seg *tcp_seg_copy(struct tcp_seg *seg); + +#define tcp_ack(pcb) if((pcb)->flags & TF_ACK_DELAY) { \ + (pcb)->flags |= TF_ACK_NOW; \ + tcp_output(pcb); \ + } else { \ + (pcb)->flags |= TF_ACK_DELAY; \ + } + +#define tcp_ack_now(pcb) (pcb)->flags |= TF_ACK_NOW; \ + tcp_output(pcb) + +err_t tcp_send_ctrl(struct tcp_pcb *pcb, uInt8 flags); +err_t tcp_enqueue(struct tcp_pcb *pcb, void *dataptr, uInt16 len, + uInt8 flags, uInt8 copy, + uInt8 *optdata, uInt8 optlen); + +void tcp_rexmit_seg(struct tcp_pcb *pcb, struct tcp_seg *seg); + +void tcp_rst(uInt32 seqno, uInt32 ackno, + struct ip_addr *local_ip, struct ip_addr *remote_ip, + uInt16 local_port, uInt16 remote_port); + +uInt32 tcp_next_iss(void); + +extern uInt32 tcp_ticks; + +#if TCP_DEBUG || TCP_INPUT_DEBUG || TCP_OUTPUT_DEBUG +void tcp_debug_print(struct tcp_hdr *tcphdr); +void tcp_debug_print_flags(uInt8 flags); +void tcp_debug_print_state(enum tcp_state s); +void tcp_debug_print_pcbs(void); +int tcp_pcbs_sane(void); +#else +#define tcp_pcbs_sane() 1 +#endif /* TCP_DEBUG */ + + +/* The TCP PCB lists. */ +extern struct tcp_pcb_listen *tcp_listen_pcbs; /* List of all TCP PCBs in LISTEN state. */ +extern struct tcp_pcb *tcp_active_pcbs; /* List of all TCP PCBs that are in a + state in which they accept or send + data. */ +extern struct tcp_pcb *tcp_tw_pcbs; /* List of all TCP PCBs in TIME-WAIT. */ + +extern struct tcp_pcb *tcp_tmp_pcb; /* Only used for temporary storage. */ + +/* Axoims about the above lists: + 1) Every TCP PCB that is not CLOSED is in one of the lists. + 2) A PCB is only in one of the lists. + 3) All PCBs in the tcp_listen_pcbs list is in LISTEN state. + 4) All PCBs in the tcp_tw_pcbs list is in TIME-WAIT state. +*/ + +/* Define two macros, TCP_REG and TCP_RMV that registers a TCP PCB + with a PCB list or removes a PCB from a list, respectively. */ +#ifdef LWIP_DEBUG +#define TCP_REG(pcbs, npcb) do {\ + DEBUGF(TCP_DEBUG, ("TCP_REG %p local port %d\n", npcb, npcb->local_port)); \ + for(tcp_tmp_pcb = *pcbs; \ + tcp_tmp_pcb != NULL; \ + tcp_tmp_pcb = tcp_tmp_pcb->next) { \ + ASSERT("TCP_REG: already registered\n", tcp_tmp_pcb != npcb); \ + } \ + ASSERT("TCP_REG: pcb->state != CLOSED", npcb->state != CLOSED); \ + npcb->next = *pcbs; \ + ASSERT("TCP_REG: npcb->next != npcb", npcb->next != npcb); \ + *pcbs = npcb; \ + ASSERT("TCP_RMV: tcp_pcbs sane", tcp_pcbs_sane()); \ + } while(0) +#define TCP_RMV(pcbs, npcb) do { \ + ASSERT("TCP_RMV: pcbs != NULL", *pcbs != NULL); \ + DEBUGF(TCP_DEBUG, ("TCP_RMV: removing %p from %p\n", npcb, *pcbs)); \ + if(*pcbs == npcb) { \ + *pcbs = (*pcbs)->next; \ + } else for(tcp_tmp_pcb = *pcbs; tcp_tmp_pcb != NULL; tcp_tmp_pcb = tcp_tmp_pcb->next) { \ + if(tcp_tmp_pcb->next != NULL && tcp_tmp_pcb->next == npcb) { \ + tcp_tmp_pcb->next = npcb->next; \ + break; \ + } \ + } \ + npcb->next = NULL; \ + ASSERT("TCP_RMV: tcp_pcbs sane", tcp_pcbs_sane()); \ + DEBUGF(TCP_DEBUG, ("TCP_RMV: removed %p from %p\n", npcb, *pcbs)); \ + } while(0) + +#else /* LWIP_DEBUG */ +#define TCP_REG(pcbs, npcb) do { \ + npcb->next = *pcbs; \ + *pcbs = npcb; \ + } while(0) +#define TCP_RMV(pcbs, npcb) do { \ + if(*pcbs == npcb) { \ + *pcbs = (*pcbs)->next; \ + } else for(tcp_tmp_pcb = *pcbs; tcp_tmp_pcb != NULL; tcp_tmp_pcb = tcp_tmp_pcb->next) { \ + if(tcp_tmp_pcb->next != NULL && tcp_tmp_pcb->next == npcb) { \ + tcp_tmp_pcb->next = npcb->next; \ + break; \ + } \ + } \ + npcb->next = NULL; \ + } while(0) +#endif /* LWIP_DEBUG */ +#endif /* __LWIP_TCP_H__ */ + + + diff --git a/src/sys/include/net/tcpip.h b/src/sys/include/net/tcpip.h new file mode 100644 index 0000000..1b74d57 --- /dev/null +++ b/src/sys/include/net/tcpip.h @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2001, Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce 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 Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (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 file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + * $Id$ + */ +#ifndef __LWIP_TCPIP_H__ +#define __LWIP_TCPIP_H__ + +#include "net/api_msg.h" +#include "net/pbuf.h" + +void tcpip_init(void (* tcpip_init_done)(void *), void *arg); +void tcpip_apimsg(struct api_msg *apimsg); +err_t tcpip_input(struct pbuf *p, struct netif *inp); + +enum tcpip_msg_type { + TCPIP_MSG_API, + TCPIP_MSG_INPUT +}; + +struct tcpip_msg { + enum tcpip_msg_type type; + sys_sem_t *sem; + union { + struct api_msg *apimsg; + struct { + struct pbuf *p; + struct netif *netif; + } inp; + } msg; +}; + + +#endif /* __LWIP_TCPIP_H__ */ diff --git a/src/sys/include/net/udp.h b/src/sys/include/net/udp.h new file mode 100644 index 0000000..c4c8693 --- /dev/null +++ b/src/sys/include/net/udp.h @@ -0,0 +1,102 @@ +/* + * Copyright (c) 2001, Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce 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 Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (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 file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + * $Id$ + */ +#ifndef __LWIP_UDP_H__ +#define __LWIP_UDP_H__ + +#include "net/arch.h" + +#include "net/pbuf.h" +//UBU +#include "net/ipv4/inet.h" +//UBU +#include "net/ipv4/ip.h" + +#include "net/err.h" + +#define UDP_HLEN 8 + +struct udp_hdr { + PACK_STRUCT_FIELD(uInt16 src); + PACK_STRUCT_FIELD(uInt16 dest); /* src/dest UDP ports */ + PACK_STRUCT_FIELD(uInt16 len); + PACK_STRUCT_FIELD(uInt16 chksum); +} PACK_STRUCT_STRUCT; + +#define UDP_FLAGS_NOCHKSUM 0x01 +#define UDP_FLAGS_UDPLITE 0x02 + +struct udp_pcb { + struct udp_pcb *next; + + struct ip_addr local_ip, remote_ip; + uInt16 local_port, remote_port; + + uInt8 flags; + uInt16 chksum_len; + + void (* recv)(void *arg, struct udp_pcb *pcb, struct pbuf *p, + struct ip_addr *addr, uInt16 port); + void *recv_arg; +}; + +/* The following functions is the application layer interface to the + UDP code. */ +struct udp_pcb * udp_new (void); +void udp_remove (struct udp_pcb *pcb); +err_t udp_bind (struct udp_pcb *pcb, struct ip_addr *ipaddr, + uInt16 port); +err_t udp_connect (struct udp_pcb *pcb, struct ip_addr *ipaddr, + uInt16 port); +void udp_recv (struct udp_pcb *pcb, + void (* recv)(void *arg, struct udp_pcb *upcb, + struct pbuf *p, + struct ip_addr *addr, + uInt16 port), + void *recv_arg); +err_t udp_send (struct udp_pcb *pcb, struct pbuf *p); + +#define udp_flags(pcb) ((pcb)->flags) +#define udp_setflags(pcb, f) ((pcb)->flags = (f)) + + +/* The following functions is the lower layer interface to UDP. */ +uInt8 udp_lookup (struct ip_hdr *iphdr, struct netif *inp); +void udp_input (struct pbuf *p, struct netif *inp); +void udp_init (void); + + +#endif /* __LWIP_UDP_H__ */ + + diff --git a/src/sys/include/netif/arp.h b/src/sys/include/netif/arp.h new file mode 100644 index 0000000..d799678 --- /dev/null +++ b/src/sys/include/netif/arp.h @@ -0,0 +1,95 @@ +/* + * Copyright (c) 2001, Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the Swedish Institute + * of Computer Science and its contributors. + * 4. Neither the name of the Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (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 file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + * $Id$ + * + */ + +#ifndef __NETIF_ARP_H__ +#define __NETIF_ARP_H__ + +#include "net/pbuf.h" +#include "net/ipv4/ip_addr.h" +#include "net/netif.h" + +struct eth_addr { + PACK_STRUCT_FIELD(uInt8 addr[6]); +} PACK_STRUCT_STRUCT; + +struct eth_hdr { + PACK_STRUCT_FIELD(struct eth_addr dest); + PACK_STRUCT_FIELD(struct eth_addr src); + PACK_STRUCT_FIELD(uInt16 type); +} PACK_STRUCT_STRUCT; + +#define ARP_TMR_INTERVAL 10000 + +#define ETHTYPE_ARP 0x0806 +#define ETHTYPE_IP 0x0800 + +/* Initializes ARP. */ +void arp_init(void); + +/* The arp_tmr() function should be called every ARP_TMR_INTERVAL + microseconds (10 seconds). This function is responsible for + expiring old entries in the ARP table. */ +void arp_tmr(void); + +/* Should be called for all incoming packets of IP kind. The function + does not alter the packet in any way, it just updates the ARP + table. After this function has been called, the normal TCP/IP stack + input function should be called. */ +void arp_ip_input(struct netif *netif, struct pbuf *p); + +/* Should be called for incoming ARP packets. The pbuf in the argument + is freed by this function. If the function returns a pbuf (i.e., + returns non-NULL), that pbuf constitutes an ARP reply and should be + sent out on the Ethernet. */ +struct pbuf *arp_arp_input(struct netif *netif, struct eth_addr *ethaddr, + struct pbuf *p); + +/* arp_loopup() is called to do an IP address -> Ethernet address + translation. If the function returns NULL, there is no mapping and + the arp_query() function should be called. */ +struct eth_addr *arp_lookup(struct ip_addr *ipaddr); + +/* Constructs an ARP query packet for the given IP address. The + function returns a pbuf that contains the reply and that should be + sent out on the Ethernet. */ +struct pbuf *arp_query(struct netif *netif, struct eth_addr *ethaddr, + struct ip_addr *ipaddr); + +#endif /* __NETIF_ARP_H__ */ diff --git a/src/sys/include/netif/ethernetif.h b/src/sys/include/netif/ethernetif.h new file mode 100644 index 0000000..5ea4e5d --- /dev/null +++ b/src/sys/include/netif/ethernetif.h @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2001, Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce 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 Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (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 file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + * $Id$ + */ +#ifndef __NETIF_ETHERNETIF_H__ +#define __NETIF_ETHERNETIF_H__ + +#include "net/netif.h" + +void ethernetif_init(struct netif *netif); + +#endif /* __NETIF_ETHERNETIF_H__ */ diff --git a/src/sys/include/netif/loopif.h b/src/sys/include/netif/loopif.h new file mode 100644 index 0000000..fbbf744 --- /dev/null +++ b/src/sys/include/netif/loopif.h @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2001, Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce 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 Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (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 file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + * $Id$ + */ +#ifndef __NETIF_LOOPIF_H__ +#define __NETIF_LOOPIF_H__ + +#include "net/netif.h" + +void loopif_init(struct netif *netif); + +#endif /* __NETIF_LOOPIF_H__ */ diff --git a/src/sys/include/netif/tcpdump.h b/src/sys/include/netif/tcpdump.h new file mode 100644 index 0000000..d2d6afc --- /dev/null +++ b/src/sys/include/netif/tcpdump.h @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2001, Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce 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 Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (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 file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + * $Id$ + */ +#ifndef __NETIF_TCPDUMP_H__ +#define __NETIF_TCPDUMP_H__ + +#include "net/pbuf.h" + +void tcpdump_init(void); +void tcpdump(struct pbuf *p); + +#endif /* __NETIF_TCPDUMP_H__ */ diff --git a/src/sys/include/objgfx/ogDisplay_VESA.h b/src/sys/include/objgfx/ogDisplay_VESA.h new file mode 100755 index 0000000..00b8e4a --- /dev/null +++ b/src/sys/include/objgfx/ogDisplay_VESA.h @@ -0,0 +1,95 @@ +#ifndef OGDISPLAY_VESA_H +#define OGDISPLAY_VESA_H + +#include "objgfx30.h" + +struct TMode_Rec { + uInt16 ModeAttributes __attribute__((packed)); + uInt8 WindowAFlags __attribute__((packed)); + uInt8 WindowBFlags __attribute__((packed)); + uInt16 Granularity __attribute__((packed)); + uInt16 WindowSize __attribute__((packed)); + uInt16 WindowASeg __attribute__((packed)); + uInt16 WindowBSeg __attribute__((packed)); + void* BankSwitch __attribute__((packed)); + uInt16 BytesPerLine __attribute__((packed)); + uInt16 xRes __attribute__((packed)); + uInt16 yRes __attribute__((packed)); + uInt8 CharWidth __attribute__((packed)); + uInt8 CharHeight __attribute__((packed)); + uInt8 NumBitPlanes __attribute__((packed)); + uInt8 BitsPerPixel __attribute__((packed)); + uInt8 NumberOfBanks __attribute__((packed)); + uInt8 MemoryModel __attribute__((packed)); + uInt8 BankSize __attribute__((packed)); + uInt8 NumOfImagePages __attribute__((packed)); + uInt8 Reserved __attribute__((packed)); + // Direct colour fields (required for Direct/6 and YUV/7 memory models + uInt8 RedMaskSize __attribute__((packed)); + uInt8 RedFieldPosition __attribute__((packed)); + uInt8 GreenMaskSize __attribute__((packed)); + uInt8 GreenFieldPosition __attribute__((packed)); + uInt8 BlueMaskSize __attribute__((packed)); + uInt8 BlueFieldPosition __attribute__((packed)); + uInt8 AlphaMaskSize __attribute__((packed)); + uInt8 AlphaFieldPosition __attribute__((packed)); + uInt8 DirectColourMode __attribute__((packed)); + // VESA 2.0 specific fields + uInt32 physBasePtr __attribute__((packed)); + void* OffScreenMemOffset __attribute__((packed)); + uInt16 OffScreenMemSize __attribute__((packed)); + uInt8 paddington[461] __attribute__((packed)); +}; + +struct TVESA_Rec { + char VBESignature[4] __attribute__((packed)); + uInt8 minVersion __attribute__((packed)); + uInt8 majVersion __attribute__((packed)); + uInt32 OEMStringPtr __attribute__((packed)); + uInt32 Capabilities __attribute__((packed)); + uInt32 VideoModePtr __attribute__((packed)); + uInt16 TotalMemory __attribute__((packed)); + // VESA 2.0 specific fields + uInt16 OEMSoftwareRev __attribute__((packed)); + uInt32 OEMVendorNamePtr __attribute__((packed)); + uInt32 OEMProductNamePtr __attribute__((packed)); + uInt32 OEMProductRevPtr __attribute__((packed)); + uInt8 paddington[474] __attribute__((packed)); +}; + +class ogDisplay_VESA : public ogSurface { + protected: + uInt16 ScreenSelector; + TVESA_Rec* VESARec; + TMode_Rec* ModeRec; + bool InGraphics; + uInt16 findMode(uInt32, uInt32, uInt32); + void getModeInfo(uInt16); + void getVESAInfo(void); + void setMode(uInt16); + virtual uInt32 rawGetPixel(uInt32, uInt32); + virtual void rawSetPixel(uInt32, uInt32, uInt32); + virtual void rawLine(uInt32, uInt32, uInt32, uInt32, uInt32); + void setPal(void); + public: + ogDisplay_VESA(void); + virtual bool ogAvail(void); + virtual bool ogAlias(ogSurface&, uInt32, uInt32, uInt32, uInt32); + virtual void ogClear(uInt32); + virtual bool ogClone(ogSurface&); + virtual void ogCopyLineTo(uInt32, uInt32, const void *, uInt32); + virtual void ogCopyLineFrom(uInt32, uInt32, void *, uInt32); + virtual void ogCopyPal(ogSurface&); + virtual bool ogCreate(uInt32, uInt32, ogPixelFmt); + virtual uInt32 ogGetPixel(int32, int32); + virtual void * ogGetPtr(uInt32, uInt32); + virtual void ogHLine(int32, int32, int32, uInt32); + virtual bool ogLoadPal(const char *); + virtual void ogSetPixel(int32, int32, uInt32); + virtual void ogSetRGBPalette(uInt8, uInt8, uInt8, uInt8); + virtual void ogVFlip(void); + virtual void ogVLine(int32, int32, int32, uInt32); + virtual ~ogDisplay_VESA(void); +}; // ogDisplay_VESA + +#endif diff --git a/src/sys/include/pci/hd.h b/src/sys/include/pci/hd.h new file mode 100644 index 0000000..f484e50 --- /dev/null +++ b/src/sys/include/pci/hd.h @@ -0,0 +1,39 @@ +#ifndef _HD_H +#define _HD_H + +#define hdData 0x0 +#define hdError 0x1 +#define hdSecCount 0x2 +#define hdSecNum 0x3 +#define hdCylLow 0x4 +#define hdCylHi 0x5 +#define hdHead 0x6 +#define hdStat 0x7 +#define hdCmd 0x7 + + +struct driveInfo { + char hdSector[512]; + char hdEnable; + char hdDev; + char hdFlags; + char hdShift; + long hdMask; + long hdMulti; + long hdPort; + long hdSize; + long hdCalc; + }; + +void initHardDisk(); +int initDrive(struct driveInfo *); +void hdWrite(struct driveInfo *hdd,long startSector,long sectorCount,void *baseAddr); +void hdRead(struct driveInfo *hdd,long startSector,long sectorCount,void *baseAddr); + +extern struct driveInfo *hdd0; +extern struct driveInfo *hdd1; +extern struct driveInfo *hdd2; +extern struct driveInfo *hdd3; + +#endif + diff --git a/src/sys/include/pci/lnc.h b/src/sys/include/pci/lnc.h new file mode 100644 index 0000000..ec867f4 --- /dev/null +++ b/src/sys/include/pci/lnc.h @@ -0,0 +1,157 @@ +#ifndef _LNC_H +#define _LNC_H + +#include + +#define NDESC(len2) (1 << len2) +#define NORMAL 0 +#define MEM_SLEW 8 +#define TRANSBUFSIZE 1518 +#define RECVBUFSIZE 1518 +#define NRDRE 3 +#define NTDRE 3 +#define ETHER_ADDR_LEN 6 +#define NE2100_IOSIZE 24 +#define PCNET_RDP 0x10 /* Register Data Port */ +#define PCNET_RAP 0x12 /* Register Address Port */ +#define PCNET_RESET 0x14 +#define PCNET_BDP 0x16 +#define PCNET_VSW 0x18 +#define NE2100 2 + +/* mem_mode values */ +#define DMA_FIXED 1 +#define DMA_MBUF 2 +#define SHMEM 4 + + +/********** Chip Types **********/ +#define UNKNOWN 0 /* Unknown */ +#define LANCE 1 /* Am7990 */ +#define C_LANCE 2 /* Am79C90 */ +#define PCnet_ISA 3 /* Am79C960 */ +#define PCnet_ISAplus 4 /* Am79C961 */ +#define PCnet_ISA_II 5 /* Am79C961A */ +#define PCnet_32 6 /* Am79C965 */ +#define PCnet_PCI 7 /* Am79C970 */ +#define PCnet_PCI_II 8 /* Am79C970A */ +#define PCnet_FAST 9 /* Am79C971 */ +#define PCnet_FASTplus 10 /* Am79C972 */ +#define PCnet_Home 11 /* Am79C978 */ + +/******** AM7990 Specifics **************/ +#define CSR0 0x0000 +#define CSR1 1 +#define CSR2 2 +#define CSR3 3 +#define CSR88 88 +#define CSR89 89 + +#define ERR 0x8000 +#define BABL 0x4000 +#define CERR 0x2000 +#define MISS 0x1000 +#define MERR 0x0800 +#define RINT 0x0400 +#define TINT 0x0200 +#define IDON 0x0100 +#define INTR 0x0080 +#define INEA 0x0040 +#define RXON 0x0020 +#define TXON 0x0010 +#define TDMD 0x0008 +#define STOP 0x0004 +#define STRT 0x0002 +#define INIT 0x0001 + + +/* CSR88-89: Chip ID masks */ +#define AMD_MASK 0x003 +#define PART_MASK 0xffff +#define Am79C960 0x0003 +#define Am79C961 0x2260 +#define Am79C961A 0x2261 +#define Am79C965 0x2430 +#define Am79C970 0x0242 +#define Am79C970A 0x2621 +#define Am79C971 0x2623 +#define Am79C972 0x2624 +#define Am79C973 0x2625 +#define Am79C978 0x2626 + +/********** Structs **********/ + + + + +struct initBlock { + uInt16 mode; /* Mode register */ + uInt8 padr[6]; /* Ethernet address */ + uInt8 ladrf[8]; /* Logical address filter (multicast) */ + uInt16 rdra; /* Low order pointer to receive ring */ + uInt16 rlen; /* High order pointer and no. rings */ + uInt16 tdra; /* Low order pointer to transmit ring */ + uInt16 tlen; /* High order pointer and no rings */ + }; + +struct mds { + uInt16 md0; + uInt16 md1; + short md2; + uInt16 md3; + }; + +struct hostRingEntry { + struct mds *md; + union { + //struct mbuf *mbuf; + char *data; + }buff; + }; + +struct arpcom { + //struct ifnet ac_if; /* network-visible interface */ + uInt8 ac_enaddr[6]; /* ethernet hardware address */ + int ac_multicnt; /* length of ac_multiaddrs list */ + void *ac_netgraph; /* ng_ether(4) netgraph node info */ + }; + +struct nicInfo { + int ident; /* Type of card */ + int ic; /* Type of ic, Am7990, Am79C960 etc. */ + int memMode; + int iobase; + int mode; /* Mode setting at initialization */ + }; + +struct lncInfo { + struct arpcom arpcom; + struct nicInfo nic; + struct hostRingEntry *recvRing; + struct hostRingEntry *transRings; + struct initBlock *initBloack; + int rap; + int rdp; + int bdp; + int nrdre; + int ntdre; + }; + +extern struct lncInfo *lnc; + +void writeCsr(struct lncInfo *lnc, uInt16 port, uInt16 val); +uInt16 readCsr(struct lncInfo *lnc, uInt16 port); +void writeBcr(struct lncInfo *lnc, uInt16 port, uInt16 val); +uInt16 readBcr(struct lncInfo *lnc, uInt16 port); + +void initLNC(); +int probe(struct lncInfo *lnc); +int lanceProbe(struct lncInfo *lnc); +int lncAttach(struct lncInfo *lnc,int unit); + + +void lncInt(); +void _lncInt(); + +#endif + diff --git a/src/sys/include/pci/pci.h b/src/sys/include/pci/pci.h new file mode 100644 index 0000000..23a846e --- /dev/null +++ b/src/sys/include/pci/pci.h @@ -0,0 +1,79 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#ifndef _PCI_H +#define _PCI_H + +#include + + +struct pciConfig { + uInt16 vendorId; + uInt16 deviceId; + + uInt16 command; + uInt16 status; + + uInt8 revisionId; + uInt8 interface; + uInt8 subClass; + uInt8 baseClass; + + uInt8 cacheLineSize; + uInt8 latencyTimer; + uInt8 headerType; + uInt8 bist; + + /* device info */ + uInt8 bus; + uInt8 dev; + uInt8 func; + uInt8 irq; + + /* base registers */ + uInt32 base[6]; + uInt32 size[6]; + + uInt16 subsysVendor; + uInt16 subsys; + + }; + +struct confadd { + uInt8 reg:8; + uInt8 func:3; + uInt8 dev:5; + uInt8 bus:8; + uInt8 rsvd:7; + uInt8 enable:1; + }; + +#define countof(a) (sizeof(a) / sizeof(a[0])) + +int pciInit(); +bool pciProbe(int bus,int dev,int func,struct pciConfig *cfg); +uInt32 pciRead(int bus, int dev, int func, int reg, int bytes); +void pciWrite(int bus,int dev,int func,int reg,uInt32 v,int bytes); + +#endif + diff --git a/src/sys/include/sde/ogDisplay_UbixOS.h b/src/sys/include/sde/ogDisplay_UbixOS.h new file mode 100755 index 0000000..74531a9 --- /dev/null +++ b/src/sys/include/sde/ogDisplay_UbixOS.h @@ -0,0 +1,87 @@ +#ifndef OGDISPLAY_UBIXOS_H +#define OGDISPLAY_UBIXOS_H + +#include + +struct ogModeInfo { + uInt16 modeAttributes __attribute__((packed)); + uInt8 windowAFlags __attribute__((packed)); + uInt8 windowBFlags __attribute__((packed)); + uInt16 granularity __attribute__((packed)); + uInt16 windowSize __attribute__((packed)); + uInt16 windowASeg __attribute__((packed)); + uInt16 windowBSeg __attribute__((packed)); + void* bankSwitch __attribute__((packed)); + uInt16 bytesPerLine __attribute__((packed)); + uInt16 xRes __attribute__((packed)); + uInt16 yRes __attribute__((packed)); + uInt8 charWidth __attribute__((packed)); + uInt8 charHeight __attribute__((packed)); + uInt8 numBitPlanes __attribute__((packed)); + uInt8 bitsPerPixel __attribute__((packed)); + uInt8 numberOfBanks __attribute__((packed)); + uInt8 memoryModel __attribute__((packed)); + uInt8 bankSize __attribute__((packed)); + uInt8 numOfImagePages __attribute__((packed)); + uInt8 reserved __attribute__((packed)); + // Direct colour fields (required for Direct/6 and YUV/7 memory models + uInt8 redMaskSize __attribute__((packed)); + uInt8 redFieldPosition __attribute__((packed)); + uInt8 greenMaskSize __attribute__((packed)); + uInt8 greenFieldPosition __attribute__((packed)); + uInt8 blueMaskSize __attribute__((packed)); + uInt8 blueFieldPosition __attribute__((packed)); + uInt8 alphaMaskSize __attribute__((packed)); + uInt8 alphaFieldPosition __attribute__((packed)); + uInt8 directColourMode __attribute__((packed)); + // VESA 2.0 specific fields + uInt32 physBasePtr __attribute__((packed)); + void* offScreenMemOffset __attribute__((packed)); + uInt16 offScreenMemSize __attribute__((packed)); + uInt8 paddington[461] __attribute__((packed)); +}; + +struct ogVESAInfo { + char VBESignature[4] __attribute__((packed)); + uInt8 minVersion __attribute__((packed)); + uInt8 majVersion __attribute__((packed)); + uInt32 OEMStringPtr __attribute__((packed)); + uInt32 capabilities __attribute__((packed)); + uInt32 videoModePtr __attribute__((packed)); + uInt16 totalMemory __attribute__((packed)); + // VESA 2.0 specific fields + uInt16 OEMSoftwareRev __attribute__((packed)); + uInt32 OEMVendorNamePtr __attribute__((packed)); + uInt32 OEMProductNamePtr __attribute__((packed)); + uInt32 OEMProductRevPtr __attribute__((packed)); + uInt8 paddington[474] __attribute__((packed)); +}; + + +class ogDisplay_UbixOS : public ogSurface { + protected: + void * pages[2]; + uInt32 activePage; + uInt32 visualPage; + ogVESAInfo * VESAInfo; + ogModeInfo * modeInfo; + + uInt16 FindMode(uInt32, uInt32, uInt32); + void GetModeInfo(uInt16); + void GetVESAInfo(void); + void SetMode(uInt16); + void SetPal(void); + public: + ogDisplay_UbixOS(void); + virtual bool Alias(ogSurface&, uInt32, uInt32, uInt32, uInt32); + virtual bool Clone(ogSurface&); + virtual void CopyPalette(ogSurface&); + virtual bool Create(uInt32, uInt32, ogPixelFmt); + virtual bool LoadPalette(const char *); + virtual void SetPalette(const ogRGBA8[]); + virtual void SetPalette(uInt8, uInt8, uInt8, uInt8); + virtual void SetPalette(uInt8, uInt8, uInt8, uInt8, uInt8); + virtual ~ogDisplay_UbixOS(void); +}; // ogDisplay_UbixOS + +#endif diff --git a/src/sys/include/sde/sde.h b/src/sys/include/sde/sde.h new file mode 100644 index 0000000..0b27d5d --- /dev/null +++ b/src/sys/include/sde/sde.h @@ -0,0 +1,55 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#ifndef _SDE_H +#define _SDE_H + +#include + +#define registerWindow 1 +#define windowReady 2 +#define drawWindow 3 +#define killWindow 4 + +#ifdef __cplusplus +extern "C" +#endif +void sdeThread(); + +#ifdef __cplusplus +extern "C" +#endif +void sysSDE(uInt32 cmd,void *ptr); + +struct sdeWindows { + struct sdeWindows *next; + struct sdeWindows *prev; + void *buf; + pidType pid; + uInt8 status; + }; + +extern struct sdeWindows *windows; + +#endif + diff --git a/src/sys/include/stdarg.h b/src/sys/include/stdarg.h new file mode 100644 index 0000000..b191b0f --- /dev/null +++ b/src/sys/include/stdarg.h @@ -0,0 +1,43 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#ifndef _STDARG_H +#define _STDARG_H + +typedef char *vaList[1]; + +#define vaStart(ap, parm) ((ap)[0] = (char *) &parm \ + + ((sizeof(parm) + sizeof(int) - 1) & ~(sizeof(int) - 1)), (void) 0) + +#define vaArg(ap, type) ((ap)[0] += \ + ((sizeof(type) + sizeof(int) - 1) & ~(sizeof(int) - 1)), \ + (*(type *) ((ap)[0] \ + - ((sizeof(type) + sizeof(int) - 1) & ~(sizeof(int) - 1)) ))) + +#define vaEnd(ap) ((ap)[0] = 0, (void) 0) + + +int vsprintf(char *buf, const char *fmt, vaList args); + +#endif + diff --git a/src/sys/include/string.h b/src/sys/include/string.h new file mode 100644 index 0000000..9df2183 --- /dev/null +++ b/src/sys/include/string.h @@ -0,0 +1,36 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#ifndef _STRING_H +#define _STRING_H + +#include + +void * kmemcpy(void * dst, const void * src, size_t length); +void *kmemset(void * dst, int c, size_t length); +int kstrlen(const char * string); + +int sprintf(char * str, const char * format, ...); + +#endif + diff --git a/src/sys/include/sys/_types.h b/src/sys/include/sys/_types.h new file mode 100644 index 0000000..0dc67df --- /dev/null +++ b/src/sys/include/sys/_types.h @@ -0,0 +1,33 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#ifndef __TYPES_H +#define __TYPES_H + +#include + +typedef unsigned long __clock_t; +typedef long __time_t; + +#endif + diff --git a/src/sys/include/sys/cdefs.h b/src/sys/include/sys/cdefs.h new file mode 100644 index 0000000..64ea869 --- /dev/null +++ b/src/sys/include/sys/cdefs.h @@ -0,0 +1,37 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#ifndef _CDEFS_H +#define _CDRES_H + +#include + +#define __dead2 __attribute__((__noreturn__)) + + +#endif + +/*** + END + ***/ + diff --git a/src/sys/include/sys/device.h b/src/sys/include/sys/device.h new file mode 100644 index 0000000..ecd8cb2 --- /dev/null +++ b/src/sys/include/sys/device.h @@ -0,0 +1,58 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#ifndef _DEVICE_H +#define _DEVICE_H + +#include + +struct device { + struct net *net; + uInt16 ioAddr; + uInt32 irq; + struct ei_device *priv; + uInt32 mtu; + }; + +struct net { + char mac[6]; + char broadcast[6]; + }; + +struct ei_device { + int txStartPage; + int rxStartPage; + int stopPage; + int currentPage; + uInt16 word16; + uInt32 pingPong; + int tx1; + int tx2; + }; + +#endif + +/*** + END + ***/ + diff --git a/src/sys/include/sys/dma.h b/src/sys/include/sys/dma.h new file mode 100644 index 0000000..1fba28b --- /dev/null +++ b/src/sys/include/sys/dma.h @@ -0,0 +1,33 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#ifndef _DMA_H +#define _DMA_H + +#include + +void dmaXfer(uChar channel,uLong address,uInt length,uChar read); +void _dmaXfer(uChar dmaChannel,uChar page,uInt offset,uInt length,uChar mode); + +#endif + diff --git a/src/sys/include/sys/driver.h b/src/sys/include/sys/driver.h new file mode 100644 index 0000000..b3b77ce --- /dev/null +++ b/src/sys/include/sys/driver.h @@ -0,0 +1,48 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#ifndef _DRIVER_H +#define _DRIVER_H + +#include + + +typedef struct devMethodType devMethod; + +struct devMethodType { + }; + +struct driverType { + const char *devName; + devMethod *methods; + } + + + + +#endif + +/*** + END + ***/ + diff --git a/src/sys/include/sys/drives.h b/src/sys/include/sys/drives.h new file mode 100644 index 0000000..01d78c5 --- /dev/null +++ b/src/sys/include/sys/drives.h @@ -0,0 +1,66 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#ifndef _DRIVES_H +#define _DRIVES_H + +#include + +#define MAXPARTITIONS 4 + +struct driveDiskLabel { + uInt32 magicNum; + uInt32 magicNum2; + uInt16 driveType; + uInt16 numPartitions; + struct drivePartitions { //the partition table + uInt32 pSize; //number of sectors in partition + uInt32 pOffset; //starting sector + uInt32 pFsSize; //filesystem basic fragment size + uInt32 pBatSize; //BAT size + uInt8 pFsType; //filesystem type, see below + uInt8 pFrag; //filesystem fragments per block + } partitions[MAXPARTITIONS]; + }; + +struct driveDriver { + struct driveDriver *prev; + struct driveDriver *next; + struct driveDiskLabel *diskLabel; + int id; + void *driveInfoStruct; + char driveType; + void (*read)(void *,long,long,void *); + void (*write)(void *,long,long,void *); + void (*reset)(void *); + }; + + +extern struct driveDriver *drives; +extern int currentDrive; + +void addDrive(int id,char type,void *driveInfoStruct,void *read,void *write,void *reset); +struct driveDriver *findDrive(int id); + +#endif + diff --git a/src/sys/include/sys/gdt.h b/src/sys/include/sys/gdt.h new file mode 100644 index 0000000..a38e234 --- /dev/null +++ b/src/sys/include/sys/gdt.h @@ -0,0 +1,88 @@ + + + +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#ifndef _GDT_H +#define _GDT_H + +/* Descriptor Definitions */ +#define dCall 0x0C00 /* 386 Call Gate */ +#define dCode 0x1800 /* Code Segment */ +#define dData 0x1000 /* Data Segment */ +#define dInt 0x0E00 /* 386 Interrupt Gate */ +#define dLdt 0x200 /* Local Descriptor Table (LDT) */ +#define dTask 0x500 /* Task gate */ +#define dTrap 0x0F00 /* 386 Trap Gate */ +#define dTss 0x900 /* Task State Segment (TSS) */ + +/* Descriptor Options */ +#define dDpl3 0x6000 /* DPL3 or mask for DPL */ +#define dDpl2 0x4000 /* DPL2 or mask for DPL */ +#define dDpl1 0x2000 /* DPL1 or mask for DPL */ +#define dPresent 0x8000 /* Present */ +#define dNpresent 0x8000 /* Not Present */ +#define dAcc 0x100 /* Accessed (Data or Code) */ +#define dWrite 0x200 /* Writable (Data segments only) */ +#define dRead 0x200 /* Readable (Code segments only) */ +#define dBusy 0xB00 /* Busy (TSS only) was 200 */ +#define dEexdown 0x400 /* Expand down (Data segments only) */ +#define dConform 0x400 /* Conforming (Code segments only) */ +#define dBig 0x40 /* Default to 32 bit mode */ +#define dBiglim 0x80 /* Limit is in 4K units */ + +/* GDT Descriptor */ +struct gdtDescriptor { + unsigned short limitLow; /* Limit 0..15 */ + unsigned short baseLow; /* Base 0..15 */ + unsigned char baseMed; /* Base 16..23 */ + unsigned char access; /* Access Byte */ + unsigned int limitHigh:4; /* Limit 16..19 */ + unsigned int granularity:4; /* Granularity */ + unsigned char baseHigh; /* Base 24..31 */ + } __attribute__ ((packed)); + +struct gdtGate { + unsigned short offsetLow; /* Offset 0..15 */ + unsigned short selector; /* Selector */ + unsigned short access; /* Access Flags */ + unsigned short offsetHigh; /* Offset 16..31 */ + } __attribute__ ((packed)); + +union descriptorTableunion { + struct gdtDescriptor descriptor; /* Normal descriptor */ + struct gdtGate gate; /* Gate descriptor */ + unsigned long dummy; /* Any other info */ + }; + + +#define descriptorTable(name,length) union descriptorTableunion name[length] = +#define standardDescriptor(base, limit, control) {descriptor: {(limit & 0xffff), (base & 0xffff), ((base >> 16) & 0xff), \ + ((control+dPresent) >> 8), (limit >> 16), \ + ((control & 0xff) >> 4), (base >> 24)}} +#define gateDescriptor(offset, selector, control) {gate: {(offset & 0xffff), selector, \ + (control+dPresent), (offset >> 16) }} + +#endif + diff --git a/src/sys/include/sys/idt.h b/src/sys/include/sys/idt.h new file mode 100644 index 0000000..ef5a0af --- /dev/null +++ b/src/sys/include/sys/idt.h @@ -0,0 +1,57 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#ifndef _IDT_H +#define _IDT_H + +#include +#include + +#define EFLAG_TF 0x100 +#define EFLAG_IF 0x200 +#define EFLAG_IOPL3 0x3000 +#define EFLAG_VM 0x20000 + +int idtInit(); +void setVector(void *handler, unsigned char interrupt, unsigned short controlMajor); +void setTaskVector(uInt8 interrupt,uInt16 controlMajor,uInt8 selector); +void intNull(); + +void _int0(); +void _int1(); +void _int2(); +void _int3(); +void _int4(); +void _int5(); +void _int6(); +void _int7(); +void _int8(); +void _int9(); +void _int10(); +void _int11(); +void _int12(); +void _int13(); +void timerInt(); + +#endif + diff --git a/src/sys/include/sys/io.h b/src/sys/include/sys/io.h new file mode 100644 index 0000000..53aba4a --- /dev/null +++ b/src/sys/include/sys/io.h @@ -0,0 +1,36 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#ifndef _IO_H +#define _IO_H + +inline unsigned char inportByte(unsigned int); +inline unsigned short inportWord(unsigned int); +inline unsigned long inportDWord(unsigned int); +inline void outportByte(unsigned int,unsigned char); +inline void outportByteP(unsigned int port,unsigned char value); +inline void outportWord(unsigned int,unsigned short); +inline void outportDWord(unsigned int port,unsigned long value); + +#endif + diff --git a/src/sys/include/sys/tss.h b/src/sys/include/sys/tss.h new file mode 100644 index 0000000..ca2b7fb --- /dev/null +++ b/src/sys/include/sys/tss.h @@ -0,0 +1,79 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#ifndef _TSS_H +#define _TSS_H + +struct tssStruct { + short back_link; + short back_link_reserved; + long esp0; + short ss0; + short ss0_reserved; + long esp1; + short ss1; + short ss1_reserved; + long esp2; + short ss2; + short ss2_reserved; + long cr3; + long eip; + long eflags; + long eax,ecx,edx,ebx; + long esp; + long ebp; + long esi; + long edi; + short es; + short es_reserved; + short cs; + short cs_reserved; + short ss; + short ss_reserved; + short ds; + short ds_reserved; + short fs; + short fs_reserved; + short gs; + short gs_reserved; + short ldt; + short ldt_reserved; + //long trace_bitmap; /* bits: trace 0, bitmap 16-31 */ + short trace_bitmap; + short io_map; + char io_space[8192]; + }; + +struct i387Struct { + long cwd; + long swd; + long twd; + long fip; + long fcs; + long foo; + long fos; + long st_space[20]; /* 8*10 bytes for each FP-reg = 80 bytes */ + }; + +#endif + diff --git a/src/sys/include/sys/video.h b/src/sys/include/sys/video.h new file mode 100644 index 0000000..e26f7bb --- /dev/null +++ b/src/sys/include/sys/video.h @@ -0,0 +1,38 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#ifndef _VIDEO_H +#define _VIDEO_H + +#include + +#define defaultColor 0x0F + +extern int printColor; + +void clearScreen(); +void kprint(char *string); +void backSpace(); + +#endif + diff --git a/src/sys/include/ubixfs/ubixfs.h b/src/sys/include/ubixfs/ubixfs.h new file mode 100644 index 0000000..da67636 --- /dev/null +++ b/src/sys/include/ubixfs/ubixfs.h @@ -0,0 +1,126 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#ifndef _UBIXFS_H +#define _UBIXFS_H + +#include +#include +#include + +#define UBIXDISKMAGIC ((uInt32)0x45) /* The disk magic number */ +#define MAXUBIXPARTITIONS 16 +#define blockSize 8 +#define blockByteSize blockSize*512 + +#define EOBC -1 + + +#define typeFile 1 +#define typeContainer 2 +#define typeDirectory 4 +#define typeDeleted 8 + +//Partition Information +struct ubixDiskLabel { + uInt32 magicNum; + uInt32 magicNum2; + uShort driveType; + uShort numPartitions; + struct ubixPartitions { //the partition table + uInt32 pSize; //number of sectors in partition + uInt32 pOffset; //starting sector + uInt32 pFsSize; //filesystem basic fragment size + uInt32 pBatSize; //BAT size + uChar pFsType; //filesystem type, see below + uChar pFrag; //filesystem fragments per block + } partitions[MAXUBIXPARTITIONS]; + }; + + +struct partitionInformation { + uInt32 size; //Size In Sectors + uInt32 startSector; //Base Sector Of Partition + uInt32 blockAllocationTable; //Base Sector Of BAT + uInt32 rootDirectory; //Base Sector Of Root Directory + }; + +//Block Allocation Table Entry +struct blockAllocationTableEntry { + long attributes; //Block Attributes + long realSector; //Real Sector + long nextBlock; //Sector Of Next Block + long reserved; //Reserved + }; + +//UbixFS Directory Entry +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 + uShort attributes; //Files Attributes + uShort permissions; //Files Permissions + char fileName[256]; //File Name + }; + +struct bootSect { + uChar jmp[4]; + uChar id[6]; + uShort version; + uShort tmp; + uShort fsStart; + uShort tmp2; + uInt32 krnl_start; + uInt BytesPerSector; + uInt SectersPerTrack; + uInt TotalHeads; + uInt32 TotalSectors; + uChar code[479]; + }; + +struct ubixFsInfo { + struct blockAllocationTableEntry *blockAllocationTable; + uInt32 batEntries; + }; + +int readFile(char *file); +int writeFileByte(int ch,fileDescriptor *fd,long offset); +int openFileUbixFS(char *file,fileDescriptor *fd); +int mkDirUbixFS(char *dir,fileDescriptor *fd); +int getFreeBlocks(int count,fileDescriptor *fd); +//extern struct ubixDiskLabel *diskLabel; + +//Good Functions +void initUbixFS(struct mountPoints *mp); +int enableUbixFS(); +int readUbixFS(fileDescriptor *fd,char *data,long offset,long size); +int writeUbixFS(fileDescriptor *fd,char *data,long offset,long size); +void syncBat(struct mountPoints *mp); +int freeBlocks(int block,fileDescriptor *fd); +int addDirEntry(struct directoryEntry *dir,fileDescriptor *fd); +void ubixFSUnlink(char *path,struct mountPoints *mp); + +#endif diff --git a/src/sys/include/ubixos/elf.h b/src/sys/include/ubixos/elf.h new file mode 100644 index 0000000..5d0cc5d --- /dev/null +++ b/src/sys/include/ubixos/elf.h @@ -0,0 +1,127 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#ifndef _ELF_H +#define _ELF_H + +#include + +#define elfExecutable 0x002 +#define elfLibrary 0x003 + + +/* 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 +/* End Elf Program Header Types */ + +typedef struct { + uChar eIdent[16]; /* File identification. */ + uShort eType; /* File type. */ + uShort eMachine; /* Machine architecture. */ + uLong eVersion; /* ELF format version. */ + uLong eEntry; /* Entry point. */ + uLong ePhoff; /* Program header file offset. */ + uLong eShoff; /* Section header file offset. */ + uLong eFlags; /* Architecture-specific flags. */ + uShort eEhsize; /* Size of ELF header in bytes. */ + uShort ePhentsize; /* Size of program header entry. */ + uShort ePhnum; /* Number of program header entries. */ + uShort eShentsize; /* Size of section header entry. */ + uShort eShnum; /* Number of section header entries. */ + uShort eShstrndx; /* Section name strings section. */ + } elfHeader; + +typedef struct { + uLong phType; /* Entry type. */ + uLong phOffset; /* File offset of contents. */ + uLong phVaddr; /* Virtual address in memory image. */ + uLong phPaddr; /* Physical address (not used). */ + uLong phFilesz; /* Size of contents in file. */ + uLong phMemsz; /* Size of contents in memory. */ + uLong phFlags; /* Access permission flags. */ + uLong phAlign; /* Alignment in memory and file. */ + } elfProgramheader; + +typedef struct { + uLong shName; /* Section name (index into the section header string table). */ + uLong shType; /* Section type. */ + uLong shFlags; /* Section flags. */ + uLong shAddr; /* Address in memory image. */ + uLong shOffset; /* Offset in file. */ + uLong shSize; /* Size in bytes. */ + uLong shLink; /* Index of a related section. */ + uLong shInfo; /* Depends on section type. */ + uLong shAddralign; /* Alignment in bytes. */ + uLong shEntsize; /* Size of each entry in section. */ + } elfSectionheader; + +typedef struct { + uLong pltOffset; + uLong pltInfo; + } elfPltInfo; + +typedef struct { + uLong dynName; + uLong dynValue; + uLong dynSize; + uLong dynInfo; + } elfDynsym; + +typedef struct { + uInt32 dynVal; + uInt32 dynPtr; + } elfDynamic; + +char *elfGetShType(int); +char *elfGetPhType(int); + +#endif + diff --git a/src/sys/include/ubixos/exec.h b/src/sys/include/ubixos/exec.h new file mode 100644 index 0000000..c16393f --- /dev/null +++ b/src/sys/include/ubixos/exec.h @@ -0,0 +1,33 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#ifndef _EXEC_H +#define _EXEC_H + +#include +#include + +uInt32 execThread(void (* tproc)(void),int stack,char *arg,char *descr); +void execFile(char *file,int argc,char **argv,int console); + +#endif diff --git a/src/sys/include/ubixos/fork.h b/src/sys/include/ubixos/fork.h new file mode 100644 index 0000000..6a6a38f --- /dev/null +++ b/src/sys/include/ubixos/fork.h @@ -0,0 +1,35 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#ifndef _FORK_H +#define _FORK_H + +#include +#include + +void sysFork(); + +int forkCopyProcess(struct taskStruct *newProcess,long ebp,long edi,long esi,long none,long ebx,long ecx,long edx,long eip,long cs,long eflags,long esp,long ss); + +#endif + diff --git a/src/sys/include/ubixos/idletask.h b/src/sys/include/ubixos/idletask.h new file mode 100644 index 0000000..ebfc2fb --- /dev/null +++ b/src/sys/include/ubixos/idletask.h @@ -0,0 +1,32 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#ifndef _IDLETASK_H +#define _IDLETASK_H + +#include + +void idleTask(); + +#endif + diff --git a/src/sys/include/ubixos/kpanic.h b/src/sys/include/ubixos/kpanic.h new file mode 100644 index 0000000..60df9d7 --- /dev/null +++ b/src/sys/include/ubixos/kpanic.h @@ -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$ + +**************************************************************************************/ + +#ifndef _KPANIC_H +#define _KPANIC_H + +void kpanic(const char *fmt, ...); + +#endif + +/*** + END + ***/ + diff --git a/src/sys/include/ubixos/ld.h b/src/sys/include/ubixos/ld.h new file mode 100644 index 0000000..dd701e1 --- /dev/null +++ b/src/sys/include/ubixos/ld.h @@ -0,0 +1,36 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#ifndef _LD_H +#define _LD_H + +#include + +void ld(int,int); + +#endif + +/*** + END + ***/ + diff --git a/src/sys/include/ubixos/sched.h b/src/sys/include/ubixos/sched.h new file mode 100644 index 0000000..f2e4a73 --- /dev/null +++ b/src/sys/include/ubixos/sched.h @@ -0,0 +1,90 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#ifndef _SCHED_H +#define _SCHED_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include +#include +#include + + +typedef enum { DEAD=-1,NEW=0,READY=1,RUNNING=2,IDLE=3 } tState; + +struct osInfo { + struct mountPoints *container; + elfSectionheader *sectionHeader; + struct taskFileInfo fileInfo; + struct consoleStruct *terminal; + uInt16 sectionCount; + uInt16 stringSection; + uInt8 timer; + uInt8 v86Task; + bool v86If; + uInt32 curDir; + uInt32 vmStart; + uInt32 stdinSize; + uInt32 controlKeys; + char *stdin; + char *shstrtab; + char *cwd; + }; + +typedef struct taskStruct { + pidType id; + struct taskStruct *prev; + struct taskStruct *next; + struct tssStruct tss; + struct i387Struct i387; + struct osInfo oInfo; + tState state; + uInt32 gid; + uInt32 uid; + uInt16 usedMath; + } kTask_t; + + +int schedInit(); +void sched(); +void schedYield(); +int schedEndTask(pidType pid); +kTask_t *schedNewTask(); +kTask_t *schedFindTask(uInt32 id); +int deleteTask(uInt32); + +extern kTask_t *taskList; +extern uInt32 nextID; +extern kTask_t *_current; +extern kTask_t *_usedMath; + +#ifdef __cplusplus +} +#endif + +#endif + diff --git a/src/sys/include/ubixos/syscall.h b/src/sys/include/ubixos/syscall.h new file mode 100644 index 0000000..0dc55f7 --- /dev/null +++ b/src/sys/include/ubixos/syscall.h @@ -0,0 +1,31 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#ifndef _SYSCALL_H +#define _SYSCALL_H + +void _sysCall(); +void invalidCall(); + +#endif + diff --git a/src/sys/include/ubixos/syscalls.h b/src/sys/include/ubixos/syscalls.h new file mode 100644 index 0000000..c4b2b92 --- /dev/null +++ b/src/sys/include/ubixos/syscalls.h @@ -0,0 +1,116 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#ifndef _SYSCALLS_H +#define _SYSCALLS_H + +#include +#include + +void sysGetpid(); +void sysExit(); +void sysExec(); +void sysFork(); +void sysCheckPid(); +void sysGetFreePage(); + +void sysFwrite(); +void sysFgetc(); +void sysFopen(); +void sysFread(); +void sysFclose(); +void sysSchedYield(); +void sysFseek(); +void sysMkDir(); +void sysRmDir(); +void sysGetUid(); +void sysGetGid(); +void sysSetUid(); +void sysSetGid(); +void sysSDE(); +void sysGetDrives(); +void sysGetCwd(); +void sysChDir(); +void sysGetUptime(); +void sysGetTime(); +void sysStartSDE(); +void sysUnlink(); + +typedef void (*functionPTR)(); + +functionPTR systemCalls[] = { + invalidCall, /** 0 **/ + sysGetpid, /** 1 **/ + sysExit, /** 2 **/ + sysExec, /** 3 **/ + sysFork, /** 4 **/ + sysFgetc, /** 5 **/ + sysCheckPid, /** 6 **/ + sysGetFreePage, /** 7 **/ + sysFopen, /** 8 **/ + invalidCall, /** 9 **/ + sysFclose, /** 10 **/ + sysSchedYield, /** 11 **/ + invalidCall, /** 12 **/ + invalidCall, /** 13 **/ + invalidCall, /** 14 **/ + invalidCall, /** 15 **/ + invalidCall, /** 16 **/ + invalidCall, /** 17 **/ + invalidCall, /** 18 **/ + invalidCall, /** 19 **/ + sysFopen, /** 20 Opens A File Node **/ + sysFclose, /** 21 Closes A File Node **/ + sysFread, /** 22 File Read **/ + sysFwrite, /** 23 File Write **/ + sysMkDir, /** 24 Make Directory **/ + sysRmDir, /** 25 Remove Directory **/ + sysGetCwd, /** 26 Get Current Working Dir **/ + sysFseek, /** 27 Set FD Position **/ + sysChDir, /** 28 Change Dir **/ + sysMkDir, /** 29 Create Directory **/ + sysUnlink, /** 30 Unlink **/ + sysGetUid, /** 31 Get User Id **/ + sysGetGid, /** 32 Get Group Id **/ + sysSetUid, /** 33 Set User Id **/ + sysSetGid, /** 34 Set Group Id **/ + invalidCall, /** 35 **/ + invalidCall, /** 36 **/ + invalidCall, /** 37 **/ + invalidCall, /** 38 **/ + invalidCall, /** 39 **/ + sysSDE, /** 40 SDE Kernel Interface **/ + invalidCall, /** 41 **/ + invalidCall, /** 42 **/ + invalidCall, /** 43 **/ + invalidCall, /** 44 **/ + sysGetDrives, /** 45 Get Drives **/ + sysGetUptime, /** 46 Get Uptime **/ + sysGetTime, /** 47 Get Time **/ + sysStartSDE, /** 48 start SDE **/ + }; + +int totalCalls = sizeof(systemCalls)/sizeof(functionPTR); + +#endif + diff --git a/src/sys/include/ubixos/time.h b/src/sys/include/ubixos/time.h new file mode 100644 index 0000000..b2553a0 --- /dev/null +++ b/src/sys/include/ubixos/time.h @@ -0,0 +1,84 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#ifndef _TIME_H +#define _TIME_H + +#include +#include + +typedef long suseconds_t; + +#define BCD_TO_BIN(val) ((val)=((val)&15) + ((val)>>4)*10) + +#define MINUTE 60 +#define HOUR (60*MINUTE) +#define DAY (24*HOUR) +#define YEAR (365*DAY) + +#ifndef _TIME_T_DECLARED +typedef __time_t time_t; +#define _TIME_T_DECLARED +#endif + +struct timespec { + time_t tv_sec; /* seconds */ + long tv_nsec; /* and nanoseconds */ +}; + + + +struct timeStruct { + int sec; + int min; + int hour; + int day; + int mon; + int year; + }; + + +struct timezone { + int tz_minuteswest; /* minutes west of Greenwich */ + int tz_dsttime; /* type of dst correction */ + }; + +struct timeval { + long tv_sec; /* seconds (XXX should be time_t) */ + suseconds_t tv_usec; /* and microseconds */ + }; + +int gettimeofday(struct timeval *tp,struct timezone *tzp); + + + +int timeInit(); +int timeCmosRead(int); +uInt32 timeMake(struct timeStruct *time); + +#endif + +/*** + END + ***/ + diff --git a/src/sys/include/ubixos/times.h b/src/sys/include/ubixos/times.h new file mode 100644 index 0000000..c8a0aa1 --- /dev/null +++ b/src/sys/include/ubixos/times.h @@ -0,0 +1,47 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#ifndef _TIMES_H +#define _TIMES_H + +#include +#include + +#ifndef _CLOCK_T_DECLARED +typedef __clock_t clock_t; +#define _CLOCK_T_DECLARED +#endif + +struct tms { + clock_t tms_utime; /* User CPU time */ + clock_t tms_stime; /* System CPU time */ + clock_t tms_cutime; /* User CPU time of terminated child procs */ + clock_t tms_cstime; /* System CPU time of terminated child procs */ +}; + +#endif + +/*** + END + ***/ + diff --git a/src/sys/include/ubixos/types.h b/src/sys/include/ubixos/types.h new file mode 100644 index 0000000..8119bb5 --- /dev/null +++ b/src/sys/include/ubixos/types.h @@ -0,0 +1,61 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#ifndef _TYPES_H +#define _TYPES_H + +#include + +#ifndef NULL +#define NULL 0x0 +#endif + +typedef unsigned char byte; /* 8-bit byte */ +typedef unsigned short word; /* 16-bit word */ +typedef unsigned long dWord; /* 32-bit dword */ + +typedef unsigned char uChar; +typedef unsigned long uLong; +typedef unsigned short uShort; +typedef unsigned int uInt; + +typedef unsigned char uInt8; +typedef unsigned short uInt16; +typedef unsigned long uInt32; +typedef char Int8; +typedef short Int16; +typedef long Int32; + +typedef unsigned char uint8_t; +typedef unsigned short uint16_t; +typedef unsigned int uint32_t; + +typedef int pidType; + +typedef int pid_t; +typedef int size_t; /* standart */ +#ifndef NOBOOL +typedef enum { FALSE=0,TRUE=1 } bool; +#endif + +#endif diff --git a/src/sys/include/ubixos/ubthread.h b/src/sys/include/ubixos/ubthread.h new file mode 100644 index 0000000..c889919 --- /dev/null +++ b/src/sys/include/ubixos/ubthread.h @@ -0,0 +1,83 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#ifndef _UBTHREAD_H +#define _UBTHREAD_H + +#include +#include +#include + +#define ETIMEDOUT -1 + +#define LOCKED 1 +#define UNLOCKED 0 + +typedef struct ubthread *ubthread_t; +typedef struct ubthread_cond *ubthread_cond_t; +typedef struct ubthread_mutex *ubthread_mutex_t; + +struct ubthread { + kTask_t *task; + }; + +struct ubthread_cond { + int id; + uInt8 locked; + }; + +struct ubthread_mutex { + int id; + uInt8 locked; + pidType pid; + }; + +struct ubthread_list { + struct ubthread_list *next; + ubthread_t thread; + }; + +struct ubthread_cond_list { + struct ubthread_cond_list *next; + ubthread_cond_t *cond; + }; + +struct ubthread_mutex_list { + struct ubthread_mutex_list *next; + ubthread_mutex_t *mutex; + }; + + +kTask_t *ubthread_self(); +int ubthread_cond_init(ubthread_cond_t *cond,const uInt32 attr); +int ubthread_mutex_init(ubthread_mutex_t *mutex,const uInt32 attr); +int ubthread_cond_destroy(ubthread_cond_t *cond); +int ubthread_mutex_destroy(ubthread_mutex_t *mutex); +int ubthread_create(kTask_t **thread,const uInt32 *attr,void *start_routine, void *arg); +int ubthread_mutex_lock(ubthread_mutex_t *mutex); +int ubthread_mutex_unlock(ubthread_mutex_t *mutex); +int ubthread_cond_timedwait(ubthread_cond_t *cond, ubthread_mutex_t *mutex, const struct timespec *abstime); +int ubthread_cond_wait(ubthread_cond_t *cond, ubthread_mutex_t *mutex); +int ubthread_cond_signal(ubthread_cond_t *cond); + +#endif diff --git a/src/sys/include/ubixos/vitals.h b/src/sys/include/ubixos/vitals.h new file mode 100644 index 0000000..a1c0ec1 --- /dev/null +++ b/src/sys/include/ubixos/vitals.h @@ -0,0 +1,51 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#ifndef _VITALS_H +#define _VITALS_H + +#include +#include +#include +#include + +typedef struct vitalsStruct { + uInt32 openFiles; + uInt32 sysTicks; + uInt32 sysUptime; + uInt32 freePages; + struct fileSystem *fileSystems; + struct mountPoints *mountPoints; + uInt32 timeStart; + void *screen; + void *font; + char *packet; + uInt32 packetLength; + } vitalsNode; + +extern vitalsNode *systemVitals; + +int initVitals(); + +#endif + diff --git a/src/sys/include/vfs/file.h b/src/sys/include/vfs/file.h new file mode 100644 index 0000000..32ba8c4 --- /dev/null +++ b/src/sys/include/vfs/file.h @@ -0,0 +1,60 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#ifndef _FILE_H +#define _FILE_H + +#include +#include + +#define SEEK_SET 0x0 + +struct taskFileInfo { + char *cwd; + }; + +typedef struct userFileDescriptorStruct { + struct fileDescriptorStruct *fd; + uInt32 fdSize; + } userFileDescriptor; + +extern fileDescriptor *fdTable; +extern fileDescriptor *lastFd; + +fileDescriptor *fopen(const char *file,const char *flags); +int unlink(const char *path); +int fclose(fileDescriptor *fd); +int feof(fileDescriptor *fd); +int fgetc(fileDescriptor *fd); +size_t fread(void *ptr, size_t size, size_t nmemb,fileDescriptor *fd); +size_t fwrite(void *ptr,int size,int nmemb,fileDescriptor *fd); +int fseek(fileDescriptor *,long,int); + +void sysFseek(userFileDescriptor *,long,int); + +//Good +void sysChDir(const char *path); +void chDir(const char *path); +char *verifyDir(const char *path); + +#endif diff --git a/src/sys/include/vfs/mount.h b/src/sys/include/vfs/mount.h new file mode 100644 index 0000000..ce5114c --- /dev/null +++ b/src/sys/include/vfs/mount.h @@ -0,0 +1,45 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#ifndef _MOUNT_H +#define _MOUNT_H + +#include + +struct mountPoints { + struct mountPoints *prev; + struct mountPoints *next; + struct fileSystem *fs; + struct driveDriver *drive; + void *fsInfo; + int partition; + char mountPoint[1024]; + char perms; + }; + +int mount(int driveId,int partition,int fsType,char *mountPoint,char *perms); +int addMount(struct mountPoints *mp); +struct mountPoints *findMount(char *mountPoint); + +#endif + diff --git a/src/sys/include/vfs/vfs.h b/src/sys/include/vfs/vfs.h new file mode 100644 index 0000000..f2b04fc --- /dev/null +++ b/src/sys/include/vfs/vfs.h @@ -0,0 +1,84 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#ifndef _VFS_H +#define _VFS_H + +#include + +#define maxFd 32 +#define fdAvail 1 +#define fdOpen 2 +#define fdRead 3 +#define fdEof 4 + + +#define fileRead 0x0001 +#define fileWrite 0x0002 +#define fileBinary 0x0004 +#define fileAppend 0x0008 + +typedef struct fileDescriptorStruct { + struct fileDescriptorStruct *prev; + struct fileDescriptorStruct *next; + struct mountPoints *mp; + uInt16 status; + uInt16 mode; + uInt32 offset; + uInt32 size; + uInt16 length; + uInt32 start; + uInt8 fileName[22]; + char *buffer; + uInt32 dirBlock; + uInt32 perms; + } fileDescriptor; + +struct fileSystem { + struct fileSystem *prev; + struct fileSystem *next; + int (*vfsInitFS)(void *); + int (*vfsRead)(void *,char *,long,long); + int (*vfsWrite)(void *,char *,long,long); + int (*vfsOpenFile)(void *,void *); + int (*vfsUnlink)(char *,void *); + int (*vfsMakeDir)(char *,void *); + int (*vfsRemDir)(char *); + int (*vfsSync)(void); + int vfsType; + }; + + +/* VFS Functions */ +int vfsInit(); +int vfsRegisterFS(int,void *,void *,void *,void *,void *,void *,void *,void *); +struct fileSystem *vfsFindFS(int); + + + +//File IO +fileDescriptor *fopen(const char *file,const char *flags); + + +#endif + diff --git a/src/sys/include/vmm/paging.h b/src/sys/include/vmm/paging.h new file mode 100644 index 0000000..02edea4 --- /dev/null +++ b/src/sys/include/vmm/paging.h @@ -0,0 +1,61 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#ifndef _PAGING_H +#define _PAGING_H + +#include + +#define pageLength 0x00000400 +#define pageSize 4096 +#define pageEntries (pageSize/4) +#define pagePresent 0x00000001 +#define pageWrite 0x00000002 +#define pageUser 0x00000004 +#define pageCow 0x00000200 +#define pageStack 0x00000400 +#define pageDefault (pagePresent|pageWrite|pageUser) +#define kernelPageDefault (pagePresent|pageWrite) +#define tablesBaseAddress 0xBFC00000 +#define parentPageDirAddr 0x100000 + +int vmmPagingInit(); +int vmmClearVirtualPage(uInt32 pageAddr); +int vmmRemapPage(uInt32,uInt32); +void vmmUnmapPage(uInt32,int); +void vmmUnmapPages(void *,uInt32); +void vmmSetPageAttribute(uInt32,int); +void *vmmMapFromTask(pidType,void *,uInt32); +void *vmmCopyVirtualSpace(pidType); +void *vmmGetFreePage(pidType); +void *vmmGetFreeKernelPage(pidType pid,uInt16 count); +void *vmmGetPhysicalAddr(uInt32); +void *vmmCreateVirtualSpace(pidType); +void *vmmGetFreeVirtualPage(pidType,int); +void vmmPageFault(); +void _vmmPageFault(); + +extern uInt32 *kernelPageDirectory; + +#endif + diff --git a/src/sys/include/vmm/vmm.h b/src/sys/include/vmm/vmm.h new file mode 100644 index 0000000..244e082 --- /dev/null +++ b/src/sys/include/vmm/vmm.h @@ -0,0 +1,55 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#ifndef _VMM_H +#define _VMM_H + +#include +#include + +#define memAvail 1 +#define memNotavail 2 +#define vmmID -3 +#define vmmMemoryMapAddr 0xE6667000 + +typedef struct { + uLong pageAddr; + uShort status; + pid_t pid; + int cowCounter; + } mMap; + +extern mMap *vmmMemoryMap; +extern int numPages; +extern uInt32 freePages; + +int vmmInit(); +int vmmMemMapInit(); +int countMemory(); +uInt32 vmmFindFreePage(pidType pid); +int freePage(uInt32 pageAddr); +int adjustCowCounter(uInt32 baseAddr,int adjustment); +void vmmFreeProcessPages(pidType pid); + +#endif + diff --git a/src/sys/init/Makefile b/src/sys/init/Makefile new file mode 100644 index 0000000..65360b4 --- /dev/null +++ b/src/sys/init/Makefile @@ -0,0 +1,27 @@ +# (C) 2002 The UbixOS Project +# $Id$ + +# Include Global 'Source' Options +include ../../Makefile.inc +include ../Makefile.inc + +# Objects +OBJS = main.o + +all: $(OBJS) + +# Compile Types +.cc.o: + $(CXX) ${CFLAGS} -Wall -fomit-frame-pointer -O -I../include -c -o $@ $< +.cc.s: + $(CXX) ${CFLAGS} -Wall -fomit-frame-pointer -O -I../include -S -o $@ $< +.c.o: + $(CC) ${CFLAGS} -Wall -fomit-frame-pointer -O -I../include -c -o $@ $< +.c.s: + $(CC) ${CFLAGS} -Wall -fomit-frame-pointer -O -I../include -S -o $@ $< +.S.o: + $(CC) ${CFLAGS} -Wall -fomit-frame-pointer -c -o $@ $< + +# Clean up the junk +clean: + $(REMOVE) $(OBJS) diff --git a/src/sys/init/main.c b/src/sys/init/main.c new file mode 100644 index 0000000..357308b --- /dev/null +++ b/src/sys/init/main.c @@ -0,0 +1,200 @@ +/***************************************************************************************** + 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. + + $Log$ + Revision 1.107 2004/04/13 16:36:33 reddawg + Changed our copyright, it is all now under a BSD-Style license + + + + $Id$ + +*****************************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +char kernelStack[8192]; // Stack Space For Our Kernel + +descriptorTable(GDT,8) { + {dummy:0}, + standardDescriptor(0x0, 0xFFFFF, (dCode + dRead + dBig + dBiglim)), + standardDescriptor(0x0, 0xFFFFF, (dData + dWrite + dBig + dBiglim)), + standardDescriptor(0x0, 0xFFFFF, (dLdt)), + standardDescriptor(0x4200, (sizeof(struct tssStruct)), (dTss)), + standardDescriptor(0x0, 0xFFFFF, (dCode + dWrite + dBig + dBiglim + dDpl3)), + standardDescriptor(0x0, 0xFFFFF, (dData + dWrite + dBig + dBiglim + dDpl3)), + standardDescriptor(0x4200, (sizeof(struct tssStruct)), (dTss)), + }; +struct { + unsigned short limit __attribute__ ((packed)); + union descriptorTableunion *gdt __attribute__ ((packed)); + } loadGdt = { (8 * sizeof(union descriptorTableunion) - 1), GDT }; + + +int main() { + + // Clear the screen so we have a nice pretty starting place for the os to spew its info + clearScreen(); + + // Initialize the kernels vital systems + // This initialization is for the systems memory and memory map for the os to allocate with + if (vmmInit() != 0x0) { + kpanic("Error: Initializing VMM Subsystem.\n"); + } + // This initialization is for the systems vital information + if (initVitals() != 0x0) { + kpanic("Error: Initializing vitals\n"); + } + // This initialization is for the VFS(Virtual file system) layer + if (vfsInit() != 0x0) { + kpanic("Error: Initializing VFS\n"); + } + if (devFSEnable() != 0x0) { + kpanic("Error: Enabling devFS\n"); + } + // This initialization is for the systems PICs for our IRQ handling + if (init8259() != 0x0) { + kpanic("Error: Initializing 8259\n"); + } + // This initialization is for the systems IDT + if (idtInit() != 0x0) { + kpanic("Error: Initializing IDT\n"); + } + // This initialization is for the operating systems scheduler + if (schedInit() != 0x0) { + kpanic("Error: Initializing: Scheduler\n"); + } + // This initialization is for the systems timer + if (pitInit(1000) != 0x0) { + kpanic("Error: Initializing PIT\n"); + } + // This initialization is for the keyboard + if (keyboardInit() != 0x0) { + kpanic("Error: Initializing Keyboard\n"); + } + /* + if (pciInit() != 0x0) { + kpanic("Error: Initializing PCI\n"); + } + */ + if (timeInit() != 0x0) { + kpanic("Error: Initializing TIME\n"); + } + if (ne2kInit(0x240) != 0x0) { + kpanic("Error: Initializing NE2000\n"); + } + enableUbixFS(); + fdcInit(); + initHardDisk(); + if (mount(0x0,0x0,0x0,"sys","rw") != 0x0) { + kprintf("Problem Mounting sys Mount Point\n"); + } + if (mount(0x1,0x0,0x0,"hd","rw") != 0x0) { + kprintf("Problem Mounting hd Mount Point\n"); + } + kprintf("Free Pages: [%i]\n",freePages); + kprintf("MemoryMap: [0x%X]\n",vmmMemoryMap); + kprintf("Starting Os\n"); + netInit(); + execThread(idleTask,(uInt32)(kmalloc(0x2000,sysID)+0x2000),0x0,"Idle Thread"); + execFile("shell@sys",0x0,0x0,0x0); + irqEnable(0x0); + sched(); + return(0x0); + } + +/************************************************************************ + +Function: _start(); +Description: This Is The Kernels Main Entry Point From Here We Must + Re-Setup Our GDT And Set All Registers To Their Default + Values So We Are Sure Of No Error When The OS Boots Up Also + We Have To Quickly Set Up Our Interrupt Table Because We Do + Not Have Any Fault Protection Yet + +Notes: + +02/17/03 - I'm Unhappy With The Infinite Loop I Decided To Do If The Call + To Main Returns I Think I Shall Change It To A Kernel Panic + At A Later Date Then Reboot The Machine + +************************************************************************/ +void _start(void) { + asm ("pushl $2; popf"); + asm volatile( + "lgdtl (loadGdt) \n" + "movw $0x10,%%ax \n" // Select Ring 0 Data Segment + "movw %%ax,%%ds \n" // Set Default Segment + "movw %%ax,%%es \n" // "" "" + "movw %%ax,%%fs \n" // "" "" + "movw %%ax,%%gs \n" // "" "" + "movw %%ax,%%ss \n" // "" "" + "movl $0x2000,%%esp \n" // Set Default Stack Pointer Its The End Of First Page + "movl $0x2000,%%ebp \n" + "mov $0x18,%%ax \n" // Set Up Dummy LDT + "lldt %%ax \n" // Load The Dummy LDT + "mov $0x20,%%ax \n" // Set Up Dummy TSS + "ltr %%ax \n" // Load The Dummy TSS + "ljmp $0x08,$next \n" + "nop\n" + "nop\n" + "next:\n" + : + : "r" (GDT), "p" (kernelStack+8192) + : "%eax" + ); + main(); + kpanic("We Should Not Get This Far\n"); + } + +/*** + END + ***/ + diff --git a/src/sys/isa/8259.c b/src/sys/isa/8259.c new file mode 100644 index 0000000..0ef7be5 --- /dev/null +++ b/src/sys/isa/8259.c @@ -0,0 +1,112 @@ +/***************************************************************************************** + 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. + + $Log$ + Revision 1.6 2004/04/13 16:36:33 reddawg + Changed our copyright, it is all now under a BSD-Style license + + + + $Id$ + +*****************************************************************************************/ + +#include +#include +#include +#include + +unsigned int irqMask = 0xFFFF; + +/************************************************************************ + +Function: int init8259() + +Description: This function will initialize both PICs for all of our IRQs + +Notes: + +02/20/2004 - Approved for quality + +************************************************************************/ +int init8259() { + outportByte(mPic, icw1); /* Initialize Master PIC */ + outportByte(sPic, icw1); /* Initialize Seconary PIC */ + outportByte(mPic+1, mVec); /* Master Interrup Vector */ + outportByte(sPic+1, sVec); /* Secondary Interrupt Vector */ + outportByte(mPic+1, 1<<2); /* Bitmask for cascade on IRQ 2 */ + outportByte(sPic+1, 2); /* Cascade on IRQ 2 */ + outportByte(mPic+1, icw4); /* Finish Primary Initialization */ + outportByte(sPic+1, icw4); /* Finish Seconary Initialization */ + outportByte(mImr, 0xff); /* Mask All Primary Interrupts */ + outportByte(sImr, 0xff); /* Mask All Seconary Interrupts */ + + /* Print out the system info for this */ + kprintf("pic0 - Port: [0x%X]\n",mPic); + kprintf("pic1 - Port: [0x%X]\n",sPic); + + /* Return so the system knows it went well */ + return(0x0); + } + +/************************************************************************ + +Function: int irqEnable() + +Description: This function is used to turn on an IRQ + +Notes: + +02/20/2004 - Approved for quality + +************************************************************************/ +void irqEnable(uInt16 irqNo) { + irqMask &= ~(1 << irqNo); + if (irqNo >= 8) { + irqMask &= ~(1 << 2); + } + outportByte(mPic+1, irqMask & 0xFF); + outportByte(sPic+1, (irqMask >> 8) & 0xFF); + } + +/************************************************************************ + +Function: int irqDisable() + +Description: This function is used to turn off an IRQ + +Notes: + +02/20/2004 - Approved for quality + +************************************************************************/ +void irqDisable(uInt16 irqNo) { + irqMask |= (1 << irqNo); + if ((irqMask & 0xFF00)==0xFF00) { + irqMask |= (1 << 2); + } + outportByte(mPic+1, irqMask & 0xFF); + outportByte(sPic+1, (irqMask >> 8) & 0xFF); + } diff --git a/src/sys/isa/Makefile b/src/sys/isa/Makefile new file mode 100644 index 0000000..b5e2b03 --- /dev/null +++ b/src/sys/isa/Makefile @@ -0,0 +1,27 @@ +# (C) 2002 The UbixOS Project +# $Id$ + +# Include Global 'Source' Options +include ../../Makefile.inc +include ../Makefile.inc + +# Objects +OBJS = ne2k.o atkbd.o fdc.o 8259.o pit.o + +all: $(OBJS) + +# Compile Types +.cc.o: + $(CXX) ${CFLAGS} -Wall -fomit-frame-pointer -O -I../include -c -o $@ $< +.cc.s: + $(CXX) ${CFLAGS} -Wall -fomit-frame-pointer -O -I../include -S -o $@ $< +.c.o: + $(CC) ${CFLAGS} -Wall -fomit-frame-pointer -O -I../include -c -o $@ $< +.c.s: + $(CC) ${CFLAGS} -Wall -fomit-frame-pointer -O -I../include -S -o $@ $< +.S.o: + $(CC) ${CFLAGS} -Wall -fomit-frame-pointer -c -o $@ $< + +# Clean up the junk +clean: + $(REMOVE) $(OBJS) diff --git a/src/sys/isa/atkbd.c b/src/sys/isa/atkbd.c new file mode 100644 index 0000000..79f6747 --- /dev/null +++ b/src/sys/isa/atkbd.c @@ -0,0 +1,461 @@ +/***************************************************************************************** + 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. + + $Log$ + Revision 1.19 2004/04/13 16:36:33 reddawg + Changed our copyright, it is all now under a BSD-Style license + + + + $Id$ + +*****************************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +unsigned int keyMap = 0; +unsigned int ledStatus = 0; + +unsigned int keyboardMap[][8] = { +/* Ascii, Shift, Ctrl, Alt, Num, Caps, Shift Caps, Shift Num */ + { 0, 0, 0, 0, 0, 0, 0, 0}, +/* ESC */ { 0x1B, 0x1B, 0x1B, 0x1B, 0x1B, 0x1B, 0x1B, 0x1B}, +/* 1,! */ { 0x31, 0x21, 0, 0, 0x31, 0x31, 0x21, 0x21}, +/* 2,@ */ { 0x32, 0x40, 0, 0, 0x32, 0x32, 0x40, 0x40}, +/* 3,# */ { 0x33, 0x23, 0, 0, 0x33, 0x33, 0x23, 0x23}, +/* 4,$ */ { 0x34, 0x24, 0, 0, 0x34, 0x34, 0x24, 0x24}, +/* 5,% */ { 0x35, 0x25, 0, 0, 0x35, 0x35, 0x25, 0x25}, +/* 6,^ */ { 0x36, 0x5E, 0, 0, 0x36, 0x36, 0x5E, 0x5E}, +/* 7,& */ { 0x37, 0x26, 0, 0, 0x37, 0x37, 0x26, 0x26}, +/* 8,* */ { 0x38, 0x2A, 0, 0, 0x38, 0x38, 0x2A, 0x2A}, +/* 9.( */ { 0x39, 0x28, 0, 0, 0x39, 0x39, 0x28, 0x28}, +/* 0,) */ { 0x30, 0x29, 0, 0, 0x30, 0x30, 0x29, 0x29}, +/* -,_ */ { 0x2D, 0x5F, 0, 0, 0x2D, 0x2D, 0x5F, 0x5F}, +/* =,+ */ { 0x3D, 0x2B, 0, 0, 0x3D, 0x3D, 0x2B, 0x2B}, +/* 14 */ { 0x08, 0x08, 0x8, 0x8, 0x08, 0x08, 0x08, 0x08}, +/* 15 */ { 0x09, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0x71, 0x51, 0, 0, 0, 0, 0, 0}, +/* */ { 0x77, 0x57, 0, 0, 0, 0, 0, 0}, +/* */ { 0x65, 0x45, 0, 0, 0, 0, 0, 0}, +/* */ { 0x72, 0x52, 0, 0, 0, 0, 0, 0}, +/* */ { 0x74, 0x54, 0, 0, 0, 0, 0, 0}, +/* */ { 0x79, 0x59, 0, 0, 0, 0, 0, 0}, +/* */ { 0x75, 0x55, 0, 0, 0, 0, 0, 0}, +/* */ { 0x69, 0x49, 0, 0, 0, 0, 0, 0}, +/* */ { 0x6F, 0x4F, 0, 0, 0, 0, 0, 0}, +/* */ { 0x70, 0x50, 0, 0, 0, 0, 0, 0}, +/* */ { 0x5B, 0x7B, 0, 0, 0, 0, 0, 0}, +/* */ { 0x5D, 0x7D, 0, 0, 0, 0, 0, 0}, +/* */ { 0x0A, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* a,A */ { 0x61, 0x41, 0x41, 0, 0, 0, 0, 0}, +/* */ { 0x73, 0x53, 0, 0, 0, 0, 0, 0}, +/* */ { 0x64, 0x44, 0, 0, 0, 0, 0, 0}, +/* */ { 0x66, 0x46, 0, 0, 0, 0, 0, 0}, +/* */ { 0x67, 0x47, 0, 0, 0, 0, 0, 0}, +/* */ { 0x68, 0x48, 0, 0, 0, 0, 0, 0}, +/* */ { 0x6A, 0x4A, 0, 0, 0, 0, 0, 0}, +/* */ { 0x6B, 0x4B, 0, 0, 0, 0, 0, 0}, +/* */ { 0x6C, 0x4C, 0, 0, 0, 0, 0, 0}, +/* */ { 0x3B, 0x3A, 0, 0, 0, 0, 0, 0}, +/* */ { 0x27, 0x22, 0, 0, 0, 0, 0, 0}, +/* */ { 0x60, 0x7E, 0, 0, 0, 0, 0, 0}, +/* */ { 0x2A, 0x0, 0, 0, 0, 0, 0, 0}, +/* */ { 0x5C, 0x3C, 0, 0, 0, 0, 0, 0}, +/* */ { 0x7A, 0x5A, 0, 0, 0, 0, 0, 0}, +/* */ { 0x78, 0x58, 0, 0, 0, 0, 0, 0}, +/* c,C */ { 0x63, 0x43, 0x3, 0, 0, 0, 0, 0}, +/* */ { 0x76, 0x56, 0, 0, 0, 0, 0, 0}, +/* */ { 0x62, 0x42, 0, 0, 0, 0, 0, 0}, +/* */ { 0x6E, 0x4E, 0, 0, 0, 0, 0, 0}, +/* */ { 0x6D, 0x4D, 0, 0, 0, 0, 0, 0}, +/* */ { 0x2C, 0x3C, 0, 0, 0, 0, 0, 0}, +/* */ { 0x2E, 0x3E, 0, 0, 0, 0, 0, 0}, +/* */ { 0x2F, 0x3F, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0x20, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* F1 */ { 0x3001, 0, 0, 0x3000, 0, 0, 0, 0}, +/* */ { 0x3C00, 0, 0, 0x3001, 0, 0, 0, 0}, +/* */ { 0x3D00, 0, 0, 0x3002, 0, 0, 0, 0}, +/* */ { 0x3E00, 0, 0, 0x3003, 0, 0, 0, 0}, +/* */ { 0x3F00, 0, 0, 0x3004, 0, 0, 0, 0}, +/* */ { 0x4000, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0x4100, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0x4200, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0x4300, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0x4400, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0x4700, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0x4800, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0x4900, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0x2D, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0x4B00, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0x4C00, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0x4D00, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0x2B, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0x4F00, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0x5000, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0x5100, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0x5200, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0x5300, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 1, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0}, +/* */ { 0, 0, 0, 0, 0, 0, 0, 0} + }; + +/************************************************************************ + +Function: int initKeyboard + +Description: This function is used to turn on the keyboard + +Notes: + +02/20/2004 - Approved for quality + +************************************************************************/ +int keyboardInit() { + + /* Insert the IDT vector for the keyboard handler */ + setVector(&keyboardISR, mVec+1, dPresent + dInt + dDpl3); + + /* Set the LEDS to their defaults */ + setLED(); + + /* Turn on the keyboard vector */ + outportByte(mPic, eoi); + irqEnable(0x1); + outportByte(mPic, eoi); + + /* Print out information on keyboard */ + kprintf("atkbd0 - Address: [0x%X]\n",&keyboardISR); + + /* Return so we know everything went well */ + return(0x0); + } + +/* + * 2-23-2004 mji I think the pusha/popa should be pushal/popal + */ + +asm( + ".globl keyboardISR \n" + "keyboardISR: \n" + " pusha \n" /* Save all registers */ + " call keyboardHandler \n" + " popa \n" + " iret \n" /* Exit interrupt */ + ); + +void keyboardHandler() { + unsigned int key = inportByte(0x60); + kTask_t *tmpTask = 0x0; + + tmpTask = schedFindTask(0); + if (tmpTask->oInfo.stdin == 0x0) { + tmpTask->oInfo.stdin = (char *)kmalloc(256,tmpTask->id); + } + /* Control Key */ + if (key == 0x1D && !(tmpTask->oInfo.controlKeys & controlKey)) { + tmpTask->oInfo.controlKeys |= controlKey; + } + if (key == 0x80 + 0x1D) { + tmpTask->oInfo.controlKeys &= (0xFF - controlKey); + } + /* ALT Key */ + if (key == 0x38 && !(tmpTask->oInfo.controlKeys & altKey)) { + tmpTask->oInfo.controlKeys |= altKey; + } + if (key == 0x80 + 0x38) { + tmpTask->oInfo.controlKeys &= (0xFF - altKey); + } + /* Shift Key */ + if ((key == 0x2A || key == 0x36) && !(tmpTask->oInfo.controlKeys & shiftKey)) { + tmpTask->oInfo.controlKeys |= shiftKey; + } + if ((key == 0x80 + 0x2A) || (key == 0x80 + 0x36)) { + tmpTask->oInfo.controlKeys &= (0xFF - shiftKey); + } + /* Caps Lock */ + if (key == 0x3A) { + ledStatus ^= ledCapslock; + setLED(); + } + /* Num Lock */ + if (key == 0x45) { + ledStatus ^= ledNumlock; + setLED(); + } + /* Scroll Lock */ + if (key == 0x46) { + ledStatus ^= ledScrolllock; + setLED(); + } + /* Pick Which Key Map */ + if (tmpTask->oInfo.controlKeys == 0) { keyMap = 0; } + else if (tmpTask->oInfo.controlKeys == 1) { keyMap = 1; } + else if (tmpTask->oInfo.controlKeys == 2) { keyMap = 2; } + else if (tmpTask->oInfo.controlKeys == 4) { keyMap = 3; } + /* If Key Is Not Null Add It To Handler */ + if (((uInt)(keyboardMap[key][keyMap]) > 0) && ((uInt32)(keyboardMap[key][keyMap]) < 0xFF)) { + switch ((uInt32)keyboardMap[key][keyMap]) { + case 8: + backSpace(); + tmpTask->oInfo.stdin[tmpTask->oInfo.stdinSize] = keyboardMap[key][keyMap]; + tmpTask->oInfo.stdinSize++; + break; + case 0x3: + schedEndTask(tmpTask->id); + break; + default: + tmpTask->oInfo.stdin[tmpTask->oInfo.stdinSize] = keyboardMap[key][keyMap]; + tmpTask->oInfo.stdinSize++; + break; + } + } + else { + switch ((keyboardMap[key][keyMap] >> 8)) { + case 0x30: + kprintf("Changing Consoles[0x%X:0x%X],Free Pages: [%i]\n",_current->id,_current,systemVitals->sysUptime);//schedFindTask(0x0),); + /* changeConsole((keyboardMap[key][keyMap] & 0xFF)); */ + break; + default: + break; + } + } + outportByte(mPic, eoi); + /* Return */ + return; + } + +void setLED() { + outportByte(0x60, 0xED); + while(inportByte(0x64) & 2); + outportByte(0x60, ledStatus); + while(inportByte(0x64) & 2); + } + +/* Temp */ +unsigned char getch() { + uInt8 retKey = 0x0; + uInt32 i = 0x0; + kTask_t *tmpTask = 0x0; + + tmpTask = schedFindTask(0); + + while (tmpTask->oInfo.stdinSize == 0); + retKey = tmpTask->oInfo.stdin[0]; + tmpTask->oInfo.stdinSize--; + + for (i=0x0;ioInfo.stdinSize;i++) { + tmpTask->oInfo.stdin[i] = tmpTask->oInfo.stdin[i+0x1]; + } + return(retKey); + } diff --git a/src/sys/isa/fdc.c b/src/sys/isa/fdc.c new file mode 100644 index 0000000..0a22528 --- /dev/null +++ b/src/sys/isa/fdc.c @@ -0,0 +1,297 @@ +/***************************************************************************************** + 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. + + $Log$ + Revision 1.6 2004/04/13 16:36:33 reddawg + Changed our copyright, it is all now under a BSD-Style license + + + + $Id$ + +*****************************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static volatile bool done = FALSE; +static drvGeom geometry = { dg144Heads,dg144Tracks,dg144Spt }; +static bool diskChange = FALSE; +static bool motor = FALSE; +static int mTick = 0; +static byte fdcTrack = 0xff; +static byte sr0 = 0; +static volatile int timeOut = 0; +static byte statSize = 0; +static byte status[7] = { 0 }; + +unsigned long tbaddr = 0x80000L; + +void fdcInit() { + setVector(floppyIsr, mVec+6, (dInt+dPresent)); + irqEnable(6); + reset(); + addDrive(0,0,0x0,fdcRead,fdcWrite,0x0); + return; + } + +asm( + ".globl floppyIsr \n" + "floppyIsr: \n" + " pusha \n" + " pushw %ds \n" + " pushw %es \n" + " pushw %ss \n" + " pushw %ss \n" + " popw %ds \n" + " popw %es \n" + " call floppyIsrhndlr \n" + " popw %es \n" + " popw %ds \n" + " popa \n" + " iret \n" + ); + +void floppyIsrhndlr() { + done = TRUE; + outportByte(0x20,0x20); + } + +void sendByte(int byte) { + volatile int msr; + int tmo; + for (tmo=0;tmo<128;tmo++) { + msr = inportByte(fdcMsr); + if ((msr & 0xc0) == 0x80) { + outportByte(fdcData,byte); + return; + } + inportByte(0x80); + } + } + +int getByte() { + volatile int msr; + int tmo; + for (tmo=0;tmo<128;tmo++) { + msr = inportByte(fdcMsr); + if ((msr & 0xd0) == 0xd0) { + return inportByte(fdcData); + } + inportByte(0x80); + } + return(-1); + } + +bool fdcRw(int block,byte *blockBuffer,bool read,unsigned long numSectors) { + int head,track,sector,tries, copyCount = 0; + unsigned char *p_tbaddr = (char *)0x80000; + unsigned char *p_blockbuff = blockBuffer; + block2Hts(block,&head,&track,§or); + motorOn(); + if (!read && blockBuffer) { + /* copy data from data buffer into track buffer */ + for (copyCount=0; copyCount<(numSectors*512); copyCount++) { + *p_tbaddr = *p_blockbuff; + p_blockbuff++; + p_tbaddr++; + } + } + for (tries = 0;tries < 3;tries++) { + if (inportByte(fdcDir) & 0x80) { + diskChange = TRUE; + seek(1); /* clear "disk change" status */ + recalibrate(); + motorOff(); + kprint("FDC: Disk change detected. Trying again.\n"); + return fdcRw(block, blockBuffer, read, numSectors); + } + if (!seek(track)) { + motorOff(); + kprintf("FDC: Error seeking to track [%i]\n",block); + return FALSE; + } + outportByte(fdcCcr,0); + if (read) { + dmaXfer(2,tbaddr,numSectors*512,FALSE); + sendByte(cmdRead); + } + else { + dmaXfer(2,tbaddr,numSectors*512,TRUE); + sendByte(cmdWrite); + } + sendByte(head << 2); + sendByte(track); + sendByte(head); + sendByte(sector); + sendByte(2); /* 512 bytes/sector */ + sendByte(geometry.spt); + if (geometry.spt == dg144Spt) { + sendByte(dg144Gap3rw); /* gap 3 size for 1.44M read/write */ + } + else { + sendByte(dg168Gap3rw); /* gap 3 size for 1.68M read/write */ + } + sendByte(0xff); /* DTL = unused */ + if (!waitFdc(TRUE)) { + kprint("Timed out, trying operation again after reset()\n"); + reset(); + return fdcRw(block, blockBuffer, read, numSectors); + } + if ((status[0] & 0xc0) == 0) break; /* worked! outta here! */ + recalibrate(); /* oops, try again... */ + } + motorOff(); + if (read && blockBuffer) { + p_blockbuff = blockBuffer; + p_tbaddr = (char *) 0x80000; + for (copyCount=0; copyCount<(numSectors*512); copyCount++) { + *p_blockbuff = *p_tbaddr; + p_blockbuff++; + p_tbaddr++; + } + } + return (tries != 3); + } + +void block2Hts(int block,int *head,int *track,int *sector) { + *head = (block % (geometry.spt * geometry.heads)) / (geometry.spt); + *track = block / (geometry.spt * geometry.heads); + *sector = block % geometry.spt + 1; + } + +void motorOn(void) { + if (!motor) { + mTick = -1; /* stop motor kill countdown */ + outportByte(fdcDor,0x1c); + motor = TRUE; + } + } + +void motorOff(void) { + if (motor) { + mTick = 13500; + } + } + +bool seek(int track) { + if (fdcTrack == track) { + return(TRUE); + } + sendByte(cmdSeek); + sendByte(0); + sendByte(track); + if (!waitFdc(TRUE)) { + return(FALSE); + } + if ((sr0 != 0x20) || (fdcTrack != track)) { + return(FALSE); + } + else { + return(TRUE); + } + } + +bool readBlock(int block,byte *blockBuffer, unsigned long numSectors) { + int track=0, sector=0, head=0, track2=0, result=0, loop=0; + block2Hts(block, &head, &track, §or); + block2Hts(block+numSectors, &head, &track2, §or); + if (track!=track2) { + for (loop=0; loop +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +static int dp_pkt2user(struct device *dev,int page,int length); +static void getblock(struct device *dev,int page,size_t offset,size_t size,void *dst); +static int dp_recv(struct device *); + +uInt32 packetLength; +char *nicPacket; +asm( + ".globl ne2kISR \n" + "ne2kISR: \n" + " pusha \n" /* Save all registers */ + " call ne2kHandler \n" + " popa \n" + " iret \n" /* Exit interrupt */ + ); + +/************************************************************************ + +Function: int ne2kInit(uInt32 ioAddr) +Description: This Function Will Initialize The Programmable Timer + +Notes: + +************************************************************************/ +int ne2kInit(uInt32 ioAddr) { + + char *packet = 0x0; + struct device *dev = (struct device *)kmalloc(sizeof(struct device),sysID); + dev->ioAddr = 0x240; + dev->irq = 3; + + setVector(&ne2kISR, mVec+3, dPresent + dInt + dDpl3); + outportByte(mPic, eoi); + irqEnable(3); + outportByte(mPic, eoi); +// kprintf("ne0 - irq: %i, ioAddr: 0x%X MAC: %X:%X:%X:%X:%X:%X\n",dev->irq,dev->ioAddr,dev->net->mac[0] & 0xFF,dev->net->mac[1] & 0xFF,dev->net->mac[2] & 0xFF,dev->net->mac[3] & 0xFF,dev->net->mac[4] & 0xFF,dev->net->mac[5] & 0xFF); + + outportByte(dev->ioAddr + NE_CMD, 0x21); //stop mode + outportByte(dev->ioAddr + NE_DCR,0x29); // 0x29 data config reg + outportByte(dev->ioAddr + NE_RBCR0,0x00); // LOW byte count (remote) + outportByte(dev->ioAddr + NE_RBCR1,0x00); // HIGH byte count (remote) + outportByte(dev->ioAddr + NE_RCR,0x3C); // receive config reg + outportByte(dev->ioAddr + NE_TCR,0x02); // LOOP mode (temp) + outportByte(dev->ioAddr + NE_PSTART,startPage); // 0x26 PAGE start + outportByte(dev->ioAddr + NE_BNRY,startPage); // 0x26 BOUNDARY + outportByte(dev->ioAddr + NE_PSTOP,stopPage); // 0x40 PAGE stop + outportByte(dev->ioAddr + NE_ISR,0xFF); // interrupt status reg + outportByte(dev->ioAddr + NE_IMR,0x0B); + outportByte(dev->ioAddr + NE_CMD,0x61); // PAGE 1 regs + + outportByte(dev->ioAddr + DP_MAR0, 0xFF); + outportByte(dev->ioAddr + DP_MAR1, 0xFF); + outportByte(dev->ioAddr + DP_MAR2, 0xFF); + outportByte(dev->ioAddr + DP_MAR3, 0xFF); + outportByte(dev->ioAddr + DP_MAR4, 0xFF); + outportByte(dev->ioAddr + DP_MAR5, 0xFF); + outportByte(dev->ioAddr + DP_MAR6, 0xFF); + outportByte(dev->ioAddr + DP_MAR7, 0xFF); + outportByte(dev->ioAddr + DP_CURR, startPage + 1); + outportByte(dev->ioAddr + NE_CMD, 0x20); + inportByte(dev->ioAddr + DP_CNTR0); /* reset counters by reading */ + inportByte(dev->ioAddr + DP_CNTR1); + inportByte(dev->ioAddr + DP_CNTR2); + + outportByte(dev->ioAddr + NE_TCR, 0x00); + + outportByte(dev->ioAddr + NE_CMD, 0x0); + outportByte(dev->ioAddr + NE_DCR, 0x29); + + packet = (char *)kmalloc(256,sysID); + + packet[00] = 0x00; + packet[01] = 0xbd; + packet[02] = 0xe4; + packet[3] = 0x70; + packet[4] = 0x01; + packet[5] = 0x00; + packet[6] = 0x01; + packet[7] = 0x02; + packet[8] = 0x03; + packet[9] = 0x04; + packet[10] = 0x05; + packet[11] = 0x06; + packet[12] = 0x08; + packet[13] = 0x00; + packet[14] = 0x45; + packet[15] = 0x00; + packet[16] = 0x00; + packet[17] = 0x54; + packet[18] = 0xab; + packet[19] = 0x89; + packet[20] = 0x00; + packet[21] = 0x00; + packet[22] = 0x40; + packet[23] = 0x01; + packet[24] = 0x4d; + packet[25] = 0xcc; + packet[26] = 0xc0; + packet[27] = 0xa8; + packet[28] = 0x00; + packet[29] = 0x45; + packet[30] = 0xc0; + packet[31] = 0xa8; + packet[32] = 0x00; + packet[33] = 0x01; + packet[34] = 0x00; + packet[35] = 0x00; + packet[36] = 0x27; + packet[37] = 0x00; + packet[38] = 0x1d; + packet[39] = 0x71; + packet[40] = 0x00; + packet[41] = 0x0d; + packet[42] = 0x2c; + packet[43] = 0xa4; + packet[44] = 0x79; + packet[45] = 0x40; + packet[46] = 0x1f; + packet[47] = 0x9a; + packet[48] = 0x0b; + packet[49] = 0x00; + packet[50] = 0x08; + packet[51] = 0x09; + packet[52] = 0x0a; + packet[53] = 0x0b; + packet[54] = 0x0c; + packet[55] = 0x0d; + packet[56] = 0x0e; + packet[57] = 0x0f; + packet[58] = 0x10; + packet[59] = 0x11; + packet[60] = 0x12; + packet[61] = 0x13; + packet[62] = 0x14; + packet[63] = 0x15; + + packet[64] = 0x16; + packet[65] = 0x17; + packet[66] = 0x18; + packet[67] = 0x19; + packet[68] = 0x1a; + packet[69] = 0x1b; + packet[70] = 0x1c; + packet[71] = 0x1d; + packet[72] = 0x1e; + packet[73] = 0x1f; + packet[74] = 0x20; + packet[75] = 0x21; + packet[76] = 0x22; + packet[77] = 0x23; + packet[78] = 0x24; + packet[79] = 0x25; + packet[80] = 0x26; + packet[81] = 0x27; + packet[82] = 0x28; + packet[83] = 0x29; + packet[84] = 0x2a; + packet[85] = 0x2b; + packet[86] = 0x2c; + packet[87] = 0x2d; + packet[88] = 0x2e; + packet[89] = 0x2f; + packet[90] = 0x30; + packet[91] = 0x31; + packet[92] = 0x32; + packet[93] = 0x33; + packet[94] = 0x34; + packet[95] = 0x35; + packet[96] = 0x36; + packet[97] = 0x37; + + kprintf("A"); + if (PCtoNIC(dev,packet,98) == 0x0) { + kprintf("Error Sending To Nic\n"); + } + + packetLength = 0x0; + nicPacket = 0x0; + + kprintf("B"); + kfree(dev); + kprintf("C"); + kfree(packet); + kprintf("Initialized"); + /* Return so we know everything went well */ + return(0x0); + } + +int PCtoNIC(struct device *dev,void *packet,int length) { + int i; + uInt16 *packet16 = (uInt16 *)packet; + uInt8 *packet8 = (uInt8 *)packet; + uInt8 word16 = 1; + + if ((inportByte(dev->ioAddr) & 0x04) == 0x04) { + kpanic("Device Not Ready\n"); + } + + if ((word16 == 1) && (length & 0x01)) { + length++; + } + + outportByte(dev->ioAddr+EN0_RCNTLO,(length & 0xFF)); + outportByte(dev->ioAddr+EN0_RCNTHI,(length >> 8)); + + outportByte(dev->ioAddr+EN0_RSARLO,0x0); + outportByte(dev->ioAddr+EN0_RSARHI,0x41); + + outportByte(dev->ioAddr,E8390_RWRITE+E8390_START); + + if (word16 != 0x0) { + for(i=0;iioAddr + NE_DATAPORT,packet16[i]); + } + } + else { + for(i=0;iioAddr + NE_DATAPORT,packet8[i]); + } + } + + for (i = 0;i<=100;i++) { + if ((inportByte(dev->ioAddr+EN0_ISR) & 0x40) == 0x40) { + break; + } + } + + outportByte(dev->ioAddr+EN0_ISR,0x40); + outportByte(dev->ioAddr+EN0_TPSR,0x41);//ei_local->txStartPage); + outportByte(dev->ioAddr+0x05,(length & 0xFF)); + outportByte(dev->ioAddr+0x06,(length >> 8)); + outportByteP(dev->ioAddr,0x26); + kprintf("SENT\n"); + return(length); + } + +int NICtoPC(struct device *dev,void *packet,int length,int nic_addr) { + int i; + uInt16 *packet16 = (uInt16 *)packet; + + if (length & 0x01) + length++; + + + outportByte(dev->ioAddr+EN0_RCNTLO,(length & 0xFF)); + outportByte(dev->ioAddr+EN0_RCNTHI,(length >> 8)); + + outportByte(dev->ioAddr+EN0_RSARLO,nic_addr & 0xFF); + outportByte(dev->ioAddr+EN0_RSARHI,nic_addr >> 8); + + outportByte(dev->ioAddr,0x0A); + + for(i=0;iioAddr + NE_DATAPORT); + } + /* + for (i = 0;i<=100;i++) { + if ((inportByte(dev->ioAddr+EN0_ISR) & 0x40) == 0x40) + break; + } + */ + outportByte(dev->ioAddr+EN0_ISR,0x40); + return(length); + } + +void ne2kHandler() { + uInt16 isr = 0x0; + uInt16 status = 0x0; + struct device *dev = (struct device *)kmalloc(sizeof(struct device),sysID); + dev->ioAddr = 0x240; + dev->irq = 3; + isr = inportByte(dev->ioAddr + NE_ISR); + if ((isr & 0x02) == 0x02) { + outportByte(dev->ioAddr + NE_ISR, 0x0A); + status = inportByte(0x240 + NE_TPSR); + //kprintf("Pack Transmitted, Status: [0x%X]\n",status); + } + if ((isr & 0x01) == 0x01) { + //kprintf("Status: [0x%X]\n",inportByte(dev->ioAddr + NE_ISR)); + if (dp_recv(dev)) { + kprintf("Error Getting Packet\n"); + } + outportByte(dev->ioAddr + NE_ISR, 0x05); + } + /* + else { + kprintf("Word: [0x%X]\n",isr); + } + */ + outportByte(dev->ioAddr + NE_IMR,0x0); + outportByte(mPic, eoi); + outportByte(dev->ioAddr + NE_IMR,0x0B); + kfree(dev); + return; + } + +static int dp_recv(struct device *dev) { + dp_rcvhdr_t header; + unsigned int pageno, curr, next; + int packet_processed = 0x0, r; + uInt16 eth_type; + + uInt32 length = 0x0;//UBU + + pageno = inportByte(dev->ioAddr + NE_BNRY) + 1; + if (pageno == stopPage) pageno = startPage; + + do { + outportByte(dev->ioAddr + NE_CMD, 0x40); + curr = inportByte(dev->ioAddr + NE_CURRENT); + outportByte(dev->ioAddr, 0x0); + if (curr == pageno) break; + getblock(dev, pageno, (size_t)0, sizeof(header), &header); + getblock(dev, pageno, sizeof(header) + 2*sizeof(ether_addr_t), sizeof(eth_type), ð_type); + + length = (header.dr_rbcl | (header.dr_rbch << 8)) - sizeof(dp_rcvhdr_t); + next = header.dr_next; + + //kprintf("length: [0x%X:0x%X:0x%X]\n",header.dr_next,header.dr_status,length); + + if (length < 60 || length > 1514) { + kprintf("dp8390: packet with strange length arrived: %d\n",length); + next= curr; + } + else if (next < startPage || next >= stopPage) { + kprintf("dp8390: strange next page\n"); + next= curr; + } + else if (header.dr_status & RSR_FO) { + kpanic("dp8390: fifo overrun, resetting receive buffer\n"); + next = curr; + } + else if (header.dr_status & RSR_PRX) { + r = dp_pkt2user(dev, pageno, length); + if (r != OK) { + kprintf("FRUIT"); + return(0x0); + } + + packet_processed = 0x1; + } + if (next == startPage) + outportByte(dev->ioAddr + NE_BNRY, stopPage - 1); + else + outportByte(dev->ioAddr + NE_BNRY, next - 1); + + pageno = next; + + } while (packet_processed == 0x0); + return(0x0); + } + +static void getblock(struct device *dev,int page,size_t offset,size_t size,void *dst) { + uInt16 *ha; + int i; + + ha = (uInt16 *) dst; + offset = page * DP_PAGESIZE + offset; + outportByte(dev->ioAddr + NE_RBCR0, size & 0xFF); + outportByte(dev->ioAddr + NE_RBCR1, size >> 8); + outportByte(dev->ioAddr + EN0_RSARLO, offset & 0xFF); + outportByte(dev->ioAddr + EN0_RSARHI, offset >> 8); + outportByte(dev->ioAddr + NE_CMD, E8390_RREAD | E8390_START); + + size /= 2; + for (i= 0; iioAddr + NE_DATAPORT); + outportByte(dev->ioAddr+EN0_ISR,0x40); + } + +static int dp_pkt2user(struct device *dev,int page,int length) { + int last; + char *packet = 0x0; + + packet = (char *)kmalloc(512,sysID); + + last = page + (length - 1) / DP_PAGESIZE; + + if (last >= stopPage) { + kprintf("A"); + } + else { + NICtoPC(dev,packet,length,page * DP_PAGESIZE + sizeof(dp_rcvhdr_t)); + //getblock(dev,page,sizeof(dp_rcvhdr_t),length,packet); + } + + packetLength = length; + nicPacket = packet; + + //packet[29] = 0x45; + //packet[33] = 0x01; + /* + + packet[00] = 0x00; + packet[01] = 0xbd; + packet[02] = 0xe4; + packet[3] = 0x70; + packet[4] = 0x01; + packet[5] = 0x00; + packet[6] = 0x01; + packet[7] = 0x02; + packet[8] = 0x03; + packet[9] = 0x04; + packet[10] = 0x05; + packet[11] = 0x06; + packet[12] = 0x08; + packet[13] = 0x00; + packet[14] = 0x45; + packet[15] = 0x00; + packet[16] = 0x00; + packet[17] = 0x54; + packet[18] = 0xab; + - packet[19] = 0x89; + packet[20] = 0x00; + packet[21] = 0x00; + packet[22] = 0x40; + packet[23] = 0x01; + packet[24] = 0x4d; + packet[25] = 0xcc; + packet[26] = 0xc0; + packet[27] = 0xa8; + packet[28] = 0x00; + packet[29] = 0x45; + packet[30] = 0xc0; + packet[31] = 0xa8; + packet[32] = 0x00; + packet[33] = 0x01; + packet[34] = 0x00; + packet[35] = 0x00; + packet[36] += 0x08; + packet[37] = 0x00; + packet[38] = 0x1d; + packet[39] = 0x71; + packet[40] = 0x00; + - packet[41] = 0x0d; + packet[42] = 0x2c; + packet[43] = 0xa4; + packet[44] = 0x79; + packet[45] = 0x40; + packet[46] = 0x1f; + packet[47] = 0x9a; + packet[48] = 0x0b; + packet[49] = 0x00; + packet[50] = 0x08; + packet[51] = 0x09; + packet[52] = 0x0a; + packet[53] = 0x0b; + packet[54] = 0x0c; + packet[55] = 0x0d; + packet[56] = 0x0e; + packet[57] = 0x0f; + packet[58] = 0x10; + packet[59] = 0x11; + packet[60] = 0x12; + packet[61] = 0x13; + packet[62] = 0x14; + packet[63] = 0x15; + packet[64] = 0x16; + packet[65] = 0x17; + packet[66] = 0x18; + packet[67] = 0x19; + packet[68] = 0x1a; + packet[69] = 0x1b; + packet[70] = 0x1c; + packet[71] = 0x1d; + packet[72] = 0x1e; + packet[73] = 0x1f; + packet[74] = 0x20; + packet[75] = 0x21; + packet[76] = 0x22; + packet[77] = 0x23; + packet[78] = 0x24; + packet[79] = 0x25; + packet[80] = 0x26; + packet[81] = 0x27; + packet[82] = 0x28; + packet[83] = 0x29; + packet[84] = 0x2a; + packet[85] = 0x2b; + packet[86] = 0x2c; + packet[87] = 0x2d; + packet[88] = 0x2e; + packet[89] = 0x2f; + packet[90] = 0x30; + packet[91] = 0x31; + packet[92] = 0x32; + packet[93] = 0x33; + packet[94] = 0x34; + packet[95] = 0x35; + packet[96] = 0x36; + packet[97] = 0x37; + + PCtoNIC(dev,packet,length); + */ + kprintf("."); + return(OK); + } + +/*** + END + ***/ + diff --git a/src/sys/isa/pit.c b/src/sys/isa/pit.c new file mode 100644 index 0000000..b5a90d8 --- /dev/null +++ b/src/sys/isa/pit.c @@ -0,0 +1,84 @@ +/***************************************************************************************** + 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. + + $Log$ + Revision 1.9 2004/04/13 16:36:33 reddawg + Changed our copyright, it is all now under a BSD-Style license + + + + $Id$ + +*****************************************************************************************/ + +#include +#include +#include + +/************************************************************************ + +Function: int pitInit() +Description: This Function Will Initialize The Programmable Timer +Notes: + +0040 r/w PIT counter 0, counter divisor (XT, AT, PS/2) +0041 r/w PIT counter 1, RAM refresh counter (XT, AT) +0042 r/w PIT counter 2, cassette & speaker (XT, AT, PS/2) +0043 r/w PIT mode port, control word register for counters 0-2 + bit 7-6 = 00 counter 0 select + = 01 counter 1 select (not PS/2) + = 10 counter 2 select + bit 5-4 = 00 counter latch command + = 01 read/write counter bits 0-7 only + = 10 read/write counter bits 8-15 only + = 11 read/write counter bits 0-7 first, then 8-15 + bit 3-1 = 000 mode 0 select + = 001 mode 1 select - programmable one shot + = x10 mode 2 select - rate generator + = x11 mode 3 select - square wave generator + = 100 mode 4 select - software triggered strobe + = 101 mode 5 select - hardware triggered strobe + bit 0 = 0 binary counter 16 bits + = 1 BCD counter + +02/20/2004 - Approved for quality + +************************************************************************/ +int pitInit(int timerHz) { + outportByteP(0x43,0x36); + outportByteP(0x40,((1193180/timerHz) & 0xFF)); + outportByte(0x40,(((1193180/timerHz) >> 8) & 0xFF)); + + /* Print out information on the PIT */ + kprintf("pit0 - Port [0x%X], Timer Hz: [%iHz]\n",0x43,timerHz); + + /* Return so we know everything went well */ + return(0x0); + } + +/*** + END + ***/ + diff --git a/src/sys/isa/rs232.c b/src/sys/isa/rs232.c new file mode 100644 index 0000000..c4fb46c --- /dev/null +++ b/src/sys/isa/rs232.c @@ -0,0 +1,43 @@ +/***************************************************************************************** + 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. + + $Log$ + Revision 1.3 2004/04/13 16:36:33 reddawg + Changed our copyright, it is all now under a BSD-Style license + + + + $Id$ + +*****************************************************************************************/ + +void rs232Init() { + return; + } + +/*** + END + ***/ + diff --git a/src/sys/kernel/Makefile b/src/sys/kernel/Makefile new file mode 100644 index 0000000..f8a6af6 --- /dev/null +++ b/src/sys/kernel/Makefile @@ -0,0 +1,27 @@ +# (C) 2002 The UbixOS Project +# $Id$ + +# Include Global 'Source' Options +include ../../Makefile.inc +include ../Makefile.inc + +# Objects +OBJS = bioscall.o ld.o time.o fork.o syscall.o elf.o file.o idletask.o exec.o sched.o kpanic.o vitals.o ubthread.o + +all: $(OBJS) + +# Compile Types +.cc.o: + $(CXX) ${CFLAGS} -fno-exceptions -DNOBOOL -Wall -fomit-frame-pointer -O -I../include -c -o $@ $< +.cc.s: + $(CXX) ${CFLAGS} -fno-exceptions -DNOBOOL -Wall -fomit-frame-pointer -O -I../include -S -o $@ $< +.c.o: + $(CC) ${CFLAGS} -Wall -fomit-frame-pointer -O -I../include -c -o $@ $< +.c.s: + $(CC) ${CFLAGS} -Wall -fomit-frame-pointer -O -I../include -S -o $@ $< +.S.o: + $(CC) ${CFLAGS} -Wall -fomit-frame-pointer -c -o $@ $< + +# Clean up the junk +clean: + $(REMOVE) $(OBJS) diff --git a/src/sys/kernel/bioscall.c b/src/sys/kernel/bioscall.c new file mode 100644 index 0000000..7d45519 --- /dev/null +++ b/src/sys/kernel/bioscall.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. + + $Log$ + Revision 1.10 2004/04/13 16:16:44 reddawg + Changed our copyright, it is all now under a BSD-Style license + + + + $Id$ + +*****************************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include + + +asm ( + ".globl bios16Code\n" + "bios16Code: \n" + "int $0x10 \n" + "int $0x69 \n" + ); + + +void biosCall(int biosInt,int eax,int ebx,int ecx,int edx,int esi,int edi,int es,int ds) { + short segment = 0x0,offset = 0x0; + uInt32 tmpAddr = (uInt32)&bios16Code; + kTask_t *newProcess = 0x0; + + offset = tmpAddr & 0xF; // lower 4 bits + segment = tmpAddr >> 4; + + newProcess = schedNewTask(); + + newProcess->tss.back_link = 0x0; + newProcess->tss.esp0 = (uInt32)kmalloc(0x2000,newProcess->id)+0x2000; + newProcess->tss.ss0 = 0x10; + newProcess->tss.esp1 = 0x0; + newProcess->tss.ss1 = 0x0; + newProcess->tss.esp2 = 0x0; + newProcess->tss.ss2 = 0x0; + newProcess->tss.cr3 = (uInt32)_current->tss.cr3;//(uInt32)vmmCreateVirtualSpace(newProcess->id); + newProcess->tss.eip = offset & 0xFFFF; + newProcess->tss.eflags = 2 | EFLAG_IF | EFLAG_VM; + newProcess->tss.eax = eax & 0xFFFF; + newProcess->tss.ebx = ebx & 0xFFFF; + newProcess->tss.ecx = ecx & 0xFFFF; + newProcess->tss.edx = edx & 0xFFFF; + newProcess->tss.esp = 0x1000 & 0xFFFF; + newProcess->tss.ebp = 0x1000 & 0xFFFF; + newProcess->tss.esi = esi & 0xFFFF; + newProcess->tss.edi = edi & 0xFFFF; + newProcess->tss.es = es & 0xFFFF; + newProcess->tss.cs = segment & 0xFFFF; + newProcess->tss.ss = 0x1000 & 0xFFFF; + newProcess->tss.ds = ds & 0xFFFF; + newProcess->tss.fs = 0x0 & 0xFFFF; + newProcess->tss.gs = 0x0 & 0xFFFF; + newProcess->tss.ldt = 0x0 & 0xFFFF; + newProcess->tss.trace_bitmap = 0x0 & 0xFFFF; + newProcess->tss.io_map = 0x0 & 0xFFFF; + newProcess->tss.io_map = sizeof(struct tssStruct)-8192; + newProcess->oInfo.v86Task = 0x1; + newProcess->state = READY; + + while (newProcess->state > 0); + + return; + } diff --git a/src/sys/kernel/elf.c b/src/sys/kernel/elf.c new file mode 100644 index 0000000..cf69f8e --- /dev/null +++ b/src/sys/kernel/elf.c @@ -0,0 +1,95 @@ +/***************************************************************************************** + 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. + + $Log$ + Revision 1.4 2004/04/13 16:16:44 reddawg + Changed our copyright, it is all now under a BSD-Style license + + + + $Id$ + +*****************************************************************************************/ + +#include + +const struct { + char *elfTypeName; + uInt32 id; + } elfType[] = { + { "ET_NONE", 0 }, + { "ET_REL", 1 }, + { "ET_EXEC", 2 }, + { "ET_DYN", 3 }, + { "ET_CORE", 4 }, + { "ET_LOPROC", 0xff00 }, + { "ET_HIPROC", 0xffff }, + }; + +const struct { + char *phTypeName; + uInt32 id; + } elfPhType[] = { + { "PT_NULL", 0 }, + { "PT_LOAD", 1 }, + { "PT_DYNAMIC", 2 }, + { "PT_INTERP", 3 }, + { "PT_NOTE", 4 }, + { "PT_SHLIB", 5 }, + { "PT_PHDR", 6 }, + { "PT_LOPROC", 0x70000000 }, + { "PT_HIPROC", 0x7fffffff }, + }; + +const struct { + char *shTypeName; + uInt32 id; + } elfShType[] = { + {"SHT_NULL", 0 }, + {"SHT_PROGBITS", 1 }, + {"SHT_SYMTAB", 2 }, + {"SHT_STRTAB", 3 }, + {"SHT_RELA", 4 }, + {"SHT_HASH", 5 }, + {"SHT_DYNAMIC", 6 }, + {"SHT_NOTE", 7 }, + {"SHT_NOBITS", 8 }, + {"SHT_REL", 9 }, + {"SHT_SHLIB", 10 }, + {"SHT_DYNSYM", 11 }, + }; + +char *elfGetShType(int shType) { + return((char *)elfShType[shType].shTypeName); + } + +char *elfGetPhType(int phType) { + return((char *)elfPhType[phType].phTypeName); + } + +/*** + END + ***/ + diff --git a/src/sys/kernel/exec.c b/src/sys/kernel/exec.c new file mode 100644 index 0000000..38dca92 --- /dev/null +++ b/src/sys/kernel/exec.c @@ -0,0 +1,409 @@ +/***************************************************************************************** + 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. + + $Log$ + Revision 1.44 2004/04/13 16:16:44 reddawg + Changed our copyright, it is all now under a BSD-Style license + + + + $Id$ + +*****************************************************************************************/ + +#include +#include +#include +#include +#include +#include + +uInt32 execThread(void (* tproc)(void),int stack,char *arg,char *descr) { + kTask_t * newProcess; + /* Find A New Thread */ + newProcess = schedNewTask(); + /* newProcess->oInfo.terminal = findConsole(0x0); */ + + /* Set All The Correct Thread Attributes */ + newProcess->tss.back_link = 0x0; + newProcess->tss.esp0 = 0x0; + newProcess->tss.ss0 = 0x0; + newProcess->tss.esp1 = 0x0; + newProcess->tss.ss1 = 0x0; + newProcess->tss.esp2 = 0x0; + newProcess->tss.ss2 = 0x0; + newProcess->tss.cr3 = (unsigned int)kernelPageDirectory; + newProcess->tss.eip = (unsigned int)tproc; + newProcess->tss.eflags = 0x206; + newProcess->tss.esp = stack; + newProcess->tss.ebp = stack; + newProcess->tss.esi = 0x0; + newProcess->tss.edi = 0x0; + + newProcess->tss.es = 0x10; + newProcess->tss.cs = 0x08; + newProcess->tss.ss = 0x10; + newProcess->tss.ds = 0x10; + newProcess->tss.fs = 0x10; + newProcess->tss.gs = 0x10; + newProcess->tss.ldt = 0x18; + + newProcess->tss.trace_bitmap = 0x0000; + newProcess->tss.io_map = 0x8000; + newProcess->oInfo.vmStart = 0x6400000; + + asm volatile( + "pusha \n" + "movl %%esp,%%ecx\n" + "movl %1,%%eax \n" + "movl %%eax,%%esp\n" + "pushl %%ebx\n" + "pushl %%ebx\n" + "pushl %%ebx\n" + "movl %%esp,%%eax\n" + "movl %%eax,%1 \n" + "movl %%ecx,%%esp\n" + "popa \n" + : + : "b" (arg),"m" (newProcess->tss.esp) + ); + + + newProcess->state = READY; + /* Return */ + return((uInt32)newProcess); + } + +/************************************************************************ + +Function: void execFile(char *file); +Description: This Function Executes A Kile Into A New VM Space With Out + Having To Fork +Notes: + +07/30/02 - I Have Made Some Heavy Changes To This As Well As Fixed A Few + Memory Leaks The Memory Allocated To Load The Binary Into Is + Now Unmapped So It Can Be Used Again And Not Held Onto Until + The Program Exits + +07/30/02 - Now I Have To Make A Better Memory Allocator So We Can Set Up + The Freshly Allocated Pages With The Correct Permissions + +************************************************************************/ +void execFile(char *file,int argc,char **argv,int console) { + int i=0,x=0,eStart=0; + char *binarySpace = (char *)0x7C0000; + char *newLoc; + fileDescriptor *tmpFd = 0x0; + elfHeader *binaryHeader = (elfHeader *)0x7C0000; + elfProgramheader *programHeader; + /* Get A New Task For This Proccess */ + _current = schedNewTask(); + /* _current->oInfo.terminal = findConsole(console); */ + _current->gid = 0; + _current->uid = 0; + /* Now We Must Create A Virtual Space For This Proccess To Run In */ + _current->tss.cr3 = (uInt32)vmmCreateVirtualSpace(_current->id); + /* To Better Load This Application We Will Switch Over To Its VM Space */ + asm( + "movl %0,%%eax \n" + "movl %%eax,%%cr3 \n" + : : "d" ((uLong *)(_current->tss.cr3)) + ); + /* Lets Find The File */ + tmpFd = fopen(file,"r"); + /* If We Dont Find the File Return */ + if (!tmpFd) { + return; + } + /* Now We Must Allocate Memory To Load The Binary Into */ + for (i=0;i<((tmpFd->size+4095)/4096);i++) { + vmmRemapPage(vmmFindFreePage(_current->id),(0x7C0000 + (0x1000 * i))); + } + /* Load The Binary Into Memory Byte For Byte I Should Find A Faster Way */ + fread(binarySpace,tmpFd->size,1,tmpFd); + /* + for (i=0;feof(tmpFd) == 0;i++) { + binarySpace[i] = fgetc(tmpFd); + } + */ + /* Close The File */ + fclose(tmpFd); + /* Set programHeader To Point To Loaded Binary So We Can Gather Info */ + programHeader = (elfProgramheader *)(0x7C0000 + binaryHeader->ePhoff); + /* Loop Through The Header And Load Sections Which Need To Be Loaded */ + for (i=0;iePhnum;i++) { + newLoc = (char *)programHeader[i].phVaddr; + /* + Allocate Memory Im Going To Have To Make This Load Memory With Corrent + Settings so it helps us in the future + */ + for (x=0;x<=((programHeader[i].phMemsz & 0xFFFFF000)+0x1000);x+=0x1000) { + vmmRemapPage(vmmFindFreePage(_current->id),((programHeader[i].phVaddr & 0xFFFFF000) + x)); + } + /* Now Copy The Binary To Its Correct Location */ + for (x=0;xoInfo.vmStart = ((programHeader[i].phVaddr & 0xFFFFF000) + 0x1900000); + /* Get The Starting Point */ + eStart = binaryHeader->eEntry; + /* Now That We Relocated The Binary We Can Unmap And Free Old Pages */ + for (i=0;i<((tmpFd->size+4095)/4096);i++) { + vmmUnmapPage((0x7C0000 + (0x1000 * i)),0); + } + /* Now Lets Make A Clean Stack */ + newLoc = (char *)0x5DB000; + vmmRemapPage(vmmFindFreePage(_current->id),0x5DC000); + vmmSetPageAttribute(0x5DC000,(pageDefault | pageStack)); + vmmRemapPage(vmmFindFreePage(_current->id),0x5DB000); + vmmSetPageAttribute(0x5DB000,(pageDefault | pageStack)); + vmmRemapPage(vmmFindFreePage(_current->id),0x5DA000); + vmmSetPageAttribute(0x5DA000,(pageDefault | pageStack)); + vmmRemapPage(vmmFindFreePage(_current->id),0x5D9000); + vmmSetPageAttribute(0x5D9000,(pageDefault | pageStack)); + + i = 0x5DD000; + + vmmRemapPage(vmmFindFreePage(_current->id),0x5D3000); + vmmSetPageAttribute(0x5D3000,(pageDefault | pageStack)); + vmmRemapPage(vmmFindFreePage(_current->id),0x5D2000); + vmmSetPageAttribute(0x5D2000,(pageDefault | pageStack)); + vmmRemapPage(vmmFindFreePage(_current->id),0x5D1000); + vmmSetPageAttribute(0x5D1000,(pageDefault | pageStack)); + vmmRemapPage(vmmFindFreePage(_current->id),0x5D0000); + vmmSetPageAttribute(0x5D0000,(pageDefault | pageStack)); + + /* Set All The Proper Information For The Task */ + _current->tss.back_link = 0x0; + _current->tss.esp0 = 0x5D4000; + _current->tss.ss0 = 0x10; + _current->tss.esp1 = 0x0; + _current->tss.ss1 = 0x0; + _current->tss.esp2 = 0x0; + _current->tss.ss2 = 0x0; + _current->tss.eip = (long)eStart; + _current->tss.eflags = 0x206; + _current->tss.esp = i-12; + _current->tss.ebp = i; + _current->tss.esi = 0x0; + _current->tss.edi = 0x0; + + _current->tss.es = 0x30+3; + _current->tss.cs = 0x28+3; + _current->tss.ss = 0x30+3; + _current->tss.ds = 0x30+3; + _current->tss.fs = 0x30+3; + _current->tss.gs = 0x30+3; + + /* + _current->tss.es = 0x10; + _current->tss.cs = 0x08; + _current->tss.ss = 0x10; + _current->tss.ds = 0x10; + _current->tss.fs = 0x10; + _current->tss.gs = 0x10; + */ + + _current->tss.ldt = 0x18; + _current->tss.trace_bitmap = 0x0000; + _current->tss.io_map = 0x8000; + _current->state = READY; + + + /* + asm volatile( + "pusha \n" + "movl %%esp,%%edx\n" + "movl %2,%%ecx \n" + "movl %%ecx,%%esp\n" + "pushl $0x0\n" + "pushl $0x0\n" + "pushl $0x0\n" + "pushl $0x0\n" + "pushl %%ebx\n" + "pushl %%eax\n" + "movl %%esp,%%ecx\n" + "movl %%ecx,%2 \n" + "movl %%edx,%%esp\n" + "popa \n" + : + : "a" (argc), "b" (argv), "m" (_current->tss.esp) + ); + */ + + + /* Switch Back To The Kernels VM Space */ + asm( + "movl %0,%%eax \n" + "movl %%eax,%%cr3 \n" + : : "d" ((uLong *)(kernelPageDirectory)) + ); + /* Finally Return */ + return; + } + +/************************************************************************ + +Function: void sysExec(); +Description: This Is The System Call To Execute A New Task + +Notes: + 04-22-03 - It Now Loads Sections Not The Full File + +************************************************************************/ +void sysExec(char *file,int argc,char **argv) { + int i = 0x0; + int x = 0x0; + uInt32 eStart = 0x0; + uInt32 *tmp = 0x0; + char *newLoc = 0x0; + char *linker = 0x0; + + fileDescriptor *tmpFd = 0x0; + elfHeader *binaryHeader = 0x0; + elfProgramheader *programHeader = 0x0; + elfSectionheader *sectionHeader = 0x0; + elfDynamic *elfDynamicS = 0x0; + + + tmpFd = fopen(file,"r"); + + /* If We Dont Find the File Return */ + if (tmpFd == 0x0) { + //*status = 0; + return; + } + if (tmpFd->perms == 0) { + //*status = -2; + kprintf("Exec Format Error: Binary File Not Executable.\n"); + fclose(tmpFd); + return; + } + + /* Load ELF Header */ + binaryHeader = (elfHeader *)kmalloc(sizeof(elfHeader),_current->id); + fread(binaryHeader,sizeof(elfHeader),1,tmpFd); + /* Set sectionHeader To Point To Loaded Binary To We Can Gather Info */ + /* sectionHeader = (elfSectionheader *)(0x7C0000 + binaryHeader->eShoff); */ + + /* Check If App Is A Real Application */ + if ((binaryHeader->eIdent[1] != 'E') && (binaryHeader->eIdent[2] != 'L') && (binaryHeader->eIdent[3] != 'F')) { + //*status = -1; + kprintf("Exec Format Error: Binary File Not Executable.\n"); + kfree(binaryHeader); + fclose(tmpFd); + return; + } + else if (binaryHeader->eType != 2) { + //*status = -2; + kprintf("Exec Format Error: Binary File Not Executable.\n"); + kfree(binaryHeader); + fclose(tmpFd); + return; + } + else if (binaryHeader->eEntry == 0x300000) { + //*status = -2; + kprintf("Exec Format Error: Binary File Not Executable.\n"); + kfree(binaryHeader); + fclose(tmpFd); + return; + } + + /* Load The Program Header(s) */ + programHeader = (elfProgramheader *)kmalloc(sizeof(elfProgramheader)*binaryHeader->ePhnum,_current->id); + fseek(tmpFd,binaryHeader->ePhoff,0); + fread(programHeader,(sizeof(elfProgramheader)*binaryHeader->ePhnum),1,tmpFd); + + sectionHeader = (elfSectionheader *)kmalloc(sizeof(elfSectionheader)*binaryHeader->eShnum,_current->id); + fseek(tmpFd,binaryHeader->eShoff,0); + fread(sectionHeader,sizeof(elfSectionheader)*binaryHeader->eShnum,1,tmpFd); + + /* Loop Through The Header And Load Sections Which Need To Be Loaded */ + for (i=0;iePhnum;i++) { + if (programHeader[i].phType == 1) { + newLoc = (char *)programHeader[i].phVaddr; + /* + Allocate Memory Im Going To Have To Make This Load Memory With Correct + Settings so it helps us in the future + */ + for (x=0;x<=((programHeader[i].phMemsz & 0xFFFFF000)+4095);x+=4096) { + vmmRemapPage(vmmFindFreePage(_current->id),((programHeader[i].phVaddr & 0xFFFFF000) + x)); + } + _current->oInfo.vmStart = ((programHeader[i].phVaddr & 0xFFFFF000) + 0x1900000); + /* Now Load Section To Memory */ + fseek(tmpFd,programHeader[i].phOffset,0); + fread(newLoc,programHeader[i].phFilesz,1,tmpFd); + } + else if (programHeader[i].phType == 2) { + newLoc = (char *)programHeader[i].phVaddr; + elfDynamicS = (elfDynamic *)programHeader[i].phVaddr; + fseek(tmpFd,programHeader[i].phOffset,0); + fread(newLoc,programHeader[i].phFilesz,1,tmpFd); + } + else if (programHeader[i].phType == 3) { + linker = (char *)kmalloc(programHeader[i].phMemsz,_current->id); + fseek(tmpFd,programHeader[i].phOffset,0); + fread(linker,programHeader[i].phFilesz,1,tmpFd); + //kprintf("Linker: [%s]\n",linker); + } + } + _current->oInfo.shstrtab = (char *)kmalloc(sectionHeader[binaryHeader->eShstrndx].shSize,_current->id); + fseek(tmpFd,sectionHeader[binaryHeader->eShstrndx].shOffset,0); + fread(_current->oInfo.shstrtab,sectionHeader[binaryHeader->eShstrndx].shSize,0,tmpFd); + + for (i=0;i<12;i++) { + if (elfDynamicS[i].dynVal == 0x3) { + tmp = (uInt32 *)elfDynamicS[i].dynPtr; + tmp[2] = (uInt32) &ld; + } + } + + _current->oInfo.sectionHeader = sectionHeader; + _current->oInfo.sectionCount = binaryHeader->eShnum; + _current->oInfo.stringSection = binaryHeader->eShstrndx; + + /* Get The Starting Point */ + eStart = binaryHeader->eEntry; + + /* Now That We Relocated The Binary We Can Unmap And Free Header Info */ + kfree(binaryHeader); + kfree(programHeader); + fclose(tmpFd); + /* Jump To Start Of New Binary */ + asm volatile( + "pushl %1\n" + "pushl %%eax\n" + "call *%0\n" + : + : "g" (eStart),"g" (argv),"a" (argc) + ); + } + +/*** + END + ***/ diff --git a/src/sys/kernel/file.c b/src/sys/kernel/file.c new file mode 100644 index 0000000..e3c222f --- /dev/null +++ b/src/sys/kernel/file.c @@ -0,0 +1,299 @@ +/***************************************************************************************** + 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. + + $Log$ + Revision 1.22 2004/04/13 16:16:44 reddawg + Changed our copyright, it is all now under a BSD-Style license + + + + $Id$ + +*****************************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include + +fileDescriptor *fdTable = 0x0; + +/* These Are Temporary */ +int sprintf(char *buf,const char *fmt, ...); +char getch(); + + + +/************************************************************************ + +Function: int feof(fileDescriptor *fd) +Description: Check A File Descriptor For EOF And Return Result +Notes: + +************************************************************************/ +int feof(fileDescriptor *fd) { + if (fd->status == fdEof) { + return(-1); + } + return(0); + } + +/************************************************************************ + +Function: int fclose(fileDescriptor *fd); +Description: This Will Close And Free A File Descriptor +Notes: + +************************************************************************/ +int fclose(fileDescriptor *fd) { + fileDescriptor *tmpFd = 0x0; + /* Search For File Descriptor */ + for (tmpFd=fdTable;tmpFd;tmpFd=tmpFd->next) { + if (tmpFd == fd) { + /* If Fd Is The First FD Then Reset fdTable */ + if (tmpFd == fdTable) { + fdTable = tmpFd->next; + if (fdTable != 0x0) { + fdTable->prev = 0x0; + } + kfree(fd->buffer); + kfree(fd); + systemVitals->openFiles--; + return(1); + } + else { + tmpFd->prev->next = tmpFd->next; + tmpFd->next->prev = tmpFd->prev; + kfree(fd->buffer); + kfree(fd); + systemVitals->openFiles--; + return(1); + } + } + } + /* Return NULL If Descriptor Was Not Found */ + return(0x0); + } + +/************************************************************************ + +Function: int fputc(int ch,fileDescriptor *fd) +Description: This Will Write Character To FD +Notes: + +************************************************************************/ +int fputc(int ch,fileDescriptor *fd) { + fileDescriptor *tmpFd = 0x0; + /* Search For File Descriptor */ + for (tmpFd=fdTable;tmpFd;tmpFd=tmpFd->next) { + /* If Found Return Next Char */ + if (tmpFd == fd) { + ch = tmpFd->mp->fs->vfsWrite(tmpFd,(char *)ch,tmpFd->offset,1); + tmpFd->offset++; + return(ch); + } + } + /* Return NULL If FD Is Not Found */ + return(0x0); + } + +/************************************************************************ + +Function: int fgetc(fileDescriptor *fd) +Description: This Will Return The Next Character In A FD Stream +Notes: + +************************************************************************/ +int fgetc(fileDescriptor *fd) { + int ch = 0x0; + fileDescriptor *tmpFd = 0x0; + /* Search For File Descriptor */ + for (tmpFd=fdTable;tmpFd;tmpFd=tmpFd->next) { + /* If Found Return Next Char */ + if (tmpFd == fd) { + tmpFd->mp->fs->vfsRead(tmpFd,(char *)&ch,tmpFd->offset,1); + tmpFd->offset++; + return(ch); + } + } + /* Return NULL If FD Is Not Found */ + return(0x0); + } + +size_t fread(void *ptr,int size,int nmemb,fileDescriptor *fd) { + fileDescriptor *tmpFd = 0x0; + /* Search For File Descriptor */ + for (tmpFd=fdTable;tmpFd;tmpFd=tmpFd->next) { + /* If Found Return Next Char */ + if (tmpFd == fd) { + if (nmemb == 0x0) nmemb = 1; //Temp Fix + tmpFd->mp->fs->vfsRead(tmpFd,ptr,tmpFd->offset,size * nmemb); + tmpFd->offset += size * nmemb; + } + } + return(0x0); + } + +size_t fwrite(void *ptr,int size,int nmemb,fileDescriptor *fd) { + fileDescriptor *tmpFd = 0x0; + /* Search For File Descriptor */ + for (tmpFd=fdTable;tmpFd;tmpFd=tmpFd->next) { + /* If Found Return Next Char */ + if (tmpFd == fd) { + tmpFd->mp->fs->vfsWrite(tmpFd,ptr,tmpFd->offset,size * nmemb); + tmpFd->offset += size * nmemb; + } + } + return(0x0); + } + +/************************************************************************ + +Function: void sysFopen(); +Description: Opens A File Descriptor For A User Task +Notes: + +************************************************************************/ +void sysFopen(char *file,char *flags,userFileDescriptor *userFd) { + userFd->fd = fopen(file,flags); + if (userFd->fd != 0x0) { + userFd->fdSize = userFd->fd->size; + } + /* Return */ + return; + } + +#if 0 +size_t fread(void *ptr, int size, int nmemb,fileDescriptor *fd) { + + /* YO! what about EOF's in the middle of reading?? */ + + int i = 0x0; + char *data = (char *)ptr; + for (i=0;ifd); + /* Return */ + return; + } + +void sysFwrite(char *ptr,int size,userFileDescriptor *userFd) { + if (userFd->fd == 0x0) { + kprintf(ptr); + } + else { + fwrite(ptr,size,1,userFd->fd); + } + return; + } + +/************************************************************************ + +Function: void sysFclse(); +Description: Closes A File Descriptor For A User Task +Notes: + +************************************************************************/ +void sysFclose(userFileDescriptor *userFd,int *status) { + *status = fclose(userFd->fd); + /* Return */ + return; + } + +void sysFgetc(int *ptr,userFileDescriptor *userFd) { + fileDescriptor *tmpFd = 0x0; + asm("sti"); + tmpFd = userFd->fd; + if (userFd->fd == 0) { + ptr[0] = (int) getch(); + } + else { + ptr[0] = (int) fgetc(tmpFd); + } + } + +void sysRmDir() { + return; + } + +int fseek(fileDescriptor *tmpFd,long offset,int whence) { + tmpFd->offset = offset+whence; + return(tmpFd->offset); + } + +void sysFseek(userFileDescriptor *userFd,long offset,int whence) { + kprintf("sysFseek: [0x%X][0x%X]\n",userFd,userFd->fd); + userFd->fd->offset = offset+whence; + } + +void sysChDir(const char *path) { + sprintf(_current->oInfo.cwd,path); + } + +void sysUnlink(const char *path,int *retVal) { + *retVal = unlink(path); + } + +/************************************************************************ + +Function: void chDir(const char *path); +Description: Changes Current Working Dir +Notes: + +************************************************************************/ +void chDir(const char *path) { + if (_current->oInfo.fileInfo.cwd != 0x0) { + kfree(_current->oInfo.fileInfo.cwd); + } + _current->oInfo.fileInfo.cwd = verifyDir(path); + return; + } + +/************************************************************************ + +Function: char *verifyDir(const char *path); +Description: Changes Current Working Dir +Notes: + +************************************************************************/ +char *verifyDir(const char *path) { + return(0x0); + } diff --git a/src/sys/kernel/fork.c b/src/sys/kernel/fork.c new file mode 100644 index 0000000..54f4004 --- /dev/null +++ b/src/sys/kernel/fork.c @@ -0,0 +1,115 @@ +/***************************************************************************************** + 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. + + $Log$ + Revision 1.18 2004/04/13 16:16:44 reddawg + Changed our copyright, it is all now under a BSD-Style license + + + + $Id$ + +*****************************************************************************************/ + +#include +#include +#include +#include + +int testF(struct taskStruct *newProcess) { + newProcess->uid = 0x0; + newProcess->tss.cr3 = (uInt32)vmmCopyVirtualSpace(newProcess->id); + return(newProcess->id); + } + +/************************************************************************ + +Function: void sysFork(); +Description: This Function Forks A Task +Notes: + +08/01/02 - This Seems To Be Working Fine However I'm Not Sure If I + Chose The Best Path To Impliment It I Guess We Will See + What The Future May Bring + +************************************************************************/ +asm( + ".globl sysFork \n" + "sysFork: \n" + " xor %eax,%eax \n" + " call schedNewTask \n" + " testl %eax,%eax \n" + " je 1f \n" + " pushl %esi \n" + " pushl %edi \n" + " pushl %ebp \n" + " pushl %eax \n" + " call forkCopyProcess \n" + " movl %eax,(%ebx) \n" + " addl $16,%esp \n" + "1: \n" + " ret \n" + ); + +int forkCopyProcess(struct taskStruct *newProcess,long ebp,long edi,long esi,long none,long ebx,long ecx,long edx,long eip,long cs,long eflags,long esp,long ss) { + + /* Set Up New Tasks Information */ + newProcess->uid = _current->uid; + newProcess->gid = _current->gid; + newProcess->tss.back_link = 0x0; + newProcess->tss.esp0 = _current->tss.esp0; + newProcess->tss.ss0 = 0x10; + newProcess->tss.esp1 = 0x0; + newProcess->tss.ss1 = 0x0; + newProcess->tss.esp2 = 0x0; + newProcess->tss.ss2 = 0x0; + newProcess->tss.eflags = eflags; + newProcess->tss.eax = 0x0; + newProcess->tss.ebx = ebx; + newProcess->tss.ecx = ecx; + newProcess->tss.edx = edx; + newProcess->tss.esi = esi; + newProcess->tss.edi = edi; + newProcess->tss.ebp = ebp; + newProcess->tss.esp = esp; + newProcess->tss.cs = cs & 0xFF; + newProcess->tss.ss = ss & 0xFF; + newProcess->tss.ds = _current->tss.ds & 0xFF; + newProcess->tss.fs = _current->tss.fs & 0xFF; + newProcess->tss.gs = _current->tss.gs & 0xFF; + newProcess->tss.es = _current->tss.es & 0xFF; + newProcess->tss.ldt = 0x18; + newProcess->tss.trace_bitmap = 0x0000; + newProcess->tss.io_map = 0x8000; + newProcess->tss.eip = eip; + /* Create A Copy Of The VM Space For New Task */ + newProcess->tss.cr3 = (uInt32)vmmCopyVirtualSpace(newProcess->id); + newProcess->oInfo.curDir = _current->oInfo.curDir; + newProcess->oInfo.container = _current->oInfo.container; + newProcess->state = READY; + /* Return Id of Proccess */ + return(newProcess->id); + } + diff --git a/src/sys/kernel/idletask.c b/src/sys/kernel/idletask.c new file mode 100644 index 0000000..2e213b2 --- /dev/null +++ b/src/sys/kernel/idletask.c @@ -0,0 +1,47 @@ +/***************************************************************************************** + 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. + + $Log$ + Revision 1.21 2004/04/13 16:16:44 reddawg + Changed our copyright, it is all now under a BSD-Style license + + + + $Id$ + +*****************************************************************************************/ + +#include +#include +#include +#include + +void idleTask() { + while(1) { + asm("hlt"); + } + return; + } + diff --git a/src/sys/kernel/kpanic.c b/src/sys/kernel/kpanic.c new file mode 100644 index 0000000..b777b23 --- /dev/null +++ b/src/sys/kernel/kpanic.c @@ -0,0 +1,70 @@ +/***************************************************************************************** + 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. + + $Log$ + Revision 1.5 2004/04/13 16:16:44 reddawg + Changed our copyright, it is all now under a BSD-Style license + + + + $Id$ + +*****************************************************************************************/ + +#include +#include +#include + +/************************************************************************ + +Function: int kpanic() + +Description: This function is used to cause a kernel panic + +Notes: + +02/20/2004 - Approved for quality + +************************************************************************/ +void kpanic(const char *fmt, ...) { + + vaList args; + int i = 0x0; + char buf[1024]; + vaStart(args, fmt); + i=vsprintf(buf,fmt,args); + vaEnd(args); + kprint(buf); + + /* Halt The System */ + while (1) { + asm("hlt"); + } + } + +/*** + END + ***/ + diff --git a/src/sys/kernel/ld.c b/src/sys/kernel/ld.c new file mode 100644 index 0000000..84e7fd9 --- /dev/null +++ b/src/sys/kernel/ld.c @@ -0,0 +1,55 @@ +/***************************************************************************************** + 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. + + $Log$ + Revision 1.2 2004/04/13 16:16:44 reddawg + Changed our copyright, it is all now under a BSD-Style license + + + + $Id$ + +*****************************************************************************************/ + +#include +#include +#include +#include +#include + +void ld(int first,int got2) { + uInt32 *tmp; + kprintf("Kernel Linker\n"); + kprintf("[0x%X][0x%X]\n",first,got2); + tmp = (uInt32 *)got2; + kprintf("[0x%X]\n",tmp[first]); + _current->state = DEAD; + while (1); + } + +/*** + END + ***/ + diff --git a/src/sys/kernel/sched.c b/src/sys/kernel/sched.c new file mode 100644 index 0000000..afffcc2 --- /dev/null +++ b/src/sys/kernel/sched.c @@ -0,0 +1,223 @@ +/***************************************************************************************** + 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. + + $Log$ + Revision 1.19 2004/04/13 16:16:44 reddawg + Changed our copyright, it is all now under a BSD-Style license + + + + $Id$ + +*****************************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +extern union descriptorTableunion GDT[5]; + +kTask_t *taskList = 0x0; +uInt32 nextID = -1; +kTask_t *_current = 0x0; +kTask_t *_usedMath = 0x0; + +/************************************************************************ + +Function: int schedInit() + +Description: This function is used to enable the kernel scheduler + +Notes: + +02/20/2004 - Approved for quality + +************************************************************************/ +int schedInit() { + + /* Allocate memory for task list */ + taskList = (kTask_t *)kmalloc(sizeof(kTask_t),sysID); + if (taskList == 0x0) { + kpanic("Error: kmalloc failed for taskList\n"); + return(0x1); + } + + /* Set up the defaults for the initial task. */ + taskList->prev = 0x0; + taskList->next = 0x0; + taskList->id = nextID++; + taskList->state = DEAD; + _current = taskList; + + /* Print out information on scheduler */ + kprintf("sched0 - Address: [0x%X]\n",taskList); + + /* Return so we know everything went well */ + return(0x0); + } + +void sched() { + uInt32 memAddr = 0x0; + kTask_t *tmpTask = 0x0; + + struct tssStruct *gpfTSS = (struct tssStruct *)0x4200; + gpfTSS->eip = (unsigned int)&_int13; + gpfTSS->esp = 0x1CFFF; + gpfTSS->ebp = 0x1CFFF; + gpfTSS->eflags = 0x206; + + +schedStart: + for (tmpTask=_current->next;tmpTask;tmpTask=tmpTask->next) { + + if (tmpTask->state > 0x0) { + _current = tmpTask; + break; + } /* if tmpTask->state > 0x0 */ + } /* for */ + + if (0x0 == tmpTask) { + _current = taskList; + goto schedStart; + } /* if 0x0 == tmpTask */ + + memAddr = (uInt32)&(_current->tss); + + if (_current->state > 0x0) { + if (_current->oInfo.v86Task == 0x1) { + //kprintf("v86Task\n"); + irqDisable(0x0); + } + GDT[4].descriptor.baseLow = (memAddr & 0xFFFF); + GDT[4].descriptor.baseMed = ((memAddr >> 16) & 0xFF); + GDT[4].descriptor.baseHigh = (memAddr >> 24); + GDT[4].descriptor.access = '\x89'; + asm("ljmp $0x20,$0\n"); + } + return; + } /* sched() */ + +kTask_t *schedNewTask() { + kTask_t *tmpTask = (kTask_t *)kmalloc(sizeof(kTask_t),sysID); + kTask_t *listLoop = 0x0; + + for (listLoop = taskList; listLoop; listLoop = listLoop->next) { + + if (0x0 == listLoop->next) { + tmpTask->prev = listLoop; + tmpTask->next = 0x0; + listLoop->next = tmpTask; + break; + } /* if listLoop->next == 0x0 */ + + } /* for */ + + tmpTask->usedMath = 0x0; + tmpTask->id = nextID++; + tmpTask->state = NEW; + //tmpTask->oInfo.container = findMount("s"); + tmpTask->oInfo.cwd = (char *)kmalloc(1024,tmpTask->id); + + return(tmpTask); + } /* schedNewTask() */ + +int schedDeleteTask(uInt32 id) { + kTask_t *tmpTask = 0x0; + + for (tmpTask = taskList; tmpTask; tmpTask=tmpTask->next) { + + if (tmpTask->id == id) { + + tmpTask->prev->next = tmpTask->next; + tmpTask->next->prev = tmpTask->prev; + + if (_current == tmpTask) { + _current = taskList; + } /* if _current == tmpTask */ + + kfree(tmpTask); + + } /* if tmpTask-> == id */ + } /* for */ + + return(0); + } /* deleteTask() */ + + +kTask_t *schedFindTask(uInt32 id) { + kTask_t *tmpTask = 0x0; + for (tmpTask = taskList; tmpTask != 0x0; tmpTask = tmpTask->next) { + + if (tmpTask->id == id) { + return(tmpTask); + } /* if tmpTask-> == id */ + + } /* for */ + return(0x0); + } /* findTask() */ + +/************************************************************************ + +Function: int schedEndTask() + +Description: This function will end a task + +Notes: + +02/20/2004 - Approved for quality + +************************************************************************/ +int schedEndTask(pidType pid) { + //vmmFreeProcessPages(_current->id); + _current->state = DEAD; + //schedDeleteTask(_current->id); + return(0x0); + } + +/************************************************************************ + +Function: int schedEndTask() + +Description: This function will yield a task + +Notes: + +02/20/2004 - Approved for quality + +************************************************************************/ +void schedYield() { + sched(); + } + +/*** + END + ***/ + diff --git a/src/sys/kernel/syscall.c b/src/sys/kernel/syscall.c new file mode 100644 index 0000000..73195cd --- /dev/null +++ b/src/sys/kernel/syscall.c @@ -0,0 +1,170 @@ +/***************************************************************************************** + 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. + + $Log$ + Revision 1.28 2004/04/13 16:16:44 reddawg + Changed our copyright, it is all now under a BSD-Style license + + + + $Id$ + +*****************************************************************************************/ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +void sdeTestThread(); + +asm( + ".globl _sysCall \n" + "_sysCall: \n" + " cmpl totalCalls,%eax \n" + " jae invalidSysCall \n" + " pushl %edx \n" + " pushl %ecx \n" + " pushl %ebx \n" + " call *systemCalls(,%eax,4) \n" + " jmp done \n" + "invalidSysCall: \n" + " call invalidCall \n" + "done: \n" + " popl %ebx \n" + " popl %ecx \n" + " popl %edx \n" + " iret \n" /* Exit interrupt */ + ); + +void invalidCall() { + kprintf("Invalid Sys Call!\n"); + } + +void sysGetpid(int *pid) { + *pid = _current->id; + return; + } + +void sysGetUid(int *uid) { + *uid = _current->uid; + return; + } + +void sysGetGid(int *gid) { + *gid = _current->gid; + return; + } + +void sysSetUid(int uid,int *status) { + if (_current->uid == 0x0) { + _current->uid = uid; + *status = 0x0; + } + else { + *status = 1; + } + return; + } + +void sysSetGid(int gid,int *status) { + if (_current->gid == 0x0) { + _current->gid = gid; + *status = 0x0; + } + else { + *status = 1; + } + return; + } + +void sysExit(int status) { + _current->state = DEAD; + //schedEndTask(_current->id); + sched(); + } + +void sysCheckPid(int pid,int *ptr) { + *ptr = schedFindTask(pid)->state; + return; + } + +/************************************************************************ + +Function: void sysGetFreePage(); +Description: Allocs A Page To The Users VM Space +Notes: + +************************************************************************/ +void sysGetFreePage(long *ptr,int count) { + *ptr = (long) vmmGetFreeVirtualPage(_current->id,count); + return; + } + +void sysGetDrives(uInt32 *ptr) { + *ptr = (uInt32)drives; + return; + } + +void sysGetUptime(uInt32 *ptr) { + *ptr = systemVitals->sysTicks; + return; + } + +void sysGetTime(uInt32 *ptr) { + *ptr = systemVitals->sysUptime + systemVitals->timeStart; + return; + } + + +void sysGetCwd(char *data) { + sprintf(data,_current->oInfo.cwd); + return; + } + +void sysSchedYield() { + schedYield(); + asm("hlt"); + } + +void sysStartSDE() { + int i = 0x0; + execThread(sdeThread,(uInt32)(kmalloc(0x2000,sysID)+0x2000),0x0,"SDE Main Thread"); + for (i=0;i<500;i++) { + asm("hlt"); + } + //execThread(sdeTestThread,(uInt32)(kmalloc(0x2000,sysID)+0x2000),"SDE Test"); + return; + } diff --git a/src/sys/kernel/time.c b/src/sys/kernel/time.c new file mode 100644 index 0000000..4469e38 --- /dev/null +++ b/src/sys/kernel/time.c @@ -0,0 +1,124 @@ +/***************************************************************************************** + 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. + + $Log$ + Revision 1.5 2004/04/13 16:16:44 reddawg + Changed our copyright, it is all now under a BSD-Style license + + + + $Id$ + +*****************************************************************************************/ +#include +#include +#include +#include + +static int month[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 timeInit() { + + struct timeStruct time; + int i; + + for (i = 0 ; i < 1000000 ; i++) { + if (!(timeCmosRead(10) & 0x80)) { + break; + } + } + + do { + time.sec = timeCmosRead(0); + time.min = timeCmosRead(2); + time.hour = timeCmosRead(4); + time.day = timeCmosRead(7); + time.mon = timeCmosRead(8); + time.year = timeCmosRead(9); + } while (time.sec != timeCmosRead(0)); + + BCD_TO_BIN(time.sec); + BCD_TO_BIN(time.min); + BCD_TO_BIN(time.hour); + BCD_TO_BIN(time.day); + BCD_TO_BIN(time.mon); + BCD_TO_BIN(time.year); + + kprintf("%i/%i/%i %i:%i.%i\n",time.mon,time.day,time.year,time.hour,time.min,time.sec); + + systemVitals->timeStart = timeMake(&time); + + /* Return so we know all went well */ + return(0x0); + } + +uInt32 timeMake(struct timeStruct *time) { + uInt32 res; + int year; + + year = (time->year+100) - 70; + /* magic offsets (y+1) needed to get leapyears right.*/ + res = YEAR*year + DAY*((year+1)/4); + res += month[time->mon]; + /* and (y+2) here. If it wasn't a leap-year, we have to adjust */ + if (time->mon>1 && ((year+2)%4)) + res -= DAY; + res += DAY*(time->day-1); + res += HOUR*time->hour; + res += MINUTE*time->min; + res += time->sec; + return(res); + } + +int gettimeofday(struct timeval *tp,struct timezone *tzp) { + //tp->tv_sec = systemVitals->timeStart + systemVitals->sysUptime; + tp->tv_sec = 0x0;//systemVitals->sysUptime; + tp->tv_usec = 0x0; + return(0x0); + } + +int timeCmosRead(int addr) { + outportByteP(0x70,addr); + return(inportByte(0x71)); + } + +/*** + END + ***/ + diff --git a/src/sys/kernel/ubthread.c b/src/sys/kernel/ubthread.c new file mode 100644 index 0000000..0112093 --- /dev/null +++ b/src/sys/kernel/ubthread.c @@ -0,0 +1,145 @@ +/***************************************************************************************** + 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. + + $Log$ + Revision 1.9 2004/04/13 21:29:52 reddawg + We now have sockets working. Lots of functionality to be added to continually + improve on the existing layers now its clean up time to get things in a better + working order. + + Revision 1.8 2004/04/13 17:13:41 reddawg + Minor Update + + Revision 1.7 2004/04/13 16:16:44 reddawg + Changed our copyright, it is all now under a BSD-Style license + + + + $Id$ + +*****************************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include +#include + +struct ubthread_cond_list *conds = 0x0; +struct ubthread_mutex_list *mutex = 0x0; + +kTask_t *ubthread_self() { + return(_current); + } + +int ubthread_cond_init(ubthread_cond_t *cond,const uInt32 attr) { + ubthread_cond_t ubcond = kmalloc(sizeof(struct ubthread_cond),sysID); + ubcond->id = (int)cond; + ubcond->locked = UNLOCKED; + *cond = ubcond; + return(0x0); + } + +int ubthread_mutex_init(ubthread_mutex_t *mutex,const uInt32 attr) { + ubthread_mutex_t ubmutex = kmalloc(sizeof(struct ubthread_mutex),sysID); + ubmutex->id = (int)mutex; + ubmutex->locked = UNLOCKED; + *mutex = ubmutex; + return(0x0); + } + +int ubthread_cond_destroy(ubthread_cond_t *cond) { + kfree(*cond); + *cond = 0x0; + return(0x0); + } + +int ubthread_mutex_destroy(ubthread_mutex_t *mutex) { + kfree(*mutex); + *mutex = 0x0; + return(0x0); + } + +int ubthread_create(kTask_t **thread,const uInt32 *attr,void *start_routine, void *arg) { + *thread = (void *)execThread((void *)start_routine,(uInt32)(kmalloc(0x4000,sysID)+0x4000),arg,"TCP/IP Thread"); + return(0x0); + } + +int ubthread_mutex_lock(ubthread_mutex_t *mutex) { + ubthread_mutex_t ubmutex = *mutex; + if (ubmutex->locked == LOCKED) { + //kprintf("Mutex Already Lock By %x Trying To Be Relocked By %x\n",ubmutex->pid,_current->id); + while (ubmutex->locked == LOCKED); + } + ubmutex->locked = LOCKED; + ubmutex->pid = _current->id; + return(0x0); + } + +int ubthread_mutex_unlock(ubthread_mutex_t *mutex) { + ubthread_mutex_t ubmutex = *mutex; + if (ubmutex->pid == _current->id) { + ubmutex->locked = UNLOCKED; + return(0x0); + } + else { + //kprintf("Trying To Unlock Mutex From No Locking Thread\n"); + ubmutex->locked = UNLOCKED; + return(-1); + } + } + +int ubthread_cond_timedwait(ubthread_cond_t *cond, ubthread_mutex_t *mutex, const struct timespec *abstime) { + ubthread_cond_t ubcond = *cond; + ubthread_mutex_t ubmutex = *mutex; + uInt32 enterTime = systemVitals->sysUptime+20; + while (enterTime > systemVitals->sysUptime) { + if (ubcond->locked == UNLOCKED) break; + schedYield(); + } + ubmutex->locked = UNLOCKED; + return(0x0); + } + +int ubthread_cond_wait(ubthread_cond_t *cond, ubthread_mutex_t *mutex) { + ubthread_cond_t ubcond = *cond; + ubthread_mutex_t ubmutex = *mutex; + while (ubcond->locked == LOCKED); + ubmutex->locked = UNLOCKED; + return(0x0); + } + +int ubthread_cond_signal(ubthread_cond_t *cond) { + ubthread_cond_t ubcond = *cond; + ubcond->locked = UNLOCKED; + return(0x0); + } + +/*** + END + ***/ diff --git a/src/sys/kernel/vitals.c b/src/sys/kernel/vitals.c new file mode 100644 index 0000000..a84385b --- /dev/null +++ b/src/sys/kernel/vitals.c @@ -0,0 +1,84 @@ +/***************************************************************************************** + 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. + + $Log$ + Revision 1.22 2004/04/13 16:16:44 reddawg + Changed our copyright, it is all now under a BSD-Style license + + + + $Id$ + +*****************************************************************************************/ + +#include +#include +#include +#include +#include + +vitalsNode *systemVitals = 0x0; + +/************************************************************************ + +Function: initVitals(); +Description: This will enable the vitals subsystem for ubixos + +Notes: + +02/20/2004 - Approved Its Quality + +************************************************************************/ +int initVitals() { + /* Initialize Memory For The System Vitals Node */ + systemVitals = (vitalsNode *) kmalloc(sizeof(vitalsNode), sysID); + + /* If malloc Failed Then Error */ + if (systemVitals == 0x0) { + kpanic("Error: kmalloc Failed In initVitals\n"); + } + + /* Set all default values */ + systemVitals->freePages = freePages; + systemVitals->sysTicks = 0x0; + systemVitals->sysUptime = 0x0; + systemVitals->fileSystems = 0x0; + systemVitals->mountPoints = 0x0; + systemVitals->timeStart = 0x0; + systemVitals->screen = 0x0; + systemVitals->font = 0x0; + + /* Print Out Info For Vitals: */ + kprintf("vitals0 - Address: [0x%X]\n",systemVitals); + + /* Return so kernel knows that there is no problem */ + return(0x0); + + } + +/**** +END +****/ + diff --git a/src/sys/lib/Makefile b/src/sys/lib/Makefile new file mode 100644 index 0000000..dbff453 --- /dev/null +++ b/src/sys/lib/Makefile @@ -0,0 +1,29 @@ +# (C) 2002 The UbixOS Project +# $Id$ + +# Include Global 'Source' Options +include ../../Makefile.inc +include ../Makefile.inc + +# Objects +OBJS = ogprintf.o sqrt.o atan.o divdi3.o libcpp.o strtok.o kmalloc.o kprintf.o vsprintf.o string.o net.o strtol.o + +all: $(OBJS) + +# Compile Types +.cpp.o: + $(CXX) ${CFLAGS} -Wall -DNOBOOL -fno-rtti -fno-exceptions -g -c -I../include -o $@ $< +.cc.o: + $(CXX) ${CFLAGS} -Wall -DNOBOOL -D__UBIXOS_KERNEL__ -fno-rtti -fno-exceptions -fomit-frame-pointer -O -I../include -I../../lib/objgfx40 -c -o $@ $< +.cc.s: + $(CXX) ${CFLAGS} -Wall -fomit-frame-pointer -O -I../include -S -o $@ $< +.c.o: + $(CC) ${CFLAGS} -Wall -fomit-frame-pointer -O -I../include -c -o $@ $< +.c.s: + $(CC) ${CFLAGS} -Wall -fomit-frame-pointer -O -I../include -S -o $@ $< +.S.o: + $(CC) ${CFLAGS} -Wall -fomit-frame-pointer -c -o $@ $< + +# Clean up the junk +clean: + $(REMOVE) $(OBJS) diff --git a/src/sys/lib/atan.c b/src/sys/lib/atan.c new file mode 100644 index 0000000..2e44c8e --- /dev/null +++ b/src/sys/lib/atan.c @@ -0,0 +1,45 @@ +/***************************************************************************************** + 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. + + $Log$ + Revision 1.2 2004/04/13 16:36:33 reddawg + Changed our copyright, it is all now under a BSD-Style license + + + + $Id$ + +*****************************************************************************************/ + +#include + +double atan(double x) { + return(x); + } + +/*** + END + ***/ + diff --git a/src/sys/lib/divdi3.c b/src/sys/lib/divdi3.c new file mode 100644 index 0000000..1603173 --- /dev/null +++ b/src/sys/lib/divdi3.c @@ -0,0 +1,49 @@ +/***************************************************************************************** + 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. + + $Log$ + Revision 1.2 2004/04/13 16:36:33 reddawg + Changed our copyright, it is all now under a BSD-Style license + + + + $Id$ + +*****************************************************************************************/ + +#include + +u_quad_t __udivdi3(u_quad_t a,u_quad_t b) { + return(0); + } + +quad_t __divdi3(quad_t a,quad_t b) { + return(0); + } + +/*** + END + ***/ + diff --git a/src/sys/lib/kmalloc.c b/src/sys/lib/kmalloc.c new file mode 100644 index 0000000..2391286 --- /dev/null +++ b/src/sys/lib/kmalloc.c @@ -0,0 +1,388 @@ +/***************************************************************************************** + 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. + + $Log$ + Revision 1.21 2004/04/13 16:36:33 reddawg + Changed our copyright, it is all now under a BSD-Style license + + + + $Id$ + +*****************************************************************************************/ + +#include +#include +#include +#include +#include +#include + +struct memDescriptor *kernDesc = 0x0; +struct memDescriptor *freeKernDesc = 0x0; +struct memDescriptor *emptyKernDesc = 0x0; + +int mallocLock = 0x0; + +void initMalloc(pidType pid) { + int i=0; + struct memDescriptor *tmpDesc1 = 0x0; + struct memDescriptor *tmpDesc2 = 0x0; + emptyKernDesc = (struct memDescriptor *)vmmGetFreeKernelPage(pid,4); + tmpDesc1 = emptyKernDesc; + tmpDesc1->prev = 0x0; + for (i=1;i<((4096/sizeof(struct memDescriptor))*4);i++) { + tmpDesc2 = &emptyKernDesc[i]; + tmpDesc2->prev = tmpDesc1; + tmpDesc1->next = tmpDesc2; + tmpDesc1 = tmpDesc2; + } + tmpDesc1->next = 0x0; + //Return + return; + } + +/************************************************************************ + +Function: void *getEmptyDesc() +Description: Find An Empty Descriptor + +Notes: + +02/17/03 - Is This Efficient? + +************************************************************************/ +void *getEmptyDesc() { + struct memDescriptor *tmpDesc = emptyKernDesc; + if (tmpDesc != 0x0) { + emptyKernDesc = tmpDesc->next; + emptyKernDesc->prev = 0x0; + tmpDesc->next = 0x0; + tmpDesc->prev = 0x0; + tmpDesc->pid = 0x0; + return(tmpDesc); + } + kpanic("Error Finding Empty Descriptor!\n"); + return(0x0); + } + +/************************************************************************ + +Function: void *kmalloc(uInt32 len,pidType pid) +Description: Allocate Kernel Memory + +Notes: + +02/17/03 - Do I Still Need To Pass In The Pid? + +************************************************************************/ +void *kmalloc(uInt32 len,pidType pid) { + struct memDescriptor *tmpDesc1 = 0x0; + struct memDescriptor *tmpDesc2 = 0x0; + char *buf = 0x0; + int i = 0x0; + + if (mallocLock != 0x0) + while (1) asm("nop"); + + mallocLock = sysID;// _current->id; + //If Kernel Descriptor Is NULL Initialize Malloc + if (emptyKernDesc == 0x0) { + initMalloc(pid); + } + len = (len + 15) & 0xFFFFFFF0; + if (len == 0x0) { + kpanic("Malloc of Size 0 Requested\n"); + return(0x0); + } + for (tmpDesc1 = freeKernDesc;tmpDesc1;tmpDesc1=tmpDesc1->next) { + if (tmpDesc1->limit >= len) { + tmpDesc1->status = 0x1; + if (tmpDesc1->prev != 0x0) { + tmpDesc1->prev->next = tmpDesc1->next; + tmpDesc1->next->prev = tmpDesc1->prev; + } + else { + freeKernDesc = tmpDesc1->next; + freeKernDesc->prev = 0x0; + } + tmpDesc1->prev = 0x0; + tmpDesc1->next = kernDesc; + kernDesc->prev = tmpDesc1; + kernDesc = tmpDesc1; + if (tmpDesc1->limit > (len + 16)) { + tmpDesc2 = getEmptyDesc(); + tmpDesc2->limit = tmpDesc1->limit - len; + tmpDesc1->limit = len; + tmpDesc2->baseAddr = tmpDesc1->baseAddr + len; + tmpDesc2->status = 0x0; + tmpDesc2->next = 0x0; + tmpDesc2->prev = 0x0; + insertFreeDesc(tmpDesc2); + } + tmpDesc1->pid = pid; + mallocLock = 0x0; + buf = (char *)tmpDesc1->baseAddr; + for (i=0;ilimit;i++) { + (char)buf[i] = (char)0x0; + } + return(tmpDesc1->baseAddr); + } + } + tmpDesc1 = getEmptyDesc(); + if (tmpDesc1 != 0x0) { + tmpDesc1->baseAddr = (struct memDescriptor *)vmmGetFreeKernelPage(pid,((len + 4095)/4096)); + tmpDesc1->limit = len; + tmpDesc1->status = 0x1; + tmpDesc1->next = kernDesc; + tmpDesc1->prev = 0x0; + kernDesc = tmpDesc1; + kernDesc->next->prev = tmpDesc1; + if ((len-4096) > 0) { + tmpDesc2 = getEmptyDesc(); + tmpDesc2->status = 0x0; + tmpDesc2->baseAddr = tmpDesc1->baseAddr + tmpDesc1->limit; + tmpDesc2->limit = ((len + 4095)/4096)*4096 - tmpDesc1->limit; + tmpDesc2->prev = 0x0; + tmpDesc2->next = 0x0; + insertFreeDesc(tmpDesc2); + } + tmpDesc1->pid = pid; + mallocLock = 0x0; + buf = (char *)tmpDesc1->baseAddr; + for (i=0;ilimit;i++) { + (char)buf[i] = (char)0x0; + } + return(tmpDesc1->baseAddr); + } + //Return Null If Unable To Malloc + mallocLock = 0x0; + return(0x0); + } + +/************************************************************************ + +Function: void kfree(void *baseAddr) +Description: This Will Find The Descriptor And Free It + +Notes: + +02/17/03 - I need To Make It Join Descriptors + +************************************************************************/ +void kfree(void *baseAddr) { + uInt32 *data = 0x0; + long i = 0x0; + struct memDescriptor *tmpDesc1 = 0x0; + struct memDescriptor *tmpDesc2 = 0x0; + + while (mallocLock != 0x0) asm("nop"); + + mallocLock = _current->id; + for (tmpDesc1=kernDesc;tmpDesc1;tmpDesc1=tmpDesc1->next) { + if (tmpDesc1->baseAddr == baseAddr) { + tmpDesc1->status = 0x0; + if (tmpDesc1->prev != 0x0) { + tmpDesc2 = tmpDesc1->prev; + tmpDesc2->next = tmpDesc1->next; + } + if (tmpDesc1->next != 0x0) { + tmpDesc2 = tmpDesc1->next; + tmpDesc2->prev = tmpDesc1->prev; + } + if (kernDesc == tmpDesc1) { + kernDesc = tmpDesc1->next; + } + tmpDesc1->next = 0x0; + tmpDesc1->prev = 0x0; + insertFreeDesc(tmpDesc1); + data = (long *)baseAddr; + for (i=0;i < (tmpDesc1->limit/4);i++) { + data[i] = 0x0; + } + //mergeMemBlocks(); + mallocLock = 0x0; + return; + } + } + kprintf("Error Freeing Descriptor! [0x%X]\n",baseAddr); + mallocLock = 0x0; + return; + } + +/************************************************************************ + +Function: void insertFreeDesc(struct memDescriptor *freeDesc) +Description: This Function Inserts A Free Descriptor On The List Which Is + Kept In Size Order + +Notes: + +02/17/03 - This Was Inspired By TCA's Great Wisdom - + "[20:20:59] You should just insert it in order" + +************************************************************************/ +void insertFreeDesc(struct memDescriptor *freeDesc) { + struct memDescriptor *tmpDesc; + freeDesc->status = 0x0; + if (freeKernDesc != 0x0) { + for (tmpDesc=freeKernDesc;tmpDesc;tmpDesc=tmpDesc->next) { + if ((freeDesc->limit >= tmpDesc->limit) && (!tmpDesc->next)) { + tmpDesc->next = freeDesc; + freeDesc->prev = tmpDesc; + freeDesc->next = 0x0; + return; + } + else if ((freeDesc->limit >= tmpDesc->limit) && (freeDesc->limit <= tmpDesc->next->limit)) { + freeDesc->next = tmpDesc->next; + freeDesc->prev = tmpDesc; + tmpDesc->next->prev = freeDesc; + tmpDesc->next = freeDesc; + return; + } + } + } + else { + freeDesc->prev = 0x0; + freeDesc->next = 0x0; + freeKernDesc = freeDesc; + return; + } + //sysErr("Error With Freeing Blocks"); + return; + } + +/************************************************************************ + +Function: void mergeMemBlocks() +Description: This Function Will Merge Free Blocks And Free Pages + +Notes: + +03/05/03 - We Have A Problem It Seems The First Block Is Limit 0x0 + +************************************************************************/ +void mergeMemBlocks() { + struct memDescriptor *tmpDesc1 = 0x0; + struct memDescriptor *tmpDesc2 = 0x0; + uInt32 baseAddr = 0x0; + + return; + + //Loop The Free Descriptors See If We Can Merge Them + for (tmpDesc1=freeKernDesc;tmpDesc1;tmpDesc1=tmpDesc1->next) { + /* + Compare The Base Addr With The Other Descriptors If You Find The One + That You Are Looking For Lets Merge Them + */ + if (tmpDesc1->limit != 0x0) { + baseAddr = (uInt32)tmpDesc1->baseAddr + (uInt32)tmpDesc1->limit; + for (tmpDesc2=freeKernDesc;tmpDesc2;tmpDesc2=tmpDesc2->next) { + if ((uInt32)tmpDesc2->baseAddr == baseAddr) { + tmpDesc1->limit += tmpDesc2->limit; + tmpDesc2->baseAddr = 0x0; + tmpDesc2->limit = 0x0; + tmpDesc2->status = 0x0; + if (tmpDesc2->prev) { + tmpDesc2->prev->next = tmpDesc2->next; + } + if (tmpDesc2->next) { + tmpDesc2->next->prev = tmpDesc2->prev; + } + tmpDesc2->prev = 0x0; + tmpDesc2->next = emptyKernDesc; + emptyKernDesc->prev = tmpDesc2; + emptyKernDesc = tmpDesc2; + if (tmpDesc1->prev) { + tmpDesc1->prev->next = tmpDesc1->next; + } + if (tmpDesc1->next) { + tmpDesc1->next->prev = tmpDesc1->prev; + } + tmpDesc1->prev = 0x0; + tmpDesc1->next = 0x0; + insertFreeDesc(tmpDesc1); + tmpDesc1 = freeKernDesc; + break; + } + } + } + } + return; + } + +/************************************************************************ + +Function: void kfreeProcess(pidType pid) +Description: This Will Find The Descriptor And Free It + +Notes: + +02/17/03 - I need To Make It Join Descriptors + +************************************************************************/ +void kfreeProcess(pidType pid) { + long *data = 0x0; + long i = 0x0; + struct memDescriptor *tmpDesc1 = 0x0; + struct memDescriptor *tmpDesc2 = 0x0; + + while (mallocLock != 0x0) { + while (1) asm("nop"); + } + + mallocLock = sysID;//_current->id; + for (tmpDesc1=kernDesc;tmpDesc1;tmpDesc1=tmpDesc1->next) { + if (tmpDesc1->pid == pid) { + tmpDesc1->status = 0x0; + if (tmpDesc1->prev != 0x0) { + tmpDesc2 = tmpDesc1->prev; + tmpDesc2->next = tmpDesc1->next; + } + if (tmpDesc1->next != 0x0) { + tmpDesc2 = tmpDesc1->next; + tmpDesc2->prev = tmpDesc1->prev; + } + if (kernDesc == tmpDesc1) { + kernDesc = tmpDesc1->next; + } + tmpDesc1->next = 0x0; + tmpDesc1->prev = 0x0; + insertFreeDesc(tmpDesc1); + data = tmpDesc1->baseAddr; + for (i=0;i < (tmpDesc1->limit/4);i++) { + data[i] = 0x0; + } + //mergeMemBlocks(); + } + } + mallocLock = 0x0; + return; + } + +/*** + END + ***/ + diff --git a/src/sys/lib/kprintf.c b/src/sys/lib/kprintf.c new file mode 100644 index 0000000..9fefe17 --- /dev/null +++ b/src/sys/lib/kprintf.c @@ -0,0 +1,84 @@ +/***************************************************************************************** + 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. + + $Log$ + Revision 1.13 2004/04/13 16:36:33 reddawg + Changed our copyright, it is all now under a BSD-Style license + + + + $Id$ + +*****************************************************************************************/ + +#include +#include + +int vsprintf(char *buf, const char *fmt, vaList args); +int ogPrintf(char *s); + +int printOff = 0x0; +int ogprintOff = 0x1; + +int kprintf(const char *fmt, ...) { + char buf[1024]; + vaList args; + int i = 0x0; + vaStart(args, fmt); + i=vsprintf(buf,fmt,args); + vaEnd(args); + if (printOff == 0x0) { + kprint(buf); + } + if (ogprintOff == 0x0) { + ogPrintf(buf); + } + return(i); + } + +int vPrintf(const char *fmt, ...) { + vaList args; + int i; + char buf[512]; + vaStart(args, fmt); + i=vsprintf(buf,fmt,args); + vaEnd(args); + if (printOff == 0x0) + kprint(buf); + return(i); + } + +int sprintf(char *buf,const char *fmt, ...) { + vaList args; + int i; + vaStart(args, fmt); + i=vsprintf(buf,fmt,args); + vaEnd(args); + return(i); + } + +/*** + END + ***/ diff --git a/src/sys/lib/libcpp.cc b/src/sys/lib/libcpp.cc new file mode 100644 index 0000000..c2ab222 --- /dev/null +++ b/src/sys/lib/libcpp.cc @@ -0,0 +1,78 @@ +/***************************************************************************************** + 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. + + $Log$ + Revision 1.2 2004/04/13 16:36:33 reddawg + Changed our copyright, it is all now under a BSD-Style license + + + + $Id$ + +*****************************************************************************************/ + +extern "C" +{ +#include +#include +void __pure_virtual() { while(1); } +void __cxa_pure_virtual() { while(1); } +} + +#include + +void * operator new[](unsigned size) +{ + return kmalloc(size,sysID); +} + +void operator delete[](void * ptr) +{ + kfree(ptr); + + return; +} + +void * operator new(unsigned size) +{ + void * ptr = kmalloc(size, sysID); + + //kprintf("Malloced: %08x\n", ptr); + + return ptr; +} + +void operator delete(void * ptr) +{ + kfree(ptr); + //kprintf("Freed: %08x\n", ptr); + + return; +} + +/*** + END + ***/ + diff --git a/src/sys/lib/net.c b/src/sys/lib/net.c new file mode 100644 index 0000000..e859209 --- /dev/null +++ b/src/sys/lib/net.c @@ -0,0 +1,176 @@ +/***************************************************************************************** + 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. + + $Log$ + Revision 1.8 2004/04/13 21:29:52 reddawg + We now have sockets working. Lots of functionality to be added to continually + improve on the existing layers now its clean up time to get things in a better + working order. + + Revision 1.7 2004/04/13 16:36:33 reddawg + Changed our copyright, it is all now under a BSD-Style license + + + + $Id$ + +*****************************************************************************************/ + +#include +#include +#include + +#ifndef _IN_ADDR_T_DECLARED +typedef uint32_t in_addr_t; +#define _IN_ADDR_T_DECLARED +#endif + +uInt32 htonl(uInt32 n) { + uInt32 retVal = 0x0; + retVal += ((n & 0xff) << 24); + retVal += ((n & 0xff00) << 8); + retVal += ((n & 0xff0000) >> 8); + retVal += ((n & 0xff000000) >> 24); + return(retVal); + } + +uInt32 htons(uInt32 n) { + uInt32 retVal = 0x0; + retVal = (((n & 0xff) << 8) | ((n & 0xff00) >> 8)); + return(retVal); + } + +void bcopy(const void *src, void *dest, int len) { + kmemcpy(dest,src,len); + } + +void bzero(void *data, int n) { + kmemset(data, 0, n); + } + + +inet_aton(cp, addr) + const char *cp; + struct in_addr *addr; +{ + uInt32 parts[4]; + in_addr_t val; + char *c; + char *endptr; + int gotend, n; + + c = (char *)cp; + n = 0; + /* + * Run through the string, grabbing numbers until + * the end of the string, or some error + */ + gotend = 0; + while (!gotend) { + //errno = 0; + val = strtol(c, &endptr, 0); + kprintf("VAL: [%x]",val); + + //if (errno == ERANGE) /* Fail completely if it overflowed. */ + // return (0); + + /* + * If the whole string is invalid, endptr will equal + * c.. this way we can make sure someone hasn't + * gone '.12' or something which would get past + * the next check. + */ + if (endptr == c) + return (0); + parts[n] = val; + c = endptr; + + /* Check the next character past the previous number's end */ + switch (*c) { + case '.' : + /* Make sure we only do 3 dots .. */ + if (n == 3) /* Whoops. Quit. */ + return (0); + n++; + c++; + break; + + case '\0': + gotend = 1; + break; + + default: + /* + if (isspace((unsigned char)*c)) { + gotend = 1; + break; + } else + */ + return (0); /* Invalid character, so fail */ + } + + } + + /* + * Concoct the address according to + * the number of parts specified. + */ + + switch (n) { + case 0: /* a -- 32 bits */ + /* + * Nothing is necessary here. Overflow checking was + * already done in strtoul(). + */ + break; + case 1: /* a.b -- 8.24 bits */ + if (val > 0xffffff || parts[0] > 0xff) + return (0); + val |= parts[0] << 24; + break; + + case 2: /* a.b.c -- 8.8.16 bits */ + if (val > 0xffff || parts[0] > 0xff || parts[1] > 0xff) + return (0); + val |= (parts[0] << 24) | (parts[1] << 16); + break; + + case 3: /* a.b.c.d -- 8.8.8.8 bits */ + if (val > 0xff || parts[0] > 0xff || parts[1] > 0xff || + parts[2] > 0xff) + return (0); + val |= (parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8); + break; + } + + if (addr != NULL) + addr->s_addr = htonl(val); + return (1); +} + +/*** + END + ***/ + diff --git a/src/sys/lib/ogprintf.cc b/src/sys/lib/ogprintf.cc new file mode 100644 index 0000000..abca029 --- /dev/null +++ b/src/sys/lib/ogprintf.cc @@ -0,0 +1,115 @@ +/***************************************************************************************** + 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. + + $Log$ + Revision 1.19 2004/04/13 16:36:33 reddawg + Changed our copyright, it is all now under a BSD-Style license + + + + $Id$ + +*****************************************************************************************/ + +#include +#include +#include + +extern "C" { +#include +int ogPrintf(char *s); + int screenRow = 0x0; + int screenCol = 0x1; + +int ogPrintf(char *s) { + int i = 0x0; + int bufHeight; + ogSurface *screen = (ogDisplay_UbixOS *)systemVitals->screen; + ogBitFont *font = (ogBitFont *)systemVitals->font; + + while ('\0' != s[i]) { + switch (s[i]) { + case '\t': + screenCol += 3; + break; + case '\b': + if (screenCol > 0) --screenCol; + case '\n': + screenCol = 0; + + bufHeight = ((screen->GetMaxY()+1) / font->GetHeight())-1; + if (screenRow < bufHeight) + ++screenRow; + else { + screen->CopyBuf(0, 0, + *screen, + 0, font->GetHeight(), + screen->GetMaxX(), screen->GetMaxY()); + screen->FillRect(0, bufHeight * font->GetHeight()+1, + screen->GetMaxX(), screen->GetMaxY(), + screen->Pack(122, 140, 163)); + } + break; + default: + font->PutChar(*screen, + screenCol * font->GetWidth(), + screenRow * font->GetHeight(), + s[i]); + break; + } /* switch */ + ++screenCol; + ++i; +#if 0 + if (screenRow > (int)((screen->GetMaxY()+1) / font->GetHeight())) { + screen->CopyBuf(0, 0, + *screen, + 0, font->GetHeight(), + screen->GetMaxX(), screen->GetMaxY()); + screen->FillRect(0, screen->GetMaxY() - font->GetHeight(), + screen->GetMaxX(), screen->GetMaxY(), + screen->Pack(122, 140, 163)); + --screenRow; + } /* if */ +#endif + } /* while */ + +#if 0 + screen->ScaleBuf(screen->GetMaxX() - (screen->GetMaxX() / 4), + screen->GetMaxY() - (screen->GetMaxY() / 4), + screen->GetMaxX(), + screen->GetMaxY(), + *screen, + 0, 0, + screen->GetMaxX() / 2, + screen->GetMaxY()); +#endif + return 0; +} // ogPrintf +} + +/*** + END + ***/ + diff --git a/src/sys/lib/sqrt.c b/src/sys/lib/sqrt.c new file mode 100644 index 0000000..782fe02 --- /dev/null +++ b/src/sys/lib/sqrt.c @@ -0,0 +1,43 @@ +/***************************************************************************************** + 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. + + $Log$ + Revision 1.2 2004/04/13 16:36:33 reddawg + Changed our copyright, it is all now under a BSD-Style license + + + + $Id$ + +*****************************************************************************************/ + +double sqrt(double x) { + return(x); + } + +/*** + END + ***/ + diff --git a/src/sys/lib/string.c b/src/sys/lib/string.c new file mode 100644 index 0000000..f4ce2ad --- /dev/null +++ b/src/sys/lib/string.c @@ -0,0 +1,152 @@ +/***************************************************************************************** + 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. + + $Log$ + Revision 1.5 2004/04/13 16:36:33 reddawg + Changed our copyright, it is all now under a BSD-Style license + + + + $Id$ + +*****************************************************************************************/ + +#include + +int kstrcmp(char *str1, char *str2) { + while ((*str1 == *str2) && (*str1 != 0x0) && (*str2 != 0x0)) { + str1++; + str2++; + } + if (*str1 == *str2) { + return(0); + } + else if (*str1 > *str2) { + return(1); + } + else { + return(-1); + } + } + +int kstrncmp(const char * a, const char * b, size_t c) +{ + int i = 0; + while (i < c) + { + if ((a[i] != b[i]) || (a[i] == '\0') || (b[i] == '\0')) + return a[i] - b[i]; + i++; + } + return 0; +} + + + +void * kmemcpy(const void *dst, const void * src, size_t length) { + size_t x = length >> 2; + size_t y = length & 0xf; + size_t i; + + for (i = 0; i < x; i++) { + ((unsigned long *)dst)[i] = ((unsigned long *)src)[i]; + } + + for (i = 0; i < y; i++) { + ((char *) dst)[length-y+i] = ((char *) src)[length-y+i]; + } + + return((void *)dst); + } + + +void *kmemset(void * dst, int c, size_t length) { + size_t x = length >> 2; + size_t y = length & 0xf; + size_t i; + + unsigned int newC = (c << 24) | (c << 16) | (c << 8) | (c); + + for (i = 0; i < x; i++) + ((unsigned long *)dst)[i] = newC; + + for (i = 0; i < y; i++) + ((char *) dst)[length-y+i] = c; + return dst; + } + +int kstrlen(const char * string) { + int i = 0; + + while (1) { + if (string[i] == '\0') + return i; + i++; + } + return 0; + } + +int kmemcmp(const void * dst, const void * src, size_t length) +{ + size_t x = length >> 2; + size_t y = length & 0xf; + size_t i; + + for (i = 0; i < x; i++) + { + if (((unsigned long *)dst)[i] > ((unsigned long *)src)[i]) + return 1; + if (((unsigned long *)dst)[i] < ((unsigned long *)src)[i]) + return -1; + } + + for (i = 0; i < y; i++) + { + if (((char *) dst)[length-y+i] > ((char *) src)[length-y+i]) + return 1; + if (((char *) dst)[length-y+i] < ((char *) src)[length-y+i]) + return -1; + } + + return 0; +} + +void kstrncpy(char * dest, const char * src, size_t size) +{ + if (size == 0) + return; + do + { + *dest = *src; + dest++; src++; + size--; + } + while(('\0' != *(src-1)) && (size)); +} + +/*** + END + ***/ + diff --git a/src/sys/lib/strtok.c b/src/sys/lib/strtok.c new file mode 100644 index 0000000..8d12a39 --- /dev/null +++ b/src/sys/lib/strtok.c @@ -0,0 +1,89 @@ +/***************************************************************************************** + 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. + + $Log$ + Revision 1.2 2004/04/13 16:36:33 reddawg + Changed our copyright, it is all now under a BSD-Style license + + + + $Id$ + +*****************************************************************************************/ + +#include +#include + +char *strtok_r(char *s, const char *delim, char **last) { + char *spanp; + int c, sc; + char *tok; + + if ((s == NULL) && ((s = *last) == NULL)) { + return(NULL); + } + +cont: + c = *s++; + for (spanp = (char *)delim; (sc = *spanp++) != 0; ) { + if (c == sc) { + goto cont; + } + } + if (c == 0) { + *last = NULL; + return(NULL); + } + tok = s - 1; + + for (;;) { + c = *s++; + spanp = (char *)delim; + do { + if ((sc = *spanp++) == c) { + if (c == 0) { + s = NULL; + } + else { + char *w = s - 1; + *w = '\0'; + } + *last = s; + return(tok); + } + } while (sc != 0); + } + } + +char *strtok(char *s, const char *delim) { + static char *last; + return (strtok_r(s, delim, &last)); + } + +/*** + END + ***/ + + diff --git a/src/sys/lib/strtol.c b/src/sys/lib/strtol.c new file mode 100644 index 0000000..8d936b5 --- /dev/null +++ b/src/sys/lib/strtol.c @@ -0,0 +1,102 @@ +#include +//#include +//#include +//#include + +#define LONG_MIN (-0x7fffffffL - 1) +#define LONG_MAX 0x7fffffffL + + + +long +strtol(const char * __restrict nptr, char ** __restrict endptr, int base) +{ + const char *s; + unsigned long acc; + char c; + unsigned long cutoff; + int neg, any, cutlim; + + /* + * Skip white space and pick up leading +/- sign if any. + * If base is 0, allow 0x for hex and 0 for octal, else + * assume decimal; if base is already 16, allow 0x. + */ + s = nptr; + /* + do { + c = *s++; + } while (isspace((unsigned char)c)); + */ + if (c == '-') { + neg = 1; + c = *s++; + } else { + neg = 0; + if (c == '+') + c = *s++; + } + if ((base == 0 || base == 16) && + c == '0' && (*s == 'x' || *s == 'X')) { + c = s[1]; + s += 2; + base = 16; + } + if (base == 0) + base = c == '0' ? 8 : 10; + acc = any = 0; + if (base < 2 || base > 36) + goto noconv; + + /* + * Compute the cutoff value between legal numbers and illegal + * numbers. That is the largest legal value, divided by the + * base. An input number that is greater than this value, if + * followed by a legal input character, is too big. One that + * is equal to this value may be valid or not; the limit + * between valid and invalid numbers is then based on the last + * digit. For instance, if the range for longs is + * [-2147483648..2147483647] and the input base is 10, + * cutoff will be set to 214748364 and cutlim to either + * 7 (neg==0) or 8 (neg==1), meaning that if we have accumulated + * a value > 214748364, or equal but the next digit is > 7 (or 8), + * the number is too big, and we will return a range error. + * + * Set 'any' if any `digits' consumed; make it negative to indicate + * overflow. + */ + cutoff = neg ? (unsigned long)-(LONG_MIN + LONG_MAX) + LONG_MAX + : LONG_MAX; + cutlim = cutoff % base; + cutoff /= base; + for ( ; ; c = *s++) { + if (c >= '0' && c <= '9') + c -= '0'; + else if (c >= 'A' && c <= 'Z') + c -= 'A' - 10; + else if (c >= 'a' && c <= 'z') + c -= '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 = (char *)(any ? s - 1 : nptr); + return (acc); +} diff --git a/src/sys/lib/vsprintf.c b/src/sys/lib/vsprintf.c new file mode 100644 index 0000000..c922052 --- /dev/null +++ b/src/sys/lib/vsprintf.c @@ -0,0 +1,270 @@ +/***************************************************************************************** + 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. + + $Log$ + Revision 1.3 2004/04/13 16:36:33 reddawg + Changed our copyright, it is all now under a BSD-Style license + + + + $Id$ + +*****************************************************************************************/ + +/* vsprintf.c -- Lars Wirzenius & Linus Torvalds. */ +/* + * Wirzenius wrote this portably, Torvalds fucked it up :-) + */ + +#include +#include + +/* we use this so that we can do without the ctype library */ +#define is_digit(c) ((c) >= '0' && (c) <= '9') + +static int skip_atoi(const char **s) +{ + int i=0; + + while (is_digit(**s)) + i = i*10 + *((*s)++) - '0'; + return i; +} + +#define ZEROPAD 1 /* pad with zero */ +#define SIGN 2 /* unsigned/signed long */ +#define PLUS 4 /* show plus */ +#define SPACE 8 /* space if plus */ +#define LEFT 16 /* left justified */ +#define SPECIAL 32 /* 0x */ +#define SMALL 64 /* use 'abcdef' instead of 'ABCDEF' */ + +#define do_div(n,base) ({ \ +int __res; \ +__asm__("divl %4":"=a" (n),"=d" (__res):"0" (n),"1" (0),"r" (base)); \ +__res; }) + +static char * number(char * str, int num, int base, int size, int precision + ,int type) +{ + char c,sign,tmp[36]; + const char *digits="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + int i; + + if (type&SMALL) digits="0123456789abcdefghijklmnopqrstuvwxyz"; + if (type&LEFT) type &= ~ZEROPAD; + if (base<2 || base>36) + return 0; + c = (type & ZEROPAD) ? '0' : ' ' ; + if (type&SIGN && num<0) { + sign='-'; + num = -num; + } else + sign=(type&PLUS) ? '+' : ((type&SPACE) ? ' ' : 0); + if (sign) size--; + if (type&SPECIAL) { + if (base==16) { size -= 2; } + else if (base==8) { size--; } + } + i=0; + if (num==0) + tmp[i++]='0'; + else while (num!=0) + tmp[i++]=digits[do_div(num,base)]; + if (i>precision) precision=i; + size -= precision; + if (!(type&(ZEROPAD+LEFT))) + while(size-->0) + *str++ = ' '; + if (sign) + *str++ = sign; + if (type&SPECIAL) { + if (base==8) { + *str++ = '0'; + } + else if (base==16) { + *str++ = '0'; + *str++ = digits[33]; + } + } + if (!(type&LEFT)) + while(size-->0) + *str++ = c; + while(i0) + *str++ = tmp[i]; + while(size-->0) + *str++ = ' '; + return str; +} + +int vsprintf(char *buf, const char *fmt, vaList args) +{ + int len; + int i; + char * str; + char *s; + int *ip; + + int flags; /* flags to number() */ + + int field_width; /* width of output field */ + int precision; /* min. # of digits for integers; max + number of chars for from string */ + int qualifier; /* 'h', 'l', or 'L' for integer fields */ + + for (str=buf ; *fmt ; ++fmt) { + if (*fmt != '%') { + *str++ = *fmt; + continue; + } + + /* process flags */ + flags = 0; + repeat: + ++fmt; /* this also skips first '%' */ + switch (*fmt) { + case '-': flags |= LEFT; goto repeat; + case '+': flags |= PLUS; goto repeat; + case ' ': flags |= SPACE; goto repeat; + case '#': flags |= SPECIAL; goto repeat; + case '0': flags |= ZEROPAD; goto repeat; + } + + /* get field width */ + field_width = -1; + if (is_digit(*fmt)) + field_width = skip_atoi(&fmt); + else if (*fmt == '*') { + /* it's the next argument */ + field_width = vaArg(args, int); + if (field_width < 0) { + field_width = -field_width; + flags |= LEFT; + } + } + + /* get the precision */ + precision = -1; + if (*fmt == '.') { + ++fmt; + if (is_digit(*fmt)) + precision = skip_atoi(&fmt); + else if (*fmt == '*') { + /* it's the next argument */ + precision = vaArg(args, int); + } + if (precision < 0) + precision = 0; + } + + /* get the conversion qualifier */ + qualifier = -1; + if (*fmt == 'h' || *fmt == 'l' || *fmt == 'L') { + qualifier = *fmt; + ++fmt; + } + + switch (*fmt) { + case 'c': + if (!(flags & LEFT)) + while (--field_width > 0) + *str++ = ' '; + *str++ = (unsigned char) vaArg(args, int); + while (--field_width > 0) + *str++ = ' '; + break; + + case 's': + s = vaArg(args, char *); + len = kstrlen(s); + if (precision < 0) + precision = len; + else if (len > precision) + len = precision; + + if (!(flags & LEFT)) + while (len < field_width--) + *str++ = ' '; + for (i = 0; i < len; ++i) + *str++ = *s++; + while (len < field_width--) + *str++ = ' '; + break; + + case 'o': + str = number(str, vaArg(args, unsigned long), 8, + field_width, precision, flags); + break; + + case 'p': + if (field_width == -1) { + field_width = 8; + flags |= ZEROPAD; + } + str = number(str, + (unsigned long) vaArg(args, void *), 16, + field_width, precision, flags); + break; + + case 'x': + flags |= SMALL; + case 'X': + str = number(str, vaArg(args, unsigned long), 16, + field_width, precision, flags); + break; + + case 'd': + case 'i': + flags |= SIGN; + case 'u': + str = number(str, vaArg(args, unsigned long), 10, + field_width, precision, flags); + break; + + case 'n': + ip = vaArg(args, int *); + *ip = (str - buf); + break; + + default: + if (*fmt != '%') + *str++ = '%'; + if (*fmt) + *str++ = *fmt; + else + --fmt; + break; + } + } + *str = '\0'; + return str-buf; +} + +/*** + END + ***/ + diff --git a/src/sys/net/Makefile b/src/sys/net/Makefile new file mode 100644 index 0000000..f009abf --- /dev/null +++ b/src/sys/net/Makefile @@ -0,0 +1,22 @@ +# $Id$ +# The System Makefile (C) 2002 The UbixOS Project + +all: core-code net-code api-code netif-code + +core-code: core + (cd core;make) + +net-code: net + (cd net;make) + +api-code: api + (cd api;make) + +netif-code: netif + (cd netif;make) + +clean: + (cd core;make clean) + (cd net;make clean) + (cd api;make clean) + (cd netif;make clean) diff --git a/src/sys/net/api/Makefile b/src/sys/net/api/Makefile new file mode 100644 index 0000000..9f74f5c --- /dev/null +++ b/src/sys/net/api/Makefile @@ -0,0 +1,28 @@ +# (C) 2002 The UbixOS Project +# +# $Id$ + +# Include Global 'Source' Options +include ../../../Makefile.inc +include ../../Makefile.inc + +# Objects +OBJS = api_lib.o api_msg.o err.o sockets.o tcpip.o + +all: $(OBJS) + +# Compile Types +.cc.o: + $(CXX) ${CFLAGS} -fno-exceptions -DNOBOOL -Wall -fomit-frame-pointer -O -I../../include -c -o $@ $< +.cc.s: + $(CXX) ${CFLAGS} -fno-exceptions -DNOBOOL -Wall -fomit-frame-pointer -O -I../../include -S -o $@ $< +.c.o: + $(CC) ${CFLAGS} -Wall -fomit-frame-pointer -O -I../../include -c -o $@ $< +.c.s: + $(CC) ${CFLAGS} -Wall -fomit-frame-pointer -O -I../../include -S -o $@ $< +.S.o: + $(CC) ${CFLAGS} -Wall -fomit-frame-pointer -c -o $@ $< + +# Clean up the junk +clean: + $(REMOVE) $(OBJS) diff --git a/src/sys/net/api/api_lib.c b/src/sys/net/api/api_lib.c new file mode 100644 index 0000000..e50658c --- /dev/null +++ b/src/sys/net/api/api_lib.c @@ -0,0 +1,643 @@ +/* + * Copyright (c) 2001, Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce 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 Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (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 file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + * $Id$ + */ + +/* This is the part of the API that is linked with + the application */ + +#include + +#include "net/debug.h" +#include "net/api.h" +#include "net/api_msg.h" +#include "net/memp.h" + +#include "net/debug.h" + +/*-----------------------------------------------------------------------------------*/ +struct +netbuf *netbuf_new(void) +{ + struct netbuf *buf; + + buf = memp_mallocp(MEMP_NETBUF); + if(buf != NULL) { + buf->p = NULL; + buf->ptr = NULL; + return buf; + } else { + return NULL; + } +} +/*-----------------------------------------------------------------------------------*/ +void +netbuf_delete(struct netbuf *buf) +{ + if(buf != NULL) { + if(buf->p != NULL) { + pbuf_free(buf->p); + buf->p = buf->ptr = NULL; + } + memp_freep(MEMP_NETBUF, buf); + } +} +/*-----------------------------------------------------------------------------------*/ +void * +netbuf_alloc(struct netbuf *buf, uInt16 size) +{ + /* Deallocate any previously allocated memory. */ + if(buf->p != NULL) { + pbuf_free(buf->p); + } + buf->p = pbuf_alloc(PBUF_TRANSPORT, size, PBUF_RAM); + if(buf->p == NULL) { + return NULL; + } + buf->ptr = buf->p; + return buf->p->payload; +} +/*-----------------------------------------------------------------------------------*/ +void +netbuf_free(struct netbuf *buf) +{ + if(buf->p != NULL) { + pbuf_free(buf->p); + } + buf->p = buf->ptr = NULL; +} +/*-----------------------------------------------------------------------------------*/ +void +netbuf_ref(struct netbuf *buf, void *dataptr, uInt16 size) +{ + if(buf->p != NULL) { + pbuf_free(buf->p); + } + buf->p = pbuf_alloc(PBUF_TRANSPORT, 0, PBUF_ROM); + buf->p->payload = dataptr; + buf->p->len = buf->p->tot_len = size; + buf->ptr = buf->p; +} +/*-----------------------------------------------------------------------------------*/ +void +netbuf_chain(struct netbuf *head, struct netbuf *tail) +{ + pbuf_chain(head->p, tail->p); + head->ptr = head->p; + memp_freep(MEMP_NETBUF, tail); +} +/*-----------------------------------------------------------------------------------*/ +uInt16 +netbuf_len(struct netbuf *buf) +{ + return buf->p->tot_len; +} +/*-----------------------------------------------------------------------------------*/ +err_t +netbuf_data(struct netbuf *buf, void **dataptr, uInt16 *len) +{ + if(buf->ptr == NULL) { + return ERR_BUF; + } + *dataptr = buf->ptr->payload; + *len = buf->ptr->len; + return ERR_OK; +} +/*-----------------------------------------------------------------------------------*/ +Int8 +netbuf_next(struct netbuf *buf) +{ + if(buf->ptr->next == NULL) { + return -1; + } + buf->ptr = buf->ptr->next; + if(buf->ptr->next == NULL) { + return 1; + } + return 0; +} +/*-----------------------------------------------------------------------------------*/ +void +netbuf_first(struct netbuf *buf) +{ + buf->ptr = buf->p; +} +/*-----------------------------------------------------------------------------------*/ +void +netbuf_copy_partial(struct netbuf *buf, void *dataptr, uInt16 len, uInt16 offset) +{ + struct pbuf *p; + uInt16 i, left; + + left = 0; + + if(buf == NULL) { + return; + } + + /* This implementation is bad. It should use bcopy + instead. */ + for(p = buf->p; left < len && p != NULL; p = p->next) { + if(offset != 0 && offset >= p->len) { + offset -= p->len; + } else { + for(i = offset; i < p->len; ++i) { + ((char *)dataptr)[left] = ((char *)p->payload)[i]; + if(++left >= len) { + return; + } + } + } + } +} +/*-----------------------------------------------------------------------------------*/ +void +netbuf_copy(struct netbuf *buf, void *dataptr, uInt16 len) +{ + netbuf_copy_partial(buf, dataptr, len, 0); +} +/*-----------------------------------------------------------------------------------*/ +struct ip_addr * +netbuf_fromaddr(struct netbuf *buf) +{ + return buf->fromaddr; +} +/*-----------------------------------------------------------------------------------*/ +uInt16 +netbuf_fromport(struct netbuf *buf) +{ + return buf->fromport; +} +/*-----------------------------------------------------------------------------------*/ +struct +netconn *netconn_new(enum netconn_type t) +{ + struct netconn *conn; + + conn = memp_mallocp(MEMP_NETCONN); + if(conn == NULL) { + return NULL; + } + conn->type = t; + conn->pcb.tcp = NULL; + + if((conn->mbox = sys_mbox_new()) == SYS_MBOX_NULL) { + memp_freep(MEMP_NETCONN, conn); + return NULL; + } + conn->recvmbox = SYS_MBOX_NULL; + conn->acceptmbox = SYS_MBOX_NULL; + conn->sem = SYS_SEM_NULL; + conn->state = NETCONN_NONE; + return conn; +} +/*-----------------------------------------------------------------------------------*/ +err_t +netconn_delete(struct netconn *conn) +{ + struct api_msg *msg; + void *mem; + + if(conn == NULL) { + return ERR_OK; + } + + if((msg = memp_mallocp(MEMP_API_MSG)) == NULL) { + return ERR_MEM; + } + + msg->type = API_MSG_DELCONN; + msg->msg.conn = conn; + api_msg_post(msg); + sys_mbox_fetch(conn->mbox, NULL); + memp_freep(MEMP_API_MSG, msg); + + /* Drain the recvmbox. */ + if(conn->recvmbox != SYS_MBOX_NULL) { + while(sys_arch_mbox_fetch(conn->recvmbox, &mem, 1) != 0) { + if(conn->type == NETCONN_TCP) { + pbuf_free((struct pbuf *)mem); + } else { + netbuf_delete((struct netbuf *)mem); + } + } + sys_mbox_free(conn->recvmbox); + conn->recvmbox = SYS_MBOX_NULL; + } + + + /* Drain the acceptmbox. */ + if(conn->acceptmbox != SYS_MBOX_NULL) { + while(sys_arch_mbox_fetch(conn->acceptmbox, &mem, 1) != 0) { + netconn_delete((struct netconn *)mem); + } + + sys_mbox_free(conn->acceptmbox); + conn->acceptmbox = SYS_MBOX_NULL; + } + + sys_mbox_free(conn->mbox); + conn->mbox = SYS_MBOX_NULL; + if(conn->sem != SYS_SEM_NULL) { + sys_sem_free(conn->sem); + } + /* conn->sem = SYS_SEM_NULL;*/ + memp_free(MEMP_NETCONN, conn); + return ERR_OK; +} +/*-----------------------------------------------------------------------------------*/ +enum netconn_type +netconn_type(struct netconn *conn) +{ + return conn->type; +} +/*-----------------------------------------------------------------------------------*/ +err_t +netconn_peer(struct netconn *conn, struct ip_addr **addr, + uInt16 *port) +{ + switch(conn->type) { + case NETCONN_UDPLITE: + case NETCONN_UDPNOCHKSUM: + case NETCONN_UDP: + *addr = &(conn->pcb.udp->remote_ip); + *port = conn->pcb.udp->remote_port; + break; + case NETCONN_TCP: + *addr = &(conn->pcb.tcp->remote_ip); + *port = conn->pcb.tcp->remote_port; + break; + } + return (conn->err = ERR_OK); +} +/*-----------------------------------------------------------------------------------*/ +err_t +netconn_addr(struct netconn *conn, struct ip_addr **addr, + uInt16 *port) +{ + switch(conn->type) { + case NETCONN_UDPLITE: + case NETCONN_UDPNOCHKSUM: + case NETCONN_UDP: + *addr = &(conn->pcb.udp->local_ip); + *port = conn->pcb.udp->local_port; + break; + case NETCONN_TCP: + *addr = &(conn->pcb.tcp->local_ip); + *port = conn->pcb.tcp->local_port; + break; + } + return (conn->err = ERR_OK); +} +/*-----------------------------------------------------------------------------------*/ +err_t +netconn_bind(struct netconn *conn, struct ip_addr *addr, + uInt16 port) +{ + struct api_msg *msg; + + if(conn == NULL) { + return ERR_VAL; + } + + if(conn->type != NETCONN_TCP && + conn->recvmbox == SYS_MBOX_NULL) { + if((conn->recvmbox = sys_mbox_new()) == SYS_MBOX_NULL) { + return ERR_MEM; + } + } + + if((msg = memp_mallocp(MEMP_API_MSG)) == NULL) { + return (conn->err = ERR_MEM); + } + msg->type = API_MSG_BIND; + msg->msg.conn = conn; + msg->msg.msg.bc.ipaddr = addr; + msg->msg.msg.bc.port = port; + api_msg_post(msg); + sys_mbox_fetch(conn->mbox, NULL); + memp_freep(MEMP_API_MSG, msg); + return conn->err; +} +/*-----------------------------------------------------------------------------------*/ +err_t +netconn_connect(struct netconn *conn, struct ip_addr *addr, + uInt16 port) +{ + struct api_msg *msg; + + if(conn == NULL) { + return ERR_VAL; + } + + + if(conn->recvmbox == SYS_MBOX_NULL) { + if((conn->recvmbox = sys_mbox_new()) == SYS_MBOX_NULL) { + return ERR_MEM; + } + } + + if((msg = memp_mallocp(MEMP_API_MSG)) == NULL) { + return ERR_MEM; + } + msg->type = API_MSG_CONNECT; + msg->msg.conn = conn; + msg->msg.msg.bc.ipaddr = addr; + msg->msg.msg.bc.port = port; + api_msg_post(msg); + sys_mbox_fetch(conn->mbox, NULL); + memp_freep(MEMP_API_MSG, msg); + return conn->err; +} +/*-----------------------------------------------------------------------------------*/ +err_t +netconn_listen(struct netconn *conn) +{ + struct api_msg *msg; + + if(conn == NULL) { + return ERR_VAL; + } + + if(conn->acceptmbox == SYS_MBOX_NULL) { + conn->acceptmbox = sys_mbox_new(); + if(conn->acceptmbox == SYS_MBOX_NULL) { + return ERR_MEM; + } + } + + if((msg = memp_mallocp(MEMP_API_MSG)) == NULL) { + return (conn->err = ERR_MEM); + } + msg->type = API_MSG_LISTEN; + msg->msg.conn = conn; + api_msg_post(msg); + sys_mbox_fetch(conn->mbox, NULL); + memp_freep(MEMP_API_MSG, msg); + return conn->err; +} +/*-----------------------------------------------------------------------------------*/ +struct netconn * +netconn_accept(struct netconn *conn) +{ + struct netconn *newconn; + + if(conn == NULL) { + return NULL; + } + + sys_mbox_fetch(conn->acceptmbox, (void **)&newconn); + + return newconn; +} +/*-----------------------------------------------------------------------------------*/ +struct netbuf * +netconn_recv(struct netconn *conn) +{ + struct api_msg *msg; + struct netbuf *buf; + struct pbuf *p; + + if(conn == NULL) { + return NULL; + } + + if(conn->recvmbox == SYS_MBOX_NULL) { + conn->err = ERR_CONN; + return NULL; + } + + if(conn->err != ERR_OK) { + return NULL; + } + + if(conn->type == NETCONN_TCP) { + if(conn->pcb.tcp->state == LISTEN) { + conn->err = ERR_CONN; + return NULL; + } + + + buf = memp_mallocp(MEMP_NETBUF); + + if(buf == NULL) { + conn->err = ERR_MEM; + return NULL; + } + + sys_mbox_fetch(conn->recvmbox, (void **)&p); + + /* If we are closed, we indicate that we no longer wish to recieve + data by setting conn->recvmbox to SYS_MBOX_NULL. */ + if(p == NULL) { + memp_freep(MEMP_NETBUF, buf); + sys_mbox_free(conn->recvmbox); + conn->recvmbox = SYS_MBOX_NULL; + return NULL; + } + + buf->p = p; + buf->ptr = p; + buf->fromport = 0; + buf->fromaddr = NULL; + + /* Let the stack know that we have taken the data. */ + if((msg = memp_mallocp(MEMP_API_MSG)) == NULL) { + conn->err = ERR_MEM; + return buf; + } + msg->type = API_MSG_RECV; + msg->msg.conn = conn; + if(buf != NULL) { + msg->msg.msg.len = buf->p->tot_len; + } else { + msg->msg.msg.len = 1; + } + api_msg_post(msg); + + sys_mbox_fetch(conn->mbox, NULL); + memp_freep(MEMP_API_MSG, msg); + } else { + sys_mbox_fetch(conn->recvmbox, (void **)&buf); + } + + + + + DEBUGF(API_LIB_DEBUG, ("netconn_recv: received %p (err %d)\n", buf, conn->err)); + + + return buf; +} +/*-----------------------------------------------------------------------------------*/ +err_t +netconn_send(struct netconn *conn, struct netbuf *buf) +{ + struct api_msg *msg; + + if(conn == NULL) { + return ERR_VAL; + } + + if(conn->err != ERR_OK) { + return conn->err; + } + + if((msg = memp_mallocp(MEMP_API_MSG)) == NULL) { + return (conn->err = ERR_MEM); + } + + DEBUGF(API_LIB_DEBUG, ("netconn_send: sending %d bytes\n", buf->p->tot_len)); + msg->type = API_MSG_SEND; + msg->msg.conn = conn; + msg->msg.msg.p = buf->p; + api_msg_post(msg); + + sys_mbox_fetch(conn->mbox, NULL); + memp_freep(MEMP_API_MSG, msg); + return conn->err; +} +/*-----------------------------------------------------------------------------------*/ +err_t +netconn_write(struct netconn *conn, void *dataptr, uInt16 size, uInt8 copy) +{ + struct api_msg *msg; + uInt16 len; + + if(conn == NULL) { + return ERR_VAL; + } + + if(conn->err != ERR_OK) { + return conn->err; + } + + if(conn->sem == SYS_SEM_NULL) { + conn->sem = sys_sem_new(0); + if(conn->sem == SYS_SEM_NULL) { + return ERR_MEM; + } + } + + if((msg = memp_mallocp(MEMP_API_MSG)) == NULL) { + return (conn->err = ERR_MEM); + } + msg->type = API_MSG_WRITE; + msg->msg.conn = conn; + + + conn->state = NETCONN_WRITE; + while(conn->err == ERR_OK && size > 0) { + msg->msg.msg.w.dataptr = dataptr; + msg->msg.msg.w.copy = copy; + + if(conn->type == NETCONN_TCP) { + if(tcp_sndbuf(conn->pcb.tcp) == 0) { + sys_sem_wait(conn->sem); + if(conn->err != ERR_OK) { + goto ret; + } + } + if(size > tcp_sndbuf(conn->pcb.tcp)) { + /* We cannot send more than one send buffer's worth of data at a + time. */ + len = tcp_sndbuf(conn->pcb.tcp); + } else { + len = size; + } + } else { + len = size; + } + + DEBUGF(API_LIB_DEBUG, ("netconn_write: writing %d bytes (%d)\n", len, copy)); + msg->msg.msg.w.len = len; + api_msg_post(msg); + sys_mbox_fetch(conn->mbox, NULL); + if(conn->err == ERR_OK) { + dataptr = (void *)((char *)dataptr + len); + size -= len; + } else if(conn->err == ERR_MEM) { + conn->err = ERR_OK; + sys_sem_wait(conn->sem); + } else { + goto ret; + } + } + ret: + memp_freep(MEMP_API_MSG, msg); + conn->state = NETCONN_NONE; + if(conn->sem != SYS_SEM_NULL) { + sys_sem_free(conn->sem); + conn->sem = SYS_SEM_NULL; + } + return conn->err; +} +/*-----------------------------------------------------------------------------------*/ +err_t +netconn_close(struct netconn *conn) +{ + struct api_msg *msg; + + if(conn == NULL) { + return ERR_VAL; + } + if((msg = memp_mallocp(MEMP_API_MSG)) == NULL) { + return (conn->err = ERR_MEM); + } + + conn->state = NETCONN_CLOSE; + again: + msg->type = API_MSG_CLOSE; + msg->msg.conn = conn; + api_msg_post(msg); + sys_mbox_fetch(conn->mbox, NULL); + if(conn->err == ERR_MEM && + conn->sem != SYS_SEM_NULL) { + sys_sem_wait(conn->sem); + goto again; + } + conn->state = NETCONN_NONE; + memp_freep(MEMP_API_MSG, msg); + return conn->err; +} +/*-----------------------------------------------------------------------------------*/ +err_t +netconn_err(struct netconn *conn) +{ + return conn->err; +} +/*-----------------------------------------------------------------------------------*/ + + + + diff --git a/src/sys/net/api/api_msg.c b/src/sys/net/api/api_msg.c new file mode 100644 index 0000000..a9965d4 --- /dev/null +++ b/src/sys/net/api/api_msg.c @@ -0,0 +1,529 @@ +/* + * Copyright (c) 2001, Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce 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 Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (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 file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + * $Id$ + */ + +#include + +#include "net/debug.h" +#include "net/arch.h" +#include "net/api_msg.h" +#include "net/memp.h" +#include "net/sys.h" +#include "net/tcpip.h" + +/*-----------------------------------------------------------------------------------*/ +static err_t +recv_tcp(void *arg, struct tcp_pcb *pcb, struct pbuf *p, err_t err) +{ + struct netconn *conn; + + conn = arg; + + if(conn == NULL) { + pbuf_free(p); + return ERR_VAL; + } + + if(conn->recvmbox != SYS_MBOX_NULL) { + conn->err = err; + sys_mbox_post(conn->recvmbox, p); + } + return ERR_OK; +} +/*-----------------------------------------------------------------------------------*/ +static void +recv_udp(void *arg, struct udp_pcb *pcb, struct pbuf *p, + struct ip_addr *addr, uInt16 port) +{ + struct netbuf *buf; + struct netconn *conn; + + conn = arg; + + if(conn == NULL) { + pbuf_free(p); + return; + } + + if(conn->recvmbox != SYS_MBOX_NULL) { + buf = memp_mallocp(MEMP_NETBUF); + if(buf == NULL) { + pbuf_free(p); + return; + } else { + buf->p = p; + buf->ptr = p; + buf->fromaddr = addr; + buf->fromport = port; + } + + sys_mbox_post(conn->recvmbox, buf); + } +} +/*-----------------------------------------------------------------------------------*/ +static err_t +poll_tcp(void *arg, struct tcp_pcb *pcb) +{ + struct netconn *conn; + + conn = arg; + if(conn != NULL && + (conn->state == NETCONN_WRITE || conn->state == NETCONN_CLOSE) && + conn->sem != SYS_SEM_NULL) { + sys_sem_signal(conn->sem); + } + return ERR_OK; +} +/*-----------------------------------------------------------------------------------*/ +static err_t +sent_tcp(void *arg, struct tcp_pcb *pcb, uInt16 len) +{ + struct netconn *conn; + + conn = arg; + if(conn != NULL && conn->sem != SYS_SEM_NULL) { + sys_sem_signal(conn->sem); + } + return ERR_OK; +} +/*-----------------------------------------------------------------------------------*/ +static void +err_tcp(void *arg, err_t err) +{ + struct netconn *conn; + + conn = arg; + + conn->pcb.tcp = NULL; + + + conn->err = err; + if(conn->recvmbox != SYS_MBOX_NULL) { + sys_mbox_post(conn->recvmbox, NULL); + } + if(conn->mbox != SYS_MBOX_NULL) { + sys_mbox_post(conn->mbox, NULL); + } + if(conn->acceptmbox != SYS_MBOX_NULL) { + sys_mbox_post(conn->acceptmbox, NULL); + } + if(conn->sem != SYS_SEM_NULL) { + sys_sem_signal(conn->sem); + } +} +/*-----------------------------------------------------------------------------------*/ +static void +setup_tcp(struct netconn *conn) +{ + struct tcp_pcb *pcb; + + pcb = conn->pcb.tcp; + tcp_arg(pcb, conn); + tcp_recv(pcb, recv_tcp); + tcp_sent(pcb, sent_tcp); + tcp_poll(pcb, poll_tcp, 4); + tcp_err(pcb, err_tcp); +} +/*-----------------------------------------------------------------------------------*/ +static err_t +accept_function(void *arg, struct tcp_pcb *newpcb, err_t err) +{ + sys_mbox_t *mbox; + struct netconn *newconn; + +#if API_MSG_DEBUG +#if TCP_DEBUG + tcp_debug_print_state(newpcb->state); +#endif /* TCP_DEBUG */ +#endif /* API_MSG_DEBUG */ + mbox = (sys_mbox_t *)arg; + newconn = memp_mallocp(MEMP_NETCONN); + if(newconn == NULL) { + return ERR_MEM; + } + newconn->type = NETCONN_TCP; + newconn->pcb.tcp = newpcb; + setup_tcp(newconn); + newconn->recvmbox = sys_mbox_new(); + if(newconn->recvmbox == SYS_MBOX_NULL) { + memp_free(MEMP_NETCONN, newconn); + return ERR_MEM; + } + newconn->mbox = sys_mbox_new(); + if(newconn->mbox == SYS_MBOX_NULL) { + sys_mbox_free(newconn->recvmbox); + memp_free(MEMP_NETCONN, newconn); + return ERR_MEM; + } + newconn->sem = sys_sem_new(0); + if(newconn->sem == SYS_SEM_NULL) { + sys_mbox_free(newconn->recvmbox); + sys_mbox_free(newconn->mbox); + memp_free(MEMP_NETCONN, newconn); + return ERR_MEM; + } + newconn->acceptmbox = SYS_MBOX_NULL; + newconn->err = err; + sys_mbox_post(*mbox, newconn); + return ERR_OK; +} +/*-----------------------------------------------------------------------------------*/ +static void +do_newconn(struct api_msg_msg *msg) +{ +} +/*-----------------------------------------------------------------------------------*/ +static void +do_delconn(struct api_msg_msg *msg) +{ + if(msg->conn->pcb.tcp != NULL) { + switch(msg->conn->type) { + case NETCONN_UDPLITE: + /* FALLTHROUGH */ + case NETCONN_UDPNOCHKSUM: + /* FALLTHROUGH */ + case NETCONN_UDP: + msg->conn->pcb.udp->recv_arg = NULL; + udp_remove(msg->conn->pcb.udp); + break; + case NETCONN_TCP: + tcp_arg(msg->conn->pcb.tcp, NULL); + tcp_sent(msg->conn->pcb.tcp, NULL); + tcp_recv(msg->conn->pcb.tcp, NULL); + tcp_accept(msg->conn->pcb.tcp, NULL); + tcp_poll(msg->conn->pcb.tcp, NULL, 0); + tcp_err(msg->conn->pcb.tcp, NULL); + if(msg->conn->pcb.tcp->state == LISTEN) { + tcp_close(msg->conn->pcb.tcp); + } else { + if(tcp_close(msg->conn->pcb.tcp) != ERR_OK) { + tcp_abort(msg->conn->pcb.tcp); + } + } + break; + } + } + if(msg->conn->mbox != SYS_MBOX_NULL) { + sys_mbox_post(msg->conn->mbox, NULL); + } +} +/*-----------------------------------------------------------------------------------*/ +static void +do_bind(struct api_msg_msg *msg) +{ + if(msg->conn->pcb.tcp == NULL) { + switch(msg->conn->type) { + case NETCONN_UDPLITE: + msg->conn->pcb.udp = udp_new(); + udp_setflags(msg->conn->pcb.udp, UDP_FLAGS_UDPLITE); + udp_recv(msg->conn->pcb.udp, recv_udp, msg->conn); + break; + case NETCONN_UDPNOCHKSUM: + msg->conn->pcb.udp = udp_new(); + udp_setflags(msg->conn->pcb.udp, UDP_FLAGS_NOCHKSUM); + udp_recv(msg->conn->pcb.udp, recv_udp, msg->conn); + break; + case NETCONN_UDP: + msg->conn->pcb.udp = udp_new(); + udp_recv(msg->conn->pcb.udp, recv_udp, msg->conn); + break; + case NETCONN_TCP: + msg->conn->pcb.tcp = tcp_new(); + setup_tcp(msg->conn); + break; + } + } + switch(msg->conn->type) { + case NETCONN_UDPLITE: + /* FALLTHROUGH */ + case NETCONN_UDPNOCHKSUM: + /* FALLTHROUGH */ + case NETCONN_UDP: + udp_bind(msg->conn->pcb.udp, msg->msg.bc.ipaddr, msg->msg.bc.port); + break; + case NETCONN_TCP: + msg->conn->err = tcp_bind(msg->conn->pcb.tcp, + msg->msg.bc.ipaddr, msg->msg.bc.port); + break; + } + sys_mbox_post(msg->conn->mbox, NULL); +} +/*-----------------------------------------------------------------------------------*/ +static err_t +do_connected(void *arg, struct tcp_pcb *pcb, err_t err) +{ + struct netconn *conn; + + conn = arg; + + if(conn == NULL) { + return ERR_VAL; + } + + conn->err = err; + + if(conn->type == NETCONN_TCP && err == ERR_OK) { + setup_tcp(conn); + } + + sys_mbox_post(conn->mbox, NULL); + return ERR_OK; +} +/*-----------------------------------------------------------------------------------*/ +static void +do_connect(struct api_msg_msg *msg) +{ + if(msg->conn->pcb.tcp == NULL) { + switch(msg->conn->type) { + case NETCONN_UDPLITE: + msg->conn->pcb.udp = udp_new(); + if(msg->conn->pcb.udp == NULL) { + msg->conn->err = ERR_MEM; + sys_mbox_post(msg->conn->mbox, NULL); + return; + } + udp_setflags(msg->conn->pcb.udp, UDP_FLAGS_UDPLITE); + udp_recv(msg->conn->pcb.udp, recv_udp, msg->conn); + break; + case NETCONN_UDPNOCHKSUM: + msg->conn->pcb.udp = udp_new(); + if(msg->conn->pcb.udp == NULL) { + msg->conn->err = ERR_MEM; + sys_mbox_post(msg->conn->mbox, NULL); + return; + } + udp_setflags(msg->conn->pcb.udp, UDP_FLAGS_NOCHKSUM); + udp_recv(msg->conn->pcb.udp, recv_udp, msg->conn); + break; + case NETCONN_UDP: + msg->conn->pcb.udp = udp_new(); + if(msg->conn->pcb.udp == NULL) { + msg->conn->err = ERR_MEM; + sys_mbox_post(msg->conn->mbox, NULL); + return; + } + udp_recv(msg->conn->pcb.udp, recv_udp, msg->conn); + break; + case NETCONN_TCP: + msg->conn->pcb.tcp = tcp_new(); + if(msg->conn->pcb.tcp == NULL) { + msg->conn->err = ERR_MEM; + sys_mbox_post(msg->conn->mbox, NULL); + return; + } + break; + } + } + switch(msg->conn->type) { + case NETCONN_UDPLITE: + /* FALLTHROUGH */ + case NETCONN_UDPNOCHKSUM: + /* FALLTHROUGH */ + case NETCONN_UDP: + udp_connect(msg->conn->pcb.udp, msg->msg.bc.ipaddr, msg->msg.bc.port); + sys_mbox_post(msg->conn->mbox, NULL); + break; + case NETCONN_TCP: + /* tcp_arg(msg->conn->pcb.tcp, msg->conn);*/ + setup_tcp(msg->conn); + tcp_connect(msg->conn->pcb.tcp, msg->msg.bc.ipaddr, msg->msg.bc.port, + do_connected); + /*tcp_output(msg->conn->pcb.tcp);*/ + break; + } +} +/*-----------------------------------------------------------------------------------*/ +static void +do_listen(struct api_msg_msg *msg) +{ + if(msg->conn->pcb.tcp != NULL) { + switch(msg->conn->type) { + case NETCONN_UDPLITE: + /* FALLTHROUGH */ + case NETCONN_UDPNOCHKSUM: + /* FALLTHROUGH */ + case NETCONN_UDP: + DEBUGF(API_MSG_DEBUG, ("api_msg: listen UDP: cannot listen for UDP.\n")); + break; + case NETCONN_TCP: + msg->conn->pcb.tcp = tcp_listen(msg->conn->pcb.tcp); + if(msg->conn->pcb.tcp == NULL) { + msg->conn->err = ERR_MEM; + } else { + if(msg->conn->acceptmbox == SYS_MBOX_NULL) { + msg->conn->acceptmbox = sys_mbox_new(); + if(msg->conn->acceptmbox == SYS_MBOX_NULL) { + msg->conn->err = ERR_MEM; + break; + } + } + tcp_arg(msg->conn->pcb.tcp, (void *)&(msg->conn->acceptmbox)); + tcp_accept(msg->conn->pcb.tcp, accept_function); + } + break; + } + } + sys_mbox_post(msg->conn->mbox, NULL); +} +/*-----------------------------------------------------------------------------------*/ +static void +do_accept(struct api_msg_msg *msg) +{ + if(msg->conn->pcb.tcp != NULL) { + switch(msg->conn->type) { + case NETCONN_UDPLITE: + /* FALLTHROUGH */ + case NETCONN_UDPNOCHKSUM: + /* FALLTHROUGH */ + case NETCONN_UDP: + DEBUGF(API_MSG_DEBUG, ("api_msg: accept UDP: cannot accept for UDP.\n")); + break; + case NETCONN_TCP: + break; + } + } +} +/*-----------------------------------------------------------------------------------*/ +static void +do_send(struct api_msg_msg *msg) +{ + if(msg->conn->pcb.tcp != NULL) { + switch(msg->conn->type) { + case NETCONN_UDPLITE: + /* FALLTHROUGH */ + case NETCONN_UDPNOCHKSUM: + /* FALLTHROUGH */ + case NETCONN_UDP: + udp_send(msg->conn->pcb.udp, msg->msg.p); + break; + case NETCONN_TCP: + break; + } + } + sys_mbox_post(msg->conn->mbox, NULL); +} +/*-----------------------------------------------------------------------------------*/ +static void +do_recv(struct api_msg_msg *msg) +{ + if(msg->conn->pcb.tcp != NULL) { + if(msg->conn->type == NETCONN_TCP) { + tcp_recved(msg->conn->pcb.tcp, msg->msg.len); + } + } + sys_mbox_post(msg->conn->mbox, NULL); +} +/*-----------------------------------------------------------------------------------*/ +static void +do_write(struct api_msg_msg *msg) +{ + err_t err; + if(msg->conn->pcb.tcp != NULL) { + switch(msg->conn->type) { + case NETCONN_UDPLITE: + /* FALLTHROUGH */ + case NETCONN_UDPNOCHKSUM: + /* FALLTHROUGH */ + case NETCONN_UDP: + msg->conn->err = ERR_VAL; + break; + case NETCONN_TCP: + err = tcp_write(msg->conn->pcb.tcp, msg->msg.w.dataptr, + msg->msg.w.len, msg->msg.w.copy); + /* This is the Nagle algorithm: inhibit the sending of new TCP + segments when new outgoing data arrives from the user if any + previously transmitted data on the connection remains + unacknowledged. */ + if(err == ERR_OK && msg->conn->pcb.tcp->unacked == NULL) { + tcp_output(msg->conn->pcb.tcp); + } + msg->conn->err = err; + break; + } + } + sys_mbox_post(msg->conn->mbox, NULL); +} +/*-----------------------------------------------------------------------------------*/ +static void +do_close(struct api_msg_msg *msg) +{ + err_t err; + if(msg->conn->pcb.tcp != NULL) { + switch(msg->conn->type) { + case NETCONN_UDPLITE: + /* FALLTHROUGH */ + case NETCONN_UDPNOCHKSUM: + /* FALLTHROUGH */ + case NETCONN_UDP: + break; + case NETCONN_TCP: + if(msg->conn->pcb.tcp->state == LISTEN) { + err = tcp_close(msg->conn->pcb.tcp); + } else { + err = tcp_close(msg->conn->pcb.tcp); + } + msg->conn->err = err; + break; + } + } + sys_mbox_post(msg->conn->mbox, NULL); +} +/*-----------------------------------------------------------------------------------*/ +typedef void (* api_msg_decode)(struct api_msg_msg *msg); +static api_msg_decode decode[API_MSG_MAX] = { + do_newconn, + do_delconn, + do_bind, + do_connect, + do_listen, + do_accept, + do_send, + do_recv, + do_write, + do_close + }; +void +api_msg_input(struct api_msg *msg) +{ + decode[msg->type](&(msg->msg)); +} +/*-----------------------------------------------------------------------------------*/ +void +api_msg_post(struct api_msg *msg) +{ + tcpip_apimsg(msg); +} +/*-----------------------------------------------------------------------------------*/ + + diff --git a/src/sys/net/api/err.c b/src/sys/net/api/err.c new file mode 100644 index 0000000..43ecf39 --- /dev/null +++ b/src/sys/net/api/err.c @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2001, Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce 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 Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (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 file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + * $Id$ + */ + +#include "net/err.h" + +#ifdef LWIP_DEBUG + +static char *err_strerr[] = {"Ok.", + "Out of memory error.", + "Buffer error.", + "Connection aborted.", + "Connection reset.", + "Connection closed.", + "Not connected.", + "Illegal value.", + "Illegal argument.", + "Routing problem.", + "Address in use." +}; + +/*-----------------------------------------------------------------------------------*/ +char * +lwip_strerr(err_t err) +{ + return err_strerr[-err]; + +} +/*-----------------------------------------------------------------------------------*/ + +#endif /* LWIP_DEBUG */ diff --git a/src/sys/net/api/sockets.c b/src/sys/net/api/sockets.c new file mode 100644 index 0000000..4656ba6 --- /dev/null +++ b/src/sys/net/api/sockets.c @@ -0,0 +1,446 @@ +/* + * Copyright (c) 2001, Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce 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 Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (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 file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + * $Id$ + */ + +#include + +#include "net/debug.h" +#include "net/api.h" + +#include "net/sockets.h" + +#define NUM_SOCKETS 10 + +struct lwip_socket { + struct netconn *conn; + struct netbuf *lastdata; + uInt16 lastoffset; +}; + +static struct lwip_socket sockets[NUM_SOCKETS]; + +/*-----------------------------------------------------------------------------------*/ +static struct lwip_socket * +get_socket(int s) +{ + struct lwip_socket *sock; + + if(s > NUM_SOCKETS) { + /* errno = EBADF; */ + return NULL; + } + + sock = &sockets[s]; + + if(sock->conn == NULL) { + /* errno = EBADF; */ + return NULL; + } + return sock; +} +/*-----------------------------------------------------------------------------------*/ +static int +alloc_socket(struct netconn *newconn) +{ + int i; + + /* allocate a new socket identifier */ + for(i = 0; i < NUM_SOCKETS; ++i) { + if(sockets[i].conn == NULL) { + sockets[i].conn = newconn; + sockets[i].lastdata = NULL; + sockets[i].lastoffset = 0; + return i; + } + } + return -1; +} +/*-----------------------------------------------------------------------------------*/ +int +lwip_accept(int s, struct sockaddr *addr, int *addrlen) +{ + struct lwip_socket *sock; + struct netconn *newconn; + struct ip_addr *naddr; + uInt16 port; + int newsock; + + sock = get_socket(s); + if(sock == NULL) { + return -1; + } + + newconn = netconn_accept(sock->conn); + + /* get the IP address and port of the remote host */ + netconn_peer(newconn, &naddr, &port); + + ((struct sockaddr_in *)addr)->sin_addr.s_addr = naddr->addr; + ((struct sockaddr_in *)addr)->sin_port = port; + + newsock = alloc_socket(newconn); + if(newsock == -1) { + netconn_delete(newconn); + /* errno = ENOBUFS; */ + } + return newsock; +} +/*-----------------------------------------------------------------------------------*/ +int +lwip_bind(int s, struct sockaddr *name, int namelen) +{ + struct lwip_socket *sock; + struct ip_addr remote_addr; + uInt16 remote_port; + err_t err; + + sock = get_socket(s); + if(sock == NULL) { + return -1; + } + + remote_addr.addr = ((struct sockaddr_in *)name)->sin_addr.s_addr; + remote_port = ((struct sockaddr_in *)name)->sin_port; + + err = netconn_bind(sock->conn, &remote_addr, ntohs(remote_port)); + + if(err != ERR_OK) { + /* errno = ... */ + return -1; + } + + return 0; +} +/*-----------------------------------------------------------------------------------*/ +int +lwip_close(int s) +{ + struct lwip_socket *sock; + + DEBUGF(SOCKETS_DEBUG, ("close: socket %d\n", s)); + sock = get_socket(s); + if(sock == NULL) { + return -1; + } + + + netconn_delete(sock->conn); + if(sock->lastdata != NULL) { + netbuf_delete(sock->lastdata); + } + sock->lastdata = NULL; + sock->lastoffset = 0; + sock->conn = NULL; + return 0; +} +/*-----------------------------------------------------------------------------------*/ +int +lwip_connect(int s, struct sockaddr *name, int namelen) +{ + struct lwip_socket *sock; + struct ip_addr remote_addr; + uInt16 remote_port; + err_t err; + + sock = get_socket(s); + if(sock == NULL) { + return -1; + } + + remote_addr.addr = ((struct sockaddr_in *)name)->sin_addr.s_addr; + remote_port = ((struct sockaddr_in *)name)->sin_port; + + err = netconn_connect(sock->conn, &remote_addr, ntohs(remote_port)); + + if(err != ERR_OK) { + /* errno = ... */ + return -1; + } + + return 0; +} +/*-----------------------------------------------------------------------------------*/ +int +lwip_listen(int s, int backlog) +{ + struct lwip_socket *sock; + err_t err; + + sock = get_socket(s); + if(sock == NULL) { + return -1; + } + + err = netconn_listen(sock->conn); + + if(err != ERR_OK) { + /* errno = ... */ + return -1; + } + + return 0; +} +/*-----------------------------------------------------------------------------------*/ +int +lwip_recvfrom(int s, void *mem, int len, unsigned int flags, + struct sockaddr *from, int *fromlen) +{ + struct lwip_socket *sock; + struct netbuf *buf; + uInt16 buflen, copylen; + struct ip_addr *addr; + uInt16 port; + + + sock = get_socket(s); + if(sock == NULL) { + return -1; + } + + /* Check if there is data left from the last recv operation. */ + if(sock->lastdata != NULL) { + buf = sock->lastdata; + } else { + /* No data was left from the previous operation, so we try to get + some from the network. */ + buf = netconn_recv(sock->conn); + + if(buf == NULL) { + /* We should really do some error checking here. */ + return 0; + } + } + + buflen = netbuf_len(buf); + + buflen -= sock->lastoffset; + + if(len > buflen) { + copylen = buflen; + } else { + copylen = len; + } + + /* copy the contents of the received buffer into + the supplied memory pointer mem */ + netbuf_copy_partial(buf, mem, copylen, sock->lastoffset); + + /* If this is a TCP socket, check if there is data left in the + buffer. If so, it should be saved in the sock structure for next + time around. */ + if(netconn_type(sock->conn) == NETCONN_TCP && buflen - copylen > 0) { + sock->lastdata = buf; + sock->lastoffset = buflen - copylen; + } else { + sock->lastdata = NULL; + sock->lastoffset = 0; + netbuf_delete(buf); + } + + /* Check to see from where the data was. */ + if(from != NULL && fromlen != NULL) { + addr = netbuf_fromaddr(buf); + port = htons(netbuf_fromport(buf)); + ((struct sockaddr_in *)from)->sin_addr.s_addr = addr->addr; + ((struct sockaddr_in *)from)->sin_port = port; + *fromlen = sizeof(struct sockaddr_in); + } + + + /* if the length of the received data is larger than + len, this data is discarded and we return len. + otherwise we return the actual length of the received + data */ + if(len > copylen) { + return copylen; + } else { + return len; + } +} +/*-----------------------------------------------------------------------------------*/ +int +lwip_read(int s, void *mem, int len) +{ + return lwip_recv(s, mem, len, 0); +} +/*-----------------------------------------------------------------------------------*/ +int +lwip_recv(int s, void *mem, int len, unsigned int flags) +{ + return lwip_recvfrom(s, mem, len, flags, NULL, NULL); +} +/*-----------------------------------------------------------------------------------*/ +int +lwip_send(int s, void *data, int size, unsigned int flags) +{ + struct lwip_socket *sock; + struct netbuf *buf; + err_t err; + + DEBUGF(SOCKETS_DEBUG, ("send: socket %d, size %d\n", s, size)); + + sock = get_socket(s); + if(sock == NULL) { + return -1; + } + + switch(netconn_type(sock->conn)) { + case NETCONN_UDP: + /* create a buffer */ + buf = netbuf_new(); + + if(buf == NULL) { + /* errno = ENOBUFS; */ + return -1; + } + + /* make the buffer point to the data that should + be sent */ + netbuf_ref(buf, data, size); + + /* send the data */ + err = netconn_send(sock->conn, buf); + + /* deallocated the buffer */ + netbuf_delete(buf); + break; + case NETCONN_TCP: + err = netconn_write(sock->conn, data, size, NETCONN_COPY); + break; + default: + err = ERR_ARG; + break; + } + if(err != ERR_OK) { + /* errno = ... */ + return -1; + } + + return size; +} +/*-----------------------------------------------------------------------------------*/ +int +lwip_sendto(int s, void *data, int size, unsigned int flags, + struct sockaddr *to, int tolen) +{ + struct lwip_socket *sock; + struct ip_addr remote_addr, *addr; + uInt16 remote_port, port; + int ret; + + sock = get_socket(s); + if(sock == NULL) { + return -1; + } + + /* get the peer if currently connected */ + netconn_peer(sock->conn, &addr, &port); + + remote_addr.addr = ((struct sockaddr_in *)to)->sin_addr.s_addr; + remote_port = ((struct sockaddr_in *)to)->sin_port; + netconn_connect(sock->conn, &remote_addr, remote_port); + + ret = lwip_send(s, data, size, flags); + + /* reset the remote address and port number + of the connection */ + netconn_connect(sock->conn, addr, port); + return ret; +} +/*-----------------------------------------------------------------------------------*/ +int +lwip_socket(int domain, int type, int protocol) +{ + struct netconn *conn; + int i; + + /* create a netconn */ + switch(type) { + case SOCK_DGRAM: + conn = netconn_new(NETCONN_UDP); + break; + case SOCK_STREAM: + conn = netconn_new(NETCONN_TCP); + break; + default: + /* errno = ... */ + return -1; + } + + if(conn == NULL) { + DEBUGF(SOCKETS_DEBUG, ("socket: could not create netconn.\n")); + /* errno = ENOBUFS; */ + return -1; + } + + i = alloc_socket(conn); + + if(i == -1) { + /* errno = ENOBUFS; */ + netconn_delete(conn); + } + return i; +} +/*-----------------------------------------------------------------------------------*/ +int +lwip_write(int s, void *data, int size) +{ + struct lwip_socket *sock; + err_t err; + + DEBUGF(SOCKETS_DEBUG, ("write: socket %d, size %d\n", s, size)); + + sock = get_socket(s); + if(sock == NULL) { + return -1; + } + + switch(netconn_type(sock->conn)) { + case NETCONN_UDP: + return lwip_send(s, data, size, 0); + + case NETCONN_TCP: + err = netconn_write(sock->conn, data, size, NETCONN_COPY); + break; + default: + err = ERR_ARG; + break; + } + if(err != ERR_OK) { + /* errno = ... */ + return -1; + } + return size; +} +/*-----------------------------------------------------------------------------------*/ diff --git a/src/sys/net/api/tcpip.c b/src/sys/net/api/tcpip.c new file mode 100644 index 0000000..62ab8c6 --- /dev/null +++ b/src/sys/net/api/tcpip.c @@ -0,0 +1,145 @@ +/* + * Copyright (c) 2001, Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce 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 Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (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 file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + * $Id$ + */ + +#include +#include + +#include "net/debug.h" + +#include "net/opt.h" + +#include "net/sys.h" + +#include "net/memp.h" +#include "net/pbuf.h" + +#include "net/ipv4/ip.h" +#include "net/udp.h" +#include "net/tcp.h" + +#include "net/tcpip.h" + +static void (* tcpip_init_done)(void *arg) = NULL; +static void *tcpip_init_done_arg; +static sys_mbox_t mbox; + +/*-----------------------------------------------------------------------------------*/ +static void +tcpip_tcp_timer(void *arg) +{ + tcp_tmr(); + sys_timeout(TCP_TMR_INTERVAL, (sys_timeout_handler)tcpip_tcp_timer, NULL); +} +/*-----------------------------------------------------------------------------------*/ + +static void +tcpip_thread(void *arg) +{ + struct tcpip_msg *msg; + + ip_init(); + udp_init(); + tcp_init(); + + sys_timeout(TCP_TMR_INTERVAL, (sys_timeout_handler)tcpip_tcp_timer, NULL); + + if(tcpip_init_done != NULL) { + tcpip_init_done(tcpip_init_done_arg); + } + + while(1) { /* MAIN Loop */ + sys_mbox_fetch(mbox, (void *)&msg); + switch(msg->type) { + case TCPIP_MSG_API: + //kprintf("tcpip_thread: API message %p\n", msg); + api_msg_input(msg->msg.apimsg); + break; + case TCPIP_MSG_INPUT: + //kprintf("tcpip_thread: IP packet %p\n", msg); + ip_input(msg->msg.inp.p, msg->msg.inp.netif); + break; + default: + break; + } + memp_freep(MEMP_TCPIP_MSG, msg); + } +} +/*-----------------------------------------------------------------------------------*/ +err_t +tcpip_input(struct pbuf *p, struct netif *inp) +{ + struct tcpip_msg *msg; + + msg = memp_mallocp(MEMP_TCPIP_MSG); + if(msg == NULL) { + //kprintf("BAD MESSAGE!!!\n"); + pbuf_free(p); + return ERR_MEM; + } + //kprintf("GOOD MESSAGE\n"); + + msg->type = TCPIP_MSG_INPUT; + msg->msg.inp.p = p; + msg->msg.inp.netif = inp; + sys_mbox_post(mbox, msg); + return ERR_OK; +} +/*-----------------------------------------------------------------------------------*/ +void +tcpip_apimsg(struct api_msg *apimsg) +{ + struct tcpip_msg *msg; + msg = memp_mallocp(MEMP_TCPIP_MSG); + if(msg == NULL) { + memp_free(MEMP_TCPIP_MSG, apimsg); + return; + } + msg->type = TCPIP_MSG_API; + msg->msg.apimsg = apimsg; + sys_mbox_post(mbox, msg); +} +/*-----------------------------------------------------------------------------------*/ +void +tcpip_init(void (* initfunc)(void *), void *arg) +{ + tcpip_init_done = initfunc; + tcpip_init_done_arg = arg; + mbox = sys_mbox_new(); + sys_thread_new((void *)tcpip_thread, NULL); +} +/*-----------------------------------------------------------------------------------*/ + + + diff --git a/src/sys/net/net/Makefile b/src/sys/net/net/Makefile new file mode 100644 index 0000000..9147cf9 --- /dev/null +++ b/src/sys/net/net/Makefile @@ -0,0 +1,27 @@ +# (C) 2002 The UbixOS Project +# $Id$ + +# Include Global 'Source' Options +include ../../../Makefile.inc +include ../../Makefile.inc + +# Objects +OBJS = udpecho.o init.o sys_arch.o shell.o + +all: $(OBJS) + +# Compile Types +.cc.o: + $(CXX) ${CFLAGS} -fno-exceptions -DNOBOOL -Wall -fomit-frame-pointer -O -I../../include -c -o $@ $< +.cc.s: + $(CXX) ${CFLAGS} -fno-exceptions -DNOBOOL -Wall -fomit-frame-pointer -O -I../../include -S -o $@ $< +.c.o: + $(CC) ${CFLAGS} -Wall -fomit-frame-pointer -O -I../../include -c -o $@ $< +.c.s: + $(CC) ${CFLAGS} -Wall -fomit-frame-pointer -O -I../../include -S -o $@ $< +.S.o: + $(CC) ${CFLAGS} -Wall -fomit-frame-pointer -c -o $@ $< + +# Clean up the junk +clean: + $(REMOVE) $(OBJS) diff --git a/src/sys/net/net/init.c b/src/sys/net/net/init.c new file mode 100644 index 0000000..54503bf --- /dev/null +++ b/src/sys/net/net/init.c @@ -0,0 +1,76 @@ +#include +#include + +#include +#include +#include +#include + +#include +#include +#include + +#include +#include +#include + +void netMainThread(); +static void tcpip_init_done(void *arg); + +int netInit() { + sys_init(); + mem_init(); + memp_init(); + pbuf_init(); + + sys_thread_new((void *)(netMainThread), NULL); + + return(0); + } + + +void netMainThread() { + struct ip_addr ipaddr, netmask, gw; + sys_sem_t sem; + + netif_init(); + sem = sys_sem_new(0); + tcpip_init(tcpip_init_done, &sem); + sys_sem_wait(sem); + kprintf("WAIT2"); + sys_sem_free(sem); + kprintf("TCP/IP initialized.\n"); + + IP4_ADDR(&gw, 192,168,0,1); + IP4_ADDR(&ipaddr, 192,168,0,69); + IP4_ADDR(&netmask, 255,255,255,0); + netif_set_default(netif_add(&ipaddr, &netmask, &gw, ethernetif_init, tcpip_input)); + + IP4_ADDR(&gw, 127,0,0,1); + IP4_ADDR(&ipaddr, 127,0,0,1); + IP4_ADDR(&netmask, 255,0,0,0); + netif_add(&ipaddr, &netmask, &gw, loopif_init, tcpip_input); + + //udpecho_init(); + shell_init(); + + kprintf("Application Started\n"); + + + _current->state = DEAD; + while (1); + } + + +static void tcpip_init_done(void *arg) { + sys_sem_t *sem = 0x0; + sem = arg; + kprintf("SIGNAL [%x]",sem); + sys_sem_signal(*sem); + kprintf("DONE"); + } + +/*** + END + ***/ + diff --git a/src/sys/net/net/shell.c b/src/sys/net/net/shell.c new file mode 100644 index 0000000..e7aac55 --- /dev/null +++ b/src/sys/net/net/shell.c @@ -0,0 +1,1073 @@ +/* + * Copyright (c) 2001, Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce 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 Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (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 file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + * $Id$ + */ + +#include +#include + +#include "net/mem.h" +#include "net/debug.h" +#include "net/def.h" +#include "net/api.h" +#include "net/stats.h" + +struct command { + struct netconn *conn; + Int8 (* exec)(struct command *); + uInt8 nargs; + char *args[10]; +}; + +char *buffer = 0x0; + +//#include +//#include + +#define ESUCCESS 0 +#define ESYNTAX -1 +#define ETOOFEW -2 +#define ETOOMANY -3 +#define ECLOSED -4 + +#define NCONNS 10 +static struct netconn *conns[NCONNS]; + +static char help_msg[] = "Avaliable commands:\n\ +open [IP address] [TCP port]: opens a TCP connection to the specified address.\n\ +lstn [TCP port]: sets up a server on the specified port.\n\ +acpt [connection #]: waits for an incoming connection request.\n\ +send [connection #] [message]: sends a message on a TCP connection.\n\ +udpc [local UDP port] [IP address] [remote port]: opens a UDP \"connection\".\n\ +udpl [local UDP port] [IP address] [remote port]: opens a UDP-Lite \"connection\".\n\ +udpn [local UDP port] [IP address] [remote port]: opens a UDP \"connection\" without checksums.\n\ +udpb [local port] [remote port]: opens a UDP broadcast \"connection\".\n\ +usnd [connection #] [message]: sends a message on a UDP connection.\n\ +recv [connection #]: recieves data on a TCP or UDP connection.\n\ +clos [connection #]: closes a TCP or UDP connection.\n\ +stat: prints out lwIP statistics.\n\ +quit: quits.\n"; + +static char *stat_msgs[] = { + "Link level * transmitted ", + " retransmitted ", + " * received ", + " forwarded ", + " * dropped ", + " * checksum errors ", + " * length errors ", + " * memory errors ", + " routing errors ", + " protocol errors ", + " option errors ", + " * misc errors ", + " cache hits ", + "IP * transmitted ", + " retransmitted ", + " * received ", + " * forwarded ", + " * dropped ", + " * checksum errors ", + " * length errors ", + " * memory errors ", + " * routing errors ", + " * protocol errors ", + " * option errors ", + " * misc errors ", + " cache hits ", + "ICMP * transmitted ", + " retransmitted ", + " * received ", + " forwarded ", + " * dropped ", + " * checksum errors ", + " length errors ", + " * memory errors ", + " routing errors ", + " * protocol errors ", + " option errors ", + " * misc errors ", + " cache hits ", + "UDP * transmitted ", + " retransmitted ", + " * received ", + " forwarded ", + " * dropped ", + " * checksum errors ", + " * length errors ", + " * memory errors ", + " * routing errors ", + " * protocol errors ", + " option errors ", + " * misc errors ", + " cache hits ", + "TCP * transmitted ", + " * retransmitted ", + " * received ", + " forwarded ", + " * dropped ", + " * checksum errors ", + " * length errors ", + " * memory errors ", + " * routing errors ", + " * protocol errors ", + " * option errors ", + " * misc errors ", + " * cache hits ", + "Pbufs * avaiable ", + " * used ", + " * high water mark ", + " * errors ", + " reclaimed ", + " pbuf_alloc() locked ", + " pbuf_refresh() locked ", + "Memory * avaliable ", + " * used ", + " * high water mark ", + " * errors ", + " * reclaimed ", + "Memp PBUF * avaliable ", + " * used ", + " * high water mark ", + " * errors ", + " * reclaimed ", + "UDP PCB * avaliable ", + " * used ", + " * high water mark ", + " * errors ", + " * reclaimed ", + "TCP PCB * avaliable ", + " * used ", + " * high water mark ", + " * errors ", + " * reclaimed ", + "TCP LISTEN * avaliable ", + " * used ", + " * high water mark ", + " * errors ", + " * reclaimed ", + "TCP SEG * avaliable ", + " * used ", + " * high water mark ", + " * errors ", + " * reclaimed ", + "Netbufs * avaliable ", + " * used ", + " * high water mark ", + " * errors ", + " * reclaimed ", + "Netconns * avaliable ", + " * used ", + " * high water mark ", + " * errors ", + " * reclaimed ", + "API msgs * avaliable ", + " * used ", + " * high water mark ", + " * errors ", + " * reclaimed ", + "TCPIP msgs * avaliable ", + " * used ", + " * high water mark ", + " * errors ", + " * reclaimed ", + "Timeouts * avaliable ", + " * used ", + " * high water mark ", + " * errors ", + " * reclaimed ", + "Semaphores * used ", + " * high water mark ", + " * errors ", + "Mailboxes * used ", + " * high water mark ", + " * errors " +}; +/*-----------------------------------------------------------------------------------*/ +static void +sendstr(const char *str, struct netconn *conn) +{ + netconn_write(conn, (void *)str, kstrlen(str), NETCONN_NOCOPY); +} +/*-----------------------------------------------------------------------------------*/ +static Int8 +com_open(struct command *com) +{ + struct ip_addr ipaddr; + uInt16 port; + int i; + err_t err; + + if(inet_aton(com->args[0], &ipaddr) == -1) { + //sendstr(strerror(errno), com->conn); + return ESYNTAX; + } + ipaddr.addr = 0xC0A80001; + port = strtol(com->args[1], NULL, 10); + + /* Find the first unused connection in conns. */ + for(i = 0; i < NCONNS && conns[i] != NULL; i++); + + if(i == NCONNS) { + sendstr("No more connections avaliable, sorry.\n", com->conn); + return ESUCCESS; + } + + sendstr("Opening connection to ", com->conn); + netconn_write(com->conn, com->args[0], kstrlen(com->args[0]), NETCONN_COPY); + sendstr(":", com->conn); + netconn_write(com->conn, com->args[1], kstrlen(com->args[1]), NETCONN_COPY); + sendstr("\n", com->conn); + + conns[i] = netconn_new(NETCONN_TCP); + if(conns[i] == NULL) { + sendstr("Could not create connection identifier (out of memory).\n", com->conn); + return ESUCCESS; + } + err = netconn_connect(conns[i], &ipaddr, port); + if(err != ERR_OK) { + //fprintf(stderr, "error %s\n", lwip_strerr(err)); + sendstr("Could not connect to remote host: ", com->conn); +#ifdef LWIP_DEBUG + sendstr(lwip_strerr(err), com->conn); +#else + sendstr("(debugging must be turned on for error message to appear)", com->conn); +#endif /* LWIP_DEBUG */ + sendstr("\n", com->conn); + netconn_delete(conns[i]); + conns[i] = NULL; + return ESUCCESS; + } + + sendstr("Opened connection, connection identifier is ", com->conn); + sprintf(buffer, "%d\n", i); + netconn_write(com->conn, buffer, kstrlen(buffer), NETCONN_COPY); + + return ESUCCESS; +} +/*-----------------------------------------------------------------------------------*/ +static Int8 +com_lstn(struct command *com) +{ + uInt16 port; + int i; + err_t err; + + port = strtol(com->args[0], NULL, 10); + + /* Find the first unused connection in conns. */ + for(i = 0; i < NCONNS && conns[i] != NULL; i++); + + if(i == NCONNS) { + sendstr("No more connections avaliable, sorry.\n", com->conn); + return ESUCCESS; + } + + sendstr("Opening a listening connection on port ", com->conn); + netconn_write(com->conn, com->args[0], kstrlen(com->args[0]), NETCONN_COPY); + sendstr("\n", com->conn); + + conns[i] = netconn_new(NETCONN_TCP); + if(conns[i] == NULL) { + sendstr("Could not create connection identifier (out of memory).\n", com->conn); + return ESUCCESS; + } + + err = netconn_bind(conns[i], IP_ADDR_ANY, port); + if(err != ERR_OK) { + netconn_delete(conns[i]); + conns[i] = NULL; + sendstr("Could not bind: ", com->conn); +#ifdef LWIP_DEBUG + sendstr(lwip_strerr(err), com->conn); +#else + sendstr("(debugging must be turned on for error message to appear)", com->conn); +#endif /* LWIP_DEBUG */ + sendstr("\n", com->conn); + return ESUCCESS; + } + + err = netconn_listen(conns[i]); + if(err != ERR_OK) { + netconn_delete(conns[i]); + conns[i] = NULL; + sendstr("Could not listen: ", com->conn); +#ifdef LWIP_DEBUG + sendstr(lwip_strerr(err), com->conn); +#else + sendstr("(debugging must be turned on for error message to appear)", com->conn); +#endif /* LWIP_DEBUG */ + sendstr("\n", com->conn); + return ESUCCESS; + } + + sendstr("Opened connection, connection identifier is ", com->conn); + sprintf(buffer, "%d\n", i); + netconn_write(com->conn, buffer, kstrlen(buffer), NETCONN_COPY); + + return ESUCCESS; +} +/*-----------------------------------------------------------------------------------*/ +/*-----------------------------------------------------------------------------------*/ +static Int8 +com_clos(struct command *com) +{ + int i; + err_t err; + + i = strtol(com->args[0], NULL, 10); + + if(i > NCONNS) { + sendstr("Connection identifier too high.\n", com->conn); + return ESUCCESS; + } + if(conns[i] == NULL) { + sendstr("Connection identifier not in use.\n", com->conn); + return ESUCCESS; + } + + err = netconn_close(conns[i]); + if(err != ERR_OK) { + sendstr("Could not close connection: ", com->conn); +#ifdef LWIP_DEBUG + sendstr(lwip_strerr(err), com->conn); +#else + sendstr("(debugging must be turned on for error message to appear)", com->conn); +#endif /* LWIP_DEBUG */ + sendstr("\n", com->conn); + return ESUCCESS; + } + + sendstr("Connection closed.\n", com->conn); + netconn_delete(conns[i]); + conns[i] = NULL; + return ESUCCESS; +} +/*-----------------------------------------------------------------------------------*/ +static Int8 +com_acpt(struct command *com) +{ + int i, j; + + /* Find the first unused connection in conns. */ + for(j = 0; j < NCONNS && conns[j] != NULL; j++); + + if(j == NCONNS) { + sendstr("No more connections avaliable, sorry.\n", com->conn); + return ESUCCESS; + } + + i = strtol(com->args[0], NULL, 10); + + if(i > NCONNS) { + sendstr("Connection identifier too high.\n", com->conn); + return ESUCCESS; + } + if(conns[i] == NULL) { + sendstr("Connection identifier not in use.\n", com->conn); + return ESUCCESS; + } + + conns[j] = netconn_accept(conns[i]); + + if(conns[j] == NULL) { + sendstr("Could not accept connection: ", com->conn); +#ifdef LWIP_DEBUG + sendstr(lwip_strerr(netconn_err(conns[i])), com->conn); +#else + sendstr("(debugging must be turned on for error message to appear)", com->conn); +#endif /* LWIP_DEBUG */ + sendstr("\n", com->conn); + return ESUCCESS; + } + + sendstr("Accepted connection, connection identifier for new connection is ", com->conn); + sprintf(buffer, "%d\n", j); + netconn_write(com->conn, buffer, kstrlen(buffer), NETCONN_COPY); + + return ESUCCESS; +} +/*-----------------------------------------------------------------------------------*/ +static Int8 +com_stat(struct command *com) +{ + int i; + char buf[100]; + uInt16 len; + + for(i = 0; i < sizeof(struct stats_) / 2; i++) { + len = sprintf(buf, "%d", ((uInt16 *)&stats)[i]); + sendstr(stat_msgs[i], com->conn); + netconn_write(com->conn, buf, len, NETCONN_COPY); + sendstr("\n", com->conn); + } + + + return ESUCCESS; +} +/*-----------------------------------------------------------------------------------*/ +static Int8 +com_send(struct command *com) +{ + int i; + err_t err; + int len; + + i = strtol(com->args[0], NULL, 10); + + if(i > NCONNS) { + sendstr("Connection identifier too high.\n", com->conn); + return ESUCCESS; + } + + if(conns[i] == NULL) { + sendstr("Connection identifier not in use.\n", com->conn); + return ESUCCESS; + } + + len = kstrlen(com->args[1]); + com->args[1][len] = '\r'; + com->args[1][len + 1] = '\n'; + com->args[1][len + 2] = 0; + + err = netconn_write(conns[i], com->args[1], len + 3, NETCONN_COPY); + if(err != ERR_OK) { + sendstr("Could not send data: ", com->conn); +#ifdef LWIP_DEBUG + sendstr(lwip_strerr(err), com->conn); +#else + sendstr("(debugging must be turned on for error message to appear)", com->conn); +#endif /* LWIP_DEBUG */ + sendstr("\n", com->conn); + return ESUCCESS; + } + + sendstr("Data enqueued for sending.\n", com->conn); + return ESUCCESS; +} +/*-----------------------------------------------------------------------------------*/ +static Int8 +com_recv(struct command *com) +{ + int i; + err_t err; + struct netbuf *buf; + uInt16 len; + + i = strtol(com->args[0], NULL, 10); + + if(i > NCONNS) { + sendstr("Connection identifier too high.\n", com->conn); + return ESUCCESS; + } + + if(conns[i] == NULL) { + sendstr("Connection identifier not in use.\n", com->conn); + return ESUCCESS; + } + + buf = netconn_recv(conns[i]); + if(buf != NULL) { + + netbuf_copy(buf, buffer, 1024); + len = netbuf_len(buf); + sendstr("Reading from connection:\n", com->conn); + netconn_write(com->conn, buffer, len, NETCONN_COPY); + netbuf_delete(buf); + } else { + sendstr("EOF.\n", com->conn); + } + err = netconn_err(conns[i]); + if(err != ERR_OK) { + sendstr("Could not receive data: ", com->conn); +#ifdef LWIP_DEBUG + sendstr(lwip_strerr(err), com->conn); +#else + sendstr("(debugging must be turned on for error message to appear)", com->conn); +#endif /* LWIP_DEBUG */ + sendstr("\n", com->conn); + return ESUCCESS; + } + return ESUCCESS; +} +/*-----------------------------------------------------------------------------------*/ +static Int8 +com_udpc(struct command *com) +{ + struct ip_addr ipaddr; + uInt16 lport, rport; + int i; + err_t err; + + lport = strtol(com->args[0], NULL, 10); + if(inet_aton(com->args[1], &ipaddr) == -1) { + //sendstr(strerror(errno), com->conn); + return ESYNTAX; + } + ipaddr.addr = 0xC0A80001; + rport = strtol(com->args[2], NULL, 10); + + /* Find the first unused connection in conns. */ + for(i = 0; i < NCONNS && conns[i] != NULL; i++); + + if(i == NCONNS) { + sendstr("No more connections avaliable, sorry.\n", com->conn); + return ESUCCESS; + } + + sendstr("Setting up UDP connection from port ", com->conn); + netconn_write(com->conn, com->args[0], kstrlen(com->args[0]), NETCONN_COPY); + sendstr(" to ", com->conn); + netconn_write(com->conn, com->args[1], kstrlen(com->args[1]), NETCONN_COPY); + sendstr(":", com->conn); + netconn_write(com->conn, com->args[2], kstrlen(com->args[2]), NETCONN_COPY); + sendstr("\n", com->conn); + + conns[i] = netconn_new(NETCONN_UDP); + if(conns[i] == NULL) { + sendstr("Could not create connection identifier (out of memory).\n", com->conn); + return ESUCCESS; + } + + err = netconn_connect(conns[i], &ipaddr, rport); + if(err != ERR_OK) { + netconn_delete(conns[i]); + conns[i] = NULL; + sendstr("Could not connect to remote host: ", com->conn); +#ifdef LWIP_DEBUG + sendstr(lwip_strerr(err), com->conn); +#else + sendstr("(debugging must be turned on for error message to appear)", com->conn); +#endif /* LWIP_DEBUG */ + sendstr("\n", com->conn); + return ESUCCESS; + } + + err = netconn_bind(conns[i], IP_ADDR_ANY, lport); + if(err != ERR_OK) { + netconn_delete(conns[i]); + conns[i] = NULL; + sendstr("Could not bind: ", com->conn); +#ifdef LWIP_DEBUG + sendstr(lwip_strerr(err), com->conn); +#else + sendstr("(debugging must be turned on for error message to appear)", com->conn); +#endif /* LWIP_DEBUG */ + sendstr("\n", com->conn); + return ESUCCESS; + } + + sendstr("Connection set up, connection identifier is ", com->conn); + sprintf(buffer, "%d\n", i); + netconn_write(com->conn, buffer, kstrlen(buffer), NETCONN_COPY); + + return ESUCCESS; +} +/*-----------------------------------------------------------------------------------*/ +static Int8 +com_udpl(struct command *com) +{ + struct ip_addr ipaddr; + uInt16 lport, rport; + int i; + err_t err; + + lport = strtol(com->args[0], NULL, 10); + if(inet_aton(com->args[1], &ipaddr) == -1) { + //sendstr(strerror(errno), com->conn); + return ESYNTAX; + } + ipaddr.addr = 0xC0A80001; + rport = strtol(com->args[2], NULL, 10); + kprintf("RPORT: [%x]",rport); + + /* Find the first unused connection in conns. */ + for(i = 0; i < NCONNS && conns[i] != NULL; i++); + + if(i == NCONNS) { + sendstr("No more connections avaliable, sorry.\n", com->conn); + return ESUCCESS; + } + + sendstr("Setting up UDP-Lite connection from port ", com->conn); + netconn_write(com->conn, com->args[0], kstrlen(com->args[0]), NETCONN_COPY); + sendstr(" to ", com->conn); + netconn_write(com->conn, com->args[1], kstrlen(com->args[1]), NETCONN_COPY); + sendstr(":", com->conn); + netconn_write(com->conn, com->args[2], kstrlen(com->args[2]), NETCONN_COPY); + sendstr("\n", com->conn); + + conns[i] = netconn_new(NETCONN_UDPLITE); + if(conns[i] == NULL) { + sendstr("Could not create connection identifier (out of memory).\n", com->conn); + return ESUCCESS; + } + + err = netconn_connect(conns[i], &ipaddr, rport); + if(err != ERR_OK) { + netconn_delete(conns[i]); + conns[i] = NULL; + sendstr("Could not connect to remote host: ", com->conn); +#ifdef LWIP_DEBUG + sendstr(lwip_strerr(err), com->conn); +#else + sendstr("(debugging must be turned on for error message to appear)", com->conn); +#endif /* LWIP_DEBUG */ + sendstr("\n", com->conn); + return ESUCCESS; + } + + err = netconn_bind(conns[i], IP_ADDR_ANY, lport); + if(err != ERR_OK) { + netconn_delete(conns[i]); + conns[i] = NULL; + sendstr("Could not bind: ", com->conn); +#ifdef LWIP_DEBUG + sendstr(lwip_strerr(err), com->conn); +#else + sendstr("(debugging must be turned on for error message to appear)", com->conn); +#endif /* LWIP_DEBUG */ + sendstr("\n", com->conn); + return ESUCCESS; + } + + sendstr("Connection set up, connection identifier is ", com->conn); + sprintf(buffer, "%d\n", i); + netconn_write(com->conn, buffer, kstrlen(buffer), NETCONN_COPY); + + return ESUCCESS; +} +/*-----------------------------------------------------------------------------------*/ +static Int8 +com_udpn(struct command *com) +{ + struct ip_addr ipaddr; + uInt16 lport, rport; + int i; + err_t err; + + lport = strtol(com->args[0], NULL, 10); + if(inet_aton(com->args[1], &ipaddr) == -1) { + //sendstr(strerror(errno), com->conn); + return ESYNTAX; + } + ipaddr.addr = 0xC0A80001; + rport = strtol(com->args[2], NULL, 10); + + /* Find the first unused connection in conns. */ + for(i = 0; i < NCONNS && conns[i] != NULL; i++); + + if(i == NCONNS) { + sendstr("No more connections avaliable, sorry.\n", com->conn); + return ESUCCESS; + } + + sendstr("Setting up UDP connection without checksums from port ", com->conn); + netconn_write(com->conn, com->args[0], kstrlen(com->args[0]), NETCONN_COPY); + sendstr(" to ", com->conn); + netconn_write(com->conn, com->args[1], kstrlen(com->args[1]), NETCONN_COPY); + sendstr(":", com->conn); + netconn_write(com->conn, com->args[2], kstrlen(com->args[2]), NETCONN_COPY); + sendstr("\n", com->conn); + + conns[i] = netconn_new(NETCONN_UDPNOCHKSUM); + if(conns[i] == NULL) { + sendstr("Could not create connection identifier (out of memory).\n", com->conn); + return ESUCCESS; + } + + err = netconn_connect(conns[i], &ipaddr, rport); + if(err != ERR_OK) { + netconn_delete(conns[i]); + conns[i] = NULL; + sendstr("Could not connect to remote host: ", com->conn); +#ifdef LWIP_DEBUG + sendstr(lwip_strerr(err), com->conn); +#else + sendstr("(debugging must be turned on for error message to appear)", com->conn); +#endif /* LWIP_DEBUG */ + sendstr("\n", com->conn); + return ESUCCESS; + } + + err = netconn_bind(conns[i], IP_ADDR_ANY, lport); + if(err != ERR_OK) { + netconn_delete(conns[i]); + conns[i] = NULL; + sendstr("Could not bind: ", com->conn); +#ifdef LWIP_DEBUG + sendstr(lwip_strerr(err), com->conn); +#else + sendstr("(debugging must be turned on for error message to appear)", com->conn); +#endif /* LWIP_DEBUG */ + sendstr("\n", com->conn); + return ESUCCESS; + } + + sendstr("Connection set up, connection identifier is ", com->conn); + sprintf(buffer, "%d\n", i); + netconn_write(com->conn, buffer, kstrlen(buffer), NETCONN_COPY); + + return ESUCCESS; +} +/*-----------------------------------------------------------------------------------*/ +static Int8 +com_udpb(struct command *com) +{ + struct ip_addr ipaddr; + uInt16 lport, rport; + int i; + err_t err; + struct ip_addr bcaddr; + + lport = strtol(com->args[0], NULL, 10); + if(inet_aton(com->args[1], &ipaddr) == -1) { + //sendstr(strerror(errno), com->conn); + return ESYNTAX; + } + ipaddr.addr = 0xC0A80001; + rport = strtol(com->args[2], NULL, 10); + + /* Find the first unused connection in conns. */ + for(i = 0; i < NCONNS && conns[i] != NULL; i++); + + if(i == NCONNS) { + sendstr("No more connections avaliable, sorry.\n", com->conn); + return ESUCCESS; + } + + sendstr("Setting up UDP broadcast connection from port ", com->conn); + netconn_write(com->conn, com->args[0], kstrlen(com->args[0]), NETCONN_COPY); + sendstr(" to ", com->conn); + netconn_write(com->conn, com->args[1], kstrlen(com->args[1]), NETCONN_COPY); + sendstr("\n", com->conn); + + conns[i] = netconn_new(NETCONN_UDP); + if(conns[i] == NULL) { + sendstr("Could not create connection identifier (out of memory).\n", com->conn); + return ESUCCESS; + } + + err = netconn_connect(conns[i], &ipaddr, rport); + if(err != ERR_OK) { + netconn_delete(conns[i]); + conns[i] = NULL; + sendstr("Could not connect to remote host: ", com->conn); +#ifdef LWIP_DEBUG + sendstr(lwip_strerr(err), com->conn); +#else + sendstr("(debugging must be turned on for error message to appear)", com->conn); +#endif /* LWIP_DEBUG */ + sendstr("\n", com->conn); + return ESUCCESS; + } + + IP4_ADDR(&bcaddr, 255,255,255,255); + err = netconn_bind(conns[i], &bcaddr, lport); + if(err != ERR_OK) { + netconn_delete(conns[i]); + conns[i] = NULL; + sendstr("Could not bind: ", com->conn); +#ifdef LWIP_DEBUG + sendstr(lwip_strerr(err), com->conn); +#else + sendstr("(debugging must be turned on for error message to appear)", com->conn); +#endif /* LWIP_DEBUG */ + sendstr("\n", com->conn); + return ESUCCESS; + } + + sendstr("Connection set up, connection identifier is ", com->conn); + sprintf(buffer, "%d\n", i); + netconn_write(com->conn, buffer, kstrlen(buffer), NETCONN_COPY); + + return ESUCCESS; +} +/*-----------------------------------------------------------------------------------*/ +static Int8 +com_usnd(struct command *com) +{ + int i; + err_t err; + struct netbuf *buf; + char *mem; + + i = strtol(com->args[0], NULL, 10); + + if(i > NCONNS) { + sendstr("Connection identifier too high.\n", com->conn); + return ESUCCESS; + } + + if(conns[i] == NULL) { + sendstr("Connection identifier not in use.\n", com->conn); + return ESUCCESS; + } + + buf = netbuf_new(); + mem = netbuf_alloc(buf, kstrlen(com->args[1]) + 1); + if(mem == NULL) { + sendstr("Could not allocate memory for sending.\n", com->conn); + return ESUCCESS; + } + kstrncpy(mem, com->args[1], kstrlen(com->args[1]) + 1); + err = netconn_send(conns[i], buf); + netbuf_delete(buf); + if(err != ERR_OK) { + sendstr("Could not send data: ", com->conn); +#ifdef LWIP_DEBUG + sendstr(lwip_strerr(err), com->conn); +#else + sendstr("(debugging must be turned on for error message to appear)", com->conn); +#endif /* LWIP_DEBUG */ + sendstr("\n", com->conn); + return ESUCCESS; + } + + sendstr("Data sent.\n", com->conn); + return ESUCCESS; +} +/*-----------------------------------------------------------------------------------*/ +static Int8 +com_help(struct command *com) +{ + sendstr(help_msg, com->conn); + return ESUCCESS; +} +/*-----------------------------------------------------------------------------------*/ +static Int8 +parse_command(struct command *com, uInt32 len) +{ + uInt16 i; + uInt16 bufp; + + if(kstrncmp(buffer, "open", 4) == 0) { + com->exec = com_open; + com->nargs = 2; + } else if(kstrncmp(buffer, "lstn", 4) == 0) { + com->exec = com_lstn; + com->nargs = 1; + } else if(kstrncmp(buffer, "acpt", 4) == 0) { + com->exec = com_acpt; + com->nargs = 1; + } else if(kstrncmp(buffer, "clos", 4) == 0) { + com->exec = com_clos; + com->nargs = 1; + } else if(kstrncmp(buffer, "stat", 4) == 0) { + com->exec = com_stat; + com->nargs = 0; + } else if(kstrncmp(buffer, "send", 4) == 0) { + com->exec = com_send; + com->nargs = 2; + } else if(kstrncmp(buffer, "recv", 4) == 0) { + com->exec = com_recv; + com->nargs = 1; + } else if(kstrncmp(buffer, "udpc", 4) == 0) { + com->exec = com_udpc; + com->nargs = 3; + } else if(kstrncmp(buffer, "udpb", 4) == 0) { + com->exec = com_udpb; + com->nargs = 2; + } else if(kstrncmp(buffer, "udpl", 4) == 0) { + com->exec = com_udpl; + com->nargs = 3; + } else if(kstrncmp(buffer, "udpn", 4) == 0) { + com->exec = com_udpn; + com->nargs = 3; + } else if(kstrncmp(buffer, "usnd", 4) == 0) { + com->exec = com_usnd; + com->nargs = 2; + } else if(kstrncmp(buffer, "help", 4) == 0) { + com->exec = com_help; + com->nargs = 0; + } else if(kstrncmp(buffer, "quit", 4) == 0) { + kprintf("quit\n"); + return ECLOSED; + } else { + return ESYNTAX; + } + + if(com->nargs == 0) { + return ESUCCESS; + } + bufp = 0; + for(; bufp < len && buffer[bufp] != ' '; bufp++); + for(i = 0; i < 10; i++) { + for(; bufp < len && buffer[bufp] == ' '; bufp++); + if(buffer[bufp] == '\r' || + buffer[bufp] == '\n') { + buffer[bufp] = 0; + if(i < com->nargs - 1) { + return ETOOFEW; + } + if(i > com->nargs - 1) { + return ETOOMANY; + } + break; + } + if(bufp > len) { + return ETOOFEW; + } + com->args[i] = &buffer[bufp]; + for(; bufp < len && buffer[bufp] != ' ' && buffer[bufp] != '\r' && + buffer[bufp] != '\n'; bufp++) { + if(buffer[bufp] == '\\') { + buffer[bufp] = ' '; + } + } + if(bufp > len) { + return ESYNTAX; + } + buffer[bufp] = 0; + bufp++; + if(i == com->nargs - 1) { + break; + } + + } + + return ESUCCESS; +} +/*-----------------------------------------------------------------------------------*/ +static void +error(Int8 err, struct netconn *conn) +{ + switch(err) { + case ESYNTAX: + sendstr("## Syntax error\n", conn); + break; + case ETOOFEW: + sendstr("## Too few arguments to command given\n", conn); + break; + case ETOOMANY: + sendstr("## Too many arguments to command given\n", conn); + break; + } +} +/*-----------------------------------------------------------------------------------*/ +static void +prompt(struct netconn *conn) +{ + sendstr("> ", conn); +} +/*-----------------------------------------------------------------------------------*/ +static void +shell_main(struct netconn *conn) +{ + struct netbuf *buf; + uInt32 len; + struct command com; + Int8 err; + int i; + + do { + buf = netconn_recv(conn); + if(buf != NULL) { + netbuf_copy(buf, buffer, 1024); + len = netbuf_len(buf); + netbuf_delete(buf); + if(len >= 4) { + if(buffer[0] != 0xff && + buffer[1] != 0xfe) { + err = parse_command(&com, len); + if(err == ESUCCESS) { + com.conn = conn; + err = com.exec(&com); + } + if(err != ESUCCESS) { + error(err, conn); + } + if(err == ECLOSED) { + kprintf("Closed\n"); + error(err, conn); + goto close; + } + } else { + sendstr("\n\n" + "lwIP simple interactive shell.\n" + "(c) Copyright 2001, Swedish Institute of Computer Science.\n" + "Written by Adam Dunkels.\n" + "For help, try the \"help\" command.\n", conn); + } + } + } + if(buf != NULL) { + prompt(conn); + } + } while(buf != NULL); + kprintf("buf == NULL err %s\n", lwip_strerr(conn->err)); + close: + netconn_close(conn); + + for(i = 0; i < NCONNS; i++) { + if(conns[i] != NULL) { + netconn_delete(conns[i]); + } + conns[i] = NULL; + } + +} +/*-----------------------------------------------------------------------------------*/ +static void +shell_thread(void *arg) +{ + struct netconn *conn, *newconn; + + char *str = (char *)kmalloc(64,sysID); + + buffer = (char *)kmalloc(1024,sysID); + + str[0] = 'a'; + str[1] = 'b'; + str[2] = 'c'; + + conn = netconn_new(NETCONN_TCP); + netconn_bind(conn, NULL, 23); + netconn_listen(conn); + + while(1) { + newconn = netconn_accept(conn); + shell_main(newconn); + netconn_delete(newconn); + } +} +/*-----------------------------------------------------------------------------------*/ +void +shell_init(void) +{ + sys_thread_new(shell_thread, NULL); +} + + + + diff --git a/src/sys/net/net/shell.h b/src/sys/net/net/shell.h new file mode 100644 index 0000000..3f2ab99 --- /dev/null +++ b/src/sys/net/net/shell.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2001, Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce 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 Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (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 file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + * $Id$ + */ +#ifndef __SHELL_H__ +#define __SHELL_H__ + +void shell_init(void); + +#endif /* __SHELL_H__ */ diff --git a/src/sys/net/net/sys_arch.c b/src/sys/net/net/sys_arch.c new file mode 100644 index 0000000..82abc40 --- /dev/null +++ b/src/sys/net/net/sys_arch.c @@ -0,0 +1,373 @@ +/* + * Copyright (c) 2001, Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce 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 Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (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 file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * Sub Author: Christopher Olsen + * + * Notes: + * Modified to work with the ubix operating system + * + * $Log$ + * Revision 1.13 2004/04/13 21:29:53 reddawg + * We now have sockets working. Lots of functionality to be added to continually + * improve on the existing layers now its clean up time to get things in a better + * working order. + * + * Revision 1.12 2004/04/13 16:08:07 reddawg + * Removed all of the old debug code the problem seems to be in ubthreads with + * ubthread_mutex_init + * + * Revision 1.11 2004/04/13 16:05:40 reddawg + * Function Renaming + * + * + * + * $Id$ + */ + +#include +#include +#include +#include +#include +#include + +#include "net/debug.h" +#include "net/sys.h" +#include "net/opt.h" +#include "net/stats.h" + +#define UMAX(a, b) ((a) > (b) ? (a) : (b)) + +static struct sys_thread *threads = NULL; + +struct sys_mbox_msg { + struct sys_mbox_msg *next; + void *msg; +}; + +#define SYS_MBOX_SIZE 100 + +struct sys_mbox { + uInt16 first, last; + void *msgs[SYS_MBOX_SIZE]; + struct sys_sem *mail; + struct sys_sem *mutex; +}; + +struct sys_sem { + unsigned int c; + ubthread_cond_t cond; + ubthread_mutex_t mutex; +}; + +struct sys_thread { + struct sys_thread *next; + struct sys_timeouts timeouts; + kTask_t *ubthread; +}; + + +static struct timeval starttime; + +static struct sys_sem *sys_sem_new_(uInt8 count); +static void sys_sem_free_(struct sys_sem *sem); + +static uInt16 cond_wait(ubthread_cond_t *cond, ubthread_mutex_t *mutex, uInt16 timeout); + +static struct sys_thread *current_thread(void) { + struct sys_thread *st; + kTask_t *pt; + pt = ubthread_self(); + for(st = threads; st != NULL; st = st->next) { + if(st->ubthread == pt) { + return st; + } + } + kprintf("sys: current_thread: could not find current thread!\n"); + kprintf("This is due to a race condition in the LinuxThreads\n"); + kprintf("ubthreads implementation. Start the program again.\n"); + + kpanic("ABORT"); + return(0x0); + } + + +struct thread_start_param { + struct sys_thread *thread; + void (* function)(void *); + void *arg; + }; + +/* +static void *thread_start(void *arg) { + struct thread_start_param *tp = arg; + tp->thread->ubthread = ubthread_self(); + tp->function(tp->arg); + kfree(tp); + return(NULL); + } +*/ + +void sys_thread_new(void (* function)(void *arg), void *arg) { + struct sys_thread *thread; + struct thread_start_param *thread_param; + + thread = kmalloc(sizeof(struct sys_thread),sysID); + thread->next = threads; + thread->timeouts.next = NULL; + thread->ubthread = 0; + threads = thread; + + thread_param = kmalloc(sizeof(struct thread_start_param),sysID); + + thread_param->function = function; + thread_param->arg = arg; + thread_param->thread = thread; + + if(ubthread_create(&(thread->ubthread), NULL, function, arg) != 0) { + kpanic("sys_thread_new: ubthread_create"); + } + } + +struct sys_mbox *sys_mbox_new() { + struct sys_mbox *mbox; + + mbox = kmalloc(sizeof(struct sys_mbox),sysID); + mbox->first = mbox->last = 0; + mbox->mail = sys_sem_new_(0); + mbox->mutex = sys_sem_new_(1); + + return(mbox); + } + +void sys_mbox_free(struct sys_mbox *mbox) { + if (mbox != SYS_MBOX_NULL) { + sys_sem_wait(mbox->mutex); + + sys_sem_free_(mbox->mail); + sys_sem_free_(mbox->mutex); + mbox->mail = mbox->mutex = NULL; + //kprintf("sys_mbox_free: mbox 0x%lx\n", mbox); + kfree(mbox); + } + } + +void sys_mbox_post(struct sys_mbox *mbox, void *msg) { + uInt8 first; + + sys_sem_wait(mbox->mutex); + + //kprintf("sys_mbox_post: mbox %p msg %p\n", mbox, msg); + + mbox->msgs[mbox->last] = msg; + + if (mbox->last == mbox->first) { + first = 1; + } + else { + first = 0; + } + + mbox->last++; + if(mbox->last == SYS_MBOX_SIZE) { + mbox->last = 0; + } + + if(first) { + sys_sem_signal(mbox->mail); + } + sys_sem_signal(mbox->mutex); + } + +uInt16 sys_arch_mbox_fetch(struct sys_mbox *mbox, void **msg, uInt16 timeout) { + uInt16 time = 1; + + /* The mutex lock is quick so we don't bother with the timeout + stuff here. */ + sys_arch_sem_wait(mbox->mutex, 0); + + while(mbox->first == mbox->last) { + sys_sem_signal(mbox->mutex); + + /* We block while waiting for a mail to arrive in the mailbox. We + must be prepared to timeout. */ + if(timeout != 0) { + time = sys_arch_sem_wait(mbox->mail, timeout); + + /* If time == 0, the sem_wait timed out, and we return 0. */ + if(time == 0) { + return 0; + } + } else { + sys_arch_sem_wait(mbox->mail, 0); + } + + sys_arch_sem_wait(mbox->mutex, 0); + } + + if(msg != NULL) { + //kprintf("sys_mbox_fetch: mbox %p msg %p\n", mbox, *msg); + *msg = mbox->msgs[mbox->first]; + } + + mbox->first++; + if(mbox->first == SYS_MBOX_SIZE) { + mbox->first = 0; + } + + sys_sem_signal(mbox->mutex); + + return(time); + } + +struct sys_sem *sys_sem_new(uInt8 count) { + return sys_sem_new_(count); + } + +static struct sys_sem *sys_sem_new_(uInt8 count) { + struct sys_sem *sem; + + sem = kmalloc(sizeof(struct sys_sem),sysID); + sem->c = count; + + ubthread_cond_init(&(sem->cond), NULL); + ubthread_mutex_init(&(sem->mutex), NULL); + + return sem; + } + +static uInt16 cond_wait(ubthread_cond_t *cond, ubthread_mutex_t *mutex, uInt16 timeout) { + unsigned int tdiff; + unsigned long sec, usec; + struct timeval rtime1, rtime2; + struct timespec ts; + struct timezone tz; + int retval; + + if (timeout > 0) { + /* Get a timestamp and add the timeout value. */ + gettimeofday(&rtime1, &tz); + sec = rtime1.tv_sec; + usec = rtime1.tv_usec; + usec += timeout % 1000 * 1000; + sec += (int)(timeout / 1000) + (int)(usec / 1000000); + usec = usec % 1000000; + ts.tv_nsec = usec * 1000; + ts.tv_sec = sec; + + retval = ubthread_cond_timedwait(cond, mutex, &ts); + if (retval == ETIMEDOUT) { + return 0; + } + else { + /* Calculate for how long we waited for the cond. */ + gettimeofday(&rtime2, &tz); + tdiff = (rtime2.tv_sec - rtime1.tv_sec) * 1000 + + (rtime2.tv_usec - rtime1.tv_usec) / 1000; + if (tdiff == 0) { + return 1; + } + return tdiff; + } + } + else { + ubthread_cond_wait(cond, mutex); + return 0; + } + } + +uInt16 sys_arch_sem_wait(struct sys_sem *sem, uInt16 timeout) { + uInt16 time = 1; + ubthread_mutex_lock(&(sem->mutex)); + while(sem->c <= 0) { + if(timeout > 0) { + time = cond_wait(&(sem->cond), &(sem->mutex), timeout); + if(time == 0) { + ubthread_mutex_unlock(&(sem->mutex)); + return 0; + } + } else { + cond_wait(&(sem->cond), &(sem->mutex), 0); + } + } + sem->c--; + ubthread_mutex_unlock(&(sem->mutex)); + return(time); + } + +void sys_sem_signal(struct sys_sem *sem) { + ubthread_mutex_lock(&(sem->mutex)); + sem->c++; + if(sem->c > 1) + sem->c = 1; + ubthread_cond_signal(&(sem->cond)); + ubthread_mutex_unlock(&(sem->mutex)); + } + +void sys_sem_free(struct sys_sem *sem) { + if(sem != SYS_SEM_NULL) { + sys_sem_free_(sem); + } + } + +static void sys_sem_free_(struct sys_sem *sem) { + ubthread_cond_destroy(&(sem->cond)); + ubthread_mutex_destroy(&(sem->mutex)); + kfree(sem); + } + +unsigned long sys_unix_now() { + struct timeval tv; + struct timezone tz; + long sec, usec; + unsigned long msec; + gettimeofday(&tv, &tz); + + sec = tv.tv_sec - starttime.tv_sec; + usec = tv.tv_usec - starttime.tv_usec; + msec = sec * 1000 + usec / 1000; + return msec; + } + +void sys_init() { + struct timezone tz; + gettimeofday(&starttime, &tz); + } + +struct sys_timeouts *sys_arch_timeouts(void) { + struct sys_thread *thread; + thread = current_thread(); + return(&thread->timeouts); + } + +/*** + END + ***/ diff --git a/src/sys/net/net/udpecho.c b/src/sys/net/net/udpecho.c new file mode 100644 index 0000000..f8b556a --- /dev/null +++ b/src/sys/net/net/udpecho.c @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2001, Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce 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 Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (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 file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + * $Id$ + */ + +#include +#include + +#include "net/api.h" +#include "net/sys.h" + +/*-----------------------------------------------------------------------------------*/ +void +udpecho_thread(void *arg) +{ + static struct netconn *conn; + static struct netbuf *buf; + static struct ip_addr *addr; + static unsigned short port; + char buffer[4096]; + + kprintf("1"); + conn = netconn_new(NETCONN_UDP); + kprintf("2"); + netconn_bind(conn, NULL, 7); + kprintf("3"); + + while(1) { + kprintf("a"); + buf = netconn_recv(conn); + kprintf("b"); + addr = netbuf_fromaddr(buf); + kprintf("c"); + port = netbuf_fromport(buf); + kprintf("d"); + netconn_connect(conn, addr, port); + kprintf("e"); + netconn_send(conn, buf); + kprintf("f"); + netbuf_copy(buf, buffer, sizeof(buffer)); + kprintf("got %s\n", buffer); + netbuf_delete(buf); + kprintf("g"); + } +} +/*-----------------------------------------------------------------------------------*/ +void +udpecho_init(void) +{ + sys_thread_new(udpecho_thread, NULL); +} diff --git a/src/sys/net/net/udpecho.h b/src/sys/net/net/udpecho.h new file mode 100644 index 0000000..9faea8f --- /dev/null +++ b/src/sys/net/net/udpecho.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2001, Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce 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 Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (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 file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + * $Id$ + */ +#ifndef __UDPECHO_H__ +#define __UDPECHO_H__ + +void udpecho_init(void); + +#endif /* __UDPECHO_H__ */ diff --git a/src/sys/net/netif/Makefile b/src/sys/net/netif/Makefile new file mode 100755 index 0000000..d11a495 --- /dev/null +++ b/src/sys/net/netif/Makefile @@ -0,0 +1,27 @@ +# (C) 2002 The UbixOS Project +# $Id$ + +# Include Global 'Source' Options +include ../../../Makefile.inc +include ../../Makefile.inc + +# Objects +OBJS = ethernetif.o loopif.o tcpdump.o arp.o + +all: $(OBJS) + +# Compile Types +.cc.o: + $(CXX) ${CFLAGS} -fno-exceptions -DNOBOOL -Wall -fomit-frame-pointer -O -I../../include -c -o $@ $< +.cc.s: + $(CXX) ${CFLAGS} -fno-exceptions -DNOBOOL -Wall -fomit-frame-pointer -O -I../../include -S -o $@ $< +.c.o: + $(CC) ${CFLAGS} -Wall -fomit-frame-pointer -O -I../../include -c -o $@ $< +.c.s: + $(CC) ${CFLAGS} -Wall -fomit-frame-pointer -O -I../../include -S -o $@ $< +.S.o: + $(CC) ${CFLAGS} -Wall -fomit-frame-pointer -c -o $@ $< + +# Clean up the junk +clean: + $(REMOVE) $(OBJS) diff --git a/src/sys/net/netif/arp.c b/src/sys/net/netif/arp.c new file mode 100644 index 0000000..48f74e6 --- /dev/null +++ b/src/sys/net/netif/arp.c @@ -0,0 +1,307 @@ +/* + * Copyright (c) 2001, Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce 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 Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (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 file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + * $Id$ + * + */ + +#include +#include + +#include "net/debug.h" +#include "net/ipv4/inet.h" +#include "netif/arp.h" +#include "net/ipv4/ip.h" + + +#define ARP_MAXAGE 2 /* 120 * 10 seconds = 20 minutes. */ + +#define HWTYPE_ETHERNET 1 + +#define ARP_REQUEST 1 +#define ARP_REPLY 2 + +/* MUST be compiled with "pack structs" or equivalent! */ +PACK_STRUCT_BEGIN +struct arp_hdr { + PACK_STRUCT_FIELD(struct eth_hdr ethhdr); + PACK_STRUCT_FIELD(uInt16 hwtype); + PACK_STRUCT_FIELD(uInt16 proto); + PACK_STRUCT_FIELD(uInt16 _hwlen_protolen); + PACK_STRUCT_FIELD(uInt16 opcode); + PACK_STRUCT_FIELD(struct eth_addr shwaddr); + PACK_STRUCT_FIELD(struct ip_addr sipaddr); + PACK_STRUCT_FIELD(struct eth_addr dhwaddr); + PACK_STRUCT_FIELD(struct ip_addr dipaddr); +} PACK_STRUCT_STRUCT; +PACK_STRUCT_END + +#define ARPH_HWLEN(hdr) (NTOHS((hdr)->_hwlen_protolen) >> 8) +#define ARPH_PROTOLEN(hdr) (NTOHS((hdr)->_hwlen_protolen) & 0xff) + + +#define ARPH_HWLEN_SET(hdr, len) (hdr)->_hwlen_protolen = HTONS(ARPH_PROTOLEN(hdr) | ((len) << 8)) +#define ARPH_PROTOLEN_SET(hdr, len) (hdr)->_hwlen_protolen = HTONS((len) | (ARPH_HWLEN(hdr) << 8)) + +PACK_STRUCT_BEGIN +struct ethip_hdr { + PACK_STRUCT_FIELD(struct eth_hdr eth); + PACK_STRUCT_FIELD(struct ip_hdr ip); +}; +PACK_STRUCT_END + +struct arp_entry { + struct ip_addr ipaddr; + struct eth_addr ethaddr; + uInt8 ctime; +}; + +static struct arp_entry arp_table[ARP_TABLE_SIZE]; +static uInt8 ctime; + +/*-----------------------------------------------------------------------------------*/ +void +arp_init(void) +{ + uInt8 i; + + for(i = 0; i < ARP_TABLE_SIZE; ++i) { + ip_addr_set(&(arp_table[i].ipaddr), + IP_ADDR_ANY); + } +} +/*-----------------------------------------------------------------------------------*/ +void +arp_tmr(void) +{ + uInt8 i; + + ++ctime; + for(i = 0; i < ARP_TABLE_SIZE; ++i) { + if(!ip_addr_isany(&arp_table[i].ipaddr) && + ctime - arp_table[i].ctime >= ARP_MAXAGE) { + DEBUGF(ARP_DEBUG, ("arp_timer: expired entry %d.\n", i)); + ip_addr_set(&(arp_table[i].ipaddr), + IP_ADDR_ANY); + } + } +} +/*-----------------------------------------------------------------------------------*/ +static void +add_arp_entry(struct ip_addr *ipaddr, struct eth_addr *ethaddr) +{ + uInt8 i, j, k; + uInt8 maxtime; + + /* Walk through the ARP mapping table and try to find an entry to + update. If none is found, the IP -> MAC address mapping is + inserted in the ARP table. */ + for(i = 0; i < ARP_TABLE_SIZE; ++i) { + + /* Only check those entries that are actually in use. */ + if(!ip_addr_isany(&arp_table[i].ipaddr)) { + /* Check if the source IP address of the incoming packet matches + the IP address in this ARP table entry. */ + if(ip_addr_cmp(ipaddr, &arp_table[i].ipaddr)) { + /* An old entry found, update this and return. */ + for(k = 0; k < 6; ++k) { + arp_table[i].ethaddr.addr[k] = ethaddr->addr[k]; + } + arp_table[i].ctime = ctime; + return; + } + } + } + + /* If we get here, no existing ARP table entry was found, so we + create one. */ + + /* First, we try to find an unused entry in the ARP table. */ + for(i = 0; i < ARP_TABLE_SIZE; ++i) { + if(ip_addr_isany(&arp_table[i].ipaddr)) { + break; + } + } + + /* If no unused entry is found, we try to find the oldest entry and + throw it away. */ + if(i == ARP_TABLE_SIZE) { + maxtime = 0; + j = 0; + for(i = 0; i < ARP_TABLE_SIZE; ++i) { + if(ctime - arp_table[i].ctime > maxtime) { + maxtime = ctime - arp_table[i].ctime; + j = i; + } + } + i = j; + } + + /* Now, i is the ARP table entry which we will fill with the new + information. */ + ip_addr_set(&arp_table[i].ipaddr, ipaddr); + for(k = 0; k < 6; ++k) { + arp_table[i].ethaddr.addr[k] = ethaddr->addr[k]; + } + arp_table[i].ctime = ctime; + return; + +} +/*-----------------------------------------------------------------------------------*/ +void +arp_ip_input(struct netif *netif, struct pbuf *p) +{ + struct ethip_hdr *hdr; + + hdr = p->payload; + + /* Only insert/update an entry if the source IP address of the + incoming IP packet comes from a host on the local network. */ + if(!ip_addr_maskcmp(&(hdr->ip.src), &(netif->ip_addr), &(netif->netmask))) { + return; + } + DEBUGF(ARP_DEBUG, ("arp_ip_input: updating ARP table.\n")); + add_arp_entry(&(hdr->ip.src), &(hdr->eth.src)); +} +/*-----------------------------------------------------------------------------------*/ +struct pbuf * +arp_arp_input(struct netif *netif, struct eth_addr *ethaddr, struct pbuf *p) +{ + struct arp_hdr *hdr; + uInt8 i; + + if(p->tot_len < sizeof(struct arp_hdr)) { + kprintf("arp_arp_input: packet too short (%d/%d)\n", p->tot_len, sizeof(struct arp_hdr)); + pbuf_free(p); + return NULL; + } + + hdr = p->payload; + + switch(htons(hdr->opcode)) { + case ARP_REQUEST: + /* ARP request. If it asked for our address, we send out a + reply. */ + if(ip_addr_cmp(&(hdr->dipaddr), &(netif->ip_addr))) { + hdr->opcode = htons(ARP_REPLY); + + ip_addr_set(&(hdr->dipaddr), &(hdr->sipaddr)); + ip_addr_set(&(hdr->sipaddr), &(netif->ip_addr)); + + for(i = 0; i < 6; ++i) { + hdr->dhwaddr.addr[i] = hdr->shwaddr.addr[i]; + hdr->shwaddr.addr[i] = ethaddr->addr[i]; + hdr->ethhdr.dest.addr[i] = hdr->dhwaddr.addr[i]; + hdr->ethhdr.src.addr[i] = ethaddr->addr[i]; + } + + hdr->hwtype = htons(HWTYPE_ETHERNET); + ARPH_HWLEN_SET(hdr, 6); + + hdr->proto = htons(ETHTYPE_IP); + ARPH_PROTOLEN_SET(hdr, sizeof(struct ip_addr)); + + hdr->ethhdr.type = htons(ETHTYPE_ARP); + return p; + } + break; + case ARP_REPLY: + /* ARP reply. We insert or update the ARP table. */ + if(ip_addr_cmp(&(hdr->dipaddr), &(netif->ip_addr))) { + add_arp_entry(&(hdr->sipaddr), &(hdr->shwaddr)); + } + break; + default: + kprintf("arp_arp_input: unknown type %d\n", htons(hdr->opcode)); + break; + } + + pbuf_free(p); + return NULL; +} +/*-----------------------------------------------------------------------------------*/ +struct eth_addr * +arp_lookup(struct ip_addr *ipaddr) +{ + uInt8 i; + + for(i = 0; i < ARP_TABLE_SIZE; ++i) { + if(ip_addr_cmp(ipaddr, &arp_table[i].ipaddr)) { + return &arp_table[i].ethaddr; + } + } + return NULL; +} +/*-----------------------------------------------------------------------------------*/ +struct pbuf * +arp_query(struct netif *netif, struct eth_addr *ethaddr, struct ip_addr *ipaddr) +{ + struct arp_hdr *hdr; + struct pbuf *p; + uInt8 i; + + p = pbuf_alloc(PBUF_LINK, sizeof(struct arp_hdr), PBUF_RAM); + if(p == NULL) { + return NULL; + } + + hdr = p->payload; + + hdr->opcode = htons(ARP_REQUEST); + + for(i = 0; i < 6; ++i) { + hdr->dhwaddr.addr[i] = 0x00; + hdr->shwaddr.addr[i] = ethaddr->addr[i]; + } + + ip_addr_set(&(hdr->dipaddr), ipaddr); + ip_addr_set(&(hdr->sipaddr), &(netif->ip_addr)); + + hdr->hwtype = htons(HWTYPE_ETHERNET); + ARPH_HWLEN_SET(hdr, 6); + + hdr->proto = htons(ETHTYPE_IP); + ARPH_PROTOLEN_SET(hdr, sizeof(struct ip_addr)); + + for(i = 0; i < 6; ++i) { + hdr->ethhdr.dest.addr[i] = 0xff; + hdr->ethhdr.src.addr[i] = ethaddr->addr[i]; + } + + hdr->ethhdr.type = htons(ETHTYPE_ARP); + return p; +} +/*-----------------------------------------------------------------------------------*/ + + + + diff --git a/src/sys/net/netif/ethernetif.c b/src/sys/net/netif/ethernetif.c new file mode 100644 index 0000000..0df8876 --- /dev/null +++ b/src/sys/net/netif/ethernetif.c @@ -0,0 +1,363 @@ +/* + * Copyright (c) 2001, Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce 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 Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (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 file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + * $Id$ + */ + +/* + * This file is a skeleton for developing Ethernet network interface + * drivers for lwIP. Add code to the low_level functions and do a + * search-and-replace for the word "ethernetif" to replace it with + * something that better describes your network interface. + */ + +#include +#include +#include +#include +#include + + +#include "net/debug.h" + +#include "net/opt.h" +#include "net/def.h" +#include "net/mem.h" +#include "net/pbuf.h" +#include "net/sys.h" + +#include "netif/arp.h" + +/* Define those to better describe your network interface. */ +#define IFNAME0 'e' +#define IFNAME1 'd' + +struct ethernetif { + struct eth_addr *ethaddr; + /* Add whatever per-interface state that is needed here. */ +}; + +static const struct eth_addr ethbroadcast = {{0xff,0xff,0xff,0xff,0xff,0xff}}; + +/* Forward declarations. */ +static void ethernetif_input(struct netif *netif); +static err_t ethernetif_output(struct netif *netif, struct pbuf *p, struct ip_addr *ipaddr); +static void ethernetif_thread(); +struct device *dev = 0x0; + +/*-----------------------------------------------------------------------------------*/ +static void low_level_init(struct netif *netif) { + struct ethernetif *ethernetif; + + ethernetif = netif->state; + dev = (struct device *)kmalloc(sizeof(struct device),sysID); + dev->ioAddr = 0x240; + dev->irq = 3; + + /* Obtain MAC address from network interface. */ + ethernetif->ethaddr->addr[0] = 0xfe; + ethernetif->ethaddr->addr[1] = 0xed; + ethernetif->ethaddr->addr[2] = 0xde; + ethernetif->ethaddr->addr[3] = 0xad; + ethernetif->ethaddr->addr[4] = 0xbe; + ethernetif->ethaddr->addr[5] = 0xef; + + /* Do whatever else is needed to initialize interface. */ + + sys_thread_new(ethernetif_thread, netif); + + } +/*-----------------------------------------------------------------------------------*/ +/* + * low_level_output(): + * + * Should do the actual transmission of the packet. The packet is + * contained in the pbuf that is passed to the function. This pbuf + * might be chained. + * + */ +/*-----------------------------------------------------------------------------------*/ + +static err_t low_level_output(struct ethernetif *ethernetif, struct pbuf *p) { + struct pbuf *q; + dev->ioAddr = 0x240; + dev->irq = 3; + + + kprintf("Sending Data\n"); + for(q = p; q != NULL; q = q->next) { + PCtoNIC(dev,q->payload,q->len); + } + + return ERR_OK; + } + + +/*-----------------------------------------------------------------------------------*/ +/* + * low_level_input(): + * + * Should allocate a pbuf and transfer the bytes of the incoming + * packet from the interface into the pbuf. + * + */ +/*-----------------------------------------------------------------------------------*/ +static struct pbuf *low_level_input(struct ethernetif *ethernetif) { + struct pbuf *p, *q; + uInt16 len; + char *bufptr; + char *buf; + //char buf[1500]; + + /* Obtain the size of the packet and put it into the "len" + variable. */ + //len = read(tapif->fd, buf, sizeof(buf)); + len = packetLength; + bufptr = nicPacket; + + /* if(((double)rand()/(double)RAND_MAX) < 0.1) { + printf("drop\n"); + return NULL; + }*/ + + + /* We allocate a pbuf chain of pbufs from the pool. */ + p = pbuf_alloc(PBUF_LINK, len, PBUF_POOL); + + if(p != NULL) { + /* We iterate over the pbuf chain until we have read the entire + packet into the pbuf. */ + //bufptr = &buf[0]; + for(q = p; q != NULL; q = q->next) { + /* Read enough bytes to fill this pbuf in the chain. The + avaliable data in the pbuf is given by the q->len + variable. */ + /* read data into(q->payload, q->len); */ + bcopy(bufptr, q->payload, q->len); + buf = q->payload; + bufptr += q->len; + } + /* acknowledge that packet has been read(); */ + } else { + /* drop packet(); */ + } + return p; +} + + +/*-----------------------------------------------------------------------------------*/ +/* + * ethernetif_output(): + * + * This function is called by the TCP/IP stack when an IP packet + * should be sent. It calls the function called low_level_output() to + * do the actuall transmission of the packet. + * + */ +/*-----------------------------------------------------------------------------------*/ +static err_t ethernetif_output(struct netif *netif, struct pbuf *p, struct ip_addr *ipaddr) { + struct ethernetif *ethernetif; + struct pbuf *q; + struct eth_hdr *ethhdr; + struct eth_addr *dest, mcastaddr; + struct ip_addr *queryaddr; + err_t err; + uInt8 i; + + ethernetif = netif->state; + + + /* Make room for Ethernet header. */ + if(pbuf_header(p, 14) != 0) { + /* The pbuf_header() call shouldn't fail, but we allocate an extra + pbuf just in case. */ + q = pbuf_alloc(PBUF_LINK, 14, PBUF_RAM); + if(q == NULL) { + return ERR_MEM; + } + pbuf_chain(q, p); + p = q; + } + + /* Construct Ethernet header. Start with looking up deciding which + MAC address to use as a destination address. Broadcasts and + multicasts are special, all other addresses are looked up in the + ARP table. */ + queryaddr = ipaddr; + if(ip_addr_isany(ipaddr) || + ip_addr_isbroadcast(ipaddr, &(netif->netmask))) { + dest = (struct eth_addr *)ðbroadcast; + } else if(ip_addr_ismulticast(ipaddr)) { + /* Hash IP multicast address to MAC address. */ + mcastaddr.addr[0] = 0x01; + mcastaddr.addr[1] = 0x0; + mcastaddr.addr[2] = 0x5e; + mcastaddr.addr[3] = ip4_addr2(ipaddr) & 0x7f; + mcastaddr.addr[4] = ip4_addr3(ipaddr); + mcastaddr.addr[5] = ip4_addr4(ipaddr); + dest = &mcastaddr; + } else { + + if(ip_addr_maskcmp(ipaddr, &(netif->ip_addr), &(netif->netmask))) { + /* Use destination IP address if the destination is on the same + subnet as we are. */ + queryaddr = ipaddr; + } else { + /* Otherwise we use the default router as the address to send + the Ethernet frame to. */ + queryaddr = &(netif->gw); + } + dest = arp_lookup(queryaddr); + } + + + /* If the arp_lookup() didn't find an address, we send out an ARP + query for the IP address. */ + if(dest == NULL) { + q = arp_query(netif, ethernetif->ethaddr, queryaddr); + if(q != NULL) { + err = low_level_output(ethernetif, q); + pbuf_free(q); + return err; + } + return ERR_MEM; + } + ethhdr = p->payload; + + for(i = 0; i < 6; i++) { + ethhdr->dest.addr[i] = dest->addr[i]; + ethhdr->src.addr[i] = ethernetif->ethaddr->addr[i]; + } + + ethhdr->type = htons(ETHTYPE_IP); + + return low_level_output(ethernetif, p); + +} +/*-----------------------------------------------------------------------------------*/ +/* + * ethernetif_input(): + * + * This function should be called when a packet is ready to be read + * from the interface. It uses the function low_level_input() that + * should handle the actual reception of bytes from the network + * interface. + * + */ +/*-----------------------------------------------------------------------------------*/ +static void ethernetif_input(struct netif *netif) { + struct ethernetif *ethernetif; + struct eth_hdr *ethhdr; + struct pbuf *p; + + + ethernetif = netif->state; + + p = low_level_input(ethernetif); + + if(p != NULL) { + + ethhdr = p->payload; + + switch(htons(ethhdr->type)) { + case ETHTYPE_IP: + arp_ip_input(netif, p); + pbuf_header(p, -14); + netif->input(p, netif); + break; + case ETHTYPE_ARP: + p = arp_arp_input(netif, ethernetif->ethaddr, p); + if(p != NULL) { + low_level_output(ethernetif, p); + pbuf_free(p); + } + break; + default: + kprintf("DEFAULT [0x%X]",ethhdr->type); + pbuf_free(p); + break; + } + } +} +/*-----------------------------------------------------------------------------------*/ +static void +arp_timer(void *arg) +{ + arp_tmr(); + sys_timeout(ARP_TMR_INTERVAL, (sys_timeout_handler)arp_timer, NULL); +} + +/*-----------------------------------------------------------------------------------*/ +/* + * ethernetif_init(): + * + * Should be called at the beginning of the program to set up the + * network interface. It calls the function low_level_init() to do the + * actual setup of the hardware. + * + */ +/*-----------------------------------------------------------------------------------*/ +void ethernetif_init(struct netif *netif) { + struct ethernetif *ethernetif; + + ethernetif = mem_malloc(sizeof(struct ethernetif)); + netif->state = ethernetif; + netif->name[0] = IFNAME0; + netif->name[1] = IFNAME1; + netif->output = ethernetif_output; + netif->linkoutput = (void *)low_level_output; + + kprintf("Star"); + ethernetif->ethaddr = (struct eth_addr *)&(netif->hwaddr[0]); + kprintf("ting"); + + low_level_init(netif); + arp_init(); + + sys_timeout(ARP_TMR_INTERVAL, (sys_timeout_handler)arp_timer, NULL); + } + +/*-----------------------------------------------------------------------------------*/ + +void ethernetif_thread(void *arg) { + struct netif *netif; + + netif = arg; + + while (1) { + if (packetLength > 0x0) { + ethernetif_input(netif); + nicPacket = 0x0; + packetLength = 0x0; + } + } + } diff --git a/src/sys/net/netif/loopif.c b/src/sys/net/netif/loopif.c new file mode 100644 index 0000000..fbf42a8 --- /dev/null +++ b/src/sys/net/netif/loopif.c @@ -0,0 +1,84 @@ +/* + * Copyright (c) 2001, Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce 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 Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (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 file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + * $Id$ + */ +#include "net/debug.h" +#include "net/mem.h" +#include "net/opt.h" +#include "netif/loopif.h" +#include "netif/tcpdump.h" + +#include "net/tcp.h" +#include "net/ipv4/ip.h" + +/*-----------------------------------------------------------------------------------*/ +static err_t +loopif_output(struct netif *netif, struct pbuf *p, + struct ip_addr *ipaddr) +{ + struct pbuf *q, *r; + char *ptr; + +#ifdef LWIP_DEBUG + tcpdump(p); +#endif /* LWIP_DEBUG */ + + r = pbuf_alloc(PBUF_RAW, p->tot_len, PBUF_RAM); + if(r != NULL) { + ptr = r->payload; + + for(q = p; q != NULL; q = q->next) { + bcopy(q->payload, ptr, q->len); + ptr += q->len; + } + netif->input(r, netif); + return ERR_OK; + } + return ERR_MEM; +} +/*-----------------------------------------------------------------------------------*/ +void +loopif_init(struct netif *netif) +{ + netif->name[0] = 'l'; + netif->name[1] = 'o'; + netif->output = loopif_output; +} +/*-----------------------------------------------------------------------------------*/ + + + + + + + diff --git a/src/sys/net/netif/tcpdump.c b/src/sys/net/netif/tcpdump.c new file mode 100644 index 0000000..582224f --- /dev/null +++ b/src/sys/net/netif/tcpdump.c @@ -0,0 +1,175 @@ +/* + * Copyright (c) 2001, Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce 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 Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (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 file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + * $Id$ + */ + +#include +#include + +#include "netif/tcpdump.h" +#include "net/ipv4/ip.h" +#include "net/tcp.h" +#include "net/udp.h" +#include "net/ipv4/inet.h" + +fileDescriptor *file = NULL; + +void tcpdump_init(void) { + char *fname; + + fname = "tcpdump"; + file = fopen(fname, "wb"); + if(file == NULL) { + kpanic("tcpdump_init: fopen\n"); + } + } + +void tcpdump(struct pbuf *p) { + struct ip_hdr *iphdr; + struct tcp_hdr *tcphdr; + struct udp_hdr *udphdr; + char flags[5]; + int i; + int len; + int offset; + + if (file == NULL) { + return; + } + + /* + iphdr = p->payload; + switch(IPH_PROTO(iphdr)) { + case IP_PROTO_TCP: + tcphdr = (struct tcp_hdr *)((char *)iphdr + IP_HLEN); + + pbuf_header(p, -IP_HLEN); + if(inet_chksum_pseudo(p, (struct ip_addr *)&(iphdr->src), + (struct ip_addr *)&(iphdr->dest), + IP_PROTO_TCP, p->tot_len) != 0) { + DEBUGF(TCPDUMP_DEBUG, ("tcpdump: IP checksum failed!\n")); + fprintf(file, "!chksum "); + } + + i = 0; + if(TCPH_FLAGS(tcphdr) & TCP_SYN) { + flags[i++] = 'S'; + } + if(TCPH_FLAGS(tcphdr) & TCP_PSH) { + flags[i++] = 'P'; + } + if(TCPH_FLAGS(tcphdr) & TCP_FIN) { + flags[i++] = 'F'; + } + if(TCPH_FLAGS(tcphdr) & TCP_RST) { + flags[i++] = 'R'; + } + if(i == 0) { + flags[i++] = '.'; + } + flags[i++] = 0; + + + + fprintf(file, "%d.%d.%d.%d.%u > %d.%d.%d.%d.%u: ", + (int)(ntohl(iphdr->src.addr) >> 24) & 0xff, + (int)(ntohl(iphdr->src.addr) >> 16) & 0xff, + (int)(ntohl(iphdr->src.addr) >> 8) & 0xff, + (int)(ntohl(iphdr->src.addr) >> 0) & 0xff, + ntohs(tcphdr->src), + (int)(ntohl(iphdr->dest.addr) >> 24) & 0xff, + (int)(ntohl(iphdr->dest.addr) >> 16) & 0xff, + (int)(ntohl(iphdr->dest.addr) >> 8) & 0xff, + (int)(ntohl(iphdr->dest.addr) >> 0) & 0xff, + ntohs(tcphdr->dest)); + offset = TCPH_OFFSET(tcphdr) >> 4; + + len = ntohs(IPH_LEN(iphdr)) - offset * 4 - IP_HLEN; + if(len != 0 || flags[0] != '.') { + fprintf(file, "%s %lu:%lu(%u) ", + flags, + ntohl(tcphdr->seqno), + ntohl(tcphdr->seqno) + len, + len); + } + if(TCPH_FLAGS(tcphdr) & TCP_ACK) { + fprintf(file, "ack %lu ", + ntohl(tcphdr->ackno)); + } + fprintf(file, "wnd %u\n", + ntohs(tcphdr->wnd)); + + fflush(file); + + pbuf_header(p, IP_HLEN); + break; + + case IP_PROTO_UDP: + udphdr = (struct udp_hdr *)((char *)iphdr + IP_HLEN); + + pbuf_header(p, -IP_HLEN); + if(inet_chksum_pseudo(p, (struct ip_addr *)&(iphdr->src), + (struct ip_addr *)&(iphdr->dest), + IP_PROTO_UDP, p->tot_len) != 0) { + kprintf("tcpdump: IP checksum failed!\n"); + fprintf(file, "!chksum "); + } + + fprintf(file, "%d.%d.%d.%d.%u > %d.%d.%d.%d.%u: ", + (int)(ntohl(iphdr->src.addr) >> 24) & 0xff, + (int)(ntohl(iphdr->src.addr) >> 16) & 0xff, + (int)(ntohl(iphdr->src.addr) >> 8) & 0xff, + (int)(ntohl(iphdr->src.addr) >> 0) & 0xff, + ntohs(udphdr->src), + (int)(ntohl(iphdr->dest.addr) >> 24) & 0xff, + (int)(ntohl(iphdr->dest.addr) >> 16) & 0xff, + (int)(ntohl(iphdr->dest.addr) >> 8) & 0xff, + (int)(ntohl(iphdr->dest.addr) >> 0) & 0xff, + ntohs(udphdr->dest)); + fprintf(file, "U "); + len = ntohs(IPH_LEN(iphdr)) - sizeof(struct udp_hdr) - IP_HLEN; + fprintf(file, " %d\n", len); + + fflush(file); + + pbuf_header(p, IP_HLEN); + break; + + } + */ + } + +/*** + END + ***/ + diff --git a/src/sys/pci/Makefile b/src/sys/pci/Makefile new file mode 100644 index 0000000..211c093 --- /dev/null +++ b/src/sys/pci/Makefile @@ -0,0 +1,27 @@ +# (C) 2002 The UbixOS Project +# $Id$ + +# Include Global 'Source' Options +include ../../Makefile.inc +include ../Makefile.inc + +# Objects +OBJS = hd.o pci.o + +all: $(OBJS) + +# Compile Types +.cc.o: + $(CXX) ${CFLAGS} -Wall -fomit-frame-pointer -O -I../include -c -o $@ $< +.cc.s: + $(CXX) ${CFLAGS} -Wall -fomit-frame-pointer -O -I../include -S -o $@ $< +.c.o: + $(CC) ${CFLAGS} -Wall -fomit-frame-pointer -O -I../include -c -o $@ $< +.c.s: + $(CC) ${CFLAGS} -Wall -fomit-frame-pointer -O -I../include -S -o $@ $< +.S.o: + $(CC) ${CFLAGS} -Wall -fomit-frame-pointer -c -o $@ $< + +# Clean up the junk +clean: + $(REMOVE) $(OBJS) diff --git a/src/sys/pci/hd.c b/src/sys/pci/hd.c new file mode 100644 index 0000000..5f5da20 --- /dev/null +++ b/src/sys/pci/hd.c @@ -0,0 +1,279 @@ +/***************************************************************************************** + 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. + + $Log$ + Revision 1.12 2004/04/13 16:36:33 reddawg + Changed our copyright, it is all now under a BSD-Style license + + + + $Id$ + +*****************************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include + +struct driveInfo *hdd0; +struct driveInfo *hdd1; +struct driveInfo *hdd2; +struct driveInfo *hdd3; + +void initHardDisk() { + hdd0 = (struct driveInfo *)kmalloc(sizeof(struct driveInfo),sysID); + hdd1 = (struct driveInfo *)kmalloc(sizeof(struct driveInfo),sysID); + hdd2 = (struct driveInfo *)kmalloc(sizeof(struct driveInfo),sysID); + hdd3 = (struct driveInfo *)kmalloc(sizeof(struct driveInfo),sysID); + hdd0->hdPort = 0x1F0; + hdd0->hdDev = 0x40; + hdd1->hdPort = 0x1F0; + hdd1->hdDev = 0x50; + hdd2->hdPort = 0x177; + hdd2->hdDev = 0x40; + hdd3->hdPort = 0x177; + hdd3->hdDev = 0x50; + if (!initDrive(hdd0)) { + addDrive(1,1,hdd0,hdRead,hdWrite,0x0); + devFsMkNod("ad0",'b',0x1,0x0); + } + /* + if (!initDrive(hdd1)) { + addDrive(2,1,hdd1,hdRead,hdWrite,0x0); + } + if (!initDrive(hdd2)) { + addDrive(3,1,hdd2,hdRead,hdWrite,0x0); + } + if (!initDrive(hdd3)) { + addDrive(4,1,hdd3,hdRead,hdWrite,0x0); + } + */ + return; + } + +int initDrive(struct driveInfo *hdd) { + char retVal = 0x0; + long counter = 0x0; + short *tmp = 0x0; + for (counter = 1000000;counter >= 0;counter--) { + retVal = inportByte(hdd->hdPort + hdStat) & 0x80; + if (!retVal) goto ready; + } + kprintf("Error Initializing Drive\n"); + return(1); + ready: + outportByte(hdd->hdPort + hdHead,hdd->hdDev); + outportByte(hdd->hdPort + hdCmd,0xEC); + for (counter = 1000000;counter >= 0;counter--) { + retVal = inportByte(hdd->hdPort + hdStat); + if ((retVal & 1) != 0x0) { + kprintf("Error Drive Not Available\n"); + return(1); + } + if ((retVal & 8) != 0x0) { + goto go; + } + } + kprintf("Time Out Waiting On Drive\n"); + return(1); + go: + tmp = (short *)hdd->hdSector; + for (counter = 0;counter < (512/2);counter++) { + tmp[counter] = inportWord(hdd->hdPort + hdData); + } + retVal = tmp[0x2F] & 0xFF; + switch (retVal) { + case 0: + hdd->hdShift = 0; + hdd->hdMulti = 1; + break; + case 2: + hdd->hdShift = 1; + hdd->hdMulti = retVal; + break; + case 4: + hdd->hdShift = 2; + hdd->hdMulti = retVal; + break; + case 8: + hdd->hdShift = 3; + hdd->hdMulti = retVal; + break; + case 16: + hdd->hdShift = 4; + hdd->hdMulti = retVal; + break; + case 32: + hdd->hdShift = 5; + hdd->hdMulti = retVal; + break; + case 64: + hdd->hdShift = 6; + hdd->hdMulti = retVal; + break; + default: + kprintf("Error BLOCK Mode Unavailable: [%i]\n",retVal); + return(1); + } + outportByte(hdd->hdPort + hdSecCount,retVal); + outportByte(hdd->hdPort + hdHead,hdd->hdDev); + outportByte(hdd->hdPort + hdCmd,0xC6); + hdd->hdMask = retVal; + hdd->hdSize = (hdd->hdSector[0x7B] * 256 * 256 * 256) + (hdd->hdSector[0x7A] * 256 * 256) + (hdd->hdSector[0x79] * 256) + hdd->hdSector[0x78]; + hdd->hdEnable = 1; + kprintf("Drive: [0x%X/0x%X], Size: [%iSectors/%iKBytes]\n",hdd->hdPort,hdd->hdDev,hdd->hdSize,((hdd->hdSize*512)/1024)); + return(0); + } + +void hdWrite(struct driveInfo *hdd,long startSector,long sectorCount,void *baseAddr) { + long counter = 0x0; + long retVal = 0x0; + short transactionCount = 0x0; + short *tmp = (short *)baseAddr; + if (hdd->hdEnable == 0x0) { + kprintf("Invalid Drive\n"); + return; + } + if ((sectorCount >> hdd->hdShift) == 0x0) { + hdd->hdCalc = sectorCount; /* hdd->hdMask; */ + transactionCount = 1; + } + else { + hdd->hdCalc = hdd->hdMulti; + transactionCount = sectorCount >> hdd->hdShift; + } + for (;transactionCount > 0;transactionCount--) { + for (counter = 1000000;counter >= 0;counter--) { + retVal = inportByte(hdd->hdPort + hdStat) & 0x80; + if (!retVal) goto ready; + } + kprintf("Time Out Waiting On Drive\n"); + return; + ready: + outportByte(hdd->hdPort + hdSecCount,hdd->hdCalc); + outportByte(hdd->hdPort + hdSecNum,(startSector & 0xFF)); + retVal = startSector >> 8; + outportByte(hdd->hdPort + hdCylLow,(retVal & 0xFF)); + retVal >>= 8; + outportByte(hdd->hdPort + hdCylHi,(retVal & 0xFF)); + retVal >>= 8; + retVal &= 0x0F; + retVal |= hdd->hdDev; + outportByte(hdd->hdPort + hdHead,(retVal & 0xFF)); + if (hdd->hdShift > 0) + outportByte(hdd->hdPort + hdCmd,0xC5); + else + outportByte(hdd->hdPort + hdCmd,0x30); + for (counter = 1000000;counter >= 0;counter--) { + retVal = inportByte(hdd->hdPort + hdStat); + if ((retVal & 1) != 0x0) { + kprintf("HD Write Error\n"); + return; + } + if ((retVal & 8) != 0x0) { + goto go; + } + } + kprintf("Time Out Waiting On Drive\n"); + return; + go: + for (counter = 0;counter < (hdd->hdCalc << 8);counter++) { + outportWord(hdd->hdPort + hdData,(short)tmp[counter]); + } + tmp += (counter + 0); + startSector += hdd->hdCalc; + } + return; + } + +void hdRead(struct driveInfo *hdd,long startSector,long sectorCount,void *baseAddr) { + long counter = 0x0; + long retVal = 0x0; + short transactionCount = 0x0; + short *tmp = (short *)baseAddr; + if (hdd->hdEnable == 0x0) { + kprintf("Invalid Drive\n"); + return; + } + if ((sectorCount >> hdd->hdShift) == 0x0) { + hdd->hdCalc = sectorCount; /* hdd->hdMask); */ + transactionCount = 1; + } + else { + hdd->hdCalc = hdd->hdMulti; + transactionCount = sectorCount >> hdd->hdShift; + } + for (;transactionCount > 0;transactionCount--) { + for (counter = 1000000;counter >= 0;counter--) { + retVal = inportByte(hdd->hdPort + hdStat) & 0x80; + if (!retVal) goto ready; + } + kprintf("Time Out Waiting On Drive\n"); + return; + ready: + outportByte(hdd->hdPort + hdSecCount,hdd->hdCalc); + outportByte(hdd->hdPort + hdSecNum,(startSector & 0xFF)); + retVal = startSector >> 8; + outportByte(hdd->hdPort + hdCylLow,(retVal & 0xFF)); + retVal >>= 8; + outportByte(hdd->hdPort + hdCylHi,(retVal & 0xFF)); + retVal >>= 8; + retVal &= 0x0F; + retVal |= hdd->hdDev; + outportByte(hdd->hdPort + hdHead,(retVal & 0xFF)); + if (hdd->hdShift > 0) + outportByte(hdd->hdPort + hdCmd,0xC4); + else + outportByte(hdd->hdPort + hdCmd,0x20); + for (counter = 1000000;counter >= 0;counter--) { + retVal = inportByte(hdd->hdPort + hdStat); + if ((retVal & 1) != 0x0) { + kprintf("HD Read Error: [%i:0x%X:%i]\n",counter,(uInt32)baseAddr,startSector); + return; + } + if ((retVal & 8) != 0x0) { + goto go; + } + } + kprintf("Error: Time Out Waiting On Drive\n"); + return; + go: + for (counter = 0;counter < (hdd->hdCalc << 8);counter++) { + tmp[counter] = inportWord(hdd->hdPort + hdData); + } + tmp += (counter + 0); + startSector += hdd->hdCalc; + } + return; + } + +/*** + END + ***/ + diff --git a/src/sys/pci/lnc.c b/src/sys/pci/lnc.c new file mode 100644 index 0000000..fa02f87 --- /dev/null +++ b/src/sys/pci/lnc.c @@ -0,0 +1,301 @@ +/***************************************************************************************** + 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. + + $Log$ + Revision 1.4 2004/04/13 16:36:33 reddawg + Changed our copyright, it is all now under a BSD-Style license + + + + $Id$ + +*****************************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +struct lncInfo *lnc = 0x0; + +static char const * const nicIdent[] = { + "Unknown", + "BICC", + "NE2100", + "DEPCA", + "CNET98S", /* PC-98 */ + }; + +static char const * const icIdent[] = { + "Unknown", + "LANCE", + "C-LANCE", + "PCnet-ISA", + "PCnet-ISA+", + "PCnet-ISA II", + "PCnet-32 VL-Bus", + "PCnet-PCI", + "PCnet-PCI II", + "PCnet-FAST", + "PCnet-FAST+", + "PCnet-Home", + }; + +void writeCsr(struct lncInfo *lnc, uInt16 port, uInt16 val) { + outportWord(lnc->rap, port); + outportWord(lnc->rdp, val); + } + +uInt16 readCsr(struct lncInfo *lnc, uInt16 port) { + outportWord(lnc->rap, port); + return(inportWord(lnc->rdp)); + } + +void writeBcr(struct lncInfo *lnc, uInt16 port, uInt16 val) { + outportWord(lnc->rap, port); + outportWord(lnc->bdp, val); + } + +uInt16 readBcr(struct lncInfo *sc, uInt16 port) { + outportWord(sc->rap, port); + return (inportWord(sc->bdp)); + } + + +void initLNC() { + int i = 0x0; + lnc = kmalloc(sizeof(struct lncInfo),-2); + + lnc->rap = 0x1000 + PCNET_RAP; + lnc->rdp = 0x1000 + PCNET_RDP; + lnc->bdp = 0x1000 + PCNET_BDP; + + lnc->nic.ic = probe(lnc); + if ((lnc->nic.ic > 0) && (lnc->nic.ic >= PCnet_32)) { + lnc->nic.ident = NE2100; + lnc->nic.memMode = DMA_FIXED; + + lnc->nrdre = NRDRE; + lnc->ntdre = NTDRE; + + /* Extract MAC address from PROM */ + for (i = 0; i < ETHER_ADDR_LEN; i++) { + lnc->arpcom.ac_enaddr[i] = inportByte(0x1000 + i); + kprintf("[0x%X]",lnc->arpcom.ac_enaddr[i]); + } + } + else { + kprintf("LNC Init Error\n"); + return; + } + lncAttach(lnc,0); + writeCsr(lnc, CSR3, 0); + writeCsr(lnc, CSR0, INIT); + for (i = 0; i < 1000; i++) + if (readCsr(lnc, CSR0) & IDON) + break; + + if (readCsr(lnc, CSR0) & IDON) { + writeCsr(lnc, CSR0, STRT | INEA); + setVector(_lncInt,mVec+9, (dInt + dPresent + dDpl3)); + enableIrq(9); + /* + * sc->arpcom.ac_if.if_flags |= IFF_RUNNING; + * sc->arpcom.ac_if.if_flags &= ~IFF_OACTIVE; + * lnc_start(&sc->arpcom.ac_if); + */ + } + else { + kprintf("LNC init Error\n"); + return; + } + return; + } + +int probe(struct lncInfo *lnc) { + uInt32 chipId = 0x0; + int type = 0x0; + + if ((type = lanceProbe(lnc))) { + chipId = readCsr(lnc, CSR89); + chipId <<= 16; + chipId |= readCsr(lnc, CSR88); + if (chipId & AMD_MASK) { + chipId >>= 12; + switch (chipId & PART_MASK) { + case Am79C960: + return(PCnet_ISA); + case Am79C961: + return (PCnet_ISAplus); + case Am79C961A: + return (PCnet_ISA_II); + case Am79C965: + return (PCnet_32); + case Am79C970: + return (PCnet_PCI); + case Am79C970A: + return (PCnet_PCI_II); + case Am79C971: + return (PCnet_FAST); + case Am79C972: + case Am79C973: + return (PCnet_FASTplus); + case Am79C978: + return (PCnet_Home); + default: + break; + } + } + } + return (type); + } + +int lanceProbe(struct lncInfo *lnc) { + writeCsr(lnc, CSR0, STOP); + if ((inportWord(lnc->rdp) & STOP) && !(readCsr(lnc, CSR3))) { + writeCsr(lnc, CSR0, INEA); + if (readCsr(lnc, CSR0) & INEA) { + return(C_LANCE); + } + else { + return(LANCE); + } + } + else { + return(UNKNOWN); + } + } + +void lncInt() { + uInt16 csr0 = 0x0; + while ((csr0 = inportWord(lnc->rdp)) & INTR) { + outportWord(lnc->rdp, csr0); + kprintf("CSR0: [0x%X]\n",csr0); + if (csr0 & ERR) { + kprintf("Error: [0x%X]\n",csr0); + } + if (csr0 & RINT) { + kprintf("RINT\n"); + } + if (csr0 & TINT) { + kprintf("TINT\n"); + } + } + kprintf("Finished!!!\n"); + outportByte(0x20,0x20); + return; + } + +asm( + ".global _lncInt \n" + "_lncInt : \n" + + " pusha \n" /* Save all registers */ + " pushw %ds \n" /* Set up the data segment */ + " pushw %es \n" + " pushw %ss \n" /* Note that ss is always valid */ + " pushw %ss \n" + " popw %ds \n" + " popw %es \n" + " call lncInt \n" + " popw %es \n" + " popw %ds \n" /* Restore registers */ + " popa \n" + " iret \n" /* Exit interrupt */ + ); + +int lncAttach(struct lncInfo *lnc,int unit) { + int lncMemSize = 0x0; + + lncMemSize = ((NDESC(lnc->nrdre) + NDESC(lnc->ntdre)) * sizeof(struct hostRingEntry)); + + if (lnc->nic.memMode != SHMEM) + lncMemSize += sizeof(struct initBlock) + (sizeof(struct mds) * (NDESC(lnc->nrdre) + NDESC(lnc->ntdre))) + MEM_SLEW; + + if (lnc->nic.memMode == DMA_FIXED) + lncMemSize += (NDESC(lnc->nrdre) * RECVBUFSIZE) + (NDESC(lnc->ntdre) * TRANSBUFSIZE); + + if (lnc->nic.memMode != SHMEM) { + if (lnc->nic.ic < PCnet_32) { + /* ISA based cards */ + kprintf("ISA Board\n"); + /* sc->recv_ring = contigmalloc(lnc_mem_size, M_DEVBUF, M_NOWAIT,0ul, 0xfffffful, 4ul, 0x1000000); */ + } + else { + /* + * For now it still needs to be below 16MB because the + * descriptor's can only hold 16 bit addresses. + */ + /* sc->recv_ring = contigmalloc(lnc_mem_size, M_DEVBUF, M_NOWAIT,0ul, 0xfffffful, 4ul, 0x1000000); */ + lnc->recvRing = kmalloc(lncMemSize,-2); + kprintf("PCI Board\n"); + } + } + + if (!lnc->recvRing) { + kprintf("lnc%d: Couldn't allocate memory for NIC\n", unit); + return (0); + } + + lnc->nic.mode = NORMAL; + + /* Fill in arpcom structure entries */ + /* + lnc->arpcom.ac_if.if_softc = sc; + lnc->arpcom.ac_if.if_name = lncdriver.name; + lnc->arpcom.ac_if.if_unit = unit; + lnc->arpcom.ac_if.if_mtu = ETHERMTU; + lnc->arpcom.ac_if.if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST; + lnc->arpcom.ac_if.if_timer = 0; + lnc->arpcom.ac_if.if_output = ether_output; + lnc->arpcom.ac_if.if_start = lnc_start; + lnc->arpcom.ac_if.if_ioctl = lnc_ioctl; + lnc->arpcom.ac_if.if_watchdog = lnc_watchdog; + lnc->arpcom.ac_if.if_init = lnc_init; + lnc->arpcom.ac_if.if_type = IFT_ETHER; + lnc->arpcom.ac_if.if_addrlen = ETHER_ADDR_LEN; + lnc->arpcom.ac_if.if_hdrlen = ETHER_HDR_LEN; + lnc->arpcom.ac_if.if_snd.ifq_maxlen = IFQ_MAXLEN; + */ + /* ether_ifattach(&sc->arpcom.ac_if, ETHER_BPF_SUPPORTED); */ + + kprintf("lnc%d: ", unit); + if (lnc->nic.ic == LANCE || lnc->nic.ic == C_LANCE) + kprintf("%s (%s)",nicIdent[lnc->nic.ident], icIdent[lnc->nic.ic]); + else + kprintf("%s", icIdent[lnc->nic.ic]); + kprintf(" address 0x%X\n", lnc->arpcom.ac_enaddr); + return(1); + } + +/*** + END + ***/ + diff --git a/src/sys/pci/pci.c b/src/sys/pci/pci.c new file mode 100644 index 0000000..5366a95 --- /dev/null +++ b/src/sys/pci/pci.c @@ -0,0 +1,323 @@ +/***************************************************************************************** + 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. + + $Log$ + Revision 1.5 2004/04/13 16:36:33 reddawg + Changed our copyright, it is all now under a BSD-Style license + + + + $Id$ + +*****************************************************************************************/ + +#include +#include +#include +#include + +const struct { + uInt8 baseClass; + uInt8 subClass; + uInt8 interface; + const char* name; + } pciClasses[] = { + { 0x00, 0x00, 0x00, "Undefined" }, + { 0x00, 0x01, 0x00, "VGA" }, + + { 0x01, 0x00, 0x00, "SCSI" }, + { 0x01, 0x01, 0x00, "IDE" }, + { 0x01, 0x01, 0x8A, "IDE" }, + { 0x01, 0x02, 0x00, "Floppy" }, + { 0x01, 0x03, 0x00, "IPI" }, + { 0x01, 0x04, 0x00, "RAID" }, + { 0x01, 0x80, 0x00, "Other" }, + + { 0x02, 0x00, 0x00, "Ethernet" }, + { 0x02, 0x01, 0x00, "Token Ring" }, + { 0x02, 0x02, 0x00, "FDDI" }, + { 0x02, 0x03, 0x00, "ATM" }, + { 0x02, 0x04, 0x00, "ISDN" }, + { 0x02, 0x80, 0x00, "Other" }, + + { 0x03, 0x00, 0x00, "VGA" }, + { 0x03, 0x00, 0x01, "VGA+8514" }, + { 0x03, 0x01, 0x00, "XGA" }, + { 0x03, 0x02, 0x00, "3D" }, + { 0x03, 0x80, 0x00, "VGA Other" }, + + { 0x04, 0x00, 0x00, "Video" }, + { 0x04, 0x01, 0x00, "Audio" }, + { 0x04, 0x02, 0x00, "Telephony" }, + { 0x04, 0x80, 0x00, "Other" }, + + { 0x05, 0x00, 0x00, "RAM" }, + { 0x05, 0x01, 0x00, "Flash" }, + { 0x05, 0x80, 0x00, "Other" }, + + { 0x06, 0x00, 0x00, "PCI to HOST" }, + { 0x06, 0x01, 0x00, "PCI to ISA" }, + { 0x06, 0x02, 0x00, "PCI to EISA" }, + { 0x06, 0x03, 0x00, "PCI to MCA" }, + { 0x06, 0x04, 0x00, "PCI to PCI" }, + { 0x06, 0x04, 0x01, "PCI to PCI (Subtractive Decode)" }, + { 0x06, 0x05, 0x00, "PCI to PCMCIA" }, + { 0x06, 0x06, 0x00, "PCI to NuBUS" }, + { 0x06, 0x07, 0x00, "PCI to Cardbus" }, + { 0x06, 0x08, 0x00, "PCI to RACEway" }, + { 0x06, 0x09, 0x00, "PCI to PCI" }, + { 0x06, 0x0A, 0x00, "PCI to InfiBand" }, + { 0x06, 0x80, 0x00, "PCI to Other" }, + + { 0x07, 0x00, 0x00, "Serial" }, + { 0x07, 0x00, 0x01, "Serial - 16450" }, + { 0x07, 0x00, 0x02, "Serial - 16550" }, + { 0x07, 0x00, 0x03, "Serial - 16650" }, + { 0x07, 0x00, 0x04, "Serial - 16750" }, + { 0x07, 0x00, 0x05, "Serial - 16850" }, + { 0x07, 0x00, 0x06, "Serial - 16950" }, + { 0x07, 0x01, 0x00, "Parallel" }, + { 0x07, 0x01, 0x01, "Parallel - BiDir" }, + { 0x07, 0x01, 0x02, "Parallel - ECP" }, + { 0x07, 0x01, 0x03, "Parallel - IEEE1284" }, + { 0x07, 0x01, 0xFE, "Parallel - IEEE1284 Target" }, + { 0x07, 0x02, 0x00, "Multiport Serial" }, + { 0x07, 0x03, 0x00, "Hayes Compatible Modem" }, + { 0x07, 0x03, 0x01, "Hayes Compatible Modem, 16450" }, + { 0x07, 0x03, 0x02, "Hayes Compatible Modem, 16550" }, + { 0x07, 0x03, 0x03, "Hayes Compatible Modem, 16650" }, + { 0x07, 0x03, 0x04, "Hayes Compatible Modem, 16750" }, + { 0x07, 0x80, 0x00, "Other" }, + + { 0x08, 0x00, 0x00, "PIC" }, + { 0x08, 0x00, 0x01, "ISA PIC" }, + { 0x08, 0x00, 0x02, "EISA PIC" }, + { 0x08, 0x00, 0x10, "I/O APIC" }, + { 0x08, 0x00, 0x20, "I/O(x) APIC" }, + { 0x08, 0x01, 0x00, "DMA" }, + { 0x08, 0x01, 0x01, "ISA DMA" }, + { 0x08, 0x01, 0x02, "EISA DMA" }, + { 0x08, 0x02, 0x00, "Timer" }, + { 0x08, 0x02, 0x01, "ISA Timer" }, + { 0x08, 0x02, 0x02, "EISA Timer" }, + { 0x08, 0x03, 0x00, "RTC" }, + { 0x08, 0x03, 0x00, "ISA RTC" }, + { 0x08, 0x03, 0x00, "Hot-Plug" }, + { 0x08, 0x80, 0x00, "Other" }, + + { 0x09, 0x00, 0x00, "Keyboard" }, + { 0x09, 0x01, 0x00, "Pen" }, + { 0x09, 0x02, 0x00, "Mouse" }, + { 0x09, 0x03, 0x00, "Scanner" }, + { 0x09, 0x04, 0x00, "Game Port" }, + { 0x09, 0x80, 0x00, "Other" }, + + { 0x0a, 0x00, 0x00, "Generic" }, + { 0x0a, 0x80, 0x00, "Other" }, + + { 0x0b, 0x00, 0x00, "386" }, + { 0x0b, 0x01, 0x00, "486" }, + { 0x0b, 0x02, 0x00, "Pentium" }, + { 0x0b, 0x03, 0x00, "PentiumPro" }, + { 0x0b, 0x10, 0x00, "DEC Alpha" }, + { 0x0b, 0x20, 0x00, "PowerPC" }, + { 0x0b, 0x30, 0x00, "MIPS" }, + { 0x0b, 0x40, 0x00, "Coprocessor" }, + { 0x0b, 0x80, 0x00, "Other" }, + + { 0x0c, 0x00, 0x00, "FireWire" }, + { 0x0c, 0x00, 0x10, "OHCI FireWire" }, + { 0x0c, 0x01, 0x00, "Access.bus" }, + { 0x0c, 0x02, 0x00, "SSA" }, + { 0x0c, 0x03, 0x00, "USB (UHCI)" }, + { 0x0c, 0x03, 0x10, "USB (OHCI)" }, + { 0x0c, 0x03, 0x80, "USB" }, + { 0x0c, 0x03, 0xFE, "USB Device" }, + { 0x0c, 0x04, 0x00, "Fiber" }, + { 0x0c, 0x05, 0x00, "SMBus Controller" }, + { 0x0c, 0x06, 0x00, "InfiniBand" }, + { 0x0c, 0x80, 0x00, "Other" }, + + { 0x0d, 0x00, 0x00, "iRDA" }, + { 0x0d, 0x01, 0x00, "Consumer IR" }, + { 0x0d, 0x10, 0x00, "RF" }, + { 0x0d, 0x80, 0x00, "Other" }, + + { 0x0e, 0x00, 0x00, "I2O" }, + { 0x0e, 0x80, 0x00, "Other" }, + + { 0x0f, 0x01, 0x00, "TV" }, + { 0x0f, 0x02, 0x00, "Audio" }, + { 0x0f, 0x03, 0x00, "Voice" }, + { 0x0f, 0x04, 0x00, "Data" }, + { 0x0f, 0x80, 0x00, "Other" }, + + { 0x10, 0x00, 0x00, "Network" }, + { 0x10, 0x10, 0x00, "Entertainment" }, + { 0x10, 0x80, 0x00, "Other" }, + + { 0x11, 0x00, 0x00, "DPIO Modules" }, + { 0x11, 0x01, 0x00, "Performance Counters" }, + { 0x11, 0x10, 0x00, "Comm Sync, Time+Frequency Measurement" }, + { 0x11, 0x80, 0x00, "Other" }, + + }; + +uInt32 pciRead(int bus,int dev,int func,int reg,int bytes) { + uInt16 base; + + union { + struct confadd c; + uInt32 n; + } u; + + u.n = 0; + u.c.enable = 1; + u.c.rsvd = 0; + u.c.bus = bus; + u.c.dev = dev; + u.c.func = func; + u.c.reg = reg & 0xFC; + + outportDWord(0xCF8, u.n); + + base = 0xCFC + (reg & 0x03); + + switch(bytes){ + case 1: return(inportByte(base)); + case 2: return(inportWord(base)); + case 4: return(inportDWord(base)); + default: return 0; + } + } + +void pciWrite(int bus,int dev,int func,int reg,uInt32 v,int bytes) { + uInt16 base; + + union { + struct confadd c; + uInt32 n; + } u; + + u.n = 0; + u.c.enable = 1; + u.c.rsvd = 0; + u.c.bus = bus; + u.c.dev = dev; + u.c.func = func; + u.c.reg = reg & 0xFC; + + base = 0xCFC + (reg & 0x03); + outportDWord(0xCF8, u.n); + switch(bytes){ + case 1: outportByte(base, (uInt8) v); break; + case 2: outportWord(base, (uInt16) v); break; + case 4: outportDWord(base, v); break; + } + } + + +bool pciProbe(int bus, int dev, int func,struct pciConfig *cfg) { + uInt32 *word = (uInt32 *) cfg; + uInt32 v; + int i; + for(i=0;i<4;i++) { + word[i] = pciRead(bus,dev,func,4*i,4); + } + if(cfg->vendorId == 0xffff) return FALSE; + if(cfg->vendorId == 0x0) return FALSE; /* Quick Hack */ + + cfg->bus = bus; + cfg->dev = dev; + cfg->func = func; + cfg->subsysVendor = pciRead(bus, dev, func, 0x2c, 2); + cfg->subsys = pciRead(bus, dev, func, 0x2e, 2); + kprintf("Device Info: /bus/pci/%d/%d/%d\n",bus,dev,func); + kprintf(" * Vendor: %X Device: %X Class/SubClass/Interface %X/%X/%X\n",cfg->vendorId,cfg->deviceId,cfg->baseClass,cfg->subClass,cfg->interface); + kprintf(" * Status: %X Command: %X BIST/Type/Lat/CLS: %X/%X/%X/%X\n",cfg->status, cfg->command, cfg->bist, cfg->headerType,cfg->latencyTimer, cfg->cacheLineSize); + switch(cfg->headerType & 0x7F){ + case 0: /* normal device */ + for(i=0;i<6;i++) { + v = pciRead(bus,dev,func,i*4 + 0x10, 4); + if(v) { + int v2; + pciWrite(bus,dev,func,i*4 + 0x10, 0xffffffff, 4); + v2 = pciRead(bus,dev,func,i*4+0x10, 4) & 0xfffffff0; + pciWrite(bus,dev,func,i*4 + 0x10, v, 4); + v2 = 1 + ~v2; + if(v & 1) { + cfg->base[i] = v & 0xffff; + cfg->size[i] = v2 & 0xffff; + } + else { + cfg->base[i] = v; + cfg->size[i] = v2; + } + } + else { + cfg->base[i] = 0; + cfg->size[i] = 0; + } + } + v = pciRead(bus,dev,func,0x3c,1); + cfg->irq = (v == 0xff ? 0 : v); + break; + case 1: + kprintf(" * PCI <-> PCI Bridge\n"); + break; + default: + kprintf(" * Unknown Header Type\n"); + break; + } + + return(TRUE); + } + +int pciInit() { + uInt16 bus,dev,func; + int i = 0x0; + struct pciConfig pcfg; + for (bus = 0; bus < 255; bus++) { + for (dev = 0; dev < 32; dev++) { + for (func = 0; func < 8; func++) { + if (pciProbe(bus, dev, func, &pcfg) == TRUE) { + /* kprintf(" * Vendor: %X Device: %X Class/SubClass/Interface %X/%X/%X\n",pcfg.vendorId,pcfg.deviceId,pcfg.baseClass,pcfg.subClass,pcfg.interface); */ + for (i=0x0;i +#include +#include + +extern "C" { + #include + #include + #include + #include + #include + #include + #include + } + +extern "C" { +void sdeTestThread() { +// uInt32 count, i = 0x0; + uInt8 r, g, b; + ogSurface *screen = 0x0; + ogPoint2d points[4]; + ogRGBA8 colours[4]; + r = g = b = 0; + while (screen == 0x0) { + screen = (ogDisplay_UbixOS *)systemVitals->screen; + } + while (!screen->Avail()); + + points[0].x = screen->GetMaxX() - 150; + points[0].y = 0; + points[1].x = screen->GetMaxX(); + points[1].y = 0; + points[2].x = screen->GetMaxX(); + points[2].y = 150; + points[3].x = screen->GetMaxX() - 250; + points[3].y = 250; + + colours[0].red = 255; + colours[0].green = 0; + colours[0].blue = 0; + colours[0].alpha = 255; + colours[1].red = 0; + colours[1].green = 255; + colours[1].blue = 128; + colours[1].alpha = 255; + colours[2].red = 128; + colours[2].green = 255; + colours[2].blue = 128; + colours[2].alpha = 255; + colours[3].red = 63; + colours[3].green = 63; + colours[3].blue = 63; + colours[3].alpha = 255; + screen->SetAntiAliasing(true); + + while (true) { +#if 0 + for (count = 150; count > 0; count--) { + screen->Line(screen->GetMaxX() / 2, screen->GetMaxY() / 2, + screen->GetMaxX(), count*8, + screen->RGB(r, g, b)); + screen->FillCircle(screen->GetMaxX() - 50, 50, count, + screen->RGB(r, g, b)); + +// screen->FillRect(screen->GetMaxX() - 50 - count, count, +// screen->GetMaxX() - count, 100 - count, +// screen->RGB(r, g, b)); + r -= 8; + g += 8; + b -= 8; + } // for +#endif + screen->FillGouraudPolygon(4, points, colours); + //kprintf("colours(0)[0x%X]\n",colours[0]); + colours[0].red -= 8; + colours[0].green += 8; + colours[0].blue -= 8; + colours[1].red += 8; + colours[1].green += 8; + colours[1].blue -= 8; + colours[2].red += 8; + colours[2].green -= 8; + colours[2].blue += 8; + colours[3].red += 8; + colours[3].green += 8; + colours[3].blue += 8; + + } // while + +} // sdeTestThread + +} + +/*** + END + ***/ + diff --git a/src/sys/sde/main.cc b/src/sys/sde/main.cc new file mode 100644 index 0000000..663316d --- /dev/null +++ b/src/sys/sde/main.cc @@ -0,0 +1,130 @@ +/***************************************************************************************** + 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. + + $Log$ + Revision 1.29 2004/04/13 16:36:33 reddawg + Changed our copyright, it is all now under a BSD-Style license + + + + $Id$ + +*****************************************************************************************/ + +extern "C" { + #include + #include + #include + #include + #include + } + +#include +#include +#include +#include + +extern "C" void sdeThread() { + ogSurface *screen = new ogDisplay_UbixOS(); + struct sdeWindows *tmp = 0x0; + ogSurface *buf = 0x0; + ogBitFont * font = new ogBitFont(); + + + font->Load("ROM8X14.DPF",0); + font->SetFGColor(255, 255, 255, 255); + font->SetBGColor(0, 0, 0, 255); + + printOff = 0x1; + + screen->Create(800,600,OG_PIXFMT_16BPP); + screen->Clear(screen->Pack(122,140,163)); + + systemVitals->screen = screen; + systemVitals->font = font; + + ogprintOff = (int)0x0; + + screen->SetAntiAliasing(false); + + while (1) { + for (tmp = windows;tmp;tmp=tmp->next) { + switch (tmp->status) { + case registerWindow: + buf = (ogSurface *)tmp->buf; + buf->buffer = (void *)vmmMapFromTask(tmp->pid,buf->buffer,buf->bSize); + if (buf->buffer == 0x0) { + kprintf("Error: buf->buffer\n"); + while (1); + } + buf->lineOfs = (uInt32 *)vmmMapFromTask(tmp->pid,buf->lineOfs,buf->lSize); + if (buf->lineOfs == 0x0) { + kprintf("Error: buf->lineOfs\n"); + while (1); + } + tmp->status = windowReady; + //kprintf("Window Registered!\n"); + break; + case drawWindow: + buf = (ogSurface *)tmp->buf; + screen->CopyBuf(screen->GetMaxX() - buf->GetMaxX(), + screen->GetMaxY() - buf->GetMaxY(), *buf,0, 0, + buf->GetMaxX(), buf->GetMaxY()); + tmp->status = windowReady; + //kprintf("Draw Window Routines Here\n"); + break; + case killWindow: + //kprintf("Killed Window\n"); + if (tmp->next != 0x0) { + tmp->next->prev = tmp->prev; + if (tmp->prev != 0x0) + tmp->prev->next = tmp->next; + } + else if (tmp->prev != 0x0) { + tmp->prev->next = tmp->next; + if (tmp->next != 0x0) + tmp->next->prev = tmp->prev; + } + else { + windows = 0x0; + } + vmmUnmapPages(buf->buffer,buf->bSize); + vmmUnmapPages(buf->lineOfs,buf->lSize); + // kfree(tmp->buf); + kfree(tmp); + tmp = 0x0; + break; + default: + break; + } + } + //sched_yield(); + } + } + +/*** + END + ***/ + diff --git a/src/sys/sde/ogDisplay_UbixOS.cc b/src/sys/sde/ogDisplay_UbixOS.cc new file mode 100755 index 0000000..a325977 --- /dev/null +++ b/src/sys/sde/ogDisplay_UbixOS.cc @@ -0,0 +1,315 @@ +/***************************************************************************************** + 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. + + $Log$ + Revision 1.20 2004/04/13 16:36:33 reddawg + Changed our copyright, it is all now under a BSD-Style license + + + + $Id$ + +*****************************************************************************************/ + +#include +#include +#include + +extern "C" { + #include + #include + #include + #include + #include + #include + } + +/* + * + * ogDisplay methods + * + */ + +void +initVESAMode(uInt16 mode) { + //kprintf("Pre-initVESAMode\n"); + biosCall(0x10,0x4F02,mode,0x0,0x0,0x0,0x0,0x0,0x0); + //kprintf("Post-initVESAMode\n"); + return; +} + +ogDisplay_UbixOS::ogDisplay_UbixOS(void) { + pages[0] = pages[1] = NULL; + activePage = visualPage = 0; + pal = new ogRGBA8[256]; + attributes = new ogAttributes(); + + VESAInfo = (ogVESAInfo *)0x11000; + modeInfo = (ogModeInfo *)0x11200; + GetVESAInfo(); + return; +} // ogDisplay_UbixOS::ogDisplay_UbixOS + +void +ogDisplay_UbixOS::GetModeInfo(uInt16 mode) { + //kprintf("Pre-getModeInfo\n"); + biosCall(0x10,0x4F01,0x0,mode,0x0,0x0,0x0,0x1120,0x0); + //kprintf("Post-getModeInfo\n"); + return; +} // ogDisplay_UbixOS::GetModeInfo + +void +ogDisplay_UbixOS::GetVESAInfo(void) { + VESAInfo->VBESignature[0] = 'V'; // First off initialize the structure. + VESAInfo->VBESignature[1] = 'B'; + VESAInfo->VBESignature[2] = 'E'; + VESAInfo->VBESignature[3] = '2'; + //kprintf("Pre-getVESAInfo\n"); + biosCall(0x10,0x4F00,0x0,0x0,0x0,0x0,0x0,0x1100,0x0); + //kprintf("Post-getVESAInfo\n"); + return; + } // ogDisplay_UbixOS::GetVESAInfo + +uInt16 +ogDisplay_UbixOS::FindMode(uInt32 _xRes, uInt32 _yRes, uInt32 _BPP) { + uInt16 mode; + + if ((320 == _xRes) && (200 == _yRes) && (8 == _BPP)) return 0x13; + +// if ((VESAInfo==NULL) || (VESAInfo->videoModePtr==NULL)) return 0; + if (NULL == modeInfo) return 0; + + for (mode = 0x100; mode < 0x1FF; mode++) { + GetModeInfo(mode); + if ((modeInfo->xRes >= _xRes) && (modeInfo->yRes >= _yRes) && + (modeInfo->bitsPerPixel == _BPP)) + return mode; + } + + return 0; +} // ogDisplay_UbixOS::FindMode + +void ogDisplay_UbixOS::SetMode(uInt16 mode) { + + uInt32 size = 0x0, count = 0x0, i = 0x0; + + if (mode==0x13) { + + xRes = 320; + yRes = 200; + maxX = 319; + maxY = 199; + BPP = 8; + bytesPerPix = 1; + + redFieldPosition = 0; + greenFieldPosition = 0; + blueFieldPosition = 0; + alphaFieldPosition = 0; + + redShifter = 0; + greenShifter = 0; + blueShifter = 0; + alphaFieldPosition = 0; + + // UBU, THIS IS NULL BECAUSE WE DON'T EVER USE 320x200x256c! + // THIS COMMENT WILL COME BACK TO BITE YOU ON THE ASS + buffer = NULL; + + } else { + buffer = NULL; + mode |= 0x4000; // attempt lfb + GetModeInfo(mode); + if (modeInfo->physBasePtr == 0) return; + buffer = (void *)modeInfo->physBasePtr; + size = (modeInfo->yRes*modeInfo->bytesPerLine+4095); + + xRes = modeInfo->bytesPerLine; + yRes = modeInfo->yRes; + maxX = modeInfo->xRes-1; + maxY = yRes-1; + + BPP = modeInfo->bitsPerPixel; + bytesPerPix = (BPP + 7) >> 3; + + redFieldPosition = modeInfo->redFieldPosition; + greenFieldPosition = modeInfo->greenFieldPosition; + blueFieldPosition = modeInfo->blueFieldPosition; + alphaFieldPosition = modeInfo->alphaFieldPosition; + + if (4 == bytesPerPix) { + modeInfo->alphaMaskSize = 8; + while ((alphaFieldPosition == redFieldPosition) || + (alphaFieldPosition == greenFieldPosition) || + (alphaFieldPosition == blueFieldPosition)) + alphaFieldPosition += 8; + } // if + + redShifter = 8-modeInfo->redMaskSize; + greenShifter = 8-modeInfo->greenMaskSize; + blueShifter = 8-modeInfo->blueMaskSize; + alphaShifter = 8-modeInfo->alphaMaskSize; + + if (modeInfo->alphaMaskSize != 0) + alphaMasker = ~(OG_MASKS[modeInfo->alphaMaskSize] << alphaFieldPosition); + else + alphaMasker = ~0; + + } // else not mode 0x13 + + printOff = 0; + for (i = 0x0; i < ((size)/4096); i++) { + vmmRemapPage(modeInfo->physBasePtr + (i * 0x1000), + modeInfo->physBasePtr + (i * 0x1000)); + } // for i + + owner = this; + dataState = ogAliasing; + + initVESAMode(mode); + + if ((lineOfs!=NULL) && (lSize!=0)) delete [] lineOfs; + lSize = yRes*sizeof(uInt32); + lineOfs = new uInt32[yRes];; + if (NULL == lineOfs) return; + + lineOfs[0] = 0; + for (count = 1; count < yRes; count++) + lineOfs[count] = lineOfs[count-1]+xRes; + + if (1 == bytesPerPix) { + pixFmtID = 0x08080808; + } else { + pixFmtID = (redFieldPosition) | + (greenFieldPosition << 8) | + (blueFieldPosition << 16) | + (alphaFieldPosition << 24); + } // else + + SetAntiAliasing(BPP > 8); + if (NULL == pal) pal = new ogRGBA8[256]; + SetPalette(DEFAULT_PALETTE); + + return; +} // ogDisplay_UbixOS::SetMode + +void +ogDisplay_UbixOS::SetPalette(const ogRGBA8 newPal[256]) { + ogSurface::SetPalette(newPal); + SetPal(); + return; +} // ogDisplay_UbixOS::SetPalette + +void ogDisplay_UbixOS::SetPal(void) { + if (bytesPerPix != 1) return; + outportByte(0x3c8,0); + for (uInt32 c = 0; c < 256; c++) { + outportByte(0x3c9, pal[c].red >> 2); + outportByte(0x3c9, pal[c].green >> 2); + outportByte(0x3c9, pal[c].blue >> 2); + } // for + return; +} // ogDisplay_UbixOS::SetPal + +bool +ogDisplay_UbixOS::Alias(ogSurface& SrcObject, uInt32 x1, + uInt32 y1, uInt32 x2, uInt32 y2) { + SetLastError(ogNoAliasing); + return false; +} // ogDisplay_UbixOS::Alias + +bool +ogDisplay_UbixOS::Create(uInt32 _xRes, uInt32 _yRes,ogPixelFmt _pixFormat) { + uInt16 mode; + mode = 0x114; // was 0x111 + SetMode(mode); + /* + mode = FindMode(_xRes, _yRes, _pixFormat.BPP); + if ((mode == 0) && ((_pixFormat.BPP==24) || (_pixFormat.BPP==32))) { + if (_pixFormat.BPP==24) _pixFormat.BPP=32; else _pixFormat.BPP=24; + mode=FindMode(_xRes,_yRes,_pixFormat.BPP); + } // if + if (mode!=0) SetMode(mode); + */ + return (mode!=0); +} // ogDisplay_UbixOS::Create + +bool +ogDisplay_UbixOS::Clone(ogSurface& SrcObject) { + SetLastError(ogNoCloning); + return false; +} // ogDisplay_UbixOS::Clone + +void +ogDisplay_UbixOS::CopyPalette(ogSurface& SrcObject) { + ogSurface::CopyPalette(SrcObject); + SetPal(); + return; +} // ogDisplay_UbixOS::CopyPalette + +bool +ogDisplay_UbixOS::LoadPalette(const char *palfile) { + bool result; + if ((result = ogSurface::LoadPalette(palfile))==true) SetPal(); + return result; +} // ogDisplay_UbixOS::LoadPalette + +void +ogDisplay_UbixOS::SetPalette(uInt8 colour, uInt8 red, uInt8 green, uInt8 blue) { + if (NULL == pal) return; + ogSurface::SetPalette(colour, red, green, blue); + outportByte(0x3c8, colour); + outportByte(0x3c9, red >> 2); + outportByte(0x3c9, green >> 2); + outportByte(0x3c9, blue >> 2); + + return; +} // ogDisplay_UbixOS::SetPalette + +void +ogDisplay_UbixOS::SetPalette(uInt8 colour, uInt8 red, uInt8 green, + uInt8 blue, uInt8 alpha) { + if (NULL == pal) return; + ogSurface::SetPalette(colour, red, green, blue, alpha); + outportByte(0x3c8, colour); + outportByte(0x3c9, red >> 2); + outportByte(0x3c9, green >> 2); + outportByte(0x3c9, blue >> 2); + + return; +} // ogDisplay_UbixOS::SetPalette + +ogDisplay_UbixOS::~ogDisplay_UbixOS(void) { + delete attributes; + delete pal; +//mji delete VESAInfo; +//mji delete modeInfo; + return; +} // ogDisplay_UbixOS::~ogDisplay_UbixOS + +/*** + END + ***/ + diff --git a/src/sys/sde/sde.cc b/src/sys/sde/sde.cc new file mode 100644 index 0000000..1f42094 --- /dev/null +++ b/src/sys/sde/sde.cc @@ -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. + + $Log$ + Revision 1.12 2004/04/13 16:36:33 reddawg + Changed our copyright, it is all now under a BSD-Style license + + + + $Id$ + +*****************************************************************************************/ + +extern "C" { + #include + #include + #include + #include + #include + #include + #include + #include +} +#include + +struct sdeWindows *windows = 0x0; + +extern "C" void sysSDE(uInt32 cmd,void *ptr) { + ogSurface *newBuf = 0x0; + ogSurface *oldBuf = (ogSurface *)ptr; + struct sdeWindows *tmp = 0x0; + + for (tmp=windows;tmp;tmp=tmp->next) { + if (tmp->pid == (int)_current->id) + break; + } + + if (tmp != 0x0) { + while (tmp->status != windowReady) + asm("hlt"); + //sched_yield(); + } + else if (tmp == 0x0 && cmd != registerWindow) { + kprintf("Invalid Window\n"); + return; + } + + switch (cmd) { + case drawWindow: + tmp->status = drawWindow; + while (tmp->status != windowReady) { + sched(); + //asm("hlt"); + } + break; + case killWindow: + tmp->status = killWindow; + break; + case registerWindow: + if (oldBuf->buffer != 0x0) { + newBuf = new ogSurface(); + newBuf->version = oldBuf->version; + newBuf->buffer = oldBuf->buffer; + newBuf->owner = oldBuf->owner; + newBuf->lineOfs = oldBuf->lineOfs; + newBuf->pal = oldBuf->pal; + newBuf->attributes = oldBuf->attributes; + newBuf->xRes = oldBuf->xRes; + newBuf->yRes = oldBuf->yRes; + newBuf->maxX = oldBuf->maxX; + newBuf->maxY = oldBuf->maxY; + newBuf->bSize = oldBuf->bSize; + newBuf->lSize = oldBuf->lSize; + newBuf->BPP = oldBuf->BPP; + newBuf->bytesPerPix = oldBuf->bytesPerPix; + newBuf->pixFmtID = oldBuf->pixFmtID; + newBuf->redFieldPosition = oldBuf->redFieldPosition; + newBuf->greenFieldPosition = oldBuf->greenFieldPosition; + newBuf->blueFieldPosition = oldBuf->blueFieldPosition; + newBuf->alphaFieldPosition = oldBuf->alphaFieldPosition; + newBuf->redShifter = oldBuf->redShifter; + newBuf->greenShifter = oldBuf->greenShifter; + newBuf->blueShifter = oldBuf->blueShifter; + newBuf->alphaShifter = oldBuf->alphaShifter; + newBuf->lastError = oldBuf->lastError; + newBuf->dataState = oldBuf->dataState; + tmp = (struct sdeWindows *)kmalloc(sizeof(struct sdeWindows),sysID); + tmp->buf = newBuf; + tmp->status = registerWindow; + tmp->pid = _current->id; + tmp->prev = 0x0; + if (windows == 0x0) { + windows = tmp; + tmp->next = 0x0; + } + else { + tmp->next = windows; + windows->prev = tmp; + windows = tmp; + } + } + else { + kprintf("Invalid Window\n"); + } + break; + default: + kprintf("Invalid SDE Command [0x%X]\n",ptr); + break; + } + return; + } + +/*** + END + ***/ + diff --git a/src/sys/sys/Makefile b/src/sys/sys/Makefile new file mode 100644 index 0000000..aeb4109 --- /dev/null +++ b/src/sys/sys/Makefile @@ -0,0 +1,27 @@ +# (C) 2002 The UbixOS Project +# $Id$ + +# Include Global 'Source' Options +include ../../Makefile.inc +include ../Makefile.inc + +# Objects +OBJS = dma.o drives.o idt.o io.o video.o + +all: $(OBJS) + +# Compile Types +.cc.o: + $(CXX) ${CFLAGS} -Wall -fomit-frame-pointer -O -I../include -c -o $@ $< +.cc.s: + $(CXX) ${CFLAGS} -Wall -fomit-frame-pointer -O -I../include -S -o $@ $< +.c.o: + $(CC) ${CFLAGS} -Wall -fomit-frame-pointer -O -I../include -c -o $@ $< +.c.s: + $(CC) ${CFLAGS} -Wall -fomit-frame-pointer -O -I../include -S -o $@ $< +.S.o: + $(CC) ${CFLAGS} -Wall -fomit-frame-pointer -c -o $@ $< + +# Clean up the junk +clean: + $(REMOVE) $(OBJS) diff --git a/src/sys/sys/dma.c b/src/sys/sys/dma.c new file mode 100644 index 0000000..2dbe6d0 --- /dev/null +++ b/src/sys/sys/dma.c @@ -0,0 +1,82 @@ +/***************************************************************************************** + 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. + + $Log$ + Revision 1.2 2004/04/13 16:36:34 reddawg + Changed our copyright, it is all now under a BSD-Style license + + + + $Id$ + +*****************************************************************************************/ + +#include +#include +#include + +#define lowByte(x) (x & 0x00FF) +#define highByte(x) ((x & 0xFF00) >> 8) + +uChar maskReg[8] = { 0x0A, 0x0A, 0x0A, 0x0A, 0xD4, 0xD4, 0xD4, 0xD4 }; +uChar clearReg[8] = { 0x0C, 0x0C, 0x0C, 0x0C, 0xD8, 0xD8, 0xD8, 0xD8 }; +uChar modeReg[8] = { 0x0B, 0x0B, 0x0B, 0x0B, 0xD6, 0xD6, 0xD6, 0xD6 }; +uChar addrPort[8] = { 0x00, 0x02, 0x04, 0x06, 0xC0, 0xC4, 0xC8, 0xCC }; +uChar pagePort[8] = { 0x87, 0x83, 0x81, 0x82, 0x8F, 0x8B, 0x89, 0x8A }; +uChar countPort[8] = { 0x01, 0x03, 0x05, 0x07, 0xC2, 0xC6, 0xCA, 0xCE }; + +void dmaXfer(uChar channel,uLong address,uInt length,uChar read) { + unsigned char page=0, mode=0; + unsigned int offset = 0; + if (read) { + mode = 0x48 + channel; + } + else { + mode = 0x44 + channel; + } + page = address >> 16; + offset = address & 0xFFFF; + length--; + _dmaXfer(channel, page, offset, length, mode); + } + +void _dmaXfer(uChar dmaChannel,uChar page,uInt offset,uInt length,uChar mode) { + asm("cli"); + outportByte(maskReg[dmaChannel], 0x04 | dmaChannel); + outportByte(clearReg[dmaChannel], 0x00); + outportByte(modeReg[dmaChannel], mode); + outportByte(addrPort[dmaChannel], lowByte(offset)); + outportByte(addrPort[dmaChannel], highByte(offset)); + outportByte(pagePort[dmaChannel], page); + outportByte(countPort[dmaChannel], lowByte(length)); + outportByte(countPort[dmaChannel], highByte(length)); + outportByte(maskReg[dmaChannel], dmaChannel); + asm("sti"); + } + +/*** + END + ***/ + diff --git a/src/sys/sys/drives.c b/src/sys/sys/drives.c new file mode 100644 index 0000000..472e21b --- /dev/null +++ b/src/sys/sys/drives.c @@ -0,0 +1,75 @@ +/***************************************************************************************** + 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. + + $Log$ + Revision 1.2 2004/04/13 16:36:34 reddawg + Changed our copyright, it is all now under a BSD-Style license + + + + $Id$ + +*****************************************************************************************/ + +#include +#include +#include + +struct driveDriver *drives = 0x0; +int currentDrive = 0x0; + +void addDrive(int id,char type,void *driveInfoStruct,void *read,void *write,void *reset) { + struct driveDriver *tmp = 0x0; + tmp = (struct driveDriver *)kmalloc(sizeof(struct driveDriver),-2); + tmp->driveInfoStruct = driveInfoStruct; + tmp->read = read; + tmp->write = write; + tmp->reset = reset; + tmp->id = id; + tmp->driveType = type; + if (!drives) { + tmp->next = 0x0; + tmp->prev = 0x0; + drives = tmp; + } + else { + tmp->next = drives; + tmp->prev = 0x0; + drives = tmp; + } + } + +struct driveDriver *findDrive(int id) { + struct driveDriver *tmp = 0x0; + for (tmp = drives;tmp;tmp=tmp->next) { + if (tmp->id == id) return(tmp); + } + return(0x0); + } + +/*** + END + ***/ + diff --git a/src/sys/sys/idt.c b/src/sys/sys/idt.c new file mode 100644 index 0000000..f8f814b --- /dev/null +++ b/src/sys/sys/idt.c @@ -0,0 +1,563 @@ +/***************************************************************************************** + 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. + + $Log$ + Revision 1.29 2004/04/13 16:36:34 reddawg + Changed our copyright, it is all now under a BSD-Style license + + + + $Id$ + +*****************************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define FP_TO_LINEAR(seg, off) ((void*) ((((uInt16) (seg)) << 4) + ((uInt16) (off)))) + +void mathStateRestore(); + +descriptorTable(IDT, 256) +{ +}; + +struct { + unsigned short limit __attribute__((packed)); + union descriptorTableunion *idt __attribute__((packed)); +} loadidt = { + + (256 * sizeof(union descriptorTableunion) - 1), IDT +}; + +/************************************************************************ + +Function: int idtInit() + +Description: This function is used to enable our IDT subsystem + +Notes: + +02/20/2004 - Approved for quality + +************************************************************************/ +int +idtInit() +{ + int i = 0x0; + + struct tssStruct *gpfTSS = (struct tssStruct *)0x4200; + + /* Set up default vector table for all possible 256 interrupts */ + for (i = 0x0; i < 256; i++) { + setVector(&intNull, i, dPresent + dInt + dDpl3); + } + + /* Load the IDT into the system */ + asm( + "cli\n" + "lidt (%0) \n" /* Load the IDT */ + "pushfl \n" /* Clear the NT flag */ + "andl $0xffffbfff,(%%esp) \n" + "popfl \n" + "sti \n" +: +: "r"((char *)&loadidt) + ); + + /* Set up the basic vectors for the reserved ints */ + setVector(&_int0, 0, dPresent + dTrap + dDpl3); + setVector(&_int1, 1, dPresent + dTrap + dDpl3); + setVector(&_int2, 2, dPresent + dTrap + dDpl3); + setVector(&_int3, 3, dPresent + dTrap + dDpl3); + setVector(&_int4, 4, dPresent + dTrap + dDpl3); + setVector(&_int5, 5, dPresent + dTrap + dDpl3); + setVector(&_int6, 6, dPresent + dTrap + dDpl3); + setVector(&_int7,7,dPresent + dTrap + dDpl3); + /* setVector(&_int8,8,dPresent + dTrap + dDpl3); */ + /* setTaskVector(8,dPresent + dTask + dDpl3,0x20); */ + setVector(&_int9, 9, dPresent + dTrap + dDpl3); + setVector(&_int10, 10, dPresent + dTrap + dDpl3); + setVector(&_int11, 11, dPresent + dTrap + dDpl3); + setVector(&_int12, 12, dPresent + dTrap + dDpl3); + /* setVector(&_int13,13,dPresent + dTrap + dDpl3); */ + setTaskVector(13, dPresent + dTask + dDpl3, 0x38); + setVector(&_vmmPageFault, 14, dPresent + dTrap + dDpl3); + setVector(&_sysCall, 128, dPresent + dTrap + dDpl3); + setVector(&timerInt, 0x68, (dInt + dPresent + dDpl3)); +// setVector(&sched,0x69,(dInt + dPresent + dDpl3)); + + + gpfTSS->back_link = 0x0; + gpfTSS->esp0 = 0x0;//(uInt32)kmalloc(4096,sysID)+4096; + gpfTSS->ss0 = 0x0;//0x10; + gpfTSS->esp1 = 0x0; + gpfTSS->ss1 = 0x0; + gpfTSS->esp2 = 0x0; + gpfTSS->ss2 = 0x0; + gpfTSS->cr3 = (unsigned int)kernelPageDirectory; + gpfTSS->eip = (unsigned int)&_int13; + gpfTSS->eflags = 0x206; + gpfTSS->esp = 0x1CFFF; + gpfTSS->ebp = 0x1CFFF; + gpfTSS->esi = 0x0; + gpfTSS->edi = 0x0; + gpfTSS->es = 0x10; + gpfTSS->cs = 0x08; + gpfTSS->ss = 0x10; + gpfTSS->ds = 0x10; + gpfTSS->fs = 0x10; + gpfTSS->gs = 0x10; + gpfTSS->ldt = 0x0; + gpfTSS->trace_bitmap = 0x0000; + gpfTSS->io_map = 0x8000; + + + /* Print out information for the IDT */ + kprintf("idt0 - Address: [0x%X]\n", &IDT); + + /* Return so we know all went well */ + return (0x0); +} + + +/* Sets Up IDT Vector */ +void +setVector(void *handler, unsigned char interrupt, unsigned short controlMajor) +{ + unsigned short codesegment = 0x08; + asm volatile ("movw %%cs,%0":"=g" (codesegment)); + + IDT[interrupt].gate.offsetLow = (unsigned short)(((unsigned long)handler) & 0xffff); + IDT[interrupt].gate.selector = codesegment; + IDT[interrupt].gate.access = controlMajor; + IDT[interrupt].gate.offsetHigh = (unsigned short)(((unsigned long)handler) >> 16); +} + +/************************************************************************ + +Function: void setTaskVector(uInt8,uInt16,uInt8); +Description: This Function Sets Up An IDT Task Vector +Notes: + +************************************************************************/ +void +setTaskVector(uInt8 interrupt, uInt16 controlMajor, uInt8 selector) +{ + uInt16 codesegment = 0x08; + asm volatile ("movw %%cs,%0":"=g" (codesegment)); + + IDT[interrupt].gate.offsetLow = 0x0; + IDT[interrupt].gate.selector = selector; + IDT[interrupt].gate.access = controlMajor; + IDT[interrupt].gate.offsetHigh = 0x0; +} + + +/* Null Intterupt Descriptor */ +void +intNull() +{ + kprintf("Woot Invalid Interrupt[%i]\n",_current->id); + + /* + * freeProcessPages(_current->id); setTaskStatus(_current->id, EXITING); + * _current->status = EMPTY; sched(); + */ + _current->state = DEAD; + sched(); + while (1); + return; +} + +void +_int0() +{ + kprintf("int0: Divide-by-Zero\n"); + + /* + * freeProcessPages(_current->id); setTaskStatus(_current->id, EXITING); + * _current->status = EMPTY; schede(); + */ + while (1); +} +void +_int1() +{ + kprintf("int1: Debug exception\n"); + + /* + * freeProcessPages(_current->id); setTaskStatus(_current->id, EXITING); + * _current->status = EMPTY; sched(); + */ + while (1); +} +void +_int2() +{ + kprintf("int2: unknown error\n"); + + /* + * freeProcessPages(_current->id); setTaskStatus(_current->id, EXITING); + * _current->status = EMPTY; sched(); + */ + while (1); +} +void +_int3() +{ + kprintf("int3: Breakpoint\n"); + + /* + * freeProcessPages(_current->id); setTaskStatus(_current->id, EXITING); + * _current->status = EMPTY; sched(); + */ + while (1); +} +void +_int4() +{ + kprintf("int4: Overflow\n"); + + /* + * freeProcessPages(_current->id); setTaskStatus(_current->id, EXITING); + * _current->status = EMPTY; sched(); + */ + while (1); +} +void +_int5() +{ + kprintf("int5: Bounds check\n"); + + /* + * freeProcessPages(_current->id); setTaskStatus(_current->id, EXITING); + * _current->status = EMPTY; sched(); + */ + while (1); +} +void +_int6() +{ + kprintf("int6: Invalid opcode!\n"); + + /* + * freeProcessPages(_current->id); setTaskStatus(_current->id, EXITING); + * _current->status = EMPTY; sched(); + */ + while (1); +} + +void +_int8() +{ + kprintf("int8: Double Fault!\n"); + while (1); +} + +void +_int9() +{ + kprintf("int9: Coprocessor Segment Overrun!\n"); + while (1); +} + +void +_int10() +{ + kprintf("int10: Invalid TSS!\n"); + while (1); +} + +void +_int11() +{ + kprintf("int11: Segment Not Present!\n"); + while (1); +} + +void +_int12() +{ + kprintf("int12: Stack-Segment Fault!\n"); + while (1); +} + +/* + * void _int13() { kprintf("int13: General Protection Fault!\n"); + * kprintf("Task Id: [%i]\n",_current->id); while(1); } + */ + +void +_int13() +{ + uInt8 *ip = 0x0; + uInt16 *stack = 0x0, *ivt = 0x0; + uInt32 *stack32 = 0x0; + bool isOperand32 = FALSE, isAddress32 = FALSE; + + irqDisable(0x0); + + ip = FP_TO_LINEAR(_current->tss.cs, _current->tss.eip); + ivt = (uInt16 *) 0x0; + stack = (uInt16 *) FP_TO_LINEAR(_current->tss.ss,_current->tss.esp); + stack32 = (uInt32 *) stack; + + //kprintf("_current->tss.cs: [0x%X:0x%X:0x%X:0x%X]\n",_current->tss.cs,_current->tss.eip,_current->id,_current->tss.ss); + //kprintf("\n\nSS: [0x%X]\n",_current->tss.eflags); + +gpfStart: + + //kprintf("ip[0]: 0x%X:0x%X\n",ip,ip[0]); + //kprintf("IP: [0x%X][0x%X][0x%X][0x%X][0x%X]\n",ip,ip[0],ip[1],ip[2],ip[3]); + switch (ip[0]) { + case 0xCD: /* INT n */ + switch (ip[1]) { + case 0x69: + kprintf("Exit Bios [0x%X]\n",_current->id); + _current->state = DEAD; + break; + case 0x20: + case 0x21: + kprintf("Help!!!\n"); + while (1); + break; + default: + stack -= 3; + _current->tss.esp = ((_current->tss.esp & 0xffff) - 6) & 0xffff; + stack[0] = (uInt16) (_current->tss.eip + 2); + stack[1] = _current->tss.cs; stack[2] = (uInt16) _current->tss.eflags; + if (_current->oInfo.v86If) + stack[2] |= EFLAG_IF; + else + stack[2] &= ~EFLAG_IF; + _current->tss.cs = ivt[ip[1] * 2 + 1] & 0xFFFF; + _current->tss.eip = ivt[ip[1] * 2] & 0xFFFF; + //kprintf("New Int [0x%X][0x%X][0x%X][0x%X]\n",ip[1],_current->tss.cs,_current->tss.eip,_current->id); + //while(1); + break; + } + break; + case 0x66: + isOperand32 = TRUE; + ip++; + _current->tss.eip = (uInt16) (_current->tss.eip + 1); + goto gpfStart; + break; + case 0x67: + isAddress32 = TRUE; + ip++; + _current->tss.eip = (uInt16) (_current->tss.eip + 1); + goto gpfStart; + break; + case 0xF0: + _current->tss.eip = (uInt16) (_current->tss.eip + 1); + kprintf("No!!!\n"); + while (1); + break; + case 0x9C: + if (isOperand32 == TRUE) { + _current->tss.esp = ((_current->tss.esp & 0xffff) - 4) & 0xffff; + stack32--; + stack32[0] = _current->tss.eflags & 0xDFF; + if (_current->oInfo.v86If == TRUE) + stack32[0] |= EFLAG_IF; + else stack32[0] &= ~EFLAG_IF; + } else { + _current->tss.esp = ((_current->tss.esp & 0xffff) - 2) & 0xffff; + stack--; + + stack[0] = (uInt16) _current->tss.eflags; + if (_current->oInfo.v86If == TRUE) stack[0] |= EFLAG_IF; + else stack[0] &= ~EFLAG_IF; + _current->tss.eip = (uInt16) (_current->tss.eip + 1); + + } + break; + case 0x9D: + if (isOperand32 == TRUE) { + _current->tss.eflags = EFLAG_IF | EFLAG_VM | (stack32[0] & 0xDFF); + _current->oInfo.v86If = (stack32[0] & EFLAG_IF) != 0; + _current->tss.esp = ((_current->tss.esp & 0xffff) + 4) & 0xffff; + } else { + _current->tss.eflags = EFLAG_IF | EFLAG_VM | stack[0]; + _current->oInfo.v86If = (stack[0] & EFLAG_IF) != 0; + _current->tss.esp = ((_current->tss.esp & 0xffff) + 2) & 0xffff; + } + _current->tss.eip = (uInt16) (_current->tss.eip + 1); + /* kprintf("popf [0x%X]\n",_current->id); */ + break; + case 0xFA: + _current->oInfo.v86If = FALSE; + _current->tss.eflags &= ~EFLAG_IF; + _current->tss.eip = (uInt16) (_current->tss.eip + 1); + _current->oInfo.timer = 0x1; + /* kprintf("cli [0x%X]\n",_current->id); */ + break; + case 0xFB: + _current->oInfo.v86If = TRUE; + _current->tss.eflags |= EFLAG_IF; + _current->tss.eip = (uInt16) (_current->tss.eip + 1); + _current->oInfo.timer = 0x0; + /* kprintf("sti [0x%X]\n",_current->id); */ + break; + case 0xCF: + _current->tss.eip = stack[0]; + _current->tss.cs = stack[1]; + _current->tss.eflags = EFLAG_IF | EFLAG_VM | stack[2]; + _current->oInfo.v86If = (stack[2] & EFLAG_IF) != 0; + _current->tss.esp = ((_current->tss.esp & 0xffff) + 6) & 0xffff; + /* kprintf("iret [0x%X]\n",_current->id); */ + break; + case 0xEC: /* IN AL,DX */ + _current->tss.eax = (_current->tss.eax & ~0xFF) | inportByte(_current->tss.edx); + _current->tss.eip = (uInt16) (_current->tss.eip + 1); + + /* + * kprintf("IN DX[0x%X],AL[0x%X] + * [0x%X]\n",_current->tss.edx,_current->tss.eax & 0xFF,_current->id); + */ + break; + case 0xED: /* IN AX,DX */ + _current->tss.eax = (_current->tss.eax & ~0xFFFF) | inportWord(_current->tss.edx); + _current->tss.eip = (uInt16) (_current->tss.eip + 1); + + /* + * kprintf("IN DX[0x%X],AX[0x%X] + * [0x%X]\n",_current->tss.edx,_current->tss.eax & 0xFFFF,_current->id); + */ + break; + case 0xEE: /* OUT DX,AL */ + outportByte(_current->tss.edx, _current->tss.eax & 0xFF); + _current->tss.eip = (uInt16) (_current->tss.eip + 1); + + /* + * kprintf("OUT DX[0x%X],AL[0x%X] + * [0x%X]\n",_current->tss.edx,_current->tss.eax & 0xFF,_current->id); + */ + break; + case 0xEF: + outportWord(_current->tss.edx, _current->tss.eax); + _current->tss.eip = (uInt16) (_current->tss.eip + 1); + + /* + * kprintf("OUT DX[0x%X],AX[0x%X] + * [0x%X]\n",_current->tss.edx,_current->tss.eax,_current->id); + */ + break; + case 0xF4: + _current->tss.eip = (uInt16) (_current->tss.eip + 1); + /* kprintf("HLT [0x%X]\n",_current->id); */ + break; + default: /* something wrong */ + kprintf("NonHandled OpCode [0x%X:0x%X]\n",_current->id,ip[0]); + _current->state = DEAD; + /* + * kprintf("Non Handled OpCode [0x%X]\n",_current->id); + * setTaskStatus(_current->id,EXITING); Temp Reboot For Now + * while(inportByte(0x64) & 0x02); outportByte(0x64, 0xfe); + */ + break; + } + //kprintf("\nEFLAGS: [0x%X]\n",_current->tss.eflags); + irqEnable(0); + while (1); +} + +/* Timer Interupt */ +__asm__( + ".globl timerInt \n" + "timerInt: \n" + " pushl %edx \n" + " pushl %ecx \n" + " pushl %ebx \n" + " pushl %eax \n" + " movl systemVitals,%ecx \n" + " incl 4(%ecx) \n" + " mov $0x20,%dx \n" + " mov $0x20,%ax \n" + " outb %al,%dx \n" + " movl 4(%ecx),%eax \n" + " movl $1000,%ebx \n" + " xor %edx,%edx \n" + " div %ebx \n" + " test %edx,%edx \n" + " jnz next \n" + " incl 8(%ecx) \n" + "next: \n" + " movl 4(%ecx),%eax \n" + " movl $5,%ebx \n" + " xor %edx,%edx \n" + " div %ebx \n" + " test %edx,%edx \n" + " jnz done \n" + " call sched \n" + "done: \n" + " popl %eax \n" + " popl %ebx \n" + " popl %ecx \n" + " popl %edx \n" + " iret \n" +); + +void _int7(); +__asm__ ( + ".globl _int7 \n" + "_int7: \n" + " pushl %eax \n" + " clts \n" + " movl _current,%eax \n" + " cmpl _usedMath,%eax \n" + " je mathDone \n" + " call mathStateRestore \n" + "mathDone: \n" + " popl %eax \n" + " iret \n" + ); + +void mathStateRestore() { + if (_usedMath != 0x0) + __asm__("fnsave %0"::"m" (_usedMath->i387)); + if (_current->usedMath != 0x0) + __asm__("frstor %0"::"m" (_current->i387)); + else { + __asm__("fninit"::); + _current->usedMath=1; + } + _usedMath=_current; + //Return + } + +/*** + END + ***/ + diff --git a/src/sys/sys/io.c b/src/sys/sys/io.c new file mode 100644 index 0000000..522ed51 --- /dev/null +++ b/src/sys/sys/io.c @@ -0,0 +1,152 @@ +/***************************************************************************************** + 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. + + $Log$ + Revision 1.5 2004/04/13 16:36:34 reddawg + Changed our copyright, it is all now under a BSD-Style license + + + + $Id$ + +*****************************************************************************************/ + +#include + +/************************************************************************ + +Function: inline unsigned char inportByte(unsigned int port); +Description: This Funciton Will Input One Byte From A Port +Notes: + +************************************************************************/ +inline unsigned char inportByte(unsigned int port) { + unsigned char retVal; + asm volatile( + "inb %%dx,%%al" + : "=a" (retVal) + : "d" (port) + ); + return(retVal); + } + +/************************************************************************ + +Function: inline unsigned char inportWord(unsigned int port); +Description: This Funciton Will Input One Word From A Port +Notes: + +************************************************************************/ +inline unsigned short inportWord(unsigned int port) { + unsigned short retVal; + asm volatile( + "inw %%dx,%%ax" + : "=a" (retVal) + : "d" (port) + ); + return(retVal); + } + +/************************************************************************ + +Function: inline void outportByte(unsigned int port,unsigned char value); +Description: This Funciton Will Outputut One Byte To A Port +Notes: + +************************************************************************/ +inline void outportByte(unsigned int port,unsigned char value) { + asm volatile( + "outb %%al,%%dx" + : + : "d" (port), "a" (value) + ); + } + +/************************************************************************ + +Function: inline void outportByteP(unsigned int port,unsigned char value); +Description: This Funciton Will Outputut One Byte To A Port With A Delay +Notes: + +************************************************************************/ +inline void outportByteP(unsigned int port,unsigned char value) { + asm volatile( + "outb %%al,%%dx\n" + "outb %%al,$0x80\n" + : + : "d" (port), "a" (value) + ); + } + +/************************************************************************ + +Function: inline void outportWord(unsigned int port,unsigned char value); +Description: This Funciton Will Outputut One Word To A Port +Notes: + +************************************************************************/ +inline void outportWord(unsigned int port,unsigned short value) { + asm volatile( + "outw %%ax,%%dx" + : + : "d" (port), "a" (value) + ); + } + +/************************************************************************ + +Function: inline void outportDWord(unsigned int port,unsigned char value); +Description: This Funciton Will Outputut One DWord To A Port +Notes: + +************************************************************************/ +inline void outportDWord(unsigned int port,unsigned long value) { + asm volatile( + "outl %%eax,%%dx" + : + : "d" (port), "a" (value) + ); + } + +/************************************************************************ + +Function: inline unsigned char inportDWord(unsigned int port); +Description: This Funciton Will Input One DWord From A Port +Notes: + +************************************************************************/ +inline unsigned long inportDWord(unsigned int port) { + unsigned long retVal; + asm volatile( + "inl %%dx,%%eax" + : "=a" (retVal) + : "d" (port) + ); + return(retVal); + } + +/*** + END + ***/ diff --git a/src/sys/sys/video.c b/src/sys/sys/video.c new file mode 100644 index 0000000..57506ac --- /dev/null +++ b/src/sys/sys/video.c @@ -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. + + $Log$ + Revision 1.24 2004/04/13 16:36:34 reddawg + Changed our copyright, it is all now under a BSD-Style license + + + + $Id$ + +*****************************************************************************************/ + +#include +#include +#include + +unsigned char *videoBuffer = (char *)0xB8000; +int printColor = defaultColor; +int cv_pos = 0x0; +int printLock = -1; + +void +backSpace() +{ + uInt32 bufferOffset = 0x0; + outportByte(0x3d4, 0x0e); + bufferOffset = inportByte(0x3d5); + bufferOffset <<= 8; /* Shift Address Left 8 Bits */ + outportByte(0x3d4, 0x0f); + bufferOffset += inportByte(0x3d5); + bufferOffset <<= 1; /* Shift Address Left 1 Bits */ + videoBuffer[bufferOffset--] = 0x20; + videoBuffer[bufferOffset--] = printColor; + videoBuffer[bufferOffset] = 0x20; + bufferOffset >>= 1; + outportByte(0x3D4, 0x0f); + outportByte(0x3D5, ((bufferOffset & 0x0ff) & 0xFF)); + outportByte(0x3D4, 0x0e); + outportByte(0x3D5, ((bufferOffset >> 8) & 0xFF)); + return; +} /* backSpace() */ + +void +kprint2(char *string) +{ + uInt8 *scrnBuf = (char *)0xB8000; + int i = 0; + + while (printLock != -1) + asm("nop"); + printLock = 0x0; + while ('\0' != string[i]) { + switch (string[i]) { + case '\t': + cv_pos += 3; + break; + case '\b': + if (cv_pos != 0) { + cv_pos -= 2; + scrnBuf[((cv_pos + 1) << 1)] = ' '; + } /* if */ + break; + case '\n': + cv_pos = cv_pos - (cv_pos % 80) + 79; + break; + default: + scrnBuf[(cv_pos << 1)] = string[i]; + scrnBuf[(cv_pos << 1) | 0x1] = printColor; + break; + } /* switch */ + + cv_pos++; + i++; + while (cv_pos >= (80 * 25)) { + + for (i = 0; i < (160 * 24); i++) { + scrnBuf[i] = scrnBuf[i + 160]; + } /* for */ + + for (i = (160 * 24); i < (160 * 25); i += 2) { + scrnBuf[i] = 0x20; + scrnBuf[i + 1] = printColor; + } /* for */ + + cv_pos -= 80; + } /* while */ + } /* while */ + outportByte(0x3D4, 0x0F); + outportByte(0x3D5, (unsigned char)cv_pos & 0xFF); + outportByte(0x3D4, 0x0E); + outportByte(0x3D5, (unsigned char)(cv_pos >> 8) & 0xFF); + printLock = -1; +} /* kprint() */ + +void +kprint(char *string) +{ + unsigned int bufferOffset = 0x0, character = 0x0, i = 0x0; + + videoBuffer = (char *)0xB8000; + + /* We Need To Get The Y Position */ + outportByte(0x3D4, 0x0e); + bufferOffset = inportByte(0x3D5); + bufferOffset <<= 8; /* Shift Address Left 8 Bits */ + /* Then We Need To Add The X Position */ + outportByte(0x3D4, 0x0f); + bufferOffset += inportByte(0x3D5); + bufferOffset <<= 1; /* Shift Address Left 1 Bits */ + + while ((character = *string++)) { + switch (character) { + case '\n': + bufferOffset = (bufferOffset / 160) * 160 + 160; + break; + default: + videoBuffer[bufferOffset++] = character; + videoBuffer[bufferOffset++] = printColor; + break; + } /* switch */ + /* Check To See If We Are Out Of Bounds */ + if (bufferOffset >= 160 * 25) { + for (i = 0; i < 160 * 24; i++) { + videoBuffer[i] = videoBuffer[i + 160]; + } /* for */ + for (i = 0; i < 80; i++) { + videoBuffer[(160 * 24) + (i * 2)] = 0x20; + videoBuffer[(160 * 24) + (i * 2) + 1] = printColor; + } /* for */ + bufferOffset -= 160; + } /* if */ + } /* while */ + bufferOffset >>= 1; /* Set the new cursor position */ + outportByte(0x3D4, 0x0f); + outportByte(0x3D5, ((bufferOffset & 0x0ff) & 0xFF)); + outportByte(0x3D4, 0x0e); + outportByte(0x3D5, ((bufferOffset >> 8) & 0xFF)); + return; +} /* kprint2() */ + +/* Clears The Screen */ +void +clearScreen() +{ + unsigned int i = 0x0; + + videoBuffer = (char *)0xB8000; + for (i = 0x0; i < (80 * 25); i++) { /* Fill the screen with */ + /* background Color */ + videoBuffer[i * 2] = 0x20; + videoBuffer[i * 2 + 1] = defaultColor; + } /* for */ + + outportByte(0x3D4, 0x0f); /* Set the cursor to the */ + outportByte(0x3D5, 0); /* upper-left corner of the */ + outportByte(0x3D4, 0x0e); /* screen */ + outportByte(0x3D5, 0); +} /* clearScreen() */ + +/*** + END + ***/ + diff --git a/src/sys/ubixfs/Makefile b/src/sys/ubixfs/Makefile new file mode 100644 index 0000000..435025c --- /dev/null +++ b/src/sys/ubixfs/Makefile @@ -0,0 +1,27 @@ +# (C) 2002 The UbixOS Project +# $Id$ + +# Include Global 'Source' Options +include ../../Makefile.inc +include ../Makefile.inc + +# Objects +OBJS = ubixfs.o directory.o block.o + +all: $(OBJS) + +# Compile Types +.cc.o: + $(CXX) ${CFLAGS} -Wall -fomit-frame-pointer -O -I../include -c -o $@ $< +.cc.s: + $(CXX) ${CFLAGS} -Wall -fomit-frame-pointer -O -I../include -S -o $@ $< +.c.o: + $(CC) ${CFLAGS} -Wall -fomit-frame-pointer -O -I../include -c -o $@ $< +.c.s: + $(CC) ${CFLAGS} -Wall -fomit-frame-pointer -O -I../include -S -o $@ $< +.S.o: + $(CC) ${CFLAGS} -Wall -fomit-frame-pointer -c -o $@ $< + +# Clean up the junk +clean: + $(REMOVE) $(OBJS) diff --git a/src/sys/ubixfs/block.c b/src/sys/ubixfs/block.c new file mode 100644 index 0000000..914c1cf --- /dev/null +++ b/src/sys/ubixfs/block.c @@ -0,0 +1,96 @@ +/***************************************************************************************** + 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. + + $Log$ + Revision 1.3 2004/04/13 16:36:34 reddawg + Changed our copyright, it is all now under a BSD-Style license + + + + $Id$ + +*****************************************************************************************/ + +#include +#include +#include +#include + + +void syncBat(struct mountPoints *mp) { + struct ubixFsInfo *fsInfo = mp->fsInfo; + mp->drive->write(mp->drive->driveInfoStruct,mp->drive->diskLabel->partitions[mp->partition].pOffset,mp->drive->diskLabel->partitions[mp->partition].pBatSize,fsInfo->blockAllocationTable); + } + +int freeBlocks(int block,fileDescriptor *fd) { + int i = block; + + struct ubixFsInfo *fsInfo = fd->mp->fsInfo; + + while (i != 0x0) { + block = fsInfo->blockAllocationTable[i].nextBlock; + + fsInfo->blockAllocationTable[i].attributes = 0x0; + fsInfo->blockAllocationTable[i].nextBlock = 0x0; + + i = block; + } + syncBat(fd->mp); + return(i); + } + +int getFreeBlocks(int count,fileDescriptor *fd) { + int i = 0x0,x = 0x0; + + struct ubixFsInfo *fsInfo = fd->mp->fsInfo; + + getBlocks: + for (i=1;i < fsInfo->batEntries;i++) { + if (fsInfo->blockAllocationTable[i].attributes == 0x0) { + for (x = 1; x < count; x++) { + if (fsInfo->blockAllocationTable[i + x].attributes != 0x0) { + goto getBlocks; + } + } + for (x = i; x < i+count;x++) { + fsInfo->blockAllocationTable[x].attributes = 0x1; + if ((x+1) == (i+count)) { + fsInfo->blockAllocationTable[x].nextBlock = -1; + } + else { + fsInfo->blockAllocationTable[x].nextBlock = x+1; + } + } + syncBat(fd->mp); + return(i); + } + } + return(0x0); + } + +/*** + END + ***/ + diff --git a/src/sys/ubixfs/directory.c b/src/sys/ubixfs/directory.c new file mode 100644 index 0000000..6f2d5f0 --- /dev/null +++ b/src/sys/ubixfs/directory.c @@ -0,0 +1,100 @@ +/***************************************************************************************** + 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. + + $Log$ + Revision 1.6 2004/04/13 16:36:34 reddawg + Changed our copyright, it is all now under a BSD-Style license + + + + $Id$ + +*****************************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include + +int addDirEntry(struct directoryEntry *dir,fileDescriptor *fd) { + int i = 0x0; + uInt32 entries = 0x0; + struct directoryEntry *tmp = 0x0; + + tmp = (struct directoryEntry *)kmalloc(fd->size,sysMalloc); + + readUbixFS(fd,(char *)tmp,fd->offset,fd->size); + entries = fd->size/sizeof(struct directoryEntry); + for (i=0;(tmp[i].attributes != 0x0) && (i < entries);i++); + + if (i == entries) { + tmp = (struct directoryEntry *)kmalloc(0x1000,sysMalloc); + i = 0x0; + } + else { + fd->offset = 0x0; + } + kmemcpy(&tmp[i],dir,sizeof(struct directoryEntry)); + + if (writeUbixFS(fd,(char *)tmp,fd->offset,fd->size) == 0x0) { + kprintf("Error Creating Directory\n"); + } + + return(0x0); + } + +int mkDirUbixFS(char *directory,fileDescriptor *fd) { + int block = 0x0; + + struct directoryEntry *dir = 0x0; + struct directoryEntry *entry = 0x0; + struct ubixFsInfo *fsInfo = fd->mp->fsInfo; + + block = getFreeBlocks(1,fd); + if (block != 0x0) { + dir = (struct directoryEntry *)kmalloc(blockByteSize,sysMalloc); + entry = (struct directoryEntry *)kmalloc(sizeof(struct directoryEntry),sysMalloc); + + entry->startCluster = block; + entry->size = blockByteSize; + entry->attributes = 0x8000; + entry->permissions = 0xEAA; + sprintf(entry->fileName,directory); + + fd->mp->drive->write(fd->mp->drive->driveInfoStruct,fd->mp->drive->diskLabel->partitions[fd->mp->partition].pOffset+fsInfo->blockAllocationTable[block].realSector,blockSize,dir); + addDirEntry(entry,fd); + kfree(dir); + kfree(entry); + } + + return(0x0); + } + +/*** + END + ***/ diff --git a/src/sys/ubixfs/ubixfs.c b/src/sys/ubixfs/ubixfs.c new file mode 100644 index 0000000..14e1b86 --- /dev/null +++ b/src/sys/ubixfs/ubixfs.c @@ -0,0 +1,329 @@ +/***************************************************************************************** + 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. + + $Log$ + Revision 1.31 2004/04/13 16:36:34 reddawg + Changed our copyright, it is all now under a BSD-Style license + + + + $Id$ + +*****************************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +int sprintf(char *buf,const char *fmt, ...); /* TEMP */ + +int enableUbixFS() { + /* Add UbixFS */ + if (vfsRegisterFS(0,initUbixFS,readUbixFS,writeUbixFS,openFileUbixFS,ubixFSUnlink,mkDirUbixFS,0x0,0x0) != 0x0) { + kpanic("Unable To Enable UbixFS"); + return(0x1); + } + /* Return */ + return(0x0); + } + +void initUbixFS(struct mountPoints *mp) { + struct ubixFsInfo *fsInfo = 0x0; + mp->drive->diskLabel = (struct driveDiskLabel *)kmalloc(512,-2); + mp->drive->read(mp->drive->driveInfoStruct,1,1,mp->drive->diskLabel); + mp->fsInfo = (struct ubixFsInfo *)kmalloc(sizeof(struct ubixFsInfo),-2); + fsInfo = mp->fsInfo; + if ((mp->drive->diskLabel->magicNum == UBIXDISKMAGIC) && (mp->drive->diskLabel->magicNum2 == UBIXDISKMAGIC)) { + fsInfo->blockAllocationTable = (struct blockAllocationTableEntry *)kmalloc(mp->drive->diskLabel->partitions[mp->partition].pBatSize*512,-2); + /* fsInfo->blockAllocationTable[0].nextBlock = 100; */ + fsInfo->batEntries = ((mp->drive->diskLabel->partitions[mp->partition].pBatSize*512)/sizeof(struct blockAllocationTableEntry)); + mp->drive->read(mp->drive->driveInfoStruct,mp->drive->diskLabel->partitions[mp->partition].pOffset,mp->drive->diskLabel->partitions[mp->partition].pBatSize,fsInfo->blockAllocationTable); + kprintf("Offset: [%i], Partition: [%i]\n",mp->drive->diskLabel->partitions[mp->partition].pOffset,mp->partition); + kprintf("UbixFS Initialized\n"); + } + else { + kprintf("Insert System Disk!\n"); + initUbixFS(mp); + } + /* Return */ + return; + } + +int openFileUbixFS(char *file,fileDescriptor *fd) { + int x=0; + struct directoryEntry *dirEntry = (struct directoryEntry *)kmalloc(4096,_current->id); + struct ubixFsInfo *fsInfo = fd->mp->fsInfo; + fd->mp->drive->read(fd->mp->drive->driveInfoStruct,(fd->mp->drive->diskLabel->partitions[fd->mp->partition].pOffset+fsInfo->blockAllocationTable[0].realSector),8,dirEntry); + if ((fd->mode & fileRead) == fileRead) { + for (x=0;x<(4096/sizeof(struct directoryEntry));x++) { + if ((int)!kstrcmp(dirEntry[x].fileName,file)) { + fd->start = dirEntry[x].startCluster; + fd->size = dirEntry[x].size; + fd->perms = dirEntry[x].permissions; + fd->dirBlock = 0x0; /* Directory Start Sector */ + kfree(dirEntry); + return((int)1); + } + } + } + else if ((fd->mode & fileWrite) == fileWrite) { + for (x=0;x<(4096/sizeof(struct directoryEntry));x++) { + if (!kstrcmp(dirEntry[x].fileName,file)) { + fd->start = dirEntry[x].startCluster; + fd->size = dirEntry[x].size; + fd->perms = dirEntry[x].permissions; + fd->dirBlock = 0x0; /* Directory Start Sector */ + kfree(dirEntry); + return(0x1); + } + if (dirEntry[x].attributes == 0x0) { + sprintf(dirEntry[x].fileName,file); + dirEntry[x].size = 0x0; + dirEntry[x].startCluster = getFreeBlocks(1,fd); + dirEntry[x].attributes = typeFile; + dirEntry[x].permissions = 3754; + fd->size = 0x0; + fd->start = dirEntry[x].startCluster; + fd->dirBlock = 0x0; + fd->mp->drive->write(fd->mp->drive->driveInfoStruct,(fd->mp->drive->diskLabel->partitions[fd->mp->partition].pOffset+fsInfo->blockAllocationTable[0].realSector),8,dirEntry); + kfree(dirEntry); + return(0x1); + } + } + } + kfree(dirEntry); + return((int)0); + } + +int writeFileByte(int ch,fileDescriptor *fd,long offset) { + + int blockCount = 0x0,batIndex = 0x0,batIndexPrev = fd->start,i = 0x0; + struct directoryEntry *dirEntry = 0x0; + struct ubixFsInfo *fsInfo = fd->mp->fsInfo; + + /* Find Out How Many Blocks Long This File Is */ + blockCount = (offset/4096); + + /* Find The Block If It Doesn't Exist We Will Have To Allocate One */ + for (i=0x0;i<=fd->mp->drive->diskLabel->partitions[fd->mp->partition].pBatSize;i++) { + batIndex = fsInfo->blockAllocationTable[batIndexPrev].nextBlock; + if (batIndex == 0x0) { + break; + } + batIndexPrev = batIndex; + } + + if ((offset%4096 == 0) && (fd->status == fdRead)) { + fd->status = fdOpen; + } + + /* If batIndex == 0x0 Then We Must Allocate A New Block */ + if (batIndex == 0x0) { + for (i=1;i < fsInfo->batEntries;i++) { + if (fsInfo->blockAllocationTable[i].attributes == 0x0) { + fsInfo->blockAllocationTable[batIndexPrev].nextBlock = i; + fsInfo->blockAllocationTable[batIndex].nextBlock = -1; + batIndex = i; + fd->start = i; + break; + } + } + /* fd->mp->drive->read(fd->mp->drive->driveInfoStruct,diskLabel->partitions[0].pOffset+blockAllocationTable[batIndex].realSector,8,fd->buffer); */ + fd->buffer[offset-(blockCount*4096)] = ch; + fd->mp->drive->write(fd->mp->drive->driveInfoStruct,fd->mp->drive->diskLabel->partitions[fd->mp->partition].pOffset+fsInfo->blockAllocationTable[batIndex].realSector,8,fd->buffer); + } + else { + if (fd->status != fdRead) { + fd->mp->drive->read(fd->mp->drive->driveInfoStruct,fd->mp->drive->diskLabel->partitions[fd->mp->partition].pOffset+fsInfo->blockAllocationTable[batIndex].realSector,8,fd->buffer); + fd->status = fdRead; + } + fd->buffer[offset-(blockCount*4096)] = ch; + fd->mp->drive->write(fd->mp->drive->driveInfoStruct,fd->mp->drive->diskLabel->partitions[fd->mp->partition].pOffset+fsInfo->blockAllocationTable[batIndex].realSector,8,fd->buffer); + } + if (offset > fd->size) { + fd->size = offset; + dirEntry = (struct directoryEntry *)kmalloc(4096,-2); + fd->mp->drive->read(fd->mp->drive->driveInfoStruct,(fd->mp->drive->diskLabel->partitions[fd->mp->partition].pOffset+fsInfo->blockAllocationTable[fd->dirBlock].realSector),8,dirEntry); + for (i=0x0;i<(4096/sizeof(struct directoryEntry));i++) { + if ((int)!kstrcmp(dirEntry[i].fileName,fd->fileName)) + break; + } + dirEntry[i].size = fd->size; + fd->mp->drive->write(fd->mp->drive->driveInfoStruct,(fd->mp->drive->diskLabel->partitions[fd->mp->partition].pOffset+fsInfo->blockAllocationTable[fd->dirBlock].realSector),8,dirEntry); + kfree(dirEntry); + } + return(ch); + } + +/* Verified Functions */ + +/************************************************************************ + +Function: int readUbixFS(fileDescriptor *fd,char *data,long offset,long size) +Description: Read File Into Data +Notes: + +************************************************************************/ +int readUbixFS(fileDescriptor *fd,char *data,long offset,long size) { + int blockCount = 0x0,batIndex = fd->start; + long i = 0x0; + struct ubixFsInfo *fsInfo = fd->mp->fsInfo; + blockCount = ((offset)/4096); + /* Find The Starting Block */ + for (i=1;i<=blockCount;i++) { + batIndex = fsInfo->blockAllocationTable[batIndex].nextBlock; + if (batIndex == 0x0) { + /* sysErr(log, "Invalid File Offset"); */ + return(0); + } + } + /* If The File Size Is Greater Then The Offset Lets Goto Work */ + fd->mp->drive->read(fd->mp->drive->driveInfoStruct,fd->mp->drive->diskLabel->partitions[fd->mp->partition].pOffset+fsInfo->blockAllocationTable[batIndex].realSector,blockSize,fd->buffer); + for (i=0x0;i fd->size) { + /* Set File EOF If There Is Nothing To Do */ + data[i] = '\0'; + fd->status = fdEof; + return(size); + } + /* Copy Data From Buffer To Data */ + data[i] = fd->buffer[offset-(blockCount*4096)]; + offset++; + if (offset%4096 == 0 && offset != size) { + batIndex = fsInfo->blockAllocationTable[batIndex].nextBlock; + fd->mp->drive->read(fd->mp->drive->driveInfoStruct,fd->mp->drive->diskLabel->partitions[fd->mp->partition].pOffset+fsInfo->blockAllocationTable[batIndex].realSector,blockSize,fd->buffer); + blockCount++; + } + } + /* Return */ + return(size); + } + + + +/************************************************************************ + +Function: int writeUbixFS(fileDescriptor *fd,char *data,long offset,long size) +Description: Write Data Into File +Notes: + +************************************************************************/ +int writeUbixFS(fileDescriptor *fd,char *data,long offset,long size) { + uInt32 blockOffset = 0x0; + uInt32 blockIndex = fd->start; + uInt32 blockIndexPrev = fd->start; + uInt32 i = 0x0; + struct ubixFsInfo *fsInfo = fd->mp->fsInfo; + struct directoryEntry *dirEntry = 0x0; + + blockOffset = (offset/0x1000); + + + if (fd->size != 0x0) { + for (i = 0x0;i < blockOffset;i++) { + blockIndex = fsInfo->blockAllocationTable[blockIndexPrev].nextBlock; + if (blockIndex == EOBC) { + blockIndex = getFreeBlocks(1,fd); + fsInfo->blockAllocationTable[blockIndexPrev].nextBlock = blockIndex; + fsInfo->blockAllocationTable[blockIndex].nextBlock = EOBC; + break; + } + blockIndexPrev = blockIndex; + } + } + + fd->mp->drive->read(fd->mp->drive->driveInfoStruct,fd->mp->drive->diskLabel->partitions[fd->mp->partition].pOffset+fsInfo->blockAllocationTable[blockIndex].realSector,blockSize,fd->buffer); + for (i = 0x0;i < size;i++) { + + fd->buffer[(offset- (blockOffset *0x1000))] = data[i]; + offset++; + + if (offset%4096 == 0x0) { + blockOffset++; + fd->mp->drive->write(fd->mp->drive->driveInfoStruct,fd->mp->drive->diskLabel->partitions[fd->mp->partition].pOffset+fsInfo->blockAllocationTable[blockIndex].realSector,blockSize,fd->buffer); + + if (fsInfo->blockAllocationTable[blockIndex].nextBlock == EOBC) { + blockIndexPrev = blockIndex; + blockIndex = getFreeBlocks(1,fd); + fsInfo->blockAllocationTable[blockIndexPrev].nextBlock = blockIndex; + fsInfo->blockAllocationTable[blockIndex].nextBlock = EOBC; + } + else { + blockIndex = fsInfo->blockAllocationTable[blockIndex].nextBlock; + fd->mp->drive->read(fd->mp->drive->driveInfoStruct,fd->mp->drive->diskLabel->partitions[fd->mp->partition].pOffset+fsInfo->blockAllocationTable[blockIndex].realSector,blockSize,fd->buffer); + } + } + } + fd->mp->drive->write(fd->mp->drive->driveInfoStruct,fd->mp->drive->diskLabel->partitions[fd->mp->partition].pOffset+fsInfo->blockAllocationTable[blockIndex].realSector,blockSize,fd->buffer); + + if (offset > fd->size) { + fd->size = offset; + dirEntry = (struct directoryEntry *)kmalloc(4096,-2); + fd->mp->drive->read(fd->mp->drive->driveInfoStruct,(fd->mp->drive->diskLabel->partitions[fd->mp->partition].pOffset+fsInfo->blockAllocationTable[fd->dirBlock].realSector),blockSize,dirEntry); + for (i=0x0;i<(4096/sizeof(struct directoryEntry));i++) { + if ((int)!kstrcmp(dirEntry[i].fileName,fd->fileName)) + break; + } + dirEntry[i].size = fd->size; + dirEntry[i].startCluster = fd->start; + fd->mp->drive->write(fd->mp->drive->driveInfoStruct,(fd->mp->drive->diskLabel->partitions[fd->mp->partition].pOffset+fsInfo->blockAllocationTable[fd->dirBlock].realSector),blockSize,dirEntry); + kfree(dirEntry); + } + /* Return */ + return(size); + } + +void ubixFSUnlink(char *path,struct mountPoints *mp) { + int x=0; + struct directoryEntry *dirEntry = (struct directoryEntry *)kmalloc(0x1000,_current->id); + struct ubixFsInfo *fsInfo = mp->fsInfo; + + mp->drive->read(mp->drive->driveInfoStruct,(mp->drive->diskLabel->partitions[mp->partition].pOffset+fsInfo->blockAllocationTable[0].realSector),8,dirEntry); + + for (x=0;x<(4096/sizeof(struct directoryEntry));x++) { + if ((int)!kstrcmp(dirEntry[x].fileName,path)) { + dirEntry[x].attributes |= typeDeleted; + dirEntry[x].fileName[0] = '?'; + mp->drive->write(mp->drive->driveInfoStruct,(mp->drive->diskLabel->partitions[mp->partition].pOffset+fsInfo->blockAllocationTable[0].realSector),8,dirEntry); + return; + } + } + kprintf("File Not Found\n"); + return; + } + +/*** + END + ***/ + diff --git a/src/sys/vfs/Makefile b/src/sys/vfs/Makefile new file mode 100644 index 0000000..e90b817 --- /dev/null +++ b/src/sys/vfs/Makefile @@ -0,0 +1,27 @@ +# (C) 2002 The UbixOS Project +# $Id$ + +# Include Global 'Source' Options +include ../../Makefile.inc +include ../Makefile.inc + +# Objects +OBJS = mount.o file.o vfs.o + +all: $(OBJS) + +# Compile Types +.cc.o: + $(CXX) ${CFLAGS} -Wall -fomit-frame-pointer -O -I../include -c -o $@ $< +.cc.s: + $(CXX) ${CFLAGS} -Wall -fomit-frame-pointer -O -I../include -S -o $@ $< +.c.o: + $(CC) ${CFLAGS} -Wall -fomit-frame-pointer -O -I../include -c -o $@ $< +.c.s: + $(CC) ${CFLAGS} -Wall -fomit-frame-pointer -O -I../include -S -o $@ $< +.S.o: + $(CC) ${CFLAGS} -Wall -fomit-frame-pointer -c -o $@ $< + +# Clean up the junk +clean: + $(REMOVE) $(OBJS) diff --git a/src/sys/vfs/file.c b/src/sys/vfs/file.c new file mode 100644 index 0000000..d9d3a21 --- /dev/null +++ b/src/sys/vfs/file.c @@ -0,0 +1,223 @@ +/***************************************************************************************** + 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. + + $Log$ + Revision 1.12 2004/04/13 16:36:34 reddawg + Changed our copyright, it is all now under a BSD-Style license + + + + $Id$ + +*****************************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include +#include + + + +/************************************************************************ + +Function: void sysMkDir(const char *path) +Description: This Will Create A New Directory +Notes: + +************************************************************************/ +int sysMkDir(const char *path) { + fileDescriptor *tmpFd = 0x0; + char *dir = 0x0,*mountPoint = 0x0; + + + /* Allocate Memory For File Descriptor */ + tmpFd = (fileDescriptor *)kmalloc(sizeof(fileDescriptor),sysMalloc); + tmpFd->mode = fileRead; + + dir = (char *)strtok((char *)path,"@"); + mountPoint = strtok(NULL,"\n"); + + if (mountPoint == 0x0) { + tmpFd->mp = _current->oInfo.container; + } + else { + tmpFd->mp = findMount(mountPoint); + } + if (tmpFd->mp == 0x0) { + kpanic("Invalid Container\n"); + return(0x1); + } + if (tmpFd->mp->fs->vfsOpenFile(":",tmpFd) == 1) { + tmpFd->buffer = (char *)kmalloc(4096,_current->id); + sprintf(tmpFd->fileName,"%s",":"); + /* Set Its Status To Open */ + tmpFd->status = fdOpen; + /* Initial File Offset Is Zero */ + tmpFd->offset = 0x0; + } + else { + return(0x0); + } + if (tmpFd->mp->fs->vfsMakeDir(dir,tmpFd) != 0x0) { + kpanic("Error Creating Directory\n"); + } + else { + kpanic("Made Directory\n"); + } + kfree(tmpFd->buffer); + kfree(tmpFd); + return(0x0); + } + + +/************************************************************************ + +Function: int unlink(const char *node) +Description: This will unlink a file +Notes: + +************************************************************************/ + +int unlink(const char *node) { + char *path = 0x0,*mountPoint = 0x0; + struct mountPoints *mp = 0x0; + + path = (char *)strtok((char *)node,"@"); + mountPoint = strtok(NULL,"\n"); + if (mountPoint == 0x0) { + mp = findMount("sys"); /* _current->oInfo.container; */ + } + else { + mp = findMount(mountPoint); + } + if (mp == 0x0) { + //kpanic("Mount Point Bad"); + return(0x0); + } + mp->fs->vfsUnlink(path,mp); + return(0x0); + } + + +/************************************************************************ + +Function: fileDescriptor *fopen(const char *file,cont char *flags) +Description: This Will Open A File And Return A File Descriptor +Notes: + +08/05/02 - Just Started A Rewrite Of This Function Should Work Out Well + +************************************************************************/ + +fileDescriptor *fopen(const char *file,const char *flags) { + int i = 0; + fileDescriptor *tmpFd = 0x0; + char *path = 0x0,*mountPoint = 0x0; + /* Allocate Memory For File Descriptor */ + tmpFd = (fileDescriptor *)kmalloc(sizeof(fileDescriptor),sysID); + + path = (char *)strtok((char *)file,"@"); + mountPoint = strtok(NULL,"\n"); + if (mountPoint == 0x0) { + tmpFd->mp = findMount("sys"); /* _current->oInfo.container; */ + } + else { + tmpFd->mp = findMount(mountPoint); + } + if (tmpFd->mp == 0x0) { + //kpanic("Mount Point Bad"); + return(0x0); + } + /* This Will Set Up The Descriptor Modes */ + tmpFd->mode = 0x0; + while ('\0' != flags[i]) { + switch(flags[i]) { + case 'w': + case 'W': + tmpFd->mode |= fileWrite; + break; + case 'r': + case 'R': + tmpFd->mode |= fileRead; + break; + case 'b': + case 'B': + tmpFd->mode |= fileBinary; + break; + case 'a': + case 'A': + tmpFd->mode |= fileAppend; + break; + default: + break; + } + i++; + } + /* Search For The File */ + if (tmpFd->mp->fs->vfsOpenFile((char *)file,tmpFd) == 1) { + /* If The File Is Found Then Set Up The Descriptor */ + tmpFd->buffer = (char *)kmalloc(4096,_current->id); + sprintf(tmpFd->fileName,"%s",file); + /* Set Its Status To Open */ + tmpFd->status = fdOpen; + /* Initial File Offset Is Zero */ + tmpFd->offset = 0x0; + /* Pointer To Next Descriptor Is NULL */ + tmpFd->prev = 0x0; + /* If This Is The First File Descriptor Then Set It Up To Be Starting Fd */ + if (fdTable == 0x0) { + fdTable = tmpFd; + tmpFd->next = 0x0; + tmpFd->prev = 0x0; + } + else { + /* If There Is Already A Starting FD Set This Up As The Last One */ + tmpFd->next = fdTable; + fdTable->prev = tmpFd; + tmpFd->prev = 0x0; + fdTable = tmpFd; + } + /* Increment Number Of Open Files */ + systemVitals->openFiles++; + + /* Return The FD */ + return(fdTable); + } + else { + /* If The File Was Not Found Free The Memory */ + kfree(tmpFd); + } + /* Return NULL */ + return(0x0); + } + +/*** + END + ***/ + diff --git a/src/sys/vfs/mount.c b/src/sys/vfs/mount.c new file mode 100644 index 0000000..50cc742 --- /dev/null +++ b/src/sys/vfs/mount.c @@ -0,0 +1,140 @@ +/***************************************************************************************** + 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. + + $Log$ + Revision 1.4 2004/04/13 16:36:34 reddawg + Changed our copyright, it is all now under a BSD-Style license + + + + $Id$ + +*****************************************************************************************/ + +#include +#include +#include +#include +#include +#include + +/************************************************************************ + +Function: mount(int driveId,int partition,int fsType,char *mountPoint,char *perms) + +Description: mount adds a mount point and returns 0 if successful 1 if it fails + +Notes: + +************************************************************************/ +int mount(int driveId,int partition,int vfsType,char *mountPoint,char *perms) { + struct mountPoints *mp = 0x0; + struct driveDriver *drive = 0x0; + + /* Allocate Memory For Mount Point */ + mp = (struct mountPoints *)kmalloc(sizeof(struct mountPoints),sysID); + + /* Copy Mount Point Into Buffer */ + sprintf(mp->mountPoint,mountPoint); + + /* Set Pointer To Physical Drive */ + drive = findDrive(driveId); + + /* Set Up Mp Defaults */ + mp->drive = drive; + mp->fs = vfsFindFS(vfsType); + mp->partition = partition; + mp->perms = *perms; + if (mp->fs == 0x0) { + /* sysErr(systemErr,"File System Type: %i Not Found\n",fsType); */ + kprintf("File System Type: %i Not Found\n",vfsType); + return(0x1); + } + /* Add Mountpoint If It Fails Free And Return */ + if (addMount(mp) != 0x0) { + kfree(mp); + return(0x1); + } + /* Initialize The File System If It Fails Return */ + if (mp->fs->vfsInitFS(mp) == 0x0) { + kfree(mp); + return(0x1); + } + /* Return */ + return(0x0); + } + +/************************************************************************ + +Function: addMount(struct mountPoints *mp) + +Description: This function adds a mount point to the system + +Notes: + +************************************************************************/ +int addMount(struct mountPoints *mp) { + + /* If There Are No Existing Mounts Make It The First */ + if (systemVitals->mountPoints == 0x0) { + mp->prev = 0x0; + mp->next = 0x0; + systemVitals->mountPoints = mp; + } + else { + mp->next = systemVitals->mountPoints; + systemVitals->mountPoints->prev = mp; + mp->prev = 0x0; + systemVitals->mountPoints = mp; + } + /* Return */ + return(0x0); + } + +/************************************************************************ + +Function: findMount(char *mountPoint) + +Description: This function finds a particular mount point + +Notes: + +************************************************************************/ +struct mountPoints *findMount(char *mountPoint) { + struct mountPoints *tmpMp = 0x0; + + for (tmpMp=systemVitals->mountPoints;tmpMp;tmpMp=tmpMp->next) { + if (kstrcmp(tmpMp->mountPoint,mountPoint) == 0x0) { + return(tmpMp); + } + } + /* Return NULL If Mount Point Not Found */ + return(0x0); + } + +/*** + END + ***/ + diff --git a/src/sys/vfs/vfs.c b/src/sys/vfs/vfs.c new file mode 100644 index 0000000..cdc2517 --- /dev/null +++ b/src/sys/vfs/vfs.c @@ -0,0 +1,118 @@ +/***************************************************************************************** + 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. + + $Log$ + Revision 1.7 2004/04/13 16:36:34 reddawg + Changed our copyright, it is all now under a BSD-Style license + + + + $Id$ + +*****************************************************************************************/ + +#include +#include +#include +#include + +/************************************************************************ + +Function: void initVFS(); + +Description: This Function Initializes The VFS Layer + +Notes: + +02/20/2004 - Approved for quality + +************************************************************************/ +int vfsInit() { + /* Set up default fileSystems list */ + systemVitals->fileSystems = 0x0; + + /* Print information */ + kprintf("vfs0 - Address: [0x%X]\n",systemVitals->fileSystems); + + /* Return so we know things went well */ + return(0x0); + } + +struct fileSystem *vfsFindFS(int vfsType) { + struct fileSystem *tmp = 0x0; + + /* Search For File System */ + for (tmp=systemVitals->fileSystems;tmp;tmp=tmp->next) { + /* If Found Return File System */ + if (tmp->vfsType == vfsType) { + return(tmp); + } + } + + /* If FS Not Found Return NULL */ + return(0x0); + } + +int vfsRegisterFS(int vfsType,void *vfsInitFS,void *vfsRead,void *vfsWrite,void *vfsOpenFile,void *vfsUnlink,void *vfsMakeDir,void *vfsRemDir,void *vfsSync) { + + struct fileSystem *tmpFs = 0x0; + + /* Allocate Memory */ + tmpFs = (struct fileSystem *)kmalloc(sizeof(struct fileSystem),-2); + if (tmpFs == 0x0) { + /* Memory Allocation Failed */ + return(0x1); + } + + /* Set Up FS Defaults */ + tmpFs->vfsType = vfsType; + tmpFs->vfsInitFS = vfsInitFS; + tmpFs->vfsRead = vfsRead; + tmpFs->vfsWrite = vfsWrite; + tmpFs->vfsOpenFile = vfsOpenFile; + tmpFs->vfsUnlink = vfsUnlink; + tmpFs->vfsMakeDir = vfsMakeDir; + tmpFs->vfsRemDir = vfsRemDir; + tmpFs->vfsSync = vfsSync; + + if (!systemVitals->fileSystems) { + tmpFs->prev = 0x0; + tmpFs->next = 0x0; + systemVitals->fileSystems = tmpFs; + } + else { + tmpFs->prev = 0x0; + tmpFs->next = systemVitals->fileSystems; + systemVitals->fileSystems->prev = tmpFs; + systemVitals->fileSystems = tmpFs; + } + + return(0x0); + } + +/*** + END + ***/ + diff --git a/src/sys/vmm/Makefile b/src/sys/vmm/Makefile new file mode 100644 index 0000000..2ee2926 --- /dev/null +++ b/src/sys/vmm/Makefile @@ -0,0 +1,27 @@ +# (C) 2002 The UbixOS Project +# $Id$ + +# Include Global 'Source' Options +include ../../Makefile.inc +include ../Makefile.inc + +# Objects +OBJS = pagefault.o vmminit.o getfreevirtualpage.o copyvirtualspace.o setpageattributes.o unmappage.o getphysicaladdr.o getfreepage.o createvirtualspace.o memory.o paging.o + +all: $(OBJS) + +# Compile Types +.cc.o: + $(CXX) ${CFLAGS} -Wall -fomit-frame-pointer -O -I../include -c -o $@ $< +.cc.s: + $(CXX) ${CFLAGS} -Wall -fomit-frame-pointer -O -I../include -S -o $@ $< +.c.o: + $(CC) ${CFLAGS} -Wall -fomit-frame-pointer -O -I../include -c -o $@ $< +.c.s: + $(CC) ${CFLAGS} -Wall -fomit-frame-pointer -O -I../include -S -o $@ $< +.S.o: + $(CC) ${CFLAGS} -Wall -fomit-frame-pointer -c -o $@ $< + +# Clean up the junk +clean: + $(REMOVE) $(OBJS) diff --git a/src/sys/vmm/copyvirtualspace.c b/src/sys/vmm/copyvirtualspace.c new file mode 100644 index 0000000..2a7ebe4 --- /dev/null +++ b/src/sys/vmm/copyvirtualspace.c @@ -0,0 +1,191 @@ +/***************************************************************************************** + 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. + + $Log$ + Revision 1.14 2004/04/13 16:36:34 reddawg + Changed our copyright, it is all now under a BSD-Style license + + + + $Id$ + +*****************************************************************************************/ + +#include + +/************************************************************************ + +Function: void *vmmCopyVirtualSpace(pidType pid); + +Description: Creates A Copy Of A Virtual Space And Set All NON Kernel + Space To COW For A Fork This Will Also Alter The Parents + VM Space To Make That COW As Well + +Notes: + +08/02/02 - Added Passing Of pidType pid So We Can Better Keep Track Of + Which Task Has Which Physical Pages + +************************************************************************/ +void * +vmmCopyVirtualSpace(pidType pid) +{ + void *newPageDirectoryAddress = 0x0; + uInt32 *parentPageDirectory = 0x0, *newPageDirectory = 0x0; + uInt32 *parentPageTable = 0x0, *newPageTable = 0x0; + uInt32 *parentStackPage = 0x0, *newStackPage = 0x0; + int x = 0, i = 0, s = 0; + + /* Set Address Of Parent Page Directory */ + parentPageDirectory = (uInt32 *) parentPageDirAddr; + /* Allocate A New Page For The New Page Directory */ + newPageDirectory = (uInt32 *) vmmGetFreePage(pid); + /* Set newPageDirectoryAddress To The Newly Created Page Directories Page */ + newPageDirectoryAddress = vmmGetPhysicalAddr((uInt32) newPageDirectory); + /* First Set Up A Flushed Page Directory */ + for (x = 0; x < pageEntries; x++) { + newPageDirectory[x] = (uInt32) 0x0; + } + /* Map The Top 1GB Region Of The VM Space */ + for (x = 768; x < pageEntries; x++) { + newPageDirectory[x] = parentPageDirectory[x]; + } + /* + * Now For The Fun Stuff For Page Tables 1-766 We Must Map These And Set + * The Permissions On Every Mapped Pages To COW This Will Conserve Memory + * Because The Two VM Spaces Will Be Sharing Some Pages + */ + for (x = 1; x <= 766; x++) { + /* If Page Table Exists Map It */ + if (parentPageDirectory[x] != 0) { + /* Set Parent To Propper Page Table */ + parentPageTable = (uInt32 *) (tablesBaseAddress + (4096 * x)); + /* Allocate A New Page Table */ + newPageTable = (uInt32 *) vmmGetFreePage(pid); + /* Set Parent And New Pages To COW */ + for (i = 0; i < pageEntries; i++) { + /* If Page Is Mapped */ + if (parentPageTable[i] != 0x0) { + /* Check To See If Its A Stack Page */ + if (((uInt32) parentPageTable[i] & pageStack) == pageStack) { + /* Alloc A New Page For This Stack Page */ + newStackPage = (uInt32 *) vmmGetFreePage(pid); + /* Set Pointer To Parents Stack Page */ + parentStackPage = (uInt32 *) (((1024 * 4096) * x) + (4096 * i)); + /* Copy The Tack Byte For Byte (I Should Find A Faster Way) */ + for (s = 0; s < pageEntries; s++) { + newStackPage[s] = parentStackPage[s]; + } + /* Insert New Stack Into Page Table */ + newPageTable[i] = ((uInt32) vmmGetPhysicalAddr((uInt32) newStackPage) | pageDefault | pageStack); + /* Unmap From Kernel Space */ + vmmUnmapPage((uInt32) newStackPage, 1); + } else { + /* Set Page To COW In Parent And Child Space */ + newPageTable[i] = (((uInt32) parentPageTable[i] & 0xFFFFF000) | (pagePresent | pageCow)); + /* Increment The COW Counter For This Page */ + if (((uInt32) parentPageTable[i] & pageCow) == pageCow) { + adjustCowCounter(((uInt32) parentPageTable[i] & 0xFFFFF000), 1); + } else { + adjustCowCounter(((uInt32) parentPageTable[i] & 0xFFFFF000), 2); + parentPageTable[i] = newPageTable[i]; + } + } + } else { + newPageTable[i] = (uInt32) 0x0; + } + } + /* Put New Page Table Into New Page Directory */ + newPageDirectory[x] = ((uInt32) vmmGetPhysicalAddr((uInt32) newPageTable) | pageDefault); + /* Unmap Page From Kernel Space But Keep It Marked As Not Avail */ + vmmUnmapPage((uInt32) newPageTable, 1); + } else { + newPageDirectory[x] = (uInt32) 0x0; + } + } + /* + * Allocate A New Page For The The First Page Table Where We Will Map The + * Lower Region + */ + newPageTable = (uInt32 *) vmmGetFreePage(pid); + /* Flush The Page From Garbage In Memory */ + for (x = 0; x < pageEntries; x++) { + newPageTable[x] = (uInt32) 0x0; + } + /* Map This Into The Page Directory */ + newPageDirectory[0] = ((uInt32) vmmGetPhysicalAddr((uInt32) newPageTable) | pageDefault); + /* Set Address Of Parents Page Table */ + parentPageTable = (uInt32 *) tablesBaseAddress; + /* Map The First 1MB Worth Of Pages */ + for (x = 0; x < (pageEntries / 4); x++) { + newPageTable[x] = parentPageTable[x]; + } + /* Map The Next 3MB Worth Of Pages But Make Them COW */ + for (x = (pageEntries / 4) + 1; x < pageEntries; x++) { + /* If Page Is Avaiable Map It */ + if (parentPageTable[x] != 0) { + /* Set Pages To COW */ + newPageTable[x] = (((uInt32) parentPageTable[x] & 0xFFFFF000) | (pagePresent | pageCow)); + /* Increment The COW Counter For This Page */ + if (((uInt32) parentPageTable[x] & pageCow) == pageCow) { + adjustCowCounter(((uInt32) parentPageTable[x] & 0xFFFFF000), 1); + } else { + adjustCowCounter(((uInt32) parentPageTable[x] & 0xFFFFF000), 2); + parentPageTable[x] = newPageTable[x]; + } + } else { + newPageTable[x] = (uInt32) 0x0; + } + } + /* Set Virtual Mapping For Page Directory */ + newPageTable[256] = ((uInt32) vmmGetPhysicalAddr((uInt32) newPageDirectory) | pageDefault); + + /* + * Now The Fun Stuff Build The Initial Virtual Page Space So We Don't Have + * To Worry About Mapping Them In Later How Ever I'm Concerned This May + * Become A Security Issue + */ + /* First Lets Unmap The Previously Allocated Page Table */ + vmmUnmapPage((uInt32) newPageTable, 1); + /* Allocate A New Page Table */ + newPageTable = (uInt32 *) vmmGetFreePage(pid); + /* First Set Our Page Directory To Contain This */ + newPageDirectory[767] = (uInt32) vmmGetPhysicalAddr((uInt32) newPageTable) | pageDefault; + /* Now Lets Build The Page Table */ + for (x = 0; x < pageEntries; x++) { + newPageTable[x] = newPageDirectory[x]; + } + /* Now We Are Done So Lets Unmap This Page */ + vmmUnmapPage((uInt32) newPageTable, 1); + /* Now We Are Done With The Page Directory So Lets Unmap That Too */ + vmmUnmapPage((uInt32) newPageDirectory, 1); + /* Return Physical Address Of Page Directory */ + return (newPageDirectoryAddress); +} + +/*** + END + ***/ + diff --git a/src/sys/vmm/createvirtualspace.c b/src/sys/vmm/createvirtualspace.c new file mode 100644 index 0000000..8a282cb --- /dev/null +++ b/src/sys/vmm/createvirtualspace.c @@ -0,0 +1,130 @@ +/***************************************************************************************** + 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. + + $Log$ + Revision 1.8 2004/04/13 16:36:34 reddawg + Changed our copyright, it is all now under a BSD-Style license + + + + $Id$ + +*****************************************************************************************/ + +#include + + +/************************************************************************ + +Function: void *vmmCreateVirtualSpace(pid_t); +Description: Creates A Virtual Space For A New Task +Notes: + +07/30/02 - This Is Going To Create A New VM Space However Its Going To + Share The Same Top 1GB Space With The Kernels VM And Lower + 1MB Of VM Space With The Kernel + +07/30/02 - Note This Is Going To Get The Top 1Gig And Lower 1MB Region + From The Currently Loaded Page Directory This Is Safe Because + All VM Spaces Will Share These Regions + +07/30/02 - Note I Realized A Mistake The First Page Table Will Need To Be + A Copy But The Page Tables For The Top 1GB Will Not Reason For + This Is That We Just Share The First 1MB In The First Page Table + So We Will Just Share Physical Pages. + +08/02/02 - Added Passing Of pid_t pid For Better Tracking Of Who Has Which + Set Of Pages + +************************************************************************/ +void * +vmmCreateVirtualSpace(pid_t pid) +{ + void *newPageDirectoryAddress = 0x0; + uInt32 *parentPageDirectory = 0x0, *newPageDirectory = 0x0; + uInt32 *parentPageTable = 0x0, *newPageTable = 0x0; + int x = 0; + + /* Set Address Of Parent Page Directory */ + parentPageDirectory = (uInt32 *) parentPageDirAddr; + /* Allocate A New Page For The New Page Directory */ + newPageDirectory = (uInt32 *) vmmGetFreePage(pid); + /* Set newPageDirectoryAddress To The Newly Created Page Directories Page */ + newPageDirectoryAddress = vmmGetPhysicalAddr((uInt32) newPageDirectory); + /* First Set Up A Flushed Page Directory */ + for (x = 0; x < pageEntries; x++) { + (uInt32) newPageDirectory[x] = (uInt32) 0x0; + } + /* Map The Top 1GB Region Of The VM Space */ + for (x = 768; x < pageEntries; x++) { + newPageDirectory[x] = parentPageDirectory[x]; + } + /* + * Allocate A New Page For The The First Page Table Where We Will Map The + * Lower Region + */ + newPageTable = (uInt32 *) vmmGetFreePage(pid); + /* Flush The Page From Garbage In Memory */ + for (x = 0; x < pageEntries; x++) { + (uInt32) newPageTable[x] = (uInt32) 0x0; + } + /* Map This Into The Page Directory */ + newPageDirectory[0] = ((uInt32) vmmGetPhysicalAddr((uInt32) newPageTable) | pageDefault); + /* Set Address Of Parents Page Table */ + parentPageTable = (uInt32 *) tablesBaseAddress; + /* Map The First 1MB Worth Of Pages */ + for (x = 0; x < (pageEntries / 4); x++) { + newPageTable[x] = parentPageTable[x]; + } + /* Set Virtual Mapping For Page Directory */ + newPageTable[256] = ((uInt32) vmmGetPhysicalAddr((uInt32) newPageDirectory) | pageDefault); + + /* + * Now The Fun Stuff Build The Initial Virtual Page Space So We Don't Have + * To Worry About Mapping Them In Later How Ever I'm Concerned This May + * Become A Security Issue + */ + /* First Lets Unmap The Previously Allocated Page Table */ + vmmUnmapPage((uInt32) newPageTable, 1); + /* Allocate A New Page Table */ + newPageTable = (uInt32 *) vmmGetFreePage(pid); + /* First Set Our Page Directory To Contain This */ + newPageDirectory[767] = (uInt32) vmmGetPhysicalAddr((uInt32) newPageTable) | pageDefault; + /* Now Lets Build The Page Table */ + for (x = 0; x < pageEntries; x++) { + newPageTable[x] = newPageDirectory[x]; + } + /* Now We Are Done So Lets Unmap This Page */ + vmmUnmapPage((uInt32) newPageTable, 1); + /* Now We Are Done With The Page Directory So Lets Unmap That Too */ + vmmUnmapPage((uInt32) newPageDirectory, 1); + /* Return Physical Address Of Page Directory */ + return (newPageDirectoryAddress); +} + +/*** + END + ***/ + diff --git a/src/sys/vmm/getfreepage.c b/src/sys/vmm/getfreepage.c new file mode 100644 index 0000000..90d303c --- /dev/null +++ b/src/sys/vmm/getfreepage.c @@ -0,0 +1,79 @@ +/***************************************************************************************** + 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. + + $Log$ + Revision 1.6 2004/04/13 16:36:34 reddawg + Changed our copyright, it is all now under a BSD-Style license + + + + $Id$ + +*****************************************************************************************/ + +#include + +/************************************************************************ + +Function: void *vmmGetFreePage(pidType pid); + +Description: Returns A Free Page Mapped To The VM Space + +Notes: + +07/30/02 - This Returns A Free Page In The Top 1GB For The Kernel + +************************************************************************/ +void * +vmmGetFreePage(pidType pid) +{ + int x = 0x0, y = 0x0; + uInt32 *pageTableSrc = 0x0; + + /* Lets Search For A Free Page */ + for (x = 768; x < 1024; x++) { + + /* Set Page Table Address */ + pageTableSrc = (uInt32 *) (tablesBaseAddress + (4096 * x)); + for (y = 0x0; y < 1024; y++) { + /* Loop Through The Page Table Find An UnAllocated Page */ + if ((uInt32) pageTableSrc[y] == (uInt32) 0x0) { + /* Map A Physical Page To The Virtual Page */ + vmmRemapPage(vmmFindFreePage(pid), ((x * (1024 * 4096)) + (y * 4096))); + /* Clear This Page So No Garbage Is There */ + vmmClearVirtualPage((uInt32) ((x * (1024 * 4096)) + (y * 4096))); + /* Return The Address Of The Newly Allocate Page */ + return ((void *)((x * (1024 * 4096)) + (y * 4096))); + } + } + } + /* If No Free Page Was Found Return NULL */ + return (0x0); +} + +/*** + END + ***/ + diff --git a/src/sys/vmm/getfreevirtualpage.c b/src/sys/vmm/getfreevirtualpage.c new file mode 100644 index 0000000..0b3a666 --- /dev/null +++ b/src/sys/vmm/getfreevirtualpage.c @@ -0,0 +1,117 @@ +/***************************************************************************************** + 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. + + $Log$ + Revision 1.10 2004/04/13 16:36:34 reddawg + Changed our copyright, it is all now under a BSD-Style license + + + + $Id$ + +*****************************************************************************************/ + +#include +#include + +/************************************************************************ + +Function: void *vmmGetFreeVirtualPage(pidType pid,int count); +Description: Returns A Free Page Mapped To The VM Space +Notes: + +08/11/02 - This Will Return Next Avilable Free Page Of Tasks VM Space + +************************************************************************/ +void * +vmmGetFreeVirtualPage(pidType pid, int count) +{ + int x = 0, y = 0, c = 0; + uInt32 *pageTableSrc = 0x0; + uInt32 *pageDir = (uInt32 *) parentPageDirAddr; + + /* Lets Search For A Free Page */ + for (x = (_current->oInfo.vmStart / (1024 * 4096)); x < 1024; x++) { + /* Set Page Table Address */ + if ((pageDir[x] & pagePresent) != pagePresent) { + /* If Page Table Is Non Existant Then Set It Up */ + pageDir[x] = (uInt32) vmmFindFreePage(_current->id) | pageDefault; + /* Also Add It To Virtual Space So We Can Make Changes Later */ + pageTableSrc = (uInt32 *) (tablesBaseAddress + (4096 * 767)); + pageTableSrc[x] = pageDir[x]; + y = 1; + /* Reload Page Directory */ + asm( + "movl %cr3,%eax\n" + "movl %eax,%cr3\n" + ); + } + pageTableSrc = (uInt32 *) (tablesBaseAddress + (0x1000 * x)); + if (y != 0x0) { + for (y = 0x0;y 0x1) { + for (c = 0; c < count; c++) { + if ((uInt32) pageTableSrc[y + c] != (uInt32) 0x0) { + c = -1; + break; + } + } + if (c != -1) { + for (c = 0; c < count; c++) { + vmmRemapPage((uInt32) vmmFindFreePage(pid), ((x * (1024 * 4096)) + ((y + c) * 4096))); + vmmClearVirtualPage((uInt32) ((x * (1024 * 4096)) + ((y + c) * 4096))); + } + return ((void *)((x * (1024 * 4096)) + (y * 4096))); + } + } else { + /* Map A Physical Page To The Virtual Page */ + + /* + * remapPage((uInt32)vmmFindFreePage(pid),((x*(1024*4096))+(y*4096)) + * ,pid); + */ + vmmRemapPage((uInt32) vmmFindFreePage(pid), ((x * (1024 * 4096)) + (y * 4096))); + /* Clear This Page So No Garbage Is There */ + vmmClearVirtualPage((uInt32) ((x * (1024 * 4096)) + (y * 4096))); + /* Return The Address Of The Newly Allocate Page */ + return ((void *)((x * (1024 * 4096)) + (y * 4096))); + } + } + } + } + /* If No Free Page Was Found Return NULL */ + return (0x0); +} + +/*** + END + ***/ + diff --git a/src/sys/vmm/getphysicaladdr.c b/src/sys/vmm/getphysicaladdr.c new file mode 100644 index 0000000..6b936a8 --- /dev/null +++ b/src/sys/vmm/getphysicaladdr.c @@ -0,0 +1,63 @@ +/***************************************************************************************** + 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. + + $Log$ + Revision 1.6 2004/04/13 16:36:34 reddawg + Changed our copyright, it is all now under a BSD-Style license + + + + $Id$ + +*****************************************************************************************/ +#include + +/************************************************************************ + +Function: void *vmmGetPhysicalAddr(); +Description: Returns The Physical Address Of The Virtual Page +Notes: + +************************************************************************/ +void * +vmmGetPhysicalAddr(uInt32 pageAddr) +{ + int pageDirectoryIndex = 0, pageTableIndex = 0; + uInt32 *pageTable = 0x0; + + /* Get The Index To The Page Directory */ + pageDirectoryIndex = (pageAddr / (1024 * 4096)); + /* Get The Index To The Page Table */ + pageTableIndex = ((pageAddr - (pageDirectoryIndex * (1024 * 4096))) / 4096); + /* Set pageTable To The Virtual Address Of Table */ + pageTable = (uInt32 *) (tablesBaseAddress + (4096 * pageDirectoryIndex)); + /* Return The Physical Address Of The Page */ + return ((void *)(pageTable[pageTableIndex] & 0xFFFFF000)); +} + +/*** + END + ***/ + diff --git a/src/sys/vmm/memory.c b/src/sys/vmm/memory.c new file mode 100644 index 0000000..cbbe02a --- /dev/null +++ b/src/sys/vmm/memory.c @@ -0,0 +1,315 @@ +/***************************************************************************************** + 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. + + $Log$ + Revision 1.27 2004/04/13 16:36:34 reddawg + Changed our copyright, it is all now under a BSD-Style license + + + + $Id$ + +*****************************************************************************************/ + +#include +#include +#include +#include +#include +#include + + +mMap *vmmMemoryMap = (mMap *) 0x101000; +int numPages = 0x0; +uInt32 freePages = 0; + + +/************************************************************************ + +Function: void vmmMemMapInit(); +Description: This Function Initializes The Memory Map For the System +Notes: + +02/20/2004 - Made It Report Real And Available Memory + +************************************************************************/ +int +vmmMemMapInit() +{ + int i = 0x0, memStart = 0x0; + + /* Count System Memory */ + numPages = countMemory(); + /* Set Memory Map To Point To First Physical Page That We Will Use */ + vmmMemoryMap = (mMap *) 0x101000; + /* Initialize Map Make All Pages Not Available */ + for (i = 0x0; i < numPages; i++) { + vmmMemoryMap[i].cowCounter = 0x0; + vmmMemoryMap[i].status = memNotavail; + vmmMemoryMap[i].pid = vmmID; + vmmMemoryMap[i].pageAddr = i * 4096; + } + /* Calculate Start Of Free Memory */ + memStart = (0x101000 / 0x1000); + memStart += (((sizeof(mMap) * numPages) + (sizeof(mMap) - 1)) / 0x1000); + /* Initialize All Free Pages To Available */ + vmmMemoryMap[(0x100000 / 0x1000)].status = memAvail; + freePages++; + for (i = memStart; i < numPages; i++) { + vmmMemoryMap[i].status = memAvail; + freePages++; + } + /* Print Out Amount Of Memory */ + kprintf("Real Memory: %iKB\n", numPages * 4); + kprintf("Available Memory: %iKB\n", freePages * 4); + /* Return */ + return (0); +} + +/************************************************************************ + +Function: int countMemory(); +Description: This Function Counts The Systems Physical Memory +Notes: + +02/20/2004 - Inspect For Quality And Approved + +************************************************************************/ +int +countMemory() +{ + register uInt32 *mem = 0x0; + unsigned long memCount = -1, tempMemory = 0x0; + unsigned short memKb = 0; + unsigned char irq1State, irq2State; + unsigned long cr0 = 0x0; + + /* + * Save The States Of Both IRQ 1 And 2 So We Can Turn Them Off And Restore + * Them Later + */ + irq1State = inportByte(0x21); + irq2State = inportByte(0xA1); + + /* Turn Off IRQ 1 And 2 To Prevent Chances Of Faults While Examining Memory */ + outportByte(0x21, 0xFF); + outportByte(0xA1, 0xFF); + + /* Save The State Of Register CR0 */ + asm volatile ( + "movl %%cr0, %%ebx\n" + : "=a" (cr0) + : + : "ebx" + ); + + asm volatile ("wbinvd"); + asm volatile ( + "movl %%ebx, %%cr0\n" + : + : "a" (cr0 | 0x00000001 | 0x40000000 | 0x20000000) + : "ebx" + ); + + while (memKb < 4096 && memCount != 0) { + memKb++; + if (memCount == -1) + memCount = 0; + memCount += 1024 * 1024; + mem = (unsigned long *)memCount; + tempMemory = *mem; + *mem = 0x55AA55AA; +asm("": : :"memory"); + if (*mem != 0x55AA55AA) { + memCount = 0; + } else { + *mem = 0xAA55AA55; + asm("": : :"memory"); + if (*mem != 0xAA55AA55) { + memCount = 0; + } + } +asm("": : :"memory"); + *mem = tempMemory; + } + asm volatile ( + "movl %%ebx, %%cr0\n" + : + : "a" (cr0) + : "ebx" + ); + + /* Restore States For Both IRQ 1 And 2 */ + outportByte(0x21, irq1State); + outportByte(0xA1, irq2State); + /* Return Amount Of Memory In Pages */ + return ((memKb * 1024 * 1024) / 4096); +} + +/************************************************************************ + +Function: uInt32 vmmFindFreePage(pid_t pid); +Description: This Returns A Free Physical Page Address Then Marks It + Not Available As Well As Setting The PID To The Proccess + Allocating This Page +Notes: + +************************************************************************/ +uInt32 +vmmFindFreePage(pidType pid) +{ + int i = 0x0; + + /* Lets Look For A Free Page */ + if (pid < sysID) { + kpanic("Error: invalid PID\n"); + } + for (i = 0; i <= numPages; i++) { + + /* + * If We Found A Free Page Set It To Not Available After That Set Its Own + * And Return The Address + */ + if ((vmmMemoryMap[i].status == memAvail) && (vmmMemoryMap[i].cowCounter == 0)) { + vmmMemoryMap[i].status = memNotavail; + vmmMemoryMap[i].pid = pid; + freePages--; + systemVitals->freePages = freePages; + return (vmmMemoryMap[i].pageAddr); + } + } + /* If No Free Memory Is Found Return NULL */ + kpanic("Out Of Memory!!!!"); + return (0x0); +} + + +/************************************************************************ + +Function: int freePage(uInt32 pageAddr); +Description: This Function Marks The Page As Free +Notes: + +************************************************************************/ +int +freePage(uInt32 pageAddr) +{ + int pageIndex = 0x0; + + /* Find The Page Index To The Memory Map */ + pageIndex = (pageAddr / 4096); + /* Check If Page COW Is Greater Then 0 If It Is Dec It If Not Free It */ + if (vmmMemoryMap[pageIndex].cowCounter == 0) { + /* Set Page As Avail So It Can Be Used Again */ + vmmMemoryMap[pageIndex].status = memAvail; + vmmMemoryMap[pageIndex].cowCounter = 0x0; + vmmMemoryMap[pageIndex].pid = -2; + freePages++; + } else { + /* Adjust The COW Counter */ + adjustCowCounter(((uInt32) vmmMemoryMap[pageIndex].pageAddr), -1); + } + /* Return */ + return (0); +} + +/************************************************************************ + +Function: int adjustCowCounter(uInt32 baseAddr,int adjustment); +Description: This Adjust The COW Counter For Page At baseAddr It Will + Error If The Count Goes Below 0 +Notes: + +08/01/02 - I Think If Counter Gets To 0 I Should Free The Page + +************************************************************************/ +int +adjustCowCounter(uInt32 baseAddr, int adjustment) +{ + int vmmMemoryMapIndex = (baseAddr / 4096); + + /* Adjust COW Counter */ + vmmMemoryMap[vmmMemoryMapIndex].cowCounter += adjustment; + + /* + * kprintf("(%i[%i]%x)\n",vmmMemoryMapIndex,vmmMemoryMap[vmmMemoryMapIndex].cowCounte + * r,baseAddr); + */ + if (vmmMemoryMap[vmmMemoryMapIndex].cowCounter == 0) { + vmmMemoryMap[vmmMemoryMapIndex].status = memAvail; + vmmMemoryMap[vmmMemoryMapIndex].cowCounter = 0x0; + vmmMemoryMap[vmmMemoryMapIndex].pid = vmmID; + freePages++; + } + /* Return */ + return (0); + } + +/************************************************************************ + +Function: void freeProcessPages(pid_t pid); +Description: This Function Will Free Up Memory For The Exiting Process +Notes: + +08/04/02 - Added Checking For COW Pages First +************************************************************************/ +void vmmFreeProcessPages(pidType pid) { + int i=0,x=0; + uLong *tmpPageTable = 0x0; + uLong *tmpPageDir = (uLong *)parentPageDirAddr; + //Check Page Directory For An Avail Page Table + for (i=0;i<=0x300;i++) { + if (tmpPageDir[i] != 0) { + //Set Up Page Table Pointer + tmpPageTable = (uLong *)(tablesBaseAddress + (i * 0x1000)); + //Check The Page Table For COW Pages + for (x=0;xfreePages = freePages; + } + } + } + //Return + } + +/*** + END + ***/ + diff --git a/src/sys/vmm/pagefault.c b/src/sys/vmm/pagefault.c new file mode 100644 index 0000000..b76bfdd --- /dev/null +++ b/src/sys/vmm/pagefault.c @@ -0,0 +1,161 @@ +/***************************************************************************************** + 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. + + $Log$ + Revision 1.4 2004/04/13 16:36:34 reddawg + Changed our copyright, it is all now under a BSD-Style license + + + + $Id$ + +*****************************************************************************************/ + +#include +#include +#include +#include + +/************************************************************************ + +Function: void vmmPageFault(); +Description: This Function Is The Second Half Of The Page Fault ISR + Currently It Handles COW However I Need To Prepar It For + Swapping +Notes: + +07/30/02 - Fixed COW However I Need To Think Of A Way To Impliment + A Paging System Also Start To Add Security Levels + +************************************************************************/ +void vmmPageFault() { + uInt32 memAddr = 0,i = 0, pageTableIndex = 0,pageDirectoryIndex = 0; + uInt32 *pageDir,*pageTable; + uInt32 *src,*dst; + pageDir = (uInt32 *)parentPageDirAddr; + //Get Memory Address For Violation + asm( + "movl %%cr2,%%eax\n" + "movl %%eax,%0\n" + + : "=g" (memAddr) + ); + //Calculate The Page Directory Index + pageDirectoryIndex = (memAddr/(1024*4096)); + //Calculate The Page Table Index + pageTableIndex = ((memAddr-(pageDirectoryIndex*(1024*4096)))/4096); + if (pageDir[pageDirectoryIndex] == 0) { + //Creat A Routine For Non Mapped Memory + kprintf("Segfault At Address: [0x%X][0x%X][%i]\n",memAddr,_current->tss.esp,_current->id); + //if ((uInt32)_current->tss.cr3 != (uInt32)kernelPageDirectory) { + // freeProcessPages(_current->id); + // } + //setTaskStatus(_current->id,EXITING); + //if (_current->id <= -1) { + //kPanic("Kernel Crashed.\n"); + // } + //schedule(); + while (1); + } + else { + //Set pageTable To Point To Virtual Address Of Page Table + pageTable = (uInt32 *)(tablesBaseAddress + (4096 * pageDirectoryIndex)); + if (((uInt32)pageTable[pageTableIndex] & pageCow) == pageCow) { + //Set Src To Base Address Of Page To Copy + src = (uInt32 *) ((1024*4096*pageDirectoryIndex) + (4096*pageTableIndex)); + //Allocate A Free Page For Destination + dst = (uInt32 *) vmmGetFreePage(-1); + //Copy Memory + for (i=0;itss.esp,_current->id); + /* + kprintf("EAX: [0x%X],EBX: [0x%X]\n",_current->tss.eax,_current->tss.ebx); + kprintf("ECX: [0x%X],EDX: [0x%X]\n",_current->tss.ecx,_current->tss.edx); + kprintf("ESP: [0x%X],EPB: [0x%X]\n",_current->tss.esp,_current->tss.ebp); + kprintf("EIP: [0x%X],CR2: [0x%X]\n",_current->tss.eip,memAddr); + kprintf("CS: [0x%X],DS: [0x%X]\n",_current->tss.cs,_current->tss.ds); + kprintf("SS: [0x%X],ES: [0x%X]\n",_current->tss.ss,_current->tss.es); + kprintf("FS: [0x%X],GS: [0x%X]\n",_current->tss.gs,_current->tss.gs); + kprintf("EFLAGS: [0x%X] \n",_current->tss.eflags); + */ + _current->state = DEAD; + /* + if ((uInt32)_current->tss.cr3 != (uInt32)kernelPageDirectory) { + freeProcessPages(_current->id); + } + setTaskStatus(_current->id,EXITING); + if (_current->id <= -1) { + panic(); + } + */ + sched(); + } + } + asm( + "movl %cr3,%eax\n" + "movl %eax,%cr3\n" + ); + } + +/************************************************************************ + +Function: void _pageFault() +Description: This Is The ASM Code That Calls The pageFault() Function +Notes: + +************************************************************************/ +asm( + ".global _vmmPageFault \n" + "_vmmPageFault: \n" + "xchgl %eax,(%esp) \n" + "pushl %ecx \n" + "pushl %edx \n" + "push %ds \n" + "push %es \n" + "push %fs \n" + "call vmmPageFault \n" + "pop %fs \n" + "pop %es \n" + "pop %ds \n" + "popl %edx \n" + "popl %ecx \n" + "popl %eax \n" + "iret \n" + ); + +/*** + END + ***/ diff --git a/src/sys/vmm/paging.c b/src/sys/vmm/paging.c new file mode 100644 index 0000000..5904d21 --- /dev/null +++ b/src/sys/vmm/paging.c @@ -0,0 +1,364 @@ +/***************************************************************************************** + 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. + + $Log$ + Revision 1.30 2004/04/13 16:36:34 reddawg + Changed our copyright, it is all now under a BSD-Style license + + + + $Id$ + +*****************************************************************************************/ + +#include +#include +#include +#include +#include +#include + +uInt32 *kernelPageDirectory = 0x0; + + +/************************************************************************ + +Function: int vmmPagingInit() +Description: This Function Will Initialize The Operating Systems Paging + Abilities. + +Notes: + +02/20/2004 - Looked Over Code And Have Approved Its Quality + +************************************************************************/ + +int +vmmPagingInit() +{ + uInt32 i = 0x0, x = 0x0; + uInt32 *pageTable = 0x0; + + /* Allocate A Page Of Memory For Kernels Page Directory */ + kernelPageDirectory = (uInt32 *) vmmFindFreePage(sysID); + if (kernelPageDirectory == 0x0) { + kpanic("Error: vmmFindFreePage Failed"); + return (0x1); + } + /* Clear The Memory To Ensure There Is No Garbage */ + for (i = 0; i < pageEntries; i++) { + (uInt32) kernelPageDirectory[i] = (uInt32) 0x0; + } + /* Allocate A Page For The First 4MB Of Memory */ + pageTable = (uInt32 *) vmmFindFreePage(sysID); + if (pageTable == 0x0) { + kpanic("Error: vmmFindFreePage Failed"); + return (0x1); + } + kernelPageDirectory[0] = (uInt32) ((uInt32) (pageTable) | pagePresent | pageWrite | pageUser); + /* Make Sure The Page Table Is Clean */ + for (i = 0; i < pageEntries; i++) { + (uInt32) pageTable[i] = (uInt32) 0x0; + } + /* Map The First 1MB Of Memory To The Kernel VM Space */ + for (i = 0; i < (pageEntries / 4); i++) { + pageTable[i] = (uInt32) ((i * 0x1000) | pagePresent | pageWrite | pageUser); + } + + /* + * Create Page Tables For The Top 1GB Of VM Space This Is To Be Shared With + * All VM Spaces + */ + for (i = 768; i < pageEntries; i++) { + pageTable = (uInt32 *) vmmFindFreePage(sysID); + if (pageTable == 0x0) { + kpanic("Error: vmmFindFreePage Failed"); + return (0x1); + } + /* Make Sure The Page Table Is Clean */ + for (x = 0; x < pageEntries; x++) { + (uInt32) pageTable[x] = (uInt32) 0x0; + } + /* Map In The Page Directory */ + kernelPageDirectory[i] = (uInt32) ((uInt32) (pageTable) | pagePresent | pageWrite); + } + /* Set Up Memory To Be All The Allocated Page Directories */ + pageTable = (uInt32 *) vmmFindFreePage(sysID); + if (pageTable == 0x0) { + kpanic("Error: vmmFindFreePage Failed"); + return (0x1); + } + /* Clean Page Table */ + for (x = 0; x < pageEntries; x++) { + (uInt32) pageTable[x] = (uInt32) 0x0; + } + kernelPageDirectory[767] = ((uInt32) pageTable | pagePresent | pageWrite); + for (i = 0; i < pageEntries; i++) { + pageTable[i] = kernelPageDirectory[i]; + } + /* Also Set Up Page Directory To Be The The First Page In 0xE0400000 */ + pageTable = (uInt32 *) (kernelPageDirectory[0] & 0xFFFFF000); + pageTable[256] = (uInt32) ((uInt32) (kernelPageDirectory) | pagePresent | pageWrite); + + /* Now Lets Turn On Paging With This Initial Page Table */ + asm( + "movl %0,%%eax \n" + "movl %%eax,%%cr3 \n" + "movl %%cr0,%%eax \n" + "orl $0x80010000,%%eax \n" /* Flags To Enable Paging With + * Protection */ + "movl %%eax,%%cr0 \n" +: : "d"((uInt32 *) (kernelPageDirectory)) + ); + + /* Remap The Memory List */ + for (i = 0x101000; i <= (0x101000 + (numPages * sizeof(mMap))); i += 0x1000) { + vmmRemapPage(i, (vmmMemoryMapAddr + (i - 0x101000))); + } + /* Set New Address For Memory Map Since Its Relocation */ + vmmMemoryMap = (mMap *) vmmMemoryMapAddr; + + /* Print information on paging */ + kprintf("paging0 - Address: [0x%X], PagingISR Address: [0x%X]\n", kernelPageDirectory, &_vmmPageFault); + + /* Return so we know everything went well */ + return (0x0); +} + +/************************************************************************ + +Function: int vmmRemapPage(Physical Source,Virtual Destination) +Description: This Function Will Remap A Physical Page Into Virtual Space +Notes: + +07/29/02 - Rewrote This To Work With Our New Paging System + +07/30/02 - Changed Address Of Page Tables And Page Directory + +************************************************************************/ +int +vmmRemapPage(uInt32 source, uInt32 dest) +{ + uInt16 destPageDirectoryIndex = 0, destPageTableIndex = 0; + uInt32 *pageDir, *pageTable; + int i = 0x0; + + /* + * Set Pointer pageDirectory To Point To The Virtual Mapping Of The Page + * Directory + */ + pageDir = (uInt32 *) parentPageDirAddr; + /* Check To See If Page Table Exists */ + destPageDirectoryIndex = (dest / (1024 * 4096)); + if ((pageDir[destPageDirectoryIndex] & pagePresent) != pagePresent) { + /* If Page Table Is Non Existant Then Set It Up */ + pageDir[destPageDirectoryIndex] = (uInt32) vmmFindFreePage(sysID) | pageDefault; + i = 1; + /* Also Add It To Virtual Space So We Can Make Changes Later */ + pageTable = (uInt32 *) (tablesBaseAddress + (4096 * 767)); + pageTable[destPageDirectoryIndex] = pageDir[destPageDirectoryIndex]; + /* Reload Page Directory */ + asm( + "movl %cr3,%eax\n" + "movl %eax,%cr3\n" + ); + } + /* Set Address To Page Table */ + pageTable = (uInt32 *) (tablesBaseAddress + (4096 * destPageDirectoryIndex)); + if (i != 0x0) { + for (i=0x0;i 1) { + for (c = 0; c < count; c++) { + if ((uInt32) pageTableSrc[y + c] != (uInt32) 0x0) { + c = -1; + break; + } + } + if (c != -1) { + for (c = 0; c < count; c++) { + vmmRemapPage((uInt32) vmmFindFreePage(pid), ((x * (1024 * 4096)) + ((y + c) * 4096))); + vmmClearVirtualPage((uInt32) ((x * (1024 * 4096)) + ((y + c) * 4096))); + } + return ((void *)((x * (1024 * 4096)) + (y * 4096))); + } + } else { + /* Map A Physical Page To The Virtual Page */ + + /* + * vmmRemapPage((uInt32)vmmFindFreePage(pid),((x*(1024*4096))+(y*409 + * 6)),pid); + */ + vmmRemapPage((uInt32) vmmFindFreePage(pid), ((x * (1024 * 4096)) + (y * 4096))); + /* Clear This Page So No Garbage Is There */ + vmmClearVirtualPage((uInt32) ((x * (1024 * 4096)) + (y * 4096))); + /* Return The Address Of The Newly Allocate Page */ + return ((void *)((x * (1024 * 4096)) + (y * 4096))); + } + } + } + } + /* If No Free Page Was Found Return NULL */ + return (0x0); +} + + +/************************************************************************ + +Function: void vmmClearVirtualPage(uInt32 pageAddr); + +Description: This Will Null Out A Page Of Memory + +Notes: + +************************************************************************/ +int +vmmClearVirtualPage(uInt32 pageAddr) +{ + uInt32 *src = 0x0; + int counter = 0x0; + + /* Set Source Pointer To Virtual Page Address */ + src = (uInt32 *) pageAddr; + + /* Clear Out The Page */ + for (counter = 0x0; counter < pageEntries; counter++) { + (uInt32) src[counter] = (uInt32) 0x0; + } + + /* Return */ + return (0x0); +} + + +void *vmmMapFromTask(pidType pid,void *ptr,uInt32 size) { + kTask_t *child = 0x0; + uInt32 i = 0x0,x = 0x0,y = 0x0,count = ((size+4095)/0x1000),c = 0x0; + uInt16 dI = 0x0,tI = 0x0; + uInt32 baseAddr = 0x0,offset = 0x0; + uInt32 *childPageDir = (uInt32 *)0x5A00000; + uInt32 *childPageTable = 0x0; + uInt32 *pageTableSrc = 0x0; + offset = (uInt32)ptr & 0xFFF; + baseAddr = (uInt32)ptr & 0xFFFFF000; + child = schedFindTask(pid); + //Calculate The Page Table Index And Page Directory Index + dI = (baseAddr/(1024*4096)); + tI = ((baseAddr-(dI*(1024*4096)))/4096); + vmmRemapPage(child->tss.cr3,0x5A00000); + for (i=0;i<0x1000;i++) { + vmmRemapPage(childPageDir[i],0x5A01000 + (i * 0x1000)); + } + for (x=(_current->oInfo.vmStart/(1024*4096));x<1024;x++) { + pageTableSrc = (uInt32 *)(tablesBaseAddress + (4096*x)); + for (y=0;y<1024;y++) { + //Loop Through The Page Table Find An UnAllocated Page + if ((uInt32)pageTableSrc[y] == (uInt32)0x0) { + if (count > 1) { + for (c=0;((c= 0x1000) { + dI++; + tI = 0-c; + } + childPageTable = (uInt32 *)(0x5A01000 + (0x1000 * dI)); + vmmRemapPage(childPageTable[tI+c],((x*(1024*4096))+((y+c)*4096))); + } + vmmUnmapPage(0x5A00000,1); + for (i=0;i<0x1000;i++) { + vmmUnmapPage((0x5A01000 + (i*0x1000)),1); + } + return((void *)((x*(1024*4096))+(y*4096)+offset)); + } + } + else { + //Map A Physical Page To The Virtual Page + childPageTable = (uInt32 *)(0x5A01000 + (0x1000 * dI)); + vmmRemapPage(childPageTable[tI],((x*(1024*4096))+(y*4096))); + //Return The Address Of The Mapped In Memory + vmmUnmapPage(0x5A00000,1); + for (i=0;i<0x1000;i++) { + vmmUnmapPage((0x5A01000 + (i*0x1000)),1); + } + return((void *)((x*(1024*4096))+(y*4096)+offset)); + } + } + } + } + return(0x0); + } + +/*** + END + ***/ + diff --git a/src/sys/vmm/setpageattributes.c b/src/sys/vmm/setpageattributes.c new file mode 100644 index 0000000..c7bb3c4 --- /dev/null +++ b/src/sys/vmm/setpageattributes.c @@ -0,0 +1,74 @@ +/***************************************************************************************** + 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. + + $Log$ + Revision 1.6 2004/04/13 16:36:34 reddawg + Changed our copyright, it is all now under a BSD-Style license + + + + $Id$ + +*****************************************************************************************/ + +#include + +/************************************************************************ + +Function: void vmmSetPageAttributes(uInt32 pageAddr,int attributes; +Description: This Function Will Set The Page Attributes Such As + A Read Only Page, Stack Page, COW Page, ETC. +Notes: + +************************************************************************/ +void +vmmSetPageAttribute(uInt32 pageAddr, int attributes) +{ + int directoryIndex, tableIndex; + uInt32 *pageTable; + + /* Get Index To Page Directory */ + directoryIndex = (pageAddr / (1024 * 4096)); + /* Get Index To Page Table */ + tableIndex = ((pageAddr - (directoryIndex * (1024 * 4096))) / 4096); + /* Set Table Pointer */ + pageTable = (uInt32 *) (tablesBaseAddress + (4096 * directoryIndex)); + /* Set Attribute If Page Is Mapped */ + if (pageTable[tableIndex] != 0) { + pageTable[tableIndex] = ((pageTable[tableIndex] & 0xFFFFF000) | attributes); + } + /* Reload The Page Table; */ + asm( + "movl %cr3,%eax\n" + "movl %eax,%cr3\n" + ); + /* Return */ + return; +} + +/*** + END + ***/ + diff --git a/src/sys/vmm/unmappage.c b/src/sys/vmm/unmappage.c new file mode 100644 index 0000000..0ce4be6 --- /dev/null +++ b/src/sys/vmm/unmappage.c @@ -0,0 +1,123 @@ +/***************************************************************************************** + 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. + + $Log$ + Revision 1.7 2004/04/13 16:36:34 reddawg + Changed our copyright, it is all now under a BSD-Style license + + + + $Id$ + +*****************************************************************************************/ + +#include + +/************************************************************************ + +Function: void vmmUnmapPage(uInt32 pageAddr,int flags); +Description: This Function Will Unmap A Page From The Kernel VM Space + The Flags Variable Decides If Its To Free The Page Or Not + A Flag Of 0 Will Free It And A Flag Of 1 Will Keep It +Notes: + +07/30/02 - I Have Decided That This Should Free The Physical Page There + Is No Reason To Keep It Marked As Not Available + +07/30/02 - Ok A Found A Reason To Keep It Marked As Available I Admit + Even I Am Not Perfect Ok The Case Where You Wouldn't Want To + Free It Would Be On Something Like Where I Allocated A Page + To Create A New Virtual Space So Now It Has A Flag + +************************************************************************/ +void +vmmUnmapPage(uInt32 pageAddr, int flags) +{ + int pageDirectoryIndex = 0, pageTableIndex = 0; + uInt32 *pageTable = 0x0; + + /* Get The Index To The Page Directory */ + pageDirectoryIndex = (pageAddr / (1024 * 4096)); + /* Get The Index To The Page Table */ + pageTableIndex = ((pageAddr - (pageDirectoryIndex * (1024 * 4096))) / 4096); + /* Set pageTable To The Virtual Address Of Table */ + pageTable = (uInt32 *) (tablesBaseAddress + (4096 * pageDirectoryIndex)); + /* Free The Physical Page If Flags Is 0 */ + if (flags == 0) { + + /* + * This is temp i think its still an issue clearVirtualPage(pageAddr); + * freePage((uInt32)(pageTable[pageTableIndex] & 0xFFFFF000)); + */ + } + /* Unmap The Page */ + pageTable[pageTableIndex] = 0x0; + /* Rehash The Page Directory */ + asm( + "movl %cr3,%eax\n" + "movl %eax,%cr3\n" + ); + /* Return */ + return; +} + + + +/************************************************************************ + +Function: void vmmUnmapPages(uInt32 pageAddr,int flags); +Description: This Function Will Unmap A Page From The Kernel VM Space + The Flags Variable Decides If Its To Free The Page Or Not + A Flag Of 0 Will Free It And A Flag Of 1 Will Keep It +Notes: + +07/30/02 - I Have Decided That This Should Free The Physical Page There + Is No Reason To Keep It Marked As Not Available + +07/30/02 - Ok A Found A Reason To Keep It Marked As Available I Admit + Even I Am Not Perfect Ok The Case Where You Wouldn't Want To + Free It Would Be On Something Like Where I Allocated A Page + To Create A New Virtual Space So Now It Has A Flag + +************************************************************************/ +void vmmUnmapPages(void *ptr,uInt32 size) { + uInt32 baseAddr = (uInt32)ptr & 0xFFFFF000; + uInt32 dI = 0x0,tI = 0x0; + uInt32 y = 0x0; + uInt32 *pageTable = 0x0; + + dI = (baseAddr/(1024*4096)); + tI = ((baseAddr-(dI*(1024*4096)))/4096); + pageTable = (uInt32 *)(tablesBaseAddress + (4096*dI)); + for (y=tI;y<(tI+((size+4095)/4096));y++) { + pageTable[y] = 0x0; + } + return; + } + +/*** + END + ***/ + diff --git a/src/sys/vmm/vmminit.c b/src/sys/vmm/vmminit.c new file mode 100644 index 0000000..e97d558 --- /dev/null +++ b/src/sys/vmm/vmminit.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. + + $Log$ + Revision 1.4 2004/04/13 16:36:34 reddawg + Changed our copyright, it is all now under a BSD-Style license + + + + $Id$ + +*****************************************************************************************/ + +#include + +/************************************************************************ + +Function: int vmmInit() + +Description: Initializes the vmm subsystem + +Notes: + +************************************************************************/ +int +vmmInit() +{ + if (vmmMemMapInit() != 0x0) { + return (0x1); + } + if (vmmPagingInit() != 0x0) { + return (0x1); + } + return (0x0); +} + +/*** + END + ***/ + diff --git a/src/tools/Makefile b/src/tools/Makefile new file mode 100644 index 0000000..6bfb593 --- /dev/null +++ b/src/tools/Makefile @@ -0,0 +1,59 @@ +# $Id$ +# Kernel Makefile (C) 2002 The UbixOS Project + +# Include Global 'Source' Options +include ../Makefile.inc + +CC=gcc + +#Kernel File Name +BINARY = format + +#Objects +OBJS = format.o + +# Link the kernel statically with fixed text+data address @1M +$(BINARY) : $(OBJS) + $(CC) -o $@ $(OBJS) + +# Compile the source files +.cc.o: + $(CXX) -Wall -fomit-frame-pointer -O -I../sys/include -c -o $@ $< + +.cc.s: + $(CXX) -Wall -fomit-frame-pointer -O -I../sys/include -S -o $@ $< + +.c.o: + $(CC) -Wall -O -c -o $@ $< + +.c.s: + $(CC) -Wall -fomit-frame-pointer -O -I../sys/include -S -o $@ $< + +.S.o: + $(CC) -Wall -fomit-frame-pointer -c -o $@ $< + +# Clean up the junk +clean: + $(REMOVE) $(OBJS) $(BINARY) *.core + +format-dsk: + (cp ../sys/compile/ubix.elf ./) + (cp ../bin/init/init ./) + (cp ../bin/login/login ./) + (cp ../bin/shell/shell ./) + (cp ../bin/ls/ls ./) + (cp ../bin/clock/clock ./) + (cp ../lib/libc/libc.so ./) + (cp ../bin/muffin/muffin ./) + (cp ../bin/cp/cp ./) + (./format 50 2000 /dev/fd0 ubix.elf 0 ROM8X14.DPF 3754 init 3754 login 3754 shell 3754 userdb 3754 ls 3754 motd 3754 clock 3754 libc.so 3754 cp 3754) + (./format 50 2000 /dev/md1 ubix.elf 0 muffin 3754 shell 3754 motd 3754 libc.so 3754) + (rm -fr ubix.elf) + (rm -fr login) + (rm -fr init) + (rm -fr shell) + (rm -fr ls) + (rm -fr clock) + (rm -fr libc.so) + (rm -fr cp) + (rm -fr muffin) diff --git a/src/tools/OLDENG.DPF b/src/tools/OLDENG.DPF new file mode 100644 index 0000000..e542aca --- /dev/null +++ b/src/tools/OLDENG.DPF Binary files differ diff --git a/src/tools/PACMAN.DPF b/src/tools/PACMAN.DPF new file mode 100644 index 0000000..4db8522 --- /dev/null +++ b/src/tools/PACMAN.DPF Binary files differ diff --git a/src/tools/ROM8X14.DPF b/src/tools/ROM8X14.DPF new file mode 100644 index 0000000..376a5ef --- /dev/null +++ b/src/tools/ROM8X14.DPF Binary files differ diff --git a/src/tools/SCRIPT.DPF b/src/tools/SCRIPT.DPF new file mode 100755 index 0000000..8adf710 --- /dev/null +++ b/src/tools/SCRIPT.DPF Binary files differ diff --git a/src/tools/format.c b/src/tools/format.c new file mode 100644 index 0000000..584f63c --- /dev/null +++ b/src/tools/format.c @@ -0,0 +1,155 @@ +#include +#include +#include +#include "./ubixfs.h" + +#define typeFile 1 +#define typeContainer 2 +#define typeDirectory 4 + + +//Michelle My Bell + +struct blockAllocationTableEntry *BAT = 0x0; + +int findFreeBlock(int cBlock,int size) { + int i = 0x0; + for (i=1;isize = (size/512); + partInfo->startSector = (startSector+1); + partInfo->blockAllocationTable = (startSector+1); + partInfo->rootDirectory = ((startSector+1) + (batSize/512)); + fseek(driveFd,(startSector * 512),0); + fwrite(partInfo,512,1,driveFd); + startSector++; + dirEntry[0].attributes = typeDirectory; + dirEntry[0].permissions = 0xEAA; + dirEntry[0].gid = 0x0; + dirEntry[0].uid = 0x0; + dirEntry[0].startCluster = 0x0; + dirEntry[0].size = 0x4000; + sprintf(dirEntry[0].fileName,":"); + dirEntry[1].attributes = typeDirectory; + dirEntry[1].permissions = 0xEAA; + dirEntry[1].gid = 0x0; + dirEntry[1].uid = 0x0; + dirEntry[1].startCluster = 0x0; + dirEntry[1].size = 0x4000; + sprintf(dirEntry[1].fileName,".."); + BAT[0].nextBlock = 0x1; + BAT[0].attributes = 1; + BAT[0].realSector = (batSize/512); + BAT[1].nextBlock = 0x2; + BAT[1].attributes = 1; + BAT[1].realSector = (batSize/512) + 1 * 8; + BAT[2].nextBlock = 0x3; + BAT[2].attributes = 1; + BAT[2].realSector = (batSize/512) + 2 * 8; + BAT[3].nextBlock = -1; + BAT[3].attributes = 1; + BAT[3].realSector = (batSize/512) + 3 * 8; + + for (i=4;i<(size/4096);i++) { + BAT[i].nextBlock = -1; + BAT[i].attributes = 0x0; + BAT[i].realSector = ((batSize/512) + (i*8)); + BAT[i].reserved = 0x0; + } + file = 0x2; + while (x < argc) { + counter = 0x0; + blockCount = 0x0; + fileFd = fopen(argv[x],"rb"); + block = findFreeBlock(-1,(size/4096)); + dirEntry[file].startCluster = block; + dirEntry[file].attributes = typeFile; + dirEntry[file].permissions = atoi(argv[x+1]); + rewind(driveFd); + /* fseek(driveFd,((BAT[startSector].realSector * 512) + ((batSize/512)+(BAT[block].realSector*4096))),0); */ + fseek(driveFd,((startSector + BAT[block].realSector) * 512),0); + while (!feof(fileFd)) { + if (4096 == (counter - (blockCount * 4096))) { + block = findFreeBlock(block,(size/4096)); + printf("Block: [%i][%s]\n",block,argv[x]); + rewind(driveFd); + /* fseek(driveFd,((startSector * 512) + ((batSize/512)+(BAT[block].realSector*4096))),0); */ + fseek(driveFd,((startSector + BAT[block].realSector) * 512),0); + blockCount++; + } + fputc(fgetc(fileFd),driveFd); + counter++; + } + i = 0; + while((counter + i)%512) { + fputc(0x0,driveFd); + i++; + } + fclose(fileFd); + dirEntry[file].size = (counter - 1); + dirEntry[file].uid = 0x0; + dirEntry[file].gid = 0x0; + sprintf(dirEntry[file].fileName,"%s",argv[x]); + x += 2; + file++; + } + dirEntry[1].attributes = typeDirectory; + dirEntry[1].permissions = 0xEAA; + dirEntry[1].gid = 0x0; + dirEntry[1].uid = 0x0; + dirEntry[1].startCluster = 0x0; + dirEntry[1].size = 0x4000; + sprintf(dirEntry[1].fileName,"fakeDir"); + rewind(driveFd); + fseek(driveFd,(long)((startSector * 512) + batSize),0); + fwrite(dirEntry,0x4000,1,driveFd); + rewind(driveFd); + fseek(driveFd,(startSector * 512),0); + if (fwrite(BAT,batSize,1,driveFd) >= 1) { +/* + * printf("size [%i]\n",partInfo->size); + * printf("startSector: [%i]\n",partInfo->startSector); + * printf("bat: [%i]\n",partInfo->blockAllocationTable); + * printf("rootDir: [%i]\n",partInfo->rootDirectory); + * printf("sizeof: [%i]\n",sizeof(struct blockAllocationTableEntry)); + * printf("size: [%i]\n",(size/4096)); + */ + printf("Formatted!\n"); + } + else { + printf("Error Formatting!!\n"); + } + fclose(driveFd); + return(0); + } diff --git a/src/tools/makeuser.c b/src/tools/makeuser.c new file mode 100644 index 0000000..29d6ce5 --- /dev/null +++ b/src/tools/makeuser.c @@ -0,0 +1,52 @@ +#include + +struct passwd { + char username[32]; + char passwd[32]; + int uid; + int gid; + char shell[128]; + char realname[256]; + char path[256]; + }; + +int main(int argc,char **argv) { + int i = 0x0; + struct passwd *password = 0x0; + FILE *out; + password = (struct passwd *)malloc(4096); + out = fopen("./userdb","wbb"); + sprintf(password[0].username,"root"); + sprintf(password[0].passwd,"user"); + sprintf(password[0].shell,"shell@sys"); + sprintf(password[0].realname,"Root User"); + sprintf(password[0].path,"root"); + password[0].uid = 0; + password[0].gid = 0; + sprintf(password[1].username,"guest"); + sprintf(password[1].passwd,"user"); + sprintf(password[1].shell,"shell@sys"); + sprintf(password[1].realname,"Guest User"); + sprintf(password[1].path,"guest"); + password[1].uid = 1; + password[1].gid = 1; + sprintf(password[2].username,"reddawg"); + sprintf(password[2].passwd,"temp123"); + sprintf(password[2].shell,"shell@sys"); + sprintf(password[2].realname,"Christopher"); + sprintf(password[2].path,"reddawg"); + password[2].uid = 1000; + password[2].gid = 1000; + fwrite(password,4096,1,out); + fclose(out); + for (i=0;i<3;i++) { + printf("User: [%s]\n",password[i].username); + printf("Pass: [%s]\n",password[i].passwd); + printf("UID: [%i]\n",password[i].uid); + printf("GID: [%i]\n",password[i].gid); + printf("Shell: [%s]\n",password[i].shell); + printf("Name: [%s]\n",password[i].realname); + printf("Path: [%s]\n",password[i].path); + } + return(0); + } diff --git a/src/tools/mbr.img b/src/tools/mbr.img new file mode 100644 index 0000000..a574013 --- /dev/null +++ b/src/tools/mbr.img Binary files differ diff --git a/src/tools/motd b/src/tools/motd new file mode 100644 index 0000000..bc2e693 --- /dev/null +++ b/src/tools/motd @@ -0,0 +1,8 @@ +Welcome to UbixOS +This is an experimental kernel so it WILL crash and when +it does please send us some info so we can fix it or +if you have access to the source fix it and commit the +changes. + +All reports can be sent to colsen@domainatlantic.com + diff --git a/src/tools/ubixfs.h b/src/tools/ubixfs.h new file mode 100644 index 0000000..608d97f --- /dev/null +++ b/src/tools/ubixfs.h @@ -0,0 +1,77 @@ +/************************************************************************************** + 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$ + +**************************************************************************************/ + +#ifndef _UBIXFS_H +#define _UBIXFS_H + +typedef unsigned long uLong; +typedef unsigned short uShort; +typedef unsigned char uChar; +typedef unsigned int uInt; + +//Partition Information +struct partitionInformation { + uLong size; //Size In Sectors + uLong startSector; //Base Sector Of Partition + uLong blockAllocationTable; //Base Sector Of BAT + uLong rootDirectory; //Base Sector Of Root Directory + }; + +//Block Allocation Table Entry +struct blockAllocationTableEntry { + long attributes; //Block Attributes + long realSector; //Real Sector + long nextBlock; //Sector Of Next Block + long reserved; //Reserved + }; + +//UbixFS Directory Entry +struct directoryEntry { + uLong startCluster; //Starting Cluster Of File + uLong size; //Size Of File + uLong creationDate; //Date Created + uLong lastModified; //Date Last Modified + uLong uid; //UID Of Owner + uLong gid; //GID Of Owner + uShort attributes; //Files Attributes + uShort permissions; //Files Permissions + char fileName[256]; //File Name + }; + + +struct bootSect { + uChar jmp[4]; + uChar id[6]; + uShort version; + uShort tmp; + uShort fsStart; + uShort tmp2; + uLong krnl_start; + uInt BytesPerSector; + uInt SectersPerTrack; + uInt TotalHeads; + uLong TotalSectors; + uChar code[479]; + }; + +#endif diff --git a/src/tools/user.c b/src/tools/user.c new file mode 100644 index 0000000..4e89daf --- /dev/null +++ b/src/tools/user.c @@ -0,0 +1,31 @@ +#include + +struct passwd { + char username[32]; + char passwd[32]; + int uid; + int gid; + char shell[128]; + char realname[256]; + char path[256]; + }; + +int main(int argc,char **argv) { + int i = 0x0; + struct passwd *password = 0x0; + FILE *in; + password = (struct passwd *)malloc(4096); + in = fopen("./userdb","rb"); + fread(password,4096,1,in); + fclose(in); + for (i=0;i<3;i++) { + printf("User: [%s]\n",password[i].username); + printf("Pass: [%s]\n",password[i].passwd); + printf("UID: [%i]\n",password[i].uid); + printf("GID: [%i]\n",password[i].gid); + printf("Shell: [%s]\n",password[i].shell); + printf("Name: [%s]\n",password[i].realname); + printf("Path: [%s]\n",password[i].path); + } + return(0); + } diff --git a/src/tools/userdb b/src/tools/userdb new file mode 100644 index 0000000..2b1853e --- /dev/null +++ b/src/tools/userdb Binary files differ