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
|
// luamm: C++ binding for lua
// Copyright (C) 2010 - 2011 Pavel Labath
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#include <config.h>
#include "Luamm.hh"
namespace lua {
namespace {
// keys for storing values in lua registry
const char cpp_exception_metatable[] = "lua::cpp_exception_metatable";
const char cpp_function_metatable [] = "lua::cpp_function_metatable";
const char lua_exception_namespace[] = "lua::lua_exception_namespace";
const char this_cpp_object [] = "lua::this_cpp_object";
// converts C++ exceptions to strings, so lua can do something with them
int exception_to_string(lua_State *l)
{
std::exception_ptr *ptr = static_cast<std::exception_ptr *>(lua_touserdata(l, -1));
assert(ptr);
try {
std::rethrow_exception(*ptr);
}
catch(std::exception &e) {
lua_pushstring(l, e.what());
}
catch(...) {
lua_pushstring(l, ptr->__cxa_exception_type()->name());
}
return 1;
}
int absindex(lua_State *l, int index) throw()
{ return index<0 && -index<=lua_gettop(l) ? lua_gettop(l)+1+index : index; }
// Just like getfield(), only without calling metamethods (or throwing random exceptions)
inline void rawgetfield(lua_State *l, int index, const char *k) throw(std::bad_alloc)
{
index = absindex(l, index);
if(not lua_checkstack(l, 1))
throw std::bad_alloc();
lua_pushstring(l, k);
lua_rawget(l, index);
}
// Just like setfield(), only without calling metamethods (or throwing random exceptions)
inline void rawsetfield(lua_State *l, int index, const char *k) throw(std::bad_alloc)
{
index = absindex(l, index);
if(not lua_checkstack(l, 2))
throw std::bad_alloc();
lua_pushstring(l, k);
lua_insert(l, -2);
lua_rawset(l, index);
}
int closure_trampoline(lua_State *l)
{
lua_checkstack(l, 2);
rawgetfield(l, REGISTRYINDEX, this_cpp_object);
assert(lua_islightuserdata(l, -1));
state *L = static_cast<state *>( lua_touserdata(l, -1) );
lua_pop(l, 1);
try {
cpp_function *fn = static_cast<cpp_function *>( L->touserdata(lua_upvalueindex(1)) );
assert(fn);
return (*fn)(L);
}
catch(lua::exception &e) {
// rethrow lua errors as such
e.push_lua_error(L);
}
catch(...) {
// C++ exceptions (pointers to them, actually) are stored as lua userdata and
// then thrown
L->createuserdata<std::exception_ptr>(std::current_exception());
L->rawgetfield(REGISTRYINDEX, cpp_exception_metatable);
L->setmetatable(-2);
}
// lua_error does longjmp(), so destructors for objects in this function will not be
// called
return lua_error(l);
}
/*
* This function is called when lua encounters an error outside of any protected
* environment
* Throwing the exception through lua code appears to work, even if it was compiled
* without -fexceptions. If it turns out, it fails in some conditions, it could be
* replaced with some longjmp() magic. But that shouldn't be necessary, as this function
* will not be called under normal conditions (we execute everything in protected mode).
*/
int panic_throw(lua_State *l)
{
if(not lua_checkstack(l, 1))
throw std::bad_alloc();
rawgetfield(l, REGISTRYINDEX, this_cpp_object);
assert(lua_islightuserdata(l, -1));
state *L = static_cast<state *>( lua_touserdata(l, -1) );
lua_pop(l, 1);
throw lua::exception(L);
}
// protected mode wrappers for various lua functions
int safe_concat_trampoline(lua_State *l)
{
lua_concat(l, lua_gettop(l));
return 1;
}
template<int (*compare)(lua_State *, int, int)>
int safe_compare_trampoline(lua_State *l)
{
int r = compare(l, 1, 2);
lua_pop(l, 2);
lua_pushinteger(l, r);
return 1;
}
int safe_gc_trampoline(lua_State *l)
{
int what = lua_tointeger(l, -2);
int data = lua_tointeger(l, -1);
lua_pop(l, 2);
lua_pushinteger(l, lua_gc(l, what, data));
return 1;
}
template<void (*misc)(lua_State *, int), int nresults>
int safe_misc_trampoline(lua_State *l)
{
misc(l, 1);
return nresults;
}
int safe_next_trampoline(lua_State *l)
{
int r = lua_next(l, 1);
lua_checkstack(l, 1);
lua_pushinteger(l, r);
return r ? 3 : 1;
}
}
std::string exception::get_error_msg(state *L)
{
static const std::string default_msg("Unknown lua exception");
try {
return L->tostring(-1);
}
catch(not_string_error &e) {
return default_msg;
}
}
exception::exception(state *l)
: std::runtime_error(get_error_msg(l)), L(l)
{
L->checkstack(1);
L->rawgetfield(REGISTRYINDEX, lua_exception_namespace);
L->insert(-2);
key = L->ref(-2);
L->pop(1);
}
exception::~exception() throw()
{
if(not L)
return;
L->checkstack(1);
L->rawgetfield(REGISTRYINDEX, lua_exception_namespace);
L->unref(-1, key);
L->pop();
}
void exception::push_lua_error(state *l)
{
if(l != L)
throw std::runtime_error("Cannot transfer exceptions between different lua contexts");
l->checkstack(2);
l->rawgetfield(REGISTRYINDEX, lua_exception_namespace);
l->rawgeti(-1, key);
l->replace(-2);
}
state::state()
{
if(lua_State *l = luaL_newstate())
cobj.reset(l, &lua_close);
else {
// docs say this can happen only in case of a memory allocation error
throw std::bad_alloc();
}
// set our panic function
lua_atpanic(cobj.get(), panic_throw);
checkstack(2);
// store a pointer to ourselves
pushlightuserdata(this);
rawsetfield(REGISTRYINDEX, this_cpp_object);
// a metatable for C++ exceptions travelling through lua code
newmetatable(cpp_exception_metatable);
lua_pushcfunction(cobj.get(), &exception_to_string);
rawsetfield(-2, "__tostring");
pushboolean(false);
rawsetfield(-2, "__metatable");
pushdestructor<std::exception_ptr>();
rawsetfield(-2, "__gc");
pop();
// a metatable for C++ functions callable from lua code
newmetatable(cpp_function_metatable);
pushboolean(false);
rawsetfield(-2, "__metatable");
pushdestructor<cpp_function>();
rawsetfield(-2, "__gc");
pop();
// while they're travelling through C++ code, lua exceptions will reside here
newtable();
rawsetfield(REGISTRYINDEX, lua_exception_namespace);
luaL_openlibs(cobj.get());
}
void state::call(int nargs, int nresults, int errfunc)
{
int r = lua_pcall(cobj.get(), nargs, nresults, errfunc);
if(r == 0)
return;
if(r == LUA_ERRMEM) {
// memory allocation error, cross your fingers
throw std::bad_alloc();
}
checkstack(3);
rawgetfield(REGISTRYINDEX, cpp_exception_metatable);
if(getmetatable(-2)) {
if(rawequal(-1, -2)) {
// it's a C++ exception, rethrow it
std::exception_ptr *ptr = static_cast<std::exception_ptr *>(touserdata(-3));
assert(ptr);
/*
* we create a copy, so we can pop the object without fearing the exception will
* be collected by lua's GC
*/
std::exception_ptr t(*ptr); ptr = NULL;
pop(3);
std::rethrow_exception(t);
}
pop(2);
}
// it's a lua exception, wrap it
if(r == LUA_ERRERR)
throw lua::errfunc_error(this);
else
throw lua::exception(this);
}
void state::checkstack(int extra) throw(std::bad_alloc)
{
if(not lua_checkstack(cobj.get(), extra))
throw std::bad_alloc();
}
void state::concat(int n)
{
assert(n>=0);
checkstack(1);
lua_pushcfunction(cobj.get(), safe_concat_trampoline);
insert(-n-1);
call(n, 1, 0);
}
bool state::equal(int index1, int index2)
{
// avoid pcall overhead in trivial cases
if( rawequal(index1, index2) )
return true;
return safe_compare(&safe_compare_trampoline<lua_equal>, index1, index2);
}
int state::gc(int what, int data)
{
checkstack(3);
lua_pushcfunction(cobj.get(), safe_gc_trampoline);
pushinteger(what);
pushinteger(data);
call(2, 1, 0);
assert(isnumber(-1));
int r = tointeger(-1);
pop();
return r;
}
void state::getfield(int index, const char *k)
{
checkstack(1);
index = absindex(index);
pushstring(k);
gettable(index);
}
void state::gettable(int index)
{
checkstack(2);
pushvalue(index);
insert(-2);
lua_pushcfunction(cobj.get(), (&safe_misc_trampoline<&lua_gettable, 1>));
insert(-3);
call(2, 1, 0);
}
bool state::lessthan(int index1, int index2)
{
return safe_compare(&safe_compare_trampoline<&lua_lessthan>, index1, index2);
}
void state::loadfile(const char *filename)
throw(lua::syntax_error, lua::file_error, std::bad_alloc)
{
switch(luaL_loadfile(cobj.get(), filename)) {
case 0:
return;
case LUA_ERRSYNTAX:
throw lua::syntax_error(this);
case LUA_ERRFILE:
throw lua::file_error(this);
case LUA_ERRMEM:
throw std::bad_alloc();
default:
assert(0);
}
}
void state::loadstring(const char *s) throw(lua::syntax_error, std::bad_alloc)
{
switch(luaL_loadstring(cobj.get(), s)) {
case 0:
return;
case LUA_ERRSYNTAX:
throw lua::syntax_error(this);
case LUA_ERRMEM:
throw std::bad_alloc();
default:
assert(0);
}
}
bool state::next(int index)
{
checkstack(2);
pushvalue(index);
insert(-2);
lua_pushcfunction(cobj.get(), &safe_next_trampoline);
insert(-3);
call(2, MULTRET, 0);
assert(isnumber(-1));
int r = tointeger(-1);
pop();
return r;
}
void state::pushclosure(const cpp_function &fn, int n)
{
checkstack(2);
createuserdata<cpp_function>(fn);
rawgetfield(REGISTRYINDEX, cpp_function_metatable);
setmetatable(-2);
insert(-n-1);
lua_pushcclosure(cobj.get(), &closure_trampoline, n+1);
}
void state::rawgetfield(int index, const char *k) throw(std::bad_alloc)
{ lua::rawgetfield(cobj.get(), index, k); }
void state::rawsetfield(int index, const char *k) throw(std::bad_alloc)
{ lua::rawsetfield(cobj.get(), index, k); }
bool state::safe_compare(lua_CFunction trampoline, int index1, int index2)
{
// if one of the indexes is invalid, return false
if(isnone(index1) || isnone(index2))
return false;
// convert relative indexes into absolute
index1 = absindex(index1);
index2 = absindex(index2);
checkstack(3);
lua_pushcfunction(cobj.get(), trampoline);
pushvalue(index1);
pushvalue(index2);
call(2, 1, 0);
assert(isnumber(-1));
int r = tointeger(-1);
pop();
return r;
}
void state::setfield(int index, const char *k)
{
checkstack(1);
index = absindex(index);
pushstring(k);
insert(-2);
settable(index);
}
void state::settable(int index)
{
checkstack(2);
pushvalue(index);
insert(-3);
lua_pushcfunction(cobj.get(), (&safe_misc_trampoline<&lua_settable, 0>));
insert(-4);
call(3, 0, 0);
}
std::string state::tostring(int index) throw(lua::not_string_error)
{
size_t len;
const char *str = lua_tolstring(cobj.get(), index, &len);
if(not str)
throw not_string_error();
return std::string(str, len);
}
}
|