robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
210ec3b7a9
master
1/* 2* This module exports three classes, and each instance of those classes has its 3* own private registry for temporary reference storage(keeping state between 4* calls). A private registry makes managing memory much easier since all we 5* have to do is call luaL_unref passing the registry reference when the 6* instance is collected by the __gc metamethod. 7* 8* This private registry is manipulated with `lmpack_ref` / `lmpack_unref` / 9* `lmpack_geti`, which are analogous to `luaL_ref` / `luaL_unref` / 10* `lua_rawgeti` but operate on the private registry passed as argument. 11* 12* In order to simplify debug registry leaks during normal operation(with the 13* leak_test.lua script), these `lmpack_*` registry functions will target the 14* normal lua registry when MPACK_DEBUG_REGISTRY_LEAK is defined during 15* compilation. 16*/ 17#define LUA_LIB 18#include <limits.h> 19#include <stdlib.h> 20#include <string.h> 21#include <stdio.h> 22 23#include <lauxlib.h> 24#include <lua.h> 25#include <luaconf.h> 26 27#include "nvim/macros_defs.h" 28 29#include "lmpack.h" 30 31#include "rpc.h" 32 33#define UNPACKER_META_NAME "mpack.Unpacker" 34#define UNPACK_FN_NAME "decode" 35#define PACKER_META_NAME "mpack.Packer" 36#define PACK_FN_NAME "encode" 37#define SESSION_META_NAME "mpack.Session" 38#define NIL_NAME "mpack.NIL" 39#define EMPTY_DICT_NAME "mpack.empty_dict" 40 41/* 42* TODO(tarruda): When targeting lua 5.3 and being compiled with `long long` 43* support(not -ansi), we should make use of lua 64 bit integers for 44* representing msgpack integers, since `double` can't represent the full range. 45*/ 46 47#ifndef luaL_reg 48/* Taken from Lua5.1's lauxlib.h */ 49#define luaL_reg luaL_Reg 50#endif 51 52#if LUA_VERSION_NUM > 501 53#ifndef luaL_register 54#define luaL_register (L ,n ,f ) luaL_setfuncs(L,f,0) 55#endif 56#endif 57 58typedef struct { 59lua_State * L ; 60mpack_parser_t * parser ; 61int reg ,ext ,unpacking ,mtdict ; 62char * string_buffer ; 63}Unpacker ; 64 65typedef struct { 66lua_State * L ; 67mpack_parser_t * parser ; 68int reg ,ext ,root ,packing ,mtdict ; 69int is_bin ,is_bin_fn ; 70}Packer ; 71 72typedef struct { 73lua_State * L ; 74int reg ; 75mpack_rpc_session_t * session ; 76struct { 77int type ; 78mpack_rpc_message_t msg ; 79int method_or_error ; 80int args_or_result ; 81 }unpacked ; 82int unpacker ; 83}Session ; 84 85static int lmpack_ref (lua_State * L ,int reg ) 86{ 87#ifdef MPACK_DEBUG_REGISTRY_LEAK 88return luaL_ref (L ,LUA_REGISTRYINDEX ); 89#else 90int rv ; 91lua_rawgeti (L ,LUA_REGISTRYINDEX ,reg ); 92lua_pushvalue (L ,-2 ); 93rv = luaL_ref (L ,-2 ); 94lua_pop (L ,2 ); 95return rv ; 96#endif 97} 98 99static void lmpack_unref (lua_State * L ,int reg ,int ref ) 100{ 101#ifdef MPACK_DEBUG_REGISTRY_LEAK 102luaL_unref (L ,LUA_REGISTRYINDEX ,ref ); 103#else 104lua_rawgeti (L ,LUA_REGISTRYINDEX ,reg ); 105luaL_unref (L ,-1 ,ref ); 106lua_pop (L ,1 ); 107#endif 108} 109 110static void lmpack_geti (lua_State * L ,int reg ,int ref ) 111{ 112#ifdef MPACK_DEBUG_REGISTRY_LEAK 113lua_rawgeti (L ,LUA_REGISTRYINDEX ,ref ); 114#else 115lua_rawgeti (L ,LUA_REGISTRYINDEX ,reg ); 116lua_rawgeti (L ,-1 ,ref ); 117lua_replace (L ,-2 ); 118#endif 119} 120 121/* make a shallow copy of the table on stack and remove it after the copy is 122* done */ 123static void lmpack_shallow_copy (lua_State * L ) 124{ 125lua_newtable (L ); 126lua_pushnil (L ); 127while (lua_next (L ,-3 )) { 128lua_pushvalue (L ,-2 ); 129lua_insert (L ,-2 ); 130lua_settable (L ,-4 ); 131 } 132lua_remove (L ,-2 ); 133} 134 135static mpack_parser_t * lmpack_grow_parser (mpack_parser_t * parser ) 136{ 137mpack_parser_t * old = parser ; 138mpack_uint32_t new_capacity = old -> capacity * 2 ; 139parser = malloc (MPACK_PARSER_STRUCT_SIZE (new_capacity )); 140if (!parser ) gotoend ; 141mpack_parser_init (parser ,new_capacity ); 142mpack_parser_copy (parser ,old ); 143free (old ); 144end : 145return parser ; 146} 147 148static mpack_rpc_session_t * lmpack_grow_session (mpack_rpc_session_t * session ) 149{ 150mpack_rpc_session_t * old = session ; 151mpack_uint32_t new_capacity = old -> capacity * 2 ; 152session = malloc (MPACK_RPC_SESSION_STRUCT_SIZE (new_capacity )); 153if (!session ) gotoend ; 154mpack_rpc_session_init (session ,new_capacity ); 155mpack_rpc_session_copy (session ,old ); 156free (old ); 157end : 158return session ; 159} 160 161static Unpacker * lmpack_check_unpacker (lua_State * L ,int index ) 162{ 163return luaL_checkudata (L ,index ,UNPACKER_META_NAME ); 164} 165 166static Packer * lmpack_check_packer (lua_State * L ,int index ) 167{ 168return luaL_checkudata (L ,index ,PACKER_META_NAME ); 169} 170 171static Session * lmpack_check_session (lua_State * L ,int index ) 172{ 173return luaL_checkudata (L ,index ,SESSION_META_NAME ); 174} 175 176static int lmpack_isnil (lua_State * L ,int index ) 177{ 178int rv ; 179if (!lua_isuserdata (L ,index ))return 0 ; 180lua_getfield (L ,LUA_REGISTRYINDEX ,NIL_NAME ); 181rv = lua_rawequal (L ,-1 ,-2 ); 182lua_pop (L ,1 ); 183return rv ; 184} 185 186static int lmpack_isunpacker (lua_State * L ,int index ) 187{ 188int rv ; 189if (!lua_isuserdata (L ,index )|| !lua_getmetatable (L ,index ))return 0 ; 190luaL_getmetatable (L ,UNPACKER_META_NAME ); 191rv = lua_rawequal (L ,-1 ,-2 ); 192lua_pop (L ,2 ); 193return rv ; 194} 195 196static void lmpack_pushnil (lua_State * L ) 197{ 198lua_getfield (L ,LUA_REGISTRYINDEX ,NIL_NAME ); 199} 200 201/* adapted from 202* https://github.com/antirez/lua-cmsgpack/blob/master/lua_cmsgpack.c */ 203static mpack_uint32_t lmpack_objlen (lua_State * L ,int * is_array ) 204{ 205size_t len ,max ; 206int isarr ; 207lua_Number n ; 208#ifndef NDEBUG 209int top = lua_gettop (L ); 210assert (top ); 211#endif 212 213if ((lua_type (L ,-1 ))!= LUA_TTABLE ) { 214#if LUA_VERSION_NUM >=502 215len = lua_rawlen (L ,-1 ); 216#elif LUA_VERSION_NUM == 501 217len = lua_objlen (L ,-1 ); 218#else 219#error You have either broken or too old Lua installation. This library requires Lua>=5.1 220#endif 221 gotoend ; 222 } 223 224/* count the number of keys and determine if it is an array */ 225len = 0 ; 226max = 0 ; 227isarr = 1 ; 228lua_pushnil (L ); 229 230while (lua_next (L ,-2 )) { 231lua_pop (L ,1 );/* pop value */ 232isarr = isarr 233&& lua_type (L ,-1 )== LUA_TNUMBER /* lua number */ 234&& (n = lua_tonumber (L ,-1 ))> 0 /* greater than 0 */ 235&& (size_t )n == n ;/* and integer */ 236max = isarr && (size_t )n > max ? (size_t )n :max ; 237len ++ ; 238 } 239 240// when len==0, the caller should guess the type! 241if (len > 0 ) { 242* is_array = isarr && max == len ; 243 } 244 245end : 246if ((size_t )-1 > (mpack_uint32_t )- 1 && len > (mpack_uint32_t )- 1 ) 247/* msgpack spec doesn't allow lengths > 32 bits */ 248len = (mpack_uint32_t )- 1 ; 249assert (top == lua_gettop (L )); 250return (mpack_uint32_t )len ; 251} 252 253static int lmpack_unpacker_new (lua_State * L ) 254{ 255Unpacker * rv ; 256 257if (lua_gettop (L )> 1 ) 258return luaL_error (L ,"expecting at most 1 table argument" ); 259 260rv = lua_newuserdata (L ,sizeof (* rv )); 261rv -> parser = malloc (sizeof (* rv -> parser )); 262if (!rv -> parser )return luaL_error (L ,"Failed to allocate memory" ); 263mpack_parser_init (rv -> parser ,0 ); 264rv -> parser -> data .p = rv ; 265rv -> string_buffer = NULL ; 266rv -> L = L ; 267rv -> unpacking = 0 ; 268luaL_getmetatable (L ,UNPACKER_META_NAME ); 269lua_setmetatable (L ,-2 ); 270 271#ifndef MPACK_DEBUG_REGISTRY_LEAK 272lua_newtable (L ); 273rv -> reg = luaL_ref (L ,LUA_REGISTRYINDEX ); 274#endif 275rv -> ext = LUA_NOREF ; 276 277lua_getfield (L ,LUA_REGISTRYINDEX ,EMPTY_DICT_NAME ); 278rv -> mtdict = lmpack_ref (L ,rv -> reg ); 279 280if (lua_istable (L ,1 )) { 281/* parse options */ 282lua_getfield (L ,1 ,"ext" ); 283if (!lua_isnil (L ,-1 )) { 284if (!lua_istable (L ,-1 )) 285return luaL_error (L ,"\"ext\" option must be a table" ); 286lmpack_shallow_copy (L ); 287 } 288rv -> ext = lmpack_ref (L ,rv -> reg ); 289 } 290 291return 1 ; 292} 293 294static int lmpack_unpacker_delete (lua_State * L ) 295{ 296Unpacker * unpacker = lmpack_check_unpacker (L ,1 ); 297if (unpacker -> ext != LUA_NOREF ) 298lmpack_unref (L ,unpacker -> reg ,unpacker -> ext ); 299#ifndef MPACK_DEBUG_REGISTRY_LEAK 300luaL_unref (L ,LUA_REGISTRYINDEX ,unpacker -> reg ); 301#endif 302free (unpacker -> parser ); 303return 0 ; 304} 305 306static void lmpack_parse_enter (mpack_parser_t * parser ,mpack_node_t * node ) 307{ 308Unpacker * unpacker = parser -> data .p ; 309lua_State * L = unpacker -> L ; 310 311switch (node -> tok .type ) { 312case MPACK_TOKEN_NIL : 313lmpack_pushnil (L );break ; 314case MPACK_TOKEN_BOOLEAN : 315lua_pushboolean (L , (int )mpack_unpack_boolean (node -> tok ));break ; 316case MPACK_TOKEN_UINT : 317case MPACK_TOKEN_SINT : 318case MPACK_TOKEN_FLOAT : 319lua_pushnumber (L ,mpack_unpack_number (node -> tok ));break ; 320case MPACK_TOKEN_CHUNK : 321assert (unpacker -> string_buffer ); 322memcpy (unpacker -> string_buffer + MPACK_PARENT_NODE (node )-> pos , 323node -> tok .data .chunk_ptr ,node -> tok .length ); 324break ; 325case MPACK_TOKEN_BIN : 326case MPACK_TOKEN_STR : 327case MPACK_TOKEN_EXT : 328unpacker -> string_buffer = malloc (node -> tok .length ); 329if (!unpacker -> string_buffer )luaL_error (L ,"Failed to allocate memory" ); 330break ; 331case MPACK_TOKEN_ARRAY : 332case MPACK_TOKEN_MAP : 333lua_newtable (L ); 334node -> data [0 ].i = lmpack_ref (L ,unpacker -> reg ); 335break ; 336 } 337} 338 339static void lmpack_parse_exit (mpack_parser_t * parser ,mpack_node_t * node ) 340{ 341Unpacker * unpacker = parser -> data .p ; 342lua_State * L = unpacker -> L ; 343mpack_node_t * parent = MPACK_PARENT_NODE (node ); 344 345switch (node -> tok .type ) { 346case MPACK_TOKEN_BIN : 347case MPACK_TOKEN_STR : 348case MPACK_TOKEN_EXT : 349lua_pushlstring (L ,unpacker -> string_buffer ,node -> tok .length ); 350free (unpacker -> string_buffer ); 351unpacker -> string_buffer = NULL ; 352if (node -> tok .type == MPACK_TOKEN_EXT && unpacker -> ext != LUA_NOREF ) { 353/* check if there's a handler for this type */ 354lmpack_geti (L ,unpacker -> reg ,unpacker -> ext ); 355lua_rawgeti (L ,-1 ,node -> tok .data .ext_type ); 356if (lua_isfunction (L ,-1 )) { 357/* stack: 358* 359* -1: ext unpacker function 360* -2: ext unpackers table 361* -3: ext string 362* 363* We want to call the ext unpacker function with the type and string 364* as arguments, so push those now 365*/ 366lua_pushinteger (L ,node -> tok .data .ext_type ); 367lua_pushvalue (L ,-4 ); 368lua_call (L ,2 ,1 ); 369/* stack: 370* 371* -1: returned object 372* -2: ext unpackers table 373* -3: ext string 374*/ 375lua_replace (L ,-3 ); 376 }else { 377/* the last lua_rawgeti should have pushed nil on the stack, 378* remove it */ 379lua_pop (L ,1 ); 380 } 381/* pop the ext unpackers table */ 382lua_pop (L ,1 ); 383 } 384break ; 385case MPACK_TOKEN_ARRAY : 386case MPACK_TOKEN_MAP : 387lmpack_geti (L ,unpacker -> reg , (int )node -> data [0 ].i ); 388lmpack_unref (L ,unpacker -> reg , (int )node -> data [0 ].i ); 389if (node -> key_visited == 0 && node -> tok .type == MPACK_TOKEN_MAP ) { 390lmpack_geti (L ,unpacker -> reg ,unpacker -> mtdict );// [table, mtdict] 391lua_setmetatable (L ,-2 );// [table] 392 } 393 394break ; 395default : 396break ; 397 } 398 399if (parent && parent -> tok .type < MPACK_TOKEN_BIN ) { 400/* At this point the parsed object is on the stack. Add it to the parent 401* container. First put the container on the stack. */ 402lmpack_geti (L ,unpacker -> reg , (int )parent -> data [0 ].i ); 403 404if (parent -> tok .type == MPACK_TOKEN_ARRAY ) { 405/* Array, save the value on key equal to `parent->pos` */ 406lua_pushnumber (L , (lua_Number )parent -> pos ); 407lua_pushvalue (L ,-3 ); 408lua_settable (L ,-3 ); 409 }else { 410assert (parent -> tok .type == MPACK_TOKEN_MAP ); 411if (parent -> key_visited ) { 412/* save the key on the registry */ 413lua_pushvalue (L ,-2 ); 414parent -> data [1 ].i = lmpack_ref (L ,unpacker -> reg ); 415 }else { 416/* set the key/value pair */ 417lmpack_geti (L ,unpacker -> reg , (int )parent -> data [1 ].i ); 418lmpack_unref (L ,unpacker -> reg , (int )parent -> data [1 ].i ); 419lua_pushvalue (L ,-3 ); 420lua_settable (L ,-3 ); 421 } 422 } 423lua_pop (L ,2 );/* pop the container/object */ 424 } 425} 426 427static int lmpack_unpacker_unpack_str (lua_State * L ,Unpacker * unpacker , 428const char ** str ,size_t * len ) 429{ 430int rv ; 431 432if (unpacker -> unpacking ) { 433return luaL_error (L ,"Unpacker instance already working. Use another " 434"Unpacker or mpack." UNPACK_FN_NAME "() if you " 435"need to " UNPACK_FN_NAME " from the ext handler" ); 436 } 437 438do { 439unpacker -> unpacking = 1 ; 440rv = mpack_parse (unpacker -> parser ,str ,len ,lmpack_parse_enter , 441lmpack_parse_exit ); 442unpacker -> unpacking = 0 ; 443 444if (rv == MPACK_NOMEM ) { 445unpacker -> parser = lmpack_grow_parser (unpacker -> parser ); 446if (!unpacker -> parser ) { 447return luaL_error (L ,"failed to grow Unpacker capacity" ); 448 } 449 } 450 }while (rv == MPACK_NOMEM ); 451 452if (rv == MPACK_ERROR ) 453return luaL_error (L ,"invalid msgpack string" ); 454 455return rv ; 456} 457 458static int lmpack_unpacker_unpack (lua_State * L ) 459{ 460int result ,argc ; 461lua_Number startpos ; 462size_t len ,offset ; 463const char * str ,* str_init ; 464Unpacker * unpacker ; 465 466if ((argc = lua_gettop (L ))> 3 || argc < 2 ) 467return luaL_error (L ,"expecting between 2 and 3 arguments" ); 468 469unpacker = lmpack_check_unpacker (L ,1 ); 470unpacker -> L = L ; 471 472str_init = str = luaL_checklstring (L ,2 ,& len ); 473startpos = lua_gettop (L )== 3 ?luaL_checknumber (L ,3 ) :1 ; 474 475luaL_argcheck (L ,startpos > 0 ,3 , 476"start position must be greater than zero" ); 477luaL_argcheck (L , (size_t )startpos == startpos ,3 , 478"start position must be an integer" ); 479luaL_argcheck (L , (size_t )startpos <=len ,3 , 480"start position must be less than or equal to the input string length" ); 481 482offset = (size_t )startpos - 1 ; 483str += offset ; 484len -= offset ; 485result = lmpack_unpacker_unpack_str (L ,unpacker ,& str ,& len ); 486 487if (result == MPACK_EOF ) 488/* if we hit EOF, return nil as the object */ 489lua_pushnil (L ); 490 491/* also return the new position in the input string */ 492lua_pushinteger (L ,str - str_init + 1 ); 493assert (lua_gettop (L )== argc + 2 ); 494return 2 ; 495} 496 497static int lmpack_packer_new (lua_State * L ) 498{ 499Packer * rv ; 500 501if (lua_gettop (L )> 1 ) 502return luaL_error (L ,"expecting at most 1 table argument" ); 503 504rv = lua_newuserdata (L ,sizeof (* rv )); 505rv -> parser = malloc (sizeof (* rv -> parser )); 506if (!rv -> parser )return luaL_error (L ,"failed to allocate parser memory" ); 507mpack_parser_init (rv -> parser ,0 ); 508rv -> parser -> data .p = rv ; 509rv -> L = L ; 510rv -> packing = 0 ; 511rv -> is_bin = 0 ; 512rv -> is_bin_fn = LUA_NOREF ; 513luaL_getmetatable (L ,PACKER_META_NAME ); 514lua_setmetatable (L ,-2 ); 515 516#ifndef MPACK_DEBUG_REGISTRY_LEAK 517lua_newtable (L ); 518rv -> reg = luaL_ref (L ,LUA_REGISTRYINDEX ); 519#endif 520rv -> ext = LUA_NOREF ; 521 522lua_getfield (L ,LUA_REGISTRYINDEX ,EMPTY_DICT_NAME ); 523rv -> mtdict = lmpack_ref (L ,rv -> reg ); 524 525if (lua_istable (L ,1 )) { 526/* parse options */ 527lua_getfield (L ,1 ,"ext" ); 528if (!lua_isnil (L ,-1 )) { 529if (!lua_istable (L ,-1 )) 530return luaL_error (L ,"\"ext\" option must be a table" ); 531lmpack_shallow_copy (L ); 532 } 533rv -> ext = lmpack_ref (L ,rv -> reg ); 534lua_getfield (L ,1 ,"is_bin" ); 535if (!lua_isnil (L ,-1 )) { 536if (!lua_isboolean (L ,-1 )&& !lua_isfunction (L ,-1 )) 537return luaL_error (L , 538"\"is_bin\" option must be a boolean or function" ); 539rv -> is_bin = lua_toboolean (L ,-1 ); 540if (lua_isfunction (L ,-1 ))rv -> is_bin_fn = lmpack_ref (L ,rv -> reg ); 541else lua_pop (L ,1 ); 542 }else { 543lua_pop (L ,1 ); 544 } 545 546 } 547 548return 1 ; 549} 550 551static int lmpack_packer_delete (lua_State * L ) 552{ 553Packer * packer = lmpack_check_packer (L ,1 ); 554if (packer -> ext != LUA_NOREF ) 555lmpack_unref (L ,packer -> reg ,packer -> ext ); 556#ifndef MPACK_DEBUG_REGISTRY_LEAK 557luaL_unref (L ,LUA_REGISTRYINDEX ,packer -> reg ); 558#endif 559free (packer -> parser ); 560return 0 ; 561} 562 563static void lmpack_unparse_enter (mpack_parser_t * parser ,mpack_node_t * node ) 564{ 565int type ; 566Packer * packer = parser -> data .p ; 567lua_State * L = packer -> L ; 568mpack_node_t * parent = MPACK_PARENT_NODE (node ); 569 570if (parent ) { 571/* get the parent */ 572lmpack_geti (L ,packer -> reg , (int )parent -> data [0 ].i ); 573 574if (parent -> tok .type > MPACK_TOKEN_MAP ) { 575/* strings are a special case, they are packed as single child chunk 576* node */ 577const char * str = lua_tolstring (L ,-1 ,NULL ); 578node -> tok = mpack_pack_chunk (str ,parent -> tok .length ); 579lua_pop (L ,1 ); 580return ; 581 } 582 583if (parent -> tok .type == MPACK_TOKEN_ARRAY ) { 584/* push the next index */ 585lua_pushnumber (L , (lua_Number )(parent -> pos + 1 )); 586/* push the element */ 587lua_gettable (L ,-2 ); 588 }else if (parent -> tok .type == MPACK_TOKEN_MAP ) { 589int result ; 590/* push the previous key */ 591lmpack_geti (L ,packer -> reg , (int )parent -> data [1 ].i ); 592/* push the pair */ 593result = lua_next (L ,-2 ); 594assert (result );/* should not be here if the map was fully processed */ 595 (void )result ;/* ignore unused warning */ 596if (parent -> key_visited ) { 597/* release the current key */ 598lmpack_unref (L ,packer -> reg , (int )parent -> data [1 ].i ); 599/* push key to the top */ 600lua_pushvalue (L ,-2 ); 601/* set the key for the next iteration, leaving value on top */ 602parent -> data [1 ].i = lmpack_ref (L ,packer -> reg ); 603/* replace key by the value */ 604lua_replace (L ,-2 ); 605 }else { 606/* pop value */ 607lua_pop (L ,1 ); 608 } 609 } 610/* remove parent, leaving only the object which will be serialized */ 611lua_remove (L ,-2 ); 612 }else { 613/* root object */ 614lmpack_geti (L ,packer -> reg ,packer -> root ); 615 } 616 617type = lua_type (L ,-1 ); 618 619switch (type ) { 620case LUA_TBOOLEAN : 621node -> tok = mpack_pack_boolean ((unsigned )lua_toboolean (L ,-1 )); 622break ; 623case LUA_TNUMBER : 624node -> tok = mpack_pack_number (lua_tonumber (L ,-1 )); 625break ; 626case LUA_TSTRING : { 627int is_bin = packer -> is_bin ; 628if (is_bin && packer -> is_bin_fn != LUA_NOREF ) { 629lmpack_geti (L ,packer -> reg ,packer -> is_bin_fn ); 630lua_pushvalue (L ,-2 ); 631lua_call (L ,1 ,1 ); 632is_bin = lua_toboolean (L ,-1 ); 633lua_pop (L ,1 ); 634 } 635if (is_bin )node -> tok = mpack_pack_bin (lmpack_objlen (L ,NULL )); 636else node -> tok = mpack_pack_str (lmpack_objlen (L ,NULL )); 637break ; 638 } 639case LUA_TTABLE : { 640mpack_uint32_t len ; 641mpack_node_t * n ; 642 643int has_meta = lua_getmetatable (L ,-1 ); 644int has_mtdict = false; 645if (has_meta && packer -> mtdict != LUA_NOREF ) { 646lmpack_geti (L ,packer -> reg ,packer -> mtdict );// [table, metatable, mtdict] 647has_mtdict = lua_rawequal (L ,-1 ,-2 ); 648lua_pop (L ,1 );// [table, metatable]; 649 } 650if (packer -> ext != LUA_NOREF && has_meta && !has_mtdict ) { 651/* check if there's a handler for this metatable */ 652lmpack_geti (L ,packer -> reg ,packer -> ext ); 653lua_pushvalue (L ,-2 ); 654lua_gettable (L ,-2 ); 655if (lua_isfunction (L ,-1 )) { 656lua_Number ext = -1 ; 657/* stack: 658* 659* -1: ext packer function 660* -2: ext packers table 661* -3: metatable 662* -4: original object 663* 664* We want to call the ext packer function with the original object as 665* argument, so push it on the top 666*/ 667lua_pushvalue (L ,-4 ); 668/* handler should return type code and string */ 669lua_call (L ,1 ,2 ); 670if (!lua_isnumber (L ,-2 )|| (ext = lua_tonumber (L ,-2 ))< 0 671|| ext > 127 || (int )ext != ext ) 672luaL_error (L , 673"the first result from ext packer must be an integer " 674"between 0 and 127" ); 675if (!lua_isstring (L ,-1 )) 676luaL_error (L , 677"the second result from ext packer must be a string" ); 678node -> tok = mpack_pack_ext ((int )ext ,lmpack_objlen (L ,NULL )); 679/* stack: 680* 681* -1: ext string 682* -2: ext type 683* -3: ext packers table 684* -4: metatable 685* -5: original table 686* 687* We want to leave only the returned ext string, so 688* replace -5 with the string and pop 3 689*/ 690lua_replace (L ,-5 ); 691lua_pop (L ,3 ); 692break ;/* done */ 693 }else { 694/* stack: 695* 696* -1: ext packers table 697* -2: metatable 698* -3: original table 699* 700* We want to leave only the original table and metatable since they 701* will be handled below, so pop 1 702*/ 703lua_pop (L ,1 ); 704 } 705 } 706 707if (has_meta ) { 708lua_pop (L ,1 );// [table] 709 } 710 711/* check for cycles */ 712n = node ; 713while ((n = MPACK_PARENT_NODE (n ))) { 714lmpack_geti (L ,packer -> reg , (int )n -> data [0 ].i ); 715if (lua_rawequal (L ,-1 ,-2 )) { 716/* break out of cycles with NIL */ 717node -> tok = mpack_pack_nil (); 718lua_pop (L ,2 ); 719lmpack_pushnil (L ); 720 gotoend ; 721 } 722lua_pop (L ,1 ); 723 } 724 725int is_array = !has_mtdict ; 726len = lmpack_objlen (L ,& is_array ); 727if (is_array ) { 728node -> tok = mpack_pack_array (len ); 729 }else { 730node -> tok = mpack_pack_map (len ); 731/* save nil as the previous key to start iteration */ 732node -> data [1 ].i = LUA_REFNIL ; 733 } 734break ; 735 } 736case LUA_TUSERDATA : 737if (lmpack_isnil (L ,-1 )) { 738node -> tok = mpack_pack_nil (); 739break ; 740 } 741FALLTHROUGH ; 742default : 743 { 744/* #define FMT */ 745char errmsg [50 ]; 746snprintf (errmsg ,50 ,"can't serialize object of type %d" ,type ); 747luaL_error (L ,errmsg ); 748 } 749 } 750 751end : 752node -> data [0 ].i = lmpack_ref (L ,packer -> reg ); 753} 754 755static void lmpack_unparse_exit (mpack_parser_t * parser ,mpack_node_t * node ) 756{ 757Packer * packer = parser -> data .p ; 758lua_State * L = packer -> L ; 759if (node -> tok .type != MPACK_TOKEN_CHUNK ) { 760/* release the object */ 761lmpack_unref (L ,packer -> reg , (int )node -> data [0 ].i ); 762if (node -> tok .type == MPACK_TOKEN_MAP ) 763lmpack_unref (L ,packer -> reg , (int )node -> data [1 ].i ); 764 } 765} 766 767static int lmpack_packer_pack (lua_State * L ) 768{ 769char * b ; 770size_t bl ; 771int result ,argc ; 772Packer * packer ; 773luaL_Buffer buffer ; 774 775if ((argc = lua_gettop (L ))!= 2 ) 776return luaL_error (L ,"expecting exactly 2 arguments" ); 777 778packer = lmpack_check_packer (L ,1 ); 779packer -> L = L ; 780packer -> root = lmpack_ref (L ,packer -> reg ); 781luaL_buffinit (L ,& buffer ); 782b = luaL_prepbuffer (& buffer ); 783bl = LUAL_BUFFERSIZE ; 784 785if (packer -> packing ) { 786return luaL_error (L ,"Packer instance already working. Use another Packer " 787"or mpack." PACK_FN_NAME "() if you need to " 788PACK_FN_NAME " from the ext handler" ); 789 } 790 791do { 792size_t bl_init = bl ; 793packer -> packing = 1 ; 794result = mpack_unparse (packer -> parser ,& b ,& bl ,lmpack_unparse_enter , 795lmpack_unparse_exit ); 796packer -> packing = 0 ; 797 798if (result == MPACK_NOMEM ) { 799packer -> parser = lmpack_grow_parser (packer -> parser ); 800if (!packer -> parser ) { 801return luaL_error (L ,"Failed to grow Packer capacity" ); 802 } 803 } 804 805luaL_addsize (& buffer ,bl_init - bl ); 806 807if (!bl ) { 808/* buffer empty, resize */ 809b = luaL_prepbuffer (& buffer ); 810bl = LUAL_BUFFERSIZE ; 811 } 812 }while (result == MPACK_EOF || result == MPACK_NOMEM ); 813 814lmpack_unref (L ,packer -> reg ,packer -> root ); 815luaL_pushresult (& buffer ); 816assert (lua_gettop (L )== argc ); 817return 1 ; 818} 819 820static int lmpack_session_new (lua_State * L ) 821{ 822Session * rv = lua_newuserdata (L ,sizeof (* rv )); 823rv -> session = malloc (sizeof (* rv -> session )); 824if (!rv -> session )return luaL_error (L ,"Failed to allocate memory" ); 825mpack_rpc_session_init (rv -> session ,0 ); 826rv -> L = L ; 827luaL_getmetatable (L ,SESSION_META_NAME ); 828lua_setmetatable (L ,-2 ); 829#ifndef MPACK_DEBUG_REGISTRY_LEAK 830lua_newtable (L ); 831rv -> reg = luaL_ref (L ,LUA_REGISTRYINDEX ); 832#endif 833rv -> unpacker = LUA_REFNIL ; 834rv -> unpacked .args_or_result = LUA_NOREF ; 835rv -> unpacked .method_or_error = LUA_NOREF ; 836rv -> unpacked .type = MPACK_EOF ; 837 838if (lua_istable (L ,1 )) { 839/* parse options */ 840lua_getfield (L ,1 ,"unpack" ); 841if (!lmpack_isunpacker (L ,-1 )) { 842return luaL_error (L , 843"\"unpack\" option must be a " UNPACKER_META_NAME " instance" ); 844 } 845rv -> unpacker = lmpack_ref (L ,rv -> reg ); 846 } 847 848return 1 ; 849} 850 851static int lmpack_session_delete (lua_State * L ) 852{ 853Session * session = lmpack_check_session (L ,1 ); 854lmpack_unref (L ,session -> reg ,session -> unpacker ); 855#ifndef MPACK_DEBUG_REGISTRY_LEAK 856luaL_unref (L ,LUA_REGISTRYINDEX ,session -> reg ); 857#endif 858free (session -> session ); 859return 0 ; 860} 861 862static int lmpack_session_receive (lua_State * L ) 863{ 864int argc ,done ,rcount = 3 ; 865lua_Number startpos ; 866size_t len ; 867const char * str ,* str_init ; 868Session * session ; 869Unpacker * unpacker = NULL ; 870 871if ((argc = lua_gettop (L ))> 3 || argc < 2 ) 872return luaL_error (L ,"expecting between 2 and 3 arguments" ); 873 874session = lmpack_check_session (L ,1 ); 875str_init = str = luaL_checklstring (L ,2 ,& len ); 876startpos = lua_gettop (L )== 3 ?luaL_checknumber (L ,3 ) :1 ; 877 878luaL_argcheck (L ,startpos > 0 ,3 , 879"start position must be greater than zero" ); 880luaL_argcheck (L , (size_t )startpos == startpos ,3 , 881"start position must be an integer" ); 882luaL_argcheck (L , (size_t )startpos <=len ,3 , 883"start position must be less than or equal to the input string length" ); 884 885size_t offset = (size_t )startpos - 1 ; 886str += offset ; 887len -= offset ; 888 889if (session -> unpacker != LUA_REFNIL ) { 890lmpack_geti (L ,session -> reg ,session -> unpacker ); 891unpacker = lmpack_check_unpacker (L ,-1 ); 892unpacker -> L = L ; 893rcount += 2 ; 894lua_pop (L ,1 ); 895 } 896 897for (;;) { 898int result ; 899 900if (session -> unpacked .type == MPACK_EOF ) { 901session -> unpacked .type = 902mpack_rpc_receive (session -> session ,& str ,& len ,& session -> unpacked .msg ); 903 904if (!unpacker || session -> unpacked .type == MPACK_EOF ) 905break ; 906 } 907 908result = lmpack_unpacker_unpack_str (L ,unpacker ,& str ,& len ); 909 910if (result == MPACK_EOF )break ; 911 912if (session -> unpacked .method_or_error == LUA_NOREF ) { 913session -> unpacked .method_or_error = lmpack_ref (L ,session -> reg ); 914 }else { 915session -> unpacked .args_or_result = lmpack_ref (L ,session -> reg ); 916break ; 917 } 918 } 919 920done = session -> unpacked .type != MPACK_EOF 921&& (session -> unpacked .args_or_result != LUA_NOREF || !unpacker ); 922 923if (!done ) { 924lua_pushnil (L ); 925lua_pushnil (L ); 926if (unpacker ) { 927lua_pushnil (L ); 928lua_pushnil (L ); 929 } 930 gotoend ; 931 } 932 933switch (session -> unpacked .type ) { 934case MPACK_RPC_REQUEST : 935lua_pushstring (L ,"request" ); 936lua_pushnumber (L ,session -> unpacked .msg .id ); 937break ; 938case MPACK_RPC_RESPONSE : 939lua_pushstring (L ,"response" ); 940lmpack_geti (L ,session -> reg , (int )session -> unpacked .msg .data .i ); 941break ; 942case MPACK_RPC_NOTIFICATION : 943lua_pushstring (L ,"notification" ); 944lua_pushnil (L ); 945break ; 946default : 947/* In most cases the only sane thing to do when receiving invalid 948* msgpack-rpc is to close the connection, so handle all errors with 949* this generic message. Later may add more detailed information. */ 950return luaL_error (L ,"invalid msgpack-rpc string" ); 951 } 952 953session -> unpacked .type = MPACK_EOF ; 954 955if (unpacker ) { 956lmpack_geti (L ,session -> reg ,session -> unpacked .method_or_error ); 957lmpack_geti (L ,session -> reg ,session -> unpacked .args_or_result ); 958lmpack_unref (L ,session -> reg ,session -> unpacked .method_or_error ); 959lmpack_unref (L ,session -> reg ,session -> unpacked .args_or_result ); 960session -> unpacked .method_or_error = LUA_NOREF ; 961session -> unpacked .args_or_result = LUA_NOREF ; 962 } 963 964end : 965lua_pushinteger (L ,str - str_init + 1 ); 966return rcount ; 967} 968 969static int lmpack_session_request (lua_State * L ) 970{ 971int result ; 972char buf [16 ],* b = buf ; 973size_t bl = sizeof (buf ); 974Session * session ; 975mpack_data_t data ; 976 977if (lua_gettop (L )> 2 || lua_gettop (L )< 1 ) 978return luaL_error (L ,"expecting 1 or 2 arguments" ); 979 980session = lmpack_check_session (L ,1 ); 981data .i = lua_isnoneornil (L ,2 ) ?LUA_NOREF :lmpack_ref (L ,session -> reg ); 982do { 983result = mpack_rpc_request (session -> session ,& b ,& bl ,data ); 984if (result == MPACK_NOMEM ) { 985session -> session = lmpack_grow_session (session -> session ); 986if (!session -> session ) 987return luaL_error (L ,"Failed to grow Session capacity" ); 988 } 989 }while (result == MPACK_NOMEM ); 990 991assert (result == MPACK_OK ); 992lua_pushlstring (L ,buf ,sizeof (buf )- bl ); 993return 1 ; 994} 995 996static int lmpack_session_reply (lua_State * L ) 997{ 998int result ; 999char buf [16 ],* b = buf ; 1000size_t bl = sizeof (buf ); 1001Session * session ; 1002lua_Number id ; 1003 1004if (lua_gettop (L )!= 2 ) 1005return luaL_error (L ,"expecting exactly 2 arguments" ); 1006 1007session = lmpack_check_session (L ,1 ); 1008id = lua_tonumber (L ,2 ); 1009luaL_argcheck (L , ((size_t )id == id && id >=0 && id <=0xffffffff ),2 , 1010"invalid request id" ); 1011result = mpack_rpc_reply (session -> session ,& b ,& bl , (mpack_uint32_t )id ); 1012assert (result == MPACK_OK ); 1013 (void )result ;/* ignore unused warning */ 1014lua_pushlstring (L ,buf ,sizeof (buf )- bl ); 1015return 1 ; 1016} 1017 1018static int lmpack_session_notify (lua_State * L ) 1019{ 1020int result ; 1021char buf [16 ],* b = buf ; 1022size_t bl = sizeof (buf ); 1023Session * session ; 1024 1025if (lua_gettop (L )!= 1 ) 1026return luaL_error (L ,"expecting exactly 1 argument" ); 1027 1028session = lmpack_check_session (L ,1 ); 1029result = mpack_rpc_notify (session -> session ,& b ,& bl ); 1030assert (result == MPACK_OK ); 1031 (void )result ;/* ignore unused warning */ 1032lua_pushlstring (L ,buf ,sizeof (buf )- bl ); 1033return 1 ; 1034} 1035 1036static int lmpack_nil_tostring (lua_State * L ) 1037{ 1038lua_pushfstring (L ,NIL_NAME ,lua_topointer (L ,1 )); 1039return 1 ; 1040} 1041 1042static int lmpack_unpack (lua_State * L ) 1043{ 1044int result ; 1045size_t len ; 1046const char * str ; 1047Unpacker unpacker ; 1048mpack_parser_t parser ; 1049 1050if (lua_gettop (L )!= 1 ) 1051return luaL_error (L ,"expecting exactly 1 argument" ); 1052 1053str = luaL_checklstring (L ,1 ,& len ); 1054 1055/* initialize unpacker */ 1056lua_newtable (L ); 1057unpacker .reg = luaL_ref (L ,LUA_REGISTRYINDEX ); 1058unpacker .ext = LUA_NOREF ; 1059unpacker .parser = & parser ; 1060mpack_parser_init (unpacker .parser ,0 ); 1061unpacker .parser -> data .p = & unpacker ; 1062unpacker .string_buffer = NULL ; 1063unpacker .L = L ; 1064 1065lua_getfield (L ,LUA_REGISTRYINDEX ,EMPTY_DICT_NAME ); 1066unpacker .mtdict = lmpack_ref (L ,unpacker .reg ); 1067 1068result = mpack_parse (& parser ,& str ,& len ,lmpack_parse_enter , 1069lmpack_parse_exit ); 1070 1071luaL_unref (L ,LUA_REGISTRYINDEX ,unpacker .reg ); 1072 1073if (result == MPACK_NOMEM ) 1074return luaL_error (L ,"object was too deep to unpack" ); 1075else if (result == MPACK_EOF ) 1076return luaL_error (L ,"incomplete msgpack string" ); 1077else if (result == MPACK_ERROR ) 1078return luaL_error (L ,"invalid msgpack string" ); 1079else if (result == MPACK_OK && len ) 1080return luaL_error (L ,"trailing data in msgpack string" ); 1081 1082assert (result == MPACK_OK ); 1083return 1 ; 1084} 1085 1086static int lmpack_pack (lua_State * L ) 1087{ 1088char * b ; 1089size_t bl ; 1090int result ; 1091Packer packer ; 1092mpack_parser_t parser ; 1093luaL_Buffer buffer ; 1094 1095if (lua_gettop (L )!= 1 ) 1096return luaL_error (L ,"expecting exactly 1 argument" ); 1097 1098/* initialize packer */ 1099lua_newtable (L ); 1100packer .reg = luaL_ref (L ,LUA_REGISTRYINDEX ); 1101packer .ext = LUA_NOREF ; 1102packer .parser = & parser ; 1103mpack_parser_init (packer .parser ,0 ); 1104packer .parser -> data .p = & packer ; 1105packer .is_bin = 0 ; 1106packer .L = L ; 1107packer .root = lmpack_ref (L ,packer .reg ); 1108 1109lua_getfield (L ,LUA_REGISTRYINDEX ,EMPTY_DICT_NAME ); 1110packer .mtdict = lmpack_ref (L ,packer .reg ); 1111 1112 1113luaL_buffinit (L ,& buffer ); 1114b = luaL_prepbuffer (& buffer ); 1115bl = LUAL_BUFFERSIZE ; 1116 1117do { 1118size_t bl_init = bl ; 1119result = mpack_unparse (packer .parser ,& b ,& bl ,lmpack_unparse_enter , 1120lmpack_unparse_exit ); 1121 1122if (result == MPACK_NOMEM ) { 1123lmpack_unref (L ,packer .reg ,packer .root ); 1124luaL_unref (L ,LUA_REGISTRYINDEX ,packer .reg ); 1125return luaL_error (L ,"object was too deep to pack" ); 1126 } 1127 1128luaL_addsize (& buffer ,bl_init - bl ); 1129 1130if (!bl ) { 1131/* buffer empty, resize */ 1132b = luaL_prepbuffer (& buffer ); 1133bl = LUAL_BUFFERSIZE ; 1134 } 1135 }while (result == MPACK_EOF ); 1136 1137lmpack_unref (L ,packer .reg ,packer .root ); 1138luaL_unref (L ,LUA_REGISTRYINDEX ,packer .reg ); 1139luaL_pushresult (& buffer ); 1140return 1 ; 1141} 1142 1143static const luaL_reg unpacker_methods []= { 1144 {"__call" ,lmpack_unpacker_unpack }, 1145 {"__gc" ,lmpack_unpacker_delete }, 1146 {NULL ,NULL } 1147}; 1148 1149static const luaL_reg packer_methods []= { 1150 {"__call" ,lmpack_packer_pack }, 1151 {"__gc" ,lmpack_packer_delete }, 1152 {NULL ,NULL } 1153}; 1154 1155static const luaL_reg session_methods []= { 1156 {"receive" ,lmpack_session_receive }, 1157 {"request" ,lmpack_session_request }, 1158 {"reply" ,lmpack_session_reply }, 1159 {"notify" ,lmpack_session_notify }, 1160 {"__gc" ,lmpack_session_delete }, 1161 {NULL ,NULL } 1162}; 1163 1164static const luaL_reg mpack_functions []= { 1165 {"Unpacker" ,lmpack_unpacker_new }, 1166 {"Packer" ,lmpack_packer_new }, 1167 {"Session" ,lmpack_session_new }, 1168 {UNPACK_FN_NAME ,lmpack_unpack }, 1169 {PACK_FN_NAME ,lmpack_pack }, 1170 {NULL ,NULL } 1171}; 1172 1173int luaopen_mpack (lua_State * L ) 1174{ 1175/* Unpacker */ 1176luaL_newmetatable (L ,UNPACKER_META_NAME ); 1177lua_pushvalue (L ,-1 ); 1178lua_setfield (L ,-2 ,"__index" ); 1179luaL_register (L ,NULL ,unpacker_methods ); 1180lua_pop (L ,1 ); 1181/* Packer */ 1182luaL_newmetatable (L ,PACKER_META_NAME ); 1183lua_pushvalue (L ,-1 ); 1184lua_setfield (L ,-2 ,"__index" ); 1185luaL_register (L ,NULL ,packer_methods ); 1186lua_pop (L ,1 ); 1187/* Session */ 1188luaL_newmetatable (L ,SESSION_META_NAME ); 1189lua_pushvalue (L ,-1 ); 1190lua_setfield (L ,-2 ,"__index" ); 1191luaL_register (L ,NULL ,session_methods ); 1192lua_pop (L ,1 ); 1193/* NIL */ 1194/* Check if NIL is already stored in the registry */ 1195lua_getfield (L ,LUA_REGISTRYINDEX ,NIL_NAME ); 1196/* If it isn't, create it */ 1197if (lua_isnil (L ,-1 )) { 1198/* Use a constant userdata to represent NIL */ 1199 (void )lua_newuserdata (L ,sizeof (void * )); 1200/* Create a metatable for NIL userdata */ 1201lua_createtable (L ,0 ,1 ); 1202lua_pushstring (L ,"__tostring" ); 1203lua_pushcfunction (L ,lmpack_nil_tostring ); 1204lua_settable (L ,-3 ); 1205/* Assign the metatable to the userdata object */ 1206lua_setmetatable (L ,-2 ); 1207/* Save NIL on the registry so we can access it easily from other functions */ 1208lua_setfield (L ,LUA_REGISTRYINDEX ,NIL_NAME ); 1209 } 1210 1211lua_pop (L ,1 ); 1212 1213/* module */ 1214lua_newtable (L ); 1215luaL_register (L ,NULL ,mpack_functions ); 1216/* save NIL on the module */ 1217lua_getfield (L ,LUA_REGISTRYINDEX ,NIL_NAME ); 1218lua_setfield (L ,-2 ,"NIL" ); 1219return 1 ; 1220}