repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
frankjas/libjr
libjr/misc/cmpstrqs.c
#include "ezport.h" #include <string.h> #include "jr/string.h" jr_int jr_strpcmp(void_arg_1,void_arg_2) const void * void_arg_1; const void * void_arg_2; { char ** sa1 = (void *) void_arg_1 ; char ** sa2 = (void *) void_arg_2 ; return(strcmp(*sa1,*sa2)) ; } jr_int jr_stricmp(void_arg_1, void_arg_2) const void * void_arg_1; const void * void_arg_2; { char * str1 = (void *) void_arg_1; char * str2 = (void *) void_arg_2; jr_int c1; jr_int c2; jr_int diff; for (; *str1 != 0 && *str2 != 0; str1++, str2++) { c1 = jr_toupper (*str1); c2 = jr_toupper (*str2); diff = c1 - c2; if (diff != 0) return diff; } return *str1 - *str2; }
frankjas/libjr
libjr/missing/memset.c
<gh_stars>0 #define _POSIX_SOURCE 1 #include "ezport.h" #include <string.h> /* * This routine conforms to the ANSI standard * description for 'memset(dest,value,nbytes)' * used for setting arbitrary byte streams to * a single value (usually zero). * We provide the source because * some C environments are not provided with all * of the ANSI specified routines. */ #ifdef missing_memset void *memset(destin_arg, value, nbytes) void *destin_arg ; int value ; unsigned long nbytes ; { char *destin = (char *) destin_arg ; unsigned jr_int i ; for (i=0; i < nbytes; i++) { destin[i] = value ; } return(destin_arg) ; } #else static void NotCalled () /* define this so ranlib doesn't complain */ { NotCalled (); /* use it so the compiler doesn't complain */ } #endif
frankjas/libjr
libjr/avl_tree/avl_trav.c
#define AVL_TRAV_SRC #include "project.h" void jr_AVL_TreeTraverseInOrder(avl_tree, printfn, data_arg) jr_AVL_Tree * avl_tree; void (*printfn)() ; void * data_arg; { jr_AVL_TreeTraverseElementInOrder (avl_tree, jr_AVL_TreeRootPtr (avl_tree), printfn, data_arg); } void jr_AVL_TreeTraverseElementInOrder(avl_tree, node, printfn, data_arg) jr_AVL_Tree * avl_tree; const void * node ; void (*printfn)() ; void * data_arg; { if (node == 0) return ; if (jr_AVL_TreeLeftChildPtr (avl_tree, node)) { jr_AVL_TreeTraverseElementInOrder ( avl_tree, jr_AVL_TreeLeftChildPtr (avl_tree, node), printfn, data_arg ); } (*printfn)(node, data_arg) ; if (jr_AVL_TreeRightChildPtr (avl_tree, node)) { jr_AVL_TreeTraverseElementInOrder ( avl_tree, jr_AVL_TreeRightChildPtr (avl_tree, node), printfn, data_arg ); } }
frankjas/libjr
libjr/missing/xdr_float.c
<reponame>frankjas/libjr /* $NetBSD: xdr_float.c,v 1.9 1995/06/05 11:48:26 pk Exp $ */ /* * Sun RPC is a product of Sun Microsystems, Inc. and is provided for * unrestricted use provided that this legend is included on all tape * media and as a part of the software program in whole or part. Users * may copy or modify Sun RPC without charge, but are not authorized * to license or distribute it to anyone else except as part of a product or * program developed by the user. * * SUN RPC IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE * WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR * PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE. * * Sun RPC is provided with no support and without any obligation on the * part of Sun Microsystems, Inc. to assist in its use, correction, * modification or enhancement. * * SUN MICROSYSTEMS, INC. SHALL HAVE NO LIABILITY WITH RESPECT TO THE * INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY SUN RPC * OR ANY PART THEREOF. * * In no event will Sun Microsystems, Inc. be liable for any lost revenue * or profits or other special, indirect and consequential damages, even if * Sun has been advised of the possibility of such damages. * * Sun Microsystems, Inc. * 2550 Garcia Avenue * Mountain View, California 94043 */ #if defined(LIBC_SCCS) && !defined(lint) /*static char *sccsid = "from: @(#)xdr_float.c 1.12 87/08/11 Copyr 1984 Sun Micro";*/ /*static char *sccsid = "from: @(#)xdr_float.c 2.1 88/07/29 4.0 RPCSRC";*/ static char *rcsid = "$NetBSD: xdr_float.c,v 1.9 1995/06/05 11:48:26 pk Exp $"; #endif /* * xdr_float.c, Generic XDR routines impelmentation. * * Copyright (C) 1984, Sun Microsystems, Inc. * * These are the "floating point" xdr routines used to (de)serialize * most common data items. See xdr.h for more info on the interface to * xdr. */ /* * NB: Not portable. * This routine works on machines with IEEE754 FP and Vaxen. */ /* ** 1/25/07 Copied from rpc/types.h and rpc/xdr.h ** Modified to use JR types for portability ** ** Only supports IEEE754, eliminated VAX support for clarity */ #include "ezport.h" #ifdef missing_xdr_float #include <stdio.h> #include "jr/xdr.h" #include "jr/misc.h" #include "jr/nettype.h" #ifndef BYTE_ORDER # error "No BYTE_ORDER defined (big, little endian)" #endif #define int32_t jr_int #define bool_t jr_int #define TRUE ((jr_int) 1) #define FALSE ((jr_int) 0) bool_t xdr_float(xdrs, fp) register XDR *xdrs; register float *fp; { bool_t rv; long tmpl; switch (xdrs->x_op) { case XDR_ENCODE: tmpl = *(int32_t *)fp; return (XDR_PUTLONG(xdrs, &tmpl)); case XDR_DECODE: rv = XDR_GETLONG(xdrs, &tmpl); *(int32_t *)fp = tmpl; return (rv); case XDR_FREE: return (TRUE); } return (FALSE); } bool_t xdr_double(xdrs, dp) register XDR *xdrs; double *dp; { register int32_t *i32p; bool_t rv; long tmpl; switch (xdrs->x_op) { case XDR_ENCODE: i32p = (int32_t *)dp; #if BYTE_ORDER == BIG_ENDIAN tmpl = *i32p++; rv = XDR_PUTLONG(xdrs, &tmpl); if (!rv) return (rv); tmpl = *i32p; rv = XDR_PUTLONG(xdrs, &tmpl); #else tmpl = *(i32p+1); rv = XDR_PUTLONG(xdrs, &tmpl); if (!rv) return (rv); tmpl = *i32p; rv = XDR_PUTLONG(xdrs, &tmpl); #endif return (rv); case XDR_DECODE: i32p = (int32_t *)dp; #if BYTE_ORDER == BIG_ENDIAN rv = XDR_GETLONG(xdrs, &tmpl); *i32p++ = tmpl; if (!rv) return (rv); rv = XDR_GETLONG(xdrs, &tmpl); *i32p = tmpl; #else rv = XDR_GETLONG(xdrs, &tmpl); *(i32p+1) = tmpl; if (!rv) return (rv); rv = XDR_GETLONG(xdrs, &tmpl); *i32p = tmpl; #endif return (rv); case XDR_FREE: return (TRUE); } return (FALSE); } #else static void NotCalled () /* define this so ranlib doesn't complain */ { NotCalled (); /* use it so the compiler doesn't complain */ } #endif
frankjas/libjr
libjr/misc/cmpfilnm.c
#include "ezport.h" #include <string.h> #include "jr/string.h" jr_int jr_trailing_filename_pcmp(sa1,sa2) char ** sa1 ; char ** sa2 ; { char * trailing1 = strrchr(*sa1, '/') ; char * trailing2 = strrchr(*sa2, '/') ; if (trailing1 == 0) trailing1 = *sa1 ; else trailing1++ ; if (trailing2 == 0) trailing2 = *sa2 ; else trailing2++ ; return(strcmp(trailing1,trailing2)) ; }
frankjas/libjr
libjr/missing/setvbuf.c
#define _POSIX_SOURCE 1 #include "ezport.h" #ifdef missing_setvbuf_objects #include <stdio.h> #include <errno.h> #ifndef _IOFBF # define _IOFBF 0 #endif extern void setlinebuf PROTO ((FILE *stream)); extern void setbuffer PROTO ((FILE *stream, char *buf, int size)); int setvbuf (stream, buf, mode, size) FILE * stream; char * buf; int mode; size_t size; { if (mode & _IOFBF) { /* * full buffering. */ errno = EINVAL; return -1; } if (mode & _IOLBF) { setlinebuf (stream); } if (mode & _IONBF) { /* * 0 buffer turns on unbuffered input/output */ setbuffer (stream, 0, 0); } if (buf) { setbuffer (stream, buf, size); } return 0; } #else static void NotCalled () /* define this so ranlib doesn't complain */ { NotCalled (); /* use it so the compiler doesn't complain */ } #endif
frankjas/libjr
include/jr/intset.h
#ifndef _intseth #define _intseth #include "ezport.h" typedef struct { jr_int *array; jr_int next_index; jr_int max_size; } jr_IntSet; extern jr_IntSet *jr_IntSetCreate PROTO((void)) ; extern void jr_IntSetInit PROTO((jr_IntSet *iset)) ; extern jr_IntSet *jr_IntSetCreateFromIntStr PROTO((jr_int *ia)) ; extern jr_int jr_IntSetCmp PROTO((jr_IntSet *iseta, jr_IntSet *isetb)) ; extern jr_int jr_IntSetFind PROTO((jr_IntSet *iset, jr_int n)) ; extern jr_int *jr_IntSetToIntStr PROTO((jr_IntSet *iset)) ; extern void jr_IntSetAdd PROTO((jr_IntSet *iset, jr_int n)) ; extern void jr_IntSetAddMax PROTO((jr_IntSet *iset, jr_int n)) ; extern void jr_IntSetAddSet PROTO((jr_IntSet *iseta, jr_IntSet *isetb)) ; extern void jr_IntSetDelete PROTO((jr_IntSet *iset, jr_int n)) ; extern void jr_IntSetDestroy PROTO((jr_IntSet *iset)) ; extern void jr_IntSetUndo PROTO((jr_IntSet *iset)) ; extern jr_int jr_IntSetFindIndex PROTO((jr_IntSet *iset, jr_int n)) ; extern void jr_IntSetIncreaseSize PROTO((jr_IntSet *iset, jr_int minelements)) ; extern void jr_IntSetUnion PROTO(( jr_IntSet *isetc, jr_IntSet *iseta, jr_IntSet *isetb )) ; extern void jr_IntSetIntersection PROTO(( jr_IntSet *isetc, jr_IntSet *iseta, jr_IntSet *isetb )) ; #define jr_IntSetSize(iset) ((iset)->next_index) #define jr_IntSetArray(iset) ((iset)->array) #define jr_IntSetElement(iset, i) ((iset)->array[i]) #define jr_IntSetDeleteMax(iset) ((iset)->next_index--) #define jr_IntSetForEachElement(iset, i, n) for (i=0, n=jr_IntSetElement(iset, 0); i < (iset)->next_index; i++, n=jr_IntSetElement(iset, i)) #define jr_IntSetEmpty(iset) ((iset)->next_index = 0) #define jr_IntSetIsEmpty(iset) ((iset)->next_index == 0) /******** Local functions and macros *******/ # endif
frankjas/libjr
libjr/misc/cmpmisc.c
<filename>libjr/misc/cmpmisc.c #include "ezport.h" #include <string.h> #include <ctype.h> #include "jr/misc.h" jr_int jr_rev_strcmp (s, t) const char *s, *t; { return (- strcmp (s, t)); } jr_int jr_opt_strcmp (str1, str2) const char * str1; const char * str2; { if (str1 == 0 && str2 == 0) return 0; if (str1 == 0 && str2 != 0) return -1; if (str1 != 0 && str2 == 0) return 1; return strcmp (str1, str2); } jr_int jr_opt_strcasecmp (str1, str2) const char * str1; const char * str2; { if (str1 == 0 && str2 == 0) return 0; if (str1 == 0 && str2 != 0) return -1; if (str1 != 0 && str2 == 0) return 1; return strcasecmp (str1, str2); } jr_int jr_opt_canon_strcmp (str1, str2) const char * str1; const char * str2; { if (str1 == 0 && str2 == 0) return 0; if (str1 == 0 && str2 != 0) return -1; if (str1 != 0 && str2 == 0) return 1; return jr_canon_strcmp (str1, str2); } jr_int jr_canon_strcmp (str1, str2) const char * str1; const char * str2; { jr_int diff; jr_int was_alnum_1 = 0; jr_int was_alnum_2 = 0; jr_int skipped_space_1 = 0; jr_int skipped_space_2 = 0; /* * Ignore case and white space, except if the * white space separates words (alphabetic/numeric characters), * but then treat arbitrary sequences of white space as equal. */ while (1) { for (; *str1; str1++) { if (isspace (*str1)) { skipped_space_1 = 1; } else { break; } } for (; *str2; str2++) { if (isspace (*str2)) { skipped_space_2 = 1; } else { break; } } if ( isalnum (*str1) && isalnum (*str2) && was_alnum_1 && was_alnum_2) { diff = skipped_space_1 - skipped_space_2; if (diff != 0) { return diff; } } diff = tolower (*str1) - tolower (*str2); if (diff != 0) { return diff; } if (*str1 == 0) { return 0; } skipped_space_1 = 0; skipped_space_2 = 0; was_alnum_1 = isalnum (*str1); was_alnum_2 = isalnum (*str2); str1++; str2++; } return 0; } jr_int jr_canon_is_prefix (str1, str2) const char * str1; const char * str2; { jr_int diff; jr_int was_alnum_1 = 0; jr_int was_alnum_2 = 0; jr_int skipped_space_1 = 0; jr_int skipped_space_2 = 0; /* * Ignore case and white space, except if the * white space separates words (alphabetic/numeric characters), * but then treat arbitrary sequences of white space as equal. */ while (1) { for (; *str1; str1++) { if (isspace (*str1)) { skipped_space_1 = 1; } else { break; } } for (; *str2; str2++) { if (isspace (*str2)) { skipped_space_2 = 1; } else { break; } } if (*str1 == 0) { return 1; } if ( isalnum (*str1) && isalnum (*str2) && was_alnum_1 && was_alnum_2) { diff = skipped_space_1 - skipped_space_2; if (diff != 0) { return 0; } } diff = tolower (*str1) - tolower (*str2); if (diff != 0) { return 0; } skipped_space_1 = 0; skipped_space_2 = 0; was_alnum_1 = isalnum (*str1); was_alnum_2 = isalnum (*str2); str1++; str2++; } return 0; }
frankjas/libjr
libjr/alist/alistfnd.c
#include "project.h" void *jr_AListFindElementPtr (list, el_ptr, cmpfn) jr_AList * list; const void * el_ptr; jr_int (*cmpfn)(); { jr_int diff; jr_int mid_index; jr_int low_index; jr_int high_index; low_index = 0; high_index = jr_AListSize (list); while (low_index != high_index) { mid_index = low_index + (high_index - low_index) / 2; diff = (*cmpfn) (el_ptr, jr_AListElementPtr (list, mid_index)); if (diff == 0) { return jr_AListElementPtr (list, mid_index); } if (diff > 0) { low_index = mid_index + 1; } else { high_index = mid_index; } } return 0; } void *jr_AListFindFirstElementPtr (list, el_ptr, cmpfn) jr_AList * list; const void * el_ptr; jr_int (*cmpfn)(); { const char * found_el_ptr; found_el_ptr = jr_AListFindElementPtr (list, el_ptr, cmpfn); if (found_el_ptr) { found_el_ptr -= jr_AListElementSize (list); while ((void *) found_el_ptr >= jr_AListHeadPtr (list)) { if ((*cmpfn) (el_ptr, found_el_ptr) != 0) { break; } found_el_ptr -= jr_AListElementSize (list); } found_el_ptr += jr_AListElementSize (list); } return (void *) found_el_ptr; } void *jr_AListFindInsertPtr (list, el_ptr, cmpfn) jr_AList * list; const void * el_ptr; jr_int (*cmpfn) (); { jr_int diff; jr_int mid_index; jr_int low_index; jr_int high_index; if (jr_AListSize (list) == 0) { jr_AListIncreaseCapacity (list, 1); return jr_AListHeadPtr (list); } low_index = 0; high_index = jr_AListSize (list); while (low_index != high_index) { mid_index = low_index + (high_index - low_index) / 2; diff = (*cmpfn) (el_ptr, jr_AListElementPtr (list, mid_index)); if (diff == 0) { return jr_AListElementPtr (list, mid_index); } if (diff > 0) { low_index = mid_index + 1; } else { high_index = mid_index; } } return jr_AListElementPtr (list, low_index); } void *jr_AListSetNewTailUniquely (list, el_ptr, cmpfn) jr_AList * list; const void * el_ptr; jr_int (*cmpfn) (); { void * found_el_ptr ; found_el_ptr = jr_AListFindElementPtr (list, el_ptr, cmpfn); if (found_el_ptr) { return 0; } return jr_AListSetNewTail (list, el_ptr); }
frankjas/libjr
include/jr/strtab.h
<filename>include/jr/strtab.h #ifndef __jr_strtab_h___ #define __jr_strtab_h___ #include "ezport.h" #include "jr/htable.h" typedef struct { jr_HTable string_table [1]; } jr_StringTableType; /* ** 11/3/05: Benefit of adding suffix "Type", can grep for all occurences ** of variable declarations more easily. */ typedef struct { const char * string; } jr_StringTableEntryType; extern void jr_StringTableInit PROTO (( jr_StringTableType * str_table_ptr, jr_int user_data_size )); extern void jr_StringTableUndo PROTO (( jr_StringTableType * str_table_ptr )); extern jr_StringTableType *jr_StringTableCreate PROTO (( jr_int user_data_size )); extern void jr_StringTableDestroy PROTO (( jr_StringTableType * str_table_ptr )); extern jr_int jr_StringTableAddNewString PROTO (( jr_StringTableType * str_table_ptr, const char * new_string )); extern jr_int jr_StringTableFindString PROTO (( jr_StringTableType * str_table_ptr, const char * string )); #define jr_StringTableSize(str_table_ptr) \ jr_HTableSize ((str_table_ptr)->string_table) #define jr_StringTableString(str_table_ptr, string_index) \ jr_StringTableEntryString ( \ jr_StringTablePrefixEntryPtr (str_table_ptr, string_index) \ ) #define jr_StringTableElementPtr(str_table_ptr, string_index) \ jr_HTableElementPtr ( \ (str_table_ptr)->string_table, string_index \ ) #define jr_StringTableForEachElementIndex(str_table_ptr, string_index) \ jr_HTableForEachElementIndex ( \ (str_table_ptr)->string_table, string_index \ ) #define jr_StringTableForEachElementPtr(str_table_ptr, el_ptr) \ jr_HTableForEachElementPtr ( \ (str_table_ptr)->string_table, el_ptr \ ) #define jr_StringTablePrefixEntryPtr(str_table_ptr, string_index) \ ((jr_StringTableEntryType *) \ jr_HTableElementPtr ( \ (str_table_ptr)->string_table, string_index \ ) - 1 \ ) #define jr_StringTableEntryString(entry_ptr) \ ((entry_ptr)->string) #endif
frankjas/libjr
libjr/syscalls/tmpdir.c
#define _POSIX_SOURCE 1 #include "ezport.h" #ifdef ostype_winnt # include <windows.h> # include <stdlib.h> #endif #include <stdio.h> #include <string.h> #include "jr/error.h" # ifdef ostype_winnt jr_int jr_GetTempDir (tmp_dir_buf, tmp_dir_buf_length, error_buf) char * tmp_dir_buf; jr_int tmp_dir_buf_length; char * error_buf; { jr_int dir_length; dir_length = GetTempPath( tmp_dir_buf_length, tmp_dir_buf); if (dir_length + 1 > tmp_dir_buf_length) { jr_esprintf (error_buf, "buffer too small, minimum size is %u", dir_length + 1); return -1; } return 0; } # else jr_int jr_GetTempDir (tmp_dir_buf, tmp_dir_buf_length, error_buf) char * tmp_dir_buf; jr_int tmp_dir_buf_length; char * error_buf; { const char * tmp_dir = "/tmp"; if ((jr_int) strlen (tmp_dir) + 1 > tmp_dir_buf_length) { jr_esprintf (error_buf, "buffer too small, minimum size is %u", (unsigned) strlen (tmp_dir) + 1); return -1; } strcpy (tmp_dir_buf, tmp_dir); return 0; } # endif
frankjas/libjr
include/jr/avl_tree.h
#ifndef __AVL_HEADER__ #define __AVL_HEADER__ #include "ezport.h" #include <stdio.h> #include <stdarg.h> typedef struct { void * root_node; jr_int element_size; jr_int (*cmpfn) (); void * cmpfn_arg; jr_int prefix_size; unsigned allocates_elements : 1; unsigned maintains_size : 1; } jr_AVL_Tree; #define jr_AVL_TREE_MAX_HEIGHT (12 * sizeof (void *)) /* * height 48 means the tree has more than 2^32 elements, * height 96 is more than 2^64 (I'm guessing here) * so if a void* is 8 bytes this will scale up to a tree with * more elements than addressable memory * AVL height < 1.44 * log2(n) < 1.44 * 8 * sizeof(void*) < 12 * sizeof(void*) */ typedef struct { void * left_node_ptr ; void * right_node_ptr ; jr_short node_height; /* * Height will never be greater than 100, on a typical system. * The size of this structure will be padded by 2 bytes on * systems with 'int' alignment requirements, so it shouldn't * keep 'int' alignment on the application's data as well. */ } jr_AVL_TreeElementStruct ; typedef struct { jr_int tree_size; } jr_AVL_TreeSizeStruct ; extern jr_AVL_Tree * jr_AVL_TreeCreate PROTO (( jr_int element_size, jr_int (*cmpfn) () )); extern void jr_AVL_TreeInit PROTO (( jr_AVL_Tree * avl_tree, jr_int element_size, jr_int (*cmpfn) () )); extern void jr_AVL_TreeDestroy PROTO ((jr_AVL_Tree *avl_tree)); extern void jr_AVL_TreeUndo PROTO ((jr_AVL_Tree *avl_tree)); extern void jr_AVL_TreeEmpty PROTO ((jr_AVL_Tree *avl_tree)); extern void jr_AVL_TreeSetMaintainsSize PROTO (( jr_AVL_Tree * avl_tree, jr_int value )); extern jr_int jr_AVL_TreeElementPrefixSize PROTO (( jr_AVL_Tree * avl_tree )); extern void jr_AVL_TreeSetPrefixSize PROTO (( jr_AVL_Tree * avl_tree, jr_int prefix_size )); extern void jr_AVL_TreeSetContainers PROTO (( jr_AVL_Tree * avl_tree, ... )); extern void jr_AVL_TreeSetContainersFromVA_List PROTO (( jr_AVL_Tree * avl_tree, va_list arg_list )); extern jr_int jr_AVL_TreeInsertElementUsingKey PROTO (( jr_AVL_Tree * avl_tree, const void * new_node, const void * key_node )); extern void jr_AVL_TreeInsertElementUsingIndex PROTO (( jr_AVL_Tree * avl_tree, const void * new_node, jr_int index )); extern void * jr_AVL_TreeExtractElementUsingKey PROTO (( jr_AVL_Tree * avl_tree, const void * key_node )); extern void * jr_AVL_TreeExtractElementUsingIndex PROTO (( jr_AVL_Tree * avl_tree, jr_int index_value )); extern void jr_AVL_TreeAppendLastIndexedElement PROTO (( jr_AVL_Tree * avl_tree, const void * new_node )); extern void * jr_AVL_TreeFindElementPtrUsingKey PROTO (( jr_AVL_Tree * avl_tree, const void * obj )); extern void * jr_AVL_TreeFindElementPtrUsingIndex PROTO (( jr_AVL_Tree * avl_tree, jr_int index )); extern void * jr_AVL_TreeSmallestElementPtr PROTO (( jr_AVL_Tree * avl_tree )); extern void * jr_AVL_TreeGreatestElementPtr PROTO (( jr_AVL_Tree * avl_tree )); extern void * jr_AVL_TreePrevElementPtr PROTO (( jr_AVL_Tree * avl_tree, const void * obj )); extern void * jr_AVL_TreeNextElementPtr PROTO (( jr_AVL_Tree * avl_tree, const void * obj )); extern void jr_AVL_TreeTransformPrefix PROTO (( jr_AVL_Tree * avl_tree, void * el_ptr, unsigned jr_int magnitude, jr_int which_way, jr_int all_elements )); extern void jr_AVL_TreeMakeNullElement PROTO (( jr_AVL_Tree * avl_tree, void * el_ptr )); extern jr_int jr_AVL_TreeIndexedCmp PROTO (( const void * void_ptr1, const void * void_ptr2 )); #define jr_AVL_TreeRootPtr(avl_tree) \ ((avl_tree)->root_node) #define jr_AVL_TreeElementSize(avl_tree) \ ((avl_tree)->element_size) #define jr_AVL_TreePrefixSize(avl_tree) \ ((avl_tree)->prefix_size) #define jr_AVL_TreeAllocatesElements(avl_tree) \ ((avl_tree)->allocates_elements) #define jr_AVL_TreeMaintainsSize(avl_tree) \ ((avl_tree)->maintains_size) #define jr_AVL_TreeIsEmpty(avl_tree) \ (jr_AVL_TreeRootPtr (avl_tree) == 0) #define jr_AVL_TreeIsRootElement(avl_tree, node) \ ((void *)(node) == jr_AVL_TreeRootPtr (avl_tree)) #define jr_AVL_TreeSetCmpFn(avl_tree, v) \ ((avl_tree)->cmpfn = (v)) #define jr_AVL_TreeSetCmpFnArg(avl_tree, v) \ ((avl_tree)->cmpfn_arg = (v)) #define jr_AVL_TreeSize(avl_tree) \ ((avl_tree)->root_node \ ? jr_AVL_TreeSubTreeSize (avl_tree, (avl_tree)->root_node) \ : 0 \ ) /******** Element Operations ********/ extern void * jr_AVL_TreeAllocateElementWithSize PROTO (( jr_AVL_Tree * avl_tree, jr_int length )); extern void jr_AVL_TreeFreeElement PROTO (( jr_AVL_Tree * avl_tree, void * node_ptr )); #define jr_AVL_ElementInfoPtrWithPrefix(node_ptr, prefix_size) \ ((jr_AVL_TreeElementStruct *) \ ((char *) (node_ptr) - (prefix_size)) - 1 \ ) #define jr_AVL_ElementSizeInfoPtrWithPrefix(nptr, pre_size) \ ((jr_AVL_TreeSizeStruct *) \ jr_AVL_ElementInfoPtrWithPrefix (nptr, pre_size) - 1 \ ) #define jr_AVL_ElementLeftChildPtrWithPrefix(node_ptr, prefix_size) \ (jr_AVL_ElementInfoPtrWithPrefix (node_ptr, prefix_size)->left_node_ptr) #define jr_AVL_ElementRightChildPtrWithPrefix(node_ptr, prefix_size) \ (jr_AVL_ElementInfoPtrWithPrefix (node_ptr, prefix_size)->right_node_ptr) #define jr_AVL_ElementHeightWithPrefix(node_ptr, prefix_size) \ (jr_AVL_ElementInfoPtrWithPrefix (node_ptr, prefix_size)->node_height) #define jr_AVL_ElementIsLeafWithPrefix(node_ptr, prefix_size) \ (jr_AVL_ElementHeightWithPrefix (node_ptr, prefix_size) == 0) #define jr_AVL_ElementTreeSizeWithPrefix(node_ptr, prefix_size) \ (jr_AVL_ElementSizeInfoPtrWithPrefix (node_ptr, prefix_size)->tree_size) /****** Convenience Functions ******/ #define jr_AVL_TreeAllocateElement(avl_tree) \ jr_AVL_TreeAllocateElementWithSize ( \ avl_tree, jr_AVL_TreeElementSize (avl_tree) \ ) extern void * jr_AVL_TreeNewElementPtrWithSize PROTO (( jr_AVL_Tree * avl_tree, const void * key_node, jr_int length )); extern void * jr_AVL_TreeSetNewElementWithSize PROTO (( jr_AVL_Tree * avl_tree, const void * key_node, jr_int length )); #define jr_AVL_TreeNewElementPtr(avl_tree, obj) \ jr_AVL_TreeNewElementPtrWithSize ( \ avl_tree, obj, jr_AVL_TreeElementSize (avl_tree) \ ) #define jr_AVL_TreeSetNewElement(avl_tree, obj) \ jr_AVL_TreeSetNewElementWithSize ( \ avl_tree, obj, jr_AVL_TreeElementSize (avl_tree) \ ) #define jr_AVL_TreeInsertElement(avl_tree, new_el) \ jr_AVL_TreeInsertElementUsingKey (avl_tree, new_el, new_el) /******** Index Insertions ********/ extern void * jr_AVL_TreeNewIndexedElementPtrWithSize PROTO (( jr_AVL_Tree * avl_tree, jr_int index, jr_int length )); extern void * jr_AVL_TreeSetNewIndexedElementWithSize PROTO (( jr_AVL_Tree * avl_tree, jr_int index, const void * new_element, jr_int length )); extern void * jr_AVL_TreeNewLastIndexedElementPtrWithSize PROTO (( jr_AVL_Tree * avl_tree, jr_int length )); extern void * jr_AVL_TreeSetNewLastIndexedElementWithSize PROTO (( jr_AVL_Tree * avl_tree, const void * new_element, jr_int length )); #define jr_AVL_TreeNewIndexedElementPtr(avl_tree, index) \ jr_AVL_TreeNewIndexedElementPtrWithSize ( \ avl_tree, index, jr_AVL_TreeElementSize (avl_tree) \ ) #define jr_AVL_TreeSetNewIndexedElement(avl_tree, index, obj) \ jr_AVL_TreeSetNewIndexedElementWithSize ( \ avl_tree, index, obj, jr_AVL_TreeElementSize (avl_tree) \ ) #define jr_AVL_TreeNewLastIndexedElementPtr(avl_tree) \ jr_AVL_TreeNewLastIndexedElementPtrWithSize ( \ avl_tree, jr_AVL_TreeElementSize (avl_tree) \ ) #define jr_AVL_TreeSetNewLastIndexedElement(avl_tree, obj) \ jr_AVL_TreeSetNewLastIndexedElementWithSize ( \ avl_tree, obj, jr_AVL_TreeElementSize (avl_tree) \ ) #define jr_AVL_TreeFindElementPtr(avl_tree, new_el) \ jr_AVL_TreeFindElementPtrUsingKey (avl_tree, new_el) #define jr_AVL_TreeFindIndexedElementPtr(avl_tree, index) \ jr_AVL_TreeFindElementPtrUsingIndex (avl_tree, index) #define jr_AVL_TreeExtractElement(avl_tree, key_el) \ jr_AVL_TreeExtractElementUsingKey (avl_tree, key_el) extern jr_int jr_AVL_TreeDeleteElement PROTO (( jr_AVL_Tree * avl_tree, void * key_node )); extern jr_int jr_AVL_TreeDeleteIndexedElement PROTO (( jr_AVL_Tree * avl_tree, jr_int index )); extern jr_int jr_AVL_TreeCalculateElementIndex PROTO (( jr_AVL_Tree * avl_tree, const void * existing_node )); /******** Traversal & Misc *********/ #ifdef AVL_TRAV_SRC # define jr_AVL_TreeTraverse_param void *data_arg #else # define jr_AVL_TreeTraverse_param ... #endif extern void jr_AVL_TreeTraverseInOrder PROTO(( jr_AVL_Tree * avl_tree, void (*printfn)(), jr_AVL_TreeTraverse_param )); #define jr_AVL_TreeTraverseForUndo(avl_tree, undo_fn) \ jr_AVL_TreeTraverseInOrder (avl_tree, undo_fn) extern void jr_AVL_TreeTraverseElementInOrder PROTO(( jr_AVL_Tree * avl_tree, const void * node, void (*printfn)(), jr_AVL_TreeTraverse_param )); extern void jr_AVL_TreePrint PROTO (( jr_AVL_Tree * avl_tree, FILE * wfp, void (*print_node_fn) (), jr_int print_width )); #define jr_AVL_TreeForEachElementIndex(avl_tree, index) \ for ((index) = 0; (index) < jr_AVL_TreeSize (avl_tree); (index)++) #define jr_AVL_TreeForEachElementIndexRev(avl_tree, index) \ for ((index) = jr_AVL_TreeSize (avl_tree) - 1; (index) >= 0; (index)--) #define jr_AVL_TreeForEachElementPtr(avl_tree, node_ptr) \ for ( \ (node_ptr) = jr_AVL_TreeSmallestElementPtr (avl_tree); \ (node_ptr) != 0; \ (node_ptr) = jr_AVL_TreeNextElementPtr (avl_tree, node_ptr) \ ) #define jr_AVL_TreeForEachElementPtrRev(avl_tree, node_ptr) \ for ( \ (node_ptr) = jr_AVL_TreeGreatestElementPtr (avl_tree); \ (node_ptr) != 0; \ (node_ptr) = jr_AVL_TreePrevElementPtr (avl_tree, node_ptr) \ ) #define jr_AVL_TreeLeftChildPtr(avl_tree, node_ptr) \ jr_AVL_ElementLeftChildPtrWithPrefix (node_ptr, jr_AVL_TreePrefixSize (avl_tree)) #define jr_AVL_TreeRightChildPtr(avl_tree, node_ptr) \ jr_AVL_ElementRightChildPtrWithPrefix (node_ptr, jr_AVL_TreePrefixSize (avl_tree)) #define jr_AVL_TreeElementHeight(avl_tree, node_ptr) \ jr_AVL_ElementHeightWithPrefix (node_ptr, jr_AVL_TreePrefixSize (avl_tree)) #define jr_AVL_TreeElementIsLeaf(avl_tree, node_ptr) \ jr_AVL_ElementIsLeafWithPrefix (node_ptr, jr_AVL_TreePrefixSize (avl_tree)) #define jr_AVL_TreeSubTreeSize(avl_tree, node_ptr) \ jr_AVL_ElementTreeSizeWithPrefix (node_ptr, jr_AVL_TreePrefixSize (avl_tree)) #define jr_AVL_TreeSetSubTreeSize(avl_tree, node_ptr, v) \ (jr_AVL_TreeSubTreeSize (avl_tree, node_ptr) = (v)) #endif
frankjas/libjr
libjr/jr_malloc/jr_exit.c
#include "ezport.h" #include <stdio.h> #include <stdlib.h> #include "jr/malloc.h" #include "jr/error.h" #include "jr/trace.h" #include "jr/apr.h" const char * jr_ProgramName = 0; /* ** 5-17-2011 Note: referencing jr_ProgramName links in the APR */ void jr_exit (exit_status) jr_int exit_status; { jr_int status; char error_buf [jr_ERROR_LEN]; jr_apr_terminate(); if (jr_do_trace (jr_malloc_stats)) { if (jr_ProgramName) { jr_esprintf (error_buf, "\n\n%s: After Undo of Everything", jr_ProgramName); } else { jr_esprintf (error_buf, "\n\nAfter Undo of Everything"); } jr_malloc_stats (stderr, error_buf); } if (jr_do_trace (jr_malloc_calls)) { status = jr_malloc_check_leaks_and_bounds (error_buf); if (status != 0) { if (jr_ProgramName) { fprintf (stderr, "%s: jr_malloc() error: %s\n", jr_ProgramName, error_buf); } else { fprintf (stderr, "jr_malloc() error: %s\n", error_buf); } if (exit_status == 0) { exit_status = 1; } } jr_malloc_dump (); } exit (exit_status); } void jr_exit_set_program_name (const char *program_name) { jr_ProgramName = program_name; }
frankjas/libjr
libjr/syscalls/jr_chown.c
<reponame>frankjas/libjr<gh_stars>0 #include "ezport.h" #include <sys/types.h> #include <sys/stat.h> #include <errno.h> #include <string.h> #include <unistd.h> #include <pwd.h> #include <grp.h> #include "jr/syscalls.h" #include "jr/error.h" jr_int jr_FileNameSetOwner ( const char * path, const char * owner_name, const char * group_name, char * error_buf) { uid_t owner_uid; gid_t group_gid; jr_int status; struct passwd * passwd_ptr ; struct group * group_ptr; errno = 0; passwd_ptr = getpwnam(owner_name) ; if (passwd_ptr == 0) { if (errno == 0) { jr_esprintf (error_buf, "user '%.32s' not found", owner_name); } else { jr_esprintf (error_buf, "user '%.32s' not accessible: %s", owner_name, strerror (errno)); } return jr_ConvertErrno (errno); } else { owner_uid = passwd_ptr->pw_uid; } errno = 0; group_ptr = getgrnam (group_name); if (group_ptr == 0) { if (errno == 0) { jr_esprintf (error_buf, "group '%.32s' not found", group_name); } else { jr_esprintf (error_buf, "group '%.32s' not accessible: %s", group_name, strerror (errno)); } return jr_ConvertErrno (errno); } else { group_gid = group_ptr->gr_gid; } /* ** 5/31/08: lchown() doesn't follow symlinks, this is more appropriate for restoring ** backups, since we need to set ownership on the link file, if the link target already ** exists, we don't want to change its ownership, and if it doesn't we don't want ** an error and the restore will restore it with proper ownership. */ status = lchown (path, owner_uid, group_gid); if (status != 0) { jr_esprintf (error_buf, "%s", strerror (errno)); return jr_ConvertErrno (errno);; } return 0; } jr_int jr_IsChownAllowed() { return jr_IsRootUser(); }
frankjas/libjr
libjr/misc/crcsum.c
#include "ezport.h" #include "jr/misc.h" /* An array useful for CRC calculations that use 0x1021 as the "seed" */ /* taken originally from the "mcvert" program */ unsigned short jr_MacBinarySeedArrayCRC[] = { 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7, 0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef, 0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6, 0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de, 0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485, 0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d, 0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4, 0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc, 0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823, 0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b, 0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12, 0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a, 0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41, 0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49, 0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70, 0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78, 0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f, 0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067, 0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e, 0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256, 0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d, 0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, 0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c, 0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634, 0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab, 0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3, 0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a, 0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92, 0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9, 0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1, 0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8, 0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0 }; /* * calc_crc() -- * Compute the MacBinary II-style CRC for the data pointed to by p, with the * crc seeded to seed. * * Modified by <NAME> to use the jr_MacBinarySeedArrayCRC array for efficiency. * code taken from mcvert application, added to support MacBinary conversion */ unsigned long jr_CRC_seeded_chksum(p, len, seed) unsigned char * p; jr_int len; short seed; { unsigned long result ; short hold; /* crc computed so far */ jr_int i; /* index into data */ hold = seed; /* start with seed */ for (i = 0; i < len; i++, p++) { hold ^= (*p << 8); hold = (hold << 8) ^ jr_MacBinarySeedArrayCRC[(unsigned char) (hold >> 8)]; } result = hold ; return(result) ; } unsigned long jr_CRC_chksum(byte_string_arg, length) void * byte_string_arg ; jr_int length ; { unsigned long result ; result = jr_CRC_seeded_chksum(byte_string_arg, length, 0) ; return(result) ; }
frankjas/libjr
libjr/symtab/project.h
#ifndef _stable_localh #define _stable_localh #define _POSIX_SOURCE 1 #include "ezport.h" #include <stdio.h> #include <string.h> #include <assert.h> #include "jr/malloc.h" #include "jr/misc.h" #include "jr/string.h" #include "jr/symtab.h" /******** jr_ST_TypeStructs, jr_ST_Symbols, and jr_ST_Identifiers ********/ extern jr_ST_Identifier * jr_ST_IdentifierCreate PROTO (( char * str )); extern void jr_ST_IdentifierInit PROTO (( jr_ST_Identifier * id_ptr, const char * str )); extern void jr_ST_IdentifierDestroy PROTO (( jr_ST_Identifier * id_ptr )); extern void jr_ST_IdentifierUndo PROTO (( jr_ST_Identifier * id_ptr )); extern jr_int jr_ST_IdentifierHash PROTO (( const void * void_arg_1 )); extern jr_int jr_ST_IdentifierCmp PROTO (( const void * void_arg_1, const void * void_arg_2 )); #define jr_ST_IdentifierSymbol(id) ((jr_ST_Symbol *)(id)->symbol) #define jr_ST_IdentifierSetSymbol(id, v) ((id)->symbol = (v)) #define jr_ST_IdentifierIsInUse(id) ((id)->num_refs > 0) #define jr_ST_IdentifierNumRefs(id) ((id)->num_refs) #define jr_ST_IdentifierIncrementRefs(id) ((id)->num_refs++) #define jr_ST_IdentifierDecrementRefs(id) ((id)->num_refs--) #define jr_ST_TypeIsInUse(type) ((type)->num_refs > 0) #define jr_ST_TypeNumRefs(type) ((type)->num_refs) #define jr_ST_TypeIncrementRefs(type) ((type)->num_refs++) #define jr_ST_TypeDecrementRefs(type) ((type)->num_refs--) extern void jr_ST_ArrayListDestroyLengthStrings PROTO ((jr_AList *list)); /******** jr_ST_TypeStruct Functions ********/ extern jr_int jr_ST_TypeHash PROTO (( const void * void_arg_1 )); extern void jr_ST_TypeInitForLookup PROTO (( jr_ST_TypeStruct * new_type, jr_int type_kind, jr_ST_Symbol * base_sym, jr_int num_stars, jr_AList * list )); extern void jr_ST_TypeUndoForLookup PROTO (( jr_ST_TypeStruct * type )); extern void jr_ST_TypeLookupInitDuplicate PROTO (( jr_ST_TypeStruct * new_type, jr_ST_SymbolTable * symbol_table )); /******** Scopes and jr_ST_Symbol Table ********/ extern jr_ST_Symbol * jr_ST_SymbolAllocate PROTO (( jr_ST_ScopeHeader * scope_header, jr_ST_Identifier * id )); extern jr_ST_Identifier * jr_ST_EnterIdentifier PROTO (( jr_ST_SymbolTable * symbol_table, const char * str )); extern jr_ST_TypeStruct * jr_ST_EnterType PROTO (( jr_ST_SymbolTable * symbol_table, jr_int type_kind, jr_ST_Symbol * base_sym, jr_int num_stars, jr_AList * list )); extern void jr_ST_UnreferenceType PROTO (( jr_ST_SymbolTable * symbol_table, jr_ST_TypeStruct * type_ptr )); extern void jr_ST_UnreferenceIdentifier PROTO (( jr_ST_SymbolTable * symbol_table, jr_ST_Identifier * id_ptr )); /******** Duplicate String Table (for file names) ********/ typedef struct { char * string; jr_int num_references; } jr_ST_StringType; extern char * jr_ST_GetUniqueString PROTO (( jr_ST_SymbolTable * stable, char * string )); extern void jr_ST_StringInit PROTO (( jr_ST_StringType * string_info, char * string )); extern void jr_ST_StringUndo PROTO (( jr_ST_StringType * string_info )); extern jr_int jr_ST_StringHash PROTO (( const void * void_arg_1 )); extern jr_int jr_ST_StringCmp PROTO (( const void * void_arg_1, const void * void_arg_2 )); extern void jr_ST_StringInitForLookUp PROTO (( jr_ST_StringType * string_info, char * string )); #define jr_ST_StringUndoForLookUp(si) ((void) (si)) #define jr_ST_StringValue(string_info) ((string_info)->string) #endif
frankjas/libjr
libjr/syscalls/jr_chmod.c
<reponame>frankjas/libjr<gh_stars>0 #include "ezport.h" #include <sys/types.h> #include <sys/stat.h> #include <errno.h> #include <string.h> #include "jr/syscalls.h" #include "jr/error.h" jr_int jr_FileNameSetPerms ( const char * path, jr_int perm_flags, char * error_buf) { jr_int status; status = chmod (path, jr_PermsToUnixMode (perm_flags)); if (status != 0) { jr_esprintf (error_buf, "%s", strerror (errno)); return jr_ConvertErrno (errno);; } return 0; } jr_int jr_FileNameGetPerms ( const char * path, char * error_buf) { struct stat stat_info[1]; jr_int perm_flags; jr_int status; status = stat (path, stat_info); if (status != 0) { jr_esprintf (error_buf, "%s", strerror (errno)); return jr_ConvertErrno (errno);; } perm_flags = jr_UnixModeToPerms (stat_info->st_mode); return perm_flags; }
frankjas/libjr
libjr/misc/heapbase.c
#include "ezport.h" #ifdef ostype_winnt #include <malloc.h> #endif #include "jr/misc.h" /* ** 6-8-2011: Used by jr_malloc() diagnostics to compare pointers ** from different runs of a program. */ #ifdef ostype_winnt void *jr_heap_base() { return (void *) _get_heap_handle(); } #else void *jr_heap_base() { return 0; } #endif
frankjas/libjr
include/jr/time.h
#ifndef _timeh #define _timeh #include "ezport.h" #include "jr/long.h" /* ** 7/31/06: Provide a portable time interface ** Define a jr_time_t to be an integer type of some kind, i.e. can be passed by value, ** compared to other integer types. */ typedef jr_int jr_seconds_t; /* 2/20/07: seconds since 1/1/70 */ typedef jr_ULong jr_useconds_t; /* 2/20/07: microseconds since 1/1/70 */ #define jr_SECONDS_MAX jr_INT_MAX typedef struct { jr_int second; jr_int minute; jr_int hour; jr_int month_day; jr_int month; jr_int year; jr_int week_day; jr_int year_day; jr_int gmt_off; unsigned is_dst : 1; unsigned is_gmt : 1; } jr_TimeStruct; #define jr_TIME_MAX jr_INT_MAX #define jr_CTIME_STRING_LENGTH 32 /* ** According to docs, should be at least 25 bytes. */ extern jr_seconds_t jr_time_seconds (void); extern jr_useconds_t jr_time_useconds (void); extern jr_int jr_time_gmt_offset(); extern unsigned jr_int jr_useconds_to_seconds ( jr_useconds_t useconds); extern jr_useconds_t jr_seconds_to_useconds( jr_seconds_t seconds); #define jr_useconds_diff( ulong_ptr, t1, t2 ) \ jr_ULongSubtract( ulong_ptr, t1, t2 ) extern char * jr_ctime ( jr_seconds_t curr_time_seconds, char * buf); /* ** 4/11/09: no trailing newline */ extern void jr_TimeInit ( jr_TimeStruct * time_ptr, jr_seconds_t time_seconds); extern jr_int jr_TimeInitFromString ( jr_TimeStruct * time_ptr, const char * time_string, char * error_buf); #define jr_TIME_STRING_LENGTH 32 /* ** 7/31/06: understands RFC 822 as updated by 1123 (i.e. w/2 digit day) ** Sun, 06 Nov 1994 08:49:37 GMT */ extern char * jr_TimeToString ( jr_TimeStruct * time_ptr, char * string, jr_int max_length); extern jr_int jr_TimeToSecondsUTC ( jr_TimeStruct * time_ptr); #define jr_SECONDS_PER_DAY (60 * 60 * 24) #define jr_SECONDS_PER_YEAR (jr_SECONDS_PER_DAY * 365) extern void jr_useconds_init ( jr_useconds_t * interval_ptr, unsigned jr_int seconds, unsigned jr_int useconds); extern void jr_useconds_subtract( jr_useconds_t * dest_ref, jr_useconds_t v1, jr_useconds_t v2); #define jr_useconds_asgn( dest_ref, src ) \ jr_ULongAsgn( dest_ref, src ) #define jr_useconds_add( dest_ref, v1, v2 ) \ jr_ULongAdd( dest_ref, v1, v2 ) #define jr_useconds_is_zero( value ) \ jr_ULongIsZero( value ) #define jr_useconds_cmp( v1, v2 ) \ jr_ULongCmp( v1, v2 ) #define jr_useconds_to_64(interval_ptr) \ jr_ULongToHost64 (*(interval_ptr)) #endif
frankjas/libjr
libjr/missing/sigprocmask.c
<filename>libjr/missing/sigprocmask.c<gh_stars>0 #define _POSIX_SOURCE 1 #include "ezport.h" #ifdef missing_sigaction_objects #include <stdio.h> #include <errno.h> #include <sys/types.h> #include <unistd.h> #include <signal.h> int sigprocmask (how, set, oldset) int how ; const sigset_t * set ; sigset_t * oldset ; { int prev_mask ; int new_mask ; prev_mask = sigblock(0) ; if (set != NULL) { switch(how) { case SIG_BLOCK : { new_mask = *set; sigblock (new_mask); break; } case SIG_UNBLOCK : { new_mask = prev_mask & ~(*set); sigsetmask (new_mask); break; } case SIG_SETMASK : { new_mask = *set; sigsetmask (new_mask); break; } default : { errno = EINVAL; return (-1); } } } if (oldset != NULL) { *oldset = prev_mask; } return(0) ; } #else static void NotCalled () /* define this so ranlib doesn't complain */ { NotCalled (); /* use it so the compiler doesn't complain */ } #endif /* void onintr(signum) jr_int signum ; { fprintf(stderr, "Interrupted with signal number %d\n", signum) ; fprintf(stderr, "Enter a return or try to kill this handler with SIGQUIT: ") ; getchar() ; fprintf(stderr, "Returning from handler now.\n") ; } main(argc, argv) jr_int argc ; char ** argv ; { sigset_t new_mask ; sigset_t old_mask ; jr_int c ; sigemptyset(&new_mask) ; sigaddset(&new_mask, SIGINT) ; sigprocmask(SIG_SETMASK, &new_mask, 0) ; sigemptyset(&new_mask) ; sigaddset(&new_mask, SIGQUIT) ; sigprocmask(SIG_BLOCK, &new_mask, &old_mask) ; fprintf(stderr,"old_mask == %#010x\n", old_mask) ; fprintf(stderr,"Signals which are blocked (masked), may not be delivered.\n") ; fprintf(stderr,"If they are generated while they are blocked, then they\n") ; fprintf(stderr,"stay 'pending' until they are unblocked.\n") ; fprintf(stderr,"A feature of the terminal driver is to empty input\n") ; fprintf(stderr,"buffers when keyboard interrupts are generated.\n") ; fprintf(stderr,"Enter text or interrupt (interrupts are blocked): ") ; while ((c = getchar()) != EOF) { putchar(c) ; if (c == '\n') { sigset_t empty ; sigemptyset(&empty) ; sigprocmask(SIG_SETMASK, &empty, 0) ; fprintf(stderr,"Enter text or interrupt (interrupts are deliverable): ") ; } } exit(0) ; } */
frankjas/libjr
libjr/dlist/dlistdel.c
#include "project.h" void *jr_DListExtractElement (list, el) jr_DList * list; const void * el; { void * next = jr_DListNextElementPtr (list, el); void * prev = jr_DListPrevElementPtr (list, el); if (next) { jr_DListPrevElementPtr (list, next) = prev; } else if (jr_DListTailPtr (list) == el) { jr_DListTailPtr(list) = prev; } /* ** 8/15/2005: else it wasn't on this list, extra check ** lets us delete an null element without effect. */ if (prev) { jr_DListNextElementPtr (list, prev) = next; } else if (jr_DListHeadPtr (list) == el) { jr_DListHeadPtr(list) = next; } /* ** 8/15/2005: else it wasn't on this list, extra check ** lets us delete an null element without effect. */ jr_DListMakeNullElement (list, el); /* * so prefix transformations on this element don't affect anything */ return (void *) el; } void jr_DListDeleteElement (list, el) jr_DList * list; void * el; { jr_DListExtractElement (list, el); if (jr_DListAllocatesElements (list)) { jr_DListFreeElement (list, el); } }
frankjas/libjr
libjr/missing/backtrace.c
<reponame>frankjas/libjr #define _POSIX_SOURCE 1 #include "ezport.h" /* * 3/31/2005: This is untested code. It doesn't work on ppc */ #if defined (missing_backtrace) && !defined (cpu_ppc) /* * 3/31/2005: the power pc has a non-standard stack. It grows larger * and doesn't contain the return address. */ int backtrace (pc_array, pc_array_size) void ** pc_array; int pc_array_size; { void * dummy_array[1]; /* 3/31/2005: must be 1st local var */ void ** curr_frame_ptr; void * curr_pc; jr_int trace_size = 0; jr_int q; /* * 3/31/2005: A deliberate array overflow, * * dummy_array[1] == stack pointer * dummy_array[2] == return address * * ==> &dummy_array[1] is the beginning of a 2 element void * array. */ curr_frame_ptr = &dummy_array[1]; for (q=0; q < pc_array_size; q++) { curr_pc = curr_frame_ptr[1]; if (curr_pc == 0) { break; } pc_array[q] = curr_pc; curr_frame_ptr = curr_frame_ptr[0]; } return trace_size; } #else static void NotCalled () /* define this so ranlib doesn't complain */ { NotCalled (); /* use it so the compiler doesn't complain */ } #endif
frankjas/libjr
libjr/missing/sigset.c
#define _POSIX_SOURCE 1 #include "ezport.h" #include <signal.h> #include <errno.h> #ifdef missing_sigset_objects int sigaddset(set, signo) sigset_t * set ; int signo ; { int mask = sigmask(signo) ; if ((signo <= 0) || (signo > 31)) { errno = EINVAL ; return(-1) ; } *set |= mask ; return(0) ; } int sigdelset(set, signo) sigset_t * set ; int signo ; { int mask = sigmask(signo) ; if ((signo <= 0) || (signo > 31)) { errno = EINVAL ; return(-1) ; } *set &= ~ mask ; return(0) ; } int sigemptyset(set) sigset_t * set ; { *set = 0 ; return(0) ; } int sigfillset(set) sigset_t * set ; { *set = 0xffffffff ; return(0) ; } int sigismember(set, signo) const sigset_t * set ; int signo ; { int mask = sigmask(signo) ; if ((signo <= 0) || (signo > 31)) { errno = EINVAL ; return(-1) ; } return(*set & mask) ; } #else static void NotCalled () /* define this so ranlib doesn't complain */ { NotCalled (); /* use it so the compiler doesn't complain */ } #endif
frankjas/libjr
libjr/syscalls/critical.c
#define _POSIX_SOURCE 1 #include "ezport.h" #include <string.h> #include <signal.h> #include "jr/syscalls.h" # ifndef ostype_winnt void jr_critical_section (how, opt_void_old_mask_ptr) char * how; void * opt_void_old_mask_ptr; { sigset_t * old_mask_ptr = opt_void_old_mask_ptr; sigset_t new_mask; sigemptyset (&new_mask); sigaddset (&new_mask, SIGHUP); /* terminal gets hung up */ sigaddset (&new_mask, SIGINT); /* cntrl-C */ sigaddset (&new_mask, SIGQUIT); /* cntrl-backslash */ sigaddset (&new_mask, SIGALRM); /* software alarm */ sigaddset (&new_mask, SIGTERM); /* software kill */ sigaddset (&new_mask, SIGTSTP); /* cntrl-Z */ if (strcmp (how, "begin") == 0) { sigprocmask (SIG_BLOCK, &new_mask, old_mask_ptr); } if (strcmp (how, "end") == 0) { sigprocmask (SIG_SETMASK, old_mask_ptr, 0); } } #endif
frankjas/libjr
libjr/misc/esis_lib.c
<filename>libjr/misc/esis_lib.c #include "esis_prj.h" char *jr_ESIS_ReadWordWithIsLast (rfp, char_list, is_last_ptr) FILE * rfp; jr_AList * char_list; jr_int * is_last_ptr; { jr_int c; jr_AListEmpty (char_list); while ((c = jr_ESIS_getc (rfp)) != EOF) { if (c == '\n' || c == ' ') { break; } if (c == jr_ESIS_EMBEDDED_NEWLINE) { c = '\n'; } jr_AListNativeSetNewTail (char_list, c, char); } jr_AListNativeSetNewTail (char_list, 0, char); if (is_last_ptr) { if (c == '\n') { *is_last_ptr = 1; } else { *is_last_ptr = 0; } } return jr_AListHeadPtr (char_list); } char *jr_ESIS_SaveWordWithIsLast (rfp, char_list, is_last_ptr) FILE * rfp; jr_AList * char_list; jr_int * is_last_ptr; { char * new_word; new_word = jr_strdup (jr_ESIS_ReadWordWithIsLast (rfp, char_list, is_last_ptr)); return new_word; } char *jr_ESIS_ReadData (rfp, char_list) FILE * rfp; jr_AList * char_list; { jr_int c; jr_AListEmpty (char_list); while ((c = jr_ESIS_getc (rfp)) != EOF) { if (c == '\n') { break; } if (c == jr_ESIS_EMBEDDED_NEWLINE) { c = '\n'; } jr_AListNativeSetNewTail (char_list, c, char); } jr_AListNativeSetNewTail (char_list, 0, char); return jr_AListHeadPtr (char_list); } char *jr_ESIS_SaveData (rfp, char_list) FILE * rfp; jr_AList * char_list; { char * new_word; new_word = jr_strdup (jr_ESIS_ReadData (rfp, char_list)); return new_word; } jr_int jr_ESIS_getc (rfp) FILE * rfp; { jr_int c; c = getc (rfp); if (c != '\\') { return c; } c = getc (rfp); switch (c) { case EOF : { return '\\'; } case '\\' : { return '\\'; } case '|' : { return jr_ESIS_SDATA_BRACKET_CHAR; } case 'n' : { return jr_ESIS_EMBEDDED_NEWLINE; } case '#' : case '%' : { /* * Number in decimal */ jr_int n = 0; while ((c = getc (rfp)) != EOF) { if (c >= '0' && c <= '7') { n = 10*n + c - '0'; } else { ungetc (c, rfp); break; } } return n; } default : { if (isdigit (c)) { /* * number in octal */ jr_int n = c - '0'; while ((c = getc (rfp)) != EOF) { if (c >= '0' && c <= '7') { n = 8*n + c - '0'; } else { ungetc (c, rfp); break; } } return n; } ungetc (c, rfp); return '\\'; } } return EOF; } jr_int jr_ESIS_putc (c, wfp) jr_int c; FILE * wfp; { switch (c) { case '\\' : { putc ('\\', wfp); putc ('\\', wfp); return c; } case '\n' : { putc ('\\', wfp); putc ('n', wfp); return c; } } if (isprint (c) && (!isspace (c) || c == ' ')) { putc (c, wfp); return c; } fprintf (wfp, "\\%o", c); return c; }
frankjas/libjr
libjr/alist/alist.c
#include "project.h" jr_AList *jr_AListCreate (objsize) jr_int objsize ; { jr_AList *list = (jr_AList *) jr_malloc (sizeof (jr_AList)); jr_AListInit (list, objsize); return (list); } void jr_AListInit (list, objsize) jr_AList * list; jr_int objsize; { list->buffer = 0; list->buffer_capacity = 0; list->free_ptr = 0; list->free_index = 0; list->objsize = objsize; list->prefix_size = 0; } void jr_AListDestroy (list) jr_AList *list; { jr_AListUndo (list); jr_free (list); } void jr_AListUndo (list) jr_AList *list; { if ( jr_AListHasPrefixTransformFn (list) && jr_AListPrefixTransformFn (list) == (void (*)()) jr_PrefixArrayTransformElement) { jr_PrefixArrayDestroy (jr_AListPrefixTransformArg (list)); } if (list->buffer) { if (jr_AListPrefixSize (list) > 0) { jr_free (list->buffer - sizeof (jr_AListPrefixTransformStruct)); } else { jr_free (list->buffer); } } } void jr_AListEmpty (list) jr_AList *list; { list->free_ptr = list->buffer; list->free_index = 0; } void *jr_AListExtractBuffer (list) jr_AList *list; { void * tptr; if (jr_AListPrefixSize (list) > 0) { void * new_buffer; jr_int num_bytes = list->free_ptr - list->buffer; new_buffer = jr_malloc (num_bytes); memcpy (new_buffer, list->buffer, num_bytes); jr_free (list->buffer - sizeof (jr_AListPrefixTransformStruct)); tptr = new_buffer; } else { tptr = list->buffer; } list->buffer = 0; list->buffer_capacity = 0; list->free_ptr = 0; list->free_index = 0; return tptr; } void jr_AListSetPrefixSize (list, new_prefix_size, prefix_transform_fn, prefix_transform_arg) jr_AList * list; jr_int new_prefix_size; void (*prefix_transform_fn) (); void * prefix_transform_arg; { jr_int malloced_num_bytes = 0; char * malloced_ptr = 0; /* * Add an extra 8 byte struct to the beginning of the list buffer. * This will store the transform function pointer and arg. * If the buffer isn't allocated, and the transform function pointer * is 0, then don't allocate a buffer yet. * * The other code will need to take into account the fact that * the transform function macro can only be used if prefix size > 0 * and the buffer is non-zero. */ assert (jr_AListIsEmpty (list)); if (list->buffer) { malloced_num_bytes = list->buffer_capacity * list->objsize; malloced_ptr = list->buffer; if (list->prefix_size > 0) { malloced_num_bytes += sizeof (jr_AListPrefixTransformStruct); malloced_ptr -= sizeof (jr_AListPrefixTransformStruct); } } if (list->prefix_size > 0) { list->objsize -= list->prefix_size; } if (new_prefix_size > 0) { list->objsize += new_prefix_size; list->prefix_size = new_prefix_size; if (malloced_ptr) { if (malloced_num_bytes < (jr_int) sizeof (jr_AListPrefixTransformStruct)) { jr_free (malloced_ptr); malloced_num_bytes = 0; malloced_ptr = 0; } } if (malloced_ptr == 0 && prefix_transform_fn) { malloced_num_bytes = sizeof (jr_AListPrefixTransformStruct); malloced_ptr = jr_malloc (malloced_num_bytes); } /* * Else we already have a malloc()ed buffer, or no transform function. */ if (malloced_ptr) { malloced_num_bytes -= sizeof (jr_AListPrefixTransformStruct); malloced_ptr += sizeof (jr_AListPrefixTransformStruct); } } if (malloced_ptr) { list->buffer = malloced_ptr; list->buffer_capacity = malloced_num_bytes / list->objsize; list->free_ptr = malloced_ptr; } if (new_prefix_size > 0 && malloced_ptr) { jr_AListPrefixTransformFn (list) = prefix_transform_fn; jr_AListPrefixTransformArg (list) = prefix_transform_arg; } if (list->prefix_size == list->objsize) { fprintf (stderr, "\n"); fprintf (stderr, "jr_AList: programmer error: prefix size == total data size\n"); fprintf (stderr, "jr_AList: foreach pointer loops will skip the last element\n"); jr_coredump (); } } jr_int jr_AListIncreaseCapacity (list, new_size) jr_AList * list; jr_int new_size; { jr_int newbytesize; jr_int free_offset; char * old_buffer_ptr; char * new_buffer_ptr; if (new_size <= list->buffer_capacity) { return (list->buffer_capacity) ; } if (list->buffer_capacity != 0 && new_size < 2 * list->buffer_capacity) { new_size = 2 * list->buffer_capacity; } free_offset = list->free_ptr - list->buffer; newbytesize = new_size * list->objsize; old_buffer_ptr = list->buffer; if (list->prefix_size > 0) { newbytesize += sizeof (jr_AListPrefixTransformStruct); if (old_buffer_ptr) { old_buffer_ptr -= sizeof (jr_AListPrefixTransformStruct); } } if (list->buffer != 0) { new_buffer_ptr = jr_realloc (old_buffer_ptr, newbytesize); } else { new_buffer_ptr = jr_malloc (newbytesize); } newbytesize = (jr_int) jr_malloc_usable_size (new_buffer_ptr, newbytesize) ; if (list->prefix_size > 0) { newbytesize -= sizeof (jr_AListPrefixTransformStruct); new_buffer_ptr += sizeof (jr_AListPrefixTransformStruct); if (old_buffer_ptr) { old_buffer_ptr += sizeof (jr_AListPrefixTransformStruct); } } list->buffer = new_buffer_ptr; list->buffer_capacity = newbytesize / list->objsize; list->free_ptr = new_buffer_ptr + free_offset; if (old_buffer_ptr == 0 && list->prefix_size > 0) { /* * Didn't allocate space for the transform info since * there were no transform functions. */ jr_AListPrefixTransformFn (list) = 0; jr_AListPrefixTransformArg (list) = 0; } if (jr_AListHasPrefixTransformFn (list)) { jr_AListTransformPrefixes ( list, old_buffer_ptr, jr_AListPrefixTransformFn (list), jr_AListPrefixTransformArg (list) ); } return list->buffer_capacity; } void *jr_AListBufferDup (list) jr_AList *list; { if (list->buffer) { void *tptr; tptr = jr_memdup (list->buffer, list->free_ptr - list->buffer); return (tptr); } else return (0); } void jr_AListSetTailIndex (list, index) jr_AList *list; jr_int index; { if (index < -1) return; if (index > jr_AListTailIndex (list)) { jr_AListIncreaseCapacity (list, index + 1); } list->free_ptr = jr_AListElementPtr (list, index + 1); list->free_index = index + 1; } void jr_AListInitCopy (dest, src) jr_AList *dest; jr_AList *src; { jr_AListInit (dest, src->objsize); if (jr_AListPrefixSize (src)) { if (jr_AListHasPrefixTransformFn (src)) { jr_AListSetPrefixSize ( dest, src->prefix_size, jr_AListPrefixTransformFn (src), jr_AListPrefixTransformArg (src) ); } else { jr_AListSetPrefixSize (dest, src->prefix_size, 0, 0); } } jr_AListSetSize (dest, jr_AListSize (src)); memcpy (dest->buffer, src->buffer, src->free_index * src->objsize); if (jr_AListHasPrefixTransformFn (dest)) { jr_AListTransformPrefixes ( dest, src->buffer, jr_AListPrefixTransformFn (dest), jr_AListPrefixTransformArg (dest) ); } } jr_AList *jr_AListDup (list) jr_AList *list; { jr_AList *new_list = jr_malloc (sizeof (jr_AList)); jr_AListInitCopy (list, new_list); return (new_list); } static void *_jr_AListElementPtr (alist, i) jr_AList * alist; jr_int i; { if (0) { _jr_AListElementPtr (alist, i); } return jr_AListElementPtr (alist, i); } void jr_AListReverse (list) jr_AList * list; { jr_int old_index; jr_int new_index; void * old_ptr; void * new_ptr; void * tmp_ptr = jr_malloc (jr_AListElementSize (list)); jr_AListForEachElementIndex (list, old_index) { if (old_index >= jr_AListSize (list) / 2) { break; } new_index = jr_AListSize (list) - old_index - 1; old_ptr = jr_AListElementPtr (list, old_index); new_ptr = jr_AListElementPtr (list, new_index); memcpy (tmp_ptr, new_ptr, jr_AListElementSize (list)); memcpy (new_ptr, old_ptr, jr_AListElementSize (list)); memcpy (old_ptr, tmp_ptr, jr_AListElementSize (list)); } jr_free (tmp_ptr); } void **jr_AListVectorPtr (list) jr_AList * list; { void * ptr; if (jr_AListSize (list) > 0) { ptr = jr_AListNativeTail (list, void *); if (ptr == 0) { return jr_AListHeadPtr (list); } } /* * 7/15/2005: Either it's empty or has no null. * Don't increase the size of the array but add a null. */ jr_AListIncreaseCapacity (list, jr_AListSize (list) + 1); jr_AListNativeSetElement (list, jr_AListSize (list), 0, void *); return jr_AListHeadPtr (list); } void jr_AListAppendString( jr_AList * char_list, const char * string) { for (; *string; string++) { jr_AListNativeSetNewTail( char_list, *string, char); } jr_AListNativeSetNewTail( char_list, 0, char); }
frankjas/libjr
include/jr/login.h
<gh_stars>0 #ifndef __JR_LOGIN_H__ #define __JR_LOGIN_H__ #include "ezport.h" typedef struct { jr_int total_number_of_users ; /* total number of user's logged in */ jr_int number_of_logins ; /* number of times this user was logged in on different ttys */ char * user_name ; /* a jr_strduped string copied from the arg to Init */ char * tty_name ; /* a jr_strduped string filled only if user on matching tty */ } jr_LoginInfoType ; extern jr_LoginInfoType * jr_LoginInfoCreate PROTO(( const char * user_name_arg, const char * tty_name_arg, char * errbuf )) ; extern void jr_LoginInfoDestroy PROTO((jr_LoginInfoType * login_info_ptr)) ; extern jr_int jr_LoginInfoInit PROTO(( jr_LoginInfoType * login_info_ptr, const char * user_name_arg, const char * tty_name_arg, char * errbuf )) ; extern void jr_LoginInfoUndo PROTO((jr_LoginInfoType * login_info_ptr)) ; extern struct passwd * jr_GetPasswdAndUserName PROTO((char *namebuf)) ; #endif
frankjas/libjr
include/jr/ezport/ansi.h
#ifndef __EZPORT_ANSI_H__ #define __EZPORT_ANSI_H__ /* * The ANSI standard specifies that there should be a #define for * the constant __STDC__ if you are using an ANSI compiler. * * 3/9/07: some compilers don't define __STDC__ even if the support * ANSI constructs when they also add other non-ANSI constructs. * So use the constant "compiler_has_ansi_support" instead, * which is now true for all compilers. */ #define compiler_has_ansi_support #define PROTO(args) args /* ** 1/23/07: PROTO is needed for old-style JR header files */ #if 0 /* ** 1/23/07: Obsolete, non-ANSI compilers don't exist any longer */ # define PROTO(args) () # ifdef _change_void_to_char # ifndef void # define void char # endif # endif # ifndef const # define const /* const not supported in old C */ # endif /* * If we are not using an ANSI compiler and we have not * specified any defines for "void" then replace every * occurence of the word "void" with the word "char". * This will have the effect of changing references * to (void *) type into (char *) type. * This will result in some type mismatch warnings, * but all code should still be semantically equivalent. */ #endif #endif
frankjas/libjr
libjr/syscalls/move.c
#define _POSIX_SOURCE 1 #include "ezport.h" #include <errno.h> #include <string.h> #include <unistd.h> #include "jr/syscalls.h" #include "jr/error.h" #include "jr/string.h" #include "jr/malloc.h" jr_int jr_MoveFileName (old_file_path, new_file_path, error_buf) const char * old_file_path; const char * new_file_path; char * error_buf; { FILE * rfp = 0; FILE * wfp = 0; jr_int c; jr_int status; status = jr_MovePath (old_file_path, new_file_path, error_buf); if (status == 0) { goto return_status; } else if (errno == EXDEV) { /* ** 11/26/05: the paths are on different devices, use a copy instead */ } else { jr_esprintf (error_buf, "%s", strerror (errno)); status = jr_ConvertErrno (errno); goto return_status; } rfp = fopen (old_file_path, "r"); if (rfp == NULL) { jr_esprintf (error_buf, "couldn't open '%s' for reading: %s", old_file_path, strerror (errno) ); status = jr_ConvertErrno (errno); goto return_status; } wfp = fopen (new_file_path, "w"); if (wfp == NULL) { jr_esprintf (error_buf, "couldn't open '%s' for writing: %s", new_file_path, strerror (errno) ); status = jr_ConvertErrno (errno); goto return_status; } while ((c = getc (rfp)) != EOF) { putc (c, wfp); } fclose (rfp); fclose (wfp); rfp = 0; wfp = 0; jr_Unlink ((char *) old_file_path, 0); status = 0; return_status : { if (rfp) { fclose (rfp); } if (wfp) { fclose (wfp); } } return status; } jr_int jr_MovePath ( const char * old_path_name, const char * new_path_name, char * error_buf) { char * new_dest_path = 0; jr_int status; status = jr_PathIsDirectory (new_path_name, error_buf); if (status < 0) { if (status != jr_NOT_FOUND_ERROR && status != jr_PERMISSION_ERROR) { jr_esprintf (error_buf, "couldn't check '%.64s': %s", new_path_name, error_buf); goto return_status; } } else if (status) { const char * path_tail = jr_PathTail (old_path_name); jr_int new_length = strlen (new_path_name); new_dest_path = jr_malloc (new_length + 1 + strlen (path_tail) + 1); if (new_path_name[new_length - 1] == '/') { sprintf (new_dest_path, "%s%s", new_path_name, path_tail); } else { sprintf (new_dest_path, "%s/%s", new_path_name, path_tail); } new_path_name = new_dest_path; } status = rename (old_path_name, new_path_name); if (status != 0) { jr_esprintf (error_buf, "%s", strerror (errno)); status = jr_ConvertErrno (errno); goto return_status; /* ** 4/17/07: Needs to set errno, is used by jr_MoveFileName() */ } status = 0; return_status : { if (new_dest_path) { jr_free (new_dest_path); } } return status; }
frankjas/libjr
libjr/string/jr_regex.c
#define _POSIX_SOURCE 1 #include "ezport.h" #include <stdlib.h> #include <sys/types.h> #include <regex.h> #include "jr/string.h" #include "jr/alist.h" #include "jr/malloc.h" #include "jr/error.h" jr_int jr_RegExMatch ( const char * source_string, const char * pattern_string, jr_int flags, char * error_buf) { regex_t regex_info[1]; jr_int undo_regex_info = 0; jr_int reg_flags = 0; jr_int num_sub_pats = 1; regmatch_t sub_pat_array[1]; jr_int status; if (flags & jr_REGEX_POSIX_EXTENDED_FLAG) { reg_flags |= REG_EXTENDED; } if (flags & jr_REGEX_IGNORE_CASE_FLAG) { reg_flags |= REG_ICASE; } status = regcomp (regex_info, pattern_string, reg_flags); if (status != 0) { jr_esprintf (error_buf, "bad pattern: %s", jr_regex_strerror (status)); status = jr_MISUSE_ERROR; goto return_status; } undo_regex_info = 1; /* ** 2-8-2011: regexec() find matches starting anywhere */ status = regexec (regex_info, source_string, num_sub_pats, sub_pat_array, 0); if (status != 0) { if (status == REG_NOMATCH) { status = 0; } else { status = jr_INTERNAL_ERROR; } jr_esprintf (error_buf, "%s", jr_regex_strerror (status)); goto return_status; } else if (sub_pat_array[0].rm_so != 0) { /* ** 2-8-2011: need to match the beginning of the string. */ status = 0; } else { status = 1; } return_status : { if (undo_regex_info) { regfree (regex_info); } } return status; } const char *jr_RegExSub ( const char * source_string, const char * pattern_string, const char * replace_string, jr_int flags, char * error_buf) { const char * result_string = 0; regex_t regex_info[1]; jr_int undo_regex_info = 0; jr_int reg_flags = 0; jr_int num_sub_pats; regmatch_t * sub_pat_array = 0; jr_int q; jr_int k; jr_int pat_index; jr_int status; jr_AList result_list[1]; jr_AListInit (result_list, sizeof (char)); num_sub_pats = 1 + jr_CountAllOfChar (pattern_string, '\\'); sub_pat_array = jr_malloc (num_sub_pats * sizeof (regmatch_t)); /* * 6/29/2005: num_sub_pats will have twice the number of sub-patterns as \(xx\) pairs */ if (flags & jr_REGEX_POSIX_EXTENDED_FLAG) { reg_flags |= REG_EXTENDED; } if (flags & jr_REGEX_IGNORE_CASE_FLAG) { reg_flags |= REG_ICASE; } status = regcomp (regex_info, pattern_string, reg_flags); if (status != 0) { jr_esprintf (error_buf, "bad pattern: %s", jr_regex_strerror (status)); goto return_result; } undo_regex_info = 1; while (1) { status = regexec (regex_info, source_string, num_sub_pats, sub_pat_array, 0); if (status != 0) { for (q = 0; source_string[q]; q++) { jr_AListNativeSetNewTail (result_list, source_string[q], char); } break; } # if 0 for (q=0; q < num_sub_pats; q++) { if (sub_pat_array[q].rm_so >= 0) { printf ("%d: [%d, %d]\n", q, sub_pat_array[q].rm_so, sub_pat_array[q].rm_eo); } } # endif /* * 6/29/2005: Sub-pat 0 is the whole match, 1 is the first \(xx\), 2 is the second, etc. */ for (q=0; q < sub_pat_array[0].rm_so; q++) { jr_AListNativeSetNewTail (result_list, source_string[q], char); } for (q=0; replace_string[q]; q++) { if (replace_string[q] == '\\') { if (isdigit (replace_string[q+1])) { pat_index = atoi (&replace_string[q+1]); for (q++; replace_string[q]; q++) { if (!isdigit (replace_string[q])) { break; } } q--; if (pat_index < num_sub_pats && sub_pat_array[pat_index].rm_so >= 0) { for ( k = sub_pat_array[pat_index].rm_so; k < sub_pat_array[pat_index].rm_eo; k++) { jr_AListNativeSetNewTail (result_list, source_string[k], char); } } } } else { jr_AListNativeSetNewTail (result_list, replace_string[q], char); } } source_string += sub_pat_array[0].rm_eo; } jr_AListNativeSetNewTail (result_list, 0, char); result_string = jr_AListExtractBuffer (result_list); return_result : { jr_AListUndo (result_list); if (undo_regex_info) { regfree (regex_info); } if (sub_pat_array) { jr_free (sub_pat_array); } } return result_string; } const char *jr_regex_strerror ( jr_int reg_errno) { static char return_buf[64]; switch (reg_errno) { case REG_NOMATCH : return "didn't find a match"; /* for regexec() */ /* POSIX regcomp return error codes. (In the order listed in the standard.) */ case REG_BADPAT : return "invalid pattern"; case REG_ECOLLATE : return "not implemented"; case REG_ECTYPE : return "invalid character class name"; case REG_EESCAPE : return "trailing backslash"; case REG_ESUBREG : return "invalid back reference"; case REG_EBRACK : return "unmatched left bracket"; case REG_EPAREN : return "parenthesis imbalance"; case REG_EBRACE : return "unmatched \\{"; case REG_BADBR : return "invalid contents of \\{\\}"; case REG_ERANGE : return "invalid range end"; case REG_ESPACE : return "ran out of memory"; case REG_BADRPT : return "io preceding re for repetition op"; /* Error codes we've added */ case REG_EEND : return "Premature end"; case REG_ESIZE : return "Compiled pattern bigger than 2^16 bytes"; case REG_ERPAREN : return "Unmatched ) or \\); not returned from regcomp"; } snprintf (return_buf, sizeof (return_buf), "unknown error code %d", reg_errno); return return_buf; }
frankjas/libjr
libjr/symtab/st_init.c
<gh_stars>0 #include "project.h" jr_ST_SymbolTable *jr_ST_SymbolTableCreate (data_size, field_data_size) jr_int data_size; jr_int field_data_size; { jr_ST_SymbolTable * symbol_table; symbol_table = jr_malloc (sizeof (jr_ST_SymbolTable)); jr_ST_SymbolTableInit (symbol_table, data_size, field_data_size); return (symbol_table); } void jr_ST_SymbolTableInit (symbol_table, data_size, field_data_size) jr_ST_SymbolTable * symbol_table; jr_int data_size; jr_int field_data_size; { memset (symbol_table, 0, sizeof (jr_ST_SymbolTable)); jr_AVL_TreeInit (symbol_table->type_table, sizeof (jr_ST_TypeStruct), jr_ST_TypeCmp); jr_AVL_TreeInit (symbol_table->id_table, sizeof (jr_ST_Identifier), jr_ST_IdentifierCmp); jr_AListInit (symbol_table->scope_headers, sizeof(jr_ST_ScopeHeader)); jr_HTableInit ( symbol_table->string_table, sizeof (jr_ST_StringType), jr_ST_StringHash, jr_ST_StringCmp ); symbol_table->data_size = data_size; symbol_table->field_data_size = field_data_size; symbol_table->semantic_error = 0; symbol_table->fatal_error = 0; symbol_table->internal_error = 0; symbol_table->print_errors = 0; jr_ST_OpenNewScope (symbol_table); /* * open the keyword scope, scope 0 */ jr_ST_OpenNewScope (symbol_table); /* * open the jr_MatchPatternLikeCshal scope, scope 1 */ } void jr_ST_SymbolTableDestroy (symbol_table) jr_ST_SymbolTable * symbol_table; { jr_ST_SymbolTableUndo (symbol_table); jr_free (symbol_table); } void jr_ST_SymbolTableUndo (symbol_table) jr_ST_SymbolTable * symbol_table; { jr_ST_ScopeHeader * scope_header; jr_AVL_TreeTraverseInOrder (symbol_table->type_table, jr_ST_TypeUndo, 0); jr_AVL_TreeUndo (symbol_table->type_table); jr_AListForEachElementPtr (symbol_table->scope_headers, scope_header) { jr_LListUndo (scope_header->symbol_list); } jr_AListUndo (symbol_table->scope_headers); jr_AVL_TreeTraverseInOrder (symbol_table->id_table, jr_ST_IdentifierUndo, 0); jr_AVL_TreeUndo (symbol_table->id_table); { jr_ST_StringType * string_info; jr_HTableForEachElementPtr (symbol_table->string_table, string_info) { jr_ST_StringUndo (string_info); } } jr_HTableUndo (symbol_table->string_table); if (symbol_table->default_file_name) { jr_free (symbol_table->default_file_name); } } void jr_ST_OpenNewScope (symbol_table) jr_ST_SymbolTable * symbol_table; { jr_ST_ScopeHeader * scope_header; scope_header = jr_AListNewTailPtr (symbol_table->scope_headers); scope_header->scope_num = jr_AListTailIndex(symbol_table->scope_headers); jr_LListInit ( scope_header->symbol_list, symbol_table->data_size + sizeof (jr_ST_Symbol) ); } void jr_ST_CloseCurrScope (symbol_table) jr_ST_SymbolTable * symbol_table; { jr_ST_Symbol * curr_symbol; if (jr_ST_CurrScopeNum (symbol_table) == 0) return; /* * can't close the keyword scope */ jr_LListForEachElementPtr (jr_ST_CurrScopeList (symbol_table), curr_symbol) { if (curr_symbol->id) { /* * identifier could be 0 for un-named symbols */ jr_ST_IdentifierSetSymbol (curr_symbol->id, curr_symbol->prev_definition); jr_ST_UnreferenceIdentifier (symbol_table, curr_symbol->id); } if (curr_symbol->type) { jr_ST_UnreferenceType (symbol_table, curr_symbol->type); } } jr_LListUndo (jr_ST_CurrScopeHeader (symbol_table)->symbol_list); jr_AListDeletedTailPtr (symbol_table->scope_headers); } jr_ST_ScopeHeader *jr_ST_CloseCurrScopeAndSave (symbol_table) jr_ST_SymbolTable * symbol_table; { jr_ST_ScopeHeader * saved_scope; jr_ST_Symbol * curr_symbol; assert (jr_ST_CurrScopeNum (symbol_table) != 0); /* * can't save the keyword scope */ jr_LListForEachElementPtr (jr_ST_CurrScopeList (symbol_table), curr_symbol) { if (curr_symbol->id) { /* * identifier could be 0 for un-named symbols */ jr_ST_IdentifierSetSymbol (curr_symbol->id, curr_symbol->prev_definition); } } saved_scope = jr_memdup (jr_ST_CurrScopeHeader (symbol_table), sizeof (*saved_scope)); jr_AListDeletedTailPtr (symbol_table->scope_headers); /* * reclaim the space of this scope */ return (saved_scope); } jr_ST_Symbol *jr_ST_FindSymbol (symbol_table, str) jr_ST_SymbolTable * symbol_table; const char * str; { jr_ST_Identifier tmp_id[1]; jr_ST_Identifier * id_ptr; jr_ST_IdentifierInit (tmp_id, str); id_ptr = jr_AVL_TreeFindElementPtr (symbol_table->id_table, tmp_id); jr_ST_IdentifierUndo (tmp_id); if (id_ptr) { return jr_ST_IdentifierSymbol (id_ptr); } return 0; } jr_ST_Symbol *jr_ST_FindCompoundSymbolName (symbol_table, str, symbol_kind) jr_ST_SymbolTable * symbol_table; char * str; jr_int symbol_kind; { char buf[512]; switch (symbol_kind) { case jr_ST_STRUCT : sprintf (buf, "struct %.256s", str); str = buf; break; case jr_ST_UNION : sprintf (buf, "union %.256s", str); str = buf; break; case jr_ST_ENUM : sprintf (buf, "enum %.256s", str); str = buf; break; case jr_ST_PRE_PROCESSOR_DEFINE : sprintf (buf, "define %.256s", str); str = buf; break; case jr_ST_PRE_PROCESSOR_MACRO : sprintf (buf, "macro %.256s", str); str = buf; break; } /* * prepend the word "struct" or "union" to the string */ return jr_ST_FindSymbol (symbol_table, str); } jr_ST_Identifier *jr_ST_EnterIdentifier (symbol_table, str) jr_ST_SymbolTable * symbol_table; const char * str; { jr_ST_Identifier tmp_id[1]; jr_ST_Identifier * id_ptr; jr_ST_IdentifierInit (tmp_id, str); id_ptr = jr_AVL_TreeFindElementPtr (symbol_table->id_table, tmp_id); if (id_ptr) { jr_ST_IdentifierUndo (tmp_id); } else { id_ptr = jr_AVL_TreeSetNewElement (symbol_table->id_table, tmp_id); } jr_ST_IdentifierIncrementRefs (id_ptr); return id_ptr; } jr_ST_Symbol * jr_ST_SymbolAllocate (scope_header, id) jr_ST_ScopeHeader * scope_header; jr_ST_Identifier * id; { jr_ST_Symbol * new_symbol; new_symbol = jr_LListNewTailPtr (scope_header->symbol_list); /* * add to tail so the scope symbol list has the same order * as the declarations. A loop on the scope will generate * the same order */ memset (new_symbol, 0, jr_LListElementSize (scope_header->symbol_list)); /* * zero the symbol and the data portion */ new_symbol->id = id; new_symbol->scope_num = scope_header->scope_num; if (id) { /* * could be unnamed symbol */ new_symbol->prev_definition = jr_ST_IdentifierSymbol(id); jr_ST_IdentifierSetSymbol (id, new_symbol); new_symbol->str = jr_ST_IdentifierStr (id); } else { new_symbol->str = 0; } new_symbol->file_name = "unknown"; return (new_symbol); } jr_ST_Symbol *jr_ST_EnterNativeSymbol (symbol_table, symbol_kind, str, token_num, keyword_group) jr_ST_SymbolTable * symbol_table; jr_int symbol_kind; const char * str; jr_int token_num; jr_int keyword_group; { jr_ST_Symbol * symbol; jr_ST_Identifier * id; /* * scope 0 is for keywords and builtin types * if a later scope has str defined then * adding str will cause a data structure inconsistency */ if (symbol = jr_ST_FindSymbol (symbol_table, str)) { return (0); /* * previously declared */ } id = jr_ST_EnterIdentifier (symbol_table, str); symbol = jr_ST_SymbolAllocate ( jr_AListElementPtr (symbol_table->scope_headers, 0), id ); symbol->symbol_kind = symbol_kind; symbol->token_num = token_num; symbol->keyword_group = keyword_group; symbol->type = 0; return (symbol); } jr_ST_Symbol *jr_ST_EnterSymbol (symbol_table, symbol_kind, str, base_sym, num_star, list) jr_ST_SymbolTable * symbol_table; jr_int symbol_kind; const char * str; jr_ST_Symbol * base_sym; jr_int num_star; jr_AList * list; { jr_ST_Symbol * symbol; jr_ST_Identifier * id; char buf[512]; if (str) { /* * could be un-named struct */ switch (symbol_kind) { case jr_ST_STRUCT : sprintf (buf, "struct %.256s", str); str = buf; break; case jr_ST_UNION : sprintf (buf, "union %.256s", str); str = buf; break; case jr_ST_ENUM : sprintf (buf, "enum %.256s", str); str = buf; break; case jr_ST_PRE_PROCESSOR_DEFINE : sprintf (buf, "define %.256s", str); str = buf; break; case jr_ST_PRE_PROCESSOR_MACRO : sprintf (buf, "macro %.256s", str); str = buf; break; } /* * prepend the word "struct" or "union" to the string */ symbol = jr_ST_FindSymbol (symbol_table, str); if (symbol && jr_ST_SymbolScopeNum (symbol) == jr_ST_CurrScopeNum (symbol_table)) { /* * already defined in the current scope */ if (symbol_kind != jr_ST_STRUCT && symbol_kind != jr_ST_UNION) { return (0); } /* * If its a struct or union, then we * may redefine it if the current definition * doesn't have any fields */ if (jr_ST_TypeNumFields (symbol->type) != 0) { return (0); } } else { id = jr_ST_EnterIdentifier (symbol_table, str); symbol = jr_ST_SymbolAllocate (jr_ST_CurrScopeHeader(symbol_table), id); } } else { symbol = jr_ST_SymbolAllocate (jr_ST_CurrScopeHeader(symbol_table), 0); } symbol->symbol_kind = symbol_kind; switch (symbol_kind) { case jr_ST_TYPEDEF: case jr_ST_VARIABLE: case jr_ST_STRUCT: case jr_ST_UNION: case jr_ST_ENUM: case jr_ST_FUNCTION: if (symbol_kind == jr_ST_TYPEDEF) { symbol_kind = jr_ST_VARIABLE; } symbol->type = jr_ST_EnterType (symbol_table, symbol_kind, base_sym, num_star, list); break; case jr_ST_PRE_PROCESSOR_DEFINE : case jr_ST_PRE_PROCESSOR_MACRO : symbol->token_num = num_star; break; } return (symbol); } void jr_ST_SetSymbolType (stable, symbol, base_sym, num_star, list) jr_ST_SymbolTable * stable; jr_ST_Symbol * symbol; jr_ST_Symbol * base_sym; jr_int num_star; jr_AList * list; { if (symbol->symbol_kind != jr_ST_STRING) { return; } symbol->symbol_kind = jr_ST_VARIABLE; symbol->type = jr_ST_EnterType (stable, jr_ST_VARIABLE, base_sym, num_star, list); } jr_ST_TypeStruct *jr_ST_EnterType (symbol_table, type_kind, base_sym, num_stars, list) jr_ST_SymbolTable * symbol_table; jr_int type_kind; jr_ST_Symbol * base_sym; jr_int num_stars; jr_AList * list; { jr_ST_TypeStruct tmp_type[1]; jr_ST_TypeStruct * type_ptr; jr_ST_TypeInitForLookup (tmp_type, type_kind, base_sym, num_stars, list); type_ptr = jr_AVL_TreeFindElementPtr (symbol_table->type_table, tmp_type); if (type_ptr == 0) { /* * else not in the table, copy the type information */ jr_ST_TypeLookupInitDuplicate (tmp_type, symbol_table); type_ptr = jr_AVL_TreeSetNewElement (symbol_table->type_table, tmp_type); } else { jr_ST_TypeUndoForLookup (tmp_type); } jr_ST_TypeIncrementRefs (type_ptr); return type_ptr; } void jr_ST_UnreferenceIdentifier (symbol_table, id_ptr) jr_ST_SymbolTable * symbol_table; jr_ST_Identifier * id_ptr; { jr_ST_IdentifierDecrementRefs (id_ptr); if (jr_ST_IdentifierNumRefs (id_ptr) == 0) { id_ptr = jr_AVL_TreeExtractElement (symbol_table->id_table, id_ptr); jr_ST_IdentifierUndo (id_ptr); jr_AVL_TreeFreeElement (symbol_table->id_table, id_ptr); } } void jr_ST_UnreferenceType (symbol_table, type_ptr) jr_ST_SymbolTable * symbol_table; jr_ST_TypeStruct * type_ptr; { jr_ST_TypeDecrementRefs (type_ptr); if (jr_ST_TypeNumRefs (type_ptr) == 0) { if (jr_ST_TypeKind (type_ptr) != jr_ST_VARIABLE) { jr_ST_FieldType * field; jr_ST_FieldListForEachElementPtr (jr_ST_TypeFieldList (type_ptr), field) { jr_ST_UnreferenceIdentifier (symbol_table, jr_ST_FieldIdentifier (field)); jr_ST_UnreferenceType (symbol_table, jr_ST_FieldTypePtr (field)); } } type_ptr = jr_AVL_TreeExtractElement (symbol_table->type_table, type_ptr); jr_ST_TypeUndo (type_ptr); jr_AVL_TreeFreeElement (symbol_table->type_table, type_ptr); } } jr_ST_Symbol *jr_ST_FindBaseTypeSymbol (type) jr_ST_TypeStruct * type; { jr_ST_Symbol * curr_base_type_sym; curr_base_type_sym = jr_ST_TypeBaseSymbol (type); if (curr_base_type_sym == 0) return (0); while (jr_ST_SymbolIsVariable (curr_base_type_sym) || jr_ST_SymbolIsFunction (curr_base_type_sym)) { /* * bottom out when we hit the first typedef, builtin, struct */ curr_base_type_sym = jr_ST_TypeBaseSymbol (jr_ST_SymbolType (curr_base_type_sym)); } return (curr_base_type_sym); } char *jr_ST_GetUniqueString (stable, string) jr_ST_SymbolTable * stable; char * string; { jr_ST_StringType tmp_string_info[1]; jr_ST_StringType * found_string_info; jr_ST_StringInitForLookUp (tmp_string_info, string); found_string_info = jr_HTableFindElementPtr (stable->string_table, tmp_string_info); jr_ST_StringUndoForLookUp (tmp_string_info); if (found_string_info == 0) { jr_ST_StringInit (tmp_string_info, string); found_string_info = jr_HTableSetNewElement (stable->string_table, tmp_string_info); } return jr_ST_StringValue (found_string_info); } void jr_ST_SetSymbolLocation (stable, symbol, file_name, line_number) jr_ST_SymbolTable * stable; jr_ST_Symbol * symbol; char * file_name; jr_int line_number; { symbol->file_name = jr_ST_GetUniqueString (stable, file_name); symbol->line_number = line_number; } void jr_ST_SetFieldLocation (stable, field, file_name, line_number) jr_ST_SymbolTable * stable; jr_ST_FieldType * field; char * file_name; jr_int line_number; { field->file_name = jr_ST_GetUniqueString (stable, file_name); field->line_number = line_number; }
frankjas/libjr
libjr/syscalls/jr_mktmp.c
#define _POSIX_SOURCE 1 #include "ezport.h" #include <string.h> #include <stdlib.h> #include "jr/misc.h" #include "jr/long.h" #include "jr/error.h" #include "jr/malloc.h" #include "jr/syscalls.h" #include "jr/time.h" void jr_MkTemp (tmp_name_template) char * tmp_name_template; { static int SeedWasSet = 0; jr_int random_int; jr_ULong random_ulong; char x_buffer[32]; char * cptr; /* * 3/11/2004: Used to use mktemp(), but that now generates * warning message whenever it is linked in. * * The following procedure should generate a random number * where the top 16 bits are process id, lower 14 are random * which should fit in 6 base 32 digits (32^6 == 2^30) */ if (! SeedWasSet) { srand (jr_time_seconds ()); SeedWasSet = 1; } random_int = rand (); if (random_int < 0) { random_int = -random_int; } random_int = (16.0 * 1024 * random_int / (RAND_MAX + 1.0)); /* * 3/11/2004: random_int == a number from 0-2^14 */ jr_ULongAsgnUInt (&random_ulong, jr_getpid ()); jr_ULongShiftInt (&random_ulong, random_ulong, -16); jr_ULongAddUInt (&random_ulong, random_ulong, random_int); jr_ULongToBase32String (random_ulong, x_buffer, 1 /* use_lower_case */); cptr = strstr (tmp_name_template, "XXXXXX"); if (cptr) { /* ** 9-6-2012: pad x_buffer by 0 on the left, a straight strncpy() ** in this case puts a null in position 5, truncating the string. */ jr_int pad_length = 6 - (jr_int) strlen( x_buffer); jr_int z; if (pad_length < 0) { pad_length = 0; } for (z=0; z < pad_length; z++, cptr++) { *cptr = '0'; } strncpy( cptr, x_buffer, 6 - pad_length); } } const char *jr_MkTempInTempDir ( const char * tmp_name_template) { char tmp_dir[64]; char * template_buf; char error_buf [jr_ERROR_LEN]; jr_int status; status = jr_GetTempDir (tmp_dir, sizeof (tmp_dir), error_buf); if (status != 0) { sprintf (tmp_dir, "."); } template_buf = jr_malloc (strlen (tmp_dir) + 1 + strlen (tmp_name_template) + 1); sprintf (template_buf, "%s/%s", tmp_dir, tmp_name_template); jr_MkTemp (template_buf); return template_buf; }
frankjas/libjr
include/jr/error.h
#ifndef __jr_error_h___ #define __jr_error_h___ #include "ezport.h" #define jr_INTERNAL_ERROR -1 #define jr_MISUSE_ERROR -2 #define jr_PERMISSION_ERROR -3 #define jr_NOT_FOUND_ERROR -4 #define jr_IS_FOUND_ERROR -5 #define jr_TIME_OUT_ERROR -6 #define jr_NO_ROOM_ERROR -7 #define jr_IO_ERROR -8 #define jr_WOULD_BLOCK_ERROR -9 #define jr_EOF_ERROR -10 #define jr_INTERRUPTED_ERROR -11 #define jr_NOT_IMPLEMENTED_ERROR -12 #define jr_MIN_ERROR -100 extern jr_int jr_ConvertErrno ( jr_int errno_value); extern jr_int jr_ConvertAprErrno ( jr_int errno_value); extern jr_int jr_ConvertLastError ( jr_int last_error); extern jr_int jr_ConvertHttpError ( jr_int http_status); extern jr_int jr_ConvertGetHostErrno ( jr_int gethost_errno); extern char * jr_GetHostErrnoString ( jr_int gethost_errno); #define jr_ERROR_LEN 512 extern jr_int jr_esprintf ( char * opt_error_buf, const char * control_string, ...) __attribute__((format(printf,2,3))); /* ** 11/16/06: helps gcc generate format string warnings? */ extern jr_int jr_ensprintf ( char * opt_error_buf, jr_int error_buf_len, const char * control_string, ...) __attribute__((format(printf,3,4))); extern jr_int jr_error_set_max_buf_length ( jr_int max_buf_length); extern jr_int jr_error_max_buf_length (void); extern void jr_error_msg_simulate ( const char * file_name, jr_int line_number); #endif
frankjas/libjr
libjr/string/vwordsip.c
#include "ezport.h" #include <stdio.h> #include <string.h> #include "jr/malloc.h" #include "jr/misc.h" #include "jr/vector.h" jr_int jr_VectorizeIntoWordsInPlace(str, sep, vector, vector_size) char * str ; const char * sep ; char ** vector ; jr_int vector_size ; { char *begin; jr_int curr_index; for (begin = 0, curr_index = 0; ; str++) { if (strchr(sep, *str) || *str == 0) { /* * saw a separator * the null at the end is an implicit separator */ if (begin == 0) { if (*str) continue; /* * if begin == 0 then we haven't started * a string and are skipping separators */ if (!*str) break; /* * if *str is null then we hit the end * before begining the next string */ } else { if (curr_index == vector_size - 1) { /* * If we have hit the last vector slot * (where a null should go) * stick the remaining un-vectorized string * into this slot and return. */ vector [curr_index] = begin; return (curr_index + 1); } else { vector [curr_index] = begin; curr_index++; begin = 0; /* * set begin to 0 to indicate we haven't * begun the string */ if (*str) { *str = 0; } else { /* * ran out of input */ break; } } } } else if (begin == 0) { /* * beginning the string */ begin = str; } } vector [curr_index] = 0 ; return (curr_index) ; } /* #include <stdio.h> PrintVector(wfp, argv) FILE *wfp ; char **argv ; { for (; *argv; argv++) { fprintf(wfp,"\"%s\"%s", *argv, argv[1]?" ":"") ; } fprintf(wfp,"\n") ; } main (argc, argv) jr_int argc ; char **argv ; { char buf[512] ; char *vbuf[5] ; fprintf (stderr, "Enter up to %d arguments on a line: ", sizeof (vbuf) / sizeof (char *) - 1 ) ; while (fgets (buf, sizeof (buf), stdin)) { argc = jr_VectorizeIntoWordsInPlace ( buf, " :\t", vbuf, sizeof (vbuf) / sizeof (char *) ) ; fprintf (stdout, "%d arguments\n", argc) ; if (argc == sizeof (vbuf) / sizeof (char *)) { jr_int i ; fprintf (stderr, "Insufficient buffer space for arguments.\n" ) ; for (i=0; i < argc; i++) { fprintf (stderr, "jr_free (argv[%d] == %s)\n", i, vbuf[i] ) ; } } else { PrintVector(stdout,vbuf) ; } fprintf (stderr, "Enter up to %d arguments on a line: ", sizeof (vbuf) / sizeof (char *) - 1 ) ; } } */
frankjas/libjr
libjr/symtab/st_type.c
<reponame>frankjas/libjr #include "project.h" jr_ST_TypeStruct *jr_ST_TypeCreate (type_kind, base_sym, num_stars, list) jr_int type_kind; jr_ST_Symbol * base_sym; jr_int num_stars; jr_AList * list; { jr_ST_TypeStruct *new_type = jr_malloc (sizeof (jr_ST_TypeStruct)); jr_ST_TypeInit (new_type, type_kind, base_sym, num_stars, list); return (new_type); } void jr_ST_TypeInitForLookup (new_type, type_kind, base_sym, num_stars, list) jr_ST_TypeStruct * new_type; jr_int type_kind; jr_ST_Symbol * base_sym; jr_int num_stars; jr_AList * list; { new_type->type_kind = type_kind; new_type->base_sym = base_sym; new_type->num_stars = num_stars; new_type->num_refs = 0; if (list) { jr_AListInitCopy (new_type->list, list); } else { jr_ST_ArrayListInit (new_type->list); /* * no list, never be added to so the type of list is arbitrary * having a list always inited makes undoing easier */ } } void jr_ST_TypeUndoForLookup (type) jr_ST_TypeStruct * type; { jr_AListUndo (type->list); /* * only the list was separately allocated */ } void jr_ST_TypeInit (new_type, type_kind, base_sym, num_stars, list) jr_ST_TypeStruct * new_type; jr_int type_kind; jr_ST_Symbol * base_sym; jr_int num_stars; jr_AList * list; { jr_ST_TypeInitForLookup (new_type, type_kind, base_sym, num_stars, list); switch (type_kind) { case jr_ST_VARIABLE : { jr_ST_ArrayDimension *tmp_dimension; /* * save the array length strings */ jr_AListForEachElementPtr (new_type->list, tmp_dimension) { if (tmp_dimension->length_expr) { tmp_dimension->length_expr = jr_C_ExprNodeCreateCopy (tmp_dimension->length_expr); } if (tmp_dimension->length_str) { tmp_dimension->length_str = jr_strdup (tmp_dimension->length_str); } } break; } default : { /* * recursively save the jr_ST_FieldType pointers, since they * are the same as the list parameter */ jr_ST_FieldType *new_field; jr_ST_FieldListForEachElementPtr (new_type->list, new_field) { new_field->id = jr_ST_IdentifierCreate (new_field->id->str); new_field->type = jr_ST_TypeCreate ( new_field->type->type_kind, new_field->type->base_sym, new_field->type->num_stars, new_field->type->list ); if (new_field->bit_field_expr) { new_field->bit_field_expr = jr_C_ExprNodeCreateCopy (new_field->bit_field_expr); } /* * this type kind is guaranteed to be simple * since field types are always simple */ } break; } } } void jr_ST_TypeLookupInitDuplicate (new_type, symbol_table) jr_ST_TypeStruct * new_type; jr_ST_SymbolTable * symbol_table; { switch (new_type->type_kind) { case jr_ST_VARIABLE : { jr_ST_ArrayDimension *tmp_dimension; /* * save the array length strings */ jr_AListForEachElementPtr (new_type->list, tmp_dimension) { if (tmp_dimension->length_expr) { tmp_dimension->length_expr = jr_C_ExprNodeCreateCopy (tmp_dimension->length_expr); } if (tmp_dimension->length_str) { tmp_dimension->length_str = jr_strdup (tmp_dimension->length_str); } } break; } case jr_ST_ENUM : { jr_ST_EnumType * enum_ptr; /* * save all the enum fields */ jr_ST_EnumListForEachElementPtr (new_type->list, enum_ptr) { enum_ptr->id = jr_ST_EnterIdentifier ( symbol_table, jr_ST_IdentifierStr (enum_ptr->id) ); if (enum_ptr->value_expr) { enum_ptr->value_expr = jr_C_ExprNodeCreateCopy (enum_ptr->value_expr); } } break; } default : { jr_ST_FieldType *new_field; /* * recursively save the fields in the list * the new type list is already non recursive copy of the list * go through and change the references to new * type table entries */ jr_ST_FieldListForEachElementPtr (new_type->list, new_field) { new_field->id = jr_ST_EnterIdentifier ( symbol_table, jr_ST_IdentifierStr (new_field->id) ); new_field->type = jr_ST_EnterType ( symbol_table, new_field->type->type_kind, new_field->type->base_sym, new_field->type->num_stars, new_field->type->list ); if (new_field->bit_field_expr) { new_field->bit_field_expr = jr_C_ExprNodeCreateCopy (new_field->bit_field_expr); } } } } } void jr_ST_TypeDestroy (type) jr_ST_TypeStruct *type; { jr_ST_TypeUndo (type); jr_free (type); } void jr_ST_TypeUndo (type) jr_ST_TypeStruct *type; { switch (jr_ST_TypeKind (type)) { case jr_ST_STRUCT : case jr_ST_UNION : case jr_ST_FUNCTION : { jr_ST_FieldListUndo (type->list); break; } case jr_ST_VARIABLE : { jr_ST_ArrayListUndo (type->list); break; } case jr_ST_ENUM : { jr_ST_EnumListUndo (type->list); break; } } } jr_int jr_ST_TypeHash (void_arg_1) const void * void_arg_1; { const jr_ST_TypeStruct * type = void_arg_1; jr_int hash_value = 0; if (jr_ST_TypeBaseSymbol (type) && jr_ST_SymbolIdentifier (jr_ST_TypeBaseSymbol(type))) { hash_value += jr_strhash (jr_ST_SymbolStr(jr_ST_TypeBaseSymbol(type))); } else { hash_value += jr_ST_TypeKind(type) << 6; } switch (jr_ST_TypeKind (type)) { case jr_ST_VARIABLE : { jr_int num_dimension = jr_ST_TypeNumArrayDimensions (type); jr_int sub = num_dimension / 3; if (num_dimension) { hash_value += jr_ST_ArrayDimensionLengthNum (type->list, 0); hash_value += jr_ST_ArrayDimensionLengthNum (type->list, sub); hash_value += jr_ST_ArrayDimensionLengthNum (type->list, sub * 2); hash_value += jr_ST_ArrayDimensionLengthNum ( type->list, num_dimension-1 ); hash_value *= num_dimension; } if (jr_ST_TypeNumStars (type)) { hash_value *= jr_ST_TypeNumStars (type); } break; } case jr_ST_STRUCT : case jr_ST_UNION : case jr_ST_FUNCTION : { jr_int num_fields = jr_ST_TypeNumFields (type); jr_int sub = num_fields / 3; jr_ST_FieldType * field; const jr_ST_FieldList * field_list = jr_ST_TypeFieldList (type); if (num_fields) { field = jr_ST_FieldListElementPtr (field_list, 0); hash_value += jr_strhash (jr_ST_FieldStr (field)); field = jr_ST_FieldListElementPtr (field_list, sub); hash_value += jr_strhash (jr_ST_FieldStr (field)); field = jr_ST_FieldListElementPtr (field_list, sub * 2); hash_value += jr_strhash (jr_ST_FieldStr (field)); field = jr_ST_FieldListElementPtr (field_list, num_fields - 1); hash_value += jr_strhash (jr_ST_FieldStr(field)); hash_value *= num_fields; } if (jr_ST_TypeNumStars (type)) { hash_value *= jr_ST_TypeNumStars (type); } break; } case jr_ST_ENUM : { jr_int num_enums = jr_ST_TypeNumEnums (type); jr_int sub = num_enums / 3; jr_ST_EnumType * enum_ptr; const jr_ST_EnumList * enum_list = jr_ST_TypeEnumList (type); if (num_enums) { enum_ptr = jr_AListElementPtr (enum_list, 0); hash_value += jr_strhash (jr_ST_EnumStr (enum_ptr)); enum_ptr = jr_AListElementPtr (enum_list, sub); hash_value += jr_strhash (jr_ST_EnumStr (enum_ptr)); enum_ptr = jr_AListElementPtr (enum_list, sub * 2); hash_value += jr_strhash (jr_ST_EnumStr (enum_ptr)); enum_ptr = jr_AListElementPtr (enum_list, num_enums - 1); hash_value += jr_strhash (jr_ST_EnumStr(enum_ptr)); hash_value *= num_enums; } break; } } return (hash_value); } jr_int jr_ST_TypeCmp (type1, type2) jr_ST_TypeStruct *type1, *type2; { jr_int comp; comp = jr_ST_TypeKind (type1) - jr_ST_TypeKind (type2); if (comp) return (comp); comp = jr_ST_TypeNumStars (type1) - jr_ST_TypeNumStars(type2); if (comp) return (comp); /* * The base sym could be 0 if its a struct * compare the base symbols using pointer comparisons */ comp = jr_ST_TypeBaseSymbol (type1) - jr_ST_TypeBaseSymbol (type2); if (comp != 0) { return comp; } switch (jr_ST_TypeKind (type1)) { case jr_ST_VARIABLE : { jr_int i; comp = jr_ST_TypeNumArrayDimensions (type1) - jr_ST_TypeNumArrayDimensions(type2); if (comp) return (comp); jr_ST_ArrayForEachDimension (type1->list, i) { comp = jr_ST_ArrayDimensionLengthNum (type1->list, i) - jr_ST_ArrayDimensionLengthNum (type2->list, i); if (comp) return (comp); } return (0); } case jr_ST_STRUCT : case jr_ST_UNION : case jr_ST_FUNCTION : { jr_ST_FieldType *field1, *field2; comp = jr_ST_TypeNumFields (type1) - jr_ST_TypeNumFields (type2); if (comp) return (comp); comp = jr_ST_FieldListDataSize (type1->list) - jr_ST_FieldListDataSize (type2->list); if (comp) return (comp); field2 = jr_AListElementPtr (type2->list, 0); jr_ST_FieldListForEachElementPtr (type1->list, field1) { comp = jr_ST_FieldCmp (field1, field2); if (comp) return (comp); if (jr_ST_FieldListDataSize (type1->list) > 0) { comp = memcmp ( jr_ST_FieldDataPtr (field1), jr_ST_FieldDataPtr (field2), jr_ST_FieldListDataSize (type1->list) ); if (comp) return (comp); } field2 = jr_AListNextElementPtr (type2->list, field2); } return (0); } case jr_ST_ENUM : { jr_ST_EnumType *enum1, *enum2; comp = jr_ST_TypeNumEnums (type1) - jr_ST_TypeNumEnums(type2); if (comp) return (comp); enum2 = jr_AListElementPtr (type2->list, 0); jr_ST_EnumListForEachElementPtr (type1->list, enum1) { comp = strcmp (jr_ST_EnumStr (enum1), jr_ST_EnumStr (enum2)); if (comp) return (comp); comp = jr_ST_EnumValue (enum1) - jr_ST_EnumValue (enum2); if (comp) return (comp); enum2 = jr_AListNextElementPtr (type2->list, enum2); } return (0); } } /* can't get here */ return 0; } jr_int jr_ST_TypeEquiv (type1, type2) jr_ST_TypeStruct *type1, *type2; { jr_int comp; jr_ST_TypeStruct new_type1[1], new_type2[1]; jr_ST_Symbol *base_sym1, *base_sym2; /* * We will factor typedefs out of the base symbol collapsing * the information into a new type until we hit a non-typedef base. * * Then compare the types, if they are equal, call recursively * on the new base syms. * * We can undo the new types before we call recursively. * * The collapsing may create an erroneous situation, i.e. * an array of functions or such like. We should check * each type before entering to make sure this * isn't possible. */ if (jr_ST_CanCollapseBaseSymbol (type1)) { jr_ST_TypeCollapsedInit (new_type1, type1); type1 = new_type1; } if (jr_ST_CanCollapseBaseSymbol (type2)) { jr_ST_TypeCollapsedInit (new_type2, type2); type2 = new_type2; } comp = jr_ST_TypeKind (type1) - jr_ST_TypeKind (type2); if (comp) goto not_equiv; comp = jr_ST_TypeNumStars (type1) - jr_ST_TypeNumStars(type2); if (comp) goto not_equiv; switch (jr_ST_TypeKind (type1)) { case jr_ST_VARIABLE : { jr_int i; comp = jr_ST_TypeNumArrayDimensions (type1) - jr_ST_TypeNumArrayDimensions(type2); if (comp) goto not_equiv; jr_ST_ArrayForEachDimension (type1->list, i) { comp = jr_ST_ArrayDimensionLengthNum (type1->list, i) - jr_ST_ArrayDimensionLengthNum (type2->list, i); if (comp) goto not_equiv; } break; } case jr_ST_STRUCT : case jr_ST_UNION : case jr_ST_FUNCTION : { jr_ST_FieldType *field1, *field2; if (jr_ST_TypeKind (type1) == jr_ST_FUNCTION && jr_ST_TypeNumFields (type1) == 0 || jr_ST_TypeNumFields (type2) == 0) { /* * if its a function and one or both has * no parameters, then that is type equivalent * to any parameter list */ break; } comp = jr_ST_TypeNumFields (type1) - jr_ST_TypeNumFields(type2); if (comp) goto not_equiv; field2 = jr_AListElementPtr (type2->list, 0); jr_ST_FieldListForEachElementPtr (type1->list, field1) { if (!jr_ST_TypeEquiv (field1->type, field2->type)) { goto not_equiv; } field2 = jr_AListNextElementPtr (type2->list, field2); } break; } case jr_ST_ENUM : { jr_ST_EnumType *enum1, *enum2; comp = jr_ST_TypeNumEnums (type1) - jr_ST_TypeNumEnums(type2); if (comp) goto not_equiv; enum2 = jr_AListElementPtr (type2->list, 0); jr_ST_EnumListForEachElementPtr (type1->list, enum1) { comp = jr_ST_EnumValueExpr (enum1) - jr_ST_EnumValueExpr (enum2); if (comp) goto not_equiv; enum2 = jr_AListNextElementPtr (type2->list, enum2); } break; } } base_sym1 = jr_ST_TypeBaseSymbol (type1); base_sym2 = jr_ST_TypeBaseSymbol (type2); if (type1 == new_type1) jr_ST_TypeUndo (new_type1); if (type2 == new_type2) jr_ST_TypeUndo (new_type2); if (base_sym1 == base_sym2) { return (1); } else { if (jr_ST_SymbolType (base_sym1) && jr_ST_SymbolType (base_sym2)) { return ( jr_ST_TypeEquiv ( jr_ST_SymbolType (base_sym1), jr_ST_SymbolType (base_sym2) ) ); /* * built-in types don't have base types * if one's is a built-in and the other isn't * they aren't equivalent */ } return (1); } not_equiv : if (type1 == new_type1) jr_ST_TypeUndo (new_type1); if (type2 == new_type2) jr_ST_TypeUndo (new_type2); return (0); } jr_int jr_ST_CanCollapseBaseSymbol (type) jr_ST_TypeStruct *type; { if (jr_ST_TypeBaseSymbol (type) && jr_ST_SymbolKind (jr_ST_TypeBaseSymbol (type)) == jr_ST_TYPEDEF) { jr_ST_Symbol *typedef_sym = jr_ST_TypeBaseSymbol (type); jr_ST_TypeStruct *typedef_type = jr_ST_SymbolType (typedef_sym); if (type->num_stars == 0 || jr_AListSize (typedef_type->list) == 0) { /* * A typedef has the same semantics as parenthesizing * declarators. A typedef can be collapsed exactly * when the parens around a declarator are trivial. * See the production for DirectDeclarator in * parsegen's grammar.g for a description of the cases. */ return (1); } } return (0); } void jr_ST_TypeCollapsedInit (new_type, type) jr_ST_TypeStruct *new_type; jr_ST_TypeStruct *type; { /* * Remove reference to typedef symbol, and remove * any trivial nesting caused by the typedef. For example: * typedef jr_int *int_pointer; int_pointer myvar[20]; * * We must know that collapsing the typedef does not * create array of functions or another nasty situation */ jr_ST_ArrayList array_list[1]; jr_AList * list = array_list; jr_int kind = jr_ST_TypeKind (type); jr_int num_stars = 0; /* * if the kind is struct or union, this will break * after the first loop. * Otherwise its either function or variable * If its a variable it will stay that way until a function * typedef is encountered, adding array dimensions */ jr_ST_ArrayListInit (array_list); while (1) { num_stars += jr_ST_TypeNumStars (type); if (jr_ST_TypeKind (type) == jr_ST_FUNCTION) { kind = jr_ST_FUNCTION; list = jr_ST_TypeParamList (type); } if (kind == jr_ST_VARIABLE) { /* * haven't encountered a function base symbol */ jr_int i; jr_ST_ArrayForEachDimension (type->list, i) { jr_ST_ArrayListAddDimension ( array_list, jr_ST_ArrayDimensionLengthNum (type->list, i), jr_ST_ArrayDimensionLengthStr (type->list, i), jr_ST_ArrayDimensionLengthExpr (type->list, i) ); } } if (!jr_ST_CanCollapseBaseSymbol (type)) break; type = jr_ST_SymbolType (jr_ST_TypeBaseSymbol (type)); } jr_ST_TypeInit (new_type, kind, type->base_sym, num_stars, list ); jr_ST_ArrayListUndo (array_list); } jr_int jr_ST_TypeIsValid (type, array_of_func, func_ret_array, func_ret_func) jr_ST_TypeStruct *type; jr_int array_of_func; jr_int func_ret_array; jr_int func_ret_func; { /* * Collapse typedefs and check for arrays of functions * or functions returning arrays or returning functions */ jr_ST_Symbol *base_sym; jr_int has_array = 0, kind = jr_ST_VARIABLE; /* * this loop changes base_sym only when the base symbol * is not collapsable * Otherwise it collapses the types looking for * the 3 error cases */ for ( base_sym = jr_ST_TypeBaseSymbol (type); !jr_ST_SymbolIsBuiltInType (base_sym); type = jr_ST_SymbolType (jr_ST_TypeBaseSymbol (type)) ) { if (jr_ST_TypeKind (type) == jr_ST_FUNCTION) { if (kind == jr_ST_FUNCTION) { return (func_ret_func); } if (has_array) { return (array_of_func); } kind = jr_ST_FUNCTION; } if (jr_ST_TypeKind (type) == jr_ST_VARIABLE) { has_array += jr_ST_TypeNumArrayDimensions (type); if (kind == jr_ST_FUNCTION) { return (func_ret_array); } } if (!jr_ST_CanCollapseBaseSymbol (type)) { base_sym = jr_ST_TypeBaseSymbol (type); has_array = 0; kind = jr_ST_VARIABLE; /* * restart collapsing check from this base symbol */ } } /* can't get here */ return 0; }
frankjas/libjr
libjr/llist/llistmrg.c
<reponame>frankjas/libjr #include "project.h" void jr_LListMergeWithUniqueFlag (list1, list2, cmpfn, unique) jr_LList * list1; jr_LList * list2; jr_int (*cmpfn) (); jr_int unique; { void * prev1; void * curr1; void * curr2; void * new; jr_int comp; prev1 = 0; curr1 = jr_LListHeadPtr (list1); curr2 = jr_LListHeadPtr (list2); while (curr2 && curr1) { comp = (*cmpfn) (curr1, curr2); if (comp < 0) { prev1 = curr1; curr1 = jr_LListNextElementPtr (list1, curr1); continue; } if (comp == 0 && unique) { curr2 = jr_LListNextElementPtr (list2, curr2); continue; } new = jr_LListAllocateElementWithSize (list2, jr_LListElementSize (list2)); memcpy (new, curr2, jr_LListElementSize (list2)); /* insert new before curr1 * the tail is either curr1 or after curr1 * so we don't have to change it */ if (prev1 == 0) { /* make new head */ jr_LListNextElementPtr (list1, new) = jr_LListHeadPtr (list1); jr_LListHeadPtr (list1) = new; } else { jr_LListNextElementPtr (list1, new) = jr_LListNextElementPtr (list1, prev1); jr_LListNextElementPtr (list1, prev1) = new; } prev1 = new; curr2 = jr_LListNextElementPtr (list2, curr2); } if (curr2 == 0) return ; /* ran out of the second list */ if (jr_LListIsEmpty (list1)) { jr_LListSetNewTail (list1, curr2); curr2 = jr_LListNextElementPtr (list2, curr2); } for (; curr2; curr2 = jr_LListNextElementPtr (list2, curr2)) { if (!unique) { jr_LListSetNewTail (list1, curr2); continue; } comp = (*cmpfn) (jr_LListTailPtr(list1), curr2); if (comp == 0) continue; jr_LListSetNewTail (list1, curr2); } }
frankjas/libjr
libjr/syscalls/chkpass.c
<filename>libjr/syscalls/chkpass.c #define _POSIX_SOURCE 1 #include "ezport.h" #include <pwd.h> #include <unistd.h> #include <string.h> #include "jr/syscalls.h" jr_int jr_CheckUnixPassword(username, unencrypted_password_text, pw_entry_arg) char * username ; char * unencrypted_password_text ; void * pw_entry_arg ; { struct passwd * pw_entry = pw_entry_arg ; char * encrypted_passwd_text ; jr_int difference ; encrypted_passwd_text = (char *) crypt(unencrypted_password_text, pw_entry->pw_passwd) ; /* Compare the supplied password with the password file entry */ difference = strcmp(encrypted_passwd_text, pw_entry->pw_passwd) ; /* fprintf(stderr, "strcmp(\"%s\", \"%s\") == %d\n", encrypted_passwd_text, pw_entry->pw_passwd, difference ) ; */ if (difference != 0) { return (-1); } else { return (0); } } /* * Sample use: if ((pw = getpwnam(user)) == NULL) { WriteToClient ("500 Unknown user, %s.", user); exit(1); } if (jr_CheckUnixPassword (user, oldpass, pw) != 0) { WriteToClient ("500 Old password is incorrect."); exit(1); } */
frankjas/libjr
libjr/syscalls/globvec.c
<reponame>frankjas/libjr #include "ezport.h" #if defined (USG) && !defined (Xenix) # if !defined (USGr3) && ! defined (USGr4) # define USGr3 # endif /* USGr3 */ #endif /* USG && !Xenix */ #include <stdlib.h> #include <sys/types.h> #include <sys/errno.h> #include <errno.h> #include <sys/param.h> #if defined (_POSIX_VERSION) || defined (USGr3) || defined (USGr4) || defined (DIRENT) # include <dirent.h> # define direct dirent # define D_NAMLEN(d) strlen((d)->d_name) #else # define D_NAMLEN(d) ((d)->d_namlen) # if defined (Xenix) # include <sys/ndir.h> # else # if defined (USG) # include "ndir.h" # else # include <sys/dir.h> # endif # endif #endif /* USGr3 || DIRENT. */ #if defined (_POSIX_SOURCE) /* Posix does not require that the d_ino field be present, and some systems do not provide it. */ # define REAL_DIR_ENTRY(dp) 1 /* TRUE ALWAYS */ #else # define REAL_DIR_ENTRY(dp) (dp->d_ino != 0) #endif /* _POSIX_SOURCE */ #include <string.h> /* * If the opendir () on your system lets you open non-directory files, * then we consider that not robust. Define OPENDIR_NOT_ROBUST in the * SYSDEP_CFLAGS for your machines entry in machines.h. */ #ifndef NULL # define NULL 0 #endif #include <pwd.h> #include "jr/malloc.h" #include "jr/string.h" #include "jr/syscalls.h" /* * Global variable which controls whether or not * matches .*. */ /* * Return a vector of names of files in directory DIR * whose names match glob pattern PAT. * The names are not in any particular order. * Wildcards at the beginning of PAT do not match an initial period. * The vector is terminated by an element that is a null pointer. * To jr_free the space allocated, first jr_free the vector's elements, * then jr_free the vector. * Return 0 if cannot get enough jr_malloc_stats to hold the pointer * and the names. * Return -1 if cannot access directory DIR. * Look in errno for more information. */ const char ** jr_VectorCreateFromDirectoryNameAndPattern ( const char * directory_name_string, const char * pattern_string, jr_int match_slashes, jr_int match_leading_dot) { struct globval { struct globval *next; char *name; }; DIR *d; register struct direct *dp; struct globval *lastlink; register struct globval *nextlink; register char *nextname; unsigned jr_int count; jr_int lose; register const char **name_vector; register unsigned jr_int i; jr_int is_match ; # if defined (OPENDIR_NOT_ROBUST) /* test dir for being a directory first */ { struct stat finfo; if (stat (directory_name_string, &finfo) < 0) { return ((char **) -1) ; } if (!S_ISDIR (finfo.st_mode)) { return ((char **) -1) ; } } # endif /* OPENDIR_NOT_ROBUST */ d = opendir (directory_name_string); if (d == NULL) { /* * opendir failed */ return ((const char **)-1) ; } lastlink = 0; count = 0; lose = 0; /* Scan the directory, finding all names that match. For each name that matches, allocate a struct globval on the stack and store the name in it. Chain those structs together; lastlink is the front of the chain. */ while (1) { dp = readdir (d); if (dp == NULL) break; /* If this directory entry is not to be used, try again. */ if (!REAL_DIR_ENTRY (dp)) continue; /* If a dot must be explicity matched, check to see if they do. */ if ( dp->d_name[0] == '.' && pattern_string[0] != '.' && !match_leading_dot) { continue; } is_match = jr_IsGlobMatch ( dp->d_name, pattern_string, match_slashes, match_leading_dot ) ; if (is_match) { nextlink = (struct globval *) alloca (sizeof (struct globval)); /* stack allocation */ nextlink->next = lastlink; nextname = (char *) jr_malloc (strlen(dp->d_name) + 1); if (nextname == NULL) { lose = 1; break; } lastlink = nextlink; nextlink->name = nextname; memcpy (nextname, dp->d_name, strlen(dp->d_name) + 1); ++count; } } (void) closedir (d); /* Have we run out of malloced space */ if (lose) { /* Here jr_free the strings we have got. */ while (lastlink) { jr_free (lastlink->name); lastlink = lastlink->next; } return 0; } else { name_vector = (const char **) jr_malloc ((count + 1) * sizeof (char *)); lose |= (name_vector == NULL) ; } /* Copy the name pointers from the linked list into the vector. */ for (i = 0; i < count; ++i) { name_vector[i] = lastlink->name; lastlink = lastlink->next; } name_vector[count] = 0; return name_vector; } /* * Return a new array which is the concatenation * of each string in ARRAY to DIR. */ static const char ** glob_dir_to_array (directory_name_string, array) const char * directory_name_string ; const char ** array; { register unsigned jr_int i, l; jr_int add_slash; const char ** result = 0 ; l = strlen (directory_name_string); if (l == 0) return array; add_slash = directory_name_string[l - 1] != '/'; i = 0; while (array[i] != 0) ++i; result = (const char **) jr_malloc ((i + 1) * sizeof (char *)); if (result == NULL) return 0; for (i = 0; array[i] != 0; i++) { result[i] = (char *) jr_malloc (l + (add_slash ? 1 : 0) + strlen (array[i]) + 1); if (result[i] == NULL) return 0; sprintf ((char *) result[i], "%s%s%s", directory_name_string, add_slash ? "/" : "", array[i]); } result[i] = 0; /* Free the input array. */ for (i = 0; array[i] != 0; i++) { jr_free (array[i]); } jr_free ((char *) array); return (result) ; } /* * Do globbing on PATHNAME. Return an array of pathnames that match, * marking the end of the array with a null-pointer as an element. * If no pathnames match, then the array is empty (first element is null). * If there isn't enough jr_malloc_stats, then return 0. * If a file system error occurs, return 0; `errno' has the error code. */ const char ** jr_VectorCreateFromCshLikeNameExpansion( const char * pathname_arg, jr_int match_slashes, jr_int match_leading_dot) { char pathname[1024] ; char * directory_name ; char * filename; unsigned jr_int directory_len; unsigned jr_int result_size; const char ** result = 0 ; if (jr_PathStringCopyWithDollarAndTildeExpansion(pathname, pathname_arg) != 0) { return(0) ; } result = (const char **) jr_malloc (sizeof (char *)); if (result == NULL) return(0); result_size = 1; result[0] = 0; /* Find the filename. */ filename = strrchr (pathname, '/'); if (filename == 0) { filename = pathname; directory_name = ""; directory_len = 0; } else { directory_len = (filename - pathname) + 1; directory_name = (char *) alloca (directory_len + 1); /* stack allocation */ memcpy (directory_name, pathname, directory_len); directory_name[directory_len] = '\0'; ++filename; } /* * If directory_name contains globbing characters, then we * have to expand the previous levels. Just recurse. */ if (jr_HasGlobPatternChars (directory_name)) { const char **directories; register unsigned jr_int i; if (directory_name[directory_len - 1] == '/') { directory_name[directory_len - 1] = '\0'; } directories = jr_VectorCreateFromCshLikeNameExpansion ( directory_name, match_slashes, match_leading_dot ); if (directories == 0) { goto cleanup_error; } else if (*directories == 0) { /* ** 12/20/07: no entries, return a null vector, the loop below ** expects some values */ return(directories) ; } /* * We have successfully globbed the preceding directory name. * For each name in DIRECTORIES, call glob_vector on it and * FILENAME. Concatenate the results together. */ for (i = 0; directories[i] != 0; ++i) { const char **temp_results; temp_results = jr_VectorCreateFromDirectoryNameAndPattern ( directories[i], filename, match_slashes, match_leading_dot ); /* Handle error cases. */ if (temp_results == 0) { goto cleanup_error; } else if (temp_results == (const char **)-1) { /* This filename is probably not a directory. Ignore it. */ ; } else { const char **array = glob_dir_to_array (directories[i], temp_results); register unsigned jr_int l; l = 0; while (array[l] != 0) ++l; result = (const char **)jr_realloc (result, (result_size + l) * sizeof (char *)); if (result == NULL) goto cleanup_error; for (l = 0; array[l] != 0; ++l) { result[result_size++ - 1] = array[l]; } result[result_size - 1] = 0; /* Note that the elements of ARRAY are not jr_freed. */ jr_free ((char *) array); } } /* for */ /* Free the directories. */ for (i = 0; directories[i]; i++) { jr_free (directories[i]); } jr_free ((char *) directories); return(result) ; } /* If there is only a directory name, return it. */ if (*filename == '\0') { result = (const char **) jr_realloc ((char *) result, 2 * sizeof (char *)); if (result == NULL) return 0; result[0] = (char *) jr_malloc (directory_len + 1); if (result[0] == NULL) goto cleanup_error; memcpy ((char *) result[0], directory_name, directory_len + 1); result[1] = 0; return result; } else { /* * Otherwise, just return what jr_VectorCreateFromCshLikeNameExpansion * returns appended to the directory name. */ const char **temp_results ; temp_results = jr_VectorCreateFromDirectoryNameAndPattern ( (directory_len == 0 ? "." : directory_name), filename, match_slashes, match_leading_dot ); if (temp_results == 0 || temp_results == (const char **)-1) { if (result != 0) { jr_free(result) ; } return(0); } if (result != 0) { jr_free(result) ; } return (glob_dir_to_array (directory_name, temp_results)); } /* * We get to jr_malloc_stats error if the program has run out of jr_malloc_stats */ cleanup_error: if (result != 0) { register unsigned jr_int i; for (i = 0; result[i] != 0; ++i) { jr_free (result[i]); } jr_free ((char *) result); } return (0) ; }
frankjas/libjr
libjr/misc/intstr.c
<filename>libjr/misc/intstr.c #include "ezport.h" #include "jr/misc.h" #include <limits.h> /* Author: <NAME> Creation Date: March 1987 */ jr_int jr_intstrcmp (is1, is2) const jr_int *is1 ; const jr_int *is2; { for (; *is1 != jr_INT_NULL; is1++, is2++) { if (*is2 == jr_INT_NULL) return (1); if (*is1 != *is2) return (*is1 - *is2); } if (*is2 == jr_INT_NULL) return (0); return (-1); /* is1 is shorter, hence it comes before is2 */ } jr_int jr_intstrlen (is) const jr_int *is; { jr_int n; for (n = 0; *is != jr_INT_NULL; is++, n++); return (n); } jr_int jr_intstrbytes (is) const jr_int *is; { jr_int n; for (n = 0; *is != jr_INT_NULL; is++, n++); return ((n + 1) * sizeof(jr_int)); } jr_int jr_intstrhash (is) const jr_int *is; { jr_int len = jr_intstrlen (is), sub = len / 3, val; /* a hashing function derived from Knuth's fundamental algorithms * is not good if the integers are uniformly small (i.e. < 20) */ val = (*is + *(is+sub) + *(is+2*sub) + *(is+len-1)+len) * len; if (val < 0) return (-val); return (val); } jr_int jr_intstrlenhash (is, len) const jr_int *is ; jr_int len; /* a hashing function derived from Knuth's * fundamental algorithms */ { jr_int sub = len / 3, val; len /= sizeof(jr_int); /* len is in bytes, we need the number of ints to avoid * running off the end of is */ sub = len / 3, val = (*is + *(is+sub) + *(is+2*sub) + *(is+len-1)+len) * len; if (val < 0) return (-val); return (val); }
frankjas/libjr
libjr/syscalls/exitstr.c
#define _POSIX_SOURCE 1 #include "ezport.h" #include <sys/wait.h> #include "jr/syscalls.h" char *jr_ExitStatusToString (status_buf, status) char * status_buf; jr_int status; { if (WIFEXITED(status)) { sprintf(status_buf, "exit status: %d", WEXITSTATUS(status)) ; } if (WIFSTOPPED(status)) { sprintf(status_buf, "stop signal: %d", WSTOPSIG(status)) ; } if (WIFSIGNALED(status)) { sprintf(status_buf, "terminated by signal: %d%s", WTERMSIG(status), WIFCORE(status) ? " (core dumped)" : "" ) ; } return status_buf; }
frankjas/libjr
libjr/htable/htabldel.c
#include "project.h" void jr_HTableDeleteIndex (htable, delete_index) jr_HTable * htable; jr_int delete_index; { assert (jr_HTableIsValidIndex (htable, delete_index)); /* * do an assert since deleting an invalid index could create * a htable with weird bucket lists which would cause * error symptoms difficult to backtrack to a bad delete */ jr_HTableDeleteFromBucketList (htable, delete_index); jr_HTableAddToDeleteList (htable, delete_index); jr_HTableHashValue (htable, delete_index) = -1; /* * reset the hash value to indicate the element is deleted. * the hash value is used when deleting from the bucket list */ } void *jr_HTableDeleteElement (htable, el_ptr) jr_HTable * htable; void * el_ptr; { jr_int index; index = jr_HTableFindElementIndex (htable, el_ptr); if (index < 0) { return 0; } jr_HTableDeleteIndex (htable, index); return jr_HTableElementPtr (htable, index); } void *jr_HTableDeletePtrValue (htable, el_ptr) jr_HTable * htable; void * el_ptr; { jr_int index; index = jr_HTableFindPtrValueIndex (htable, el_ptr); if (index < 0) { return 0; } jr_HTableDeleteIndex (htable, index); return jr_HTableKeyPtrValue (htable, index); } void jr_HTableDeleteFromBucketList (htable, delete_index) jr_HTable * htable; jr_int delete_index; { jr_int hash_value; jr_int bucket; jr_int curr_index; jr_int prev_index; if (htable->num_buckets == 0) { return; } hash_value = jr_HTableHashValue (htable, delete_index); /* * need to know the index of the previous * previous element in the bucket list * in order to delete from the bucket list */ bucket = hash_value % htable->num_buckets; curr_index = htable->buckets_array[bucket]; prev_index = curr_index; while (curr_index != -1) { if (curr_index == delete_index) { break; } prev_index = curr_index; curr_index = jr_HTableNextElementIndex (htable, curr_index); } if (prev_index == curr_index) { htable->buckets_array[bucket] = jr_HTableNextElementIndex (htable, curr_index); } else { jr_HTableNextElementIndex (htable, prev_index) = jr_HTableNextElementIndex (htable, curr_index); } } void jr_HTableAddToDeleteList (htable, delete_index) jr_HTable * htable; jr_int delete_index; { jr_HTableNextElementIndex (htable, delete_index) = htable->delete_list; htable->delete_list = delete_index; htable->num_deletes ++; }
frankjas/libjr
libjr/missing/getuid.c
<gh_stars>0 #define _POSIX_SOURCE 1 #include "ezport.h" #ifdef missing_getuid #include <stdio.h> #include <sys/types.h> #include <unistd.h> uid_t getuid() { return(0) ; } #else static void NotCalled () /* define this so ranlib doesn't complain */ { NotCalled (); /* use it so the compiler doesn't complain */ } #endif
frankjas/libjr
include/jr/math.h
<filename>include/jr/math.h #ifndef _jr_math_h__ #define _jr_math_h__ #include "ezport.h" extern double jr_DegreesToRadians PROTO((double degrees)) ; extern double jr_RadiansToDegrees PROTO((double radians)) ; extern double jr_DegreesToRadians PROTO((double degrees)) ; extern double jr_PointAngleInDegrees PROTO(( double x1, double y1, double x2, double y2 )) ; extern double jr_PointAngleInRadians PROTO(( double x1, double y1, double x2, double y2 )) ; extern double jr_PointDistance PROTO(( double x1, double y1, double x2, double y2 )) ; extern jr_int jr_PointQuadrant PROTO((double x, double y)) ; #define jr_InterpolationChange(x, y, num_frames, frame_number) \ (((y) - (x)) * ((frame_number) / (float) (num_frames))) #endif
frankjas/libjr
libjr/jr_malloc/project.h
<filename>libjr/jr_malloc/project.h #ifndef _local_jr_malloc_h #define _local_jr_malloc_h #define _POSIX_C_SOURCE 200809L #include "ezport.h" #include <stdio.h> #include <string.h> #include <stdlib.h> #include <errno.h> #include "jr/error.h" #include "jr/trace.h" #include "jr/htable.h" #include "jr/misc.h" #include "jr/error.h" #include "jr/syscalls.h" #include "jr/apr.h" #include "jr/malloc.h" /***** OverHead Type and Pointer Sizes *****/ #ifdef has_malloc_size # ifdef ostype_linux # define jr_malloc_usable_size_macro(ptr, amt) malloc_usable_size ((void *) ptr) # else # define jr_malloc_usable_size_macro(ptr, amt) malloc_size ((void *) ptr) # endif # define jr_malloc_may_have_slop #else # define jr_malloc_usable_size_macro(ptr, amt) (amt) #endif /******** Trap and Other Diagnostic Support ********/ #define MAX_BOOKKEEPING_MALLOCS 64 #define MAX_MALLOC_BUCKETS 50 /* * the maximum allowed, keep in mind the user can add buckets at will */ #define SUFFIX_BOUNDS_STRING "BND " #define PREFIX_BOUNDS_STRING "PBND" #define FIXED_BOUNDS_MARKER_SIZE 4 /* * the chars BND plus 1 for the null * * 3/23/07: can't be less than the jr_MallocSizeStruct, because: * we use the prefix on bookkeeping pointers to store the size. * Why? Here's the case: * - malloc_calls isn't on, but recording ptrs only * -> bookkeeping pointers are using bounds memory * -> jr_malloc_usable_size() would return junk on bookkeeping pointers * * Note that bookkeeping always uses bounds memory, because when freeing * a bookkeeping pointer we can't look it up to figure out whether it uses * bounds or not, so it needs to be either always there or not. * Note also that bookkeeping pointers don't verify the bounds, so we * can put other information there. * * ToDo: on systems where we don't prepend the size, this will break. * Such systems should generate a syntax error since * jr_malloc_requested_size() will be undefined. */ #define jr_malloc_suffix_marker_char(i) (SUFFIX_BOUNDS_STRING[(i) % 4]) #define jr_malloc_prefix_marker_char(i) (PREFIX_BOUNDS_STRING[(i) % 4]) #define jr_MALLOC_MAX_BOUNDS_MARKER_MULTIPLE 8 /* ** 4/14/07: default is 4 bytes ** multiple of 1 is 8 == 4*2, 2 is 16 == 4*4, 3 is 32, 5 is 128 == 4*32, etc. ** 4*2^1 4*2^2 4*2^5 */ #define jr_malloc_is_suffix_same(v) \ (jr_MallocSuffixBoundsMarkerMultiple != jr_get2power(v)) #define jr_malloc_is_prefix_same(v) \ (jr_MallocPrefixBoundsMarkerMultiple != jr_get2power(v)) #define jr_malloc_set_suffix_multiple(v) \ ((v) > 0 \ ? jr_MallocSuffixBoundsMarkerMultiple = jr_get2power(v) \ : (unsigned jr_int) (v) \ ) #define jr_malloc_set_prefix_multiple(v) \ ((v) > 0 \ ? jr_MallocPrefixBoundsMarkerMultiple = jr_get2power(v) \ : (unsigned jr_int) (v) \ ) #define jr_malloc_prefix_bounds_marker_size() \ (jr_MallocPrefixBoundsMarkerMultiple > 0 \ ? jr_MallocPrefixBoundsMarkerMultiple * FIXED_BOUNDS_MARKER_SIZE \ : FIXED_BOUNDS_MARKER_SIZE \ ) /* * 7/23/2003 Has to be constant, since given a malloc pointer, we need * to be able to find the requested size part, i.e. skip over the prepended * bounds. So the prepended bounds size can't depend on the requested size. */ #define jr_malloc_suffix_slop_divisor() (1) /* ** 4/8/07: if you want to use the requested_size as the bounds marker, ** do the following: ** - set the slop_divisor() to (jr_MallocSuffixBoundsMarkerMultiple + 1) ** - make the suffix_bounds_marker() condition "requested_size" instead of 0 below. ** - set suffix_multiple() to just "1". ** -- could also set to "v" but this will increase total memory usage by that factor ** -- getting a decent prefix bounds (32 bytes) would bump total memory too much ** -- or require programs to set them separately, requiring another trace arg */ #define jr_malloc_suffix_bounds_marker_size(requested_size) \ (jr_MallocSuffixBoundsMarkerMultiple > 0 \ ? jr_MallocSuffixBoundsMarkerMultiple * \ (0 ? requested_size : FIXED_BOUNDS_MARKER_SIZE) \ : FIXED_BOUNDS_MARKER_SIZE \ ) #define jr_DESTRUCTIVE_FREE_STRING "jr_free jr_free jr_free jr_free jr_free " /* * Note the 8 char pattern, which generates regular values * when viewed as an integer or pointer. */ extern void jr_malloc_destroy_data PROTO (( void * mptr, size_t num_bytes )); extern jr_int jr_malloc_record_ptrs_only (); /******** Malloc Pointer State Information ********/ typedef struct { const void * ptr; size_t amt_requested; const void * calling_pc; const void * heap_base_ptr; jr_int occurrence; unsigned is_malloced : 1; unsigned is_bookkeeping : 1; unsigned has_bounds_marker : 1; } jr_MallocPtrInfoStruct; extern void jr_MallocPtrInfoInit PROTO (( jr_MallocPtrInfoStruct * mptr_info, const void * mptr, size_t amt_requested, const void * calling_pc, const void * heap_base_ptr, jr_int is_malloc, jr_int is_bookkeeping, jr_int has_bounds_marker )); extern char * jr_MallocPtrInfoFormatString PROTO (( jr_MallocPtrInfoStruct * ptr_info, char * sbuf, jr_int sbuf_size )); extern void jr_MallocPtrInfoPrint PROTO (( jr_MallocPtrInfoStruct * ptr_info, FILE * wfp )); extern jr_int jr_MallocPtrInfoHash PROTO (( const void * void_arg_1 )); extern jr_int jr_MallocPtrInfoCmp PROTO (( const void * void_arg_1, const void * void_arg_2 )); extern jr_int jr_MallocPtrInfoCheckBounds PROTO (( jr_MallocPtrInfoStruct * ptr_info, char * error_buf )); #define jr_MallocPtrInfoPtr(ptr_info) ((ptr_info)->ptr) #define jr_MallocPtrInfoOccurence(ptr_info) ((ptr_info)->occurrence) #define jr_MallocPtrInfoRequestedSize(ptr_info) ((ptr_info)->amt_requested) #define jr_MallocPtrInfoCallingPC(ptr_info) ((ptr_info)->calling_pc) #define jr_MallocPtrInfoHeapBase(ptr_info) ((ptr_info)->heap_base_ptr) #define jr_MallocPtrInfoIsMalloced(ptr_info) ((ptr_info)->is_malloced) #define jr_MallocPtrInfoIsBookkeeping(ptr_info) ((ptr_info)->is_bookkeeping) #define jr_MallocPtrInfoHasBoundsMarker(ptr_info) ((ptr_info)->has_bounds_marker) #define jr_MallocPtrInfoIsFreed(ptr_info) (! (ptr_info)->is_malloced) #define jr_MallocPtrInfoSetRequestedSize(ptr_info, v) ((ptr_info)->amt_requested = (v)) #define jr_MallocPtrInfoSetCallingPC(ptr_info, v) ((ptr_info)->calling_pc = (v)) #define jr_MallocPtrInfoSetHeapBase(ptr_info, v) ((ptr_info)->heap_base_ptr = (v)) #define jr_MallocPtrInfoSetHasBoundsMarker(ptr_info, v) ((ptr_info)->has_bounds_marker = (v)!= 0) #define jr_MallocPtrInfoMakeMalloced(ptr_info) ((ptr_info)->is_malloced = 1) #define jr_MallocPtrInfoMakeBookkeeping(ptr_info) ((ptr_info)->is_bookkeeping = 1) #define jr_MallocPtrInfoClearMalloced(ptr_info) ((ptr_info)->is_malloced = 0) #define jr_MallocPtrInfoClearBookkeeping(ptr_info) ((ptr_info)->is_bookkeeping = 0) /***** Malloc Stats *****/ typedef struct { jr_int nbuckets; jr_int did_initialization; size_t s_bucket[MAX_MALLOC_BUCKETS+1]; jr_int n_malloc[MAX_MALLOC_BUCKETS+1] ; jr_int n_freedp[MAX_MALLOC_BUCKETS+1] ; jr_int n_maxnum[MAX_MALLOC_BUCKETS+1] ; } jr_MallocStatStruct; extern void jr_MallocStatInit PROTO (( jr_MallocStatStruct * msp )); extern void jr_MallocStatUndo PROTO (( jr_MallocStatStruct * msp )); extern void jr_MallocStatReset PROTO (( jr_MallocStatStruct * msp )); extern void jr_MallocStatPrint PROTO (( FILE * wfp, jr_MallocStatStruct * msp, char * message )) ; extern jr_int jr_MallocStatNumAllocated PROTO (( jr_MallocStatStruct * msp )); extern void jr_MallocStatRecordMalloc PROTO (( jr_MallocStatStruct * msp, void * mptr, unsigned jr_int amt_allocated )) ; extern void jr_MallocStatRecordFree PROTO (( jr_MallocStatStruct * msp, const void * mptr, unsigned jr_int amt_allocated )) ; extern void jr_MallocSetBucketSizes PROTO ((unsigned jr_int *s_bucket)); extern void jr_MallocStatAddBucketSize PROTO (( jr_MallocStatStruct * msp, size_t bucket_size )) ; /***** Bucket Sizes (derived once experimentally) *****/ #define MALLOC_BUCKET_SIZES \ {16,32,64,128,252,340,508,680,1020,1360, 2044,2724,4088,8192,16384,24576,32768, 0} #define jr_MallocStatBucketSize(msp, b) ((msp)->s_bucket[b]) extern void * jr_MallocGetGrandParentPC PROTO ((void)); /******** Malloc Diag Stuff ********/ typedef struct { jr_int did_initialization; jr_int doing_initialization; void * TrapPtr; jr_int TrapOnOccurence; jr_int TrapPtrAmount; jr_int TrapPtrMallocIndexIsBookkeeping; jr_int CurrOccurence; /* * allocation checking fields */ jr_HTable PointerTable[1]; jr_int DoingBookkeeping; jr_int NextBookkeepingIndex; jr_int FirstBookkeepingIndex; jr_int BookkeepingArrayOverflow; jr_MallocPtrInfoStruct BookkeepingArray [MAX_BOOKKEEPING_MALLOCS]; /* * we are using an jr_HTable to store all the bookkeeping info * this data structure grows dynamically, and as such will need * to call jr_malloc while doing bookkeeping. The above * fields keep track off whether we are doing bookkeeping * If we are bookkeeping, then temporarily put the pointers * being jr_malloced for the bookkeeping data structures * in a book keeping array */ void * heap_base_ptr; jr_int * exempt_fd_array; FILE * trace_wfp; unsigned did_trace_file_empty : 1; } jr_MallocDiagStruct; extern void jr_MallocDiagInit PROTO((jr_MallocDiagStruct *mdp)); extern void jr_MallocDiagUndo PROTO((jr_MallocDiagStruct *mdp)); extern void jr_MallocDiagReset PROTO((jr_MallocDiagStruct *mdp)); extern void jr_MallocDiagPrintTrace ( jr_MallocDiagStruct * mdp, jr_MallocPtrInfoStruct * ptr_info); extern void jr_MallocDiagInitExemptDescriptorArray PROTO (( jr_MallocDiagStruct * mdp )); extern jr_int jr_MallocDiagNumOpenFiles PROTO (( jr_MallocDiagStruct * mdp, FILE * wfp, char * error_buf )); extern void jr_MallocDiagDump PROTO((jr_MallocDiagStruct *mdp)); extern const char * jr_MallocDiagPtrType PROTO(( jr_MallocDiagStruct * mdp, const void * ptr )); extern void jr_MallocDiagDoTrap PROTO (( jr_MallocDiagStruct * mdp, const void * mptr, jr_int is_malloc )); extern void jr_MallocDiagRecordInfo PROTO (( jr_MallocDiagStruct * mdp, const void * mptr, size_t amt_requested, jr_int is_malloc, jr_int is_bookkeeping, jr_int is_ptr_only, size_t * amt_ref, jr_int * has_bounds_ref )); #define jr_MallocDiagDoMallocTrap(mdp, mptr) \ jr_MallocDiagDoTrap (mdp, mptr, 1) #define jr_MallocDiagDoFreeTrap(mdp, mptr) \ jr_MallocDiagDoTrap (mdp, mptr, 0) #define jr_MallocDiagRecordMalloc(mdp, mptr, amt, ptr_only) \ jr_MallocDiagRecordInfo (mdp, mptr, amt, 1, 0, ptr_only, 0, 0) #define jr_MallocDiagRecordFree(mdp, mptr, amt_ref, has_bounds_ref) \ jr_MallocDiagRecordInfo (mdp, mptr, 0, 0, 0, 0, amt_ref, has_bounds_ref) extern jr_MallocPtrInfoStruct *jr_MallocDiagFindPtrInfo PROTO (( jr_MallocDiagStruct * mdp, const void * mptr )); extern jr_MallocPtrInfoStruct *jr_MallocDiagNewPtrInfo PROTO (( jr_MallocDiagStruct * mdp, const void * mptr, size_t amt_requested, const void * calling_pc, const void * heap_base_ptr, jr_int is_malloced, jr_int is_bookkeeping, jr_int has_bounds_marker )); extern jr_int jr_MallocDiagCheckLeaksAndBounds PROTO (( jr_MallocDiagStruct * mdp, char * error_buf )); extern jr_int jr_MallocDiagNumLeaks PROTO (( jr_MallocDiagStruct * mdp )); extern void jr_MallocDiagSetSizeRequested PROTO (( jr_MallocDiagStruct * mdp, void * mptr, size_t usable_size )); #define jr_MallocDiagIsDoingBookkeeping(mdp) \ ((mdp)->DoingBookkeeping) #define jr_MallocDiagTrapPtr(mdp) \ ((mdp)->TrapPtr) /******** Malloc Pointer Interface (uses global MallocDiag state) ********/ extern jr_int jr_MallocPtrDoBounds PROTO (( const void * mptr, size_t amt_requested, jr_int for_malloc, char * error_buf )); #define jr_MallocPtrDoBoundsCheck(mptr, amt_requested, error_buf) \ jr_MallocPtrDoBounds (mptr, amt_requested, 0, error_buf) extern void jr_MallocPtrMakeTrapFile PROTO (( const void *pointer, const char *error_mesg )); extern void jr_MallocPtrPrintInfo PROTO ((void *pointer)); extern void jr_MallocPtrDumpPrevPtrInfo PROTO ((void *pointer)); extern size_t jr_MallocPtrSizeRequested PROTO ((void *pointer)); extern jr_int jr_MallocCheckBounds PROTO ((void)); extern jr_int jr_MallocPrintOpenFiles PROTO ((void)); extern void jr_MallocPrintFunctions PROTO ((void)); extern jr_int jr_MallocPtrCheckBounds PROTO ((const void *mptr)); #endif
frankjas/libjr
include/jr/long.h
<reponame>frankjas/libjr<filename>include/jr/long.h #ifndef _long_long_h__ #define _long_long_h__ #include "ezport.h" /* * struct assignment and parameter passing * is allowed by most non-ANSI compilers. * K&R edition 1 even states (pg 209) that * allow forbidden, will probably be allowed * in the future. * * This is good news since it is probably most * practical to use the following types as if * they were built-in numerical types * and to pass them by value. * * It is therefore assumed that normal assignment and * may be used to copy these types. */ /* * the jr_Long is a 64 bit quantity * * Check the word align macros in misc.h for porting * Perhaps they should be written with a 4 hard-wired. */ #ifdef jr_IS_64_BIT /* * This code should be tested before used. */ typedef uint64_t jr_ULong; #define jr_ULongSetMSW(longp, v) (*(longp) = (((jr_ULong) (v) << 32) | *(longp) & 0xffffffffL)) #define jr_ULongSetLSW(longp, v) (*(longp) = (*(longp) & 0xffffffff00000000L) | (v) & 0xffffffff) #define jr_ULongSet(resultp, msw, lsw) \ (*(resultp) = (((jr_ULong) (msw) << 32) | (lsw) & 0xffffffffL)) #define jr_ULongMSW(longv) ((uint32_t) (((longv) & 0xffffffff00000000L) >> 32)) #define jr_ULongLSW(longv) ((uint32_t) ((longv) & 0xffffffffL)) #define jr_ULongAsgnUInt(longp, i) (*(longp) = (unsigned jr_int) (i)) #define jr_ULongAsgn(longp1, long2) (*(longp1) = (long2)) #define jr_ULongAsgnLong(longp1, long2) (*(longp1) = (uint64_t)(long2)) #define jr_ULongAsgnNetULong(resultp, net_long) \ jr_ULongSet(resultp, jr_NetULongMSW (net_long), jr_NetULongLSW (net_long)) #define jr_ULongAsgnZero(longp) jr_ULongAsgnUInt (longp, 0) #define jr_ULongIsUInt(longv) ((longv) <= jr_UINT_MAX) #define jr_ULongEqualsUInt(longv, i) ((longv) == (i)) #define jr_ULongIsZero(longv) ((longv) == 0) #define jr_ULongIsNonZero(longv) ((longv) != 0) #define jr_ULongIsMaxValue(longv) ((longv) == UINT64_MAX) #define jr_ULongAsgnMaxValue(longp) (*(longp) = UINT64_MAX) #define jr_ULongToUInt(longv) ((unsigned jr_int) (longv)) #define jr_ULongToHost(longv) ((uint64_t) (longv)) #define jr_ULongAsgnHost(longp, o) (*(longp) = (o)) #define jr_ULongToFloat(longv) ((float) (longv)) #define jr_ULongAsgnFloat(longp, v) (*(longp) = (v)) #define jr_ULongAdd(result, long1, long2) (*(result) = (long1) + (long2)) #define jr_ULongSubtract(result, long1, long2) (*(result) = (long1) - (long2)) #define jr_ULongAddUInt(result, long1, uint_v) (*(result) = (long1) + (uint_v)) #define jr_ULongSubtractUInt(result, long1, uint_v) (*(result) = (long1) - (uint_v)) #define jr_ULongModUInt(long1, uint_v) ((uint32_t)((long1) % (uint32_t)(uint_v))) #define jr_ULongDivideUInt(result, long1, uint_v) (*(result) = (long1) / (uint_v)) #define jr_ULongMultUInt(result, long1, uint_v) (*(result) = (long1) * (uint_v)) #define jr_ULongShiftInt(result, long1, int_v) ((int_v) > 0 \ ? (*(result) = (long1) >> (int_v)) \ : (*(result) = (long1) << -(int_v))) #define jr_ULongAsgn64(longp1, long2) jr_ULongAsgn (longp1, long2) #define jr_ULongToHost64(longv) (longv) #else /* * long is 32 bits */ typedef struct { unsigned jr_int u_msw; unsigned jr_int u_lsw; } jr_ULong; #define jr_ULongSetMSW(longp, v) ((longp)->u_msw = (v)) #define jr_ULongSetLSW(longp, v) ((longp)->u_lsw = (v)) #define jr_ULongSet(resultp, msw, lsw) \ ((resultp)->u_msw = (msw), (resultp)->u_lsw = (lsw)) #define jr_ULongMSW(longv) ((longv).u_msw) #define jr_ULongLSW(longv) ((longv).u_lsw) #define jr_ULongAsgnUInt(longp, i) ((longp)->u_msw = 0, (longp)->u_lsw = (i)) #define jr_ULongAsgn(longp1, longv2) \ ( \ jr_ULongSetMSW (longp1, jr_ULongMSW (longv2)), \ jr_ULongSetLSW (longp1, jr_ULongLSW (longv2)) \ ) #define jr_ULongAsgnLong(longp1, longv2) \ ( \ jr_ULongSetMSW (longp1, jr_LongMSW (longv2)), \ jr_ULongSetLSW (longp1, jr_LongLSW (longv2)) \ ) #define jr_ULongAsgnNetULong(longp, net_long) \ ( \ jr_ULongSetMSW (longp, jr_NetULongMSW (net_long)), \ jr_ULongSetLSW (longp, jr_NetULongLSW (net_long)) \ ) /* ** 1/1/07: ToDo: technically this shouldn't be necessary, ** since if there are 64 bit integers, the other jr_ULong implementation should be used. */ #define jr_ULongAsgn64(longp, v) ( (longp)->u_msw = (v) >> 32, \ (longp)->u_lsw = (v) & 0xffffffffL \ ) #define jr_ULongToHost64(longv) (((long long) jr_ULongMSW (longv) << 32) \ | (long long) jr_ULongLSW (longv)) #define jr_ULongIsUInt(longv) (jr_ULongMSW (longv) == 0) #define jr_ULongEqualsUInt(longv, i) (jr_ULongIsUInt (longv) && (longv).u_lsw == (i)) #define jr_ULongIsZero(longv) jr_ULongEqualsUInt(longv, 0) #define jr_ULongIsNonZero(longv) (! jr_ULongIsZero (longv)) #define jr_ULongIsMaxValue(longv) \ (jr_ULongMSW (longv) == jr_UINT_MAX && jr_ULongLSW (longv) == jr_UINT_MAX) #define jr_ULongAsgnMaxValue(longp) \ (jr_ULongSetMSW (longp, jr_UINT_MAX), jr_ULongSetLSW (longp, jr_UINT_MAX)) #define jr_ULongToUInt(longv) (jr_ULongLSW (longv)) #define jr_ULongToHost(longv) (jr_ULongLSW (longv)) #define jr_ULongAsgnHost(longp, o) jr_ULongAsgnUInt (longp, o) #define jr_ULongAdd(result, long1, long2) \ ( \ jr_ULongAddUInt (result, long1, (long2).u_lsw), \ (result)->u_msw += (long2).u_msw \ ) #define jr_ULongSubtract(result, long1, long2) \ ( \ jr_ULongSubtractUInt (result, long1, (long2).u_lsw), \ (result)->u_msw -= (long2).u_msw \ ) extern void jr_ULongAddUInt PROTO (( jr_ULong * result, jr_ULong long1, unsigned jr_int mod_value )); extern void jr_ULongSubtractUInt PROTO (( jr_ULong * result, jr_ULong long1, unsigned jr_int mod_value )); extern void jr_ULongShiftInt PROTO (( jr_ULong * result, jr_ULong long1, jr_int shift_value )); extern jr_int jr_ULongModUInt PROTO (( jr_ULong long1, unsigned jr_int mod_value )); extern void jr_ULongDivideUInt PROTO (( jr_ULong * result_ptr, jr_ULong long1, unsigned jr_int div_value )); extern void jr_ULongMultUInt PROTO (( jr_ULong * result_ptr, jr_ULong long1, unsigned jr_int div_value )); extern void jr_ULongAsgnUIntMult PROTO (( jr_ULong * result_ptr, unsigned jr_int u, unsigned jr_int v )); /* * jr_ULongMult() doesn't make sense, because if both values > 2^32, * the the result won't fit in a jr_ULong */ extern double jr_ULongToFloat PROTO (( jr_ULong ulong_value )); extern void jr_ULongAsgnFloat PROTO (( jr_ULong * ulong_value_ptr, double float_value )); #endif extern jr_int jr_ULongCmp PROTO (( jr_ULong long1, jr_ULong long2 )); extern jr_int jr_ULongCmpUInt PROTO (( jr_ULong long1, unsigned jr_int uint_value )); #ifdef jr_IS_64_BIT /* * This code should be tested before used. */ typedef int64_t jr_Long; extern void jr_LongSetMSW( jr_Long * longp, jr_int value); extern void jr_LongSetLSW( jr_Long * longp, jr_int value); #define jr_LongMSW(longv) ((int32_t)(((longv) & 0xffffffff00000000L) >> 32)) #define jr_LongLSW(longv) ((int32_t)((longv) & 0xffffffff)) #define jr_LongAsgnInt(longp, i) (*(longp) = (i)) #define jr_LongAsgn(longp1, long2) (*(longp1) = (long2)) #define jr_LongAsgnULong(longp1, ulong2) (*(longp1) = (ulong2)) #define jr_LongAsgnNetLong(resultp, net_long) \ (jr_NetLongMSW (net_long) == 0 \ ? (*(resultp) = jr_NetLongLSW (net_long)) \ : ( \ *(resultp) = jr_NetLongLSW (net_long), \ jr_LongSetMSW (resultp, jr_NetLongMSW (net_long)),0 \ ) \ ) /* * If the msw == 0, then the lsw may be negative. A regular assignment * takes care of the sign extension. * In the case msw !=, the lsw is not negative. Use regular assignment * first, which is cheaper the the SetLSW macro, and then OR in the msw */ #define jr_LongIsInt(longv) ((longv) < jr_INT_MAX) #define jr_LongEqualsInt(longv, i) ((longv) == (i)) #define jr_LongIsZero(longv) ((longv) == 0) #define jr_LongIsNonZero(longv) ((longv) != 0) #define jr_LongIsPositive(longv) ((longv) >= 0) #define jr_LongIsNegative(longv) ((longv) < 0) #define jr_LongIsMaxValue(longv) ((longv) == LONG_MAX) #define jr_LongAsgnMaxValue(longp) (*(longp) = LONG_MAX) #define jr_LongToHost(longv) (longv) #define jr_LongAsgnHost(longp, v) (*(longp) = v) #define jr_LongAsgnAbsValue(longp, longv) ((longv) < 0 \ ? (*(longp) = -(longv)) \ : (*(longp) = (longv))) #define jr_LongAdd(result, long1, long2) (*(result) = (long1) + (long2)) #define jr_LongSubtract(result, long1, long2) (*(result) = (long1) - (long2)) #define jr_LongAddInt(result, long1, uint_v) (*(result) = (long1) + (uint_v)) #define jr_LongSubtractInt(result, long1, uint_v) (*(result) = (long1) - (uint_v)) #define jr_LongShiftInt(result, long1, int_v) ((int_v) > 0 \ ? *(result) = (long1) >> (int_v) \ : *(result) = (long1) << -(int_v)) #else typedef struct { jr_int msw; jr_int lsw; } jr_Long; /* * We need to use a sign bit in each 32 bit quantity * in order to store the numbers -1 - -LONG_MIN * * the lsw will only be < 0 if msw == 0 */ /* ** 5-15-2018: MSW, LSW should only be used for debugging with signed longs. ** It's not well defined wrt all combinations of signed/unsigned values, set in any order ** for native 64 bit implementations. */ #define jr_LongSetMSW(longp, v) ((longp)->msw = (v)) #define jr_LongSetLSW(longp, v) ((longp)->lsw = (v)) #define jr_LongMSW(longv) ((longv).msw) #define jr_LongLSW(longv) ((longv).lsw) #define jr_LongAsgn(long1, long2) ((long1)->msw = (long2).msw, (long1)->lsw = (long2).lsw) #define jr_LongAsgnInt(longp, i) ((longp)->msw = 0, (longp)->lsw = (i)) #define jr_LongAsgnULong(long1, ulong2) \ ((long1)->msw = (ulong2).u_msw, (long1)->lsw = (ulong2).u_lsw) #define jr_LongAsgnNetLong(result, net_long) \ ( \ jr_LongSetMSW (result, jr_NetLongMSW (net_long)), \ jr_LongSetLSW (result, jr_NetLongLSW (net_long)) \ ) \ #define jr_LongAsgnZero(longp) jr_LongAsgnInt (longp, 0) #define jr_LongIsInt(longv) ((longv).msw == 0) #define jr_LongEqualsInt(longv, i) (jr_LongIsInt (longv) && (longv).lsw == (i)) #define jr_LongIsZero(longv) jr_LongEqualsInt(longv, 0) #define jr_LongIsNonZero(longv) (! jr_LongIsZero (longv)) #define jr_LongIsPositive(longv) (! jr_LongIsNegative (longv)) #define jr_LongIsNegative(longv) ((longv).msw < 0 || (longv).lsw < 0) /* * the lsw will only be < 0 if msw == 0 */ #define jr_LongIsMaxValue(longv) ((longv).msw == jr_INT_MAX && (longv).lsw == jr_INT_MAX) #define jr_LongAsgnMaxValue(longp) ((longp)->msw = jr_INT_MAX, (longp)->lsw = jr_INT_MAX) #define jr_LongIsMinValue(longv) ((longv).msw == jr_INT_MIN && (longv).lsw == jr_INT_MAX) #define jr_LongAsgnMinValue(longp) ((longp)->msw = jr_INT_MIN, (longp)->lsw = jr_INT_MAX) #define jr_LongToHost(longv) (jr_LongLSW (longv)) #define jr_LongAsgnHost(longp, v) jr_LongAsgnInt (longp, v) #define jr_LongCmpIntMacro(long1, i) \ ( \ (long1).msw ? \ (long1).msw : \ (long1).lsw - (i) \ ) extern jr_int jr_LongCmpInt PROTO ((const jr_Long * long1, long int_value)); extern jr_int jr_LongCmpRev PROTO ((const jr_Long * long1, const jr_Long * long2)); extern void jr_LongAddInt PROTO (( jr_Long * result, jr_Long long1, jr_int int_value )); #define jr_LongSubtractInt(result, long1, int_value) \ jr_LongAddInt (result, long1, -(int_value)) extern void jr_LongAdd PROTO (( jr_Long * result, jr_Long long1, jr_Long long2 )); extern void jr_LongSubtract PROTO (( jr_Long * result, jr_Long long1, jr_Long long2 )); extern jr_int jr_LongModUInt PROTO (( jr_Long long1, jr_int mod_value )); extern void jr_LongAsgnAbsValue PROTO (( jr_Long * result_ptr, jr_Long long1 )); extern void jr_LongDivideUInt PROTO (( jr_Long * result_ptr, jr_Long long1, jr_int div_value )); extern void jr_LongMultUInt PROTO (( jr_Long * result_ptr, jr_Long long1, jr_int div_value )); extern void jr_LongAsgnUIntMult PROTO (( jr_Long * result_ptr, jr_int u, jr_int v )); #endif extern jr_int jr_LongCmp PROTO ((const jr_Long long1, const jr_Long long2)); extern jr_int jr_LongPtrCmp PROTO ((const void * long1, const void * long2)); #define jr_ULONG_BASE32_STRING_LENGTH 30 /* ** 4/15/08: every 5 bits is 1 char, 64 bits yields 13 chars */ extern jr_int jr_ULongPtrCmp PROTO (( const void * void_arg_1, const void * void_arg_2 )); extern jr_int jr_ULongPtrHash PROTO (( const void * void_arg_1 )); extern char * jr_ULongToBase32String PROTO (( jr_ULong ulong_value, char * number_string, jr_int use_lower_case )); extern jr_int jr_ULongInitFromBase32String PROTO (( jr_ULong * ulong_ptr, const char * number_string, char * error_buf )); #define jr_ULongMaskedLSW(ulong, mask) \ (jr_ULongLSW (ulong) & (mask)) #define jr_ULongMaskedMSW(ulong, mask) \ (jr_ULongMSW (ulong) & (mask)) #define jr_ULongSetMaskedLSW(ulongp, mask, v) \ jr_ULongSetLSW ( \ ulongp, ((jr_ULongLSW (*(ulongp)) & ~(mask)) | ((v) & (mask))) \ ) #define jr_ULongSetMaskedMSW(ulongp, mask, v) \ jr_ULongSetMSW ( \ ulongp, ((jr_ULongMSW (*(ulongp)) & ~(mask)) | ((v) & (mask))) \ ) #endif
frankjas/libjr
libjr/string/ctltoesc.c
#include "ezport.h" #include <stdio.h> #include <string.h> #include "jr/string.h" /* * memmove takes care of overlapping copies */ void jr_CopyControlCharsToEscapedChars(target, bounds_arg, source) char * target ; jr_int bounds_arg ; const char * source ; { const char * escape_string ; jr_int escape_length ; jr_int target_index ; jr_int source_index ; jr_int bounds ; bounds = bounds_arg - 1 ; for ( target_index = 0, source_index = 0 ; target_index < bounds; target_index += escape_length, source_index++ ) { if (source[source_index] == 0) break ; escape_length = 2 ; switch(source[source_index]) { case '\a': escape_string = "\\a" ; break ; case '\b': escape_string = "\\b" ; break ; case '\f': escape_string = "\\f" ; break ; case '\n': escape_string = "\\n" ; break ; case '\r': escape_string = "\\r" ; break ; case '\t': escape_string = "\\t" ; break ; case '\v': escape_string = "\\v" ; break ; default : { escape_string = jr_StringFromControlChar(source[source_index]) ; if (escape_string[1] != 0) { escape_length = (jr_int) strlen(escape_string) ; } else { escape_length = 1 ; } break ; } } if ((target_index + escape_length) > bounds) break ; strcpy(target+target_index, escape_string) ; } target[target_index] = 0 ; } void jr_ControlCharsToEscapedChars(str) char * str ; { char * f = str ; for(; *f; f++) { switch(*f) { case '\a': memmove(f+2, f+1, strlen(f+1) + 1) ; *f++ = '\\' ; *f = 'a'; break ; case '\b': memmove(f+2, f+1, strlen(f+1) + 1) ; *f++ = '\\' ; *f = 'b'; break ; case '\f': memmove(f+2, f+1, strlen(f+1) + 1) ; *f++ = '\\' ; *f = 'f'; break ; case '\n': memmove(f+2, f+1, strlen(f+1) + 1) ; *f++ = '\\' ; *f = 'n'; break ; case '\r': memmove(f+2, f+1, strlen(f+1) + 1) ; *f++ = '\\' ; *f = 'r'; break ; case '\t': memmove(f+2, f+1, strlen(f+1) + 1) ; *f++ = '\\' ; *f = 't'; break ; case '\v': memmove(f+2, f+1, strlen(f+1) + 1) ; *f++ = '\\' ; *f = 'v'; break ; default : { if (*f < ' ') { char buf[128] ; memmove(f+4, f+1, strlen(f+1) + 1) ; sprintf(buf, "\\%03o", *f) ; *f++ = buf[0] ; *f++ = buf[1]; *f++ = buf[2] ; *f = buf[3] ; } break ; } } } } /* void main() { char result[128] ; char * original = "\f\fline 1\012hello 12345 there 6" ; strcpy(result, original) ; jr_ControlCharsToEscapedChars(result) ; fprintf(stdout, "jr_ControlCharsToEscapedChars() == '%s'\n", result ) ; jr_CopyControlCharsToEscapedChars(result, sizeof(result), original) ; fprintf(stdout, "jr_CopyControlCharsToEscapedChars(%#010x, %d, \"%s\") == '%s'\n", result, sizeof(result), original, result ) ; } */
frankjas/libjr
libjr/struct/jr_ulong.c
#include "ezport.h" #include <assert.h> #include <ctype.h> #include <stdio.h> #include "jr/long.h" #include "jr/error.h" #ifdef jr_IS_64_BIT jr_int jr_ULongCmp (long1, long2) jr_ULong long1; jr_ULong long2; { if (long1 > long2) { return (1); } if (long1 < long2) { return (-1); } return (0); } jr_int jr_ULongCmpUInt (long1, uint_value) jr_ULong long1; unsigned jr_int uint_value; { if (long1 > uint_value) { return (1); } if (long1 < uint_value) { return (-1); } return (0); } jr_int jr_ULongPtrCmp (void_arg_1, void_arg_2) const void * void_arg_1; const void * void_arg_2; { const jr_ULong * long1 = void_arg_1; const jr_ULong * long2 = void_arg_2; if (*long1 > *long2) { return 1; } if (*long1 < *long2) { return -1; } return 0; } jr_int jr_ULongPtrHash (void_arg_1) const void * void_arg_1; { const jr_ULong * long_ptr = void_arg_1; jr_int hash_value = 0; hash_value += (*long_ptr & ((uint64_t) 0xffffffff << 32)) >> 32; hash_value += *long_ptr & 0xffffffff; return hash_value; } #else void jr_ULongAddUInt (result, long1, uint_value) jr_ULong * result; jr_ULong long1; unsigned jr_int uint_value; { /* * In the following, if the lsw + u > jr_UINT_MAX * then a carry should occur into the msw * * u + lsw == u + lsw + jr_UINT_MAX - jr_UINT_MAX + 1 - 1 * * == jr_UINT_MAX + 1 + u + lsw - jr_UINT_MAX - 1 * * == <carry into msw> + u - (jr_UINT_MAX - lsw) - 1 * * Note the reorganisation of the order of evaluation to avoid * any overflows */ if ((uint_value) > jr_UINT_MAX - jr_ULongLSW (long1)) { jr_ULongSetMSW (result, jr_ULongMSW (long1) + 1); jr_ULongSetLSW (result, uint_value - (jr_UINT_MAX - jr_ULongLSW (long1)) - 1); } else { jr_ULongSetMSW (result, jr_ULongMSW (long1)); jr_ULongSetLSW (result, jr_ULongLSW (long1) + uint_value); } } void jr_ULongSubtractUInt (result, long1, uint_value) jr_ULong * result; jr_ULong long1; unsigned jr_int uint_value; { if ((uint_value) > jr_ULongLSW (long1)) { jr_ULongSetMSW (result, jr_ULongMSW (long1) - 1); jr_ULongSetLSW (result, jr_UINT_MAX - uint_value + 1 + jr_ULongLSW (long1)); } else { jr_ULongSetMSW (result, jr_ULongMSW (long1)); jr_ULongSetLSW (result, jr_ULongLSW (long1) - uint_value); } } void jr_ULongShiftInt (result, long1, shift_value) jr_ULong * result; jr_ULong long1; jr_int shift_value; { jr_int i; jr_int mask; jr_int right_shift; jr_int left_shift; unsigned jr_int msw; /* need to be unsigned */ unsigned jr_int msw_bits; /* otherwise shift does sign extension */ unsigned jr_int lsw; unsigned jr_int lsw_bits; right_shift = 0; left_shift = 0; if (shift_value > 0) { right_shift = 1; } if (shift_value < 0) { shift_value = -shift_value; left_shift = 1; } if (shift_value >= 64) { jr_ULongAsgnUInt (result, 0); return; } if (shift_value >= 32) { if (right_shift) { jr_ULongSetLSW (result, jr_ULongMSW (long1) >> (shift_value - 32)); jr_ULongSetMSW (result, 0); } else { jr_ULongSetMSW (result, jr_ULongLSW (long1) << (shift_value - 32)); jr_ULongSetLSW (result, 0); } return; } for (mask=1, i=0; i < shift_value; i++) { mask *= 2; } mask --; if (right_shift) { msw_bits = jr_ULongMSW (long1) & mask; lsw = jr_ULongLSW (long1) >> shift_value; lsw |= msw_bits << (sizeof (long) * CHAR_BIT - shift_value); jr_ULongSetMSW (result, jr_ULongMSW (long1) >> shift_value); jr_ULongSetLSW (result, lsw); } if (left_shift) { mask <<= sizeof (long) * CHAR_BIT - shift_value; lsw_bits = jr_ULongLSW (long1) & mask; msw = jr_ULongMSW (long1) << shift_value; msw |= lsw_bits >> (sizeof (long) * CHAR_BIT - shift_value); jr_ULongSetMSW (result, msw); jr_ULongSetLSW (result, jr_ULongLSW (long1) << shift_value); } } jr_int jr_ULongModUInt (long1, mod_value) jr_ULong long1; unsigned jr_int mod_value; { /* * a long value == 2^32*msw + lsw * == (2^32 - 1 + 1)*msw + lsw * == (2^32 - 1)*msw + msw + lsw * so, * * jr_long % m == ((2^32 - 1)*msw + msw + lsw) % m * == [((2^32 - 1)%m) * (msw%m) + msw%m + lsw%m ] % m * == [ rem1 * rem2 + rem2 + rem3 ] % m */ unsigned jr_int rem1; unsigned jr_int rem2; unsigned jr_int rem3; jr_ULong tmp_ulong; rem1 = jr_UINT_MAX % mod_value; rem2 = jr_ULongMSW (long1) % mod_value; rem3 = jr_ULongLSW (long1) % mod_value; jr_ULongAsgnUInt (&tmp_ulong, rem1 * rem2); jr_ULongAddUInt (&tmp_ulong, tmp_ulong, rem2); jr_ULongAddUInt (&tmp_ulong, tmp_ulong, rem3); assert (jr_ULongIsUInt (tmp_ulong)); return jr_ULongToHost (tmp_ulong) % mod_value; } void jr_ULongDivideUInt (result_ptr, long1, div_value) jr_ULong * result_ptr; jr_ULong long1; unsigned jr_int div_value; { /* * jr_long == 2^32*msw + lsw * * Let: * q1 == msw/d * r1 == msw%d * q2 == lsw/d * r2 == lsw%d * * where / stands for integer division * * msw == q1*d + r1 * lsw == q2*d + r2 * * * jr_long == 2^32*msw + lsw * == 2^32*(q1*d + r1) + q2*d + r2 * == 2^32*q1*d + 2^32*r1 + q2*d + r2 * * Note that (d * k) / d == k * and that (d * k + m) / d == k + m/d * * where / is integer division. * * So jr_long after division by d equals: * * A) == 2^32*q1 + q2 + (2^32*r1 + r2)/d * * Note: * * 2^32*r1 == (2^32 - 1)*r1 + r1 * * Note further: * * (2^32 - 1)*r1 == [d*((2^32 - 1)/d) + ((2^32 - 1)%d)] * r1 * == d*((2^32 - 1)/d)*r1 + ((2^32 - 1)%d)*r1 * == d*q3*r1 + r3*r1 * * Where q3 == (2^32 - 1)/d * r3 == (2^32 - 1)%d (which is < d) * * So, * * 2^32*r1 == (2^32 - 1)*r1 + r1 * == d*q3*r1 + r3*r1 + r1 * * Substituting in into A: * * B) == 2^32*q1 + q2 + (d*q3*r1 + r3*r1 + r1 + r2) / d * == 2^32*q1 + q2 + q3*r1 + (r3*r1 + r1 + r2) / d * Alternatively, == 2^32*q1 + q2 + q3*r1 + (r1*(r3 + 1) + r2) / d * * Note that: * q3*r1 < (2^32/d)*d == 2^32 * Since * r1 < d * q3 <= 2^32/d * * But also note that r1*(r3 + 1) + r2 may be greater than 2^32. * Or in other words, r1*(r3 + 1) may be greater than 2^32 - r2 * Or (r3 + 1) may be greater than (2^32 - r2) / r1 */ unsigned jr_int q1 = jr_ULongMSW (long1) / div_value; unsigned jr_int r1 = jr_ULongMSW (long1) % div_value; unsigned jr_int q2 = jr_ULongLSW (long1) / div_value; unsigned jr_int r2 = jr_ULongLSW (long1) % div_value; unsigned jr_int q3 = jr_UINT_MAX / div_value; unsigned jr_int r3 = jr_UINT_MAX % div_value; jr_ULongSetMSW (result_ptr, q1); jr_ULongSetLSW (result_ptr, q2); jr_ULongAddUInt (result_ptr, *result_ptr, q3 * r1); if (r1 && r3 && (r3 + 1) > (jr_UINT_MAX - r2) / r1) { jr_ULong tmp1; jr_ULongAsgnUIntMult (&tmp1, r1, r3 + 1); jr_ULongAddUInt (&tmp1, tmp1, r2); jr_ULongDivideUInt (&tmp1, tmp1, div_value); /* * tmp1 < long1, so with each recursive call, msw will decrease, * eventually to 0, which will make r1 0 */ jr_ULongAdd (result_ptr, *result_ptr, tmp1); } else { jr_ULongAddUInt (result_ptr, *result_ptr, (r1*(r3 + 1) + r2) / div_value); } } void jr_ULongMultUInt (result_ptr, long_val, mult_value) jr_ULong * result_ptr; jr_ULong long_val; unsigned jr_int mult_value; { /* * jr_long == (2^32*msw + lsw) * jr_long * x == (2^32*msw + lsw) * x * * == 2^32*msw*x + lsw*x * * both x*msw and x*lsw may be greater than 2^32 * */ jr_ULong tmp1; jr_ULongAsgnUIntMult (result_ptr, jr_ULongMSW (long_val), mult_value); jr_ULongShiftInt (result_ptr, *result_ptr, -32); jr_ULongAsgnUIntMult (&tmp1, jr_ULongLSW (long_val), mult_value); jr_ULongAdd (result_ptr, *result_ptr, tmp1); } void jr_ULongAsgnUIntMult (result_ptr, u, v) jr_ULong * result_ptr; unsigned jr_int u; unsigned jr_int v; { /* * The following definitions are used below, where / is integer division: * * q1 == u / 64k * q2 == v / 64k * r1 == u % 64k * r2 == v % 64k * * Each of q1, q2, r1, and r2 are < 64k because: * * 2^32 > u * 2^32/64k > u/64k * 64k > u/64k * * u == 64k * q1 + r1 * v == 64k * q2 + r2 * * u * v == (64k*q1 + r1) * (64k*q2 + r2) * == 64k*q1*64k*q2 + 64k*q1*r2 + r1*64k*q2 + r1*r2 * == 64k*64k*q1*q2 + 64k*q1*r2 + 64k*r1*q2 + r1*r2 * == 2^32 * val1 + 64k* val2 + 64k* val3 + val4 * * Since q1 and q2 are < 64k, then val1 < 2^32, * as are all the other 'val' terms. * */ unsigned jr_int q1 = u / (64 * 1024); unsigned jr_int r1 = u % (64 * 1024); unsigned jr_int q2 = v / (64 * 1024); unsigned jr_int r2 = v % (64 * 1024); unsigned jr_int val1 = q1 * q2; unsigned jr_int val2 = q1 * r2; unsigned jr_int val3 = r1 * q2; unsigned jr_int val4 = r2 * r1; jr_ULong tmp1; jr_ULongSetMSW (result_ptr, val1); jr_ULongSetLSW (result_ptr, 0); jr_ULongAsgnUInt (&tmp1, val2); jr_ULongShiftInt (&tmp1, tmp1, -16); jr_ULongAdd (result_ptr, *result_ptr, tmp1); jr_ULongAsgnUInt (&tmp1, val3); jr_ULongShiftInt (&tmp1, tmp1, -16); jr_ULongAdd (result_ptr, *result_ptr, tmp1); jr_ULongAddUInt (result_ptr, *result_ptr, val4); } void jr_ULongDivide (result_ptr, long1, long2) jr_ULong * result_ptr; jr_ULong long1; jr_ULong long2; { /* * long1 == 2^32*msw1 + lsw1 * long2 == 2^32*msw2 + lsw2 * long1/long2 == (2^32*msw1 + lsw1) / (2^32*msw2 + lsw2) * == 2^32*msw1 / (2^32*msw2 + lsw2) + lsw1 / (2^32*msw2 + lsw2) * == */ } double jr_ULongToFloat (ulong_value) jr_ULong ulong_value; { double float_value; jr_int i; float_value = jr_ULongMSW (ulong_value); if (float_value != 0) { for (i = 0; i < (jr_int) sizeof (long) * CHAR_BIT; i++) { float_value *= 2; } } float_value += jr_ULongLSW (ulong_value); return float_value; } void jr_ULongAsgnFloat (ulong_value_ptr, float_value) jr_ULong * ulong_value_ptr; double float_value; { double high_order; high_order = (double) float_value / jr_INT_MAX; jr_ULongSetMSW (ulong_value_ptr, high_order); jr_ULongSetLSW (ulong_value_ptr, float_value - (high_order * jr_INT_MAX)); } jr_int jr_ULongCmp (long1, long2) jr_ULong long1; jr_ULong long2; { if (long1.u_msw < long2.u_msw) { return (-1); } if (long1.u_msw > long2.u_msw) { return (1); } if (long1.u_lsw < long2.u_lsw) { return (-1); } if (long1.u_lsw > long2.u_lsw) { return (1); } return (0); } jr_int jr_ULongCmpUInt (long1, uint_value) jr_ULong long1; unsigned jr_int uint_value; { if (!jr_ULongIsUInt (long1)) { return (1); } if (long1.u_lsw > uint_value) { return (1); } if (long1.u_lsw < uint_value) { return (-1); } return (0); } jr_int jr_ULongPtrCmp (void_arg_1, void_arg_2) const void * void_arg_1; const void * void_arg_2; { const jr_ULong * long1 = void_arg_1; const jr_ULong * long2 = void_arg_2; if (long1->u_msw < long2->u_msw) { return (-1); } if (long1->u_msw > long2->u_msw) { return (1); } if (long1->u_lsw < long2->u_lsw) { return (-1); } if (long1->u_lsw > long2->u_lsw) { return (1); } return (0); } jr_int jr_ULongPtrHash (void_arg_1) const void * void_arg_1; { const jr_ULong * long_ptr = void_arg_1; jr_int hash_value = 0; hash_value += jr_ULongMSW (*long_ptr); hash_value += jr_ULongLSW (*long_ptr); return hash_value; } #endif char *jr_ULongToBase32String (ulong_value, number_string, use_lower_case) jr_ULong ulong_value; char * number_string; jr_int use_lower_case; { char tmp_buf [32]; jr_int i = 0; jr_int remainder; jr_int num_digits; do { remainder = jr_ULongLSW (ulong_value) & 0x1f; if (remainder < 10) { tmp_buf[i++] = '0' + remainder; } else if (use_lower_case) { tmp_buf[i++] = 'a' + remainder - 10; } else { tmp_buf[i++] = 'A' + remainder - 10; } jr_ULongShiftInt (&ulong_value, ulong_value, 5); } while (jr_ULongIsNonZero (ulong_value)); num_digits = i; for (i=0; i < num_digits; i++) { number_string[i] = tmp_buf [num_digits - 1 - i]; } number_string [i] = 0; return number_string; } jr_int jr_ULongInitFromBase32String (ulong_ptr, number_string, error_buf) jr_ULong * ulong_ptr; const char * number_string; char * error_buf; { jr_int i; jr_int c; jr_int n; jr_ULong curr_ulong; jr_ULong tmp_ulong; jr_ULong max_base; jr_ULongAsgnMaxValue (&max_base); jr_ULongShiftInt (&max_base, max_base, 5); jr_ULongAsgnUInt (&curr_ulong, 0); for (i=0; number_string[i]; i++) { c = number_string [i]; if (isdigit (c)) { n = c - '0'; } else if (isupper (c)) { n = 10 + c - 'A'; } else if (islower (c)) { n = 10 + c - 'a'; } else { jr_esprintf (error_buf, "bad id digit '%c'", c); return -1; } if (jr_ULongCmp (curr_ulong, max_base) > 0) { jr_esprintf (error_buf, "id overflow"); return -1; } jr_ULongShiftInt (&curr_ulong, curr_ulong, -5); jr_ULongAsgnMaxValue (&tmp_ulong); jr_ULongSubtractUInt (&tmp_ulong, tmp_ulong, n); if (jr_ULongCmp (curr_ulong, tmp_ulong) > 0) { jr_esprintf (error_buf, "id overflow"); return -1; } jr_ULongAddUInt (&curr_ulong, curr_ulong, n); } jr_ULongAsgn (ulong_ptr, curr_ulong); return 0; }
frankjas/libjr
libjr/syscalls/isdir.c
#include "ezport.h" #include "jr/syscalls.h" #include "jr/apr.h" jr_int jr_PathIsDirectory(pathname, error_buf) const char * pathname ; char * error_buf; { struct jr_stat stat_buf[1]; jr_int status; jr_int is_dir; status = jr_stat(pathname, stat_buf, error_buf); if (status != 0) { return status; } is_dir = jr_stat_is_directory (stat_buf); return(is_dir) ; } jr_int jr_PathIsFile(pathname, error_buf) const char * pathname ; char * error_buf; { struct jr_stat stat_buf[1]; jr_int status; jr_int is_file; status = jr_stat(pathname, stat_buf, error_buf); if (status != 0) { return status; } is_file = jr_stat_is_file (stat_buf); return(is_file) ; } jr_int jr_PathIsLink(pathname, error_buf) const char * pathname ; char * error_buf; { struct jr_stat stat_buf[1]; jr_int status; jr_int is_link; status = jr_lstat(pathname, stat_buf, error_buf); if (status != 0) { return status; } is_link = jr_stat_is_link (stat_buf); return(is_link) ; }
frankjas/libjr
libjr/missing/waitpid.c
<reponame>frankjas/libjr #define _POSIX_SOURCE 1 #include "ezport.h" #ifdef missing_waitpid #include <sys/types.h> #include <sys/wait.h> #include <sys/resource.h> extern int wait4 PROTO (( int pid, union wait * statusp, int options, struct rusage * rusage )); pid_t waitpid(pid, statusp, options) int pid ; int * statusp ; int options ; { if (pid == -1) { pid = 0 ; } return wait4(pid, (union wait *) statusp, options, 0) ; } #else static void NotCalled () /* define this so ranlib doesn't complain */ { NotCalled (); /* use it so the compiler doesn't complain */ } #endif
frankjas/libjr
libjr/syscalls/pathabs.c
#define _POSIX_SOURCE 1 #include "ezport.h" #include <string.h> #include <unistd.h> #include "jr/syscalls.h" #include "jr/string.h" #include "jr/error.h" jr_int jr_FileNameToAbsolutePath(result, result_length, filename) char * result ; jr_int result_length; const char * filename ; { jr_int status; /* * This function is supposed to fill up its * result argument with the absolute path of its * filename argument. */ if ((filename[0] == '.') && (filename[1] == '/')) { filename += 2 ; } if (*filename == '/') { strncpy(result, filename, result_length - 1) ; result [result_length - 1] = 0; } else { char dirname_buffer[2048] ; jr_int nbytes ; char * end_ptr ; status = jr_getcwd (dirname_buffer, sizeof (dirname_buffer), 0); if (status != 0) { return(-1) ; } nbytes = result_length - 1 ; sprintf(result, "%.*s", nbytes, dirname_buffer) ; end_ptr = strchr(result, 0) ; nbytes = result_length - (end_ptr - result) - 2 ; /* null and / */ if (nbytes <= 0) return(-1) ; sprintf(end_ptr, "/%.*s", nbytes, filename) ; } jr_RemoveContiguousDuplicateChar(result, '/') ; { char * end_ptr = strrchr(result, '/') ; if (end_ptr && (end_ptr[1] == 0)) *end_ptr = 0 ; /* remove trailing '/' */ } return(0) ; }
frankjas/libjr
include/jr/bufio.h
<reponame>frankjas/libjr<filename>include/jr/bufio.h #ifndef _jr_buf_io_h___ #define _jr_buf_io_h___ #include "ezport.h" #include <stdio.h> #include "jr/alist.h" #include "jr/apr.h" typedef struct jr_buffered_io jr_BufferedIoType; typedef jr_int (jr_BufferedIoRawReadFn) ( void * raw_read_arg, unsigned jr_int max_data_length, const char ** data_ptr_ref, unsigned jr_int * data_length_ref, char * error_buf); struct jr_buffered_io { jr_BufferedIoRawReadFn * raw_read_fn; void * raw_read_arg; const char * data_ptr; unsigned jr_int data_length; jr_AList data_buffer[1]; const void * read_buffer; jr_int read_buffer_length; FILE * rfp; jr_file_t * file_info; jr_socket_t * sock_info; }; extern void jr_BufferedIoInit ( jr_BufferedIoType * buf_io); extern void jr_BufferedIoUndo ( jr_BufferedIoType * buf_io); extern void jr_BufferedIoSetRawReadFn( jr_BufferedIoType * buf_io, jr_BufferedIoRawReadFn * raw_read_fn, void * raw_read_arg); extern jr_int jr_BufferedIoGetLine ( jr_BufferedIoType * buf_io, char ** line_buffer_ref, char * error_buf); extern jr_int jr_BufferedIoGetString ( jr_BufferedIoType * buf_io, unsigned jr_int desired_string_length, char ** string_ref, char * error_buf); extern jr_int jr_BufferedIoRead ( jr_BufferedIoType * buf_io, unsigned jr_int max_data_length, const char ** data_buffer_ref, unsigned jr_int * data_length_ref, char * error_buf); extern void jr_BufferedIoSetFilePtr( jr_BufferedIoType * buf_io, FILE * rfp); extern jr_int jr_BufferedIoFread( void * raw_read_arg, unsigned jr_int max_data_length, const char ** data_ptr_ref, unsigned jr_int * data_length_ref, char * error_buf); extern void jr_BufferedIoSetFileInfo( jr_BufferedIoType * buf_io, jr_file_t * file_info); extern jr_int jr_BufferedIoFileRead( void * raw_read_arg, unsigned jr_int max_data_length, const char ** data_ptr_ref, unsigned jr_int * data_length_ref, char * error_buf); extern void jr_BufferedIoSetSocket( jr_BufferedIoType * buf_io, jr_socket_t * sock_info); extern jr_int jr_BufferedIoSocketRead( void * raw_read_arg, unsigned jr_int max_data_length, const char ** data_ptr_ref, unsigned jr_int * data_length_ref, char * error_buf); #endif
frankjas/libjr
libjr/string/struquot.c
<filename>libjr/string/struquot.c #include "ezport.h" #include <stdio.h> #include <string.h> #include <ctype.h> #include "jr/string.h" void jr_StringUnQuote(str) char *str ; { char *lastchr ; if (*str == '"') { jr_int nbytes = strlen(str+1) + 1 ; memmove(str, str+1, nbytes) ; } lastchr = (char *) strchr(str, 0) ; lastchr-- ; if (*lastchr == '"') { *lastchr = 0 ; } } /* void main() { char * original ; char result[128] ; original = "\"This is a test of \"quotes\" \\\"ha\\\" a litte more\"" ; strcpy(result, original) ; jr_StringUnQuote(result) ; fprintf(stdout,"jr_StringUnQuote(%s) == '%s'\n", original, result ) ; } */
frankjas/libjr
libjr/syscalls/touch.c
<reponame>frankjas/libjr #define _POSIX_SOURCE 1 #include "ezport.h" #include <stdio.h> #include <sys/types.h> #include <sys/time.h> #include <unistd.h> #include <time.h> #include <errno.h> #include <string.h> #include "jr/syscalls.h" #include "jr/time.h" #include "jr/error.h" jr_seconds_t jr_FileNameModTimeTouch(filename, error_buf) const char * filename ; char * error_buf; { jr_seconds_t current_time ; jr_int status; if (access((char *) filename,R_OK) != 0) { FILE * tfp ; tfp = fopen(filename,"w") ; if (tfp != NULL) { fclose(tfp) ; } else { jr_esprintf (error_buf, "%s", strerror (errno)); return(jr_ConvertErrno (errno)) ; } } current_time = jr_time_seconds(); status = jr_FileNameSetModTime(filename, current_time, error_buf) ; if (status != 0) { return status; } return current_time; } jr_seconds_t jr_FileNameSetModTime(filename, mod_time, error_buf) const char * filename ; jr_seconds_t mod_time ; char * error_buf; { # ifdef NeXT struct timeval t1, t2 ; struct timeval *tvp[2] ; tvp[0] = &t1 ; tvp[1] = &t2 ; t1.tv_sec = mod_time ; t1.tv_usec = 0 ; t2.tv_sec = mod_time ; t2.tv_usec = 0 ; if (utimes(filename, (void *) tvp) != 0) { jr_esprintf (error_buf, "%s", strerror (errno)); return(jr_ConvertErrno (errno)) ; } # else struct timeval tvp[2] ; tvp[0].tv_sec = mod_time ; tvp[0].tv_usec = 0 ; tvp[1].tv_sec = mod_time ; tvp[1].tv_usec = 0 ; if (utimes((char *) filename, tvp) != 0) { jr_esprintf (error_buf, "%s", strerror (errno)); return(jr_ConvertErrno (errno)) ; } # endif return(0) ; }
frankjas/libjr
libjr/syscalls/which.c
<filename>libjr/syscalls/which.c #define _POSIX_SOURCE 1 #include "ezport.h" #include <sys/types.h> #include <sys/stat.h> #include <sys/file.h> #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include "jr/malloc.h" #include "jr/vector.h" #include "jr/misc.h" #include "jr/syscalls.h" #define jr_STAT_STRUCT_PTR_IS_FROM_DIRECTORY(stat_ptr) \ (((stat_ptr)->st_mode & S_IFMT) == S_IFDIR) jr_int jr_FileNameFindInPathString(file_name, path_string, result_buf, result_buf_length) const char * path_string ; char * result_buf ; jr_int result_buf_length ; const char * file_name ; { char ** path_vector ; jr_int max_vector_size ; jr_int status ; jr_int n ; if (path_string == 0) { return -1; } max_vector_size = strlen(path_string) ; path_vector = (char **) alloca(max_vector_size * sizeof(char *)) ; n = jr_VectorizeIntoWords(path_string, ":", path_vector, max_vector_size) ; if (n == max_vector_size) { path_vector[n-1] = 0; } status = jr_FileNameFindInPathVector( file_name, path_vector, result_buf, result_buf_length ) ; jr_VectorUndo(path_vector) ; return(status) ; } jr_int jr_FileNameFindInPathVector(file_name, path_vector, result_buf, result_buf_length) char ** path_vector ; char * result_buf ; jr_int result_buf_length ; const char * file_name ; { jr_int search_file_name_length ; jr_int status ; struct stat stat_info[1] ; char ** vp ; jr_int nbytes ; char * best_file_name_so_far ; char * full_path_name_buf ; jr_int best_file_mode_so_far ; jr_int current_mode ; search_file_name_length = strlen(file_name) ; best_file_mode_so_far = 0 ; best_file_name_so_far = 0 ; for (vp = path_vector ; *vp ; vp++) { nbytes = strlen(*vp) + search_file_name_length + 2 ; /* one null one '/' */ full_path_name_buf = (char *) jr_malloc(nbytes) ; strcpy(full_path_name_buf, *vp) ; strcat(full_path_name_buf, "/") ; strcat(full_path_name_buf, file_name) ; status = stat(full_path_name_buf, stat_info) ; if (status == 0) { if (jr_STAT_STRUCT_PTR_IS_FROM_DIRECTORY(stat_info)) { current_mode = -2 ; } else { current_mode = access(full_path_name_buf, X_OK) ; } if (best_file_name_so_far == 0) { best_file_name_so_far = full_path_name_buf ; full_path_name_buf = 0 ; best_file_mode_so_far = current_mode ; } else if (current_mode > best_file_mode_so_far) { if (best_file_name_so_far) jr_free(best_file_name_so_far) ; best_file_name_so_far = full_path_name_buf ; full_path_name_buf = 0 ; best_file_mode_so_far = current_mode ; } } if (full_path_name_buf) { jr_free(full_path_name_buf) ; } } if (best_file_name_so_far) { strncpy(result_buf, best_file_name_so_far, result_buf_length - 1) ; result_buf[result_buf_length - 1] = 0 ; jr_free(best_file_name_so_far) ; return(0) ; } return(-1) ; }
frankjas/libjr
libjr/io/logfile.h
#ifndef __log_proj_h___ #define __log_proj_h___ #define _POSIX_SOURCE 1 #include "ezport.h" #include <errno.h> #include <string.h> #include "jr/string.h" #include "jr/malloc.h" #include "jr/log.h" #include "jr/io.h" #include "jr/syscalls.h" #include "jr/time.h" #include "jr/error.h" extern jr_int jr_LogEntryInitFromFilePtr PROTO (( jr_LogEntryType * entry_info, jr_file_t * file_info, jr_int block_size, char * opt_error_buf )); #define jr_LogEntryInitFromLog(entry_info, li, opt_error_buf) \ jr_LogEntryInitFromFilePtr (entry_info, (li)->file_info, (li)->block_size, opt_error_buf) #define jr_LogEntrySetOffset(entry_info, v) \ jr_ULongAsgn(&(entry_info)->entry_offset, (v)) extern jr_int jr_LogHeaderEntryLength PROTO ((void)); /******** Log File Data Structures ********/ #define jr_LOG_MAGIC_NUMBER 0x5a5b5a5b typedef struct { jr_NetInt magic_number; jr_NetInt is_synced; jr_NetInt block_size; /* store the block size in case log file is moved */ } jr_LogHeaderStruct; typedef struct { jr_NetInt magic_number; jr_NetShort type_number; jr_NetChar num_int_values; jr_NetChar num_ptr_values; jr_NetULong entry_time; } jr_LogEntryHeaderStruct; /* * in the log, the entry header is followed by * an array of ints, num_int_values long, and * an array of ints, num_ptr_values long, and * then the variable data pieces, one after another */ extern void jr_LogEntryHeaderInit PROTO (( jr_LogEntryHeaderStruct * entry_header, jr_int type_number, jr_int num_int_values, jr_int num_ptr_values, jr_ULong entry_time )); /******** Transaction Support Data Structures ********/ typedef struct { jr_ULong begin_offset; unsigned requires_sync : 1; } jr_LogTransInfoType; extern void jr_LogTransInfoInit PROTO (( jr_LogTransInfoType * trans_info, jr_ULong begin_offset )); extern void jr_LogTransInfoUndo PROTO (( jr_LogTransInfoType * trans_info )); #define jr_LogTransInfoSetSyncBit(trans_info, v) ((trans_info)->requires_sync = (v)) #endif
frankjas/libjr
libjr/misc/binsrch.c
#include "ezport.h" #include <stdio.h> #include <ctype.h> #include "jr/misc.h" /* * Our convention is that if the search results in a ptr * which is really the non-zero place where the key SHOULD * be inserted even if it isn't there, then the function * should have 'InsertPtr' as part of its name. * * A simple Search function should return a pointer which is also * a boolean value that says whether the thing is in the list or not. * The simple Search functions are generally layered on top of the * more general SearchInsertPtr functions. */ void * jr_BinarySearch(base_arg, num_items, sizeof_each_item, compf, search_key) const void * base_arg ; jr_int num_items ; jr_int sizeof_each_item ; jr_int (*compf)() ; const void * search_key ; { const char * base = (const char *) base_arg ; char * insertion_ptr ; jr_int index ; insertion_ptr = jr_BinarySearchInsertPtr( base_arg, num_items, sizeof_each_item, compf, search_key ) ; index = (insertion_ptr - base) / sizeof_each_item ; if (index < num_items) { if ((*compf)(search_key, insertion_ptr) == 0) { return((void *) insertion_ptr) ; } } return(0) ; } void * jr_BinarySearchInsertPtr(base_arg, num_items, sizeof_each_item, compf, search_key) const void * base_arg ; jr_int num_items ; jr_int sizeof_each_item ; jr_int (*compf)() ; const void * search_key ; { const char * base = (const char *) base_arg ; jr_int compval ; jr_int mid_index ; jr_int byte_offset ; jr_int low_index ; jr_int high_index ; low_index = 0; high_index = num_items ; while (low_index != high_index) { mid_index = low_index + (high_index - low_index)/2; byte_offset = mid_index * sizeof_each_item ; compval = (*compf) (search_key, base + byte_offset) ; if (compval == 0) { return((void *)(base + byte_offset)) ; } if (compval > 0) { low_index = mid_index + 1; } else { high_index = mid_index ; } } byte_offset = low_index * sizeof_each_item ; return ((void *)(base + byte_offset)); }
frankjas/libjr
libjr/missing/strchr.c
#define _POSIX_SOURCE 1 #include "ezport.h" #include <string.h> /* This function is identical to 'index(str,c)' */ #ifdef missing_strchr char *strchr(str, chr) const char *str ; int chr ; { for (; *str; str++) { if (*str == chr) return((char *) str) ; } if (chr == 0) return((char *) str) ; return(0) ; } #else static void NotCalled () /* define this so ranlib doesn't complain */ { NotCalled (); /* use it so the compiler doesn't complain */ } #endif
frankjas/libjr
include/jr/log.h
<reponame>frankjas/libjr #ifndef __jr_log_h___ #define __jr_log_h___ #include "ezport.h" #include <stdio.h> #include "jr/alist.h" #include "jr/nettype.h" #include "jr/log.h" #include "jr/apr.h" typedef struct { char * file_name; jr_file_t file_info[1]; jr_int opened_how; jr_int block_size; jr_ULong start_time; jr_int in_transaction; jr_AList transaction_stack [1]; jr_ULong truncate_offset; unsigned is_file_synced : 1; unsigned is_executing : 1; } jr_LogType; #define jr_LogFileName(log_info) ((log_info)->file_name) #define jr_LogFileIsSynced(log_info) ((log_info)->is_file_synced) #define jr_LogOpenedReadOnly(log_info) ((log_info)->opened_how == 'r') #define jr_LogGetStartTime(log_info, ulong_ref) jr_ULongAsgn( ulong_ref, (log_info)->start_time) #define jr_LogIsInTransaction(log_info) ((log_info)->in_transaction > 0) #define jr_LogBlockSize(log_info) ((log_info)->block_size) #define jr_LogIsExecuting(log_info) ((log_info)->is_executing) #define jr_LOG_GENERIC_ERROR -1 #define jr_LOG_CORRUPTED_ERROR -2 extern jr_LogType * jr_LogCreate(void); extern void jr_LogInit( jr_LogType * log_info); extern jr_int jr_LogOpen PROTO (( jr_LogType * log_info, const char * file_name, const char * how_string, jr_int block_size, char * error_buf )); extern void jr_LogDestroy PROTO (( jr_LogType * log_info )); extern void jr_LogUndo PROTO (( jr_LogType * log_info )); extern jr_int jr_LogSize PROTO (( jr_LogType * log_info, jr_ULong * file_size_ref, char * error_buf )); extern jr_int jr_LogGetOffset( jr_LogType * log_info, jr_ULong * curr_offset_ref, char * error_buf); extern jr_int jr_LogTransactionBegin PROTO (( jr_LogType * log_info, char * opt_error_buf )); extern jr_int jr_LogTransactionCommit PROTO (( jr_LogType * log_info, char * opt_error_buf )); extern jr_int jr_LogTransactionAbort PROTO (( jr_LogType * log_info, char * opt_error_buf )); extern jr_int jr_LogSync PROTO (( jr_LogType * log_info, char * opt_error_buf )); extern jr_int jr_LogSyncAllEntries PROTO (( jr_LogType * log_info, char * opt_error_buf )); extern jr_int jr_LogExecuteEntries PROTO (( jr_LogType * log_info, jr_int execution_style, jr_ULong start_value, jr_ULong stop_value, jr_int (*entry_fn) (), void * entry_fn_arg, jr_ULong * opt_offset_ref, char * opt_error_buf )); #define jr_LOG_EXECUTE_BY_OFFSET 0x00000001 #define jr_LOG_EXECUTE_BY_TIME 0x00000002 #define jr_LOG_TRUNCATE_INCOMPLETE_TRANSACTION 0x00000004 #define jr_LOG_EXECUTE_TO_TRANSACTION_END 0x00000008 #define jr_LOG_EXECUTE_NEXT_ENTRY 0x00000010 /* * entry_fn return values, negative terminates the execution */ #define jr_LOG_STOP_IF_NOT_IN_TRANSACTION 1 #define jr_LogExecuteEntriesByOffset( \ log_info, start_offset, stop_offset, entry_fn, fn_arg, opt_off_ref, opt_eb \ ) \ jr_LogExecuteEntries ( \ log_info, jr_LOG_EXECUTE_BY_OFFSET, \ start_offset, stop_offset, entry_fn, fn_arg, opt_off_ref, opt_eb \ ) #define jr_LogExecuteEntriesByOffsetAndTruncate( \ log_info, start_offset, stop_offset, entry_fn, fn_arg, opt_off_ref, opt_eb \ ) \ jr_LogExecuteEntries ( \ log_info, \ jr_LOG_EXECUTE_BY_OFFSET \ | jr_LOG_TRUNCATE_INCOMPLETE_TRANSACTION, \ start_offset, stop_offset, entry_fn, fn_arg, opt_off_ref, opt_eb \ ) #define jr_LogExecuteTransactionByOffset( \ log_info, start_offset, stop_offset, entry_fn, fn_arg, opt_off_ref, opt_eb \ ) \ jr_LogExecuteEntries ( \ log_info, \ jr_LOG_EXECUTE_BY_OFFSET \ | jr_LOG_EXECUTE_TO_TRANSACTION_END, \ start_offset, stop_offset, entry_fn, fn_arg, opt_off_ref, opt_eb \ ) #define jr_LogExecuteTransactionByOffsetAndTruncate( \ log_info, start_offset, stop_offset, entry_fn, fn_arg, opt_off_ref, opt_eb \ ) \ jr_LogExecuteEntries ( \ log_info, \ jr_LOG_EXECUTE_BY_OFFSET \ | jr_LOG_EXECUTE_TO_TRANSACTION_END \ | jr_LOG_TRUNCATE_INCOMPLETE_TRANSACTION, \ start_offset, stop_offset, entry_fn, fn_arg, opt_off_ref, opt_eb \ ) #define jr_LogExecuteNextTransactionByOffset( \ log_info, start_offset, entry_fn, fn_arg, opt_off_ref, opt_eb \ ) \ jr_LogExecuteEntries ( \ log_info, \ jr_LOG_EXECUTE_BY_OFFSET \ | jr_LOG_EXECUTE_TO_TRANSACTION_END \ | jr_LOG_EXECUTE_NEXT_ENTRY, \ start_offset, start_offset, entry_fn, fn_arg, opt_off_ref, opt_eb \ ) #define jr_LogExecuteNextTransactionByOffsetAndTruncate( \ log_info, start_offset, entry_fn, fn_arg, opt_off_ref, opt_eb \ ) \ jr_LogExecuteEntries ( \ log_info, \ jr_LOG_EXECUTE_BY_OFFSET \ | jr_LOG_EXECUTE_TO_TRANSACTION_END \ | jr_LOG_TRUNCATE_INCOMPLETE_TRANSACTION \ | jr_LOG_EXECUTE_NEXT_ENTRY, \ start_offset, start_offset, entry_fn, fn_arg, opt_off_ref, opt_eb \ ) #define jr_LogExecuteEntriesByTime( \ log_info, start_time, stop_time, entry_fn, fn_arg, opt_off_ref, opt_eb \ ) \ jr_LogExecuteEntries ( \ log_info, jr_LOG_EXECUTE_BY_TIME, \ start_time, stop_time, entry_fn, fn_arg, opt_off_ref, opt_eb \ ) #define jr_LogExecuteEntriesByTimeAndTruncate( \ log_info, start_time, stop_time, entry_fn, fn_arg, opt_off_ref, opt_eb \ ) \ jr_LogExecuteEntries ( \ log_info, \ jr_LOG_EXECUTE_TO_TRANSACTION_END \ | jr_LOG_EXECUTE_BY_TIME \ | jr_LOG_TRUNCATE_INCOMPLETE_TRANSACTION, \ start_time, stop_time, entry_fn, fn_arg, opt_off_ref, opt_eb \ ) extern jr_int jr_LogGetStartTimeFromFileName PROTO (( char * log_file_name, jr_ULong * start_time_ref, char * error_buf )); extern jr_int jr_LogSetFileSyncBit PROTO (( jr_LogType * log_info, jr_int synced_bit, char * opt_error_buf )); extern jr_int jr_LogSetStartTime PROTO (( jr_LogType * log_info, jr_ULong start_time, char * error_buf )); extern jr_int jr_AvoidLogBlockBoundary PROTO (( jr_file_t * file_info, jr_int block_size, jr_int log_entry_length, jr_ULong * opt_end_offset_ref, char * opt_error_buf )); #define jr_LogPadToBlockBoundary(li, end_offset_ref, opt_error_buf) \ jr_AvoidLogBlockBoundary ( \ (li)->file_info, (li)->block_size, jr_INT_MAX, end_offset_ref, opt_error_buf \ ) extern off_t jr_NextLogEntryOffset PROTO (( off_t curr_end_offset, jr_int log_entry_length, jr_int block_size )); #define jr_LogNextEntryOffset(log_info, ceo, lel) \ jr_NextLogEntryOffset (ceo, lel, (log_info)->block_size) extern jr_int jr_LogDeleteRange PROTO (( jr_LogType * log_info, jr_ULong start_offset, jr_ULong end_offset, char * opt_error_buf )); extern jr_int jr_LogGetResetOffset PROTO (( jr_LogType * log_info, jr_ULong start_time, jr_ULong* reset_offset_ref, char * error_buf )); extern jr_int jr_LogSetTruncateOffset PROTO (( jr_LogType * log_info, char * error_buf )); extern jr_int jr_LogTruncate PROTO (( jr_LogType * log_info, jr_ULong truncate_offset, char * opt_error_buf )); extern jr_int jr_LogResetFromOffset PROTO (( jr_LogType * log_info, jr_ULong new_start_time, jr_ULong reset_offset, char * error_buf )); #define jr_LogReset(log_info, eb) jr_LogResetFromOffset (log_info, LONG_MAX, eb) /******** Log Entry ********/ #define jr_LOG_ENTRY_MAX_VALUES 256 /* * 256 because the log entry header has 1 char for the number of values * The limits on the number of int and var values should be * published in the documentation, and will not be checked. */ typedef struct { jr_int type_number; jr_ULong entry_time; jr_ULong entry_offset; jr_int num_int_values; jr_int num_ptr_values; jr_NetInt int_values [jr_LOG_ENTRY_MAX_VALUES]; const void * ptr_values [jr_LOG_ENTRY_MAX_VALUES]; jr_NetInt data_lengths [jr_LOG_ENTRY_MAX_VALUES]; unsigned requires_sync : 1; unsigned has_malloced_ptrs : 1; } jr_LogEntryType; /* * Built-in entry type numbers. User defined entry type * number should be positive. */ #define jr_LOG_HEADER_ENTRY -1 #define jr_LOG_PAD_ENTRY -2 #define jr_LOG_TRANSACTION_BEGIN_ENTRY -10 #define jr_LOG_TRANSACTION_COMMIT_ENTRY -11 #define jr_LOG_TRANSACTION_ABORT_ENTRY -12 #define jr_LogEntryGetTime(entry_info, ulong_ref) jr_ULongAsgn( ulong_ref, (entry_info)->entry_time) #define jr_LogEntryTypeNumber(entry_info) ((entry_info)->type_number) #define jr_LogEntryGetOffset(entry_info, ulong_ref) jr_ULongAsgn( ulong_ref, (entry_info)->entry_offset) #define jr_LogEntryRequiresSync(entry_info) ((entry_info)->requires_sync) #define jr_LogEntryIntValue(entry_info, index) \ jr_NetIntToHost ((entry_info)->int_values[index]) #define jr_LogEntrySetTime(entry_info, v) ((entry_info)->entry_time = (v)) #define jr_LogEntrySetIntValue(entry_info, index, value) \ jr_NetIntAsgnInt ((entry_info)->int_values + (index), value) #define jr_LogEntryPtrValue(entry_info, index) \ ((entry_info)->ptr_values[index]) extern void jr_LogEntrySetPtrValue PROTO (( jr_LogEntryType * entry_info, jr_int index, const void * ptr_value, jr_int data_length )); #define jr_LogEntryDataLength(entry_info, index) \ jr_NetIntToHost ((entry_info)->data_lengths[index]) #define jr_LogEntryNumInts(entry_info) ((entry_info)->num_int_values) #define jr_LogEntryNumPtrs(entry_info) ((entry_info)->num_ptr_values) extern void jr_LogEntryInit PROTO (( jr_LogEntryType * entry_info, jr_int type_number, jr_int num_int_values, jr_int num_ptr_values, jr_ULong entry_time, jr_int requires_sync )); extern void jr_LogEntryUndo PROTO (( jr_LogEntryType * entry_info )); extern jr_int jr_LogEntrySavedLength PROTO (( jr_LogEntryType * entry_info )); extern jr_int jr_LogEntryAddToFilePtr PROTO (( jr_LogEntryType * entry_info, jr_file_t * file_info, jr_int block_size, char * opt_error_buf )); extern jr_int jr_LogAddEntry PROTO(( jr_LogType * log_info, jr_LogEntryType * entry_info, char * opt_error_buf )); /******** Functions For Testing ********/ /* * simulate a crash */ extern void jr_LogCrash PROTO (( jr_LogType * log_info )); /* * to be used for testing purposes only. * changing the block size on a log with data will * effectively make the log unusable */ extern jr_int jr_LogSetFileBlockSize PROTO (( jr_LogType * log_info, jr_int block_size, char * error_buf )); extern jr_int jr_LogFlushIO( jr_LogType * log_info, char * error_buf); #define jr_LogCurrOffset(log_info) ftell ((log_info)->fp) #endif
frankjas/libjr
libjr/misc/jr_error.c
<filename>libjr/misc/jr_error.c<gh_stars>0 #include "ezport.h" #include <stdio.h> #include <string.h> #include <stdarg.h> #include "jr/trace.h" #include "jr/misc.h" #include "jr/malloc.h" #include "jr/error.h" static jr_int jr_ErrorBufMaxLength = jr_ERROR_LEN; static jr_int jr_ErrorWasSimulated = 0; static const char * jr_ErrorSimulatedFileName = ""; static jr_int jr_ErrorSimulatedLineNumber = 0; jr_int jr_esprintf ( char * opt_error_buf, const char * control_string, ...) { char * tmp_error_buf; va_list arg_list; jr_int status; if (opt_error_buf == 0) { return 0; } tmp_error_buf = jr_malloc (jr_ErrorBufMaxLength); if (jr_ErrorWasSimulated) { status = snprintf (opt_error_buf, jr_ErrorBufMaxLength, "simulated error %.64s:%d", jr_ErrorSimulatedFileName, jr_ErrorSimulatedLineNumber ); jr_ErrorWasSimulated = 0; } else { /* * Could do optimization for control strings without format specifiers. * Then we wouldn't need the local_error_buf because there is no race condition. * But the optimization may require as much work than the copy (linear time). */ va_start (arg_list, control_string); status = vsnprintf (tmp_error_buf, jr_ErrorBufMaxLength, control_string, arg_list); if (status >= jr_ErrorBufMaxLength) { tmp_error_buf[ jr_ErrorBufMaxLength-1 ] = 0; } strcpy (opt_error_buf, tmp_error_buf); va_end (arg_list); } if (status > jr_ErrorBufMaxLength - 1) { status = jr_ErrorBufMaxLength - 1; } jr_free (tmp_error_buf); return status; } jr_int jr_ensprintf ( char * opt_error_buf, jr_int error_buf_len, const char * control_string, ...) { va_list arg_list; char * tmp_error_buf; jr_int status; if (opt_error_buf == 0) { return 0; } tmp_error_buf = jr_malloc (error_buf_len); if (jr_ErrorWasSimulated) { status = snprintf (tmp_error_buf, error_buf_len, "simulated error %.64s:%d", jr_ErrorSimulatedFileName, jr_ErrorSimulatedLineNumber ); jr_ErrorWasSimulated = 0; } else { va_start (arg_list, control_string); status = vsnprintf (tmp_error_buf, error_buf_len, control_string, arg_list); if (status >= error_buf_len) { tmp_error_buf[ error_buf_len - 1 ] = 0; } strcpy (opt_error_buf, tmp_error_buf); va_end (arg_list); } if (status > error_buf_len - 1) { status = error_buf_len - 1; } jr_free (tmp_error_buf); return status; } jr_int jr_error_set_max_buf_length ( jr_int max_buf_length) { if (max_buf_length <= jr_ERROR_LEN) { jr_ErrorBufMaxLength = max_buf_length; } return jr_ErrorBufMaxLength; } jr_int jr_error_max_buf_length (void) { return jr_ErrorBufMaxLength; } void jr_error_msg_simulate ( const char * file_name, jr_int line_number) { jr_ErrorWasSimulated = 1; jr_ErrorSimulatedFileName = file_name; jr_ErrorSimulatedLineNumber = line_number; }
frankjas/libjr
libjr/alist/alistdel.c
<gh_stars>0 #include "project.h" void *jr_AListDeletedTailPtr (list) jr_AList *list; { if (jr_AListSize(list) == 0) return (0); list->free_ptr -= list->objsize; list->free_index--; return (list->free_ptr + list->prefix_size); } void jr_AListTruncate (list, i) jr_AList * list; jr_int i; { if (i >= jr_AListSize (list)) { return; } if (i < 0) { i = 0; } list->free_index = i; list->free_ptr = jr_AListElementPtr (list, i); } void jr_AListDeleteRangeFromPtr (list, delete_ptr_arg, num_entries) jr_AList * list; void * delete_ptr_arg; jr_int num_entries; { register char * delete_ptr = delete_ptr_arg ; jr_int num_move_bytes; jr_int num_delete_bytes; if (num_entries <= 0) { return; } delete_ptr -= list->prefix_size; assert ((delete_ptr >= list->buffer) && (delete_ptr < list->free_ptr)); num_delete_bytes = list->objsize * num_entries; num_move_bytes = list->free_ptr - delete_ptr - num_delete_bytes; if (jr_AListHasPrefixTransformFn (list)) { char * curr_ptr; jr_int i; for ( curr_ptr = delete_ptr + num_delete_bytes; curr_ptr < list->free_ptr; curr_ptr += list->objsize) { for (i = 0; i < list->objsize; i++) { curr_ptr[i - num_delete_bytes] = curr_ptr[i]; } (*jr_AListPrefixTransformFn (list)) ( jr_AListPrefixTransformArg (list), curr_ptr - num_delete_bytes + list->prefix_size, num_delete_bytes, -1, 0 ); } } else { memmove (delete_ptr, delete_ptr + num_delete_bytes, num_move_bytes); } list->free_ptr -= num_delete_bytes; list->free_index -= num_entries; }
frankjas/libjr
libjr/string/sgetline.c
<reponame>frankjas/libjr #include "ezport.h" #include <stdio.h> #include "jr/string.h" char *jr_StringFgets(target, bounds_arg, source) char * target ; jr_int bounds_arg ; const char * source ; { jr_int target_array_bounds ; jr_int i ; if (*source == '\0') return(0) ; target_array_bounds = bounds_arg - 1 ; for (i=0; i < target_array_bounds; i++) { if (*source == '\0') break ; if (*source == '\n') { *target = '\n' ; target++ ; break ; } *target = *source ; target++ ; source++ ; } *target = 0 ; while (*source && (*source != '\n')) source++ ; if (*source == '\n') source++ ; return((char *) source) ; } /* void main() { char * input_buf ; char * input_ptr ; char line_buf[128] ; jr_int i ; input_buf = "test\ntwo\nthree\nfour\n\nsix\n\n" ; input_ptr = input_buf ; i = 0 ; while (input_ptr = jr_StringFgets(line_buf, sizeof(line_buf), input_ptr)) { i++ ; fprintf(stdout, "%d) %s", i, line_buf) ; } } */
frankjas/libjr
libjr/misc/tabstops.c
#define _POSIX_SOURCE 1 #include "ezport.h" #include <stdlib.h> #include "jr/misc.h" jr_int jr_EnvTabStops () { char * value_str; jr_int tabstops = 0; value_str = getenv ("TABSTOPS"); if (value_str) { tabstops = atoi (value_str); } if (tabstops == 0) { tabstops = 8; } return tabstops; }
frankjas/libjr
include/jr/ezport/replace.h
<reponame>frankjas/libjr<gh_stars>0 #ifndef __EZPORT_REPLACE_H__ #define __EZPORT_REPLACE_H__ #ifdef replace_buggy_inet_ntoa # define inet_ntoa(in_addr) jr_inet_ntoa(in_addr) extern char *jr_inet_ntoa PROTO ((struct in_addr sin_addr)); #endif #ifdef replace_buggy_getenv # define getenv(name) jr_system_getenv (name) extern char *jr_system_getenv PROTO ((const char *name)); /* * There is a jr_getenv() in jr/string.h */ #endif #ifdef replace_sun_siglist_names # define sys_siglist _sys_siglistp # define NSIG _sys_siglistn #endif #ifdef missing_utmp_ut_host_field # define jr_UTmpHasHostArray(utmp_ptr) (0) # define jr_UTmpHostArraySize(utmp_ptr) (0) # define jr_UTmpHostArrayPtr(utmp_ptr) (0) #else # define jr_UTmpHasHostArray(utmp_ptr) (1) # define jr_UTmpHostArraySize(utmp_ptr) sizeof ((utmp_ptr)->ut_host) # define jr_UTmpHostArrayPtr(utmp_ptr) ((utmp_ptr)->ut_host) #endif #endif
frankjas/libjr
libjr/io/prn_data.c
<gh_stars>0 #include "ezport.h" #include <ctype.h> #include "jr/io.h" void jr_PrintArbitraryData (wfp, void_ptr, data_length, max_width) FILE * wfp; const void * void_ptr; jr_int data_length; jr_int max_width; { const char * data_ptr = void_ptr; jr_int truncated_data; jr_int non_printing_data; jr_int i; if (data_length > max_width) { data_length = max_width - 3; truncated_data = 1; /* * -3 for the three dots ... * which will always print */ } else { truncated_data = 0; } non_printing_data = 0; for (i = 0; i < data_length; i++, data_ptr++) { if (!non_printing_data && isprint (*(char *)data_ptr)) { putc (*(char *)data_ptr, wfp); } else { non_printing_data = 1; putc ('?', wfp); } } if (truncated_data) { putc ('.', wfp); putc ('.', wfp); putc ('.', wfp); } }
frankjas/libjr
libjr/llist/llistcpy.c
#include "project.h" jr_LList *jr_LListCopy (dest, src) jr_LList *dest; jr_LList *src; { void *obj; jr_LListInit (dest, src->objsize); jr_LListSetPrefixSize (dest, jr_LListPrefixSize (src)); jr_LListForEachElementPtr (src, obj) { jr_LListSetNewTail(dest, obj); } return (dest); }
frankjas/libjr
libjr/dlist/dlistadd.c
#include "project.h" void *jr_DListInsertElement (list, next_const_ptr, new_const_ptr) jr_DList * list ; const void * next_const_ptr ; const void * new_const_ptr ; { void * next = (void *) next_const_ptr; void * new = (void *) new_const_ptr; void * prev; jr_DListNextElementPtr (list, new) = next; if (next == 0) { /* append to the tail */ prev = jr_DListTailPtr(list); jr_DListTailPtr(list) = new; } else { prev = jr_DListPrevElementPtr (list,next); jr_DListPrevElementPtr (list, next) = new; } jr_DListPrevElementPtr (list,new) = prev; if (prev == 0) { /* insert at the head */ jr_DListHeadPtr(list) = new; } else { jr_DListNextElementPtr (list,prev) = new; } return (void *) new; } void *jr_DListAppendElement (list, prev_const_ptr, new_const_ptr) jr_DList * list; const void * prev_const_ptr; const void * new_const_ptr; { void * prev = (void *) prev_const_ptr; void * new = (void *) new_const_ptr; void * next; jr_DListPrevElementPtr (list, new) = prev; if (prev == 0) { /* insert to the head */ next = jr_DListHeadPtr(list); jr_DListHeadPtr(list) = new; } else { next = jr_DListNextElementPtr (list, prev); jr_DListNextElementPtr (list, prev) = new; } jr_DListNextElementPtr (list,new) = next; if (next == 0) { /* add to tail */ jr_DListTailPtr(list) = new; } else { jr_DListPrevElementPtr (list,next) = new; } return (void *) new; }
frankjas/libjr
libjr/avl_tree/avl_pfx.c
#include "project.h" void jr_AVL_TreeSetContainers ( jr_AVL_Tree * avl_tree, ...) { va_list arg_list; va_start (arg_list, avl_tree); jr_AVL_TreeSetContainersFromVA_List (avl_tree, arg_list); va_end (arg_list); } void jr_AVL_TreeSetContainersFromVA_List (avl_tree, arg_list) jr_AVL_Tree * avl_tree; va_list arg_list; { jr_PrefixInfoType * prefix_array; jr_int prefix_size; jr_int needs_transform_fn = 0; prefix_array = jr_PrefixArrayCreateFromVA_List (arg_list, needs_transform_fn); prefix_size = jr_PrefixArrayInitPrefixes (prefix_array); jr_AVL_TreeSetPrefixSize (avl_tree, prefix_size); jr_PrefixArrayDestroy (prefix_array); } void jr_AVL_TreeTransformPrefix (avl_tree, el_ptr, magnitude, which_way, all_elements) jr_AVL_Tree * avl_tree; void * el_ptr; unsigned jr_int magnitude; jr_int which_way; jr_int all_elements; { char * left_ptr; char * right_ptr; void * old_el_ptr; if (jr_AVL_TreeElementHeight (avl_tree, el_ptr) < 0) { /* * Means it has been removed from the tree */ return; } old_el_ptr = jr_UnTransformAListPtr (el_ptr, magnitude, which_way); if (old_el_ptr == jr_AVL_TreeRootPtr (avl_tree)) { jr_AVL_TreeRootPtr (avl_tree) = el_ptr; } if (all_elements) { left_ptr = jr_AVL_TreeLeftChildPtr (avl_tree, el_ptr); right_ptr = jr_AVL_TreeRightChildPtr (avl_tree, el_ptr); if (left_ptr) { left_ptr = jr_TransformAListPtr (left_ptr, magnitude, which_way); jr_AVL_TreeLeftChildPtr (avl_tree, el_ptr) = left_ptr; } if (right_ptr) { right_ptr = jr_TransformAListPtr (right_ptr, magnitude, which_way); jr_AVL_TreeRightChildPtr (avl_tree, el_ptr) = right_ptr; } } else { /* * need to find parent of this element (already took care of root node case) */ void * path [jr_AVL_TREE_MAX_HEIGHT]; jr_int path_length; void * prev_node; path_length = jr_AVL_TreeFillSearchPath (avl_tree, path, el_ptr); if (path_length > 1) { if (old_el_ptr == path[path_length - 1]) { prev_node = path [path_length - 2]; if (jr_AVL_TreeLeftChildPtr (avl_tree, prev_node) == old_el_ptr) { jr_AVL_TreeLeftChildPtr (avl_tree, prev_node) = el_ptr; } else if (jr_AVL_TreeRightChildPtr (avl_tree, prev_node) == old_el_ptr) { jr_AVL_TreeRightChildPtr (avl_tree, prev_node) = el_ptr; } } } } }
frankjas/libjr
libjr/alist/alistadd.c
#include "project.h" void *jr_AListNewTailPtr (list) jr_AList *list; { if (jr_AListSize(list) == list->buffer_capacity) { jr_AListIncreaseCapacity (list, jr_AListSize(list) + 1); } list->free_ptr += list->objsize; list->free_index++; return (list->free_ptr - list->objsize + list->prefix_size); } void *jr_AListNewPrevElementPtr (list, insert_ptr_arg) jr_AList * list; void * insert_ptr_arg; { register char * insert_ptr = insert_ptr_arg ; if (insert_ptr) { assert ((insert_ptr >= list->buffer) && (insert_ptr <= list->free_ptr)); insert_ptr -= list->prefix_size; } else { insert_ptr = list->free_ptr; } if (jr_AListSize(list) == list->buffer_capacity) { jr_int insert_offset; insert_offset = insert_ptr - list->buffer; jr_AListIncreaseCapacity (list, jr_AListSize(list) + 1); insert_ptr = list->buffer + insert_offset; } if (jr_AListHasPrefixTransformFn (list)) { register char * curr_ptr; register jr_int objsize = list->objsize; register jr_int i; for ( curr_ptr = list->free_ptr - objsize; curr_ptr >= insert_ptr; curr_ptr -= objsize) { for (i = 0; i < objsize; i++) { curr_ptr[objsize + i] = curr_ptr[i]; } (*jr_AListPrefixTransformFn (list)) ( jr_AListPrefixTransformArg (list), curr_ptr + objsize + list->prefix_size, objsize, 1, 0 ); } } else { memmove (insert_ptr + list->objsize, insert_ptr, list->free_ptr - insert_ptr); } list->free_ptr += list->objsize; list->free_index++; return (insert_ptr + list->prefix_size); } void *jr_AListNewNextElementPtr (list, prev_ptr_arg) jr_AList * list; void * prev_ptr_arg; { char * prev_ptr = prev_ptr_arg; char * insert_ptr; register char * new_ptr; if (prev_ptr) { insert_ptr = prev_ptr + list->objsize; assert ((prev_ptr >= list->buffer) && (prev_ptr < list->free_ptr)); } else { insert_ptr = list->buffer + list->prefix_size; } new_ptr = jr_AListNewPrevElementPtr (list, insert_ptr); return new_ptr; }
frankjas/libjr
libjr/string/ttyname.c
<reponame>frankjas/libjr<gh_stars>0 #include "ezport.h" #include <string.h> #include "jr/string.h" char *jr_TTY_LettersFromDeviceName(dev_name) char * dev_name ; { char *tty_string ; char *tty_letters ; if (tty_string = strstr(dev_name, "ttydf")) { tty_letters = tty_string + 5 ; } else if (tty_string = strstr(dev_name, "ttyd")) { tty_letters = tty_string + 4 ; } else if (tty_string = strstr(dev_name, "tty")) { tty_letters = tty_string + 3 ; } else if (tty_string = strstr(dev_name, "cuf")) { tty_letters = tty_string + 3 ; } else if (tty_string = strstr(dev_name, "cu")) { tty_letters = tty_string + 2 ; } else { tty_letters = dev_name ; } return(tty_letters) ; }
frankjas/libjr
libjr/string/lcase.c
<reponame>frankjas/libjr #include "ezport.h" #include "jr/string.h" void jr_ConvertToUpperCase(string) char *string ; { for (; *string ; string++) { *string = jr_toupper(*string) ; } } void jr_ConvertToLowerCase (string) char *string ; { for (; *string ; string++) { *string = jr_tolower(*string) ; } } void jr_CopyAndConvertCase (target_string, bounds_arg, source_string, case_control_string) char * target_string; jr_int bounds_arg ; const char * source_string ; const char * case_control_string ; { jr_int target_array_bounds ; target_array_bounds = bounds_arg - 1 ; /* leave room for null */ if ((*case_control_string == 'u') || (*case_control_string == 'U')) { jr_int i ; for (i=0; i < target_array_bounds; i++) { if (source_string[i] == '\0') break ; target_string[i] = jr_toupper(source_string[i]) ; } target_string[i] = 0 ; } else { jr_int i ; for (i=0; i < target_array_bounds; i++) { if (source_string[i] == '\0') break ; target_string[i] = jr_tolower(source_string[i]) ; } target_string[i] = 0 ; } } jr_int jr_StringIsAllUpper(str) const char *str ; { for (; *str; str++) { if ((isalpha(*str)) && (! isupper(*str))) return(0) ; } return(1) ; } jr_int jr_StringIsAllLower(str) const char *str ; { for (; *str; str++) { if ((isalpha(*str)) && (! islower(*str))) return(0) ; } return(1) ; }
frankjas/libjr
libjr/jr_malloc/jr_malloc.c
<reponame>frankjas/libjr<filename>libjr/jr_malloc/jr_malloc.c #include "project.h" static jr_MallocStatStruct jr_MallocStatInfo [1]; static jr_MallocDiagStruct jr_MallocDiagInfo [1]; static jr_int jr_MallocClearOnFree = 1 ; static unsigned jr_int jr_MallocMaxRequestSize = jr_MALLOC_DEFAULT_MAX_REQUEST; static unsigned jr_int jr_MallocNumCalls = 0; static unsigned jr_int jr_MallocNumUnRecordedCalls = 0; static unsigned jr_int jr_MallocNumBoundsMarkedPtrs = 0; unsigned jr_int jr_FreeNumCalls = 0 ; size_t jr_MallocBytesInUse = 0 ; size_t jr_MallocMaxBytesInUse = 0 ; jr_int jr_MallocMaxLeakTrapPrint = jr_MALLOC_MAX_LEAK_TRAP_PRINT; jr_int jr_MallocOtherResourceLeak = 0; unsigned jr_int jr_MallocSuffixBoundsMarkerMultiple = 0 ; unsigned jr_int jr_MallocPrefixBoundsMarkerMultiple = 0 ; static void jr_MallocDiagLock (jr_MallocDiagStruct *mdp); static void jr_MallocDiagUnLock (jr_MallocDiagStruct *mdp); static void jr_MallocStatLock (); static void jr_MallocStatUnLock (); void *jr_malloc (amt_requested) size_t amt_requested ; { void * new_ptr ; size_t bytes_needed = amt_requested; jr_int needs_bounds_marker = 0; if ( jr_do_trace (jr_malloc_calls) || jr_do_trace (jr_malloc_trap) || jr_MallocDiagIsDoingBookkeeping (jr_MallocDiagInfo)) { /* ** 4/6/07: if we're recording ptrs (as part of C++ global object init, for ex.) ** we wind up doing bookkeeping pointers, which always have bounds markers. ** One bounds marker before, one after, the one before to catch container prefix errors */ needs_bounds_marker = 1; bytes_needed += jr_malloc_prefix_bounds_marker_size () + jr_malloc_suffix_bounds_marker_size (amt_requested); if (amt_requested > jr_MallocMaxRequestSize) { fprintf(stderr,"Illegally large jr_malloc(%ld)\n", (long) amt_requested) ; jr_coredump() ; } } new_ptr = malloc (bytes_needed); if (new_ptr == 0) { if (jr_MallocNoMemoryHandler) { (*jr_MallocNoMemoryHandler) (bytes_needed); } return 0; } if (jr_do_trace (jr_malloc_stats)) { jr_MallocStatLock (); { jr_MallocStatRecordMalloc( jr_MallocStatInfo, new_ptr, jr_malloc_usable_size_macro (new_ptr, 0) ); /* ** 4/07/07: Use 0 as the size so that if we're just doing stats and ** the platform doesn't have a "usable size" implementation, we'll count ** everything as size 0. Otherwise we can't account for free() properly. ** If we're tracing calls, we could use the amt_requested info on free. */ } jr_MallocStatUnLock(); } if (needs_bounds_marker) { new_ptr = (char *) new_ptr + jr_malloc_prefix_bounds_marker_size (); } if (jr_do_trace (jr_malloc_calls) || jr_do_trace (jr_malloc_trap) || jr_MallocRecordPtrsOnly) { jr_MallocDiagLock(jr_MallocDiagInfo); { jr_MallocDiagRecordMalloc (jr_MallocDiagInfo, new_ptr, amt_requested, needs_bounds_marker); if (jr_do_trace (jr_malloc_trap) || jr_MallocRecordPtrsOnly) { /* ** 5/1/08: If pointer is free()ed during the C++ translation unit execution, ** before argments and "jr_malloc_trap" has been set, is later leaked, ** the occurence count will be off, since the first occurence won't be counted. ** In that case, record the occurence even if "jr_malloc_trap" isn't set. ** This is most likely going to be a bookkeeping pointer. ** ** Note that as a result, a leak in a C++ translation unit static allocations ** will trap even without setting "jr_malloc_trap", as long as the ** trap file exists. The trap file can only get created if "jr_malloc_calls" ** is set, this typically implies memory leaks are being sought out, ** and trapping on the following run with "jr_malloc_calls" ** will probably not be too much of an incovenience. */ jr_MallocDiagDoMallocTrap (jr_MallocDiagInfo, new_ptr); } if (needs_bounds_marker) { jr_MallocNumBoundsMarkedPtrs++; } } jr_MallocDiagUnLock(jr_MallocDiagInfo); } else { jr_MallocNumUnRecordedCalls++; } jr_MallocNumCalls++ ; /* * 7/28/2005: This increment must follow the diagnostics, otherwise it thinks * malloc() has been called before diagnostics are started. */ return(new_ptr) ; } void jr_free (mptr) const void * mptr ; { size_t amt_requested = 0; jr_int has_bounds_marker = 0; if (mptr == 0) return ; if (jr_do_trace (jr_malloc_calls) || jr_do_trace (jr_malloc_trap) || jr_MallocRecordPtrsOnly) { jr_MallocDiagLock (jr_MallocDiagInfo); { if (jr_do_trace (jr_malloc_trap) || jr_MallocRecordPtrsOnly) { jr_MallocDiagDoFreeTrap (jr_MallocDiagInfo, mptr); } jr_MallocDiagRecordFree (jr_MallocDiagInfo, mptr, &amt_requested, &has_bounds_marker); } jr_MallocDiagUnLock (jr_MallocDiagInfo); if (has_bounds_marker) { mptr = (char *) mptr - jr_malloc_prefix_bounds_marker_size (); jr_MallocNumBoundsMarkedPtrs++; } } if (jr_do_trace(jr_malloc_stats)) { jr_MallocStatLock (); { jr_MallocStatRecordFree (jr_MallocStatInfo, mptr, jr_malloc_usable_size_macro (mptr, 0)) ; } jr_MallocStatUnLock(); } if (amt_requested > 0 && jr_MallocClearOnFree) { size_t usable_size; /* ** 4/7/07: jr_malloc_usable_size_macro() can only be used after we adjust the pointer */ if (has_bounds_marker) { jr_malloc_destroy_data ( (void *) mptr, amt_requested + jr_malloc_prefix_bounds_marker_size () + jr_malloc_suffix_bounds_marker_size (amt_requested) ); } else { usable_size = jr_malloc_usable_size_macro (mptr, amt_requested); /* * The usable size is actual memory available, and >= amt_requested */ jr_malloc_destroy_data ((void *) mptr, usable_size); } } jr_FreeNumCalls ++; free ((void *) mptr); /* * do the real free() after the bookkeeping since * free() may be destructive and wipe out our prepended size information */ } void *jr_realloc (old_ptr, amt_requested) const void * old_ptr; size_t amt_requested; { void * new_ptr; size_t bytes_needed = amt_requested; jr_int has_bounds_marker = 0; jr_int needs_bounds_marker = 0; size_t old_amt_requested = 0; if (old_ptr) { if (jr_do_trace (jr_malloc_calls) || jr_do_trace (jr_malloc_trap) || jr_MallocRecordPtrsOnly) { jr_MallocDiagLock (jr_MallocDiagInfo); { if (jr_do_trace (jr_malloc_trap) || jr_MallocRecordPtrsOnly) { jr_MallocDiagDoFreeTrap (jr_MallocDiagInfo, old_ptr); } jr_MallocDiagRecordFree ( jr_MallocDiagInfo, old_ptr, &old_amt_requested, &has_bounds_marker ); } jr_MallocDiagUnLock (jr_MallocDiagInfo); if (has_bounds_marker) { old_ptr = (char *) old_ptr - jr_malloc_prefix_bounds_marker_size (); } } if (jr_do_trace(jr_malloc_stats)) { jr_MallocStatLock (); { jr_MallocStatRecordFree( jr_MallocStatInfo, old_ptr, jr_malloc_usable_size_macro (old_ptr, 0) ) ; } jr_MallocStatUnLock(); } } if ( jr_do_trace (jr_malloc_calls) || jr_do_trace (jr_malloc_trap) || jr_MallocDiagIsDoingBookkeeping (jr_MallocDiagInfo)) { /* ** 4/6/07: if we're recording ptrs (as part of C++ global object init, for ex.) ** we wind up doing bookkeeping pointers, which always have bounds markers. ** One bounds marker before, one after, the one before to catch container prefix errors */ needs_bounds_marker = 1; bytes_needed += jr_malloc_prefix_bounds_marker_size () + jr_malloc_suffix_bounds_marker_size (amt_requested); if (amt_requested > jr_MallocMaxRequestSize) { fprintf(stderr,"Illegally large jr_realloc(%ld)\n", (long) amt_requested) ; jr_coredump() ; } } if (old_ptr) { new_ptr = realloc ((void *) old_ptr, bytes_needed); } else { new_ptr = malloc (bytes_needed); } if (new_ptr == 0) { if (jr_MallocNoMemoryHandler) { (*jr_MallocNoMemoryHandler) (bytes_needed); } return 0; } if (jr_do_trace (jr_malloc_stats)) { jr_MallocStatLock (); { jr_MallocStatRecordMalloc( jr_MallocStatInfo, new_ptr, jr_malloc_usable_size_macro (new_ptr, 0) ); } jr_MallocStatUnLock(); } if (needs_bounds_marker) { new_ptr = (char *) new_ptr + jr_malloc_prefix_bounds_marker_size (); } if (jr_do_trace (jr_malloc_calls) || jr_do_trace (jr_malloc_trap) || jr_MallocRecordPtrsOnly) { jr_MallocDiagLock (jr_MallocDiagInfo); { jr_MallocDiagRecordMalloc (jr_MallocDiagInfo, new_ptr, amt_requested, needs_bounds_marker); if (jr_do_trace (jr_malloc_trap) || jr_MallocRecordPtrsOnly) { jr_MallocDiagDoMallocTrap (jr_MallocDiagInfo, new_ptr); } } jr_MallocDiagUnLock (jr_MallocDiagInfo); } else { jr_MallocNumUnRecordedCalls++; } jr_MallocNumCalls++ ; /* * 7/28/2005: This increment must follow the diagnostics, otherwise it things * malloc() has been called before diagnostics are started. */ return (new_ptr); } void *jr_calloc (num_elements, element_size) size_t num_elements; size_t element_size; { size_t num_bytes = num_elements * element_size; void * new_array; new_array = jr_malloc (num_bytes); memset (new_array, 0, num_bytes); return new_array; } void jr_malloc_good_size (good_size) size_t good_size; { # ifdef has_malloc_good_size { malloc_good_size (good_size); } # endif jr_MallocStatLock (); { jr_MallocStatAddBucketSize (jr_MallocStatInfo, good_size); } jr_MallocStatUnLock(); } size_t jr_malloc_usable_size ( const void * mptr, size_t amt_requested) { size_t usable_size; if ( jr_do_trace (jr_malloc_calls) || jr_do_trace (jr_malloc_trap) || jr_MallocDiagIsDoingBookkeeping (jr_MallocDiagInfo)) { /* ** 4/7/07: Assume we'll only be called right after a malloc() if we're bookkeeping */ usable_size = jr_malloc_usable_size_macro ( (char *) mptr - jr_malloc_prefix_bounds_marker_size (), amt_requested ); if (usable_size > amt_requested) { /* * Assume the application is going to use the extra * space, so update the diagnostic's idea of how * much space is available at this pointer (stats * recording already uses the real available size). * * Adjust the returned available size to accomodate the bounds markers. * * 4/7/07: Note that the extra space needs to be split between the usable size and the * suffix bounds marker. If the bounds marker multiple is 1, then split evenly (by 2), * if greater than one (e.g. 3) then give 1/4 to the usable space. */ size_t memory_size; size_t slop_size; size_t new_total_size; jr_int divisor = jr_malloc_suffix_slop_divisor(); memory_size = jr_malloc_prefix_bounds_marker_size () + amt_requested + jr_malloc_suffix_bounds_marker_size (amt_requested); slop_size = usable_size - memory_size; if (memory_size < usable_size && slop_size / divisor > 0) { new_total_size = jr_malloc_prefix_bounds_marker_size() + amt_requested + slop_size/divisor + jr_malloc_suffix_bounds_marker_size (amt_requested + slop_size/divisor); if (new_total_size <= usable_size) { jr_MallocDiagLock (jr_MallocDiagInfo); { jr_MallocDiagSetSizeRequested ( jr_MallocDiagInfo, (void *) mptr, amt_requested + slop_size/divisor ); } jr_MallocDiagUnLock (jr_MallocDiagInfo); } usable_size = amt_requested + slop_size/divisor; } else { usable_size = amt_requested; } } } else { usable_size = jr_malloc_usable_size_macro (mptr, amt_requested); } return usable_size; } void jr_malloc_stats (wfp, message) FILE *wfp; char *message; { if (! jr_do_trace(jr_malloc_stats)) { fprintf(wfp,"=====> no memory traces were run <======\n") ; return ; } jr_MallocStatLock (); { jr_MallocStatPrint (wfp, jr_MallocStatInfo, message); } jr_MallocStatUnLock(); /* * check that all file descriptors are closed */ if (jr_do_trace(jr_malloc_calls)) { jr_MallocDiagLock (jr_MallocDiagInfo); { jr_MallocDiagNumOpenFiles (jr_MallocDiagInfo, wfp, 0); } jr_MallocDiagUnLock (jr_MallocDiagInfo); } } const char *jr_malloc_type (mptr) const void * mptr; { const char * type_string; jr_MallocDiagLock (jr_MallocDiagInfo); { type_string = jr_MallocDiagPtrType (jr_MallocDiagInfo, mptr); } jr_MallocDiagUnLock (jr_MallocDiagInfo); return type_string; } void jr_malloc_reset_calls () { jr_MallocDiagLock (jr_MallocDiagInfo); { jr_MallocDiagReset (jr_MallocDiagInfo); } jr_MallocDiagUnLock (jr_MallocDiagInfo); } void jr_malloc_reset_stats () { jr_MallocStatLock (); { jr_MallocStatReset (jr_MallocStatInfo); } jr_MallocStatUnLock(); } void jr_malloc_make_trap_file (mptr) const void * mptr; { jr_MallocPtrMakeTrapFile (mptr, ""); } int jr_malloc_is_trap_ptr ( const void * mptr) { if (jr_MallocDiagTrapPtr (jr_MallocDiagInfo) == mptr) { return 1; } return 0; } void jr_malloc_destroy_data (mptr, num_bytes) void * mptr; size_t num_bytes; { size_t j; char * mptr_str = mptr; const char * new_data_str = jr_DESTRUCTIVE_FREE_STRING; const char * curr_char_ptr = new_data_str; for (j=0; j < num_bytes; j++) { mptr_str[j] = *curr_char_ptr; curr_char_ptr++; if (*curr_char_ptr == 0) { curr_char_ptr = new_data_str; } } } void jr_malloc_set_bounds_marker_multiple (bounds_marker_multiple) jr_int bounds_marker_multiple; { if ( jr_malloc_is_suffix_same (bounds_marker_multiple) && jr_malloc_is_prefix_same (bounds_marker_multiple) ) { /* ** 9/4/07: to avoid the 'change' error below */ return; } if (jr_MallocNumBoundsMarkedPtrs > 0) { fprintf (stderr, "\n%s: already allocated bounds marked pointers, can't change multiple now\n", "jr_malloc_set_bounds_marker_multiple()" ); jr_coredump() ; } if (bounds_marker_multiple < 0 || bounds_marker_multiple > jr_MALLOC_MAX_BOUNDS_MARKER_MULTIPLE) { fprintf (stderr, "\n%s: multiple %d not in [0, %d]\n", "jr_malloc_set_bounds_marker_multiple()", bounds_marker_multiple, jr_MALLOC_MAX_BOUNDS_MARKER_MULTIPLE ); jr_coredump() ; } jr_malloc_set_suffix_multiple (bounds_marker_multiple); jr_malloc_set_prefix_multiple (bounds_marker_multiple); } void jr_malloc_set_no_memory_handler ( void (*handler_fn) (size_t)) { jr_MallocNoMemoryHandler = handler_fn; } void jr_MallocDefaultNoMemoryHandler ( size_t bytes_needed) { fprintf(stderr, "Out of memory.\n") ; exit(1) ; } unsigned jr_int jr_malloc_max_request_size() { return jr_MallocMaxRequestSize; } void jr_malloc_set_max_request_size (unsigned jr_int v) { jr_MallocMaxRequestSize = v; } jr_int jr_malloc_has_clear_on_free() { return jr_MallocClearOnFree; } void jr_malloc_set_clear_on_free (jr_int v) { jr_MallocClearOnFree = v != 0; } unsigned jr_int jr_malloc_num_calls() { return jr_MallocNumCalls; } void jr_malloc_set_num_calls (unsigned jr_int v) { jr_MallocNumCalls = v; } unsigned jr_int jr_malloc_num_unrecorded_calls() { return jr_MallocNumUnRecordedCalls; } static jr_int jr_MallocNumCppTranslationUnits = 0; static jr_int jr_MallocDumpWasDelayed = 0; static jr_int jr_MallocCheckLeaksWasDelayed = 0; void jr_malloc_begin_cpp_trans_unit_constructor () { jr_MallocRecordPtrsOnly = 1; jr_MallocNumCppTranslationUnits ++; } void jr_malloc_begin_cpp_trans_unit_destructor () { char error_buf[jr_ERROR_LEN]; jr_int status; jr_MallocNumCppTranslationUnits --; if (jr_MallocNumCppTranslationUnits == 0) { if (jr_MallocCheckLeaksWasDelayed) { status = jr_malloc_check_leaks_and_bounds (error_buf); if (status != 0) { fprintf (stderr, "jr_malloc() error: %s\n", error_buf); } } if (jr_MallocDumpWasDelayed) { jr_malloc_dump(); } } } void jr_malloc_end_cpp_trans_unit_constructor () { jr_MallocRecordPtrsOnly = 0; } jr_int jr_malloc_num_cpp_trans_units() { return jr_MallocNumCppTranslationUnits; } jr_int jr_malloc_record_ptrs_only () { return jr_MallocRecordPtrsOnly; } void jr_malloc_dump () { if (jr_malloc_num_cpp_trans_units() > 0) { jr_MallocDumpWasDelayed = 1; return; } jr_MallocDiagLock (jr_MallocDiagInfo); { jr_MallocDiagDump (jr_MallocDiagInfo); } jr_MallocDiagUnLock (jr_MallocDiagInfo); } jr_int jr_malloc_check_leaks_and_bounds (error_buf) char * error_buf; { jr_int num_open_files; jr_int status; if (jr_malloc_num_cpp_trans_units() > 0) { jr_MallocCheckLeaksWasDelayed = 1; return 0; } jr_MallocDiagLock (jr_MallocDiagInfo); if ( !jr_do_trace(jr_malloc_calls) && !jr_do_trace(jr_malloc_trap)) { jr_esprintf (error_buf, "can't check for leaks: jr_do_trace (jr_malloc_calls) not set"); status = -1; goto return_status; } num_open_files = jr_MallocDiagNumOpenFiles (jr_MallocDiagInfo, 0 /* wfp */, error_buf); if (num_open_files < 0) { status = -1; goto return_status; } status = jr_MallocDiagCheckLeaksAndBounds (jr_MallocDiagInfo, error_buf); if (status == 0) { if (num_open_files > 0) { jr_esprintf (error_buf, "%d files still open: (%s)", num_open_files, error_buf); status = -1; } } else { if (num_open_files > 0) { jr_esprintf (error_buf, "%.150s, %d files still open", error_buf, num_open_files); } else { } } if (jr_malloc_has_resource_leak ()) { if (status == 0) { jr_esprintf (error_buf, "application resource leak"); } else { jr_esprintf (error_buf, "%.150s, and application resource leak", error_buf); } status = -1; } return_status : { jr_MallocDiagUnLock (jr_MallocDiagInfo); } return status; } jr_int jr_malloc_num_open_files (opt_wfp, error_buf) FILE * opt_wfp; char * error_buf; { jr_int num_open_files; jr_MallocDiagLock (jr_MallocDiagInfo); { num_open_files = jr_MallocDiagNumOpenFiles (jr_MallocDiagInfo, opt_wfp, error_buf); } jr_MallocDiagUnLock (jr_MallocDiagInfo); if (num_open_files < 0) { return -1; } return num_open_files; } void (*jr_MallocNoMemoryHandler) (size_t) = jr_MallocDefaultNoMemoryHandler; static jr_mutex_t jr_MallocDiagMutex[1]; static jr_mutex_t jr_MallocStatMutex[1]; jr_thread_once_declare_and_init (DiagThreadOnceControl); jr_thread_once_declare_and_init (StatThreadOnceControl); static void jr_MallocDiagMutexInit () { jr_mutex_init (jr_MallocDiagMutex, 1); /* ** 3/23/07: can be recursive, since bookkeeping allocations and jr_MallocDiagDump() ** may call jr_malloc. The latter is ok to call MallocDiag routines since it ** will only do so when unlinking the trap file, and the former already ** has logic to deal with reentrant bookkeeping calls. */ } static void jr_MallocStatMutexInit () { jr_mutex_init (jr_MallocStatMutex, 0); } static void jr_MallocDiagLock (jr_MallocDiagStruct *mdp) { jr_thread_once_call (&DiagThreadOnceControl, jr_MallocDiagMutexInit); jr_mutex_lock (jr_MallocDiagMutex); } static void jr_MallocDiagUnLock (jr_MallocDiagStruct *mdp) { jr_mutex_unlock (jr_MallocDiagMutex); } static void jr_MallocStatLock () { jr_thread_once_call (&StatThreadOnceControl, jr_MallocStatMutexInit); jr_mutex_lock (jr_MallocStatMutex); } static void jr_MallocStatUnLock () { jr_mutex_unlock (jr_MallocStatMutex); }
frankjas/libjr
include/jr/esis/lib.h
<reponame>frankjas/libjr #ifndef __esis_lib_h___ #define __esis_lib_h___ #include "ezport.h" #include <stdio.h> #include "jr/alist.h" #include "jr/llist.h" #include "jr/htable.h" #include "jr/attribut.h" #define jr_ESIS_ILLEGAL_INPUT_ERROR -1; #define jr_ESIS_NOT_IMPLEMENTED_ERROR -2; #define jr_ESIS_NOT_CONFORMING_ERROR -3; #define jr_ESIS_EMBEDDED_NEWLINE (jr_INT_MIN + 1) #define jr_ESIS_SDATA_BRACKET_CHAR (jr_INT_MIN + 2) /******** Parsing Support ********/ extern jr_int jr_ESIS_getc PROTO (( FILE * rfp )); extern jr_int jr_ESIS_putc PROTO (( jr_int c, FILE * wfp )); extern char * jr_ESIS_ReadWordWithIsLast PROTO (( FILE * rfp, jr_AList * char_list, jr_int * is_last_ptr )); extern char * jr_ESIS_SaveWordWithIsLast PROTO (( FILE * rfp, jr_AList * char_list, jr_int * is_last_ptr )); #define jr_ESIS_ReadWord(rfp, char_list) jr_ESIS_ReadWordWithIsLast (rfp, char_list, 0) #define jr_ESIS_SaveWord(rfp, char_list) jr_ESIS_SaveWordWithIsLast (rfp, char_list, 0) extern char * jr_ESIS_ReadData PROTO (( FILE * rfp, jr_AList * char_list )); extern char * jr_ESIS_SaveData PROTO (( FILE * rfp, jr_AList * char_list )); /******** Tree Support ********/ typedef struct { jr_LList data_list [1]; } jr_ESIS_ElementList; typedef struct { jr_AList data_list [1]; } jr_ESIS_ElementStack; typedef struct { char * name_str; jr_ESIS_ElementList element_list [1]; } jr_ESIS_GenericElementType; typedef struct { jr_AttributeList attr_list[1]; jr_ESIS_ElementList sub_element_list [1]; void * parent_element_ptr; jr_AList data_list[1]; } jr_ESIS_ElementType; typedef struct { char * attr_name_str; char * opt_generic_name_str; jr_HTable attr_value_table[1]; } jr_ESIS_IndexType; typedef struct { char * attr_value_str; jr_ESIS_ElementList matching_element_list[1]; } jr_ESIS_IndexValueType; /******* ESIS Tree ********/ typedef struct { jr_AttributeManagerType * attr_manager; jr_HTable generic_element_table[1]; jr_ESIS_ElementList element_list[1]; jr_ESIS_ElementStack element_stack[1]; } jr_ESIS_TreeType; extern void jr_ESIS_TreeInit PROTO (( jr_ESIS_TreeType * tree_info, jr_AttributeManagerType * attr_manager )); extern void jr_ESIS_TreeUndo PROTO (( jr_ESIS_TreeType * tree_info )); extern jr_ESIS_ElementType *jr_ESIS_TreeNewElementPtr PROTO (( jr_ESIS_TreeType * tree_info, jr_ESIS_ElementType * parent_element_ptr )); #define jr_ESIS_TreeStackTop(tree_info) \ jr_ESIS_ElementStackTop ((tree_info)->element_stack) #define jr_ESIS_TreeStackPop(tree_info) \ jr_ESIS_ElementStackPop ((tree_info)->element_stack) #define jr_ESIS_TreeStackPush(tree_info, v) \ jr_ESIS_ElementStackPush ((tree_info)->element_stack, v) /******** Element Stack ********/ #define jr_ESIS_ElementStackPush(stack, el_ptr) \ jr_AListNativeSetNewTail ((stack)->data_list, el_ptr, jr_ESIS_ElementType *) #define jr_ESIS_ElementStackTop(stack) \ jr_AListNativeTail ((stack)->data_list, jr_ESIS_ElementType *) #define jr_ESIS_ElementStackPop(stack) \ jr_AListNativeDeletedTail ((stack)->data_list, jr_ESIS_ElementType *) #endif
frankjas/libjr
libjr/io/mailtime.c
#include "mailproj.h" #include <setjmp.h> #include <signal.h> static sigjmp_buf JumpBuffer ; static void local_alarm_handler(signum) int signum ; { siglongjmp (JumpBuffer , 17) ; } jr_int jr_MailServerValidateWithTimeOut ( smtp_server_name, opt_sender_address, time_out_seconds, error_buf ) const char * smtp_server_name; const char * opt_sender_address; jr_int time_out_seconds; char * error_buf; { struct sigaction new_action[1]; struct sigaction old_action[1]; jr_int prev_alarm_time ; jr_int timed_out; jr_int status; if (sigsetjmp (JumpBuffer, 1) == 0) { /* * If we are inside this condition then * this is the first time that setjmp was called * and we should therefore set up the signal handler * and alarm values before we begin the "timed work". */ new_action->sa_handler = local_alarm_handler; sigemptyset (&new_action->sa_mask); new_action->sa_flags = SA_RESTART; prev_alarm_time = alarm(0); sigaction (SIGALRM, new_action, old_action) ; alarm (time_out_seconds); /* timed work */ status = jr_MailServerValidate ( smtp_server_name, opt_sender_address, error_buf ); timed_out = 0; } else { /* * If we are inside this condition, then the alarm * went off and we weren't done reading. */ timed_out = 1; } /* reset the old alarm and handler */ alarm (0); sigaction(SIGALRM , old_action , 0) ; alarm(prev_alarm_time) ; if (timed_out) { jr_esprintf (error_buf, "connect timed out"); status = jr_INET_TIMED_OUT; } return status; } jr_int jr_MailAddressValidateWithTimeOut ( recipient_address, smtp_server_name, sender_address, time_out_seconds, error_buf ) const char * recipient_address; const char * smtp_server_name; const char * sender_address; jr_int time_out_seconds; char * error_buf; { struct sigaction new_action[1]; struct sigaction old_action[1]; jr_int prev_alarm_time ; jr_int timed_out; jr_int status; if (sigsetjmp (JumpBuffer, 1) == 0) { /* * If we are inside this condition then * this is the first time that setjmp was called * and we should therefore set up the signal handler * and alarm values before we begin the "timed work". */ new_action->sa_handler = local_alarm_handler; sigemptyset (&new_action->sa_mask); new_action->sa_flags = SA_RESTART; prev_alarm_time = alarm(0); sigaction (SIGALRM, new_action, old_action) ; alarm (time_out_seconds); /* timed work */ status = jr_MailAddressValidate ( recipient_address, smtp_server_name, sender_address, error_buf ); timed_out = 0; } else { /* * If we are inside this condition, then the alarm * went off and we weren't done reading. */ timed_out = 1; } /* reset the old alarm and handler */ alarm (0); sigaction(SIGALRM , old_action , 0) ; alarm(prev_alarm_time) ; if (timed_out) { jr_esprintf (error_buf, "connect timed out"); status = jr_INET_TIMED_OUT; } return status; }
frankjas/libjr
libjr/string/pathtail.c
#define _POSIX_SOURCE 1 #include "ezport.h" #include <string.h> #include "jr/string.h" const char *jr_PathTail (file_path) const char * file_path; { const char * path_tail; path_tail = strrchr (file_path, '/'); if (path_tail) { path_tail ++; } else { path_tail = file_path; } return path_tail; } const char *jr_GetTrailingPath (path_string, trailing_path_buf, trailing_path_buf_size) const char * path_string; char * trailing_path_buf; jr_int trailing_path_buf_size; { jr_int path_length = (jr_int) strlen (path_string); if (path_length < trailing_path_buf_size) { strcpy (trailing_path_buf, path_string); } else { strcpy (trailing_path_buf, "..."); strcat ( trailing_path_buf, path_string + path_length - (trailing_path_buf_size - 3 - 1) ); } return trailing_path_buf; } void jr_NormalizePath ( char * file_path) { jr_int q; char * second_last_separator = 0; for (q=0; file_path[q]; q++) { if ( q >= 1 && file_path[q-1] == '/' && file_path[q] == '/') { /* ** 11/24/06 ** transform: "/home/frank/src/cw//libcw/cw_mod.c" ** into: "/home/frank/src/cw/libcw/cw_mod.c" */ memmove (file_path + q, file_path + q+1, strlen (file_path + q+1) + 1); q -= 1; } else if ( q >= 2 && file_path[q-2] == '/' && file_path[q-1] == '.' && file_path[q] == '/') { /* ** 11/24/06 ** transform: "/home/frank/src/cw/./libcw/cw_mod.c" ** into: "/home/frank/src/cw/libcw/cw_mod.c" */ memmove (file_path + q-1, file_path + q+1, strlen (file_path + q+1) + 1); q -= 2; } else if ( q >= 3 && second_last_separator && file_path[q-3] == '/' && file_path[q-2] == '.' && file_path[q-1] == '.' && file_path[q] == '/') { /* ** 12/31/06 ** transform: "/home/frank/src/cw/../libjr/alist/alist.c" ** into: "/home/frank/src/libjr/alist/alist.c" */ memmove (second_last_separator + 1, file_path + q+1, strlen (file_path + q+1) + 1); q = second_last_separator - file_path; } if (file_path[q] == '/') { second_last_separator = jr_rstrchr (file_path + q - 1, file_path, '/'); } } if ( q >= 2 && file_path[q-2] == '/' && file_path[q-1] == '.') { /* ** 11/24/06 ** transform: "/home/frank/src/cw/." ** into: "/home/frank/src/cw/" */ file_path[q-1] = 0; q -= 1; } if ( q >= 3 && file_path[q-3] == '/' && file_path[q-2] == '.' && file_path[q-1] == '.') { /* ** 11/24/06 ** transform: "/home/frank/src/cw/.." ** into: "/home/frank/src/" */ file_path[second_last_separator + 1 - file_path] = 0; q = second_last_separator + 1 - file_path; } if ( q >= 1 && file_path[q-1] == '/') { /* ** 11/24/06 ** transform: "/home/frank/src/cw/" ** into: "/home/frank/src/cw" */ file_path[q-1] = 0; q -= 1; } }
frankjas/libjr
libjr/io/paragrph.c
#define _POSIX_SOURCE 1 #include "ezport.h" #include <stdio.h> #include <string.h> #include <stdlib.h> #ifndef missing_regex_h # include <regex.h> #endif #include "jr/inputbuf.h" #include "jr/string.h" #include "jr/trace.h" #include "jr/paragrph.h" #include "jr/malloc.h" char * jr_ParagraphReadNewString(paragraph_info, input_buffer) jr_ParagraphStateInfoType * paragraph_info ; jr_IB_InputBuffer * input_buffer ; { jr_AList * result_listbuf = paragraph_info->result_listbuf ; char * push_back_string = 0 ; jr_int did_read_line = 0 ; jr_ParagraphStart(paragraph_info) ; /* re-sets initial values of some fields */ jr_ParagraphReadLine(paragraph_info, input_buffer) ; /* this reads the heading, or minimum allowed text in a paragraph (1 line) */ if (jr_is_trace_at_level(jr_io,2)) { fprintf(stderr,"Heading: {%s}", jr_ParagraphCurrentParagraphPtr(paragraph_info)) ; } if (paragraph_info->paragraph_ends_with_unescaped_newline) { if (paragraph_info->number_of_unescaped_newlines > 0) { jr_ParagraphSkipToNonBlankOrCommentLine(paragraph_info, input_buffer) ; if (jr_is_trace_at_level(jr_io,2)) { fprintf(stderr, "Stopping at unescaped newline\n") ; } goto return_point ; } } /* * This loop will absorb trailing blank lines and other text until * we see the start of another paragraph. */ while (did_read_line = jr_ParagraphReadLine(paragraph_info, input_buffer)) { if (jr_is_trace_at_level(jr_io,2)) { fprintf(stderr,"Offset %d: {%s}", paragraph_info->current_line_starting_index, paragraph_info->current_line_ptr ) ; } push_back_string = 0 ; if (paragraph_info->paragraph_ends_with_unescaped_newline) { if (paragraph_info->number_of_unescaped_newlines > 0) { jr_ParagraphSkipToNonBlankOrCommentLine(paragraph_info, input_buffer) ; if (jr_is_trace_at_level(jr_io,2)) { fprintf(stderr, "Stopping at unescaped newline\n") ; } break ; } } if (paragraph_info->paragraph_ends_with_blank_line) { if (! paragraph_info->current_line_is_blank_or_comment) { if (paragraph_info->number_of_blank_lines > 0) { push_back_string = jr_ParagraphCurrentLinePtr(paragraph_info) ; if (jr_is_trace_at_level(jr_io,2)) { fprintf(stderr, "Stopping at blank line\n") ; } break ; } } } if (! paragraph_info->current_line_is_blank_or_comment) { if (paragraph_info->paragraph_starts_with_indent_less_than) { if (jr_is_trace_at_level(jr_io,2)) { fprintf(stderr, "Testing current indent %d < allowable indent %d\n", paragraph_info->current_line_indentation, paragraph_info->end_indentation ) ; } if (paragraph_info->current_line_indentation < paragraph_info->end_indentation) { push_back_string = jr_ParagraphCurrentLinePtr(paragraph_info) ; if (jr_is_trace_at_level(jr_io,2)) { fprintf(stderr, "Stopping because line indent %d, less than allowed %d\n", paragraph_info->current_line_indentation, paragraph_info->end_indentation ) ; } break ; } else { if (jr_is_trace_at_level(jr_io,2)) { fprintf(stderr, "Indent allowed continuation of paragraph\n") ; } } } if (paragraph_info->paragraph_starts_with_indent_greater_than) { if (jr_is_trace_at_level(jr_io,2)) { fprintf(stderr, "Testing current indent %d > allowable indent %d\n", paragraph_info->current_line_indentation, paragraph_info->end_indentation ) ; } if (paragraph_info->current_line_indentation > paragraph_info->end_indentation) { push_back_string = jr_ParagraphCurrentLinePtr(paragraph_info) ; if (jr_is_trace_at_level(jr_io,2)) { fprintf(stderr, "Stopping because line indent %d, more than allowed %d\n", paragraph_info->current_line_indentation, paragraph_info->end_indentation ) ; } break ; } else { if (jr_is_trace_at_level(jr_io,2)) { fprintf(stderr, "Indent allowed continuation of paragraph\n") ; } } } } if (paragraph_info->paragraph_starts_with_regular_expression) { if (paragraph_info->end_expression) { /* char * current_line_of_text = jr_ParagraphCurrentLinePtr(paragraph_info) ; if (recmp(paragraph_info->end_expression, current_line_of_text) == 0) { push_back_string = current_line_of_text ; if (jr_is_trace_at_level(jr_io,2)) { fprintf(stderr, "Stopping cuz regular current line matched expression '%s'\n", paragraph_info->end_expression ) ; } break ; } */ } } } return_point : ; if (push_back_string) { char * start_of_paragraph ; jr_int length_of_paragraph ; start_of_paragraph = jr_ParagraphCurrentParagraphPtr(paragraph_info) ; length_of_paragraph = push_back_string - start_of_paragraph ; if (jr_is_trace_at_level(jr_io,2)) { fprintf(stderr, "Pushing back {%s} on the input for start of next paragraph.\n", push_back_string ) ; } jr_IB_ungetstring(input_buffer, push_back_string) ; *push_back_string = 0 ; jr_AListSetSize(result_listbuf, length_of_paragraph) ; } if ((jr_AListSize(result_listbuf) <= 1) && (did_read_line == 0)) { if (jr_is_trace_at_level(jr_io,2)) { fprintf(stderr, "Returning 0 at AListSize %d.\n", jr_AListSize(result_listbuf) ) ; } return(0) ; } else { char * new_string ; new_string = jr_strdup(jr_AListHeadPtr(result_listbuf)) ; if (jr_is_trace_at_level(jr_io,2)) { fprintf(stderr, "Returning paragraph string at AListSize %d.\n", jr_AListSize(result_listbuf) ) ; } return(new_string) ; } } void jr_ParagraphStateInfoInit(paragraph_info, end_indentation, end_expression, comment_character, flags) jr_ParagraphStateInfoType * paragraph_info ; jr_int end_indentation ; const char * end_expression ; jr_int comment_character ; jr_int flags ; { memset(paragraph_info, 0, sizeof(*paragraph_info)) ; jr_AListInit(paragraph_info->result_listbuf, sizeof(char)) ; paragraph_info->end_indentation = end_indentation ; if (end_expression) { paragraph_info->end_expression = jr_strdup(end_expression) ; } paragraph_info->comment_character = comment_character ; paragraph_info->current_line_indentation = -1 ; paragraph_info->previous_line_indentation = -1 ; paragraph_info->heading_line_indentation = -1 ; if (flags & jr_PARAGRAPH_ENDS_WITH_BLANK_LINE) paragraph_info->paragraph_ends_with_blank_line = 1 ; if (flags & jr_PARAGRAPH_ENDS_WITH_UNESCAPED_NEWLINE) paragraph_info->paragraph_ends_with_unescaped_newline = 1 ; if (flags & jr_PARAGRAPH_STARTS_WITH_INDENT_LESS_THAN) paragraph_info->paragraph_starts_with_indent_less_than = 1 ; if (flags & jr_PARAGRAPH_STARTS_WITH_INDENT_GREATER_THAN) paragraph_info->paragraph_starts_with_indent_greater_than = 1 ; if (flags & jr_PARAGRAPH_STARTS_WITH_REGULAR_EXPRESSION) paragraph_info->paragraph_starts_with_regular_expression = 1 ; if (flags & jr_PARAGRAPH_PRESERVE_INDENTATION) paragraph_info->paragraph_preserve_indentation = 1 ; } void jr_ParagraphStart(paragraph_info) jr_ParagraphStateInfoType * paragraph_info ; { jr_AListEmpty(paragraph_info->result_listbuf) ; paragraph_info->number_of_unescaped_newlines = 0 ; paragraph_info->current_line_indentation = -1 ; paragraph_info->previous_line_indentation = -1 ; paragraph_info->heading_line_indentation = -1 ; paragraph_info->number_of_blank_lines = 0 ; paragraph_info->current_line_is_blank_or_comment = 1 ; paragraph_info->first_non_white_this_line = 0 ; paragraph_info->current_line_starting_index = 0 ; paragraph_info->previous_line_starting_index = 0 ; } void jr_ParagraphStateInfoUndo(paragraph_info) jr_ParagraphStateInfoType * paragraph_info ; { if (paragraph_info->end_expression) { jr_free(paragraph_info->end_expression) ; } jr_AListUndo(paragraph_info->result_listbuf) ; memset(paragraph_info, 0, sizeof(*paragraph_info)) ; } jr_int jr_ParagraphReadLine(paragraph_info, input_buffer) jr_ParagraphStateInfoType * paragraph_info ; jr_IB_InputBuffer * input_buffer ; { jr_AList * result_listbuf = paragraph_info->result_listbuf ; jr_int this_char ; jr_int previous_char ; jr_int newline = '\n' ; jr_int back_slash = '\\' ; jr_int number_of_contiguous_back_slashes ; if (jr_AListSize(result_listbuf) > 0) { jr_int end_char ; end_char = jr_AListNativeTail(result_listbuf, char) ; if (end_char == 0) { /* * We had put a null on the end to keep the thing a valid string. * Now remove the null before continuing to fillup characters * in that string. */ if (jr_is_trace_at_level(jr_io,2)) { fprintf(stderr, "Deleting null placed after end-of-line in AList of size %d.\n", jr_AListSize(result_listbuf) ) ; } jr_AListDeletedTailPtr(result_listbuf) ; } } paragraph_info->previous_line_starting_index = paragraph_info->current_line_starting_index ; paragraph_info->previous_line_ptr = jr_ParagraphCurrentLinePtr(paragraph_info) ; paragraph_info->previous_line_indentation = paragraph_info->current_line_indentation ; paragraph_info->current_line_starting_index = jr_AListSize(result_listbuf) ; number_of_contiguous_back_slashes = 0 ; paragraph_info->current_line_is_blank_or_comment = 1 ; paragraph_info->first_non_white_this_line = 0 ; for (previous_char = 0; ((this_char = jr_IB_getc(input_buffer)) != EOF) ; previous_char = this_char) { if (previous_char == 0) { paragraph_info->current_line_indentation = 0 ; } if (this_char == newline) { jr_AListNativeSetNewTail(result_listbuf, this_char, char) ; if ((previous_char == back_slash) && (number_of_contiguous_back_slashes % 2)) { if (jr_is_trace_at_level(jr_io,2)) { fprintf(stderr,"Odd number of backslashes at end count as escape no added line\n") ; } } else { if (jr_is_trace_at_level(jr_io,2)) { fprintf(stderr,"Even number of backslashes at end of line don't count as escape\n") ; } paragraph_info->number_of_unescaped_newlines++ ; } break ; } if ((this_char != newline) && isspace(this_char)) { if (paragraph_info->first_non_white_this_line == 0) { paragraph_info->current_line_indentation++ ; if (paragraph_info->paragraph_preserve_indentation) { /* preserving white space */ } else { continue ; } } } else if (! isspace(this_char)) { if (paragraph_info->first_non_white_this_line == 0) { paragraph_info->first_non_white_this_line = this_char ; } paragraph_info->current_line_is_blank_or_comment = 0 ; } if (this_char == back_slash) { number_of_contiguous_back_slashes++ ; } else { number_of_contiguous_back_slashes = 0 ; } jr_AListNativeSetNewTail(result_listbuf, this_char, char) ; } if (paragraph_info->comment_character && (paragraph_info->first_non_white_this_line == paragraph_info->comment_character)) { paragraph_info->current_line_is_blank_or_comment++ ; } if (paragraph_info->current_line_is_blank_or_comment) { paragraph_info->number_of_blank_lines++ ; } if (paragraph_info->heading_line_indentation < 0) { paragraph_info->heading_line_indentation = paragraph_info->current_line_indentation ; } jr_AListNativeSetNewTail(result_listbuf, 0, char) ; /* null out the end of this string */ paragraph_info->current_line_ptr = jr_ParagraphCurrentLinePtr(paragraph_info) ; if ((this_char == EOF) && (previous_char == 0)) { /* * We didn't manage to read even one character before hitting EOF */ return(0) ; } else { return(1) ; } } jr_int jr_ParagraphCurrentLineIsBlankOrComment(paragraph_info) jr_ParagraphStateInfoType * paragraph_info ; { char * start_of_text = 0; if (! paragraph_info->current_line_ptr) return(1) ; for (start_of_text = paragraph_info->current_line_ptr ; *start_of_text; start_of_text++) { if (*start_of_text == '\n') return(1) ; if (*start_of_text == paragraph_info->comment_character) return(1) ; if (isspace(*start_of_text)) continue ; break ; } return(0) ; } char * jr_ParagraphCurrentLinePtr(paragraph_info) jr_ParagraphStateInfoType * paragraph_info ; { jr_AList * result_listbuf = paragraph_info->result_listbuf ; char * current_line_ptr ; current_line_ptr = jr_AListElementPtr( result_listbuf, paragraph_info->current_line_starting_index ) ; return(current_line_ptr) ; } char * jr_ParagraphCurrentParagraphPtr(paragraph_info) jr_ParagraphStateInfoType * paragraph_info ; { jr_AList * result_listbuf = paragraph_info->result_listbuf ; char * current_paragraph_ptr ; current_paragraph_ptr = jr_AListHeadPtr(result_listbuf) ; return(current_paragraph_ptr) ; } void jr_ParagraphSkipToNonBlankOrCommentLine(paragraph_info, input_buffer) jr_ParagraphStateInfoType * paragraph_info ; jr_IB_InputBuffer * input_buffer ; { jr_AList * result_listbuf = paragraph_info->result_listbuf ; while(jr_ParagraphReadLine(paragraph_info, input_buffer)) { if (! jr_ParagraphCurrentLineIsBlankOrComment(paragraph_info)) { char * push_back_string ; char * start_of_paragraph ; jr_int length_of_paragraph ; push_back_string = jr_ParagraphCurrentLinePtr(paragraph_info) ; start_of_paragraph = jr_ParagraphCurrentParagraphPtr(paragraph_info) ; length_of_paragraph = push_back_string - start_of_paragraph ; jr_IB_ungetstring(input_buffer, push_back_string) ; *push_back_string = 0 ; jr_AListSetSize(result_listbuf, length_of_paragraph) ; break ; } } }
frankjas/libjr
libjr/jr_malloc/memdup.c
#include "ezport.h" #include <string.h> #include "jr/malloc.h" void * jr_memdup (p, n) const void * p; size_t n; { void * np ; np = (void *) jr_malloc (n); memcpy(np, p, n) ; return(np) ; }
frankjas/libjr
libjr/misc/shortstr.c
#include "ezport.h" #include <limits.h> #include "jr/misc.h" /* Author: <NAME> Creation Date: March 1987 */ jr_int jr_shortstrcmp (is1, is2) const short *is1 ; const short *is2; { for (; *is1 != jr_SHRT_NULL; is1++, is2++) { if (*is2 == jr_SHRT_NULL) return (1); if (*is1 != *is2) return (*is1 - *is2); } if (*is2 == jr_SHRT_NULL) return (0); return (-1); /* is1 is shorter, hence it comes before is2 */ } jr_int shortstrlen (is) const short *is; { jr_int n; for (n = 0; *is != jr_SHRT_NULL; is++, n++); return (n); } jr_int jr_shortstrbytes (is) const short *is; { jr_int n; for (n = 0; *is != jr_SHRT_NULL; is++, n++); return ((n + 1) * sizeof(short)); } jr_int jr_shortstrhash (is) const short *is; { jr_int len = shortstrlen (is), sub = len / 3, val; /* a hashing function derived from Knuth's fundamental algorithms */ /* is not good if the integers are uniformly small (i.e. < 20) */ val = (*is + *(is+sub) + *(is+2*sub) + *(is+len-1)+len) * len; if (val < 0) return (-val); return (val); } jr_int jr_shortstrlenhash (is, len) const short * is ; jr_int len; /* a hashing function derived from Knuth's * fundamental algorithms */ { jr_int sub = len / 3, val; len /= sizeof(short); /* len is in bytes, we need the number of ints to avoid * running off the end of is */ sub = len / 3, val = (*is + *(is+sub) + *(is+2*sub) + *(is+len-1)+len) * len; if (val < 0) return (-val); return (val); }
frankjas/libjr
libjr/syscalls/jr_stat.c
#include "jr_apr.h" void jr_stat_init ( jr_stat_t * jr_stat_ptr) { memset (jr_stat_ptr, 0, sizeof (*jr_stat_ptr)); } void jr_stat_asgn_apr_finfo ( jr_stat_t * jr_stat_ptr, const apr_finfo_t * apr_finfo_ptr) { jr_stat_init (jr_stat_ptr); if (sizeof (apr_finfo_ptr->size) <= sizeof (jr_int)) { jr_ULongAsgnUInt (&jr_stat_ptr->file_size, apr_finfo_ptr->size); } else { jr_ULongAsgn64 (&jr_stat_ptr->file_size, apr_finfo_ptr->size); } jr_stat_ptr->mtime = apr_time_sec (apr_finfo_ptr->mtime); jr_stat_ptr->atime = apr_time_sec (apr_finfo_ptr->atime); jr_stat_ptr->ctime = apr_time_sec (apr_finfo_ptr->ctime); jr_stat_ptr->perms = jr_AprPermsToPerms (apr_finfo_ptr->protection); switch (apr_finfo_ptr->filetype) { case APR_REG : jr_stat_ptr->is_file = 1; break; case APR_DIR : jr_stat_ptr->is_directory = 1; break; case APR_LNK : jr_stat_ptr->is_link = 1; break; case APR_CHR : jr_stat_ptr->is_char_dev = 1; break; default : break; } } jr_int jr_stat_common ( const char * file_name, jr_stat_t * opt_jr_stat_ptr, jr_int flags, const char ** opt_user_name_ref, const char ** opt_group_name_ref, char * error_buf) { apr_finfo_t apr_finfo[1]; apr_pool_t * apr_pool_ptr = 0; jr_int info_bits = APR_FINFO_NORM; jr_int status; jr_apr_initialize(); apr_pool_create (&apr_pool_ptr, NULL); if (flags & jr_STAT_GET_LINK_INFO) { info_bits |= APR_FINFO_LINK; } status = apr_stat (apr_finfo, file_name, info_bits, apr_pool_ptr); if (status != 0) { jr_esprintf (error_buf, "%s", jr_apr_strerror( status, error_buf)); status = jr_ConvertAprErrno (status); goto return_status; } status = jr_stat_prepare_return( opt_jr_stat_ptr, flags, opt_user_name_ref, opt_group_name_ref, apr_finfo, apr_pool_ptr, error_buf ); if (status != 0) { goto return_status; } status = 0; return_status : { apr_pool_destroy (apr_pool_ptr); } return status; } jr_int jr_stat_prepare_return ( jr_stat_t * opt_jr_stat_ptr, jr_int flags, const char ** opt_user_name_ref, const char ** opt_group_name_ref, apr_finfo_t * apr_finfo, apr_pool_t * apr_pool_ptr, char * error_buf) { char * user_name = 0; char * group_name = 0; jr_int status; if (opt_user_name_ref) { status = apr_uid_name_get (&user_name, apr_finfo->user, apr_pool_ptr); if (status != 0 && !(flags & jr_STAT_IGNORE_UID_ERRORS)) { jr_esprintf (error_buf, "couldn't get user name: %s", jr_apr_strerror( status, error_buf) ); status = jr_ConvertAprErrno (status); goto return_status; } } if (opt_group_name_ref) { status = apr_gid_name_get (&group_name, apr_finfo->group, apr_pool_ptr); if (status != 0 && !(flags & jr_STAT_IGNORE_UID_ERRORS)) { jr_esprintf (error_buf, "couldn't get group name: %s", jr_apr_strerror( status, error_buf) ); status = jr_ConvertAprErrno (status); goto return_status; } } status = 0; if (opt_jr_stat_ptr) { jr_stat_asgn_apr_finfo (opt_jr_stat_ptr, apr_finfo); } if (opt_user_name_ref) { if (user_name) { *opt_user_name_ref = jr_strdup (user_name); } else { *opt_user_name_ref = 0; } } if (opt_group_name_ref) { if (group_name) { *opt_group_name_ref = jr_strdup (group_name); } else { *opt_group_name_ref = 0; } } return_status : { } return status; } jr_int jr_stat_mtime_cmp ( const void * void_ptr_1, const void * void_ptr_2) { const jr_stat_t * jr_stat_ptr_1 = void_ptr_1; const jr_stat_t * jr_stat_ptr_2 = void_ptr_2; if (jr_stat_ptr_1->mtime > jr_stat_ptr_2->mtime) { return 1; } if (jr_stat_ptr_1->mtime < jr_stat_ptr_2->mtime) { return -1; } return 0; } /* ** 3-15-2013: apr_file_mtime_set() is part of filestat.c in APR */ jr_int jr_FileNameSetMtime ( const char * file_path, jr_seconds_t time_sec, char * error_buf) { apr_pool_t * apr_pool_ptr; apr_time_t apr_time_sec = time_sec * 1000000LL; jr_int status; jr_apr_initialize(); apr_pool_create (&apr_pool_ptr, NULL); status = apr_file_mtime_set (file_path, apr_time_sec, apr_pool_ptr); if (status != 0) { jr_esprintf (error_buf, "%s", jr_apr_strerror( status, error_buf)); status = jr_ConvertAprErrno (status); goto return_status; } status = 0; return_status : { apr_pool_destroy (apr_pool_ptr); } return status; } jr_int jr_FileNameGetMtime ( const char * file_path, jr_seconds_t * time_sec_ref, char * error_buf) { jr_stat_t stat_info[1]; jr_int status; jr_stat_init( stat_info); status = jr_stat( file_path, stat_info, error_buf); if (status != 0) { goto return_status; } *time_sec_ref = jr_stat_mtime( stat_info); status = 0; return_status : { } return status; }
frankjas/libjr
libjr/misc/hashstr.c
<reponame>frankjas/libjr #include "jr/misc.h" #include <limits.h> #include <ctype.h> #include <string.h> jr_int jr_strhash_old (void_arg_1) const void * void_arg_1; { const char * str = void_arg_1; size_t length = strlen (str); unsigned jr_int hash_value = 0; jr_int i; for (i=0; str[i]; i++) { hash_value += str[i]; } hash_value *= (unsigned jr_int) length; return hash_value; } /* .bp */ #define BITS_IN_int (sizeof (jr_int) * CHAR_BIT) #define THREE_QUARTERS ((jr_int) ((BITS_IN_int * 3) / 4)) #define ONE_EIGHTH ((jr_int) (BITS_IN_int / 8)) #define HIGH_BITS ( ~((unsigned jr_int) (~0) >> ONE_EIGHTH)) jr_int jr_strhash_pjw (void_arg_1) const void * void_arg_1; { const char * string = void_arg_1; /* * An adaptation of <NAME>'s generic hashing algorithm * based on <NAME>'s version. From Dr. Dobbs, April, 1996 */ unsigned jr_int hash_value; jr_int i; for (hash_value = 0; *string; string++) { hash_value = (hash_value << ONE_EIGHTH) + *string; if ((i = hash_value & HIGH_BITS) != 0) { hash_value = (hash_value ^ (i >> THREE_QUARTERS)) & ~HIGH_BITS; } } return hash_value; } jr_int jr_strcasehash_pjw (void_arg_1) const void * void_arg_1; { const char * string = void_arg_1; /* * An adaptation of <NAME>'s generic hashing algorithm * based on <NAME>'s version. From Dr. Dobbs, April, 1996 */ unsigned jr_int hash_value; jr_int i; for (hash_value = 0; *string; string++) { hash_value = (hash_value << ONE_EIGHTH) + toupper (*string); if ((i = hash_value & HIGH_BITS) != 0) { hash_value = (hash_value ^ (i >> THREE_QUARTERS)) & ~HIGH_BITS; } } return hash_value; } jr_int jr_strhash (void_arg_1) const void * void_arg_1; { const char * str = void_arg_1; size_t length = strlen (str); jr_int hash_value = 0; jr_int i; for (i=0; str[i]; i++) { hash_value += str[i] * ((unsigned jr_int) length + i); } return hash_value; }
frankjas/libjr
libjr/syscalls/jr_unlink.c
#include "ezport.h" #include <apr-1/apr_pools.h> #include <apr-1/apr_file_io.h> #include "jr/syscalls.h" #include "jr/apr.h" #include "jr/error.h" jr_int jr_Unlink ( const char * file_path, char * error_buf) { apr_pool_t * apr_pool_ptr; jr_int status; jr_apr_initialize(); apr_pool_create (&apr_pool_ptr, NULL); status = apr_file_remove (file_path, apr_pool_ptr); if (status != 0) { jr_esprintf (error_buf, "%s", jr_apr_strerror( status, error_buf)); status = jr_ConvertAprErrno (status); goto return_status; } status = 0; return_status : { apr_pool_destroy (apr_pool_ptr); } return status; }
frankjas/libjr
libjr/replace/getenv.c
#define _POSIX_SOURCE 1 #include "ezport.h" #ifdef replace_buggy_getenv #include <stdlib.h> #include <string.h> #undef getenv extern char **environ; char *jr_system_getenv (search_str) const char * search_str ; { char ** vp ; char * ptr_to_lhs ; char * ptr_to_equal_sign ; int search_length ; int length_of_current_lhs ; search_length = strlen(search_str) ; for (vp = environ ; *vp; vp++) { ptr_to_lhs = *vp ; ptr_to_equal_sign = strchr(ptr_to_lhs, '=') ; if (ptr_to_equal_sign == 0) continue ; length_of_current_lhs = (ptr_to_equal_sign - ptr_to_lhs) ; if (length_of_current_lhs != search_length) continue ; if (strncmp(search_str, ptr_to_lhs, search_length) == 0) { return(ptr_to_equal_sign + 1) ; } } return(0) ; } #else static void NotCalled () /* define this so ranlib doesn't complain */ { NotCalled (); /* use it so the compiler doesn't complain */ } #endif
frankjas/libjr
libjr/struct/bitset.c
#define _POSIX_SOURCE 1 #include "ezport.h" #include <stdio.h> #include <string.h> #include "jr/bitset.h" #include "jr/misc.h" #include "jr/malloc.h" void jr_BitSetInit (bset, num_bits) jr_BitSet * bset; jr_int num_bits; { memset (bset, 0, sizeof (*bset)); if (num_bits > 0) { jr_BitSetChangeNumBits (bset, num_bits); } } void jr_BitSetUndo (bset) jr_BitSet * bset; { if (bset->int_array) { jr_free (bset->int_array); } } jr_BitSet *jr_BitSetCreate (num_bits) jr_int num_bits; { jr_BitSet * bset = jr_malloc (sizeof (jr_BitSet)); jr_BitSetInit (bset, num_bits); return bset; } void jr_BitSetDestroy (bset) jr_BitSet * bset; { jr_BitSetUndo (bset); jr_free (bset); } void jr_BitSetChangeNumBits (bset, new_num_bits) jr_BitSet * bset; jr_int new_num_bits; { jr_int old_num_ints; jr_int new_num_ints; jr_int num_last_bits; jr_int last_bits_mask; jr_int i; if (new_num_bits <= bset->num_bits) { /* * 7/23/2005: don't deallocate if the bit set is shrinking, since * if the application is changing the bit set size, it's likely to be * changed upward again. * If the application wants to deallocate a large bit set and get a small one * then undo and re-init. */ bset->num_bits = new_num_bits; return; } old_num_ints = bset->num_bits >> jr_INT_BIT_SIZE_POWER; /* division */ new_num_ints = new_num_bits >> jr_INT_BIT_SIZE_POWER; /* division */ if (bset->num_bits & jr_INT_BIT_SIZE_MASK) { /* mod */ old_num_ints++; } if (new_num_bits & jr_INT_BIT_SIZE_MASK) { /* mod */ new_num_ints++; } if (new_num_ints > old_num_ints) { bset->int_array = jr_realloc (bset->int_array, new_num_ints * sizeof (jr_int)); } /* * zero the new bits, first do the partial int at the end of the old int_array */ num_last_bits = bset->num_bits & jr_INT_BIT_SIZE_MASK; /* mod by bits-per-int */ last_bits_mask = 0xffffffff >> (sizeof (jr_int) * CHAR_BIT - num_last_bits); if (old_num_ints > 0) { bset->int_array[old_num_ints - 1] &= last_bits_mask; } for (i = old_num_ints; i < new_num_ints; i++) { bset->int_array[i] = 0; } bset->num_bits = new_num_bits; } void jr_BitSetUnion (bsetc, bseta, bsetb) jr_BitSet *bsetc; jr_BitSet *bseta; jr_BitSet *bsetb; { jr_BitSetEmpty (bsetc); jr_BitSetAddSet (bsetc, bseta); jr_BitSetAddSet (bsetc, bsetb); } void jr_BitSetAddSet (dest, src) jr_BitSet * dest; jr_BitSet * src; { jr_int i; jr_int num_ints ; if (dest->num_bits < src->num_bits) { jr_BitSetChangeNumBits (dest, src->num_bits); } num_ints = src->num_bits >> jr_INT_BIT_SIZE_POWER; if (src->num_bits & jr_INT_BIT_SIZE_MASK) { num_ints++; } for (i = 0; i < num_ints; i++) { dest->int_array[i] |= src->int_array[i]; } } void jr_BitSetEmpty (bset) jr_BitSet * bset; { register jr_int num_ints; register jr_int i; num_ints = bset->num_bits >> jr_INT_BIT_SIZE_POWER; if (bset->num_bits & jr_INT_BIT_SIZE_MASK) { num_ints++; } for (i=0; i < num_ints; i++) { bset->int_array[i] = 0; } } void jr_BitSetAddAll (bset) jr_BitSet * bset; { register jr_int num_ints; register jr_int i; num_ints = bset->num_bits >> jr_INT_BIT_SIZE_POWER; if (bset->num_bits & jr_INT_BIT_SIZE_MASK) { num_ints++; } for (i=0; i < num_ints; i++) { bset->int_array[i] = 0xffffffff; } } int jr_BitSetIsEmpty (bset) jr_BitSet * bset; { register jr_int num_ints; register jr_int i; register jr_int last_bits_mask; register jr_int num_last_bits; num_ints = bset->num_bits >> jr_INT_BIT_SIZE_POWER; if (bset->num_bits & jr_INT_BIT_SIZE_MASK) { num_ints++; } for (i=0; i < num_ints; i++) { if (i == num_ints - 1) { /* * The last partial int may have 1's off the end */ num_last_bits = bset->num_bits & jr_INT_BIT_SIZE_MASK; /* mod by bits-per-int */ last_bits_mask = 0xffffffff >> (sizeof (jr_int) * CHAR_BIT - num_last_bits); if ((bset->int_array[i] & last_bits_mask) != 0) { return 0; } } else if (bset->int_array[i] != 0) { return 0; } } return 1; } int jr_BitSetIsFull (bset) jr_BitSet * bset; { jr_int num_ints; jr_int i; unsigned jr_int last_bits_mask; jr_int num_last_bits; num_ints = bset->num_bits >> jr_INT_BIT_SIZE_POWER; if (bset->num_bits & jr_INT_BIT_SIZE_MASK) { num_ints++; } for (i=0; i < num_ints; i++) { if (i == num_ints - 1) { /* * The last partial int may have 0's off the end */ num_last_bits = bset->num_bits & jr_INT_BIT_SIZE_MASK; /* mod by bits-per-int */ last_bits_mask = 0xffffffff >> (sizeof (jr_int) * CHAR_BIT - num_last_bits); if ((bset->int_array[i] & last_bits_mask) != last_bits_mask) { return 0; } } else if (~bset->int_array[i] != 0) { return 0; } } return 1; } int jr_BitSetSize (bset) jr_BitSet * bset; { jr_int b; jr_int count = 0; jr_BitSetForEachElement (bset, b) { count++; } return (count); }
frankjas/libjr
libjr/alist/alistpfx.c
<gh_stars>0 #include "project.h" void jr_AListSetContainers (jr_AList *list, ...) { va_list arg_list; va_start (arg_list, list); jr_AListSetContainersFromVA_List (list, arg_list); va_end (arg_list); } void jr_AListSetContainersFromVA_List (list, arg_list) jr_AList * list; va_list arg_list; { jr_PrefixInfoType * prefix_array; jr_int prefix_size; jr_int needs_transform_fn = 1; prefix_array = jr_PrefixArrayCreateFromVA_List (arg_list, needs_transform_fn); prefix_size = jr_PrefixArrayInitPrefixes (prefix_array); if (list) { jr_AListSetPrefixSize ( list, prefix_size, (void (*) ()) jr_PrefixArrayTransformElement, prefix_array ); } } void jr_AListTransformPrefixes (list, old_buffer_ptr, prefix_transform_fn, prefix_transform_arg) jr_AList * list; void * old_buffer_ptr; void (*prefix_transform_fn) (); void * prefix_transform_arg; { void * el_ptr; unsigned jr_int magnitude; jr_int which_way; jr_int all_elements = 1; if ((char *) old_buffer_ptr > list->buffer) { magnitude = (char *) old_buffer_ptr - list->buffer; which_way = -1; } else { magnitude = list->buffer - (char *) old_buffer_ptr; which_way = 1; } jr_AListForEachElementPtr (list, el_ptr) { (*prefix_transform_fn) (prefix_transform_arg, el_ptr, magnitude, which_way, all_elements); } }
frankjas/libjr
libjr/jr_malloc/jr_strdup.c
#include "ezport.h" #include <string.h> #include "jr/misc.h" #include "jr/malloc.h" char * jr_strdup(str) const char * str ; { char * result = jr_malloc (strlen(str) + 1) ; strcpy(result, str) ; return(result) ; } char * jr_strndup(str, max_length) const char * str ; size_t max_length; { size_t str_length = strlen (str); char * result; if (max_length < str_length) { result = jr_malloc (max_length + 1) ; strncpy (result, str, max_length); result[max_length] = 0; } else { result = jr_malloc (str_length + 1) ; strcpy(result, str) ; } return(result) ; }
frankjas/libjr
libjr/string/ccnt.c
<reponame>frankjas/libjr #include "ezport.h" #include "jr/string.h" jr_int jr_CountAllOfChar (search_string, char_val_counted) const char * search_string ; jr_int char_val_counted; { jr_int retval=0 ; for (;*search_string; search_string++) { if (*search_string == char_val_counted) retval++ ; } return(retval) ; }
frankjas/libjr
libjr/syscalls/jr_popen.c
#include "ezport.h" #include <stdlib.h> #include <stdio.h> #include <string.h> #include <errno.h> #include "jr/syscalls.h" #include "jr/error.h" FILE *jr_popen ( const char * command_str, const char * mode_str, char * error_buf) { FILE * fp; fp = popen (command_str, mode_str); if (fp == 0) { jr_esprintf (error_buf, "%s", strerror (errno)); return 0; } return fp; } jr_int jr_pclose ( FILE * fp, char * error_buf) { jr_int status; status = pclose (fp); if (WIFEXITED (status)) { jr_esprintf (error_buf, "exit status was %d", WEXITSTATUS (status)); return WEXITSTATUS (status); } if (WIFSIGNALED (status)) { jr_esprintf (error_buf, "process was killed with %d", WTERMSIG (status)); return jr_EXEC_ERROR; } if (WIFSTOPPED (status)) { jr_esprintf (error_buf, "process was stopped"); return jr_EXEC_ERROR; } jr_esprintf (error_buf, "no exit status, not stopped or killed"); return jr_EXEC_INTERNAL_ERROR; }
frankjas/libjr
libjr/jr_malloc/mempre.c
#include "jr/malloc.h" jr_int jr_MallocRecordPtrsOnly = jr_MALLOC_BEGIN_CPP_INIT_VALUE;
frankjas/libjr
libjr/misc/pfx_init.c
#include "pfx_proj.h" jr_PrefixInfoType jr_PrefixInfoArray [jr_PREFIX_MAX_TYPES]; jr_int jr_PrefixNumTypes = 0; static jr_mutex_t jr_PrefixMutex[1]; jr_thread_once_declare_and_init (ThreadOnceControl); void jr_PrefixMutexInit () { jr_mutex_init (jr_PrefixMutex, 0); } void jr_PrefixAddContainerType ( container_name, element_prefix_size_fn, prefix_transform_fn, set_prefix_size_fn, needs_transform_fn ) char * container_name; jr_int (*element_prefix_size_fn)(); void (*prefix_transform_fn) (); void (*set_prefix_size_fn) (); jr_int needs_transform_fn; { jr_thread_once_call (&ThreadOnceControl, jr_PrefixMutexInit); jr_mutex_lock (jr_PrefixMutex); if (jr_PrefixNumTypes >= jr_PREFIX_MAX_TYPES) { fprintf (stderr, "jr_PrefixAddContainerType(%s): Too many prefix types, max. is %d\n", container_name, jr_PREFIX_MAX_TYPES ); abort (); } jr_PrefixNumTypes ++; jr_PrefixInfoArray [jr_PrefixNumTypes-1].prefix_id = jr_PrefixNumTypes - 1; jr_PrefixInfoArray [jr_PrefixNumTypes-1].element_prefix_size_fn = element_prefix_size_fn; jr_PrefixInfoArray [jr_PrefixNumTypes-1].prefix_transform_fn = prefix_transform_fn; jr_PrefixInfoArray [jr_PrefixNumTypes-1].set_prefix_size_fn = set_prefix_size_fn; jr_PrefixInfoArray [jr_PrefixNumTypes-1].needs_transform_fn = needs_transform_fn; /* * Reserve an entry, whose container_name field is guaranteed to be 0 */ jr_PrefixInfoArray [jr_PrefixNumTypes-1].container_name = container_name; /* * Put the container name in last, so that we don't have to mutex lock * the code which uses this type info array. That code always * stops when the container name is 0. */ jr_mutex_unlock (jr_PrefixMutex); }
frankjas/libjr
include/jr/ezport/microsoft.h
#ifndef __JR_EZPORT_MICROSOFT_H___ #define __JR_EZPORT_MICROSOFT_H___ /* ** GNU/ANSI Fixes */ #ifndef __attribute__ # define __attribute__(arg) #endif #ifdef needs_winnt_snprintf #ifndef snprintf # define snprintf _snprintf #endif #endif #ifdef needs_winnt_vsnprintf #ifndef vsnprintf # define vsnprintf _vsnprintf #endif #endif #ifdef needs_winnt_defines_for_APR # define _CRT_SECURE_NO_DEPRECATE # ifndef WIN32 /* ** 1/25/07: WIN32 is defined by including <windows.h> ** apr.h requires it to trigger the proper behavior. */ # define WIN32 # endif #endif /* * Exclusions: define variables to exclude selected header files. * For complete explanation, see Rector & Newcomer, Win32 Programming, pp 25ff. * * These definitions also reduce the pch and improve compiling time. * All the programs in the book will still compile with these definitions. * You can also eliminate, for example, security with #define NOSECURITY. * * WIN32_LEAN_AND_MEAN has the largest impact, halving the pch file size. */ #ifdef reduce_winnt_compile #define jr_UNDO_NOCTLMGR /* ** 5-17-2011: can't include windows.h, winsock2.h, w/o CTLMGR, ** get syntax errors in prsht.h (property sheet) */ #define jr_UNDO_NOMSG /* ** 5-17-2011: can't include windows.h, winsock2.h, w/o MSG, ** get syntax errors in oleidl.h */ #ifndef jr_UNDO_NOATOM # define NOATOM #endif #ifndef jr_UNDO_NOCLIPBOARD # define NOCLIPBOARD #endif #ifndef jr_UNDO_NOCOMM # define NOCOMM #endif #ifndef jr_UNDO_NOCTLMGR # define NOCTLMGR #endif #ifndef jr_UNDO_NOCOLOR # define NOCOLOR #endif #ifndef jr_UNDO_NODEFERWINDOWPOS # define NODEFERWINDOWPOS #endif #ifndef jr_UNDO_NODESKTOP # define NODESKTOP #endif #ifndef jr_UNDO_NODRAWTEXT # define NODRAWTEXT #endif #ifndef jr_UNDO_NOEXTAPI # define NOEXTAPI #endif #ifndef jr_UNDO_NOGDICAPMASKS # define NOGDICAPMASKS #endif #ifndef jr_UNDO_NOHELP # define NOHELP #endif #ifndef jr_UNDO_NOICONS # define NOICONS #endif #ifndef jr_UNDO_NOTIME # define NOTIME #endif #ifndef jr_UNDO_NOIMM # define NOIMM #endif #ifndef jr_UNDO_NOKANJI # define NOKANJI #endif #ifndef jr_UNDO_NOKERNEL # define NOKERNEL #endif #ifndef jr_UNDO_NOKEYSTATES # define NOKEYSTATES #endif #ifndef jr_UNDO_NOMCX # define NOMCX #endif #ifndef jr_UNDO_NOMEMMGR # define NOMEMMGR #endif #ifndef jr_UNDO_NOMENUS # define NOMENUS #endif #ifndef jr_UNDO_NOMETAFILE # define NOMETAFILE #endif #ifndef jr_UNDO_NOMSG # define NOMSG #endif #ifndef jr_UNDO_NONCMESSAGES # define NONCMESSAGES #endif #ifndef jr_UNDO_NOPROFILER # define NOPROFILER #endif #ifndef jr_UNDO_NORASTEROPS # define NORASTEROPS #endif #ifndef jr_UNDO_NORESOURCE # define NORESOURCE #endif #ifndef jr_UNDO_NOSCROLL # define NOSCROLL #endif #ifndef jr_UNDO_NOSERVICE # define NOSERVICE #endif #ifndef jr_UNDO_NOSHOWWINDOW # define NOSHOWWINDOW #endif #ifndef jr_UNDO_NOSOUND # define NOSOUND #endif #ifndef jr_UNDO_NOSYSCOMMANDS # define NOSYSCOMMANDS #endif #ifndef jr_UNDO_NOSYSMETRICS # define NOSYSMETRICS #endif #ifndef jr_UNDO_NOSYSPARAMS # define NOSYSPARAMS #endif #ifndef jr_UNDO_NOTEXTMETRIC # define NOTEXTMETRIC #endif #ifndef jr_UNDO_NOVIRTUALKEYCODES # define NOVIRTUALKEYCODES #endif #ifndef jr_UNDO_NOWH # define NOWH #endif #ifndef jr_UNDO_NOWINDOWSTATION # define NOWINDOWSTATION #endif #ifndef jr_UNDO_NOWINMESSAGES # define NOWINMESSAGES #endif #ifndef jr_UNDO_NOWINOFFSETS # define NOWINOFFSETS #endif #ifndef jr_UNDO_NOWINSTYLES # define NOWINSTYLES #endif #ifndef jr_UNDO_OEMRESOURCE # define OEMRESOURCE #endif #endif /* ** 1/27/07: Don't include windows header files since the defininition TokenType, VOID, etc, ** in the ansi_c parser and other identifiers that cause conflicts. */ #endif
frankjas/libjr
libjr/struct/bitsetpn.c
#define _POSIX_SOURCE 1 #include "ezport.h" #include <stdio.h> #include "jr/bitset.h" void jr_BitSetPrint (bset, wfp) jr_BitSet * bset; FILE * wfp; { register jr_int num_ints = bset->num_bits >> jr_INT_BIT_SIZE_POWER; jr_int i; if (bset->num_bits & jr_INT_BIT_SIZE_MASK) { /* If n is not a multiple of the number of bites per int, then * add another int. */ num_ints++; } for (i=0; i < num_ints; i++) { fprintf (wfp, "%08x|", bset->int_array[i]); } }
frankjas/libjr
libjr/syscalls/safecopy.c
<reponame>frankjas/libjr<filename>libjr/syscalls/safecopy.c #define _POSIX_SOURCE 1 #include "ezport.h" #include <stdio.h> #include <signal.h> #include <errno.h> #include <string.h> #include <unistd.h> #include <stdlib.h> #include "jr/io.h" #include "jr/syscalls.h" #include "jr/error.h" #include "jr/malloc.h" #include "jr/error.h" /*| begin jr_FileNameSafeCopy_decl |*/ jr_int jr_FileNameSafeCopy ( const char * replaced_file, const char * new_data_file, FILE * opt_new_data_file_ptr, char * error_buf) { sigset_t new_mask; sigset_t old_mask; char * tmp_file_name = 0; FILE * wfp = 0; FILE * rfp = 0; jr_int status; sigemptyset (&new_mask); sigaddset (&new_mask, SIGHUP); /* terminal gets hung up */ sigaddset (&new_mask, SIGINT); /* cntrl-C */ sigaddset (&new_mask, SIGQUIT); /* cntrl-backslash */ sigaddset (&new_mask, SIGALRM); /* software alarm */ sigaddset (&new_mask, SIGTERM); /* software kill */ sigaddset (&new_mask, SIGTSTP); /* cntrl-Z */ /*\f8*/sigprocmask (SIG_BLOCK, &new_mask, &old_mask);/*\fP*/ /* begin critical section */ if (access (replaced_file, F_OK) == 0) { tmp_file_name = jr_malloc (strlen (replaced_file) + 9 + 1); if (strchr (replaced_file, '/')) { strcpy (tmp_file_name, replaced_file); strcpy (strrchr (tmp_file_name, '/') + 1, "tmpXXXXXX"); } else { strcpy (tmp_file_name, "tmpXXXXXX"); /*@ string_constant_copy @*/ } jr_MkTemp (tmp_file_name); /* 3/11/2004: for classes, #define of mktemp() */ status = rename (replaced_file, tmp_file_name); if (status != 0) { jr_esprintf (error_buf, "couldn't rename '%.64s' to temp file '%.64s': %s", replaced_file, tmp_file_name, strerror (errno) ); status = jr_ConvertErrno (errno); goto return_status; } } /* .bp */ wfp = fopen (replaced_file, "w+b"); if (wfp == NULL) { jr_esprintf (error_buf, "couldn't open '%.64s' for writing: %s", replaced_file, strerror (errno) ); status = jr_ConvertErrno (errno); goto return_status; } if (opt_new_data_file_ptr) { rfp = opt_new_data_file_ptr; } else { rfp = fopen (new_data_file, "rb"); if (rfp == NULL) { jr_esprintf (error_buf, "couldn't open '%.64s' for reading: %s", new_data_file, strerror (errno) ); status = jr_ConvertErrno (errno); goto return_status; } } /* .bp */ status = jr_FilePtrCopy (wfp, rfp, error_buf); if (status != 0) { const char * first_rename_strerror; jr_int tmp_status; first_rename_strerror = strerror (errno); if (tmp_file_name) { unlink (replaced_file); /* it may have been created above */ tmp_status = rename (tmp_file_name, replaced_file); } else { tmp_status = 0; } if (tmp_status != 0) { jr_esprintf (error_buf, "couldn't copy '%.32s' to '%.32s' (%.32s), '%.32s' is now in '%.32s' (%.32s)", new_data_file, replaced_file, error_buf, replaced_file, tmp_file_name, first_rename_strerror ); status = jr_ConvertErrno (errno); } else { jr_esprintf (error_buf, "couldn't copy '%.64s' to '%.64s': %s", new_data_file, replaced_file, error_buf ); } goto return_status; } unlink (tmp_file_name); status = 0; return_status: { if (tmp_file_name) { jr_free (tmp_file_name); } if (wfp) { fclose (wfp); } if (rfp) { fclose (rfp); } } /*\f8*/sigprocmask (SIG_SETMASK, &old_mask, 0);/*\fP*/ /* end critical section */ return status; } /*| end jr_FileNameSafeCopy_decl |*/
frankjas/libjr
libjr/dlist/dlistcmp.c
#include "project.h" void *jr_DListFindElementPtr (list, obj, cmpfn) jr_DList * list; void * obj; jr_int (*cmpfn) (); { char * current; jr_DListForEachElementPtr (list, current) { if ((*cmpfn) (obj, current) == 0) return (current); } return (0); } jr_int jr_DListCmp (list1, list2, cmpfn) jr_DList * list1; jr_DList * list2; jr_int (*cmpfn) (); { void * obj_p1; void * obj_p2; jr_int comp; obj_p1 = jr_DListHeadPtr (list1); obj_p2 = jr_DListHeadPtr (list2); while (obj_p1 && obj_p2) { comp = (*cmpfn) (obj_p1, obj_p2); if (comp) return (comp); obj_p1 = jr_DListNextElementPtr (list1, obj_p1); obj_p2 = jr_DListNextElementPtr (list2, obj_p2); } if (obj_p1 == 0 && obj_p2 == 0) { return 0; } if (obj_p1 == 0) { return -1; } if (obj_p2 == 0) { return 1; } return 0; } jr_int jr_DListHash (list, hashfn) jr_DList * list; jr_int (*hashfn) (); { void * element; jr_int hash_value = 0; jr_DListForEachElementPtr (list, element) { hash_value += hashfn (element); } return hash_value; }
frankjas/libjr
libjr/misc/memswtch.c
<gh_stars>0 #include "ezport.h" #include "jr/misc.h" void jr_memswitch (vp1, vp2, nbytes) void * vp1; void * vp2; jr_int nbytes; { char * p1 = vp1; char * p2 = vp2; jr_int i; jr_int c; for (i=0; i < nbytes; i++, p1++, p2++) { c = *p1; *p1 = *p2; *p2 = c; } } jr_int jr_memisset (vp1, value, nbytes) void * vp1; jr_int value; jr_int nbytes; { char * p1 = vp1; jr_int i; for (i=0; i < nbytes; i++, p1++) { if (*p1 != value) { return 0; } } return 1; }
frankjas/libjr
libjr/string/url_str.c
<reponame>frankjas/libjr #define _POSIX_SOURCE 1 #include "ezport.h" #include <ctype.h> #include "jr/string.h" #include "jr/alist.h" char *jr_StringEncodeForURL (input_string) const char * input_string; { jr_AList result_chars[1]; char small_buf[16]; char * encoded_string; jr_int curr_char; jr_int j; jr_AListInit (result_chars, sizeof (char)); for (; *input_string; input_string++) { curr_char = *input_string; switch (curr_char) { /* * Characters from O'Reilly's 'HTML: The definitive guide' * 3rd edition, page 196 */ case '$' : case '-' : case '_' : case '.' : case '+' : case '!' : case '*' : case '\'' : case '(' : case ')' : case ',' : { jr_AListNativeSetNewTail (result_chars, curr_char, char); break; } default : { if (isalnum (curr_char)) { jr_AListNativeSetNewTail (result_chars, curr_char, char); } else { jr_AListNativeSetNewTail (result_chars, '%', char); sprintf (small_buf, "%02X", curr_char); for (j=0; small_buf[j]; j++) { jr_AListNativeSetNewTail (result_chars, small_buf[j], char); } } break; } } } jr_AListNativeSetNewTail (result_chars, 0, char); encoded_string = jr_AListExtractBuffer (result_chars); jr_AListUndo (result_chars); return encoded_string; } char *jr_StringEncodeForQuotes (input_string, quotes_string) const char * input_string; const char * quotes_string; { jr_AList result_chars[1]; char small_buf[16]; char * encoded_string; jr_int curr_char; jr_int encode_char; jr_int j; jr_AListInit (result_chars, sizeof (char)); for (; *input_string; input_string++) { curr_char = *input_string; if ( curr_char == '%' || curr_char < 32 || curr_char >= 127) { encode_char = 1; } else if (strchr (quotes_string, curr_char)) { encode_char = 1; } else { encode_char = 0; } if (encode_char) { jr_AListNativeSetNewTail (result_chars, '%', char); sprintf (small_buf, "%02X", curr_char); for (j=0; small_buf[j]; j++) { jr_AListNativeSetNewTail (result_chars, small_buf[j], char); } } else { jr_AListNativeSetNewTail (result_chars, curr_char, char); } } jr_AListNativeSetNewTail (result_chars, 0, char); encoded_string = jr_AListExtractBuffer (result_chars); jr_AListUndo (result_chars); return encoded_string; } char *jr_StringDecodeFromURLWithFixReturn (input_string, fix_return_newline) const char * input_string; jr_int fix_return_newline; { jr_AList result_chars[1]; char * encoded_string; jr_int curr_char; jr_int getting_hex_value = 0; jr_int hex_value = 0; jr_int num_hex_digits = 0; jr_int digit_value; jr_int saw_return = 0; jr_AListInit (result_chars, sizeof (char)); for (; *input_string; input_string++) { curr_char = *input_string; if (getting_hex_value) { if (isxdigit (curr_char) && num_hex_digits < 2) { if (isdigit (curr_char)) { digit_value = curr_char - '0'; } else if (isupper (curr_char)) { digit_value = 10 + curr_char - 'A'; } else { digit_value = 10 + curr_char - 'a'; } hex_value = 16 * hex_value + digit_value; num_hex_digits ++; continue; } if (hex_value == '\r' && fix_return_newline) { /* * On Mac (and probably DOS), input into a TEXTAREA * gets an ASCII 13, 10, sequence. We need to remove * the ASCII 13, i.e. the '\r' to make it correct * as a C string. */ saw_return = 1; } else { if (saw_return && hex_value != '\n') { jr_AListNativeSetNewTail (result_chars, '\r', char); } jr_AListNativeSetNewTail (result_chars, hex_value, char); saw_return = 0; } getting_hex_value = 0; } switch (curr_char) { case '%' : { getting_hex_value = 1; hex_value = 0; num_hex_digits = 0; break; } default : { if (saw_return) { /* * Put the return in if it wasn't followed by a '\n' */ jr_AListNativeSetNewTail (result_chars, '\r', char); } jr_AListNativeSetNewTail (result_chars, curr_char, char); saw_return = 0; break; } } } if (saw_return) { /* * Put the return in if it wasn't followed by a '\n' */ jr_AListNativeSetNewTail (result_chars, '\r', char); } if (getting_hex_value) { jr_AListNativeSetNewTail (result_chars, hex_value, char); } jr_AListNativeSetNewTail (result_chars, 0, char); encoded_string = jr_AListExtractBuffer (result_chars); jr_AListUndo (result_chars); return encoded_string; }
frankjas/libjr
libjr/syscalls/modtime.c
#define _POSIX_SOURCE 1 #include "ezport.h" #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include "jr/syscalls.h" time_t jr_FilePtrModifiedTime(fp) FILE *fp ; { struct stat buf ; jr_int fd = fileno(fp) ; if (fstat(fd,&buf) != 0) { return(0) ; } return(buf.st_mtime) ; } time_t jr_FileDescModifiedTime(fd) jr_int fd ; { struct stat buf ; if (fstat(fd,&buf) != 0) { return(0) ; } return((jr_int) buf.st_mtime) ; } time_t jr_FileNameModifiedTime(fn) const char * fn ; { struct stat buf ; if (stat(fn,&buf) != 0) { return(0) ; } return((jr_int) buf.st_mtime) ; }
frankjas/libjr
libjr/misc/freeref.c
#include "ezport.h" #include "jr/misc.h" #include "jr/malloc.h" void jr_freeref(sa) char ** sa ; { jr_free(*sa) ; }
frankjas/libjr
libjr/misc/tracevar.c
<gh_stars>0 #define is_libjr_build #include "jr/trace.h" jr_trace_t jr_TraceValues[jr_TRACE_NUM_VALUES];
frankjas/libjr
libjr/io/maillib.c
#include "mailproj.h" jr_int jr_MailStringMessage ( smtp_server_name, sender_address, recipient_address, opt_header_vector, message_string, error_buf ) char * smtp_server_name; char * sender_address; char * recipient_address; char ** opt_header_vector; char * message_string; char * error_buf; { jr_int smtp_fd = -1; FILE * smtp_wfp = 0; char * smtp_command; jr_int smtp_status; char local_hostname [256]; char line_buffer [SMTP_MAX_RESPONSE_LENGTH]; jr_int status; status = gethostname (local_hostname, sizeof (local_hostname) - 1); if (status != 0) { jr_esprintf (error_buf, "couldn't get local host name: %s", strerror (errno)); status = jr_INET_HOST_NOT_FOUND; goto return_status; } smtp_fd = jr_InetConnectToService ( smtp_server_name, SMTP_PORT, error_buf ); if (smtp_fd < 0) { jr_esprintf (error_buf, "couldn't connect to '%.64s': %s", smtp_server_name, error_buf ); return smtp_fd; } smtp_wfp = fdopen (smtp_fd, "w"); if (smtp_wfp == 0) { jr_esprintf (error_buf, "couldn't get connection wfp: %s", strerror (errno)); status = jr_INET_SYSTEM_ERROR; goto return_status; } status = setvbuf (smtp_wfp, 0, _IOLBF, 0); if (status != 0) { jr_esprintf (error_buf, "couldn't get setvbuf(wfp): %s", strerror (errno)); status = jr_INET_SYSTEM_ERROR; goto return_status; } status = jr_socket_readlines (smtp_fd, line_buffer, sizeof (line_buffer)); if (status < 0) { jr_esprintf (error_buf, "unexpected EOF after connection"); status = jr_INET_SYSTEM_ERROR; goto return_status; } smtp_status = atoi (line_buffer); if (smtp_status != SMTP_INIT_STATUS) { jr_esprintf (error_buf, "smtp init status %d != %d", smtp_status, SMTP_INIT_STATUS); status = jr_INET_CONNECTION_REFUSED; goto return_status; } smtp_command = "HELO"; fprintf (smtp_wfp, "%s %s\r\n", smtp_command, local_hostname); /* * Some SMTP servers send multiple 220 init messages. */ status = jr_socket_readlines (smtp_fd, line_buffer, sizeof (line_buffer)); if (status < 0) { jr_esprintf (error_buf, "unexpected EOF after %s", smtp_command); status = jr_INET_SYSTEM_ERROR; goto return_status; } smtp_status = atoi (line_buffer); if (smtp_status != SMTP_OK_STATUS && smtp_status != SMTP_INIT_STATUS) { jr_esprintf (error_buf, "%s status %d != %d", smtp_command, smtp_status, SMTP_OK_STATUS); status = jr_INET_SYSTEM_ERROR; goto return_status; } smtp_command = "MAIL"; if (sender_address[0] == '<') { fprintf (smtp_wfp, "%s From:%s\r\n", smtp_command, sender_address); } else { fprintf (smtp_wfp, "%s From:<%s>\r\n", smtp_command, sender_address); } status = jr_socket_readlines (smtp_fd, line_buffer, sizeof (line_buffer)); if (status < 0) { jr_esprintf (error_buf, "unexpected EOF after %s", smtp_command); status = jr_INET_SYSTEM_ERROR; goto return_status; } smtp_status = atoi (line_buffer); if (smtp_status != SMTP_OK_STATUS) { jr_esprintf (error_buf, "%s status %d != %d", smtp_command, smtp_status, SMTP_OK_STATUS); status = jr_INET_SYSTEM_ERROR; goto return_status; } smtp_command = "RCPT"; if (recipient_address[0] == '<') { fprintf (smtp_wfp, "%s To:%s\r\n", smtp_command, recipient_address); } else { fprintf (smtp_wfp, "%s To:<%s>\r\n", smtp_command, recipient_address); } status = jr_socket_readlines (smtp_fd, line_buffer, sizeof (line_buffer)); if (status < 0) { jr_esprintf (error_buf, "unexpected EOF after %s", smtp_command); status = jr_INET_SYSTEM_ERROR; goto return_status; } smtp_status = atoi (line_buffer); if (smtp_status != SMTP_OK_STATUS) { jr_esprintf (error_buf, "%s status %d != %d", smtp_command, smtp_status, SMTP_OK_STATUS); status = jr_INET_SYSTEM_ERROR; goto return_status; } smtp_command = "DATA"; fprintf (smtp_wfp, "%s\r\n", smtp_command); status = jr_socket_readlines (smtp_fd, line_buffer, sizeof (line_buffer)); if (status < 0) { jr_esprintf (error_buf, "unexpected EOF after %s", smtp_command); status = jr_INET_SYSTEM_ERROR; goto return_status; } smtp_status = atoi (line_buffer); /* * The RCPT command could have two status responses? */ switch (smtp_status) { case SMTP_OK_STATUS : case SMTP_DATA_OK_STATUS : case SMTP_WILL_FORWARD_STATUS : { break; } default : { jr_esprintf (error_buf, "%s status %d != %d", smtp_command, smtp_status, SMTP_DATA_OK_STATUS); status = jr_INET_SYSTEM_ERROR; goto return_status; break; } } if (opt_header_vector) { jr_int i; for (i=0; opt_header_vector[i] != 0; i++) { fprintf (smtp_wfp, "%s\r\n", opt_header_vector[i]); } fprintf (smtp_wfp, "\r\n"); } fprintf (smtp_wfp, "%s\r\n.\r\n", message_string); status = jr_socket_readlines (smtp_fd, line_buffer, sizeof (line_buffer)); if (status < 0) { jr_esprintf (error_buf, "unexpected EOF after %s", smtp_command); status = jr_INET_SYSTEM_ERROR; goto return_status; } smtp_status = atoi (line_buffer); if (smtp_status != SMTP_OK_STATUS) { jr_esprintf (error_buf, "%s status %d != %d", smtp_command, smtp_status, SMTP_OK_STATUS); status = jr_INET_SYSTEM_ERROR; goto return_status; } smtp_command = "QUIT"; fprintf (smtp_wfp, "%s\r\n", smtp_command); status = jr_socket_readlines (smtp_fd, line_buffer, sizeof (line_buffer)); if (status < 0) { jr_esprintf (error_buf, "unexpected EOF after %s", smtp_command); status = jr_INET_SYSTEM_ERROR; goto return_status; } smtp_status = atoi (line_buffer); if (smtp_status != SMTP_QUIT_OK_STATUS) { jr_esprintf (error_buf, "%s status %d != %d", smtp_command, smtp_status, SMTP_QUIT_OK_STATUS); status = jr_INET_SYSTEM_ERROR; goto return_status; } status = 0; return_status : { if (smtp_fd >= 0) { shutdown (smtp_fd, jr_ALL_DISALLOW); close (smtp_fd); } if (smtp_wfp) { fclose (smtp_wfp); } } return status; } jr_int jr_MailStringMessageWithSubjectOnly ( smtp_server_name, sender_address, recipient_address, opt_subject_buf, message_string, error_buf ) char * smtp_server_name; char * sender_address; char * recipient_address; char * opt_subject_buf; char * message_string; char * error_buf; { char * header_vector[32]; char subject_buf[256]; jr_int i = 0; jr_int status; if (opt_subject_buf) { sprintf (subject_buf, "Subject: %.210s", opt_subject_buf); header_vector[i++] = subject_buf; header_vector[i++] = 0; } status = jr_MailStringMessage ( smtp_server_name, sender_address, recipient_address, opt_subject_buf ? header_vector : 0, message_string, error_buf ); return status; } jr_int jr_MailServerValidate (smtp_server_name, opt_sender_address, error_buf) const char * smtp_server_name; const char * opt_sender_address; char * error_buf; { jr_int smtp_fd = -1; FILE * smtp_wfp = 0; char * smtp_command; jr_int smtp_status; jr_int server_is_valid = 0; char local_hostname [256]; char line_buffer [SMTP_MAX_RESPONSE_LENGTH]; jr_int status; status = gethostname (local_hostname, sizeof (local_hostname) - 1); if (status != 0) { jr_esprintf (error_buf, "couldn't get local host name: %s", strerror (errno)); status = jr_INET_HOST_NOT_FOUND; goto return_status; } smtp_fd = jr_InetConnectToService ( smtp_server_name, SMTP_PORT, error_buf ); if (smtp_fd < 0) { jr_esprintf (error_buf, "couldn't connect to '%.64s': %s", smtp_server_name, error_buf ); return smtp_fd; } smtp_wfp = fdopen (smtp_fd, "w"); if (smtp_wfp == 0) { jr_esprintf (error_buf, "couldn't get connection wfp: %s", strerror (errno)); status = jr_INET_SYSTEM_ERROR; goto return_status; } status = setvbuf (smtp_wfp, 0, _IOLBF, 0); if (status != 0) { jr_esprintf (error_buf, "couldn't get setvbuf(wfp): %s", strerror (errno)); status = jr_INET_SYSTEM_ERROR; goto return_status; } status = jr_socket_readlines (smtp_fd, line_buffer, sizeof (line_buffer)); if (status < 0) { jr_esprintf (error_buf, "unexpected EOF after connection"); status = jr_INET_SYSTEM_ERROR; goto return_status; } smtp_status = atoi (line_buffer); if (smtp_status != SMTP_INIT_STATUS) { jr_esprintf (error_buf, "smtp init status %d != %d", smtp_status, SMTP_INIT_STATUS); status = jr_INET_CONNECTION_REFUSED; goto return_status; } smtp_command = "HELO"; fprintf (smtp_wfp, "%s %s\r\n", smtp_command, local_hostname); /* * Some SMTP servers send multiple 220 init messages. */ status = jr_socket_readlines (smtp_fd, line_buffer, sizeof (line_buffer)); if (status < 0) { jr_esprintf (error_buf, "unexpected EOF after %s", smtp_command); status = jr_INET_SYSTEM_ERROR; goto return_status; } smtp_status = atoi (line_buffer); if (opt_sender_address) { if (smtp_status != SMTP_OK_STATUS && smtp_status != SMTP_INIT_STATUS) { jr_esprintf (error_buf, "%s status %d != %d", smtp_command, smtp_status, SMTP_OK_STATUS); status = jr_INET_SYSTEM_ERROR; goto return_status; } smtp_command = "MAIL"; if (opt_sender_address[0] == '<') { fprintf (smtp_wfp, "%s From:%s\r\n", smtp_command, opt_sender_address); } else { fprintf (smtp_wfp, "%s From:<%s>\r\n", smtp_command, opt_sender_address); } status = jr_socket_readlines (smtp_fd, line_buffer, sizeof (line_buffer)); if (status < 0) { jr_esprintf (error_buf, "unexpected EOF after %s", smtp_command); status = jr_INET_SYSTEM_ERROR; goto return_status; } smtp_status = atoi (line_buffer); } if (smtp_status == SMTP_OK_STATUS) { server_is_valid = 1; } else { jr_esprintf (error_buf, "%s", line_buffer); server_is_valid = 0; } smtp_command = "QUIT"; fprintf (smtp_wfp, "%s\r\n", smtp_command); status = jr_socket_readlines (smtp_fd, line_buffer, sizeof (line_buffer)); if (status < 0) { status = server_is_valid; goto return_status; } smtp_status = atoi (line_buffer); if (smtp_status != SMTP_QUIT_OK_STATUS) { status = server_is_valid; goto return_status; } status = server_is_valid; return_status : { if (smtp_fd >= 0) { shutdown (smtp_fd, jr_ALL_DISALLOW); close (smtp_fd); } if (smtp_wfp) { fclose (smtp_wfp); } } return status; } jr_int jr_MailAddressValidate ( recipient_address, smtp_server_name, sender_address, error_buf ) const char * recipient_address; const char * smtp_server_name; const char * sender_address; char * error_buf; { jr_int smtp_fd = -1; FILE * smtp_wfp = 0; char * smtp_command; jr_int smtp_status; jr_int address_is_valid = 0; char local_hostname [256]; char line_buffer [SMTP_MAX_RESPONSE_LENGTH]; jr_int status; status = gethostname (local_hostname, sizeof (local_hostname) - 1); if (status != 0) { jr_esprintf (error_buf, "couldn't get local host name: %s", strerror (errno)); status = jr_INET_HOST_NOT_FOUND; goto return_status; } smtp_fd = jr_InetConnectToService ( smtp_server_name, SMTP_PORT, error_buf ); if (smtp_fd < 0) { jr_esprintf (error_buf, "couldn't connect to '%.64s': %s", smtp_server_name, error_buf ); return smtp_fd; } smtp_wfp = fdopen (smtp_fd, "w"); if (smtp_wfp == 0) { jr_esprintf (error_buf, "couldn't get connection wfp: %s", strerror (errno)); status = jr_INET_SYSTEM_ERROR; goto return_status; } status = setvbuf (smtp_wfp, 0, _IOLBF, 0); if (status != 0) { jr_esprintf (error_buf, "couldn't get setvbuf(wfp): %s", strerror (errno)); status = jr_INET_SYSTEM_ERROR; goto return_status; } status = jr_socket_readlines (smtp_fd, line_buffer, sizeof (line_buffer)); if (status < 0) { jr_esprintf (error_buf, "unexpected EOF after connection"); status = jr_INET_SYSTEM_ERROR; goto return_status; } smtp_status = atoi (line_buffer); if (smtp_status != SMTP_INIT_STATUS) { jr_esprintf (error_buf, "smtp init status %d != %d", smtp_status, SMTP_INIT_STATUS); status = jr_INET_CONNECTION_REFUSED; goto return_status; } smtp_command = "HELO"; fprintf (smtp_wfp, "%s %s\r\n", smtp_command, local_hostname); /* * Some SMTP servers send multiple 220 init messages. */ status = jr_socket_readlines (smtp_fd, line_buffer, sizeof (line_buffer)); if (status < 0) { jr_esprintf (error_buf, "unexpected EOF after %s", smtp_command); status = jr_INET_SYSTEM_ERROR; goto return_status; } smtp_status = atoi (line_buffer); if (smtp_status != SMTP_OK_STATUS && smtp_status != SMTP_INIT_STATUS) { jr_esprintf (error_buf, "%s status %d != %d", smtp_command, smtp_status, SMTP_OK_STATUS); status = jr_INET_SYSTEM_ERROR; goto return_status; } smtp_command = "MAIL"; if (sender_address[0] == '<') { fprintf (smtp_wfp, "%s From:%s\r\n", smtp_command, sender_address); } else { fprintf (smtp_wfp, "%s From:<%s>\r\n", smtp_command, sender_address); } status = jr_socket_readlines (smtp_fd, line_buffer, sizeof (line_buffer)); if (status < 0) { jr_esprintf (error_buf, "unexpected EOF after %s", smtp_command); status = jr_INET_SYSTEM_ERROR; goto return_status; } smtp_status = atoi (line_buffer); if (smtp_status != SMTP_OK_STATUS) { jr_esprintf (error_buf, "%s status %d != %d", smtp_command, smtp_status, SMTP_OK_STATUS); status = jr_INET_SYSTEM_ERROR; goto return_status; } smtp_command = "RCPT"; if (recipient_address[0] == '<') { fprintf (smtp_wfp, "%s To:%s\r\n", smtp_command, recipient_address); } else { fprintf (smtp_wfp, "%s To:<%s>\r\n", smtp_command, recipient_address); } status = jr_socket_readlines (smtp_fd, line_buffer, sizeof (line_buffer)); if (status < 0) { jr_esprintf (error_buf, "unexpected EOF after %s", smtp_command); status = jr_INET_SYSTEM_ERROR; goto return_status; } smtp_status = atoi (line_buffer); if (smtp_status == SMTP_OK_STATUS || smtp_status == SMTP_WILL_FORWARD_STATUS) { address_is_valid = 1; } else { jr_esprintf (error_buf, "%s", line_buffer); address_is_valid = 0; } smtp_command = "QUIT"; fprintf (smtp_wfp, "%s\r\n", smtp_command); status = jr_socket_readlines (smtp_fd, line_buffer, sizeof (line_buffer)); if (status < 0) { status = address_is_valid; goto return_status; } smtp_status = atoi (line_buffer); if (smtp_status != SMTP_QUIT_OK_STATUS) { status = address_is_valid; goto return_status; } status = address_is_valid; return_status : { if (smtp_fd >= 0) { shutdown (smtp_fd, jr_ALL_DISALLOW); close (smtp_fd); } if (smtp_wfp) { fclose (smtp_wfp); } } return status; }
frankjas/libjr
libjr/missing/setpgid.c
#define _POSIX_SOURCE 1 #include "ezport.h" #ifdef missing_setpgid #include <sys/types.h> #include <unistd.h> #include <sys/ioctl.h> int setpgid(pid, pgrp) pid_t pid ; pid_t pgrp ; { if (pgrp == 0) { pgrp = getpid() ; } if (pid == 0) { pid = getpid() ; } return setpgrp(pid, pgrp) ; } #else static void NotCalled () /* define this so ranlib doesn't complain */ { NotCalled (); /* use it so the compiler doesn't complain */ } #endif
frankjas/libjr
libjr/syscalls/copyfd.c
<reponame>frankjas/libjr #define _POSIX_SOURCE 1 #include "ezport.h" #include <unistd.h> #include "jr/io.h" jr_int jr_FileDescCopy(wfd, rfd, buf, bufsize) jr_int wfd ; jr_int rfd ; void * buf ; jr_int bufsize ; { ssize_t nbytes ; while (nbytes = read(rfd, buf, bufsize)) { if (nbytes == -1) { return(-1) ; } if (write(wfd, buf, nbytes) != nbytes) { return(-1) ; } } return(0) ; }