summaryrefslogtreecommitdiff
path: root/byterun/extern.c
blob: eadea204046f0668faac0bf2f78b664bb4f869b7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
/***********************************************************************/
/*                                                                     */
/*                           Objective Caml                            */
/*                                                                     */
/*            Xavier Leroy, projet Cristal, INRIA Rocquencourt         */
/*                                                                     */
/*  Copyright 1996 Institut National de Recherche en Informatique et   */
/*  en Automatique.  All rights reserved.  This file is distributed    */
/*  under the terms of the GNU Library General Public License.         */
/*                                                                     */
/***********************************************************************/

/* $Id$ */

/* Structured output */

#include <string.h>
#include "alloc.h"
#include "custom.h"
#include "fail.h"
#include "gc.h"
#include "intext.h"
#include "io.h"
#include "memory.h"
#include "misc.h"
#include "mlvalues.h"
#include "reverse.h"

/* To keep track of sharing in externed objects */

typedef unsigned long byteoffset_t;

struct extern_obj {
  byteoffset_t ofs;
  value obj;
};

static byteoffset_t initial_ofs = 1; /* Initial value of object offsets */
static struct extern_obj * extern_table = NULL;
static unsigned long extern_table_size;
static byteoffset_t obj_counter;    /* Number of objects emitted so far */

#ifdef ARCH_SIXTYFOUR
#define Hash(v) (((unsigned long) ((v) >> 3)) % extern_table_size)
#else
#define Hash(v) (((unsigned long) ((v) >> 2)) % extern_table_size)
#endif

/* Allocate a new extern table */
static void alloc_extern_table(void)
{
  asize_t i;
  extern_table = (struct extern_obj *)
                 stat_alloc(extern_table_size * sizeof(struct extern_obj));
  for (i = 0; i < extern_table_size; i++) extern_table[i].ofs = 0;
}

/* Grow the extern table */
static void resize_extern_table(void)
{
  asize_t oldsize;
  struct extern_obj * oldtable;
  value obj;
  byteoffset_t ofs;
  asize_t i, h;

  oldsize = extern_table_size;
  oldtable = extern_table;
  extern_table_size = 2 * extern_table_size;
  alloc_extern_table();
  for (i = 0; i < oldsize; i++) {
    ofs = oldtable[i].ofs;
    if (ofs >= initial_ofs) {
      obj = oldtable[i].obj;
      h = Hash(obj);
      while (extern_table[h].ofs >= initial_ofs) {
        h++;
        if (h >= extern_table_size) h = 0;
      }
      extern_table[h].ofs = ofs;
      extern_table[h].obj = obj;
    }
  }
  stat_free(oldtable);
}

/* Free the extern table. We keep it around for next call if
   it's still small (we did not grow it) and the initial offset
   does not risk running over next time. */
static void free_extern_table(void)
{
  if (extern_table_size > INITIAL_EXTERN_TABLE_SIZE ||
      initial_ofs >= INITIAL_OFFSET_MAX) {
    stat_free(extern_table);
    extern_table = NULL;
  }
}

/* To buffer the output */

static char * extern_block, * extern_ptr, * extern_limit;
static int extern_block_malloced;

static void alloc_extern_block(void)
{
  extern_block = stat_alloc(INITIAL_EXTERN_BLOCK_SIZE);
  extern_limit = extern_block + INITIAL_EXTERN_BLOCK_SIZE;
  extern_ptr = extern_block;
  extern_block_malloced = 1;
}

static void resize_extern_block(int required)
{
  long curr_pos, size, reqd_size;

  if (! extern_block_malloced) {
    initial_ofs += obj_counter;
    free_extern_table();
    failwith("Marshal.to_buffer: buffer overflow");
  }
  curr_pos = extern_ptr - extern_block;
  size = extern_limit - extern_block;
  reqd_size = curr_pos + required;
  while (size <= reqd_size) size *= 2;
  extern_block = stat_resize(extern_block, size);
  extern_limit = extern_block + size;
  extern_ptr = extern_block + curr_pos;
}

/* Write characters, integers, and blocks in the output buffer */

#define Write(c) \
  if (extern_ptr >= extern_limit) resize_extern_block(1); \
  *extern_ptr++ = (c)

static void writeblock(char *data, long int len)
{
  if (extern_ptr + len > extern_limit) resize_extern_block(len);
  memmove(extern_ptr, data, len);
  extern_ptr += len;
}

