Debian Codegraph @

terps/agility/util.c

raw symbols SCIP
1 /* util.c-- wrappers around memory allocation and other misc. */
2 /* utilities */
3 /* Copyright (C) 1996-1999,2001 Robert Masenten */
4 /* This program may be redistributed under the terms of the
5 GNU General Public License, version 2; see agility.h for details. */
6 /* */
7 /* This is part of the source for both AGiliTy: the (Mostly) Universal */
8 /* AGT Interpreter and for the Magx adventure game compiler. */
9
10 /* This includes wrappers for malloc, realloc, strdup, and free
11 that exit gracefully if we run out of memory. */
12 /* There are also various utilities:
13 concdup: Creates a new string that is concatation of two others.
14 strcasecmp: case insensitive comparison of strings
15 strncasecmp: case insensitive compare of first n characters of strings
16 fixsign16, fixsign32: routines to assemble signed ints out of
17 individual bytes in an endian-free way. */
18 /* Also buffered file i/o routines and some misc. file utilites. */
19
20
21 #include <assert.h>
22 #include <stdlib.h>
23 #include <stdarg.h>
24 #include <ctype.h>
25 #include <errno.h>
26 #include "agility.h"
27
28 #ifdef force16
29 #undef int
30 #endif
31
32 #ifdef PROFILE_SUPPORT
33 #include <sys/times.h>
34 #endif
35
36 #ifdef MEM_INFO
37 #include <malloc.h>
38 #endif
39
40 #ifdef force16
41 #define int short
42 #endif
43
44
45 long rangefix(long n)
46 {
47 if (n>0) return n;
48 return 0;
49 }
50
51 /*-------------------------------------------------------------------*/
52 /* Sign fixing routines, to build a signed 16- and 32-bit quantities */
53 /* out of their component bytes. */
54 /*-------------------------------------------------------------------*/
55
56 #ifndef FAST_FIXSIGN
57 short fixsign16(uchar n1,uchar n2)
58 {
59 rbool sflag;
60 short n;
61
62 if (n2>0x80) {n2&=0x7F;sflag=1;}
63 else sflag=0;
64
65 n=n1+(n2<<8);
66 if (sflag) n=n-0x7fff-1;
67 return n;
68 }
69
70 long fixsign32(uchar n1,uchar n2,uchar n3,uchar n4)
71 {
72 rbool sflag;
73 long n;
74
75 if (n4>0x80) {n4&=0x7F;sflag=1;}
76 else sflag=0;
77
78 n=n1+(((long)n2)<<8)+(((long)n3)<<16)+(((long)n4)<<24);
79 if (sflag) n=n-0x7fffffffL-1L;
80 return n;
81 }
82 #endif
83
84
85
86 /*----------------------------------------------------------------------*/
87 /* rprintf(), uses writestr for output */
88 /* This function is used mainly for diagnostic information */
89 /* There should be no newlines in the format string or in any of the */
90 /* arguments as those could confuse writestr, except for the last */
91 /* character in the string which can be a newline. */
92 /*----------------------------------------------------------------------*/
93
94 void rprintf(const char *fmt, ...)
95 {
96 int i;
97 char s[100];
98 va_list args;
99
100 va_start(args,fmt);
101 vsprintf(s,fmt,args);
102 va_end(args);
103 i=strlen(s)-1;
104 if (i>=0 && s[i]=='\n') {
105 s[i]=0;
106 writeln(s);
107 }
108 else writestr(s);
109 }
110
111
112 /*----------------------------------------------------------------------*/
113 /* Memory allocation wrappers: All memory allocation should run through */
114 /* these routines, which trap error conditions and do accounting to */
115 /* help track down memory leaks. */
116 /*----------------------------------------------------------------------*/
117
118 rbool rm_trap=1;
119
120 long get_rm_size(void)
121 /* Return the amount of space being used by dynamically allocated things */
122 {
123 #ifdef MEM_INFO
124 struct mstats memdata;
125
126 memdata=mstats();
127 return memdata.bytes_used;
128 #endif
129 return 0;
130 }
131
132 long get_rm_freesize(void)
133 /* Return estimate of amount of space left */
134 {
135 #ifdef MEM_INFO
136 struct mstats memdata;
137
138 memdata=mstats();
139 return memdata.bytes_free;
140 #endif
141 return 0;
142 }
143
144
145 void *rmalloc(long size)
146 {
147 void *p;
148
149 if (size>MAXSTRUC) {
150 printf("Memory allocation error: Over-sized structure requested.\n");
151 exit(EXIT_FAILURE);
152 }
153 assert(size>=0);
154 if (size==0) return NULL;
155 p=malloc((size_t)size);
156 if (p==NULL && rm_trap && size>0)
157 {
158 printf("Memory allocation error: Out of memory.\n");
159 exit(EXIT_FAILURE);
160 }
161 if (rm_acct) ralloc_cnt++;
162 return p;
163 }
164
165 void *rrealloc(void *old,long size)
166 {
167 void *p;
168
169 if (size>MAXSTRUC) {
170 printf("Memory reallocation error: Oversized structure requested.\n");
171 exit(EXIT_FAILURE);
172 }
173 assert(size>=0);
174 if (size==0) {
175 r_free(old);
176 return NULL;
177 }
178 if (rm_acct && old==NULL) ralloc_cnt++;
179 p=realloc(old,(size_t)size);
180 if (p==NULL && rm_trap && size>0)
181 {
182 printf("Memory reallocation error: Out of memory.\n");
183 exit(EXIT_FAILURE);
184 }
185 return p;
186 }
187
188 char *rstrdup(const char *s)
189 {
190 char *t;
191 #ifndef HAVE_STRDUP
192 int i;
193 #endif
194
195 if (s==NULL) return NULL;
196 #ifdef HAVE_STRDUP
197 t=strdup(s);
198 #else
199 t=malloc((strlen(s)+1)*sizeof(char));
200 #endif
201 if (t==NULL && rm_trap)
202 {
203 printf("Memory duplication error: Out of memory.\n");
204 exit(EXIT_FAILURE);
205 }
206 if (rm_acct) ralloc_cnt++;
207 #ifndef HAVE_STRDUP
208 for(i=0;s[i]!=0;i++)
209 t[i]=s[i];
210 t[i]=0;
211 #endif
212 return t;
213 }
214
215 void r_free(void *p)
216 {
217 int tmp;
218
219 if (p==NULL) return;
220
221 tmp=get_rm_size(); /* Take worst case in all cases */
222 if (tmp>rm_size) rm_size=tmp;
223 tmp=get_rm_freesize();
224 if (tmp<rm_freesize) rm_freesize=tmp;
225
226 if (rm_acct) rfree_cnt++;
227 free(p);
228 }
229
230
231
232 /*----------------------------------------------------------------------*/
233 /* String utilities: These are utilities to manipulate strings. */
234 /*----------------------------------------------------------------------*/
235
236 /* rnstrncpy copies src to dest, copying at most (max-1) characters.
237 Unlike ANSI strncpy, it doesn't fill extra space will nulls and
238 it always puts a terminating null. */
239 char *rstrncpy(char *dest,const char *src,int max)
240 {
241 int i;
242 for(i=0; i<max-1 && src[i];i++)
243 dest[i]=src[i];
244 dest[i]=0;
245 return dest;
246 }
247
248 /* This does a case-insensitive match of the beginning of *pstr to match */
249 /* <match> must be all upper case */
250 /* *pstr is updated to point after the match, if it is succesful.
251 Otherwise *pstr is left alone. */
252 rbool match_str(const char **pstr,const char *match)
253 {
254 int i;
255 const char *s;
256
257 s=*pstr;
258 for(i=0; match[i]!=0 && s[i]!=0;i++)
259 if (toupper(s[i])!=match[i]) return 0;
260 if (match[i]!=0) return 0;
261 *pstr+=i;
262 return 1;
263 }
264
265
266
267
268 /* Utility to concacate two strings with a space inserted */
269
270 char *concdup(const char *s1,const char *s2)
271 {
272 int len1, len2;
273 char *s;
274
275 len1=len2=0;
276 if (s1!=NULL) len1=strlen(s1);
277 if (s2!=NULL) len2=strlen(s2);
278
279 s=rmalloc(sizeof(char)*(len1+len2+2));
280 if (s1!=NULL)
281 memcpy(s,s1,len1);
282 memcpy(s+len1," ",1);
283 if (s2!=NULL)
284 memcpy(s+len1+1,s2,len2);
285 s[len1+len2+1]=0;
286 return s;
287 }
288
289
290 /* Misc. C utility functions that may be supported locally.
291 If they are, use the local functions since they'll probably be faster
292 and more efficiant. */
293
294 #ifdef NEED_STR_CMP
295 int strcasecmp(const char *s1,const char *s2)
296 /* Compare strings s1 and s2, case insensitive; */
297 /* If equal, return 0. Otherwise return nonzero. */
298 {
299 int i;
300
301 for(i=0;tolower(s1[i])==tolower(s2[i]) && s1[i]!=0;i++);
302 if (tolower(s1[i])==tolower(s2[i])) return 0;
303 if (s1[i]==0) return -1;
304 if (s2[i]==0) return 1;
305 if (tolower(s1[i])<tolower(s2[i])) return -1;
306 return 1;
307 }
308 #endif /* NEED_STR_CMP */
309
310 #ifdef NEED_STRN_CMP
311 int strncasecmp(const char *s1,const char *s2,size_t n)
312 /* Compare first n letters of strings s1 and s2, case insensitive; */
313 /* If equal, return 0. Otherwise return nonzero. */
314 {
315 size_t i;
316
317 for(i=0;i<n && tolower(s1[i])==tolower(s2[i]) && s1[i]!=0;i++);
318 if (i==n || tolower(s1[i])==tolower(s2[i])) return 0;
319 if (s1[i]==0) return -1;
320 if (s2[i]==0) return 1;
321 if (tolower(s1[i])<tolower(s2[i])) return -1;
322 return 1;
323 }
324 #endif /* NEED_STRN_CMP */
325
326 /*----------------------------------------------------------------------*/
327 /* Character utilities: Do character translation */
328 /*----------------------------------------------------------------------*/
329
330 void build_trans_ascii(void)
331 {
332 int i;
333
334 for(i=0;i<256;i++)
335 trans_ascii[i]= (!fix_ascii_flag || i<0x80) ? i : trans_ibm[i&0x7f];
336 trans_ascii[0xFF]=0xFF; /* Preserve format character */
337 }
338
339
340 /*----------------------------------------------------------------------*/
341 /* File utilities: Utilities to manipulate files. */
342 /*----------------------------------------------------------------------*/
343
344 void print_error(char *fname, filetype ext, char *err, rbool ferr)
345 {
346 char *estring; /* Hold error string */
347 estring=rmalloc(strlen(err)+strlen(fname)+2);
348 sprintf(estring,err,fname);
349 if (ferr) fatal(estring); else writeln(estring);
350 rfree(estring);
351 }
352
353 /* Routine to open files with extensions and handle basic error conditions */
354
355 genfile openfile(fc_type fc,filetype ext,char *err,rbool ferr)
356 /* Opens the file fname+ext, printing out err if something goes wrong.
357 (unless err==NULL, in which case nothing will be printed) */
358 /* err can have one %s paramater in it, which will have the file name
359 plugged in to it. */
360 /* If ferr is true, then on failure the routine will abort with a fatal
361 error. */
362 {
363 genfile tfile; /* Actually, this may not be a text file anymore */
364 char *errstr;
365
366 tfile=readopen(fc,ext,&errstr);
367 if (errstr!=NULL && err!=NULL)
368 print_error("",ext,err,ferr);
369 rfree(errstr);
370 return tfile;
371 }
372
373
374 genfile openbin(fc_type fc,filetype ext,char *err,rbool ferr)
375 /* Opens the file fname+ext, printing out err if something goes wrong.
376 (unless err==NULL, in which case nothing will be printed) */
377 /* err can have one %s paramater in it, which will have the file name
378 plugged in to it. */
379 /* If ferr is true, then on failure the routine will abort with a fatal
380 error. */
381 {
382 genfile f; /* Actually, this may not be a text file anymore */
383 char *errstr;
384 char *fname;
385
386 f=readopen(fc,ext,&errstr);
387 if (errstr!=NULL && err!=NULL) {
388 fname=formal_name(fc,ext);
389 print_error(fname,ext,err,ferr);
390 rfree(fname);
391 }
392 rfree(errstr);
393 return f;
394 }
395
396
397
398 /* This routine reads in a line from a 'text' file; it's designed to work
399 regardless of the EOL conventions of the platform, at least up to a point.
400 It should work with files that have \n, \r, or \r\n termined lines. */
401
402 #define READLN_GRAIN 64 /* Granularity of readln() rrealloc requests
403 this needs to be at least the size of a tab
404 character */
405 #define DOS_EOF 26 /* Ctrl-Z is the DOS end-of-file marker */
406
407 char *readln(genfile f, char *buff, int n)
408 /* Reads first n characters of line, eliminates any newline,
409 and truncates the rest of the line. 'n' does *not* include terminating
410 null. */
411 /* If we pass it BUFF=NULL, then it will reallocate buff as needed and
412 pass it back as its return value. n is ignored in this case */
413 /* If it reaches EOF, it will return NULL */
414 /* This routine recognizes lines terminated by \n, \r, or \r\n */
415 {
416 int c;
417 int i, j, csize;
418 int buffsize; /* Current size of buff, if we are allocating it dynamically */
419
420 if (buff==NULL) {
421 buff=rrealloc(buff,READLN_GRAIN*sizeof(char));
422 buffsize=READLN_GRAIN;
423 n=buffsize-1;
424 }
425 else buffsize=-1; /* So we know that we are using a fixed-size buffer */
426
427 i=0;
428 for(;;) {
429 c=textgetc(f);
430
431 if (c=='\n' || c=='\r' || c==EOF || c==DOS_EOF) break;
432
433 csize= (c=='\t') ? 5 : 1; /* Tabs are translated into five spaces */
434
435 if (i+csize>=n && buffsize>=0) {
436 buffsize+=READLN_GRAIN; n=buffsize-1;
437 buff=rrealloc(buff,buffsize*sizeof(char));
438 }
439
440 if (c==0) c=FORMAT_CODE;
441 else if (c!='\t') {if (i<n) buff[i++]=c;}
442 else for(j=0;j<5 && i<n;j++) buff[i++]=' ';
443
444 /* We can't exit the loop if i>n since we still need to discard
445 the rest of the line */
446 }
447
448 buff[i]=0;
449
450 if (c=='\r') { /* Check for \r\n DOS-style newline */
451 char newc;
452 newc=textgetc(f);
453 if (newc!='\n') textungetc(f,newc);
454 /* Replace the character we just read. */
455 } else if (c==DOS_EOF) /* Ctrl-Z is the DOS EOF marker */
456 textungetc(f,c); /* So it will be the first character we see next time */
457
458 if (i==0 && (c==EOF || c==DOS_EOF)) {/* We've hit the end of the file */
459 if (buffsize>=0) rfree(buff);
460 return NULL;
461 }
462
463 if (buffsize>=0) { /* Shrink buffer to appropriate size */
464 buffsize=i+1;
465 buff=rrealloc(buff,buffsize);
466 }
467
468 return buff;
469 }
470
471
472 /*-------------------------------------------------------------------------*/
473 /* Buffered file Input: Routines to do buffered file I/O for files organized */
474 /* into records. These routines are highly non-reentrant: they use a */
475 /* global buffer and a global file id, so only they can only access one */
476 /* file at a time. */
477 /* buffopen() should not be called on a new file until buffclose has been */
478 /* called on the old one. */
479 /*-------------------------------------------------------------------------*/
480
481 genfile bfile;
482
483 static uchar *buffer=NULL;
484 static long buffsize; /* How big the buffer is */
485 static long record_size; /* Size of a record in the file */
486 static long buff_frame; /* The file index corrosponding to buffer[0] */
487 static long buff_fcnt; /* Number of records that can be held in the buffer */
488 static long real_buff_fcnt; /* Number of records actually held in buffer */
489 static long buff_rsize; /* Minimum amount that must be read. */
490
491 static long block_size; /* Size of the current block
492 (for non-AGX files, this is just the filesize) */
493 static long block_offset; /* Offset of current block in file (this should
494 be zero for non-AGX files) */
495
496
497 static void buff_setrecsize(long recsize)
498 {
499 char *errstr;
500
501 record_size=recsize;
502 real_buff_fcnt=buff_fcnt=buffsize/record_size;
503 buff_frame=0;
504
505 /* Note that real_buff_cnt==buff_fcnt in this case because
506 the buffer will have already been resized to be <=
507 the block size-- so we don't need to worry about the
508 buffer being larger than the data we're reading in. */
509
510 binseek(bfile,block_offset);
511 if (!binread(bfile,buffer,record_size,real_buff_fcnt,&errstr))
512 fatal(errstr);
513 }
514
515
516
517 long buffopen(fc_type fc,filetype ext,long minbuff,char *rectype,long recnum)
518 /* Returns record size; print out error and halt on failure */
519 /* (if agx_file, it returns the filesize instead) */
520 /* rectype="noun","room", etc. recnum=number of records expected */
521 /* If rectype==NULL, buffopen() will return 0 on failure instead of
522 halting */
523 /* For AGX files, recsize should be set to minbuff... but
524 buffreopen will be called before any major file activity
525 (in particular, recnum should be 1) */
526 {
527 long filesize;
528 long recsize;
529 char ebuff[200];
530 char *errstr;
531
532 assert(buffer==NULL); /* If not, it means these routines have been
533 called by someone else who isn't done yet */
534
535 bfile=readopen(fc,ext,&errstr);
536 if (errstr!=NULL) {
537 if (rectype==NULL)
538 { rfree(errstr); return 0;}
539 else
540 fatal(errstr);
541 }
542
543 filesize=binsize(bfile);
544
545 block_size=filesize;
546 block_offset=0;
547 if (agx_file) block_size=minbuff; /* Just for the beginning */
548
549 if (block_size % recnum !=0) {
550 sprintf(ebuff,"Fractional record count in %s file.",rectype);
551 agtwarn(ebuff,0);}
552 buff_rsize=recsize=block_size/recnum;
553 if (buff_rsize>minbuff) buff_rsize=minbuff;
554
555 /* No point in having a buffer bigger than the block size */
556 buffsize=BUFF_SIZE;
557 if (block_size<buffsize) buffsize=block_size;
558
559 /* ... but it needs to be big enough: */
560 if (buffsize<minbuff) buffsize=minbuff;
561 if (buffsize<recsize) buffsize=recsize;
562
563 buffer=rmalloc(buffsize); /* Might want to make this adaptive eventually */
564
565 buff_setrecsize(recsize);
566 if (!agx_file && DIAG) {
567 char *s;
568 s=formal_name(fc,ext);
569 rprintf("Reading %s file %s (size:%ld)\n",rectype,s,filesize);
570 rfree(s);
571 rprintf(" Record size= Formal:%d File:%ld",minbuff,recsize);
572 }
573 if (agx_file) return (long) filesize;
574 else return (long) recsize;
575 }
576
577
578 /* Compute the game signature: a checksum of relevant parts of the file */
579
580 static void compute_sig(uchar *buff)
581 {
582 long bp;
583 for(bp=0;bp<buff_rsize;bp++)
584 game_sig=( game_sig+buff[bp] ) & 0xFFFF;
585 }
586
587 uchar *buffread(long index)
588 {
589 uchar *bptr;
590 char *errstr;
591
592 assert(buff_rsize<=record_size);
593 if (index>=buff_frame && index<buff_frame+real_buff_fcnt)
594 bptr=buffer+(index-buff_frame)*record_size;
595 else {
596 binseek(bfile,block_offset+index*record_size);
597 real_buff_fcnt=block_size/record_size-index; /* How many records
598 could we read in? */
599 if (real_buff_fcnt>buff_fcnt)
600 real_buff_fcnt=buff_fcnt; /* Don't overflow buffer */
601 if (!binread(bfile,buffer,record_size,real_buff_fcnt,&errstr))
602 fatal(errstr);
603 buff_frame=index;
604 bptr=buffer;
605 }
606 if (!agx_file) compute_sig(bptr);
607 return bptr;
608 }
609
610
611 void buffclose(void)
612 {
613 readclose(bfile);
614 rfree(buffer);
615 }
616
617
618 /* This changes the record size and offset settings of the buffered
619 file so we can read files that consist of multiple sections with
620 different structures */
621 static void buffreopen(long f_ofs, long file_recsize, long recnum,
622 long bl_size, char *rectype)
623 {
624 char ebuff[200];
625 long recsize;
626
627 /* Compute basic statistics */
628 block_offset=f_ofs; /* Offset of this block */
629 block_size=bl_size; /* Size of the entire block (all records) */
630 if (block_size % recnum !=0) {
631 /* Check that the number of records divides the block size evenly */
632 sprintf(ebuff,"Fractional record count in %s block.",rectype);
633 agtwarn(ebuff,0);}
634 buff_rsize=recsize=block_size/recnum;
635 if (buff_rsize>file_recsize) buff_rsize=file_recsize;
636 /* recsize is the size of each record in the file.
637 buff_rsize is the internal size of each record (the part
638 we actually look at, which may be smaller than recsize) */
639
640 /* No point in having a buffer bigger than the block size */
641 buffsize=BUFF_SIZE;
642 if (block_size<buffsize) buffsize=block_size;
643
644 /* The buffer needs to be at least as big as one block, so
645 we have space to both read it in and so we can look at the
646 block without having to worry about how big it really is */
647 if (buffsize<file_recsize) buffsize=file_recsize;
648 if (buffsize<recsize) buffsize=recsize;
649
650 rfree(buffer);
651 buffer=rmalloc(buffsize); /* Resize the buffer */
652
653 buff_setrecsize(recsize); /* Set up remaining stats */
654 }
655
656
657 /*-------------------------------------------------------------------------*/
658 /* Buffered file output: Routines to buffer output for files organized */
659 /* into records. These routines are highly non-reentrant: they use a */
660 /* global buffer and a global file id, so only they can only access one */
661 /* file at a time. */
662 /* This routine uses the same buffer and data structures as the reading */
663 /* routines above, so both sets of routines should not be used */
664 /* concurrently */
665 /*-------------------------------------------------------------------------*/
666
667 /* #define DEBUG_SEEK*/ /* Debug seek beyond EOF problem */
668
669 static long bw_first,bw_last; /* First and last record in buffer written to.
670 This is relative to the beginning of the
671 buffer bw_last points just beyond the last
672 one written to */
673 #ifdef DEBUG_SEEK
674 static long bw_fileleng; /* Current file length */
675 #endif /* DEBUG_SEEK */
676 file_id_type bw_fileid;
677
678 /* Unlike is reading counterpart, this doesn't actually allocate
679 a buffer; that's done by bw_setblock() which should be called before
680 any I/O */
681 void bw_open(fc_type fc,filetype ext)
682 {
683 char *errstr;
684
685 assert(buffer==NULL);
686
687 bfile=writeopen(fc,ext,&bw_fileid,&errstr);
688 if (errstr!=NULL) fatal(errstr);
689 bw_last=0;
690 buffsize=0;
691 buffer=NULL;
692 #ifdef DEBUG_SEEK
693 bw_fileleng=0;
694 #endif
695 }
696
697 static void bw_seek(long offset)
698 {
699 #ifdef DEBUG_SEEK
700 assert(offset<=bw_fileleng);
701 #endif
702 binseek(bfile,offset);
703 }
704
705
706 static void bw_flush(void)
707 {
708 if (bw_first==bw_last) return; /* Nothing to do */
709 bw_first+=buff_frame;
710 bw_last+=buff_frame;
711 bw_seek(block_offset+bw_first*record_size);
712 binwrite(bfile,buffer,record_size,bw_last-bw_first,1);
713 #ifdef DEBUG_SEEK
714 if (block_offset+bw_last*record_size>bw_fileleng)
715 bw_fileleng=block_offset+bw_last*record_size;
716 #endif
717 bw_first=bw_last=0;
718 }
719
720
721
722 static void bw_setblock(long fofs, long recnum, long rsize)
723 /* Set parameters for current block */
724 {
725 /* First, flush old block if neccessary */
726 if (buffer!=NULL) {
727 bw_flush();
728 rfree(buffer);
729 }
730 block_size=rsize*recnum;
731 block_offset=fofs;
732 record_size=rsize;
733 buff_frame=0;bw_first=bw_last=0;
734 buffsize=BUFF_SIZE;
735 if (buffsize>block_size) buffsize=block_size;
736 if (buffsize<rsize) buffsize=rsize;
737 buff_fcnt=buffsize/rsize;
738 buffsize=buff_fcnt*rsize;
739 buffer=rmalloc(buffsize);
740 }
741
742 /* This routine returns a buffer of the current recsize and with
743 the specified index into the file */
744 /* The buffer will be written to disk after the next call to
745 bw_getbuff() or bw_closebuff() */
746 static uchar *bw_getbuff(long index)
747 {
748 index-=buff_frame;
749 if (index<bw_first || index>bw_last || index>=buff_fcnt) {
750 bw_flush();
751 bw_first=bw_last=0;
752 buff_frame=buff_frame+index;
753 index=0;
754 }
755 if (index==bw_last) bw_last++;
756 return buffer+record_size*index;
757 }
758
759
760 /* This flushes all buffers to disk and closes all files */
761 void bw_close(void)
762 {
763 bw_flush();
764 rfree(buffer);
765 writeclose(bfile,bw_fileid);
766 }
767
768 void bw_abort(void)
769 {
770 binremove(bfile,bw_fileid);
771 }
772
773
774 /*-------------------------------------------------------------------------*/
775 /* Block reading and writing code and support for internal buffers */
776 /*-------------------------------------------------------------------------*/
777
778
779 /* If the internal buffer is not NULL, it is used instead of a file */
780 /* (This is used by RESTART, etc. to save state to memory rather than
781 to a file) */
782 static uchar *int_buff=NULL;
783 static long ibuff_ofs, ibuff_rsize;
784
785 void set_internal_buffer(void *buff)
786 {
787 int_buff=(uchar*)buff;
788 }
789
790 static void set_ibuff(long offset, long rsize)
791 {
792 ibuff_ofs=offset;
793 record_size=ibuff_rsize=rsize;
794 }
795
796 static uchar *get_ibuff(long index)
797 {
798 return int_buff+ibuff_ofs+index*ibuff_rsize;
799 }
800
801 /* This does a block write to the currently buffered file.
802 At the moment this itself does no buffering at all; it's intended
803 for high speed reading of blocks of chars for which we've already
804 allocated the space. */
805 static void buff_blockread(void *buff,long size,long offset)
806 {
807 char *errstr;
808
809 if (int_buff!=NULL)
810 memcpy((char*)buff,int_buff+offset,size);
811 else {
812 binseek(bfile,offset);
813 if (!binread(bfile,buff,size,1,&errstr)) fatal(errstr);
814 }
815 }
816
817
818 /* This writes buff to disk. */
819 static void bw_blockwrite(char *buff,long size,long offset)
820 {
821 if (int_buff!=NULL)
822 memcpy(int_buff+offset,(char*)buff,size);
823 else {
824 bw_flush();
825 bw_seek(offset);
826 binwrite(bfile,buff,size,1,1);
827 #ifdef DEBUG_SEEK
828 if (offset+size>bw_fileleng) bw_fileleng=offset+size;
829 #endif
830 }
831 }
832
833
834 /*-------------------------------------------------------------------------*/
835 /* Platform-independent record-based file I/O: Routines to read and write */
836 /* files according to the file_info data structures. */
837 /* These routines use the buffered I/O routines above */
838 /*-------------------------------------------------------------------------*/
839
840 /* Length of file datatypes */
841 const size_t ft_leng[FT_COUNT]={0,2,2, /* END, int16, and uint16 */
842 4,4, /* int32 and uint32 */
843 1,2,0, /* byte, version, rbool */
844 8,4, /* descptr, ss_ptr */
845 2,26, /* slist, path[13] */
846 4,4, /* cmdptr, dictptr */
847 81, /* tline */
848 1,1}; /* char, cfg */
849
850
851 long compute_recsize(file_info *recinfo)
852 {
853 long cnt, bcnt;
854
855 cnt=0;
856 for(;recinfo->ftype!=FT_END;recinfo++)
857 if (recinfo->ftype==FT_BOOL) {
858 for(bcnt=0;recinfo->ftype==FT_BOOL;recinfo++,bcnt++);
859 recinfo--;
860 cnt+=(bcnt+7)/8; /* +7 is to round up */
861 } else
862 cnt+=ft_leng[recinfo->ftype];
863 return cnt;
864 }
865
866 static const int agx_version[]={0,0000,1800,2000,3200,3500,8200,8300,
867 5000,5050,5070,10000,10050,15000,15500,16000,20000};
868
869 static int agx_decode_version(int vercode)
870 {
871 if (vercode&1) /* Large/Soggy */
872 if (vercode==3201) ver=4;
873 else ver=2;
874 else
875 if (vercode<10000) ver=1;
876 else ver=3;
877 switch(vercode&(~1))
878 {
879 case 0000: return AGT10;
880 case 1800: return AGT118;
881 case 1900: return AGT12;
882 case 2000: return AGT12;
883 case 3200: return AGTCOS;
884 case 3500: return AGT135;
885 case 5000: return AGT15;
886 case 5050: return AGT15F;
887 case 5070: return AGT16;
888 case 8200: return AGT182;
889 case 8300: return AGT183;
890 case 8350: return AGT183;
891 case 10000:return AGTME10;
892 case 10050:return AGTME10A;
893 case 15000:return AGTME15;
894 case 15500:return AGTME155;
895 case 16000:return AGTME16;
896 case 20000:return AGX00;
897 default:agtwarn("Unrecognize AGT version",0);
898 return 0;
899 }
900 }
901
902 /* The following reads a section of a file into variables, doing
903 the neccessary conversions. It is the foundation of all the generic
904 file reading code */
905
906 #define p(t) ((t*)(rec_desc->ptr))
907 #define fixu16(n1,n2) ( ((long)(n1))|( ((long)(n2))<<8 ))
908
909 /* This is as large as the largest data structure we could run into */
910 static const uchar zero_block[81]={0,0,0,0,0,0,0,0,
911 0,0,0,0,0,0,0,0,
912 0,0,0,0,0,0,0,0,
913 0,0,0,0,0,0,0,0,
914 0,0,0,0,0,0,0,0,
915 0,0,0,0,0,0,0,0,
916 0,0,0,0,0,0,0,0,
917 0,0,0,0,0,0,0,0,
918 0,0,0,0,0,0,0,0,
919 0,0,0,0,0,0,0,0,
920 0};
921
922 static void read_filerec(const file_info *rec_desc, const uchar *filedata)
923 {
924 uchar mask;
925 rbool past_eob; /* Are we past the end of block? */
926 const uchar *filebase;
927
928 mask=1;
929 past_eob=0;
930 filebase=filedata;
931 for(;rec_desc->ftype!=FT_END;rec_desc++) {
932 if (mask!=1 && rec_desc->ftype!=FT_BOOL) { /* Just finished rboolean */
933 mask=1;
934 filedata+=1;
935 }
936 if (filebase==NULL || (filedata-filebase)>=record_size ) {
937 /* We're past the end of the block; read in zeros for the rest
938 of entries. */
939 past_eob=1;
940 filedata=zero_block;
941 filebase=NULL;
942 }
943 switch(rec_desc->ftype)
944 {
945 case FT_INT16:
946 if (rec_desc->dtype==DT_LONG)
947 *p(long)=fixsign16(filedata[0],filedata[1]);
948 else
949 *p(integer)=fixsign16(filedata[0],filedata[1]);
950 break;
951 case FT_UINT16:
952 *p(long)=fixu16(filedata[0],filedata[1]);
953 break;
954 case FT_CMDPTR: /* cmd ptr */
955 case FT_INT32:
956 *p(long)=fixsign32(filedata[0],filedata[1],
957 filedata[2],filedata[3]);
958 break;
959 case FT_UINT32:
960 if (filedata[3]&0x80)
961 agtwarn("File value out of range",0);
962 *p(long)=fixsign32(filedata[0],filedata[1],
963 filedata[2],filedata[3]&0x7F);
964 break;
965 case FT_BYTE: *p(uchar)=filedata[0];break;
966 case FT_CHAR:
967 *p(uchar)=trans_ascii[filedata[0]^'r'];
968 break;
969 case FT_VERSION:
970 *p(int)=agx_decode_version(fixu16(filedata[0],filedata[1]));
971 break;
972 case FT_CFG:
973 if (filedata[0]!=2 && !past_eob)
974 *p(rbool)=filedata[0];
975 break;
976 case FT_BOOL:
977 *p(rbool)=( (filedata[0]&mask)!=0);
978 if (mask==0x80) {
979 filedata++; mask=1;
980 } else
981 mask<<=1;
982 break;
983 case FT_DESCPTR:
984 if (skip_descr) break;
985 p(descr_ptr)->start=fixsign32(filedata[0],filedata[1],
986 filedata[2],filedata[3]);
987 p(descr_ptr)->size=fixsign32(filedata[4],filedata[5],
988 filedata[6],filedata[7]);
989 break;
990 case FT_STR: /* ss_string ptr */
991 *p(char*)=static_str+fixsign32(filedata[0],filedata[1],
992 filedata[2],filedata[3]);
993 break;
994 case FT_SLIST:
995 *p(slist)=fixsign16(filedata[0],filedata[1]);
996 break;
997 case FT_PATHARRAY: /* integer array[13] */
998 {
999 int i;
1000 for(i=0;i<13;i++)
1001 p(integer)[i]=fixsign16(filedata[2*i],filedata[2*i+1]);
1002 break;
1003 }
1004 case FT_TLINE: { /* string of length at most 80 characters +null */
1005 uchar *s;
1006 int i;
1007 s=(uchar*)*p(tline);
1008 for(i=0; i<80; i++)
1009 s[i]=trans_ascii[filedata[i]^'r'];
1010 s[80]=0;
1011 break;
1012 }
1013 case FT_DICTPTR: /* ptr into dictstr */
1014 *p(char*)=dictstr+fixsign32(filedata[0],filedata[1],
1015 filedata[2],filedata[3]);
1016 break;
1017 default:fatal("Unreconized field type");
1018 }
1019 filedata+=ft_leng[rec_desc->ftype];
1020 }
1021 }
1022
1023
1024 #define v(t) (*(t*)(rec_desc->ptr))
1025 /* Here is the corresponding routien for _writing_ to files */
1026 /* This copies the contents of a record into a buffer */
1027
1028 static void write_filerec(const file_info *rec_desc, uchar *filedata)
1029 {
1030 uchar mask;
1031
1032 mask=1;
1033 for(;rec_desc->ftype!=FT_END;rec_desc++) {
1034 if (mask!=1 && rec_desc->ftype!=FT_BOOL) { /* Just finished rboolean */
1035 mask=1;
1036 filedata+=1;
1037 }
1038 switch(rec_desc->ftype)
1039 {
1040 case FT_INT16:
1041 if (rec_desc->dtype==DT_LONG) {
1042 filedata[0]=v(long)&0xFF;
1043 filedata[1]=(v(long)>>8)&0xFF;
1044 } else {
1045 filedata[0]=v(integer)&0xFF;
1046 filedata[1]=(v(integer)>>8)&0xFF;
1047 }
1048 break;
1049 case FT_UINT16:
1050 filedata[0]=v(long)&0xFF;
1051 filedata[1]=(v(long)>>8)&0xFF;
1052 break;
1053 case FT_CMDPTR: /* cmd ptr */
1054 case FT_INT32:
1055 case FT_UINT32:
1056 filedata[0]=v(long)&0xFF;
1057 filedata[1]=(v(long)>>8)&0xFF;
1058 filedata[2]=(v(long)>>16)&0xFF;
1059 filedata[3]=(v(long)>>24)&0xFF;
1060 break;
1061 case FT_BYTE: filedata[0]=v(uchar);break;
1062 case FT_CFG: filedata[0]=v(uchar);break;
1063 case FT_CHAR: filedata[0]=v(uchar)^'r';break;
1064 case FT_VERSION:
1065 {
1066 int tver;
1067 tver=agx_version[v(int)];
1068 if (ver==2 || ver==4) tver+=1;
1069 filedata[0]=tver&0xFF;
1070 filedata[1]=(tver>>8)&0xFF;
1071 break;
1072 }
1073 case FT_BOOL:
1074 if (mask==1) filedata[0]=0;
1075 filedata[0]|=v(rbool)?mask:0;
1076 if (mask==0x80) {
1077 filedata++; mask=1;
1078 } else
1079 mask<<=1;
1080 break;
1081 case FT_DESCPTR:
1082 {
1083 long i,n1,n2;
1084 n1=p(descr_ptr)->start;
1085 n2=p(descr_ptr)->size;
1086 for(i=0;i<4;i++) {
1087 filedata[i]=n1&0xFF;
1088 filedata[i+4]=n2&0xFF;
1089 n1>>=8;n2>>=8;
1090 }
1091 }
1092 break;
1093 case FT_STR: /* ss_string ptr */
1094 {
1095 long delta;
1096 delta=v(char*)-static_str;
1097 filedata[0]=delta&0xFF;
1098 filedata[1]=(delta>>8)&0xFF;
1099 filedata[2]=(delta>>16)&0xFF;
1100 filedata[3]=(delta>>24)&0xFF;
1101 break;
1102 }
1103 case FT_SLIST:
1104 filedata[0]=v(slist)&0xFF;
1105 filedata[1]=(v(slist)>>8)&0xFF;
1106 break;
1107 case FT_PATHARRAY: /* integer array[13] */
1108 {
1109 int i;
1110 for(i=0;i<13;i++) {
1111 filedata[2*i]=*(p(integer)+i)&0xFF;
1112 filedata[2*i+1]=(*(p(integer)+i)>>8)&0xFF;
1113 }
1114 break;
1115 }
1116 case FT_TLINE: { /* string of length at most 80 characters +null */
1117 uchar *s;
1118 int i;
1119 s=(uchar*)v(tline);
1120 for(i=0; i<80; i++)
1121 filedata[i]=s[i]^'r';
1122 filedata[80]=0;
1123 break;
1124 }
1125 case FT_DICTPTR: /* ptr into dictstr */
1126 {
1127 long delta;
1128 delta=v(char*)-dictstr;
1129 filedata[0]=delta&0xFF;
1130 filedata[1]=(delta>>8)&0xFF;
1131 filedata[2]=(delta>>16)&0xFF;
1132 filedata[3]=(delta>>24)&0xFF;
1133 break;
1134 }
1135 default:fatal("Unreconized field type");
1136 }
1137 filedata+=ft_leng[rec_desc->ftype];
1138 }
1139 }
1140
1141 #undef v
1142 #undef p
1143
1144
1145
1146
1147 /* This reads in a structure array */
1148 /* base=the beginning of the array. If NULL, this is malloc'd and returned
1149 eltsize = the size of each structure
1150 numelts = the number of elements in the array
1151 field_info = the arrangement of fields within the strucutre
1152 rectype = string to print out for error messages
1153 file_offset = the offset of the beginning of the array into the file
1154 */
1155 void *read_recarray(void *base, long eltsize, long numelts,
1156 file_info *field_info, char *rectype,
1157 long file_offset, long file_blocksize)
1158 {
1159 long i;
1160 file_info *curr;
1161 uchar *file_data;
1162
1163 if (numelts==0) return NULL;
1164
1165 if (int_buff)
1166 set_ibuff(file_offset,compute_recsize(field_info));
1167 else
1168 buffreopen(file_offset, compute_recsize(field_info), numelts,
1169 file_blocksize, rectype);
1170
1171 if (base==NULL)
1172 base=rmalloc(eltsize*numelts);
1173
1174 for(curr=field_info;curr->ftype!=FT_END;curr++)
1175 if (curr->dtype!=DT_DESCPTR && curr->dtype!=DT_CMDPTR)
1176 curr->ptr=( (char*)base + curr->offset);
1177
1178 for(i=0;i<numelts;i++) {
1179 if (!int_buff)
1180 file_data=buffread(i);
1181 else
1182 file_data=get_ibuff(i);
1183 read_filerec(field_info,file_data);
1184 for(curr=field_info;curr->ftype!=FT_END;curr++)
1185 if (curr->dtype==DT_DESCPTR)
1186 curr->ptr=(char*)(curr->ptr)+sizeof(descr_ptr);
1187 else if (curr->dtype==DT_CMDPTR)
1188 curr->ptr=(char*)(curr->ptr)+sizeof(long);
1189 else
1190 curr->ptr=(char*)(curr->ptr)+eltsize;
1191 }
1192
1193 return base;
1194 }
1195
1196
1197 /* A NULL value means to write junk; we're just producing
1198 a placeholder for systems that can't seek beyond the end-of-file */
1199
1200 long write_recarray(void *base, long eltsize, long numelts,
1201 file_info *field_info, long file_offset)
1202 {
1203 long i;
1204 file_info *curr;
1205 uchar *file_data;
1206
1207 if (numelts==0) return 0;
1208
1209 if (int_buff)
1210 set_ibuff(file_offset,compute_recsize(field_info));
1211 else
1212 bw_setblock(file_offset, numelts, compute_recsize(field_info));
1213
1214 if (base!=NULL)
1215 for(curr=field_info;curr->ftype!=FT_END;curr++)
1216 if (curr->dtype!=DT_DESCPTR && curr->dtype!=DT_CMDPTR)
1217 curr->ptr=( (char*)base + curr->offset);
1218
1219 for(i=0;i<numelts;i++) {
1220 if (int_buff)
1221 file_data=get_ibuff(i);
1222 else
1223 file_data=bw_getbuff(i);
1224 if (base!=NULL) {
1225 write_filerec(field_info,file_data);
1226 for(curr=field_info;curr->ftype!=FT_END;curr++)
1227 if (curr->dtype==DT_DESCPTR)
1228 curr->ptr=(char*)(curr->ptr)+sizeof(descr_ptr);
1229 else if (curr->dtype==DT_CMDPTR)
1230 curr->ptr=(char*)(curr->ptr)+sizeof(long);
1231 else
1232 curr->ptr=(char*)(curr->ptr)+eltsize;
1233 }
1234 }
1235 return compute_recsize(field_info)*numelts;
1236 }
1237
1238
1239 void read_globalrec(file_info *global_info, char *rectype,
1240 long file_offset, long file_blocksize)
1241 {
1242 uchar *file_data;
1243
1244 if (int_buff) {
1245 set_ibuff(file_offset,compute_recsize(global_info));
1246 file_data=get_ibuff(0);
1247 } else {
1248 buffreopen(file_offset, compute_recsize(global_info), 1, file_blocksize,
1249 rectype);
1250 file_data=buffread(0);
1251 }
1252 read_filerec(global_info,file_data);
1253 }
1254
1255
1256 long write_globalrec(file_info *global_info, long file_offset)
1257 {
1258 uchar *file_data;
1259
1260 if (int_buff) {
1261 set_ibuff(file_offset,compute_recsize(global_info));
1262 file_data=get_ibuff(0);
1263 } else {
1264 bw_setblock(file_offset, 1, compute_recsize(global_info));
1265 file_data=bw_getbuff(0);
1266 }
1267 write_filerec(global_info,file_data);
1268 return compute_recsize(global_info);
1269 }
1270
1271
1272
1273 static file_info fi_temp[]={
1274 {0,DT_DEFAULT,NULL,0},
1275 endrec
1276 };
1277
1278 /* This routine reads in an array of simple data */
1279
1280 void *read_recblock(void *base,int ftype,long numrec,
1281 long offset, long bl_size)
1282 {
1283 int dsize;
1284
1285 switch(ftype)
1286 {
1287 case FT_CHAR:
1288 case FT_BYTE:
1289 if (base==NULL) base=rmalloc(numrec*sizeof(char));
1290 buff_blockread(base,numrec,offset);
1291 if (ftype==FT_CHAR) {
1292 long i;
1293 for(i=0;i<numrec;i++)
1294 ((uchar*)base)[i]=trans_ascii[ ((uchar*)base)[i]^'r' ];
1295 }
1296 return base;
1297 case FT_SLIST: dsize=sizeof(slist);break;
1298 case FT_INT16: dsize=sizeof(integer);break;
1299 case FT_UINT16:
1300 case FT_INT32: dsize=sizeof(long); break;
1301 case FT_STR:
1302 case FT_DICTPTR: dsize=sizeof(char*);break;
1303 default:
1304 fatal("Invalid argument to read_recblock.");
1305 dsize=0; /* Silence compiler warnings; this will never actually
1306 be reached. */
1307 }
1308
1309 fi_temp[0].ftype=ftype;
1310 return read_recarray(base, dsize, numrec, fi_temp, "", offset, bl_size);
1311 }
1312
1313
1314 long write_recblock(void *base,int ftype,long numrec, long offset)
1315 {
1316 int dsize;
1317
1318 if (numrec==0) return 0;
1319 switch(ftype)
1320 {
1321 case FT_CHAR: {
1322 int i;
1323 for(i=0;i<numrec;i++)
1324 ((uchar*)base)[i]=((uchar*)base)[i]^'r';
1325 }
1326 /* Fall through.... */
1327 case FT_BYTE:
1328 bw_blockwrite(base,numrec,offset);
1329 return numrec;
1330 case FT_SLIST: dsize=sizeof(slist);break;
1331 case FT_INT16: dsize=sizeof(integer);break;
1332 case FT_INT32: dsize=sizeof(long); break;
1333 case FT_STR:
1334 case FT_DICTPTR: dsize=sizeof(char*);break;
1335 default:
1336 fatal("Invalid argument to write_recblock.");
1337 dsize=0; /* Silence compiler warnings; this will never actually
1338 be reached. */
1339 }
1340
1341 fi_temp[0].ftype=ftype;
1342 return write_recarray(base, dsize, numrec, fi_temp, offset);
1343 }
1344
1345
1346 /* ------------------------------------------------------------------- */
1347 /* "Profiling" functions */
1348 /* Routines for timing code execution */
1349 /* These will only work on POSIX systems */
1350
1351 #ifdef PROFILE_SUPPORT
1352
1353 static struct tms start;
1354 clock_t start_realtime;
1355 static struct tms delta;
1356 clock_t delta_realtime;
1357
1358 void resetwatch(void)
1359 {
1360 delta.tms_utime=delta.tms_stime=delta.tms_cutime=delta.tms_cstime=0;
1361 delta_realtime=0;
1362 start_realtime=times(&start);
1363 }
1364
1365 void startwatch(void)
1366 {
1367 start_realtime=times(&start);
1368 }
1369
1370 static char watchbuff[81];
1371 char *timestring(void)
1372 {
1373 sprintf(watchbuff,"User:%ld.%02ld Sys:%ld.%02ld Total:%ld.%02ld"
1374 " Real:%ld.%02ld",
1375 delta.tms_utime/100, delta.tms_utime%100,
1376 delta.tms_stime/100, delta.tms_stime%100,
1377 (delta.tms_utime+delta.tms_stime)/100,
1378 (delta.tms_utime+delta.tms_stime)%100,
1379 delta_realtime/100, delta_realtime%100
1380 );
1381 return watchbuff;
1382 }
1383
1384 char *stopwatch(void)
1385 {
1386 struct tms curr;
1387
1388 delta_realtime+=times(&curr)-start_realtime;
1389 delta.tms_utime+=(curr.tms_utime-start.tms_utime);
1390 delta.tms_stime+=(curr.tms_stime-start.tms_stime);
1391 delta.tms_cutime+=(curr.tms_cutime-start.tms_cutime);
1392 delta.tms_cstime+=(curr.tms_cstime-start.tms_cstime);
1393 return timestring();
1394 }
1395
1396 /* 5+7+9+8+4*3+4*?? = 41+?? */
1397
1398 #endif /* PROFILE_SUPPORT */
1399
1400
1401
1402
1403
1404