whelk/whelk.c
author J. Ali Harlow <ali@juiblex.co.uk>
Thu Feb 21 18:53:57 2019 +0000 (2019-02-21)
changeset 21 285b05022b5a
parent 10 9ae1a7880142
permissions -rw-r--r--
Better error messages for spawn
     1 #include <stdlib.h>
     2 #include <string.h>
     3 #include <errno.h>
     4 #include <lua.h>
     5 #include <lualib.h>
     6 #include <lauxlib.h>
     7 #include "config.h"
     8 #include "_whelk.h"
     9 
    10 #ifdef __WIN32__
    11 int whelk_win32_error(lua_State *L,DWORD err)
    12 {
    13     DWORD n;
    14     WCHAR *buf;
    15     char *utf8;
    16     lua_pushnil(L);
    17     buf=NULL;
    18     n=FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER|\
    19       FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS,0,err,0,
    20       (LPWSTR)&buf,0,NULL);
    21     if (n)
    22     {
    23 	if (n>2 && buf[n-2]=='\r' && buf[n-1]=='\n')
    24 	    n-=2;
    25 	utf8=whelk_utf16_to_utf8(buf,n);
    26 	LocalFree(buf);
    27 	lua_pushstring(L,utf8);
    28 	free(utf8);
    29     }
    30     else
    31 	lua_pushstring(L,"Unknown error");
    32     lua_pushinteger(L,err);
    33     return 3;
    34 }
    35 #endif
    36 
    37 int whelk_perror(lua_State *L,const char *s)
    38 {
    39     lua_pushnil(L);
    40     if (s)
    41 	lua_pushfstring(L,"%s: %s",s,strerror(errno));
    42     else
    43 	lua_pushstring(L,strerror(errno));
    44     lua_pushinteger(L,errno);
    45     return 3;
    46 }
    47 
    48 static int whelk_unsupported(lua_State *L)
    49 {
    50     errno=ENOSYS;
    51     return whelk_perror(L,NULL);
    52 }
    53 
    54 #ifdef __WIN32__
    55 #define WIN32_ONLY(func)	func
    56 #else
    57 #define WIN32_ONLY(func)	whelk_unsupported
    58 #endif
    59 
    60 static const luaL_reg whelk_functions[]={
    61     { "GetFolderPath",WIN32_ONLY(whelk_get_folder_path) },
    62     { "CreateShortCut",WIN32_ONLY(whelk_create_short_cut) },
    63     { "Spawn",WIN32_ONLY(whelk_spawn) },
    64     { "CryptCATAdmin",WIN32_ONLY(whelk_crypt_cat_admin_new) },
    65     { "SetupCopyOEMInf",WIN32_ONLY(whelk_setup_copy_oem_inf) },
    66     { "SetupUninstallOEMInf",WIN32_ONLY(whelk_setup_uninstall_oem_inf) },
    67     { NULL }
    68 };
    69 
    70 LUALIB_API int luaopen_whelk(lua_State *L)
    71 {
    72     luaL_register(L,"whelk",whelk_functions);
    73     lua_pushliteral(L,"version");
    74     lua_pushliteral(L,PACKAGE_STRING);
    75     lua_settable(L,-3);
    76 #ifdef __WIN32__
    77     whelk_open_get_folder_path(L);
    78     whelk_open_reg_keys(L);
    79     whelk_open_setup(L);
    80 #endif
    81     return 1;
    82 }