static void writecode8(int code, long int val)
{
  if (extern_ptr + 2 > extern_limit) resize_extern_block(2);
  extern_ptr[0] = code;
  extern_ptr[1] = val;
  extern_ptr += 2;
}

static void writecode16(int code, long int val)
{
  if (extern_ptr + 3 > extern_limit) resize_extern_block(3);
  extern_ptr[0] = code;
  extern_ptr[1] = val >> 8;
  extern_ptr[2] = val;
  extern_ptr += 3;
}

static void write32(long int val)
{
  if (extern_ptr + 4 > extern_limit) resize_extern_block(4);
  extern_ptr[0] = val >> 24;
  extern_ptr[1] = val >> 16;
  extern_ptr[2] = val >> 8;
  extern_ptr[3] = val;
  extern_ptr += 4;
}

static void writecode32(int code, long int val)
{
  if (extern_ptr + 5 > extern_limit) resize_extern_block(5);
  extern_ptr[0] = code;
  extern_ptr[1] = val >> 24;
  extern_ptr[2] = val >> 16;
  extern_ptr[3] = val >> 8;
  extern_ptr[4] = val;
  extern_ptr += 5;
}

#ifdef ARCH_SIXTYFOUR
static void writecode64(int code, long val)
{
  int i;
  if (extern_ptr + 9 > extern_limit) resize_extern_block(9);
  *extern_ptr ++ = code;
  for (i = 64 - 8; i >= 0; i -= 8) *extern_ptr++ = val >> i;
}
#endif

/* Marshal the given value in the output buffer */

static unsigned long size_32;  /* Size in words of 32-bit block for struct. */
static unsigned long size_64;  /* Size in words of 64-bit block for struct. */

static int extern_ignore_sharing; /* Flag to ignore sharing */
static int extern_closures;     /* Flag to allow externing code pointers */

static void extern_invalid_argument(char *msg)
{
  if (extern_block_malloced) stat_free(extern_block);
  initial_ofs += obj_counter;
  free_extern_table();
  invalid_argument(msg);
}

