eabort.c B~ abort() { exit(99); } abs.c B~ # abs(i){ return i < 0 ? -i : i; } access.c B~ #include "../include/lib.h" PUBLIC int access(name, mode) char *name; int mode; { return callm3(FS, ACCESS, mode, name); } alarm.c B~ #include "../include/lib.h" PUBLIC int alarm(sec) unsigned sec; { return callm1(MM, ALARM, (int) sec, 0, 0, NIL_PTR, NIL_PTR, NIL_PTR); } atoi.c B~ #define isascii(c) (((unsigned) (c) & 0xFF) < 0200) /* For all the following functions the parameter must be ASCII */ #define _between(a,b,c) ((unsigned) ((b) - (a)) < (c) - (a)) #define isupper(c) _between('A', c, 'Z') #define islower(c) _between('a', c, 'z') #define isdigit(c) _between('0', c, '9') #define isprint(c) _between(' ', c, '~') /* The others are problematic as the parameter may only be evaluated once */ static _c_; /* used to store the evaluated parameter */ #define isalpha(c) (isupper(_c_ = (c)) || islower(_c_)) #define isalnum(c) (isalpha(c) || isdigit(_c_)) #define _isblank(c) ((_c_ = (c)) == ' ' || _c_ == '\t') #define isspace(c) (_isblank(c) || _c_=='\r' || _c_=='\n' || _c_=='\f') #define iscntrl(c) ((_c_ = (c)) == 0177 || _c_ < ' ') atoi(s) register char *s; { register int total = 0; register unsigned digit; register minus = 0; while (isspace(*s)) s++; if (*s == '-') { s++; minus = 1; } while ((digit = *s++ - '0') < 10) { total *= 10; total += digit; } return(minus ? -total : total); } atol.c B~ ?#include "../include/ctype.h" long atol(s) register char *s; { register long total = 0; register unsigned digit; register minus = 0; while (isspace(*s)) s++; if (*s == '-') { s++; minus = 1; } while ((digit = *s++ - '0') < 10) { total *= 10; total += digit; } return(minus ? -total : total); } tbcopy.c B~ t bcopy(old, new, n) register char *old, *new; int n; { /* Copy a block of data. */ while (n--) *new++ = *old++; } brk.c B~ #include "../include/lib.h" extern char *brksize; PUBLIC char *brk(addr) char *addr; { int k; k = callm1(MM, BRK, 0, 0, 0, addr, NIL_PTR, NIL_PTR); if (k == OK) { brksize = M.m2_p1; return(NIL_PTR); } else { return( (char*) -1 ); } } PUBLIC char *sbrk(incr) char *incr; { char *newsize, *oldsize; extern int endv, dorgv; oldsize = brksize; newsize = brksize + (int) incr; if (brk(newsize) == 0) return(oldsize); else return( (char *) -1 ); } brk2.c B~ #include "../include/lib.h" PUBLIC brk2() { char *p1, *p2; p1 = (char *) get_size(); callm1(MM, BRK2, 0, 0, 0, p1, p2, NIL_PTR); } _call.c B~ '#include "../include/lib.h" PUBLIC int errno; /* place where error numbers go */ PUBLIC int callm1(proc, syscallnr, int1, int2, int3, ptr1, ptr2, ptr3) int proc; /* FS or MM */ int syscallnr; /* which system call */ int int1; /* first integer parameter */ int int2; /* second integer parameter */ int int3; /* third integer parameter */ char *ptr1; /* pointer parameter */ char *ptr2; /* pointer parameter */ char *ptr3; /* pointer parameter */ { /* Send a message and get the response. The 'M.m_type' field of the * reply contains a value (>= 0) or an error code (<0). Use message format m1. */ M.m1_i1 = int1; M.m1_i2 = int2; M.m1_i3 = int3; M.m1_p1 = ptr1; M.m1_p2 = ptr2; M.m1_p3 = ptr3; return callx(proc, syscallnr); } PUBLIC int callm3(proc, syscallnr, int1, name) int proc; /* FS or MM */ int syscallnr; /* which system call */ int int1; /* integer parameter */ char *name; /* string */ { /* This form of system call is used for those calls that contain at most * one integer parameter along with a string. If the string fits in the * message, it is copied there. If not, a pointer to it is passed. */ register int k; register char *rp; k = len(name); M.m3_i1 = k; M.m3_i2 = int1; M.m3_p1 = name; rp = &M.m3_ca1[0]; if (k <= M3_STRING) while (k--) *rp++ = *name++; return callx(proc, syscallnr); } PUBLIC int callx(proc, syscallnr) int proc; /* FS or MM */ int syscallnr; /* which system call */ { /* Send a message and get the response. The 'M.m_type' field of the * reply contains a value (>= 0) or an error code (<0). */ int k; M.m_type = syscallnr; k = sendrec(proc, &M); if (k != OK) return(k); /* send itself failed */ if (M.m_type < 0) {errno = -M.m_type; return(-1);} return(M.m_type); } PUBLIC int len(s) register char *s; /* character string whose length is needed */ { /* Return the length of a character string, including the 0 at the end. */ register int k; k = 0; while (*s++ != 0) k++; return(k+1); /* return length including the 0-byte at end */ } chdir.c B~ j #include "../include/lib.h" PUBLIC int chdir(name) char *name; { return callm3(FS, CHDIR, 0, name); } chmod.c B~ } #include "../include/lib.h" PUBLIC int chmod(name, mode) char* name; int mode; { return callm3(FS, CHMOD, mode, name); } rchown.c C~ #include "../include/lib.h" PUBLIC int chown(name, owner, grp) char *name; int owner, grp; { return callm1(FS, CHOWN, len(name), owner, grp, name, NIL_PTR, NIL_PTR); } )chroot.c C~ l #include "../include/lib.h" PUBLIC int chroot(name) char* name; { return callm3(FS, CHROOT, 0, name); } cleanup.c C~ #include "../include/stdio.h" _cleanup() { register int i; for ( i = 0 ; i < NFILES ; i++ ) if ( _io_table[i] != NULL ) fflush(_io_table[i]); } Sclose.c C~ #include "../include/lib.h" PUBLIC int close(fd) int fd; { return callm1(FS, CLOSE, fd, 0, 0, NIL_PTR, NIL_PTR, NIL_PTR); } creat.c C~ | #include "../include/lib.h" PUBLIC int creat(name, mode) char* name; int mode; { return callm3(FS, CREAT, mode, name); } crypt.c C~ pchar *crypt(pw, salt) char *pw, *salt; { static char buf[14]; register char bits[67]; register int i; register int j, rot; for (i=0; i < 67; i++) bits[i] = 0; if (salt[1] == 0) salt[1] = salt[0]; rot = (salt[1] * 4 - salt[0]) % 128; for (i=0; *pw && i < 8; i++) { for (j=0; j < 7; j++) bits[i+j*8] = (*pw & (1 << j) ? 1 : 0); bits[i+56] = (salt[i / 4] & (1 << (i % 4)) ? 1 : 0); pw++; } bits[64] = (salt[0] & 1 ? 1 : 0); bits[65] = (salt[1] & 1 ? 1 : 0); bits[66] = (rot & 1 ? 1 : 0); while (rot--) { for (i=65; i >= 0; i--) bits[i+1] = bits[i]; bits[0] = bits[66]; } for (i=0; i < 12; i++) { buf[i+2] = 0; for (j=0; j < 6; j++) buf[i+2] |= (bits[i*6+j] ? (1 << j) : 0); buf[i+2] += 48; if (buf[i+2] > '9') buf[i+2] += 7; if (buf[i+2] > 'Z') buf[i+2] += 6; } buf[0] = salt[0]; buf[1] = salt[1]; buf[13] = '\0'; return(buf); } ctype.c C~ l#include "../include/ctype.h" char _ctype_[] = { 0, _C, _C, _C, _C, _C, _C, _C, _C, _C, _S, _S, _S, _S, _S, _C, _C, _C, _C, _C, _C, _C, _C, _C, _C, _C, _C, _C, _C, _C, _C, _C, _C, _S, _P, _P, _P, _P, _P, _P, _P, _P, _P, _P, _P, _P, _P, _P, _P, _N, _N, _N, _N, _N, _N, _N, _N, _N, _N, _P, _P, _P, _P, _P, _P, _P, _U|_X, _U|_X, _U|_X, _U|_X, _U|_X, _U|_X, _U, _U, _U, _U, _U, _U, _U, _U, _U, _U, _U, _U, _U, _U, _U, _U, _U, _U, _U, _U, _P, _P, _P, _P, _P, _P, _L|_X, _L|_X, _L|_X, _L|_X, _L|_X, _L|_X, _L, _L, _L, _L, _L, _L, _L, _L, _L, _L, _L, _L, _L, _L, _L, _L, _L, _L, _L, _L, _P, _P, _P, _P, _C }; doprintf.c C~ #include "../include/stdio.h" #define MAXDIGITS 12 #define PRIVATE static /* This is the same as varargs , on BSD systems */ #define GET_ARG(arglist,mode) ((mode *)(arglist += sizeof(mode)))[-1] _doprintf(fp, format, args) FILE *fp; register char *format; int args; { register char *vl; int r, w1, w2, sign; long l; char c; char *s; char padchar; char a[MAXDIGITS]; vl = (char *) args; while ( *format != '\0') { if ( *format != '%' ) { putc( *format++, fp ); continue; } w1 = 0; w2 = 0; sign = 1; padchar = ' '; format++; if ( *format == '-' ) { sign = -1; format++; } if ( *format == '0') { padchar = '0'; format++; } while ( *format >='0' && *format <='9' ){ w1 = 10 * w1 + sign * ( *format - '0' ); format++; } if ( *format == '.'){ format++; while ( *format >='0' && *format <='9' ){ w2 = 10 * w2 + ( *format - '0' ); format++; } } switch (*format) { case 'd': l = (long) GET_ARG(vl, int); r = 10; break; case 'u': l = (long) GET_ARG(vl, int); l = l & 0xFFFF; r = 10; break; case 'o': l = (long) GET_ARG(vl, int); if (l < 0) l = l & 0xFFFF; r = 8; break; case 'x': l = (long) GET_ARG(vl, int); if (l < 0) l = l & 0xFFFF; r = 16; break; case 'D': l = (long) GET_ARG(vl, long); r = 10; break; case 'O': l = (long) GET_ARG(vl, long); r = 8; break; case 'X': l = (long) GET_ARG(vl, long); r = 16; break; case 'c': c = (char) GET_ARG(vl, int); /* char's are casted back to int's */ putc( c, fp); format++; continue; case 's': s = GET_ARG(vl, char *); _printit(s,w1,w2,padchar,strlen(s),fp); format++; continue; default: putc('%',fp); putc(*format++,fp); continue; } _bintoascii (l, r, a); _printit(a,w1,w2,padchar,strlen(a),fp); format++; } } PRIVATE _bintoascii (num, radix, a) long num; int radix; char *a; { char b[MAXDIGITS]; int hit, negative; register int n, i; negative = 0; if (num == 0) { a[0] = '0'; a[1] = '\0'; return; } if (radix == 10) { if (num < 0) {num = -num; negative++;} } for (n = 0; n < MAXDIGITS; n++) b[n] = 0; n = 0; do { if (radix == 10) { b[n] = num % 10; num = (num - b[n]) / 10; } if (radix == 8) { b[n] = num & 0x7; num = (num >> 3) & 0x1FFFFFFF; } if (radix == 16) { b[n] = num & 0xF; num = (num >> 4) & 0x0FFFFFFF; } n++; } while (num != 0); /* Convert to ASCII. */ hit = 0; for (i = n - 1; i >= 0; i--) { if (b[i] == 0 && hit == 0) { b[i] = ' '; } else { if (b[i] < 10) b[i] += '0'; else b[i] += 'A' - 10; hit++; } } if (negative) b[n++] = '-'; for(i = n - 1 ; i >= 0 ; i-- ) *a++ = b[i]; *a = '\0'; } PRIVATE _printit(str, w1, w2, padchar, length, file) char *str; int w1, w2; char padchar; int length; FILE *file; { int len2 = length; int temp; if ( w2 > 0 && length > w2) len2 = w2; temp = len2; if ( w1 > 0 ) while ( w1 > len2 ){ --w1; putc(padchar,file); } while ( *str && ( len2-- != 0 )) putc(*str++, file); if ( w1 < 0 ) if ( padchar == '0' ){ putc('.',file); w1++; } while ( w1 < -temp ){ w1++; putc(padchar,file); } } dup.c C~ { #include "../include/lib.h" PUBLIC int dup(fd) int fd; { return callm1(FS, DUP, fd, 0, 0, NIL_PTR, NIL_PTR, NIL_PTR); } 'dup2.c C~ #include "../include/lib.h" PUBLIC int dup2(fd, fd2) int fd, fd2; { return callm1(FS, DUP, fd+0100, fd2, 0, NIL_PTR, NIL_PTR, NIL_PTR); } exec.c C~ #include "../include/lib.h" char *nullptr[1]; /* the EXEC calls need a zero pointer */ PUBLIC int execl(name, arg0) char *name; char *arg0; { return execve(name, &arg0, nullptr); } PUBLIC int execle(name, argv) char *name, *argv; { char **p; p = (char **) &argv; while (*p++) /* null statement */ ; return execve(name, &argv, *p); } PUBLIC int execv(name, argv) char *name, *argv[]; { return execve(name, argv, nullptr); } PUBLIC int execve(name, argv, envp) char *name; /* pointer to name of file to be executed */ char *argv[]; /* pointer to argument array */ char *envp[]; /* pointer to environment */ { char stack[MAX_ISTACK_BYTES]; char **argorg, **envorg, *hp, **ap, *p; int i, nargs, nenvps, stackbytes, ptrsize, offset; /* Count the argument pointers and environment pointers. */ nargs = 0; nenvps = 0; argorg = argv; envorg = envp; while (*argorg++ != NIL_PTR) nargs++; while (*envorg++ != NIL_PTR) nenvps++; ptrsize = sizeof(NIL_PTR); /* Prepare to set up the initial stack. */ hp = &stack[(nargs + nenvps + 3) * ptrsize]; if (hp + nargs + nenvps >= &stack[MAX_ISTACK_BYTES]) return(E2BIG); ap = (char **) stack; *ap++ = (char *) nargs; /* Prepare the argument pointers and strings. */ for (i = 0; i < nargs; i++) { offset = hp - stack; *ap++ = (char *) offset; p = *argv++; while (*p) { *hp++ = *p++; if (hp >= &stack[MAX_ISTACK_BYTES]) return(E2BIG); } *hp++ = (char) 0; } *ap++ = NIL_PTR; /* Prepare the environment pointers and strings. */ for (i = 0; i < nenvps; i++) { offset = hp - stack; *ap++ = (char *) offset; p = *envp++; while (*p) { *hp++ = *p++; if (hp >= &stack[MAX_ISTACK_BYTES]) return(E2BIG); } *hp++ = (char) 0; } *ap++ = NIL_PTR; stackbytes = ( ( (hp - stack) + ptrsize - 1)/ptrsize) * ptrsize; return callm1(MM_PROC_NR, EXEC, len(name), stackbytes, 0,name, stack,NIL_PTR); } PUBLIC execn(name) char *name; /* pointer to file to be exec'd */ { /* Special version used when there are no args and no environment. This call * is principally used by INIT, to avoid having to allocate MAX_ISTACK_BYTES. */ char stack[4]; stack[0] = 0; stack[1] = 0; stack[2] = 0; stack[3] = 0; return callm1(MM_PROC_NR, EXEC, len(name), 4, 0, name, stack, NIL_PTR); } kexit.c C~ #include "../include/lib.h" PUBLIC int exit(status) int status; { return callm1(MM, EXIT, status, 0, 0, NIL_PTR, NIL_PTR, NIL_PTR); } fclose.c C~ :#include "../include/stdio.h" fclose(fp) FILE *fp; { register int i; for (i=0; i<NFILES; i++) if (fp == _io_table[i]) { _io_table[i] = 0; break; } if (i >= NFILES) return(EOF); fflush(fp); close(fp->_fd); if ( testflag(fp,IOMYBUF) && fp->_buf ) free( fp->_buf ); free(fp); return(NULL); } fflush.c D~ o#include "../include/stdio.h" fflush(iop) FILE *iop; { int count; if ( testflag(iop,UNBUFF) || !testflag(iop,WRITEMODE) ) return(0); if ( iop->_count <= 0 ) return(0); count = write(iop->_fd,iop->_buf,iop->_count); if ( count == iop->_count) { iop->_count = 0; iop->_ptr = iop->_buf; return(count); } iop->_flags |= _ERR; return(EOF); } )fgets.c D~ <#include "../include/stdio.h" char *fgets(str, n, file) char *str; unsigned n; FILE *file; { register int ch; register char *ptr; ptr = str; while ( --n > 0 && (ch = getc(file)) != EOF){ *ptr++ = ch; if ( ch == '\n') break; } if (ch == EOF && ptr==str) return(NULL); *ptr = '\0'; return(str); } fopen.c D~ #include "../include/stdio.h" #define PMODE 0644 FILE *fopen(name,mode) char *name , *mode; { register int i; FILE *fp; char *malloc(); int fd, flags = 0; for (i = 0; _io_table[i] != 0 ; i++) if ( i >= NFILES ) return(NULL); switch(*mode){ case 'w': flags |= WRITEMODE; if (( fd = creat (name,PMODE)) < 0) return(NULL); break; case 'a': flags |= WRITEMODE; if (( fd = open(name,1)) < 0 ) return(NULL); lseek(fd,0L,2); break; case 'r': flags |= READMODE; if (( fd = open (name,0)) < 0 ) return(NULL); break; default: return(NULL); } if (( fp = (FILE *) malloc (sizeof( FILE))) == NULL ) return(NULL); fp->_count = 0; fp->_fd = fd; fp->_flags = flags; fp->_buf = malloc( BUFSIZ ); if ( fp->_buf == NULL ) fp->_flags |= UNBUFF; else fp->_flags |= IOMYBUF; fp->_ptr = fp->_buf; _io_table[i] = fp; return(fp); } Dfork.c D~ r #include "../include/lib.h" PUBLIC int fork() { return callm1(MM, FORK, 0, 0, 0, NIL_PTR, NIL_PTR, NIL_PTR); } fprintf.c D~ @#include "../include/stdio.h" fprintf (file, fmt, args) FILE *file; char *fmt; int args; { _doprintf (file, fmt, &args); if ( testflag(file,PERPRINTF) ) fflush(file); } printf (fmt, args) char *fmt; int args; { _doprintf (stdout, fmt, &args); if ( testflag(stdout,PERPRINTF) ) fflush(stdout); } fputs.c D~ q #include "../include/stdio.h" fputs(s,file) register char *s; FILE *file; { while ( *s ) putc(*s++,file); } ,fread.c D~ i#include "../include/stdio.h" fread(ptr, size, count, file) char *ptr; unsigned size, count; FILE *file; { register int c; unsigned ndone = 0, s; ndone = 0; if (size) while ( ndone < count ) { s = size; do { if ((c = getc(file)) != EOF) *ptr++ = (char) c; else return(ndone); } while (--s); ndone++; } return(ndone); } tfreopen.c E~ #include "../include/stdio.h" FILE *freopen(name,mode,stream) char *name,*mode; FILE *stream; { FILE *fopen(); if ( fclose(stream) != 0 ) return NULL; return fopen(name,mode); } fseek.c E~ i#include "../include/stdio.h" fseek(iop, offset, where) FILE *iop; long offset; { int count; long lseek(); long pos; iop->_flags &= ~(_EOF | _ERR); /* Clear both the end of file and error flags */ if ( testflag(iop,READMODE) ) { if ( where < 2 && iop->_buf && !testflag(iop,UNBUFF) ) { count = iop->_count; pos = offset; if ( where == 0 ) pos += count - lseek(fileno(iop), 0L,1) - 1; /*^^^ This caused the problem : - 1 corrected it */ else offset -= count; if ( count > 0 && pos <= count && pos >= iop->_buf - iop->_ptr ) { iop->_ptr += (int) pos; iop->_count -= (int) pos; return(0); } } pos = lseek(fileno(iop), offset, where); iop->_count = 0; } else if ( testflag(iop,WRITEMODE) ) { fflush(iop); pos = lseek(fileno(iop), offset, where); } return((pos == -1) ? -1 : 0 ); } fstat.c E~ #include "../include/lib.h" PUBLIC int fstat(fd, buffer) int fd; char *buffer; { int n; n = callm1(FS, FSTAT, fd, 0, 0, buffer, NIL_PTR, NIL_PTR); return(n); } ftell.c E~ #include "../include/stdio.h" long ftell(iop) FILE *iop; { long result; long lseek(); int adjust = 0; if ( testflag(iop,READMODE) ) adjust -= iop->_count; else if ( testflag(iop,WRITEMODE) && iop->_buf && !testflag(iop,UNBUFF)) adjust = iop->_ptr - iop->_buf; else return(-1); result = lseek(fileno(iop), 0L, 1); if ( result < 0 ) return ( result ); result += (long) adjust; return(result); } fwrite.c F~ F#include "../include/stdio.h" fwrite(ptr, size, count, file) unsigned size, count; char *ptr; FILE *file; { unsigned s; unsigned ndone = 0; if (size) while ( ndone < count ) { s = size; do { putc(*ptr++, file); if (ferror(file)) return(ndone); } while (--s); ndone++; } return(ndone); } getc.c F~ M#include "../include/stdio.h" getc(iop) FILE *iop; { int ch; if ( testflag(iop, (_EOF | _ERR ))) return (EOF); if ( !testflag(iop, READMODE) ) return (EOF); if (--iop->_count <= 0){ if ( testflag(iop, UNBUFF) ) iop->_count = read(iop->_fd,&ch,1); else iop->_count = read(iop->_fd,iop->_buf,BUFSIZ); if (iop->_count <= 0){ if (iop->_count == 0) iop->_flags |= _EOF; else iop->_flags |= _ERR; return (EOF); } else iop->_ptr = iop->_buf; } if (testflag(iop,UNBUFF)) return (ch & CMASK); else return (*iop->_ptr++ & CMASK); } lgetegid.c F~ #include "../include/lib.h" PUBLIC gid getegid() { int k; k = callm1(MM, GETGID, 0, 0, 0, NIL_PTR, NIL_PTR, NIL_PTR); if (k < 0) return ( (gid) k); return( (gid) M.m2_i1); } >getenv.c F~ #define NULL (char *) 0 char *getenv(name) register char *name; { extern char **environ; register char **v = environ, *p, *q; while ((p = *v) != NULL) { q = name; while (*p++ == *q) if (*q++ == 0) continue; if (*(p - 1) != '=') continue; return(p); } return(0); } ogeteuid.c F~ #include "../include/lib.h" PUBLIC uid geteuid() { int k; k = callm1(MM, GETUID, 0, 0, 0, NIL_PTR, NIL_PTR, NIL_PTR); if (k < 0) return ( (uid) k); return ((uid) M.m2_i1); } +getgid.c F~ #include "../include/lib.h" PUBLIC gid getgid() { int k; k = callm1(MM, GETGID, 0, 0, 0, NIL_PTR, NIL_PTR, NIL_PTR); return( (gid) k); } getgrent.c F~ /* * get entry from group file * * By: Patrick van Kleef */ #include "../include/grp.h" #define PRIVATE static PRIVATE char _gr_file[] = "/etc/group"; PRIVATE char _grbuf[256]; PRIVATE char _buffer[1024]; PRIVATE char *_pnt; PRIVATE char *_buf; PRIVATE int _gfd = -1; PRIVATE int _bufcnt; PRIVATE struct group grp; setgrent () { if (_gfd >= 0) lseek (_gfd, 0L, 0); else _gfd = open (_gr_file, 0); _bufcnt = 0; return (_gfd); } endgrent () { if (_gfd >= 0) close (_gfd); _gfd = -1; _bufcnt = 0; } static getline () { if (_gfd < 0 && setgrent () < 0) return (0); _buf = _grbuf; do { if (--_bufcnt <= 0){ if ((_bufcnt = read (_gfd, _buffer, 1024)) <= 0) return (0); else _pnt = _buffer; } *_buf++ = *_pnt++; } while (*_pnt != '\n'); _pnt++; _bufcnt--; *_buf = 0; _buf = _grbuf; return (1); } static skip_period () { while (*_buf != ':') _buf++; *_buf++ = '\0'; } struct group *getgrent () { if (getline () == 0) return (0); grp.name = _buf; skip_period (); grp.passwd = _buf; skip_period (); grp.gid = atoi (_buf); skip_period (); return (&grp); } struct group *getgrnam (name) char *name; { struct group *grp; setgrent (); while ((grp = getgrent ()) != 0) if (!strcmp (grp -> name, name)) break; endgrent (); if (grp != 0) return (grp); else return (0); } struct group *getgrgid (gid) int gid; { struct group *grp; setgrent (); while ((grp = getgrent ()) != 0) if (grp -> gid == gid) break; endgrent (); if (grp != 0) return (grp); else return (0); } getpass.c F~ #include "../h/sgtty.h" static char pwdbuf[9]; char * getpass(prompt) char *prompt; { int i = 0; struct sgttyb tty; prints(prompt); ioctl(0, TIOCGETP, &tty); tty.sg_flags = 06020; ioctl(0, TIOCSETP, &tty); i = read(0, pwdbuf, 9); while (pwdbuf[i - 1] != '\n') read(0, &pwdbuf[i - 1], 1); pwdbuf[i - 1] = '\0'; tty.sg_flags = 06030; ioctl(0, TIOCSETP, &tty); prints("\n"); return(pwdbuf); } getpid.c F~ v #include "../include/lib.h" PUBLIC int getpid() { return callm1(MM, GETPID, 0, 0, 0, NIL_PTR, NIL_PTR, NIL_PTR); } getpwent.c F~ /* * get entry from password file * * By Patrick van Kleef * */ #include "../include/pwd.h" #define PRIVATE static PRIVATE char _pw_file[] = "/etc/passwd"; PRIVATE char _pwbuf[256]; PRIVATE char _buffer[1024]; PRIVATE char *_pnt; PRIVATE char *_buf; PRIVATE int _pw = -1; PRIVATE int _bufcnt; PRIVATE struct passwd pwd; setpwent() { if (_pw >= 0) lseek (_pw, 0L, 0); else _pw = open (_pw_file, 0); _bufcnt = 0; return (_pw); } endpwent () { if (_pw >= 0) close (_pw); _pw = -1; _bufcnt = 0; } static getline () { if (_pw < 0 && setpwent () < 0) return (0); _buf = _pwbuf; do { if (--_bufcnt <= 0){ if ((_bufcnt = read (_pw, _buffer, 1024)) <= 0) return (0); else _pnt = _buffer; } *_buf++ = *_pnt++; } while (*_pnt != '\n'); _pnt++; _bufcnt--; *_buf = 0; _buf = _pwbuf; return (1); } static skip_period () { while (*_buf != ':') _buf++; *_buf++ = '\0'; } struct passwd *getpwent () { if (getline () == 0) return (0); pwd.name = _buf; skip_period (); pwd.passwd = _buf; skip_period (); pwd.uid = atoi (_buf); skip_period (); pwd.gid = atoi (_buf); skip_period (); pwd.gecos = _buf; skip_period (); pwd.dir = _buf; skip_period (); pwd.shell = _buf; return (&pwd); } struct passwd *getpwnam (name) char *name; { struct passwd *pwd; setpwent (); while ((pwd = getpwent ()) != 0) if (!strcmp (pwd -> name, name)) break; endpwent (); if (pwd != 0) return (pwd); else return (0); } struct passwd *getpwuid (uid) int uid; { struct passwd *pwd; setpwent (); while ((pwd = getpwent ()) != 0) if (pwd -> uid == uid) break; endpwent (); if (pwd != 0) return (pwd); else return (0); } gets.c F~ #include "../include/stdio.h" char *gets(str) char *str; { register int ch; register char *ptr; ptr = str; while ((ch = getc(stdin)) != EOF && ch != '\n') *ptr++ = ch; if (ch == EOF && ptr==str) return(NULL); *ptr = '\0'; return(str); } agetuid.c F~ #include "../include/lib.h" PUBLIC uid getuid() { int k; k = callm1(MM, GETUID, 0, 0, 0, NIL_PTR, NIL_PTR, NIL_PTR); return( (uid) k); } index.c G~ q char *index(s, c) register char *s, c; { do { if (*s == c) return(s); } while (*s++ != 0); return(0); } Iioctl.c G~ #include "../include/lib.h" #include "../h/com.h" #include "../include/sgtty.h" PUBLIC int ioctl(fd, request, u) int fd; int request; union { struct sgttyb *argp; struct tchars *argt; } u; { int n; long erase, kill, intr, quit, xon, xoff, eof, brk; M.TTY_REQUEST = request; M.TTY_LINE = fd; switch(request) { case TIOCSETP: erase = u.argp->sg_erase & 0377; kill = u.argp->sg_kill & 0377; M.TTY_SPEK = (erase << 8) | kill; M.TTY_FLAGS = u.argp->sg_flags; n = callx(FS, IOCTL); return(n); case TIOCSETC: intr = u.argt->t_intrc & 0377; quit = u.argt->t_quitc & 0377; xon = u.argt->t_startc & 0377; xoff = u.argt->t_stopc & 0377; eof = u.argt->t_eofc & 0377; brk = u.argt->t_brkc & 0377; /* not used at the moment */ M.TTY_SPEK = (intr<<24) | (quit<<16) | (xon<<8) | (xoff<<0); M.TTY_FLAGS = (eof<<8) | (brk<<0); n = callx(FS, IOCTL); return(n); case TIOCGETP: n = callx(FS, IOCTL); u.argp->sg_erase = (M.TTY_SPEK >> 8) & 0377; u.argp->sg_kill = (M.TTY_SPEK >> 0) & 0377; u.argp->sg_flags = M.TTY_FLAGS; return(n); case TIOCGETC: n = callx(FS, IOCTL); u.argt->t_intrc = (M.TTY_SPEK >> 24) & 0377; u.argt->t_quitc = (M.TTY_SPEK >> 16) & 0377; u.argt->t_startc = (M.TTY_SPEK >> 8) & 0377; u.argt->t_stopc = (M.TTY_SPEK >> 0) & 0377; u.argt->t_eofc = (M.TTY_FLAGS >> 8) & 0377; u.argt->t_brkc = (M.TTY_FLAGS >> 8) & 0377; return(n); default: n = -1; errno = -(EINVAL); return(n); } } isatty.c G~ #include "../include/stat.h" int isatty(fd) int fd; { struct stat s; fstat(fd, &s); if ( (s.st_mode&S_IFMT) == S_IFCHR) return(1); else return(0); } >itoa.c G~ /* Integer to ASCII for signed decimal integers. */ static int next; static char qbuf[8]; char *itoa(n) int n; { register int r, k; int flag = 0; next = 0; if (n < 0) { qbuf[next++] = '-'; n = -n; } if (n == 0) { qbuf[next++] = '0'; } else { k = 10000; while (k > 0) { r = n/k; if (flag || r > 0) { qbuf[next++] = '0' + r; flag = 1; } n -= r * k; k = k/10; } } qbuf[next] = 0; return(qbuf); } kill.c G~ #include "../include/lib.h" PUBLIC int kill(proc, sig) int proc; /* which process is to be sent the signal */ int sig; /* signal number */ { return callm1(MM, KILL, proc, sig, 0, NIL_PTR, NIL_PTR, NIL_PTR); } link.c G~ #include "../include/lib.h" PUBLIC int link(name, name2) char *name, *name2; { return callm1(FS, LINK, len(name), len(name2), 0, name, name2, NIL_PTR); } lseek.c G~ #include "../include/lib.h" PUBLIC long lseek(fd, offset, whence) int fd; long offset; int whence; { int k; M.m2_i1 = fd; M.m2_l1 = offset; M.m2_i2 = whence; k = callx(FS, LSEEK); if (k != OK) return( (long) k); /* send itself failed */ return(M.m2_l1); } malloc.c G~ #define CLICK_SIZE 16 typedef unsigned short vir_bytes; extern bcopy(); #define ALIGN(x, a) (((x) + (a - 1)) & ~(a - 1)) #define BUSY 1 #define NEXT(p) (* (char **) (p)) extern char *sbrk(); static char *bottom, *top; static grow(len) unsigned len; { register char *p; p = (char *) ALIGN((vir_bytes) top + sizeof(char *) + len, CLICK_SIZE) - sizeof(char *); if (p < top || brk(p) < 0) return(0); top = p; for (p = bottom; NEXT(p) != 0; p = (char *) (* (vir_bytes *) p & ~BUSY)) ; NEXT(p) = top; NEXT(top) = 0; return(1); } char *malloc(size) unsigned size; { register char *p, *next, *new; register unsigned len = ALIGN(size, sizeof(char *)) + sizeof(char *); if ((p = bottom) == 0) { top = bottom = p = sbrk(sizeof(char *)); NEXT(top) = 0; } while ((next = NEXT(p)) != 0) if ((vir_bytes) next & BUSY) /* already in use */ p = (char *) ((vir_bytes) next & ~BUSY); else { while ((new = NEXT(next)) != 0 && !((vir_bytes) new & BUSY)) next = new; if (next - p >= len) { /* fits */ if ((new = p + len) < next) /* too big */ NEXT(new) = next; NEXT(p) = (char *) ((vir_bytes) new | BUSY); return(p + sizeof(char *)); } p = next; } return grow(len) ? malloc(size) : 0; } char *realloc(old, size) char *old; unsigned size; { register char *p = old - sizeof(char *), *next, *new; register unsigned len = ALIGN(size, sizeof(char *)) + sizeof(char *), n; next = (char *) (* (vir_bytes *) p & ~BUSY); n = next - old; /* old size */ while ((new = NEXT(next)) != 0 && !((vir_bytes) new & BUSY)) next = new; if (next - p >= len) { /* does it still fit */ if ((new = p + len) < next) { /* even too big */ NEXT(new) = next; NEXT(p) = (char *) ((vir_bytes) new | BUSY); } else NEXT(p) = (char *) ((vir_bytes) next | BUSY); return(old); } if ((new = malloc(size)) == 0) /* it didn't fit */ return(0); bcopy(old, new, n); /* n < size */ * (vir_bytes *) p &= ~BUSY; return(new); } free(p) char *p; { * (vir_bytes *) (p - sizeof(char *)) &= ~BUSY; } !message.c H~ ; #include "../h/const.h" #include "../h/type.h" message M; mknod.c H~ #include "../include/lib.h" PUBLIC int mknod(name, mode, addr) char *name; int mode, addr; { return callm1(FS, MKNOD, len(name), mode, addr, name, NIL_PTR, NIL_PTR); } )mktemp.c H~ /* mktemp - make a name for a temporary file */ char *mktemp(template) char *template; { int pid, k; char *p; pid = getpid(); /* get process id as semi-unique number */ p = template; while (*p++) ; /* find end of string */ p--; /* backup to last character */ /* Replace XXXXXX at end of template with pid. */ while (*--p == 'X') { *p = '0' + (pid % 10); pid = pid/10; } return(template); } mount.c H~ #include "../include/lib.h" PUBLIC int mount(special, name, rwflag) char *name, *special; int rwflag; { return callm1(FS, MOUNT, len(special), len(name), rwflag, special, name, NIL_PTR); } open.c H~ z #include "../include/lib.h" PUBLIC int open(name, mode) char* name; int mode; { return callm3(FS, OPEN, mode, name); } pause.c H~ t #include "../include/lib.h" PUBLIC int pause() { return callm1(MM, PAUSE, 0, 0, 0, NIL_PTR, NIL_PTR, NIL_PTR); } perror.c H~ /* perror(s) print the current error message. */ #include "../h/error.h" extern int errno; char *error_message[NERROR+1] = { "Error 0", "Not owner", "No such file or directory", "No such process", "Interrupted system call", "I/O error", "No such device or address", "Arg list too long", "Exec format error", "Bad file number", "No children", "No more processes", "Not enough core", "Permission denied", "Bad address", "Block device required", "Mount device busy", "File exists", "Cross-device link", "No such device", "Not a directory", "Is a directory", "Invalid argument", "File table overflow", "Too many open files", "Not a typewriter", "Text file busy", "File too large", "No space left on device", "Illegal seek", "Read-only file system", "Too many links", "Broken pipe", "Math argument", "Result too large" }; perror(s) char *s; { if (errno < 0 || errno > NERROR) { write(2, "Invalid errno\n", 14); } else { write(2, s, slen(s)); write(2, ": ", 2); write(2, error_message[errno], slen(error_message[errno])); write(2, "\n", 1); } } static int slen(s) char *s; { int k = 0; while (*s++) k++; return(k); } pipe.c H~ #include "../include/lib.h" PUBLIC int pipe(fild) int fild[2]; { int k; k = callm1(FS, PIPE, 0, 0, 0, NIL_PTR, NIL_PTR, NIL_PTR); if (k >= 0) { fild[0] = M.m1_i1; fild[1] = M.m1_i2; return(0); } else return(k); } printdat.c I~ s#include "../include/stdio.h" char __stdin[BUFSIZ]; char __stdout[BUFSIZ]; struct _io_buf _stdin = { 0, 0, READMODE , __stdin, __stdin }; struct _io_buf _stdout = { 1, 0, WRITEMODE + PERPRINTF, __stdout, __stdout }; struct _io_buf _stderr = { 2, 0, WRITEMODE + UNBUFF, NULL, NULL }; struct _io_buf *_io_table[NFILES] = { &_stdin, &_stdout, &_stderr, 0 }; sprintk.c I~ Y/* This is a special version of printf. It is used only by the operating * system itself, and should never be included in user programs. The name * printk never appears in the operating system, because the macro printf * has been defined as printk there. */ #define MAXDIGITS 12 printk(s, arglist) char *s; int *arglist; { int w, k, r, *valp; unsigned u; long l, *lp; char a[MAXDIGITS], *p, *p1, c; valp = (int *) &arglist; while (*s != '\0') { if (*s != '%') { putc(*s++); continue; } w = 0; s++; while (*s >= '0' && *s <= '9') { w = 10 * w + (*s - '0'); s++; } lp = (long *) valp; switch(*s) { case 'd': k = *valp++; l = k; r = 10; break; case 'o': k = *valp++; u = k; l = u; r = 8; break; case 'x': k = *valp++; u = k; l = u; r = 16; break; case 'D': l = *lp++; r = 10; valp = (int *) lp; break; case 'O': l = *lp++; r = 8; valp = (int *) lp; break; case 'X': l = *lp++; r = 16; valp = (int *) lp; break; case 'c': k = *valp++; putc(k); s++; continue; case 's': p = (char *) *valp++; p1 = p; while(c = *p++) putc(c); s++; if ( (k = w - (p-p1-1)) > 0) while (k--) putc(' '); continue; default: putc('%'); putc(*s++); continue; } k = bintoascii(l, r, a); if ( (r = w - k) > 0) while(r--) putc(' '); for (r = k - 1; r >= 0; r--) putc(a[r]); s++; } } static int bintoascii(num, radix, a) long num; int radix; char a[MAXDIGITS]; { int i, n, hit, negative; negative = 0; if (num == 0) {a[0] = '0'; return(1);} if (num < 0 && radix == 10) {num = -num; negative++;} for (n = 0; n < MAXDIGITS; n++) a[n] = 0; n = 0; do { if (radix == 10) {a[n] = num % 10; num = (num -a[n])/10;} if (radix == 8) {a[n] = num & 0x7; num = (num >> 3) & 0x1FFFFFFF;} if (radix == 16) {a[n] = num & 0xF; num = (num >> 4) & 0x0FFFFFFF;} n++; } while (num != 0); /* Convert to ASCII. */ hit = 0; for (i = n - 1; i >= 0; i--) { if (a[i] == 0 && hit == 0) { a[i] = ' '; } else { if (a[i] < 10) a[i] += '0'; else a[i] += 'A' - 10; hit++; } } if (negative) a[n++] = '-'; return(n); } Gprints.c I~ /* prints() is like printf(), except that it can only handle %s and %c. It * cannot print any of the numeric types such as %d, %o, etc. It has the * advantage of not requiring the runtime code for converting binary numbers * to ASCII, which saves 1K bytes in the object program. Since many of the * small utilities do not need numeric printing, they all use prints. */ #define TRUNC_SIZE 128 char Buf[TRUNC_SIZE], *Bufp; #define OUT 1 prints(s, arglist) register char *s; int *arglist; { register w; int k, r, *valp; char *p, *p1, c; Bufp = Buf; valp = (int *) &arglist; while (*s != '\0') { if (*s != '%') { put(*s++); continue; } w = 0; s++; while (*s >= '0' && *s <= '9') { w = 10 * w + (*s - '0'); s++; } switch(*s) { case 'c': k = *valp++; put(k); s++; continue; case 's': p = (char *) *valp++; p1 = p; while(c = *p++) put(c); s++; if ( (k = w - (p-p1-1)) > 0) while (k--) put(' '); continue; default: put('%'); put(*s++); continue; } } write(OUT, Buf, Bufp - Buf); /* write everything in one blow. */ } static put(c) char c; { if (Bufp < &Buf[TRUNC_SIZE]) *Bufp++ = c; } +putc.c I~ #include "../include/stdio.h" putc(ch, iop) char ch; FILE *iop; { int n, didwrite = 0; if (testflag(iop, (_ERR | _EOF))) return (EOF); if ( !testflag(iop,WRITEMODE)) return(EOF); if ( testflag(iop,UNBUFF)){ n = write(iop->_fd,&ch,1); iop->_count = 1; didwrite++; } else{ *iop->_ptr++ = ch; if ((++iop->_count) >= BUFSIZ && !testflag(iop,STRINGS) ){ n = write(iop->_fd,iop->_buf,iop->_count); iop->_ptr = iop->_buf; didwrite++; } } if (didwrite){ if (n<=0 || iop->_count != n){ if (n < 0) iop->_flags |= _ERR; else iop->_flags |= _EOF; return (EOF); } iop->_count=0; } return(0); } rand.c I~ | static long seed = 1L; int rand() { seed = (1103515245L * seed + 12345) & 0x7FFFFFFF; return((int) (seed & 077777)); } read.c I~ #include "../include/lib.h" PUBLIC int read(fd, buffer, nbytes) int fd; char *buffer; int nbytes; { int n; n = callm1(FS, READ, fd, nbytes, 0, buffer, NIL_PTR, NIL_PTR); return(n); } regexp.c I~ l/* * regcomp and regexec -- regsub and regerror are elsewhere * * Copyright (c) 1986 by University of Toronto. * Written by Henry Spencer. Not derived from licensed software. * * Permission is granted to anyone to use this software for any * purpose on any computer system, and to redistribute it freely, * subject to the following restrictions: * * 1. The author is not responsible for the consequences of use of * this software, no matter how awful, even if they arise * from defects in it. * * 2. The origin of this software must not be misrepresented, either * by explicit claim or by omission. * * 3. Altered versions must be plainly marked as such, and must not * be misrepresented as being the original software. * * Beware that some of this code is subtly aware of the way operator * precedence is structured in regular expressions. Serious changes in * regular-expression syntax might require a total rethink. * * The third parameter to regexec was added by Martin C. Atkins. * Andy Tanenbaum also made some changes. */ #include "../include/stdio.h" #include "../include/regexp.h" /* * The first byte of the regexp internal "program" is actually this magic * number; the start node begins in the second byte. */ #define MAGIC 0234 /* * The "internal use only" fields in regexp.h are present to pass info from * compile to execute that permits the execute phase to run lots faster on * simple cases. They are: * * regstart char that must begin a match; '\0' if none obvious * reganch is the match anchored (at beginning-of-line only)? * regmust string (pointer into program) that match must include, or NULL * regmlen length of regmust string * * Regstart and reganch permit very fast decisions on suitable starting points * for a match, cutting down the work a lot. Regmust permits fast rejection * of lines that cannot possibly match. The regmust tests are costly enough * that regcomp() supplies a regmust only if the r.e. contains something * potentially expensive (at present, the only such thing detected is * or + * at the start of the r.e., which can involve a lot of backup). Regmlen is * supplied because the test in regexec() needs it and regcomp() is computing * it anyway. */ /* * Structure for regexp "program". This is essentially a linear encoding * of a nondeterministic finite-state machine (aka syntax charts or * "railroad normal form" in parsing technology). Each node is an opcode * plus a "next" pointer, possibly plus an operand. "Next" pointers of * all nodes except BRANCH implement concatenation; a "next" pointer with * a BRANCH on both ends of it is connecting two alternatives. (Here we * have one of the subtle syntax dependencies: an individual BRANCH (as * opposed to a collection of them) is never concatenated with anything * because of operator precedence.) The operand of some types of node is * a literal string; for others, it is a node leading into a sub-FSM. In * particular, the operand of a BRANCH node is the first node of the branch. * (NB this is *not* a tree structure: the tail of the branch connects * to the thing following the set of BRANCHes.) The opcodes are: */ /* definition number opnd? meaning */ #define END 0 /* no End of program. */ #define BOL 1 /* no Match "" at beginning of line. */ #define EOL 2 /* no Match "" at end of line. */ #define ANY 3 /* no Match any one character. */ #define ANYOF 4 /* str Match any character in this string. */ #define ANYBUT 5 /* str Match any character not in this string. */ #define BRANCH 6 /* node Match this alternative, or the next... */ #define BACK 7 /* no Match "", "next" ptr points backward. */ #define EXACTLY 8 /* str Match this string. */ #define NOTHING 9 /* no Match empty string. */ #define STAR 10 /* node Match this (simple) thing 0 or more times. */ #define PLUS 11 /* node Match this (simple) thing 1 or more times. */ #define OPEN 20 /* no Mark this point in input as start of #n. */ /* OPEN+1 is number 1, etc. */ #define CLOSE 30 /* no Analogous to OPEN. */ /* * Opcode notes: * * BRANCH The set of branches constituting a single choice are hooked * together with their "next" pointers, since precedence prevents * anything being concatenated to any individual branch. The * "next" pointer of the last BRANCH in a choice points to the * thing following the whole choice. This is also where the * final "next" pointer of each individual branch points; each * branch starts with the operand node of a BRANCH node. * * BACK Normal "next" pointers all implicitly point forward; BACK * exists to make loop structures possible. * * STAR,PLUS '?', and complex '*' and '+', are implemented as circular * BRANCH structures using BACK. Simple cases (one character * per match) are implemented with STAR and PLUS for speed * and to minimize recursive plunges. * * OPEN,CLOSE ...are numbered at compile time. */ /* * A node is one char of opcode followed by two chars of "next" pointer. * "Next" pointers are stored as two 8-bit pieces, high order first. The * value is a positive offset from the opcode of the node containing it. * An operand, if any, simply follows the node. (Note that much of the * code generation knows about this implicit relationship.) * * Using two bytes for the "next" pointer is vast overkill for most things, * but allows patterns to get big without disasters. */ #define OP(p) (*(p)) #define NEXT(p) (((*((p)+1)&0377)<<8) + *((p)+2)&0377) #define OPERAND(p) ((p) + 3) /* * Utility definitions. */ #ifndef CHARBITS #define UCHARAT(p) ((int)*(unsigned char *)(p)) #else #define UCHARAT(p) ((int)*(p)&CHARBITS) #endif #define FAIL(m) { regerror(m); return(NULL); } #define ISMULT(c) ((c) == '*' || (c) == '+' || (c) == '?') #define META "^$.[()|?+*\\" /* * Flags to be passed up and down. */ #define HASWIDTH 01 /* Known never to match null string. */ #define SIMPLE 02 /* Simple enough to be STAR/PLUS operand. */ #define SPSTART 04 /* Starts with * or +. */ #define WORST 0 /* Worst case. */ /* * Global work variables for regcomp(). */ static char *regparse; /* Input-scan pointer. */ static int regnpar; /* () count. */ static char regdummy; static char *regcode; /* Code-emit pointer; ®dummy = don't. */ static long regsize; /* Code size. */ /* * Forward declarations for regcomp()'s friends. */ #ifndef STATIC #define STATIC static #endif STATIC char *reg(); STATIC char *regbranch(); STATIC char *regpiece(); STATIC char *regatom(); STATIC char *regnode(); STATIC char *regnext(); STATIC void regc(); STATIC void reginsert(); STATIC void regtail(); STATIC void regoptail(); STATIC int strcspn(); /* - regcomp - compile a regular expression into internal code * * We can't allocate space until we know how big the compiled form will be, * but we can't compile it (and thus know how big it is) until we've got a * place to put the code. So we cheat: we compile it twice, once with code * generation turned off and size counting turned on, and once "for real". * This also means that we don't allocate space until we are sure that the * thing really will compile successfully, and we never have to move the * code and thus invalidate pointers into it. (Note that it has to be in * one piece because free() must be able to free it all.) * * Beware that the optimization-preparation code in here knows about some * of the structure of the compiled regexp. */ regexp * regcomp(exp) char *exp; { register regexp *r; register char *scan; register char *longest; register int len; int flags; extern char *malloc(); if (exp == NULL) FAIL("NULL argument"); /* First pass: determine size, legality. */ regparse = exp; regnpar = 1; regsize = 0L; regcode = ®dummy; regc(MAGIC); if (reg(0, &flags) == NULL) return(NULL); /* Small enough for pointer-storage convention? */ if (regsize >= 32767L) /* Probably could be 65535L. */ FAIL("regexp too big"); /* Allocate space. */ r = (regexp *)malloc(sizeof(regexp) + (unsigned)regsize); if (r == NULL) FAIL("out of space"); /* Second pass: emit code. */ regparse = exp; regnpar = 1; regcode = r->program; regc(MAGIC); if (reg(0, &flags) == NULL) return(NULL); /* Dig out information for optimizations. */ r->regstart = '\0'; /* Worst-case defaults. */ r->reganch = 0; r->regmust = NULL; r->regmlen = 0; scan = r->program+1; /* First BRANCH. */ if (OP(regnext(scan)) == END) { /* Only one top-level choice. */ scan = OPERAND(scan); /* Starting-point info. */ if (OP(scan) == EXACTLY) r->regstart = *OPERAND(scan); else if (OP(scan) == BOL) r->reganch++; /* * If there's something expensive in the r.e., find the * longest literal string that must appear and make it the * regmust. Resolve ties in favor of later strings, since * the regstart check works with the beginning of the r.e. * and avoiding duplication strengthens checking. Not a * strong reason, but sufficient in the absence of others. */ if (flags&SPSTART) { longest = NULL; len = 0; for (; scan != NULL; scan = regnext(scan)) if (OP(scan) == EXACTLY && strlen(OPERAND(scan)) >= len) { longest = OPERAND(scan); len = strlen(OPERAND(scan)); } r->regmust = longest; r->regmlen = len; } } return(r); } /* - reg - regular expression, i.e. main body or parenthesized thing * * Caller must absorb opening parenthesis. * * Combining parenthesis handling with the base level of regular expression * is a trifle forced, but the need to tie the tails of the branches to what * follows makes it hard to avoid. */ static char * reg(paren, flagp) int paren; /* Parenthesized? */ int *flagp; { register char *ret; register char *br; register char *ender; register int parno; int flags; *flagp = HASWIDTH; /* Tentatively. */ /* Make an OPEN node, if parenthesized. */ if (paren) { if (regnpar >= NSUBEXP) FAIL("too many ()"); parno = regnpar; regnpar++; ret = regnode(OPEN+parno); } else ret = NULL; /* Pick up the branches, linking them together. */ br = regbranch(&flags); if (br == NULL) return(NULL); if (ret != NULL) regtail(ret, br); /* OPEN -> first. */ else ret = br; if (!(flags&HASWIDTH)) *flagp &= ~HASWIDTH; *flagp |= flags&SPSTART; while (*regparse == '|') { regparse++; br = regbranch(&flags); if (br == NULL) return(NULL); regtail(ret, br); /* BRANCH -> BRANCH. */ if (!(flags&HASWIDTH)) *flagp &= ~HASWIDTH; *flagp |= flags&SPSTART; } /* Make a closing node, and hook it on the end. */ ender = regnode((paren) ? CLOSE+parno : END); regtail(ret, ender); /* Hook the tails of the branches to the closing node. */ for (br = ret; br != NULL; br = regnext(br)) regoptail(br, ender); /* Check for proper termination. */ if (paren && *regparse++ != ')') { FAIL("unmatched ()"); } else if (!paren && *regparse != '\0') { if (*regparse == ')') { FAIL("unmatched ()"); } else FAIL("junk on end"); /* "Can't happen". */ /* NOTREACHED */ } return(ret); } /* - regbranch - one alternative of an | operator * * Implements the concatenation operator. */ static char * regbranch(flagp) int *flagp; { register char *ret; register char *chain; register char *latest; int flags; *flagp = WORST; /* Tentatively. */ ret = regnode(BRANCH); chain = NULL; while (*regparse != '\0' && *regparse != '|' && *regparse != ')') { latest = regpiece(&flags); if (latest == NULL) return(NULL); *flagp |= flags&HASWIDTH; if (chain == NULL) /* First piece. */ *flagp |= flags&SPSTART; else regtail(chain, latest); chain = latest; } if (chain == NULL) /* Loop ran zero times. */ (void) regnode(NOTHING); return(ret); } /* - regpiece - something followed by possible [*+?] * * Note that the branching code sequences used for ? and the general cases * of * and + are somewhat optimized: they use the same NOTHING node as * both the endmarker for their branch list and the body of the last branch. * It might seem that this node could be dispensed with entirely, but the * endmarker role is not redundant. */ static char * regpiece(flagp) int *flagp; { register char *ret; register char op; register char *next; int flags; ret = regatom(&flags); if (ret == NULL) return(NULL); op = *regparse; if (!ISMULT(op)) { *flagp = flags; return(ret); } if (!(flags&HASWIDTH) && op != '?') FAIL("*+ operand could be empty"); *flagp = (op != '+') ? (WORST|SPSTART) : (WORST|HASWIDTH); if (op == '*' && (flags&SIMPLE)) reginsert(STAR, ret); else if (op == '*') { /* Emit x* as (x&|), where & means "self". */ reginsert(BRANCH, ret); /* Either x */ regoptail(ret, regnode(BACK)); /* and loop */ regoptail(ret, ret); /* back */ regtail(ret, regnode(BRANCH)); /* or */ regtail(ret, regnode(NOTHING)); /* null. */ } else if (op == '+' && (flags&SIMPLE)) reginsert(PLUS, ret); else if (op == '+') { /* Emit x+ as x(&|), where & means "self". */ next = regnode(BRANCH); /* Either */ regtail(ret, next); regtail(regnode(BACK), ret); /* loop back */ regtail(next, regnode(BRANCH)); /* or */ regtail(ret, regnode(NOTHING)); /* null. */ } else if (op == '?') { /* Emit x? as (x|) */ reginsert(BRANCH, ret); /* Either x */ regtail(ret, regnode(BRANCH)); /* or */ next = regnode(NOTHING); /* null. */ regtail(ret, next); regoptail(ret, next); } regparse++; if (ISMULT(*regparse)) FAIL("nested *?+"); return(ret); } /* - regatom - the lowest level * * Optimization: gobbles an entire sequence of ordinary characters so that * it can turn them into a single node, which is smaller to store and * faster to run. Backslashed characters are exceptions, each becoming a * separate node; the code is simpler that way and it's not worth fixing. */ static char * regatom(flagp) int *flagp; { register char *ret; int flags; *flagp = WORST; /* Tentatively. */ switch (*regparse++) { case '^': ret = regnode(BOL); break; case '$': ret = regnode(EOL); break; case '.': ret = regnode(ANY); *flagp |= HASWIDTH|SIMPLE; break; case '[': { register int class; register int classend; if (*regparse == '^') { /* Complement of range. */ ret = regnode(ANYBUT); regparse++; } else ret = regnode(ANYOF); if (*regparse == ']' || *regparse == '-') regc(*regparse++); while (*regparse != '\0' && *regparse != ']') { if (*regparse == '-') { regparse++; if (*regparse == ']' || *regparse == '\0') regc('-'); else { class = UCHARAT(regparse-2)+1; classend = UCHARAT(regparse); if (class > classend+1) FAIL("invalid [] range"); for (; class <= classend; class++) regc(class); regparse++; } } else regc(*regparse++); } regc('\0'); if (*regparse != ']') FAIL("unmatched []"); regparse++; *flagp |= HASWIDTH|SIMPLE; } break; case '(': ret = reg(1, &flags); if (ret == NULL) return(NULL); *flagp |= flags&(HASWIDTH|SPSTART); break; case '\0': case '|': case ')': FAIL("internal urp"); /* Supposed to be caught earlier. */ break; case '?': case '+': case '*': FAIL("?+* follows nothing"); break; case '\\': if (*regparse == '\0') FAIL("trailing \\"); ret = regnode(EXACTLY); regc(*regparse++); regc('\0'); *flagp |= HASWIDTH|SIMPLE; break; default: { register int len; register char ender; regparse--; len = strcspn(regparse, META); if (len <= 0) FAIL("internal disaster"); ender = *(regparse+len); if (len > 1 && ISMULT(ender)) len--; /* Back off clear of ?+* operand. */ *flagp |= HASWIDTH; if (len == 1) *flagp |= SIMPLE; ret = regnode(EXACTLY); while (len > 0) { regc(*regparse++); len--; } regc('\0'); } break; } return(ret); } /* - regnode - emit a node */ static char * /* Location. */ regnode(op) char op; { register char *ret; register char *ptr; ret = regcode; if (ret == ®dummy) { regsize += 3; return(ret); } ptr = ret; *ptr++ = op; *ptr++ = '\0'; /* Null "next" pointer. */ *ptr++ = '\0'; regcode = ptr; return(ret); } /* - regc - emit (if appropriate) a byte of code */ static void regc(b) char b; { if (regcode != ®dummy) *regcode++ = b; else regsize++; } /* - reginsert - insert an operator in front of already-emitted operand * * Means relocating the operand. */ static void reginsert(op, opnd) char op; char *opnd; { register char *src; register char *dst; register char *place; if (regcode == ®dummy) { regsize += 3; return; } src = regcode; regcode += 3; dst = regcode; while (src > opnd) *--dst = *--src; place = opnd; /* Op node, where operand used to be. */ *place++ = op; *place++ = '\0'; *place++ = '\0'; } /* - regtail - set the next-pointer at the end of a node chain */ static void regtail(p, val) char *p; char *val; { register char *scan; register char *temp; register int offset; if (p == ®dummy) return; /* Find last node. */ scan = p; for (;;) { temp = regnext(scan); if (temp == NULL) break; scan = temp; } if (OP(scan) == BACK) offset = scan - val; else offset = val - scan; *(scan+1) = (offset>>8)&0377; *(scan+2) = offset&0377; } /* - regoptail - regtail on operand of first argument; nop if operandless */ static void regoptail(p, val) char *p; char *val; { /* "Operandless" and "op != BRANCH" are synonymous in practice. */ if (p == NULL || p == ®dummy || OP(p) != BRANCH) return; regtail(OPERAND(p), val); } /* * regexec and friends */ /* * Global work variables for regexec(). */ static char *reginput; /* String-input pointer. */ static char *regbol; /* Beginning of input, for ^ check. */ static char **regstartp; /* Pointer to startp array. */ static char **regendp; /* Ditto for endp. */ /* * Forwards. */ STATIC int regtry(); STATIC int regmatch(); STATIC int regrepeat(); #ifdef DEBUG int regnarrate = 0; void regdump(); STATIC char *regprop(); #endif /* - regexec - match a regexp against a string */ int regexec(prog, string, bolflag) register regexp *prog; register char *string; int bolflag; { register char *s; extern char *strchr(); /* Be paranoid... */ if (prog == NULL || string == NULL) { regerror("NULL parameter"); return(0); } /* Check validity of program. */ if (UCHARAT(prog->program) != MAGIC) { regerror("corrupted program"); return(0); } /* If there is a "must appear" string, look for it. */ if (prog->regmust != NULL) { s = string; while ((s = strchr(s, prog->regmust[0])) != NULL) { if (strncmp(s, prog->regmust, prog->regmlen) == 0) break; /* Found it. */ s++; } if (s == NULL) /* Not present. */ return(0); } /* Mark beginning of line for ^ . */ if(bolflag) regbol = string; else regbol = NULL; /* Simplest case: anchored match need be tried only once. */ if (prog->reganch) return(regtry(prog, string)); /* Messy cases: unanchored match. */ s = string; if (prog->regstart != '\0') /* We know what char it must start with. */ while ((s = strchr(s, prog->regstart)) != NULL) { if (regtry(prog, s)) return(1); s++; } else /* We don't -- general case. */ do { if (regtry(prog, s)) return(1); } while (*s++ != '\0'); /* Failure. */ return(0); } /* - regtry - try match at specific point */ static int /* 0 failure, 1 success */ regtry(prog, string) regexp *prog; char *string; { register int i; register char **sp; register char **ep; reginput = string; regstartp = prog->startp; regendp = prog->endp; sp = prog->startp; ep = prog->endp; for (i = NSUBEXP; i > 0; i--) { *sp++ = NULL; *ep++ = NULL; } if (regmatch(prog->program + 1)) { prog->startp[0] = string; prog->endp[0] = reginput; return(1); } else return(0); } /* - regmatch - main matching routine * * Conceptually the strategy is simple: check to see whether the current * node matches, call self recursively to see whether the rest matches, * and then act accordingly. In practice we make some effort to avoid * recursion, in particular by going through "ordinary" nodes (that don't * need to know whether the rest of the match failed) by a loop instead of * by recursion. */ static int /* 0 failure, 1 success */ regmatch(prog) char *prog; { register char *scan; /* Current node. */ char *next; /* Next node. */ extern char *strchr(); scan = prog; #ifdef DEBUG if (scan != NULL && regnarrate) fprintf(stderr, "%s(\n", regprop(scan)); #endif while (scan != NULL) { #ifdef DEBUG if (regnarrate) fprintf(stderr, "%s...\n", regprop(scan)); #endif next = regnext(scan); switch (OP(scan)) { case BOL: if (reginput != regbol) return(0); break; case EOL: if (*reginput != '\0') return(0); break; case ANY: if (*reginput == '\0') return(0); reginput++; break; case EXACTLY: { register int len; register char *opnd; opnd = OPERAND(scan); /* Inline the first character, for speed. */ if (*opnd != *reginput) return(0); len = strlen(opnd); if (len > 1 && strncmp(opnd, reginput, len) != 0) return(0); reginput += len; } break; case ANYOF: if (*reginput == '\0' || strchr(OPERAND(scan), *reginput) == NULL) return(0); reginput++; break; case ANYBUT: if (*reginput == '\0' || strchr(OPERAND(scan), *reginput) != NULL) return(0); reginput++; break; case NOTHING: break; case BACK: break; case OPEN+1: case OPEN+2: case OPEN+3: case OPEN+4: case OPEN+5: case OPEN+6: case OPEN+7: case OPEN+8: case OPEN+9: { register int no; register char *save; no = OP(scan) - OPEN; save = reginput; if (regmatch(next)) { /* * Don't set startp if some later * invocation of the same parentheses * already has. */ if (regstartp[no] == NULL) regstartp[no] = save; return(1); } else return(0); } break; case CLOSE+1: case CLOSE+2: case CLOSE+3: case CLOSE+4: case CLOSE+5: case CLOSE+6: case CLOSE+7: case CLOSE+8: case CLOSE+9: { register int no; register char *save; no = OP(scan) - CLOSE; save = reginput; if (regmatch(next)) { /* * Don't set endp if some later * invocation of the same parentheses * already has. */ if (regendp[no] == NULL) regendp[no] = save; return(1); } else return(0); } break; case BRANCH: { register char *save; if (OP(next) != BRANCH) /* No choice. */ next = OPERAND(scan); /* Avoid recursion. */ else { do { save = reginput; if (regmatch(OPERAND(scan))) return(1); reginput = save; scan = regnext(scan); } while (scan != NULL && OP(scan) == BRANCH); return(0); /* NOTREACHED */ } } break; case STAR: case PLUS: { register char nextch; register int no; register char *save; register int min; /* * Lookahead to avoid useless match attempts * when we know what character comes next. */ nextch = '\0'; if (OP(next) == EXACTLY) nextch = *OPERAND(next); min = (OP(scan) == STAR) ? 0 : 1; save = reginput; no = regrepeat(OPERAND(scan)); while (no >= min) { /* If it could work, try it. */ if (nextch == '\0' || *reginput == nextch) if (regmatch(next)) return(1); /* Couldn't or didn't -- back up. */ no--; reginput = save + no; } return(0); } break; case END: return(1); /* Success! */ break; default: regerror("memory corruption"); return(0); break; } scan = next; } /* * We get here only if there's trouble -- normally "case END" is * the terminating point. */ regerror("corrupted pointers"); return(0); } /* - regrepeat - repeatedly match something simple, report how many */ static int regrepeat(p) char *p; { register int count = 0; register char *scan; register char *opnd; scan = reginput; opnd = OPERAND(p); switch (OP(p)) { case ANY: count = strlen(scan); scan += count; break; case EXACTLY: while (*opnd == *scan) { count++; scan++; } break; case ANYOF: while (*scan != '\0' && strchr(opnd, *scan) != NULL) { count++; scan++; } break; case ANYBUT: while (*scan != '\0' && strchr(opnd, *scan) == NULL) { count++; scan++; } break; default: /* Oh dear. Called inappropriately. */ regerror("internal foulup"); count = 0; /* Best compromise. */ break; } reginput = scan; return(count); } /* - regnext - dig the "next" pointer out of a node */ static char * regnext(p) register char *p; { register int offset; if (p == ®dummy) return(NULL); offset = NEXT(p); if (offset == 0) return(NULL); if (OP(p) == BACK) return(p-offset); else return(p+offset); } #ifdef DEBUG STATIC char *regprop(); /* - regdump - dump a regexp onto stdout in vaguely comprehensible form */ void regdump(r) regexp *r; { register char *s; register char op = EXACTLY; /* Arbitrary non-END op. */ register char *next; extern char *strchr(); s = r->program + 1; while (op != END) { /* While that wasn't END last time... */ op = OP(s); printf("%2d%s", s-r->program, regprop(s)); /* Where, what. */ next = regnext(s); if (next == NULL) /* Next ptr. */ printf("(0)"); else printf("(%d)", (s-r->program)+(next-s)); s += 3; if (op == ANYOF || op == ANYBUT || op == EXACTLY) { /* Literal string, where present. */ while (*s != '\0') { putchar(*s); s++; } s++; } putchar('\n'); } /* Header fields of interest. */ if (r->regstart != '\0') printf("start `%c' ", r->regstart); if (r->reganch) printf("anchored "); if (r->regmust != NULL) printf("must have \"%s\"", r->regmust); printf("\n"); } /* - regprop - printable representation of opcode */ static char * regprop(op) char *op; { register char *p; static char buf[50]; (void) strcpy(buf, ":"); switch (OP(op)) { case BOL: p = "BOL"; break; case EOL: p = "EOL"; break; case ANY: p = "ANY"; break; case ANYOF: p = "ANYOF"; break; case ANYBUT: p = "ANYBUT"; break; case BRANCH: p = "BRANCH"; break; case EXACTLY: p = "EXACTLY"; break; case NOTHING: p = "NOTHING"; break; case BACK: p = "BACK"; break; case END: p = "END"; break; case OPEN+1: case OPEN+2: case OPEN+3: case OPEN+4: case OPEN+5: case OPEN+6: case OPEN+7: case OPEN+8: case OPEN+9: sprintf(buf+strlen(buf), "OPEN%d", OP(op)-OPEN); p = NULL; break; case CLOSE+1: case CLOSE+2: case CLOSE+3: case CLOSE+4: case CLOSE+5: case CLOSE+6: case CLOSE+7: case CLOSE+8: case CLOSE+9: sprintf(buf+strlen(buf), "CLOSE%d", OP(op)-CLOSE); p = NULL; break; case STAR: p = "STAR"; break; case PLUS: p = "PLUS"; break; default: regerror("corrupted opcode"); break; } if (p != NULL) (void) strcat(buf, p); return(buf); } #endif /* * The following is provided for those people who do not have strcspn() in * their C libraries. They should get off their butts and do something * about it; at least one public-domain implementation of those (highly * useful) string routines has been published on Usenet. */ /* * strcspn - find length of initial segment of s1 consisting entirely * of characters not from s2 */ static int strcspn(s1, s2) char *s1; char *s2; { register char *scan1; register char *scan2; register int count; count = 0; for (scan1 = s1; *scan1 != '\0'; scan1++) { for (scan2 = s2; *scan2 != '\0';) /* ++ moved down. */ if (*scan1 == *scan2++) return(count); count++; } return(count); } regsub.c I~ I/* * regsub * * Copyright (c) 1986 by University of Toronto. * Written by Henry Spencer. Not derived from licensed software. * * Permission is granted to anyone to use this software for any * purpose on any computer system, and to redistribute it freely, * subject to the following restrictions: * * 1. The author is not responsible for the consequences of use of * this software, no matter how awful, even if they arise * from defects in it. * * 2. The origin of this software must not be misrepresented, either * by explicit claim or by omission. * * 3. Altered versions must be plainly marked as such, and must not * be misrepresented as being the original software. */ #include "../include/stdio.h" #include "../include/regexp.h" /* * The first byte of the regexp internal "program" is actually this magic * number; the start node begins in the second byte. */ #define MAGIC 0234 #define CHARBITS 0377 #ifndef CHARBITS #define UCHARAT(p) ((int)*(unsigned char *)(p)) #else #define UCHARAT(p) ((int)*(p)&CHARBITS) #endif /* - regsub - perform substitutions after a regexp match */ regsub(prog, source, dest) regexp *prog; char *source; char *dest; { register char *src; register char *dst; register char c; register int no; register int len; extern char *strncpy(); if (prog == NULL || source == NULL || dest == NULL) { regerror("NULL parm to regsub"); return; } if (UCHARAT(prog->program) != MAGIC) { regerror("damaged regexp fed to regsub"); return; } src = source; dst = dest; while ((c = *src++) != '\0') { if (c == '&') no = 0; else if (c == '\\' && '0' <= *src && *src <= '9') no = *src++ - '0'; else no = -1; if (no < 0) { /* Ordinary character. */ if (c == '\\' && (*src == '\\' || *src == '&')) c = *src++; *dst++ = c; } else if (prog->startp[no] != NULL && prog->endp[no] != NULL) { len = prog->endp[no] - prog->startp[no]; strncpy(dst, prog->startp[no], len); dst += len; if (len !=0 && *(dst-1) == '\0') { /* strncpy hit NUL. */ regerror("damaged match string"); return; } } } *dst++ = '\0'; } =rindex.c I~ char *rindex(s, c) register char *s, c; { register char *result; result = 0; do if (*s == c) result = s; while (*s++ != 0); return(result); } setbuf.c J~ 6#include "../include/stdio.h" setbuf(iop, buffer) FILE *iop; char *buffer; { if ( iop->_buf && testflag(iop,IOMYBUF) ) free(iop->_buf); iop->_flags &= ~(IOMYBUF | UNBUFF | PERPRINTF); iop->_buf = buffer; if ( iop->_buf == NULL ) iop->_flags |= UNBUFF; iop->_ptr = iop->_buf; iop->_count = 0; } setgid.c J~ #include "../include/lib.h" PUBLIC int setgid(grp) int grp; { return callm1(MM, SETGID, grp, 0, 0, NIL_PTR, NIL_PTR, NIL_PTR); } setuid.c J~ #include "../include/lib.h" PUBLIC int setuid(usr) int usr; { return callm1(MM, SETUID, usr, 0, 0, NIL_PTR, NIL_PTR, NIL_PTR); } signal.c J~ F#include "../include/lib.h" #include "../include/signal.h" int (*vectab[NR_SIGS])(); /* array of functions to catch signals */ /* The definition of signal really should be * PUBLIC int (*signal(signr, func))() * but some compilers refuse to accept this, even though it is correct. * The only thing to do if you are stuck with such a defective compiler is * change it to * PUBLIC int *signal(signr, func) * and change ../h/signal.h accordingly. */ PUBLIC int (*signal(signr, func))() int signr; /* which signal is being set */ int (*func)(); /* pointer to function that catches signal */ { int r,(*old)(); old = vectab[signr - 1]; vectab[signr - 1] = func; M.m6_i1 = signr; M.m6_f1 = ( (func == SIG_IGN || func == SIG_DFL) ? func : begsig); r = callx(MM, SIGNAL); return( (r < 0 ? (int (*)()) r : old) ); } sleep.c J~ #include "../include/lib.h" #include "../include/signal.h" PRIVATE alfun(){} /* used with sleep() below */ PUBLIC sleep(n) int n; { /* sleep(n) pauses for 'n' seconds by scheduling an alarm interrupt. */ signal(SIGALRM, alfun); alarm(n); pause(); } sprintf.c J~ 1#include "../include/stdio.h" char *sprintf(buf,format,args) char *buf, *format; int args; { FILE _tempfile; _tempfile._fd = -1; _tempfile._flags = WRITEMODE + STRINGS; _tempfile._buf = buf; _tempfile._ptr = buf; _doprintf(&_tempfile,format,&args); putc('\0',&_tempfile); return buf; } (stat.c J~ #include "../include/lib.h" PUBLIC int stat(name, buffer) char *name; char *buffer; { int n; n = callm1(FS, STAT, len(name), 0, 0, name, buffer, NIL_PTR); return(n); } 0stb.c J~ /* library routine for copying structs with unpleasant alignment */ __stb(n, f, t) register char *f, *t; register int n; { if (n > 0) do *t++ = *f++; while (--n); } Tstderr.c J~ T std_err(s) char *s; { char *p = s; while(*p != 0) p++; write(2, s, p - s); } stime.c J~ o #include "../include/lib.h" PUBLIC int stime(top) long *top; { M.m2_l1 = *top; return callx(FS, STIME); } *strcat.c K~ char *strcat(s1, s2) register char *s1, *s2; { /* Append s2 to the end of s1. */ char *original = s1; /* Find the end of s1. */ while (*s1 != 0) s1++; /* Now copy s2 to the end of s1. */ while (*s2 != 0) *s1++ = *s2++; *s1 = 0; return(original); } astrcmp.c K~ int strcmp(s1, s2) register char *s1, *s2; { /* Compare 2 strings. */ while (1) { if (*s1 != *s2) return(*s1 - *s2); if (*s1 == 0) return(0); s1++; s2++; } } Nstrcpy.c K~ char *strcpy(s1, s2) register char *s1, *s2; { /* Copy s2 to s1. */ char *original = s1; while (*s2 != 0) *s1++ = *s2++; *s1 = 0; return(original); } ;strlen.c L~ | int strlen(s) char *s; { /* Return length of s. */ char *original = s; while (*s != 0) s++; return(s - original); } strncat.c L~ jchar *strncat(s1, s2, n) register char *s1, *s2; int n; { /* Append s2 to the end of s1, but no more than n characters */ char *original = s1; if (n == 0) return(s1); /* Find the end of s1. */ while (*s1 != 0) s1++; /* Now copy s2 to the end of s1. */ while (*s2 != 0) { *s1++ = *s2++; if (--n == 0) break; } *s1 = 0; return(original); } strncmp.c L~ int strncmp(s1, s2, n) register char *s1, *s2; int n; { /* Compare two strings, but at most n characters. */ while (1) { if (*s1 != *s2) return(*s1 - *s2); if (*s1 == 0 || --n == 0) return(0); s1++; s2++; } } strncpy.c L~ char *strncpy(s1, s2, n) register char *s1, *s2; int n; { /* Copy s2 to s1, but at most n characters. */ char *original = s1; while (*s2 != 0) { *s1++ = *s2++; if (--n == 0) break; } *s1 = 0; return(original); } sync.c L~ r #include "../include/lib.h" PUBLIC int sync() { return callm1(FS, SYNC, 0, 0, 0, NIL_PTR, NIL_PTR, NIL_PTR); } syslib.c #include "../h/const.h" #include "../h/type.h" #include "../h/callnr.h" #include "../h/com.h" #include "../h/error.h" #define FS FS_PROC_NR #define MM MMPROCNR extern int errno; extern message M; /*---------------------------------------------------------------------------- Messages to systask (special calls) ----------------------------------------------------------------------------*/ PUBLIC sys_xit(parent, proc) int parent; /* parent of exiting proc. */ int proc; /* which proc has exited */ { /* A proc has exited. Tell the kernel. */ callm1(SYSTASK, SYS_XIT, parent, proc, 0, NIL_PTR, NIL_PTR, NIL_PTR); } PUBLIC sys_getsp(proc, newsp) int proc; /* which proc has enabled signals */ vir_bytes *newsp; /* place to put sp read from kernel */ { /* Ask the kernel what the sp is. */ callm1(SYSTASK, SYS_GETSP, proc, 0, 0, NIL_PTR, NIL_PTR, NIL_PTR); *newsp = (vir_bytes) M.STACK_PTR; } PUBLIC sys_sig(proc, sig, sighandler) int proc; /* which proc has exited */ int sig; /* signal number: 1 - 16 */ int (*sighandler)(); /* pointer to signal handler in user space */ { /* A proc has to be signaled. Tell the kernel. */ M.m6_i1 = proc; M.m6_i2 = sig; M.m6_f1 = sighandler; callx(SYSTASK, SYS_SIG); } PUBLIC sys_fork(parent, child, pid) int parent; /* proc doing the fork */ int child; /* which proc has been created by the fork */ int pid; /* process id assigned by MM */ { /* A proc has forked. Tell the kernel. */ callm1(SYSTASK, SYS_FORK, parent, child, pid, NIL_PTR, NIL_PTR, NIL_PTR); } PUBLIC sys_exec(proc, ptr) int proc; /* proc that did exec */ char *ptr; /* new stack pointer */ { /* A proc has exec'd. Tell the kernel. */ callm1(SYSTASK, SYS_EXEC, proc, 0, 0, ptr, NIL_PTR, NIL_PTR); } PUBLIC sys_newmap(proc, ptr) int proc; /* proc whose map is to be changed */ char *ptr; /* pointer to new map */ { /* A proc has been assigned a new memory map. Tell the kernel. */ callm1(SYSTASK, SYS_NEWMAP, proc, 0, 0, ptr, NIL_PTR, NIL_PTR); } PUBLIC sys_copy(mptr) message *mptr; /* pointer to message */ { /* A proc wants to use local copy. */ /* Make this routine better. Also check other guys' error handling -DEBUG */ mptr->m_type = SYS_COPY; if (sendrec(SYSTASK, mptr) != OK) panic("sys_copy can't send", NO_NUM); } PUBLIC sys_times(proc, ptr) int proc; /* proc whose times are needed */ real_time ptr[4]; /* pointer to time buffer */ { /* Fetch the accounting info for a proc. */ callm1(SYSTASK, SYS_TIMES, proc, 0, 0, ptr, NIL_PTR, NIL_PTR); ptr[0] = M.USER_TIME; ptr[1] = M.SYSTEM_TIME; ptr[2] = M.CHILD_UTIME; ptr[3] = M.CHILD_STIME; } PUBLIC sys_abort() { /* Something awful has happened. Abandon ship. */ callm1(SYSTASK, SYS_ABORT, 0, 0, 0, NIL_PTR, NIL_PTR, NIL_PTR); } PUBLIC int tell_fs(what, p1, p2, p3) int what, p1, p2, p3; { /* This routine is only used by MM to inform FS of certain events: * tell_fs(CHDIR, slot, dir, 0) * tell_fs(EXIT, proc, 0, 0) * tell_fs(FORK, parent, child, 0) * tell_fs(SETGID, proc, realgid, effgid) * tell_fs(SETUID, proc, realuid, effuid) * tell_fs(SYNC, 0, 0, 0) * tell_fs(UNPAUSE, proc, signr, 0) */ callm1(FS, what, p1, p2, p3, NIL_PTR, NIL_PTR, NIL_PTR); } time.c L~ #include "../include/lib.h" PUBLIC long time(tp) long *tp; { int k; long l; k = callm1(FS, TIME, 0, 0, 0, NIL_PTR, NIL_PTR, NIL_PTR); if (M.m_type < 0 || k != OK) {errno = -M.m_type; return(-1L);} l = M.m2_l1; if (tp != (long *) 0) *tp = l; return(l); } ttimes.c L~ #include "../include/lib.h" struct tbuf { long b1, b2, b3, b4;}; PUBLIC int times(buf) struct tbuf *buf; { int k; k = callm1(FS, TIMES, 0, 0, 0, NIL_PTR, NIL_PTR, NIL_PTR); buf->b1 = M.m4_l1; buf->b2 = M.m4_l2; buf->b3 = M.m4_l3; buf->b4 = M.m4_l4; return(k); } sumask.c L~ #include "../include/lib.h" PUBLIC int umask(complmode) int complmode; { return callm1(FS, UMASK, complmode, 0, 0, NIL_PTR, NIL_PTR, NIL_PTR); } umount.c M~ k #include "../include/lib.h" PUBLIC int umount(name) char* name; { return callm3(FS, UMOUNT, 0, name); } oungetc.c M~ )#include "../include/stdio.h" ungetc(ch, iop) int ch; FILE *iop; { if ( ch < 0 || !testflag(iop,READMODE) || testflag(iop,UNBUFF) ) return( EOF ); if ( iop->_count >= BUFSIZ) return(EOF); if ( iop->_ptr == iop->_buf) iop->_ptr++; iop->_count++; *--iop->_ptr = ch; return(ch); } iunlink.c M~ k #include "../include/lib.h" PUBLIC int unlink(name) char *name; { return callm3(FS, UNLINK, 0, name); } )utime.c M~ #include "../include/lib.h" PUBLIC int utime(name, timp) char *name; long timp[2]; { M.m2_i1 = len(name); M.m2_l1 = timp[0]; M.m2_l2 = timp[1]; M.m2_p1 = name; return callx(FS, UTIME); } wait.c M~ #include "../include/lib.h" PUBLIC int wait(status) int *status; { int k; k = callm1(MM, WAIT, 0, 0, 0, NIL_PTR, NIL_PTR, NIL_PTR); *status = M.m2_i1; return(k); } ewrite.c M~ #include "../include/lib.h" PUBLIC int write(fd, buffer, nbytes) char *buffer; int nbytes; { return callm1(FS, WRITE, fd, nbytes, 0, buffer, NIL_PTR, NIL_PTR); } brksize.s Q~ 5 .data .globl endbss, _brksize _brksize: .word endbss fcatchsig.s Q~ .globl _begsig .globl _vectab, _M mtype = 2 | M+mtype = &M.m_type _begsig: push ax | after interrupt, save all regs push bx push cx push dx push si push di push bp push ds push es mov bx,sp mov bx,18(bx) | bx = signal number mov ax,bx | ax = signal number dec bx | vectab[0] is for sig 1 add bx,bx | pointers are two bytes on 8088 mov bx,_vectab(bx) | bx = address of routine to call push _M+mtype | push status of last system call push ax | func called with signal number as arg call (bx) back: pop ax | get signal number off stack pop _M+mtype | restore status of previous system call pop es | signal handling finished pop ds pop bp pop di pop si pop dx pop cx pop bx pop ax pop dummy | remove signal number from stack iret .data dummy: .word 0 csv.s Q~ WRITE = 4 FS = 1 |*===========================================================================* |* csv & cret * |*===========================================================================* | This version of csv replaces the standard one. It checks sp. .globl csv, cret, _sp_limit, _sendrec, _M csv: pop bx | bx = return address push bp | stack old frame pointer mov bp,sp | set new frame pointer to sp push di | save di push si | save si sub sp,ax | ax = # bytes of local variables cmp sp,_sp_limit | has stack overflowed? jb csv.err | jump if stack overflow jmp (bx) | normal return: copy bx to pc csv.err: | come here if stack overflow mov _M+2,#WRITE | m_type mov _M+4,#2 | file descriptor 2 is std error mov _M+6,#15 | prepare to print error message mov _M+10,#stkovmsg | error message mov ax,#_M | prepare to call sendrec(FS, &M); push ax | push second parameter mov ax,#FS | prepare to push first parameter push ax | push first parameter call _sendrec | write(fd, stkovmsg, 15); add sp,#4 | clean up stack L0: jmp L0 | hang forever cret: lea sp,*-4(bp) pop si pop di pop bp ret .data _sp_limit: .word 0 | stack limit default is 0 stkovmsg: .asciz "Stack overflow\n" rgetutil.s Q~ .globl _get_base, _get_size, _get_tot_mem .globl endbss |*========================================================================* | utilities * |*========================================================================* _get_base: | return click at which prog starts mov ax,ds ret _get_size: | return prog size in bytes (text+data+bss) mov ax,#endbss | end is compiler label at end of bss ret | Find out how much memory the machine has, including vectors, kernel MM, etc. _get_tot_mem: cli push es push di mov ax,#8192 | start search at 128K (8192 clicks) sub di,di L1: mov es,ax seg es mov (di),#0xA5A4 | write random bit pattern to memory xor bx,bx seg es mov bx,(di) | read back pattern just written cmp bx,#0xA5A4 | compare with expected value jne L2 | if different, no memory present add ax,#4096 | advance counter by 64K cmp ax,#0xA000 | stop seaching at 640K jne L1 L2: pop di pop es sti ret sendrec.s Q~ | See ../h/com.h for C definitions SEND = 1 RECEIVE = 2 BOTH = 3 SYSVEC = 32 |*========================================================================* | send and receive * |*========================================================================* | send(), receive(), sendrec() all save bp, but destroy ax, bx, and cx. .globl _send, _receive, _sendrec _send: mov cx,*SEND | send(dest, ptr) jmp L0 _receive: mov cx,*RECEIVE | receive(src, ptr) jmp L0 _sendrec: mov cx,*BOTH | sendrec(srcdest, ptr) jmp L0 L0: push bp | save bp mov bp,sp | can't index off sp mov ax,4(bp) | ax = dest-src mov bx,6(bp) | bx = message pointer int SYSVEC | trap to the kernel pop bp | restore bp ret | return crtso.s Q~ V| This is the C run-time start-off routine. It's job is to take the | arguments as put on the stack by EXEC, and to parse them and set them up the | way _main expects them. .globl _main, _exit, crtso, _environ .globl begtext, begdata, begbss, endtext, enddata, endbss .text begtext: crtso: mov bx,sp mov cx,(bx) add bx,*2 mov ax,cx inc ax shl ax,#1 add ax,bx mov _environ,ax | save envp in environ push ax | push environ push bx | push argv push cx | push argc call _main add sp,*6 push ax | push exit status call _exit .data begdata: _environ: .word 0 .bss begbss: end.s Q~ K .globl endtext, enddata, endbss .text endtext: .data enddata: .bss endbss: shead.s Q~ .globl _main, _stackpt, begtext, begdata, begbss, _data_org, _exit .text begtext: jmp L0 .zerow 7 | kernel uses this area as stack for inital IRET L0: mov sp,_stackpt call _main L1: jmp L1 | this will never be executed _exit: jmp _exit | this will never be executed either .data begdata: _data_org: | fs needs to know where build stuffed table .word 0xDADA,0,0,0,0,0,0,0 | first 8 words of MM, FS, INIT are for stack | 0xDADA is magic number for build .bss begbss: setjmp.s Q~ .globl _setjmp, _longjmp .globl csv .text _setjmp: mov bx,sp mov ax,(bx) mov bx,*2(bx) mov (bx),bp mov *2(bx),sp mov *4(bx),ax xor ax,ax ret _longjmp: xor ax,ax call csv mov bx,*4(bp) mov ax,*6(bp) or ax,ax jne L1 inc ax L1: mov cx,(bx) L2: cmp cx,*0(bp) je L3 mov bp,*0(bp) or bp,bp jne L2 hlt L3: mov di,*-2(bp) mov si,*-4(bp) mov bp,*0(bp) mov sp,*2(bx) mov cx,*4(bx) mov bx,sp mov (bx),cx ret bscanf.c = /* scanf - formatted input conversion Author: Patrick van Kleef */ #include <stdio.h> int scanf (format, args) char *format; unsigned args; { return _doscanf (0, stdin, format, &args); } int fscanf (fp, format, args) FILE *fp; char *format; unsigned args; { return _doscanf (0, fp, format, &args); } int sscanf (string, format, args) char *string; /* source of data */ char *format; /* control string */ unsigned args; /* our args */ { return _doscanf (1, string, format, &args); } union ptr_union { char *chr_p; unsigned int *uint_p; unsigned long *ulong_p; }; static int ic; /* the current character */ static char *rnc_arg; /* the string or the filepointer */ static rnc_code; /* 1 = read from string, else from FILE */ /* get the next character */ static rnc () { if (rnc_code) { if (!(ic = *rnc_arg++)) ic = EOF; } else ic = getc ((FILE *) rnc_arg); } /* * unget the current character */ static ugc () { if (rnc_code) --rnc_arg; else ungetc (ic, rnc_arg); } static index(ch, string) char ch; char *string; { while (*string++ != ch) if (!*string) return 0; return 1; } /* * this is cheaper than iswhite from <ctype.h> */ static iswhite (ch) int ch; { return (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r'); } static isdigit (ch) int ch; { return (ch >= '0' && ch <= '9'); } static tolower (ch) int ch; { if (ch >= 'A' && ch <= 'Z') ch = ch + 'a' - 'A'; return ch; } /* * the routine that does the job */ _doscanf (code, funcarg, format, argp) int code; /* function to get a character */ char *funcarg; /* an argument for the function */ char *format; /* the format control string */ union ptr_union *argp; /* our argument list */ { int done = 0; /* number of items done */ int base; /* conversion base */ long val; /* an integer value */ int sign; /* sign flag */ int do_assign; /* assignment suppression flag */ unsigned width; /* width of field */ int widflag; /* width was specified */ int longflag; /* true if long */ int done_some; /* true if we have seen some data */ int reverse; /* reverse the checking in [...] */ char *endbracket; /* position of the ] in format string */ rnc_arg = funcarg; rnc_code = code; rnc (); /* read the next character */ if (ic == EOF) { done = EOF; goto quit; } while (1) { while (iswhite (*format)) ++format; /* skip whitespace */ if (!*format) goto all_done; /* end of format */ if (ic < 0) goto quit; /* seen an error */ if (*format != '%') { while (iswhite (ic)) rnc (); if (ic != *format) goto all_done; ++format; rnc (); ++done; continue; } ++format; do_assign = 1; if (*format == '*') { ++format; do_assign = 0; } if (isdigit (*format)) { widflag = 1; for (width = 0; isdigit (*format);) width = width * 10 + *format++ - '0'; } else widflag = 0; /* no width spec */ if (longflag = (tolower (*format) == 'l')) ++format; if (*format != 'c') while (iswhite (ic)) rnc (); done_some = 0; /* nothing yet */ switch (*format) { case 'o': base = 8; goto decimal; case 'u': case 'd': base = 10; goto decimal; case 'x': base = 16; if (((!widflag) || width >= 2) && ic == '0') { rnc (); if (tolower (ic) == 'x') { width -= 2; done_some = 1; rnc (); } else { ugc (); ic = '0'; } } decimal: val = 0L; /* our result value */ sign = 0; /* assume positive */ if (!widflag) width = 0xffff; /* very wide */ if (width && ic == '+') rnc (); else if (width && ic == '-') { sign = 1; rnc (); } while (width--) { if (isdigit (ic) && ic - '0' < base) ic -= '0'; else if (base == 16 && tolower (ic) >= 'a' && tolower (ic) <= 'f') ic = 10 + tolower (ic) - 'a'; else break; val = val * base + ic; rnc (); done_some = 1; } if (do_assign) { if (sign) val = -val; if (longflag) *(argp++)->ulong_p = (unsigned long) val; else *(argp++)->uint_p = (unsigned) val; } if (done_some) ++done; else goto all_done; break; case 'c': if (!widflag) width = 1; while (width-- && ic >= 0) { if (do_assign) *(argp)->chr_p++ = (char) ic; rnc (); done_some = 1; } if (do_assign) argp++; /* done with this one */ if (done_some) ++done; break; case 's': if (!widflag) width = 0xffff; while (width-- && !iswhite (ic) && ic > 0) { if (do_assign) *(argp)->chr_p++ = (char) ic; rnc (); done_some = 1; } if (do_assign) /* terminate the string */ *(argp++)->chr_p = '\0'; if (done_some) ++done; else goto all_done; break; case '[': if (!widflag) width = 0xffff; if ( *(++format) == '^' ) { reverse = 1; format++; } else reverse = 0; endbracket = format; while ( *endbracket != ']' && *endbracket != '\0') endbracket++; if (!*endbracket) goto quit; *endbracket = '\0'; /* change format string */ while (width-- && !iswhite (ic) && ic > 0 && (index (ic, format) ^ reverse)) { if (do_assign) *(argp)->chr_p++ = (char) ic; rnc (); done_some = 1; } format = endbracket; *format = ']'; /* put it back */ if (do_assign) /* terminate the string */ *(argp++)->chr_p = '\0'; if (done_some) ++done; else goto all_done; break; } /* end switch */ ++format; } all_done: if (ic >= 0) ugc (); /* restore the character */ quit: return done; } t