/
record.c
670 lines (589 loc) · 16.7 KB
/
record.c
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
/*
* Dynamic Lua binding to GObject using dynamic gobject-introspection.
*
* Copyright (c) 2010, 2011, 2012 Pavel Holejsovsky
* Licensed under the MIT license:
* http://www.opensource.org/licenses/mit-license.php
*
* Management of structures and unions (i.e. records).
*/
#include <string.h>
#include "lgi.h"
/* Available record store modes. */
typedef enum _RecordStore
{
/* We do not have ownership of the record. */
RECORD_STORE_EXTERNAL,
/* Record is stored in data section of Record proxy itself. */
RECORD_STORE_EMBEDDED,
/* Record is placed inside some other (parent) record. In order
to keep parent record alive, parent record is stored in
parent_cache table. */
RECORD_STORE_NESTED,
/* Record is allocated by its GLib means and must be freed (by
g_boxed_free). */
RECORD_STORE_ALLOCATED,
} RecordStore;
/* Userdata containing record reference. Table with record type is
attached as userdata environment. */
typedef struct _Record
{
/* Address of the record memory data. */
gpointer addr;
/* Store mode of the record. */
RecordStore store;
/* If the record is allocated 'on the stack', its data is
here. Anonymous union makes sure that data is properly aligned to
hold (hopefully) any structure. */
union {
gchar data[1];
double align_double;
long align_long;
gpointer align_ptr;
};
} Record;
/* lightuserdata key to LUA_REGISTRYINDEX containing metatable for
record. */
static int record_mt;
/* lightuserdata key to cache table containing
lightuserdata(record->addr) -> weak(record) */
static int record_cache;
/* lightuserdata key to cache table containing
recordproxy(weak) -> parent */
static int parent_cache;
gpointer
lgi_record_new (lua_State *L, int count)
{
Record *record;
size_t size;
luaL_checkstack (L, 4, "");
/* Calculate size of the record to allocate. */
lua_getfield (L, -1, "_size");
size = G_STRUCT_OFFSET (Record, data) + lua_tonumber (L, -1) * count;
lua_pop (L, 1);
/* Allocate new userdata for record object, attach proper
metatable. */
record = lua_newuserdata (L, size);
lua_pushlightuserdata (L, &record_mt);
lua_rawget (L, LUA_REGISTRYINDEX);
lua_setmetatable (L, -2);
record->addr = record->data;
memset (record->addr, 0, size - G_STRUCT_OFFSET (Record, data));
record->store = RECORD_STORE_EMBEDDED;
/* Get ref_repo table, attach it as an environment. */
lua_pushvalue (L, -2);
lua_setfenv (L, -2);
/* Store newly created record into the cache. */
lua_pushlightuserdata (L, &record_cache);
lua_rawget (L, LUA_REGISTRYINDEX);
lua_pushlightuserdata (L, record->addr);
lua_pushvalue (L, -3);
lua_rawset (L, -3);
lua_pop (L, 1);
/* Invoke '_attach' method if present on the typetable. */
lua_getfield (L, -2, "_attach");
if (!lua_isnil (L, -1))
{
lua_pushvalue (L, -3);
lua_pushvalue (L, -3);
lua_call (L, 2, 0);
}
else
lua_pop (L, 1);
/* Remove refrepo table from the stack. */
lua_remove (L, -2);
return record->addr;
}
void
lgi_record_2lua (lua_State *L, gpointer addr, gboolean own, int parent)
{
Record *record;
luaL_checkstack (L, 5, "");
/* NULL pointer results in 'nil'. */
if (addr == NULL)
{
lua_pop (L, 1);
lua_pushnil (L);
return;
}
/* Convert 'parent' index to an absolute one. */
if (parent == LGI_PARENT_IS_RETVAL || parent == LGI_PARENT_FORCE_POINTER)
parent = 0;
else
lgi_makeabs (L, parent);
/* Prepare access to cache. */
lua_pushlightuserdata (L, &record_cache);
lua_rawget (L, LUA_REGISTRYINDEX);
/* Check whether the record is already cached. */
lua_pushlightuserdata (L, addr);
lua_rawget (L, -2);
if (!lua_isnil (L, -1) && parent == 0)
{
/* Remove unneeded tables under our requested object. */
lua_replace (L, -3);
lua_pop (L, 1);
/* In case that we want to own the record, make sure that the
ownership is properly updated. */
record = lua_touserdata (L, -1);
g_assert (record->addr == addr);
if (own && record->store == RECORD_STORE_EXTERNAL)
record->store = RECORD_STORE_ALLOCATED;
return;
}
/* Allocate new userdata for record object, attach proper
metatable. */
record = lua_newuserdata (L, G_STRUCT_OFFSET (Record, data));
lua_pushlightuserdata (L, &record_mt);
lua_rawget (L, LUA_REGISTRYINDEX);
lua_setmetatable (L, -2);
record->addr = addr;
if (parent != 0)
{
/* Store reference to the parent argument into parent reference
cache. */
lua_pushlightuserdata (L, &parent_cache);
lua_rawget (L, LUA_REGISTRYINDEX);
lua_pushvalue (L, -2);
lua_pushvalue (L, parent);
lua_rawset (L, -3);
lua_pop (L, 1);
record->store = RECORD_STORE_NESTED;
}
else
{
if (!own)
{
/* Check, whether refrepo table specifies custom _refsink
function. */
void (*refsink_func)(gpointer) =
lgi_gi_load_function (L, -4, "_refsink");
if (refsink_func)
{
refsink_func(addr);
own = TRUE;
}
}
record->store = own ? RECORD_STORE_ALLOCATED : RECORD_STORE_EXTERNAL;
}
/* Assign refrepo table (on the stack when we are called) as
environment for our proxy. */
lua_pushvalue (L, -4);
lua_setfenv (L, -2);
/* Store newly created record into the cache. */
if (parent == 0 && own)
{
lua_pushlightuserdata (L, addr);
lua_pushvalue (L, -2);
lua_rawset (L, -5);
}
/* Invoke '_attach' method if present on the typetable. */
lua_getfield (L, -4, "_attach");
if (!lua_isnil (L, -1))
{
lua_pushvalue (L, -5);
lua_pushvalue (L, -3);
lua_call (L, 2, 0);
}
else
lua_pop (L, 1);
/* Clean up the stack; remove cache table from under our result, and
remove also typetable which was present when we were called. */
lua_replace (L, -4);
lua_pop (L, 2);
}
/* Checks that given argument is Record userdata and returns pointer
to it. Returns NULL if narg has bad type. */
static Record *
record_check (lua_State *L, int narg)
{
/* Check using metatable that narg is really Record type. */
Record *record = lua_touserdata (L, narg);
luaL_checkstack (L, 3, "");
if (!lua_getmetatable (L, narg))
return NULL;
lua_pushlightuserdata (L, &record_mt);
lua_rawget (L, LUA_REGISTRYINDEX);
if (!lua_equal (L, -1, -2))
record = NULL;
lua_pop (L, 2);
return record;
}
/* Throws error that narg is not of expected type. */
static int
record_error (lua_State *L, int narg, const gchar *expected_name)
{
luaL_checkstack (L, 2, "");
lua_pushstring (L, lua_typename (L, lua_type (L, narg)));
lua_pushfstring (L, "%s expected, got %s",
expected_name ? expected_name : "lgi.record",
lua_tostring (L, -1));
return luaL_argerror (L, narg, lua_tostring (L, -1));
}
/* Similar to record_check, but throws in case of failure. */
static Record *
record_get (lua_State *L, int narg)
{
Record *record = record_check (L, narg);
if (record == NULL)
record_error (L, narg, NULL);
return record;
}
gpointer
lgi_record_2c (lua_State *L, int narg, gboolean optional, gboolean nothrow)
{
Record *record;
/* Check for nil. */
if (optional && lua_isnoneornil (L, narg))
{
lua_pop (L, 1);
return NULL;
}
/* Get record and check its type. */
lgi_makeabs (L, narg);
luaL_checkstack (L, 4, "");
record = record_check (L, narg);
if (record)
{
/* Check, whether type fits. Also take into account possible
inheritance. */
lua_getfenv (L, narg);
for (;;)
{
if (lua_equal (L, -1, -2))
break;
/* Try to get parent of the real type. */
lua_getfield (L, -1, "_parent");
lua_replace (L, -2);
if (lua_isnil (L, -1))
{
record = NULL;
break;
}
}
lua_pop (L, 1);
}
if (!nothrow && !record)
{
const gchar *name = NULL;
if (!lua_isnil (L, -1))
{
lua_getfield (L, -1, "_name");
name = lua_tostring (L, -1);
}
record_error (L, narg, name);
}
lua_pop (L, 1);
return record ? record->addr : NULL;
}
static int
record_gc (lua_State *L)
{
Record *record = record_get (L, 1);
if (record->store == RECORD_STORE_EMBEDDED
|| record->store == RECORD_STORE_NESTED)
{
/* Check whether record has registered '_uninit' function, and
invoke it if yes. */
lua_getfenv (L, 1);
void (*uninit)(gpointer) = lgi_gi_load_function (L, -1, "_uninit");
if (uninit != NULL)
uninit (record->addr);
}
else if (record->store == RECORD_STORE_ALLOCATED)
{
/* Free the owned record. */
GType gtype;
lua_getfenv (L, 1);
for (;;)
{
lua_getfield (L, -1, "_gtype");
gtype = (GType) lua_touserdata (L, -1);
lua_pop (L, 1);
if (G_TYPE_IS_BOXED (gtype))
{
g_boxed_free (gtype, record->addr);
break;
}
else
{
/* Use custom _free function. */
void (*free_func)(gpointer) =
lgi_gi_load_function (L, -1, "_free");
if (free_func)
{
free_func (record->addr);
break;
}
}
/* Try to get parent of the type. */
lua_getfield (L, -1, "_parent");
lua_replace (L, -2);
if (lua_isnil (L, -1))
{
lua_getfenv (L, 1);
lua_getfield (L, -1, "_name");
g_warning ("unable to record_gc %s, leaking it",
lua_tostring (L, -1));
lua_pop (L, 2);
break;
}
}
}
if (record->store == RECORD_STORE_NESTED)
{
/* Free the reference to the parent. */
lua_pushlightuserdata (L, record);
lua_pushnil (L);
lua_rawset (L, LUA_REGISTRYINDEX);
}
return 0;
}
static int
record_tostring (lua_State *L)
{
Record *record = record_get (L, 1);
lua_pushfstring (L, "lgi.rec %p:", record->addr);
lua_getfenv (L, 1);
lua_getfield (L, -1, "_name");
lua_replace (L, -2);
if (!lua_isnil (L, -1))
lua_concat (L, 2);
else
lua_pop (L, 1);
return 1;
}
/* Worker method for __index and __newindex implementation. */
static int
record_access (lua_State *L)
{
gboolean getmode = lua_isnone (L, 3);
/* Check that 1st arg is a record and invoke one of the forms:
result = type:_access(recordinstance, name)
type:_access(recordinstance, name, val) */
record_get (L, 1);
lua_getfenv (L, 1);
return lgi_marshal_access (L, getmode, 1, 2, 3);
}
/* Worker method for __len implementation. */
static int
record_len (lua_State *L)
{
/* Check record, get its typetable and try to invoke _len method. */
record_get (L, 1);
lua_getfenv (L, 1);
lua_getfield (L, -1, "_len");
if (lua_isnil (L, -1))
{
lua_getfield (L, -2, "_name");
return luaL_error (L, "`%s': attempt to get length",
lua_tostring (L, -1));
}
lua_pushvalue (L, 1);
lua_call (L, 1, 1);
return 1;
}
static const struct luaL_Reg record_meta_reg[] = {
{ "__gc", record_gc },
{ "__tostring", record_tostring },
{ "__index", record_access },
{ "__newindex", record_access },
{ "__len", record_len },
{ NULL, NULL }
};
/* Implements generic record creation. Creates new record instance,
unless 'addr' argument (lightuserdata or integer) is specified, in
which case wraps specified address as record. Lua prototype:
recordinstance = core.record.new(repotable[, nil[, count]])
recordinstance = core.record.new(repotable[, addr[, own]])
own (default false) means whether Lua takes record ownership
(i.e. if it tries to deallocate the record when created Lua proxy
dies). */
static int
record_new (lua_State *L)
{
if (lua_isnoneornil (L, 2))
{
/* Create new record instance. */
lua_pushvalue (L, 1);
lgi_record_new (L, luaL_optinteger (L, 3, 1));
}
else
{
/* Wrap record at existing address. */
gpointer addr = (lua_type (L, 2) == LUA_TLIGHTUSERDATA)
? addr = lua_touserdata (L, 2)
: (gpointer) luaL_checkinteger (L, 2);
gboolean own = lua_toboolean (L, 3);
lua_pushvalue (L, 1);
lgi_record_2lua (L, addr, own, 0);
}
return 1;
}
static const char* const query_modes[] = { "gtype", "repo", "addr", NULL };
/* Returns specific information mode about given record. Lua prototype:
res = record.query(instance, mode)
Supported 'mode' strings are:
'gtype': returns real gtype of this instance, nil when it is not boxed.
'repo': returns repotable of this instance.
'addr': returns address of the object. If 3rd argument is either
repotable, checks, whether record conforms to the specs and
if not, throws an error. */
static int
record_query (lua_State *L)
{
Record *record;
int mode = luaL_checkoption (L, 2, query_modes[0], query_modes);
if (mode < 2)
{
record = record_check (L, 1);
if (!record)
return 0;
lua_getfenv (L, 1);
if (mode == 0)
{
GType gtype;
if (lua_isnil (L, -1))
return 0;
lua_getfield (L, -1, "_gtype");
gtype = luaL_optinteger (L, -1, G_TYPE_INVALID);
lua_pushstring (L, g_type_name (gtype));
}
return 1;
}
else
{
if (lua_isnoneornil (L, 3))
lua_pushlightuserdata (L, record_check (L, 1)->addr);
else
{
lua_pushvalue (L, 3);
lua_pushlightuserdata (L, lgi_record_2c (L, 1, TRUE, FALSE));
}
return 1;
}
}
/* Implements set/get field operation. Lua prototypes:
res = core.record.field(recordinstance, fieldinfo)
core.record.field(recordinstance, fieldinfo, newval) */
static int
record_field (lua_State *L)
{
gboolean getmode;
Record *record;
/* Check, whether we are doing set or get operation. */
getmode = lua_isnone (L, 3);
/* Get record instance. */
record = record_get (L, 1);
/* Call field marshalling worker. */
return lgi_marshal_field (L, record->addr, getmode, 1, 2, 3);
}
/* Casts given record to another record type. Lua prototype:
res = core.record.cast(recordinstance, targettypetable) */
static int
record_cast (lua_State *L)
{
Record *record = record_get (L, 1);
luaL_checktype (L, 2, LUA_TTABLE);
lgi_record_2lua (L, record->addr, FALSE, 1);
return 1;
}
/* Assumes that given record is the first of the array of records and
fetches record with specified index. Negative indices are allowed,
but no boundschecking is made.
res = core.record.fromarray(recordinstance, index) */
static int
record_fromarray (lua_State *L)
{
Record *record = record_get (L, 1);
int index = luaL_checkinteger (L, 2);
int parent = 0;
gboolean own = FALSE;
int size;
/* Find out the size of this record. */
lua_getfenv (L, 1);
lua_getfield (L, -1, "_size");
size = lua_tonumber (L, -1);
if (record->store == RECORD_STORE_EMBEDDED)
/* Parent is actually our embedded record. */
parent = 1;
else if (record->store == RECORD_STORE_NESTED)
{
/* Share parent with the original record. */
lua_pushlightuserdata (L, &parent_cache);
lua_rawget (L, LUA_REGISTRYINDEX);
lua_pushvalue (L, 1);
lua_rawget (L, -2);
parent = -2;
}
lua_getfenv (L, 1);
lgi_record_2lua (L, ((guint8 *) record->addr) + size * index, own, parent);
return 1;
}
/* Changes ownership mode or repotable of the record.
record.set(recordinstance, true|false)
- 'own' if true, changing ownership to owned, otherwise to
unowned.
record.set(recordinstance, repotable)
- 'repotable' record repotable to which this instance should be
reassigned. */
static int
record_set (lua_State *L)
{
Record *record = record_get (L, 1);
if (lua_type (L, 2) == LUA_TTABLE)
{
/* Assign new typeinfo to the record instance. */
lua_pushvalue (L, 2);
lua_setfenv (L, 1);
}
else
{
/* Change ownership type of the record. */
if (lua_toboolean (L, 2))
{
if (record->store == RECORD_STORE_EXTERNAL)
record->store = RECORD_STORE_ALLOCATED;
}
else
{
if (record->store == RECORD_STORE_ALLOCATED)
record->store = RECORD_STORE_EXTERNAL;
}
}
return 0;
}
static const struct luaL_Reg record_api_reg[] = {
{ "new", record_new },
{ "query", record_query },
{ "field", record_field },
{ "cast", record_cast },
{ "fromarray", record_fromarray },
{ "set", record_set },
{ NULL, NULL }
};
/* Workaround for g_value_unset(), which complains when invoked on
uninitialized GValue instance. */
static void
record_value_unset (GValue *value)
{
if (G_IS_VALUE (value))
g_value_unset (value);
}
void
lgi_record_init (lua_State *L)
{
/* Register record metatable. */
lua_pushlightuserdata (L, &record_mt);
lua_newtable (L);
luaL_register (L, NULL, record_meta_reg);
lua_rawset (L, LUA_REGISTRYINDEX);
/* Create caches. */
lgi_cache_create (L, &record_cache, "v");
lgi_cache_create (L, &parent_cache, "k");
/* Create 'record' API table in main core API table. */
lua_newtable (L);
luaL_register (L, NULL, record_api_reg);
lua_pushlightuserdata (L, record_value_unset);
lua_setfield (L, -2, "value_unset");
lua_setfield (L, -2, "record");
}