File: context.c

package info (click to toggle)
libi8x 0.0.5-1
  • links: PTS
  • area: main
  • in suites: sid
  • size: 7,192 kB
  • ctags: 1,365
  • sloc: ansic: 6,874; python: 1,339; makefile: 146; sh: 102
file content (910 lines) | stat: -rw-r--r-- 20,987 bytes parent folder | download
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
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
/* Copyright (C) 2016-17 Red Hat, Inc.
   This file is part of the Infinity Note Execution Library.

   The Infinity Note Execution Library is free software; you can
   redistribute it and/or modify it under the terms of the GNU Lesser
   General Public License as published by the Free Software
   Foundation; either version 2.1 of the License, or (at your option)
   any later version.

   The Infinity Note Execution Library is distributed in the hope that
   it will be useful, but WITHOUT ANY WARRANTY; without even the
   implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
   PURPOSE.  See the GNU Lesser General Public License for more
   details.

   You should have received a copy of the GNU Lesser General Public
   License along with the Infinity Note Execution Library; if not, see
   <http://www.gnu.org/licenses/>.  */

#include <ctype.h>
#include <stdio.h>
#include <string.h>
#include "libi8x-private.h"

/**
 * SECTION:libi8x
 * @short_description: libi8x context
 *
 * The context contains the default values for the library user,
 * and is passed to all library operations.
 */

/**
 * i8x_ctx:
 *
 * Opaque object representing the library context.
 */
struct i8x_ctx
{
  I8X_OBJECT_FIELDS;

  i8x_log_fn_t *log_fn;
  int log_priority;

  bool use_debug_interpreter_default;

  struct i8x_note *error_note;	/* Note that caused the last error.  */
  const char *error_ptr;	/* Pointer into error_note.  */

  struct i8x_list *funcrefs;	/* List of interned function references.  */
  struct i8x_list *functypes;	/* List of interned function types.  */

  struct i8x_list *functions;	/* List of registered functions.  */

  /* User-supplied function called when a function becomes available.  */
  i8x_notify_fn_t *func_avail_observer_fn;

  /* User-supplied function called when a function is about to become
     unavailable.  */
  i8x_notify_fn_t *func_unavail_observer_fn;

  /* The three core types.  */
  struct i8x_type *integer_type;
  struct i8x_type *pointer_type;
  struct i8x_type *opaque_type;

  /* Special type internal to the validator.  */
  struct i8x_type *int_or_ptr_type;

  /* The interpreters' dispatch tables.  */
  void **dispatch_std;
  void **dispatch_dbg;
};

void
i8x_ctx_log (struct i8x_ctx *ctx,
	     int priority, const char *file, int line, const char *fn,
	     const char *format, ...)
{
  va_list args;

  /* We have a super-low internal priority, LOG_TRACE, but
     user-supplied logging functions are likely to expect
     the RFC 5424 value 0..7, so we cap what we supply.  */
  if (priority > LOG_DEBUG)
    priority = LOG_DEBUG;

  va_start (args, format);
  ctx->log_fn (ctx, priority, file, line, fn, format, args);
  va_end (args);
}

static void
log_stderr (struct i8x_ctx *ctx,
	    int priority, const char *file, int line, const char *fn,
	    const char *format, va_list args)
{
  fprintf (stderr, "libi8x: %s: ", fn);
  vfprintf (stderr, format, args);
}

struct i8x_logprio
{
  const char *name;
  int priority;
};

/* Lifted from syslog.h.  */
struct i8x_logprio prioritynames[] =
{
  { "alert", LOG_ALERT },
  { "crit", LOG_CRIT },
  { "debug", LOG_DEBUG },
  { "emerg", LOG_EMERG },
  { "err", LOG_ERR },
  { "info", LOG_INFO },
  { "notice", LOG_NOTICE },
  { "panic", LOG_EMERG },
  { "trace", LOG_TRACE },
  { "warn", LOG_WARNING },
  { NULL, -1 }
};

static int
strtoprio (const char *str)
{
  struct i8x_logprio *pn;
  char *endptr;
  int numeric;

  numeric = strtol (str, &endptr, 10);
  if (endptr[0] == '\0' || isspace (endptr[0]))
    return numeric;

  for (pn = prioritynames; pn->name != NULL; pn++)
    {
      if (strncasecmp (str, pn->name, strlen (pn->name)) == 0)
	return pn->priority;
    }

  return 0;
}

