File: libi8x.c.in

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 (1184 lines) | stat: -rw-r--r-- 29,050 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
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
/* Copyright (C) 2017 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 <py3c.h>
#include <libi8x.h>

#define PY8X_MAX(a, b) ((a) > (b) ? (a) : (b))

#define PY8X_STRINGIZE(x) PY8X_STRINGIZE_1(x)
#define PY8X_STRINGIZE_1(x) #x

#define py8x_not_implemented()						\
  do {									\
    PyErr_SetString (PyExc_NotImplementedError,				\
		     __FILE__ ":" PY8X_STRINGIZE (__LINE__));		\
    return NULL;							\
  } while (0)

/* Exceptions.  */

static PyObject *py8x_I8XError;

#define PY8X_RAISE(msg)							\
  do {									\
    PyErr_SetString (py8x_I8XError, msg);				\
    return NULL;							\
  } while (0)

#define PY8X_CHECK_CALL(ctx, err)					\
  do {									\
    if (err == I8X_ENOMEM)						\
      return PyErr_NoMemory ();						\
    else if ((err == I8X_NATCALL_FAILED					\
	      || err == I8X_READ_MEM_FAILED				\
	      || err == I8X_RELOC_FAILED)				\
	     && PyErr_Occurred () != NULL)				\
      return NULL; /* User code raised an exception.  */		\
    else if (err != I8X_OK)						\
      {									\
        char buf[1024];							\
	PY8X_RAISE (i8x_ctx_strerror_r (ctx, err, buf,  sizeof (buf)));	\
      }									\
  } while (0)

/* Attribute name under which py8x_encapsulate* stores libi8x
   object PyCapsules in the Python wrapper objects it creates.  */

#define PY8X_CNAME_ATTR "__i8x_object"

/* Helpers for each libi8x object.  */

