repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
|---|---|---|
frankjas/libjr
|
libjr/syscalls/async_fn.c
|
<filename>libjr/syscalls/async_fn.c
#include "async_fn.h"
static jr_int InitializedTree = 0;
static jr_AVL_Tree HandlerTree[1];
static jr_int CurrentTime = 0;
static jr_int AlarmTime = 0;
static jr_int NumAlarms = 0;
static struct sigaction OldAction[1];
jr_int jr_AddAsyncFunction (
void (*handler_fn) (),
void * handler_param,
jr_int num_seconds,
jr_int do_repeat,
char * error_buf)
{
struct sigaction new_action[1];
sigset_t new_mask;
sigset_t old_mask;
jr_int sig_num;
jr_int old_alarm;
jr_int status;
sig_num = SIGALRM;
sigemptyset (&new_mask);
sigaddset (&new_mask, sig_num);
sigprocmask (SIG_BLOCK, &new_mask, &old_mask);
{
jr_AsyncFunctionStruct tmp_handler_info[1];
jr_AsyncFunctionStruct * handler_info_ptr;
void (*curr_handler_fn) () = 0;
if (num_seconds <= 0) {
jr_esprintf (error_buf, "num_seconds must be greater than zero, not %d", num_seconds);
status = -1;
goto return_status;
}
CurrentTime = time (0);
/*
* 8/4/2005: get the time now so that we're sure the new call times will be after this.
*/
if (!InitializedTree) {
InitializedTree = 1;
jr_AVL_TreeInit (
HandlerTree, sizeof (jr_AsyncFunctionStruct), jr_AsyncFunctionCmp
);
new_action->sa_handler = jr_AsyncFunctionHandler;
sigemptyset (&new_action->sa_mask);
new_action->sa_flags = SA_RESTART;
sigaction (sig_num, new_action, OldAction);
if ( OldAction->sa_handler != SIG_IGN
&& OldAction->sa_handler != SIG_DFL) {
curr_handler_fn = OldAction->sa_handler;
}
old_alarm = alarm (0);
if (old_alarm > 0 && curr_handler_fn) {
status = jr_AddAsyncFunction (curr_handler_fn, 0, old_alarm, 0, error_buf);
iferr (status != 0) {
alarm (old_alarm);
jr_esprintf (error_buf, "couldn't add existing handler %p: %s",
curr_handler_fn, error_buf
);
status = -1;
goto return_status;
}
}
}
/*
** 8/9/2005: remove any handlers that went off but didn't repeat.
** Couldn't deallocate them inside the signal handler
*/
handler_info_ptr = jr_AVL_TreeGreatestElementPtr (HandlerTree);
while (handler_info_ptr) {
if (jr_AsyncFunctionCallTime (handler_info_ptr) == jr_INT_MAX) {
jr_AVL_TreeExtractElement (HandlerTree, handler_info_ptr);
jr_AsyncFunctionUndo (handler_info_ptr);
jr_AVL_TreeFreeElement (HandlerTree, handler_info_ptr);
}
else {
break;
}
handler_info_ptr = jr_AVL_TreeGreatestElementPtr (HandlerTree);
}
jr_AVL_TreeForEachElementPtr (HandlerTree, handler_info_ptr) {
iferr_sim ( jr_AsyncFunctionPtr (handler_info_ptr) == handler_fn
&& jr_AsyncFunctionParam (handler_info_ptr) == handler_param) {
jr_esprintf (error_buf, "handler fn %p with parameter %p already loaded",
handler_fn, handler_param
);
status = -1;
goto return_status;
}
}
jr_AsyncFunctionInit (tmp_handler_info, handler_fn, handler_param, num_seconds, do_repeat);
handler_info_ptr = jr_AVL_TreeFindElementPtr (HandlerTree, tmp_handler_info);
iferr_sim (handler_info_ptr) {
jr_AsyncFunctionUndo (tmp_handler_info);
jr_esprintf (error_buf, "can't insert into handler tree after duplicate check??");
status = -1;
goto return_status;
}
jr_AVL_TreeSetNewElement (HandlerTree, tmp_handler_info);
handler_info_ptr = jr_AVL_TreeSmallestElementPtr (HandlerTree);
if (jr_AsyncFunctionCallTime (handler_info_ptr) - CurrentTime > 0) {
alarm (jr_AsyncFunctionCallTime (handler_info_ptr) - CurrentTime);
}
else {
alarm (1);
}
}
status = 0;
return_status : {
sigprocmask (SIG_SETMASK, &old_mask, 0);
}
return status;
}
void jr_RemoveAsyncFunction (
void (*handler_fn) (),
void * handler_param)
{
sigset_t new_mask;
sigset_t old_mask;
jr_int sig_num;
sig_num = SIGALRM;
sigemptyset (&new_mask);
sigaddset (&new_mask, sig_num);
sigprocmask (SIG_BLOCK, &new_mask, &old_mask);
{
jr_AsyncFunctionStruct * handler_info_ptr;
jr_AVL_TreeForEachElementPtr (HandlerTree, handler_info_ptr) {
if ( jr_AsyncFunctionPtr (handler_info_ptr) == handler_fn
&& jr_AsyncFunctionParam (handler_info_ptr) == handler_param) {
jr_AVL_TreeExtractElement (HandlerTree, handler_info_ptr);
jr_AsyncFunctionUndo (handler_info_ptr);
jr_AVL_TreeFreeElement (HandlerTree, handler_info_ptr);
break;
}
}
if (jr_AVL_TreeIsEmpty (HandlerTree)) {
sigaction (sig_num, OldAction, 0);
jr_AVL_TreeUndo (HandlerTree);
InitializedTree = 0;
}
}
sigprocmask (SIG_SETMASK, &old_mask, 0);
}
jr_int jr_GetAsyncFunctionNumSeconds (
void (*handler_fn) (),
void * handler_param)
{
jr_AsyncFunctionStruct * handler_info_ptr;
jr_AVL_TreeForEachElementPtr (HandlerTree, handler_info_ptr) {
if ( jr_AsyncFunctionPtr (handler_info_ptr) == handler_fn
&& jr_AsyncFunctionParam (handler_info_ptr) == handler_param) {
return jr_AsyncFunctionNumSeconds (handler_info_ptr);
}
}
return 0;
}
jr_int jr_GetAsyncFunctionCallTime (
void (*handler_fn) (),
void * handler_param)
{
jr_AsyncFunctionStruct * handler_info_ptr;
jr_AVL_TreeForEachElementPtr (HandlerTree, handler_info_ptr) {
if ( jr_AsyncFunctionPtr (handler_info_ptr) == handler_fn
&& jr_AsyncFunctionParam (handler_info_ptr) == handler_param) {
return jr_AsyncFunctionCallTime (handler_info_ptr);
}
}
return 0;
}
void jr_AsyncFunctionHandler (
jr_int signum)
{
jr_AsyncFunctionStruct * handler_info_ptr;
jr_AsyncFunctionStruct * next_handler_info_ptr;
if (NumAlarms % 20 == 0) {
CurrentTime = time (0);
}
else {
CurrentTime += AlarmTime;
}
if (!InitializedTree) {
return;
}
handler_info_ptr = jr_AVL_TreeSmallestElementPtr (HandlerTree);
/*
** 8/9/2005: can't do any malloc()/free() operations
*/
while (handler_info_ptr) {
if (jr_AsyncFunctionCallTime (handler_info_ptr) > CurrentTime) {
alarm (jr_AsyncFunctionCallTime (handler_info_ptr) - CurrentTime);
break;
}
next_handler_info_ptr = jr_AVL_TreeNextElementPtr (HandlerTree, handler_info_ptr);
if (jr_AsyncFunctionCallTime (handler_info_ptr) <= CurrentTime) {
(*handler_info_ptr->handler_fn) (handler_info_ptr->handler_param, CurrentTime);
jr_AVL_TreeExtractElement (HandlerTree, handler_info_ptr);
if (jr_AsyncFunctionDoRepeat (handler_info_ptr)) {
jr_AsyncFunctionSetCallTime (
handler_info_ptr, CurrentTime + jr_AsyncFunctionNumSeconds (handler_info_ptr)
);
}
else {
jr_AsyncFunctionSetCallTime (handler_info_ptr, jr_INT_MAX);
}
jr_AVL_TreeInsertElement (HandlerTree, handler_info_ptr);
if ( next_handler_info_ptr == 0
&& jr_AsyncFunctionCallTime (handler_info_ptr) > CurrentTime) {
next_handler_info_ptr = handler_info_ptr;
}
}
handler_info_ptr = next_handler_info_ptr;
}
}
void jr_AsyncFunctionInit (
jr_AsyncFunctionStruct * handler_info_ptr,
void (*handler_fn) (),
void * handler_param,
jr_int num_seconds,
jr_int do_repeat)
{
memset (handler_info_ptr, 0, sizeof (*handler_info_ptr));
handler_info_ptr->call_time = time (0) + num_seconds;
handler_info_ptr->handler_fn = handler_fn;
handler_info_ptr->handler_param = handler_param;
handler_info_ptr->num_seconds = num_seconds;
handler_info_ptr->do_repeat = do_repeat != 0;
}
void jr_AsyncFunctionUndo (
jr_AsyncFunctionStruct * handler_info_ptr)
{
}
jr_int jr_AsyncFunctionCmp (
const void * void_arg_1,
const void * void_arg_2)
{
const jr_AsyncFunctionStruct * handler_info_ptr_1 = void_arg_1;
const jr_AsyncFunctionStruct * handler_info_ptr_2 = void_arg_2;
if (handler_info_ptr_1->call_time < handler_info_ptr_2->call_time) {
return -1;
}
if (handler_info_ptr_1->call_time > handler_info_ptr_2->call_time) {
return 1;
}
if (handler_info_ptr_1->handler_fn < handler_info_ptr_2->handler_fn) {
return -1;
}
if (handler_info_ptr_1->handler_fn > handler_info_ptr_2->handler_fn) {
return 1;
}
if (handler_info_ptr_1->handler_param < handler_info_ptr_2->handler_param) {
return -1;
}
if (handler_info_ptr_1->handler_param > handler_info_ptr_2->handler_param) {
return 1;
}
return 0;
}
|
frankjas/libjr
|
libjr/llist/llistfnd.c
|
<reponame>frankjas/libjr
#include "project.h"
void *jr_LListFindElementPtr (list, obj, cmpfn)
jr_LList *list;
void *obj;
jr_int (*cmpfn) ();
{
void *lep;
jr_LListForEachElementPtr (list, lep) {
if (! (*cmpfn) (obj, lep)) return (lep);
}
return (0);
}
void *jr_LListFindAppendPtr (list, obj, cmpfn)
jr_LList *list;
void *obj;
jr_int (*cmpfn) ();
{
void *last, *current;
jr_int cmp;
last = 0;
jr_LListForEachElementPtr (list, current) {
cmp = (*cmpfn) (obj, current);
if (cmp <= 0) {
return last;
}
last = current;
}
return (last);
}
void *jr_LListNewElementPtrInOrderWithSizeAndUniqueFlag (list, obj, cmpfn, size, unique)
jr_LList * list;
void * obj;
jr_int (*cmpfn) ();
jr_int size;
jr_int unique;
{
void *prev, *new, *next;
prev = jr_LListFindAppendPtr (list, obj, cmpfn);
if (unique && !jr_LListIsEmpty(list)) {
if (prev == 0) {
next = jr_LListHeadPtr(list);
}
else {
next = jr_LListNextElementPtr (list, prev);
}
if (next) {
if ((*cmpfn) (obj, next) == 0) return 0;
/* next is the same as obj */
}
}
new = jr_LListNewNextElementPtrWithSize (list, prev, size);
return (new);
}
void *jr_LListSetNewElementUniquely (list, obj, cmpfn)
jr_LList * list;
void * obj;
jr_int (*cmpfn) ();
{
void * new;
new = jr_LListNewElementPtrUniquely (list, obj, cmpfn);
if (new) {
memcpy (new, obj, jr_LListElementSize (list));
}
return new;
}
|
frankjas/libjr
|
libjr/misc/linsrch.c
|
<filename>libjr/misc/linsrch.c
#include "ezport.h"
#include <stdio.h>
#include <ctype.h>
#include "jr/string.h"
void *jr_LinearSearch(base_arg, num_items, sizeof_each_item, compf, key_or_pattern)
const void * base_arg ;
jr_int num_items ;
jr_int sizeof_each_item ;
jr_int (*compf)() ;
const void * key_or_pattern ;
{
const char * base = (const char *) base_arg ;
jr_int byte_offset ;
jr_int i ;
jr_int compval ;
for (i=0; i < num_items; i++) {
byte_offset = (i * sizeof_each_item) ;
compval = (*compf) (key_or_pattern, base + byte_offset) ;
if (compval == 0) return((void *) (base + byte_offset)) ;
}
return(0) ;
}
|
frankjas/libjr
|
libjr/syscalls/sighndlr.c
|
<reponame>frankjas/libjr<gh_stars>0
#define _POSIX_SOURCE 1
#include "ezport.h"
#include <sys/wait.h>
#include "jr/syscalls.h"
void jr_SigChildHandler (signum)
jr_int signum;
{
while (waitpid(-1, 0, WNOHANG) > 0);
}
|
frankjas/libjr
|
libjr/io/jr_tar.c
|
#define _POSIX_SOURCE 1
#include "ezport.h"
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/stat.h>
#include "jr/malloc.h"
#include "jr/error.h"
#include "jr/tar.h"
#include "jr/syscalls.h"
jr_int jr_TarEntryInitFromRfp (tar_entry_ptr, rfp, error_buf)
jr_TarEntryType * tar_entry_ptr ;
FILE * rfp ;
char * error_buf ;
{
jr_int header_offset;
jr_int data_offset;
jr_int status;
header_offset = ftell (rfp) ;
status = jr_TarEntryInitFromFifoRfp (tar_entry_ptr, rfp, error_buf);
data_offset = ftell(rfp) ;
jr_TarEntrySetHeaderOffset (tar_entry_ptr, header_offset);
jr_TarEntrySetDataOffset (tar_entry_ptr, data_offset);
if (status > 0) {
status = 0;
}
return status;
}
jr_int jr_TarEntryInitFromFifoRfp (tar_entry_ptr, rfp, error_buf)
jr_TarEntryType * tar_entry_ptr ;
FILE * rfp ;
char * error_buf ;
{
jr_int magic_length;
jr_int num_items;
long tmp_value;
jr_int status;
char tmp_buf [16]; /* must hold mtime, size fields */
jr_TarEntryInit (tar_entry_ptr);
num_items = fread (
jr_TarEntryHeaderPtr (tar_entry_ptr),
sizeof (*jr_TarEntryHeaderPtr (tar_entry_ptr)),
1, rfp
);
if (num_items != 1) {
if (feof (rfp)) {
jr_esprintf (error_buf, "couldn't read: end-of-file");
status = jr_TAR_EOF_ERROR;
}
else {
jr_esprintf (error_buf, "couldn't read: %s", strerror (errno));
status = jr_TAR_INTERNAL_ERROR;
}
goto return_status;
}
if (jr_TAR_BLOCK_SIZE < sizeof (*jr_TarEntryHeaderPtr (tar_entry_ptr))) {
jr_esprintf (error_buf, "jr_TAR_BLOCK_SIZE (%d) < sizeof (jr_TarHeaderStruct) (%d)",
jr_TAR_BLOCK_SIZE, (jr_int) sizeof (*jr_TarEntryHeaderPtr (tar_entry_ptr))
);
status = jr_TAR_INTERNAL_ERROR;
goto return_status;
}
if (sizeof (tmp_buf) < jr_TAR_BLOCK_SIZE - sizeof (*jr_TarEntryHeaderPtr (tar_entry_ptr))) {
jr_esprintf (error_buf, "couldn't align input: tmp_buf too small, should be at least %d bytes",
jr_TAR_BLOCK_SIZE - (jr_int) sizeof (*jr_TarEntryHeaderPtr (tar_entry_ptr))
);
status = jr_TAR_INTERNAL_ERROR;
goto return_status;
}
num_items = fread (
tmp_buf,
jr_TAR_BLOCK_SIZE - sizeof (*jr_TarEntryHeaderPtr (tar_entry_ptr)),
1, rfp
);
if (num_items != 1 && !feof (rfp)) {
jr_esprintf (error_buf, "couldn't read: %s", strerror (errno));
status = jr_TAR_INTERNAL_ERROR;
goto return_status;
}
if ( jr_TarEntryHeaderName (tar_entry_ptr)[0] == 0
&& jr_TarEntryPrefix (tar_entry_ptr)[0] == 0) {
/*
* This is the case which will be encountered
* in the first of the 2 NULL blocks at the end
* of a tar file.
*/
jr_esprintf (error_buf, "couldn't read: null tar block");
status = jr_TAR_EOF_ERROR;
goto return_status;
}
magic_length = strlen (TMAGIC);
if (strncmp (jr_TarEntryHeaderMagic (tar_entry_ptr), TMAGIC, magic_length) != 0) {
if ( jr_TarEntryHeaderMagic (tar_entry_ptr)[magic_length] != 0
&& jr_TarEntryHeaderMagic (tar_entry_ptr)[magic_length] != ' ') {
jr_esprintf (error_buf, "%.128s: bad magic field", jr_TarEntryHeaderName( tar_entry_ptr));
status = jr_TAR_INTERNAL_ERROR;
goto return_status;
}
}
switch (jr_TarEntryHeaderTypeFlag (tar_entry_ptr)) {
case LNKTYPE :
case SYMTYPE :
case DIRTYPE :
case BLKTYPE :
case CHRTYPE :
case FIFOTYPE : {
jr_TarEntrySetSizeInt (tar_entry_ptr, 0);
jr_TarEntrySetNumBlocks (tar_entry_ptr, 0);
break ;
}
default :
case REGTYPE :
case AREGTYPE :
case CONTTYPE : {
strncpy (
tmp_buf, jr_TarEntryHeaderSize (tar_entry_ptr),
sizeof (jr_TarEntryHeaderSize (tar_entry_ptr))
);
tmp_buf [sizeof (jr_TarEntryHeaderSize (tar_entry_ptr))] = 0;
num_items = sscanf (tmp_buf, " %lo", &tmp_value) ;
if (num_items != 1) {
jr_esprintf (error_buf, "couldn't parse 'size' field");
status = jr_TAR_INTERNAL_ERROR;
goto return_status;
}
jr_TarEntrySetSizeInt (tar_entry_ptr, tmp_value);
tmp_value = (jr_TarEntrySize (tar_entry_ptr) + (jr_TAR_BLOCK_SIZE-1));
tmp_value /= jr_TAR_BLOCK_SIZE ;
jr_TarEntrySetNumBlocks (tar_entry_ptr, tmp_value);
break ;
}
}
num_items = sscanf (jr_TarEntryHeaderMode (tar_entry_ptr), " %lo", &tmp_value) ;
if (num_items != 1) {
jr_esprintf (error_buf, "couldn't parse 'mode' field");
status = jr_TAR_INTERNAL_ERROR;
goto return_status;
}
jr_TarEntrySetModeInt (tar_entry_ptr, tmp_value);
num_items = sscanf (jr_TarEntryHeaderUID (tar_entry_ptr), " %lo", &tmp_value) ;
if (num_items != 1) {
jr_esprintf (error_buf, "couldn't parse 'uid' field");
status = jr_TAR_INTERNAL_ERROR;
goto return_status;
}
jr_TarEntrySetUIDInt (tar_entry_ptr, tmp_value);
num_items = sscanf (jr_TarEntryHeaderGID (tar_entry_ptr), " %lo", &tmp_value) ;
if (num_items != 1) {
jr_esprintf (error_buf, "couldn't parse 'gid' field");
status = jr_TAR_INTERNAL_ERROR;
goto return_status;
}
jr_TarEntrySetGIDInt (tar_entry_ptr, tmp_value);
strncpy (
tmp_buf, jr_TarEntryHeaderMTime (tar_entry_ptr),
sizeof (jr_TarEntryHeaderMTime (tar_entry_ptr))
);
tmp_buf [sizeof (jr_TarEntryHeaderMTime (tar_entry_ptr))] = 0;
num_items = sscanf (tmp_buf, " %lo", &tmp_value) ;
if (num_items != 1) {
jr_esprintf (error_buf, "couldn't parse 'mtime' field");
status = jr_TAR_INTERNAL_ERROR;
goto return_status;
}
jr_TarEntrySetMTimeInt (tar_entry_ptr, tmp_value);
num_items = sscanf (jr_TarEntryHeaderDevMajor (tar_entry_ptr), " %lo", &tmp_value) ;
if (num_items != 1) {
if (jr_TarEntryHeaderDevMajor (tar_entry_ptr) [0] != 0) {
jr_esprintf (error_buf, "couldn't parse 'devmajor' field");
status = jr_TAR_INTERNAL_ERROR;
goto return_status;
}
}
else {
jr_TarEntrySetDevMajorInt (tar_entry_ptr, tmp_value);
}
num_items = sscanf (jr_TarEntryHeaderDevMinor (tar_entry_ptr), " %lo", &tmp_value) ;
if (num_items != 1) {
if (jr_TarEntryHeaderDevMinor (tar_entry_ptr) [0] != 0) {
jr_esprintf (error_buf, "couldn't parse 'devminor' field");
status = jr_TAR_INTERNAL_ERROR;
goto return_status;
}
}
else {
jr_TarEntrySetDevMinorInt (tar_entry_ptr, tmp_value);
}
num_items = sscanf (jr_TarEntryHeaderChkSum (tar_entry_ptr), " %lo", &tmp_value) ;
if (num_items != 1) {
jr_esprintf (error_buf, "couldn't parse 'chksum' field");
status = jr_TAR_INTERNAL_ERROR;
goto return_status;
}
jr_TarEntrySetChkSumInt (tar_entry_ptr, tmp_value);
status = jr_TAR_BLOCK_SIZE;
return_status : {
if (status != 0) {
jr_TarEntryUndo (tar_entry_ptr);
}
}
return status;
}
jr_int jr_TarEntryReadData (tar_entry_ptr, rfp, opt_data_ref, error_buf)
jr_TarEntryType * tar_entry_ptr ;
FILE * rfp ;
void ** opt_data_ref;
char * error_buf ;
{
struct stat stat_info[1];
void * data_ptr = 0;
jr_int num_items;
jr_int is_fifo_rfp = 0;
jr_int align_bytes = 0;
unsigned jr_int k;
jr_int status;
if (opt_data_ref) {
data_ptr = jr_malloc (jr_TarEntrySize (tar_entry_ptr) + 1) ;
/*
* add 1 since we want to make a string out of it
* added 3/1/94
*/
if (data_ptr == 0) {
jr_esprintf (error_buf, "couldn't allocate %ld bytes for data (header offset %ld)",
(long) jr_TarEntrySize (tar_entry_ptr),
(long) jr_TarEntryHeaderOffset (tar_entry_ptr)
) ;
status = jr_TAR_INTERNAL_ERROR;
goto return_status;
}
}
if (jr_TarEntrySize (tar_entry_ptr) > 0) {
if (data_ptr) {
num_items = fread (data_ptr, jr_TarEntrySize (tar_entry_ptr), 1, rfp) ;
if (num_items != 1) {
jr_esprintf (error_buf, "couldn't read %ld bytes for (data header block %ld) : %s",
(long) jr_TarEntrySize (tar_entry_ptr),
(long) jr_TarEntryHeaderOffset (tar_entry_ptr),
strerror(errno)
) ;
status = jr_TAR_INTERNAL_ERROR;
goto return_status;
}
}
else {
status = fstat (fileno (rfp), stat_info);
if (status != 0) {
jr_esprintf (error_buf, "couldn't fstat() input: %s",
strerror(errno)
) ;
status = jr_TAR_INTERNAL_ERROR;
goto return_status;
}
is_fifo_rfp = S_ISFIFO (stat_info->st_mode);
if (is_fifo_rfp) {
for (k=0; k < jr_TarEntrySize (tar_entry_ptr); k++) {
if (getc (rfp) == EOF) {
break;
}
}
}
else {
fseek (rfp, jr_TarEntrySize (tar_entry_ptr), SEEK_CUR) ;
}
}
align_bytes = jr_TarFilePtrAlignFifoRead (rfp, jr_TarEntrySize (tar_entry_ptr));
}
if (opt_data_ref) {
((char *) data_ptr) [jr_TarEntrySize (tar_entry_ptr)] = 0;
*opt_data_ref = data_ptr;
data_ptr = 0;
}
status = jr_TarEntrySize (tar_entry_ptr) + align_bytes;
return_status : {
if (data_ptr) {
jr_free (data_ptr);
}
}
return status;
}
jr_int jr_TarEntryCopyData (tar_entry_ptr, rfp, wfp, error_buf)
jr_TarEntryType * tar_entry_ptr ;
FILE * rfp ;
FILE * wfp ;
char * error_buf ;
{
unsigned jr_int k;
jr_int c;
jr_int align_bytes = 0;
jr_int status;
if (jr_TarEntrySize (tar_entry_ptr) > 0) {
for (k=0; k < jr_TarEntrySize (tar_entry_ptr); k++) {
if ((c = getc (rfp)) == EOF) {
jr_esprintf (error_buf, "unexpected EOF after byte %d", k);
status = jr_TAR_EOF_ERROR;
goto return_status;
}
putc (c, wfp);
}
align_bytes = jr_TarFilePtrAlignFifoWrite (wfp, jr_TarEntrySize (tar_entry_ptr));
align_bytes = jr_TarFilePtrAlignFifoRead (rfp, jr_TarEntrySize (tar_entry_ptr));
}
status = jr_TarEntrySize (tar_entry_ptr) + align_bytes;
return_status : {
}
return status;
}
jr_int jr_TarEntryWriteSegment (
jr_TarEntryType * tar_entry_ptr ,
unsigned jr_int total_data_size,
const void * opt_data_ptr,
FILE * opt_data_rfp,
unsigned jr_int curr_data_size,
FILE * wfp,
char * error_buf)
{
char tmp_buf [16]; /* must hold mtime, size fields */
jr_int num_items;
jr_int status;
/*
* This function writes out the 512 byte tar header
* followed by the data and seeks to the next 512 block boundary
* after the data has been written.
* The tar header data will be adjusted to match the new size
* argument passed in, and a new checksum will be calculated.
*/
switch (jr_TarEntryTypeFlag (tar_entry_ptr)) {
case DIRTYPE :
case LNKTYPE :
case SYMTYPE : {
total_data_size = 0;
break;
}
}
jr_TarEntrySetSize (tar_entry_ptr, total_data_size);
jr_TarEntryMakePosixConformant (tar_entry_ptr);
num_items = fwrite (
jr_TarEntryHeaderPtr (tar_entry_ptr),
sizeof (*jr_TarEntryHeaderPtr (tar_entry_ptr)),
1, wfp
);
if (num_items != 1) {
jr_esprintf (error_buf, "couldn't write tar header: %s", strerror (errno));
status = jr_TAR_INTERNAL_ERROR;
goto return_status;
}
if (sizeof (*jr_TarEntryHeaderPtr (tar_entry_ptr)) > jr_TAR_BLOCK_SIZE) {
jr_esprintf (error_buf, "sizeof (jr_TarHeaderStruct) (%d) > jr_TAR_BLOCK_SIZE (%d)",
(jr_int) sizeof (*jr_TarEntryHeaderPtr (tar_entry_ptr)), jr_TAR_BLOCK_SIZE
);
status = jr_TAR_INTERNAL_ERROR;
goto return_status;
}
if (jr_TAR_BLOCK_SIZE - sizeof (*jr_TarEntryHeaderPtr (tar_entry_ptr)) > sizeof (tmp_buf)) {
jr_esprintf (error_buf, "couldn't align input: tmp_buf too small, should be at least %d bytes",
jr_TAR_BLOCK_SIZE - (jr_int) sizeof (*jr_TarEntryHeaderPtr (tar_entry_ptr))
);
status = jr_TAR_INTERNAL_ERROR;
goto return_status;
}
memset (tmp_buf, 0, sizeof (tmp_buf));
num_items = fwrite (
tmp_buf,
jr_TAR_BLOCK_SIZE - sizeof (*jr_TarEntryHeaderPtr (tar_entry_ptr)),
1, wfp
);
if (num_items != 1) {
jr_esprintf (error_buf, "couldn't write tar header alignment: %s", strerror (errno));
status = jr_TAR_INTERNAL_ERROR;
goto return_status;
}
if (curr_data_size > 0) {
if (opt_data_ptr) {
num_items = fwrite (opt_data_ptr, curr_data_size, 1, wfp);
if (num_items != 1) {
jr_esprintf (error_buf, "couldn't write data: %s", strerror (errno));
status = jr_TAR_INTERNAL_ERROR;
goto return_status;
}
}
else if (opt_data_rfp) {
/*
* Fill with null if no data or not enough data.
*/
jr_int c = 0;
unsigned jr_int k;
for (k=0; k < curr_data_size; k++) {
if (opt_data_rfp) {
c = getc (opt_data_rfp);
if (c == EOF) {
c = 0;
}
}
putc (c, wfp);
}
}
if (opt_data_ptr || opt_data_rfp) {
if (curr_data_size == total_data_size) {
jr_TarFilePtrAlignFifoWrite (wfp, curr_data_size);
}
}
}
status = 0;
return_status : {
}
return status;
}
void jr_TarEntrySetIsDir (tar_entry_ptr)
jr_TarEntryType * tar_entry_ptr;
{
jr_TarEntrySetTypeFlag (tar_entry_ptr, DIRTYPE);
}
void jr_TarEntrySetIsFile (tar_entry_ptr)
jr_TarEntryType * tar_entry_ptr;
{
jr_TarEntrySetTypeFlag (tar_entry_ptr, REGTYPE);
}
void jr_TarEntrySetCustomType (tar_entry_ptr, type_value)
jr_TarEntryType * tar_entry_ptr;
jr_int type_value;
{
jr_TarEntrySetTypeFlag (tar_entry_ptr, type_value);
}
void jr_TarEntrySetIsSymLink (tar_entry_ptr, link_name)
jr_TarEntryType * tar_entry_ptr;
const char * link_name;
{
jr_TarEntrySetTypeFlag (tar_entry_ptr, SYMTYPE);
strncpy (
jr_TarEntryHeaderLinkName (tar_entry_ptr),
link_name,
sizeof (jr_TarEntryHeaderLinkName (tar_entry_ptr)) - 1
);
}
void jr_TarEntrySetUserInfo (tar_entry_ptr, uid, opt_uname, gid, opt_gname)
jr_TarEntryType * tar_entry_ptr;
jr_int uid;
const char * opt_uname;
jr_int gid;
const char * opt_gname;
{
jr_TarEntrySetUID (tar_entry_ptr, uid);
jr_TarEntrySetGID (tar_entry_ptr, gid);
if (opt_uname) {
strncpy (
jr_TarEntryHeaderUName (tar_entry_ptr),
opt_uname,
sizeof (jr_TarEntryHeaderUName (tar_entry_ptr)) - 1
);
}
if (opt_gname) {
strncpy (
jr_TarEntryHeaderGName (tar_entry_ptr),
opt_gname,
sizeof (jr_TarEntryHeaderGName (tar_entry_ptr)) - 1
);
}
}
void jr_TarEntrySetPathInfo (tar_entry_ptr, pathname, is_dir, mode, mtime)
jr_TarEntryType * tar_entry_ptr ;
const char * pathname ;
jr_int is_dir;
jr_int mode;
jr_int mtime;
{
jr_int pathname_length = strlen (pathname);
jr_int tar_pathname_length = pathname_length;
jr_int has_trailing_slash = 0;
if (is_dir && pathname_length > 0) {
if (pathname [pathname_length - 1] != '/') {
has_trailing_slash = 0;
tar_pathname_length ++;
}
}
if ( tar_pathname_length
> (jr_int) (sizeof(jr_TarEntryHeaderName (tar_entry_ptr))
+ sizeof(jr_TarEntryHeaderPrefix (tar_entry_ptr)))) {
/*
* Path name too long. Is caller's responsibility to check.
*/
return;
}
if (is_dir) {
jr_TarEntrySetIsDir (tar_entry_ptr);
}
else {
jr_TarEntrySetIsFile (tar_entry_ptr);
}
jr_TarEntrySetMode (tar_entry_ptr, mode);
jr_TarEntrySetMTime (tar_entry_ptr, mtime);
if (tar_pathname_length > (jr_int) sizeof(jr_TarEntryHeaderName (tar_entry_ptr))) {
const char * cp ;
jr_int prefix_length = tar_pathname_length;
for (cp = pathname + pathname_length; cp >= pathname; cp--) {
if (*cp == '/') {
prefix_length = cp - pathname + 1;
if (prefix_length <= (jr_int) sizeof(jr_TarEntryHeaderPrefix (tar_entry_ptr))) {
break ;
}
}
}
if ( (*cp == '/') && (cp != pathname)
&& tar_pathname_length - prefix_length
<= (jr_int) sizeof (jr_TarEntryHeaderName (tar_entry_ptr))) {
strncpy (
jr_TarEntryHeaderPrefix (tar_entry_ptr),
pathname,
prefix_length
);
if (prefix_length < (jr_int) sizeof(jr_TarEntryHeaderPrefix (tar_entry_ptr))) {
/*
** 9/11/06: if it has no null, use trailing '/' instead, otherwise no null?
** 12/31/06: use "null required if null fits" rule?
** ToDo: verify with standard.
*/
jr_TarEntryHeaderPrefix (tar_entry_ptr)[prefix_length] = 0;
}
strncpy (
jr_TarEntryHeaderName (tar_entry_ptr),
cp + 1,
sizeof (jr_TarEntryHeaderName (tar_entry_ptr))
);
if (is_dir && !has_trailing_slash) {
jr_TarEntryHeaderName (tar_entry_ptr)[pathname_length - prefix_length] = '/';
}
/*
* Use tar_pathname_length since we've added the trailing slash if it's a dir.
*/
if ( tar_pathname_length - prefix_length
< (jr_int) sizeof(jr_TarEntryHeaderName (tar_entry_ptr))) {
jr_TarEntryHeaderName (tar_entry_ptr)[tar_pathname_length - prefix_length] = 0;
/*
* Null required if the null fits.
*/
}
}
else {
/*
* Path name too long. Is caller's responsibility to check.
*/
jr_TarEntryHeaderName (tar_entry_ptr)[0] = 0;
}
}
else {
strncpy (
jr_TarEntryHeaderName (tar_entry_ptr),
pathname,
sizeof (jr_TarEntryHeaderName (tar_entry_ptr))
);
memset (
jr_TarEntryHeaderPrefix (tar_entry_ptr),
0,
sizeof (jr_TarEntryHeaderPrefix (tar_entry_ptr))
);
if (is_dir && !has_trailing_slash) {
jr_TarEntryHeaderName (tar_entry_ptr)[pathname_length] = '/';
}
/*
* Use tar_pathname_length since we've added the trailing slash if it's a dir.
*/
if (tar_pathname_length < (jr_int) sizeof(jr_TarEntryHeaderName (tar_entry_ptr))) {
jr_TarEntryHeaderName (tar_entry_ptr)[tar_pathname_length] = 0;
}
}
}
void jr_TarEntryInit (tar_entry_ptr)
jr_TarEntryType * tar_entry_ptr;
{
memset (tar_entry_ptr, 0, sizeof (*tar_entry_ptr));
}
void jr_TarEntryUndo (tar_entry_ptr)
jr_TarEntryType * tar_entry_ptr;
{
}
void jr_TarEntrySetMode (tar_entry_ptr, mode_int)
jr_TarEntryType * tar_entry_ptr;
jr_int mode_int;
{
if (mode_int < 0) {
mode_int = 0;
}
jr_TarEntrySetModeInt (tar_entry_ptr, mode_int);
if ((unsigned) mode_int < jr_TAR_MAX_7_BYTE_ASCII_OCTAL) {
sprintf (jr_TarEntryHeaderMode (tar_entry_ptr) ,"%07o", (unsigned) mode_int) ;
}
}
void jr_TarEntrySetUID (tar_entry_ptr, uid_int)
jr_TarEntryType * tar_entry_ptr;
jr_int uid_int;
{
if (uid_int < 0) {
uid_int = jr_USHRT_MAX; /* 1/5/07: Unix id for "nobody"? */
}
jr_TarEntrySetUIDInt (tar_entry_ptr, uid_int);
if ((unsigned) uid_int < jr_TAR_MAX_7_BYTE_ASCII_OCTAL) {
sprintf (jr_TarEntryHeaderUID (tar_entry_ptr) ,"%07o", (unsigned) uid_int) ;
}
}
void jr_TarEntrySetGID (tar_entry_ptr, gid_int)
jr_TarEntryType * tar_entry_ptr;
jr_int gid_int;
{
if (gid_int < 0) {
gid_int = jr_USHRT_MAX; /* 1/5/07: Unix id for "nobody"? */
}
jr_TarEntrySetGIDInt (tar_entry_ptr, gid_int);
if ((unsigned) gid_int < jr_TAR_MAX_7_BYTE_ASCII_OCTAL) {
sprintf (jr_TarEntryHeaderGID (tar_entry_ptr) ,"%07o", (unsigned) gid_int) ;
}
}
void jr_TarEntrySetSize (tar_entry_ptr, size_int)
jr_TarEntryType * tar_entry_ptr;
unsigned jr_int size_int;
{
jr_TarEntrySetSizeInt (tar_entry_ptr, size_int);
if (size_int < jr_TAR_MAX_12_BYTE_ASCII_OCTAL) {
sprintf (jr_TarEntryHeaderSize (tar_entry_ptr) ,"%011o", size_int) ;
}
else {
sprintf (jr_TarEntryHeaderSize (tar_entry_ptr) ,"%011o", jr_TAR_MAX_12_BYTE_ASCII_OCTAL) ;
}
}
void jr_TarEntrySetMTime (tar_entry_ptr, mtime_int)
jr_TarEntryType * tar_entry_ptr;
jr_int mtime_int;
{
if (mtime_int < 0) {
mtime_int = 0;
}
jr_TarEntrySetMTimeInt (tar_entry_ptr, mtime_int);
if ((unsigned) mtime_int < jr_TAR_MAX_12_BYTE_ASCII_OCTAL) {
sprintf (jr_TarEntryHeaderMTime (tar_entry_ptr) ,"%011o", (unsigned) mtime_int) ;
}
}
void jr_TarEntrySetDevMajor (tar_entry_ptr, dev_major)
jr_TarEntryType * tar_entry_ptr;
jr_int dev_major;
{
if (dev_major < 0) {
dev_major = 0;
}
jr_TarEntrySetDevMajorInt (tar_entry_ptr, dev_major);
if ((unsigned) dev_major < jr_TAR_MAX_7_BYTE_ASCII_OCTAL) {
sprintf (jr_TarEntryHeaderDevMajor (tar_entry_ptr) ,"%07o", (unsigned) dev_major) ;
}
}
void jr_TarEntrySetDevMinor (tar_entry_ptr, dev_minor)
jr_TarEntryType * tar_entry_ptr;
jr_int dev_minor;
{
if (dev_minor < 0) {
dev_minor = 0;
}
jr_TarEntrySetDevMinorInt (tar_entry_ptr, dev_minor);
if ((unsigned) dev_minor < jr_TAR_MAX_7_BYTE_ASCII_OCTAL) {
sprintf (jr_TarEntryHeaderDevMinor (tar_entry_ptr) ,"%07o", (unsigned) dev_minor) ;
}
}
void jr_TarEntrySetMagic (tar_entry_ptr, magic_string)
jr_TarEntryType * tar_entry_ptr;
const char * magic_string;
{
sprintf (jr_TarEntryHeaderMagic (tar_entry_ptr), "%.*s",
(jr_int) sizeof(jr_TarEntryHeaderMagic (tar_entry_ptr))-1,
TMAGIC
) ;
}
void jr_TarEntrySetVersion (tar_entry_ptr, magic_string)
jr_TarEntryType * tar_entry_ptr;
const char * magic_string;
{
jr_TarHeaderStruct * tar_header_ptr = jr_TarEntryHeaderPtr (tar_entry_ptr);
tar_header_ptr->version [0] = '0';
tar_header_ptr->version [1] = '0';
/*
* No null in this field.
*/
}
static unsigned long SumByteString(string, nbytes)
unsigned char * string ;
jr_int nbytes ;
{
unsigned long sum = 0L;
jr_int i;
for (i=0; i < nbytes; i++) {
sum += string[i] ;
}
return(sum) ;
}
void jr_TarEntryInitCheckSum (tar_entry_ptr)
jr_TarEntryType * tar_entry_ptr;
{
jr_TarHeaderStruct * thp = jr_TarEntryHeaderPtr (tar_entry_ptr);
jr_int chksum_val = 0;
chksum_val += SumByteString (jr_TarHeaderName (thp), sizeof(jr_TarHeaderName (thp))) ;
chksum_val += SumByteString (jr_TarHeaderMode (thp), sizeof(jr_TarHeaderMode (thp))) ;
chksum_val += SumByteString (jr_TarHeaderUID (thp), sizeof(jr_TarHeaderUID (thp))) ;
chksum_val += SumByteString (jr_TarHeaderGID (thp), sizeof(jr_TarHeaderGID (thp))) ;
chksum_val += SumByteString (jr_TarHeaderSize (thp), sizeof(jr_TarHeaderSize (thp))) ;
chksum_val += SumByteString (jr_TarHeaderMTime (thp), sizeof(jr_TarHeaderMTime (thp))) ;
chksum_val += SumByteString (" ", sizeof(jr_TarHeaderChkSum (thp))) ;
chksum_val += SumByteString (&jr_TarHeaderTypeFlag (thp), sizeof(thp->typeflag)) ;
chksum_val += SumByteString (jr_TarHeaderLinkName (thp), sizeof(jr_TarHeaderLinkName (thp))) ;
chksum_val += SumByteString (jr_TarHeaderMagic (thp), sizeof(jr_TarHeaderMagic (thp))) ;
chksum_val += SumByteString (jr_TarHeaderVersion (thp), sizeof(jr_TarHeaderVersion (thp))) ;
chksum_val += SumByteString (jr_TarHeaderUName (thp), sizeof(jr_TarHeaderUName (thp))) ;
chksum_val += SumByteString (jr_TarHeaderGName (thp), sizeof(jr_TarHeaderGName (thp))) ;
chksum_val += SumByteString (jr_TarHeaderDevMajor (thp), sizeof(jr_TarHeaderDevMajor (thp))) ;
chksum_val += SumByteString (jr_TarHeaderDevMinor (thp), sizeof(jr_TarHeaderDevMinor (thp))) ;
chksum_val += SumByteString (jr_TarHeaderPrefix (thp), sizeof(jr_TarHeaderPrefix (thp))) ;
jr_TarEntrySetChkSumInt (tar_entry_ptr, chksum_val);
if ((unsigned) chksum_val < jr_TAR_MAX_7_BYTE_ASCII_OCTAL) {
sprintf(jr_TarHeaderChkSum (thp), "%07o", (unsigned) chksum_val) ;
}
else {
/*
* max. check sum : 512 * 256 == 131072 < 2079151 == MAX_7_BYTE_ASCII_OCTAL
*/
}
}
void jr_TarEntryMakePosixConformant (tar_entry_ptr)
jr_TarEntryType * tar_entry_ptr;
{
jr_TarEntrySetMagic (tar_entry_ptr, TMAGIC);
jr_TarEntrySetVersion (tar_entry_ptr, TVERSION);
jr_TarEntryInitCheckSum (tar_entry_ptr);
}
const char *jr_TarEntryMakeFullPath (tar_entry_ptr)
jr_TarEntryType * tar_entry_ptr;
{
jr_int prefix_length = strlen (jr_TarEntryPrefix (tar_entry_ptr));
jr_int name_length = strlen (jr_TarEntryName (tar_entry_ptr));
jr_int path_length = prefix_length + 1 + name_length;
char * path_string;
path_string = jr_malloc (path_length + 1);
if (jr_TarEntryPrefix (tar_entry_ptr)[0]) {
if (jr_TarEntryPrefix(tar_entry_ptr)[prefix_length - 1] == '/') {
sprintf (path_string, "%s%s",
jr_TarEntryPrefix (tar_entry_ptr), jr_TarEntryName (tar_entry_ptr)
);
}
else {
sprintf (path_string, "%s/%s",
jr_TarEntryPrefix (tar_entry_ptr), jr_TarEntryName (tar_entry_ptr)
);
}
}
else {
sprintf (path_string, "%s", jr_TarEntryName (tar_entry_ptr));
}
return path_string;
}
void jr_TarFilePtrAlign (fp)
FILE * fp;
{
unsigned jr_int absolute_offset ;
unsigned jr_int offset_within_block ;
absolute_offset = ftell(fp) ;
offset_within_block = (absolute_offset % jr_TAR_BLOCK_SIZE) ;
if (offset_within_block != 0) {
absolute_offset += jr_TAR_BLOCK_SIZE - offset_within_block ;
fseek(fp, absolute_offset, SEEK_SET) ;
}
}
jr_int jr_TarFilePtrAlignFifoRead (rfp, num_bytes_moved)
FILE * rfp;
unsigned jr_int num_bytes_moved;
{
unsigned jr_int offset_within_block ;
unsigned jr_int bytes_to_block_end = 0;
unsigned jr_int k;
offset_within_block = (num_bytes_moved % jr_TAR_BLOCK_SIZE) ;
if (offset_within_block != 0) {
bytes_to_block_end = jr_TAR_BLOCK_SIZE - offset_within_block;
for (k=0; k < bytes_to_block_end; k++) {
if (getc (rfp) == EOF) {
break;
}
}
}
return bytes_to_block_end;
}
jr_int jr_TarFilePtrAlignFifoWrite (wfp, num_bytes_moved)
FILE * wfp;
unsigned jr_int num_bytes_moved;
{
unsigned jr_int offset_within_block ;
unsigned jr_int bytes_to_block_end = 0;
unsigned jr_int k;
offset_within_block = (num_bytes_moved % jr_TAR_BLOCK_SIZE) ;
if (offset_within_block != 0) {
bytes_to_block_end = jr_TAR_BLOCK_SIZE - offset_within_block;
for (k=0; k < bytes_to_block_end; k++) {
putc (0, wfp);
}
}
return bytes_to_block_end;
}
jr_int jr_TarFileWriteEOF (wfp, error_buf)
FILE * wfp;
char * error_buf;
{
jr_int num_items;
jr_int k;
char null_buf [jr_TAR_BLOCK_SIZE];
/*
* 6/15/2004: two null blocks signify the end of a tar file
* according to /usr/include/tar.h on Linux.
*/
memset (null_buf, 0, jr_TAR_BLOCK_SIZE);
for (k=0; k < 2; k++) {
num_items = fwrite (null_buf, jr_TAR_BLOCK_SIZE, 1, wfp);
if (num_items != 1) {
jr_esprintf (error_buf, "couldn't write null tar header: %s", strerror (errno));
return jr_TAR_INTERNAL_ERROR;
}
}
return 0;
}
const char * jr_TarTypeFlagToString(type_flag)
jr_int type_flag;
{
char * type_desc ;
switch (type_flag) {
case LNKTYPE : type_desc = "hard-link" ; break ;
case SYMTYPE : type_desc = "symb-link" ; break ;
case DIRTYPE : type_desc = "directory" ; break ;
case BLKTYPE : type_desc = "blck-spec" ; break ;
case CHRTYPE : type_desc = "char-spec" ; break ;
case FIFOTYPE : type_desc = "fifo-spec" ; break ;
case REGTYPE : type_desc = "file" ; break;
case AREGTYPE : type_desc = "file" ; break;
case CONTTYPE : type_desc = "cont-spec" ; break ;
default : type_desc = "UNKNOWN" ; break ;
}
return(type_desc) ;
}
unsigned jr_int jr_TarModeToPerms (
jr_int tar_mode)
{
unsigned jr_int perm_flags = 0;
if (tar_mode & TSUID) {
perm_flags |= jr_PERM_S_OWNER;
}
if (tar_mode & TSGID) {
perm_flags |= jr_PERM_S_GROUP;
}
if (tar_mode & TUREAD) {
perm_flags |= jr_PERM_R_OWNER;
}
if (tar_mode & TUWRITE) {
perm_flags |= jr_PERM_W_OWNER;
}
if (tar_mode & TUEXEC) {
perm_flags |= jr_PERM_X_OWNER;
}
if (tar_mode & TGREAD) {
perm_flags |= jr_PERM_R_GROUP;
}
if (tar_mode & TGWRITE) {
perm_flags |= jr_PERM_W_GROUP;
}
if (tar_mode & TGEXEC) {
perm_flags |= jr_PERM_X_GROUP;
}
if (tar_mode & TOREAD) {
perm_flags |= jr_PERM_R_OTHER;
}
if (tar_mode & TOWRITE) {
perm_flags |= jr_PERM_W_OTHER;
}
if (tar_mode & TOEXEC) {
perm_flags |= jr_PERM_X_OTHER;
}
return perm_flags;
}
|
frankjas/libjr
|
libjr/struct/ptrmap.c
|
<gh_stars>0
#include "ptrmap.h"
void jr_PtrMapInit (ptr_map, max_category_size, ptr_data_size)
jr_PtrMapType * ptr_map;
jr_int max_category_size;
jr_int ptr_data_size;
{
memset (ptr_map, 0, sizeof (jr_PtrMapType));
ptr_map->max_category_size = max_category_size;
ptr_map->ptr_data_size = ptr_data_size;
jr_AListInit (ptr_map->category_list, sizeof (jr_PtrCategoryType));
}
void jr_PtrMapUndo (ptr_map)
jr_PtrMapType * ptr_map;
{
jr_PtrCategoryType * ptr_category;
jr_AListForEachElementPtr (ptr_map->category_list, ptr_category) {
jr_PtrCategoryUndo (ptr_category);
}
jr_AListUndo (ptr_map->category_list);
}
jr_PtrMapType *jr_PtrMapCreate (max_category_size, ptr_data_size)
jr_int max_category_size;
jr_int ptr_data_size;
{
jr_PtrMapType * ptr_map = jr_malloc (sizeof (jr_PtrMapType));
jr_PtrMapInit (ptr_map, max_category_size, ptr_data_size);
return ptr_map;
}
void jr_PtrMapDestroy (ptr_map)
jr_PtrMapType * ptr_map;
{
jr_PtrMapUndo (ptr_map);
jr_free (ptr_map);
}
jr_int jr_PtrMapAddNewPtrWithFileName (ptr_map, category_kind, ptr_value, file_name, line_number)
jr_PtrMapType * ptr_map;
jr_int category_kind;
void * ptr_value;
const char * file_name;
jr_int line_number;
{
jr_PtrCategoryType * ptr_category;
while (jr_AListSize (ptr_map->category_list) <= category_kind) {
ptr_category = jr_AListNewTailPtr (ptr_map->category_list);
jr_PtrCategoryInit (
ptr_category,
ptr_map->max_category_size * jr_AListTailIndex (ptr_map->category_list),
ptr_map->max_category_size,
ptr_map->ptr_data_size
);
}
ptr_category = jr_AListElementPtr (ptr_map->category_list, category_kind);
return jr_PtrCategoryOpenPtr (ptr_category, ptr_value, file_name, line_number);
}
void jr_PtrCategoryInit (ptr_category, min_value, num_values, ptr_data_size)
jr_PtrCategoryType * ptr_category;
jr_int min_value;
jr_int num_values;
jr_int ptr_data_size;
{
memset (ptr_category, 0, sizeof (jr_PtrCategoryType));
ptr_category->min_value = min_value;
ptr_category->num_values = num_values;
ptr_category->next_deleted_desc = -1;
jr_AListInit (ptr_category->ptr_list, sizeof (jr_PtrInfoStruct) + ptr_data_size);
}
void jr_PtrCategoryUndo (ptr_category)
jr_PtrCategoryType * ptr_category;
{
jr_AListUndo (ptr_category->ptr_list);
}
jr_int jr_PtrCategoryOpenPtr (ptr_category, ptr_value, file_name, line_number)
jr_PtrCategoryType * ptr_category;
void * ptr_value;
const char * file_name;
jr_int line_number;
{
jr_PtrInfoStruct * ptr_info;
jr_int ptr_desc;
if (ptr_category->next_deleted_desc >= 0) {
ptr_desc = ptr_category->next_deleted_desc;
ptr_category->next_deleted_desc = jr_PtrCategoryNextDeletedDesc (ptr_category, ptr_desc);
ptr_category->num_deletes--;
}
else {
if (jr_AListSize (ptr_category->ptr_list) >= ptr_category->num_values) {
return -1;
}
jr_AListNewTailPtr (ptr_category->ptr_list);
ptr_desc = ptr_category->min_value + jr_AListTailIndex (ptr_category->ptr_list);
}
ptr_info = jr_PtrCategoryPtrInfo (ptr_category, ptr_desc);
jr_PtrInfoInit (ptr_info, ptr_value, file_name, line_number);
memset (
jr_PtrCategoryDataPtr (ptr_category, ptr_desc), 0, jr_PtrCategoryDataPtrSize (ptr_category)
);
return ptr_desc;
}
void jr_PtrCategoryCloseDesc (ptr_category, ptr_desc)
jr_PtrCategoryType * ptr_category;
jr_int ptr_desc;
{
if (!jr_PtrCategoryIsValidDesc (ptr_category, ptr_desc)) {
return;
}
if (jr_PtrCategoryPtrValue (ptr_category, ptr_desc) == 0) {
return;
}
jr_PtrCategorySetPtrValue (ptr_category, ptr_desc, 0);
jr_PtrCategorySetNextDeletedDesc (ptr_category, ptr_desc, ptr_category->next_deleted_desc);
ptr_category->next_deleted_desc = ptr_desc;
ptr_category->num_deletes++;
}
void *jr_PtrCategoryGetPtr (ptr_category, ptr_desc)
jr_PtrCategoryType * ptr_category;
jr_int ptr_desc;
{
if (jr_PtrCategoryIsValidDesc (ptr_category, ptr_desc)) {
return jr_PtrCategoryPtrValue (ptr_category, ptr_desc);
}
return 0;
}
void jr_PtrCategorySetPtr (ptr_category, ptr_desc, ptr_value)
jr_PtrCategoryType * ptr_category;
jr_int ptr_desc;
void * ptr_value;
{
if (jr_PtrCategoryIsValidDesc (ptr_category, ptr_desc)) {
jr_PtrCategorySetPtrValue (ptr_category, ptr_desc, ptr_value);
}
}
const char *jr_PtrCategoryGetFileName (ptr_category, ptr_desc)
jr_PtrCategoryType * ptr_category;
jr_int ptr_desc;
{
if (jr_PtrCategoryIsValidDesc (ptr_category, ptr_desc)) {
return jr_PtrCategoryFileName (ptr_category, ptr_desc);
}
return 0;
}
jr_int jr_PtrCategoryGetLineNumber (ptr_category, ptr_desc)
jr_PtrCategoryType * ptr_category;
jr_int ptr_desc;
{
if (jr_PtrCategoryIsValidDesc (ptr_category, ptr_desc)) {
return jr_PtrCategoryLineNumber (ptr_category, ptr_desc);
}
return 0;
}
void *jr_PtrCategoryGetDataPtr (ptr_category, ptr_desc)
jr_PtrCategoryType * ptr_category;
jr_int ptr_desc;
{
if (jr_PtrCategoryIsValidDesc (ptr_category, ptr_desc)) {
return jr_PtrCategoryDataPtr (ptr_category, ptr_desc);
}
return 0;
}
void jr_PtrInfoInit (ptr_info, ptr_value, file_name, line_number)
jr_PtrInfoStruct * ptr_info;
void * ptr_value;
const char * file_name;
jr_int line_number;
{
ptr_info->ptr_value = ptr_value;
ptr_info->next_deleted_desc = -1;
ptr_info->file_name = file_name;
ptr_info->line_number = line_number;
}
void *_jr_PtrMapDataPtr (ptr_map, category_kind, ptr_desc)
jr_PtrMapType * ptr_map;
jr_int category_kind;
jr_int ptr_desc;
{
return jr_PtrMapDataPtr (ptr_map, category_kind, ptr_desc);
}
|
frankjas/libjr
|
libjr/syscalls/jr_sleep.c
|
#include "ezport.h"
#include <apr-1/apr_time.h>
#ifdef ostype_winnt
#else
# include <sys/select.h>
#endif
#include "jr/syscalls.h"
void jr_sleep (sleep_sec, sleep_usec)
jr_int sleep_sec;
jr_int sleep_usec;
{
apr_interval_time_t apr_interval;
apr_interval = sleep_sec * 1000000LL + sleep_usec;
apr_sleep (apr_interval);
}
#ifdef ostype_winnt
jr_int jr_uninterrupted_sleep (
jr_int sleep_sec,
jr_int sleep_usec)
{
Sleep( (sleep_sec * 1000000.0 + sleep_usec) / 1000);
/*
** 2/27/07: Doesn't return a value, expects milli-seconds
*/
return 0;
}
#else
jr_int jr_uninterrupted_sleep (
jr_int sleep_sec,
jr_int sleep_usec)
{
struct timeval last_tv;
struct timeval curr_tv;
jr_int status;
curr_tv.tv_sec = sleep_sec;
curr_tv.tv_usec = sleep_usec;
last_tv = curr_tv;
/*
** 2/27/07: ToDo: On systems where select() doesn't decrement the timeval,
** use time() to figure out how much time is left.
*/
while (curr_tv.tv_sec > 0 || curr_tv.tv_usec > 0) {
status = select (0, 0, 0, 0, &curr_tv);
if (status != 0 && errno == EINTR) {
if (curr_tv.tv_sec >= last_tv.tv_sec) {
last_tv.tv_sec--;
last_tv.tv_usec = 0;
}
else {
/*
** 2/27/07: else select is decrementing the time on it's own
*/
last_tv = curr_tv;
}
curr_tv = last_tv;
}
else {
break;
}
}
return 0;
# ifdef mess_with_alarms_to_sleep
{
while (sleep_amount > 0) {
sleep_amount = sleep (sleep_amount);
}
return sleep_amount;
}
# endif
}
#endif
#ifdef use_unix_setitimer_sleep
static void on_alarm (sig)
jr_int sig;
{
}
void jr_sleep (sleep_sec, sleep_usec)
jr_int sleep_sec;
jr_int sleep_usec;
{
struct sigaction new_action[1];
struct sigaction old_action[1];
struct itimerval new_timer_value[1];
struct itimerval old_timer_value[1];
/*
* Turn off any timers before setting a new alarm handler
*/
memset (new_timer_value, 0, sizeof (*new_timer_value));
setitimer (ITIMER_REAL, new_timer_value, old_timer_value);
new_action->sa_handler = on_alarm;
sigemptyset (&new_action->sa_mask);
new_action->sa_flags = SA_RESTART;
sigaction (SIGALRM, new_action, old_action) ;
/*
* We need to set a handler for SIGALRM, since according
* to POSIX, only a signal that executes a signal handling
* function causes pause() to awake.
*/
new_timer_value->it_value.tv_sec = sleep_sec;
new_timer_value->it_value.tv_usec = sleep_usec;
setitimer (ITIMER_REAL, new_timer_value, 0);
pause ();
memset (new_timer_value, 0, sizeof (*new_timer_value));
setitimer (ITIMER_REAL, new_timer_value, 0);
sigaction (SIGALRM, old_action, 0);
setitimer (ITIMER_REAL, old_timer_value, 0);
}
#endif
|
frankjas/libjr
|
libjr/misc/trace.c
|
<filename>libjr/misc/trace.c
#define is_libjr_build
#include "ezport.h"
#include <stdio.h>
#include <string.h>
#include "jr/trace.h"
#include "jr/malloc.h"
#include "jr/misc.h"
void jr_check_trace(trace_num, file_name, line_number)
jr_int trace_num;
const char * file_name ;
jr_int line_number;
{
/*
** 3/2/07: Can't do a malloc(), since called from inside jr_MallocDiag() code
*/
if (trace_num >= jr_malloc_calls_TRACE && trace_num <= jr_malloc_stats_TRACE) {
if (jr_malloc_num_unrecorded_calls () > 0) {
fprintf(stderr,
"\n==== %s:%d: jr_set_trace(jr_malloc...): jr_malloc() has already been called ====\n",
file_name, line_number
) ;
fprintf(stderr,
"==== %s:%d: jr_set_trace(jr_malloc...): expect jr_malloc errors and/or abort() ====\n",
file_name, line_number
) ;
/*
* can't coredump, because in some apps the traces are set via a UI
* which may not be set before jr_mallocs have been done
*/
}
}
}
jr_int jr_trace_bit (jr_int trace_value)
{
jr_int q;
for (q=0; trace_value > 0; q++) {
trace_value >>= 1;
}
return q;
}
|
frankjas/libjr
|
libjr/missing/noinfo.c
|
<filename>libjr/missing/noinfo.c
#include "ezport.h"
#include <stdlib.h>
/*
** 4-15-2011: Fix the C++ problem wrt linking debug builds
** against no-debug libraries. The no-debug libraries call
** _invalid_parameter_noinfo(), but that isn't provided
** when linking agains the debug standard libraries.
**
** The following define may help
** #define _SCL_SECURE 0
**
** Can set a custom handler with: _set_invalid_parameter_handler()?
*/
#ifdef missing_invalid_parameter_noinfo
jr_EXTERN(void) __cdecl _invalid_parameter_noinfo(void)
{
abort();
}
#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/htable.h
|
<reponame>frankjas/libjr
#ifndef _htableh
#define _htableh
#include "ezport.h"
#include <stdio.h>
#include <stdarg.h>
#include "jr/alist.h"
typedef struct {
jr_int hash_value; /* makes rehashing easier */
jr_int next_index; /* next entry element */
} jr_HTableElementStruct;
typedef struct {
jr_int element_size;
jr_int (*hashfn) PROTO ((const void *));
jr_int (*cmpfn) PROTO ((const void *, const void *, ...));
/* -1, 0, 1, like strcmp */
void * cmp_arg;
jr_int * buckets_array;
jr_int num_buckets; /* number of hash buckets */
jr_AList entry_array[1];
jr_int delete_list; /* for deleted entries */
jr_int num_deletes;
} jr_HTable;
extern jr_HTable * jr_HTableCreate PROTO ((
jr_int key_size,
jr_int (*hashfn) (const void *),
jr_int (*cmpfn) (const void *, const void *)
));
extern void jr_HTableInit PROTO ((
jr_HTable * htable,
jr_int key_size,
jr_int (*hashfn) (const void *),
jr_int (*cmpfn) (const void *, const void *)
));
extern void jr_HTableDestroy PROTO ((jr_HTable *htable));
extern void jr_HTableUndo PROTO ((jr_HTable *htable));
extern void jr_HTableEmpty PROTO ((jr_HTable *htable));
extern void jr_HTableIncreaseCapacity PROTO ((
jr_HTable * htable,
jr_int new_capacity
));
extern void jr_HTableSetPrefixSize PROTO ((
jr_HTable * htable,
jr_int prefix_size,
void (*prefix_transform_fn) (),
void * prefix_transform_arg
));
extern void jr_HTableSetContainers PROTO ((
jr_HTable * htable,
...
));
extern void jr_HTableSetContainersFromVA_List PROTO ((
jr_HTable * htable,
va_list arg_list
));
extern jr_int jr_HTableFindIndexGeneric PROTO ((
jr_HTable * htable,
const void * key_ptr,
jr_int is_ptr_value
));
extern jr_int jr_HTableNewIndexGeneric PROTO ((
jr_HTable * htable,
const void * key_ptr,
jr_int is_ptr_value
));
extern void jr_HTableDeleteIndex PROTO ((
jr_HTable * htable,
jr_int index
));
#define jr_HTableFindElementIndex(htable, ptr_value) \
jr_HTableFindIndexGeneric (htable, ptr_value, 0)
#define jr_HTableNewElementIndex(htable, ptr_value) \
jr_HTableNewIndexGeneric (htable, ptr_value, 0)
#define jr_HTableFindPtrValueIndex(htable, ptr_value) \
jr_HTableFindIndexGeneric (htable, ptr_value, 1)
extern void jr_HTableHashDist PROTO ((
jr_HTable * htable,
FILE * fp,
char * s
));
#define jr_HTableElementSize(htable) \
((htable)->element_size)
#define jr_HTableSize(htable) \
(jr_AListSize ((htable)->entry_array) - (htable)->num_deletes)
#define jr_HTableIsEmpty(htable) \
(jr_HTableSize (htable) == 0)
#define jr_HTableNumBytes(htable) \
jr_AListNumBytes ((htable)->entry_array)
#define jr_HTablePrefixSize(htable) \
jr_AListPrefixSize ((htable)->entry_array)
#define jr_HTableAllocatesElements(htable) \
jr_AListAllocatesElements ((htable)->entry_array)
#define jr_HTableSetCmpFnArg(htable, v) \
((htable)->cmp_arg = (v))
#define jr_HTableForEachElementIndexWithPrefix(htable, i, prefix_size) \
jr_AListForEachElementIndex ((htable)->entry_array, i) \
if (jr_HTableHashValueWithPrefix(htable, i, prefix_size) != -1)
#define jr_HTableForEachElementPtrWithPrefix(htable, el_ptr, prefix_size) \
jr_AListForEachElementPtrWithPrefix ( \
(htable)->entry_array, el_ptr, prefix_size \
) if (((jr_HTableElementStruct *) \
((char *) (el_ptr) - (prefix_size)) \
)->hash_value != -1)
/******** Element Macros ********/
#define jr_HTableElementInfoPtrWithPrefix(htable, i, prefix_size) \
((jr_HTableElementStruct *) \
jr_AListElementPtrWithPrefix ((htable)->entry_array, i, 0) \
)
/*
* The above has to use 0, since the jr_HTableElementStruct is in the prefix.
*/
#define jr_HTableElementPtrWithPrefix(htable, i, prefix_size) \
((void *) (jr_AListElementPtrWithPrefix ((htable)->entry_array, i, prefix_size)))
#define jr_HTableElementIndexWithPrefix(htable, ptr, prefix_size) \
jr_AListElementIndexWithPrefix ((htable)->entry_array, ptr, prefix_size)
#define jr_HTableHashValueWithPrefix(htable, i, prefix_size) \
(jr_HTableElementInfoPtrWithPrefix (htable, i, prefix_size)->hash_value)
#define jr_HTableNextElementIndexWithPrefix(htable, i, prefix_size) \
(jr_HTableElementInfoPtrWithPrefix (htable, i, prefix_size)->next_index)
#define jr_HTableIsValidIndexWithPrefix(htable, i, prefix_size) \
( jr_AListIsValidIndex ((htable)->entry_array, i) \
&& jr_HTableHashValueWithPrefix (htable, i, prefix_size) != -1 \
)
#define jr_HTableIsDeletedIndexWithPrefix(htable, i, prefix_size) \
(jr_HTableHashValueWithPrefix (htable, i, prefix_size) == -1)
/******** Convenience Functions ********/
#define jr_HTableInitForPtrValues(htable, hashfn, cmpfn) \
jr_HTableInit (htable, 2 * sizeof (void *), hashfn, cmpfn)
#define jr_HTableCreateForPtrValues(hashfn, cmpfn) \
jr_HTableCreate (2 * sizeof (void *), hashfn, cmpfn)
extern void * jr_HTableFindPtrGeneric PROTO ((
jr_HTable * htable,
const void * key_ptr,
jr_int is_ptr_value
));
extern void * jr_HTableNewPtrGeneric PROTO ((
jr_HTable * htable,
const void * key_ptr,
jr_int is_ptr_value
));
extern void * jr_HTableDeleteElement PROTO ((
jr_HTable * htable,
void * el_ptr
));
extern void * jr_HTableDeletePtrValue PROTO ((
jr_HTable * htable,
void * el_ptr
));
#define jr_HTableFindElementPtr(htable, ptr_value) \
jr_HTableFindPtrGeneric (htable, ptr_value, 0)
#define jr_HTableNewElementPtr(htable, ptr_value) \
jr_HTableNewPtrGeneric (htable, ptr_value, 0)
extern void * jr_HTableSetNewElement PROTO ((
jr_HTable * htable,
const void * key_ptr
));
extern jr_int jr_HTableSetNewElementIndex PROTO ((
jr_HTable * htable,
const void * key_ptr
));
#define jr_HTableFindPtrValue(htable, ptr_value) \
jr_HTableFindPtrGeneric (htable, ptr_value, 1)
#define jr_HTableNewPtrValueIndex(htable, ptr_value) \
jr_HTableNewIndexGeneric (htable, ptr_value, 1)
#define jr_HTableNewPtrValue(htable, ptr_value) \
jr_HTableNewPtrGeneric (htable, ptr_value, 1)
#define jr_HTableForEachElementIndex(htable, index) \
jr_HTableForEachElementIndexWithPrefix ( \
htable, index, jr_HTablePrefixSize (htable) \
)
#define jr_HTableForEachElementPtr(htable, key_ptr) \
jr_HTableForEachElementPtrWithPrefix ( \
htable, key_ptr, jr_HTablePrefixSize (htable) \
)
#define jr_HTableNativeElementWithPrefix(htable, i, type, prefix_size) \
(*(type *) jr_HTableElementPtrWithPrefix (htable, i, prefix_size))
#define jr_HTableSetNativeElementWithPrefix(htable, i, v, type, prefix_size) \
(*(type *) jr_HTableElementPtrWithPrefix (htable, i, prefix_size) = (v))
#define jr_HTableElementPtr(htable, i) \
jr_HTableElementPtrWithPrefix(htable, i, jr_HTablePrefixSize (htable))
#define jr_HTableElementIndex(htable, ptr) \
jr_HTableElementIndexWithPrefix(htable, ptr, jr_HTablePrefixSize (htable))
#define jr_HTableHashValue(htable, i) \
jr_HTableHashValueWithPrefix(htable, i, jr_HTablePrefixSize (htable))
#define jr_HTableNextElementIndex(htable, i) \
jr_HTableNextElementIndexWithPrefix(htable, i, jr_HTablePrefixSize (htable))
#define jr_HTableIsValidIndex(htable, i) \
jr_HTableIsValidIndexWithPrefix(htable, i, jr_HTablePrefixSize (htable))
#define jr_HTableIsDeletedIndex(htable, i) \
jr_HTableIsDeletedIndexWithPrefix(htable, i, jr_HTablePrefixSize (htable))
#define jr_HTableNativeElement(htable, i, type) \
jr_HTableNativeElementWithPrefix (htable, i, type, jr_HTablePrefixSize (htable))
#define jr_HTableSetNativeElement(htable, i, v, type) \
jr_HTableSetNativeElementWithPrefix ( \
htable, i, v, type, jr_HTablePrefixSize (htable) \
)
/******** Ptr Value Interface ********/
#define jr_HTableKeyPtrValueWithPrefix(htable, i, prefix_size) \
jr_HTableNativeElementWithPrefix (htable, i, void *, prefix_size)
#define jr_HTableSetKeyPtrValueWithPrefix(htable, i, v, prefix_size) \
jr_HTableSetNativeElementWithPrefix (htable, i, v, void *, prefix_size)
#define jr_HTableDataPtrValueFromElementPtr(htable, element_ptr) \
(((void **) (element_ptr))[1])
#define jr_HTableDataPtrValueWithPrefix(htable, i, prefix_size) \
jr_HTableDataPtrValueFromElementPtr ( \
htable, jr_HTableElementPtrWithPrefix (htable, i, prefix_size) \
)
#define jr_HTableSetDataPtrValueWithPrefix(htable, i, v, prefix_size) \
(jr_HTableDataPtrValueWithPrefix (htable, i, prefix_size) = (v))
#define jr_HTableKeyPtrValue(htable, i) \
jr_HTableKeyPtrValueWithPrefix (htable, i, jr_HTablePrefixSize (htable))
#define jr_HTableSetKeyPtrValue(htable, i, v) \
jr_HTableSetKeyPtrValueWithPrefix (htable, i, v, jr_HTablePrefixSize (htable))
#define jr_HTableDataPtrValue(htable, i) \
jr_HTableDataPtrValueWithPrefix (htable, i, jr_HTablePrefixSize (htable))
#define jr_HTableSetDataPtrValue(htable, i, v) \
jr_HTableSetDataPtrValueWithPrefix (htable, i, v, jr_HTablePrefixSize (htable))
#endif
|
frankjas/libjr
|
include/jr/ptrmap.h
|
<gh_stars>0
#ifndef __jr_ptrmap_h___
#define __jr_ptrmap_h___
#include "ezport.h"
#include "jr/alist.h"
typedef struct {
jr_AList category_list[1];
jr_int max_category_size;
jr_int ptr_data_size;
} jr_PtrMapType;
typedef struct {
jr_int min_value;
jr_int num_values;
jr_int next_deleted_desc;
jr_int num_deletes;
jr_AList ptr_list[1];
} jr_PtrCategoryType;
extern void jr_PtrMapInit PROTO ((
jr_PtrMapType * ptr_map,
jr_int max_category_size,
jr_int ptr_data_size
));
extern void jr_PtrMapUndo PROTO ((
jr_PtrMapType * ptr_map
));
extern jr_PtrMapType * jr_PtrMapCreate PROTO ((
jr_int max_category_size,
jr_int ptr_data_size
));
extern void jr_PtrMapDestroy PROTO ((
jr_PtrMapType * ptr_map
));
extern jr_int jr_PtrMapAddNewPtrWithFileName PROTO ((
jr_PtrMapType * ptr_map,
jr_int category_kind,
void * ptr_value,
const char * file_name,
jr_int line_number
));
#define jr_PtrMapAddNewPtr(ptr_map, category_kind, ptr_value) \
jr_PtrMapAddNewPtrWithFileName ( \
ptr_map, category_kind, ptr_value, 0, 0 \
)
#define jr_PtrMapCloseDesc(ptr_map, category_kind, ptr_desc) \
jr_PtrCategoryCloseDesc ( \
jr_PtrMapCategoryPtr (ptr_map, category_kind), ptr_desc \
)
#define jr_PtrMapGetPtr(ptr_map, category_kind, ptr_desc) \
jr_PtrCategoryGetPtr ( \
jr_PtrMapCategoryPtr (ptr_map, category_kind), ptr_desc \
)
#define jr_PtrMapSetPtr(ptr_map, category_kind, ptr_desc, v) \
jr_PtrCategorySetPtr ( \
jr_PtrMapCategoryPtr (ptr_map, category_kind), ptr_desc, v \
)
#define jr_PtrMapGetFileName(ptr_map, category_kind, ptr_desc) \
jr_PtrCategoryGetFileName ( \
jr_PtrMapCategoryPtr (ptr_map, category_kind), ptr_desc \
)
#define jr_PtrMapGetLineNumber(ptr_map, category_kind, ptr_desc) \
jr_PtrCategoryGetLineNumber ( \
jr_PtrMapCategoryPtr (ptr_map, category_kind), ptr_desc \
)
#define jr_PtrMapGetDataPtr(ptr_map, category_kind, ptr_desc) \
jr_PtrCategoryGetDataPtr ( \
jr_PtrMapCategoryPtr (ptr_map, category_kind), ptr_desc \
)
#define jr_PtrMapDataPtr(ptr_map, category_kind, ptr_desc) \
jr_PtrCategoryDataPtr ( \
jr_PtrMapCategoryPtr (ptr_map, category_kind), ptr_desc \
)
#define jr_PtrMapIsValidDesc(ptr_map, category_kind, ptr_desc) \
( jr_PtrMapIsValidCategory (ptr_map, category_kind) \
&& jr_PtrCategoryIsValidDesc ( \
jr_PtrMapCategoryPtr (ptr_map, category_kind), \
ptr_desc \
) \
)
extern void jr_PtrCategoryCloseDesc PROTO ((
jr_PtrCategoryType * ptr_category,
jr_int ptr_desc
));
extern void * jr_PtrCategoryGetPtr PROTO ((
jr_PtrCategoryType * ptr_category,
jr_int ptr_desc
));
extern void jr_PtrCategorySetPtr PROTO ((
jr_PtrCategoryType * ptr_category,
jr_int ptr_desc,
void * ptr_value
));
extern const char * jr_PtrCategoryGetFileName PROTO ((
jr_PtrCategoryType * ptr_category,
jr_int ptr_desc
));
extern jr_int jr_PtrCategoryGetLineNumber PROTO ((
jr_PtrCategoryType * ptr_category,
jr_int ptr_desc
));
extern void * jr_PtrCategoryGetDataPtr PROTO ((
jr_PtrCategoryType * ptr_category,
jr_int ptr_desc
));
#define jr_PtrMapMaxOpenPtrs(ptr_map) \
((ptr_map)->max_category_size)
#define jr_PtrMapForEachCategoryKind(ptr_map, category_kind) \
jr_AListForEachElementIndex ((ptr_map)->category_list, category_kind)
#define jr_PtrMapCategoryNumOpenPtrs(ptr_map, category_kind) \
jr_PtrCategoryNumOpenPtrs (jr_PtrMapCategoryPtr (ptr_map, category_kind))
#define jr_PtrMapIsValidCategory(ptr_map, i) \
jr_AListIsValidIndex ((ptr_map)->category_list, i)
#define jr_PtrMapCategoryPtr(ptr_map, i) \
((jr_PtrCategoryType *) jr_AListElementPtr ((ptr_map)->category_list, i))
#define jr_PtrCategoryIsValidDesc(ptr_category, ptr_desc) \
(jr_AListIsValidIndex ( \
(ptr_category)->ptr_list, (ptr_desc) - (ptr_category)->min_value \
) && jr_PtrCategoryPtrValue (ptr_category, ptr_desc) != 0)
#define jr_PtrCategoryNumOpenPtrs(ptr_category) \
(jr_AListSize ((ptr_category)->ptr_list) - (ptr_category)->num_deletes)
#define jr_PtrCategoryMinValue(ptr_category) \
((ptr_category)->min_value)
#define jr_PtrCategoryMaxValue(ptr_category) \
((ptr_category)->min_value + jr_AListSize ((ptr_category)->ptr_list))
#define jr_PtrCategoryForEachOpenDesc(ptr_category, ptr_desc) \
for ((ptr_desc) = jr_PtrCategoryMinValue (ptr_category); \
(ptr_desc) < jr_PtrCategoryMaxValue (ptr_category); \
(ptr_desc)++) \
if (jr_PtrCategoryPtrValue (ptr_category, ptr_desc))
typedef struct {
void * ptr_value;
jr_int next_deleted_desc;
const char * file_name;
jr_int line_number;
} jr_PtrInfoStruct;
#define jr_PtrCategoryPtrInfo(ptr_category, ptr_desc) \
((jr_PtrInfoStruct *) jr_AListElementPtr ( \
(ptr_category)->ptr_list, (ptr_desc) - (ptr_category)->min_value) \
)
#define jr_PtrCategoryPtrValue(ptr_category, ptr_desc) \
(jr_PtrCategoryPtrInfo (ptr_category, ptr_desc)->ptr_value)
#define jr_PtrCategoryFileName(ptr_category, ptr_desc) \
(jr_PtrCategoryPtrInfo (ptr_category, ptr_desc)->file_name)
#define jr_PtrCategoryLineNumber(ptr_category, ptr_desc) \
(jr_PtrCategoryPtrInfo (ptr_category, ptr_desc)->line_number)
#define jr_PtrCategoryDataPtr(ptr_category, ptr_desc) \
(((jr_PtrInfoStruct *) jr_AListElementPtr ( \
(ptr_category)->ptr_list, (ptr_desc) - (ptr_category)->min_value) \
) + 1)
#define jr_PtrCategoryDataPtrSize(ptr_category) \
(jr_AListElementSize ((ptr_category)->ptr_list) - sizeof (jr_PtrInfoStruct))
#endif
|
frankjas/libjr
|
libjr/misc/exceptn.c
|
<reponame>frankjas/libjr
#include "exn_proj.h"
jr_HTable jr_ExceptionTable [1];
static jr_int DidInit = 0;
jr_int jr_ExceptionRaiseWithCoreDump (exception_name, core_dump, opt_error_buf)
char * exception_name;
jr_int core_dump;
char * opt_error_buf;
{
jr_ExceptionStack * exception_stack;
jr_ExceptionType * exception_ptr;
jr_int index;
if (jr_ExceptionBreakPoint (0) != 0) {
/*
* this function servers only as a place to
* set a break point in the debugger. Its
* should be compiled with the debugger
* option on
*/
return (-1);
}
if (!DidInit) {
jr_HTableInitForPtrValues (
jr_ExceptionTable, jr_strhash_pjw,
(int (*) (const void *, const void *)) strcmp
);
DidInit = 1;
}
index = jr_HTableFindPtrValueIndex (jr_ExceptionTable, exception_name);
if (index == -1) {
return (-1);
}
exception_stack = jr_HTableDataPtrValue (jr_ExceptionTable, index);
if (core_dump && exception_stack->core_dump) {
jr_coredump ();
}
if (jr_AListSize (exception_stack->jmp_buf_list) < 1) return (-1);
exception_ptr = jr_AListNativeTail (exception_stack->jmp_buf_list, jr_ExceptionType *);
if (core_dump && exception_ptr->core_dump) {
jr_coredump ();
}
if (opt_error_buf) {
strcpy (exception_ptr->error_buf, opt_error_buf);
}
else {
strcpy (exception_ptr->error_buf, "<no msg>");
}
siglongjmp (exception_ptr->jump_buffer, -1);
}
jr_ExceptionType *jr_ExceptionGetPtrFromVector (exception_vector, error_buf)
char ** exception_vector;
char * error_buf;
{
jr_ExceptionStack * exception_stack;
jr_ExceptionType * exception_ptr;
char * exception_name;
jr_int vector_length;
jr_int i, index;
if (!DidInit) {
jr_HTableInitForPtrValues (
jr_ExceptionTable, jr_strhash_pjw,
(int (*) (const void *, const void *)) strcmp
);
DidInit = 1;
}
exception_ptr = jr_ExceptionCreate (error_buf);
vector_length = jr_VectorLength (exception_vector);
for (i = 0; i < vector_length; i++) {
exception_name = exception_vector [i];
index = jr_HTableFindPtrValueIndex (jr_ExceptionTable, exception_name);
if (index == -1) {
char * new_str;
new_str = jr_strdup (exception_name);
index = jr_HTableNewPtrValueIndex (jr_ExceptionTable, new_str);
exception_stack = jr_ExceptionStackCreate ();
jr_HTableSetDataPtrValue (jr_ExceptionTable, index, exception_stack);
}
exception_stack = jr_HTableDataPtrValue (jr_ExceptionTable, index);
jr_ExceptionStackPush (exception_stack, exception_ptr);
}
return (exception_ptr);
}
void jr_ExceptionUnCatchVector (exception_vector)
char ** exception_vector;
{
jr_ExceptionStack * exception_stack;
char * exception_name;
jr_int vector_length;
jr_int i, index;
if (!DidInit) {
jr_HTableInitForPtrValues (
jr_ExceptionTable, jr_strhash_pjw,
(int (*) (const void *, const void *)) strcmp
);
DidInit = 1;
}
vector_length = jr_VectorLength (exception_vector);
for (i = 0; i < vector_length; i++) {
exception_name = exception_vector [i];
index = jr_HTableFindPtrValueIndex (jr_ExceptionTable, exception_name);
if (index == -1) {
return;
}
exception_stack = jr_HTableDataPtrValue (jr_ExceptionTable, index);
exception_stack = jr_ExceptionStackPop (exception_stack);
if (exception_stack) {
jr_ExceptionStackDestroy (exception_stack);
exception_name = jr_HTableKeyPtrValue (jr_ExceptionTable, index);
jr_HTableDeleteIndex (jr_ExceptionTable, index);
jr_free (exception_name);
if (jr_HTableSize (jr_ExceptionTable) == 0) {
jr_HTableUndo (jr_ExceptionTable);
DidInit = 0;
}
}
}
}
jr_ExceptionType *jr_ExceptionGetPtr (exception_name, error_buf)
char * exception_name;
char * error_buf;
{
jr_ExceptionType * exception_ptr;
char * exception_vector[2];
exception_vector[0] = exception_name;
exception_vector[1] = 0;
exception_ptr = jr_ExceptionGetPtrFromVector (exception_vector, error_buf);
return (exception_ptr);
}
void jr_ExceptionUnCatch (exception_name)
char * exception_name;
{
char * exception_vector[2];
exception_vector[0] = exception_name;
exception_vector[1] = 0;
jr_ExceptionUnCatchVector (exception_vector);
}
void jr_ExceptionSetCoreDumpOnRaise (exception_name, value)
char * exception_name;
jr_int value;
{
jr_ExceptionStack * exception_stack;
jr_int index;
if (!DidInit) {
jr_HTableInitForPtrValues (
jr_ExceptionTable, jr_strhash_pjw,
(int (*) (const void *, const void *)) strcmp
);
DidInit = 1;
}
index = jr_HTableFindPtrValueIndex (jr_ExceptionTable, exception_name);
if (index == -1) {
return;
}
exception_stack = jr_HTableDataPtrValue (jr_ExceptionTable, index);
exception_stack->core_dump = value;
}
jr_ExceptionType *jr_ExceptionCreate (error_buf)
char * error_buf;
{
jr_ExceptionType * exception_ptr;
exception_ptr = jr_malloc (sizeof (jr_ExceptionType));
memset (exception_ptr, 0, sizeof (jr_ExceptionType));
exception_ptr->error_buf = error_buf;
return (exception_ptr);
}
void jr_ExceptionDestroy (exception_ptr)
jr_ExceptionType * exception_ptr;
{
jr_free (exception_ptr);
}
jr_ExceptionStack * jr_ExceptionStackCreate ()
{
jr_ExceptionStack * exception_stack;
exception_stack = jr_malloc (sizeof (jr_ExceptionStack));
jr_ExceptionStackInit (exception_stack);
return (exception_stack);
}
void jr_ExceptionStackInit (exception_stack)
jr_ExceptionStack * exception_stack;
{
memset ((void *)exception_stack, 0, sizeof (*exception_stack));
jr_AListInit (exception_stack->jmp_buf_list, sizeof (jr_ExceptionType));
}
void jr_ExceptionStackDestroy (exception_stack)
jr_ExceptionStack * exception_stack;
{
jr_ExceptionStackUndo (exception_stack);
jr_free (exception_stack);
}
void jr_ExceptionStackUndo (exception_stack)
jr_ExceptionStack * exception_stack;
{
jr_AListUndo (exception_stack->jmp_buf_list);
}
jr_ExceptionType *jr_ExceptionStackPush (exception_stack, exception_ptr)
jr_ExceptionStack * exception_stack;
jr_ExceptionType * exception_ptr;
{
jr_AListNativeSetNewTail (
exception_stack->jmp_buf_list, exception_ptr, jr_ExceptionType *
);
exception_ptr->num_references++;
return (exception_ptr);
}
jr_ExceptionStack *jr_ExceptionStackPop (exception_stack)
jr_ExceptionStack * exception_stack;
{
jr_ExceptionType * exception_ptr;
if (jr_AListSize (exception_stack->jmp_buf_list) > 0) {
exception_ptr = jr_AListNativeTail (
exception_stack->jmp_buf_list, jr_ExceptionType *
);
jr_AListDeletedTailPtr (exception_stack->jmp_buf_list);
exception_ptr->num_references--;
if (exception_ptr->num_references == 0) {
jr_ExceptionDestroy (exception_ptr);
}
}
if (jr_AListSize (exception_stack->jmp_buf_list) == 0) {
return (exception_stack);
}
return (0);
}
|
frankjas/libjr
|
libjr/missing/getcwd.c
|
#define _POSIX_SOURCE 1
#include "ezport.h"
#ifdef missing_getcwd_objects
#include <stdio.h>
#include <sys/types.h>
#include <errno.h>
#include <string.h>
/* getcwd should be declared extern in unistd.h */
#include <unistd.h>
char * getcwd(dirname_buf_arg, buffer_length)
char * dirname_buf_arg ;
size_t buffer_length ;
{
char local_buffer[2048] ;
if ((dirname_buf_arg != 0) && (buffer_length == 0)) {
errno = EINVAL ;
return(0) ;
}
if (getwd(local_buffer) == 0) {
/* errno should be set by getwd */
strncpy(dirname_buf_arg, local_buffer, buffer_length-1) ;
dirname_buf_arg[buffer_length-1] = 0 ;
return(0) ;
}
else {
if (dirname_buf_arg == 0) {
buffer_length = strlen(local_buffer) + 1 ;
dirname_buf_arg = (char *) malloc(buffer_length) ;
if (dirname_buf_arg == 0) {
errno = EAGAIN ;
return(0) ;
}
}
if (strlen(local_buffer) > (buffer_length-1)) {
errno = ERANGE ;
return(0) ;
}
strcpy(dirname_buf_arg, local_buffer) ;
}
return(dirname_buf_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/io/logfile.c
|
#include "logfile.h"
jr_LogType *jr_LogCreate()
{
jr_LogType * log_info = jr_malloc (sizeof (jr_LogType));
jr_LogInit( log_info);
return log_info;
}
void jr_LogInit(
jr_LogType * log_info)
{
memset (log_info, 0, sizeof (*log_info));
jr_file_init( log_info->file_info);
jr_AListInit (log_info->transaction_stack, sizeof (jr_LogTransInfoType));
}
jr_int jr_LogOpen(
jr_LogType * log_info,
const char * file_name,
const char * how_string,
jr_int block_size,
char * error_buf)
{
jr_int open_flags = jr_FILE_OPEN_BUFFERED | jr_FILE_OPEN_READ;
jr_int file_lock = 0;
jr_ULong file_size;
jr_ULong tmp_ulong;
jr_ULong start_time;
jr_int is_synced;
jr_int status;
switch (how_string[0]) {
default :
case 'r' : {
file_lock = jr_FILE_LOCK_READ;
break;
}
case 'w' : {
open_flags |= jr_FILE_OPEN_WRITING;
file_lock = jr_FILE_LOCK_WRITE;
break;
}
case 'a' : {
open_flags |= jr_FILE_OPEN_APPENDING;
file_lock = jr_FILE_LOCK_WRITE;
break;
}
}
status = jr_file_open (log_info->file_info, file_name, open_flags, jr_PERM_RWX_OWNER, error_buf);
if (status != 0) {
jr_esprintf (error_buf, "couldn't open file: %s", error_buf);
goto return_status;
}
status = jr_file_lock (log_info->file_info, file_lock, 0, error_buf);
if (status != 0) {
jr_esprintf (error_buf, "couldn't lock log file: %s", error_buf);
goto return_status;
}
jr_ULongAsgnUInt( &tmp_ulong, 0);
status = jr_file_seek( log_info->file_info, tmp_ulong, jr_FILE_SEEK_END, error_buf);
if (status != 0) {
jr_esprintf (error_buf, "couldn't seek: %s", error_buf);
goto return_status;
}
status = jr_file_get_offset( log_info->file_info, &file_size, error_buf);
if (status != 0) {
jr_esprintf (error_buf, "couldn't get offset: %s", error_buf);
goto return_status;
}
if (jr_ULongIsZero( file_size) && how_string[0] != 'r') {
jr_LogEntryType entry_info[1];
jr_LogHeaderStruct log_header [1];
if (block_size == 0) {
jr_esprintf (error_buf, "block size can't be zero");
status = jr_MISUSE_ERROR;
goto return_status;
}
is_synced = 1;
jr_ULongAsgnUInt( &start_time, jr_time_seconds());
jr_NetIntAsgnInt (&log_header->magic_number, jr_LOG_MAGIC_NUMBER);
jr_NetIntAsgnInt (&log_header->is_synced, is_synced);
jr_NetIntAsgnInt (&log_header->block_size, block_size);
jr_LogEntryInit (
entry_info, jr_LOG_HEADER_ENTRY, 0, 1, start_time, 0
);
jr_LogEntrySetPtrValue (entry_info, 0, log_header, sizeof (log_header));
status = jr_LogEntryAddToFilePtr (entry_info, log_info->file_info, block_size, error_buf);
jr_LogEntryUndo (entry_info);
if (status != 0) {
jr_esprintf (error_buf, "couldn't add log header: %s", error_buf);
goto return_status;
}
}
else {
jr_LogEntryType entry_info[1];
const jr_LogHeaderStruct * log_header;
jr_int seek_whence;
jr_ULongAsgnUInt( &tmp_ulong, 0);
status = jr_file_seek( log_info->file_info, tmp_ulong, jr_FILE_SEEK_SET, error_buf);
if (status != 0) {
jr_esprintf (error_buf, "couldn't seek: %s", error_buf);
goto return_status;
}
if (block_size == 0) {
jr_esprintf (error_buf, "block size can't be zero");
status = jr_MISUSE_ERROR;
goto return_status;
}
if (block_size && block_size < jr_LogHeaderEntryLength ()) {
jr_esprintf (error_buf, "block size %d < minimum of %d",
block_size, jr_LogHeaderEntryLength ()
);
status = jr_MISUSE_ERROR;
goto return_status;
}
status = jr_LogEntryInitFromFilePtr (
entry_info, log_info->file_info, block_size, error_buf
);
if (status != 0) {
jr_esprintf (error_buf, "couldn't read log header: %s", error_buf);
goto return_status;
}
log_header = jr_LogEntryPtrValue (entry_info, 0);
if (jr_NetIntToHost (log_header->magic_number) != jr_LOG_MAGIC_NUMBER) {
jr_esprintf (error_buf, "bad magic number");
jr_LogEntryUndo (entry_info);
status = jr_INTERNAL_ERROR;
goto return_status;
}
if (block_size != jr_NetIntToHost (log_header->block_size)) {
jr_esprintf (error_buf, "desired block size %d != current block size %d",
block_size, jr_NetIntToHost (log_header->block_size)
);
jr_LogEntryUndo (entry_info);
status = jr_INTERNAL_ERROR;
goto return_status;
}
block_size = jr_NetIntToHost( log_header->block_size);
is_synced = jr_NetIntToHost( log_header->is_synced);
jr_LogEntryGetTime( entry_info, &start_time);
jr_LogEntryUndo (entry_info);
if (how_string[0] == 'a') {
seek_whence = jr_FILE_SEEK_END;
}
else {
seek_whence = jr_FILE_SEEK_CUR;
/*
* so that we may do fwrite()s after the fread() above
*/
}
jr_ULongAsgnUInt( &tmp_ulong, 0);
status = jr_file_seek( log_info->file_info, tmp_ulong, seek_whence, error_buf);
if (status != 0) {
jr_esprintf (error_buf, "couldn't seek: %s", error_buf);
goto return_status;
}
}
log_info->block_size = block_size;
jr_ULongAsgn( &log_info->start_time, start_time);
log_info->file_name = jr_strdup (file_name);
log_info->opened_how = how_string[0];
log_info->is_file_synced = is_synced;
jr_ULongAsgn( &log_info->truncate_offset, file_size);
log_info->in_transaction = 0;
jr_AListInit (log_info->transaction_stack, sizeof (jr_LogTransInfoType));
return 0;
return_status : {
return status;
}
}
void jr_LogDestroy (log_info)
jr_LogType * log_info;
{
jr_LogUndo (log_info);
jr_free (log_info);
}
void jr_LogUndo (log_info)
jr_LogType * log_info;
{
jr_LogTransInfoType * trans_info;
jr_file_undo( log_info->file_info);
if (log_info->file_name) {
jr_free (log_info->file_name);
}
jr_AListForEachElementPtr (log_info->transaction_stack, trans_info) {
jr_LogTransInfoUndo (trans_info);
}
jr_AListUndo (log_info->transaction_stack);
}
void jr_LogEntryInit (
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)
{
entry_info->type_number = type_number;
entry_info->num_int_values = num_int_values;
entry_info->num_ptr_values = num_ptr_values;
jr_ULongAsgn( &entry_info->entry_time, entry_time);
entry_info->requires_sync = requires_sync;
entry_info->has_malloced_ptrs = 0;
}
void jr_LogEntryUndo (entry_info)
jr_LogEntryType * entry_info;
{
jr_int i;
if (entry_info->has_malloced_ptrs) {
for (i=0; i < entry_info->num_ptr_values; i++) {
jr_free (entry_info->ptr_values[i]);
}
}
}
void jr_LogEntrySetPtrValue (entry_info, index, ptr_value, data_length)
jr_LogEntryType * entry_info;
jr_int index;
const void * ptr_value;
jr_int data_length;
{
entry_info->ptr_values[index] = ptr_value;
jr_NetIntAsgnInt (entry_info->data_lengths + index, data_length);
}
jr_int jr_LogEntrySavedLength (entry_info)
jr_LogEntryType * entry_info;
{
jr_int total_entry_length;
jr_int var_data_length;
jr_int i;
for (var_data_length = 0, i = 0; i < entry_info->num_ptr_values; i++) {
var_data_length += jr_NetIntToHost (entry_info->data_lengths [i]);
}
total_entry_length = 0;
total_entry_length += sizeof (jr_LogEntryHeaderStruct);
total_entry_length += entry_info->num_int_values * sizeof (jr_NetInt);
total_entry_length += entry_info->num_ptr_values * sizeof (jr_NetInt); /* for data lengths */
total_entry_length += var_data_length;
return total_entry_length;
}
jr_int jr_LogHeaderEntryLength ()
{
jr_LogEntryType entry_info[1];
jr_LogHeaderStruct log_header [1];
jr_ULong tmp_ulong;
jr_ULongAsgnUInt( &tmp_ulong, 0);
jr_LogEntryInit (
entry_info, jr_LOG_HEADER_ENTRY, 0, 1, tmp_ulong, 0
);
jr_LogEntrySetPtrValue (entry_info, 0, log_header, sizeof (log_header));
return jr_LogEntrySavedLength (entry_info);
}
void jr_LogEntryHeaderInit(
jr_LogEntryHeaderStruct * entry_header,
jr_int type_number,
jr_int num_int_values,
jr_int num_ptr_values,
jr_ULong entry_time)
{
jr_NetIntAsgnInt (&entry_header->magic_number, jr_LOG_MAGIC_NUMBER);
jr_NetShortAsgnShort (&entry_header->type_number, type_number);
jr_NetCharAsgnInt (&entry_header->num_int_values, num_int_values);
jr_NetCharAsgnInt (&entry_header->num_ptr_values, num_ptr_values);
jr_NetULongAsgnULong (&entry_header->entry_time, entry_time);
}
jr_int jr_LogAddEntry (log_info, entry_info, opt_error_buf)
jr_LogType * log_info;
jr_LogEntryType * entry_info;
char * opt_error_buf;
{
jr_int status;
/*
* can't fseek() to the end each time because fseek()
* calls fflush()
*/
if (jr_LogOpenedReadOnly (log_info)) {
jr_esprintf (opt_error_buf, "not opened for writing");
return -1;
}
if (jr_LogFileIsSynced (log_info)) {
status = jr_LogSetFileSyncBit (log_info, 0, opt_error_buf);
if (status != 0) {
jr_esprintf (opt_error_buf, "couldn't clear synced bit: %s", opt_error_buf);
return -1;
}
}
if (log_info->is_executing) {
jr_esprintf (opt_error_buf, "can't add entries while log is executing");
return -1;
}
status = jr_LogEntryAddToFilePtr(
entry_info, log_info->file_info, log_info->block_size, opt_error_buf
);
if (status != 0) {
return -1;
}
if (entry_info->requires_sync) {
if (jr_LogIsInTransaction (log_info)) {
jr_LogTransInfoType * trans_info;
trans_info = jr_AListTailPtr (log_info->transaction_stack);
jr_LogTransInfoSetSyncBit (trans_info, 1);
}
else {
status = jr_file_flush( log_info->file_info, opt_error_buf);
if (status != 0) {
jr_esprintf (opt_error_buf, "couldn't sync entry: flush failed: %s", opt_error_buf);
return status;
}
status = jr_file_sync( log_info->file_info, opt_error_buf);
if (status != 0) {
jr_esprintf (opt_error_buf, "couldn't sync entry: %s", opt_error_buf);
return -1;
}
}
}
return 0;
}
jr_int jr_LogEntryAddToFilePtr(
jr_LogEntryType * entry_info,
jr_file_t * file_info,
jr_int block_size,
char * error_buf)
{
jr_int num_bytes;
jr_int w_bytes;
jr_int total_entry_length;
jr_LogEntryHeaderStruct entry_header[1];
jr_int i;
jr_int data_length;
jr_int status;
jr_LogEntryHeaderInit (entry_header,
entry_info->type_number,
entry_info->num_int_values,
entry_info->num_ptr_values,
entry_info->entry_time
);
total_entry_length = jr_LogEntrySavedLength (entry_info);
if (block_size) {
/*
* if the entry doesn't fit on the block, pad to the block boundary
*/
status = jr_AvoidLogBlockBoundary (file_info, block_size, total_entry_length, 0, error_buf);
if (status < 0) {
return -1;
}
}
num_bytes = 0;
w_bytes = sizeof( jr_LogEntryHeaderStruct);
status = jr_file_write( file_info, entry_header, w_bytes, error_buf);
if (status != w_bytes) {
if (status < 0) {
jr_esprintf( error_buf, "write error: %s", error_buf);
}
else {
jr_esprintf( error_buf, "only wrote %d of %d bytes", status, w_bytes);
status = jr_IO_ERROR;
}
return status;
}
num_bytes += status;
w_bytes = entry_info->num_int_values * sizeof (jr_NetInt);
status = jr_file_write( file_info, entry_info->int_values, w_bytes, error_buf);
if (status != w_bytes) {
if (status < 0) {
jr_esprintf( error_buf, "write error: %s", error_buf);
}
else {
jr_esprintf( error_buf, "only wrote %d of %d bytes", status, w_bytes);
status = jr_IO_ERROR;
}
return status;
}
num_bytes += status;
w_bytes = entry_info->num_ptr_values * sizeof (jr_NetInt);
status = jr_file_write( file_info, entry_info->data_lengths, w_bytes, error_buf);
if (status != w_bytes) {
if (status < 0) {
jr_esprintf( error_buf, "write error: %s", error_buf);
}
else {
jr_esprintf( error_buf, "only wrote %d of %d bytes", status, w_bytes);
status = jr_IO_ERROR;
}
return status;
}
num_bytes += status;
for (i=0; i < entry_info->num_ptr_values; i++) {
data_length = jr_NetIntToHost (entry_info->data_lengths[i]);
if (entry_info->ptr_values[i]) {
w_bytes = data_length;
status = jr_file_write( file_info, entry_info->ptr_values[i], w_bytes, error_buf);
if (status != w_bytes) {
if (status < 0) {
jr_esprintf( error_buf, "write error: %s", error_buf);
}
else {
jr_esprintf( error_buf, "only wrote %d of %d bytes", status, w_bytes);
status = jr_IO_ERROR;
}
return status;
}
}
else {
jr_ULong tmp_ulong;
jr_ULongAsgnUInt( &tmp_ulong, data_length);
status = jr_file_seek( file_info, tmp_ulong, jr_FILE_SEEK_CUR, error_buf);
if (status != 0) {
jr_esprintf (error_buf, "couldn't seek: %s", error_buf);
return status;
}
}
num_bytes += data_length;
}
if (num_bytes != total_entry_length) {
jr_esprintf (error_buf, "only wrote %d of %d bytes", num_bytes, total_entry_length);
return -1;
}
return 0;
}
jr_int jr_LogEntryInitFromFilePtr(
jr_LogEntryType * entry_info,
jr_file_t * file_info,
jr_int block_size,
char * opt_error_buf)
{
jr_LogEntryHeaderStruct entry_header [1];
jr_int r_bytes;
jr_ULong curr_offset;
jr_int i;
jr_ULong tmp_ulong;
jr_int read_size;
jr_int status;
while (1) {
/*
* skip to next block boundary if there isn't enough room
* for a whole entry
*/
status = jr_file_get_offset( file_info, &curr_offset, opt_error_buf);
if (status != 0) {
jr_esprintf (opt_error_buf, "couldn't get offset: %s", opt_error_buf);
return status;
}
if (block_size) {
jr_int space_in_block;
space_in_block = block_size - jr_ULongModUInt( curr_offset, block_size);
if (space_in_block < (jr_int) sizeof (jr_LogEntryHeaderStruct)) {
/*
** Using SEEK_CUR on an odd offset, incrementing by an odd value
** sometimes causes fseek() to return -1, errno is 0, under Next 3.3.
*/
jr_ULongAddUInt( &curr_offset, curr_offset, space_in_block);
status = jr_file_seek (file_info, curr_offset, jr_FILE_SEEK_SET, opt_error_buf);
if (status != 0) {
jr_esprintf (opt_error_buf, "couldn't seek: %s", opt_error_buf);
return status;
}
}
}
read_size = sizeof (jr_LogEntryHeaderStruct);
status = jr_file_read( file_info, entry_header, read_size, opt_error_buf);
if (status != read_size) {
if (status < 0) {
jr_esprintf (opt_error_buf, "error reading log entry: %s", opt_error_buf);
}
else if (status == 0) {
jr_esprintf (opt_error_buf, "end of file");
status = jr_EOF_ERROR;
}
else {
jr_esprintf (opt_error_buf, "read %d bytes of %d requested", status, read_size);
status = jr_IO_ERROR;
}
return status;
}
if (jr_NetShortToHost (entry_header->type_number) == jr_LOG_PAD_ENTRY) {
/*
* this is padding, time field tells how much padding, should put
* us at the next block boundary.
*/
jr_ULong tmp_ulong;
jr_ULong padding_size;
jr_ULongAsgnNetULong (&tmp_ulong, entry_header->entry_time);
jr_ULongSubtractUInt( &padding_size, tmp_ulong, sizeof(jr_LogEntryHeaderStruct));
status = jr_file_seek( file_info, padding_size, jr_FILE_SEEK_CUR, opt_error_buf);
if (status != 0) {
jr_esprintf (opt_error_buf, "couldn't seek: %s", opt_error_buf);
return status;
}
continue;
}
break;
}
if (jr_NetIntToHost (entry_header->magic_number) != jr_LOG_MAGIC_NUMBER) {
jr_esprintf (opt_error_buf, "bad magic number");
return jr_INTERNAL_ERROR;
}
jr_ULongAsgnNetULong (&tmp_ulong, entry_header->entry_time);
jr_LogEntryInit (
entry_info,
jr_NetShortToHost (entry_header->type_number),
(unsigned) jr_NetCharToHost (entry_header->num_int_values),
(unsigned) jr_NetCharToHost (entry_header->num_ptr_values),
tmp_ulong,
0 /* requires_sync */
);
jr_LogEntrySetOffset (entry_info, curr_offset);
r_bytes = entry_info->num_int_values * sizeof (jr_NetInt),
status = jr_file_read( file_info, entry_info->int_values, r_bytes, opt_error_buf);
if (status < r_bytes) {
if (status < 0) {
jr_esprintf (opt_error_buf, "error reading log entry: %s", opt_error_buf);
}
else if (status == 0) {
jr_esprintf (opt_error_buf, "premature end of file");
status = jr_INTERNAL_ERROR;
}
else {
jr_esprintf (opt_error_buf, "read %d bytes of %d requested", status, r_bytes);
status = jr_IO_ERROR;
}
return status;
}
r_bytes = entry_info->num_ptr_values * sizeof (jr_NetInt),
status = jr_file_read( file_info, entry_info->data_lengths, r_bytes, opt_error_buf);
if (status < r_bytes) {
if (status < 0) {
jr_esprintf (opt_error_buf, "error reading log entry: %s", opt_error_buf);
}
else if (status == 0) {
jr_esprintf (opt_error_buf, "premature end of file");
status = jr_INTERNAL_ERROR;
}
else {
jr_esprintf (opt_error_buf, "read %d bytes of %d requested", status, r_bytes);
status = jr_IO_ERROR;
}
return status;
}
for (i=0; i < entry_info->num_ptr_values; i++) {
r_bytes = jr_NetIntToHost (entry_info->data_lengths[i]);
entry_info->ptr_values[i] = jr_malloc (r_bytes);
entry_info->has_malloced_ptrs = 1;
status = jr_file_read( file_info, (void *) entry_info->ptr_values[i], r_bytes, opt_error_buf);
if (status < r_bytes) {
entry_info->num_ptr_values = i+1;
jr_LogEntryUndo (entry_info);
if (status < 0) {
jr_esprintf (opt_error_buf, "error reading log entry: %s", opt_error_buf);
}
else if (status == 0) {
jr_esprintf (opt_error_buf, "premature end of file");
status = jr_INTERNAL_ERROR;
}
else {
jr_esprintf (opt_error_buf, "read %d bytes of %d requested", status, r_bytes);
status = jr_IO_ERROR;
}
return status;
}
}
return 0;
}
jr_int jr_LogExecuteEntries(
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)
{
jr_ULong start_offset;
jr_ULong stop_offset;
jr_ULong start_time;
jr_ULong stop_time;
jr_int num_executed_entries = 0;
jr_int stop_if_not_in_transaction = 0;
jr_int execute_by_time;
jr_int truncate_incomplete_transaction;
jr_int execute_transaction;
jr_int execute_next_entry;
jr_LogEntryType entry_info [1];
jr_ULong last_valid_offset;
jr_int in_transaction;
jr_ULong curr_offset;
jr_ULong old_offset;
jr_ULong curr_time;
jr_int status;
jr_ULongAsgn( &start_offset, start_value);
jr_ULongAsgn( &stop_offset, stop_value);
jr_ULongAsgn( &start_time, start_value);
jr_ULongAsgn( &stop_time, stop_value);
jr_ULongAsgnUInt( &curr_time, 0);
execute_by_time = execution_style & jr_LOG_EXECUTE_BY_TIME;
truncate_incomplete_transaction = execution_style & jr_LOG_TRUNCATE_INCOMPLETE_TRANSACTION;
execute_transaction = execution_style & jr_LOG_EXECUTE_TO_TRANSACTION_END;
execute_next_entry = execution_style & jr_LOG_EXECUTE_NEXT_ENTRY;
status = jr_file_get_offset( log_info->file_info, &old_offset, opt_error_buf);
if (status != 0) {
jr_esprintf (opt_error_buf, "couldn't get offset: %s", opt_error_buf);
goto return_bad;
}
if (execute_by_time) {
jr_ULongAsgnUInt( &start_offset, 0);
jr_ULongAsgnMaxValue( &stop_offset);
}
if (execute_next_entry) {
jr_ULongAsgnMaxValue( &stop_offset);
}
status = jr_file_seek( log_info->file_info, start_offset, jr_FILE_SEEK_SET, opt_error_buf);
if (status != 0) {
jr_esprintf (opt_error_buf, "couldn't seek: %s", opt_error_buf);
return -1;
}
status = jr_file_get_offset( log_info->file_info, &curr_offset, opt_error_buf);
if (status != 0) {
jr_esprintf (opt_error_buf, "couldn't get offset: %s", opt_error_buf);
goto return_bad;
}
jr_ULongAsgn( &last_valid_offset, curr_offset);
in_transaction = 0;
log_info->is_executing = 1;
while (jr_ULongCmp( curr_offset, stop_offset) < 0 || execute_transaction && in_transaction) {
if ( truncate_incomplete_transaction
&& jr_ULongCmp( curr_offset, log_info->truncate_offset) >= 0) {
break;
}
if ( execute_next_entry
&& num_executed_entries > 0
&& !(execute_transaction && in_transaction)) {
break;
}
status = jr_LogEntryInitFromLog (entry_info, log_info, opt_error_buf);
if (status == jr_EOF_ERROR) {
break;
}
else if (status != 0) {
jr_esprintf (opt_error_buf, "couldn't read log entry: %s", opt_error_buf);
status = -1;
goto return_bad;
}
status = jr_file_get_offset( log_info->file_info, &curr_offset, opt_error_buf);
if (status != 0) {
jr_esprintf (opt_error_buf, "couldn't get offset: %s", opt_error_buf);
goto return_bad;
}
jr_ULongAsgn( &curr_time, entry_info->entry_time);
if ( execute_by_time
&& !jr_ULongIsZero( entry_info->entry_time)
&& jr_ULongCmp( entry_info->entry_time, start_time) < 0) {
jr_LogEntryUndo (entry_info);
continue;
}
if (execute_by_time
&& !jr_ULongIsZero( stop_time) && jr_ULongCmp( curr_time, stop_time) >= 0
&& !(execute_transaction && in_transaction)
) {
jr_LogEntryUndo (entry_info);
break;
}
switch (entry_info->type_number) {
case jr_LOG_TRANSACTION_BEGIN_ENTRY : in_transaction++; break;
case jr_LOG_TRANSACTION_COMMIT_ENTRY : in_transaction--; break;
case jr_LOG_HEADER_ENTRY : {
jr_LogEntryUndo (entry_info);
continue;
}
}
if (entry_fn) {
status = (*entry_fn) (entry_fn_arg, entry_info, opt_error_buf);
if (status < 0) {
jr_LogEntryUndo (entry_info);
goto return_bad;
}
if (status == jr_LOG_STOP_IF_NOT_IN_TRANSACTION) {
stop_if_not_in_transaction = 1;
}
else {
stop_if_not_in_transaction = 0;
}
}
jr_LogEntryUndo (entry_info);
num_executed_entries ++;
if (! in_transaction) {
/*
* if we're in a transaction, wait until we see the end
* to decide if the transaction should be kept
*/
last_valid_offset = curr_offset;
if (stop_if_not_in_transaction) {
break;
}
}
}
if (in_transaction && truncate_incomplete_transaction) {
if (entry_fn) {
jr_ULong tmp_ulong;
jr_ULongAsgnUInt( &tmp_ulong, 0);
/*
* If we stop in the middle of a transaction,
* abort the transaction we're in.
*/
jr_LogEntryInit (entry_info, jr_LOG_TRANSACTION_ABORT_ENTRY, 0, 0, tmp_ulong, 0);
jr_LogEntrySetOffset (entry_info, curr_offset);
status = (*entry_fn) (entry_fn_arg, entry_info, opt_error_buf);
jr_LogEntryUndo (entry_info);
if (status < 0) {
goto return_bad;
}
}
status = jr_LogDeleteRange ( /*@ delete_partial @*/
log_info, last_valid_offset, log_info->truncate_offset, opt_error_buf
);
if (status != 0) {
jr_esprintf (opt_error_buf, "couldn't remove incomplete transaction: %s",
opt_error_buf
);
status = -1;
goto return_bad;
}
curr_offset = last_valid_offset;
/*
* Delete range leaves the fp at the new end of the log
*/
}
else {
status = jr_file_seek( log_info->file_info, old_offset, jr_FILE_SEEK_SET, opt_error_buf);
if (status != 0) {
jr_esprintf (opt_error_buf, "couldn't seek: %s", opt_error_buf);
goto return_bad;
}
}
log_info->is_executing = 0;
if (opt_offset_ref) {
jr_ULongAsgn( opt_offset_ref, curr_offset);
}
status = 0;
return_bad : {
if (status != 0) {
jr_file_seek( log_info->file_info, old_offset, jr_FILE_SEEK_SET, 0);
log_info->is_executing = 0;
}
}
return status;
}
jr_int jr_LogSetTruncateOffset (log_info, error_buf)
jr_LogType * log_info;
char * error_buf;
{
jr_ULong truncate_offset;
jr_int status;
status = jr_LogPadToBlockBoundary (log_info, &truncate_offset, error_buf);
if (status < 0) {
return status;
}
jr_ULongAsgn( &log_info->truncate_offset, truncate_offset);
return 0;
}
jr_int jr_AvoidLogBlockBoundary(
jr_file_t * file_info,
jr_int block_size,
jr_int log_entry_length,
jr_ULong * opt_end_offset_ref,
char * opt_error_buf)
{
jr_LogEntryHeaderStruct entry_header [1];
jr_ULong curr_end_offset;
jr_ULong padding_size;
jr_int space_in_block;
jr_int w_bytes;
jr_int status;
status = jr_file_get_offset( file_info, &curr_end_offset, opt_error_buf);
if (status != 0) {
jr_esprintf( opt_error_buf, "can't get file size: %s", opt_error_buf);
return status;
}
if (block_size == 0 || jr_ULongModUInt( curr_end_offset, block_size) == 0) {
if (opt_end_offset_ref) {
jr_ULongAsgn( opt_end_offset_ref, curr_end_offset);
}
return 0;
}
space_in_block = block_size - jr_ULongModUInt( curr_end_offset, block_size);
if (space_in_block < log_entry_length) {
/*
* no room on this block for the next entry
* create a pad entry which contains the number of bytes to the
* next entry in the entry_time field.
* If there is no room for the pad entry, then skip to the next block
* boundary.
*/
w_bytes = sizeof (jr_LogEntryHeaderStruct);
if (w_bytes <= space_in_block) {
jr_ULongAsgnUInt( &padding_size, space_in_block);
jr_LogEntryHeaderInit (entry_header, jr_LOG_PAD_ENTRY, 0, 0, padding_size);
status = jr_file_write( file_info, entry_header, w_bytes, opt_error_buf);
if (status != w_bytes) {
if (status < 0) {
jr_esprintf( opt_error_buf, "write error: %s", opt_error_buf);
}
else {
jr_esprintf( opt_error_buf, "only wrote %d of %d bytes", status, w_bytes);
status = jr_IO_ERROR;
}
return status;
}
}
jr_ULongAddUInt( &curr_end_offset, curr_end_offset, space_in_block);
status = jr_file_seek( file_info, curr_end_offset, jr_FILE_SEEK_SET, opt_error_buf);
if (status != 0) {
jr_esprintf (opt_error_buf, "couldn't seek: %s", opt_error_buf);
return -1;
}
}
if (opt_end_offset_ref) {
jr_ULongAsgn( opt_end_offset_ref, curr_end_offset);
}
return 0;
}
off_t jr_NextLogEntryOffset (curr_end_offset, log_entry_length, block_size)
off_t curr_end_offset;
jr_int log_entry_length;
jr_int block_size;
{
jr_int space_in_block;
if (block_size == 0 || curr_end_offset % block_size == 0) {
return curr_end_offset;
}
space_in_block = block_size - curr_end_offset % block_size;
if (space_in_block < log_entry_length) {
curr_end_offset += space_in_block;
}
return curr_end_offset;
}
jr_int jr_LogTransactionBegin (log_info, opt_error_buf)
jr_LogType * log_info;
char * opt_error_buf;
{
jr_LogEntryType entry_info [1];
jr_LogTransInfoType * trans_info;
jr_ULong curr_offset;
jr_ULong tmp_ulong;
jr_int status;
status = jr_file_get_offset( log_info->file_info, &curr_offset, opt_error_buf);
if (status != 0) {
jr_esprintf( opt_error_buf, "couldn't seek: %s", opt_error_buf);
return -1;
}
jr_ULongAsgnUInt( &tmp_ulong, 0);
jr_LogEntryInit (entry_info, jr_LOG_TRANSACTION_BEGIN_ENTRY, 0, 0, tmp_ulong, 0);
status = jr_LogAddEntry (log_info, entry_info, opt_error_buf);
if (status != 0) {
jr_esprintf (opt_error_buf, "couldn't log begin transaction request: %s", opt_error_buf);
return -1;
}
log_info->in_transaction ++;
trans_info = jr_AListNewTailPtr (log_info->transaction_stack);
jr_LogTransInfoInit (trans_info, curr_offset);
return 0;
}
jr_int jr_LogTransactionCommit (log_info, opt_error_buf)
jr_LogType * log_info;
char * opt_error_buf;
{
jr_LogEntryType entry_info [1];
jr_LogTransInfoType * trans_info;
jr_ULong tmp_ulong;
jr_int status;
if (!jr_LogIsInTransaction (log_info)) {
jr_esprintf (opt_error_buf, "not in transaction");
return -1;
}
log_info->in_transaction --;
trans_info = jr_AListDeletedTailPtr (log_info->transaction_stack);
/*
* setup a new tail before the AddEntry() so that this commit
* is conceptually part of the outer transaction
*/
jr_ULongAsgnUInt( &tmp_ulong, 0);
jr_LogEntryInit (
entry_info, jr_LOG_TRANSACTION_COMMIT_ENTRY, 0, 0, tmp_ulong, trans_info->requires_sync
);
status = jr_LogAddEntry (log_info, entry_info, opt_error_buf);
if (status != 0) {
char other_error_buf [jr_ERROR_LEN];
status = jr_LogTruncate (log_info, trans_info->begin_offset, other_error_buf);
if (status != 0) {
jr_esprintf (opt_error_buf, "couldn't add log entry (%s), then couldn't truncate(): %s",
opt_error_buf, other_error_buf
);
return -1;
}
jr_esprintf (opt_error_buf, "couldn't log transaction commit: %s", opt_error_buf);
return -1;
}
return 0;
}
jr_int jr_LogTransactionAbort (log_info, opt_error_buf)
jr_LogType * log_info;
char * opt_error_buf;
{
jr_LogTransInfoType * trans_info;
jr_int status;
if (!jr_LogIsInTransaction (log_info)) {
jr_esprintf (opt_error_buf, "not in transaction");
return -1;
}
log_info->in_transaction --;
trans_info = jr_AListDeletedTailPtr (log_info->transaction_stack);
status = jr_LogTruncate (log_info, trans_info->begin_offset, opt_error_buf);
if (status != 0) {
jr_esprintf (opt_error_buf, "couldn't truncate log: %s", opt_error_buf);
return -1;
}
return 0;
}
void jr_LogTransInfoInit(
jr_LogTransInfoType * trans_info,
jr_ULong begin_offset)
{
jr_ULongAsgn( &trans_info->begin_offset, begin_offset);
trans_info->requires_sync = 0;
}
void jr_LogTransInfoUndo (trans_info)
jr_LogTransInfoType * trans_info;
{
}
jr_int jr_LogDeleteRange(
jr_LogType * log_info,
jr_ULong start_offset,
jr_ULong end_offset,
char * opt_error_buf)
{
jr_ULong eof_offset;
jr_ULong num_bytes;
jr_int read_size;
void * read_buffer;
jr_int wrote_bytes = 1;
jr_int status;
if (jr_ULongCmp( end_offset, start_offset) < 0) {
jr_esprintf (opt_error_buf, "invalid range [%ld - %ld]",
(long) jr_ULongToHost( start_offset), (long) jr_ULongToHost( end_offset)
);
return jr_LOG_GENERIC_ERROR;
}
if (jr_ULongCmp( start_offset, end_offset) == 0) {
return 0;
}
if ( log_info->block_size
&& jr_ULongModUInt( start_offset, log_info->block_size)
!= jr_ULongModUInt( end_offset, log_info->block_size)
) {
/*
** Relative block offsets are not equal. In this case
** the end offset must either be a block boundary or the end of the file.
*/
jr_ULongAsgnUInt( &eof_offset, 0);
status = jr_file_seek( log_info->file_info, eof_offset, jr_FILE_SEEK_END, opt_error_buf);
if (status != 0) {
jr_esprintf (opt_error_buf, "couldn't seek: %s", opt_error_buf);
return jr_LOG_GENERIC_ERROR;
}
status = jr_file_get_offset( log_info->file_info, &eof_offset, opt_error_buf);
if (status != 0) {
jr_esprintf (opt_error_buf, "couldn't get offset: %s", opt_error_buf);
return jr_LOG_GENERIC_ERROR;
}
if (jr_ULongCmp( end_offset, eof_offset) >= 0) {
jr_ULongAsgn( &end_offset, eof_offset);
}
else {
if (jr_ULongModUInt( end_offset, log_info->block_size)) {
jr_esprintf (opt_error_buf, "end offset %u bytes past block boundary",
jr_ULongModUInt( end_offset, log_info->block_size)
);
return jr_LOG_GENERIC_ERROR;
}
if (jr_ULongModUInt( start_offset, log_info->block_size)) {
status = jr_file_seek(
log_info->file_info, start_offset, jr_FILE_SEEK_SET, opt_error_buf
);
if (status != 0) {
jr_esprintf (opt_error_buf, "couldn't seek: %s", opt_error_buf);
return jr_LOG_GENERIC_ERROR;
}
status = jr_LogPadToBlockBoundary (log_info, &start_offset, opt_error_buf);
if (status < 0) {
jr_esprintf (opt_error_buf, "couldn't pad %u bytes of start block: %s",
jr_ULongModUInt( start_offset, log_info->block_size),
opt_error_buf
);
return jr_LOG_GENERIC_ERROR;
}
wrote_bytes = 1;
}
}
}
read_size = log_info->block_size;
read_buffer = jr_malloc (read_size);
jr_ULongAsgnUInt( &eof_offset, 0);
status = jr_file_seek( log_info->file_info, eof_offset, jr_FILE_SEEK_END, opt_error_buf);
if (status != 0) {
jr_esprintf (opt_error_buf, "couldn't seek: %s", opt_error_buf);
goto return_bad;
}
status = jr_file_get_offset( log_info->file_info, &eof_offset, opt_error_buf);
if (status != 0) {
jr_esprintf (opt_error_buf, "couldn't get offset: %s", opt_error_buf);
goto return_bad;
}
/*
** 3-12-2013: copy from the end of the deleted section to the end of the file
** over the start of the deleted section.
*/
jr_ULongSubtract( &num_bytes, eof_offset, end_offset);
while (jr_ULongIsNonZero( num_bytes)) {
status = jr_file_seek( log_info->file_info, end_offset, jr_FILE_SEEK_SET, opt_error_buf);
if (status != 0) {
jr_esprintf (opt_error_buf, "couldn't seek: %s", opt_error_buf);
goto return_bad;
}
if (jr_ULongCmpUInt( num_bytes, read_size) < 0) {
read_size = jr_ULongToHost( num_bytes);
}
status = jr_file_read( log_info->file_info, read_buffer, read_size, opt_error_buf);
if (status != read_size) {
if (status < 0) {
jr_esprintf (opt_error_buf, "error reading log entry: %s", opt_error_buf);
}
else {
jr_esprintf (opt_error_buf, "read %d bytes of %d requested", status, read_size);
status = jr_IO_ERROR;
}
goto return_bad;
}
status = jr_file_seek( log_info->file_info, start_offset, jr_FILE_SEEK_SET, opt_error_buf);
if (status != 0) {
jr_esprintf (opt_error_buf, "couldn't seek: %s", opt_error_buf);
goto return_bad;
}
status = jr_file_write( log_info->file_info, read_buffer, read_size, opt_error_buf);
if (status != read_size) {
if (status < 0) {
jr_esprintf( opt_error_buf, "write error: %s", opt_error_buf);
}
else {
jr_esprintf( opt_error_buf, "only wrote %d of %d bytes", status, read_size);
status = jr_IO_ERROR;
}
goto return_bad;
}
wrote_bytes = 1;
jr_ULongSubtractUInt( &num_bytes, num_bytes, read_size);
jr_ULongAddUInt( &start_offset, start_offset, read_size);
jr_ULongAddUInt( &end_offset, end_offset, read_size);
}
status = jr_LogTruncate (log_info, start_offset, opt_error_buf);
if (status != 0) {
jr_esprintf (opt_error_buf, "couldn't truncate log: %s", opt_error_buf);
goto return_bad;
}
if (0) return_bad : {
if (wrote_bytes) {
status = jr_LOG_CORRUPTED_ERROR;
}
else {
status = jr_LOG_GENERIC_ERROR;
}
}
else {
status = 0;
}
jr_free (read_buffer);
return status;
}
jr_int jr_LogSync (log_info, opt_error_buf)
jr_LogType * log_info;
char * opt_error_buf;
{
jr_int status;
status = jr_LogSetFileSyncBit (log_info, 1, opt_error_buf);
if (status != 0) {
return -1;
}
status = jr_file_flush( log_info->file_info, opt_error_buf);
if (status != 0) {
jr_esprintf (opt_error_buf, "couldn't flush: %s", opt_error_buf);
return -1;
}
return 0;
}
jr_int jr_LogSyncAllEntries (log_info, opt_error_buf)
jr_LogType * log_info;
char * opt_error_buf;
{
jr_int status;
status = jr_file_flush( log_info->file_info, opt_error_buf);
if (status != 0) {
jr_esprintf (opt_error_buf, "couldn't flush: %s", opt_error_buf);
return -1;
}
return 0;
}
|
frankjas/libjr
|
include/jr/prefix.h
|
#ifndef __jr_prefix_h___
#define __jr_prefix_h___
#include "ezport.h"
#include <stdarg.h>
typedef struct {
char * container_name;
void * container_ptr;
jr_int prefix_id;
jr_int prefix_size;
jr_int (*element_prefix_size_fn) ();
void (*prefix_transform_fn) ();
void (*set_prefix_size_fn) ();
unsigned needs_transform_fn : 1;
} jr_PrefixInfoType;
extern void jr_PrefixAddContainerType PROTO ((
char * str_const_container_name,
jr_int (*element_prefix_size_fn) (),
void (*prefix_transform_fn) (),
void (*set_prefix_size_fn) (),
jr_int needs_transform_fn
));
extern void jr_SetContainers PROTO ((
char * container_name,
void * container_ptr,
...
));
extern jr_PrefixInfoType *jr_PrefixArrayCreateFromVA_List PROTO ((
va_list arg_list,
jr_int needs_transform_fn
));
extern void jr_PrefixArrayDestroy PROTO ((
jr_PrefixInfoType * prefix_array
));
extern void jr_PrefixArraySetInfo PROTO ((
jr_PrefixInfoType * prefix_array,
char * container_name,
jr_int prefix_size,
void (*prefix_transform_fn) ()
));
extern void jr_PrefixArrayTransformElement PROTO ((
jr_PrefixInfoType * prefix_array,
void * el_ptr,
unsigned jr_int magnitude,
jr_int which_way,
jr_int all_elements
));
extern jr_int jr_PrefixArrayInitPrefixes PROTO ((
jr_PrefixInfoType * prefix_array
));
#define jr_PrefixArrayForEachInfoPtr(prefix_array, prefix_info) \
for ((prefix_info) = prefix_array; !jr_PrefixInfoIsNull (prefix_info); (prefix_info)++)
/******** Prefix Info ********/
extern void jr_PrefixInfoInit PROTO ((
jr_PrefixInfoType * prefix_info,
char * container_name,
void * container_ptr
));
extern void jr_PrefixInfoUndo PROTO ((
jr_PrefixInfoType * prefix_info
));
extern void jr_PrefixInfoInitPrefix PROTO ((
jr_PrefixInfoType * prefix_info
));
#define jr_PrefixInfoContainerPtr(prefix_info) ((prefix_info)->container_ptr)
#define jr_PrefixInfoContainerName(prefix_info) ((prefix_info)->container_name)
#define jr_PrefixInfoPrefixSize(prefix_info) ((prefix_info)->prefix_size)
#define jr_PrefixInfoTransformFn(prefix_info) ((prefix_info)->prefix_transform_fn)
#define jr_PrefixInfoNeedsTransformFn(prefix_info) ((prefix_info)->needs_transform_fn)
#define jr_PrefixInfoSetTransformFn(prefix_info, v) ((prefix_info)->prefix_transform_fn = (v))
#define jr_PrefixInfoSetPrefixSize(prefix_info, v) ((prefix_info)->prefix_size = (v))
#define jr_PrefixInfoIsNull(prefix_info) ((prefix_info)->container_name == 0)
extern jr_PrefixInfoType jr_PrefixInfoArray [];
#endif
|
frankjas/libjr
|
include/jr/alist.h
|
#ifndef __ALIST_HEADER__
#define __ALIST_HEADER__
#include "ezport.h"
#include <string.h>
#include <stdarg.h>
typedef struct {
char * buffer; /* buffer where elements are stored */
jr_int buffer_capacity; /* maximum number of objects allowed */
char * free_ptr;
jr_int objsize;
jr_int free_index;
jr_int prefix_size;
} jr_AList;
typedef jr_AList jr_AListType;
/*
* To reduce the size of the jr_AList,
* we can instead allocate a separate structure to hold the
* prefix transformation code, and keep a pointer to that structure.
* The we only allocate that structure when the prefix is non-zero.
* But this means all HTable element accesses are more expensive.
*
* We could actually store the prefix_size in the structure, and if
* the prefix size is non-zero, than an extra 8 bytes is added to
* the buffer (as a prefix, perhaps), that hold the prefix transformation
* information.
*/
typedef struct {
void (*prefix_transform_fn) ();
void * prefix_transform_arg;
} jr_AListPrefixTransformStruct;
extern void jr_AListInit PROTO ((jr_AList *list, jr_int objsize));
extern void jr_AListUndo PROTO ((jr_AList *list));
extern jr_AList *jr_AListCreate PROTO ((jr_int objsize));
extern void jr_AListDestroy PROTO ((jr_AList *list));
extern void jr_AListEmpty PROTO ((jr_AList *list));
extern void jr_AListInitCopy PROTO ((jr_AList *dest, jr_AList *src));
extern void * jr_AListExtractBuffer PROTO ((jr_AList *list));
extern void jr_AListTruncate PROTO ((jr_AList *list, jr_int i));
extern void jr_AListReverse PROTO ((jr_AList *list));
#define jr_AListMove(src, dest) memcpy (dest, src, sizeof (jr_AList));
extern jr_int jr_AListIncreaseCapacity PROTO ((jr_AList *list, jr_int new_size));
extern void * jr_AListNewTailPtr PROTO ((jr_AList *list));
extern void * jr_AListDeletedTailPtr PROTO ((jr_AList *list));
extern void * jr_AListNewPrevElementPtr PROTO ((jr_AList *list, void *insertptr));
extern void * jr_AListNewNextElementPtr PROTO ((jr_AList *list, void *insertptr));
extern void jr_AListSetTailIndex PROTO ((jr_AList *list, jr_int index));
extern jr_AList *jr_AListDup PROTO ((jr_AList *list));
extern void * jr_AListBufferDup PROTO ((jr_AList *list));
extern void jr_AListDeleteRangeFromPtr PROTO ((
jr_AList * list,
void * ptr,
jr_int num_entries
));
extern void ** jr_AListVectorPtr PROTO ((jr_AList *list));
extern void jr_AListSetPrefixSize PROTO ((
jr_AList * list,
jr_int prefix_size,
void (*prefix_transform_fn) (),
void * prefix_transform_arg
));
/*
void prefix_transform_fn PROTO ((
void * container_ptr,
void * el_ptr,
unsigned jr_int magnitude,
jr_int which_way,
jr_int all_elements
))
*/
extern void jr_AListSetContainers PROTO ((
jr_AList * list,
...
));
/*
* jr_AListSetContainers (list, "jr_LList", llist_ptr, "jr_GNode", graph_ptr, 0);
* also accepts "MyContainerType", container_ptr
* use jr_AListSetCustomPrefixInfo (list, "MyContainerType", etc.)
* to set the container's prefix size and prefix transform function
*/
extern void jr_AListSetCustomPrefixInfo PROTO ((
jr_AList * list,
char * container_name,
jr_int prefix_size,
void (*prefix_transform_fn) ()
));
extern void jr_AListSetContainersFromVA_List PROTO ((
jr_AList * list,
va_list arg_list
));
#define jr_AListSize(list) ((list)->free_index)
#define jr_AListEndPtr(list) ((void *) ((list)->free_ptr))
#define jr_AListElementSize(list) ((list)->objsize - (list)->prefix_size)
#define jr_AListPrefixSize(list) ((list)->prefix_size)
#define jr_AListTailIndex(list) ((list)->free_index - 1)
#define jr_AListNumBytes(list) ((char *) (list)->free_ptr - (char *) (list)->buffer)
#define jr_AListCapacity(list) ((list)->buffer_capacity)
#define jr_AListIsEmpty(list) ((list)->free_index == 0)
#define jr_AListAllocatesElements(list) (1)
#define jr_AListHasPrefixTransformFn(list) \
( jr_AListPrefixSize (list) > 0 \
&& (list)->buffer != 0 \
&& jr_AListPrefixTransformFn (list) \
)
#define jr_AListPrefixTransformPtr(list) \
((jr_AListPrefixTransformStruct *) \
((list)->buffer - sizeof (jr_AListPrefixTransformStruct)) \
)
#define jr_AListPrefixTransformFn(list) \
(jr_AListPrefixTransformPtr (list)->prefix_transform_fn)
#define jr_AListPrefixTransformArg(list) \
(jr_AListPrefixTransformPtr (list)->prefix_transform_arg)
#define jr_AListElementPtrWithPrefix(list, i, prefix_size) \
((void *)((list)->buffer + (i)*(list)->objsize + (prefix_size)))
#define jr_AListTailPtrWithPrefix(list, prefix_size) \
((void *)((list)->free_ptr - (list)->objsize + (prefix_size)))
#define jr_AListHeadPtrWithPrefix(list, prefix_size) \
((void *)((list)->buffer + (prefix_size)))
#define jr_AListElementIndexWithPrefix(list, ptr, prefix_size) \
( (((char *) (ptr) - (prefix_size)) - (list)->buffer) / (list)->objsize)
#define jr_AListIncrElementPtr(list, elptr) \
((void *)(((char *) (elptr)) + (list)->objsize))
#define jr_AListDecrElementPtr(list, elptr) \
((void *)(((char *) (elptr)) - (list)->objsize))
#define jr_AListNextElementPtr(list, elptr) \
(jr_AListIncrElementPtr(list, elptr) < jr_AListEndPtr (list) \
? jr_AListIncrElementPtr(list, elptr) \
: 0 \
)
#define jr_AListPrevElementPtr(list, elptr) \
((void *)(elptr) > jr_AListHeadPtr (list) \
? jr_AListDecrElementPtr(list, elptr) \
: 0 \
)
#define jr_TransformAListPtr(ptr, magnitude, which_way) \
((void *) ((which_way) > 0 \
? ((char *) (ptr)) + (magnitude) \
: ((char *) (ptr)) - (magnitude)) \
)
#define jr_UnTransformAListPtr(ptr, magnitude, which_way) \
jr_TransformAListPtr (ptr, magnitude, -(which_way))
/******** Convenience Functions ********/
#define jr_AListNewElementPtr(list, i) \
jr_AListNewPrevElementPtr (list, jr_AListElementPtr(list, i))
#define jr_AListElementPtr(list, i) \
jr_AListElementPtrWithPrefix (list, i, jr_AListPrefixSize (list))
#define jr_AListTailPtr(list) \
jr_AListTailPtrWithPrefix (list, jr_AListPrefixSize (list))
#define jr_AListHeadPtr(list) \
jr_AListHeadPtrWithPrefix (list, jr_AListPrefixSize (list))
#define jr_AListElementIndex(list, ptr) \
jr_AListElementIndexWithPrefix (list, ptr, jr_AListPrefixSize (list))
#define jr_AListForEachElementPtr(list, current) \
jr_AListForEachElementPtrWithPrefix (list, current, jr_AListPrefixSize (list))
#define jr_AListForEachElementPtrRev(list, current)\
jr_AListForEachElementPtrRevWithPrefix (list, current, jr_AListPrefixSize (list))
#define jr_AListSetSize(list, size) jr_AListSetTailIndex (list, (size) - 1)
#define jr_AListSetNewTail(list, elptr) \
memcpy (jr_AListNewTailPtr(list), elptr, jr_AListElementSize (list))
#define jr_AListSetNewElement(list, i, elptr) \
memcpy ( \
jr_AListNewPrevElementPtr(list, jr_AListElementPtr(list, i)), \
elptr, \
jr_AListElementSize (list) \
)
#define jr_AListSetNewPrevElement(list, next_elptr, elptr) \
memcpy ( \
jr_AListNewPrevElementPtr(list, next_elptr), \
elptr, \
jr_AListElementSize (list) \
)
#define jr_AListSetNewNextElement(list, prev_elptr, elptr) \
memcpy ( \
jr_AListNewNextElementPtr(list, prev_elptr), \
elptr, \
jr_AListElementSize (list) \
)
#define jr_AListSetElement(list, i, elptr) \
memcpy ( \
jr_AListElementPtr(list, i), \
elptr, \
jr_AListElementSize (list) \
)
#define jr_AListGetTail(list, elptr) \
memcpy (elptr, jr_AListTailPtr(list), jr_AListElementSize (list))
#define jr_AListGetHead(list, elptr) \
memcpy (elptr, jr_AListHeadPtr(list), jr_AListElementSize (list))
#define jr_AListGetElement(list, i, elptr) \
memcpy (elptr, jr_AListElementPtr(list, i), jr_AListElementSize (list))
#define jr_AListDeleteTail(list) \
((void) jr_AListDeletedTailPtr (list))
#define jr_AListGetDeletedTail(list, elptr) \
memcpy (elptr, jr_AListDeletedTailPtr(list), jr_AListElementSize (list))
#define jr_AListDeleteElement(list, elptr) \
jr_AListDeleteRangeFromPtr (list, elptr, 1)
#define jr_AListDeleteIndex(list, i) \
jr_AListDeleteRangeFromPtr (list, jr_AListElementPtr (list, i), 1)
#define jr_AListDeleteRangeFromIndex(list, i, num_to_delete) \
jr_AListDeleteRangeFromPtr (list, jr_AListElementPtr (list, i), num_to_delete)
extern void jr_AListAppendString(
jr_AList * char_list,
const char * string);
extern void * jr_AListFindInsertPtr PROTO ((
jr_AList * list,
const void * elptr,
jr_int (*cmpfn)()
));
extern void * jr_AListFindElementPtr PROTO ((
jr_AList * list,
const void * elptr,
jr_int (*cmpfn)()
));
extern void * jr_AListFindFirstElementPtr PROTO ((
jr_AList * list,
const void * elptr,
jr_int (*cmpfn)()
));
extern void * jr_AListSetNewTailUniquely PROTO ((
jr_AList * list,
const void * elptr,
jr_int (*cmpfn)()
));
extern void jr_AListSortRange PROTO ((
jr_AList * list,
jr_int start_index,
jr_int num_elements,
jr_int (*cmpfn)()
));
extern jr_int jr_AListCmp PROTO ((
const jr_AList * list1,
const jr_AList * list2,
jr_int (*cmpfn)()
));
extern jr_int jr_AListHash PROTO ((
const jr_AList * list,
jr_int (*hash_fn) ()
));
#define jr_AListNewElementPtrInOrder(list, elptr, cmpfn) \
jr_AListNewPrevElementPtr (list, jr_AListFindInsertPtr (list, elptr, cmpfn))
#define jr_AListSetNewElementInOrder(list, elptr, cmpfn) \
memcpy ( \
jr_AListNewElementPtrInOrder (list, elptr, cmpfn), \
elptr, \
jr_AListElementSize (list) \
)
#define jr_AListQSort(list, cmpfn) \
qsort ( \
jr_AListElementPtr(list, 0), jr_AListSize(list), \
jr_AListElementSize(list), cmpfn \
)
#define jr_AListSort(list, cmpfn) \
jr_AListSortRange (list, 0, jr_AListSize (list), cmpfn)
#define jr_AListSortUniquely(list, cmpfn) \
jr_AListSortUniquelyRange (list, 0, jr_AListSize (list), cmpfn)
#define jr_AListSortUniquelyRange(list, start_index, num_elements, cmpfn) \
jr_AListSortUniquelyRangeFreeingDeletes ( \
list, start_index, num_elements, cmpfn, 0, 0 \
)
#define jr_AListSortUniquelyFreeingDeletes(list, cmpfn, freefunc, arg) \
jr_AListSortUniquelyRangeFreeingDeletes ( \
list, 0, jr_AListSize (list), cmpfn, freefunc, arg \
)
extern void jr_AListSortUniquelyRangeFreeingDeletes PROTO ((
jr_AList * list,
jr_int start_index,
jr_int num_elements,
jr_int (*cmpfn)(),
void (*freefunc)(),
void * freefunc_arg
));
/******** Native jr_AList Macros ********/
#define jr_AListNativeSetNewTail(list, element, type) \
(* (type *) jr_AListNewTailPtr (list) = element)
#define jr_AListNativeSetNewElement(list, i, element, type) \
(* (type *) jr_AListNewPrevElementPtr (list, jr_AListElementPtr (list, i)) = element)
#define jr_AListNativeDeletedTail(list, type) (* (type *) jr_AListDeletedTailPtr (list))
#define jr_AListNativeTail(list, type) (* (type *) jr_AListTailPtr (list))
#define jr_AListNativeHead(list, type) (* (type *) jr_AListHeadPtr (list))
#define jr_AListNativeElement(list, i, type) (* (type *) jr_AListElementPtr (list, i))
#define jr_AListNativeSetTail(list, v, type) (* (type *) jr_AListTailPtr (list) = (v))
#define jr_AListNativeSetHead(list, v, type) (* (type *) jr_AListHeadPtr (list) = (v))
#define jr_AListNativeSetElement(list, i, v, type) \
(* (type *) jr_AListElementPtr (list, i) = (v))
#define jr_AListNativeGetDeletedTail(list, type) jr_AListNativeDeletedTail(list, type)
/******** For Each Loop Macros ********/
#define jr_AListIsValidIndex(list, i) ((i) >= 0 && (i) < jr_AListSize (list))
#define jr_AListForEachElementIndex(list, i) \
for ((i) = 0; (i) < jr_AListSize(list); (i)++)
#define jr_AListForEachElementIndexRev(list, i) \
for ((i) = jr_AListSize(list) - 1; i >= 0; i--)
#define jr_AListForEachElementPtrWithPrefix(list, current, prefix_size) \
for ( (current) = jr_AListHeadPtrWithPrefix (list, prefix_size); \
((void *) (current)) < jr_AListEndPtr (list); \
(current) = jr_AListIncrElementPtr (list, current) \
)
/*
** 9/5/05: if the object size if 0 and the prefix is > 0, then using
** "< end ptr" as the test will skip the last element,
** but using "< tail ptr" will screw up on an empty list, since you
** can't subtract from a null pointer.
*/
#define jr_AListForEachElementPtrRevWithPrefix(list, current, prefix_size) \
if (jr_AListSize (list) > 0) \
for ( (current) = jr_AListTailPtrWithPrefix (list, prefix_size); \
((void *) (current)) >= jr_AListHeadPtr (list); \
(current) = jr_AListDecrElementPtr (list, current) \
)
#if defined(__cplusplus)
/*
* void * assignment generates warnings in C++, but
* by casting the address of the loop pointer to a void **,
* we create a void * expression on the left of the assignment.
* These operations do not actually execute at run time.
*/
# undef jr_AListForEachElementPtrWithPrefix
# undef jr_AListForEachElementPtrRevWithPrefix
# define jr_AListForEachElementPtrWithPrefix(list, current, prefix_size) \
for ( (*(void **)&(current)) = jr_AListHeadPtrWithPrefix (list, prefix_size); \
( (void *) (current)) < jr_AListEndPtr (list); \
(*(void **)&(current)) = jr_AListIncrElementPtr (list, current) \
)
/*
** 9/5/05: if the object size if 0 and the prefix is > 0, then using
** "< end ptr" as the test will skip the last element,
** but using "< tail ptr" will screw up on an empty list, since you
** can't subtract from a null pointer.
*/
# define jr_AListForEachElementPtrRevWithPrefix(list, current, prefix_size) \
if (jr_AListSize (list) > 0) \
for ( (*(void **)&(current)) = jr_AListTailPtrWithPrefix (list, prefix_size);\
( (void *) (current)) >= jr_AListHeadWithPrefixPtr (list, prefix_size);\
(*(void **)&(current)) = jr_AListDecrElementPtr (list, current) \
)
#endif
#endif
|
frankjas/libjr
|
libjr/syscalls/jr_poll.h
|
<gh_stars>0
#ifndef _jr_poll_proj_h___
#define _jr_poll_proj_h___
#include "ezport.h"
#include <string.h>
#include <apr-1/apr_pools.h>
#include <apr-1/apr_poll.h>
#include <apr-1/apr_errno.h>
#include "jr/poll.h"
#include "jr/apr.h"
#include "jr/error.h"
#include "jr/syscalls.h"
#include "jr/misc.h"
#define MIN_APR_POLLSET_SIZE 8
extern jr_int jr_poll_add_generic (
jr_poll_t * poll_ptr,
void * generic_io_ptr,
jr_int poll_flags,
jr_int (*opt_handler_fn) (
void * data_ptr,
jr_poll_t * poll_ptr,
void * generic_io_ptr,
jr_int io_style_ready,
char * error_buf
),
void * opt_handler_data_ptr,
char * error_buf);
extern void jr_poll_delete_generic (
jr_poll_t * poll_ptr,
void * generic_io_ptr,
jr_int poll_flags);
extern jr_pollevent_t * jr_poll_get_new_event (
jr_poll_t * poll_ptr,
void * generic_io_ptr,
jr_int io_style,
jr_int (*handler_fn) (
void * data_ptr,
jr_poll_t * poll_ptr,
void * generic_io_ptr,
jr_int io_style,
char * error_buf
),
void * handler_data_ptr);
extern void jr_poll_delete_event (
jr_poll_t * poll_ptr,
void * generic_io_ptr,
jr_int poll_flags);
extern void jr_pollevent_init (
jr_pollevent_t * event_ptr,
void * generic_io_ptr,
jr_int io_style,
jr_int (*handler_fn) (
void * data_ptr,
jr_poll_t * poll_ptr,
void * generic_io_ptr,
jr_int io_style,
char * error_buf
),
void * handler_data_ptr);
extern void jr_pollevent_undo (
jr_pollevent_t * event_ptr);
extern jr_int jr_pollevent_ptr_cmp (
const void * void_ptr_1,
const void * void_ptr_2);
extern jr_int jr_pollevent_ptr_hash (
const void * void_ptr);
extern jr_int jr_pollevent_add_to_pollset (
jr_pollevent_t * event_ptr,
apr_pollset_t * apr_pollset_ptr,
char * error_buf);
#endif
|
frankjas/libjr
|
libjr/missing/memmove.c
|
#define _POSIX_SOURCE 1
#include "ezport.h"
#include <string.h>
/*
* This routine conforms to the ANSI standard
* description for 'memmove(dest,src,nbytes)'
* used for copying arbitrary byte streams from
* one location in memory to another even if those
* locations overlap. We provide the source because
* some C environments are not provided with all
* of the ANSI specified routines.
*/
#ifdef missing_memmove
void *memmove(destin_arg, source_arg, nbytes)
void * destin_arg ;
const void * source_arg ;
unsigned int nbytes ;
{
char *destin = (char *) destin_arg ;
char *source = (char *) source_arg ;
jr_int i ;
if (source_arg == destin_arg) return(destin_arg) ;
if ((destin < source) && ((destin + nbytes) > source)) {
/* top of dest dest overlaps bottom of source */
for (i=0; i < nbytes ; i++) {
destin[i] = source[i] ;
}
}
else if ((destin > source) && (destin < (source + nbytes))) {
/* bottom of dest overlaps top of source */
for (i = nbytes - 1 ; i >= 0 ; i--) {
destin[i] = source[i] ;
}
}
else /* no overlap */ {
for (i=0; i < nbytes ; i++) {
destin[i] = source[i] ;
}
}
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/syscalls/remove.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/malloc.h"
jr_int jr_RemovePath (
const char * path_name,
char * error_buf)
{
jr_int is_dir;
char * cmd_buf = 0;
jr_int status;
status = jr_PathIsDirectory (path_name, error_buf);
if (status == jr_NOT_FOUND_ERROR) {
status = 0;
goto return_status;
}
else if (status < 0) {
jr_esprintf (error_buf, "couldn't check path '%.32s': %s", path_name, error_buf);
goto return_status;
}
is_dir = status;
if (is_dir) {
cmd_buf = jr_malloc (strlen (path_name) + 20);
sprintf (cmd_buf, "rm -rf '%s'", path_name);
status = jr_exec_cmd (cmd_buf, error_buf);
if (status != 0) {
goto return_status;
}
}
else {
status = jr_Unlink (path_name, error_buf);
if (status != 0) {
goto return_status;
}
}
status = 0;
return_status : {
if (cmd_buf) {
jr_free (cmd_buf);
}
}
return status;
}
|
frankjas/libjr
|
libjr/struct/att_list.c
|
#include "att_mngr.h"
void jr_AttributeListInit(attribute_list, manager)
jr_AttributeList * attribute_list ;
jr_AttributeManagerType * manager ;
{
attribute_list->list_id = jr_AttributeManagerGetListId (manager);
attribute_list->manager = manager ;
jr_DListInit(attribute_list->list_of_pairs, sizeof(jr_AttributeType)) ;
}
void jr_AttributeListUndo(attribute_list)
jr_AttributeList * attribute_list ;
{
jr_AttributeType * attribute_ptr;
jr_DListForEachElementPtr (attribute_list->list_of_pairs, attribute_ptr) {
jr_AttributeManagerDeleteAttribute (attribute_list->manager, attribute_ptr);
}
jr_DListUndo(attribute_list->list_of_pairs) ;
}
jr_AttributeList * jr_AttributeListCreate(manager)
jr_AttributeManagerType * manager ;
{
jr_AttributeList * new_attribute_list ;
new_attribute_list = (jr_AttributeList *) jr_malloc(sizeof(jr_AttributeList)) ;
jr_AttributeListInit(new_attribute_list, manager) ;
return(new_attribute_list) ;
}
void jr_AttributeListDestroy(attribute_list)
jr_AttributeList * attribute_list ;
{
jr_AttributeListUndo(attribute_list) ;
jr_free(attribute_list) ;
}
void jr_AttributeListEmpty(attribute_list)
jr_AttributeList * attribute_list ;
{
jr_AttributeType * attribute_ptr;
jr_DListForEachElementPtr (attribute_list->list_of_pairs, attribute_ptr) {
jr_AttributeManagerDeleteAttribute (attribute_list->manager, attribute_ptr);
}
jr_DListEmpty (attribute_list->list_of_pairs) ;
}
void jr_AttributeListAddAttribute (attribute_list, name_string, value_string)
jr_AttributeList * attribute_list ;
const char * name_string ;
const char * value_string ;
{
jr_AttributeType * old_attribute ;
jr_AttributeType * new_attribute ;
old_attribute = jr_AttributeManagerFindAttribute (
attribute_list->manager, attribute_list->list_id, name_string
) ;
if (old_attribute) {
if (old_attribute->value_string) {
jr_AttributeManagerDeleteValueString(
attribute_list->manager, old_attribute->value_string
) ;
old_attribute->value_string = 0;
}
if (value_string) {
old_attribute->value_string = (char *) jr_AttributeManagerAddValueString(
attribute_list->manager, value_string
) ;
}
new_attribute = old_attribute ;
}
else {
jr_AttributeType new_attribute_buf[1] ;
const char * new_string_value ;
const char * new_name_string ;
new_name_string = jr_AttributeManagerAddNameString(
attribute_list->manager, name_string
) ;
new_string_value = jr_AttributeManagerAddValueString(
attribute_list->manager, value_string
) ;
new_attribute_buf->name_string = (char *) new_name_string ;
new_attribute_buf->value_string = (char *) new_string_value ;
new_attribute_buf->list_id = attribute_list->list_id;
new_attribute = jr_DListSetNewHead(attribute_list->list_of_pairs, new_attribute_buf) ;
jr_AttributeManagerAddAttribute (attribute_list->manager, new_attribute);
}
}
const char * jr_AttributeListGetValue(list, name_string)
jr_AttributeList * list ;
const char * name_string ;
{
jr_AttributeType * attribute ;
attribute = jr_AttributeManagerFindAttribute(
list->manager, list->list_id, name_string
) ;
if (attribute) {
return attribute->value_string;
}
return 0;
}
void jr_AttributeListDeleteAttribute (attribute_list, name_string)
jr_AttributeList * attribute_list ;
const char * name_string ;
{
jr_AttributeType * old_attribute ;
old_attribute = jr_AttributeManagerFindAttribute (
attribute_list->manager, attribute_list->list_id, name_string
) ;
if (old_attribute) {
jr_DListDeleteElement (attribute_list->list_of_pairs, old_attribute);
}
}
|
frankjas/libjr
|
libjr/syscalls/login.c
|
<reponame>frankjas/libjr
#define _POSIX_SOURCE 1
#include "ezport.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "jr/misc.h"
#include "jr/string.h"
#include "jr/malloc.h"
#include "jr/syscalls.h"
#include "jr/error.h"
#include "jr/login.h"
jr_LoginInfoType * jr_LoginInfoCreate(user_name_arg,tty_name_arg,errbuf)
const char * user_name_arg ;
const char * tty_name_arg ;
char * errbuf ;
{
jr_LoginInfoType * new_login_info_result ;
new_login_info_result = (jr_LoginInfoType *) jr_malloc(sizeof(jr_LoginInfoType)) ;
if (jr_LoginInfoInit(new_login_info_result, user_name_arg, tty_name_arg, errbuf) == 0) {
return(new_login_info_result) ;
}
else {
jr_free(new_login_info_result) ;
return(0) ;
}
}
void jr_LoginInfoUndo(login_info_ptr)
jr_LoginInfoType * login_info_ptr ;
{
if (login_info_ptr->user_name) jr_free(login_info_ptr->user_name) ;
if (login_info_ptr->tty_name) jr_free(login_info_ptr->tty_name) ;
memset(login_info_ptr, 0, sizeof(*login_info_ptr)) ;
}
void jr_LoginInfoDestroy(login_info_ptr)
jr_LoginInfoType * login_info_ptr ;
{
jr_LoginInfoUndo(login_info_ptr) ;
jr_free(login_info_ptr) ;
}
#ifndef missing_utmp
#include <utmp.h>
jr_int jr_LoginInfoInit(login_info_ptr, user_name_arg, tty_name_arg, errbuf)
jr_LoginInfoType * login_info_ptr ;
const char * user_name_arg ;
const char * tty_name_arg ;
char * errbuf ;
{
struct utmp utmp ;
char * rfn = "/etc/utmp" ;
FILE * rfp ;
if ((rfp = fopen(rfn, "r")) == NULL) {
jr_esprintf (errbuf, "couldn't open '%.32s' for reading", rfn) ;
return(-1) ;
}
/* look in utmp file for information */
login_info_ptr->total_number_of_users = 0 ;
login_info_ptr->number_of_logins = 0 ;
login_info_ptr->tty_name = 0 ;
login_info_ptr->user_name = jr_strdup(user_name_arg) ;
while (fread((char *)&utmp, sizeof(utmp), 1, rfp) == 1) {
if(utmp.ut_name[0] == '\0') {
continue; /* null entries are people who logged out */
}
login_info_ptr->total_number_of_users++ ;
if (strcmp(login_info_ptr->user_name, utmp.ut_name) == 0) {
char * tty_letters_from_arg ;
char * tty_letters_from_utmp ;
login_info_ptr->number_of_logins++ ;
tty_letters_from_arg = jr_TTY_LettersFromDeviceName((char *) tty_name_arg) ;
tty_letters_from_utmp = jr_TTY_LettersFromDeviceName((char *) utmp.ut_line) ;
if (strcmp(tty_letters_from_arg, tty_letters_from_utmp) == 0) {
/* make sure the person logged in is both the user
and has the right terminal before saying that
he is still logged in */
login_info_ptr->tty_name = jr_strdup(tty_name_arg) ;
}
}
}
fclose(rfp) ;
return(0) ;
}
#else
jr_int jr_LoginInfoInit(login_info_ptr, user_name, tty_name)
jr_LoginInfoType * login_info_ptr ;
const char * user_name_arg ;
const char * tty_name_arg ;
{
login_info_ptr->total_number_of_users = 1 ;
login_info_ptr->number_of_logins = 1 ;
login_info_ptr->tty_name = jr_strdup("console") ;
login_info_ptr->user_name = jr_strdup(user_name_arg) ;
return(0) ;
}
#endif
|
frankjas/libjr
|
libjr/string/strnchr.c
|
#include "ezport.h"
#include "jr/string.h"
char *jr_strnchr (
const char * str,
jr_int c,
jr_int len)
{
jr_int q;
for (q=0; str[q] && q < len; q++) {
if (str[q] == c) {
return (char *) str + q;
}
}
return 0;
}
char *jr_rstrchr (
const char * end_str,
const char * str,
jr_int c)
{
for (; end_str >= str; end_str--) {
if (*end_str == c) {
return (char *) end_str;
}
}
return 0;
}
|
frankjas/libjr
|
include/jr/malloc.h
|
<gh_stars>0
#ifndef _jr_malloch
#define _jr_malloch
#include "ezport.h"
#include <stdio.h> /* required for args to jr_MallocStatPrint */
jr_EXTERN(void *) jr_malloc PROTO ((size_t amt_requested)) ;
jr_EXTERN(void *) jr_calloc PROTO ((size_t num_elem, size_t elem_size)) ;
#if defined (realloc) || defined (free) || defined (jr_redefined_malloc)
/*
* 'realloc' was most likely defined as 'jr_realloc', so the 'const' pointer declaration
* conflicts with the standard libraries definition
*/
jr_EXTERN(void *) jr_realloc PROTO ((void *old_ptr, size_t new_size)) ;
jr_EXTERN(void) jr_free PROTO ((void *mptr)) ;
#else
jr_EXTERN(void *) jr_realloc PROTO ((const void *old_ptr, size_t new_size)) ;
jr_EXTERN(void) jr_free PROTO ((const void *mptr)) ;
#endif
jr_EXTERN(char *) jr_strdup PROTO ((const char *str));
jr_EXTERN(char *) jr_strndup PROTO ((const char *str, size_t max_length));
jr_EXTERN(void *) jr_memdup PROTO ((const void *, size_t)) ;
jr_EXTERN(void) jr_exit (jr_int status);
jr_EXTERN(void) jr_exit_set_program_name (const char *program_name);
jr_EXTERN(const char *) jr_ProgramName;
extern size_t jr_malloc_usable_size PROTO ((const void *mptr, size_t amt_requested));
extern void jr_malloc_good_size PROTO ((size_t new_size));
extern void jr_malloc_stats PROTO ((FILE *wfp, char *message)) ;
extern void jr_malloc_dump PROTO ((void));
extern const char * jr_malloc_type PROTO ((const void *ptr));
extern jr_int jr_malloc_check_leaks_and_bounds PROTO ((char *error_buf));
extern jr_int jr_malloc_num_open_files PROTO ((FILE *opt_wfp, char *error_buf));
extern const void * jr_malloc_check_bounds PROTO ((char *error_buf));
extern void jr_malloc_make_trap_file PROTO ((const void *pointer));
extern int jr_malloc_is_trap_ptr (const void *mptr);
extern void jr_malloc_reset_calls PROTO ((void));
extern void jr_malloc_reset_stats PROTO ((void));
jr_EXTERN(void) jr_malloc_set_bounds_marker_multiple PROTO ((
jr_int bounds_marker_multiple
));
extern void jr_malloc_set_no_memory_handler (
void (*handler_fn) (size_t));
extern unsigned jr_int jr_malloc_max_request_size (void);
jr_EXTERN(void) jr_malloc_set_max_request_size (unsigned jr_int v);
extern jr_int jr_malloc_has_clear_on_free (void);
jr_EXTERN(void) jr_malloc_set_clear_on_free (jr_int v);
extern unsigned jr_int jr_malloc_num_calls (void );
extern void jr_malloc_set_num_calls (unsigned jr_int v);
extern unsigned jr_int jr_malloc_num_unrecorded_calls (void);
/*
** 3/20/08: to correctly account for C++ dynamic initialization of statics
** and globals, place a call to:
**
** jr_malloc_begin_cpp_trans_unit()
**
** at the top of every C++ translation unit that performs dynamic
** allocation as part of static/global object construction.
** For dynamically loaded translations units, call:
**
** jr_malloc_end_cpp_trans_unit()
**
** after all static/global variable declarations.
**
** Then calls to jr_malloc_dump(), and jr_malloc_check_leaks_and_bounds()
** will be delayed until the last C++ translation unit has been deconstructed.
**
*/
#define jr_malloc_begin_cpp_trans_unit() \
class jr_malloc_cpp_begin_trans_unit_t { \
public : \
jr_malloc_cpp_begin_trans_unit_t () \
{ \
jr_malloc_begin_cpp_trans_unit_constructor (); \
} \
~jr_malloc_cpp_begin_trans_unit_t () \
{ \
jr_malloc_begin_cpp_trans_unit_destructor (); \
} \
}; \
static jr_malloc_cpp_begin_trans_unit_t jr_MallocCppBeginTransUnit \
#define jr_malloc_end_cpp_trans_unit() \
class jr_malloc_cpp_end_trans_unit_t { \
public : \
jr_malloc_cpp_end_trans_unit_t () \
{ \
jr_malloc_end_cpp_trans_unit_constructor (); \
} \
}; \
static jr_malloc_cpp_end_trans_unit_t jr_MallocCppEndTransUnit \
jr_EXTERN(void) jr_malloc_begin_cpp_main();
jr_EXTERN(void) jr_malloc_begin_cpp_trans_unit_constructor ();
jr_EXTERN(void) jr_malloc_begin_cpp_trans_unit_destructor ();
jr_EXTERN(void) jr_malloc_end_cpp_trans_unit_constructor ();
jr_EXTERN(jr_int) jr_malloc_num_cpp_trans_units();
jr_EXTERN(jr_int) jr_malloc_dump_was_called();
#ifndef jr_MALLOC_NO_MEMORY_EXCEPTION
# define jr_MALLOC_NO_MEMORY_EXCEPTION "jr_malloc:no memory"
#endif
#ifndef jr_MALLOC_TRAP_FILE_NAME
# define jr_MALLOC_TRAP_FILE_NAME "trap.jr_mem"
#endif
#ifndef jr_MALLOC_TRACE_FILE_NAME
# define jr_MALLOC_TRACE_FILE_NAME "trace.jr_mem"
#endif
#ifndef jr_MALLOC_DEFAULT_MAX_REQUEST
# define jr_MALLOC_DEFAULT_MAX_REQUEST jr_UINT_MAX
#endif
#ifndef jr_MALLOC_MAX_LEAK_TRAP_PRINT
# define jr_MALLOC_MAX_LEAK_TRAP_PRINT 20
#endif
#ifndef jr_MALLOC_BEGIN_CPP_INIT_VALUE
# define jr_MALLOC_BEGIN_CPP_INIT_VALUE 0
#endif
/*
** 3/23/07: The following should be converted to use a function call-based API
** to avoid MS DLL export/import issues.
*/
extern jr_int jr_MallocOtherResourceLeak;
extern jr_int jr_MallocMaxPrintBucketVar;
extern char * jr_MallocTrapFileName;
extern char * jr_MallocTraceFileName;
extern unsigned jr_int jr_MallocSuffixBoundsMarkerMultiple;
extern unsigned jr_int jr_MallocPrefixBoundsMarkerMultiple;
extern jr_int jr_MallocMaxLeakTrapPrint;
extern size_t jr_MallocBytesInUse;
extern size_t jr_MallocMaxBytesInUse;
extern void (*jr_MallocNoMemoryHandler) (size_t);
extern jr_int jr_MallocCalledByNew;
jr_EXTERN(jr_int) jr_MallocRecordPtrsOnly;
#define jr_malloc_bytes_in_use() (jr_MallocBytesInUse)
#define jr_malloc_max_bytes_in_use() (jr_MallocMaxBytesInUse)
#define jr_malloc_max_leak_trap_print() (jr_MallocMaxLeakTrapPrint)
#define jr_malloc_has_resource_leak() (jr_MallocOtherResourceLeak)
#define jr_malloc_max_print_bucket() (jr_MallocMaxPrintBucketVar)
#define jr_malloc_called_by_new() (jr_MallocCalledByNew)
#define jr_malloc_set_trap_file_name(str) (jr_MallocTrapFileName = (str))
#define jr_malloc_set_trace_file_name(str) (jr_MallocTraceFileName = (str))
#define jr_malloc_set_resource_leak() (jr_MallocOtherResourceLeak = 1)
#define jr_malloc_clear_resource_leak() (jr_MallocOtherResourceLeak = 0)
#define jr_malloc_set_max_leak_trap_print(v) (jr_MallocMaxLeakTrapPrint = (v))
#define jr_malloc_no_memory_handler() (jr_MallocNoMemoryHandler)
#define jr_malloc_set_max_print_bucket(v) (jr_MallocMaxPrintBucketVar = (v))
#define jr_malloc_set_called_by_new(v) (jr_MallocCalledByNew = (v) != 0)
#endif
|
frankjas/libjr
|
libjr/misc/geometry.c
|
<reponame>frankjas/libjr<filename>libjr/misc/geometry.c
#include "ezport.h"
#include <math.h>
#include <stdio.h>
#include "jr/misc.h"
#include "jr/math.h"
/*
-225deg | Q1
135deg |
(-10, 10) |
* | * (10, 10) 45deg counter-clockwise
| -265deg clockwise
Q2 |
|
-----------------------------
Q3 |
|
|
* | * (10, -10) -45deg
(-10, -10) | 265deg
-135deg |
225deg | Q4
*/
int jr_PointQuadrant(x, y)
double x ;
double y ;
{
if (y > 0) {
if (x > 0) return(1) ;
else return(2) ;
}
else {
if (x > 0) return(4) ;
else return(3) ;
}
}
double jr_PointDistance(x1, y1, x2, y2)
double x1 ;
double y1 ;
double x2 ;
double y2 ;
{
double distance ;
distance = sqrt(
((x1 - x2) * (x1 - x2)) +
((y1 - y2) * (y1 - y2))
) ;
return(distance) ;
}
double jr_PointAngleInRadians(x1, y1, x2, y2)
double x1 ;
double y1 ;
double x2 ;
double y2 ;
{
double angle_in_radians ;
double x, y ;
jr_int quadrant ;
x = fabs(x2 - x1) ;
y = fabs(y2 - y1) ;
angle_in_radians = atan2(y, x) ;
quadrant = jr_PointQuadrant(x2 - x1, y2 - y1) ;
switch(quadrant) {
case 1 : {
/* angle_in_radians ; unchanged */
break ;
}
case 2 : {
angle_in_radians = jr_PI - angle_in_radians ;
break ;
}
case 3 : {
angle_in_radians = jr_PI + angle_in_radians ;
break ;
}
case 4 : {
angle_in_radians = 2 * jr_PI - angle_in_radians ;
break ;
}
}
return(angle_in_radians) ;
}
double jr_PointAngleInDegrees(x1, y1, x2, y2)
double x1 ;
double y1 ;
double x2 ;
double y2 ;
{
double angle_in_radians ;
angle_in_radians = jr_PointAngleInRadians(x1,y1,x2,y2) ;
return(jr_RadiansToDegrees(angle_in_radians)) ;
}
double jr_DegreesToRadians(degrees)
double degrees ;
{
double radians ;
radians = jr_PI / 180 * degrees ;
return (radians);
}
double jr_RadiansToDegrees(radians)
double radians ;
{
double degrees ;
degrees = 180 / jr_PI * radians ;
return(degrees) ;
}
/*
void main()
{
double angle_in_radians ;
double angle_in_degrees ;
angle_in_radians = jr_PointAngleRadians(0.0, 0.0, 3.0, 4.0) ;
angle_in_degrees = jr_RadiansToDegrees(angle_in_radians) ;
fprintf(stdout, "Q0 angle(0,0,3,4) == %lg\n", angle_in_degrees) ;
angle_in_radians = jr_PointAngleRadians(0.0, 0.0, -3.0, 4.0) ;
angle_in_degrees = jr_RadiansToDegrees(angle_in_radians) ;
fprintf(stdout, "Q1 angle(0,0,-3,4) == %lg\n", angle_in_degrees) ;
angle_in_radians = jr_PointAngleRadians(0.0, 0.0, -3.0, -4.0) ;
angle_in_degrees = jr_RadiansToDegrees(angle_in_radians) ;
fprintf(stdout, "Q2 angle(0,0,-3,-4) == %lg\n", angle_in_degrees) ;
angle_in_radians = jr_PointAngleRadians(0.0, 0.0, 3.0, -4.0) ;
angle_in_degrees = jr_RadiansToDegrees(angle_in_radians) ;
fprintf(stdout, "Q3 angle(0,0,3,-4) == %lg\n", angle_in_degrees) ;
}
*/
|
frankjas/libjr
|
libjr/string/vector.c
|
#include "ezport.h"
#include <stdio.h>
#include "jr/vector.h"
#include "jr/malloc.h"
void * jr_VectorCreateWithOneItem (zeroth_item_value)
const void * zeroth_item_value;
{
void ** new_vector;
new_vector = (void **) jr_malloc (2 * sizeof (void *));
new_vector[0] = (void *) zeroth_item_value;
new_vector[1] = 0;
return ((void *)new_vector);
}
void * jr_VectorCreateFromVectorAndItem(source_vector_arg, source_item)
void * source_vector_arg ;
void * source_item ;
{
void ** source_vector = source_vector_arg ;
jr_int source_vector_size ;
jr_int target_vector_size ;
void ** target_vector ;
jr_int i ;
source_vector_size = jr_VectorLength(source_vector_arg) ;
target_vector_size = source_vector_size + 1 ;
target_vector = jr_malloc((target_vector_size + 1) * sizeof(void *)) ;
for (i= 0 ; source_vector[i] ; i++) {
target_vector[i] = source_vector[i] ;
}
target_vector[i] = source_item ;
i++ ;
target_vector[i] = 0 ;
return((void *) target_vector) ;
}
void jr_VectorDestroy (vector_arg)
const void * vector_arg ;
{
jr_VectorUndo (vector_arg);
jr_free(vector_arg) ;
}
void jr_VectorUndo(vector_arg)
const void * vector_arg;
{
const void ** vp ;
for (vp = (void *)vector_arg; *vp; vp++) {
jr_free (*vp) ;
}
}
jr_int jr_VectorLength (vector_arg)
const void * vector_arg;
{
const void ** vp = (const void **) vector_arg ;
jr_int dimen = 0;
while ( *vp++ ) dimen++;
return (dimen);
}
void *jr_VectorDup(vector_arg, savefunc)
const void * vector_arg ;
void * (*savefunc)() ;
{
char ** source_vector = (char **) vector_arg ;
char ** target_vector ;
jr_int vector_length = jr_VectorLength(source_vector) ;
jr_int i ;
target_vector = (char **) jr_malloc((vector_length + 1) * sizeof(char *)) ;
for (i=0; source_vector[i]; i++) {
if (savefunc) {
target_vector[i] = (*savefunc)(source_vector[i]) ;
}
else {
target_vector[i] = source_vector[i] ;
}
}
target_vector[i] = 0 ;
return((void *)target_vector) ;
}
void jr_VectorConcatenate(target_vector_arg, source_vector_arg)
void * target_vector_arg ;
void * source_vector_arg ;
{
void ** target_vector = target_vector_arg ;
void ** source_vector = source_vector_arg ;
jr_int target_vector_size ;
jr_int i ;
target_vector_size = jr_VectorLength(target_vector) ;
for (i= 0 ; source_vector[i] ; i++) {
target_vector[target_vector_size + i] = source_vector[i] ;
}
target_vector[target_vector_size + i] = 0 ;
}
jr_int jr_VectorFindMaximum(void_vector_arg, n, maxfunc)
const void * void_vector_arg ;
jr_int n ;
jr_int (*maxfunc)() ;
{
void ** vector_arg = (void **) void_vector_arg ;
jr_int max_so_far = 0 ;
jr_int current_value ;
jr_int i ;
for (i = 0 ; i < n; i++) {
current_value = (*maxfunc)(vector_arg[i]) ;
if (current_value > max_so_far) {
max_so_far = current_value ;
}
}
return(max_so_far) ;
}
|
frankjas/libjr
|
libjr/struct/strtab.h
|
<filename>libjr/struct/strtab.h
#ifndef __strtab_h___
#define __strtab_h___
#define _POSIX_SOURCE 1
#include "ezport.h"
#include <assert.h>
#include "jr/strtab.h"
#include "jr/string.h"
#include "jr/misc.h"
#include "jr/malloc.h"
extern void jr_StringTableEntryInit PROTO ((
jr_StringTableEntryType * str_entry_ptr,
const char * string
));
extern void jr_StringTableEntryUndo PROTO ((
jr_StringTableEntryType * str_entry_ptr
));
extern jr_int jr_StringTableEntryCmp PROTO ((
const void * void_ptr_1,
const void * void_ptr_2
));
extern jr_int jr_StringTableEntryHash PROTO ((
const void * void_ptr
));
#endif
|
frankjas/libjr
|
libjr/misc/cmpint.c
|
<gh_stars>0
#include "ezport.h"
#include "jr/misc.h"
jr_int jr_intcmp(n,m)
jr_int n, m ;
{
if (n < 0 && m > 0) {
return -1;
}
if (n > 0 && m < 0) {
return 1;
}
return((n)-(m)) ;
}
jr_int jr_intpcmp (void_arg_1, void_arg_2)
const void * void_arg_1;
const void * void_arg_2;
{
const jr_int * np = void_arg_1;
const jr_int * mp = void_arg_2;
if (*np < 0 && *mp > 0) {
return -1;
}
if (*np > 0 && *mp < 0) {
return 1;
}
return((*np)-(*mp)) ;
}
jr_int jr_rintcmp(n,m)
jr_int n, m ;
{
if (n < 0 && m > 0) {
return 1;
}
if (n > 0 && m < 0) {
return -1;
}
return((m)-(n)) ;
}
jr_int jr_rintpcmp(np,mp)
const jr_int *np ;
const jr_int *mp ;
{
if (*np < 0 && *mp > 0) {
return 1;
}
if (*np > 0 && *mp < 0) {
return -1;
}
return((*mp)-(*np)) ;
}
jr_int jr_posintpcmp(np,mp)
const jr_int *np ;
const jr_int *mp ;
{
if ((! *np) && (! *mp)) return(0) ;
if (! *np) return(1) ;
if (! *mp) return(-1) ;
return((*np)-(*mp)) ;
}
jr_int jr_posintcmp(n,m)
jr_int n,m ;
{
if ((! n) && (! m)) return(0) ;
if (! n) return(1) ;
if (! m) return(-1) ;
return(n-m) ;
}
|
frankjas/libjr
|
libjr/string/isident.c
|
<filename>libjr/string/isident.c
#include "ezport.h"
#include "jr/string.h"
jr_int jr_StringIsValidIdentifier (str)
const char * str;
{
/*
* first character must be alphabetic or underscore
*/
if ((!isalpha(*str)) && (*str != '_')) {
return (0);
}
str++;
for (; *str; str++) {
if (!isalnum(*str) && *str != '_') {
return (0);
}
}
return (1);
}
|
frankjas/libjr
|
include/jr/circbuf.h
|
<filename>include/jr/circbuf.h
#ifndef __CIRCBUF_HEADER__
#define __CIRCBUF_HEADER__
#include "ezport.h"
typedef struct {
char *element_array;
char *head;
char *tail;
jr_int size;
jr_int num_elements;
jr_int max_size;
jr_int element_size;
} jr_CB_CircularBuffer;
extern void jr_CB_CircularBufferInit PROTO((jr_CB_CircularBuffer *buffer,
jr_int max_elements, jr_int element_size));
extern void jr_CB_CircularBufferUndo PROTO((jr_CB_CircularBuffer *buffer));
extern void jr_CB_CircularBufferReset PROTO((jr_CB_CircularBuffer *buffer));
extern void jr_CB_GetTail PROTO((jr_CB_CircularBuffer *buffer, void *element));
extern void jr_CB_GetHead PROTO((jr_CB_CircularBuffer *buffer, void *element));
extern void *jr_CB_SetNewTail PROTO((jr_CB_CircularBuffer *buffer,
void *element, void *bumped_element));
extern void *jr_CB_SetNewHead PROTO((jr_CB_CircularBuffer *buffer,
void *element, void *bumped_element));
extern void *jr_CB_ElementPtr PROTO((jr_CB_CircularBuffer *buffer, jr_int i));
extern void Getjr_CB_ElementPtr PROTO((jr_CB_CircularBuffer *buffer, jr_int i, void *element));
#define jr_CB_CircularBufferSize(buffer) ((buffer)->num_elements)
/* if the buffer is full, this doesn't loop at all
#define jr_CB_ForEachElementPtr(buffer, ptr) \
for ( (ptr) = (void *) (buffer)->head; \
(void *) (ptr) != (void *) (buffer)->tail; \
(ptr) = (void*) ((char *) (ptr) + (buffer)->element_size), \
(char *) (ptr) == (buffer)->element_array + (buffer)->max_size ? \
(ptr) = (void *) (buffer)->element_array : 0)
*/
#define jr_CB_ForEachElementIndex(buffer, i) \
for ((i)=0; (i) < (buffer)->num_elements; (i)++)
#endif
|
frankjas/libjr
|
libjr/string/ctlstrc.c
|
<reponame>frankjas/libjr<filename>libjr/string/ctlstrc.c<gh_stars>0
#include "ezport.h"
#include <string.h>
#include "jr/string.h"
const char * jr_EscapedStringFromControlChar(c)
jr_int c ;
{
static char buf[16] ;
char * escape_string ;
escape_string = buf ;
switch(c) {
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 : {
if ((c < 32) || (c >= 127)) {
sprintf(buf, "\\%#04o", c) ;
}
else {
buf[0] = c ;
buf[1] = 0 ;
}
break ;
}
}
return escape_string ;
}
const char * jr_StringFromControlChar(c)
jr_int c ;
{
static char buf[16] ;
if (c < 32) {
sprintf(buf, "^%c", c + 'A' - 1) ;
}
else if (c == 127) {
sprintf(buf, "^?") ;
}
else if (c > 127) {
sprintf(buf, "\\%#04o", c) ;
}
else {
sprintf(buf, "%c", c) ;
}
return buf ;
}
/*
void main()
{
char * result ;
jr_int char_val = '\f' ;
result = jr_StringFromControlChar(char_val) ;
fprintf(stdout, "jr_StringFromControlChar('\%#03o') == '%s'\n",
char_val,
result
) ;
}
*/
|
frankjas/libjr
|
libjr/syscalls/jr_pool.c
|
#include "ezport.h"
#include <apr-1/apr_pools.h>
#include "jr/apr.h"
#include "jr/malloc.h"
void jr_pool_init (
jr_pool_t * pool_ptr,
jr_pool_t * opt_parent_pool_ptr)
{
memset (pool_ptr, 0, sizeof (*pool_ptr));
pool_ptr->parent_pool_ptr = opt_parent_pool_ptr;
jr_apr_initialize();
}
void jr_pool_undo (
jr_pool_t * pool_ptr)
{
if (pool_ptr->apr_pool_ptr) {
/*
** 5/13/08: If there's no pool, there's either no apr_file_ptr or it's the write
** of a pipe, which will be closed when the parent pipe is closed.
*/
apr_pool_destroy (pool_ptr->apr_pool_ptr);
}
}
jr_pool_t *jr_pool_create(
jr_pool_t * opt_parent_pool_ptr)
{
jr_pool_t * pool_ptr;
if (opt_parent_pool_ptr) {
pool_ptr = jr_pool_alloc( opt_parent_pool_ptr, sizeof(*pool_ptr));
}
else {
pool_ptr = jr_malloc( sizeof(*pool_ptr));
}
jr_pool_init( pool_ptr, opt_parent_pool_ptr);
return pool_ptr;
}
void jr_pool_destroy (
jr_pool_t * pool_ptr)
{
jr_pool_t * parent_pool_ptr = pool_ptr->parent_pool_ptr;
jr_pool_undo( pool_ptr);
if (parent_pool_ptr == 0) {
jr_free( pool_ptr);
}
}
void *jr_pool_alloc(
jr_pool_t * pool_ptr,
size_t mem_size)
{
jr_int status;
if (pool_ptr->apr_pool_ptr == 0) {
status = apr_pool_create(
(apr_pool_t **) &pool_ptr->apr_pool_ptr, (apr_pool_t *) pool_ptr->parent_pool_ptr
);
if (status != 0) {
return 0;
}
}
return apr_palloc( pool_ptr->apr_pool_ptr, mem_size);
}
char *jr_pool_strdup(
jr_pool_t * pool_ptr,
const char * src_str)
{
char * new_str = jr_pool_alloc( pool_ptr, strlen( src_str) + 1);
jr_int z;
if (new_str == 0) {
return 0;
}
for (z=0; src_str[z] != 0; z++) {
new_str[z] = src_str[z];
}
new_str[z] = 0;
return new_str;
}
|
frankjas/libjr
|
libjr/syscalls/jr_socket.c
|
<filename>libjr/syscalls/jr_socket.c
#include "ezport.h"
#include <string.h>
#include <apr-1/apr_pools.h>
#include <apr-1/apr_network_io.h>
#include <apr-1/apr_lib.h>
#include <apr-1/apr_portable.h>
#include "jr/apr.h"
#include "jr/error.h"
#include "jr/malloc.h"
#include "jr/misc.h"
#include "jr/nettype.h"
extern void jr_sockaddr_set_pool (
jr_sockaddr_t * sockaddr_info,
void * apr_pool_ptr);
extern jr_int jr_sockaddr_init_pool (
jr_sockaddr_t * sockaddr_info,
char * error_buf);
extern jr_int jr_sockaddr_reset (
jr_sockaddr_t * sockaddr_info,
char * error_buf);
extern jr_int jr_sockaddr_alloc (
jr_sockaddr_t * sockaddr_info,
char * error_buf);
void jr_socket_init (
jr_socket_t * socket_info,
jr_int socket_type)
{
memset (socket_info, 0, sizeof (jr_socket_t));
socket_info->socket_type = socket_type;
jr_apr_initialize();
}
void jr_socket_undo (
jr_socket_t * socket_info)
{
if (socket_info->apr_socket_ptr) {
apr_socket_close (socket_info->apr_socket_ptr);
}
if (socket_info->apr_pool_ptr) {
apr_pool_destroy (socket_info->apr_pool_ptr);
}
if (socket_info->aprbuf_ptr) {
jr_aprbuf_destroy (socket_info->aprbuf_ptr);
}
}
jr_socket_t *jr_socket_create (
jr_int socket_type)
{
jr_socket_t * socket_info = jr_malloc (sizeof (*socket_info));
jr_socket_init (socket_info, socket_type);
return socket_info;
}
void jr_socket_destroy (
jr_socket_t * socket_info)
{
jr_socket_undo (socket_info);
jr_free (socket_info);
}
jr_int jr_socket_is_open(
jr_socket_t * socket_info)
{
if (socket_info->apr_socket_ptr) {
return 1;
}
return 0;
}
jr_int jr_socket_init_pool (
jr_socket_t * socket_info,
char * error_buf)
{
jr_int status;
if (socket_info->apr_pool_ptr == 0) {
status = apr_pool_create ((apr_pool_t **) &socket_info->apr_pool_ptr, NULL);
if (status != 0) {
jr_esprintf (error_buf, "couldn't create pool: %s",
jr_apr_strerror( status, error_buf)
);
status = jr_ConvertAprErrno (status);
goto return_status;
}
}
status = 0;
return_status : {
}
return status;
}
void jr_sockaddr_init (
jr_sockaddr_t * sockaddr_info)
{
memset (sockaddr_info, 0, sizeof (jr_sockaddr_t));
jr_apr_initialize();
}
void jr_sockaddr_undo (
jr_sockaddr_t * sockaddr_info)
{
if (sockaddr_info->apr_pool_ptr && !sockaddr_info->has_borrowed_pool) {
apr_pool_destroy (sockaddr_info->apr_pool_ptr);
}
}
void jr_sockaddr_set_pool (
jr_sockaddr_t * sockaddr_info,
void * apr_pool_ptr)
{
if (sockaddr_info->apr_pool_ptr && !sockaddr_info->has_borrowed_pool) {
apr_pool_destroy (sockaddr_info->apr_pool_ptr);
}
sockaddr_info->apr_pool_ptr = apr_pool_ptr;
sockaddr_info->has_borrowed_pool = 1;
}
jr_int jr_sockaddr_init_pool (
jr_sockaddr_t * sockaddr_info,
char * error_buf)
{
jr_int status;
if (sockaddr_info->apr_pool_ptr == 0) {
status = apr_pool_create ((apr_pool_t **) &sockaddr_info->apr_pool_ptr, NULL);
if (status != 0) {
jr_esprintf (error_buf, "couldn't create pool: %s",
jr_apr_strerror( status, error_buf)
);
status = jr_ConvertAprErrno (status);
goto return_status;
}
}
status = 0;
return_status : {
}
return status;
}
jr_int jr_sockaddr_reset (
jr_sockaddr_t * sockaddr_info,
char * error_buf)
{
apr_pool_t * borrowed_pool_ptr = 0;
jr_int status;
if (sockaddr_info->has_borrowed_pool) {
borrowed_pool_ptr = sockaddr_info->apr_pool_ptr;
}
jr_sockaddr_undo( sockaddr_info);
jr_sockaddr_init( sockaddr_info);
if (borrowed_pool_ptr) {
jr_sockaddr_set_pool( sockaddr_info, borrowed_pool_ptr);
}
else {
status = jr_sockaddr_init_pool( sockaddr_info, error_buf);
if (status != 0) {
goto return_status;
}
}
sockaddr_info->apr_sockaddr_ptr = 0;
status = 0;
return_status : {
}
return status;
}
jr_int jr_sockaddr_alloc (
jr_sockaddr_t * sockaddr_info,
char * error_buf)
{
jr_int status;
status = jr_sockaddr_reset( sockaddr_info, error_buf);
if (status != 0) {
goto return_status;
}
sockaddr_info->apr_sockaddr_ptr = apr_palloc( sockaddr_info->apr_pool_ptr, sizeof (apr_sockaddr_t));
status = 0;
return_status : {
}
return status;
}
jr_int jr_sockaddr_lookup (
jr_sockaddr_t * sockaddr_info,
const char * host_name,
jr_int port_number,
char * error_buf)
{
jr_int addr_family = APR_INET;
jr_int status;
status = jr_sockaddr_reset( sockaddr_info, error_buf);
if (status != 0) {
goto return_status;
}
if (host_name == 0 || strcmp (host_name, "0.0.0.0") == 0) {
host_name = 0;
}
status = apr_sockaddr_info_get (
(apr_sockaddr_t **) &sockaddr_info->apr_sockaddr_ptr,
host_name,
addr_family,
port_number,
0, /* 2/23/05: could be: APR_IPV4_ADDR_OK */
sockaddr_info->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 : {
}
return status;
}
jr_sockaddr_t *jr_sockaddr_init_foreach (
jr_sockaddr_t * sockaddr_info)
{
jr_sockaddr_t * curr_sockaddr_ptr = sockaddr_info;
jr_sockaddr_t * next_sockaddr_ptr;
apr_sockaddr_t * next_apr_sockaddr_ptr;
for ( next_apr_sockaddr_ptr = ((apr_sockaddr_t *)sockaddr_info->apr_sockaddr_ptr)->next;
next_apr_sockaddr_ptr;
next_apr_sockaddr_ptr = next_apr_sockaddr_ptr->next
) {
next_sockaddr_ptr = apr_palloc( sockaddr_info->apr_pool_ptr, sizeof (jr_sockaddr_t));
jr_sockaddr_init( next_sockaddr_ptr);
jr_sockaddr_set_pool( next_sockaddr_ptr, sockaddr_info->apr_pool_ptr);
next_sockaddr_ptr->apr_sockaddr_ptr = next_apr_sockaddr_ptr;
curr_sockaddr_ptr->next_sockaddr_ptr = next_sockaddr_ptr;
curr_sockaddr_ptr = next_sockaddr_ptr;
}
return sockaddr_info;
}
jr_int jr_sockaddr_dup (
const jr_sockaddr_t * src_sockaddr_info,
jr_sockaddr_t * dest_sockaddr_info,
char * error_buf)
{
jr_int status;
status = jr_sockaddr_alloc( dest_sockaddr_info, error_buf);
if (status != 0) {
/*
** 2-18-2013: fails if no pool can be allocated.
*/
return status;
}
apr_sockaddr_dup(
(apr_sockaddr_t *)src_sockaddr_info->apr_sockaddr_ptr,
(apr_sockaddr_t *)dest_sockaddr_info->apr_sockaddr_ptr
);
return 0;
}
jr_int jr_sockaddr_cmp (
const jr_sockaddr_t * sockaddr_info_1,
const jr_sockaddr_t * sockaddr_info_2)
{
jr_int is_equal;
jr_int port_1;
jr_int port_2;
is_equal = apr_sockaddr_equal(
(apr_sockaddr_t *) sockaddr_info_1->apr_sockaddr_ptr,
(apr_sockaddr_t *) sockaddr_info_2->apr_sockaddr_ptr
);
if (!is_equal) {
return 1;
}
port_1 = jr_sockaddr_port( sockaddr_info_1);
port_2 = jr_sockaddr_port( sockaddr_info_1);
if (port_1 < port_2) {
return -1;
}
if (port_1 > port_2) {
return 1;
}
return 0;
}
void *jr_sockaddr_ipaddr_ptr (
const jr_sockaddr_t * sockaddr_info)
{
return ((apr_sockaddr_t *) sockaddr_info->apr_sockaddr_ptr)->ipaddr_ptr;
}
jr_int jr_sockaddr_ipaddr_len (
const jr_sockaddr_t * sockaddr_info)
{
return ((apr_sockaddr_t *) sockaddr_info->apr_sockaddr_ptr)->ipaddr_len;
}
jr_int jr_sockaddr_port (
const jr_sockaddr_t * sockaddr_info)
{
return ((apr_sockaddr_t *) sockaddr_info->apr_sockaddr_ptr)->port;
}
jr_int jr_sockaddr_network_number(
const jr_sockaddr_t * sockaddr_info)
{
return jr_inet_network_number( *(unsigned jr_int *) jr_sockaddr_ipaddr_ptr( sockaddr_info));
}
jr_int jr_sockaddr_host_number(
const jr_sockaddr_t * sockaddr_info)
{
return jr_inet_host_number( *(unsigned jr_int *) jr_sockaddr_ipaddr_ptr( sockaddr_info));
}
jr_int jr_sockaddr_ip_cmp (
const jr_sockaddr_t * sockaddr_info_1,
const jr_sockaddr_t * sockaddr_info_2)
{
jr_int is_equal;
is_equal = apr_sockaddr_equal(
(apr_sockaddr_t *) sockaddr_info_1->apr_sockaddr_ptr,
(apr_sockaddr_t *) sockaddr_info_2->apr_sockaddr_ptr
);
if (!is_equal) {
return 1;
}
return 0;
}
const char *jr_sockaddr_get_ip_str (
jr_sockaddr_t * sockaddr_info)
{
jr_int status;
if (sockaddr_info->ip_str == 0) {
jr_int addr_str_len;
/*
** 2-18-2013: could also initialize a pool and ignore the failure case
*/
addr_str_len = ((apr_sockaddr_t *) sockaddr_info->apr_sockaddr_ptr)->addr_str_len;
sockaddr_info->ip_str = apr_palloc( sockaddr_info->apr_pool_ptr, addr_str_len);
status = apr_sockaddr_ip_getbuf(
(char *) sockaddr_info->ip_str,
addr_str_len,
(apr_sockaddr_t *) sockaddr_info->apr_sockaddr_ptr
);
if (status != 0) {
return "<unsupported address family>";
}
}
return sockaddr_info->ip_str;
}
jr_int jr_socket_open_generic (
jr_socket_t * socket_info,
jr_int opt_os_sock,
char * error_buf)
{
jr_int status;
jr_int apr_family = APR_INET;
jr_int apr_type;
jr_int apr_protocol = APR_UNSPEC;
status = jr_socket_init_pool( socket_info, error_buf);
if (status != 0) {
goto return_status;
}
switch (socket_info->socket_type) {
case jr_SOCK_STREAM : apr_type = SOCK_STREAM; break;
case jr_SOCK_DGRAM : apr_type = SOCK_DGRAM; break;
default : {
jr_esprintf (error_buf, "bad socket type %d", socket_info->socket_type);
status = jr_MISUSE_ERROR;
goto return_status;
}
}
if (opt_os_sock != jr_INVALID_OS_SOCKET) {
apr_os_sock_info_t os_sock_info[1];
apr_os_sock_t os_sock = opt_os_sock;
memset( os_sock_info, 0, sizeof( *os_sock_info));
os_sock_info->os_sock = &os_sock;
os_sock_info->family = apr_family;
os_sock_info->type = apr_type;
os_sock_info->protocol = apr_protocol;
status = apr_os_sock_make(
(apr_socket_t **) &socket_info->apr_socket_ptr,
os_sock_info,
socket_info->apr_pool_ptr
);
if (status != 0) {
jr_esprintf (error_buf, "%s", jr_apr_strerror( status, error_buf));
status = jr_ConvertAprErrno (status);
goto return_status;
}
}
else {
status = apr_socket_create (
(apr_socket_t **) &socket_info->apr_socket_ptr,
apr_family,
apr_type,
apr_protocol,
socket_info->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 : {
}
return status;
}
jr_int jr_socket_close (
jr_socket_t * socket_info,
char * error_buf)
{
jr_int status;
if (socket_info->aprbuf_ptr && jr_aprbuf_needs_flush (socket_info->aprbuf_ptr)) {
status = jr_socket_flush (socket_info, error_buf);
if (status != 0) {
goto return_status;
}
}
if (socket_info->apr_socket_ptr) {
status = apr_socket_close (socket_info->apr_socket_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 : {
if (socket_info->apr_pool_ptr) {
apr_pool_destroy (socket_info->apr_pool_ptr);
}
socket_info->apr_socket_ptr = 0;
socket_info->apr_pool_ptr = 0;
}
return status;
}
jr_int jr_socket_connect (
jr_socket_t * socket_info,
const char * host_name,
jr_int port_number,
char * error_buf)
{
jr_sockaddr_t sockaddr_info[1];
jr_int opened_socket = 0;
jr_int status;
jr_sockaddr_init (sockaddr_info);
if (socket_info->socket_type != jr_SOCK_STREAM) {
jr_esprintf (error_buf, "non-stream socket for connect()");
status = jr_MISUSE_ERROR;
goto return_status;
}
status = jr_sockaddr_lookup (sockaddr_info, host_name, port_number, error_buf);
if (status != 0) {
jr_esprintf (error_buf, "couldn't find host '%.32s': %s", host_name, error_buf);
goto return_status;
}
status = jr_socket_open (socket_info, error_buf);
if (status != 0) {
goto return_status;
}
else {
opened_socket = 1;
}
status = apr_socket_connect (
socket_info->apr_socket_ptr,
sockaddr_info->apr_sockaddr_ptr
);
if (status != 0) {
jr_esprintf (error_buf, "%s", jr_apr_strerror( status, error_buf));
status = jr_ConvertAprErrno (status);
goto return_status;
}
if (socket_info->is_nonblocking) {
/*
** 2/27/07: The default is blocking.
** 2/10/13: Set non-blocking after the connect since a blocking poll() on windows
** will hang on a non-blocking connect if there's no listener.
*/
status = jr_socket_set_nonblock (socket_info, 1, error_buf);
if (status != 0) {
goto return_status;
}
}
status = 0;
return_status : {
jr_sockaddr_undo (sockaddr_info);
if (status != 0 && opened_socket) {
jr_socket_close (socket_info, 0);
}
}
return status;
}
jr_int jr_socket_open_dgram (
jr_socket_t * socket_info,
const char * local_host_name,
jr_int port_number,
char * error_buf)
{
jr_int status;
status = jr_socket_offer_service( socket_info, local_host_name, port_number, error_buf);
if (status != 0) {
goto return_status;
}
status = 0;
return_status : {
}
return status;
}
jr_int jr_socket_offer_service (
jr_socket_t * socket_info,
const char * host_name,
jr_int port_number,
char * error_buf)
{
jr_sockaddr_t sockaddr_info[1];
jr_int opened_socket = 0;
jr_int status;
jr_sockaddr_init (sockaddr_info);
/*
** 2-22-2013: need to initialize the pool before borrowing it for the sockaddr.
*/
status = jr_socket_init_pool( socket_info, error_buf);
if (status != 0) {
jr_esprintf (error_buf, "couldn't init pool: %s", error_buf);
goto return_status;
}
jr_sockaddr_set_pool( sockaddr_info, socket_info->apr_pool_ptr);
/*
** 2-22-2013: use the socket's pool since apr_socket_bind() takes the
** apr_sockaddr_t and points to it.
*/
status = jr_sockaddr_lookup (sockaddr_info, host_name, port_number, error_buf);
if (status != 0) {
jr_esprintf (error_buf, "couldn't find host '%.32s': %s", host_name, error_buf);
goto return_status;
}
status = jr_socket_open (socket_info, error_buf);
if (status != 0) {
goto return_status;
}
else {
opened_socket = 1;
}
status = apr_socket_bind (
socket_info->apr_socket_ptr,
sockaddr_info->apr_sockaddr_ptr
);
if (status != 0) {
jr_esprintf (error_buf, "couldn't bind: %s", jr_apr_strerror( status, error_buf));
status = jr_ConvertAprErrno (status);
goto return_status;
}
if (socket_info->socket_type == jr_SOCK_STREAM) {
status = apr_socket_listen (socket_info->apr_socket_ptr, 3);
if (status != 0) {
jr_esprintf (error_buf, "couldn't set backlog: %s",
jr_apr_strerror( status, error_buf)
);
status = jr_ConvertAprErrno (status);
goto return_status;
}
}
if (socket_info->is_nonblocking) {
status = jr_socket_set_nonblock (socket_info, 1, error_buf);
if (status != 0) {
goto return_status;
}
}
status = 0;
return_status : {
jr_sockaddr_undo (sockaddr_info);
if (status != 0 && opened_socket) {
jr_socket_close (socket_info, 0);
}
}
return status;
}
jr_int jr_socket_accept (
jr_socket_t * accept_socket_info,
jr_socket_t * client_socket_info,
char * error_buf)
{
jr_int status;
if (accept_socket_info->socket_type != jr_SOCK_STREAM) {
jr_esprintf (error_buf, "non-stream accept socket for accept()");
status = jr_MISUSE_ERROR;
goto return_status;
}
if (client_socket_info->socket_type != jr_SOCK_STREAM) {
jr_esprintf (error_buf, "non-stream client socket for accept()");
status = jr_MISUSE_ERROR;
goto return_status;
}
status = jr_socket_init_pool( client_socket_info, error_buf);
if (status != 0) {
goto return_status;
}
status = apr_socket_accept (
(apr_socket_t **) &client_socket_info->apr_socket_ptr,
accept_socket_info->apr_socket_ptr,
client_socket_info->apr_pool_ptr
);
if (status != 0) {
jr_esprintf (error_buf, "%s", jr_apr_strerror( status, error_buf));
# ifdef ostype_winnt
{
status = jr_ConvertLastError (APR_TO_OS_ERROR(status));
}
# else
{
status = jr_ConvertErrno (APR_TO_OS_ERROR(status));
}
# endif
goto return_status;
}
status = 0;
return_status : {
}
return status;
}
jr_int jr_socket_shutdown (
jr_socket_t * socket_info,
char * error_buf)
{
jr_int status;
if (socket_info->aprbuf_ptr && jr_aprbuf_needs_flush (socket_info->aprbuf_ptr)) {
status = jr_socket_flush (socket_info, error_buf);
if (status != 0) {
goto return_status;
}
}
if (socket_info->apr_socket_ptr) {
status = apr_socket_shutdown (socket_info->apr_socket_ptr, APR_SHUTDOWN_READWRITE);
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 : {
}
return status;
}
jr_int jr_socket_set_nonblock (
jr_socket_t * socket_info,
jr_int value,
char * error_buf)
{
jr_int status;
socket_info->is_nonblocking = value != 0;
if (socket_info->apr_socket_ptr) {
if (socket_info->is_nonblocking) {
status = apr_socket_opt_set (socket_info->apr_socket_ptr, APR_SO_NONBLOCK, 1);
if (status != 0) {
jr_esprintf (error_buf, "%s", jr_apr_strerror( status, error_buf));
status = jr_ConvertAprErrno (status);
goto return_status;
}
status = apr_socket_timeout_set (socket_info->apr_socket_ptr, 0);
if (status != 0) {
jr_esprintf (error_buf, "%s", jr_apr_strerror( status, error_buf));
status = jr_ConvertAprErrno (status);
goto return_status;
}
}
else {
status = apr_socket_opt_set (socket_info->apr_socket_ptr, APR_SO_NONBLOCK, 0);
if (status != 0) {
jr_esprintf (error_buf, "%s", jr_apr_strerror( status, error_buf));
status = jr_ConvertAprErrno (status);
goto return_status;
}
status = apr_socket_timeout_set (socket_info->apr_socket_ptr, -1);
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 : {
}
return status;
}
jr_int jr_socket_port(
jr_socket_t * socket_info,
char * error_buf)
{
jr_int status;
apr_sockaddr_t * sockaddr_ptr;
status = apr_socket_addr_get( &sockaddr_ptr, APR_LOCAL, socket_info->apr_socket_ptr);
if (status != 0) {
jr_esprintf (error_buf, "%s", jr_apr_strerror( status, error_buf));
status = jr_ConvertAprErrno (status);
goto return_status;
}
status = sockaddr_ptr->port;
return_status : {
}
return status;
}
jr_int jr_socket_recv (
jr_socket_t * socket_info,
void * data_buf,
jr_int data_buf_len,
char * error_buf)
{
jr_int status;
apr_size_t apr_length = data_buf_len;
if (socket_info->socket_type != jr_SOCK_STREAM) {
jr_esprintf (error_buf, "socket type not 'stream'");
status = jr_MISUSE_ERROR;
goto return_status;
}
if (data_buf_len > jr_INT_MAX) {
jr_esprintf (error_buf, "recv length %d too large, max is %d", data_buf_len, jr_INT_MAX);
status = jr_MISUSE_ERROR;
goto return_status;
}
status = apr_socket_recv (
socket_info->apr_socket_ptr,
data_buf,
&apr_length
);
if (APR_STATUS_IS_EOF (status)) {
status = 0;
}
else if (status != 0) {
jr_esprintf (error_buf, "%s", jr_apr_strerror( status, error_buf));
status = jr_ConvertAprErrno (status);
goto return_status;
}
status = (jr_int) apr_length;
return_status : {
}
return status;
}
jr_int jr_socket_send (
jr_socket_t * socket_info,
const void * data_buf,
jr_int data_buf_len,
char * error_buf)
{
jr_int status;
apr_size_t apr_length = data_buf_len;
if (socket_info->socket_type != jr_SOCK_STREAM) {
jr_esprintf (error_buf, "socket type not 'stream'");
status = jr_MISUSE_ERROR;
goto return_status;
}
if (data_buf_len > jr_INT_MAX) {
jr_esprintf (error_buf, "send length %d too large, max is %d", data_buf_len, jr_INT_MAX);
status = jr_MISUSE_ERROR;
goto return_status;
}
if (socket_info->aprbuf_ptr && jr_aprbuf_needs_flush (socket_info->aprbuf_ptr)) {
/*
** 3/29/08: allow abitrary combinations of jr_socket_send() and jr_socket_printf()
*/
status = jr_socket_flush (socket_info, error_buf);
if (status != 0) {
goto return_status;
}
}
status = apr_socket_send (
socket_info->apr_socket_ptr,
data_buf,
&apr_length
);
if (status != 0) {
jr_esprintf (error_buf, "%s", jr_apr_strerror( status, error_buf));
status = jr_ConvertAprErrno (status);
goto return_status;
}
status = (jr_int) apr_length;
return_status : {
}
return status;
}
jr_int jr_socket_sendto_iov (
jr_socket_t * socket_info,
jr_sockaddr_t * sockaddr_info,
struct iovec * iov,
jr_int iovlen,
char * error_buf)
{
jr_int flags = 0;
jr_int status;
apr_size_t apr_length;
if (socket_info->socket_type == jr_SOCK_STREAM) {
if (socket_info->aprbuf_ptr && jr_aprbuf_needs_flush (socket_info->aprbuf_ptr)) {
/*
** 3/29/08: allow abitrary combinations of jr_socket_send() and jr_socket_printf()
*/
status = jr_socket_flush (socket_info, error_buf);
if (status != 0) {
goto return_status;
}
}
}
status = apr_socket_sendto_iov (
socket_info->apr_socket_ptr,
sockaddr_info->apr_sockaddr_ptr,
flags, iov, iovlen,
&apr_length
);
if (status != 0) {
jr_esprintf (error_buf, "%s", jr_apr_strerror( status, error_buf));
status = jr_ConvertAprErrno (status);
goto return_status;
}
status = (jr_int) apr_length;
return_status : {
}
return status;
}
jr_int jr_socket_recvfrom (
jr_socket_t * socket_info,
jr_sockaddr_t * sockaddr_info,
void * data_buf,
jr_int data_buf_len,
char * error_buf)
{
jr_int flags = 0;
jr_int status;
apr_size_t apr_length = data_buf_len;
if (socket_info->socket_type != jr_SOCK_DGRAM) {
jr_esprintf (error_buf, "socket type not 'dgram'");
status = jr_MISUSE_ERROR;
goto return_status;
}
status = jr_sockaddr_alloc( sockaddr_info, error_buf);
if (status != 0) {
goto return_status;
}
status = apr_socket_recvfrom (
sockaddr_info->apr_sockaddr_ptr,
socket_info->apr_socket_ptr,
flags,
data_buf,
&apr_length
);
if (status != 0) {
jr_esprintf (error_buf, "%s", jr_apr_strerror( status, error_buf));
status = jr_ConvertAprErrno (status);
goto return_status;
}
status = (jr_int) apr_length;
return_status : {
}
return status;
}
jr_int jr_socket_printf (
jr_socket_t * socket_info,
const char * control_string,
...)
{
va_list arg_list;
jr_int nbytes;
jr_int status;
va_start (arg_list, control_string);
if (socket_info->aprbuf_ptr == 0) {
socket_info->aprbuf_ptr = jr_aprbuf_create (
socket_info,
(jr_aprbuf_writefn_t) jr_socket_send,
jr_SOCKBUF_DEFAULT_SIZE
);
}
jr_aprbuf_set_error_buf (socket_info->aprbuf_ptr, 0);
if (socket_info->socket_type != jr_SOCK_STREAM) {
status = jr_MISUSE_ERROR;
goto return_status;
}
status = jr_aprbuf_vformatter ( socket_info->aprbuf_ptr, control_string, arg_list );
if (status < 0) {
/*
** 2/7/07: only fails if flush() fails, so use that status, error_buf already filled in
*/
status = jr_ConvertAprErrno (jr_aprbuf_status (socket_info->aprbuf_ptr));
goto return_status;
}
else {
nbytes = status;
}
/*
** 3/29/08: Not all data may be written out, need to call jr_socket_flush()
** to flush any buffered data.
*/
status = nbytes;
return_status : {
va_end (arg_list);
}
return status;
}
jr_int jr_socket_flush (
jr_socket_t * socket_info,
char * error_buf)
{
jr_int status;
if (socket_info->aprbuf_ptr && jr_aprbuf_needs_flush (socket_info->aprbuf_ptr)) {
jr_aprbuf_set_error_buf (socket_info->aprbuf_ptr, error_buf);
status = jr_aprbuf_flush (socket_info->aprbuf_ptr);
if (status != 0) {
goto return_status;
}
}
status = 0;
return_status : {
}
return status;
}
jr_int jr_socket_cmp (
const void * void_ptr_1,
const void * void_ptr_2)
{
const jr_socket_t * socket_ptr_1 = void_ptr_1;
const jr_socket_t * socket_ptr_2 = void_ptr_2;
return jr_ptrcmp (socket_ptr_1->apr_socket_ptr, socket_ptr_2->apr_socket_ptr);
}
jr_int jr_socket_hash (
const void * void_ptr)
{
const jr_socket_t * socket_ptr = void_ptr;
return jr_ptrhash (socket_ptr->apr_socket_ptr);
}
|
frankjas/libjr
|
libjr/missing/dup2.c
|
<reponame>frankjas/libjr<filename>libjr/missing/dup2.c
#define _POSIX_SOURCE 1
#include "ezport.h"
#ifdef missing_dup2
#include <stdio.h>
#include <errno.h>
#include <sys/errno.h>
#include <fcntl.h>
#include <unistd.h>
int dup2(oldd, target_descriptor)
int oldd ;
int target_descriptor ;
{
jr_int descriptor_set[FOPEN_MAX] ;
jr_int newd ;
jr_int set_index ;
if ((target_descriptor < 0) ||
(target_descriptor >= FOPEN_MAX)) {
errno = EINVAL ;
return(-1) ;
}
if (close(target_descriptor) == -1) {
errno = 0 ;
}
set_index = 0 ;
while ((newd = dup(oldd)) != target_descriptor) {
if (newd == -1) {
break ;
}
/* Remember The Descriptor */ {
descriptor_set[set_index] = newd ;
set_index++ ;
}
}
/* ForEachRememberedDescriptor */ {
jr_int i ;
for (i = 0; i < set_index ; i++) {
close(descriptor_set[i]) ;
}
}
return(newd) ;
}
#else
static void NotCalled () /* define this so ranlib doesn't complain */
{
NotCalled (); /* use it so the compiler doesn't complain */
}
#endif
/*
void main()
{
char buf[128] ;
jr_int new_stderr = dup2(2, 27) ;
jr_int next_descriptor = dup(1) ;
sprintf(buf, "new_stderr == %d, next available descriptor == %d\n",
new_stderr,
next_descriptor
) ;
write(new_stderr, buf, strlen(buf)) ;
exit(0) ;
}
*/
|
frankjas/libjr
|
libjr/io/copyfp.c
|
#define _POSIX_SOURCE 1
#include "ezport.h"
#include <stdio.h>
#include <errno.h>
#include <string.h>
/*| begin jr_FileNameCopy_decl |*/
#include "jr/io.h"
#include "jr/syscalls.h"
int jr_FileNameCopy (dest_file_name, src_file_name, error_buf)
const char * dest_file_name;
const char * src_file_name;
char * error_buf;
{
FILE * wfp;
FILE * rfp;
int status;
if (strcmp (src_file_name, "-") == 0) {
rfp = stdin;
}
else {
rfp = fopen (src_file_name, "rb");
if (rfp == NULL) {
jr_esprintf (error_buf, "couldn't open '%.64s' for reading: %s",
src_file_name, strerror (errno)
);
return jr_ConvertErrno (errno);
}
}
if (strcmp (dest_file_name, "-") == 0) {
wfp = stdout;
}
else {
wfp = fopen (dest_file_name, "w+b");
if (wfp == NULL) {
jr_esprintf (error_buf, "couldn't open '%.64s' for writing: %s",
dest_file_name, strerror (errno)
);
return jr_ConvertErrno (errno);
}
}
status = jr_FilePtrCopy (wfp, rfp, error_buf);
if (rfp != stdin) {
fclose (rfp);
}
if (wfp != stdout) {
fclose (wfp);
}
return status;
}
/* .bp */
int jr_FilePtrCopy (wfp, rfp, error_buf)
FILE * wfp;
FILE * rfp;
char * error_buf;
{
int c;
errno = 0;
while ((c = getc (rfp)) != EOF) {
errno = 0;
putc (c, wfp);
if (errno != 0) {
jr_esprintf (error_buf, "write failure: %s", strerror (errno));
return jr_ConvertErrno (errno);
}
}
if (errno != 0) {
jr_esprintf (error_buf, "read failure: %s", strerror (errno));
return jr_ConvertErrno (errno);
}
return 0;
}
/*| end jr_FileNameCopy_decl |*/
|
frankjas/libjr
|
libjr/syscalls/timelock.c
|
#define _POSIX_SOURCE 1
#include "ezport.h"
#include <stdio.h>
#include <sys/file.h>
#include <signal.h>
#include <unistd.h>
#include <setjmp.h>
#include "jr/trace.h"
#define __jr_compiling_timelock
#include "jr/syscalls.h"
#define ENDPERM (S_IREAD | S_IWRITE | 0660 )
/*--------------------------------*/
static sigjmp_buf env ;
static void onalarm(signum)
jr_int signum ;
{
siglongjmp(env, 1) ;
}
/*--------------------------------*/
jr_int jr_FileDescTimedFlock (fd, how, time)
jr_int fd ;
const char * how ;
jr_int time ;
{
struct sigaction new_action [1];
struct sigaction old_action [1];
unsigned jr_int savealarm = 0 ; /* to shutup 'uninit.' msg */
jr_int kind = LOCK_SH ; /* to shutup 'uninit.' msg */
jr_int retval ;
if (*how == 'u') {
flock (fd, LOCK_UN) ;
retval = 1 ;
if (jr_do_trace(jr_locks)) {
fprintf(stderr,"jr_FileDescTimedFlock(%d,\"%s\", %d) unlocking. return(%d)\n",
fd, how, time, retval) ;
}
}
else {
switch (*how) {
case 'r' :
kind = LOCK_SH ;
break ;
default :
case 'w' :
kind = LOCK_EX ;
break ;
}
retval = (flock (fd, kind | LOCK_NB) == 0) ;
if ((time == 0) | (retval)) {
if (jr_do_trace(jr_locks)) {
fprintf(stderr,"jr_FileDescTimedFlock(%d,\"%s\", %d) No wait. return(%d)\n",
fd, how, time, retval) ;
}
return (retval) ;
}
/*-------------------------------------------------*/
if (sigsetjmp(env, 1) == 0) {
new_action->sa_handler = onalarm;
sigemptyset (&new_action->sa_mask);
new_action->sa_flags = SA_RESTART;
savealarm = alarm(0);
sigaction (SIGALRM, new_action, old_action);
savealarm = alarm(time);
}
else {
alarm (0);
sigaction (SIGALRM, old_action, 0);
alarm (savealarm);
retval = 0 ;
if (jr_do_trace(jr_locks)) {
fprintf(stderr," timed out. return(%d)\n", retval) ;
}
return(retval) ;
}
/*-------------------------------------------------*/
if (jr_do_trace(jr_locks)) {
fprintf(stderr,"jr_FileDescTimedFlock(%d,\"%s\", %d) waiting....",
fd, how, time
) ;
}
retval = (flock (fd, kind) == 0) ;
alarm (0);
sigaction (SIGALRM, old_action, 0);
alarm (savealarm);
if (jr_do_trace(jr_locks)) {
fprintf(stderr," got \"%s\" lock. return(%d)\n", how, retval) ;
}
}
return(retval) ;
}
|
frankjas/libjr
|
libjr/avl_tree/avl_find.c
|
<reponame>frankjas/libjr<gh_stars>0
#include "project.h"
/*| begin jr_AVL_TreeFindElementPtr_decl |*/
void *jr_AVL_TreeFindElementPtrUsingKey (avl_tree, obj)
jr_AVL_Tree * avl_tree;
const void * obj ;
{
jr_int comp_val;
const void * curr_node = avl_tree->root_node;
while (curr_node != 0) {
comp_val = (*avl_tree->cmpfn) (obj, curr_node, avl_tree->cmpfn_arg) ;
if (comp_val == 0) {
return (void *) curr_node;
}
if (comp_val < 0) {
curr_node = jr_AVL_TreeLeftChildPtr (avl_tree, curr_node);
}
else {
curr_node = jr_AVL_TreeRightChildPtr (avl_tree, curr_node);
}
}
return 0;
}
/*| end jr_AVL_TreeFindElementPtr_decl |*/
void *jr_AVL_TreeSmallestElementPtr (avl_tree)
jr_AVL_Tree * avl_tree;
{
const void * curr_node = avl_tree->root_node;
while (curr_node && jr_AVL_TreeLeftChildPtr (avl_tree, curr_node)) {
curr_node = jr_AVL_TreeLeftChildPtr (avl_tree, curr_node);
}
return (void *) curr_node;
}
void *jr_AVL_TreeGreatestElementPtr (avl_tree)
jr_AVL_Tree * avl_tree;
{
const void * curr_node = avl_tree->root_node;
while (curr_node && jr_AVL_TreeRightChildPtr (avl_tree, curr_node)) {
curr_node = jr_AVL_TreeRightChildPtr (avl_tree, curr_node);
}
return (void *) curr_node;
}
|
frankjas/libjr
|
libjr/syscalls/isinput.c
|
<gh_stars>0
#define _POSIX_SOURCE 1
#include "ezport.h"
#include <stdio.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include "jr/syscalls.h"
jr_int jr_FileDescHasPendingInput(fd)
jr_int fd ;
{
# ifdef FIONREAD
{
long nchars = 0 ;
if (ioctl(fd, FIONREAD, &nchars) == 0) {
return((jr_int) nchars) ;
}
else {
return(-1) ;
}
}
# else
{
errno = ENOSYS ; /* function not implemented */
return(-1) ;
}
# endif
}
|
frankjas/libjr
|
libjr/jr_malloc/memdiag.c
|
#include "project.h"
/*
** 4/6/07: ok to use static vars since the code below is protected by mutexes.
**
** Note: do not use jr_esprintf() which could call jr_malloc().
*/
char * jr_MallocTrapFileName = jr_MALLOC_TRAP_FILE_NAME;
char * jr_MallocTraceFileName = jr_MALLOC_TRACE_FILE_NAME;
int jr_MallocCalledByNew = 0;
static char ErrorBuf[jr_ERROR_LEN];
static jr_MallocDiagStruct * Mdp = 0 ;
void jr_MallocDiagRecordInfo (
jr_MallocDiagStruct * mdp,
const void * mptr,
size_t amt_requested,
jr_int is_malloc,
jr_int is_bookkeeping,
jr_int has_bounds_marker,
size_t * amt_requested_ref,
jr_int * has_bounds_marker_ref)
{
jr_MallocPtrInfoStruct * ptr_info;
jr_int old_doing_bookkeeping;
void * calling_pc = 0;
if (!mdp->did_initialization) {
Mdp = mdp; /* DiagInit() may call functions using Mdp*/
jr_MallocDiagInit (mdp);
}
if (is_malloc) {
calling_pc = jr_MallocGetGrandParentPC ();
}
if (mdp->DoingBookkeeping) {
/*
** 3/23/07: we always add bounds to bookkeeping pointers, since otherwise
** we can't figure out what to do when realloc()ing bookkeeping pointers
** while not doing bounds on application pointers.
*/
has_bounds_marker = 1;
is_bookkeeping = 1;
if (mdp->NextBookkeepingIndex == MAX_BOOKKEEPING_MALLOCS) {
/*
* can't record it
*/
mdp->BookkeepingArrayOverflow = 1;
}
else {
ptr_info = mdp->BookkeepingArray + mdp->NextBookkeepingIndex;
jr_MallocPtrInfoInit (
ptr_info, mptr, amt_requested, calling_pc, mdp->heap_base_ptr,
is_malloc, is_bookkeeping, has_bounds_marker
);
mdp->NextBookkeepingIndex++;
}
/*
* Can't do bounds checking if we're doing bookkeeping, because the pointer hash table
* is being manipulated, and may be in an inconsistent state.
*/
if (has_bounds_marker_ref) {
*has_bounds_marker_ref = has_bounds_marker;
}
if (amt_requested_ref) {
*amt_requested_ref = amt_requested;
}
return;
}
old_doing_bookkeeping = mdp->DoingBookkeeping;
mdp->DoingBookkeeping = 1;
ptr_info = jr_MallocDiagFindPtrInfo (mdp, mptr);
if (ptr_info) {
if (is_malloc) {
if (jr_MallocPtrInfoIsMalloced (ptr_info)) {
/*
* already allocated
*/
fprintf (stderr,
"===> jr_MallocDiagRecordInfo: jr_malloc of %p but already allocated\n", mptr
);
jr_MallocPtrMakeTrapFile (mptr, "already allocated");
jr_coredump ();
}
else {
jr_MallocPtrInfoMakeMalloced (ptr_info);
if (is_bookkeeping) {
jr_MallocPtrInfoMakeBookkeeping (ptr_info);
}
else {
jr_MallocPtrInfoClearBookkeeping (ptr_info);
}
jr_MallocPtrInfoSetHasBoundsMarker (ptr_info, has_bounds_marker);
jr_MallocPtrInfoSetRequestedSize (ptr_info, amt_requested);
jr_MallocPtrInfoSetCallingPC (ptr_info, calling_pc);
jr_MallocPtrInfoSetHeapBase (ptr_info, mdp->heap_base_ptr);
jr_MallocPtrInfoOccurence (ptr_info) ++;
}
}
else {
/*
* is being jr_free()ed
*/
if (jr_MallocPtrInfoIsMalloced (ptr_info)) {
/*
* allocated, don't reset is bookkeeping,
* that info is needed later in the bounds checking
*/
jr_MallocPtrInfoClearMalloced (ptr_info);
has_bounds_marker = jr_MallocPtrInfoHasBoundsMarker (ptr_info);
amt_requested = jr_MallocPtrInfoRequestedSize (ptr_info);
}
else {
/*
* already jr_free()ed
*/
fprintf (stderr,
"===> jr_MallocDiagRecordInfo: jr_free(%p) already freed\n", mptr
);
jr_MallocPtrMakeTrapFile (mptr, "already freed");
jr_coredump ();
}
}
}
else {
if (is_malloc) {
ptr_info = jr_MallocDiagNewPtrInfo (
mdp, mptr, amt_requested, calling_pc, mdp->heap_base_ptr,
1, is_bookkeeping, has_bounds_marker
);
}
else {
/*
* never allocated
*/
fprintf (stderr,
"===> jr_MallocDiagRecordInfo: jr_free(%p) was never allocated.\n",
mptr
);
jr_coredump ();
}
}
if (! is_bookkeeping && has_bounds_marker) {
/*
* need to bounds check before they are actually free()ed, but
* bookkeeping pointers have already been free()ed by the
* the time we execute the bounds check
*/
jr_int status;
char * error_buf = ErrorBuf;
status = jr_MallocPtrDoBounds (
mptr, jr_MallocPtrInfoRequestedSize (ptr_info), is_malloc, error_buf
);
if (status != 0) {
/*
* 7/23/2003 Only returns bad if is for free
*/
fprintf (stderr, "===> jr_free(%p): %s\n", mptr, error_buf);
jr_MallocPtrMakeTrapFile (mptr, error_buf);
jr_coredump ();
}
}
/*
* now each pointer allocated as part of the
* bookkeeping must be recorded
* turn off bookkeeping so that they will be inserted
*/
mdp->DoingBookkeeping = 0;
if (mdp->NextBookkeepingIndex > 0) {
jr_MallocPtrInfoStruct * bk_ptr_info;
if (mdp->FirstBookkeepingIndex == mdp->NextBookkeepingIndex) {
/*
* we've recorded all the pointers in the array
* reset it to the beginning
*/
mdp->FirstBookkeepingIndex = 0;
mdp->NextBookkeepingIndex = 0;
}
else {
bk_ptr_info = mdp->BookkeepingArray + mdp->FirstBookkeepingIndex;
mdp->FirstBookkeepingIndex++;
jr_MallocDiagRecordInfo (
mdp,
jr_MallocPtrInfoPtr (bk_ptr_info),
jr_MallocPtrInfoRequestedSize (bk_ptr_info),
jr_MallocPtrInfoIsMalloced (bk_ptr_info),
1,
jr_MallocPtrInfoHasBoundsMarker (bk_ptr_info),
0, 0
);
/*
* 1 since it is a bookkeeping pointer
* this will recursively process all the pointers
* in the bookkeeping array.
*
* Don't check for traps here, since each bookkeeping pointer
* was allocated via jr_malloc() or jr_realloc(), and those
* functions bumped the number of occurences already.
*/
}
}
mdp->DoingBookkeeping = old_doing_bookkeeping;
if (jr_do_trace (jr_malloc_trace)) {
/*
** 6/27/08: do after the bounds are added, and after DoingBookkeeping is reset.
*/
jr_MallocDiagPrintTrace (mdp, ptr_info);
}
if (has_bounds_marker_ref) {
*has_bounds_marker_ref = has_bounds_marker;
}
if (amt_requested_ref) {
*amt_requested_ref = amt_requested;
}
}
void jr_MallocDiagInit (mdp)
jr_MallocDiagStruct * mdp;
{
FILE * trap_fp;
char trap_file_name[256];
jr_check_trace_macro (0) ; /* here to make buggy linker work */
memset (mdp, 0, sizeof (*mdp));
mdp->did_initialization = 1;
mdp->doing_initialization = 1;
mdp->heap_base_ptr = jr_heap_base();
/*
* Set the trap pointer first so that if the trap pointer
* was a bookkeeping pointer first, the number of occurences
* will be incremented correctly. Otherwise early bookkeeping
* occurences of the trap pointer will not be counted, because
* the mdp->TrapPtr field is not set.
*
* The following code should not call jr_malloc() or jr_free()?
*/
jr_MakeDiagFileName (trap_file_name, sizeof (trap_file_name), jr_MallocTrapFileName);
trap_fp = fopen (trap_file_name, "r");
if (trap_fp == 0) {
if (jr_do_trace (jr_malloc_trap)) {
fprintf (stderr, "===> jr_MallocDiagInit: couldn't open %s: %s\n",
trap_file_name, strerror (errno)
);
}
}
else {
char buf[256];
jr_int nitems;
void * tmp_ptr;
jr_int num_bytes;
jr_int occurrence;
void * old_heapbase;
while (fgets (buf, sizeof(buf), trap_fp)) {
nitems = sscanf (buf,
"%p : from jr_malloc(%d bytes) occurrence %d (pc %*p, heap %p)",
&tmp_ptr, &num_bytes, &occurrence, &old_heapbase
);
if (nitems >= 3) {
if (nitems >= 4) {
/*
** 6-8-2011: To account for possible heap randomization, map the old pointer into
** the new heap's address range.
*/
tmp_ptr = (char *) mdp->heap_base_ptr + ((char *) tmp_ptr - (char *) old_heapbase);
}
mdp->TrapPtr = tmp_ptr;
mdp->TrapPtrAmount = num_bytes;
mdp->TrapOnOccurence = occurrence;
break;
}
mdp->TrapPtr = 0;
mdp->TrapPtrAmount = 0;
mdp->TrapOnOccurence = 0;
}
fclose (trap_fp);
}
if (jr_do_trace (jr_malloc_trace)) {
char trace_file_name[256];
jr_MakeDiagFileName (trace_file_name, sizeof (trace_file_name), jr_MallocTraceFileName);
if (mdp->did_trace_file_empty) {
mdp->did_trace_file_empty = 1;
mdp->trace_wfp = fopen (trace_file_name, "a");
}
else {
mdp->trace_wfp = fopen (trace_file_name, "w");
}
if (mdp->trace_wfp == NULL) {
fprintf (stderr, "===> jr_MallocDiagInit(): can't open '%s': %s\n",
trace_file_name, strerror (errno)
);
}
}
if ( jr_do_trace (jr_malloc_calls)
|| jr_do_trace (jr_malloc_trap)
|| jr_malloc_record_ptrs_only()
) {
mdp->DoingBookkeeping = 1;
{
/*
* if in the initialize routines any jr_mallocs occur,
* we have to be sure not to use the pointer table
*/
jr_HTableInit (
mdp->PointerTable, sizeof (jr_MallocPtrInfoStruct),
jr_MallocPtrInfoHash,
jr_MallocPtrInfoCmp
);
jr_HTableIncreaseCapacity (mdp->PointerTable, 8);
/*
* make sure the table will hold enough pointers to store 1 plus
* any bookkeeping pointers without needing to reallocate
* Otherwise a malloc diag error occurs when it trys to grow the pointer
* table while recording the orignal bookkeeping pointers.
*/
jr_MallocDiagInitExemptDescriptorArray (mdp);
}
mdp->DoingBookkeeping = 0;
}
mdp->doing_initialization = 0;
if (jr_do_trace( jr_malloc_trap)) {
/*
** 8/3/09: Application code may do things differently if jr_malloc_calls is on,
** i.e. extra checking, etc. If we're trapping, this code should also execute.
** Within jr_malloc, all logic checks for both appropriately, but application
** code assumes calls is traced when trap is, which is in fact true.
*/
jr_set_trace( jr_malloc_calls);
}
}
void jr_MallocDiagUndo (mdp)
jr_MallocDiagStruct * mdp;
{
mdp->DoingBookkeeping = 1;
{
jr_HTableUndo (mdp->PointerTable);
if (mdp->exempt_fd_array) {
jr_free (mdp->exempt_fd_array);
}
mdp->did_initialization = 0;
}
mdp->DoingBookkeeping = 0;
if (mdp->trace_wfp) {
fclose (mdp->trace_wfp);
}
}
void jr_MallocDiagReset (mdp)
jr_MallocDiagStruct * mdp;
{
if (jr_do_trace (jr_malloc_calls) || jr_do_trace (jr_malloc_trap)) {
if (mdp->did_initialization) {
jr_MallocDiagUndo (mdp);
jr_malloc_set_num_calls (0) ; /* do this first to avoid jr_check_trace error */
jr_MallocDiagInit (mdp);
}
}
}
void jr_MallocDiagPrintTrace (
jr_MallocDiagStruct * mdp,
jr_MallocPtrInfoStruct * ptr_info)
{
char trace_file_name[256];
if (mdp->trace_wfp == 0) {
jr_MakeDiagFileName (trace_file_name, sizeof (trace_file_name), jr_MallocTraceFileName);
/*
** 6/27/08: Can't use jr_Unlink() to empty the file, since that calls jr_malloc()
** (it uses APR, which calls jr_malloc()), and this causes recursion back to here.
*/
if (mdp->did_trace_file_empty) {
mdp->did_trace_file_empty = 1;
mdp->trace_wfp = fopen (trace_file_name, "a");
}
else {
mdp->trace_wfp = fopen (trace_file_name, "w");
}
if (mdp->trace_wfp == NULL) {
fprintf (stderr, "===> jr_MallocDiagPrintTrace(): can't open '%s': %s\n",
trace_file_name, strerror (errno)
);
return;
}
}
/*
** 6-8-2011: used only for tracing all allocations, use simpler print to
** instead of jr_MallocPtrInfoPrint() avoid extra work of checking bounds?
** Or because of possible malloc recursion?
*/
fprintf (mdp->trace_wfp, "%p : from jr_malloc(%d bytes) occurrence %d (pc %p) %s%s%s\n",
jr_MallocPtrInfoPtr (ptr_info),
(jr_int) jr_MallocPtrInfoRequestedSize (ptr_info),
jr_MallocPtrInfoOccurence (ptr_info),
jr_MallocPtrInfoCallingPC (ptr_info),
jr_MallocPtrInfoIsMalloced (ptr_info)? "jr_malloc()ed" : "jr_free()ed",
jr_MallocPtrInfoIsBookkeeping (ptr_info) ? " bookkeeping" : " ",
jr_MallocPtrInfoHasBoundsMarker (ptr_info) ? " " : " (no bounds)"
);
}
void jr_MallocPtrInfoInit (
jr_MallocPtrInfoStruct * mptr_info,
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)
{
mptr_info->ptr = mptr;
mptr_info->amt_requested = amt_requested;
mptr_info->calling_pc = calling_pc;
mptr_info->heap_base_ptr = heap_base_ptr;
mptr_info->is_malloced = is_malloced;
mptr_info->is_bookkeeping = is_bookkeeping;
mptr_info->has_bounds_marker = has_bounds_marker;
mptr_info->occurrence = 1;
}
jr_int jr_MallocPtrInfoHash (void_arg_1)
const void * void_arg_1;
{
const jr_MallocPtrInfoStruct * ptr_info_1 = void_arg_1;
return jr_ptrhash (ptr_info_1->ptr);
}
jr_int jr_MallocPtrInfoCmp (void_arg_1, void_arg_2)
const void * void_arg_1;
const void * void_arg_2;
{
const jr_MallocPtrInfoStruct * ptr_info_1 = void_arg_1;
const jr_MallocPtrInfoStruct * ptr_info_2 = void_arg_2;
return jr_ptrcmp (ptr_info_1->ptr, ptr_info_2->ptr);
}
jr_MallocPtrInfoStruct *jr_MallocDiagFindPtrInfo (mdp, mptr)
jr_MallocDiagStruct * mdp;
const void * mptr;
{
jr_MallocPtrInfoStruct tmp_ptr_info[1];
jr_MallocPtrInfoStruct * ptr_info;
jr_MallocPtrInfoInit (tmp_ptr_info, mptr, 0, 0, 0, 0, 0, 0);
ptr_info = jr_HTableFindElementPtr (mdp->PointerTable, tmp_ptr_info);
return ptr_info;
}
jr_MallocPtrInfoStruct *jr_MallocDiagNewPtrInfo (
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)
{
jr_MallocPtrInfoStruct tmp_ptr_info[1];
jr_MallocPtrInfoStruct * ptr_info;
unsigned jr_int old_max_request_size = jr_malloc_max_request_size ();
jr_malloc_set_max_request_size (jr_UINT_MAX);
jr_MallocPtrInfoInit (
tmp_ptr_info, mptr, amt_requested, calling_pc, heap_base_ptr,
is_malloced, is_bookkeeping, has_bounds_marker
);
ptr_info = jr_HTableSetNewElement (mdp->PointerTable, tmp_ptr_info);
jr_malloc_set_max_request_size (old_max_request_size);
return ptr_info;
}
jr_int jr_MallocPtrDoBounds (mptr_arg, amt_requested, for_malloc, error_buf)
const void * mptr_arg ;
size_t amt_requested;
jr_int for_malloc;
char * error_buf;
{
char * mptr = (char *) mptr_arg ;
char * cptr;
jr_int i;
jr_int suffix_bounds_marker_size;
jr_int prefix_bounds_marker_size;
/*
* Assumes the amt_requested passed is is correct
*/
suffix_bounds_marker_size = jr_malloc_suffix_bounds_marker_size (amt_requested);
prefix_bounds_marker_size = jr_malloc_prefix_bounds_marker_size ();
if (for_malloc) {
/*
* Put a marker at the end of the amt_requested to
* check for bounds errors upon jr_free()
*/
cptr = mptr + amt_requested;
for (i = 0; i < suffix_bounds_marker_size; i++) {
cptr [i] = jr_malloc_suffix_marker_char (i);
}
cptr [suffix_bounds_marker_size - 1] = 0;
/*
* Put a marker before pointer to check for prefix errors upon jr_free().
*/
cptr = mptr - prefix_bounds_marker_size;
for (i = 0; i < prefix_bounds_marker_size; i++) {
cptr [i] = jr_malloc_prefix_marker_char (i);
}
}
else {
cptr = mptr + amt_requested;
for (i = 0; i < suffix_bounds_marker_size - 1; i++) {
if (cptr [i] != jr_malloc_suffix_marker_char (i)) {
sprintf (error_buf, "bounds error, marker index %d", i);
return -1;
}
}
if (cptr [suffix_bounds_marker_size - 1] != 0) {
sprintf (error_buf, "bounds error, marker index %d", suffix_bounds_marker_size - 1);
return -1;
}
cptr = mptr - prefix_bounds_marker_size;
for (i = 0; i < prefix_bounds_marker_size; i++) {
if (cptr [i] != jr_malloc_prefix_marker_char (i)) {
sprintf (error_buf, "prefix bounds error, marker index %d", i);
return -1;
}
}
}
return 0;
}
void jr_MallocDiagDoTrap (mdp, mptr, is_malloc)
jr_MallocDiagStruct * mdp;
const void * mptr;
jr_int is_malloc;
{
if (!mdp->did_initialization) {
Mdp = mdp; /* The init may call functions using Mdp*/
jr_MallocDiagInit (mdp);
}
if (mptr == mdp->TrapPtr) {
if (is_malloc) mdp->CurrOccurence++;
if (mdp->CurrOccurence >= mdp->TrapOnOccurence ||
mdp->TrapOnOccurence == 0) {
fprintf(stderr, "%s : trap file occurrence %d of %p found\n",
is_malloc ? "jr_malloc()" : "jr_free()",
mdp->CurrOccurence, mptr
) ;
jr_debugger_trap ();
}
}
}
void jr_MallocDiagDump (mdp)
jr_MallocDiagStruct * mdp;
{
jr_MallocPtrInfoStruct * ptr_info;
jr_int num_leaks = 0;
FILE * trap_fp;
char trap_file_name[256];
jr_int bounds_status;
if (!mdp->did_initialization) {
return;
}
if ( !jr_do_trace(jr_malloc_calls) && !jr_do_trace (jr_malloc_trap)) {
fprintf(stderr, "===> Can't jr_MallocDiagDump without jr_do_trace(jr_malloc_calls) on.\n") ;
return ;
}
if (mdp->BookkeepingArrayOverflow) {
fprintf (stderr, "===> jr_Malloc checking internal overflow.\n");
fprintf (stderr, "===> Increase MAX_BOOKKEEPING_MALLOCS in jr_malloc.c\n");
}
jr_MakeDiagFileName (trap_file_name, sizeof (trap_file_name), jr_MallocTrapFileName);
trap_fp = fopen (trap_file_name, "w");
if (trap_fp == 0) {
fprintf (stderr, "===> jr_MallocDiagDump(): can't open '%s': %s\n",
trap_file_name, strerror (errno)
);
}
else {
jr_HTableForEachElementPtr (mdp->PointerTable, ptr_info) {
if ( jr_MallocPtrInfoIsMalloced (ptr_info)
&& !jr_MallocPtrInfoIsBookkeeping (ptr_info)) {
if (jr_MallocPtrInfoHasBoundsMarker (ptr_info)) {
bounds_status = jr_MallocPtrInfoCheckBounds (ptr_info, ErrorBuf);
}
else {
bounds_status = 0;
}
if (bounds_status != 0) {
jr_MallocPtrInfoPrint (ptr_info, trap_fp);
}
else if (num_leaks < jr_malloc_max_leak_trap_print ()) {
jr_MallocPtrInfoPrint (ptr_info, trap_fp);
}
num_leaks ++;
}
}
if (num_leaks) {
fprintf (trap_fp, "Total still allocated: %d\n", num_leaks);
if (jr_trace_level (jr_malloc_calls) < 2) {
fprintf (trap_fp, "For valid PC values, set jr_malloc_calls level to 2 or higher\n");
}
}
fclose (trap_fp);
if (num_leaks == 0) {
jr_UnlinkNoApr (trap_file_name, 0);
}
}
}
jr_int jr_MallocDiagCheckLeaksAndBounds (mdp, error_buf)
jr_MallocDiagStruct * mdp;
char * error_buf;
{
jr_MallocPtrInfoStruct * ptr_info;
jr_int num_allocated = 0;
jr_int num_bounds_errors = 0;
jr_int status;
if (!mdp->did_initialization) {
return 0;
}
if ( !jr_do_trace(jr_malloc_calls) && !jr_do_trace (jr_malloc_trap)) {
sprintf (error_buf,
"can't count jr_malloc() calls without jr_do_trace(jr_malloc_calls).\n"
);
return -1;
}
if (mdp->BookkeepingArrayOverflow) {
sprintf (error_buf, "jr_Malloc checking internal overflow.");
return -1;
}
jr_HTableForEachElementPtr (mdp->PointerTable, ptr_info) {
if (jr_MallocPtrInfoIsBookkeeping (ptr_info)) {
continue;
}
if (jr_MallocPtrInfoIsMalloced (ptr_info)) {
/*
* check for the bounds error marker, bookkeeping mallocs aren't bounds checked
*/
num_allocated ++;
if (jr_MallocPtrInfoHasBoundsMarker (ptr_info)) {
status = jr_MallocPtrInfoCheckBounds (ptr_info, error_buf);
if (status != 0) {
num_bounds_errors++;
}
}
}
}
if (num_allocated || num_bounds_errors) {
if (num_bounds_errors == 0) {
sprintf (error_buf, "%d still allocated", num_allocated);
}
else if (num_allocated == 0) {
sprintf (error_buf, "%d bounds errors", num_bounds_errors);
}
else {
sprintf (error_buf, "%d still allocated, %d bounds errors",
num_allocated, num_bounds_errors
);
}
return -1;
}
return 0;
}
jr_int jr_MallocDiagNumLeaks (mdp)
jr_MallocDiagStruct * mdp;
{
jr_MallocPtrInfoStruct * ptr_info;
jr_int num_leaks = 0;
if (!mdp->did_initialization) {
return 0;
}
if ( !jr_do_trace(jr_malloc_calls) && !jr_do_trace (jr_malloc_trap)) {
fprintf(stderr,
"===> Can't jr_MallocDiagNumLeaks() without jr_do_trace(jr_malloc_calls) on.\n"
) ;
return 0;
}
jr_HTableForEachElementPtr (mdp->PointerTable, ptr_info) {
if ( jr_MallocPtrInfoIsMalloced (ptr_info)
&& !jr_MallocPtrInfoIsBookkeeping (ptr_info)) {
num_leaks ++;
}
}
return num_leaks;
}
const char *jr_MallocDiagPtrType(mdp, pointer)
jr_MallocDiagStruct * mdp;
const void * pointer ;
{
static char sbuf[256] ;
jr_MallocPtrInfoStruct * ptr_info;
if (! pointer) {
snprintf(sbuf, sizeof(sbuf), "%p : (null address)", pointer) ;
}
else if (pointer > (void *) (&pointer)) {
snprintf(sbuf, sizeof(sbuf), "%p : (stack address)", pointer) ;
}
else if (jr_do_trace(jr_malloc_calls) || jr_do_trace(jr_malloc_trap)) {
ptr_info = jr_MallocDiagFindPtrInfo (mdp, pointer) ;
if (ptr_info) {
jr_MallocPtrInfoFormatString (ptr_info, sbuf, sizeof(sbuf));
}
else {
snprintf(sbuf, sizeof(sbuf), "%p : (unknown)", pointer) ;
}
}
else {
snprintf(sbuf, sizeof(sbuf),
"%p : (unknown, not tracing jr_malloc)",
pointer) ;
}
return(sbuf) ;
}
char *jr_MallocPtrInfoFormatString (ptr_info, sbuf, sbuf_size)
jr_MallocPtrInfoStruct * ptr_info;
char * sbuf ;
jr_int sbuf_size;
{
jr_int pid = jr_getpid ();
jr_int bounds_status = 0;
jr_int status;
char tmp_buf[jr_ERROR_LEN] ;
if (jr_MallocPtrInfoIsMalloced (ptr_info)) {
bounds_status = jr_MallocPtrInfoCheckBounds (ptr_info, tmp_buf);
}
status = snprintf (sbuf, sbuf_size,
"%p : from jr_malloc(%d bytes) occurrence %d (pc %p, heap %p) %s%s%s pid %d%s%s",
jr_MallocPtrInfoPtr (ptr_info),
(jr_int) jr_MallocPtrInfoRequestedSize (ptr_info),
jr_MallocPtrInfoOccurence (ptr_info),
jr_MallocPtrInfoCallingPC (ptr_info),
jr_MallocPtrInfoHeapBase (ptr_info),
jr_MallocPtrInfoIsMalloced (ptr_info)? "jr_malloc()ed" : "jr_free()ed",
jr_MallocPtrInfoIsBookkeeping (ptr_info) ? " bookkeeping" : " ",
jr_MallocPtrInfoHasBoundsMarker (ptr_info) ? " " : " (no bounds)",
pid,
bounds_status != 0 ? ", " : "",
bounds_status != 0 ? tmp_buf : ""
);
if (status >= sbuf_size ) {
sbuf[ sbuf_size - 1 ] = 0;
}
return(sbuf) ;
}
void jr_MallocPtrInfoPrint (ptr_info, wfp)
jr_MallocPtrInfoStruct * ptr_info;
FILE * wfp ;
{
char sbuf[256] ;
jr_MallocPtrInfoFormatString (ptr_info, sbuf, sizeof(sbuf)) ;
if (wfp == 0) {
wfp = stdout ;
}
fprintf (wfp, "%s\n", sbuf) ;
}
void jr_MallocPtrMakeTrapFile (pointer, error_mesg)
const void * pointer;
const char * error_mesg;
{
jr_MallocPtrInfoStruct * ptr_info;
if (error_mesg == 0) {
error_mesg = "0";
}
if (Mdp == 0) {
fprintf (stderr, "===> jr_MallocPtrMakeTrapFile(%p, \"%s\"): malloc tracing not active\n",
pointer, error_mesg
);
return;
}
ptr_info = jr_MallocDiagFindPtrInfo (Mdp, pointer);
if (ptr_info == 0) {
fprintf (stderr, "===> jr_MallocPtrMakeTrapFile(%p, \"%s\"): %s, not jr_malloc pointer\n",
pointer, error_mesg, jr_MallocDiagPtrType (Mdp, pointer));
}
else {
FILE * trap_fp;
char trap_file_name[256];
jr_MallocPtrInfoPrint (ptr_info, stderr);
jr_MakeDiagFileName (trap_file_name, sizeof (trap_file_name), jr_MallocTrapFileName);
trap_fp = fopen (trap_file_name, "w");
if (trap_fp == 0) {
fprintf (stderr, "===> jr_MallocPtrMakeTrapFile(): can't open '%s': %s\n",
trap_file_name, strerror (errno)
);
}
else {
jr_MallocPtrInfoPrint (ptr_info, trap_fp);
fprintf (trap_fp, "====> jr_MallocPtrMakeTrapFile (%p, \"%s\")\n",
pointer, error_mesg
);
fclose (trap_fp);
}
}
}
size_t jr_MallocPtrSizeRequested (mptr)
void * mptr;
{
jr_MallocPtrInfoStruct * ptr_info;
jr_int i;
/*
* first look through all the bookkeeping pointers
* since any changes to the size not yet updated
* (in the case of jr_reallocs) is kept here
* only if in bookkeeping will this loop do anything
*
* start with the most recent information
*/
if (Mdp == 0) {
fprintf (stderr, "===> jr_MallocPtrSizeRequested(%p): malloc tracing not active\n", mptr);
return 0;
}
for (i = Mdp->NextBookkeepingIndex - 1; i >= 0; i--) {
ptr_info = Mdp->BookkeepingArray + i;
if (jr_MallocPtrInfoPtr (ptr_info) == mptr) {
if (jr_MallocPtrInfoIsMalloced (ptr_info)) {
return (jr_MallocPtrInfoRequestedSize (ptr_info));
}
else {
/*
* most recent activity is a jr_free
*/
fprintf (stderr, "===> jr_MallocPtrSizeRequested (%p): ptr has been jr_free()ed\n",
mptr
);
jr_coredump ();
}
}
}
if (Mdp->doing_initialization) {
fprintf (stderr, "===> jr_MallocPtrSizeRequested (%p): can't find ptr while doing init\n",
mptr
);
jr_coredump ();
}
ptr_info = jr_MallocDiagFindPtrInfo (Mdp, mptr);
if (ptr_info) {
fprintf (stderr, "===> jr_MallocPtrSizeRequested (%p): %s, not jr_malloc pointer\n",
mptr, jr_MallocDiagPtrType (Mdp, mptr));
jr_coredump ();
}
if (! jr_MallocPtrInfoIsMalloced (ptr_info)) {
fprintf (stderr, "===> jr_MallocPtrSizeRequested (%p): not currently allocated\n",
mptr
);
jr_coredump ();
}
return jr_MallocPtrInfoRequestedSize (ptr_info);
}
void jr_MallocDiagSetSizeRequested (mdp, mptr, requested_size)
jr_MallocDiagStruct * mdp;
void * mptr;
size_t requested_size;
{
jr_MallocPtrInfoStruct * ptr_info;
jr_int i;
jr_int status;
/*
* first look through all the bookkeeping pointers
* since any changes to the size not yet updated
* (in the case of jr_reallocs) is kept here
* only if in bookkeeping will this loop do anything
*
* start with the most recent information
*/
for (i = mdp->NextBookkeepingIndex - 1; i >= 0; i--) {
ptr_info = mdp->BookkeepingArray + i;
if (jr_MallocPtrInfoPtr (ptr_info) == mptr) {
if (jr_MallocPtrInfoIsMalloced (ptr_info)) {
jr_MallocPtrInfoSetRequestedSize (ptr_info, requested_size);
return;
}
else {
/*
* most recent activity is a jr_free
*/
fprintf (stderr,
"===> jr_MallocDiagSetSizeRequested (%p): ptr has been jr_free()ed\n",
mptr
);
jr_coredump ();
}
}
}
if (mdp->doing_initialization) {
fprintf (stderr,
"===> jr_MallocDiagSetSizeRequested (%p): can't find ptr while doing init\n",
mptr
);
jr_coredump ();
}
ptr_info = jr_MallocDiagFindPtrInfo (mdp, mptr);
if (ptr_info == 0) {
fprintf (stderr,
"===> jr_MallocDiagSetSizeRequested (%p): %s, not jr_malloc pointer\n",
mptr, jr_MallocDiagPtrType (mdp, mptr));
jr_coredump ();
}
if (! jr_MallocPtrInfoIsMalloced (ptr_info)) {
fprintf (stderr,
"===> jr_MallocDiagSetSizeRequested (%p): not currently allocated\n",
mptr
);
jr_coredump ();
}
jr_MallocPtrInfoSetRequestedSize (ptr_info, requested_size);
status = jr_MallocPtrDoBounds (mptr, requested_size, 1, ErrorBuf);
if (status != 0) {
fprintf (stderr, "===> jr_MallocDiagSetSizeRequested(%p): %s\n", mptr, ErrorBuf);
jr_MallocPtrMakeTrapFile (mptr, ErrorBuf);
jr_coredump ();
}
}
jr_MallocPtrInfoStruct * jr_MallocPtrFindInfoPtr (pointer)
void * pointer;
{
jr_MallocPtrInfoStruct * ptr_info;
if (Mdp == 0) {
fprintf (stderr, "===> Can't run search without jr_do_trace(jr_malloc_calls) on.\n") ;
return 0;
}
ptr_info = jr_MallocDiagFindPtrInfo (Mdp, pointer);
return ptr_info;
}
void jr_MallocPtrPrintInfo (pointer)
void * pointer;
{
jr_MallocPtrInfoStruct * ptr_info;
if (Mdp == 0) {
fprintf (stderr, "===> Can't run search without jr_do_trace(jr_malloc_calls) on.\n") ;
return ;
}
ptr_info = jr_MallocDiagFindPtrInfo (Mdp, pointer);
if (ptr_info == 0) {
fprintf (stderr, "===> jr_MallocPtrPrintInfo: %s, not jr_malloc pointer\n",
jr_MallocDiagPtrType (Mdp, pointer)
);
return;
}
jr_MallocPtrInfoPrint( ptr_info, stderr);
}
const void *jr_MallocPtrPrintPrevInfo (search_pointer)
const void * search_pointer ;
{
jr_MallocPtrInfoStruct * ptr_info;
const void * current_pointer ;
jr_MallocPtrInfoStruct * best_ptr_info;
jr_MallocPtrInfoStruct * other_ptr_info;
const void * current_allocated_guess = 0 ;
jr_MallocPtrInfoStruct * current_allocated_info = 0;
const void * current_free_guess = 0 ;
jr_MallocPtrInfoStruct * current_free_info = 0;
char trap_file_name[256];
FILE * trap_fp;
if (Mdp == 0) {
fprintf(stderr, "===> Can't run search without jr_do_trace(jr_malloc_calls) on.\n") ;
return 0;
}
jr_HTableForEachElementPtr (Mdp->PointerTable, ptr_info) {
current_pointer = jr_MallocPtrInfoPtr (ptr_info);
if (jr_MallocPtrInfoIsMalloced (ptr_info)) {
if ((current_pointer > current_allocated_guess) &&
(current_pointer < search_pointer)) {
current_allocated_guess = current_pointer ;
current_allocated_info = ptr_info;
}
}
else {
if ((current_pointer > current_free_guess) &&
(current_pointer < search_pointer)) {
current_free_guess = current_pointer ;
current_free_info = ptr_info;
}
}
}
if (current_free_guess == 0 && current_allocated_guess == 0) {
fprintf(stderr,"===> No previous pointers encountered.\n") ;
return 0;
}
if (current_allocated_guess > current_free_guess) {
best_ptr_info = current_allocated_info ;
other_ptr_info = current_free_info ;
}
else {
best_ptr_info = current_free_info ;
other_ptr_info = current_allocated_info ;
}
fprintf (stderr,
"Previous pointers of %p:\n", search_pointer
);
if (best_ptr_info) {
jr_MallocPtrInfoPrint (best_ptr_info, stderr);
}
if (other_ptr_info) {
jr_MallocPtrInfoPrint (other_ptr_info, stderr);
}
ptr_info = jr_MallocDiagFindPtrInfo (Mdp, search_pointer);
if (ptr_info) {
fprintf (stderr, "Original pointer %p is a jr_malloc()ed pointer\n", search_pointer);
}
jr_MakeDiagFileName (trap_file_name, sizeof (trap_file_name), jr_MallocTrapFileName);
trap_fp = fopen (trap_file_name, "w");
if (trap_fp == 0) {
fprintf (stderr, "===> jr_MallocPtrPrintPrevInfo(): can't open '%s': %s\n",
trap_file_name, strerror (errno)
);
}
else {
if (best_ptr_info) {
jr_MallocPtrInfoPrint (best_ptr_info, trap_fp);
}
if (other_ptr_info) {
jr_MallocPtrInfoPrint (other_ptr_info, trap_fp);
}
fprintf (trap_fp, "Previous pointers of %p\n", search_pointer);
fclose (trap_fp);
fprintf (stderr, "Made trap file.\n");
}
return jr_MallocPtrInfoPtr (best_ptr_info);
}
jr_int jr_MallocPtrCheckBounds (pointer_arg)
const void * pointer_arg;
{
const char * pointer = pointer_arg ;
jr_MallocPtrInfoStruct * ptr_info;
jr_int status;
if (Mdp == 0) {
fprintf (stderr, "Can't check bounds without jr_do_trace(jr_malloc_calls) on\n") ;
return -1;
}
ptr_info = jr_MallocDiagFindPtrInfo (Mdp, pointer);
if (ptr_info == 0) {
fprintf (stderr, "%p not jr_malloc() pointer", pointer);
return -1;
}
if (jr_MallocPtrInfoIsBookkeeping (ptr_info)) {
fprintf (stderr, "%p is a jr_malloc() bookkeeping pointer", pointer);
return -1;
}
if (!jr_MallocPtrInfoHasBoundsMarker (ptr_info)) {
fprintf (stderr, "%p has no bounds marker", pointer);
return -1;
}
if (jr_MallocPtrInfoIsFreed (ptr_info)) {
fprintf (stderr, "%p is already jr_free()ed (size %d)",
pointer, (jr_int) jr_MallocPtrInfoRequestedSize (ptr_info)
);
return -1;
}
/*
* check for the bounds error marker
*/
status = jr_MallocPtrInfoCheckBounds (ptr_info, ErrorBuf);
if (status != 0) {
fprintf (stderr, "%p bounds error: %s\n", pointer, ErrorBuf);
jr_MallocPtrMakeTrapFile (pointer, ErrorBuf);
fprintf (stderr, "Made trap file.\n");
}
else {
fprintf (stderr, "%p bounds ok\n", pointer);
}
return status;
}
jr_int jr_MallocPtrInfoCheckBounds (ptr_info, error_buf)
jr_MallocPtrInfoStruct * ptr_info;
char * error_buf;
{
const void * mptr;
size_t requested_size;
jr_int status;
mptr = jr_MallocPtrInfoPtr (ptr_info);
requested_size = jr_MallocPtrInfoRequestedSize (ptr_info);
status = jr_MallocPtrDoBoundsCheck (mptr, requested_size, error_buf);
return status;
}
jr_int jr_MallocCheckBounds ()
{
const void * bad_ptr;
bad_ptr = jr_malloc_check_bounds (ErrorBuf);
if (bad_ptr != 0) {
fprintf (stderr, "jr_MallocCheckBounds(): %s\n", ErrorBuf);
if (bad_ptr != (const void *) 0x1) {
jr_MallocPtrMakeTrapFile (bad_ptr, ErrorBuf);
fprintf (stderr, "Made trap file for %p.\n", bad_ptr);
}
return -1;
}
fprintf (stderr, "jr_MallocCheckBounds(): bounds ok\n");
return 0;
}
jr_int jr_MallocNumLeaks ()
{
jr_int num_leaks;
if (Mdp == 0) {
fprintf (stderr, "jr_MallocNumLeaks(): jr_do_trace(jr_malloc_calls) not set.\n") ;
return 0;
}
num_leaks = jr_MallocDiagNumLeaks (Mdp);
return num_leaks;
}
jr_int jr_MallocPrintOpenFiles ()
{
jr_int num_files;
if (Mdp == 0) {
fprintf (stderr, "jr_MallocPrintOpenFiles(): jr_do_trace(jr_malloc_calls) not set.\n") ;
return -1;
}
num_files = jr_MallocDiagNumOpenFiles (Mdp, stderr, 0);
return num_files;
}
const void *jr_malloc_check_bounds (error_buf)
char * error_buf;
{
/*
* Must be in this file since it uses static variable 'Mdp'.
*/
jr_MallocPtrInfoStruct * ptr_info;
jr_int status;
if (Mdp == 0) {
sprintf (error_buf, "can't do bounds check without jr_do_trace(jr_malloc_calls) on.") ;
return (void *) 0x1;
}
jr_HTableForEachElementPtr (Mdp->PointerTable, ptr_info) {
if ( !jr_MallocPtrInfoIsMalloced (ptr_info)
|| !jr_MallocPtrInfoHasBoundsMarker (ptr_info)
|| jr_MallocPtrInfoIsBookkeeping (ptr_info)) {
continue;
}
/*
* check for the bounds error marker
*/
status = jr_MallocPtrInfoCheckBounds (ptr_info, error_buf);
if (status != 0) {
return jr_MallocPtrInfoPtr (ptr_info);
}
}
return 0;
}
void jr_MallocPrintFunctions ()
{
fprintf (stderr, "void jr_MallocCheckBounds (void)\n");
fprintf (stderr, "void jr_MallocNumLeaks (void)\n");
fprintf (stderr, "void jr_MallocPrintOpenFiles (void)\n");
fprintf (stderr, "void jr_MallocPtrCheckBounds (void *mptr)\n");
fprintf (stderr, "void jr_MallocPtrPrintInfo (void *mptr)\n");
fprintf (stderr, "void jr_MallocPtrPrintPrevInfo (void *mptr)\n");
fprintf (stderr, "void jr_MallocPtrMakeTrapFile (void *mptr, char *error_msg)\n");
fprintf (stderr, "void jr_MallocPtrSizeRequested (void *mptr)\n");
fprintf (stderr, "void jr_MallocPtrSetTrap (void *mptr, int occurence)\n");
fprintf (stderr, "\n");
fprintf (stderr, "jr_MallocPtrInfoStruct * jr_MallocPtrFindInfoPtr (void *mptr)\n");
if ( !jr_do_trace(jr_malloc_calls) && !jr_do_trace (jr_malloc_trap)) {
fprintf (stderr, "WARNING: jr_do_trace(jr_malloc_calls) is not on.\n") ;
}
}
void jr_MallocDebuggerFunctions ()
{
jr_MallocPrintFunctions ();
}
void jr_MallocFunctions ()
{
jr_MallocPrintFunctions ();
}
void jr_MallocPtrSetTrap (mptr, occurence)
void * mptr;
jr_int occurence;
{
if (Mdp == 0) {
fprintf(stderr, "jr_MallocPtrSetTrap(): jr_malloc() tracing is not active.\n") ;
return;
}
Mdp->TrapPtr = mptr;
Mdp->TrapOnOccurence = occurence;
}
void *jr_MallocGetGrandParentPC ()
{
void * pc_array[6];
int trace_size;
if (jr_trace_level (jr_malloc_calls) > 1 || jr_trace_level (jr_malloc_trap) > 1) {
trace_size = jr_backtrace (pc_array, sizeof (pc_array) / sizeof (void *));
/*
* 3/31/05: pc_array[0] is the line above, pc_array[1] is caller's line.
* so pc_array[2] is caller's parent, and pc_array[3] is caller's grand parent.
*/
if (jr_malloc_called_by_new()) {
if (trace_size > 4) {
return pc_array[4];
}
}
else {
if (trace_size > 3) {
return pc_array[3];
}
}
}
return 0;
}
#ifdef ostype_linux
# ifndef INTERNAL_SIZE_T
# define INTERNAL_SIZE_T size_t
# endif
struct malloc_chunk
{
INTERNAL_SIZE_T prev_size; /* Size of previous chunk (if free). */
INTERNAL_SIZE_T size; /* Size in bytes, including overhead. */
struct malloc_chunk* fd; /* double links -- used only if free. */
struct malloc_chunk* bk;
};
typedef struct malloc_chunk* mchunkptr;
# define NAV 128 /* number of bins */
# define mutex_t jr_int
typedef struct malloc_chunk* mbinptr;
/* An arena is a configuration of malloc_chunks together with an array
of bins. With multiple threads, it must be locked via a mutex
before changing its data structures. One or more `heaps' are
associated with each arena, except for the main_arena, which is
associated only with the `main heap', i.e. the conventional free
store obtained with calls to MORECORE() (usually sbrk). The `av'
array is never mentioned directly in the code, but instead used via
bin access macros. */
typedef struct _arena {
mbinptr av[2*NAV + 2];
struct _arena *next;
size_t size;
#if THREAD_STATS
long stat_lock_direct, stat_lock_loop, stat_lock_wait;
#endif
mutex_t mutex;
} arena;
#endif
void jr_MallocDummyFunction ()
{
# ifdef ostype_linux
mchunkptr dummy_ptr;
# else
void * dummy_ptr;
# endif
printf( "%d\n", (jr_int) sizeof(dummy_ptr));
}
|
frankjas/libjr
|
include/jr/dlist.h
|
#ifndef _dlisth
#define _dlisth 1
#include "ezport.h"
#include <string.h>
#include <stdarg.h>
typedef struct {
void * tail;
void * head;
jr_int objsize;
jr_int prefix_size;
unsigned allocates_elements : 1;
} jr_DList;
extern void jr_DListInit PROTO ((jr_DList *list, jr_int objsize));
extern jr_DList * jr_DListCreate PROTO ((jr_int objsize));
extern void jr_DListDestroy PROTO ((jr_DList *list));
extern void jr_DListUndo PROTO ((jr_DList *list));
extern void jr_DListEmpty PROTO ((jr_DList *list));
extern void * jr_DListInsertElement PROTO ((
jr_DList * list,
const void * next_el,
const void * new_el
));
extern void * jr_DListAppendElement PROTO ((
jr_DList * list,
const void * prev_el,
const void * new_el
));
extern void * jr_DListExtractElement PROTO ((jr_DList *list, const void *el)) ;
extern void jr_DListDeleteElement PROTO ((jr_DList *list, void *el));
extern jr_int jr_DListElementPrefixSize PROTO ((jr_DList *list));
extern void jr_DListSetPrefixSize PROTO ((jr_DList *list, jr_int prefix_size));
extern void jr_DListTransformPrefix PROTO ((
jr_DList * list,
void * el_ptr,
unsigned jr_int magnitude,
jr_int which_way,
jr_int all_elements
));
extern void jr_DListSetContainers PROTO ((jr_DList *list, ...));
extern void jr_DListSetContainersFromVA_List PROTO ((
jr_DList * list,
va_list arg_list
));
#define jr_DListHeadPtr(list) ((list)->head)
#define jr_DListTailPtr(list) ((list)->tail)
#define jr_DListIsEmpty(list) ((list)->head == 0)
#define jr_DListElementSize(list) ((list)->objsize)
#define jr_DListPrefixSize(list) ((list)->prefix_size)
#define jr_DListAllocatesElements(list) ((list)->allocates_elements)
#define jr_DListSetAllocatesElements(list) ((list)->allocates_elements = 1)
#define jr_DListBytesPerElement(list) \
(jr_DListElementSize (list) + jr_DListPrefixSize (list))
#define jr_DListHasMultipleElements(list) \
(!jr_DListIsEmpty (list) && jr_DListHeadPtr (list) != jr_DListTailPtr (list))
/******** Element Operations ********/
extern void * jr_DListAllocateElementWithSize PROTO ((jr_DList *list, jr_int size));
extern void * jr_DListAllocateTmpElementWithSize PROTO ((jr_DList *list, jr_int size));
/*
* Used to allocate an element with particular values
* without adding it to the list. Used for creating
* temporaries lookup elements, where the lookup uses
* list next,prev pointer info, for example, jr_Graph
* edge lookups
*/
extern void jr_DListFreeElement PROTO ((
jr_DList * list,
void * obj_ptr
));
#define jr_FreeDListElementWithPrefix(obj_ptr, prefix_size) \
jr_free ((char *) (obj_ptr) - 2 * sizeof (void *) - (prefix_size));
#define jr_NextDListElementPtrWithPrefix(objptr, prefix_size) \
(((void **) ((char *) (objptr) - (prefix_size)))[-1])
#define jr_PrevDListElementPtrWithPrefix(objptr, prefix_size) \
(((void **) ((char *) (objptr) - (prefix_size)))[-2])
extern void jr_MakeNullDListElementWithPrefix PROTO ((const void *el, jr_int prefix_size));
extern jr_int jr_IsNullDListElementWithPrefix PROTO ((const void *el, jr_int prefix_size));
/*
** 8/15/2005: A null element doesn't mean the element isn't on a list
** since the only element on a list will have null prev and next pointers.
*/
/******* ForEach Loops ********/
#define jr_DListForEachElementPtrWithPrefix(list, current, prefix_size) \
for ( (current) = jr_DListHeadPtr (list); \
(current) != 0; \
(current) = jr_NextDListElementPtrWithPrefix(current, prefix_size) \
)
#define jr_DListForEachElementPtrRevWithPrefix(list, current, prefix_size) \
for ( (current) = jr_DListTailPtr (list); \
(current) != 0; \
(current) = jr_PrevDListElementPtrWithPrefix(current, prefix_size) \
)
#if defined(__cplusplus)
# undef jr_DListForEachElementPtrWithPrefix
# undef jr_DListForEachElementPtrRevWithPrefix
# define jr_DListForEachElementPtrWithPrefix(list, current, prefix_size) \
for ( (*(void **)&(current)) = jr_DListHeadPtr (list); \
(current) != 0 ; \
(*(void **)&(current)) = jr_NextDListElementPtrWithPrefix (current, prefix_size)\
)
# define jr_DListForEachElementPtrRevWithPrefix(list, current, prefix_size) \
for ( (*(void **)&(current)) = jr_DListTailPtr (list); \
(current) != 0 ; \
(*(void **)&(current)) = jr_DListElementPrevPtrWithPrefix (current, prefix_size)\
)
#endif
#define jr_DListForEachElementPtr(list, current) \
jr_DListForEachElementPtrWithPrefix (list, current, jr_DListPrefixSize (list))
#define jr_DListForEachElementPtrRev(list, current) \
jr_DListForEachElementPtrRevWithPrefix (list, current, jr_DListPrefixSize (list))
/****** Convenience Functions ******/
#define jr_DListAllocateElement(list) \
jr_DListAllocateElementWithSize (list, jr_DListElementSize (list))
#define jr_DListAllocateTmpElement(list) \
jr_DListAllocateTmpElementWithSize (list, jr_DListElementSize (list))
#define jr_FreeDListElement(obj_ptr) \
jr_FreeDListElementWithPrefix (obj_ptr, 0)
#define jr_DListNextElementPtr(list, objptr) \
jr_NextDListElementPtrWithPrefix (objptr, jr_DListPrefixSize (list))
#define jr_DListPrevElementPtr(list, objptr) \
jr_PrevDListElementPtrWithPrefix (objptr, jr_DListPrefixSize (list))
#define jr_DListMakeNullElement(list, objptr) \
jr_MakeNullDListElementWithPrefix (objptr, jr_DListPrefixSize (list))
#define jr_DListIsNullElement(list, objptr) \
jr_IsNullDListElementWithPrefix (objptr, jr_DListPrefixSize (list))
/*
** 8/15/2005: A null element doesn't mean the element isn't on a list
** since the only element on a list will have null prev and next pointers.
*/
#define jr_DListNewPrevElementPtrWithSize(list, next, size) \
jr_DListInsertElement (list, next, jr_DListAllocateElementWithSize (list, size))
#define jr_DListNewNextElementPtrWithSize(list, next, size) \
jr_DListAppendElement (list, next, jr_DListAllocateElementWithSize (list, size))
#define jr_DListNewHeadPtrWithSize(list, s) \
jr_DListNewNextElementPtrWithSize(list, 0, s)
#define jr_DListNewTailPtrWithSize(list, s) \
jr_DListNewPrevElementPtrWithSize(list, 0, s)
#define jr_DListNewHeadPtr(list) \
jr_DListNewHeadPtrWithSize (list, jr_DListElementSize (list))
#define jr_DListNewTailPtr(list) \
jr_DListNewTailPtrWithSize (list, jr_DListElementSize (list))
#define jr_DListNewPrevElementPtr(list, where) \
jr_DListNewPrevElementPtrWithSize(list, where, jr_DListElementSize (list))
#define jr_DListNewNextElementPtr(list, where) \
jr_DListNewNextElementPtrWithSize(list, where, jr_DListElementSize (list))
#define jr_DListSetNewHeadWithSize(list, obj, s) \
memcpy ( \
jr_DListNewHeadPtrWithSize(list, s), obj, s \
)
#define jr_DListSetNewTailWithSize(list, obj, s) \
memcpy ( \
jr_DListNewTailPtrWithSize(list, s), obj, s \
)
#define jr_DListSetNewPrevElementWithSize(list, where, obj, s) \
memcpy ( \
jr_DListNewPrevElementPtrWithSize(list, where, s), obj, s \
)
#define jr_DListSetNewNextElementWithSize(list, where, obj, s) \
memcpy ( \
jr_DListNewNextElementPtrWithSize(list, where, s), obj, s \
)
#define jr_DListSetNewHead(list, obj) \
jr_DListSetNewHeadWithSize (list, obj, jr_DListElementSize (list))
#define jr_DListSetNewTail(list, obj) \
jr_DListSetNewTailWithSize (list, obj, jr_DListElementSize (list))
#define jr_DListSetNewPrevElement(list, where, obj) \
jr_DListSetNewPrevElementWithSize (list, where, obj, jr_DListElementSize (list))
#define jr_DListSetNewNextElement(list, where, obj) \
jr_DListSetNewNextElementWithSize (list, where, obj, jr_DListElementSize (list))
#define jr_DListInsertToHead(list, prev) \
jr_DListAppendElement (list, 0, prev)
#define jr_DListAppendToTail(list, next) \
jr_DListAppendElement (list, jr_DListTailPtr (list), next)
#define jr_DListDeleteHead(list) \
jr_DListDeleteElement (list, jr_DListHeadPtr (list))
#define jr_DListDeleteTail(list) \
jr_DListDeleteElement (list, jr_DListTailPtr (list))
extern void * jr_DListNewElementPtrInOrderWithSizeAndUnique PROTO ((
jr_DList *list,
void *obj,
jr_int (*cmpfn) (),
jr_int size,
jr_int unique
));
#define jr_DListNewElementPtrInOrder(list, obj, cmpfn) \
jr_DListNewElementPtrInOrderWithSizeAndUnique ( \
list, obj, cmpfn, jr_DListElementSize (list), 0 \
)
#define jr_DListNewElementPtrInOrderWithSize(list, obj, cmpfn, size) \
jr_DListNewElementPtrInOrderWithSizeAndUnique ( \
list, obj, cmpfn, size, 0 \
)
#define jr_DListNewElementPtrUniquely(list, obj, cmpfn) \
jr_DListNewElementPtrInOrderWithSizeAndUnique ( \
list, obj, cmpfn, jr_DListElementSize (list), 1 \
)
#define jr_DListNewElementPtrUniquelyWithSize(list, obj, cmpfn, size) \
jr_DListNewElementPtrInOrderWithSizeAndUnique (list, obj, cmpfn, size, 1)
extern jr_int jr_DListCmp PROTO ((
jr_DList * list1,
jr_DList * list2,
jr_int (*cmpfn)()
));
extern jr_int jr_DListHash PROTO ((jr_DList *list, jr_int (*hashfn)()));
extern void * jr_DListFindInsertPtr PROTO ((
jr_DList * list,
void * obj,
jr_int (*cmpfn)()
));
extern void * jr_DListFindElementPtr PROTO ((
jr_DList * list,
void * obj,
jr_int (*cmpfn)()
));
/******** Native jr_DList Macros ********/
#define jr_DListNativeSetNewHead(list, element, type) \
(* (type *) jr_DListNewHeadPtr (list) = element)
#define jr_DListNativeSetNewTail(list, element, type) \
(* (type *) jr_DListNewTailPtr (list) = element)
#define jr_DListNativeHead(list, type) (* (type *) jr_DListHeadPtr (list))
#define jr_DListNativeTail(list, type) (* (type *) jr_DListTailPtr (list))
#endif
|
frankjas/libjr
|
include/jr/mime.h
|
#ifndef __jr_mime_h___
#define __jr_mime_h___
#include "jr/htable.h"
/******** Mime Table ********/
#define jr_MIME_FILE_LINE_COMMENT_CHAR '#'
#define jr_MIME_FILE_LINE_COMMENT_STR "//"
#define jr_MIME_FILE_WORD_DELIMITERS "\t \n"
#define jr_MIME_TABLE_FLAG_REDEFINITIONS 0x0001
#define jr_MIME_TABLE_EXIT_ON_ERROR 0x0002
typedef struct {
jr_HTable str_table [1];
} jr_MimeTableType;
typedef struct {
char * file_ext_str;
char * mime_type_str;
char * file_name;
jr_int line_number;
} jr_MimeInfoType;
extern void jr_MimeTableInit PROTO ((
jr_MimeTableType * mime_table_ptr
));
extern void jr_MimeTableUndo PROTO ((
jr_MimeTableType * mime_table_ptr
));
extern jr_int jr_MimeTableAddNewElement PROTO ((
jr_MimeTableType * mime_table_ptr,
const char * file_ext_str,
const char * mime_type_str,
const char * file_name,
jr_int line_number,
char * error_buf
));
extern const char * jr_MimeTableFindMimeType(
jr_MimeTableType * mime_table_ptr,
const char * file_ext_str);
extern jr_int jr_MimeTableLoadFromFileName PROTO ((
jr_MimeTableType * mime_table_ptr,
char * rfn,
jr_int mode,
char * error_buf
));
extern jr_int jr_MimeTableLoadFromFilePtr PROTO ((
jr_MimeTableType * mime_table_ptr,
FILE * rfp,
char * rfn,
jr_int mode,
char * error_buf
));
extern void jr_MimeTablePrintForPhp PROTO ((
jr_MimeTableType * mime_table_ptr,
const char * var_name,
const char * indent_str,
FILE * wfp
));
#define jr_MimeTableForEachMimeInfoPtr(mime_table_ptr, mime_info_ptr) \
jr_HTableForEachElementPtr ((mime_table_ptr)->str_table, mime_info_ptr)
extern void jr_MimeInfoInit PROTO ((
jr_MimeInfoType * mime_info_ptr,
const char * file_ext_str,
const char * opt_mime_type_str,
const char * opt_file_name,
jr_int opt_line_number
));
extern void jr_MimeInfoUndo PROTO ((
jr_MimeInfoType * mime_info_ptr
));
extern jr_int jr_MimeInfoCmp PROTO ((
const void * void_ptr_1,
const void * void_ptr_2
));
extern jr_int jr_MimeInfoHash PROTO ((
const void * void_ptr_1
));
#define jr_MimeInfoFileExtString(mime_info_ptr) \
((mime_info_ptr)->file_ext_str)
#define jr_MimeInfoMimeTypeString(mime_info_ptr) \
((mime_info_ptr)->mime_type_str)
#define jr_MimeInfoFileName(mime_info_ptr) \
((mime_info_ptr)->file_name)
#define jr_MimeInfoLineNumber(mime_info_ptr) \
((mime_info_ptr)->line_number)
#endif
|
frankjas/libjr
|
libjr/struct/jr_heap.c
|
#include "jr/heap.h"
#include "jr/misc.h"
void jr_HeapInsert (heap, obj, cmpfn)
jr_AList *heap;
void *obj;
jr_int (*cmpfn) ();
{
memcpy (jr_AListNewTailPtr (heap), obj, jr_HeapElementSize(heap));
if (jr_HeapSize(heap) > 1) {
jr_HeapPercolateUp (heap, jr_HeapLastLeafIndex(heap), cmpfn);
}
}
void jr_HeapDeleteMin (heap, obj, cmpfn)
jr_AList *heap;
void *obj;
jr_int (*cmpfn) ();
{
/* save the root
*/
memcpy (obj, jr_HeapElementPtr(heap, 0), jr_HeapElementSize(heap));
/* copy the last leaf into root
*/
memcpy (jr_HeapElementPtr(heap, 0), jr_HeapLastLeafPtr(heap), jr_HeapElementSize(heap));
jr_AListDeletedTailPtr (heap);
jr_HeapPercolateDown (heap, 0, cmpfn);
}
void jr_Heapify (heap, cmpfn)
jr_AList *heap;
jr_int (*cmpfn) ();
{
jr_int node_index;
for (node_index = jr_HeapLastNodeIndex(heap); node_index >= 0; node_index--) {
jr_HeapPercolateDown (heap, node_index, cmpfn);
}
}
void jr_HeapPercolateDown (heap, node_index, cmpfn)
jr_AList *heap;
jr_int node_index;
jr_int (*cmpfn) ();
{
void *node_ptr, *right_child_ptr, *left_child_ptr;
if (!jr_HeapHasRightChildIndex (heap, node_index)) return;
/*
* it has no children, return
*/
node_ptr = jr_HeapElementPtr(heap, node_index);
right_child_ptr = jr_HeapRightChildPtr (heap, node_index);
left_child_ptr = jr_HeapLeftChildPtr (heap, node_index);
/*
* right <= node and (no left or right <= left)
* switch right and node
*/
if ((*cmpfn) (right_child_ptr, node_ptr) <= 0 &&
(!jr_HeapHasLeftChildIndex(heap, node_index) ||
(*cmpfn) (right_child_ptr, left_child_ptr) <= 0)) {
jr_memswitch (node_ptr, right_child_ptr, jr_HeapElementSize(heap));
if (!jr_HeapIsNodeIndex(heap, jr_HeapRightChildIndex(heap, node_index))) return;
jr_HeapPercolateDown (heap, jr_HeapRightChildIndex(heap, node_index), cmpfn);
return;
}
/* we know right > node or
* right <= node and has left and left < right
*/
/* check if has left and left < node and left <= right
* switch left and node
*/
if (jr_HeapHasLeftChildIndex(heap, node_index) &&
(*cmpfn) (left_child_ptr, node_ptr) <= 0) {
jr_memswitch (node_ptr, left_child_ptr, jr_HeapElementSize(heap));
if (!jr_HeapIsNodeIndex(heap, jr_HeapLeftChildIndex(heap, node_index))) return;
jr_HeapPercolateDown (heap, jr_HeapLeftChildIndex(heap, node_index), cmpfn);
return;
}
}
void jr_HeapPercolateUp (heap, node_index, cmpfn)
jr_AList *heap;
jr_int node_index;
jr_int (*cmpfn) ();
{
void *node_ptr, *parent_ptr;
node_ptr = jr_HeapElementPtr(heap, node_index);
parent_ptr = jr_HeapParentPtr(heap, node_index);
if ((*cmpfn) (node_ptr, parent_ptr) < 0) {
jr_memswitch (node_ptr, parent_ptr, jr_HeapElementSize(heap));
if (!jr_HeapIsRootIndex(heap, jr_HeapParentIndex(heap, node_index))) {
jr_HeapPercolateUp (heap, jr_HeapParentIndex(heap, node_index), cmpfn);
}
}
}
/*
void HeapToSortedAL (heap, cmpfn)
jr_AList *heap;
jr_int (*cmpfn) ();
{
jr_int size = jr_HeapSize(heap);
while (jr_HeapSize(heap) > 0) {
jr_memswitch (jr_HeapElementPtr(heap, 0), jr_HeapLastLeafPtr(heap),
jr_HeapElementSize(heap));
jr_AListDeletedTailPtr (heap);
jr_HeapPercolateDown (heap, 0, cmpfn);
}
}
*/
|
frankjas/libjr
|
libjr/syscalls/jr_aprbuf.c
|
<reponame>frankjas/libjr
#include "ezport.h"
#include <string.h>
#include <apr-1/apr_pools.h>
#include <apr-1/apr_lib.h>
#include "jr/apr.h"
#include "jr/malloc.h"
/*
** 3/29/08: jr_aprbuf_t defined here to avoid exposing APR headers
** jr_aprbuf_t must by type compatible with apr_vformatter_buff_t, which
** must be the first field.
*/
struct jr_aprbuf {
apr_vformatter_buff_t vbuff[1];
char * output_buffer;
jr_int buf_size;
jr_int error_status;
char * error_buf;
void * io_info;
int (*write_fn)(
void * io_info,
void * buf,
int buf_len,
char * error_buf);
unsigned is_in_flush : 1;
};
#define jr_aprbuf_is_in_flush(aprbuf_ptr) \
((aprbuf_ptr)->is_in_flush)
#define jr_aprbuf_set_is_in_flush(aprbuf_ptr, v) \
((aprbuf_ptr)->is_in_flush = (v) != 0)
void jr_aprbuf_init (
jr_aprbuf_t * aprbuf_ptr,
void * io_info,
int (*write_fn)( void *io_info, void *buf, int buf_len, char *error_buf ),
jr_int buf_size)
{
memset (aprbuf_ptr, 0, sizeof (*aprbuf_ptr));
aprbuf_ptr->io_info = io_info;
aprbuf_ptr->write_fn = write_fn;
aprbuf_ptr->output_buffer = jr_malloc (buf_size);
aprbuf_ptr->buf_size = buf_size;
aprbuf_ptr->vbuff->curpos = aprbuf_ptr->output_buffer;
aprbuf_ptr->vbuff->endpos = aprbuf_ptr->vbuff->curpos + aprbuf_ptr->buf_size;
}
void jr_aprbuf_undo (
jr_aprbuf_t * aprbuf_ptr)
{
jr_free (aprbuf_ptr->output_buffer);
}
jr_aprbuf_t *jr_aprbuf_create (
void * io_info,
int (*write_fn)( void *io_info, void *buf, int buf_len, char *error_buf ),
jr_int buf_size)
{
jr_aprbuf_t * aprbuf_ptr = jr_malloc (sizeof (jr_aprbuf_t));
jr_aprbuf_init (aprbuf_ptr, io_info, write_fn, buf_size);
return aprbuf_ptr;
}
void jr_aprbuf_destroy (
jr_aprbuf_t * aprbuf_ptr)
{
jr_aprbuf_undo (aprbuf_ptr);
jr_free (aprbuf_ptr);
}
jr_int jr_aprbuf_flush (
jr_aprbuf_t * aprbuf_ptr)
{
jr_int num_bytes;
jr_int status;
char * error_buf = aprbuf_ptr->error_buf;
jr_aprbuf_set_is_in_flush (aprbuf_ptr, 1);
num_bytes = aprbuf_ptr->vbuff->curpos - aprbuf_ptr->output_buffer;
if (num_bytes >= 0) {
status = (*aprbuf_ptr->write_fn) (
aprbuf_ptr->io_info,
aprbuf_ptr->output_buffer, num_bytes,
error_buf
);
if (status < 0) {
aprbuf_ptr->error_status = status;
goto return_status;
}
else if (status < num_bytes) {
/*
** 2/7/07: didn't write everything, shift the leftover to the front of the buffer
*/
memmove (
aprbuf_ptr->output_buffer,
aprbuf_ptr->output_buffer + status,
num_bytes - status
);
aprbuf_ptr->vbuff->curpos = aprbuf_ptr->output_buffer + num_bytes - status;
}
else {
aprbuf_ptr->vbuff->curpos = aprbuf_ptr->output_buffer;
}
}
status = 0;
return_status : {
jr_aprbuf_set_is_in_flush (aprbuf_ptr, 0);
}
return status;
}
typedef jr_int (*jr_aprbuf_flushfn_t)( apr_vformatter_buff_t * apr_buff_ptr);
jr_int jr_aprbuf_vformatter(
jr_aprbuf_t * aprbuf_ptr,
const char * control_string,
va_list arg_list)
{
jr_int status;
/*
** 3/25/09: aprbuf_ptr and apr_vformatter_buff_t need to be type compatible
** because of this call.
*/
status = apr_vformatter (
(jr_aprbuf_flushfn_t) jr_aprbuf_flush, (apr_vformatter_buff_t *) aprbuf_ptr,
control_string,
arg_list
);
return status;
}
void jr_aprbuf_set_error_buf(
jr_aprbuf_t * aprbuf_ptr,
char * error_buf)
{
aprbuf_ptr->error_buf = error_buf;
}
int jr_aprbuf_status(
jr_aprbuf_t * aprbuf_ptr)
{
return aprbuf_ptr->error_status;
}
int jr_aprbuf_needs_flush(
jr_aprbuf_t * aprbuf_ptr)
{
if ( !jr_aprbuf_is_in_flush( aprbuf_ptr )
&& (aprbuf_ptr)->vbuff->curpos - (aprbuf_ptr)->output_buffer) {
return 1;
}
return 0;
}
|
frankjas/libjr
|
libjr/syscalls/jr_socket_unix.c
|
<reponame>frankjas/libjr
#include "ezport.h"
#ifndef ostype_winnt
#include <string.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include <apr-1/apr_pools.h>
#include <apr-1/apr_portable.h>
#include "jr/apr.h"
#include "jr/error.h"
jr_int jr_socket_connect_unix (
jr_socket_t * socket_info,
const char * socket_path,
char * error_buf)
{
apr_os_sock_info_t apr_sock_info[1];
struct sockaddr_un sockaddr_un[1];
unsigned jr_int max_path_length = sizeof( sockaddr_un->sun_path) - 1;
jr_int sd = -1;
jr_int status;
if (strlen( socket_path) > max_path_length) {
jr_esprintf( error_buf, "path too long (%d): max. is %u",
(jr_int) strlen( socket_path), max_path_length
);
status = jr_MISUSE_ERROR;
goto return_status;
}
if (socket_info->apr_pool_ptr == 0) {
status = apr_pool_create ((apr_pool_t **) &socket_info->apr_pool_ptr, NULL);
if (status != 0) {
jr_esprintf (error_buf, "couldn't create pool: %s",
jr_apr_strerror( status, error_buf)
);
status = jr_ConvertAprErrno (status);
goto return_status;
}
}
memset( sockaddr_un, 0, sizeof( *sockaddr_un));
sockaddr_un->sun_family = AF_LOCAL;
snprintf( sockaddr_un->sun_path, max_path_length, "%s", socket_path);
memset( apr_sock_info, 0, sizeof( *apr_sock_info));
apr_sock_info->family = sockaddr_un->sun_family;
apr_sock_info->type = SOCK_STREAM;
apr_sock_info->protocol = 0;
sd = socket( apr_sock_info->family, apr_sock_info->type, apr_sock_info->protocol);
if (sd < 0) {
jr_esprintf( error_buf, "couldn't create socket: %s", strerror( errno));
status = jr_ConvertErrno (status);
goto return_status;
}
status = connect( sd, (struct sockaddr *) sockaddr_un, sizeof( *sockaddr_un));
if (status != 0) {
jr_esprintf( error_buf, "couldn't connect socket: %s", strerror( errno));
status = jr_ConvertErrno (status);
goto return_status;
}
apr_sock_info->os_sock = (apr_os_sock_t *) &sd;
/*
** 6-5-2012: re-allocates the apr socket.
*/
status = apr_os_sock_make (
(apr_socket_t **) &socket_info->apr_socket_ptr,
apr_sock_info,
socket_info->apr_pool_ptr
);
if (status != 0) {
jr_esprintf (error_buf, "%s", jr_apr_strerror( status, error_buf));
status = jr_ConvertAprErrno (status);
goto return_status;
}
if (socket_info->is_nonblocking) {
/*
** 2/27/07: The default is blocking.
*/
status = jr_socket_set_nonblock (socket_info, 1, error_buf);
if (status != 0) {
goto return_status;
}
}
status = 0;
sd = -1;
return_status : {
if (sd >= 0) {
close( sd);
}
}
return status;
}
#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/syscalls.h
|
#ifndef __jr_syscalls_h___
#define __jr_syscalls_h___
#include "ezport.h"
#include <stdio.h>
#include <sys/types.h>
#include "jr/time.h"
/******** permissions ********/
#define jr_PERM_S_OWNER 02000
#define jr_PERM_S_GROUP 01000
#define jr_PERM_R_OWNER 00400
#define jr_PERM_W_OWNER 00200
#define jr_PERM_X_OWNER 00100
#define jr_PERM_R_GROUP 00040
#define jr_PERM_W_GROUP 00020
#define jr_PERM_X_GROUP 00010
#define jr_PERM_R_OTHER 00004
#define jr_PERM_W_OTHER 00002
#define jr_PERM_X_OTHER 00001
#define jr_PERM_RW_OWNER (jr_PERM_R_OWNER | jr_PERM_W_OWNER)
#define jr_PERM_RW_GROUP (jr_PERM_R_GROUP | jr_PERM_W_GROUP)
#define jr_PERM_RW_OTHER (jr_PERM_R_OTHER | jr_PERM_W_OTHER)
#define jr_PERM_RW_ALL \
(jr_PERM_RW_OWNER | jr_PERM_RW_GROUP | jr_PERM_RW_OTHER)
#define jr_PERM_RWX_OWNER (jr_PERM_R_OWNER | jr_PERM_W_OWNER | jr_PERM_X_OWNER)
#define jr_PERM_RWX_GROUP (jr_PERM_R_GROUP | jr_PERM_W_GROUP | jr_PERM_X_GROUP)
#define jr_PERM_RWX_OTHER (jr_PERM_R_OTHER | jr_PERM_W_OTHER | jr_PERM_X_OTHER)
#define jr_PERM_RWX_ALL \
(jr_PERM_RWX_OWNER | jr_PERM_RWX_GROUP | jr_PERM_RWX_OTHER)
extern jr_int jr_FileNameSetPerms (
const char * path,
jr_int mode,
char * error_buf);
extern jr_int jr_FileNameGetPerms (
const char * path,
char * error_buf);
extern jr_int jr_UnixModeToPerms (
mode_t unix_mode);
extern mode_t jr_PermsToUnixMode (
unsigned jr_int perm_flags);
extern unsigned jr_int jr_PermsFromString (
const char * perms_string);
extern jr_int jr_PermsAddFromString (
jr_int curr_perms,
const char * perms_string);
#define jr_PERMS_STRING_LENGTH 9
extern void jr_PermsToString (
char * perm_string,
unsigned jr_int perm_flags);
/******** file ownership ********/
extern jr_int jr_FileNameSetOwner (
const char * path,
const char * owner_name,
const char * group_name,
char * error_buf);
extern jr_int jr_IsChownAllowed();
/******** directories ********/
extern jr_int jr_chdir (
const char * dir_path,
char * error_buf);
extern jr_int jr_getcwd (
char * path_buf,
jr_int path_buf_size,
char * opt_error_buf);
extern char * jr_getcwd_malloc (
char * opt_error_buf);
extern jr_int jr_MakeDirectoryPath PROTO((
const char * pathname,
jr_int perm_flags,
char * errbuf
)) ;
/******** File Descriptor Operations ********/
extern jr_int jr_FileDescHasPendingInput PROTO((jr_int fd)) ;
extern time_t jr_FilePtrModifiedTime PROTO((FILE *fp)) ;
extern time_t jr_FileDescModifiedTime PROTO((jr_int fd)) ;
extern time_t jr_FileNameModifiedTime PROTO((const char *filename)) ;
extern jr_seconds_t jr_FileNameSetModTime PROTO((
const char * filename,
jr_seconds_t mod_time,
char * error_buf
));
extern jr_seconds_t jr_FileNameModTimeTouch PROTO((
const char * filename,
char * error_buf
));
extern size_t jr_FilePtrDiskSize PROTO((FILE *fp)) ;
extern size_t jr_FileDescDiskSize PROTO((jr_int fd)) ;
extern size_t jr_FileNameDiskSize PROTO((const char *fn)) ;
extern off_t jr_FileDescBlockSize PROTO((jr_int fd));
/*
* These functions added by FJ 4/30/94
*/
extern jr_int jr_FileDescReadLock PROTO ((
jr_int file_descriptor,
jr_int time_out,
char * error_buf
));
extern jr_int jr_FileDescWriteLock PROTO ((
jr_int file_descriptor,
jr_int time_out,
char * error_buf
));
extern void jr_FileDescUnLock PROTO ((
jr_int file_descriptor
));
#define jr_FilePtrReadLock(fp, time_out, error_buf) \
jr_FileDescReadLock (fileno (fp), time_out, error_buf)
#define jr_FilePtrWriteLock(fp, time_out, error_buf) \
jr_FileDescWriteLock (fileno (fp), time_out, error_buf)
#define jr_FilePtrUnLock(fp) \
jr_FileDescUnLock (fileno (fp))
extern jr_int jr_fcntl_flock PROTO ((
jr_int fd,
jr_int operation,
jr_int is_blocking
));
/*
* jr_fcntl_flock() lock types are: F_UNLCK, F_RDLCK, F_WRLCK
*/
#ifdef __jr_compiling_timelock
extern jr_int jr_FileDescTimedFlock PROTO((
jr_int fd,
const char * how,
jr_int time_seconds
)) ;
#else
extern jr_int jr_FileDescTimedFlock PROTO((
jr_int fd,
const char * how,
...
)) ;
#endif
extern jr_int jr_FileDescCopy PROTO((
jr_int wfd,
jr_int rfd,
void * buf,
jr_int buffer_length
)) ;
/******** Non-Blocking I/O ********/
extern jr_int jr_FileDescInitNonBlockingIO PROTO ((
jr_int fd,
char * opt_error_buf
));
extern jr_int jr_FileDescUndoNonBlockingIO PROTO ((
jr_int fd,
char * opt_error_buf
));
#define jr_FilePtrInitNonBlockingIO(fp, opt_error_buf) \
jr_FileDescInitNonBlockingIO (fileno (fp), opt_error_buf)
#define jr_FilePtrUndoNonBlockingIO(fp, opt_error_buf) \
jr_FileDescUndoNonBlockingIO (fileno (fp), opt_error_buf)
/******** Asynchronous I/O ********/
extern void jr_BlockAsyncIO PROTO ((
void * old_mask_ptr
));
extern void jr_UnBlockAsyncIO PROTO ((
void * old_mask_ptr
));
extern jr_int jr_InitAsyncIO PROTO ((
jr_int fd,
FILE * fp,
void (*handler_fn) (),
void * handler_param,
jr_int is_for_reading,
char * opt_error_buf
));
extern jr_int jr_UndoAsyncIO PROTO ((
jr_int fd,
jr_int is_for_reading,
char * opt_error_buf
));
#define jr_FileDescInitReadAsyncIO(fd, handler_fn, handler_param, opt_error_buf) \
jr_InitAsyncIO (fd, 0, handler_fn, handler_param, 1, opt_error_buf)
#define jr_FileDescUndoReadAsyncIO(fd, opt_eb) \
jr_UndoAsyncIO (fd, 1, opt_eb)
#define jr_FileDescInitWriteAsyncIO(fd, handler_fn, handler_param, opt_error_buf) \
jr_InitAsyncIO (fd, 0, handler_fn, handler_param, 0, opt_error_buf)
#define jr_FileDescUndoWriteAsyncIO(fd, opt_eb) \
jr_UndoAsyncIO (fd, 0, opt_eb)
#define jr_FilePtrInitReadAsyncIO(fp, handler_fn, handler_param, opt_error_buf) \
jr_InitAsyncIO (fileno (fp), fp, handler_fn, handler_param, 1, opt_error_buf)
#define jr_FilePtrUndoReadAsyncIO(fp, opt_eb) \
jr_UndoAsyncIO (fileno (fp), 1, opt_eb)
#define jr_FilePtrInitWriteAsyncIO(fp, handler_fn, handler_param, opt_error_buf) \
jr_InitAsyncIO (fileno (fp), fp, handler_fn, handler_param, 0, opt_error_buf)
#define jr_FilePtrUndoWriteAsyncIO(fp, opt_eb) \
jr_UndoAsyncIO (fileno (fp), 0, opt_eb)
/*
* These functions should return a 'pid_t'
* but that would require _POSIX_SOURCE to include
* this header file
*/
/******** Terminal Control *******/
extern jr_int jr_SetTerminalMode PROTO ((
jr_int fd,
jr_int mode_constant,
jr_int turn_on_mode,
char * error_buf
));
#define jr_CBREAK_MODE 1
#define jr_SetCbreakMode(fd, turn_on_mode, error_buf) \
jr_SetTerminalMode (fd, jr_CBREAK_MODE, turn_on_mode, error_buf)
extern jr_int jr_SimulateTerminalInputFromString PROTO((
const char * string_arg
)) ;
/******** Path Manipulations ********/
extern jr_int jr_FileNameToAbsolutePath PROTO((
char * result_buf,
jr_int result_buf_length,
const char * potentially_relative_filename
)) ;
extern void jr_FileNameToRelativePath PROTO((
char * target_path_buf,
jr_int buflen,
const char * source_path_arg,
const char * relative_to_here_arg
)) ;
extern char * jr_PathSearch PROTO ((
char * file_name,
char ** dir_vector
));
extern jr_int jr_FileNameFindInPathString PROTO((
const char * search_for_file_name,
const char * path_string,
char * result_buf,
jr_int result_buf_length
)) ;
extern jr_int jr_FileNameFindInPathVector PROTO((
const char * search_for_file_name,
char ** path_vector,
char * result_buf,
jr_int result_buf_length
)) ;
extern jr_int jr_PathStringCopyWithDollarAndTildeExpansion PROTO((
char * target_str,
const char * source_str
)) ;
extern char * jr_NewStringFromDollarAndTildeExpansion PROTO((
const char * word
)) ;
/******** Canonical Paths ********/
extern jr_int jr_GetCanonicalPath (
const char * user_path,
char * path_buf,
jr_int path_buf_size,
char * error_buf);
extern const char * jr_MallocCanonicalPath (
const char * user_path,
char * error_buf);
/******** Temporary Files ********/
extern void jr_MkTemp PROTO ((
char * tmp_name_template
));
extern const char * jr_MkTempInTempDir (
const char * tmp_name_template);
extern FILE * jr_TempFileOpen PROTO ((
char * opt_template,
char * error_buf
));
extern jr_int jr_GetTempDir PROTO ((
char * tmp_dir_buf,
jr_int tmp_dir_buf_length,
char * error_buf
));
/******** File Types ********/
extern jr_int jr_PathIsDirectory (
const char * pathname,
char * error_buf) ;
extern jr_int jr_PathIsLink (
const char * pathname,
char * error_buf);
extern jr_int jr_PathIsFile(
const char * pathname,
char * opt_error_buf);
/******** Moving/Copying/Removing Files ********/
extern jr_int jr_FileNameSafeCopy PROTO ((
const char * replaced_file,
const char * new_data_file,
FILE * opt_new_data_file_ptr,
char * error_buf
));
extern jr_int jr_MoveFileName PROTO ((
const char * old_file_path,
const char * new_file_path,
char * error_buf
));
/*
** 11/26/05: Copies the file if the rename fails,
** i.e. if the files are on different devices.
*/
extern jr_int jr_MovePath (
const char * old_path_name,
const char * new_path_name,
char * error_buf);
/*
** 11/26/05: no copy, so works for directories as well.
*/
extern jr_int jr_RemovePath (
const char * path_name,
char * error_buf);
extern jr_int jr_Unlink (
const char * file_path,
char * opt_error_buf);
extern jr_int jr_UnlinkNoApr (
const char * file_path,
char * opt_error_buf);
extern jr_int jr_SymLink (
const char * link_target_path,
const char * new_link_path,
char * error_buf);
extern jr_int jr_ReadLink (
const char * link_path,
char * link_target_buf,
jr_int buf_length,
char * error_buf);
extern jr_int jr_FileExists(
const char * file_path);
extern jr_int jr_FileNameSetMtime (
const char * file_path,
jr_seconds_t time_sec,
char * error_buf);
extern jr_int jr_FileNameGetMtime (
const char * file_path,
jr_seconds_t * time_sec_ref,
char * error_buf);
/******** User Names and attributes ********/
extern jr_int jr_CheckUnixPassword PROTO((
char * username,
char * unencrypted_password_text,
void * pw_entry
)) ;
extern jr_int jr_GetUserName PROTO ((
char * namebuf,
jr_int buf_length,
char * error_buf
));
extern jr_int jr_GetGroupName PROTO ((
char * namebuf,
jr_int buf_length,
char * error_buf
));
extern jr_int jr_GetUserHomeDir PROTO ((
char * path_buf,
jr_int path_buf_length,
char * error_buf
));
extern jr_int jr_IsRootUser PROTO ((void));
/******** Signals ********/
extern void jr_SigChildHandler PROTO ((jr_int signum));
extern char * jr_SignalName PROTO ((unsigned jr_int signum));
/******** Asynchronous Function Calls ********/
extern jr_int jr_AddAsyncFunction (
void (*handler_fn) (),
void * handler_param,
jr_int num_seconds,
jr_int do_repeat,
char * error_buf);
extern void jr_RemoveAsyncFunction (
void (*handler_fn) (),
void * handler_param);
extern jr_int jr_GetAsyncFunctionNumSeconds (
void (*handler_fn) (),
void * handler_param);
extern jr_int jr_GetAsyncFunctionCallTime (
void (*handler_fn) (),
void * handler_param);
/******** executing commands ********/
#define jr_EXEC_ERROR -1
#define jr_EXEC_SPAWN_ERROR -2
#define jr_EXEC_RUN_ERROR -3
#define jr_EXEC_INTERNAL_ERROR -4
extern jr_int jr_exec_cmd (
const char * command_str,
char * error_buf);
extern FILE * jr_popen (
const char * command_str,
const char * mode_str,
char * error_buf);
extern jr_int jr_pclose (
FILE * fp,
char * error_buf);
extern char * jr_NewStringFilteredFromCommandVector PROTO((
char ** argv,
const char * input_str,
char *error_buf
));
extern jr_int jr_Invoke1WayCommandVector PROTO ((
char ** argv,
FILE ** rfp_ptr,
char * error_buf
));
extern jr_int jr_Invoke1WayCommandVectorWithStderr PROTO ((
char ** argv,
FILE ** rfp_ptr,
char * error_buf
));
extern jr_int jr_InvokeCommandVector PROTO ((
char ** argv,
FILE * fp_array[],
jr_int num_fps,
char * error_buf
));
#define jr_Invoke2WayCommandVector(argv, fps, eb) \
jr_InvokeCommandVector (argv, fps, 2, eb)
#define jr_Invoke2WayCommandVectorWithStderr(argv, fps, eb) \
jr_InvokeCommandVector (argv, fps, 3, eb)
/******** Miscellaneous ********/
extern void jr_critical_section PROTO ((
char * how,
void * opt_old_mask_ptr
));
extern char * jr_ExitStatusToString PROTO ((
char * status_buf,
jr_int status
));
extern jr_int jr_uninterrupted_sleep PROTO ((
jr_int sleep_sec,
jr_int sleep_usec
));
extern void jr_sleep PROTO ((
jr_int sleep_sec,
jr_int sleep_usec
));
extern jr_int jr_getpid (void);
extern jr_int jr_IsTapeFilePtr PROTO ((
FILE * fp,
char * error_buf
));
extern jr_int jr_IsInteractiveFilePtr PROTO ((
FILE * fp,
char * error_buf
));
extern jr_int jr_gethostname(
char * host_name,
jr_int buf_length,
char * error_buf);
#define jr_MAXHOSTNAME 128
#endif
|
frankjas/libjr
|
libjr/string/vlsout.c
|
#define _POSIX_SOURCE 1
#include "ezport.h"
#include <stdio.h>
#include <string.h>
#include "jr/vector.h"
void jr_VectorDisplayLikeLs(wfp, vector_arg, num_items_in_vector, display_width)
FILE * wfp ;
const char ** vector_arg ;
jr_int num_items_in_vector ;
jr_int display_width ;
{
jr_int max_length_entry = jr_VectorFindMaximum(
vector_arg, num_items_in_vector,
(jr_int (*) ()) strlen
) ;
jr_int column_width = (max_length_entry + 2) ;
jr_int num_columns = display_width / column_width ;
jr_int num_rows ;
num_rows = (num_items_in_vector / num_columns) ;
if ((num_items_in_vector % num_columns) > 0) num_rows++ ;
{
jr_int row_index ;
jr_int column_index ;
jr_int vector_index ;
jr_int padding_width ;
jr_int i ;
row_index = 0 ;
column_index = 0 ;
for (i = 0 ; i < num_items_in_vector; i++) {
vector_index = ((column_index * num_rows) + row_index) ;
if (column_index >= (num_columns-1)) padding_width = 1 ;
else padding_width = column_width ;
if (vector_index < num_items_in_vector) {
fprintf(wfp, "%-*.*s",
padding_width, column_width, vector_arg[vector_index]
) ;
}
else {
fprintf(wfp, "%-*.*s",
padding_width, column_width, ""
) ;
}
column_index++ ;
if (column_index >= (num_columns-1)) {
fprintf(wfp, "\n") ;
column_index = 0 ;
row_index++ ;
}
}
if (column_index != 0) {
for ( ; column_index < num_columns; column_index++) {
if (column_index >= (num_columns-1)) padding_width = 1 ;
else padding_width = column_width ;
fprintf(wfp, "%-*.*s",
column_width, column_width, ""
) ;
}
fprintf(wfp, "\n") ;
}
}
}
|
frankjas/libjr
|
libjr/string/substrix.c
|
#include "ezport.h"
#include <string.h>
#include "jr/string.h"
jr_int jr_SubStringIndex(search_string, pattern)
const char * search_string ;
const char * pattern ;
{
char * substring_location ;
substring_location = strstr((char *) search_string, (char *) pattern) ;
if (substring_location == 0) {
return(-1) ;
}
else {
return(substring_location - search_string) ;
}
}
|
frankjas/libjr
|
libjr/missing/rewinddir.c
|
<gh_stars>0
#define _POSIX_SOURCE 1
#include "ezport.h"
#ifdef missing_rewinddir_objects
#include <dirent.h>
void rewinddir(dirp)
DIR * dirp;
{
seekdir (dirp, 0L);
}
#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/jr_uuid.c
|
<reponame>frankjas/libjr
#define _POSIX_SOURCE 1
#include "ezport.h"
#include <apr-1/apr_uuid.h>
#include "jr/uuid.h"
void jr_UUIdAsgnRandom (uuid_info)
jr_UUIdStruct * uuid_info;
{
apr_uuid_get ((apr_uuid_t *) uuid_info);
}
void jr_UUIdAsgnTime (uuid_info)
jr_UUIdStruct * uuid_info;
{
apr_uuid_get ((apr_uuid_t *) uuid_info);
}
void jr_UUIdAsgnFromString (uuid_info, string_buf)
jr_UUIdStruct * uuid_info;
const char * string_buf;
{
apr_uuid_parse ((apr_uuid_t *) uuid_info, string_buf);
}
char *jr_UUIdToString (uuid_info, string_buf)
const jr_UUIdStruct * uuid_info;
char * string_buf;
{
apr_uuid_format (string_buf, (apr_uuid_t *) uuid_info);
return string_buf;
}
void jr_UUIdAvoidMallocLeak ()
{
apr_uuid_t tmp_uuid[1];
apr_uuid_get (tmp_uuid);
}
|
frankjas/libjr
|
libjr/htable/htable.c
|
#include "project.h"
jr_HTable *jr_HTableCreate (element_size, hashfn, cmpfn)
jr_int element_size;
jr_int (*hashfn) PROTO ((const void *));
jr_int (*cmpfn) PROTO ((const void *, const void *));
{
jr_HTable *htable = (jr_HTable *) jr_malloc (sizeof (jr_HTable));
jr_HTableInit (htable, element_size, hashfn, cmpfn);
return(htable) ;
}
void jr_HTableInit (htable, element_size, hashfn, cmpfn)
jr_HTable * htable;
jr_int element_size;
jr_int (*hashfn) PROTO ((const void *));
jr_int (*cmpfn) PROTO ((const void *, const void *));
{
htable->element_size = element_size;
htable->hashfn = hashfn;
htable->cmpfn = (jr_int (*) (const void *, const void *, ...)) cmpfn;
htable->cmp_arg = 0;
htable->buckets_array = 0;
htable->num_buckets = 0;
htable->delete_list = -1; /* end-of-list marker */
htable->num_deletes = 0;
jr_AListInit (htable->entry_array, element_size);
jr_AListSetPrefixSize (htable->entry_array, sizeof (jr_HTableElementStruct), 0, 0);
}
void jr_HTableDestroy (htable)
jr_HTable * htable;
{
jr_HTableUndo (htable);
jr_free (htable);
}
void jr_HTableUndo (htable)
jr_HTable * htable;
{
jr_AListUndo (htable->entry_array);
if (htable->buckets_array) {
jr_free (htable->buckets_array);
}
}
void jr_HTableSetPrefixSize (htable, prefix_size, prefix_transform_fn, prefix_transform_arg)
jr_HTable * htable;
jr_int prefix_size;
void (*prefix_transform_fn) ();
void * prefix_transform_arg;
{
jr_AListSetPrefixSize (
htable->entry_array,
prefix_size + sizeof (jr_HTableElementStruct),
prefix_transform_fn, prefix_transform_arg
);
}
static void *_jr_HTableElementPtr (htable, i)
jr_HTable * htable;
jr_int i;
{
if (0) {
_jr_HTableElementPtr (htable, i);
}
return jr_HTableElementPtr (htable, i);
}
|
frankjas/libjr
|
libjr/missing/pathconf.c
|
#define _POSIX_SOURCE 1
#include "ezport.h"
#ifdef missing_pathconf_objects
#include <errno.h>
#include <unistd.h>
#include <sys/param.h>
#include <sys/dir.h>
long pathconf(file_name, desired_value)
const char * file_name ;
int desired_value ;
{
switch(desired_value) {
case _PC_LINK_MAX :
/*
* maximum number of links to a file or directory.
* We should open this name to see if its a directory
* and report zero in that event on most systems.
*/
return(MAXLINK) ; /* sys/param.h */
case _PC_MAX_CANON :
/*
* maximum number of bytes on a line
* using canonical input processing
*/
return(CANBSIZ) ; /* sys/param.h */
case _PC_MAX_INPUT :
/*
* maximum "packet" size that can be sent to a tty device.
* I couldn't find a constant like this so I assumed
* it would be the same as CANBSIZ
*/
return(CANBSIZ) ; /* sys/param.h */
case _PC_NAME_MAX :
return(MAXNAMLEN) ; /* sys/dir.h */
case _PC_PATH_MAX :
return(MAXPATHLEN) ; /* sys/param.h */
case _PC_PIPE_BUF :
/*
* 4096 is in the BUGS section of the man
* page for pipe() but not a constant anywhere
* that I can find.
*/
return(4096) ;
case _PC_CHOWN_RESTRICTED :
/*
* Use of chown is always restricted to root on our system
*/
return(1) ; /* Boolean determined experimentally */
case _PC_NO_TRUNC :
/*
* always 1 on reasonable systems, where if you try to create
* a file with a name that is too long, open or creat fail
* and errno will be set to ENAMETOOLONG
*/
return(1) ; /* Boolean from the man for open() */
case _PC_VDISABLE :
/*
* Is there a character that can disable special tty functions?
* None that I can be sure of, so just return false.
*/
return(0) ; /* Boolean, same as found on Sun and safest */
default :
errno = EINVAL ;
return(-1) ;
}
}
long fpathconf(fd, desired_value)
int fd ;
int desired_value ;
{
return pathconf("dummy", desired_value) ;
}
#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/memcpy.c
|
<gh_stars>0
#define _POSIX_SOURCE 1
#include "ezport.h"
#include <string.h>
/*
* This routine conforms to the ANSI standard
* description for 'memcpy(dest,src,nbytes)'
* used for copying arbitrary byte streams from
* one location in memory to another even if those
* locations overlap. We provide the source because
* some C environments are not provided with all
* of the ANSI specified routines.
*/
#ifdef missing_memcpy
void *memcpy(destin_arg, source_arg, nbytes)
void *destin_arg ;
void *source_arg ;
unsigned long nbytes ;
{
char *destin = (char *) destin_arg ;
char *source = (char *) source_arg ;
jr_int i ;
if (source_arg == destin_arg) return(destin_arg) ;
if ((destin < source) && ((destin + nbytes) > source)) {
/* top of dest dest overlaps bottom of source */
for (i=0; i < nbytes ; i++) {
destin[i] = source[i] ;
}
}
else if ((destin > source) && (destin < (source + nbytes))) {
/* bottom of dest overlaps top of source */
for (i = nbytes - 1 ; i >= 0 ; i--) {
destin[i] = source[i] ;
}
}
else /* no overlap */ {
for (i=0; i < nbytes ; i++) {
destin[i] = source[i] ;
}
}
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/dlist/dlistpfx.c
|
#include "project.h"
void jr_DListSetContainers (
jr_DList * list, ...)
{
va_list arg_list;
va_start (arg_list, list);
jr_DListSetContainersFromVA_List (list, arg_list);
va_end (arg_list);
}
void jr_DListSetContainersFromVA_List (list, arg_list)
jr_DList * list;
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_DListSetPrefixSize (list, prefix_size);
jr_PrefixArrayDestroy (prefix_array);
}
void jr_DListTransformPrefix (list, el_ptr, magnitude, which_way, all_elements)
jr_DList * list;
void * el_ptr;
unsigned jr_int magnitude;
jr_int which_way;
jr_int all_elements;
{
void * next_ptr;
void * prev_ptr;
void * old_el_ptr;
prev_ptr = jr_DListPrevElementPtr (list, el_ptr);
next_ptr = jr_DListNextElementPtr (list, el_ptr);
old_el_ptr = jr_UnTransformAListPtr (el_ptr, magnitude, which_way);
if (old_el_ptr == jr_DListHeadPtr (list)) {
jr_DListHeadPtr (list) = el_ptr;
}
if (old_el_ptr == jr_DListTailPtr (list)) {
jr_DListTailPtr (list) = el_ptr;
}
if (all_elements) {
/*
* Do this element's references
*/
if (prev_ptr) {
prev_ptr = jr_TransformAListPtr (prev_ptr, magnitude, which_way);
jr_DListPrevElementPtr (list, el_ptr) = prev_ptr;
}
if (next_ptr) {
next_ptr = jr_TransformAListPtr (next_ptr, magnitude, which_way);
jr_DListNextElementPtr (list, el_ptr) = next_ptr;
}
}
else {
/*
* Do references to this element
*/
if (prev_ptr) {
jr_DListNextElementPtr (list, prev_ptr) = el_ptr;
}
if (next_ptr) {
jr_DListPrevElementPtr (list, next_ptr) = el_ptr;
}
}
}
void jr_MakeNullDListElementWithPrefix (el_ptr, prefix_size)
const void * el_ptr;
jr_int prefix_size;
{
jr_NextDListElementPtrWithPrefix ((void *) el_ptr, prefix_size) = 0;
jr_PrevDListElementPtrWithPrefix ((void *) el_ptr, prefix_size) = 0;
}
jr_int jr_IsNullDListElementWithPrefix (el_ptr, prefix_size)
const void * el_ptr;
jr_int prefix_size;
{
if ( jr_NextDListElementPtrWithPrefix ((void *) el_ptr, prefix_size) == 0
&& jr_PrevDListElementPtrWithPrefix ((void *) el_ptr, prefix_size) == 0) {
return 1;
}
return 0;
}
|
frankjas/libjr
|
libjr/string/endword.c
|
#include "ezport.h"
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include "jr/string.h"
jr_int jr_RemoveTrailingWhiteSpace (word_arg)
char * word_arg;
{
char * end_ptr ;
jr_int count = 0;
if (*word_arg == 0) return count;
end_ptr = (char *) strchr(word_arg, 0) ;
end_ptr-- ; /* to back off one from null */
for (; end_ptr >= word_arg; end_ptr--, count++) {
if (! isspace(*end_ptr)) {
end_ptr++ ;
*end_ptr = 0 ;
return count;
}
}
*word_arg = 0 ;
return count;
}
/*
void main()
{
char result[128] ;
char * original = " first word last word " ;
strcpy(result, original) ;
jr_RemoveTrailingWhiteSpace(result) ;
fprintf(stdout, "jr_RemoveTrailingWhiteSpace('%s') == '%s'\n",
original,
result
) ;
}
*/
|
frankjas/libjr
|
libjr/struct/inputbuf.c
|
#include "ezport.h"
#include <stdio.h>
#include <string.h>
#include "jr/string.h"
#include "jr/malloc.h"
#include "jr/misc.h"
#include "jr/inputbuf.h"
jr_int jr_IB_NumCharReadCalls;
jr_int jr_IB_NumCharsRead;
jr_int jr_IB_NumCharsFromString;
jr_int jr_IB_NumCharsUnRead;
void jr_IB_InputBufferInit (input_buffer)
jr_IB_InputBuffer *input_buffer;
{
memset (input_buffer, 0, sizeof (*input_buffer));
jr_AListInit (input_buffer->context_stack, sizeof (jr_IB_ContextType));
jr_HTableInitForPtrValues (input_buffer->context_names, jr_strhash, (jr_CmpFnType) strcmp);
input_buffer->eof_line_number = 0;
input_buffer->eof_column_number = 0;
input_buffer->eof_byte_offset = 0;
input_buffer->tab_stops = jr_EnvTabStops ();
}
void jr_IB_InputBufferUndo (input_buffer)
jr_IB_InputBuffer *input_buffer;
{
jr_IB_ContextType *input_context;
jr_int i;
jr_AListForEachElementPtr (input_buffer->context_stack, input_context) {
jr_IB_UndoContext (input_context);
}
jr_AListUndo (input_buffer->context_stack);
jr_HTableForEachElementIndex (input_buffer->context_names, i) {
jr_free (jr_HTableKeyPtrValue (input_buffer->context_names, i));
}
jr_HTableUndo (input_buffer->context_names);
}
jr_IB_InputBuffer *jr_IB_InputBufferCreate (void)
{
jr_IB_InputBuffer *input_buffer = jr_malloc (sizeof (jr_IB_InputBuffer));
jr_IB_InputBufferInit (input_buffer);
return (input_buffer);
}
void jr_IB_InputBufferDestroy (input_buffer)
jr_IB_InputBuffer *input_buffer;
{
jr_IB_InputBufferUndo (input_buffer);
jr_free (input_buffer);
}
void jr_IB_InputBufferReset (input_buffer)
jr_IB_InputBuffer *input_buffer;
{
while (jr_IB_CloseCurrentContext (input_buffer));
}
jr_int jr_IB_getc (input_buffer)
jr_IB_InputBuffer * input_buffer;
{
jr_IB_ContextType * input_context;
jr_int c = 0; /* to shutup 'uninit.' warning */
if (jr_AListIsEmpty (input_buffer->context_stack)) {
return (EOF);
}
jr_IB_NumCharReadCalls ++;
input_context = jr_AListTailPtr (input_buffer->context_stack);
if (jr_AListSize (input_context->unread_chars) > 0) {
c = jr_AListNativeDeletedTail (input_context->unread_chars, char);
}
else {
switch (input_context->context_type) {
case jr_IB_FILE_CONTEXT : {
c = getc (input_context->src_rfp);
jr_IB_NumCharsRead ++;
/* deal with reading DOS text files and getting rid of trailing ^M */
if (c == '\r') {
c = getc(input_context->src_rfp);
if (c != '\n') {
ungetc(c, input_context->src_rfp);
c = '\r' ;
}
}
if (c == EOF) {
if (input_context->transparent_close) {
jr_IB_CloseCurrentContext (input_buffer);
return (jr_IB_getc (input_buffer));
}
}
break;
}
case jr_IB_STRING_CONTEXT : {
c = input_context->src_string [input_context->string_index];
jr_IB_NumCharsFromString ++;
if (c == 0) {
if (input_context->transparent_close) {
jr_IB_CloseCurrentContext (input_buffer);
return (jr_IB_getc (input_buffer));
}
}
else {
/*
* read a character, increment our idea of
* where we are
*/
input_context->string_index ++;
}
break;
}
}
}
if (c == 0 && input_context->context_type == jr_IB_STRING_CONTEXT) {
c = EOF;
}
input_context->byte_offset ++;
if (input_context->column_number != 0) {
input_context->column_number ++;
}
switch (c) {
case '\n' : {
input_context->line_number ++;
input_context->last_num_columns = input_context->column_number;
input_context->column_number = 1;
break;
}
case '\t' : {
jr_int spaces_to_tab_stop;
spaces_to_tab_stop = input_context->tab_stops
- input_context->column_number % input_buffer->tab_stops;
input_context->column_number += spaces_to_tab_stop;
}
}
if (c != '\n') {
input_context->saw_new_line = 0;
}
return (c);
}
void jr_IB_ungetc (input_buffer, c)
jr_IB_InputBuffer *input_buffer;
jr_int c;
{
jr_IB_ContextType *input_context;
jr_IB_NumCharsUnRead ++;
if (jr_AListIsEmpty (input_buffer->context_stack)) {
return ;
}
input_context = jr_AListTailPtr (input_buffer->context_stack);
jr_AListNativeSetNewTail (input_context->unread_chars, c, char);
if (input_context->column_number != 0) {
input_context->column_number --;
}
if (input_context->byte_offset != 0) {
input_context->byte_offset --;
}
if (c == '\n') {
input_context->line_number --;
input_context->column_number = input_context->last_num_columns;
input_context->saw_new_line = 1;
input_context->last_num_columns = 0;
}
}
char *jr_IB_gets (input_buffer, string_buf, max_length)
jr_IB_InputBuffer * input_buffer;
char * string_buf;
jr_int max_length;
{
jr_int c, i;
if (max_length == 0) return (string_buf);
i = 0;
while ((c = jr_IB_getc (input_buffer)) != EOF) {
string_buf [i] = c;
i++;
if (i == max_length - 1) break;
if (c == '\n') break;
}
if (i == 0) return (NULL);
string_buf [i] = 0;
return (string_buf);
}
void jr_IB_ungetstring (input_buffer, string)
jr_IB_InputBuffer *input_buffer;
char *string;
{
jr_IB_ContextType *input_context;
char *end_string;
jr_int c;
if (jr_AListIsEmpty (input_buffer->context_stack)) {
return ;
}
input_context = jr_AListTailPtr (input_buffer->context_stack);
end_string = strchr (string, 0);
for (end_string--; end_string >= string; end_string--) {
c = *end_string;
jr_IB_NumCharsUnRead ++;
jr_AListNativeSetNewTail (input_context->unread_chars, c, char);
if (input_context->column_number != 0) {
input_context->column_number --;
}
if (input_context->byte_offset != 0) {
input_context->byte_offset --;
}
if (c == '\n') {
input_context->line_number --;
input_context->column_number = input_context->last_num_columns;
input_context->saw_new_line = 1;
input_context->last_num_columns = 0;
}
}
}
char *jr_IB_getword (input_buffer, string_buf, max_length)
jr_IB_InputBuffer * input_buffer;
char * string_buf;
jr_int max_length;
{
jr_int c, i;
if (max_length == 0) return (string_buf);
i = 0;
while ((c = jr_IB_getc (input_buffer)) != EOF) {
string_buf [i] = c;
i++;
if (i == max_length - 1) break;
if (isspace (c)) break;
}
if (i == 0) return (NULL);
string_buf [i] = 0;
return (string_buf);
}
void jr_IB_OpenContext ( input_buffer, type,
name, do_save_name,
ptr, do_fclose_or_free,
transparent_close
)
jr_IB_InputBuffer * input_buffer;
jr_int type;
const char * name;
jr_int do_save_name;
void * ptr;
jr_int do_fclose_or_free;
jr_int transparent_close;
{
jr_IB_ContextType * input_context;
jr_IB_ContextType * parent_context;
input_context = jr_AListNewTailPtr (input_buffer->context_stack);
memset (input_context, 0, sizeof (jr_IB_ContextType));
input_context->context_type = type;
input_context->do_fclose_or_free = do_fclose_or_free;
input_context->transparent_close = transparent_close;
input_context->tab_stops = input_buffer->tab_stops;
input_context->last_num_columns = 0;
if (name) {
input_context->saw_new_line = 1;
input_context->line_number = 1;
input_context->column_number = 1;
}
else if (jr_AListSize (input_buffer->context_stack) > 1) {
/*
* if no name and a parent context, then the
* name and line numbers come from the parent
*/
parent_context = jr_IB_ContextPtr (
input_buffer, jr_IB_ContextDepth (input_buffer) - 2
);
name = parent_context->context_name;
input_context->line_number = parent_context->line_number;
input_context->column_number = parent_context->column_number;
input_context->is_inherited = 1;
}
else {
name = "";
input_context->saw_new_line = 1;
input_context->line_number = 1;
input_context->column_number = 1;
}
switch (input_context->context_type) {
case jr_IB_FILE_CONTEXT : {
input_context->src_rfp = ptr;
break;
}
case jr_IB_STRING_CONTEXT : {
input_context->src_string = ptr;
input_context->string_index = 0;
break;
}
}
jr_AListInit (input_context->unread_chars, sizeof (char));
jr_IB_SetCurrentContextName (input_buffer, (char *) name, do_save_name);
}
jr_int jr_IB_CloseCurrentContext (input_buffer)
jr_IB_InputBuffer *input_buffer;
{
jr_IB_ContextType *input_context;
if (jr_AListIsEmpty (input_buffer->context_stack)) {
return (0);
}
input_context = jr_AListTailPtr (input_buffer->context_stack);
input_buffer->eof_line_number = input_context->line_number + 1;
input_buffer->eof_column_number = 1;
input_buffer->eof_byte_offset = input_context->byte_offset + 1;
jr_IB_UndoContext (input_context);
jr_AListDeletedTailPtr (input_buffer->context_stack);
return (1);
}
void jr_IB_UndoContext (input_context)
jr_IB_ContextType *input_context;
{
jr_AListUndo (input_context->unread_chars);
switch (input_context->context_type) {
case jr_IB_FILE_CONTEXT : {
if (input_context->do_fclose_or_free) {
fclose (input_context->src_rfp);
}
break;
}
case jr_IB_STRING_CONTEXT : {
if (input_context->do_fclose_or_free) {
jr_free (input_context->src_string);
}
break;
}
}
}
char *jr_IB_ContextDescription (input_buffer, string, max_size)
jr_IB_InputBuffer * input_buffer;
char * string;
jr_int max_size;
{
jr_IB_ContextType * input_context;
char digit_str[64];
char * curr_end;
jr_int current_length;
jr_int added_length;
current_length = 0;
*string = 0;
jr_AListForEachElementPtrRev (input_buffer->context_stack, input_context) {
sprintf (digit_str, "%d", input_context->line_number);
added_length = (jr_int) (strlen (input_context->context_name) + strlen (digit_str));
if (current_length != 0) {
added_length += 4;
/*
* for the ->, separating contexts
*/
}
if (current_length + added_length + 1 > max_size) {
return (string);
}
curr_end = strchr (string, 0);
sprintf (curr_end, "%s%s:%s",
current_length == 0 ? "" : "\n\tincluded by: ",
input_context->context_name, digit_str
);
current_length += added_length;
}
return (string);
}
void jr_IB_SetCurrentContextName (input_buffer, name, save_name)
jr_IB_InputBuffer * input_buffer;
char * name;
jr_int save_name;
{
jr_IB_ContextType *input_context;
if (jr_AListIsEmpty (input_buffer->context_stack)) {
return;
}
input_context = jr_AListTailPtr (input_buffer->context_stack);
if (save_name) {
/*
* put the name in the context name table
*/
jr_int i;
i = jr_HTableFindPtrValueIndex (input_buffer->context_names, name);
if (i == -1) {
name = jr_strdup (name);
i = jr_HTableNewPtrValueIndex (input_buffer->context_names, name);
}
name = jr_HTableKeyPtrValue (input_buffer->context_names, i);
}
input_context->context_name = name;
/*
* name will either be the arg passed in or a jr_strdupd copy
*/
}
jr_int _jr_IB_CurrentContextLine (input_buffer)
jr_IB_InputBuffer * input_buffer;
{
return jr_IB_CurrentContextLine(input_buffer);
}
char * _jr_IB_CurrentContextName (input_buffer)
jr_IB_InputBuffer * input_buffer;
{
return jr_IB_CurrentContextName(input_buffer);
}
|
frankjas/libjr
|
include/jr/ezport/types.h
|
#ifndef __jr_EZPORT_TYPES_H___
#define __jr_EZPORT_TYPES_H___
/*
** use #defines so 'unsigned jr_short' is valid syntax
** use jr_int for all 32 bit quantities
*/
#include <limits.h>
#include <stdint.h>
#if defined (__GNUC__)
/*
** 10/26/05 <float.h> is in gcc's private include dir, /usr/lib/gcc/...
** is indicated by GNU_INCLUDE_DIR for the JR parsing library.
** If this generates an error, check the value of that env. variable.
*/
#include <float.h>
#endif
#ifdef _WIN64
# define jr_IS_64_BIT 1
#endif
#if __WORDSIZE == 64
# define jr_IS_64_BIT 1
#endif
#if __LP64__ == 64
# define jr_IS_64_BIT 1
#endif
#define jr_short short
#define jr_CHAR_MAX INT8_MAX
#define jr_UCHAR_MAX UINT8_MAX
#define jr_SCHAR_MAX INT8_MAX
#define jr_SHRT_MAX INT16_MAX
#define jr_SHRT_MIN INT16_MIN
#define jr_USHRT_MAX UINT16_MAX
#define jr_INT_MAX INT32_MAX
#define jr_INT_MIN INT32_MIN
#define jr_UINT_MAX UINT32_MAX
#define jr_FLOAT_MAX FLT_MAX
#define jr_FLOAT_MIN FLT_MIN
#ifdef replace_2_byte_int_with_4_byte_long
# define jr_int long
#else
# define jr_int int
#endif
#ifdef jr_IS_64_BIT
# define jr_long long
#else
# define jr_long long long
#endif
/*
* These belong in jr/misc.h, but their values are justified
* by the code here. Any changes here requires changing these
* constants
*/
#define jr_INT_BIT_SIZE_POWER 5 /* bits in an int are 2^5 = 32, used for division */
#define jr_SHORT_BIT_SIZE_POWER 4 /* bits in a short are 2^4 = 16 */
#define jr_CHAR_BIT_SIZE_POWER 3 /* bits in a char are 2^3 = 8 */
#define jr_INT_NUM_BITS 32
#define jr_INT_BIT_SIZE_MASK (jr_INT_NUM_BITS - 1) /* used for modulus */
#define jr_INT_NUM_BYTES (jr_INT_NUM_BITS / 8)
#define jr_INT_NUM_BYTES_MASK (jr_INT_NUM_BYTES - 1) /* used for modulus */
/*
** 3/15/07: Under Unix/Linux, see pthread.h for definition of PTHREAD_ONCE_INIT
*/
#ifdef ostype_winnt
# define jr_PTHREAD_ONCE_INIT {0}
#elif defined(ostype_cygwin)
# if (__version__ <= 5100)
# define jr_PTHREAD_ONCE_INIT {{(void*) 20, 0}}
# else
# define jr_PTHREAD_ONCE_INIT {{(void*) 19, 0}}
# endif
#elif defined(ostype_macosx)
# define jr_PTHREAD_ONCE_INIT {{0x30B1BCBA, {0}}}
#else
# define jr_PTHREAD_ONCE_INIT {0}
#endif
/*
** 3/21/07: May only need to explicitly declare "dllimport" on global variables.
** It looks like the MS linker automatically links functions if the __imp__ version
** of an undefined function is available.
** NOTE: jr_EXTERN() can probably only be used on global vars going into libjr.dll.
** Due to MS's scheme, each library needs their own jr_EXTERN() and corresponding
** ifdefs. See APR_DECLARE and APU_DECLARE (in "apr" and "apr-utils") as examples.
**
** NOTE: when compiling "libjr" files, define "is_libjr_build" to avoid warnings
*/
#if defined(ostype_winnt) && defined(PIC) && !defined(is_libjr_build)
# define jr_EXTERN(type) extern __declspec(dllimport) type
# define jr_EXTERN_DEF(type) __declspec(dllimport) type
#else
# define jr_EXTERN(type) extern type
# define jr_EXTERN_DEF(type) type
#endif
#endif
|
frankjas/libjr
|
include/jr/nettype.h
|
<reponame>frankjas/libjr
#ifndef _net_inth
#define _net_inth
#include "ezport.h"
#include <sys/types.h>
#include "jr/long.h"
#include "jr/misc.h"
extern unsigned jr_int jr_bswap_32 (unsigned jr_int value);
extern unsigned jr_int jr_bswap_16 (unsigned jr_short value);
extern unsigned jr_int jr_inet_host_number (unsigned jr_int ip_number);
extern unsigned jr_int jr_inet_network_number (unsigned jr_int ip_number);
#ifdef replace_byte_order_funcs
# ifdef ostype_winnt
# define LITTLE_ENDIAN 1234
# define BIG_ENDIAN 4321
# if defined(_M_IX86) || defined(_M_IX64) || defined(_M_X86) || defined(_M_X64)
# define BYTE_ORDER LITTLE_ENDIAN
# else
# error "No endian defined"
# endif
# else
# include <endian.h>
# endif
# ifndef BYTE_ORDER
# error "No BYTE_ORDER defined (big, little endian)"
# endif
# if BYTE_ORDER == BIG_ENDIAN
# define jr_ntohl(x) (x)
# define jr_ntohs(x) (x)
# define jr_htonl(x) (x)
# define jr_htons(x) (x)
# endif
# if BYTE_ORDER == LITTLE_ENDIAN
# define jr_ntohl(x) jr_bswap_32 (x)
# define jr_ntohs(x) jr_bswap_16 (x)
# define jr_htonl(x) jr_bswap_32 (x)
# define jr_htons(x) jr_bswap_16 (x)
# endif
#else
# ifndef ostype_winnt
# include <netinet/in.h>
# endif
# define jr_ntohl(x) ntohl (x)
# define jr_ntohs(x) ntohs (x)
# define jr_htonl(x) htonl (x)
# define jr_htons(x) htons (x)
#endif
/*
* jr_NetChar should be 1 byte
* jr_NetInt should be 4 bytes
* jr_NetLong should be 8 bytes
*/
typedef char jr_NetChar;
#define jr_NetCharToHost(c) ((c))
#define jr_NetCharAsgnInt(c_ptr, v) (*(c_ptr) = (v))
typedef unsigned char jr_NetUChar;
#define jr_NetUCharToHost(c) ((c))
#define jr_NetUCharAsgnUInt(c_ptr, v) (*(c_ptr) = (v))
#define jr_NetUCharMaskedAsgn(c_ptr, mask, v) \
jr_NetUCharAsgnUInt ( \
c_ptr, ((jr_NetUCharToHost (*(c_ptr)) & ~(mask)) | ((v) & (mask))) \
)
#define jr_NetUCharMaskedValue(c, mask) \
(jr_NetUCharToHost (c) & (mask))
typedef struct {
jr_short net_short_value;
} jr_NetShort;
#define jr_NetShortAsgnShort(short_number, host_value) \
((short_number)->net_short_value = (short) jr_htons ((unsigned short) (host_value)))
#define jr_NetShortToHost(short_number) \
((short) jr_ntohs((short_number).net_short_value))
typedef struct {
unsigned jr_short net_u_short_value;
} jr_NetUShort;
#define jr_NetUShortAsgnUShort(short_number, host_value) \
((short_number)->net_u_short_value = jr_htons ((unsigned short) (host_value)))
#define jr_NetUShortToHost(short_number) \
((unsigned short) jr_ntohs((short_number).net_u_short_value))
#define jr_NetUShortMaskedAsgn(l, mask, v) \
jr_NetUShortAsgnUShort ( \
l, ((jr_NetUShortToHost (*(l)) & ~(mask)) | ((v) & (mask))) \
)
#define jr_NetUShortMaskedValue(l, mask) \
(jr_NetUShortToHost (l) & (mask))
typedef struct {
jr_int net_int_value;
} jr_NetInt;
#define jr_NetIntAsgnInt(int_number, host_value) \
((int_number)->net_int_value = jr_htonl ((unsigned jr_int) (host_value)))
#define jr_NetIntToHost(int_number) \
((jr_int) jr_ntohl((int_number).net_int_value))
typedef struct {
unsigned jr_int net_u_int_value;
} jr_NetUInt;
#define jr_NetUIntAsgnUInt(int_number, host_value) \
((int_number)->net_u_int_value = jr_htonl ((unsigned jr_int) (host_value)))
#define jr_NetUIntToHost(int_number) \
((unsigned jr_int) jr_ntohl((int_number).net_u_int_value))
#define jr_NetUIntMaskedValue(l, mask) \
(jr_NetUIntToHost (l) & (mask))
#define jr_NetUIntMaskedAsgn(l, mask, v) \
jr_NetUIntAsgnUInt ( \
l, ((jr_NetUIntToHost (*(l)) & ~(mask)) | ((v) & (mask))) \
)
/******** jr_NetLong ********/
typedef struct {
jr_int net_msw;
jr_int net_lsw;
} jr_NetLong;
#define jr_NetLongSetMSW(longv, v) ((longv)->net_msw = jr_htonl ((jr_int) (v)))
#define jr_NetLongSetLSW(longv, v) ((longv)->net_lsw = jr_htonl ((jr_int) (v)))
#define jr_NetLongMSW(longv) ((jr_int) jr_ntohl ((longv).net_msw))
#define jr_NetLongLSW(longv) ((jr_int) jr_ntohl ((longv).net_lsw))
#define jr_NetLongAsgnLong(long_number, host_value) \
( \
jr_NetLongSetMSW (long_number, jr_LongMSW (host_value)), \
jr_NetLongSetLSW (long_number, jr_LongLSW (host_value)) \
)
#define jr_NetLongAsgnInt(long_number, host_value) \
( \
jr_NetLongSetMSW (long_number, 0), \
jr_NetLongSetLSW (long_number, host_value) \
)
extern jr_int jr_NetLongPtrCmp PROTO ((const jr_NetLong *netlong1,const jr_NetLong *netlong2));
/******** jr_NetULong ********/
typedef struct {
unsigned jr_int net_u_msw;
unsigned jr_int net_u_lsw;
} jr_NetULong;
#define jr_NetULongSetMSW(longv, v) ((longv)->net_u_msw = jr_htonl ((unsigned jr_int) (v)))
#define jr_NetULongSetLSW(longv, v) ((longv)->net_u_lsw = jr_htonl ((unsigned jr_int) (v)))
#define jr_NetULongMSW(longv) ((unsigned jr_int) jr_ntohl ((longv).net_u_msw))
#define jr_NetULongLSW(longv) ((unsigned jr_int) jr_ntohl ((longv).net_u_lsw))
#define jr_NetULongIsZero(longv) \
((longv).net_u_msw == 0 && (longv).net_u_lsw == 0)
#define jr_NetULongIsNonZero(longv) (! jr_NetULongIsZero (longv))
#define jr_NetULongIsMaxValue(longv) \
((longv).net_u_msw == jr_UINT_MAX && (longv).net_u_lsw == jr_UINT_MAX)
#define jr_NetULongAsgnMaxValue(long_number) \
( \
jr_NetULongSetMSW (long_number, ULONG_MAX), \
jr_NetULongSetLSW (long_number, ULONG_MAX) \
)
#define jr_NetULongAsgnULong(long_number, host_value) \
( \
jr_NetULongSetMSW (long_number, jr_ULongMSW (host_value)), \
jr_NetULongSetLSW (long_number, jr_ULongLSW (host_value)) \
)
#define jr_NetULongAsgnUInt(long_number, host_value) \
( \
jr_NetULongSetMSW (long_number, 0), \
jr_NetULongSetLSW (long_number, host_value) \
)
#define jr_NetULongAsgn(long1, long2) \
( \
(long1)->net_u_msw = (long2).net_u_msw, \
(long1)->net_u_lsw = (long2).net_u_lsw \
)
extern jr_int jr_NetIntPtrCmp PROTO ((const jr_NetInt *netlong1, const jr_NetInt *netlong2));
extern jr_int jr_NetUIntPtrCmp PROTO ((const jr_NetUInt *netlong1, const jr_NetUInt *netlong2));
extern jr_int jr_NetIntPtrCmpRev PROTO ((const jr_NetInt *netlong1, const jr_NetInt *netlong2));
extern jr_int jr_NetULongPtrCmp PROTO ((const jr_NetULong *netlong1,const jr_NetULong *netlong2));
/******* Floating Point ********/
typedef struct {
double net_double_value;
} jr_NetDouble;
typedef struct {
float net_float_value;
} jr_NetFloat;
extern float jr_NetFloatToHost PROTO ((
jr_NetFloat net_float
));
extern void jr_NetFloatAsgnFloat PROTO ((
jr_NetFloat * net_float,
double host_value
));
extern double jr_NetDoubleToHost PROTO ((
jr_NetDouble net_double
));
extern void jr_NetDoubleAsgnDouble PROTO ((
jr_NetDouble * net_double,
double host_value
));
/*
* Takes an array of NetUChar and extracts the given bit range
*/
extern void jr_NetBitAsgn PROTO ((
jr_NetUChar * bit_array,
unsigned jr_int bit_value,
jr_int bit_position,
jr_int num_bits
));
extern unsigned jr_int jr_NetBitToHost PROTO ((
jr_NetUChar * bit_array,
jr_int bit_position,
jr_int num_bits
));
#endif
|
frankjas/libjr
|
libjr/missing/sigaction.c
|
<reponame>frankjas/libjr
#define _POSIX_SOURCE 1
#include "ezport.h"
#ifdef missing_sigaction_objects
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <signal.h>
int sigaction(signal_number, new_action, old_action)
int signal_number ;
const struct sigaction * new_action ;
struct sigaction * old_action ;
{
struct sigvec new_vec[1] ;
struct sigvec old_vec[1] ;
jr_int status ;
if (new_action != NULL) {
new_vec->sv_handler = new_action->sa_handler ;
new_vec->sv_mask = new_action->sa_mask ;
new_vec->sv_flags = new_action->sa_flags ;
status = sigvec(signal_number, new_vec, old_vec) ;
}
else {
status = sigvec(signal_number, 0, old_vec) ;
}
if (old_action != NULL) {
old_action->sa_handler = old_vec->sv_handler ;
old_action->sa_mask = old_vec->sv_mask ;
old_action->sa_flags = old_vec->sv_flags ;
}
return(status) ;
}
#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 ;
{
struct sigaction new_action[1] ;
struct sigaction old_action[1] ;
jr_int c ;
new_action->sa_handler = onintr ;
sigemptyset(&(new_action->sa_mask)) ;
sigaddset(&(new_action->sa_mask), SIGQUIT) ;
new_action->sa_flags = 0 ;
sigaction(SIGINT, new_action, 0) ;
sigaction(SIGINT, new_action, old_action) ;
fprintf(stdout,"old_action->sa_handler == %#010x\n", old_action->sa_handler) ;
fprintf(stdout,"old_action->sa_mask == %#010x\n", old_action->sa_mask) ;
fprintf(stdout,"old_action->sa_flags == %#010x\n", old_action->sa_flags) ;
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,"Enter text or interrupt: ") ;
while ((c = getchar()) != EOF) {
putchar(c) ;
if (c == '\n') {
fprintf(stderr,"Enter text or interrupt: ") ;
}
}
exit(0) ;
}
*/
|
frankjas/libjr
|
libjr/replace/inet_ntoa.c
|
<reponame>frankjas/libjr<filename>libjr/replace/inet_ntoa.c<gh_stars>0
#include "ezport.h"
#ifdef has_buggy_inet_ntoa
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
char *jr_inet_ntoa (sin_addr)
struct in_addr sin_addr;
{
static char inet_str [32];
sprintf (inet_str, "%d.%d.%d.%d",
sin_addr.s_net,
sin_addr.s_host,
sin_addr.s_lh,
sin_addr.s_impno
) ;
return (inet_str);
}
#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/jr_perms.c
|
<reponame>frankjas/libjr<filename>libjr/syscalls/jr_perms.c<gh_stars>0
#include "ezport.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include "jr/syscalls.h"
jr_int jr_UnixModeToPerms (
mode_t unix_mode)
{
jr_int perm_flags = 0;
if (unix_mode & S_ISUID) {
perm_flags |= jr_PERM_S_OWNER;
}
if (unix_mode & S_ISGID) {
perm_flags |= jr_PERM_S_GROUP;
}
if (unix_mode & S_IRUSR) {
perm_flags |= jr_PERM_R_OWNER;
}
if (unix_mode & S_IWUSR) {
perm_flags |= jr_PERM_W_OWNER;
}
if (unix_mode & S_IXUSR) {
perm_flags |= jr_PERM_X_OWNER;
}
if (unix_mode & S_IRGRP) {
perm_flags |= jr_PERM_R_GROUP;
}
if (unix_mode & S_IWGRP) {
perm_flags |= jr_PERM_W_GROUP;
}
if (unix_mode & S_IXGRP) {
perm_flags |= jr_PERM_X_GROUP;
}
if (unix_mode & S_IROTH) {
perm_flags |= jr_PERM_R_OTHER;
}
if (unix_mode & S_IWOTH) {
perm_flags |= jr_PERM_W_OTHER;
}
if (unix_mode & S_IXOTH) {
perm_flags |= jr_PERM_X_OTHER;
}
return perm_flags;
}
mode_t jr_PermsToUnixMode (
unsigned jr_int perm_flags)
{
mode_t unix_mode = 0;
if (perm_flags & jr_PERM_S_OWNER) {
unix_mode |= S_ISUID;
}
if (perm_flags & jr_PERM_S_GROUP) {
unix_mode |= S_ISGID;
}
if (perm_flags & jr_PERM_R_OWNER) {
unix_mode |= S_IRUSR;
}
if (perm_flags & jr_PERM_W_OWNER) {
unix_mode |= S_IWUSR;
}
if (perm_flags & jr_PERM_X_OWNER) {
unix_mode |= S_IXUSR;
}
if (perm_flags & jr_PERM_R_GROUP) {
unix_mode |= S_IRGRP;
}
if (perm_flags & jr_PERM_W_GROUP) {
unix_mode |= S_IWGRP;
}
if (perm_flags & jr_PERM_X_GROUP) {
unix_mode |= S_IXGRP;
}
if (perm_flags & jr_PERM_R_OTHER) {
unix_mode |= S_IROTH;
}
if (perm_flags & jr_PERM_W_OTHER) {
unix_mode |= S_IWOTH;
}
if (perm_flags & jr_PERM_X_OTHER) {
unix_mode |= S_IXOTH;
}
return unix_mode;
}
unsigned jr_int jr_PermsFromString (
const char * perms_string)
{
unsigned jr_int perm_flags = 0;
jr_int q;
for (q=0; perms_string[q]; q++) {
switch (q) {
case 0 : {
if (perms_string[q] == 'r') {
perm_flags |= jr_PERM_R_OWNER;
}
break;
}
case 1 : {
if (perms_string[q] == 'w') {
perm_flags |= jr_PERM_W_OWNER;
}
break;
}
case 2 : {
if (perms_string[q] == 'x') {
perm_flags |= jr_PERM_X_OWNER;
}
if (perms_string[q] == 's') {
perm_flags |= jr_PERM_X_OWNER | jr_PERM_S_OWNER;
}
break;
}
case 3 : {
if (perms_string[q] == 'r') {
perm_flags |= jr_PERM_R_GROUP;
}
break;
}
case 4 : {
if (perms_string[q] == 'w') {
perm_flags |= jr_PERM_W_GROUP;
}
break;
}
case 5 : {
if (perms_string[q] == 'x') {
perm_flags |= jr_PERM_X_GROUP;
}
if (perms_string[q] == 's') {
perm_flags |= jr_PERM_X_GROUP | jr_PERM_S_GROUP;
}
break;
}
case 6 : {
if (perms_string[q] == 'r') {
perm_flags |= jr_PERM_R_OTHER;
}
break;
}
case 7 : {
if (perms_string[q] == 'w') {
perm_flags |= jr_PERM_W_OTHER;
}
break;
}
case 8 : {
if (perms_string[q] == 'x') {
perm_flags |= jr_PERM_X_OTHER;
}
break;
}
}
}
return perm_flags;
}
jr_int jr_PermsAddFromString (
jr_int curr_perms,
const char * perms_string)
{
jr_int q;
jr_int do_add = 0;
jr_int do_subtract = 0;
jr_int for_user = 0;
jr_int for_group = 0;
jr_int for_other = 0;
for (q=0; perms_string[q]; q++) {
switch (perms_string[q]) {
case '+' : {
do_add = 1;
break;
}
case '-' : {
do_subtract = 1;
break;
}
case '=' : {
do_add = 1;
curr_perms = 0;
break;
}
case 'a' : {
for_user = 1;
for_group = 1;
for_other = 1;
break;
}
case 'u' : {
for_user = 1;
break;
}
case 'g' : {
for_group = 1;
break;
}
case 'o' : {
for_other = 1;
break;
}
case 'r' : {
if (for_user) {
if (do_add) {
curr_perms |= jr_PERM_R_OWNER;
}
if (do_subtract) {
curr_perms &= ~jr_PERM_R_OWNER;
}
}
if (for_group) {
if (do_add) {
curr_perms |= jr_PERM_R_GROUP;
}
if (do_subtract) {
curr_perms &= ~jr_PERM_R_GROUP;
}
}
if (for_other) {
if (do_add) {
curr_perms |= jr_PERM_R_OTHER;
}
if (do_subtract) {
curr_perms &= ~jr_PERM_R_OTHER;
}
}
break;
}
case 'w' : {
if (for_user) {
if (do_add) {
curr_perms |= jr_PERM_W_OWNER;
}
if (do_subtract) {
curr_perms &= ~jr_PERM_W_OWNER;
}
}
if (for_group) {
if (do_add) {
curr_perms |= jr_PERM_W_GROUP;
}
if (do_subtract) {
curr_perms &= ~jr_PERM_W_GROUP;
}
}
if (for_other) {
if (do_add) {
curr_perms |= jr_PERM_W_OTHER;
}
if (do_subtract) {
curr_perms &= ~jr_PERM_W_OTHER;
}
}
break;
}
case 'x' : {
if (for_user) {
if (do_add) {
curr_perms |= jr_PERM_X_OWNER;
}
if (do_subtract) {
curr_perms &= ~jr_PERM_X_OWNER;
}
}
if (for_group) {
if (do_add) {
curr_perms |= jr_PERM_X_GROUP;
}
if (do_subtract) {
curr_perms &= ~jr_PERM_X_GROUP;
}
}
if (for_other) {
if (do_add) {
curr_perms |= jr_PERM_X_OTHER;
}
if (do_subtract) {
curr_perms &= ~jr_PERM_X_OTHER;
}
}
break;
}
case 's' : {
if (for_user) {
if (do_add) {
curr_perms |= jr_PERM_X_OWNER | jr_PERM_S_OWNER;
}
if (do_subtract) {
curr_perms &= ~jr_PERM_S_OWNER;
}
}
if (for_group) {
if (do_add) {
curr_perms |= jr_PERM_X_GROUP | jr_PERM_S_GROUP;
}
if (do_subtract) {
curr_perms &= ~jr_PERM_S_GROUP;
}
}
break;
}
}
}
return curr_perms;
}
void jr_PermsToString (
char * perm_string,
unsigned jr_int perm_flags)
{
perm_string[0] = 0;
if (perm_flags & jr_PERM_R_OWNER) {
strcat (perm_string, "r");
}
else {
strcat (perm_string, "-");
}
if (perm_flags & jr_PERM_W_OWNER) {
strcat (perm_string, "w");
}
else {
strcat (perm_string, "-");
}
if (perm_flags & jr_PERM_S_OWNER) {
strcat (perm_string, "s");
}
else if (perm_flags & jr_PERM_X_OWNER) {
strcat (perm_string, "x");
}
else {
strcat (perm_string, "-");
}
if (perm_flags & jr_PERM_R_GROUP) {
strcat (perm_string, "r");
}
else {
strcat (perm_string, "-");
}
if (perm_flags & jr_PERM_W_GROUP) {
strcat (perm_string, "w");
}
else {
strcat (perm_string, "-");
}
if (perm_flags & jr_PERM_S_GROUP) {
strcat (perm_string, "s");
}
else if (perm_flags & jr_PERM_X_GROUP) {
strcat (perm_string, "x");
}
else {
strcat (perm_string, "-");
}
if (perm_flags & jr_PERM_R_OTHER) {
strcat (perm_string, "r");
}
else {
strcat (perm_string, "-");
}
if (perm_flags & jr_PERM_W_OTHER) {
strcat (perm_string, "w");
}
else {
strcat (perm_string, "-");
}
if (perm_flags & jr_PERM_X_OTHER) {
strcat (perm_string, "x");
}
else {
strcat (perm_string, "-");
}
}
#ifndef ostype_winnt
unsigned jr_int jr_umask(
unsigned jr_int perm_flags)
{
mode_t mode_flags = jr_PermsToUnixMode( perm_flags);
mode_t old_mode;
old_mode = umask( mode_flags);
return jr_UnixModeToPerms( old_mode);
}
#endif
|
frankjas/libjr
|
libjr/misc/jr_iferr.c
|
#include "ezport.h"
#include <stdio.h>
#include "jr/errsim.h"
#include "jr/misc.h"
jr_int jr_iferr_sim (
jr_int is_err,
jr_int is_orig_err,
jr_int negate_err,
const char * file_name,
jr_int line_number)
{
return is_err;
}
#if 0
/*
* 7/26/2005: Sample code with iferr()
* Check output with: gcc -I$I -E t.c >& t.out
* Undef one or both of jr_IFERR_USE to trigger different expansions.
*/
#define jr_IFERR_ID err_base
#define jr_IFERR_USE_CACHED 1
#define jr_IFERR_USE_CUSTOM 1
#include "ezport.h"
#include "jr/error.h"
void main ()
{
jr_int status = __LINE__;
status = myfunc ();
iferr (status != 0) {
fprintf ("Failed");
}
}
#endif
/*
* 7/28/2005: Not used from here down?
*/
char jr_HasFakeError[jr_NUM_FAKE_ERRORS];
void jr_check_fake_error (error_number, file_name, line_number)
jr_int error_number;
const char * file_name;
jr_int line_number;
{
if (error_number < 0 || error_number >= jr_NUM_FAKE_ERRORS) {
if (file_name) {
fprintf (stderr, "\n%s:%d: ", file_name, line_number);
}
else {
fprintf (stderr, "\n");
}
fprintf (stderr, "jr_check_fake_error (%d): error number %d too large, max. is %d\n",
error_number, error_number, jr_NUM_FAKE_ERRORS
);
jr_coredump ();
}
if (jr_use_fake_error (error_number)) {
if (file_name) {
fprintf (stderr, "\n%s:%d: ", file_name, line_number);
}
else {
fprintf (stderr, "\n");
}
fprintf (stderr, "jr_check_fake_error (%d): error number %d already set\n",
error_number, error_number
);
jr_coredump ();
}
}
|
frankjas/libjr
|
libjr/missing/strstr.c
|
#define _POSIX_SOURCE 1
#include "ezport.h"
#include <string.h>
#include <ctype.h>
/*
* This routine conforms to the ANSI standard
* description for 'strstr(string,pattern)'
* used for finding a substring pattern in
* a larger string. We provide the source because
* some C environments are not provided with all
* of the ANSI specified routines.
*/
#ifdef missing_strstr
char *strstr(string,pattern) /* position of pattern in string */
const char *string ;
const char *pattern ;
{
jr_int patlen = strlen( pattern ) ;
jr_int match = 0 ;
char *strptr = (char *) string ;
if (*pattern == '\0') return((char *) string) ;
if (*string == '\0') return(0) ;
while((strptr = (char *) strchr(strptr,*pattern)) != 0) {
if(strncmp(strptr,pattern,patlen) == 0) {
match = 1 ;
break ;
}
strptr++ ;
}
return( match ? strptr : 0 ) ;
}
#else
static void NotCalled () /* define this so ranlib doesn't complain */
{
NotCalled (); /* use it so the compiler doesn't complain */
}
#endif
#ifdef missing_strcasestr
static char *strcasechr(
const char * string,
int search_char)
{
for (; *string; string++) {
if (tolower( *string) == tolower( search_char)) {
return (char *) string;
}
}
if (search_char == 0) {
return (char *) string;
}
return 0;
}
char *strcasestr(string,pattern) /* position of pattern in string */
const char *string ;
const char *pattern ;
{
jr_int patlen = strlen( pattern ) ;
jr_int match = 0 ;
char *strptr = (char *) string ;
if (*pattern == '\0') return((char *) string) ;
if (*string == '\0') return(0) ;
while((strptr = (char *) strcasechr(strptr,*pattern)) != 0) {
if(strncasecmp(strptr,pattern,patlen) == 0) {
match = 1 ;
break ;
}
strptr++ ;
}
return( match ? strptr : 0 ) ;
}
#endif
|
frankjas/libjr
|
libjr/struct/att_mngr.h
|
#ifndef __att_mngr_h_
#define __att_mngr_h_
#include "ezport.h"
#include <stdio.h>
#include <string.h>
#include "jr/malloc.h"
#include "jr/string.h"
#include "jr/misc.h"
#include "jr/attribut.h"
extern jr_int jr_AttributeManagerGetListId PROTO ((
jr_AttributeManagerType * manager
));
extern void jr_AttributeManagerAddAttribute PROTO ((
jr_AttributeManagerType * manager,
jr_AttributeType * attribute_ptr
));
extern jr_AttributeType *jr_AttributeManagerFindAttribute PROTO ((
jr_AttributeManagerType * manager,
jr_int list_id,
const char * name_string
));
extern void jr_AttributeManagerDeleteAttribute PROTO ((
jr_AttributeManagerType * manager,
jr_AttributeType * attribute_ptr
));
typedef struct {
char * string;
jr_int num_references;
jr_int mask_value;
} jr_StringRefsStruct;
extern void jr_StringRefsInit PROTO ((
jr_StringRefsStruct * string_info,
const char * string
));
extern void jr_StringRefsUndo PROTO ((
jr_StringRefsStruct * string_info
));
extern jr_int jr_StringRefsHash PROTO ((
const void * void_arg_1
));
extern jr_int jr_StringRefsCmp PROTO ((
const void * void_arg_1,
const void * void_arg_2
));
extern jr_int jr_AttributeHash PROTO ((
const void * void_arg_1
));
extern jr_int jr_AttributeCmp PROTO ((
const void * void_arg_1,
const void * void_arg_2
));
#endif
|
frankjas/libjr
|
libjr/llist/llist.c
|
#include "project.h"
jr_LList *jr_LListCreate (objsize)
jr_int objsize;
{
jr_LList *ptr = (jr_LList *) jr_malloc (sizeof (jr_LList));
jr_LListInit (ptr, objsize);
return (ptr);
}
void jr_LListInit (list, objsize)
jr_LList *list;
jr_int objsize;
{
static jr_int added_prefix_info = 0;
if (!added_prefix_info) {
added_prefix_info = 1;
jr_PrefixAddContainerType (
"jr_LList",
jr_LListElementPrefixSize,
jr_LListTransformPrefix,
jr_LListSetPrefixSize,
0
);
}
list->head = 0;
list->tail = 0;
list->objsize = objsize;
list->prefix_size = 0;
list->allocates_elements = 0;
}
void jr_LListDestroy (list)
jr_LList *list;
{
jr_LListEmpty (list);
jr_free (list);
}
void jr_LListUndo (list)
jr_LList *list;
{
jr_LListEmpty (list);
}
void jr_LListEmpty (list)
jr_LList *list;
{
if (jr_LListAllocatesElements (list)) {
void * lep;
void * next;
lep = jr_LListHeadPtr(list) ;
while (lep) {
next = jr_LListNextElementPtr (list, lep) ;
jr_LListFreeElement (list, lep);
lep = next ;
}
}
jr_LListHeadPtr(list) = 0;
jr_LListTailPtr(list) = 0;
}
jr_int jr_LListElementPrefixSize (list)
jr_LList * list;
{
return sizeof (void *);
}
void jr_LListSetPrefixSize (list, prefix_size)
jr_LList * list;
jr_int prefix_size;
{
assert (jr_LListIsEmpty (list));
list->prefix_size = prefix_size;
}
void *jr_LListAllocateElementWithSize (list, element_size)
jr_LList * list;
jr_int element_size;
{
void * new;
list->allocates_elements = 1;
new = jr_NewLListElementWithPrefix (element_size, list->prefix_size);
return new;
}
void *jr_NewLListElementWithPrefix (element_size, prefix_size)
jr_int element_size;
jr_int prefix_size;
{
void * new;
new = jr_malloc (prefix_size + sizeof (void *) + element_size);
return ((char *) new) + prefix_size + sizeof (void *);
}
|
frankjas/libjr
|
libjr/alist/alistcmp.c
|
<gh_stars>0
#include "project.h"
jr_int jr_AListCmp (list1, list2, cmpfn)
const jr_AList * list1 ;
const jr_AList * list2 ;
jr_int (*cmpfn)() ;
{
jr_int n1 ;
jr_int n2 ;
jr_int shortest ;
jr_int diff ;
jr_int i ;
void * elem1 ;
void * elem2 ;
n1 = jr_AListSize(list1) ;
n2 = jr_AListSize(list2) ;
shortest = (n1 < n2) ? n1 : n2 ;
for (i = 0 ; i < shortest ; i++) {
elem1 = jr_AListElementPtr(list1, i) ;
elem2 = jr_AListElementPtr(list2, i) ;
diff = (*cmpfn)(elem1, elem2) ;
if (diff != 0) {
return(diff) ;
}
}
return (n1 - n2) ;
}
jr_int jr_AListHash (list, hash_fn)
const jr_AList * list;
jr_int (*hash_fn) ();
{
void * el_ptr;
jr_int hash_value = 0;
jr_AListForEachElementPtr (list, el_ptr) {
hash_value += (*hash_fn) (el_ptr);
}
return hash_value;
}
|
frankjas/libjr
|
include/jr/apr.h
|
<filename>include/jr/apr.h
#ifndef _jr_apr_h___
#define _jr_apr_h___
#include <stdarg.h>
#include <stddef.h>
#include "jr/long.h"
#include "jr/time.h"
/******** APR Support ********/
extern void jr_apr_initialize (void);
extern void jr_apr_terminate (void);
extern jr_int jr_apr_is_initialized (void);
extern jr_int jr_apr_initialize_count ();
extern const char * jr_apr_strerror(
jr_int status,
char * error_buf);
/******** Permissions ********/
extern unsigned jr_int jr_PermsToAprPerms (
unsigned jr_int perm_flags);
extern unsigned jr_int jr_AprPermsToPerms (
unsigned jr_int apr_mode);
extern unsigned jr_int jr_umask(
unsigned jr_int perm_flags);
extern unsigned jr_int jr_umask_winnt(
unsigned jr_int perm_flags);
/*
** 2-25-2012: Under Unix use native umask. Under WinNt
** use default umask of jr_PERM_RW_OWNER, and allow
** programmatic change to this value. jr_umask_winnt()
** is a no-op under Unix to allow for #ifdef-less
** programming to change the default for WinNt.
*/
#ifdef ostype_winnt
#define jr_PermsToUmaskedAprPerms( perm_flags) \
jr_PermsToAprPerms( (perm_flags) & ~jr_WinNtUmask)
#define jr_umask( perm_flags) \
jr_umask_winnt( perm_flags)
extern unsigned jr_int jr_WinNtUmask;
#else
/*
** 2-25-2012: under Unix, umasking is builtin to file/dir creates.
*/
#define jr_PermsToUmaskedAprPerms( perm_flags) \
jr_PermsToAprPerms( perm_flags)
#endif
/******** stat ********/
typedef struct jr_stat {
jr_ULong file_size;
jr_seconds_t atime;
jr_seconds_t mtime;
jr_seconds_t ctime;
unsigned jr_int perms;
unsigned is_directory : 1;
unsigned is_file : 1;
unsigned is_link : 1; /* will only be set by jr_lstat() */
unsigned is_char_dev : 1;
} jr_stat_t;
/*
** 2-24-2012: calling jr_stat_init() is unnecessary
*/
extern void jr_stat_init (
jr_stat_t * jr_stat_ptr);
extern 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);
#define jr_stat_copy( dest_stat_ptr, src_stat_ptr) \
memcpy( dest_stat_ptr, src_stat_ptr, sizeof( jr_stat_t))
#define jr_STAT_GET_LINK_INFO 0x0001
#define jr_STAT_IGNORE_UID_ERRORS 0x0002
#define jr_stat(file_name, opt_stat_ptr, error_buf) \
jr_stat_common (file_name, opt_stat_ptr, 0, 0, 0, error_buf)
#define jr_lstat(file_name, opt_stat_ptr, error_buf) \
jr_stat_common (file_name, opt_stat_ptr, jr_STAT_GET_LINK_INFO, 0, 0, error_buf)
#define jr_stat_with_user_name( \
file_name, opt_stat_ptr, \
opt_user_name_ref, opt_group_name_ref, error_buf \
) \
jr_stat_common ( \
file_name, opt_stat_ptr, 0, \
opt_user_name_ref, opt_group_name_ref, error_buf \
)
#define jr_lstat_with_user_name( \
file_name, opt_stat_ptr, \
opt_user_name_ref, opt_group_name_ref, error_buf \
) \
jr_stat_common ( \
file_name, opt_stat_ptr, jr_STAT_GET_LINK_INFO, \
opt_user_name_ref, opt_group_name_ref, error_buf \
)
#define jr_stat_with_user_name_if_available( \
file_name, opt_stat_ptr, \
opt_user_name_ref, opt_group_name_ref, error_buf \
) \
jr_stat_common ( \
file_name, opt_stat_ptr, jr_STAT_IGNORE_UID_ERRORS, \
opt_user_name_ref, opt_group_name_ref, error_buf \
)
#define jr_lstat_with_user_name_if_available( \
file_name, opt_stat_ptr, \
opt_user_name_ref, opt_group_name_ref, error_buf \
) \
jr_stat_common ( \
file_name, opt_stat_ptr, \
jr_STAT_GET_LINK_INFO | jr_STAT_IGNORE_UID_ERRORS, \
opt_user_name_ref, opt_group_name_ref, error_buf \
)
extern jr_int jr_stat_mtime_cmp (
const void * void_ptr_1,
const void * void_ptr_2);
#define jr_stat_set_mtime(stat_ptr, v) \
((stat_ptr)->mtime = (v))
#define jr_stat_file_lsize(stat_ptr) \
((stat_ptr)->file_size)
#define jr_stat_file_size(stat_ptr) \
jr_ULongToUInt((stat_ptr)->file_size)
#define jr_stat_atime(stat_ptr) \
((stat_ptr)->atime)
#define jr_stat_mtime(stat_ptr) \
((stat_ptr)->mtime)
#define jr_stat_ctime(stat_ptr) \
((stat_ptr)->ctime)
#define jr_stat_perms(stat_ptr) \
((stat_ptr)->perms)
#define jr_stat_is_file(stat_ptr) \
((stat_ptr)->is_file)
#define jr_stat_is_directory(stat_ptr) \
((stat_ptr)->is_directory)
#define jr_stat_is_link(stat_ptr) \
((stat_ptr)->is_link)
#define jr_stat_is_char_dev(stat_ptr) \
((stat_ptr)->is_char_dev)
/******** Users and Groups ********/
/*
** 4/27/08: Use structs to prevent ordinary int comparisons, which
** won't work under NT.
*/
#ifdef ostype_winnt
typedef struct {
void * id_value;
void * apr_pool_ptr;
} jr_uid_t;
typedef struct {
void * id_value;
void * apr_pool_ptr;
} jr_gid_t;
#else
typedef struct {
jr_int id_value;
void * apr_pool_ptr;
} jr_uid_t;
typedef struct {
jr_int id_value;
void * apr_pool_ptr;
} jr_gid_t;
#endif
extern void jr_uid_init (
jr_uid_t * uid_ptr);
extern void jr_uid_undo (
jr_uid_t * uid_ptr);
extern void jr_gid_init (
jr_gid_t * gid_ptr);
extern void jr_gid_undo (
jr_gid_t * gid_ptr);
extern jr_int jr_uid_cmp (
const void * void_ptr_1,
const void * void_ptr_2);
extern jr_int jr_gid_cmp (
const void * void_ptr_1,
const void * void_ptr_2);
extern jr_int jr_uid_init_current (
jr_uid_t * uid_ptr,
char * error_buf);
extern jr_int jr_gid_init_current (
jr_gid_t * gid_ptr,
char * error_buf);
extern jr_int jr_uid_init_from_name (
jr_uid_t * uid_ptr,
const char * user_name,
char * error_buf);
extern jr_int jr_gid_init_from_name (
jr_gid_t * gid_ptr,
const char * group_name,
char * error_buf);
extern jr_int jr_uid_get_name (
jr_uid_t * uid_ptr,
const char ** user_name_ref,
char * error_buf);
extern jr_int jr_gid_get_name (
jr_gid_t * gid_ptr,
const char ** group_name_ref,
char * error_buf);
/******** Users and Groups ********/
extern jr_int jr_password_check(
const char * password_str,
const char * hashed_str);
extern void jr_password_hash(
const char * password_str,
const char * salt_str,
char * hash_buf,
jr_int hash_buf_len);
#define jr_PASSWORD_HASH_LEN 128
/******** IO Buffering For printf-like support ********/
typedef struct jr_aprbuf jr_aprbuf_t;
typedef int (*jr_aprbuf_writefn_t)( void *io_info, void *buf, int buf_len, char *error_buf );
extern void jr_aprbuf_init (
jr_aprbuf_t * aprbuf_ptr,
void * io_info,
int (*write_fn)(
void * io_info,
void * buf,
int buf_len,
char * error_buf),
jr_int buf_size);
extern void jr_aprbuf_undo (
jr_aprbuf_t * aprbuf_ptr);
extern jr_aprbuf_t * jr_aprbuf_create (
void * io_info,
int (*write_fn)(
void * io_info,
void * buf,
int buf_len,
char * error_buf),
jr_int buf_size);
extern jr_int jr_aprbuf_vformatter(
jr_aprbuf_t * aprbuf_ptr,
const char * control_string,
va_list arg_list);
extern void jr_aprbuf_destroy (
jr_aprbuf_t * aprbuf_ptr);
extern void jr_aprbuf_set_error_buf(
jr_aprbuf_t * aprbuf_ptr,
char * error_buf);
extern int jr_aprbuf_status(
jr_aprbuf_t * aprbuf_ptr);
extern int jr_aprbuf_needs_flush(
jr_aprbuf_t * aprbuf_ptr);
extern jr_int jr_aprbuf_flush (
jr_aprbuf_t * aprbuf_ptr);
/******** directories ********/
typedef struct {
void * apr_pool_ptr;
void * apr_dir_ptr;
} jr_dir_t;
extern void jr_dir_init (
jr_dir_t * dir_info);
extern void jr_dir_undo (
jr_dir_t * dir_info);
extern jr_int jr_dir_open (
jr_dir_t * dir_info,
const char * path,
char * error_buf);
extern void jr_dir_close (
jr_dir_t * dir_info);
extern jr_int jr_dir_read (
jr_dir_t * dir_info,
const char ** opt_entry_name_ref,
jr_stat_t * opt_stat_info,
char * error_buf);
/******** Files ********/
typedef struct jr_file {
void * apr_file_ptr;
void * apr_pool_ptr;
jr_aprbuf_t * aprbuf_ptr;
} jr_file_t;
#define jr_FILE_OPEN_READ 0x0001
#define jr_FILE_OPEN_WRITE 0x0002
#define jr_FILE_OPEN_APPEND 0x0004
#define jr_FILE_OPEN_CREATE 0x0008
#define jr_FILE_OPEN_TRUNCATE 0x0010
#define jr_FILE_OPEN_BUFFERED 0x0020
#define jr_FILE_OPEN_DEL_ON_CLOSE 0x0040
#define jr_FILE_OPEN_EXCLUSIVE 0x0080
/*
** 4/17/08: Buffered I/O works like FILE under Unix.
** For MS, the gets() functionality doesn't take advantage.
*/
#define jr_FILE_OPEN_RDWR (jr_FILE_OPEN_READ | jr_FILE_OPEN_WRITE)
#define jr_FILE_OPEN_WRITING \
(jr_FILE_OPEN_WRITE | jr_FILE_OPEN_CREATE | jr_FILE_OPEN_TRUNCATE)
#define jr_FILE_OPEN_APPENDING \
(jr_FILE_OPEN_WRITE | jr_FILE_OPEN_CREATE )
extern void jr_file_init (
jr_file_t * file_info);
extern void jr_file_undo (
jr_file_t * file_info);
extern jr_int jr_file_open (
jr_file_t * file_info,
const char * file_name,
jr_int open_flags,
jr_int file_perms,
char * error_buf);
/*
** 5/31/08: can reuse an already open jr_file_t,
** but is better to close first, since otherwise
** memory allocations keep accumulating.
*/
extern jr_int jr_file_close (
jr_file_t * file_info,
char * error_buf);
extern jr_int jr_file_open_stdin (
jr_file_t * file_info,
char * error_buf);
extern jr_int jr_file_open_stdout (
jr_file_t * file_info,
char * error_buf);
extern jr_int jr_file_open_stderr (
jr_file_t * file_info,
char * error_buf);
extern jr_int jr_file_open_pipe (
jr_file_t * read_file_info,
jr_file_t * write_file_info,
char * error_buf);
/*
** 5/8/08: The read file should be undone after the write.
*/
extern jr_int jr_file_open_tmp (
jr_file_t * file_info,
char * file_name,
jr_int open_flags,
jr_int file_perms,
char * error_buf);
extern int jr_file_setbufsize(
jr_file_t * file_info,
jr_int buf_size,
char * error_buf);
extern jr_int jr_file_read (
jr_file_t * file_info,
void * buffer,
unsigned jr_int data_length,
char * error_buf);
extern jr_int jr_file_write (
jr_file_t * file_info,
const void * data_buf,
unsigned jr_int data_length,
char * error_buf);
extern jr_int jr_file_printf (
jr_file_t * file_info,
const char * control_string,
...);
extern jr_int jr_file_flush (
jr_file_t * file_info,
char * error_buf);
extern jr_int jr_file_sync (
jr_file_t * file_info,
char * error_buf);
#define jr_FILE_SEEK_SET 0
#define jr_FILE_SEEK_CUR 1
#define jr_FILE_SEEK_END 2
extern jr_int jr_file_seek (
jr_file_t * file_info,
jr_ULong offset,
jr_int whence,
char * error_buf);
extern jr_int jr_file_get_offset (
jr_file_t * file_info,
jr_ULong * offset_ref,
char * error_buf);
extern jr_int jr_file_truncate (
jr_file_t * file_info,
jr_ULong offset,
char * error_buf);
extern jr_int jr_file_gets (
jr_file_t * file_info,
char * buffer,
jr_int buffer_length,
char * error_buf);
extern jr_int jr_file_copy(
jr_file_t * dest_file_info,
jr_file_t * src_file_info,
char * error_buf);
extern jr_int jr_file_stat_common (
jr_file_t * file_info,
jr_int flags,
jr_stat_t * opt_jr_stat_ptr,
const char ** opt_user_name_ref,
const char ** opt_group_name_ref,
char * error_buf);
#define jr_file_stat(file_info, opt_stat_ptr, error_buf) \
jr_file_stat_common (file_info, 0, opt_stat_ptr, 0, 0, error_buf)
#define jr_file_stat_with_user_name( \
file_info, opt_stat_ptr, \
opt_user_name_ref, opt_group_name_ref, error_buf \
) \
jr_file_stat_common ( \
file_info, 0, opt_stat_ptr, \
opt_user_name_ref, opt_group_name_ref, error_buf \
)
#define jr_file_stat_with_user_name_if_available( \
file_info, opt_stat_ptr, \
opt_user_name_ref, opt_group_name_ref, error_buf \
) \
jr_file_stat_common ( \
file_info, jr_STAT_IGNORE_UID_ERRORS, opt_stat_ptr, \
opt_user_name_ref, opt_group_name_ref, error_buf \
)
extern jr_int jr_file_is_tape(
jr_file_t * file_info,
char * error_buf);
#define jr_FILE_LOCK_READ 1
#define jr_FILE_LOCK_WRITE 2
/*
** 4/17/08: for write locks, file must be open for writing.
*/
extern jr_int jr_file_lock (
jr_file_t * file_info,
jr_int lock_type,
jr_int time_out,
char * error_buf);
extern jr_int jr_file_unlock (
jr_file_t * file_info,
char * error_buf);
#define jr_file_lock_read(file_info, time_out, error_buf) \
jr_file_lock (file_info, jr_FILE_LOCK_READ, time_out, error_buf)
#define jr_file_lock_write(file_info, time_out, error_buf) \
jr_file_lock (file_info, jr_FILE_LOCK_WRITE, time_out, error_buf)
extern jr_int jr_file_cmp (
const void * void_ptr_1,
const void * void_ptr_2);
extern jr_int jr_file_hash (
const void * void_ptr);
#define jr_file_apr_ptr(file_info) \
((file_info)->apr_file_ptr)
#define jr_file_set_apr_ptr(file_info, v) \
((file_info)->apr_file_ptr = (v))
/******** Socket Operations *********/
#define jr_SOCK_STREAM 1
#define jr_SOCK_DGRAM 2
#define jr_SOCKBUF_DEFAULT_SIZE 1024
/*
** 2/7/07: standard network packet/data size
*/
typedef struct jr_socket {
void * apr_socket_ptr;
void * apr_pool_ptr;
jr_int socket_type;
jr_aprbuf_t * aprbuf_ptr;
unsigned is_nonblocking : 1;
} jr_socket_t;
typedef struct jr_sockaddr {
void * apr_sockaddr_ptr;
void * apr_pool_ptr;
const char * ip_str;
struct jr_sockaddr *next_sockaddr_ptr;
unsigned has_borrowed_pool : 1;
} jr_sockaddr_t;
extern void jr_sockaddr_init (
jr_sockaddr_t * sockaddr_info);
extern void jr_sockaddr_undo (
jr_sockaddr_t * sockaddr_info);
extern jr_int jr_sockaddr_lookup (
jr_sockaddr_t * sockaddr_info,
const char * host_name,
jr_int port_number,
char * error_buf);
extern jr_sockaddr_t * jr_sockaddr_init_foreach (
jr_sockaddr_t * sockaddr_info);
/*
** 2-18-2013: fails if no pool can be allocated.
*/
extern jr_int jr_sockaddr_dup (
const jr_sockaddr_t * src_sockaddr_info,
jr_sockaddr_t * dest_sockaddr_info,
char * error_buf);
extern jr_int jr_sockaddr_cmp (
const jr_sockaddr_t * sockaddr_info_1,
const jr_sockaddr_t * sockaddr_info_2);
extern void * jr_sockaddr_ipaddr_ptr (
const jr_sockaddr_t * sockaddr_info);
extern jr_int jr_sockaddr_ipaddr_len (
const jr_sockaddr_t * sockaddr_info);
extern jr_int jr_sockaddr_port (
const jr_sockaddr_t * sockaddr_info);
extern jr_int jr_sockaddr_network_number(
const jr_sockaddr_t * sockaddr_info);
extern jr_int jr_sockaddr_host_number(
const jr_sockaddr_t * sockaddr_info);
extern jr_int jr_sockaddr_ip_cmp (
const jr_sockaddr_t * sockaddr_info_1,
const jr_sockaddr_t * sockaddr_info_2);
extern const char * jr_sockaddr_get_ip_str (
jr_sockaddr_t * sockaddr_info);
#define jr_sockaddr_ip_str(sockaddr_info) \
((const char *) (sockaddr_info)->ip_str \
? (sockaddr_info)->ip_str \
: jr_sockaddr_get_ip_str( (jr_sockaddr_t*) sockaddr_info) \
)
/*
** 2-18-2013: strip "const" above, eventhough the ip_str
** value is stored. Only non-const on the first call,
** is that good enough?
*/
#define jr_sockaddr_next_addr_ptr( sockaddr_info) \
((sockaddr_info)->next_sockaddr_ptr)
#define jr_sockaddr_foreach_addr_ptr( sockaddr_info, sockaddr_ptr) \
for ( (sockaddr_ptr) = jr_sockaddr_init_foreach( sockaddr_info); \
(sockaddr_ptr) != 0; \
(sockaddr_ptr) = jr_sockaddr_next_addr_ptr( sockaddr_ptr))
extern void jr_socket_init (
jr_socket_t * socket_info,
jr_int socket_type);
extern void jr_socket_undo (
jr_socket_t * socket_info);
extern jr_socket_t * jr_socket_create (
jr_int socket_type);
extern void jr_socket_destroy (
jr_socket_t * socket_info);
extern jr_int jr_socket_is_open(
jr_socket_t * socket_info);
extern jr_int jr_socket_open_generic (
jr_socket_t * socket_info,
jr_int opt_os_sock,
char * error_buf);
#ifdef ostype_winnt
#define jr_INVALID_OS_SOCKET INVALID_SOCKET
#else
#define jr_INVALID_OS_SOCKET -1
#endif
#define jr_socket_open( socket_info, error_buf) \
jr_socket_open_generic( socket_info, jr_INVALID_OS_SOCKET, error_buf)
#define jr_socket_open_from_fd( socket_info, socket_fd, error_buf) \
jr_socket_open_generic( socket_info, socket_fd, error_buf)
extern jr_int jr_socket_close (
jr_socket_t * socket_info,
char * error_buf);
extern jr_int jr_socket_connect (
jr_socket_t * socket_info,
const char * host_name,
jr_int port_number,
char * error_buf);
extern jr_int jr_socket_open_dgram (
jr_socket_t * socket_info,
const char * local_host_name,
jr_int port_number,
char * error_buf);
extern jr_int jr_socket_connect_unix (
jr_socket_t * socket_info,
const char * socket_path,
char * error_buf);
extern jr_int jr_socket_offer_service (
jr_socket_t * socket_info,
const char * host_name,
jr_int port_number,
char * error_buf);
extern jr_int jr_socket_accept (
jr_socket_t * accept_socket_info,
jr_socket_t * client_socket_info,
char * error_buf);
extern jr_int jr_socket_shutdown (
jr_socket_t * socket_info,
char * error_buf);
extern jr_int jr_socket_set_nonblock (
jr_socket_t * socket_info,
jr_int value,
char * error_buf);
extern jr_int jr_socket_port(
jr_socket_t * socket_info,
char * error_buf);
extern jr_int jr_socket_recv (
jr_socket_t * socket_info,
void * data_buf,
jr_int data_buf_len,
char * error_buf);
extern jr_int jr_socket_send (
jr_socket_t * socket_info,
const void * data_buf,
jr_int data_buf_len,
char * error_buf);
struct iovec;
extern jr_int jr_socket_sendto_iov (
jr_socket_t * socket_info,
jr_sockaddr_t * sockaddr_info,
struct iovec * iov,
jr_int iovlen,
char * error_buf);
extern jr_int jr_socket_recvfrom (
jr_socket_t * socket_info,
jr_sockaddr_t * sockaddr_info,
void * data_buf,
jr_int data_buf_len,
char * error_buf);
/*
** 11-30-2011: need to call jr_socket_flush() after jr_socket_printf()s
*/
extern jr_int jr_socket_printf (
jr_socket_t * socket_info,
const char * control_string, ...);
extern jr_int jr_socket_flush (
jr_socket_t * socket_info,
char * error_buf);
extern jr_int jr_socket_cmp (
const void * void_ptr_1,
const void * void_ptr_2);
extern jr_int jr_socket_hash (
const void * void_ptr);
#define jr_socket_apr_ptr(socket_info) \
((socket_info)->apr_socket_ptr)
/******** Process Spawning ********/
typedef struct jr_process {
void * apr_pool_ptr;
void * apr_proc_ptr;
void * apr_procattr_ptr;
jr_file_t input_wfi[1];
jr_file_t output_rfi[1];
jr_file_t error_rfi[1];
unsigned do_debug : 1;
} jr_process_t;
/*
** 4/19/09: NOTE: Undo()ing a running process will first send SIGTERM,
** wait 3 seconds, then send SIGKILL, then wait()
*/
#define jr_PROCESS_EXITTED 0x0001
#define jr_PROCESS_WAS_SIGNALLED 0x0002
#define jr_PROCESS_HAS_CORE 0x0004
#define jr_PROCESS_WAIT_BLOCK 0x0000
#define jr_PROCESS_WAIT_NON_BLOCK 0x0010
#define jr_PROCESS_NO_PIPE 0
#define jr_PROCESS_BLOCKING_PIPE 1
#define jr_PROCESS_NONBLOCKING_PIPE 2
extern void jr_process_init (
jr_process_t * process_ptr);
extern void jr_process_undo (
jr_process_t * process_ptr);
/*
** 5/4/08: Set the child's stdin to come from child_rfi.
** If that is the read side of a pipe, pass the write side in as well,
** otherwise pass a null
*/
extern jr_int jr_process_set_input (
jr_process_t * process_ptr,
jr_file_t * child_rfi,
jr_file_t * opt_parent_pipe_wfi,
char * error_buf);
/*
** 5/4/08: Set the child's stdout to go to child_wfi.
** If that is the write side of a pipe, pass the read side in as well,
** otherwise pass a null.
** Note: the wfi will be dup()ed, so if it's the write end of a pipe,
** the value passed in will need to closed.
*/
extern jr_int jr_process_set_output (
jr_process_t * process_ptr,
jr_file_t * child_wfi,
jr_file_t * opt_parent_pipe_rfi,
char * error_buf);
extern jr_int jr_process_set_error (
jr_process_t * process_ptr,
jr_file_t * child_wfi,
jr_file_t * opt_parent_pipe_rfi,
char * error_buf);
/*
** 4/30/09: each call to make_pipes() overwrites the previous
** pipes. So if you make an input pipe then an output pipe,
** the input pipe will be erase.
*/
extern jr_int jr_process_make_pipes(
jr_process_t * process_ptr,
jr_int input_kind,
jr_int output_kind,
jr_int error_kind,
char * error_buf);
#define jr_process_make_input_pipe( process_ptr, pipe_kind, error_buf) \
jr_process_make_pipes( \
process_ptr, pipe_kind, jr_PROCESS_NO_PIPE, jr_PROCESS_NO_PIPE, \
error_buf \
)
#define jr_process_make_output_pipe( process_ptr, pipe_kind, error_buf) \
jr_process_make_pipes( \
process_ptr, jr_PROCESS_NO_PIPE, pipe_kind, jr_PROCESS_NO_PIPE, \
error_buf \
)
extern jr_int jr_process_spawn (
jr_process_t * process_ptr,
const char * prog_name,
const char ** opt_argv,
const char ** opt_envp,
char * error_buf);
extern jr_int jr_process_wait (
jr_process_t * process_ptr,
jr_int flags,
jr_int * exit_status_ref,
jr_int * exit_why_ref,
char * error_buf);
extern jr_int jr_process_kill (
jr_process_t * process_ptr,
jr_int signum_status,
char * error_buf);
/*
** 11-29-2011: in MS the signal is used for the exit status?
*/
extern jr_int jr_process_id (
jr_process_t * process_ptr);
#define jr_process_set_do_debug(process_ptr, v) \
((process_ptr)->do_debug = (v) != 0)
#define jr_process_input_wfi(process_ptr) \
((process_ptr)->input_wfi)
#define jr_process_output_rfi(process_ptr) \
((process_ptr)->output_rfi)
#define jr_process_error_rfi(process_ptr) \
((process_ptr)->error_rfi)
/******** Threads/Mutexes ********/
#if defined(ostype_macosx)
#ifdef jr_IS_64_BIT
# define jr_THREAD_OSX_ONCE_SIZE 8
#else
# define jr_THREAD_OSX_ONCE_SIZE 4
#endif
#endif
typedef struct jr_thread_once {
# ifdef ostype_winnt
volatile long control_value;
# elif defined(ostype_cygwin)
struct {
void * mutex;
int state;
} control_value;
# elif defined(ostype_macosx)
struct {
long __sig;
char __opaque[jr_THREAD_OSX_ONCE_SIZE];
} control_value;
# else
int control_value;
# endif
} jr_thread_once_t;
# define jr_thread_once_declare_and_init(var_name) \
static jr_thread_once_t var_name = jr_PTHREAD_ONCE_INIT
extern void jr_thread_once_call (
jr_thread_once_t * once_control_ptr,
void (*some_func)());
/******** Mutexes ********/
/*
** 3/2/07: Can't use APR for mutexes because:
** - library functions need to initialize mutex
** -- APR mutex allocates memory
** -- so need a mutex to protect initialization
** - also, jr_apr_terminate() would free library mutexes
** -- need to re-initialize
** -- need a global datastructure of thread_once structures to reset
** -- need a mutex to keep track of this.
*/
#ifdef jr_IS_64_BIT
# define jr_SIZEOF_PTHREAD_MUTEX_T 64
# define jr_SIZEOF_MICROSOFT_MUTEX_T 64
#else
# define jr_SIZEOF_PTHREAD_MUTEX_T 32
# define jr_SIZEOF_MICROSOFT_MUTEX_T 32
#endif
typedef struct jr_mutex {
union {
char pthread_data[jr_SIZEOF_PTHREAD_MUTEX_T];
char microsoft_data[jr_SIZEOF_MICROSOFT_MUTEX_T];
} arch_data;
unsigned is_recursive : 1;
} jr_mutex_t;
extern void jr_mutex_init (
jr_mutex_t * mutex_ptr,
jr_int is_recursive);
extern void jr_mutex_undo (
jr_mutex_t * mutex_ptr);
extern void jr_mutex_lock (
jr_mutex_t * mutex_ptr);
extern void jr_mutex_unlock (
jr_mutex_t * mutex_ptr);
typedef struct jr_thread {
void * apr_pool_ptr;
void * apr_thread_ptr;
void (*thread_fn)(struct jr_thread *, void * arg_ptr);
void * arg_ptr;
} jr_thread_t;
extern void jr_thread_init (
jr_thread_t * thread_ptr);
extern void jr_thread_undo (
jr_thread_t * mutex_ptr);
extern jr_int jr_thread_spawn (
jr_thread_t * thread_ptr,
void (*thread_fn)(
jr_thread_t * thread_ptr,
void * arg_ptr
),
void * arg_ptr,
char * error_buf);
extern jr_int jr_thread_detach (
jr_thread_t * thread_ptr,
char * error_buf);
extern void jr_thread_exit(
jr_thread_t * thread_ptr,
jr_int exit_status);
extern jr_int jr_thread_wait(
jr_thread_t * thread_ptr,
jr_int * exit_status_ref,
char * error_buf);
typedef struct jr_pool {
void * apr_pool_ptr;
struct jr_pool * parent_pool_ptr;
} jr_pool_t;
extern void jr_pool_init (
jr_pool_t * pool_ptr,
jr_pool_t * opt_parent_pool_ptr);
extern void jr_pool_undo (
jr_pool_t * pool_ptr);
extern jr_pool_t * jr_pool_create(
jr_pool_t * opt_parent_pool_ptr);
extern void jr_pool_destroy (
jr_pool_t * pool_ptr);
extern void * jr_pool_alloc(
jr_pool_t * pool_ptr,
size_t mem_size);
extern char * jr_pool_strdup(
jr_pool_t * pool_ptr,
const char * src_str);
#define jr_pool_apr_pool_ptr( pool_ptr) \
((pool_ptr)->apr_pool_ptr)
#endif
|
frankjas/libjr
|
libjr/syscalls/jr_canon.c
|
<gh_stars>0
#include "ezport.h"
#include "jr/syscalls.h"
#include "jr/io.h"
#include "jr/error.h"
#include "jr/malloc.h"
jr_int jr_GetCanonicalPath (
const char * user_path,
char * path_buf,
jr_int path_buf_size,
char * error_buf)
{
const char * curr_path = 0;
jr_int status;
status = jr_getcwd (path_buf, path_buf_size, error_buf);
if (status != 0) {
goto return_status;
}
curr_path = jr_strdup (path_buf);
status = jr_chdir (user_path, error_buf);
if (status != 0) {
jr_esprintf (error_buf, "couldn't 'cd' to '%.64s': %s", path_buf, error_buf);
goto return_status;
}
status = jr_getcwd (path_buf, path_buf_size, error_buf);
if (status != 0) {
goto return_status;
}
status = jr_chdir (curr_path, error_buf);
if (status != 0) {
jr_esprintf (error_buf, "couldn't 'cd' back to '%.64s': %s", curr_path, error_buf);
goto return_status;
}
jr_free (curr_path);
curr_path = 0;
status = 0;
return_status : {
if (curr_path) {
jr_chdir (curr_path, error_buf);
jr_free (curr_path);
}
}
return status;
}
const char *jr_MallocCanonicalPath (
const char * user_path,
char * error_buf)
{
const char * curr_path = 0;
const char * canon_path = 0;
jr_int status;
curr_path = jr_getcwd_malloc (error_buf);
if (curr_path == 0) {
status = jr_INTERNAL_ERROR;
goto return_status;
}
status = jr_chdir (user_path, error_buf);
if (status != 0) {
jr_esprintf (error_buf, "couldn't 'cd' to '%.64s': %s", curr_path, error_buf);
goto return_status;
}
canon_path = jr_getcwd_malloc (error_buf);
if (canon_path == 0) {
status = jr_INTERNAL_ERROR;
goto return_status;
}
status = jr_chdir (curr_path, error_buf);
if (status != 0) {
jr_esprintf (error_buf, "couldn't 'cd' back to '%.64s': %s", curr_path, error_buf);
goto return_status;
}
jr_free (curr_path);
curr_path = 0;
status = 0;
return_status : {
if (status != 0) {
if (canon_path) {
jr_free (canon_path);
canon_path = 0;
}
}
if (curr_path) {
jr_chdir (curr_path, error_buf);
jr_free (curr_path);
}
}
return canon_path;
}
|
frankjas/libjr
|
libjr/syscalls/tmpfile.c
|
#define _POSIX_SOURCE 1
#include "ezport.h"
#include <string.h>
#include <stdlib.h>
#ifdef ostype_winnt
#include <crtdefs.h>
#include <io.h>
#include <fcntl.h>
#include <apr-1/apr_file_io.h>
#include <apr-1/apr_errno.h>
#else
#include <sys/types.h>
#include <unistd.h>
#include <errno.h>
#endif
#include "jr/syscalls.h"
#include "jr/error.h"
#include "jr/apr.h"
FILE *jr_TempFileOpen (opt_template, error_buf)
char * opt_template;
char * error_buf;
{
char * template = opt_template;
FILE * fp = 0;
jr_int fd = -1;
char tmp_dir[32];
char template_buf[sizeof (tmp_dir) + 10];
jr_int status;
/*
** 7/6/2004: returns a FILE * to a temporary file which disappears when closed.
**
** 2/8/07: apr_file_mktemp() provides for exclusive open and delete-on-close,
** however, getting a file pointer from it is impossible w/o keeping the apr_file_t
** around as well, so this API won't work.
** For win32, you need to use _open_osfhandle() then _fdopen(),
** see http://support.microsoft.com/kb/139640
*/
if (opt_template == 0) {
status = jr_GetTempDir (tmp_dir, sizeof (tmp_dir), error_buf);
if (status != 0) {
jr_esprintf (error_buf, "couldn't get tmp. directory: %s", error_buf);
fp = NULL;
goto return_fp;
}
sprintf (template_buf, "%s/jtXXXXXX", tmp_dir);
template = template_buf;
}
# ifdef ostype_winnt
{
HANDLE handle;
DWORD createflags = CREATE_NEW;
DWORD oflags = GENERIC_READ | GENERIC_WRITE;
DWORD attributes = FILE_FLAG_DELETE_ON_CLOSE;
DWORD sharemode = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
jr_int crt_handle;
jr_MkTemp (template);
handle = CreateFileA (
template, oflags, sharemode, NULL, createflags, attributes, 0
);
if (handle == INVALID_HANDLE_VALUE) {
jr_esprintf (error_buf, "couldn't CreateFile(): %s",
jr_apr_strerror (apr_get_os_error(), error_buf)
);
fp = NULL;
goto return_fp;
}
crt_handle = _open_osfhandle ((intptr_t) handle, _O_RDWR);
if (crt_handle < 0) {
CloseHandle (handle);
jr_esprintf (error_buf, "couldn't _open_osfhandle(): %s", strerror (errno));
fp = NULL;
goto return_fp;
}
fp = _fdopen (crt_handle, "w+b");
if (fp == NULL) {
_close (crt_handle); /* 2/8/07: closes 'handle' implicitly */
jr_esprintf (error_buf, "couldn't fdopen(): %s", strerror (errno));
goto return_fp;
}
}
# else
{
fd = mkstemp (template);
if (fd < 0) {
if (errno == EINVAL) {
jr_esprintf (error_buf, "no trailing 'XXXXXX' in temp. file name");
}
else if (errno == EEXIST) {
jr_esprintf (error_buf, "couldn't create temp. name");
}
else {
jr_esprintf (error_buf, "couldn't mkstemp(): %s", strerror (errno));
}
fp = NULL;
goto return_fp;
}
jr_Unlink (template, 0);
fp = fdopen (fd, "w+b");
if (fp == NULL) {
jr_esprintf (error_buf, "couldn't fdopen(): %s", strerror (errno));
goto return_fp;
}
fd = -1;
}
# endif
return_fp : {
if (fd >= 0) {
close (fd);
}
}
return fp;
}
|
frankjas/libjr
|
include/jr/mail.h
|
<reponame>frankjas/libjr<filename>include/jr/mail.h<gh_stars>0
#ifndef __jr_mail_h___
#define __jr_mail_h___
#include "ezport.h"
#include "jr/alist.h"
/******** Mail Library ********/
extern jr_int jr_MailStringMessage PROTO ((
char * smtp_server_name,
char * sender_full_address,
char * recipient_address,
char ** opt_header_vector,
char * message_string,
char * error_buf
));
extern jr_int jr_MailStringMessageWithSubjectOnly PROTO ((
char * smtp_server_name,
char * sender_address,
char * recipient_address,
char * opt_subject_buf,
char * message_string,
char * error_buf
));
extern jr_int jr_MailServerValidate PROTO ((
const char * smtp_server_name,
const char * sender_address,
char * error_buf
));
extern jr_int jr_MailAddressValidate PROTO ((
const char * recipient_address,
const char * smtp_server_name,
const char * sender_address,
char * error_buf
));
extern jr_int jr_MailServerValidateWithTimeOut PROTO ((
const char * smtp_server_name,
const char * opt_sender_address,
jr_int time_out_seconds,
char * error_buf
));
extern jr_int jr_MailAddressValidateWithTimeOut PROTO ((
const char * recipient_address,
const char * smtp_server_name,
const char * sender_address,
jr_int time_out_seconds,
char * error_buf
));
/******* MX Record Lookup ********/
/*
* Need to link with -lresolv
*/
extern jr_int jr_MailGetMailExchanger PROTO ((
const char * host_name,
char * smtp_server_name,
jr_int smtp_server_name_length,
char * error_buf
));
typedef struct {
const char * mx_name;
jr_int mx_preference;
jr_int inet_addr_number;
} jr_MX_EntryType;
typedef struct {
jr_AList list_field[1];
} jr_MX_EntryListType;
extern void jr_MX_EntryListInit PROTO ((
jr_MX_EntryListType * mx_entry_list
));
extern void jr_MX_EntryListUndo PROTO ((
jr_MX_EntryListType * mx_entry_list
));
extern void jr_MX_EntryListAddEntry PROTO ((
jr_MX_EntryListType * mx_entry_list,
const char * mx_name,
jr_int mx_preference
));
extern void jr_MX_EntryListSetInetAddress PROTO ((
jr_MX_EntryListType * mx_entry_list,
const char * mx_name,
jr_int inet_addr_number
));
extern jr_int jr_MX_EntryListLoadHostNameInfo PROTO ((
jr_MX_EntryListType * mx_entry_list,
const char * host_name,
char * error_buf
));
#define jr_MX_EntryListIsEmpty(mx_entry_list) \
jr_AListIsEmpty ((mx_entry_list)->list_field)
#define jr_MX_EntryListSize(mx_entry_list) \
jr_AListSize ((mx_entry_list)->list_field)
#define jr_MX_EntryListSortByPreference(mx_entry_list) \
jr_AListQSort ((mx_entry_list)->list_field, jr_MX_EntryPreferenceCmp)
#define jr_MX_EntryListEntryPtr(mx_entry_list, k) \
((jr_MX_EntryType *) jr_AListElementPtr ((mx_entry_list)->list_field, k))
#define jr_MX_EntryListFirstEntryPtr(mx_entry_list) \
((jr_MX_EntryType *) jr_AListHeadPtr ((mx_entry_list)->list_field))
#define jr_MX_EntryListForEachEntryPtr(mx_entry_list, mx_entry_ptr) \
jr_AListForEachElementPtr ((mx_entry_list)->list_field, mx_entry_ptr)
#define jr_MX_EntryListForEachEntryIndex(mx_entry_list, k) \
jr_AListForEachElementIndex ((mx_entry_list)->list_field, k)
extern void jr_MX_EntryInit PROTO ((
jr_MX_EntryType * mx_entry_ptr,
const char * mx_name,
jr_int mx_preference
));
extern void jr_MX_EntryUndo PROTO ((
jr_MX_EntryType * mx_entry_ptr
));
extern jr_int jr_MX_EntryPreferenceCmp PROTO ((
const void * void_ptr_1,
const void * void_ptr_2
));
#define jr_MX_EntryName(mx_entry_ptr) ((mx_entry_ptr)->mx_name)
#define jr_MX_EntryPreference(mx_entry_ptr) ((mx_entry_ptr)->mx_preference)
#define jr_MX_EntryInetAddrNumber(mx_entry_ptr) ((mx_entry_ptr)->inet_addr_number)
#define jr_MX_EntrySetInetAddrNumber(mx_entry_ptr, v) \
((mx_entry_ptr)->inet_addr_number = (v))
#endif
|
frankjas/libjr
|
libjr/symtab/st_prnt.c
|
#include "project.h"
jr_int jr_ST_PrintDeclaration (declarator_type, opt_declarator_name, prefix, wfp)
jr_ST_TypeStruct * declarator_type;
char * opt_declarator_name;
char * prefix;
FILE * wfp;
{
char dest_buf [1024];
jr_int status;
status = jr_ST_DeclarationToString (
declarator_type,
0, /* opt_base_type_sym */
opt_declarator_name,
0, /* nesting_level */
dest_buf, sizeof (dest_buf)
);
if (prefix == 0) {
prefix = "";
}
if (status == 0) {
fprintf (wfp, "%s%s", prefix, dest_buf);
}
else {
fprintf (wfp, "%s%s...(decl. too long)", prefix, dest_buf);
}
return (status);
}
jr_int jr_ST_DeclarationToString (
declarator_type, opt_base_type_sym, opt_declarator_name,
nesting_level, dest_buf, buf_length
)
jr_ST_TypeStruct * declarator_type;
jr_ST_Symbol * opt_base_type_sym;
char * opt_declarator_name;
jr_int nesting_level;
char * dest_buf;
jr_int buf_length;
{
char * end_ptr;
jr_ST_Symbol * curr_base_type_sym;
jr_ST_Symbol * base_type_sym;
jr_int i;
jr_int * ip;
jr_AList stars_list[1];
jr_int status;
end_ptr = dest_buf + buf_length - 1;
*end_ptr = 0;
/*
* null out the string so that after an array bounds error
* they still get a valid string
*/
jr_AListInit (stars_list, sizeof (jr_int));
/*
* for each type in the list of abstract declarators
* record the number of stars
*/
jr_AListNativeSetNewTail (stars_list, jr_ST_TypeNumStars (declarator_type), jr_int);
/*
* count the number of stars per nesting level in declaration
*/
curr_base_type_sym = jr_ST_TypeBaseSymbol (declarator_type);
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
*/
jr_AListNativeSetNewTail (
stars_list, jr_ST_TypeNumStars (jr_ST_SymbolType (curr_base_type_sym)), int
);
curr_base_type_sym = jr_ST_TypeBaseSymbol (jr_ST_SymbolType (curr_base_type_sym));
}
/*
* print the passed in base type for this symbol, not the actual base type
* (to allow a caller to change the base type)
*/
if (opt_base_type_sym) {
base_type_sym = opt_base_type_sym;
}
else {
base_type_sym = jr_ST_FindBaseTypeSymbol (declarator_type);
}
buf_length = end_ptr - dest_buf;
status = jr_ST_TypeSymbolToString (
base_type_sym, nesting_level + 1, dest_buf, buf_length + 1
);
if (status != 0) goto return_bad;
dest_buf = strchr (dest_buf, 0);
*dest_buf = ' '; dest_buf++; if (dest_buf == end_ptr) goto return_bad;
/*
* print the stars in reverse order, with open paren around each
* new level, except for the first
*/
jr_AListForEachElementPtrRev (stars_list, ip) {
for (i=0; i < *ip; i++) {
/*
* add a star to the buffer
*/
*dest_buf = '*'; dest_buf++; if (dest_buf == end_ptr) goto return_bad;
}
if (ip != jr_AListHeadPtr (stars_list)) {
*dest_buf = '('; dest_buf ++; if (dest_buf == end_ptr) goto return_bad;
}
}
/*
* put the name of the variable
*/
if (opt_declarator_name) {
jr_int str_length = (jr_int) strlen (opt_declarator_name);
buf_length = end_ptr - dest_buf;
if (str_length > buf_length) goto return_bad;
strcpy (dest_buf, opt_declarator_name);
dest_buf += str_length;
}
/*
* put the array or parameter parts of the declaration(s)
* followed by the close parens
*/
buf_length = end_ptr - dest_buf;
status = jr_ST_TypeListToString (declarator_type, dest_buf, buf_length + 1);
if (status != 0) goto return_bad;
dest_buf = strchr (dest_buf, 0);
/*
* loop through each nesting level to print the parameter list or
* array dimensions (using TypeListToString).
* Also print close paren.
*/
curr_base_type_sym = jr_ST_TypeBaseSymbol (declarator_type);
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
*/
*dest_buf = ')'; dest_buf ++; if (dest_buf == end_ptr) goto return_bad;
buf_length = end_ptr - dest_buf;
status = jr_ST_TypeListToString (
jr_ST_SymbolType (curr_base_type_sym), dest_buf, buf_length + 1
);
if (status != 0) goto return_bad;
dest_buf = strchr (dest_buf, 0);
curr_base_type_sym = jr_ST_TypeBaseSymbol (jr_ST_SymbolType (curr_base_type_sym));
}
if (1) {
status = 0;
}
else {
return_bad :
status = -1;
}
jr_AListUndo (stars_list);
return (status);
}
jr_int jr_ST_TypeSymbolToString (base_type_sym, nesting_level, dest_buf, buf_length)
jr_ST_Symbol * base_type_sym;
jr_int nesting_level;
char * dest_buf;
jr_int buf_length;
{
/*
* this function can only be called on typedefs, builtins
* structs or unions
*/
char * end_ptr;
jr_int status, i;
end_ptr = dest_buf + buf_length - 1;
*end_ptr = 0;
/*
* null out the string so that after an array bounds error
* they still get a valid string
*/
switch (jr_ST_SymbolKind (base_type_sym)) {
/*
* a string will act like a built in
*/
case jr_ST_STRING :
case jr_ST_BUILTIN :
case jr_ST_TYPEDEF : {
char *string;
jr_int str_length;
string = jr_ST_SymbolStr (base_type_sym);
str_length = (jr_int) strlen (string);
buf_length = end_ptr - dest_buf;
if (str_length > buf_length) goto return_bad;
strcpy (dest_buf, string);
dest_buf += str_length;
break;
}
case jr_ST_STRUCT :
case jr_ST_UNION :
case jr_ST_ENUM : {
jr_ST_FieldList * field_list;
jr_ST_FieldType * field;
char * string;
if (jr_ST_SymbolStr (base_type_sym)) {
string = jr_ST_SymbolStr (base_type_sym);
}
else if (jr_ST_SymbolKind(base_type_sym) == jr_ST_STRUCT) {
string = "struct {\n";
}
else if (jr_ST_SymbolKind(base_type_sym) == jr_ST_UNION) {
string = "union {\n";
}
else {
string = "enum {\n";
}
{
jr_int str_length = (jr_int) strlen (string);
buf_length = end_ptr - dest_buf;
if (str_length > buf_length) goto return_bad;
strcpy (dest_buf, string);
dest_buf += str_length;
}
if (jr_ST_SymbolStr (base_type_sym)) {
break;
}
if (jr_ST_SymbolKind (base_type_sym) == jr_ST_ENUM) {
break;
}
/*
* its an un-named struct, print the fields in the declaration
*/
field_list = jr_ST_TypeFieldList (jr_ST_SymbolType (base_type_sym));
jr_ST_FieldListForEachElementPtr (field_list, field) {
for (i=0; i < nesting_level; i++) {
/*
* add a tab to the buffer
*/
*dest_buf = '\t'; dest_buf++; if (dest_buf == end_ptr) goto return_bad;
}
buf_length = end_ptr - dest_buf;
status = jr_ST_DeclarationToString (
jr_ST_FieldTypePtr (field),
jr_ST_FindBaseTypeSymbol (jr_ST_FieldTypePtr (field)),
jr_ST_FieldStr (field),
nesting_level,
dest_buf, buf_length + 1
);
if (status != 0) goto return_bad;
dest_buf = strchr (dest_buf, 0);
*dest_buf = ';'; dest_buf++; if (dest_buf == end_ptr) goto return_bad;
*dest_buf = '\n'; dest_buf++; if (dest_buf == end_ptr) goto return_bad;
}
for (i=0; i < nesting_level-1; i++) {
*dest_buf = '\t'; dest_buf++; if (dest_buf == end_ptr) goto return_bad;
}
*dest_buf = '}'; dest_buf++; if (dest_buf == end_ptr) goto return_bad;
*dest_buf = ' '; dest_buf++; if (dest_buf == end_ptr) goto return_bad;
*dest_buf = 0;
break;
}
}
if (1) {
status = 0;
}
else {
return_bad: status = -1;
}
return (status);
}
jr_int jr_ST_TypeListToString (type, dest_buf, buf_length)
jr_ST_TypeStruct * type;
char * dest_buf;
jr_int buf_length;
{
/*
* only should be called for variables or functions
*/
char * end_ptr;
jr_int status = 0;
end_ptr = dest_buf + buf_length - 1;
*end_ptr = 0;
switch (jr_ST_TypeKind (type)) {
case jr_ST_VARIABLE : {
jr_ST_ArrayList * list = jr_ST_TypeArrayList (type);
jr_int i, str_length;
char * string;
char digit_buf [64];
jr_ST_ArrayForEachDimension (list, i) {
*dest_buf = '['; dest_buf++; if (dest_buf == end_ptr) goto return_bad;
/*
* first use the length number, then the length str,
* then the length expr
*/
if ( jr_ST_ArrayDimensionLengthNum (list, i) > 0
|| jr_ST_ArrayDimensionLengthStr (list, i)) {
if (jr_ST_ArrayDimensionLengthNum (list, i) > 0) {
sprintf (digit_buf, "%d", jr_ST_ArrayDimensionLengthNum (list, i));
string = digit_buf;
}
else {
string = jr_ST_ArrayDimensionLengthStr (list, i);
}
str_length = (jr_int) strlen (string);
buf_length = end_ptr - dest_buf;
if (str_length > buf_length) goto return_bad;
strcpy (dest_buf, string);
dest_buf += str_length;
}
else if (jr_ST_ArrayDimensionLengthExpr (list, i)) {
char error_buf [512];
buf_length = end_ptr - dest_buf;
status = jr_C_ExprNodeToString (
dest_buf, buf_length + 1, jr_ST_ArrayDimensionLengthExpr (list, i), error_buf
);
if (status != 0) goto return_bad;
dest_buf = strchr (dest_buf, 0);
}
*dest_buf = ']'; dest_buf++; if (dest_buf == end_ptr) goto return_bad;
}
*dest_buf = 0;
break;
}
case jr_ST_FUNCTION : {
jr_ST_ParamList *list = jr_ST_TypeParamList (type);
jr_ST_ParamType *param;
jr_int first_time = 1;
*dest_buf = ' '; dest_buf++; if (dest_buf == end_ptr) goto return_bad;
*dest_buf = '('; dest_buf++; if (dest_buf == end_ptr) goto return_bad;
jr_ST_ParamListForEachElementPtr (list, param) {
if (!first_time) {
*dest_buf = ','; dest_buf++; if (dest_buf == end_ptr) goto return_bad;
*dest_buf = ' '; dest_buf++; if (dest_buf == end_ptr) goto return_bad;
}
buf_length = end_ptr - dest_buf;
status = jr_ST_DeclarationToString (
jr_ST_ParamTypePtr (param),
jr_ST_FindBaseTypeSymbol (jr_ST_ParamTypePtr (param)),
jr_ST_ParamStr (param),
0, /* nesting_level */
dest_buf, buf_length + 1
);
if (status != 0) goto return_bad;
dest_buf = strchr (dest_buf, 0);
first_time = 0;
}
*dest_buf = ')'; dest_buf++; if (dest_buf == end_ptr) goto return_bad;
*dest_buf = 0;
}
}
if (1) {
status = 0;
}
else {
return_bad : status = -1;
}
return (status);
}
|
frankjas/libjr
|
libjr/io/lineone.c
|
<filename>libjr/io/lineone.c
#include "ezport.h"
#include <stdio.h>
#include <string.h>
#include "jr/io.h"
jr_int jr_FirstLineOfFileName(rfn, result_buf, result_buf_length)
const char * rfn ;
char * result_buf ;
jr_int result_buf_length ;
{
FILE * rfp ;
char * tp ;
rfp = fopen(rfn, "r") ;
if (rfp == NULL) {
return(-1) ;
}
if (result_buf_length > 0) {
*result_buf = 0 ;
}
fgets(result_buf, result_buf_length, rfp) ;
fclose(rfp) ;
if (tp = (char *) strchr(result_buf,'\n')) {
*tp = 0 ;
}
return(0) ;
}
|
frankjas/libjr
|
include/ezport.h
|
#ifndef __ezport_h__
#define __ezport_h__
#ifdef __cplusplus
extern "C" {
#endif
/*
** 4-11-2011: the jr header files are all straight C
*/
#ifdef WIN32
# ifndef ostype_winnt
# define ostype_winnt
# endif
#endif
#ifdef __linux
# ifndef ostype_linux
# define ostype_linux
# endif
# define _GNU_SOURCE 1
# define missing_wifcore_macro
# define missing_msghdr_accrights_fields
#endif
#ifdef __APPLE__
# ifndef ostype_macosx
# define ostype_macosx
# endif
#endif
#ifdef ostype_winnt
# if (_MSC_VER <= 1400)
# define missing_tar_h
# define missing_crypt_extern
/*
** 1/25/07: accessing htonl() etc requires including windows header
** files in "jr" headers which cause other compilation problems:
** - can't 'extern "C"' jr headers (windows headers have templates)
*/
# define has_broken_sigio_on_pipes
# define missing_regex
# define needs_winnt_vsnprintf
# endif
# if (_MSC_VER <= 1500)
# define missing_addr_types
# define missing_getrusage
# define missing_roundf
# define missing_xdr_float
# define missing_xdrmem_create
# define missing_sigaction_types
/*
** 5-17-2011: temporary define to allow inclusion of tcpd.h
** See also io/http_lib.h and the #define of _POSIX_SOURCE
*/
# endif
# if (_MSC_VER <= 1600)
# define missing_stdbool_header
# endif
# if (_MSC_VER <= 1800)
# define needs_winnt_snprintf
# endif
# define reduce_winnt_compile
# define needs_winnt_defines_for_APR
# define needs_POSIX_fixes
# define missing_struct_iov
# define missing_rpc_headers
# define missing_strptime
# define missing_execinfo_h
# define missing_file_descriptors
# define missing_mode_t
# define missing_strcasecmp
# define missing_wifcore_macro
# define replace_byte_order_funcs
# define missing_sys_siglist_extern
# define missing_sys_siglist_objects
# define missing_unistd_h
/*
** from jr/posix/ezport.h
*/
# include "jr/ezport/microsoft.h"
#endif
#ifdef ostype_linux
# ifdef _POSIX_SOURCE
# define missing_strcasestr
# endif
#endif
#ifdef ostype_macosx
# define missing_strcasecmp_extern
#endif
#include "jr/ezport/apr.h"
#include "jr/ezport/types.h"
#include "jr/ezport/ansi.h"
#include "jr/ezport/missing.h"
#ifdef __cplusplus
}
#endif
/*
* This is an example ezport.h header file.
* In order to be able to compile code provided
* by JR International, you need to create a file
* named ezport.h
*
* If you encounter problems compiling JR code,
* then you should add a platform specifier
* corresponding to your platform in this file
*
* Create a #define which identifies the porting
* problem (see jr/ezport.h for an example).
* Then create a conditionally compiled solution
* for that problem (see jr/ezport/missing.h for
* an example).
*
* You may want to look through jr/ezport/ files
* since the problem you encountered may already
* have a solution provided by JR International.
*/
#define jr_pp_string_value(v) #v
#define jr_pp_value(v) pp_string_value(v)
/*
** For debugging macro values (MS Visual Studio only) use:
**
** #pragma message ("Version is " jr_pp_value( __version__))
*/
#endif
|
frankjas/libjr
|
include/jr/string.h
|
#ifndef __jr_string_h__
#define __jr_string_h__
#include "ezport.h"
#include <stdio.h>
#include <ctype.h>
extern void jr_RemoveAllOfChar (
char * modifiable_string,
jr_int char_val_removed) ;
extern void jr_RemoveContiguousDuplicateChar (
char * string_with_possible_duplicate_chars, /* mypath//tmp///dir */
jr_int char_to_be_eliminated /* '/' mypath/tmp/dir */
) ;
extern jr_int jr_CountAllOfChar (
const char * search_string,
jr_int char_val_counted);
extern void jr_ReplaceAllOfChar (
char * modifiable_string,
jr_int old_char_val,
jr_int new_char_val) ;
extern const char * jr_EscapedStringFromControlChar (jr_int c) ;
extern const char * jr_StringFromControlChar (
jr_int char_val) ;
extern void jr_CopyControlCharsToEscapedChars (
char * modifiable_target_string,
jr_int target_array_bounds,
const char * source_string) ;
extern void jr_ControlCharsToEscapedChars (
char * modifiable_string) ;
extern jr_int jr_RemoveTrailingWhiteSpace (
char * modifiable_string) ;
extern char ** jr_extendpath (
char ** jr_malloced_env_vector,
const char * pathname) ;
extern const char * jr_PathTail (
const char * file_path);
extern const char *jr_GetTrailingPath (
const char * path_string,
char * trailing_path_buf,
jr_int trailing_path_buf_size);
extern void jr_NormalizePath (
char * file_path);
extern void jr_EscapedCharsToControlChars (
char * modifiable_string) ;
extern jr_int jr_EndsWithOddBackslashes (
const char * string) ;
extern jr_int jr_IsString (
char * data_ptr,
jr_int data_length);
extern jr_int jr_StringIsAllDigits (
const char * string) ;
extern jr_int jr_StringIsValidIdentifier (
const char * potential_identifier_string) ;
extern char * jr_strnchr (
const char * str,
jr_int c,
jr_int len);
extern char * jr_rstrchr (
const char * end_str,
const char * str,
jr_int c);
#ifdef compiler_has_ansi_support
extern jr_int jr_ColumnScanf (
const char * input_str,
const char * control_str,
...
) ;
#else
extern jr_int jr_ColumnScanf () ;
#endif
extern void jr_ConvertToUpperCase (
char * modifiable_string) ;
extern void jr_ConvertToLowerCase (
char * modifiable_string) ;
extern void jr_CopyAndConvertCase (
char * modifiable_target_string,
jr_int target_array_bounds,
const char * source,
const char * case_control_string) ;
extern jr_int jr_StringIsAllUpper (
const char * string) ;
extern jr_int jr_StringIsAllLower (
const char * string) ;
extern jr_int jr_CountSubByteMatches (
const void * source_buf_arg,
jr_int source_len,
const void * pattern_arg,
jr_int patlen) ;
extern jr_int jr_IsGlobMatch PROTO((
const char * text,
const char * pattern,
jr_int match_slashes,
jr_int match_leading_dot
)) ;
extern jr_int jr_HasGlobPatternChars PROTO((
const char * potential_pattern_string
)) ;
extern jr_int jr_GlobPatternOffset PROTO((
const char * potential_pattern_string
)) ;
/*
** 8-8-2011: alternate API using APR
*/
#define jr_GLOB_MATCH_PATH_SEPARATOR 0x0001
#define jr_GLOB_MATCH_PERIOD 0x0002
#define jr_GLOB_NO_ESCAPES 0x0004
#define jr_GLOB_IGNORE_CASE 0x0008
extern jr_int jr_StringHasGlobChars(
const char * string);
extern jr_int jr_StringHasGlobMatch(
const char * string,
const char * pattern,
unsigned jr_int flags);
extern const char * jr_regex_strerror (
jr_int reg_errno);
#define jr_REGEX_NO_FLAGS 0x0000
#define jr_REGEX_POSIX_EXTENDED_FLAG 0x0001
#define jr_REGEX_IGNORE_CASE_FLAG 0x0002
extern const char * jr_RegExSub (
const char * source_string,
const char * pattern_string,
const char * replace_string,
jr_int flags,
char * error_buf);
extern jr_int jr_RegExMatch (
const char * source_string,
const char * pattern_string,
jr_int flags,
char * error_buf);
extern char * jr_ReplaceSubStringGlobally (
const char * source_buf_arg,
const char * old_pattern_arg,
const char * new_pattern_arg) ;
extern void * jr_ReplaceSubByteMatches (
const void * source_buf_arg,
jr_int source_buf_len,
const void * old_pattern_arg,
jr_int old_pattern_len,
const void * new_pattern_arg,
jr_int new_pattern_len) ;
extern char * jr_StringFgets (
char * modifiable_target_string,
jr_int target_array_bounds,
const char * source_string) ;
extern char * jr_FirstNonWhiteSpacePtr ( /* was skip */
const char * search_string) ;
extern jr_int jr_FirstNonWhiteSpaceIndex (
const char * search_string) ;
extern char * jr_NextNonWhiteSpacePtr (
const char * search_string) ;
/*
** 1/24/07: Skip over non-white space followed by white-space
*/
extern char * jr_FirstWhiteSpacePtr (
const char * search_string) ;
extern jr_int jr_FirstWhiteSpaceIndex (
const char * search_string) ;
extern jr_int jr_SubStringIndex (
const char * search_string,
const char * pattern) ;
extern void jr_StringUnQuote (
char * modifiable_string) ;
extern char * jr_TTY_LettersFromDeviceName (
char * dev_name_string) ;
/******** URL Encoding/Decoding ********/
extern char * jr_StringEncodeForURL (
const char * input_string);
extern char * jr_StringDecodeFromURLWithFixReturn (
const char * input_string,
jr_int fix_return_newline);
#define jr_StringDecodeFromURLAndFixReturn(input_string) \
jr_StringDecodeFromURLWithFixReturn (input_string, 1)
/*
* Remove <CR> from <CR><LF> sequences
*/
#define jr_StringDecodeFromURL(input_string) \
jr_StringDecodeFromURLWithFixReturn (input_string, 0)
extern char * jr_StringEncodeForQuotes (
const char * input_string,
const char * quotes_string);
#define jr_StringDecode(input_string) \
jr_StringDecodeFromURL (input_string)
/******** URL Encoding/Decoding ********/
#define jr_tolower(c) (isupper(c) ? (c) | 040 : (c))
#define jr_toupper(c) (islower(c) ? (c) &(~040) : (c))
#define jr_ForEachOccurenceInStr(str,pattern,pos,i) \
for ( \
(pos) = jr_SubStringIndex(str,pattern); \
(pos)>=0; \
(pos) = ( \
(i) = jr_SubStringIndex ((str)+(pos)+1, pattern)) < 0 \
? (i) \
: (i)+(pos)+1 \
)
#if 0
/*
** 1/24/07: Dangerous use of sscanf()
*/
#define jr_ForEachWordInString(str,ptr,word,word_size) \
for ( \
(ptr) = jr_FirstNonWhiteSpacePtr(str); \
*(ptr); \
(ptr) += strlen(word), (ptr) = jr_FirstNonWhiteSpacePtr(ptr) \
) if (sscanf(ptr,"%s", word)<1) break ; else
#define jr_ForEachLineInBuffer(buf,line,ptr) \
for ( \
(ptr)=(buf); \
*(ptr); \
(ptr) += strlen(line) + 1 \
) if (sscanf (ptr, "%[^\n]", line) < 1) break; else
#endif
#define jr_ForEachLinePtrInBuffer(buf,cp) \
for ( \
(cp) = (buf); \
(cp) && *(cp); \
(cp) = strchr (cp, '\n'), (cp) \
? (cp) = jr_FirstNonWhiteSpacePtr(cp) \
: 0 \
)
#endif
|
frankjas/libjr
|
libjr/misc/pfx_proj.h
|
#ifndef __misc_prefix_h____
#define __misc_prefix_h____
#include "ezport.h"
#include <stdlib.h>
#include "jr/prefix.h"
#include "jr/string.h"
#include "jr/malloc.h"
#include "jr/syscalls.h"
#include "jr/apr.h"
#include "jr/alist.h"
#define jr_PREFIX_MAX_TYPES 256
extern jr_int jr_PrefixInfoElementPrefixSize PROTO ((
jr_PrefixInfoType * prefix_info
));
#endif
|
frankjas/libjr
|
libjr/avl_tree/project.h
|
#ifndef __project_h___
#define __project_h___
#include "ezport.h"
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include "jr/avl_tree.h"
#include "jr/malloc.h"
#include "jr/misc.h"
#include "jr/alist.h"
#include "jr/prefix.h"
#define has_jr_avl_tree_with_prefix
/*
* These ifdefs enable this source code to be used as
* class examples. Creating separate copies, like is
* done for the other data structures, creates more of
* an update problem, since the avl tree code is more
* complex.
*/
extern void jr_AVL_TreeTraverseFree PROTO ((
jr_AVL_Tree * avl_tree,
void * node
));
extern void jr_AVL_TreeAppendToPath PROTO ((
jr_AVL_Tree * avl_tree,
void * path[],
jr_int path_length,
jr_int is_left_child,
const void * new_node
));
extern void * jr_AVL_TreeExtractPathEnd PROTO ((
jr_AVL_Tree * avl_tree,
void * path[],
jr_int path_length
));
extern void jr_AVL_TreeBalancePath PROTO ((
jr_AVL_Tree * avl_tree,
void ** path,
jr_int path_length
));
extern void jr_AVL_TreeBalanceElement PROTO ((
jr_AVL_Tree * avl_tree,
void * curr_node,
void * parent_node
));
extern jr_int jr_AVL_TreeFillSearchPath PROTO ((
jr_AVL_Tree * avl_tree,
void ** path,
const void * obj
));
extern void * jr_AVL_TreeGetPrevPtrFromPath PROTO ((
jr_AVL_Tree * avl_tree,
void ** path,
jr_int path_length
));
extern void * jr_AVL_TreeGetNextPtrFromPath PROTO ((
jr_AVL_Tree * avl_tree,
void ** path,
jr_int path_length
));
extern void ** jr_AVL_TreeToElementArray PROTO ((
jr_AVL_Tree * avl_tree
));
extern void jr_AVL_TreeTraverseForElementArray PROTO ((
jr_AVL_Tree * avl_tree,
const void * node,
void ** node_array,
jr_int array_index
));
extern void jr_AVL_TreeElementUpdateTreeSize PROTO ((
jr_AVL_Tree * avl_tree,
void * node_ptr
));
#define jr_AVL_TreeIncrementElementTreeSize(avl_tree, node_ptr) \
(jr_AVL_TreeSubTreeSize (avl_tree, node_ptr) ++)
#define jr_AVL_TreeDecrementElementTreeSize(avl_tree, node_ptr) \
(jr_AVL_TreeSubTreeSize (avl_tree, node_ptr) --)
#endif
|
frankjas/libjr
|
libjr/struct/jr_long.c
|
#include "ezport.h"
#include "jr/misc.h"
#include "jr/long.h"
#ifdef jr_IS_64_BIT
jr_int jr_LongCmp (long1, long2)
jr_Long long1;
jr_Long long2;
{
if (long1 > long2) {
return (1);
}
if (long1 < long2) {
return (-1);
}
return (0);
}
jr_int jr_LongCmpInt (long1, int_value)
jr_Long long1;
jr_int int_value;
{
if (long1 > int_value) {
return (1);
}
if (long1 < int_value) {
return (-1);
}
return (0);
}
jr_int jr_LongPtrCmp (void_arg_1, void_arg_2)
const void * void_arg_1;
const void * void_arg_2;
{
const jr_Long * long1 = void_arg_1;
const jr_Long * long2 = void_arg_2;
if (*long1 > *long2) {
return 1;
}
if (*long1 < *long2) {
return -1;
}
return 0;
}
jr_int jr_LongPtrHash (void_arg_1)
const void * void_arg_1;
{
const jr_Long * 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;
}
void jr_LongSetMSW(
jr_Long * longp,
jr_int value)
{
jr_int abs_lsw = *longp % jr_INT_MIN;
if (abs_lsw < 0) {
abs_lsw = -abs_lsw;
}
if (value < 0) {
*longp = ((jr_Long) value << 31) - abs_lsw;
}
else {
*longp = ((jr_Long) value << 31) + abs_lsw;
}
}
void jr_LongSetLSW(
jr_Long * longp,
jr_int value)
{
jr_int abs_lsw = *longp % jr_INT_MIN;
if (abs_lsw < 0) {
abs_lsw = -abs_lsw;
}
if (*longp < 0) {
*longp = *longp + abs_lsw - value;
}
else {
*longp = *longp - abs_lsw + value;
}
}
#else
jr_int jr_LongCmp (long1, long2)
const jr_Long long1;
const jr_Long long2;
{
if (long1.msw < long2.msw) {
return -1;
}
if (long1.msw > long2.msw) {
return 1;
}
if (long1.lsw < long2.lsw) {
return -1;
}
if (long1.lsw > long2.lsw) {
return 1;
}
return 0;
}
jr_int jr_LongPtrCmp (void_arg_1, void_arg_2)
const void * void_arg_1;
const void * void_arg_2;
{
const jr_Long * long1 = void_arg_1;
const jr_Long * long2 = void_arg_2;
if (long1->msw < long2->msw) {
return -1;
}
if (long1->msw > long2->msw) {
return 1;
}
if (long1->lsw < long2->lsw) {
return -1;
}
if (long1->lsw > long2->lsw) {
return 1;
}
return 0;
}
void jr_LongAddInt (result, long1, int_value)
jr_Long * result;
jr_Long long1;
jr_int int_value;
{
if (int_value >= 0) {
/* addition */
if (jr_LongIsPositive (long1)) {
if (int_value > jr_INT_MAX - jr_LongLSW (long1)) {
jr_LongSetMSW (result, jr_LongMSW (long1) + 1);
jr_LongSetLSW (result, int_value - (jr_INT_MAX - jr_LongLSW (long1)) - 1);
}
else {
jr_LongSetMSW (result, jr_LongMSW (long1));
jr_LongSetLSW (result, jr_LongLSW (long1) + int_value);
}
}
else if (jr_LongLSW (long1) < 0) {
/* MSW == 0 */
jr_LongSetMSW (result, 0);
jr_LongSetLSW (result, jr_LongLSW (long1) + int_value);
}
else {
/* MSW < 0, LSW > 0 */
if ((int_value) > jr_LongLSW (long1)) {
jr_LongSetMSW (result, jr_LongMSW (long1) + 1);
jr_LongSetLSW (result, jr_INT_MAX - int_value + jr_LongLSW (long1) + 1);
if (jr_LongMSW (*result) == 0) {
jr_LongSetLSW (result, -jr_LongLSW (*result));
}
}
else {
jr_LongSetMSW (result, jr_LongMSW (long1));
jr_LongSetLSW (result, jr_LongLSW (long1) - int_value);
}
}
}
else {
/* subtraction */
int_value = -int_value;
if (jr_LongLSW (long1) >= 0) {
if (jr_LongMSW (long1) == 0) {
jr_LongSetMSW (result, jr_LongMSW (long1));
jr_LongSetLSW (result, jr_LongLSW (long1) - int_value);
}
else if (jr_LongMSW (long1) < 0) {
if (jr_INT_MAX - jr_LongLSW (long1) > int_value) {
jr_LongSetMSW (result, jr_LongMSW (long1));
jr_LongSetLSW (result, jr_LongLSW (long1) + int_value);
}
else {
jr_LongSetMSW (result, jr_LongMSW (long1) - 1);
jr_LongSetLSW (result, jr_INT_MAX - int_value - jr_LongLSW (long1) + 1);
}
}
else {
if (jr_LongLSW (long1) >= int_value) {
jr_LongSetMSW (result, jr_LongMSW (long1));
jr_LongSetLSW (result, jr_LongLSW (long1) - int_value);
}
else {
jr_LongSetMSW (result, jr_LongMSW (long1) - 1);
jr_LongSetLSW (result, jr_INT_MAX - int_value + jr_LongLSW (long1) + 1);
}
}
}
else {
/* MSW == 0, LSW < 0 */
if (jr_INT_MAX + jr_LongLSW (long1) > int_value) {
jr_LongSetMSW (result, 0);
jr_LongSetLSW (result, jr_LongLSW (long1) - int_value);
}
else {
jr_LongSetMSW (result, -1);
jr_LongSetLSW (result, int_value - (jr_INT_MAX + jr_LongLSW (long1)) - 1);
}
}
}
}
void jr_LongAdd (result, long1, long2)
jr_Long * result;
jr_Long long1;
jr_Long long2;
{
if (jr_LongIsPositive (long2)) {
jr_LongAddInt (result, long1, jr_LongLSW (long2));
if (jr_LongIsNegative( *result)) {
if (jr_LongLSW (*result) < 0 && jr_LongMSW (long2) > 0) {
/* carry jr_INT_MAX to LSW */
jr_LongSetMSW (result, jr_LongMSW (long2) - 1);
jr_LongSetLSW (result, jr_INT_MAX + jr_LongLSW (*result) + 1);
}
else {
/* result msw < 0, lsw >= 0 */
if (jr_LongMSW(long2) > 0 && jr_LongMSW(*result) + jr_LongMSW(long2) == 0) {
jr_LongSetLSW( result, -jr_LongLSW(*result));
}
jr_LongSetMSW (result, jr_LongMSW (*result) + jr_LongMSW (long2));
}
}
else {
jr_LongSetMSW (result, jr_LongMSW (*result) + jr_LongMSW (long2));
}
}
else {
if (jr_LongMSW (long2) == 0) {
/* long2: MSW == 0, LSW < 0 */
jr_LongAddInt (result, long1, jr_LongLSW (long2));
}
else {
/* long2: MSW < 0, LSW >= 0 */
jr_LongAddInt (result, long1, -jr_LongLSW (long2));
if (jr_LongLSW (*result) < 0) {
jr_LongSetMSW (result, jr_LongMSW (long2) - 1);
jr_LongSetLSW (result, jr_INT_MAX + jr_LongLSW (*result) + 1);
}
else {
if (jr_LongMSW (*result) < 0) {
jr_LongSetMSW (result, jr_LongMSW (*result) + jr_LongMSW (long2));
}
else {
/* result: MSW >= 0 LSW >= 0 */
/* long2: MSW < 0 */
jr_int msw_diff;
msw_diff = jr_LongMSW (*result) + jr_LongMSW (long2);
if (msw_diff < 0 && jr_LongLSW (*result) > 0) {
jr_LongSetMSW (result, msw_diff + 1);
jr_LongSetLSW (result, - (jr_INT_MAX - jr_LongLSW (*result) + 1));
}
else {
jr_LongSetMSW (result, jr_LongMSW (*result) + jr_LongMSW (long2));
}
}
}
}
}
}
void jr_LongSubtract (result, long1, long2)
jr_Long * result;
jr_Long long1;
jr_Long long2;
{
jr_Long tmp_long;
if (jr_LongMSW (long2) == 0) {
jr_LongSetMSW (&tmp_long, 0);
jr_LongSetLSW (&tmp_long, -jr_LongLSW (long2));
}
else {
jr_LongSetMSW (&tmp_long, -jr_LongMSW (long2));
jr_LongSetLSW (&tmp_long, jr_LongLSW (long2));
}
jr_LongAdd (result, long1, tmp_long);
}
jr_int jr_LongModInt (long1, mod_value)
jr_Long long1;
jr_int mod_value;
{
jr_ULong ulong1;
jr_int result;
if (jr_LongIsPositive (long1)) {
jr_ULongAsgnLong (&ulong1, long1);
}
else {
jr_Long tmp_long;
jr_LongAsgnAbsValue (&tmp_long, long1);
jr_ULongAsgnLong (&ulong1, tmp_long);
}
if (mod_value < 0) {
result = jr_ULongModUInt (ulong1, -mod_value);
}
else {
result = jr_ULongModUInt (ulong1, -mod_value);
}
if (jr_LongIsPositive (long1)) {
return result;
}
return result;
}
void jr_LongAsgnAbsValue (result_ptr, long1)
jr_Long * result_ptr;
jr_Long long1;
{
if (jr_LongIsNegative (long1)) {
if (jr_LongIsInt (long1)) {
jr_LongSetMSW (result_ptr, 0);
jr_LongSetLSW (result_ptr, - jr_LongLSW (long1));
}
else {
jr_LongSetMSW (result_ptr, - jr_LongMSW (long1));
jr_LongSetLSW (result_ptr, jr_LongLSW (long1));
}
}
else {
jr_LongAsgn (result_ptr, long1);
}
#define jr_LongAsgnAbsValue(long1, long2) \
(jr_LongIsNegative(long2) \
? ((long1)->msw = -(long2).msw, (long1)->lsw = -(long2).lsw) \
: ((long1)->msw = (long2).msw, (long1)->lsw = (long2).lsw) \
)
}
void jr_LongDivideInt (result_ptr, long1, div_value)
jr_Long * result_ptr;
jr_Long long1;
jr_int div_value;
{
jr_coredump ();
}
void jr_LongMultInt (result_ptr, long_val, mult_value)
jr_Long * result_ptr;
jr_Long long_val;
jr_int mult_value;
{
jr_coredump ();
}
void jr_LongAsgnIntMult (result_ptr, u, v)
jr_Long * result_ptr;
jr_int u;
jr_int v;
{
}
#endif
char *jr_LongToBase32String (long_value, number_string, use_lower_case)
jr_Long long_value;
char * number_string;
jr_int use_lower_case;
{
jr_ULong ulong_value;
jr_int is_negative;
if (jr_LongIsNegative (long_value)) {
number_string[0] = '-';
is_negative = 1;
jr_LongAsgnAbsValue (&long_value, long_value);
}
else {
is_negative = 0;
}
jr_ULongAsgnLong (&ulong_value, long_value);
return jr_ULongToBase32String (ulong_value, number_string + is_negative, use_lower_case);
}
/*
jr_int jr_LongInitFromBase32String (long_ptr, number_string, error_buf)
jr_Long * long_ptr;
char * number_string;
char * error_buf;
{
jr_ULong ulong_value;
jr_int is_negative;
number_string = jr_FirstNonWhiteSpacePtr (number_string);
if (number_string[0] == '-') {
is_negative = 1;
}
else {
is_negative = 0;
}
status = jr_ULongInitFromBase32String (ulong_value, number_string, error_buf)
if (status != 0) {
return status;
}
jr_LongAsgnULong (long_ptr, ulong_value);
if (is_negative) {
jr_LongMult
}
return 0;
}
*/
|
frankjas/libjr
|
libjr/alist/alistsrt.c
|
<reponame>frankjas/libjr
#include "project.h"
void jr_AListSortRange (list, start_index, num_elements, cmpfn)
jr_AList * list;
jr_int start_index;
jr_int num_elements;
jr_int (*cmpfn) ();
/*
* using a selection sort since the most
* time-consuming operation is the swap
*/
{
register char * currptr;
register char * minptr;
register char * tailptr;
register jr_int objsize = list->objsize;
char * switchptr;
char * tptr ;
jr_int diff;
unsigned jr_int magnitude;
jr_int which_way;
if (start_index + num_elements > jr_AListSize (list)) {
num_elements = jr_AListSize(list) - start_index;
}
if (num_elements <= 1) return ;
tptr = jr_malloc (objsize);
switchptr = jr_AListElementPtr (list, start_index);
tailptr = jr_AListElementPtr (list, start_index + num_elements - 1);
/*
* ignore the prefix stuff when switching
*/
for (; switchptr < tailptr; switchptr += objsize) {
minptr = switchptr;
for (currptr = minptr + objsize; currptr <= tailptr; currptr += objsize) {
diff = (*cmpfn) (currptr + list->prefix_size, minptr + list->prefix_size);
if (diff < 0) {
minptr = currptr;
}
}
if (minptr == switchptr) continue;
memcpy (tptr, switchptr, objsize);
if (jr_AListHasPrefixTransformFn (list)) {
if (tptr > switchptr) {
magnitude = tptr - switchptr;
which_way = 1;
}
else {
magnitude = switchptr - tptr;
which_way = -1;
}
(*jr_AListPrefixTransformFn (list)) (
jr_AListPrefixTransformArg (list),
tptr + list->prefix_size, magnitude, which_way, 0
);
}
memcpy (switchptr, minptr, objsize);
if (jr_AListHasPrefixTransformFn (list)) {
if (switchptr > minptr) {
magnitude = switchptr - minptr;
which_way = 1;
}
else {
magnitude = minptr - switchptr;
which_way = -1;
}
(*jr_AListPrefixTransformFn (list)) (
jr_AListPrefixTransformArg (list),
switchptr + list->prefix_size, magnitude, -which_way, 0
);
}
memcpy (minptr, tptr, objsize);
if (jr_AListHasPrefixTransformFn (list)) {
if (minptr > tptr) {
magnitude = minptr - tptr;
which_way = 1;
}
else {
magnitude = tptr - minptr;
which_way = -1;
}
(*jr_AListPrefixTransformFn (list)) (
jr_AListPrefixTransformArg (list),
minptr + list->prefix_size, magnitude, which_way, 0
);
}
}
jr_free (tptr);
}
void jr_AListSortUniquelyRangeFreeingDeletes (
list, start_index, num_elements, cmpfn, freefunc, freefunc_arg
)
jr_AList * list;
jr_int start_index;
jr_int num_elements;
jr_int (*cmpfn) ();
void (*freefunc) ();
void * freefunc_arg;
{
register char * currptr;
register char * minptr;
register char * tailptr;
register jr_int objsize = list->objsize;
char * switchptr;
char * startptr;
char * tptr;
jr_int diff;
unsigned jr_int magnitude;
jr_int which_way;
if (start_index + num_elements > jr_AListSize (list)) {
num_elements = jr_AListSize(list) - start_index;
}
if (num_elements <= 1) return ;
tptr = jr_malloc (objsize);
switchptr = jr_AListElementPtr (list, start_index);
startptr = switchptr;
tailptr = jr_AListElementPtr (list, start_index + num_elements - 1);
for (; switchptr <= tailptr; switchptr += objsize) {
/* <= since we have to check the tail for
* duplicates, the test minptr == switchptr
* will prevent a copy over itself
*/
minptr = switchptr;
for (currptr = minptr + objsize; currptr <= tailptr; currptr += objsize) {
diff = (*cmpfn) (currptr + list->prefix_size, minptr + list->prefix_size);
if (diff < 0) {
minptr = currptr;
}
}
/* found the minimum element */
if (switchptr != startptr) { /* not the first time through */
/*
* check the min value for duplicates
*/
diff = (*cmpfn) (switchptr - objsize + list->prefix_size, minptr + list->prefix_size);
if (diff == 0) {
/*
* copy tail of un-sorted portion over duplicate entry, then delete the tail
*/
if (freefunc) {
(*freefunc) (minptr + list->prefix_size, freefunc_arg);
}
if (minptr != tailptr) {
memcpy (minptr, tailptr, objsize);
if (jr_AListHasPrefixTransformFn (list)) {
magnitude = tailptr - minptr;
which_way = -1;
(*jr_AListPrefixTransformFn (list)) (
jr_AListPrefixTransformArg (list),
minptr + list->prefix_size, magnitude, which_way, 0
);
}
}
jr_AListDeleteRangeFromPtr (list, tailptr, 1);
tailptr -= objsize; /* adjust tail down */
switchptr -= objsize; /* decrement switch to offset the increment later */
}
}
else {
diff = 1;
}
if (diff != 0 && minptr != switchptr) {
memcpy (tptr, switchptr, objsize);
if (jr_AListHasPrefixTransformFn (list)) {
if (tptr > switchptr) {
magnitude = tptr - switchptr;
which_way = 1;
}
else {
magnitude = switchptr - tptr;
which_way = -1;
}
(*jr_AListPrefixTransformFn (list)) (
jr_AListPrefixTransformArg (list),
tptr + list->prefix_size, magnitude, which_way, 0
);
}
memcpy (switchptr, minptr, objsize);
if (jr_AListHasPrefixTransformFn (list)) {
if (switchptr > minptr) {
magnitude = switchptr - minptr;
which_way = 1;
}
else {
magnitude = minptr - switchptr;
which_way = -1;
}
(*jr_AListPrefixTransformFn (list)) (
jr_AListPrefixTransformArg (list),
switchptr + list->prefix_size, magnitude, -which_way, 0
);
}
memcpy (minptr, tptr, objsize);
if (jr_AListHasPrefixTransformFn (list)) {
if (minptr > tptr) {
magnitude = minptr - tptr;
which_way = 1;
}
else {
magnitude = tptr - minptr;
which_way = -1;
}
(*jr_AListPrefixTransformFn (list)) (
jr_AListPrefixTransformArg (list),
minptr + list->prefix_size, magnitude, which_way, 0
);
}
}
}
jr_free (tptr);
}
|
frankjas/libjr
|
include/jr/linebuf.h
|
<reponame>frankjas/libjr<filename>include/jr/linebuf.h
#ifndef _linebufh
#define _linebufh
#include "ezport.h"
typedef struct {
char * buffer;
char ** prev_buffers;
jr_int * prev_lines;
jr_int max_lines;
jr_int line;
jr_int column;
jr_int max_size;
jr_int tab_stops;
} jr_LB_LineBuffer;
extern void jr_LB_LineBufferInit PROTO ((
jr_LB_LineBuffer * line_buffer,
jr_int max_size,
jr_int max_lines
));
extern void jr_LB_LineBufferUndo PROTO ((
jr_LB_LineBuffer * line_buffer
));
extern void jr_LB_LineBufferReset PROTO ((
jr_LB_LineBuffer * line_buffer,
jr_int line
));
extern void jr_LB_AddString PROTO ((
jr_LB_LineBuffer * line_buffer,
char * str,
jr_int line,
jr_int desired_column
));
extern void jr_LB_AddChar PROTO ((
jr_LB_LineBuffer * line_buffer,
jr_int c
));
extern void jr_LB_SetPreviousLine PROTO ((
jr_LB_LineBuffer * line_buffer,
jr_int line,
char * buffer
));
extern void jr_LB_SetCurrentColumn PROTO ((
jr_LB_LineBuffer * line_buffer,
jr_int column
));
extern void jr_LB_SetCurrentLine PROTO ((
jr_LB_LineBuffer * line_buffer,
jr_int line
));
extern void jr_LB_LineBufferCopy PROTO ((
jr_LB_LineBuffer * dest,
jr_LB_LineBuffer * src
));
extern char * jr_LB_sprint_lines PROTO ((
char * str,
jr_LB_LineBuffer * line_buffer,
jr_int start_line,
jr_int end_line,
char * number_format
));
#define jr_LB_sprint(str, lb, format) \
jr_LB_sprint_lines (str, lb, 0, 0, format)
#define jr_LB_CurrentColumn(lb) ((lb)->column)
#define jr_LB_NumLines(lb) ((lb)->line)
#define jr_LB_TabStops(lb, v) ((lb)->tab_stops)
#define jr_LB_SetTabStops(lb, v) ((lb)->tab_stops = (v))
#endif
|
frankjas/libjr
|
libjr/syscalls/nblk_io.c
|
#define _POSIX_SOURCE 1
#include "ezport.h"
#include <errno.h>
#include <fcntl.h>
#include <string.h>
#include <stdio.h>
#include "jr/io.h"
#include "jr/error.h"
jr_int jr_FileDescInitNonBlockingIO (fd, error_buf)
jr_int fd;
char * error_buf;
{
jr_int flags;
jr_int status;
flags = fcntl (fd, F_GETFL, 0);
if (flags == -1) {
jr_esprintf (error_buf, "couldn't fcntl (%d, F_GETFL): %s",
fd, strerror (errno)
);
return jr_INTERNAL_ERROR;
}
flags |= O_NONBLOCK;
status = fcntl (fd, F_SETFL, flags);
if (status == -1) {
jr_esprintf (error_buf, "couldn't fcntl (%d, F_SETFL, %#x): %s",
fd, flags, strerror (errno)
);
return jr_INTERNAL_ERROR;
}
return 0;
}
jr_int jr_FileDescUndoNonBlockingIO (fd, error_buf)
jr_int fd;
char * error_buf;
{
jr_int flags;
jr_int status;
flags = fcntl (fd, F_GETFL, 0);
if (flags == -1) {
jr_esprintf (error_buf, "couldn't fcntl (%d, F_GETFL): %s",
fd, strerror (errno)
);
return jr_INTERNAL_ERROR;
}
flags &= ~O_NONBLOCK;
status = fcntl (fd, F_SETFL, flags);
if (status == -1) {
jr_esprintf (error_buf, "couldn't fcntl (%d, F_SETFL, %#x): %s",
fd, flags, strerror (errno)
);
return jr_INTERNAL_ERROR;
}
return 0;
}
|
frankjas/libjr
|
libjr/jr_malloc/memstats.c
|
<gh_stars>0
#include "project.h"
jr_int jr_MallocMaxPrintBucketVar = 10;
static unsigned jr_int InitialBucketSizes [MAX_MALLOC_BUCKETS + 1] =
MALLOC_BUCKET_SIZES;
void jr_MallocStatInit (msp)
jr_MallocStatStruct *msp;
{
jr_int b;
memset (msp, 0, sizeof (jr_MallocStatStruct));
msp->did_initialization = 1 ;
for (b=0; b < MAX_MALLOC_BUCKETS; b++) {
msp->s_bucket[b] = InitialBucketSizes [b];
msp->n_malloc[b] = 0 ;
msp->n_freedp[b] = 0 ;
msp->n_maxnum[b] = 0 ;
if (msp->nbuckets == 0 && msp->s_bucket [b] == 0) {
msp->nbuckets = b - 1;
}
}
}
void jr_MallocStatUndo (msp)
jr_MallocStatStruct *msp;
{
}
void jr_MallocStatReset (msp)
jr_MallocStatStruct *msp;
{
jr_MallocStatUndo (msp);
jr_MallocStatInit (msp);
}
void jr_MallocStatRecordMalloc (msp, mptr, amt_allocated)
jr_MallocStatStruct * msp;
void * mptr ;
unsigned jr_int amt_allocated;
{
if (!msp->did_initialization) {
jr_MallocStatInit (msp);
}
/* Record Bucket Statistics */ {
register jr_int b ;
for (b=0; b < MAX_MALLOC_BUCKETS; b++) {
if (b == msp->nbuckets) {
/*
* add a bucket if the size is bigger than
* anything we keep track of
*/
jr_MallocStatBucketSize(msp, b) = amt_allocated ;
msp->nbuckets++ ;
}
if (jr_MallocStatBucketSize(msp, b) >= amt_allocated) {
msp->n_malloc[b]++ ;
if (msp->n_malloc[b] - msp->n_freedp[b] > msp->n_maxnum[b]) {
msp->n_maxnum[b] = msp->n_malloc[b] - msp->n_freedp[b] ;
/*
* reset the maximum number of allocated at any one time
* for this bucket
*/
}
break;
}
}
}
jr_MallocBytesInUse += amt_allocated;
if (jr_MallocBytesInUse > jr_MallocMaxBytesInUse) {
jr_MallocMaxBytesInUse = jr_MallocBytesInUse;
}
}
void jr_MallocStatRecordFree (msp, mptr, amt_allocated)
jr_MallocStatStruct * msp;
const void * mptr ;
unsigned jr_int amt_allocated;
{
if (!msp->did_initialization) {
jr_MallocStatInit (msp);
}
/* Record Bucket Statistics */ {
register jr_int b ;
for (b=0; b < MAX_MALLOC_BUCKETS; b++) {
if (jr_MallocStatBucketSize(msp, b) >= amt_allocated) {
msp->n_freedp[b]++ ;
break;
}
}
}
jr_MallocBytesInUse -= amt_allocated;
}
void jr_MallocSetBucketSizes (s_bucket)
unsigned jr_int *s_bucket;
{
jr_int i;
for (i=0; s_bucket [i]; i++) {
InitialBucketSizes [i] = s_bucket [i];
}
}
void jr_MallocStatAddBucketSize (msp, bucket_size)
jr_MallocStatStruct * msp;
size_t bucket_size ;
{
register jr_int b ;
jr_int position ;
if (!msp->did_initialization) {
jr_MallocStatInit (msp);
}
if (msp->nbuckets == MAX_MALLOC_BUCKETS) return;
for (b=0; b < MAX_MALLOC_BUCKETS; b++) {
if (b == msp->nbuckets) break ;
if (jr_MallocStatBucketSize(msp, b) >= bucket_size) break ;
}
if (jr_MallocStatBucketSize(msp, b) == bucket_size) return;
position = b ;
for (b = msp->nbuckets; b > position; b--) {
msp->s_bucket[b] = msp->s_bucket[b-1] ;
msp->n_malloc[b] = msp->n_malloc[b-1] ;
msp->n_freedp[b] = msp->n_freedp[b-1] ;
msp->n_maxnum[b] = msp->n_maxnum[b-1] ;
}
msp->nbuckets++ ;
msp->s_bucket[position] = bucket_size ;
msp->n_malloc[position] = 0 ;
msp->n_freedp[position] = 0 ;
msp->n_maxnum[position] = 0 ;
}
void jr_MallocStatPrint(wfp, msp, message)
FILE * wfp ;
jr_MallocStatStruct * msp;
char * message;
{
register jr_int b;
size_t size ;
size_t total_bytes_free;
size_t total_bytes_used;
size_t max_bytes_used ;
jr_int num_ptrs_still_allocated;
jr_int needblank ;
fprintf(wfp," %s\n",message) ;
if (!msp->did_initialization) {
jr_MallocStatInit (msp);
}
needblank = 1 ;
fprintf(wfp," size:");
for (b = 0; b < jr_MallocMaxPrintBucketVar ; b++) {
size = jr_MallocStatBucketSize (msp, b);
if (size >= 1024) {
if (needblank) {
putc(' ',wfp) ;
needblank = 0 ;
}
fprintf (wfp, " %3dK", (jr_int) size / 1024);
}
else fprintf(wfp, " %4d", (jr_int) size);
}
if (needblank) fprintf(wfp," ") ;
fprintf(wfp," | totals \n") ;
fprintf(wfp, "----------");
for (b = 0; b < MAX_MALLOC_BUCKETS; b++) {
if (b < jr_MallocMaxPrintBucketVar) fprintf(wfp, "-----") ;
}
fprintf(wfp,"--|-----------\n") ;
max_bytes_used = 0 ;
total_bytes_used = 0 ;
num_ptrs_still_allocated = 0;
fprintf(wfp, "max. used:");
for (b = 0; b < MAX_MALLOC_BUCKETS; b++) {
if (b < jr_MallocMaxPrintBucketVar) fprintf(wfp, " %4d", msp->n_maxnum[b]);
max_bytes_used += msp->n_maxnum[b] * jr_MallocStatBucketSize (msp, b);
total_bytes_used += msp->n_malloc[b] * jr_MallocStatBucketSize (msp, b);
}
if (max_bytes_used >= 1024) {
fprintf (wfp, " | %4dK+%4d\n", (jr_int) max_bytes_used / 1024, (jr_int) max_bytes_used % 1024);
}
else {
fprintf(wfp, " | %4d \n", (jr_int) max_bytes_used);
}
total_bytes_free = 0 ;
fprintf(wfp,"tot. call:") ;
for (b = 0; b < MAX_MALLOC_BUCKETS; b++) {
if (b < jr_MallocMaxPrintBucketVar) {
fprintf(wfp, " %4d", msp->n_freedp[b]);
}
total_bytes_free += msp->n_freedp[b] * jr_MallocStatBucketSize (msp, b);
}
if (total_bytes_free >= 1024) {
fprintf (wfp, " | %4dK+%4d\n", (jr_int) total_bytes_free / 1024, (jr_int) total_bytes_free % 1024);
}
else {
fprintf(wfp, " | %4d \n", (jr_int) total_bytes_free);
}
fprintf(wfp, "----------");
for (b = 0; b < MAX_MALLOC_BUCKETS; b++) {
if (b < jr_MallocMaxPrintBucketVar) {
fprintf(wfp, "-----") ;
}
}
fprintf(wfp,"--|-----------\n") ;
fprintf(wfp,"cur. used:") ;
for (b = 0; b < MAX_MALLOC_BUCKETS; b++) {
if (b < jr_MallocMaxPrintBucketVar) {
fprintf(wfp, " %4d", msp->n_malloc[b] - msp->n_freedp[b]) ;
}
num_ptrs_still_allocated += msp->n_malloc[b] - msp->n_freedp[b];
}
total_bytes_used -= total_bytes_free ;
if (total_bytes_used >= 1024) {
fprintf (wfp, " | %4dK+%4d\n", (jr_int) total_bytes_used / 1024, (jr_int) total_bytes_used % 1024);
}
else {
fprintf(wfp, " | %4d \n", (jr_int) total_bytes_used);
}
fprintf (wfp,"\n%d pointers still allocated\n", num_ptrs_still_allocated);
if (jr_do_trace(jr_malloc_calls) || jr_do_trace(jr_malloc_trap)) {
fprintf(wfp,"\t(expect ~3 jr_malloc_calls book-keeping pointers)\n") ;
}
}
jr_int jr_MallocStatNumAllocated (msp)
jr_MallocStatStruct * msp;
{
jr_int num_ptrs_still_allocated = 0;
jr_int b;
if (!msp->did_initialization) {
jr_MallocStatInit (msp);
}
for (b = 0; b < MAX_MALLOC_BUCKETS; b++) {
num_ptrs_still_allocated += msp->n_malloc[b] - msp->n_freedp[b];
}
return num_ptrs_still_allocated;
}
|
frankjas/libjr
|
include/jr/poll.h
|
#ifndef __jr_poll_h___
#define __jr_poll_h___
#include "ezport.h"
#include "jr/htable.h"
#include "jr/dlist.h"
#include "jr/time.h"
#include "jr/apr.h"
/*
** 2/22/07: Separate from jr/apr.h due to the additional data structures.
*/
/******** Polled I/O ********/
typedef struct jr_poll {
void * apr_pollset_ptr;
void * apr_pool_ptr;
jr_int num_descriptors;
jr_int max_descriptors;
jr_DList event_list[1];
jr_HTable event_table[1];
jr_AList result_list[1];
unsigned can_wakeup : 1;
} jr_poll_t;
#define jr_POLL_READ 0x0001
#define jr_POLL_WRITE 0x0002
#define jr_POLL_HUP 0x0004
#define jr_POLL_CLOSE 0x0008
#define jr_POLL_IS_SOCKET 0x0100
#define jr_POLL_IS_FILE 0x0200
#define jr_POLL_IS_MASK 0x0f00
typedef jr_int (*jr_poll_handler_fn_t) (
void * data_ptr,
jr_poll_t * poll_ptr,
void * generic_io_ptr,
jr_int io_style_ready,
char * error_buf
);
typedef struct jr_pollevent {
void * generic_io_ptr;
jr_int poll_flags;
jr_int io_style_ready;
jr_int (*opt_handler_fn) (
void * data_ptr,
jr_poll_t * poll_ptr,
void * generic_io_ptr,
jr_int io_style_ready,
char * error_buf
);
void * opt_handler_data_ptr;
} jr_pollevent_t;
extern void jr_poll_init (
jr_poll_t * poll_ptr);
extern void jr_poll_undo (
jr_poll_t * poll_ptr);
extern jr_int jr_poll_wait (
jr_poll_t * poll_ptr,
jr_useconds_t * opt_interval_ptr,
char * error_buf);
extern void jr_poll_wakeup (
jr_poll_t * poll_ptr);
extern jr_int jr_poll_add_socket (
jr_poll_t * poll_ptr,
jr_socket_t * socket_ptr,
jr_int poll_flags,
jr_int (*opt_handler_fn) (
void * data_ptr,
jr_poll_t * poll_ptr,
jr_socket_t * socket_ptr,
jr_int is_style_ready,
char * error_buf
),
void * opt_handler_data_ptr,
char * error_buf);
extern jr_int jr_poll_add_file (
jr_poll_t * poll_ptr,
jr_file_t * file_ptr,
jr_int poll_flags,
jr_int (*opt_handler_fn) (
void * data_ptr,
jr_poll_t * poll_ptr,
jr_file_t * file_ptr,
jr_int is_style_ready,
char * error_buf
),
void * opt_handler_data_ptr,
char * error_buf);
extern void jr_poll_delete_socket (
jr_poll_t * poll_ptr,
jr_socket_t * socket_ptr);
extern void jr_poll_delete_file (
jr_poll_t * poll_ptr,
jr_file_t * file_ptr);
#define jr_poll_set_can_wakeup( poll_ptr, v) \
((poll_ptr)->can_wakeup = (v) != 0)
#define jr_poll_can_wakeup( poll_ptr) \
((poll_ptr)->can_wakeup)
#define jr_poll_foreach_event_ptr(poll_ptr, event_ptr) \
jr_AListForEachElementPtr ((poll_ptr)->result_list, event_ptr)
#define jr_poll_num_events( poll_ptr) \
jr_AListSize( (poll_ptr)->result_list)
#define jr_poll_get_event_ptr( poll_ptr, index) \
jr_AListElementPtr( (poll_ptr)->result_list, index)
extern jr_int jr_poll_call_handler (
jr_poll_t * poll_ptr,
jr_pollevent_t * event_ptr,
char * error_buf);
extern jr_int jr_poll_increase_capacity (
jr_poll_t * poll_ptr,
jr_int new_size,
char * error_buf);
#define jr_pollevent_socket_ptr( event_ptr) \
((jr_socket_t *) (event_ptr)->generic_io_ptr)
#define jr_pollevent_file_ptr( event_ptr) \
((jr_file_t *) (event_ptr)->generic_io_ptr)
#define jr_pollevent_handler_fn( event_ptr) \
((event_ptr)->opt_handler_fn)
#define jr_pollevent_handler_data_ptr( event_ptr) \
((event_ptr)->opt_handler_data_ptr)
#endif
|
frankjas/libjr
|
libjr/avl_tree/avl_indx.c
|
#include "project.h"
void *jr_AVL_TreeFindElementPtrUsingIndex (avl_tree, index_value)
jr_AVL_Tree * avl_tree;
jr_int index_value;
{
void * curr_node;
jr_int curr_index;
void * left_child;
jr_int left_tree_size;
assert (jr_AVL_TreeMaintainsSize (avl_tree));
curr_node = avl_tree->root_node;
curr_index = 0;
while (curr_node) {
left_child = jr_AVL_TreeLeftChildPtr (avl_tree, curr_node);
if (left_child) {
left_tree_size = jr_AVL_TreeSubTreeSize (avl_tree, left_child);
}
else {
left_tree_size = 0;
}
if (index_value == curr_index + left_tree_size) {
return curr_node;
}
if (index_value < curr_index + left_tree_size) {
curr_node = left_child;
}
else {
curr_node = jr_AVL_TreeRightChildPtr (avl_tree, curr_node);
curr_index += left_tree_size + 1;
}
}
/*
* Bigger than anything in the tree. Could have checked the root node
* above for this.
*/
return 0;
}
void jr_AVL_TreeInsertElementUsingIndex (avl_tree, new_node, index_value)
jr_AVL_Tree * avl_tree;
const void * new_node;
jr_int index_value;
{
void * path[jr_AVL_TREE_MAX_HEIGHT];
jr_int path_index;
void * curr_node;
jr_int curr_index;
void * left_child;
jr_int left_tree_size;
assert (jr_AVL_TreeMaintainsSize (avl_tree));
assert (index_value <= jr_AVL_TreeSize (avl_tree));
/*
* Same as find() above, but keeps track of the path.
*/
curr_node = avl_tree->root_node;
curr_index = 0;
path_index = 0;
while (curr_node) {
path[path_index] = curr_node;
path_index++;
left_child = jr_AVL_TreeLeftChildPtr (avl_tree, curr_node);
if (left_child) {
left_tree_size = jr_AVL_TreeSubTreeSize (avl_tree, left_child);
}
else {
left_tree_size = 0;
}
if (index_value == curr_index + left_tree_size) {
break;
}
if (index_value < curr_index + left_tree_size) {
curr_node = left_child;
}
else {
curr_node = jr_AVL_TreeRightChildPtr (avl_tree, curr_node);
curr_index += left_tree_size + 1;
}
}
if (curr_node) {
curr_node = jr_AVL_TreeLeftChildPtr (avl_tree, curr_node);
if (curr_node) {
for (; curr_node; curr_node = jr_AVL_TreeRightChildPtr (avl_tree, curr_node)) {
path [path_index] = curr_node;
path_index ++;
}
jr_AVL_TreeAppendToPath (avl_tree, path, path_index, 0, new_node);
}
else {
jr_AVL_TreeAppendToPath (avl_tree, path, path_index, 1, new_node);
}
}
else {
jr_AVL_TreeAppendToPath (avl_tree, path, path_index, 0, new_node);
}
}
void *jr_AVL_TreeExtractElementUsingIndex (avl_tree, index_value)
jr_AVL_Tree * avl_tree;
jr_int index_value;
{
void * path[jr_AVL_TREE_MAX_HEIGHT];
jr_int path_index;
void * curr_node;
jr_int curr_index;
void * left_child;
jr_int left_tree_size;
assert (jr_AVL_TreeMaintainsSize (avl_tree));
assert (index_value < jr_AVL_TreeSize (avl_tree));
/*
* Same as find() above, but keeps track of the path.
*/
curr_node = avl_tree->root_node;
curr_index = 0;
path_index = 0;
while (curr_node) {
path[path_index] = curr_node;
path_index++;
left_child = jr_AVL_TreeLeftChildPtr (avl_tree, curr_node);
if (left_child) {
left_tree_size = jr_AVL_TreeSubTreeSize (avl_tree, left_child);
}
else {
left_tree_size = 0;
}
if (index_value == curr_index + left_tree_size) {
break;
}
if (index_value < curr_index + left_tree_size) {
curr_node = left_child;
}
else {
curr_node = jr_AVL_TreeRightChildPtr (avl_tree, curr_node);
curr_index += left_tree_size + 1;
}
}
curr_node = jr_AVL_TreeExtractPathEnd (avl_tree, path, path_index);
return curr_node;
}
void jr_AVL_TreeAppendLastIndexedElement (avl_tree, new_node)
jr_AVL_Tree * avl_tree;
const void * new_node;
{
void * path[jr_AVL_TREE_MAX_HEIGHT];
jr_int path_index;
void * curr_node;
curr_node = avl_tree->root_node;
for (path_index=0; curr_node; path_index++) {
path[path_index] = curr_node;
curr_node = jr_AVL_TreeRightChildPtr (avl_tree, curr_node);
}
jr_AVL_TreeAppendToPath (avl_tree, path, path_index, 0, new_node);
}
jr_int jr_AVL_TreeIndexedCmp (void_ptr1, void_ptr2)
const void * void_ptr1;
const void * void_ptr2;
{
const jr_int * int_ptr1 = void_ptr1;
const jr_int * int_ptr2 = void_ptr2;
return *int_ptr1 - *int_ptr2;
}
void jr_AVL_TreeSetMaintainsSize (avl_tree, value)
jr_AVL_Tree * avl_tree;
jr_int value;
{
if ( avl_tree->allocates_elements
&& avl_tree->maintains_size != (unsigned) (value != 0)) {
fprintf (stderr, "\n\njr_AVL_TreeSetMaintainsSize(): called on non-empty tree\n");
jr_coredump ();
}
avl_tree->maintains_size = value != 0;
}
void *jr_AVL_TreeSetNewIndexedElementWithSize (avl_tree, index, new_element, length)
jr_AVL_Tree * avl_tree;
jr_int index;
const void * new_element;
jr_int length ;
{
void * new_node;
new_node = jr_AVL_TreeNewIndexedElementPtrWithSize (avl_tree, index, length);
if (new_node) {
memcpy (new_node, new_element, length);
}
return new_node;
}
void *jr_AVL_TreeNewIndexedElementPtrWithSize (avl_tree, index, length)
jr_AVL_Tree * avl_tree;
jr_int index;
jr_int length ;
{
void * new_node;
new_node = jr_AVL_TreeAllocateElementWithSize (avl_tree, length);
jr_AVL_TreeInsertElementUsingIndex (avl_tree, new_node, index);
return new_node;
}
void *jr_AVL_TreeSetNewLastIndexedElementWithSize (avl_tree, new_element, length)
jr_AVL_Tree * avl_tree;
const void * new_element;
jr_int length ;
{
void * new_node;
new_node = jr_AVL_TreeNewLastIndexedElementPtrWithSize (avl_tree, length);
if (new_node) {
memcpy (new_node, new_element, length);
}
return new_node;
}
void *jr_AVL_TreeNewLastIndexedElementPtrWithSize (avl_tree, length)
jr_AVL_Tree * avl_tree;
jr_int length ;
{
void * new_node;
new_node = jr_AVL_TreeAllocateElementWithSize (avl_tree, length);
jr_AVL_TreeAppendLastIndexedElement (avl_tree, new_node);
return new_node;
}
jr_int jr_AVL_TreeDeleteIndexedElement (avl_tree, index)
jr_AVL_Tree * avl_tree;
jr_int index;
{
void * deleted_node;
deleted_node = jr_AVL_TreeExtractElementUsingIndex (avl_tree, index);
if (deleted_node == 0) {
return -1;
}
if (jr_AVL_TreeAllocatesElements (avl_tree)) {
jr_AVL_TreeFreeElement (avl_tree, deleted_node);
}
return 0;
}
jr_int jr_AVL_TreeCalculateElementIndex (avl_tree, existing_node)
jr_AVL_Tree * avl_tree;
const void * existing_node;
{
const void * curr_node;
jr_int curr_index;
jr_AVL_TreeForEachElementIndex (avl_tree, curr_index) {
curr_node = jr_AVL_TreeFindIndexedElementPtr (avl_tree, curr_index);
if (existing_node == curr_node) {
return curr_index;
}
}
return -1;
}
|
frankjas/libjr
|
libjr/syscalls/jr_tty.c
|
#include "ezport.h"
#include <unistd.h>
#include <stdio.h>
jr_int jr_IsInteractiveFilePtr (
FILE * fp,
char * error_buf)
{
return isatty (fileno (fp));
}
|
frankjas/libjr
|
include/jr/llist.h
|
<reponame>frankjas/libjr<gh_stars>0
#ifndef _llisth
#define _llisth
#include "ezport.h"
#include <string.h>
#include <stdarg.h>
typedef struct {
void * tail;
void * head;
jr_int objsize;
jr_int prefix_size;
unsigned allocates_elements : 1;
} jr_LList;
extern jr_LList * jr_LListCreate PROTO ((jr_int objsize));
extern void jr_LListDestroy PROTO ((jr_LList *list));
extern void jr_LListInit PROTO ((jr_LList *list, jr_int objsize));
extern void jr_LListUndo PROTO ((jr_LList *list));
extern void jr_LListEmpty PROTO ((jr_LList *list));
extern void * jr_LListAppendElement PROTO ((jr_LList *list, void *next_el, void *new_el));
extern void * jr_LListExtractNextElement PROTO ((jr_LList *list, void *curr));
extern void jr_LListDeleteNextElement PROTO ((jr_LList *list, void *curr));
extern void jr_LListMakeNullElement PROTO ((jr_LList *dlist, void *el));
extern jr_int jr_LListElementPrefixSize PROTO ((jr_LList *list));
extern void jr_LListSetPrefixSize PROTO ((jr_LList *list, jr_int prefix_size));
extern void jr_LListTransformPrefix PROTO ((
jr_LList * list,
void * el_ptr,
unsigned jr_int magnitude,
jr_int which_way,
jr_int all_elements
));
extern void jr_LListSetContainers PROTO ((jr_LList *list, ...));
extern void jr_LListSetContainersFromVA_List PROTO ((
jr_LList * list,
va_list arg_list
));
/***** List Query Operations *****/
#define jr_LListHeadPtr(list) ((list)->head)
#define jr_LListTailPtr(list) ((list)->tail)
#define jr_LListIsEmpty(list) ((list)->tail == 0)
#define jr_LListElementSize(list) ((list)->objsize)
#define jr_LListPrefixSize(list) ((list)->prefix_size)
#define jr_LListAllocatesElements(list) ((list)->allocates_elements)
#define jr_LListSetAllocatesElements(list, v) ((list)->allocates_elements = (v))
#define jr_LListHasMultipleElements(list) \
(!jr_LListIsEmpty (list) && jr_LListHeadPtr (list) != jr_LListTailPtr (list))
/***** Element Allocation *****/
extern void * jr_LListAllocateElementWithSize PROTO ((jr_LList *list, jr_int size));
extern void * jr_NewLListElementWithPrefix PROTO ((
jr_int element_size,
jr_int prefix_size
));
#define jr_FreeLListElementWithPrefix(objptr, prefix_size) \
jr_free ((char *) (objptr) - (prefix_size) - sizeof (void *))
#define jr_NextLListElementPtrWithPrefix(objptr, prefix_size) \
(((void **) ((char *) (objptr) - (prefix_size)))[-1])
/***** Looping Constructs *****/
#define jr_LListForEachElementPtrWithPrefix(list, current, prefix_size) \
for ((current) = jr_LListHeadPtr (list); \
(current) != 0; \
(current) = jr_NextLListElementPtrWithPrefix(current, prefix_size) \
)
#if defined(__cplusplus)
# undef jr_LListForEachElementPtrWithPrefix
# define jr_LListForEachElementPtrWithPrefix(list, current, prefix_size) \
for ( (*(void **)&(current)) = jr_LListHeadPtr (list); \
(current) != 0 ; \
(*(void **)&(current)) = jr_NextLListElementPtrWithPrefix (current, prefix_size)\
)
#endif
/***** Convenience Functions *****/
#define jr_LListAllocateElement(list) \
jr_LListAllocateElementWithSize (list, jr_LListElementSize (list))
#define jr_LListFreeElement(list, objptr) \
jr_FreeLListElementWithPrefix (objptr, (list)->prefix_size);
#define jr_NewLListElement(el_size) \
jr_NewLListElementWithPrefix (el_size, 0)
#define jr_FreeLListElement(objptr) \
jr_FreeLListElementWithPrefix (objptr, 0)
#define jr_NextLListElementPtr(objptr) \
jr_NextLListElementPtrWithPrefix (objptr, 0)
#define jr_LListNewNextElementPtrWithSize(list, prev, size) \
jr_LListAppendElement (list, prev, jr_LListAllocateElementWithSize (list, size))
#define jr_LListNewHeadPtrWithSize(list, size) \
jr_LListNewNextElementPtrWithSize (list, 0, size)
#define jr_LListNewTailPtrWithSize(list, size) \
jr_LListNewNextElementPtrWithSize (list, jr_LListTailPtr (list), size)
#define jr_LListNewNextElementPtr(list, prev) \
jr_LListNewNextElementPtrWithSize(list, prev, jr_LListElementSize (list))
#define jr_LListNewHeadPtr(list) \
jr_LListNewHeadPtrWithSize(list, jr_LListElementSize (list))
#define jr_LListNewTailPtr(list) \
jr_LListNewTailPtrWithSize(list, jr_LListElementSize (list))
#define jr_LListInsertToHead(list, prev) \
jr_LListAppendElement (list, 0, prev)
#define jr_LListAppendToTail(list, next) \
jr_LListAppendElement (list, jr_LListTailPtr (list), next)
#define jr_LListSetNewHeadWithSize(list, obj, size) \
memcpy ( \
jr_LListNewHeadPtrWithSize(list, size), obj, size \
)
#define jr_LListSetNewTailWithSize(list, obj, size) \
memcpy ( \
jr_LListNewTailPtrWithSize(list, size), obj, size \
)
#define jr_LListSetNewNextElementWithSize(list, el, obj, size) \
memcpy ( \
jr_LListNewNextElementPtrWithSize (list, el, size), obj, size \
)
#define jr_LListSetNewHead(list, obj) \
jr_LListSetNewHeadWithSize (list, obj, jr_LListElementSize (list))
#define jr_LListSetNewTail(list, obj) \
jr_LListSetNewTailWithSize (list, obj, jr_LListElementSize (list))
#define jr_LListSetNewNextElement(list, el, obj) \
jr_LListSetNewNextElementWithSize (list, el, obj, jr_LListElementSize (list))
#define jr_LListGetTail(list, elptr) \
memcpy (elptr, jr_LListTailPtr(list), (list)->element_size)
#define jr_LListGetHead(list, elptr) \
memcpy (elptr, jr_LListHeadPtr(list), (list)->element_size)
#define jr_LListDeleteHead(list) \
jr_LListDeleteNextElement (list, 0)
extern jr_LList * jr_LListCopy PROTO ((
jr_LList * dest,
jr_LList * src
));
#define jr_LListDup(src) \
jr_LListCopy (jr_LListCreate (jr_LListElementSize (src)), src)
extern void * jr_LListFindElementPtr PROTO ((
jr_LList * list,
void * obj,
jr_int (*cmpfn)()
));
extern jr_int jr_LListCmp PROTO ((
jr_LList * list1,
jr_LList * list2,
jr_int (*cmpfn)()
));
extern jr_int jr_LListHash PROTO ((jr_LList *list, jr_int (*hashfn)()));
extern void * jr_LListFindAppendPtr PROTO ((
jr_LList * list,
void * obj,
jr_int (*cmpfn) ()
));
extern void * jr_LListNewElementPtrInOrderWithSizeAndUniqueFlag PROTO ((
jr_LList * list,
void * obj,
jr_int (* cmpfn)(),
jr_int size,
jr_int unique
));
#define jr_LListNewElementPtrInOrder(list, obj, cmpfn) \
jr_LListNewElementPtrInOrderWithSizeAndUniqueFlag ( \
list, obj, cmpfn, jr_LListElementSize (list), 0 \
)
#define jr_LListNewElementPtrInOrderWithSize(list, obj, cmpfn, size) \
jr_LListNewElementPtrInOrderWithSizeAndUniqueFlag (list, obj, cmpfn, size, 0)
#define jr_LListNewElementPtrUniquely(list, obj, cmpfn) \
jr_LListNewElementPtrInOrderWithSizeAndUniqueFlag ( \
list, obj, cmpfn, jr_LListElementSize (list), 1 \
)
extern void * jr_LListSetNewElementUniquely PROTO ((
jr_LList * list,
void * obj,
jr_int (*cmpfn) ()
));
#define jr_LListNewElementPtrUniquelyWithSize(list, obj, cmpfn, size) \
jr_LListNewElementPtrInOrderWithSizeAndUniqueFlag (list, obj, cmpfn, size, 1)
#define jr_LListSetNewElementInOrder(list, obj, cmpfn) \
memcpy ( \
jr_LListNewElementPtrInOrder (list, obj, cmpfn), obj, \
jr_LListElementSize (list) \
)
extern void jr_LListMergeWithUniqueFlag PROTO ((
jr_LList *list1, jr_LList *list2, jr_int (*cmpfn)(), jr_int unique
));
#define jr_LListMerge(l1, l2, cmpfn) \
jr_LListMergeWithUniqueFlag (l1, l2, cmpfn, 0)
#define jr_LListMergeUniquely(l1, l2, cmpfn) \
jr_LListMergeWithUniqueFlag (l1, l2, cmpfn, 1)
/***** Native List Macros *****/
#define jr_LListNativeSetNewTail(list, v, type) \
(* (type *) jr_LListNewTailPtr(list) = v)
#define jr_LListNativeSetNewHead(list, v, type) \
(* (type *) jr_LListNewHeadPtr(list) = v)
#define jr_LListNativeTail(list, type) (* (type *) jr_LListTailPtr (list))
#define jr_LListNativeHead(list, type) (* (type *) jr_LListHeadPtr (list))
#define jr_LListNextElementPtr(list, objptr) \
jr_NextLListElementPtrWithPrefix (objptr, jr_LListPrefixSize (list))
#define jr_LListForEachElementPtr(list, current) \
jr_LListForEachElementPtrWithPrefix (list, current, jr_LListPrefixSize (list))
#endif
/*
.EXIT
Out of Date - preserved for historical reasons.
This library provides several general list manipulation functions.
The object is copied into the list, the objects must be referenced
through pointers.
LinkedListInit (objectsize, fn) : takes size of the object to be stored
in the list and the object comparison function and returns
a pointer to a list.
AddToTail (list, obj) : Creates new element at the tail and copies
object into it.
AddToHead (list, obj) : Creates new element at the head and copies
object into it.
AddToSort (list, obj) : Creates new element and inserts in sorted
(lower to higher) order according to the list cmp function.
SortLinkedList (list) : sorts the list.
IsInLinkedList (list, obj) : 0 if object not in list, returns object
of element found.
DeleteObj (list, obj) : If object is in the list, deletes it.
EmptyLinkedList (list) : frees up all the elements of the list.
FreeLinkedList (list) : frees up the elements and the list.
HeadOf(list) : (define) returns ptr to object of head of list.
TailOf(list) : (define) returns ptr to object of tail of list.
ObjectOf(elementptr) : (define) returns object of elementptr.
IsLinkedListEmpty(list) : (define) true if list is empty.
ForEachLinkedListElement(list, elptr) : (define) is a standard for-loop.
*/
|
frankjas/libjr
|
libjr/syscalls/pathrel.c
|
<gh_stars>0
#define _POSIX_SOURCE 1
#include "ezport.h"
#include <string.h>
#include <stdlib.h>
#include <alloca.h>
#include "jr/syscalls.h"
#include "jr/string.h"
void jr_FileNameToRelativePath(target_path_buf, buflen, source_path_arg, relative_to_here_arg)
char * target_path_buf ;
jr_int buflen ;
const char * source_path_arg ;
const char * relative_to_here_arg ;
{
char * source_abspath = alloca(buflen) ;
char * relative_to_here = alloca(buflen) ;
jr_int skip_length ;
/* expand and adjust the two path arguments to be complete path names */ {
char * expanded_source_path = alloca(buflen*2) ;
char * expanded_relative_to_here = alloca(buflen*2) ;
jr_PathStringCopyWithDollarAndTildeExpansion(expanded_source_path, source_path_arg) ;
jr_PathStringCopyWithDollarAndTildeExpansion(expanded_relative_to_here,relative_to_here_arg) ;
jr_FileNameToAbsolutePath(source_abspath, buflen-2, expanded_source_path) ;
jr_FileNameToAbsolutePath(relative_to_here, buflen-2, expanded_relative_to_here) ;
}
strcat(relative_to_here, "/") ;
jr_RemoveContiguousDuplicateChar(relative_to_here, '/') ;
jr_RemoveContiguousDuplicateChar(source_abspath, '/') ;
skip_length = strlen(relative_to_here) ;
if (strncmp(source_abspath, relative_to_here, skip_length) == 0) {
/*
* if the leading section of the source path contains the relative_to_here path
* then we want to skip over the relative to here path and just get
* the trailing relative path then.
*/
strncpy(target_path_buf, source_abspath + skip_length, buflen-1) ;
target_path_buf[buflen-1] = 0 ;
}
else {
/*
* If the source path does not start with the relative_to_here path
* then the source and relative_to arguments were not even
* part of the same directory hierarchy and so we can't
* really adjust anything, in this case the abspath is put
* into the result.
*/
strncpy(target_path_buf, source_abspath, buflen-1) ;
target_path_buf[buflen-1] = 0 ;
}
}
|
frankjas/libjr
|
libjr/htable/htablsts.c
|
#include "project.h"
void jr_HTableHashDist (htable, wfp, heading_string)
jr_HTable * htable;
FILE * wfp;
char * heading_string;
{
jr_int * hashdist;
jr_int allzeros;
jr_int bucket;
jr_int curr_index;
jr_int num_elements;
jr_int i;
hashdist = (jr_int *) jr_malloc (htable->num_buckets * sizeof(jr_int));
for (bucket=0; bucket < htable->num_buckets; bucket++) {
curr_index = htable->buckets_array[bucket];
for (num_elements = 0; curr_index != -1; num_elements++) {
curr_index = jr_HTableNextElementIndex (htable, curr_index);
}
hashdist[bucket] = num_elements;
}
/*
* print 50 elements on a line
*/
for (bucket=0; bucket < htable->num_buckets; bucket += 50) {
fprintf (wfp, " __________________%s______________________\n", heading_string);
fprintf (wfp, "%3d >0123456789-123456789-123456789-123456789-123456789< %3d\n",
bucket, bucket+49
);
allzeros = 0;
/* print out a histogram sideways
* keep printing lines until one line has no stars on it
*/
while (!allzeros) {
fprintf (wfp, " ");
for (i=0, allzeros = 1; i < 50; i++) {
if (bucket+i < htable->num_buckets && hashdist[bucket+i] > 0) {
allzeros = 0;
putc('*', wfp);
hashdist[bucket+i]--;
}
else putc(' ', wfp);
}
putc('\n', wfp);
}
}
jr_free (hashdist);
}
|
frankjas/libjr
|
libjr/missing/siglist.c
|
<filename>libjr/missing/siglist.c
#define _POSIX_SOURCE 1
#include "ezport.h"
#ifdef missing_sys_siglist_objects
#include <signal.h>
#ifdef ostype_winnt
/*
** 1/27/07: don't make these globally available, since
** other code may have ifdefs based on the existence
** of these signals (coredump(), for example)
*/
#define SIGHUP (64 + 0)
#define SIGQUIT (64 + 1)
#define SIGTRAP (64 + 2)
#define SIGIOT (64 + 3)
#define SIGBUS (64 + 4)
#define SIGKILL (64 + 5)
#define SIGUSR1 (64 + 6)
#define SIGUSR2 (64 + 7)
#define SIGPIPE (64 + 8)
#define SIGALRM (64 + 9)
#define SIGCHLD (64 + 10)
#define SIGCONT (64 + 11)
#define SIGSTOP (64 + 12)
#define SIGTSTP (64 + 13)
#define SIGTTIN (64 + 14)
#define SIGTTOU (64 + 15)
#define SIGURG (64 + 16)
#define SIGXCPU (64 + 17)
#define SIGXFSZ (64 + 18)
#define SIGVTALRM (64 + 19)
#define SIGPROF (64 + 20)
#define SIGWINCH (64 + 21)
#define SIGIO (64 + 22)
#define SIGPWR (64 + 23)
#define SIGSYS (64 + 24)
#endif
char * sys_siglist[128]; /* 1/27/07: Need 128 for fake Microsoft signals */
void jr_sys_siglist_init ()
{
sys_siglist [SIGHUP] = "Hangup"; /*(POSIX). */
sys_siglist [SIGINT] = "Interrupt"; /*(ANSI). */
sys_siglist [SIGQUIT] = "Quit"; /*(POSIX). */
sys_siglist [SIGILL] = "Illegal instruction"; /*(ANSI). */
sys_siglist [SIGTRAP] = "Trace trap"; /*(POSIX). */
sys_siglist [SIGABRT] = "Abort"; /*(ANSI). */
sys_siglist [SIGIOT] = "IOT trap"; /*(4.2 BSD). */
sys_siglist [SIGBUS] = "BUS error"; /*(4.2 BSD). */
sys_siglist [SIGFPE] = "Floating-point exception"; /*(ANSI). */
sys_siglist [SIGKILL] = "Kill"; /*(POSIX). */
sys_siglist [SIGSEGV] = "Segmentation violation"; /*(ANSI). */
sys_siglist [SIGUSR1] = "User-defined signal 1"; /*(POSIX). */
sys_siglist [SIGUSR2] = "User-defined signal 2"; /*(POSIX). */
sys_siglist [SIGPIPE] = "Broken pipe"; /*(POSIX). */
sys_siglist [SIGALRM] = "Alarm clock"; /*(POSIX). */
sys_siglist [SIGTERM] = "Termination"; /*(ANSI). */
sys_siglist [SIGCHLD] = "Child status has changed"; /*(POSIX). */
sys_siglist [SIGCONT] = "Continue"; /*(POSIX). */
sys_siglist [SIGSTOP] = "Stop"; /*(POSIX). */
sys_siglist [SIGTSTP] = "Keyboard stop"; /*(POSIX). */
sys_siglist [SIGTTIN] = "Background read from tty"; /*(POSIX). */
sys_siglist [SIGTTOU] = "Background write to tty"; /*(POSIX). */
sys_siglist [SIGURG] = "Urgent condition on socket"; /*(4.2 BSD). */
sys_siglist [SIGXCPU] = "CPU limit exceeded"; /*(4.2 BSD). */
sys_siglist [SIGXFSZ] = "File size limit exceeded"; /*(4.2 BSD). */
sys_siglist [SIGVTALRM] = "Virtual alarm clock"; /*(4.2 BSD). */
sys_siglist [SIGPROF] = "Profiling alarm clock"; /*(4.2 BSD). */
sys_siglist [SIGWINCH] = "Window size change"; /*(4.3 BSD, Sun). */
sys_siglist [SIGIO] = "I/O now possible"; /*(4.2 BSD). */
sys_siglist [SIGPWR] = "Power failure restart"; /*(System V). */
sys_siglist [SIGSYS] = "Bad system call";
}
#else
#ifdef ostype_macosx
#pragma GCC diagnostic ignored "-Winfinite-recursion"
#endif
static void NotCalled () /* define this so ranlib doesn't complain */
{
NotCalled (); /* use it so the compiler doesn't complain */
}
#endif
|
frankjas/libjr
|
libjr/htable/htablemt.c
|
#include "project.h"
void jr_HTableEmpty (htable)
jr_HTable * htable ;
{
jr_int i;
for (i = 0; i < htable->num_buckets; i++) {
htable->buckets_array[i] = -1;
}
jr_AListEmpty (htable->entry_array);
htable->delete_list = -1 ; /* end-of-list marker */
htable->num_deletes = 0 ;
}
|
frankjas/libjr
|
libjr/syscalls/jr_noapr.c
|
#include "ezport.h"
/*
** 5-17-2011: implementation that avoid dependency on APR
** to allow export of jr_malloc() w/o requiring APR.
*/
#ifdef ostype_winnt
# include <windows.h>
# include <stdlib.h>
# include <io.h>
#else
# include <unistd.h>
# include <string.h>
# include <errno.h>
#endif
#include "jr/syscalls.h"
#include "jr/error.h"
#ifdef ostype_winnt
jr_int jr_UnlinkNoApr (
const char * file_path,
char * error_buf)
{
wchar_t wpath_buf[ MAX_PATH+1];
size_t num_converted_chars;
jr_int status;
status = mbstowcs_s(
&num_converted_chars,
wpath_buf,
sizeof( wpath_buf) / sizeof( wchar_t),
file_path,
_TRUNCATE
);
if (status != 0) {
jr_esprintf (error_buf, "%s", strerror(status));
goto return_status;
}
if (! DeleteFileW( wpath_buf)) {
status = GetLastError();
jr_esprintf (error_buf, "%s", strerror(status));
status = jr_ConvertLastError( status);
goto return_status;
}
return_status : {
}
return status;
}
jr_int jr_FileExists(
const char * file_path)
{
if (_access( file_path, 00) == 0) {
return 1;
}
return 0;
}
#else
jr_int jr_UnlinkNoApr (
const char * file_path,
char * error_buf)
{
jr_int status;
status = unlink (file_path);
if (status != 0) {
jr_esprintf (error_buf, "%s", strerror( errno));
status = jr_ConvertErrno (errno);
goto return_status;
}
status = 0;
return_status : {
}
return status;
}
jr_int jr_FileExists(
const char * file_path)
{
if (access( file_path, F_OK) == 0) {
return 1;
}
return 0;
}
#endif
|
frankjas/libjr
|
libjr/string/vsigsepi.c
|
<gh_stars>0
#include "ezport.h"
#include <stdio.h>
#include <string.h>
#include "jr/malloc.h"
#include "jr/misc.h"
#include "jr/vector.h"
jr_int jr_VectorizeWithSkipSeparatorsInPlace(str, significant_sep, skip_sep, vector, vector_size)
char * str ;
const char * significant_sep ;
const char * skip_sep ;
char ** vector ;
jr_int vector_size ;
{
char * begin ;
jr_int length ;
jr_int argc = 0 ;
/*
* skip leading separators
*/
for (; *str && strchr(skip_sep, *str); str++) ;
if (! *str) {
vector[0] = 0;
return(0) ;
}
begin = str ;
length = 0 ;
for ( ;; str++) {
if ((! *str) || strchr(skip_sep, *str) || strchr(significant_sep, *str)) {
if (argc == (vector_size - 1)) {
/*
* If we have hit the last valid index (where a null should go)
* then stick the remaining un-vectorized string into this slot
* and return.
*/
vector[argc++] = begin ;
return(argc) ;
}
else {
/*
* Since we remembered the beginning of the string
* and have counted the length up to this position
* we are ready to save the bytes from the beginning
* of the last argument to the current position.
*/
vector[argc++] = begin ;
}
for (; *str && (strchr(skip_sep, *str) || strchr(significant_sep, *str)) ; str++) {
if (strchr(significant_sep, *str)) {
for (str++; *str && strchr(skip_sep, *str) ; str++) ;
break ;
}
}
if (! *str) break ;
begin[length] = 0 ;
begin = str ;
length = 0 ;
if (*str && strchr(significant_sep, *str)) {
str-- ;
continue ;
}
}
/*
* If the char is not a separator than it is
* part of an argument, so increment the length
* of that arguemnt.
*/
length++ ;
}
if (length) begin[length] = 0 ;
vector[argc] = 0 ;
return(argc) ;
}
/*
#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_VectorizeWithSkipSeparatorsInPlace (
buf,
":",
" \t\n",
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]
) ;
jr_free (vbuf[i]) ;
}
}
else {
PrintVector(stdout,vbuf) ;
}
fprintf (stderr,
"Enter up to %d arguments on a line: ",
sizeof (vbuf) / sizeof (char *) - 1
) ;
}
}
*/
|
frankjas/libjr
|
include/jr/symtab.h
|
#ifndef _stableh
#define _stableh
#include "ezport.h"
#include <stdio.h>
#include "jr/avl_tree.h"
#include "jr/llist.h"
#include "jr/alist.h"
#include "jr/htable.h"
#include "jr/ansi_c/exprnode.h"
/******** jr_ST_TypeStructs, jr_ST_Symbols, and jr_ST_Identifiers ********/
typedef struct {
char * str;
void * symbol;
jr_int num_refs;
} jr_ST_Identifier;
#define jr_ST_IdentifierStr(id) ((id)->str)
typedef struct {
void * base_sym; /* pointer to st symbol, 0 for struct/unions */
jr_int num_stars; /* levels of indirection */
jr_int type_kind; /* either variable, function, struct, union */
jr_AList list[1]; /* holds the array sizes, fields, parameters */
jr_int num_refs;
} jr_ST_TypeStruct;
#define jr_ST_TypeKind(t) ((t)->type_kind)
#define jr_ST_TypeBaseSymbol(t) ((jr_ST_Symbol *) (t)->base_sym)
#define jr_ST_TypeNumStars(t) ((t)->num_stars)
#define jr_ST_TypeFieldList(t) ((t)->list)
#define jr_ST_TypeParamList(t) ((t)->list)
#define jr_ST_TypeArrayList(t) ((t)->list)
#define jr_ST_TypeEnumList(t) ((t)->list)
#define jr_ST_TypeNumFields(t) jr_AListSize ((t)->list)
#define jr_ST_TypeNumParams(t) jr_AListSize ((t)->list)
#define jr_ST_TypeNumEnums(t) jr_AListSize ((t)->list)
#define jr_ST_TypeNumArrayDimensions(t) jr_AListSize ((t)->list)
#define jr_ST_TypeIsVariable(t) (jr_ST_TypeKind (t) == jr_ST_VARIABLE)
#define jr_ST_TypeIsFunction(t) (jr_ST_TypeKind (t) == jr_ST_FUNCTION)
#define jr_ST_TypeIsStruct(t) (jr_ST_TypeKind (t) == jr_ST_STRUCT)
#define jr_ST_TypeIsUnion(t) (jr_ST_TypeKind (t) == jr_ST_UNION)
#define jr_ST_TypeIsEnum(t) (jr_ST_TypeKind (t) == jr_ST_ENUM)
/******** jr_ST_Symbol Definition ********/
typedef struct symbol_struct {
struct symbol_struct * prev_definition; /* prev definition of id */
jr_ST_Identifier * id; /* id associated with sym */
jr_ST_TypeStruct * type; /* associated type */
jr_int storage_class;
struct symbol_struct * user_storage_class;
struct symbol_struct * user_type_qualifier;
char * str; /* a copy of the id pointer */
jr_int symbol_kind; /* keyword, typedef etc. */
jr_int scope_num; /* which scope it belongs to */
jr_int token_num; /* used for keywords mostly */
jr_int keyword_group; /* only used for keywords */
char * file_name;
jr_int line_number;
} jr_ST_Symbol;
#define jr_ST_KEYWORD 1
#define jr_ST_BUILTIN 2
#define jr_ST_TYPEDEF 4
#define jr_ST_VARIABLE 5
#define jr_ST_STRUCT 6
#define jr_ST_UNION 7
#define jr_ST_FUNCTION 8
#define jr_ST_STRING 9
#define jr_ST_USER_STORAGE_CLASS 10
#define jr_ST_CONSTANT 11
#define jr_ST_ENUM 12
#define jr_ST_USER_TYPE_QUALIFIER 13
#define jr_ST_PRE_PROCESSOR_DEFINE 14
#define jr_ST_PRE_PROCESSOR_MACRO 15
/******** Array Specification ********/
typedef struct {
jr_int length_num;
char * length_str;
jr_C_ExprNodeType * length_expr;
} jr_ST_ArrayDimension;
typedef jr_AList jr_ST_ArrayList;
#define jr_ST_ArrayListCreate() jr_AListCreate(sizeof (jr_ST_ArrayDimension))
#define jr_ST_ArrayListInit(list) jr_AListInit (list, sizeof (jr_ST_ArrayDimension))
extern void jr_ST_ArrayListInitCopy PROTO ((
jr_AList * dest_list,
jr_AList * src_list
));
extern jr_AList *jr_ST_ArrayListCreateCopy PROTO ((jr_AList *src_list));
extern void jr_ST_ArrayListDestroy PROTO ((jr_AList *list));
extern void jr_ST_ArrayListUndo PROTO ((jr_AList *list));
extern jr_int jr_ST_ArrayListAddDimension PROTO ((
jr_AList * list,
jr_int length_num,
char * length_str,
jr_C_ExprNodeType * length_expr
));
#define jr_ST_ArrayForEachDimension(list, i) \
jr_AListForEachElementIndex(list, i)
#define jr_ST_ArrayListDimensionPtr(list, i) \
((jr_ST_ArrayDimension *) jr_AListElementPtr (list, i))
#define jr_ST_ArrayDimensionLengthNum(list, i) \
(jr_ST_ArrayListDimensionPtr (list, i)->length_num)
#define jr_ST_ArrayDimensionLengthStr(list, i) \
(jr_ST_ArrayListDimensionPtr (list, i)->length_str)
#define jr_ST_ArrayDimensionLengthExpr(list, i) \
(jr_ST_ArrayListDimensionPtr (list, i)->length_expr)
#define jr_ST_ArrayListNumDimensions(list) \
(jr_AListSize (list))
/******** Field Specification ********/
typedef struct {
jr_ST_Identifier * id;
jr_ST_TypeStruct * type;
jr_C_ExprNodeType * bit_field_expr;
jr_int bit_field_value;
jr_int storage_class;
jr_ST_Symbol * user_storage_sym;
jr_ST_Symbol * user_qualifier_sym;
char * file_name;
jr_int line_number;
} jr_ST_FieldType;
typedef jr_AList jr_ST_FieldList;
/******** jr_ST_Fields ********/
extern void jr_ST_FieldInit PROTO ((
jr_ST_FieldType * field,
char * str,
jr_int storage_class,
jr_ST_Symbol * user_storage_sym,
jr_ST_Symbol * user_qualifier_sym,
jr_ST_Symbol * base_sym,
jr_int num_stars,
jr_ST_ArrayList * array,
jr_int bit_field_value,
jr_C_ExprNodeType * bit_field_expr
));
extern void jr_ST_FieldUndo PROTO ((
jr_ST_FieldType * field
));
extern jr_int jr_ST_FieldCmp PROTO ((
jr_ST_FieldType * field1,
jr_ST_FieldType * field2
));
#define jr_ST_FieldListCreate(stable) \
jr_AListCreate((stable)->field_data_size + sizeof(jr_ST_FieldType))
#define jr_ST_FieldListInit(list, stable) \
jr_AListInit (list, (stable)->field_data_size + sizeof(jr_ST_FieldType))
extern void jr_ST_FieldListDestroy PROTO((jr_ST_FieldList *list));
extern void jr_ST_FieldListUndo PROTO((jr_ST_FieldList *list));
#define jr_ST_FieldListSize(list) \
jr_AListSize (list)
#define jr_ST_FieldListDataSize(list) \
(jr_AListElementSize (list) - sizeof (jr_ST_FieldType))
extern jr_int jr_ST_FieldListAddField PROTO((
jr_ST_FieldList * list,
char * str,
jr_int storage_class,
jr_ST_Symbol * user_storage_sym,
jr_ST_Symbol * user_qualifier_sym,
jr_ST_Symbol * base_sym,
jr_int num_stars,
jr_ST_ArrayList * array,
jr_int bit_field_value,
jr_C_ExprNodeType * bit_field_expr
));
#define jr_ST_FieldListElementPtr(field_list, i) \
((jr_ST_FieldType *) jr_AListElementPtr (field_list, i))
#define jr_ST_FieldListForEachElementIndex(list, i) \
jr_AListForEachElementIndex (list, i)
#define jr_ST_FieldListForEachElementPtr(list, field) \
jr_AListForEachElementPtr (list, field)
#define jr_ST_FieldTypePtr(field) ((field)-> type)
#define jr_ST_FieldIdentifier(field) ((field)-> id)
#define jr_ST_FieldStorageClass(field) ((field)-> user_storage_sym)
#define jr_ST_FieldTypeQualifier(field) ((field)-> user_qualifier_sym)
#define jr_ST_FieldBitFieldValue(field) ((field)-> bit_field_value)
#define jr_ST_FieldBitFieldExpr(field) ((field)-> bit_field_expr)
#define jr_ST_FieldFileName(field) ((field)-> file_name)
#define jr_ST_FieldLineNumber(field) ((field)-> line_number)
#define jr_ST_FieldStr(field) jr_ST_IdentifierStr (jr_ST_FieldIdentifier(field))
#define jr_ST_FieldDataPtr(field) ((void *) (((jr_ST_FieldType *) (field)) + 1))
#define jr_ST_FieldPrintDecl(field, prefix, wfp) \
jr_ST_PrintDeclaration ( \
jr_ST_FieldTypePtr (field), jr_ST_FieldStr (field), prefix, wfp \
)
extern void jr_ST_FieldSetBitFieldExpr PROTO ((
jr_ST_FieldType * field,
jr_C_ExprNodeType * length_expr
));
typedef jr_ST_FieldType jr_ST_ParamType;
typedef jr_AList jr_ST_ParamList;
#define jr_ST_ParamListCreate jr_ST_FieldListCreate
#define jr_ST_ParamListInit jr_ST_FieldListInit
#define jr_ST_ParamListDestroy jr_ST_FieldListDestroy
#define jr_ST_ParamListUndo jr_ST_FieldListUndo
#define jr_ST_ParamListAddParam(list, str, sc, uss, uqs, bs, ns, array) \
jr_ST_FieldListAddField(list, str, sc, uss, uqs, bs, ns, array, -1, 0)
#define jr_ST_ParamTypePtr jr_ST_FieldTypePtr
#define jr_ST_ParamIdentifier jr_ST_FieldIdentifier
#define jr_ST_ParamStr jr_ST_FieldStr
#define jr_ST_ParamDataPtr jr_ST_FieldDataPtr
#define jr_ST_ParamListElementPtr jr_ST_FieldListElementPtr
#define jr_ST_ParamListForEachElementPtr(list, field) \
jr_ST_FieldListForEachElementPtr(list, field)
#define jr_ST_ParamListForEachElementIndex(list, i) \
jr_ST_FieldListForEachElementIndex(list, i)
#define jr_ST_ParamPrintDecl jr_ST_FieldPrintDecl
/******** Enum Specification ********/
typedef struct {
jr_ST_Identifier * id;
jr_int enum_value;
jr_C_ExprNodeType * value_expr;
} jr_ST_EnumType;
typedef jr_AList jr_ST_EnumList;
#define jr_ST_EnumListCreate() jr_AListCreate(sizeof(jr_ST_EnumType))
#define jr_ST_EnumListInit(list) jr_AListInit (list, sizeof(jr_ST_EnumType))
extern void jr_ST_EnumListDestroy PROTO((jr_ST_EnumList *list));
extern void jr_ST_EnumListUndo PROTO((jr_ST_EnumList *list));
extern jr_int jr_ST_EnumListAddEnum PROTO ((
jr_ST_FieldList * list,
char * str,
jr_int enum_value,
jr_C_ExprNodeType * value_expr
));
#define jr_ST_EnumIdentifier(enum_ptr) ((enum_ptr)->id)
#define jr_ST_EnumStr(enum_ptr) jr_ST_IdentifierStr (jr_ST_EnumIdentifier(enum_ptr))
#define jr_ST_EnumValue(enum_ptr) ((enum_ptr)->enum_value)
#define jr_ST_EnumValueExpr(enum_ptr) ((enum_ptr)->value_expr)
#define jr_ST_EnumListForEachElementPtr(list, enum) \
jr_AListForEachElementPtr (list,enum)
/******** jr_ST_TypeStruct Functions ********/
extern jr_ST_TypeStruct *jr_ST_TypeCreate PROTO((
jr_int type_kind,
jr_ST_Symbol * base_sym,
jr_int num_stars,
jr_AList * list
));
extern void jr_ST_TypeInit 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_TypeDestroy PROTO ((jr_ST_TypeStruct *type));
extern void jr_ST_TypeUndo PROTO ((jr_ST_TypeStruct *type));
extern void jr_ST_TypeCollapsedInit PROTO((
jr_ST_TypeStruct * new_type,
jr_ST_TypeStruct * type
));
extern jr_int jr_ST_CanCollapseBaseSymbol PROTO ((
jr_ST_TypeStruct * type
));
extern jr_int jr_ST_TypeCmp PROTO ((
jr_ST_TypeStruct * type1,
jr_ST_TypeStruct * type2
));
extern jr_int jr_ST_TypeEquiv PROTO ((
jr_ST_TypeStruct * type1,
jr_ST_TypeStruct * type2
));
extern jr_int jr_ST_TypeIsValid PROTO((
jr_ST_TypeStruct * type,
jr_int array_of_func,
jr_int func_ret_array,
jr_int func_ret_func
));
#define jr_ST_TypeVariableInit(type, base, num_stars, list) \
jr_ST_TypeInit (type, jr_ST_VARIABLE, base, num_stars, list)
#define jr_ST_TypeFunctionInit(type, base, num_stars, list) \
jr_ST_TypeInit (type, jr_ST_FUNCTION, base, num_stars, list)
#define jr_ST_TypeStructInit(type, num_stars, list) \
jr_ST_TypeInit (type, jr_ST_STRUCT, 0, num_stars, list)
#define jr_ST_TypeUnionInit(type, num_stars, list) \
jr_ST_TypeInit (type, jr_ST_UNION, 0, num_stars, list)
#define jr_ST_TypeEnumInit(type, num_stars, list) \
jr_ST_TypeInit (type, jr_ST_ENUM, 0, num_stars, list)
#define jr_ST_TypeVariableCreate(type, base, num_stars, list) \
jr_ST_TypeCreate (type, jr_ST_VARIABLE, base, num_stars, list)
#define jr_ST_TypeFunctionCreate(type, base, num_stars, list) \
jr_ST_TypeCreate (type, jr_ST_FUNCTION, base, num_stars, list)
#define jr_ST_TypeStructCreate(type, num_stars, list) \
jr_ST_TypeCreate (type, jr_ST_STRUCT, 0, num_stars, list)
#define jr_ST_TypeUnionCreate(type, num_stars, list) \
jr_ST_TypeCreate (type, jr_ST_UNION, 0, num_stars, list)
#define jr_ST_TypeEnumCreate(type, num_stars, list) \
jr_ST_TypeCreate (type, jr_ST_ENUM, 0, num_stars, list)
/******** Scopes and jr_ST_Symbol Table ********/
typedef struct {
jr_LList symbol_list[1];
jr_int scope_num;
} jr_ST_ScopeHeader;
typedef struct {
jr_AList scope_headers[1];
jr_AVL_Tree id_table[1];
jr_AVL_Tree type_table[1];
jr_HTable string_table[1];
char * default_file_name;
jr_int data_size;
jr_int field_data_size;
unsigned semantic_error : 1;
unsigned fatal_error : 1;
unsigned internal_error : 1;
unsigned print_errors : 1;
} jr_ST_SymbolTable;
extern jr_ST_SymbolTable * jr_ST_SymbolTableCreate PROTO ((
jr_int data_size,
jr_int field_data_size
));
extern void jr_ST_SymbolTableInit PROTO ((
jr_ST_SymbolTable * symbol_table,
jr_int data_size,
jr_int field_data_size
));
extern void jr_ST_SymbolTableDestroy PROTO ((
jr_ST_SymbolTable * symbol_table
));
extern void jr_ST_SymbolTableUndo PROTO ((
jr_ST_SymbolTable * symbol_table
));
extern void jr_ST_OpenNewScope PROTO ((
jr_ST_SymbolTable * symbol_table
));
extern void jr_ST_CloseCurrScope PROTO ((
jr_ST_SymbolTable * symbol_table
));
extern jr_ST_ScopeHeader * jr_ST_CloseCurrScopeAndSave PROTO ((
jr_ST_SymbolTable * symbol_table
));
#define jr_ST_CurrScopeNum(st) \
jr_AListTailIndex((st)->scope_headers)
#define jr_ST_CurrScopeHeader(st) \
((jr_ST_ScopeHeader *) jr_AListTailPtr((st)->scope_headers))
#define jr_ST_CurrScopeList(st) \
(jr_ST_CurrScopeHeader(st)->symbol_list)
#define jr_ST_ForEachScopeNum(st, scope_num) \
for ((scope_num) = 1; (scope_num) <= jr_ST_CurrScopeNum(st); (scope_num)++)
#define jr_ST_ForEachSymbolInScope(st, scope_num, symbol) \
jr_LListForEachElementPtr (jr_ST_GetScopeList(st, scope_num), symbol)
#define jr_ST_ForEachSymbolInCurrScope(st, symbol) \
jr_LListForEachElementPtr (jr_ST_CurrScopeList(st), symbol)
#define jr_ST_ForEachNamedSymbolInScope(st, scope_num, symbol) \
jr_ST_ForEachSymbolInScope (st, scope_num, symbol) \
if (jr_ST_SymbolStr (symbol))
#define jr_ST_ForEachNamedSymbolInCurrScope(st, symbol) \
jr_ST_ForEachSymbolInCurrScope (st, symbol) \
if (jr_ST_SymbolStr (symbol))
#define jr_ST_GetScopeHeader(st, scope_num) \
((jr_ST_ScopeHeader *) jr_AListElementPtr((st)->scope_headers, scope_num))
#define jr_ST_GetScopeList(st, scope_num) \
(jr_ST_GetScopeHeader(st, scope_num)->symbol_list)
/*
* for the user to set and clear
*/
#define jr_ST_HasSemanticError(st) ((st)->semantic_error)
#define jr_ST_SetSemanticError(st) ((st)->semantic_error = 1)
#define jr_ST_ClearSemanticError(st) ((st)->semantic_error = 0)
#define jr_ST_HasFatalError(st) ((st)->fatal_error)
#define jr_ST_SetFatalError(st) ((st)->fatal_error = 1)
#define jr_ST_ClearFatalError(st) ((st)->fatal_error = 0)
#define jr_ST_HasInternalError(st) ((st)->internal_error)
#define jr_ST_SetInternalError(st) ((st)->internal_error = 1)
#define jr_ST_ClearInternalError(st) ((st)->internal_error = 0)
#define jr_ST_SetPrintErrorMessages(st) ((st)->print_errors = 1)
#define jr_ST_PrintErrorMessages(st) ((st)->print_errors)
#define jr_ST_ClearPrintErrorMessages(st) ((st)->print_errors = 0)
extern jr_ST_Symbol * jr_ST_EnterNativeSymbol PROTO ((
jr_ST_SymbolTable * symbol_table,
jr_int symbol_kind,
const char * str,
jr_int token_num,
jr_int keyword_group
));
extern jr_ST_Symbol * jr_ST_EnterSymbol PROTO ((
jr_ST_SymbolTable * symbol_table,
jr_int symbol_kind,
const char * str,
jr_ST_Symbol * base_sym,
jr_int num_star,
jr_AList * list
));
extern void jr_ST_SetSymbolType PROTO ((
jr_ST_SymbolTable * stable,
jr_ST_Symbol * symbol,
jr_ST_Symbol * base_sym,
jr_int num_star,
jr_AList * list
));
extern void jr_ST_SetSymbolLocation PROTO ((
jr_ST_SymbolTable * stable,
jr_ST_Symbol * symbol,
char * file_name,
jr_int line_number
));
extern void jr_ST_SetFieldLocation PROTO ((
jr_ST_SymbolTable * stable,
jr_ST_FieldType * field,
char * file_name,
jr_int line_number
));
extern jr_ST_Symbol * jr_ST_FindSymbol PROTO ((
jr_ST_SymbolTable * symbol_table,
const char * str
));
extern jr_ST_Symbol * jr_ST_FindBaseTypeSymbol PROTO ((
jr_ST_TypeStruct * type
));
extern jr_ST_Symbol * jr_ST_FindCompoundSymbolName PROTO ((
jr_ST_SymbolTable * symbol_table,
char * str,
jr_int symbol_kind
));
#define jr_ST_FindUnionSymbol(st, str) \
jr_ST_FindCompoundSymbolName(st, str, jr_ST_UNION)
#define jr_ST_FindStructSymbol(st, str) \
jr_ST_FindCompoundSymbolName(st, str, jr_ST_STRUCT)
#define jr_ST_FindEnumSymbol(st, str) \
jr_ST_FindCompoundSymbolName(st, str, jr_ST_ENUM)
#define jr_ST_FindPreProcessorDefine(st, str) \
jr_ST_FindCompoundSymbolName(st, str, jr_ST_PRE_PROCESSOR_DEFINE)
#define jr_ST_FindPreProcessorMacro(st, str) \
jr_ST_FindCompoundSymbolName(st, str, jr_ST_PRE_PROCESSOR_MACRO)
/*
* didn't rename find_struct_union when I added the enum support
*/
#define jr_ST_EnterKeyword(st, str, token_num, keyword_group) \
jr_ST_EnterNativeSymbol(st, jr_ST_KEYWORD, str, token_num, keyword_group)
#define jr_ST_EnterBuiltInType(st, str, token_num, keyword_group) \
jr_ST_EnterNativeSymbol(st, jr_ST_BUILTIN, str, token_num, keyword_group)
#define jr_ST_EnterStringDef(st, str) \
jr_ST_EnterSymbol(st, jr_ST_STRING, str, 0, 0, 0)
#define jr_ST_EnterVariableDef(st, str, base, num_star, array) \
jr_ST_EnterSymbol(st, jr_ST_VARIABLE, str, base, num_star, array)
#define jr_ST_EnterTypedef(st, str, base, num_star, array) \
jr_ST_EnterSymbol(st, jr_ST_TYPEDEF, str, base, num_star, array)
#define jr_ST_EnterUserStorageClass(st, str) \
jr_ST_EnterSymbol(st, jr_ST_USER_STORAGE_CLASS, str, 0, 0, 0)
#define jr_ST_EnterUserTypeQualifier(st, str) \
jr_ST_EnterSymbol(st, jr_ST_USER_TYPE_QUALIFIER, str, 0, 0, 0)
#define jr_ST_EnterConstant(st, str) \
jr_ST_EnterSymbol(st, jr_ST_CONSTANT, str, 0, 0, 0)
#define jr_ST_EnterStructDef(st, str, fields) \
jr_ST_EnterSymbol(st, jr_ST_STRUCT, str, 0, 0, fields)
#define jr_ST_EnterUnionDef(st, str, fields) \
jr_ST_EnterSymbol(st, jr_ST_UNION, str, 0, 0, fields)
#define jr_ST_EnterEnumDef(st, str, values) \
jr_ST_EnterSymbol(st, jr_ST_ENUM, str, 0, 0, values)
#define jr_ST_EnterFunctionDef(st, str, base, num_star, params) \
jr_ST_EnterSymbol(st, jr_ST_FUNCTION, str, base, num_star, params)
#define jr_ST_EnterPreProcessorDefine(st, str, macro_index) \
jr_ST_EnterSymbol(st, jr_ST_PRE_PROCESSOR_DEFINE, str, 0, macro_index, 0)
#define jr_ST_EnterPreProcessorMacro(st, str, macro_index) \
jr_ST_EnterSymbol(st, jr_ST_PRE_PROCESSOR_MACRO, str, 0, macro_index, 0)
#define jr_ST_SymbolHasType(symbol) jr_ST_SymbolType(symbol)
#define jr_ST_SymbolIsKeyword(symbol) \
(jr_ST_SymbolKind (symbol) == jr_ST_KEYWORD)
#define jr_ST_SymbolIsBuiltInType(symbol) \
(jr_ST_SymbolKind (symbol) == jr_ST_BUILTIN)
#define jr_ST_SymbolIsTypedef(symbol) \
(jr_ST_SymbolKind (symbol) == jr_ST_TYPEDEF)
#define jr_ST_SymbolIsUserStorageClass(symbol) \
(jr_ST_SymbolKind (symbol) == jr_ST_USER_STORAGE_CLASS)
#define jr_ST_SymbolIsUserTypeQualifier(symbol) \
(jr_ST_SymbolKind (symbol) == jr_ST_USER_TYPE_QUALIFIER)
#define jr_ST_SymbolIsConstant(symbol) \
(jr_ST_SymbolKind (symbol) == jr_ST_CONSTANT)
#define jr_ST_SymbolIsString(symbol) \
(jr_ST_SymbolKind (symbol) == jr_ST_STRING)
#define jr_ST_SymbolIsVariable(symbol) \
(jr_ST_SymbolKind (symbol) == jr_ST_VARIABLE)
#define jr_ST_SymbolIsFunction(symbol) \
(jr_ST_SymbolKind(symbol) == jr_ST_FUNCTION)
#define jr_ST_SymbolIsStruct(symbol) \
(jr_ST_SymbolKind(symbol) == jr_ST_STRUCT)
#define jr_ST_SymbolIsUnion(symbol) \
(jr_ST_SymbolKind(symbol) == jr_ST_UNION)
#define jr_ST_SymbolIsEnum(symbol) \
(jr_ST_SymbolKind(symbol) == jr_ST_ENUM)
#define jr_ST_SymbolIsPreProcessorDefine(symbol) \
(jr_ST_SymbolKind(symbol) == jr_ST_PRE_PROCESSOR_DEFINE)
#define jr_ST_SymbolIsPreProcessorMacro(symbol) \
(jr_ST_SymbolKind(symbol) == jr_ST_PRE_PROCESSOR_MACRO)
#define jr_ST_SymbolDataPtr(symbol) ((void *)((symbol)+1))
#define jr_ST_SymbolIdentifier(symbol) ((symbol)->id)
#define jr_ST_SymbolStr(symbol) ((symbol)->str)
#define jr_ST_SymbolKind(symbol) ((symbol)->symbol_kind)
#define jr_ST_SymbolType(symbol) ((symbol)->type)
#define jr_ST_SymbolStorageClass(symbol) ((symbol)->storage_class)
#define jr_ST_SymbolUserStorageClass(symbol) ((symbol)->user_storage_class)
#define jr_ST_SymbolUserTypeQualifier(symbol) ((symbol)->user_type_qualifier)
#define jr_ST_SymbolScopeNum(symbol) ((symbol)->scope_num)
#define jr_ST_SymbolFileName(symbol) ((symbol)->file_name)
#define jr_ST_SymbolLineNumber(symbol) ((symbol)->line_number)
#define jr_ST_KeywordTokenNum(symbol) ((symbol)->token_num)
#define jr_ST_SymbolTokenNum(symbol) ((symbol)->token_num)
#define jr_ST_SymbolPreProcessorIndex(symbol) jr_ST_SymbolTokenNum (symbol)
#define jr_ST_SymbolSetUserStorageClass(symbol, v) ((symbol)->user_storage_class = (v))
#define jr_ST_SymbolSetUserTypeQualifier(symbol, v) ((symbol)->user_type_qualifier = (v))
#define jr_ST_SymbolIsInKeyWordGroup(symbol, group) \
((symbol)->keyword_group & (group))
extern jr_int jr_ST_PrintDeclaration PROTO ((
jr_ST_TypeStruct * declarator_type,
char * opt_declarator_name,
char * prefix,
FILE * wfp
));
extern jr_int jr_ST_DeclarationToString PROTO ((
jr_ST_TypeStruct * declarator_type,
jr_ST_Symbol * opt_base_type_sym,
char * opt_declarator_name,
jr_int nesting_level,
char * dest_buf,
jr_int buf_length
));
extern jr_int jr_ST_TypeSymbolToString PROTO ((
jr_ST_Symbol * base_type_sym,
jr_int nesting_level,
char * dest_buf,
jr_int buf_length
));
extern jr_int jr_ST_TypeListToString PROTO ((
jr_ST_TypeStruct * type,
char * dest_buf,
jr_int buf_length
));
#endif
|
frankjas/libjr
|
libjr/alist/project.h
|
<reponame>frankjas/libjr
#ifndef __project_h___
#define __project_h___
#define _POSIX_SOURCE 1
#include "ezport.h"
#include <assert.h>
#include <stdarg.h>
#include "jr/alist.h"
#include "jr/malloc.h"
#include "jr/misc.h"
#include "jr/string.h"
#include "jr/prefix.h"
extern void jr_AListTransformPrefixes PROTO ((
jr_AList * list,
void * old_buffer_ptr,
void (*prefix_transform_fn) (),
void * prefix_transform_arg
));
#endif
|
frankjas/libjr
|
libjr/missing/getpw.c
|
#define _POSIX_SOURCE 1
#include "ezport.h"
#ifdef missing_passwd_funcs
#include <pwd.h>
#include <stdio.h>
# ifdef has_hesiod
struct passwd *getpwuid(uid)
jr_int uid ;
{
char uid_string[128] ;
static struct passwd pw_entry[1] ;
static char pw_name[128] ;
static char pw_passwd[128] ;
static char pw_comment[128] ;
static char pw_dir[512] ;
static char pw_shell[512] ;
char *entry_text ;
char **vp ;
jr_int nfields ;
sprintf(uid_string,"%d", uid) ;
vp = (char **) hes_resolve(uid_string, "uid") ;
if (! (vp && *vp)) {
fprintf(stderr,"no matching password entry for uid %d\n",
uid) ;
return(0) ;
}
entry_text = *vp ;
/*
* fprintf(stderr,"%s\n", entry_text) ;
*/
pw_entry->pw_name = pw_name ;
pw_entry->pw_passwd = <PASSWORD> ;
pw_entry->pw_comment = pw_comment ;
pw_entry->pw_dir = pw_dir ;
pw_entry->pw_shell = pw_shell ;
nfields = sscanf(entry_text, "%[^:]:%[^:]:%d:%d:%[^:]:%[^:]:%[^:\n]",
pw_entry->pw_name,
pw_entry->pw_passwd,
&(pw_entry->pw_uid),
&(pw_entry->pw_gid),
pw_entry->pw_comment,
pw_entry->pw_dir,
pw_entry->pw_shell
) ;
if (nfields != 7) {
fprintf(stderr,"mis-matching number of struct entries %d of %d: '%s'\n",
nfields, entry_text, 7) ;
return(0) ;
}
return(pw_entry) ;
}
# else
struct passwd * getpwuid(uid_arg)
uid_t uid_arg ;
{
char username_buf[128] ;
char * username ;
struct passwd * passwd_ptr;
username = getenv("USER") ;
if (username == 0) {
sprintf(username_buf, "%d", uid_arg) ;
username = username_buf ;
}
passwd_ptr = getpwnam(username) ;
passwd_ptr->pw_uid = uid_arg;
return passwd_ptr;
}
struct passwd * getpwnam(username)
const char * username ;
{
static struct passwd result[1] ;
static char pw_name_buf[128] ;
static char pw_passwd_buf[4] ;
static char pw_comment_buf[4] ;
static char pw_gecos_buf[4] ;
static char pw_dir_buf[4] ;
static char pw_shell_buf[4] ;
result->pw_name = pw_name_buf ;
result->pw_passwd = pw_passwd_buf ;
result->pw_uid = -1;
result->pw_gid = -1;
result->pw_quota = 0;
result->pw_comment = pw_comment_buf ;
result->pw_gecos = pw_gecos_buf ;
result->pw_dir = pw_dir_buf ;
result->pw_shell = pw_shell_buf ;
*pw_name_buf = 0 ;
*pw_passwd_buf = 0 ;
*pw_comment_buf = 0 ;
*pw_gecos_buf = 0 ;
*pw_dir_buf = 0 ;
*pw_shell_buf = 0 ;
strncpy(pw_name_buf, username, sizeof(pw_name_buf) - 1) ;
pw_name_buf[sizeof(pw_name_buf) - 1] = 0 ;
{
char * env_value_equivalent ;
if (env_value_equivalent = getenv("PASSWD")) {
result->pw_passwd = env_value_equivalent ;
}
if (env_value_equivalent = getenv("GECOS")) {
result->pw_gecos = env_value_equivalent ;
}
if (env_value_equivalent = getenv("HOME")) {
result->pw_dir = env_value_equivalent ;
}
if (env_value_equivalent = getenv("SHELL")) {
result->pw_shell = env_value_equivalent ;
}
}
return(result) ;
}
# endif
#else
static void NotCalled () /* define this so ranlib doesn't complain */
{
NotCalled (); /* use it so the compiler doesn't complain */
}
#endif
|
frankjas/libjr
|
libjr/llist/llistcmp.c
|
<filename>libjr/llist/llistcmp.c
#include "project.h"
jr_int jr_LListCmp (list1, list2, cmpfn)
jr_LList *list1, *list2;
jr_int (*cmpfn) ();
{
char *obj_p1, *obj_p2;
jr_int comp;
obj_p1 = jr_LListHeadPtr (list1);
obj_p2 = jr_LListHeadPtr (list2);
while (obj_p1 && obj_p2) {
comp = (*cmpfn) (obj_p1, obj_p2);
if (comp != 0) {
return (comp);
}
obj_p1 = jr_LListNextElementPtr (list1, obj_p1);
obj_p2 = jr_LListNextElementPtr (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_LListHash (list, hashfn)
jr_LList * list;
jr_int (*hashfn) ();
{
jr_int hash_value = 0;
void * el_ptr;
jr_LListForEachElementPtr (list, el_ptr) {
hash_value += hashfn (el_ptr);
}
return hash_value;
}
|
frankjas/libjr
|
include/jr/errsim.h
|
#ifndef _jr_errsim_h___
#define _jr_errsim_h___
extern jr_int jr_iferr_sim (
jr_int is_err,
jr_int is_orig_err,
jr_int negate_err,
const char * file_name,
jr_int line_number);
#ifdef jr_IFERR_ID
# define iferr(v) \
iferr_macro (jr_IFERR_ID, __LINE__) (v,0,0, jr_IFERR_ID, __LINE__)
# define iferr_sim(v) \
iferr_macro (jr_IFERR_ID, __LINE__) (v,1,0, jr_IFERR_ID, __LINE__)
# define ifnerr(v) \
iferr_macro (jr_IFERR_ID, __LINE__) (v,0,1, jr_IFERR_ID, __LINE__)
# define ifnerr_sim(v) \
iferr_macro (jr_IFERR_ID, __LINE__) (v,1,1, jr_IFERR_ID, __LINE__)
# define iferr_lic(v) \
iferr_lic_macro (jr_IFERR_ID, __LINE__) (v,0,0, jr_IFERR_ID, __LINE__)
# define iferr_sim_lic(v) \
iferr_lic_macro (jr_IFERR_ID, __LINE__) (v,1,0, jr_IFERR_ID, __LINE__)
# define ifnerr_lic(v) \
iferr_lic_macro (jr_IFERR_ID, __LINE__) (v,0,1, jr_IFERR_ID, __LINE__)
# define ifnerr_sim_lic(v) \
iferr_lic_macro (jr_IFERR_ID, __LINE__) (v,1,1, jr_IFERR_ID, __LINE__)
#else
# define iferr(v) if (v)
# define iferr_sim(v) if (v)
# define ifnerr(v) if (v)
# define ifnerr_sim(v) if (v)
# define iferr_lic(v) if (v)
# define iferr_sim_lic(v) if (v)
# define ifnerr_lic(v) if (v)
# define ifnerr_sim_lic(v) if (v)
#endif
#define iferr_assert(v) if (v)
#define iferr_macro(file_id, line) iferr_macro_2 (file_id, line)
#define iferr_lic_macro(file_id, line) iferr_lic_macro_2 (file_id, line)
/*
* 7/26/2005: Need an extra layer of macro call to get ## to work as desired under gcc,
* i.e. to get the arguments substituted before the ## happens.
*/
#ifdef jr_IFERR_USE_CUSTOM
# define iferr_macro_2(file_id, line) iferr_ ## file_id ## line
#elif jr_IFERR_USE_CACHED
# define iferr_macro_2(file_id, line) jr_iferr_cached
#else
# define iferr_macro_2(file_id, line) jr_iferr
#endif
#ifdef jr_IFERR_USE_CUSTOM
# define iferr_lic_macro_2(file_id, line) iferr_lic_ ## file_id ## line
#elif jr_IFERR_USE_CACHED
# define iferr_lic_macro_2(file_id, line) jr_iferr_cached
#else
# define iferr_lic_macro_2(file_id, line) jr_iferr
#endif
#define jr_iferr(is_err, is_orig_err, negate_err, file_id, line) \
if (jr_iferr_sim (is_err, is_orig_err, negate_err, __FILE__, line))
#define jr_iferr_cached(is_err, is_orig_err, negate_err, file_id, line) \
if (jr_iferr_var (file_id, line) >= 0 \
? jr_iferr_var (file_id, line) \
: jr_iferr_var (file_id, line) = jr_iferr_sim ( \
is_err, is_orig_err, negate_err, __FILE__, line \
) \
)
#define jr_iferr_var(base, suffix) jr_iferr_id (base, suffix)
#ifndef jr_iferr_id
# define jr_iferr_id(base, suffix) base ## suffix
#endif
/******** Diagnostic Error Macros ********/
/*
** 1/19/07: Unused in code
*/
#define jr_NUM_FAKE_ERRORS 1024
extern char jr_HasFakeError[];
#define jr_set_fake_error(n) (jr_check_fake_error_macro (n); jr_HasFakeError [n] = 1)
#ifdef jr_NO_FAKE_ERRORS
# define jr_use_fake_error(n) (0)
#else
# define jr_use_fake_error(n) (jr_HasFakeError [n])
#endif
#ifdef compiler_has_ansi_support
# define jr_check_fake_error_macro(n) jr_check_fake_error (n, __FILE__, __LINE__)
#else
# define jr_check_fake_error_macro(n) jr_check_fake_error (n, 0, 0)
#endif
extern void jr_check_fake_error PROTO ((
jr_int error_number,
const char * file_name,
jr_int line_number
));
#endif
|
frankjas/libjr
|
libjr/struct/net_flt.c
|
<gh_stars>0
#define _POSIX_SOURCE 1
#include "ezport.h"
#include "jr/nettype.h"
#include "jr/xdr.h"
static XDR FloatEncodeXDR[1];
static XDR FloatDecodeXDR[1];
static jr_int DidInit = 0;
static float FloatEncodeBuf[16];
static float FloatDecodeBuf[16];
/*
* Only need 1 float, verified by examining source for xdr_float
* make it 16 to be sure.
*/
#define FloatXDR_InitIfNecessary() \
( DidInit ? 0 : (FloatXDR_Init (), DidInit = 1))
static void FloatXDR_Init ()
{
xdrmem_create (FloatEncodeXDR, (caddr_t) FloatEncodeBuf, sizeof (FloatEncodeBuf), XDR_ENCODE);
xdrmem_create (FloatDecodeXDR, (caddr_t) FloatDecodeBuf, sizeof (FloatDecodeBuf), XDR_DECODE);
/*
* no need to Undo, since xdr_destroy, for mem xdr's is a null op
*/
DidInit = 1;
}
float jr_NetFloatToHost (net_float)
jr_NetFloat net_float;
{
float tmp_float = net_float.net_float_value;
FloatXDR_InitIfNecessary ();
FloatDecodeBuf[0] = net_float.net_float_value;
xdr_setpos (FloatDecodeXDR, 0);
xdr_float (FloatDecodeXDR, &tmp_float);
return tmp_float;
}
void jr_NetFloatAsgnFloat (net_float_ptr, host_value_dbl)
jr_NetFloat * net_float_ptr;
double host_value_dbl;
{
float host_value_flt = host_value_dbl;
FloatXDR_InitIfNecessary ();
xdr_setpos (FloatEncodeXDR, 0);
xdr_float (FloatEncodeXDR, &host_value_flt);
net_float_ptr->net_float_value = FloatEncodeBuf[0];
}
|
frankjas/libjr
|
include/jr/bitset.h
|
<filename>include/jr/bitset.h
#ifndef __BINSET_HEADER__
#define __BINSET_HEADER__
#include "ezport.h"
#include <stdio.h>
typedef struct {
jr_int num_bits;
unsigned jr_int * int_array;
} jr_BitSet;
/*
* 7/23/2005: can't use small in array local to the struct
* since then the object can't be moved.
*/
extern jr_BitSet * jr_BitSetCreate PROTO ((jr_int num_bits));
extern void jr_BitSetInit PROTO ((jr_BitSet *bset, jr_int num_bits));
extern void jr_BitSetDestroy PROTO ((jr_BitSet *bset));
extern void jr_BitSetUndo PROTO ((jr_BitSet *bset));
extern jr_int jr_BitSetSize PROTO ((jr_BitSet *bset));
extern jr_int jr_BitSetIsEmpty PROTO ((jr_BitSet *bset));
extern jr_int jr_BitSetIsFull PROTO ((jr_BitSet *bset));
extern void jr_BitSetEmpty PROTO ((jr_BitSet *bset));
extern void jr_BitSetAddAll PROTO ((jr_BitSet *bset));
extern void jr_BitSetAddSet PROTO ((jr_BitSet *bsetb, jr_BitSet *bseta));
extern void jr_BitSetUnion PROTO ((
jr_BitSet * bsetc,
jr_BitSet * bseta,
jr_BitSet * bsetb
));
extern void jr_BitSetChangeNumBits PROTO ((jr_BitSet *bset, jr_int new_num_bits));
extern void jr_BitSetPrint PROTO ((jr_BitSet *bset, FILE *wfp));
#define jr_BitSetNumBits(bset) ((bset)->num_bits)
#define jr_BitSetElementInt(bset, b) \
((bset)->int_array[((unsigned) (b)) >> jr_INT_BIT_SIZE_POWER])
#define jr_BitSetElementMask(bset, b) \
(1 << ((b) & jr_INT_BIT_SIZE_MASK))
#define jr_BitSetHasElement(bset, b) \
((jr_BitSetElementInt (bset, b) & jr_BitSetElementMask (bset, b)) != 0)
#define jr_BitSetAddElement(bset, b) \
((void) (jr_BitSetElementInt (bset, b) |= jr_BitSetElementMask (bset, b)))
#define jr_BitSetDeleteElement(bset, b) \
((void) (jr_BitSetElementInt (bset, b) &= ~jr_BitSetElementMask (bset, b)))
#define jr_BitSetForEachPossibleElement(bset, b) \
for ((b) = 0; (b) < (bset)->num_bits; (b)++)
#define jr_BitSetForEachElement(bset, b) \
jr_BitSetForEachPossibleElement (bset, b) if (jr_BitSetHasElement(bset, b))
#define jr_BitSetForEachElementSparse(bset, b) \
for ( (b) = 0; \
(b) < (bset)->num_bits); \
jr_BitSetElementInt (bset, b) \
? (b)++ \
: ( (b) += jr_INT_NUM_BITS, \
(b) -= (b) & jr_INT_BIT_SIZE_MASK) \
) if (jr_BitSetHasElement (bset, b))
#define jr_BitSetIsSparse(bset, num_elements) \
(jr_BitSetNumBits(bset) / (num_elements) >= 32)
/*
* 7/21/2005: Normal loop: 3 accesses, 1 compare, 1 increment
* Sparse loop: 3 accesses, 1 compare, 1 increment, 1 shift, 1 access, 1 test
*
* Rounding in favor of a straight loop: 1 compare, 1 increment
* sparse: 1 compare, 1 increment, 1 shift, 1 access, 1 test
*
* Total cost: 5N versus 2N.
* Question: how many skips in a sparse loop will it take to make them even?
* In other words, for what S is 5N - 64S < 2N (use 64 since a skip saves 32 increments, compares)?
* 5N - 2N < 64S
* 3N < 64S
* (3/64) N < S
*
* Need to skip 3 out of 64 ints.
*
* Conclusion: the above is a pretty good approximation.
*/
#endif
|
frankjas/libjr
|
include/jr/ezport/apr.h
|
#ifndef _jr_ezport_apr_h___
#define _jr_ezport_apr_h___
/*
** 11/21/06: Match apr-1 compiling options
** Need to define before any other files are included
*/
#ifdef ostype_linux
# ifndef _GNU_SOURCE
# define _GNU_SOURCE 1
# endif
# if !defined(LINUX) && (__version__ >= 2000)
# define LINUX 2
# endif
# ifndef _REENTRANT
# define _REENTRANT
# endif
# ifndef _LARGEFILE64_SOURCE
# define _LARGEFILE64_SOURCE
# endif
#endif
#ifdef ostype_winnt
# define APR_DECLARE_STATIC
# define APU_DECLARE_STATIC
#endif
#endif
|
frankjas/libjr
|
libjr/string/isstring.c
|
#include "ezport.h"
#include <ctype.h>
#include "jr/string.h"
jr_int jr_IsString (data_ptr, data_length)
char * data_ptr;
jr_int data_length;
{
jr_int i;
for (i=0; i < data_length - 1; i++) {
if (data_ptr [i] == 0) break;
if (!isprint (data_ptr [i]) && !isspace (data_ptr [i])) {
return (0);
}
}
if (data_ptr [i] != 0) return (0);
return (1);
}
|
Sestowner/dwm
|
config.h
|
<reponame>Sestowner/dwm
/* See LICENSE file for copyright and license details. */
#include <X11/XF86keysym.h>
/* appearance */
static const unsigned int borderpx = 1; /* border pixel of MODKEY */
static const unsigned int snap = 32; /* snap pixel */
static const unsigned int systraypinning = 0; /* 0: sloppy systray follows selected monitor, >0: pin systray to monitor X */
static const unsigned int systrayspacing = 2; /* systray spacing */
static const int systraypinningfailfirst = 1; /* 1: if pinning fails, display systray on the first monitor, False: display systray on the last monitor*/
static const int showsystray = 1; /* 0 means no systray */
static const int showbar = 1; /* 0 means no bar */
static const int topbar = 1; /* 0 means bottom bar */
static const char *fonts[] = {"monospace:size=10"};
static const char dmenufont[] = "monospace:size=10";
static const char col_black[] = "black";
static const char col_gray2[] = "#444444";
static const char col_gray3[] = "#bbbbbb";
static const char col_gray4[] = "#eeeeee";
static const char col_green[] = "green3";
static const char *colors[][3] = {
/* fg bg border */
[SchemeNorm] = {col_gray3, col_black, col_gray2},
[SchemeSel] = {col_green, col_black, col_green},
};
/* tagging */
static const char *tags[] = {"1", "2", "3", "4"};
static const Rule rules[] = {
/* xprop(1):
* WM_CLASS(STRING) = instance, class
* WM_NAME(STRING) = title
*/
/* class instance title tags mask isfloating monitor */
{NULL, NULL, "Picture in picture", ~0, 1, -1},
};
/* layout(s) */
static const float mfact = 0.50; /* factor of master area size [0.05..0.95] */
static const int nmaster = 1; /* number of clients in master area */
static const int resizehints = 0; /* 1 means respect size hints in tiled resizals */
static const int lockfullscreen = 1; /* 1 will force focus on the fullscreen window */
static const Layout layouts[] = {
/* symbol arrange function */
{"[]=", tile}, /* first entry is default */
{"><>", NULL},
{"[M]", monocle},
};
/* key definitions */
#define MODKEY Mod4Mask
#define TAGKEYS(KEY, TAG) \
{MODKEY, KEY, view, {.ui = 1 << TAG}}, \
{MODKEY | ControlMask, KEY, toggleview, {.ui = 1 << TAG}}, \
{MODKEY | ShiftMask, KEY, tag, {.ui = 1 << TAG}}, \
{MODKEY | ControlMask | ShiftMask, KEY, toggletag, {.ui = 1 << TAG}},
/* helper for spawning shell commands in the pre dwm-5.0 fashion */
#define CMD(cmd) \
{ \
.v = (const char *[]) { "/bin/sh", "-c", cmd, NULL } \
}
/* commands */
static char dmenumon[2] = "0"; /* component of dmenucmd, manipulated in spawn() */
static const char *dmenucmd[] = {"dmenu_run", "-m", dmenumon, "-fn", dmenufont, "-nb", col_black, "-nf", col_gray3, "-sb", col_black, "-sf", col_green, NULL};
static const char *termcmd[] = {"st", NULL};
static Key keys[] = {
/* modifier key function argument */
{Mod1Mask, XK_F2, spawn, {.v = dmenucmd}},
{Mod1Mask | ControlMask, XK_t, spawn, {.v = termcmd}},
{MODKEY, XK_b, togglebar, {0}},
{MODKEY, XK_j, focusstack, {.i = +1}},
{MODKEY, XK_k, focusstack, {.i = -1}},
{MODKEY, XK_Up, incnmaster, {.i = +1}},
{MODKEY, XK_Down, incnmaster, {.i = -1}},
{MODKEY, XK_Left, setmfact, {.f = -0.05}},
{MODKEY, XK_Right, setmfact, {.f = +0.05}},
{MODKEY, XK_Return, zoom, {0}},
{Mod1Mask, XK_Tab, view, {0}},
{Mod1Mask, XK_F4, killclient, {0}},
{MODKEY, XK_t, setlayout, {.v = &layouts[0]}},
{MODKEY, XK_f, setlayout, {.v = &layouts[1]}},
{MODKEY, XK_m, setlayout, {.v = &layouts[2]}},
{MODKEY, XK_space, setlayout, {0}},
{MODKEY, XK_x, togglefloating, {0}},
{MODKEY, XK_z, resizemouse, {0}},
{Mod1Mask | ControlMask, XK_Down, view, {.ui = ~0}},
{MODKEY, XK_0, tag, {.ui = ~0}},
{Mod1Mask, XK_comma, focusmon, {.i = -1}},
{Mod1Mask, XK_period, focusmon, {.i = +1}},
{Mod1Mask | ControlMask, XK_comma, tagmon, {.i = -1}},
{Mod1Mask | ControlMask, XK_period, tagmon, {.i = +1}},
TAGKEYS(XK_1, 0)
TAGKEYS(XK_2, 1)
TAGKEYS(XK_3, 2)
TAGKEYS(XK_4, 3)
{MODKEY | ControlMask, XK_q, quit, {0}},
{MODKEY, XK_BackSpace, quit, {1}},
{MODKEY | ControlMask, XK_t, spawn, CMD("synclient TouchpadOff=$(synclient -l | grep -c 'TouchpadOff.*=.*0')")},
{ControlMask | ShiftMask, XK_Escape, spawn, CMD("xkill")},
{0, XF86XK_MonBrightnessUp, spawn, CMD("brightnessctl s +1%")},
{0, XF86XK_MonBrightnessDown, spawn, CMD("brightnessctl s 1%-")},
{0, XF86XK_AudioRaiseVolume, spawn, CMD("pactl set-sink-volume 0 +1%")},
{0, XF86XK_AudioLowerVolume, spawn, CMD("pactl set-sink-volume 0 -1%")},
{0, XF86XK_AudioMute, spawn, CMD("pactl set-sink-mute 0 toggle")},
{0, XF86XK_AudioPrev, spawn, CMD("mpctl prev")},
{0, XF86XK_AudioPlay, spawn, CMD("mpctl toggle")},
{0, XF86XK_AudioNext, spawn, CMD("mpctl next")},
{Mod1Mask | ControlMask, XK_l, spawn, CMD("slock xset dpms force off")},
{0, XK_Print, spawn, CMD("imshot")},
{ShiftMask, XK_Print, spawn, CMD("imshot area")},
{Mod1Mask, XK_Print, spawn, CMD("imshot window")},
{0, XF86XK_PowerOff, spawn, CMD("dpower")},
{MODKEY, XK_p, spawn, CMD("passmenu")},
{MODKEY, XK_q, spawn, CMD("qrscanner")},
};
/* button definitions */
/* click can be ClkTagBar, ClkLtSymbol, ClkStatusText, ClkWinTitle, ClkClientWin, or ClkRootWin */
static Button buttons[] = {
/* click event mask button function argument */
{ClkLtSymbol, 0, Button1, setlayout, {0}},
{ClkLtSymbol, 0, Button3, setlayout, {.v = &layouts[2]}},
{ClkClientWin, MODKEY, Button1, movemouse, {0}},
{ClkTagBar, 0, Button1, view, {0}},
{ClkTagBar, 0, Button3, toggleview, {0}},
{ClkTagBar, Mod1Mask, Button1, tag, {0}},
{ClkTagBar, Mod1Mask, Button3, toggletag, {0}},
};
|
robot-dreams/secp256k1-zkp
|
src/modules/ecdsa_adaptor/tests_impl.h
|
#ifndef SECP256K1_MODULE_ECDSA_ADAPTOR_TESTS_H
#define SECP256K1_MODULE_ECDSA_ADAPTOR_TESTS_H
#include "include/secp256k1_ecdsa_adaptor.h"
void rand_scalar(secp256k1_scalar *scalar) {
unsigned char buf32[32];
secp256k1_testrand256(buf32);
secp256k1_scalar_set_b32(scalar, buf32, NULL);
}
void rand_point(secp256k1_ge *point) {
secp256k1_scalar x;
secp256k1_gej pointj;
rand_scalar(&x);
secp256k1_ecmult_gen(&ctx->ecmult_gen_ctx, &pointj, &x);
secp256k1_ge_set_gej(point, &pointj);
}
void dleq_nonce_bitflip(unsigned char **args, size_t n_flip, size_t n_bytes) {
secp256k1_scalar k1, k2;
CHECK(secp256k1_dleq_nonce(&k1, args[0], args[1], args[2], args[3], NULL, args[4]) == 1);
secp256k1_testrand_flip(args[n_flip], n_bytes);
CHECK(secp256k1_dleq_nonce(&k2, args[0], args[1], args[2], args[3], NULL, args[4]) == 1);
CHECK(secp256k1_scalar_eq(&k1, &k2) == 0);
}
void dleq_tests(void) {
secp256k1_scalar s, e, sk, k;
secp256k1_ge gen2, p1, p2;
unsigned char *args[5];
unsigned char sk32[32];
unsigned char gen2_33[33];
unsigned char p1_33[33];
unsigned char p2_33[33];
unsigned char aux_rand[32];
int i;
size_t pubkey_size = 33;
rand_point(&gen2);
rand_scalar(&sk);
secp256k1_dleq_pair(&ctx->ecmult_gen_ctx, &p1, &p2, &sk, &gen2);
CHECK(secp256k1_dleq_prove(ctx, &s, &e, &sk, &gen2, &p1, &p2, NULL, NULL) == 1);
CHECK(secp256k1_dleq_verify(&s, &e, &p1, &gen2, &p2) == 1);
{
secp256k1_scalar tmp;
secp256k1_scalar_set_int(&tmp, 1);
CHECK(secp256k1_dleq_verify(&tmp, &e, &p1, &gen2, &p2) == 0);
CHECK(secp256k1_dleq_verify(&s, &tmp, &p1, &gen2, &p2) == 0);
}
{
secp256k1_ge p_tmp;
rand_point(&p_tmp);
CHECK(secp256k1_dleq_verify(&s, &e, &p_tmp, &gen2, &p2) == 0);
CHECK(secp256k1_dleq_verify(&s, &e, &p1, &p_tmp, &p2) == 0);
CHECK(secp256k1_dleq_verify(&s, &e, &p1, &gen2, &p_tmp) == 0);
}
{
secp256k1_ge p_inf;
secp256k1_ge_set_infinity(&p_inf);
CHECK(secp256k1_dleq_prove(ctx, &s, &e, &sk, &p_inf, &p1, &p2, NULL, NULL) == 0);
CHECK(secp256k1_dleq_prove(ctx, &s, &e, &sk, &gen2, &p_inf, &p2, NULL, NULL) == 0);
CHECK(secp256k1_dleq_prove(ctx, &s, &e, &sk, &gen2, &p1, &p_inf, NULL, NULL) == 0);
}
/* Nonce tests */
secp256k1_scalar_get_b32(sk32, &sk);
CHECK(secp256k1_eckey_pubkey_serialize(&gen2, gen2_33, &pubkey_size, 1));
CHECK(secp256k1_eckey_pubkey_serialize(&p1, p1_33, &pubkey_size, 1));
CHECK(secp256k1_eckey_pubkey_serialize(&p2, p2_33, &pubkey_size, 1));
CHECK(secp256k1_dleq_nonce(&k, sk32, gen2_33, p1_33, p2_33, NULL, NULL) == 1);
secp256k1_rfc6979_hmac_sha256_generate(&secp256k1_test_rng, sk32, sizeof(sk32));
secp256k1_rfc6979_hmac_sha256_generate(&secp256k1_test_rng, gen2_33, sizeof(gen2_33));
secp256k1_rfc6979_hmac_sha256_generate(&secp256k1_test_rng, p1_33, sizeof(p1_33));
secp256k1_rfc6979_hmac_sha256_generate(&secp256k1_test_rng, p2_33, sizeof(p2_33));
secp256k1_rfc6979_hmac_sha256_generate(&secp256k1_test_rng, aux_rand, sizeof(aux_rand));
/* Check that a bitflip in an argument results in different nonces. */
args[0] = sk32;
args[1] = gen2_33;
args[2] = p1_33;
args[3] = p2_33;
args[4] = aux_rand;
for (i = 0; i < count; i++) {
dleq_nonce_bitflip(args, 0, sizeof(sk32));
dleq_nonce_bitflip(args, 1, sizeof(gen2_33));
dleq_nonce_bitflip(args, 2, sizeof(p1_33));
/* Flip p2 */
dleq_nonce_bitflip(args, 3, sizeof(p2_33));
/* Flip p2 again */
dleq_nonce_bitflip(args, 3, sizeof(p2_33));
dleq_nonce_bitflip(args, 4, sizeof(aux_rand));
}
/* NULL aux_rand argument is allowed. */
CHECK(secp256k1_dleq_nonce(&k, sk32, gen2_33, p1_33, p2_33, NULL, NULL) == 1);
}
void rand_flip_bit(unsigned char *array, size_t n) {
array[secp256k1_testrand_int(n)] ^= 1 << secp256k1_testrand_int(8);
}
/* Helper function for test_ecdsa_adaptor_spec_vectors
* Checks that the adaptor signature is valid for the public and encryption keys. */
void test_ecdsa_adaptor_spec_vectors_check_verify(const unsigned char *adaptor_sig162, const unsigned char *msg32, const unsigned char *pubkey33, const unsigned char *encryption_key33, int expected) {
secp256k1_pubkey pubkey;
secp256k1_ge pubkey_ge;
secp256k1_pubkey encryption_key;
secp256k1_ge encryption_key_ge;
CHECK(secp256k1_eckey_pubkey_parse(&encryption_key_ge, encryption_key33, 33) == 1);
secp256k1_pubkey_save(&encryption_key, &encryption_key_ge);
CHECK(secp256k1_eckey_pubkey_parse(&pubkey_ge, pubkey33, 33) == 1);
secp256k1_pubkey_save(&pubkey, &pubkey_ge);
CHECK(expected == secp256k1_ecdsa_adaptor_verify(ctx, adaptor_sig162, &pubkey, msg32, &encryption_key));
}
/* Helper function for test_ecdsa_adaptor_spec_vectors
* Checks that the signature can be decrypted from the adaptor signature and the decryption key. */
void test_ecdsa_adaptor_spec_vectors_check_decrypt(const unsigned char *adaptor_sig162, const unsigned char *decryption_key32, const unsigned char *signature64, int expected) {
unsigned char signature[64];
secp256k1_ecdsa_signature s;
CHECK(secp256k1_ecdsa_adaptor_decrypt(ctx, &s, decryption_key32, adaptor_sig162) == 1);
CHECK(secp256k1_ecdsa_signature_serialize_compact(ctx, signature, &s) == 1);
CHECK(expected == !(secp256k1_memcmp_var(signature, signature64, 64)));
}
/* Helper function for test_ecdsa_adaptor_spec_vectors
* Checks that the decryption key can be recovered from the adaptor signature, encryption key, and the signature. */
void test_ecdsa_adaptor_spec_vectors_check_recover(const unsigned char *adaptor_sig162, const unsigned char *encryption_key33, const unsigned char *decryption_key32, const unsigned char *signature64, int expected) {
unsigned char deckey32[32] = { 0 };
secp256k1_ecdsa_signature sig;
secp256k1_pubkey encryption_key;
secp256k1_ge encryption_key_ge;
CHECK(secp256k1_eckey_pubkey_parse(&encryption_key_ge, encryption_key33, 33) == 1);
secp256k1_pubkey_save(&encryption_key, &encryption_key_ge);
CHECK(secp256k1_ecdsa_signature_parse_compact(ctx, &sig, signature64) == 1);
CHECK(expected == secp256k1_ecdsa_adaptor_recover(ctx, deckey32, &sig, adaptor_sig162, &encryption_key));
if (decryption_key32 != NULL) {
CHECK(expected == !(secp256k1_memcmp_var(deckey32, decryption_key32, 32)));
}
}
/* Helper function for test_ecdsa_adaptor_spec_vectors
* Checks deserialization and serialization. */
void test_ecdsa_adaptor_spec_vectors_check_serialization(const unsigned char *adaptor_sig162, int expected) {
unsigned char buf[162];
secp256k1_scalar dleq_proof_s, dleq_proof_e;
secp256k1_ge r, rp;
secp256k1_scalar sp;
secp256k1_scalar sigr;
CHECK(expected == secp256k1_ecdsa_adaptor_sig_deserialize(&r, &sigr, &rp, &sp, &dleq_proof_e, &dleq_proof_s, adaptor_sig162));
if (expected == 1) {
CHECK(secp256k1_ecdsa_adaptor_sig_serialize(buf, &r, &rp, &sp, &dleq_proof_e, &dleq_proof_s) == 1);
CHECK(secp256k1_memcmp_var(buf, adaptor_sig162, 162) == 0);
}
}
/* Test vectors according to ECDSA adaptor signature spec. See
* https://github.com/discreetlogcontracts/dlcspecs/blob/596a177375932a47306f07e7385f398f52519a83/test/ecdsa_adaptor.json. */
void test_ecdsa_adaptor_spec_vectors(void) {
{
/* Test vector 0 */
/* kind: verification test */
/* plain valid adaptor signature */
const unsigned char adaptor_sig[162] = {
0x03, 0x42, 0x4d, 0x14, 0xa5, 0x47, 0x1c, 0x04,
0x8a, 0xb8, 0x7b, 0x3b, 0x83, 0xf6, 0x08, 0x5d,
0x12, 0x5d, 0x58, 0x64, 0x24, 0x9a, 0xe4, 0x29,
0x7a, 0x57, 0xc8, 0x4e, 0x74, 0x71, 0x0b, 0xb6,
0x73, 0x02, 0x23, 0xf3, 0x25, 0x04, 0x2f, 0xce,
0x53, 0x5d, 0x04, 0x0f, 0xee, 0x52, 0xec, 0x13,
0x23, 0x1b, 0xf7, 0x09, 0xcc, 0xd8, 0x42, 0x33,
0xc6, 0x94, 0x4b, 0x90, 0x31, 0x7e, 0x62, 0x52,
0x8b, 0x25, 0x27, 0xdf, 0xf9, 0xd6, 0x59, 0xa9,
0x6d, 0xb4, 0xc9, 0x9f, 0x97, 0x50, 0x16, 0x83,
0x08, 0x63, 0x3c, 0x18, 0x67, 0xb7, 0x0f, 0x3a,
0x18, 0xfb, 0x0f, 0x45, 0x39, 0xa1, 0xae, 0xce,
0xdc, 0xd1, 0xfc, 0x01, 0x48, 0xfc, 0x22, 0xf3,
0x6b, 0x63, 0x03, 0x08, 0x3e, 0xce, 0x3f, 0x87,
0x2b, 0x18, 0xe3, 0x5d, 0x36, 0x8b, 0x39, 0x58,
0xef, 0xe5, 0xfb, 0x08, 0x1f, 0x77, 0x16, 0x73,
0x6c, 0xcb, 0x59, 0x8d, 0x26, 0x9a, 0xa3, 0x08,
0x4d, 0x57, 0xe1, 0x85, 0x5e, 0x1e, 0xa9, 0xa4,
0x5e, 0xfc, 0x10, 0x46, 0x3b, 0xbf, 0x32, 0xae,
0x37, 0x80, 0x29, 0xf5, 0x76, 0x3c, 0xeb, 0x40,
0x17, 0x3f
};
const unsigned char message_hash[32] = {
0x81, 0x31, 0xe6, 0xf4, 0xb4, 0x57, 0x54, 0xf2,
0xc9, 0x0b, 0xd0, 0x66, 0x88, 0xce, 0xea, 0xbc,
0x0c, 0x45, 0x05, 0x54, 0x60, 0x72, 0x99, 0x28,
0xb4, 0xee, 0xcf, 0x11, 0x02, 0x6a, 0x9e, 0x2d
};
const unsigned char pubkey[33] = {
0x03, 0x5b, 0xe5, 0xe9, 0x47, 0x82, 0x09, 0x67,
0x4a, 0x96, 0xe6, 0x0f, 0x1f, 0x03, 0x7f, 0x61,
0x76, 0x54, 0x0f, 0xd0, 0x01, 0xfa, 0x1d, 0x64,
0x69, 0x47, 0x70, 0xc5, 0x6a, 0x77, 0x09, 0xc4,
0x2c
};
const unsigned char encryption_key[33] = {
0x02, 0xc2, 0x66, 0x2c, 0x97, 0x48, 0x8b, 0x07,
0xb6, 0xe8, 0x19, 0x12, 0x4b, 0x89, 0x89, 0x84,
0x92, 0x06, 0x33, 0x4a, 0x4c, 0x2f, 0xbd, 0xf6,
0x91, 0xf7, 0xb3, 0x4d, 0x2b, 0x16, 0xe9, 0xc2,
0x93
};
const unsigned char decryption_key[32] = {
0x0b, 0x2a, 0xba, 0x63, 0xb8, 0x85, 0xa0, 0xf0,
0xe9, 0x6f, 0xa0, 0xf3, 0x03, 0x92, 0x0c, 0x7f,
0xb7, 0x43, 0x1d, 0xdf, 0xa9, 0x43, 0x76, 0xad,
0x94, 0xd9, 0x69, 0xfb, 0xf4, 0x10, 0x9d, 0xc8
};
const unsigned char signature[64] = {
0x42, 0x4d, 0x14, 0xa5, 0x47, 0x1c, 0x04, 0x8a,
0xb8, 0x7b, 0x3b, 0x83, 0xf6, 0x08, 0x5d, 0x12,
0x5d, 0x58, 0x64, 0x24, 0x9a, 0xe4, 0x29, 0x7a,
0x57, 0xc8, 0x4e, 0x74, 0x71, 0x0b, 0xb6, 0x73,
0x29, 0xe8, 0x0e, 0x0e, 0xe6, 0x0e, 0x57, 0xaf,
0x3e, 0x62, 0x5b, 0xba, 0xe1, 0x67, 0x2b, 0x1e,
0xca, 0xa5, 0x8e, 0xff, 0xe6, 0x13, 0x42, 0x6b,
0x02, 0x4f, 0xa1, 0x62, 0x1d, 0x90, 0x33, 0x94
};
test_ecdsa_adaptor_spec_vectors_check_verify(adaptor_sig, message_hash, pubkey, encryption_key, 1);
test_ecdsa_adaptor_spec_vectors_check_decrypt(adaptor_sig, decryption_key, signature, 1);
test_ecdsa_adaptor_spec_vectors_check_recover(adaptor_sig, encryption_key, decryption_key, signature, 1);
}
{
/* Test vector 1 */
/* verification test */
/* the decrypted signature is high so it must be negated first
* AND the extracted decryption key must be negated */
const unsigned char adaptor_sig[162] = {
0x03, 0x60, 0x35, 0xc8, 0x98, 0x60, 0xec, 0x62,
0xad, 0x15, 0x3f, 0x69, 0xb5, 0xb3, 0x07, 0x7b,
0xcd, 0x08, 0xfb, 0xb0, 0xd2, 0x8d, 0xc7, 0xf7,
0xf6, 0xdf, 0x4a, 0x05, 0xcc, 0xa3, 0x54, 0x55,
0xbe, 0x03, 0x70, 0x43, 0xb6, 0x3c, 0x56, 0xf6,
0x31, 0x7d, 0x99, 0x28, 0xe8, 0xf9, 0x10, 0x07,
0x33, 0x57, 0x48, 0xc4, 0x98, 0x24, 0x22, 0x0d,
0xb1, 0x4a, 0xd1, 0x0d, 0x80, 0xa5, 0xd0, 0x0a,
0x96, 0x54, 0xaf, 0x09, 0x96, 0xc1, 0x82, 0x4c,
0x64, 0xc9, 0x0b, 0x95, 0x1b, 0xb2, 0x73, 0x4a,
0xae, 0xcf, 0x78, 0xd4, 0xb3, 0x61, 0x31, 0xa4,
0x72, 0x38, 0xc3, 0xfa, 0x2b, 0xa2, 0x5e, 0x2c,
0xed, 0x54, 0x25, 0x5b, 0x06, 0xdf, 0x69, 0x6d,
0xe1, 0x48, 0x3c, 0x37, 0x67, 0x24, 0x2a, 0x37,
0x28, 0x82, 0x6e, 0x05, 0xf7, 0x9e, 0x39, 0x81,
0xe1, 0x25, 0x53, 0x35, 0x5b, 0xba, 0x8a, 0x01,
0x31, 0xcd, 0x37, 0x0e, 0x63, 0xe3, 0xda, 0x73,
0x10, 0x6f, 0x63, 0x85, 0x76, 0xa5, 0xaa, 0xb0,
0xea, 0x6d, 0x45, 0xc0, 0x42, 0x57, 0x4c, 0x0c,
0x8d, 0x0b, 0x14, 0xb8, 0xc7, 0xc0, 0x1c, 0xfe,
0x90, 0x72
};
const unsigned char message_hash[32] = {
0x81, 0x31, 0xe6, 0xf4, 0xb4, 0x57, 0x54, 0xf2,
0xc9, 0x0b, 0xd0, 0x66, 0x88, 0xce, 0xea, 0xbc,
0x0c, 0x45, 0x05, 0x54, 0x60, 0x72, 0x99, 0x28,
0xb4, 0xee, 0xcf, 0x11, 0x02, 0x6a, 0x9e, 0x2d
};
const unsigned char pubkey[33] = {
0x03, 0x5b, 0xe5, 0xe9, 0x47, 0x82, 0x09, 0x67,
0x4a, 0x96, 0xe6, 0x0f, 0x1f, 0x03, 0x7f, 0x61,
0x76, 0x54, 0x0f, 0xd0, 0x01, 0xfa, 0x1d, 0x64,
0x69, 0x47, 0x70, 0xc5, 0x6a, 0x77, 0x09, 0xc4,
0x2c
};
const unsigned char encryption_key[33] = {
0x02, 0x4e, 0xee, 0x18, 0xbe, 0x9a, 0x5a, 0x52,
0x24, 0x00, 0x0f, 0x91, 0x6c, 0x80, 0xb3, 0x93,
0x44, 0x79, 0x89, 0xe7, 0x19, 0x4b, 0xc0, 0xb0,
0xf1, 0xad, 0x7a, 0x03, 0x36, 0x97, 0x02, 0xbb,
0x51
};
const unsigned char decryption_key[32] = {
0xdb, 0x2d, 0xeb, 0xdd, 0xb0, 0x02, 0x47, 0x3a,
0x00, 0x1d, 0xd7, 0x0b, 0x06, 0xf6, 0xc9, 0x7b,
0xdc, 0xd1, 0xc4, 0x6b, 0xa1, 0x00, 0x12, 0x37,
0xfe, 0x0e, 0xe1, 0xae, 0xff, 0xb2, 0xb6, 0xc4
};
const unsigned char signature[64] = {
0x60, 0x35, 0xc8, 0x98, 0x60, 0xec, 0x62, 0xad,
0x15, 0x3f, 0x69, 0xb5, 0xb3, 0x07, 0x7b, 0xcd,
0x08, 0xfb, 0xb0, 0xd2, 0x8d, 0xc7, 0xf7, 0xf6,
0xdf, 0x4a, 0x05, 0xcc, 0xa3, 0x54, 0x55, 0xbe,
0x4c, 0xea, 0xcf, 0x92, 0x15, 0x46, 0xc0, 0x3d,
0xd1, 0xbe, 0x59, 0x67, 0x23, 0xad, 0x1e, 0x76,
0x91, 0xbd, 0xac, 0x73, 0xd8, 0x8c, 0xc3, 0x6c,
0x42, 0x1c, 0x5e, 0x7f, 0x08, 0x38, 0x43, 0x05
};
test_ecdsa_adaptor_spec_vectors_check_verify(adaptor_sig, message_hash, pubkey, encryption_key, 1);
test_ecdsa_adaptor_spec_vectors_check_decrypt(adaptor_sig, decryption_key, signature, 1);
test_ecdsa_adaptor_spec_vectors_check_recover(adaptor_sig, encryption_key, decryption_key, signature, 1);
}
{
/* Test vector 2 */
/* verification test */
/* proof is wrong */
const unsigned char adaptor_sig[162] = {
0x03, 0xf9, 0x4d, 0xca, 0x20, 0x6d, 0x75, 0x82,
0xc0, 0x15, 0xfb, 0x9b, 0xff, 0xe4, 0xe4, 0x3b,
0x14, 0x59, 0x1b, 0x30, 0xef, 0x7d, 0x2b, 0x46,
0x4d, 0x10, 0x3e, 0xc5, 0xe1, 0x16, 0x59, 0x5d,
0xba, 0x03, 0x12, 0x7f, 0x8a, 0xc3, 0x53, 0x3d,
0x24, 0x92, 0x80, 0x33, 0x24, 0x74, 0x33, 0x90,
0x00, 0x92, 0x2e, 0xb6, 0xa5, 0x8e, 0x3b, 0x9b,
0xf4, 0xfc, 0x7e, 0x01, 0xe4, 0xb4, 0xdf, 0x2b,
0x7a, 0x41, 0x00, 0xa1, 0xe0, 0x89, 0xf1, 0x6e,
0x5d, 0x70, 0xbb, 0x89, 0xf9, 0x61, 0x51, 0x6f,
0x1d, 0xe0, 0x68, 0x4c, 0xc7, 0x9d, 0xb9, 0x78,
0x49, 0x5d, 0xf2, 0xf3, 0x99, 0xb0, 0xd0, 0x1e,
0xd7, 0x24, 0x0f, 0xa6, 0xe3, 0x25, 0x2a, 0xed,
0xb5, 0x8b, 0xdc, 0x6b, 0x58, 0x77, 0xb0, 0xc6,
0x02, 0x62, 0x8a, 0x23, 0x5d, 0xd1, 0xcc, 0xae,
0xbd, 0xdd, 0xcb, 0xe9, 0x61, 0x98, 0xc0, 0xc2,
0x1b, 0xea, 0xd7, 0xb0, 0x5f, 0x42, 0x3b, 0x67,
0x3d, 0x14, 0xd2, 0x06, 0xfa, 0x15, 0x07, 0xb2,
0xdb, 0xe2, 0x72, 0x2a, 0xf7, 0x92, 0xb8, 0xc2,
0x66, 0xfc, 0x25, 0xa2, 0xd9, 0x01, 0xd7, 0xe2,
0xc3, 0x35
};
const unsigned char message_hash[32] = {
0x81, 0x31, 0xe6, 0xf4, 0xb4, 0x57, 0x54, 0xf2,
0xc9, 0x0b, 0xd0, 0x66, 0x88, 0xce, 0xea, 0xbc,
0x0c, 0x45, 0x05, 0x54, 0x60, 0x72, 0x99, 0x28,
0xb4, 0xee, 0xcf, 0x11, 0x02, 0x6a, 0x9e, 0x2d
};
const unsigned char pubkey[33] = {
0x03, 0x5b, 0xe5, 0xe9, 0x47, 0x82, 0x09, 0x67,
0x4a, 0x96, 0xe6, 0x0f, 0x1f, 0x03, 0x7f, 0x61,
0x76, 0x54, 0x0f, 0xd0, 0x01, 0xfa, 0x1d, 0x64,
0x69, 0x47, 0x70, 0xc5, 0x6a, 0x77, 0x09, 0xc4,
0x2c
};
const unsigned char encryption_key[33] = {
0x02, 0x14, 0xcc, 0xb7, 0x56, 0x24, 0x9a, 0xd6,
0xe7, 0x33, 0xc8, 0x02, 0x85, 0xea, 0x7a, 0xc2,
0xee, 0x12, 0xff, 0xeb, 0xbc, 0xee, 0x4e, 0x55,
0x6e, 0x68, 0x10, 0x79, 0x3a, 0x60, 0xc4, 0x5a,
0xd4
};
const unsigned char decryption_key[32] = {
0x1d, 0xfc, 0xfc, 0x08, 0x80, 0xe7, 0x25, 0x09,
0x76, 0x8a, 0xb4, 0x6f, 0x25, 0x45, 0xb3, 0x31,
0x68, 0xb8, 0xb8, 0xdf, 0x8e, 0x4f, 0x5f, 0xeb,
0x50, 0x59, 0xaa, 0x37, 0x50, 0xee, 0x59, 0xd0
};
const unsigned char signature[64] = {
0x42, 0x4d, 0x14, 0xa5, 0x47, 0x1c, 0x04, 0x8a,
0xb8, 0x7b, 0x3b, 0x83, 0xf6, 0x08, 0x5d, 0x12,
0x5d, 0x58, 0x64, 0x24, 0x9a, 0xe4, 0x29, 0x7a,
0x57, 0xc8, 0x4e, 0x74, 0x71, 0x0b, 0xb6, 0x73,
0x29, 0xe8, 0x0e, 0x0e, 0xe6, 0x0e, 0x57, 0xaf,
0x3e, 0x62, 0x5b, 0xba, 0xe1, 0x67, 0x2b, 0x1e,
0xca, 0xa5, 0x8e, 0xff, 0xe6, 0x13, 0x42, 0x6b,
0x02, 0x4f, 0xa1, 0x62, 0x1d, 0x90, 0x33, 0x94
};
test_ecdsa_adaptor_spec_vectors_check_verify(adaptor_sig, message_hash, pubkey, encryption_key, 0);
test_ecdsa_adaptor_spec_vectors_check_decrypt(adaptor_sig, decryption_key, signature, 0);
test_ecdsa_adaptor_spec_vectors_check_recover(adaptor_sig, encryption_key, decryption_key, signature, 0);
}
{
/* Test vector 3 */
/* recovery test */
/* plain recovery */
const unsigned char adaptor_sig[162] = {
0x03, 0xf2, 0xdb, 0x6e, 0x9e, 0xd3, 0x30, 0x92,
0xcc, 0x0b, 0x89, 0x8f, 0xd6, 0xb2, 0x82, 0xe9,
0x9b, 0xda, 0xec, 0xcb, 0x3d, 0xe8, 0x5c, 0x2d,
0x25, 0x12, 0xd8, 0xd5, 0x07, 0xf9, 0xab, 0xab,
0x29, 0x02, 0x10, 0xc0, 0x1b, 0x5b, 0xed, 0x70,
0x94, 0xa1, 0x26, 0x64, 0xae, 0xaa, 0xb3, 0x40,
0x2d, 0x87, 0x09, 0xa8, 0xf3, 0x62, 0xb1, 0x40,
0x32, 0x8d, 0x1b, 0x36, 0xdd, 0x7c, 0xb4, 0x20,
0xd0, 0x2f, 0xb6, 0x6b, 0x12, 0x30, 0xd6, 0x1c,
0x16, 0xd0, 0xcd, 0x0a, 0x2a, 0x02, 0x24, 0x6d,
0x5a, 0xc7, 0x84, 0x8d, 0xcd, 0x6f, 0x04, 0xfe,
0x62, 0x70, 0x53, 0xcd, 0x3c, 0x70, 0x15, 0xa7,
0xd4, 0xaa, 0x6a, 0xc2, 0xb0, 0x43, 0x47, 0x34,
0x8b, 0xd6, 0x7d, 0xa4, 0x3b, 0xe8, 0x72, 0x25,
0x15, 0xd9, 0x9a, 0x79, 0x85, 0xfb, 0xfa, 0x66,
0xf0, 0x36, 0x5c, 0x70, 0x1d, 0xe7, 0x6f, 0xf0,
0x40, 0x0d, 0xff, 0xdc, 0x9f, 0xa8, 0x4d, 0xdd,
0xf4, 0x13, 0xa7, 0x29, 0x82, 0x3b, 0x16, 0xaf,
0x60, 0xaa, 0x63, 0x61, 0xbc, 0x32, 0xe7, 0xcf,
0xd6, 0x70, 0x1e, 0x32, 0x95, 0x7c, 0x72, 0xac,
0xe6, 0x7b
};
const unsigned char encryption_key[33] = {
0x02, 0x7e, 0xe4, 0xf8, 0x99, 0xbc, 0x9c, 0x5f,
0x2b, 0x62, 0x6f, 0xa1, 0xa9, 0xb3, 0x7c, 0xe2,
0x91, 0xc0, 0x38, 0x8b, 0x52, 0x27, 0xe9, 0x0b,
0x0f, 0xd8, 0xf4, 0xfa, 0x57, 0x61, 0x64, 0xed,
0xe7
};
const unsigned char decryption_key[32] = {
0x9c, 0xf3, 0xea, 0x9b, 0xe5, 0x94, 0x36, 0x6b,
0x78, 0xc4, 0x57, 0x16, 0x29, 0x08, 0xaf, 0x3c,
0x2e, 0xa1, 0x77, 0x05, 0x81, 0x77, 0xe9, 0xc6,
0xbf, 0x99, 0x04, 0x79, 0x27, 0x77, 0x3a, 0x06
};
const unsigned char signature[64] = {
0xf2, 0xdb, 0x6e, 0x9e, 0xd3, 0x30, 0x92, 0xcc,
0x0b, 0x89, 0x8f, 0xd6, 0xb2, 0x82, 0xe9, 0x9b,
0xda, 0xec, 0xcb, 0x3d, 0xe8, 0x5c, 0x2d, 0x25,
0x12, 0xd8, 0xd5, 0x07, 0xf9, 0xab, 0xab, 0x29,
0x21, 0x81, 0x1f, 0xe7, 0xb5, 0x3b, 0xec, 0xf3,
0xb7, 0xaf, 0xfa, 0x94, 0x42, 0xab, 0xaa, 0x93,
0xc0, 0xab, 0x8a, 0x8e, 0x45, 0xcd, 0x7e, 0xe2,
0xea, 0x8d, 0x25, 0x8b, 0xfc, 0x25, 0xd4, 0x64
};
test_ecdsa_adaptor_spec_vectors_check_decrypt(adaptor_sig, decryption_key, signature, 1);
test_ecdsa_adaptor_spec_vectors_check_recover(adaptor_sig, encryption_key, decryption_key, signature, 1);
}
{
/* Test vector 4 */
/* recovery test */
/* the R value of the signature does not match */
const unsigned char adaptor_sig[162] = {
0x03, 0xaa, 0x86, 0xd7, 0x80, 0x59, 0xa9, 0x10,
0x59, 0xc2, 0x9e, 0xc1, 0xa7, 0x57, 0xc4, 0xdc,
0x02, 0x9f, 0xf6, 0x36, 0xa1, 0xe6, 0xc1, 0x14,
0x2f, 0xef, 0xe1, 0xe9, 0xd7, 0x33, 0x96, 0x17,
0xc0, 0x03, 0xa8, 0x15, 0x3e, 0x50, 0xc0, 0xc8,
0x57, 0x4a, 0x38, 0xd3, 0x89, 0xe6, 0x1b, 0xbb,
0x0b, 0x58, 0x15, 0x16, 0x9e, 0x06, 0x09, 0x24,
0xe4, 0xb5, 0xf2, 0xe7, 0x8f, 0xf1, 0x3a, 0xa7,
0xad, 0x85, 0x8e, 0x0c, 0x27, 0xc4, 0xb9, 0xee,
0xd9, 0xd6, 0x05, 0x21, 0xb3, 0xf5, 0x4f, 0xf8,
0x3c, 0xa4, 0x77, 0x4b, 0xe5, 0xfb, 0x3a, 0x68,
0x0f, 0x82, 0x0a, 0x35, 0xe8, 0x84, 0x0f, 0x4a,
0xaf, 0x2d, 0xe8, 0x8e, 0x7c, 0x5c, 0xff, 0x38,
0xa3, 0x7b, 0x78, 0x72, 0x59, 0x04, 0xef, 0x97,
0xbb, 0x82, 0x34, 0x13, 0x28, 0xd5, 0x59, 0x87,
0x01, 0x9b, 0xd3, 0x8a, 0xe1, 0x74, 0x5e, 0x3e,
0xfe, 0x0f, 0x8e, 0xa8, 0xbd, 0xfe, 0xde, 0x0d,
0x37, 0x8f, 0xc1, 0xf9, 0x6e, 0x94, 0x4a, 0x75,
0x05, 0x24, 0x9f, 0x41, 0xe9, 0x37, 0x81, 0x50,
0x9e, 0xe0, 0xba, 0xde, 0x77, 0x29, 0x0d, 0x39,
0xcd, 0x12
};
const unsigned char encryption_key[33] = {
0x03, 0x51, 0x76, 0xd2, 0x41, 0x29, 0x74, 0x1b,
0x0f, 0xca, 0xa5, 0xfd, 0x67, 0x50, 0x72, 0x7c,
0xe3, 0x08, 0x60, 0x44, 0x7e, 0x0a, 0x92, 0xc9,
0xeb, 0xeb, 0xde, 0xb7, 0xc3, 0xf9, 0x39, 0x95,
0xed
};
const unsigned char signature[64] = {
0xf7, 0xf7, 0xfe, 0x6b, 0xd0, 0x56, 0xfc, 0x4a,
0xbd, 0x70, 0xd3, 0x35, 0xf7, 0x2d, 0x0a, 0xa1,
0xe8, 0x40, 0x6b, 0xba, 0x68, 0xf3, 0xe5, 0x79,
0xe4, 0x78, 0x94, 0x75, 0x32, 0x35, 0x64, 0xa4,
0x52, 0xc4, 0x61, 0x76, 0xc7, 0xfb, 0x40, 0xaa,
0x37, 0xd5, 0x65, 0x13, 0x41, 0xf5, 0x56, 0x97,
0xda, 0xb2, 0x7d, 0x84, 0xa2, 0x13, 0xb3, 0x0c,
0x93, 0x01, 0x1a, 0x77, 0x90, 0xba, 0xce, 0x8c
};
test_ecdsa_adaptor_spec_vectors_check_recover(adaptor_sig, encryption_key, NULL, signature, 0);
}
{
/* Test vector 5 */
/* recovery test */
/* recovery from high s signature */
const unsigned char adaptor_sig[162] = {
0x03, 0x2c, 0x63, 0x7c, 0xd7, 0x97, 0xdd, 0x8c,
0x2c, 0xe2, 0x61, 0x90, 0x7e, 0xd4, 0x3e, 0x82,
0xd6, 0xd1, 0xa4, 0x8c, 0xba, 0xbb, 0xbe, 0xce,
0x80, 0x11, 0x33, 0xdd, 0x8d, 0x70, 0xa0, 0x1b,
0x14, 0x03, 0xeb, 0x61, 0x5a, 0x3e, 0x59, 0xb1,
0xcb, 0xbf, 0x4f, 0x87, 0xac, 0xaf, 0x64, 0x5b,
0xe1, 0xed, 0xa3, 0x2a, 0x06, 0x66, 0x11, 0xf3,
0x5d, 0xd5, 0x55, 0x78, 0x02, 0x80, 0x2b, 0x14,
0xb1, 0x9c, 0x81, 0xc0, 0x4c, 0x3f, 0xef, 0xac,
0x57, 0x83, 0xb2, 0x07, 0x7b, 0xd4, 0x3f, 0xa0,
0xa3, 0x9a, 0xb8, 0xa6, 0x4d, 0x4d, 0x78, 0x33,
0x2a, 0x5d, 0x62, 0x1e, 0xa2, 0x3e, 0xca, 0x46,
0xbc, 0x01, 0x10, 0x11, 0xab, 0x82, 0xdd, 0xa6,
0xde, 0xb8, 0x56, 0x99, 0xf5, 0x08, 0x74, 0x4d,
0x70, 0xd4, 0x13, 0x4b, 0xea, 0x03, 0xf7, 0x84,
0xd2, 0x85, 0xb5, 0xc6, 0xc1, 0x5a, 0x56, 0xe4,
0xe1, 0xfa, 0xb4, 0xbc, 0x35, 0x6a, 0xbb, 0xde,
0xbb, 0x3b, 0x8f, 0xe1, 0xe5, 0x5e, 0x6d, 0xd6,
0xd2, 0xa9, 0xea, 0x45, 0x7e, 0x91, 0xb2, 0xe6,
0x64, 0x2f, 0xae, 0x69, 0xf9, 0xdb, 0xb5, 0x25,
0x88, 0x54
};
const unsigned char encryption_key[33] = {
0x02, 0x04, 0x25, 0x37, 0xe9, 0x13, 0xad, 0x74,
0xc4, 0xbb, 0xd8, 0xda, 0x96, 0x07, 0xad, 0x3b,
0x9c, 0xb2, 0x97, 0xd0, 0x8e, 0x01, 0x4a, 0xfc,
0x51, 0x13, 0x30, 0x83, 0xf1, 0xbd, 0x68, 0x7a,
0x62
};
const unsigned char decryption_key[32] = {
0x32, 0x47, 0x19, 0xb5, 0x1f, 0xf2, 0x47, 0x4c,
0x94, 0x38, 0xeb, 0x76, 0x49, 0x4b, 0x0d, 0xc0,
0xbc, 0xce, 0xeb, 0x52, 0x9f, 0x0a, 0x54, 0x28,
0xfd, 0x19, 0x8a, 0xd8, 0xf8, 0x86, 0xe9, 0x9c
};
const unsigned char signature[64] = {
0x2c, 0x63, 0x7c, 0xd7, 0x97, 0xdd, 0x8c, 0x2c,
0xe2, 0x61, 0x90, 0x7e, 0xd4, 0x3e, 0x82, 0xd6,
0xd1, 0xa4, 0x8c, 0xba, 0xbb, 0xbe, 0xce, 0x80,
0x11, 0x33, 0xdd, 0x8d, 0x70, 0xa0, 0x1b, 0x14,
0xb5, 0xf2, 0x43, 0x21, 0xf5, 0x50, 0xb7, 0xb9,
0xdd, 0x06, 0xee, 0x4f, 0xcf, 0xd8, 0x2b, 0xda,
0xd8, 0xb1, 0x42, 0xff, 0x93, 0xa7, 0x90, 0xcc,
0x4d, 0x9f, 0x79, 0x62, 0xb3, 0x8c, 0x6a, 0x3b
};
test_ecdsa_adaptor_spec_vectors_check_decrypt(adaptor_sig, decryption_key, signature, 0);
test_ecdsa_adaptor_spec_vectors_check_recover(adaptor_sig, encryption_key, decryption_key, signature, 1);
}
{
/* Test vector 6 */
/* serialization test */
const unsigned char adaptor_sig[162] = {
0x03, 0xe6, 0xd5, 0x1d, 0xa7, 0xbc, 0x2b, 0xf2,
0x4c, 0xf9, 0xdf, 0xd9, 0xac, 0xc6, 0xc4, 0xf0,
0xa3, 0xe7, 0x4d, 0x8a, 0x62, 0x73, 0xee, 0x5a,
0x57, 0x3e, 0xd6, 0x81, 0x8e, 0x30, 0x95, 0xb6,
0x09, 0x03, 0xf3, 0x3b, 0xc9, 0x8f, 0x9d, 0x2e,
0xa3, 0x51, 0x1f, 0x2e, 0x24, 0xf3, 0x35, 0x85,
0x57, 0xc8, 0x15, 0xab, 0xd7, 0x71, 0x3c, 0x93,
0x18, 0xaf, 0x9f, 0x4d, 0xfa, 0xb4, 0x44, 0x18,
0x98, 0xec, 0xd6, 0x19, 0xac, 0xb1, 0xcb, 0x75,
0xc1, 0xa5, 0x94, 0x6f, 0xba, 0xf7, 0x16, 0xd2,
0x27, 0x19, 0x9a, 0x64, 0x79, 0xa6, 0x78, 0xd1,
0x0a, 0x6d, 0x95, 0x51, 0x2d, 0x67, 0x4f, 0xb7,
0x70, 0x3d, 0x85, 0xb5, 0x89, 0x80, 0xb8, 0xe6,
0xc5, 0x4b, 0xd2, 0x06, 0x16, 0xbd, 0xb9, 0x46,
0x1d, 0xcc, 0xd8, 0xee, 0xbb, 0x7d, 0x7e, 0x7c,
0x83, 0xa9, 0x14, 0x52, 0xcc, 0x20, 0xed, 0xf5,
0x3b, 0xe5, 0xb0, 0xfe, 0x0d, 0xb4, 0x4d, 0xdd,
0xaa, 0xaf, 0xbe, 0x73, 0x76, 0x78, 0xc6, 0x84,
0xb6, 0xe8, 0x9b, 0x9b, 0x4b, 0x67, 0x9b, 0x18,
0x55, 0xaa, 0x6e, 0xd6, 0x44, 0x49, 0x8b, 0x89,
0xc9, 0x18
};
test_ecdsa_adaptor_spec_vectors_check_serialization(adaptor_sig, 1);
}
{
/* Test vector 7 */
/* serialization test */
/* R can be above curve order */
const unsigned char adaptor_sig[162] = {
0x03, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xfe, 0xff, 0xff, 0xfc,
0x2c, 0x03, 0xf3, 0x3b, 0xc9, 0x8f, 0x9d, 0x2e,
0xa3, 0x51, 0x1f, 0x2e, 0x24, 0xf3, 0x35, 0x85,
0x57, 0xc8, 0x15, 0xab, 0xd7, 0x71, 0x3c, 0x93,
0x18, 0xaf, 0x9f, 0x4d, 0xfa, 0xb4, 0x44, 0x18,
0x98, 0xec, 0xd6, 0x19, 0xac, 0xb1, 0xcb, 0x75,
0xc1, 0xa5, 0x94, 0x6f, 0xba, 0xf7, 0x16, 0xd2,
0x27, 0x19, 0x9a, 0x64, 0x79, 0xa6, 0x78, 0xd1,
0x0a, 0x6d, 0x95, 0x51, 0x2d, 0x67, 0x4f, 0xb7,
0x70, 0x3d, 0x85, 0xb5, 0x89, 0x80, 0xb8, 0xe6,
0xc5, 0x4b, 0xd2, 0x06, 0x16, 0xbd, 0xb9, 0x46,
0x1d, 0xcc, 0xd8, 0xee, 0xbb, 0x7d, 0x7e, 0x7c,
0x83, 0xa9, 0x14, 0x52, 0xcc, 0x20, 0xed, 0xf5,
0x3b, 0xe5, 0xb0, 0xfe, 0x0d, 0xb4, 0x4d, 0xdd,
0xaa, 0xaf, 0xbe, 0x73, 0x76, 0x78, 0xc6, 0x84,
0xb6, 0xe8, 0x9b, 0x9b, 0x4b, 0x67, 0x9b, 0x18,
0x55, 0xaa, 0x6e, 0xd6, 0x44, 0x49, 0x8b, 0x89,
0xc9, 0x18
};
test_ecdsa_adaptor_spec_vectors_check_serialization(adaptor_sig, 1);
}
{
/* Test vector 8 */
/* serialization test */
/* R_a can be above curve order */
const unsigned char adaptor_sig[162] = {
0x03, 0xe6, 0xd5, 0x1d, 0xa7, 0xbc, 0x2b, 0xf2,
0x4c, 0xf9, 0xdf, 0xd9, 0xac, 0xc6, 0xc4, 0xf0,
0xa3, 0xe7, 0x4d, 0x8a, 0x62, 0x73, 0xee, 0x5a,
0x57, 0x3e, 0xd6, 0x81, 0x8e, 0x30, 0x95, 0xb6,
0x09, 0x03, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xff, 0xff,
0xfc, 0x2c, 0xd6, 0x19, 0xac, 0xb1, 0xcb, 0x75,
0xc1, 0xa5, 0x94, 0x6f, 0xba, 0xf7, 0x16, 0xd2,
0x27, 0x19, 0x9a, 0x64, 0x79, 0xa6, 0x78, 0xd1,
0x0a, 0x6d, 0x95, 0x51, 0x2d, 0x67, 0x4f, 0xb7,
0x70, 0x3d, 0x85, 0xb5, 0x89, 0x80, 0xb8, 0xe6,
0xc5, 0x4b, 0xd2, 0x06, 0x16, 0xbd, 0xb9, 0x46,
0x1d, 0xcc, 0xd8, 0xee, 0xbb, 0x7d, 0x7e, 0x7c,
0x83, 0xa9, 0x14, 0x52, 0xcc, 0x20, 0xed, 0xf5,
0x3b, 0xe5, 0xb0, 0xfe, 0x0d, 0xb4, 0x4d, 0xdd,
0xaa, 0xaf, 0xbe, 0x73, 0x76, 0x78, 0xc6, 0x84,
0xb6, 0xe8, 0x9b, 0x9b, 0x4b, 0x67, 0x9b, 0x18,
0x55, 0xaa, 0x6e, 0xd6, 0x44, 0x49, 0x8b, 0x89,
0xc9, 0x18
};
test_ecdsa_adaptor_spec_vectors_check_serialization(adaptor_sig, 1);
}
{
/* Test vector 9 */
/* serialization test */
/* s_a cannot be zero */
const unsigned char adaptor_sig[162] = {
0x03, 0xe6, 0xd5, 0x1d, 0xa7, 0xbc, 0x2b, 0xf2,
0x4c, 0xf9, 0xdf, 0xd9, 0xac, 0xc6, 0xc4, 0xf0,
0xa3, 0xe7, 0x4d, 0x8a, 0x62, 0x73, 0xee, 0x5a,
0x57, 0x3e, 0xd6, 0x81, 0x8e, 0x30, 0x95, 0xb6,
0x09, 0x03, 0xf3, 0x3b, 0xc9, 0x8f, 0x9d, 0x2e,
0xa3, 0x51, 0x1f, 0x2e, 0x24, 0xf3, 0x35, 0x85,
0x57, 0xc8, 0x15, 0xab, 0xd7, 0x71, 0x3c, 0x93,
0x18, 0xaf, 0x9f, 0x4d, 0xfa, 0xb4, 0x44, 0x18,
0x98, 0xec, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x85, 0xb5, 0x89, 0x80, 0xb8, 0xe6,
0xc5, 0x4b, 0xd2, 0x06, 0x16, 0xbd, 0xb9, 0x46,
0x1d, 0xcc, 0xd8, 0xee, 0xbb, 0x7d, 0x7e, 0x7c,
0x83, 0xa9, 0x14, 0x52, 0xcc, 0x20, 0xed, 0xf5,
0x3b, 0xe5, 0xb0, 0xfe, 0x0d, 0xb4, 0x4d, 0xdd,
0xaa, 0xaf, 0xbe, 0x73, 0x76, 0x78, 0xc6, 0x84,
0xb6, 0xe8, 0x9b, 0x9b, 0x4b, 0x67, 0x9b, 0x18,
0x55, 0xaa, 0x6e, 0xd6, 0x44, 0x49, 0x8b, 0x89,
0xc9, 0x18
};
test_ecdsa_adaptor_spec_vectors_check_serialization(adaptor_sig, 0);
}
{
/* Test vector 10 */
/* serialization test */
/* s_a too high */
const unsigned char adaptor_sig[162] = {
0x03, 0xe6, 0xd5, 0x1d, 0xa7, 0xbc, 0x2b, 0xf2,
0x4c, 0xf9, 0xdf, 0xd9, 0xac, 0xc6, 0xc4, 0xf0,
0xa3, 0xe7, 0x4d, 0x8a, 0x62, 0x73, 0xee, 0x5a,
0x57, 0x3e, 0xd6, 0x81, 0x8e, 0x30, 0x95, 0xb6,
0x09, 0x03, 0xf3, 0x3b, 0xc9, 0x8f, 0x9d, 0x2e,
0xa3, 0x51, 0x1f, 0x2e, 0x24, 0xf3, 0x35, 0x85,
0x57, 0xc8, 0x15, 0xab, 0xd7, 0x71, 0x3c, 0x93,
0x18, 0xaf, 0x9f, 0x4d, 0xfa, 0xb4, 0x44, 0x18,
0x98, 0xec, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xfe, 0xba, 0xae, 0xdc, 0xe6, 0xaf, 0x48,
0xa0, 0x3b, 0xbf, 0xd2, 0x5e, 0x8c, 0xd0, 0x36,
0x41, 0x41, 0x85, 0xb5, 0x89, 0x80, 0xb8, 0xe6,
0xc5, 0x4b, 0xd2, 0x06, 0x16, 0xbd, 0xb9, 0x46,
0x1d, 0xcc, 0xd8, 0xee, 0xbb, 0x7d, 0x7e, 0x7c,
0x83, 0xa9, 0x14, 0x52, 0xcc, 0x20, 0xed, 0xf5,
0x3b, 0xe5, 0xb0, 0xfe, 0x0d, 0xb4, 0x4d, 0xdd,
0xaa, 0xaf, 0xbe, 0x73, 0x76, 0x78, 0xc6, 0x84,
0xb6, 0xe8, 0x9b, 0x9b, 0x4b, 0x67, 0x9b, 0x18,
0x55, 0xaa, 0x6e, 0xd6, 0x44, 0x49, 0x8b, 0x89,
0xc9, 0x18
};
test_ecdsa_adaptor_spec_vectors_check_serialization(adaptor_sig, 0);
}
}
/* Nonce function that returns constant 0 */
static int ecdsa_adaptor_nonce_function_failing(unsigned char *nonce32, const unsigned char *msg32, const unsigned char *key32, const unsigned char *encryption_key33, const unsigned char *algo, size_t algolen, void *data) {
(void) msg32;
(void) key32;
(void) encryption_key33;
(void) algo;
(void) algolen;
(void) data;
(void) nonce32;
return 0;
}
/* Nonce function that sets nonce to 0 */
static int ecdsa_adaptor_nonce_function_0(unsigned char *nonce32, const unsigned char *msg32, const unsigned char *key32, const unsigned char *encryption_key33, const unsigned char *algo, size_t algolen, void *data) {
(void) msg32;
(void) key32;
(void) encryption_key33;
(void) algo;
(void) algolen;
(void) data;
memset(nonce32, 0, 32);
return 1;
}
/* Nonce function that sets nonce to 0xFF...0xFF */
static int ecdsa_adaptor_nonce_function_overflowing(unsigned char *nonce32, const unsigned char *msg32, const unsigned char *key32, const unsigned char *encryption_key33, const unsigned char *algo, size_t algolen, void *data) {
(void) msg32;
(void) key32;
(void) encryption_key33;
(void) algo;
(void) algolen;
(void) data;
memset(nonce32, 0xFF, 32);
return 1;
}
/* Checks that a bit flip in the n_flip-th argument (that has n_bytes many
* bytes) changes the hash function
*/
void nonce_function_ecdsa_adaptor_bitflip(unsigned char **args, size_t n_flip, size_t n_bytes, size_t algolen) {
unsigned char nonces[2][32];
CHECK(nonce_function_ecdsa_adaptor(nonces[0], args[0], args[1], args[2], args[3], algolen, args[4]) == 1);
secp256k1_testrand_flip(args[n_flip], n_bytes);
CHECK(nonce_function_ecdsa_adaptor(nonces[1], args[0], args[1], args[2], args[3], algolen, args[4]) == 1);
CHECK(secp256k1_memcmp_var(nonces[0], nonces[1], 32) != 0);
}
/* Tests for the equality of two sha256 structs. This function only produces a
* correct result if an integer multiple of 64 many bytes have been written
* into the hash functions. */
void ecdsa_adaptor_test_sha256_eq(const secp256k1_sha256 *sha1, const secp256k1_sha256 *sha2) {
/* Is buffer fully consumed? */
CHECK((sha1->bytes & 0x3F) == 0);
CHECK(sha1->bytes == sha2->bytes);
CHECK(secp256k1_memcmp_var(sha1->s, sha2->s, sizeof(sha1->s)) == 0);
}
void run_nonce_function_ecdsa_adaptor_tests(void) {
unsigned char tag[16] = "ECDSAadaptor/non";
unsigned char aux_tag[16] = "ECDSAadaptor/aux";
unsigned char algo[16] = "ECDSAadaptor/non";
size_t algolen = sizeof(algo);
unsigned char dleq_tag[4] = "DLEQ";
secp256k1_sha256 sha;
secp256k1_sha256 sha_optimized;
unsigned char nonce[32];
unsigned char msg[32];
unsigned char key[32];
unsigned char pk[33];
unsigned char aux_rand[32];
unsigned char *args[5];
int i;
/* Check that hash initialized by
* secp256k1_nonce_function_ecdsa_adaptor_sha256_tagged has the expected
* state. */
secp256k1_sha256_initialize_tagged(&sha, tag, sizeof(tag));
secp256k1_nonce_function_ecdsa_adaptor_sha256_tagged(&sha_optimized);
ecdsa_adaptor_test_sha256_eq(&sha, &sha_optimized);
/* Check that hash initialized by
* secp256k1_nonce_function_ecdsa_adaptor_sha256_tagged_aux has the expected
* state. */
secp256k1_sha256_initialize_tagged(&sha, aux_tag, sizeof(aux_tag));
secp256k1_nonce_function_ecdsa_adaptor_sha256_tagged_aux(&sha_optimized);
ecdsa_adaptor_test_sha256_eq(&sha, &sha_optimized);
/* Check that hash initialized by
* secp256k1_nonce_function_dleq_sha256_tagged_aux has the expected
* state. */
secp256k1_sha256_initialize_tagged(&sha, dleq_tag, sizeof(dleq_tag));
secp256k1_nonce_function_dleq_sha256_tagged(&sha_optimized);
ecdsa_adaptor_test_sha256_eq(&sha, &sha_optimized);
secp256k1_rfc6979_hmac_sha256_generate(&secp256k1_test_rng, msg, sizeof(msg));
secp256k1_rfc6979_hmac_sha256_generate(&secp256k1_test_rng, key, sizeof(key));
secp256k1_rfc6979_hmac_sha256_generate(&secp256k1_test_rng, pk, sizeof(pk));
secp256k1_rfc6979_hmac_sha256_generate(&secp256k1_test_rng, aux_rand, sizeof(aux_rand));
/* Check that a bitflip in an argument results in different nonces. */
args[0] = msg;
args[1] = key;
args[2] = pk;
args[3] = algo;
args[4] = aux_rand;
for (i = 0; i < count; i++) {
nonce_function_ecdsa_adaptor_bitflip(args, 0, sizeof(msg), algolen);
nonce_function_ecdsa_adaptor_bitflip(args, 1, sizeof(key), algolen);
nonce_function_ecdsa_adaptor_bitflip(args, 2, sizeof(pk), algolen);
/* Flip algo special case "ECDSAadaptor/non" */
nonce_function_ecdsa_adaptor_bitflip(args, 3, sizeof(algo), algolen);
/* Flip algo again */
nonce_function_ecdsa_adaptor_bitflip(args, 3, sizeof(algo), algolen);
nonce_function_ecdsa_adaptor_bitflip(args, 4, sizeof(aux_rand), algolen);
}
/* NULL algo is disallowed */
CHECK(nonce_function_ecdsa_adaptor(nonce, msg, key, pk, NULL, 0, NULL) == 0);
/* Empty algo is fine */
memset(algo, 0x00, algolen);
CHECK(nonce_function_ecdsa_adaptor(nonce, msg, key, pk, algo, algolen, NULL) == 1);
/* Other algo is fine */
memset(algo, 0xFF, algolen);
CHECK(nonce_function_ecdsa_adaptor(nonce, msg, key, pk, algo, algolen, NULL) == 1);
/* dleq algo is fine */
CHECK(nonce_function_ecdsa_adaptor(nonce, msg, key, pk, dleq_algo, sizeof(dleq_algo), NULL) == 1);
/* Different algolen gives different nonce */
for (i = 0; i < count; i++) {
unsigned char nonce2[32];
uint32_t offset = secp256k1_testrand_int(algolen - 1);
size_t algolen_tmp = (algolen + offset) % algolen;
CHECK(nonce_function_ecdsa_adaptor(nonce2, msg, key, pk, algo, algolen_tmp, NULL) == 1);
CHECK(secp256k1_memcmp_var(nonce, nonce2, 32) != 0);
}
/* NULL aux_rand argument is allowed. */
CHECK(nonce_function_ecdsa_adaptor(nonce, msg, key, pk, algo, algolen, NULL) == 1);
}
void test_ecdsa_adaptor_api(void) {
secp256k1_pubkey pubkey;
secp256k1_pubkey enckey;
secp256k1_pubkey zero_pk;
secp256k1_ecdsa_signature sig;
unsigned char sk[32];
unsigned char msg[32];
unsigned char asig[162];
unsigned char deckey[32];
/** setup **/
secp256k1_context *none = secp256k1_context_create(SECP256K1_CONTEXT_NONE);
secp256k1_context *sign = secp256k1_context_create(SECP256K1_CONTEXT_SIGN);
secp256k1_context *vrfy = secp256k1_context_create(SECP256K1_CONTEXT_VERIFY);
secp256k1_context *both = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY);
int ecount;
secp256k1_context_set_error_callback(none, counting_illegal_callback_fn, &ecount);
secp256k1_context_set_error_callback(sign, counting_illegal_callback_fn, &ecount);
secp256k1_context_set_error_callback(vrfy, counting_illegal_callback_fn, &ecount);
secp256k1_context_set_error_callback(both, counting_illegal_callback_fn, &ecount);
secp256k1_context_set_illegal_callback(none, counting_illegal_callback_fn, &ecount);
secp256k1_context_set_illegal_callback(sign, counting_illegal_callback_fn, &ecount);
secp256k1_context_set_illegal_callback(vrfy, counting_illegal_callback_fn, &ecount);
secp256k1_context_set_illegal_callback(both, counting_illegal_callback_fn, &ecount);
secp256k1_testrand256(sk);
secp256k1_testrand256(msg);
secp256k1_testrand256(deckey);
CHECK(secp256k1_ec_pubkey_create(ctx, &pubkey, sk) == 1);
CHECK(secp256k1_ec_pubkey_create(ctx, &enckey, deckey) == 1);
memset(&zero_pk, 0, sizeof(zero_pk));
/** main test body **/
ecount = 0;
CHECK(secp256k1_ecdsa_adaptor_encrypt(none, asig, sk, &enckey, msg, NULL, NULL) == 0);
CHECK(ecount == 1);
CHECK(secp256k1_ecdsa_adaptor_encrypt(vrfy, asig, sk, &enckey, msg, NULL, NULL) == 0);
CHECK(ecount == 2);
CHECK(secp256k1_ecdsa_adaptor_encrypt(sign, asig, sk, &enckey, msg, NULL, NULL) == 1);
CHECK(ecount == 2);
CHECK(secp256k1_ecdsa_adaptor_encrypt(sign, NULL, sk, &enckey, msg, NULL, NULL) == 0);
CHECK(ecount == 3);
CHECK(secp256k1_ecdsa_adaptor_encrypt(sign, asig, sk, &enckey, NULL, NULL, NULL) == 0);
CHECK(ecount == 4);
CHECK(secp256k1_ecdsa_adaptor_encrypt(sign, asig, NULL, &enckey, msg, NULL, NULL) == 0);
CHECK(ecount == 5);
CHECK(secp256k1_ecdsa_adaptor_encrypt(sign, asig, sk, NULL, msg, NULL, NULL) == 0);
CHECK(ecount == 6);
CHECK(secp256k1_ecdsa_adaptor_encrypt(sign, asig, sk, &zero_pk, msg, NULL, NULL) == 0);
CHECK(ecount == 7);
ecount = 0;
CHECK(secp256k1_ecdsa_adaptor_encrypt(sign, asig, sk, &enckey, msg, NULL, NULL) == 1);
CHECK(secp256k1_ecdsa_adaptor_verify(none, asig, &pubkey, msg, &enckey) == 1);
CHECK(secp256k1_ecdsa_adaptor_verify(sign, asig, &pubkey, msg, &enckey) == 1);
CHECK(secp256k1_ecdsa_adaptor_verify(vrfy, asig, &pubkey, msg, &enckey) == 1);
CHECK(ecount == 0);
CHECK(secp256k1_ecdsa_adaptor_verify(vrfy, NULL, &pubkey, msg, &enckey) == 0);
CHECK(ecount == 1);
CHECK(secp256k1_ecdsa_adaptor_verify(vrfy, asig, &pubkey, NULL, &enckey) == 0);
CHECK(ecount == 2);
CHECK(secp256k1_ecdsa_adaptor_verify(vrfy, asig, &pubkey, msg, NULL) == 0);
CHECK(ecount == 3);
CHECK(secp256k1_ecdsa_adaptor_verify(vrfy, asig, NULL, msg, &enckey) == 0);
CHECK(ecount == 4);
CHECK(secp256k1_ecdsa_adaptor_verify(vrfy, asig, &zero_pk, msg, &enckey) == 0);
CHECK(ecount == 5);
CHECK(secp256k1_ecdsa_adaptor_verify(vrfy, asig, &pubkey, msg, &zero_pk) == 0);
CHECK(ecount == 6);
ecount = 0;
CHECK(secp256k1_ecdsa_adaptor_decrypt(none, &sig, deckey, asig) == 1);
CHECK(secp256k1_ecdsa_adaptor_decrypt(sign, &sig, deckey, asig) == 1);
CHECK(secp256k1_ecdsa_adaptor_decrypt(vrfy, &sig, deckey, asig) == 1);
CHECK(secp256k1_ecdsa_adaptor_decrypt(both, &sig, deckey, asig) == 1);
CHECK(secp256k1_ecdsa_adaptor_decrypt(both, NULL, deckey, asig) == 0);
CHECK(ecount == 1);
CHECK(secp256k1_ecdsa_adaptor_decrypt(both, &sig, NULL, asig) == 0);
CHECK(ecount == 2);
CHECK(secp256k1_ecdsa_adaptor_decrypt(both, &sig, deckey, NULL) == 0);
CHECK(ecount == 3);
ecount = 0;
CHECK(secp256k1_ecdsa_adaptor_decrypt(both, &sig, deckey, asig) == 1);
CHECK(secp256k1_ecdsa_adaptor_recover(none, deckey, &sig, asig, &enckey) == 0);
CHECK(ecount == 1);
CHECK(secp256k1_ecdsa_adaptor_recover(vrfy, deckey, &sig, asig, &enckey) == 0);
CHECK(ecount == 2);
CHECK(secp256k1_ecdsa_adaptor_recover(sign, deckey, &sig, asig, &enckey) == 1);
CHECK(ecount == 2);
CHECK(secp256k1_ecdsa_adaptor_recover(sign, NULL, &sig, asig, &enckey) == 0);
CHECK(ecount == 3);
CHECK(secp256k1_ecdsa_adaptor_recover(sign, deckey, NULL, asig, &enckey) == 0);
CHECK(ecount == 4);
CHECK(secp256k1_ecdsa_adaptor_recover(sign, deckey, &sig, NULL, &enckey) == 0);
CHECK(ecount == 5);
CHECK(secp256k1_ecdsa_adaptor_recover(sign, deckey, &sig, asig, NULL) == 0);
CHECK(ecount == 6);
CHECK(secp256k1_ecdsa_adaptor_recover(sign, deckey, &sig, asig, &zero_pk) == 0);
CHECK(ecount == 7);
secp256k1_context_destroy(none);
secp256k1_context_destroy(sign);
secp256k1_context_destroy(vrfy);
secp256k1_context_destroy(both);
}
void adaptor_tests(void) {
unsigned char seckey[32];
secp256k1_pubkey pubkey;
unsigned char msg[32];
unsigned char deckey[32];
secp256k1_pubkey enckey;
unsigned char adaptor_sig[162];
secp256k1_ecdsa_signature sig;
unsigned char zeros162[162] = { 0 };
unsigned char zeros64[64] = { 0 };
unsigned char big[32];
secp256k1_testrand256(seckey);
secp256k1_testrand256(msg);
secp256k1_testrand256(deckey);
CHECK(secp256k1_ec_pubkey_create(ctx, &pubkey, seckey) == 1);
CHECK(secp256k1_ec_pubkey_create(ctx, &enckey, deckey) == 1);
CHECK(secp256k1_ecdsa_adaptor_encrypt(ctx, adaptor_sig, seckey, &enckey, msg, NULL, NULL) == 1);
{
/* Test overflowing seckey */
memset(big, 0xFF, 32);
CHECK(secp256k1_ecdsa_adaptor_encrypt(ctx, adaptor_sig, big, &enckey, msg, NULL, NULL) == 0);
CHECK(secp256k1_memcmp_var(adaptor_sig, zeros162, sizeof(adaptor_sig)) == 0);
/* Test different nonce functions */
memset(adaptor_sig, 1, sizeof(adaptor_sig));
CHECK(secp256k1_ecdsa_adaptor_encrypt(ctx, adaptor_sig, seckey, &enckey, msg, ecdsa_adaptor_nonce_function_failing, NULL) == 0);
CHECK(secp256k1_memcmp_var(adaptor_sig, zeros162, sizeof(adaptor_sig)) == 0);
memset(&adaptor_sig, 1, sizeof(adaptor_sig));
CHECK(secp256k1_ecdsa_adaptor_encrypt(ctx, adaptor_sig, seckey, &enckey, msg, ecdsa_adaptor_nonce_function_0, NULL) == 0);
CHECK(secp256k1_memcmp_var(adaptor_sig, zeros162, sizeof(adaptor_sig)) == 0);
CHECK(secp256k1_ecdsa_adaptor_encrypt(ctx, adaptor_sig, seckey, &enckey, msg, ecdsa_adaptor_nonce_function_overflowing, NULL) == 1);
CHECK(secp256k1_memcmp_var(adaptor_sig, zeros162, sizeof(adaptor_sig)) != 0);
}
{
/* Test adaptor_sig_serialize roundtrip */
secp256k1_ge r, rp;
secp256k1_scalar sigr;
secp256k1_scalar sp;
secp256k1_scalar dleq_proof_s, dleq_proof_e;
secp256k1_ge p_inf;
unsigned char adaptor_sig_tmp[162];
CHECK(secp256k1_ecdsa_adaptor_sig_deserialize(&r, &sigr, &rp, &sp, &dleq_proof_e, &dleq_proof_s, adaptor_sig) == 1);
CHECK(secp256k1_ecdsa_adaptor_sig_serialize(adaptor_sig_tmp, &r, &rp, &sp, &dleq_proof_e, &dleq_proof_s) == 1);
CHECK(secp256k1_memcmp_var(adaptor_sig_tmp, adaptor_sig, sizeof(adaptor_sig_tmp)) == 0);
/* Test adaptor_sig_serialize points at infinity */
secp256k1_ge_set_infinity(&p_inf);
CHECK(secp256k1_ecdsa_adaptor_sig_serialize(adaptor_sig_tmp, &p_inf, &rp, &sp, &dleq_proof_e, &dleq_proof_s) == 0);
CHECK(secp256k1_ecdsa_adaptor_sig_serialize(adaptor_sig_tmp, &r, &p_inf, &sp, &dleq_proof_e, &dleq_proof_s) == 0);
}
{
/* Test adaptor_sig_deserialize */
secp256k1_ge r, rp;
secp256k1_scalar sigr;
secp256k1_scalar sp;
secp256k1_scalar dleq_proof_s, dleq_proof_e;
unsigned char adaptor_sig_tmp[162];
CHECK(secp256k1_ecdsa_adaptor_sig_deserialize(&r, &sigr, &rp, &sp, &dleq_proof_e, &dleq_proof_s, adaptor_sig) == 1);
/* r */
CHECK(secp256k1_ecdsa_adaptor_sig_deserialize(&r, &sigr, NULL, NULL, NULL, NULL, adaptor_sig) == 1);
memcpy(adaptor_sig_tmp, adaptor_sig, sizeof(adaptor_sig_tmp));
memset(&adaptor_sig_tmp[0], 0xFF, 33);
CHECK(secp256k1_ecdsa_adaptor_sig_deserialize(&r, &sigr, NULL, NULL, NULL, NULL, adaptor_sig_tmp) == 0);
/* sigr */
CHECK(secp256k1_ecdsa_adaptor_sig_deserialize(NULL, &sigr, NULL, NULL, NULL, NULL, adaptor_sig) == 1);
memcpy(adaptor_sig_tmp, adaptor_sig, sizeof(adaptor_sig_tmp));
memset(&adaptor_sig_tmp[1], 0xFF, 32);
CHECK(secp256k1_ecdsa_adaptor_sig_deserialize(NULL, &sigr, NULL, NULL, NULL, NULL, adaptor_sig_tmp) == 1);
memset(&adaptor_sig_tmp[1], 0, 32);
CHECK(secp256k1_ecdsa_adaptor_sig_deserialize(NULL, &sigr, NULL, NULL, NULL, NULL, adaptor_sig_tmp) == 0);
/* rp */
CHECK(secp256k1_ecdsa_adaptor_sig_deserialize(NULL, NULL, &rp, NULL, NULL, NULL, adaptor_sig) == 1);
memcpy(adaptor_sig_tmp, adaptor_sig, sizeof(adaptor_sig_tmp));
memset(&adaptor_sig_tmp[33], 0xFF, 33);
CHECK(secp256k1_ecdsa_adaptor_sig_deserialize(NULL, NULL, &rp, NULL, NULL, NULL, adaptor_sig_tmp) == 0);
/* sp */
CHECK(secp256k1_ecdsa_adaptor_sig_deserialize(NULL, NULL, NULL, &sp, NULL, NULL, adaptor_sig) == 1);
memcpy(adaptor_sig_tmp, adaptor_sig, sizeof(adaptor_sig_tmp));
memset(&adaptor_sig_tmp[66], 0xFF, 32);
CHECK(secp256k1_ecdsa_adaptor_sig_deserialize(NULL, NULL, NULL, &sp, NULL, NULL, adaptor_sig_tmp) == 0);
/* dleq_proof_e */
CHECK(secp256k1_ecdsa_adaptor_sig_deserialize(NULL, NULL, NULL, NULL, &dleq_proof_e, NULL, adaptor_sig) == 1);
memcpy(adaptor_sig_tmp, adaptor_sig, sizeof(adaptor_sig_tmp));
memset(&adaptor_sig_tmp[98], 0xFF, 32);
CHECK(secp256k1_ecdsa_adaptor_sig_deserialize(NULL, NULL, NULL, NULL, &dleq_proof_e, NULL, adaptor_sig_tmp) == 1);
/* dleq_proof_s */
CHECK(secp256k1_ecdsa_adaptor_sig_deserialize(NULL, NULL, NULL, NULL, NULL, &dleq_proof_s, adaptor_sig) == 1);
memcpy(adaptor_sig_tmp, adaptor_sig, sizeof(adaptor_sig_tmp));
memset(&adaptor_sig_tmp[130], 0xFF, 32);
CHECK(secp256k1_ecdsa_adaptor_sig_deserialize(NULL, NULL, NULL, NULL, NULL, &dleq_proof_s, adaptor_sig_tmp) == 0);
}
/* Test adaptor_sig_verify */
CHECK(secp256k1_ecdsa_adaptor_verify(ctx, adaptor_sig, &pubkey, msg, &enckey) == 1);
CHECK(secp256k1_ecdsa_adaptor_verify(ctx, adaptor_sig, &enckey, msg, &enckey) == 0);
CHECK(secp256k1_ecdsa_adaptor_verify(ctx, adaptor_sig, &pubkey, msg, &pubkey) == 0);
{
/* Test failed adaptor sig deserialization */
unsigned char adaptor_sig_tmp[162];
memset(&adaptor_sig_tmp, 0xFF, 162);
CHECK(secp256k1_ecdsa_adaptor_verify(ctx, adaptor_sig_tmp, &pubkey, msg, &enckey) == 0);
}
{
/* Test that any flipped bit in the adaptor signature will make
* verification fail */
unsigned char adaptor_sig_tmp[162];
memcpy(adaptor_sig_tmp, adaptor_sig, sizeof(adaptor_sig_tmp));
rand_flip_bit(&adaptor_sig_tmp[1], sizeof(adaptor_sig_tmp) - 1);
CHECK(secp256k1_ecdsa_adaptor_verify(ctx, adaptor_sig_tmp, &pubkey, msg, &enckey) == 0);
}
{
unsigned char msg_tmp[32];
memcpy(msg_tmp, msg, sizeof(msg_tmp));
rand_flip_bit(msg_tmp, sizeof(msg_tmp));
CHECK(secp256k1_ecdsa_adaptor_verify(ctx, adaptor_sig, &pubkey, msg_tmp, &enckey) == 0);
}
{
/* Verification must check that the derived R' is not equal to the point at
* infinity before negating it. R' is derived as follows:
*
* R' == s'⁻¹(m * G + R.x * X)
*
* When the base point, G, is multiplied by the subgroup order, q, the
* result is the point at infinity, 0:
*
* q * G = 0
*
* Thus, if we set s' equal to R.x, m equal to (q - 1) * R.x, and X equal to
* G, then our derived R' will be 0:
*
* R' = R.x⁻¹((q - 1 * R.x) * G + R.x * G) = q * G = 0 */
/* t := q - 1 */
const unsigned char target[32] = {
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe,
0xba, 0xae, 0xdc, 0xe6, 0xaf, 0x48, 0xa0, 0x3b,
0xbf, 0xd2, 0x5e, 0x8c, 0xd0, 0x36, 0x41, 0x40
};
unsigned char seckey_tmp[32] = { 0 };
unsigned char msg_tmp[32];
unsigned char adaptor_sig_tmp[162];
secp256k1_pubkey pubkey_tmp;
secp256k1_scalar sigr, t, m;
/* m := t * sigr */
CHECK(secp256k1_ecdsa_adaptor_sig_deserialize(NULL, &sigr, NULL, NULL, NULL, NULL, adaptor_sig) == 1);
secp256k1_scalar_set_b32(&t, target, NULL);
secp256k1_scalar_mul(&m, &t, &sigr);
secp256k1_scalar_get_b32(msg_tmp, &m);
/* X := G */
seckey_tmp[31] = 1;
CHECK(secp256k1_ec_pubkey_create(ctx, &pubkey_tmp, seckey_tmp) == 1);
/* sp := sigr */
memcpy(adaptor_sig_tmp, adaptor_sig, sizeof(adaptor_sig_tmp));
memcpy(&adaptor_sig_tmp[66], &adaptor_sig_tmp[1], 32);
CHECK(secp256k1_ecdsa_adaptor_verify(ctx, adaptor_sig_tmp, &pubkey_tmp, msg_tmp, &enckey) == 0);
}
/* Test decryption */
CHECK(secp256k1_ecdsa_adaptor_decrypt(ctx, &sig, deckey, adaptor_sig) == 1);
CHECK(secp256k1_ecdsa_verify(ctx, &sig, msg, &pubkey) == 1);
{
/* Test overflowing decryption key */
secp256k1_ecdsa_signature s;
memset(big, 0xFF, 32);
CHECK(secp256k1_ecdsa_adaptor_decrypt(ctx, &s, big, adaptor_sig) == 0);
CHECK(secp256k1_memcmp_var(&s.data[0], zeros64, sizeof(&s.data[0])) == 0);
}
{
/* Test key recover */
unsigned char decryption_key_tmp[32];
unsigned char adaptor_sig_tmp[162];
CHECK(secp256k1_ecdsa_adaptor_recover(ctx, decryption_key_tmp, &sig, adaptor_sig, &enckey) == 1);
CHECK(secp256k1_memcmp_var(deckey, decryption_key_tmp, sizeof(deckey)) == 0);
/* Test failed sp deserialization */
memcpy(adaptor_sig_tmp, adaptor_sig, sizeof(adaptor_sig_tmp));
memset(&adaptor_sig_tmp[66], 0xFF, 32);
CHECK(secp256k1_ecdsa_adaptor_recover(ctx, decryption_key_tmp, &sig, adaptor_sig_tmp, &enckey) == 0);
}
}
void multi_hop_lock_tests(void) {
unsigned char seckey_a[32];
unsigned char seckey_b[32];
unsigned char pop[32];
unsigned char tx_ab[32];
unsigned char tx_bc[32];
unsigned char buf[32];
unsigned char asig_ab[162];
unsigned char asig_bc[162];
secp256k1_pubkey pubkey_pop;
secp256k1_pubkey pubkey_a, pubkey_b;
secp256k1_pubkey l, r;
secp256k1_ge l_ge, r_ge;
secp256k1_scalar t1, t2, tp;
secp256k1_scalar deckey;
secp256k1_ecdsa_signature sig_ab, sig_bc;
secp256k1_testrand256(seckey_a);
secp256k1_testrand256(seckey_b);
CHECK(secp256k1_ec_pubkey_create(ctx, &pubkey_a, seckey_a));
CHECK(secp256k1_ec_pubkey_create(ctx, &pubkey_b, seckey_b));
/* Carol setup */
/* Proof of payment */
secp256k1_testrand256(pop);
CHECK(secp256k1_ec_pubkey_create(ctx, &pubkey_pop, pop));
/* Alice setup */
secp256k1_testrand256(tx_ab);
rand_scalar(&t1);
rand_scalar(&t2);
secp256k1_scalar_add(&tp, &t1, &t2);
/* Left lock */
secp256k1_pubkey_load(ctx, &l_ge, &pubkey_pop);
CHECK(secp256k1_eckey_pubkey_tweak_add(&l_ge, &t1));
secp256k1_pubkey_save(&l, &l_ge);
/* Right lock */
secp256k1_pubkey_load(ctx, &r_ge, &pubkey_pop);
CHECK(secp256k1_eckey_pubkey_tweak_add(&r_ge, &tp));
secp256k1_pubkey_save(&r, &r_ge);
CHECK(secp256k1_ecdsa_adaptor_encrypt(ctx, asig_ab, seckey_a, &l, tx_ab, NULL, NULL));
/* Bob setup */
CHECK(secp256k1_ecdsa_adaptor_verify(ctx, asig_ab, &pubkey_a, tx_ab, &l));
secp256k1_testrand256(tx_bc);
CHECK(secp256k1_ecdsa_adaptor_encrypt(ctx, asig_bc, seckey_b, &r, tx_bc, NULL, NULL));
/* Carol decrypt */
CHECK(secp256k1_ecdsa_adaptor_verify(ctx, asig_bc, &pubkey_b, tx_bc, &r));
secp256k1_scalar_set_b32(&deckey, pop, NULL);
secp256k1_scalar_add(&deckey, &deckey, &tp);
secp256k1_scalar_get_b32(buf, &deckey);
CHECK(secp256k1_ecdsa_adaptor_decrypt(ctx, &sig_bc, buf, asig_bc));
CHECK(secp256k1_ecdsa_verify(ctx, &sig_bc, tx_bc, &pubkey_b));
/* Bob recover and decrypt */
CHECK(secp256k1_ecdsa_adaptor_recover(ctx, buf, &sig_bc, asig_bc, &r));
secp256k1_scalar_set_b32(&deckey, buf, NULL);
secp256k1_scalar_negate(&t2, &t2);
secp256k1_scalar_add(&deckey, &deckey, &t2);
secp256k1_scalar_get_b32(buf, &deckey);
CHECK(secp256k1_ecdsa_adaptor_decrypt(ctx, &sig_ab, buf, asig_ab));
CHECK(secp256k1_ecdsa_verify(ctx, &sig_ab, tx_ab, &pubkey_a));
/* Alice recover and derive proof of payment */
CHECK(secp256k1_ecdsa_adaptor_recover(ctx, buf, &sig_ab, asig_ab, &l));
secp256k1_scalar_set_b32(&deckey, buf, NULL);
secp256k1_scalar_negate(&t1, &t1);
secp256k1_scalar_add(&deckey, &deckey, &t1);
secp256k1_scalar_get_b32(buf, &deckey);
CHECK(secp256k1_memcmp_var(buf, pop, 32) == 0);
}
void run_ecdsa_adaptor_tests(void) {
int i;
run_nonce_function_ecdsa_adaptor_tests();
test_ecdsa_adaptor_api();
test_ecdsa_adaptor_spec_vectors();
for (i = 0; i < count; i++) {
dleq_tests();
}
for (i = 0; i < count; i++) {
adaptor_tests();
}
for (i = 0; i < count; i++) {
multi_hop_lock_tests();
}
}
#endif /* SECP256K1_MODULE_ECDSA_ADAPTOR_TESTS_H */
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.