static bool
strtobool (const char *str)
{
  char *endptr;
  int numeric;

  numeric = strtol (str, &endptr, 10);
  if (endptr[0] == '\0' || isspace (endptr[0]))
    return numeric != 0;

  if (strncasecmp (str, "yes", 3) == 0)
    return true;
  if (strncasecmp (str, "true", 4) == 0)
    return true;

  return false;
}

static i8x_err_e
i8x_ctx_make_dispatch_table (struct i8x_ctx *ctx, bool is_debug,
			     void ***tablep)
{
  size_t table_size = i8x_ctx_get_dispatch_table_size (ctx);
  void **table;
  i8x_err_e err;

  table = calloc (table_size, sizeof (void *));
  if (table == NULL)
    return i8x_out_of_memory (ctx);

  err = i8x_ctx_init_dispatch_table (ctx, table, table_size, is_debug);
  if (err != I8X_OK)
    return err;

  *tablep = table;

  return I8X_OK;
}

static i8x_err_e
i8x_ctx_init (struct i8x_ctx *ctx)
{
  i8x_err_e err;

  err = i8x_list_new (ctx, true, &ctx->functions);
  if (err != I8X_OK)
    return err;

  err = i8x_list_new (ctx, false, &ctx->funcrefs);
  if (err != I8X_OK)
    return err;

  err = i8x_list_new (ctx, false, &ctx->functypes);
  if (err != I8X_OK)
    return err;

  err = i8x_type_new_coretype (ctx, I8_TYPE_INTEGER, &ctx->integer_type);
  if (err != I8X_OK)
    return err;

  err = i8x_type_new_coretype (ctx, I8_TYPE_POINTER, &ctx->pointer_type);
  if (err != I8X_OK)
    return err;

  err = i8x_type_new_coretype (ctx, I8_TYPE_OPAQUE, &ctx->opaque_type);
  if (err != I8X_OK)
    return err;

  err = i8x_type_new_coretype (ctx, I8X_TYPE_INTPTR, &ctx->int_or_ptr_type);
  if (err != I8X_OK)
    return err;

  err = i8x_ctx_make_dispatch_table (ctx, false, &ctx->dispatch_std);
  if (err != I8X_OK)
    return err;

  err = i8x_ctx_make_dispatch_table (ctx, true, &ctx->dispatch_dbg);
  if (err != I8X_OK)
    return err;

  return err;
}

static void
i8x_ctx_unlink (struct i8x_object *ob)
{
  struct i8x_ctx *ctx = (struct i8x_ctx *) ob;

  ctx->error_note = i8x_note_unref (ctx->error_note);

  ctx->functions = i8x_list_unref (ctx->functions);

  ctx->funcrefs = i8x_list_unref (ctx->funcrefs);
  ctx->functypes = i8x_list_unref (ctx->functypes);

  ctx->integer_type = i8x_type_unref (ctx->integer_type);
  ctx->pointer_type = i8x_type_unref (ctx->pointer_type);
  ctx->opaque_type = i8x_type_unref (ctx->opaque_type);

  ctx->int_or_ptr_type = i8x_type_unref (ctx->int_or_ptr_type);
}

static void
i8x_ctx_free (struct i8x_object *ob)
{
  struct i8x_ctx *ctx = (struct i8x_ctx *) ob;

  if (ctx->dispatch_std != NULL)
    free (ctx->dispatch_std);

  if (ctx->dispatch_dbg != NULL)
    free (ctx->dispatch_dbg);
}

const struct i8x_object_ops i8x_ctx_ops =
  {
    "ctx",			/* Object name.  */
    sizeof (struct i8x_ctx),	/* Object size.  */
    i8x_ctx_unlink,		/* Unlink function.  */
    i8x_ctx_free,		/* Free function.  */
  };

/**
 * i8x_ctx_new:
 *
 * Create i8x library context. This reads the i8x configuration
 * and fills in the default values.
 *
 * The initial refcount is 1, and needs to be decremented to
 * release the resources of the i8x library context.
 *
 * Returns: a new i8x library context
 **/