#define PY8X_OBJECT_FUNCTIONS(TYPE, PREFIX)				\
  static inline struct i8x_ ## TYPE * __attribute__ ((always_inline))	\
  py8x_ ## PREFIX ## _from_capsule (PyObject *wrapped)			\
  {									\
    PyObject *c = PyObject_GetAttrString (wrapped, PY8X_CNAME_ATTR);	\
    if (c == NULL)							\
      return NULL;							\
    void *result = PyCapsule_GetPointer (c, NULL);			\
    Py_DECREF (c);							\
    return (struct i8x_ ## TYPE *) result;				\
  }
#pragma libi8x_api_object_functions

#define PY8X_FROM_CAPSULE_2(TYPE, NAME)					\
  py8x_ ## TYPE ## _from_capsule (NAME ## c);				\
  if (NAME == NULL)							\
    return NULL

#define PY8X_FROM_CAPSULE(TYPENAME)					\
  PY8X_FROM_CAPSULE_2 (TYPENAME, TYPENAME)

/* Userdata for all libi8x objects we create.  May be extended.
   Every libi8x object we pass into Python-space has one of these.
   It can be supplied to py8x_encapsulate* by the object's creator
   (if the object requires extended userdata).  If not supplied a
   generic userdata will be created.  It has two functions:

    1) It contains a regular reference to the parent object's
       Python wrapper.  This ensures parent objects remain live
       while live Python references to their children exist.
       (Python-side references are all child-parent).

    2) It contains a weak reference to this object's Python
       wrapper.  This interning means that Python objects can
       be compared using "is".  */

struct py8x_userdata;

struct py8x_userdata_ops
{
  const char *name;
  size_t size;
  void (*cleanup) (struct py8x_userdata *ud);
};

struct py8x_userdata
{
  const struct py8x_userdata_ops *ops;

  /* PyCapsule of parent object (referenced by us).
     NULL for i8x_ctx objects.  */
  PyObject *parent;

  /* PyWeakref of our own wrapped PyCapsule.  */
  PyObject *selfwr;
};

#define PY8X_USERDATA_FIELDS struct py8x_userdata _oud

/* Generic userdata ops for nonspecialized objects.  */

static const struct py8x_userdata_ops py8x_ob_udops =
  {
    "i8x_object",
    sizeof (struct py8x_userdata),
  };

/* Allocate and initialize a new py8x_userdata.  */

static struct py8x_userdata *
py8x_userdata_new (const struct py8x_userdata_ops *ops)
{
  struct py8x_userdata *ud;

  ud = calloc (1, ops->size);
  if (ud != NULL)
    ud->ops = ops;

  return ud;
}

/* Userdata cleanup for all objects.  */

static void
py8x_userdata_free (void *ud_p)
{
  struct py8x_userdata *ud = (struct py8x_userdata *) ud_p;

  if (ud->ops->cleanup != NULL)
    ud->ops->cleanup (ud);

  Py_XDECREF (ud->parent);
  Py_XDECREF (ud->selfwr);

  free (ud);
}

/* Get an object's userdata.  */

#define py8x_get_userdata(o)						\
  ((struct py8x_userdata *)						\
     i8x_ob_get_userdata ((struct i8x_object *) (o)))

/* PyCapsule_Destructor suitable for all libi8x objects.  */

static void
py8x_ob_unref (PyObject *obc)
{
  struct i8x_object *ob = PyCapsule_GetPointer (obc, NULL);
  struct py8x_userdata *ud = py8x_get_userdata (ob);

  if (ud == NULL)
    abort ();

  /* Release the child before the parent.  */
  PyObject *parent = ud->parent;
  ud->parent = NULL;

  i8x_ob_unref (ob);
  Py_XDECREF (parent);
}

/* Encapsulate and return a libi8x object.  */

static PyObject *py8x_ob_get_wrap_fn (struct i8x_object *ob);

static PyObject *
py8x_encapsulate_2 (struct i8x_object *ob, struct py8x_userdata *new_ud)
{
  struct py8x_userdata *ud;
  PyObject *result = NULL;

  /* Encapsulate NULLs as Py_None.  */
  if (ob == NULL)
    {
      if (new_ud != NULL)
	{
	  /* The caller supplied userdata for a NULL object.  */
	  PyErr_SetString (PyExc_AssertionError,
			   "ob == NULL && new_ud != NULL");
	  return NULL;
	}

      Py_RETURN_NONE;
    }

  ud = py8x_get_userdata (ob);
  if (ud != NULL && new_ud != NULL)
    {
      /* The caller supplied userdata for an object that already has
	 userdata set.  This is a programmer error.  */
      PyErr_SetString (PyExc_AssertionError,
		       "ud != NULL && new_ud != NULL");
      return NULL;
    }

  if (ud == NULL)
    {
      /* The object has no userdata. Create if necessary.  */
      ud = new_ud;
      if (ud == NULL)
	ud = py8x_userdata_new (&py8x_ob_udops);
      if (ud == NULL)
	return PyErr_NoMemory ();

      /* Attach it to the object. */
      i8x_ob_set_userdata (ob, ud, py8x_userdata_free);
    }

  /* Reference the object's parent's wrapper.  */
  if (ud->parent == NULL)
    {
      struct i8x_object *parent = i8x_ob_get_parent (ob);

      if (parent != NULL)
	{
	  ud->parent = py8x_encapsulate_2 (parent, NULL);
	  if (ud->parent == NULL)
	    return NULL;
	}
    }

  /* Try and use a previously-created wrapped capsule.  */
  if (ud->selfwr != NULL)
    {
      result = PyWeakref_GetObject (ud->selfwr);
      if (result == NULL)
	return NULL;

      if (result == Py_None)
	{
	  result = NULL;

	  Py_DECREF (ud->selfwr);
	  ud->selfwr = NULL;
	}
      else
	Py_INCREF (result);
    }

  /* Create a new wrapped capsule if necessary.  */
  if (result == NULL)
    {
      PyObject *capsule;

      /* Create a capsule to hold the object.  */
      capsule = PyCapsule_New (i8x_ob_ref (ob), NULL, py8x_ob_unref);
      if (capsule == NULL)
	return NULL;

      /* Create a Python object to hold the capsule.  */
      result = PyObject_CallFunction (py8x_ob_get_wrap_fn (ob),
				      "s", i8x_ob_get_classname (ob));
      if (result == NULL)
	{
	  Py_DECREF (capsule);
	  return NULL;
	}

      /* Store the capsule in the wrapper object.  */
      int err = PyObject_SetAttrString (result, PY8X_CNAME_ATTR, capsule);
      Py_DECREF (capsule);
      if (err != 0)
	{
	  Py_DECREF (result);
	  return NULL;
	}

      /* Store a weak reference to our own wrapper object.  */
      ud->selfwr = PyWeakref_NewRef (result, NULL);
      if (ud->selfwr == NULL)
	{
	  Py_DECREF (result);
	  return NULL;
	}
    }

  return result;
}

static PyObject *
py8x_encapsulate_1 (struct i8x_object *ob, struct py8x_userdata *ud)
{
  PyObject *result = py8x_encapsulate_2 (ob, ud);

  i8x_ob_unref (ob);

  return result;
}

#define py8x_encapsulate(x)						\
  (py8x_encapsulate_1 ((struct i8x_object *) x, NULL))

/* Helpers for objects with extended userdata.  */

#define PY8X_USERDATA_FUNCTIONS(TYPE)					\
  static inline struct py8x_ ## TYPE ## _userdata *			\
    __attribute__ ((always_inline))					\
  py8x_ ## TYPE ## _userdata_new (void)					\
  {									\
    return (struct py8x_ ## TYPE ## _userdata *)			\
      py8x_userdata_new (&py8x_ ## TYPE ## _udops);			\
  }									\
									\
  static inline struct py8x_ ## TYPE ## _userdata *			\
    __attribute__ ((always_inline))					\
  py8x_ ## TYPE ## _get_userdata (struct i8x_ ## TYPE *x)		\
  {									\
    return (struct py8x_ ## TYPE ## _userdata *)			\
      i8x_ ## TYPE ## _get_userdata (x);				\
  }									\
									\
  static inline PyObject * __attribute__ ((always_inline))		\
  py8x_ ## TYPE ## _encapsulate (struct i8x_ ## TYPE *x,		\
				 struct py8x_ ## TYPE ## _userdata *ud) \
  {									\
    return py8x_encapsulate_1 ((struct i8x_object *) x,			\
			       (struct py8x_userdata *) ud);		\
  }

/* Context (i8x_ctx) userdata.  */

struct py8x_ctx_userdata
{
  PY8X_USERDATA_FIELDS;

  /* Object wrapping function.  */
  PyObject *wrap_fn;

  /* Logging function.  */
  PyObject *log_fn;
};

static void
py8x_ctx_userdata_cleanup (struct py8x_userdata *ud_p)
{
  struct py8x_ctx_userdata *ud = (struct py8x_ctx_userdata *) ud_p;

  Py_DECREF (ud->wrap_fn);
  Py_DECREF (ud->log_fn);
}

static const struct py8x_userdata_ops py8x_ctx_udops =
  {
    "i8x_ctx",
    sizeof (struct py8x_ctx_userdata),
    py8x_ctx_userdata_cleanup,
  };

PY8X_USERDATA_FUNCTIONS (ctx)

static PyObject *
py8x_ob_get_wrap_fn (struct i8x_object *ob)
{
  return py8x_ctx_get_userdata (i8x_ob_get_ctx (ob))->wrap_fn;
}

/* Userdata for the context currently being created by i8x_ctx_new.
   i8x_ctx_new can log before we have a chance to set the context's
   userdata; this static global exists so that py8x_log can access
   the Python log function it needs in this case.  */

static struct py8x_ctx_userdata *py8x_new_context_ud;

/* Logging function for all py8x-created contexts.  */

static void
py8x_log (struct i8x_ctx *ctx,
	  int pri, const char *file, int line, const char *fn,
	  const char *format, va_list args)
{
  struct py8x_ctx_userdata *ud = py8x_ctx_get_userdata (ctx);
  char *msg;
  int count;
  PyObject *result = NULL;

  /* No userdata means we're in i8x_ctx_new, before
     py8x_ctx_new has had chance to set it.  */
  if (ud == NULL)
    ud = py8x_new_context_ud;
  if (ud == NULL)
    abort ();

  count = vasprintf (&msg, format, args);
  if (count < 0)
    msg = "vasprintf failed";

  /* Call the user-defined logging function if there is one.  */
  if (ud->log_fn != Py_None)
    {
      result = PyObject_CallFunction (ud->log_fn, "isiss", pri,
				      file, line, fn, msg);

      /* Note that there's no way to signal an error to libi8x
	 in the event the logging function raises an exception,
	 so exceptions here may appear in place of others.  We
	 write what's happening to stderr to give some kind of
	 clue.  */

      if (result == NULL)
	{
	  PySys_WriteStderr ("py8x: user-defined logger failed with "
			     "the following exception:\n");
	  PyErr_PrintEx (0);
	  PySys_WriteStderr ("py8x: the message being logged was:\n");
	}
    }

  if (result == NULL)
    {
      /* PySys_WriteStderr wants 1000 bytes max.  */
      char buf[1000];

      snprintf (buf, sizeof (buf), "py8x: %s: %s", fn, msg);
      buf[sizeof (buf) - 1] = '\0';
      PySys_WriteStderr ("%s", buf);
    }

  Py_XDECREF (result);

  if (count >= 0)
    free (msg);
}

/* Python binding for i8x_ctx_new.  */

static PyObject *
py8x_ctx_new (PyObject *self, PyObject *args)
{
  PyObject *wrap_fn;
  int flags;
  PyObject *log_fn;
  struct py8x_ctx_userdata *ud;
  struct i8x_ctx *ctx = NULL;
  i8x_err_e err;

  if (!PyArg_ParseTuple (args, "OiO", &wrap_fn, &flags, &log_fn))
    return NULL;

  ud = py8x_ctx_userdata_new ();
  if (ud == NULL)
    return NULL;

  Py_INCREF (wrap_fn);
  ud->wrap_fn = wrap_fn;

  Py_INCREF (log_fn);
  ud->log_fn = log_fn;

  py8x_new_context_ud = ud;
  err = i8x_ctx_new (flags, py8x_log, &ctx);
  py8x_new_context_ud = NULL;

  if (err != I8X_OK)
    py8x_userdata_free (ud);

  PY8X_CHECK_CALL (NULL, err);

  return py8x_ctx_encapsulate (ctx, ud);
}

/* Python binding for i8x_ctx_set_log_fn.  */

static PyObject *
py8x_ctx_set_log_fn (PyObject *self, PyObject *args)
{
  PyObject *ctxc, *log_fn;

  if (!PyArg_ParseTuple (args, "OO", &ctxc, &log_fn))
    return NULL;

  struct i8x_ctx *ctx = PY8X_FROM_CAPSULE (ctx);
  struct py8x_ctx_userdata *ud = py8x_ctx_get_userdata (ctx);

  Py_DECREF (ud->log_fn);
  Py_INCREF (log_fn);
  ud->log_fn = log_fn;

  Py_RETURN_NONE;
}

/* Function (i8x_func) userdata.  */

struct py8x_func_userdata
{
  PY8X_USERDATA_FIELDS;

  /* Implementation (native only).  */
  PyObject *impl;
};

static void
py8x_func_userdata_cleanup (struct py8x_userdata *ud_p)
{
  struct py8x_func_userdata *ud = (struct py8x_func_userdata *) ud_p;

  Py_XDECREF (ud->impl);
}

static const struct py8x_userdata_ops py8x_func_udops =
  {
    "i8x_func",
    sizeof (struct py8x_func_userdata),
    py8x_func_userdata_cleanup,
  };

PY8X_USERDATA_FUNCTIONS (func)

/* Actions for py8x_unpack_tuple.  */

typedef enum
{
  PY8X_ARGS,
  PY8X_RETS
}
py8x_argsrets_e;

/* Helper for py8x_{pack,unpack}_tuple.  */

#define py8x_pack_unpack_types(ref, what)				\
  (what == PY8X_ARGS							\
   ? i8x_funcref_get_ptypes (ref)					\
   : i8x_funcref_get_rtypes (ref))

/* Pack a Python tuple from an array of i8x_values.  */

static PyObject *
py8x_pack_tuple (union i8x_value *src, struct i8x_funcref *ref,
		 py8x_argsrets_e what)
{
  struct i8x_list *types =  py8x_pack_unpack_types (ref, what);
  size_t length = i8x_list_size (types);
  size_t offset = what == PY8X_ARGS ? 3 : 0;
  struct i8x_listitem *li;
  size_t i;

  PyObject *result = PyTuple_New (length + offset);
  if (result == NULL)
    return NULL;

  i8x_list_foreach_indexed (types, li, i)
    {
      struct i8x_type *type = i8x_listitem_get_type (li);
      int index = what == PY8X_ARGS ? i + offset : length - i - 1;
      PyObject *item;

      if (i8x_type_is_functype (type))
	item = py8x_encapsulate (i8x_funcref_ref (src[i].f));
      else
	item = PyLong_FromUnsignedLong (src[i].u);

      if (item == NULL || PyTuple_SetItem (result, index, item) != 0)
	{
	  Py_DECREF (result);
	  return NULL;
	}
    }

  return result;
}

/* Unpack a Python tuple into an array of i8x_values.  */

static bool
py8x_unpack_tuple (union i8x_value *dst, PyObject *src,
		   struct i8x_funcref *ref, py8x_argsrets_e what)
{
  struct i8x_list *types =  py8x_pack_unpack_types (ref, what);
  size_t length = i8x_list_size (types);
  struct i8x_listitem *li;
  size_t i;

  if (PySequence_Length (src) != length)
    {
      PyErr_SetString (py8x_I8XError,
		       what == PY8X_ARGS
		       ? "wrong number of arguments"
		       : "wrong number of returns");
      return false;
    }

  i8x_list_foreach_indexed (types, li, i)
    {
      struct i8x_type *type = i8x_listitem_get_type (li);
      int index = what == PY8X_ARGS ? i : length - i - 1;
      PyObject *item = PySequence_GetItem (src, index);

      if (item == NULL)
	return false;

      if (i8x_type_is_functype (type))
	{
	  struct i8x_funcref *value = py8x_funcref_from_capsule (item);

	  Py_DECREF (item);
	  if (value == NULL)
	    return false;

	  dst[i].f = value;
	}
      else
	{
	  long value = PyLong_AsLong (item);

	  Py_DECREF (item);
	  if (value == -1 && PyErr_Occurred () != NULL)
	    return false;

	  dst[i].i = value;
	}
    }

  return true;
}

#define py8x_pack_args(src, ref) 					\
  py8x_pack_tuple (src, ref, PY8X_ARGS)

#define py8x_pack_rets(src, ref) 					\
  py8x_pack_tuple (src, ref, PY8X_RETS)

#define py8x_unpack_args(dst, src, ref) 				\
  py8x_unpack_tuple (dst, src, ref, PY8X_ARGS)

#define py8x_unpack_rets(dst, src, ref) 				\
  py8x_unpack_tuple (dst, src, ref, PY8X_RETS)

/* Helper for py8x_natfunc_impl.  */

#define PY8X_NFI_SETARG(i, v)						\
  do {									\
    PyObject *arg = v;							\
									\
    if (arg == NULL || PyTuple_SetItem (args, (i), arg) != 0)		\
      {									\
	Py_DECREF (args);						\
	return I8X_NATCALL_FAILED;					\
      }									\
  } while (0)

/* Implementation function for all py8x-created native functions.  */

static i8x_err_e
py8x_natfunc_impl (struct i8x_xctx *xctx,
		   struct i8x_inf *inf,
		   struct i8x_func *func,
		   union i8x_value *argv,
		   union i8x_value *retv)
{
  struct i8x_funcref *ref = i8x_func_get_funcref (func);

  /* Pack the arguments.  */
  PyObject *args = py8x_pack_args (argv, ref);

  if (args == NULL)
    return I8X_NATCALL_FAILED;

  PY8X_NFI_SETARG (0, py8x_encapsulate (i8x_xctx_ref (xctx)));
  PY8X_NFI_SETARG (1, py8x_encapsulate (i8x_inf_ref (inf)));
  PY8X_NFI_SETARG (2, py8x_encapsulate (i8x_func_ref (func)));

  /* Make the call.  */
  struct py8x_func_userdata *ud = py8x_func_get_userdata (func);

  PyObject *rets = PyObject_Call (ud->impl, args, NULL);
  Py_DECREF (args);
  if (rets == NULL)
    return I8X_NATCALL_FAILED;

  /* Unpack the returns.  */
  bool success = py8x_unpack_rets (retv, rets, ref);
  Py_DECREF (rets);
  return success ? I8X_OK : I8X_NATCALL_FAILED;
}

/* Python binding for i8x_ctx_import_bytecode.  */

static PyObject *
py8x_ctx_import_bytecode (PyObject *self, PyObject *args)
{
  PyObject *ctxc;
  Py_buffer buffer;
  const char *srcname;
  long srcoff;

  if (!PyArg_ParseTuple (args, "O"
#if IS_PY3
			 "y"
#else
			 "s"
#endif /* IS_PY3 */
			 "*zl", &ctxc, &buffer, &srcname, &srcoff))
    return NULL;

  struct py8x_func_userdata *ud = py8x_func_userdata_new ();
  if (ud == NULL)
    return PyErr_NoMemory ();

  struct i8x_ctx *ctx = PY8X_FROM_CAPSULE (ctx);
  struct i8x_func *func;
  i8x_err_e err = i8x_ctx_import_bytecode (ctx,
					   buffer.buf, buffer.len,
					   srcname, srcoff,
					   &func);
  PyBuffer_Release (&buffer);

  if (err != I8X_OK)
    py8x_userdata_free (ud);

  PY8X_CHECK_CALL (ctx, err);

  return py8x_func_encapsulate (func, ud);
}

/* Python binding for i8x_ctx_import_native.  */

static PyObject *
py8x_ctx_import_native (PyObject *self, PyObject *args)
{
  PyObject *ctxc;
  const char *provider, *name, *ptypes, *rtypes;
  PyObject *impl;

  if (!PyArg_ParseTuple (args, "OssssO", &ctxc,
			 &provider, &name, &ptypes, &rtypes, &impl))
    return NULL;

  struct py8x_func_userdata *ud = py8x_func_userdata_new ();
  if (ud == NULL)
    return PyErr_NoMemory ();

  Py_INCREF (impl);
  ud->impl = impl;

  struct i8x_ctx *ctx = PY8X_FROM_CAPSULE (ctx);
  struct i8x_func *func;
  i8x_err_e err = i8x_ctx_import_native (ctx,
					 provider, name, ptypes, rtypes,
					 py8x_natfunc_impl, &func);
  if (err != I8X_OK)
    py8x_userdata_free (ud);

  PY8X_CHECK_CALL (ctx, err);

  return py8x_func_encapsulate (func, ud);
}

/* Python binding for i8x_xctx_call.  */

static PyObject *
py8x_xctx_call (PyObject *self, PyObject *args)
{
  PyObject *xctxc, *refc, *infc, *tmp;

  if (!PyArg_ParseTuple (args, "OOOO", &xctxc, &refc, &infc, &tmp))
    return NULL;
  args = tmp;

  struct i8x_funcref *ref = PY8X_FROM_CAPSULE_2 (funcref, ref);
  size_t argc = i8x_funcref_get_num_params (ref);
  size_t retc = i8x_funcref_get_num_returns (ref);
  union i8x_value *argv = alloca (PY8X_MAX (argc, retc));
  union i8x_value *retv = argv;

  if (!py8x_unpack_args (argv, args, ref))
    return NULL;

  struct i8x_xctx *xctx = PY8X_FROM_CAPSULE (xctx);
  struct i8x_inf *inf = PY8X_FROM_CAPSULE (inf);
  struct i8x_ctx *ctx = i8x_xctx_get_ctx (xctx);
  i8x_err_e err = i8x_xctx_call (xctx, ref, inf, argv, retv);

  PY8X_CHECK_CALL (ctx, err);

  return py8x_pack_rets (retv, ref);
}

/* Inferior (i8x_inf) userdata.  */

struct py8x_inf_userdata
{
  PY8X_USERDATA_FIELDS;

  /* Memory reader function.  */
  PyObject *read_mem_fn;

  /* Relocation function.  */
  PyObject *relocate_fn;
};

static void
py8x_inf_userdata_cleanup (struct py8x_userdata *ud_p)
{
  struct py8x_inf_userdata *ud = (struct py8x_inf_userdata *) ud_p;

  Py_XDECREF (ud->read_mem_fn);
  Py_XDECREF (ud->relocate_fn);
}

static const struct py8x_userdata_ops py8x_inf_udops =
  {
    "i8x_inf",
    sizeof (struct py8x_inf_userdata),
    py8x_inf_userdata_cleanup,
  };

PY8X_USERDATA_FUNCTIONS (inf)

/* Helpers for py8x_read_mem_fn and py8x_relocate_fn.  */

#define PY8X_RxF_SETARG(i, v, e)					\
  do {									\
    PyObject *arg = v;							\
									\
    if (arg == NULL || PyTuple_SetItem (args, (i), arg) != 0)		\
      {									\
	Py_DECREF (args);						\
	return e;							\
      }									\
  } while (0)

#define PY8X_RMF_SETARG(i, v) PY8X_RxF_SETARG(i, v, I8X_READ_MEM_FAILED)
#define PY8X_RLF_SETARG(i, v) PY8X_RxF_SETARG(i, v, I8X_RELOC_FAILED)

/* Memory reader function for all py8x-created inferiors.  */

static i8x_err_e
py8x_read_mem_fn (struct i8x_inf *inf, uintptr_t addr, size_t len,
		  void *result)
{
  struct py8x_inf_userdata *ud = py8x_inf_get_userdata (inf);

  if (ud->read_mem_fn == NULL || ud->read_mem_fn == Py_None)
    {
      PyErr_SetString (py8x_I8XError,
		       "inferior has no read_mem function");
      return I8X_READ_MEM_FAILED;
    }

  /* Pack the arguments.  */
  PyObject *args = PyTuple_New (3);
  if (args == NULL)
    return I8X_READ_MEM_FAILED;

  PY8X_RMF_SETARG (0, py8x_encapsulate (i8x_inf_ref (inf)));
  PY8X_RMF_SETARG (1, PyLong_FromUnsignedLong (addr));
  PY8X_RMF_SETARG (2, PyLong_FromSize_t (len));

  /* Make the call.  */
  PyObject *ret = PyObject_Call (ud->read_mem_fn, args, NULL);
  Py_DECREF (args);
  if (ret == NULL)
    return I8X_READ_MEM_FAILED;

  /* Read out the result.  */
  Py_buffer buf;

  if (PyObject_GetBuffer (ret, &buf, PyBUF_SIMPLE) != 0)
    {
      Py_DECREF (ret);
      return I8X_READ_MEM_FAILED;
    }

  if (buf.len != len)
    {
      Py_DECREF (ret);
      PyErr_SetString (py8x_I8XError,
		       "read_mem_fn returned bad length");
      return I8X_READ_MEM_FAILED;
    }

  memcpy (result, buf.buf, len);
  return I8X_OK;
}

/* Relocation function for all py8x-created inferiors.  */

static i8x_err_e
py8x_relocate_fn (struct i8x_inf *inf, struct i8x_reloc *reloc,
		  uintptr_t *result)
{
  struct py8x_inf_userdata *ud = py8x_inf_get_userdata (inf);

  if (ud->relocate_fn == NULL || ud->relocate_fn == Py_None)
    {
      PyErr_SetString (py8x_I8XError,
		       "inferior has no relocate function");
      return I8X_RELOC_FAILED;
    }

  /* Pack the arguments.  */
  PyObject *args = PyTuple_New (2);
  if (args == NULL)
    return I8X_RELOC_FAILED;

  PY8X_RLF_SETARG (0, py8x_encapsulate (i8x_inf_ref (inf)));
  PY8X_RLF_SETARG (1, py8x_encapsulate (i8x_reloc_ref (reloc)));

  /* Make the call.  */
  PyObject *ret = PyObject_Call (ud->relocate_fn, args, NULL);
  Py_DECREF (args);
  if (ret == NULL)
    return I8X_RELOC_FAILED;

  /* Read out the result.  */
  uintptr_t res = PyLong_AsUnsignedLong (ret);
  if (PyErr_Occurred () != NULL)
    return I8X_RELOC_FAILED;

  *result = res;
  return I8X_OK;
}

/* Python binding for i8x_inf_new.  */

static PyObject *
py8x_inf_new (PyObject *self, PyObject *args)
{
  PyObject *ctxc;

  if (!PyArg_ParseTuple (args, "O", &ctxc))
    return NULL;

  struct py8x_inf_userdata *ud = py8x_inf_userdata_new ();
  if (ud == NULL)
    return PyErr_NoMemory ();

  struct i8x_ctx *ctx = PY8X_FROM_CAPSULE (ctx);
  struct i8x_inf *inf;
  i8x_err_e err = i8x_inf_new (ctx, &inf);

  if (err != I8X_OK)
    py8x_userdata_free (ud);

  PY8X_CHECK_CALL (ctx, err);

  i8x_inf_set_read_mem_fn (inf, py8x_read_mem_fn);
  i8x_inf_set_relocate_fn (inf, py8x_relocate_fn);

  return py8x_inf_encapsulate (inf, ud);
}

/* Python binding for i8x_ctx_set_read_mem_fn.  */

static PyObject *
py8x_inf_set_read_mem_fn (PyObject *self, PyObject *args)
{
  PyObject *infc, *read_mem_fn;

  if (!PyArg_ParseTuple (args, "OO", &infc, &read_mem_fn))
    return NULL;

  struct i8x_inf *inf = PY8X_FROM_CAPSULE (inf);
  struct py8x_inf_userdata *ud = py8x_inf_get_userdata (inf);

  Py_XDECREF (ud->read_mem_fn);
  Py_INCREF (read_mem_fn);
  ud->read_mem_fn = read_mem_fn;

  Py_RETURN_NONE;
}

/* Python binding for i8x_ctx_set_relocate_fn.  */

static PyObject *
py8x_inf_set_relocate_fn (PyObject *self, PyObject *args)
{
  PyObject *infc, *relocate_fn;

  if (!PyArg_ParseTuple (args, "OO", &infc, &relocate_fn))
    return NULL;

  struct i8x_inf *inf = PY8X_FROM_CAPSULE (inf);
  struct py8x_inf_userdata *ud = py8x_inf_get_userdata (inf);

  Py_XDECREF (ud->relocate_fn);
  Py_INCREF (relocate_fn);
  ud->relocate_fn = relocate_fn;

  Py_RETURN_NONE;
}

/* Helper for methods that return list items (i8x_listitem).  */

#define PY8X_RETURN_LISTITEM(value)					\
  do {									\
    struct i8x_listitem *result = value;				\
									\
    if (result == NULL)							\
      {									\
	PyErr_SetNone(PyExc_StopIteration);				\
	return NULL;							\
      }									\
									\
    return py8x_encapsulate (i8x_listitem_ref (result));		\
  } while (0)

/* Python binding for i8x_list_get_first.  */

static PyObject *
py8x_list_get_first (PyObject *self, PyObject *args)
{
  PyObject *listc;

  if (!PyArg_ParseTuple (args, "O", &listc))
    return NULL;

  struct i8x_list *list = PY8X_FROM_CAPSULE (list);

  PY8X_RETURN_LISTITEM (i8x_list_get_first (list));
}

/* Python binding for i8x_list_get_next.  */

static PyObject *
py8x_list_get_next (PyObject *self, PyObject *args)
{
  PyObject *listc;
  PyObject *currc;

  if (!PyArg_ParseTuple (args, "OO", &listc, &currc))
    return NULL;

  struct i8x_list *list = PY8X_FROM_CAPSULE (list);
  struct i8x_listitem *curr = PY8X_FROM_CAPSULE_2 (listitem, curr);

  PY8X_RETURN_LISTITEM (i8x_list_get_next (list, curr));
}

/* Python binding for i8x_note_get_unique_chunk.  */

static PyObject *
py8x_note_get_unique_chunk (PyObject *self, PyObject *args)
{
  PyObject *notec;
  uintptr_t type_id;
  int must_exist;

  if (!PyArg_ParseTuple (args, "Oki", &notec, &type_id, &must_exist))
    return NULL;

  struct i8x_note *note = PY8X_FROM_CAPSULE (note);
  struct i8x_chunk *chunk;
  i8x_err_e err = i8x_note_get_unique_chunk (note, type_id, must_exist,
					     &chunk);

  PY8X_CHECK_CALL (i8x_note_get_ctx (note), err);

  return py8x_encapsulate (i8x_chunk_ref (chunk));
}

/* Python binding for i8x_chunk_get_encoded.  */

static PyObject *
py8x_chunk_get_encoded (PyObject *self, PyObject *args)
{
  PyObject *chunkc;

  if (!PyArg_ParseTuple (args, "O", &chunkc))
    return NULL;

  struct i8x_chunk *chunk = PY8X_FROM_CAPSULE (chunk);

  return PyBytes_FromStringAndSize (i8x_chunk_get_encoded (chunk),
				    i8x_chunk_get_encoded_size (chunk));
}

#pragma libi8x_api_functions

/* Convert an unsigned value to signed w.r.t. libi8x's wordsize.  */

static PyObject *
py8x_to_signed (PyObject *self, PyObject *args)
{
  PyObject *n;
  union i8x_value v;

  if (!PyArg_ParseTuple (args, "O", &n))
    return NULL;

  v.u = PyLong_AsUnsignedLong (n);
  if (PyErr_Occurred () != NULL)
    return NULL;

  return PyLong_FromLong (v.i);
}

/* Convert an signed value to unsigned w.r.t. libi8x's wordsize.  */

static PyObject *
py8x_to_unsigned (PyObject *self, PyObject *args)
{
  union i8x_value v;

  if (!PyArg_ParseTuple (args, "l", &v.i))
    return NULL;

  return PyLong_FromUnsignedLong (v.u);
}

/* Module-level functions table.  */

#define PY8X_FUNCTION(name) {#name, py8x_ ## name, METH_VARARGS, NULL}

static PyMethodDef libi8x_methods[] = {
  PY8X_FUNCTION (ctx_new),
  PY8X_FUNCTION (ctx_set_log_fn),
  PY8X_FUNCTION (ctx_import_bytecode),
  PY8X_FUNCTION (ctx_import_native),
  PY8X_FUNCTION (xctx_call),
  PY8X_FUNCTION (inf_new),
  PY8X_FUNCTION (inf_set_read_mem_fn),
  PY8X_FUNCTION (inf_set_relocate_fn),
  PY8X_FUNCTION (list_get_first),
  PY8X_FUNCTION (list_get_next),
  PY8X_FUNCTION (note_get_unique_chunk),
  PY8X_FUNCTION (chunk_get_encoded),
  PY8X_FUNCTION (to_signed),
  PY8X_FUNCTION (to_unsigned),
#pragma libi8x_api_function_table
  {NULL, NULL, 0, NULL}
};

/* Module definition.  */

static struct PyModuleDef libi8x_moduledef =
  {
    PyModuleDef_HEAD_INIT,
    .m_name = "_libi8x",
    .m_doc = PyDoc_STR ("Python bindings for libi8x."),
    .m_size = -1,
    .m_methods = libi8x_methods,
  };

/* Module initialization function.  */

#define PY8X_CONSTANT(mod, name)					\
  PyModule_AddIntConstant (mod, #name, name)

MODULE_INIT_FUNC (_libi8x)
{
  PyObject *m = PyModule_Create (&libi8x_moduledef);
  if (m == NULL)
    return NULL;

  py8x_I8XError = PyErr_NewException ("_libi8x.I8XError",
				   PyExc_RuntimeError, NULL);
  if (py8x_I8XError == NULL)
    return NULL;

  if (PyModule_AddObject (m, "I8XError", py8x_I8XError) != 0)
    return NULL;

#pragma libi8x_api_constants

  return m;
}