static void extern_rec(value v)
{
 tailcall:
  if (Is_long(v)) {
    long n = Long_val(v);
    if (n >= 0 && n < 0x40) {
      Write(PREFIX_SMALL_INT + n);
    } else if (n >= -(1 << 7) && n < (1 << 7)) {
      writecode8(CODE_INT8, n);
    } else if (n >= -(1 << 15) && n < (1 << 15)) {
      writecode16(CODE_INT16, n);
#ifdef ARCH_SIXTYFOUR
    } else if (n < -(1L << 31) || n >= (1L << 31)) {
      writecode64(CODE_INT64, n);
#endif
    } else
      writecode32(CODE_INT32, n);
    return;
  }
  if (Is_young(v) || Is_in_heap(v) || Is_atom(v)) {
    header_t hd = Hd_val(v);
    tag_t tag = Tag_hd(hd);
    mlsize_t sz = Wosize_hd(hd);
    asize_t h;
    /* Atoms are treated specially for two reasons: they are not allocated
       in the externed block, and they are automatically shared. */
    if (sz == 0) {
      if (tag < 16) {
        Write(PREFIX_SMALL_BLOCK + tag);
      } else {
        writecode32(CODE_BLOCK32, hd);
      }
      return;
    }
    /* Check if already seen */
    if (! extern_ignore_sharing && tag != Infix_tag) {
      if (2 * obj_counter >= extern_table_size) resize_extern_table();
      h = Hash(v);
      while (extern_table[h].ofs >= initial_ofs) {
        if (extern_table[h].obj == v) {
          byteoffset_t d = obj_counter - (extern_table[h].ofs - initial_ofs);
          if (d < 0x100) {
            writecode8(CODE_SHARED8, d);
          } else if (d < 0x10000) {
            writecode16(CODE_SHARED16, d);
          } else {
            writecode32(CODE_SHARED32, d);
          }
          return;
        }
        h++;
        if (h >= extern_table_size) h = 0;
      }
      /* Not seen yet. Record the object */
      extern_table[h].ofs = initial_ofs + obj_counter;
      extern_table[h].obj = v;
      obj_counter++;
    }
    /* Output the contents of the object */
    switch(tag) {
    case String_tag: {
      mlsize_t len = string_length(v);
      if (len < 0x20) {
        Write(PREFIX_SMALL_STRING + len);
      } else if (len < 0x100) {
        writecode8(CODE_STRING8, len);
      } else {
        writecode32(CODE_STRING32, len);
      }
      writeblock(String_val(v), len);
      size_32 += 1 + (len + 4) / 4;
      size_64 += 1 + (len + 8) / 8;
      break;
    }
    case Double_tag: {
      if (sizeof(double) != 8)
        extern_invalid_argument("output_value: non-standard floats");
      Write(CODE_DOUBLE_NATIVE);
      writeblock((char *) v, 8);
      size_32 += 1 + 2;
      size_64 += 1 + 1;
      break;
    }
    case Double_array_tag: {
      mlsize_t nfloats;
      if (sizeof(double) != 8)
        extern_invalid_argument("output_value: non-standard floats");
      nfloats = Wosize_val(v) / Double_wosize;
      if (nfloats < 0x100) {
        writecode8(CODE_DOUBLE_ARRAY8_NATIVE, nfloats);
      } else {
        writecode32(CODE_DOUBLE_ARRAY32_NATIVE, nfloats);
      }
      writeblock((char *) v, Bosize_val(v));
      size_32 += 1 + nfloats * 2;
      size_64 += 1 + nfloats;
      break;
    }
    case Abstract_tag:
      extern_invalid_argument("output_value: abstract value");
      break;
    case Infix_tag:
      writecode32(CODE_INFIXPOINTER, Infix_offset_hd(hd));
      extern_rec(v - Infix_offset_hd(hd));
      break;
    case Object_tag:
      extern_invalid_argument("output_value: object value");
      break;
    case Custom_tag: {
      unsigned long sz_32, sz_64;
      char * ident = Custom_ops_val(v)->identifier;
      Write(CODE_CUSTOM);
      writeblock(ident, strlen(ident) + 1);
      Custom_ops_val(v)->serialize(v, &sz_32, &sz_64);
      size_32 += 2 + ((sz_32 + 3) >> 2);  /* header + ops + data */
      size_64 += 2 + ((sz_64 + 7) >> 3);
      break;
    }
    default: {
      mlsize_t i;
      if (tag < 16 && sz < 8) {
        Write(PREFIX_SMALL_BLOCK + tag + (sz << 4));
      } else {
        writecode32(CODE_BLOCK32, Whitehd_hd (hd));
      }
      size_32 += 1 + sz;
      size_64 += 1 + sz;
      for (i = 0; i < sz - 1; i++) extern_rec(Field(v, i));
      v = Field(v, i);
      goto tailcall;
      }
    }
    return;
  }
  if ((char *) v >= code_area_start && (char *) v < code_area_end) {
    if (!extern_closures)
      extern_invalid_argument("output_value: functional value");
    writecode32(CODE_CODEPOINTER, (char *) v - code_area_start);
    writeblock((char *) code_checksum(), 16);
    return;
  }
  extern_invalid_argument("output_value: abstract value");
}

enum { NO_SHARING = 1, CLOSURES = 2 };
static int extern_flags[] = { NO_SHARING, CLOSURES };

static long extern_value(value v, value flags)
{
  long res_len;
  int fl;
  /* Parse flag list */
  fl = convert_flag_list(flags, extern_flags);
  extern_ignore_sharing = fl & NO_SHARING;
  extern_closures = fl & CLOSURES;
  /* Allocate hashtable of objects already seen, if needed */
  extern_table_size = INITIAL_EXTERN_TABLE_SIZE;
  if (extern_table == NULL) {
    alloc_extern_table();
    initial_ofs = 1;
  }
  obj_counter = 0;
  size_32 = 0;
  size_64 = 0;
  /* Write magic number */
  write32(Intext_magic_number);
  /* Set aside space for the sizes */
  extern_ptr += 4*4;
  /* Marshal the object */
  extern_rec(v);
  /* Update initial offset for next call to extern_value(),
     if we decide to keep the table of shared objects. */
  initial_ofs += obj_counter;
  /* Free the table of shared objects (if needed) */
  free_extern_table();
  /* Write the sizes */
#ifdef ARCH_SIXTYFOUR
  if (size_32 >= (1L << 32) || size_64 >= (1L << 32)) {
    /* The object is so big its size cannot be written in the header.
       Besides, some of the block sizes or string lengths or shared offsets
       it contains may have overflowed the 32 bits used to write them. */
    failwith("output_value: object too big");
  }
#endif
  res_len = extern_ptr - extern_block;
  extern_ptr = extern_block + 4;
  write32(res_len - 5*4);
  write32(obj_counter);
  write32(size_32);
  write32(size_64);
  /* Result is res_len bytes starting at extern_block */
  return res_len;
}