I8X_EXPORT i8x_err_e
i8x_ctx_new (int flags, i8x_log_fn_t *log_fn, struct i8x_ctx **ctx)
{
  const char *env;
  struct i8x_ctx *c;
  i8x_err_e err;

  err = i8x_ob_new (NULL, &i8x_ctx_ops, &c);
  if (err != I8X_OK)
    return err;

  /* Set up logging at the earliest opportunity.  */
  if (log_fn != NULL)
    c->log_fn = log_fn;
  else
    c->log_fn = log_stderr;

  if (flags & I8X_LOG_TRACE)
    c->log_priority = LOG_TRACE;
  else
    c->log_priority = LOG_PRI (flags);

  env = secure_getenv ("I8X_LOG");
  if (env != NULL)
    i8x_ctx_set_log_priority (c, strtoprio (env));

  /* Now log the message i8x_ob_new deferred to us.  */
  dbg (c, "ctx %p created\n", c);

  if (flags & I8X_DBG_MEM)
    c->_ob.use_debug_allocator = true;

  env = secure_getenv ("I8X_DEBUG");
  if (env != NULL && strtobool (env))
    {
      c->_ob.use_debug_allocator = true;
      c->use_debug_interpreter_default = true;
    }

  dbg (c, "log_priority=%d\n", c->log_priority);
  dbg (c, "use_debug_allocator=%d\n", c->_ob.use_debug_allocator);

  err = i8x_ctx_init (c);
  if (err != I8X_OK)
    {
      c = i8x_ctx_unref (c);

      return err;
    }

  *ctx = c;

  return I8X_OK;
}

/**
 * i8x_ctx_set_log_fn:
 * @ctx: i8x library context
 * @log_fn: function to be called for logging messages
 *
 * The built-in logging writes to stderr. It can be
 * overridden by a custom function, to plug log messages
 * into the user's logging functionality.
 *
 **/
I8X_EXPORT void
i8x_ctx_set_log_fn (struct i8x_ctx *ctx, i8x_log_fn_t *log_fn)
{
  ctx->log_fn = log_fn;
}

/**
 * i8x_ctx_get_log_priority:
 * @ctx: i8x library context
 *
 * Returns: the current logging priority
 **/
I8X_EXPORT int
i8x_ctx_get_log_priority (struct i8x_ctx *ctx)
{
  return ctx->log_priority;
}

/**
 * i8x_ctx_set_log_priority:
 * @ctx: i8x library context
 * @priority: the new logging priority
 *
 * Set the current logging priority. The value controls which messages
 * are logged.
 **/
I8X_EXPORT void
i8x_ctx_set_log_priority (struct i8x_ctx *ctx, int priority)
{
  ctx->log_priority = priority;
}

bool
i8x_ctx_get_use_debug_interpreter_default (struct i8x_ctx *ctx)
{
  return ctx->use_debug_interpreter_default;
}


I8X_EXPORT void
i8x_ctx_set_func_available_cb (struct i8x_ctx *ctx,
			       i8x_notify_fn_t *func_avail_cb_fn)
{
  ctx->func_avail_observer_fn = func_avail_cb_fn;
}

I8X_EXPORT void
i8x_ctx_set_func_unavailable_cb (struct i8x_ctx *ctx,
				 i8x_notify_fn_t *func_unavail_cb_fn)
{
  ctx->func_unavail_observer_fn = func_unavail_cb_fn;
}

void
i8x_ctx_fire_availability_observer (struct i8x_func *func,
				    bool is_available)
{
  struct i8x_ctx *ctx = i8x_func_get_ctx (func);

  info (ctx, "%s became %s\n", i8x_func_get_fullname (func),
	is_available ? "available" : "unavailable");

  i8x_notify_fn_t *callback = is_available
    ? ctx->func_avail_observer_fn
    : ctx->func_unavail_observer_fn;

  if (callback != NULL)
    callback (func);
}

i8x_err_e
i8x_ctx_set_error (struct i8x_ctx *ctx, i8x_err_e code,
		   struct i8x_note *cause_note, const char *cause_ptr)
{
  i8x_assert (code != I8X_OK);

  if (ctx != NULL)
    {
      ctx->error_note = i8x_note_unref (ctx->error_note);
      ctx->error_note = i8x_note_ref (cause_note);

      ctx->error_ptr = cause_ptr;
    }

  return code;
}

static const char *
error_message_for (i8x_err_e code)
{
  switch (code)
    {
    case I8X_OK:
      return _("No error");

    case I8X_ENOMEM:
      return _("Out of memory");

    case I8X_EINVAL:
      return _("Invalid argument");

    case I8X_NOTE_CORRUPT:
      return _("Corrupt note");

    case I8X_NOTE_UNHANDLED:
      return _("Unhandled note");

    case I8X_NOTE_INVALID:
      return _("Invalid note");

    case I8X_UNRESOLVED_FUNC:
      return _("Unresolved function");

    case I8X_STACK_OVERFLOW:
      return _("Stack overflow");

    case I8X_RELOC_FAILED:
      return _("Relocation failed");

    case I8X_READ_MEM_FAILED:
      return _("Read memory failed");

    case I8X_DIVIDE_BY_ZERO:
      return _("Division by zero");

    case I8X_NATCALL_FAILED:
      return _("Native call failed");

    default:
      return NULL;
    }
}

