1/*
2** C data management.
3** Copyright (C) 2005-2021 Mike Pall. See Copyright Notice in luajit.h
4*/
5
6#ifndef _LJ_CDATA_H
7#define _LJ_CDATA_H
8
9#include "lj_obj.h"
10#include "lj_gc.h"
11#include "lj_ctype.h"
12
13#if LJ_HASFFI
14
15/* Get C data pointer. */
16static LJ_AINLINE void *cdata_getptr(void *p, CTSize sz)
17{
18 if (LJ_64 && sz == 4) { /* Support 32 bit pointers on 64 bit targets. */
19 return ((void *)(uintptr_t)*(uint32_t *)p);
20 } else {
21 lj_assertX(sz == CTSIZE_PTR, "bad pointer size %d", sz);
22 return *(void **)p;
23 }
24}
25
26/* Set C data pointer. */
27static LJ_AINLINE void cdata_setptr(void *p, CTSize sz, const void *v)
28{
29 if (LJ_64 && sz == 4) { /* Support 32 bit pointers on 64 bit targets. */
30 *(uint32_t *)p = (uint32_t)(uintptr_t)v;
31 } else {
32 lj_assertX(sz == CTSIZE_PTR, "bad pointer size %d", sz);
33 *(void **)p = (void *)v;
34 }
35}
36
37/* Allocate fixed-size C data object. */
38static LJ_AINLINE GCcdata *lj_cdata_new(CTState *cts, CTypeID id, CTSize sz)
39{
40 GCcdata *cd;
41#ifdef LUA_USE_ASSERT
42 CType *ct = ctype_raw(cts, id);
43 lj_assertCTS((ctype_hassize(ct->info) ? ct->size : CTSIZE_PTR) == sz,
44 "inconsistent size of fixed-size cdata alloc");
45#endif
46 cd = (GCcdata *)lj_mem_newgco(cts->L, sizeof(GCcdata) + sz);
47 cd->gct = ~LJ_TCDATA;
48 cd->ctypeid = ctype_check(cts, id);
49 return cd;
50}
51
52/* Variant which works without a valid CTState. */
53static LJ_AINLINE GCcdata *lj_cdata_new_(lua_State *L, CTypeID id, CTSize sz)
54{
55 GCcdata *cd = (GCcdata *)lj_mem_newgco(L, sizeof(GCcdata) + sz);
56 cd->gct = ~LJ_TCDATA;
57 cd->ctypeid = id;
58 return cd;
59}
60
61LJ_FUNC GCcdata *lj_cdata_newref(CTState *cts, const void *pp, CTypeID id);
62LJ_FUNC GCcdata *lj_cdata_newv(lua_State *L, CTypeID id, CTSize sz,
63 CTSize align);
64LJ_FUNC GCcdata *lj_cdata_newx(CTState *cts, CTypeID id, CTSize sz,
65 CTInfo info);
66
67LJ_FUNC void LJ_FASTCALL lj_cdata_free(global_State *g, GCcdata *cd);
68LJ_FUNC void lj_cdata_setfin(lua_State *L, GCcdata *cd, GCobj *obj,
69 uint32_t it);
70
71LJ_FUNC CType *lj_cdata_index(CTState *cts, GCcdata *cd, cTValue *key,
72 uint8_t **pp, CTInfo *qual);
73LJ_FUNC int lj_cdata_get(CTState *cts, CType *s, TValue *o, uint8_t *sp);
74LJ_FUNC void lj_cdata_set(CTState *cts, CType *d, uint8_t *dp, TValue *o,
75 CTInfo qual);
76
77#endif
78
79#endif
80