void output_val(struct channel *chan, value v, value flags)
{
  long len;
  char * block;

  if (! channel_binary_mode(chan))
    failwith("output_value: not a binary channel");
  alloc_extern_block();
  len = extern_value(v, flags);
  /* During really_putblock, concurrent output_val operations can take
     place (via signal handlers or context switching in systhreads),
     and extern_block may change.  So, save the pointer in a local variable. */
  block = extern_block;
  really_putblock(chan, extern_block, len);
  stat_free(block);
}

value output_value(value vchan, value v, value flags) /* ML */
{
  CAMLparam3 (vchan, v, flags);
  struct channel * channel = Channel(vchan);

  Lock(channel);
  output_val(channel, v, flags);
  Unlock(channel);
  CAMLreturn (Val_unit);
}

value output_value_to_string(value v, value flags) /* ML */
{
  long len;
  value res;
  alloc_extern_block();
  len = extern_value(v, flags);
  res = alloc_string(len);
  memmove(String_val(res), extern_block, len);
  stat_free(extern_block);
  return res;
}

value output_value_to_buffer(value buf, value ofs, value len, value v, value flags) /* ML */
{
  long len_res;
  extern_block = &Byte(buf, Long_val(ofs));
  extern_limit = extern_block + Long_val(len);
  extern_ptr = extern_block;
  extern_block_malloced = 0;
  len_res = extern_value(v, flags);
  return Val_long(len_res);
}

void output_value_to_malloc(value v, value flags,
                            /*out*/ char ** buf, /*out*/ long * len)
{
  long len_res;
  alloc_extern_block();
  len_res = extern_value(v, flags);
  *buf = extern_block;
  *len = len_res;
}

/* Functions for writing user-defined marshallers */

void serialize_int_1(int i)
{
  if (extern_ptr + 1 > extern_limit) resize_extern_block(1);
  extern_ptr[0] = i;
  extern_ptr += 1;
}

void serialize_int_2(int i)
{
  if (extern_ptr + 2 > extern_limit) resize_extern_block(2);
  extern_ptr[0] = i >> 8;
  extern_ptr[1] = i;
  extern_ptr += 2;
}

void serialize_int_4(int32 i)
{
  if (extern_ptr + 4 > extern_limit) resize_extern_block(4);
  extern_ptr[0] = i >> 24;
  extern_ptr[1] = i >> 16;
  extern_ptr[2] = i >> 8;
  extern_ptr[3] = i;
  extern_ptr += 4;
}

void serialize_int_8(int64 i)
{
  serialize_block_8(&i, 1);
}

void serialize_float_4(float f)
{
  serialize_block_4(&f, 1);
}

void serialize_float_8(double f)
{
  serialize_block_8(&f, 1);
}

void serialize_block_1(void * data, long len)
{
  if (extern_ptr + len > extern_limit) resize_extern_block(len);
  memmove(extern_ptr, data, len);
  extern_ptr += len;
}

void serialize_block_2(void * data, long len)
{
  unsigned char * p;
  char * q;
  if (extern_ptr + 2 * len > extern_limit) resize_extern_block(2 * len);
#ifndef ARCH_BIG_ENDIAN
  for (p = data, q = extern_ptr; len > 0; len--, p += 2, q += 2)
    Reverse_16(q, p);
  extern_ptr = q;
#else
  memmove(extern_ptr, data, len * 2);
  extern_ptr += len * 2;
#endif
}

void serialize_block_4(void * data, long len)
{
  unsigned char * p;
  char * q;
  if (extern_ptr + 4 * len > extern_limit) resize_extern_block(4 * len);
#ifndef ARCH_BIG_ENDIAN
  for (p = data, q = extern_ptr; len > 0; len--, p += 4, q += 4)
    Reverse_32(q, p);
  extern_ptr = q;
#else
  memmove(extern_ptr, data, len * 4);
  extern_ptr += len * 4;
#endif
}

void serialize_block_8(void * data, long len)
{
  unsigned char * p;
  char * q;
  if (extern_ptr + 8 * len > extern_limit) resize_extern_block(8 * len);
#ifndef ARCH_BIG_ENDIAN
  for (p = data, q = extern_ptr; len > 0; len--, p += 8, q += 8)
    Reverse_64(q, p);
  extern_ptr = q;
#else
  memmove(extern_ptr, data, len * 8);
  extern_ptr += len * 8;
#endif
}