static void __attribute__ ((format (printf, 3, 4)))
xsnprintf (char **bufp, char *limit, const char *format, ...)
{
  char *buf = *bufp;
  size_t bufsiz = limit - buf;
  va_list args;

  va_start (args, format);
  vsnprintf (buf, bufsiz, format, args);
  va_end (args);

  buf[bufsiz - 1] = '\0';
  *bufp = buf + strlen (buf);
}

I8X_EXPORT const char *
i8x_ctx_strerror_r (struct i8x_ctx *ctx, i8x_err_e code,
		    char *buf, size_t bufsiz)
{
  char *ptr = buf;
  char *limit = ptr + bufsiz;
  const char *prefix = NULL;
  ssize_t offset = -1;
  const char *msg = error_message_for (code);

  if (ctx != NULL && ctx->error_note != NULL)
    {
      prefix = i8x_note_get_src_name (ctx->error_note);
      offset = i8x_note_get_src_offset (ctx->error_note);

      if (offset >= 0 && ctx->error_ptr != NULL)
	offset += ctx->error_ptr
	          - i8x_note_get_encoded (ctx->error_note);
    }

  if (prefix == NULL)
    prefix = PACKAGE;

  xsnprintf (&ptr, limit, "%s", prefix);

  if (offset >= 0)
    xsnprintf (&ptr, limit, "[" LHEX "]", offset);

  xsnprintf (&ptr, limit, ": ");

  if (msg == NULL)
    xsnprintf (&ptr, limit, _("unhandled error %d"), code);
  else
    xsnprintf (&ptr, limit, "%s", msg);

  return buf;
}

struct i8x_type *
i8x_ctx_get_integer_type (struct i8x_ctx *ctx)
{
  return ctx->integer_type;
}

struct i8x_type *
i8x_ctx_get_pointer_type (struct i8x_ctx *ctx)
{
  return ctx->pointer_type;
}

struct i8x_type *
i8x_ctx_get_opaque_type (struct i8x_ctx *ctx)
{
  return ctx->opaque_type;
}

struct i8x_type *
i8x_ctx_get_int_or_ptr_type (struct i8x_ctx *ctx)
{
  return ctx->int_or_ptr_type;
}

void
i8x_ctx_get_dispatch_tables (struct i8x_ctx *ctx,
			     void ***dispatch_std,
			     void ***dispatch_dbg)
{
  *dispatch_std = ctx->dispatch_std;
  *dispatch_dbg = ctx->dispatch_dbg;
}

/* Internal version of i8x_ctx_get_funcref with an extra source note
   argument for error-reporting.  If the source note is not NULL then
   rtypes and ptypes MUST be pointers into the note's buffer or any
   resulting error messages will contain nonsense offsets.  */

i8x_err_e
i8x_ctx_get_funcref_with_note (struct i8x_ctx *ctx,
			       const char *provider, const char *name,
			       const char *ptypes, const char *rtypes,
			       struct i8x_note *src_note,
			       struct i8x_funcref **refp)
{
  struct i8x_listitem *li;
  struct i8x_funcref *ref;
  struct i8x_type *functype;
  size_t fullname_size;
  char *fullname;
  i8x_err_e err = I8X_OK;

  /* Build the full name.  */
  fullname_size = (strlen (provider)
		   + 2   /* "::"  */
		   + strlen (name)
		   + 1   /* '('  */
		   + strlen (ptypes)
		   + 1   /* ')'  */
		   + strlen (rtypes)
		   + 1); /* '\0'  */
  fullname = malloc (fullname_size);
  if (fullname == NULL)
    return i8x_out_of_memory (ctx);

  snprintf (fullname, fullname_size,
	    "%s::%s(%s)%s", provider, name, ptypes, rtypes);

  /* If we have this reference already then return it.  */
  i8x_list_foreach (ctx->funcrefs, li)
    {
      ref = i8x_listitem_get_funcref (li);

      if (strcmp (i8x_funcref_get_fullname (ref), fullname) == 0)
	{
	  *refp = i8x_funcref_ref (ref);

	  goto cleanup;
	}
    }

