home *** CD-ROM | disk | FTP | other *** search
/ Dream 52 / Amiga_Dream_52.iso / RiscOS / APP / DEVS / FORTH / BEETLE / BEETLE.ZIP / Beetle / loadobj.c < prev    next >
C/C++ Source or Header  |  1997-04-22  |  2KB  |  79 lines

  1. /* LOADOBJ.C
  2.  
  3.     Vrsn  Date   Comment
  4.     ----|-------|---------------------------------------------------------------
  5.     0.00 24jan95
  6.     0.01 24feb95 Made internal routines and globals static, and made the array
  7.                  magic in load_object one byte smaller, as it can be. A bug in
  8.                  detecting when a module would not fit in memory was corrected,
  9.                  and CELL_W used to replace 4 where appropriate.
  10.     0.02 01apr95 Made length be read correctly on big-endian machines.
  11.     0.03 21may96 Made error -1 be returned always if address = MEMORY.
  12.     0.04 23may96 Fixed some unbalanced brackets.
  13.  
  14.     Reuben Thomas
  15.  
  16.  
  17.     The interface call load_object(file, address) : integer.
  18.  
  19. */
  20.  
  21.  
  22. #include <stdio.h>
  23. #include <string.h>
  24. #include <setjmp.h>
  25. #include "beetle.h"     /* main header */
  26.  
  27.  
  28. static void reverse(CELL *start, UCELL length)
  29. {
  30.     UCELL i;
  31.  
  32.     for (i = 0; i < length; i++)
  33.         start[i] = (CELL)(((UCELL) start[i] << 24) | ((UCELL)start[i] >> 24) |
  34.             (((UCELL)start[i] & 0xff00) << 8) |
  35.             (((UCELL)start[i] & 0xff0000) >> 8));
  36. }
  37.  
  38.  
  39. static jmp_buf env;
  40.  
  41. static int get(FILE *fp)
  42. {
  43.     int t = getc(fp);
  44.     if (t == EOF) longjmp(env, -3);
  45.     return t;
  46. }
  47.  
  48. int load_object(FILE *file, CELL *address)
  49. {
  50.     char magic[8];
  51.     int endism, reversed, i, err = 0;
  52.     UCELL length = 0;
  53.  
  54.     if ((err = setjmp(env)) == 0) {
  55.         for (i = 0; i < 7; i++) magic[i] = get(file);
  56.         magic[7] = '\0';
  57.         if (strcmp(magic, "BEETLE")) { err = -2; goto error; }
  58.  
  59.         endism = get(file);
  60.         if (endism != 0 && endism != 1) { err = -2; goto error; }
  61.         reversed = endism ^ ENDISM;
  62.  
  63.         for (i = 0; i < CELL_W; i++) length |= get(file) << (8 * i);
  64.         if (endism) reverse((CELL *)&length, 1);
  65.         if ((((address - (CELL *)M0) + length) * CELL_W > MEMORY) ||
  66.             (address - (CELL *)M0) * CELL_W == MEMORY) {
  67.             err = -1;
  68.             goto error;
  69.         }
  70.  
  71.         for (i = 0; i < length * CELL_W; i++) ((BYTE *)address)[i] = get(file);
  72.         if (reversed) reverse(address, length);
  73.  
  74.         return 0;
  75.     } else {
  76. error:  return err;
  77.     }
  78. }
  79.