  /* It's a new reference that needs creating.  */
  err = i8x_ctx_get_functype (ctx,
			      ptypes, ptypes + strlen (ptypes),
			      rtypes, rtypes + strlen (rtypes),
			      src_note, &functype);
  if (err != I8X_OK)
    goto cleanup;

  err = i8x_funcref_new (ctx, fullname, functype, &ref);
  i8x_type_unref (functype);
  if (err != I8X_OK)
    goto cleanup;

  err = i8x_list_append_funcref (ctx->funcrefs, ref);
  if (err != I8X_OK)
    {
      ref = i8x_funcref_unref (ref);

      goto cleanup;
    }

  *refp = ref;

 cleanup:
  free (fullname);

  return err;
}

I8X_EXPORT i8x_err_e
i8x_ctx_get_funcref (struct i8x_ctx *ctx, const char *provider,
		     const char *name, const char *ptypes,
		     const char *rtypes, struct i8x_funcref **refp)
{
  return i8x_ctx_get_funcref_with_note (ctx, provider, name,
					ptypes, rtypes, NULL, refp);
}

void
i8x_ctx_forget_funcref (struct i8x_funcref *ref)
{
  struct i8x_ctx *ctx = i8x_funcref_get_ctx (ref);

  i8x_list_remove_funcref (ctx->funcrefs, ref);
}

i8x_err_e
i8x_ctx_get_functype (struct i8x_ctx *ctx,
		      const char *ptypes_start,
		      const char *ptypes_limit,
		      const char *rtypes_start,
		      const char *rtypes_limit,
		      struct i8x_note *src_note,
		      struct i8x_type **typep)
{
  struct i8x_listitem *li;
  struct i8x_type *type;
  size_t ptypes_size = ptypes_limit - ptypes_start;
  size_t rtypes_size = rtypes_limit - rtypes_start;
  size_t encoded_size;
  char *encoded, *ptr;
  i8x_err_e err = I8X_OK;

  /* Build the encoded form.  */
  encoded_size = (1	/* I8_TYPE_FUNCTION  */
		  + rtypes_size
		  + 1   /* '('  */
		  + ptypes_size
		  + 1   /* ')'  */
		  + 1); /* '\0'  */
  ptr = encoded = malloc (encoded_size);
  if (encoded == NULL)
    return i8x_out_of_memory (ctx);

  *(ptr++) = I8_TYPE_FUNCTION;
  memcpy (ptr, rtypes_start, rtypes_size);
  ptr += rtypes_size;
  *(ptr++) = '(';
  memcpy (ptr, ptypes_start, ptypes_size);
  ptr += ptypes_size;
  *(ptr++) = ')';
  *(ptr++) = '\0';

  /* If we have this type already then return it.  */
  i8x_list_foreach (ctx->functypes, li)
    {
      type = i8x_listitem_get_type (li);

      if (strcmp (i8x_type_get_encoded (type), encoded) == 0)
	{
	  *typep = i8x_type_ref (type);

	  goto cleanup;
	}
    }

  /* It's a new type that needs creating.  */
  err = i8x_type_new_functype (ctx, encoded,
			       ptypes_start, ptypes_limit,
			       rtypes_start, rtypes_limit,
			       src_note, &type);
  if (err != I8X_OK)
    goto cleanup;

  err = i8x_list_append_type (ctx->functypes, type);
  if (err != I8X_OK)
    {
      type = i8x_type_unref (type);

      goto cleanup;
    }

  *typep = type;

 cleanup:
  free (encoded);

  return err;
}

void
i8x_ctx_forget_functype (struct i8x_type *type)
{
  struct i8x_ctx *ctx = i8x_type_get_ctx (type);

  i8x_list_remove_type (ctx->functypes, type);
}

static void
i8x_ctx_resolve_funcrefs (struct i8x_ctx *ctx)
{
  struct i8x_listitem *li;
  bool finished = false;

  /* Mark all function references as resolved or not based
     on whether they resolve to a unique registered function.
     Dependencies are ignored at this stage.  */
  i8x_list_foreach (ctx->funcrefs, li)
    {
      struct i8x_funcref *ref = i8x_listitem_get_funcref (li);

      i8x_funcref_reset_is_resolved (ref);
    }

  /* Mark functions unresolved if any of their dependencies
     are unresolved.  Repeat until nothing changes.  */
  while (!finished)
    {
      finished = true;

      i8x_list_foreach (ctx->functions, li)
	{
	  struct i8x_func *func = i8x_listitem_get_func (li);
	  struct i8x_funcref *ref = i8x_func_get_funcref (func);

	  if (!i8x_funcref_is_resolved (ref))
	    continue;

	  if (i8x_func_all_deps_resolved (func))
	    continue;

	  i8x_funcref_mark_unresolved (ref);

	  finished = false;
	}
    }

  /* Notify the user of any function availability changes.  */
  i8x_list_foreach (ctx->functions, li)
    {
      struct i8x_func *func = i8x_listitem_get_func (li);

      i8x_func_fire_availability_observers (func);
    }
}

I8X_EXPORT i8x_err_e
i8x_ctx_register_func (struct i8x_ctx *ctx, struct i8x_func *func)
{
  i8x_err_e err;

  dbg (ctx, "registering func %p\n", func);
  i8x_assert (i8x_func_get_ctx (func) == ctx);

  err = i8x_list_append_func (ctx->functions, func);
  if (err != I8X_OK)
    return err;

  i8x_func_register (func);
  i8x_ctx_resolve_funcrefs (ctx);

  return I8X_OK;
}

I8X_EXPORT i8x_err_e
i8x_ctx_unregister_func (struct i8x_ctx *ctx, struct i8x_func *func)
{
  dbg (ctx, "unregistering func %p\n", func);
  i8x_assert (i8x_func_get_ctx (func) == ctx);

  struct i8x_listitem *li
    = i8x_list_get_item (ctx->functions, (struct i8x_object *) func);
  if (li == NULL)
    return i8x_invalid_argument (ctx);

  func = i8x_func_ref (func);
  i8x_listitem_remove (li);

  i8x_func_unregister (func);
  i8x_ctx_resolve_funcrefs (ctx);

  func = i8x_func_unref (func);

  return I8X_OK;
}

/* convenience */

I8X_EXPORT i8x_err_e
i8x_ctx_import_bytecode (struct i8x_ctx *ctx,
			 const char *buf, size_t bufsiz,
			 const char *srcname, ssize_t srcoffset,
			 struct i8x_func **func)
{
  struct i8x_note *note;
  struct i8x_func *f;
  i8x_err_e err;

  err = i8x_note_new (ctx, buf, bufsiz, srcname, srcoffset, &note);
  if (err != I8X_OK)
    return err;

  err = i8x_func_new_bytecode (note, &f);
  note = i8x_note_unref (note);
  if (err != I8X_OK)
    return err;

  err = i8x_ctx_register_func (ctx, f);
  if (err == I8X_OK && func != NULL)
    *func = f;
  else
    f = i8x_func_unref (f);

  return err;
}

/* convenience */

I8X_EXPORT i8x_err_e
i8x_ctx_import_native (struct i8x_ctx *ctx, const char *provider,
		       const char *name, const char *ptypes,
		       const char *rtypes, i8x_nat_fn_t *impl_fn,
		       struct i8x_func **func)
{
  struct i8x_funcref *sig;
  struct i8x_func *f;
  i8x_err_e err;

  err = i8x_ctx_get_funcref (ctx, provider, name, ptypes, rtypes, &sig);
  if (err != I8X_OK)
    return err;

  err = i8x_func_new_native (ctx, sig, impl_fn, &f);
  sig = i8x_funcref_unref (sig);
  if (err != I8X_OK)
    return err;

  err = i8x_ctx_register_func (ctx, f);
  if (err == I8X_OK && func != NULL)
    *func = f;
  else
    f = i8x_func_unref (f);

  return err;
}

I8X_EXPORT void
i8x_inf_invalidate_relocs (struct i8x_inf *inf)
{
  struct i8x_ctx *ctx = i8x_inf_get_ctx (inf);
  struct i8x_listitem *li;

  i8x_list_foreach (ctx->functions, li)
    {
      struct i8x_func *func = i8x_listitem_get_func (li);
      struct i8x_list *relocs = i8x_func_get_relocs (func);
      struct i8x_listitem *lj;

      i8x_list_foreach (relocs, lj)
	{
	  struct i8x_reloc *reloc = i8x_listitem_get_reloc (lj);

	  i8x_reloc_invalidate_for_inferior (reloc, inf);
	}
    }
}

I8X_EXPORT struct i8x_list *
i8x_ctx_get_functions (struct i8x_ctx *ctx)
{
  return ctx->functions;
}