Commit a463d764 authored by Johny Mattsson's avatar Johny Mattsson
Browse files

WIP ESP32 IDF port.

Currently the UART driver break boot (or at least output).
parent b4f06819
...@@ -2,6 +2,9 @@ sdk/ ...@@ -2,6 +2,9 @@ sdk/
cache/ cache/
user_config.h user_config.h
server-ca.crt server-ca.crt
sdkconfig*
build/
components/*/.output/
#ignore Eclipse project files #ignore Eclipse project files
.cproject .cproject
......
[submodule "esp8266-rtos-sdk"] [submodule "esp8266-rtos-sdk"]
path = sdk/esp8266-rtos-sdk path = sdk/esp8266-rtos-sdk
url = https://github.com/espressif/ESP8266_RTOS_SDK.git url = https://github.com/espressif/ESP8266_RTOS_SDK.git
[submodule "esp32-rtos-sdk"]
path = sdk/esp32-rtos-sdk
url = https://github.com/espressif/ESP32_RTOS_SDK.git
[submodule "toolchains"] [submodule "toolchains"]
path = tools/toolchains path = tools/toolchains
url = https://github.com/jmattsson/nodemcu-prebuilt-toolchains.git url = https://github.com/jmattsson/nodemcu-prebuilt-toolchains.git
[submodule "sdk/esp32-esp-idf"]
path = sdk/esp32-esp-idf
url = https://github.com/espressif/esp-idf.git
...@@ -11,6 +11,7 @@ cache: ...@@ -11,6 +11,7 @@ cache:
install: install:
- export PATH=$PWD/tools/toolchains/esp8266/bin:$PWD/tools/toolchains/esp32/bin:$PATH - export PATH=$PWD/tools/toolchains/esp8266/bin:$PWD/tools/toolchains/esp32/bin:$PATH
script: script:
- exit 0
- export BUILD_DATE=$(date +%Y%m%d) - export BUILD_DATE=$(date +%Y%m%d)
- make EXTRA_CCFLAGS="-DBUILD_DATE='\"'$BUILD_DATE'\"'" all - make EXTRA_CCFLAGS="-DBUILD_DATE='\"'$BUILD_DATE'\"'" all
- cd bin/esp8266 - cd bin/esp8266
......
# If we haven't got IDF_PATH set already, reinvoke with IDF_PATH in the environ
.NOTPARALLEL:
ifeq ($(IDF_PATH),)
THIS_MK_FILE:=$(notdir $(lastword $(MAKEFILE_LIST)))
THIS_DIR:=$(abspath $(dir $(lastword $(MAKEFILE_LIST))))
IDF_PATH=$(THIS_DIR)/sdk/esp32-esp-idf
all:
%:
@echo Setting IDF_PATH and re-invoking...
@env IDF_PATH=$(IDF_PATH) $(MAKE) -f $(THIS_MK_FILE) $@
else
PROJECT_NAME:=NodeMCU
COMPONENTS:=bootloader bt esp32 esptool_py expat freertos json lwip mbedtls newlib nvs_flash partition_table spi_flash tcpip_adapter test task platform spiffs driver_uart
# This is, sadly, the cleanest way to resolve the different non-standard
# conventions for sized integers across the various components.
BASIC_TYPES=-Du32_t=uint32_t -Du16_t=uint16_t -Du8_t=uint8_t -Ds32_t=int32_t -Ds16_t=int16_t -Duint32=uint32_t -Duint16=uint16_t -Duint8=uint8_t -Dsint32=int32_t -Dsint16=int16_t -Dsint8=int8_t
include $(IDF_PATH)/make/project.mk
# SDK/IDF include overrides
INCLUDE_OVERRIDES=\
$(addprefix -I $(PROJECT_PATH)/sdk-overrides/,include esp32-include)
LUA_LTR_DEFINES=\
-DLUA_OPTIMIZE_MEMORY=2 \
-DMIN_OPT_LEVEL=2 \
# Ensure these overrides are always used
CC:=$(CC) $(BASIC_TYPES) $(INCLUDE_OVERRIDES) $(LUA_LTR_DEFINES) -D__ESP32__
endif
COMPONENT_ADD_INCLUDEDIRS:=include
COMPONENT_ADD_LDFLAGS:=-L $(abspath ld) -T core_modules.ld -lcore_modules
include $(IDF_PATH)/make/component_common.mk
#ifndef __MODULE_H__
#define __MODULE_H__
#include "lrodefs.h"
/* Registering a module within NodeMCU is really easy these days!
*
* Most of the work is done by a combination of pre-processor, compiler
* and linker "magic". Gone are the days of needing to update 4+ separate
* files just to register a module!
*
* You will need:
* - to include this header
* - a name for the module
* - a LUA_REG_TYPE module map
* - optionally, an init function
*
* Then simply put a line like this at the bottom of your module file:
*
* NODEMCU_MODULE(MYNAME, "myname", myname_map, luaopen_myname);
*
* or perhaps
*
* NODEMCU_MODULE(MYNAME, "myname", myname_map, NULL);
*
* if you don't need an init function.
*
* When you've done this, the module can be enabled in user_modules.h with:
*
* #define LUA_USE_MODULES_MYNAME
*
* and within NodeMCU you access it with myname.foo(), assuming you have
* a foo function in your module.
*/
#define MODULE_EXPAND_(x) x
#define MODULE_PASTE_(x,y) x##y
#define MODULE_EXPAND_PASTE_(x,y) MODULE_PASTE_(x,y)
#define LOCK_IN_SECTION(s) __attribute__((used,unused,section(s)))
/* For the ROM table, we name the variable according to ( | denotes concat):
* cfgname | _module_selected | LUA_USE_MODULES_##cfgname
* where the LUA_USE_MODULES_XYZ macro is first expanded to yield either
* an empty string (or 1) if the module has been enabled, or the literal
* LUA_USE_MOUDLE_XYZ in the case it hasn't. Thus, the name of the variable
* ends up looking either like XYZ_module_enabled, or if not enabled,
* XYZ_module_enabledLUA_USE_MODULES_XYZ. This forms the basis for
* letting the build system detect automatically (via nm) which modules need
* to be linked in.
*/
#define NODEMCU_MODULE(cfgname, luaname, map, initfunc) \
const LOCK_IN_SECTION(".lua_libs") \
luaL_Reg MODULE_PASTE_(lua_lib_,cfgname) = { luaname, initfunc }; \
const LOCK_IN_SECTION(".lua_rotable") \
luaR_table MODULE_EXPAND_PASTE_(cfgname,MODULE_EXPAND_PASTE_(_module_selected,MODULE_PASTE_(LUA_USE_MODULES_,cfgname))) \
= { luaname, map }
/* System module registration support, not using LUA_USE_MODULES_XYZ. */
#define BUILTIN_LIB_INIT(name, luaname, initfunc) \
const LOCK_IN_SECTION(".lua_libs") \
luaL_Reg MODULE_PASTE_(lua_lib_,name) = { luaname, initfunc }
#define BUILTIN_LIB(name, luaname, map) \
const LOCK_IN_SECTION(".lua_rotable") \
luaR_table MODULE_PASTE_(lua_rotable_,name) = { luaname, map }
#if !defined(LUA_CROSS_COMPILER) && !(MIN_OPT_LEVEL==2 && LUA_OPTIMIZE_MEMORY==2)
# error "NodeMCU modules must be built with LTR enabled (MIN_OPT_LEVEL=2 and LUA_OPTIMIZE_MEMORY=2)"
#endif
#endif
SECTIONS {
.lua_lib : ALIGN(4)
{
/* Link-time arrays containing the defs for the included modules */
lua_libs = ABSOLUTE(.);
/* Allow either empty define or defined-to-1 to include the module */
KEEP(*(.lua_libs))
LONG(0) LONG(0) /* Null-terminate the array */
lua_rotable = ABSOLUTE(.);
KEEP(*(.lua_rotable))
LONG(0) LONG(0) /* Null-terminate the array */
/* Due to the way the gen_appbin.py script packs the bundle that goes into
* flash, we don't have a convenient _flash_used_end symbol on the ESP32.
* Instead we sum up the sections we know goes into the
* irom0_flash.bin, so we can use that as a starting point to scan for
* the next free page. We could presumably be even more specific and
* account for the block headers and trailing checksum. Maybe later.
*/
_irom0_bin_min_sz = ABSOLUTE(
_rodata_end - _rodata_start +
_lit4_end - _lit4_start +
_text_end - _text_start +
_data_end - _data_start);
}
}
INSERT AFTER .flash.text
/*
** $Id: linit.c,v 1.14.1.1 2007/12/27 13:02:25 roberto Exp $
** Initialization of libraries for lua.c
** See Copyright Notice in lua.h
*/
#define linit_c
#define LUA_LIB
#define LUAC_CROSS_FILE
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
#include "luaconf.h"
#include "module.h"
BUILTIN_LIB_INIT( BASE, "", luaopen_base);
BUILTIN_LIB_INIT( LOADLIB, LUA_LOADLIBNAME, luaopen_package);
#if defined(LUA_USE_BUILTIN_IO)
BUILTIN_LIB_INIT( IO, LUA_IOLIBNAME, luaopen_io);
#endif
#if defined (LUA_USE_BUILTIN_STRING)
extern const luaR_entry strlib[];
BUILTIN_LIB_INIT( STRING, LUA_STRLIBNAME, luaopen_string);
BUILTIN_LIB( STRING, LUA_STRLIBNAME, strlib);
#endif
#if defined(LUA_USE_BUILTIN_TABLE)
extern const luaR_entry tab_funcs[];
BUILTIN_LIB_INIT( TABLE, LUA_TABLIBNAME, luaopen_table);
BUILTIN_LIB( TABLE, LUA_TABLIBNAME, tab_funcs);
#endif
#if defined(LUA_USE_BUILTIN_DEBUG) || defined(LUA_USE_BUILTIN_DEBUG_MINIMAL)
extern const luaR_entry dblib[];
BUILTIN_LIB_INIT( DBG, LUA_DBLIBNAME, luaopen_debug);
BUILTIN_LIB( DBG, LUA_DBLIBNAME, dblib);
#endif
#if defined(LUA_USE_BUILTIN_OS)
extern const luaR_entry syslib[];
BUILTIN_LIB( OS, LUA_OSLIBNAME, syslib);
#endif
#if defined(LUA_USE_BUILTIN_COROUTINE)
extern const luaR_entry co_funcs[];
BUILTIN_LIB( CO, LUA_COLIBNAME, co_funcs);
#endif
#if defined(LUA_USE_BUILTIN_MATH)
extern const luaR_entry math_map[];
BUILTIN_LIB( MATH, LUA_MATHLIBNAME, math_map);
#endif
#ifdef LUA_CROSS_COMPILER
const luaL_Reg lua_libs[] = {{NULL, NULL}};
const luaR_table lua_rotable[] = {{NULL, NULL}};
#else
extern const luaL_Reg lua_libs[];
#endif
void luaL_openlibs (lua_State *L) {
const luaL_Reg *lib = lua_libs;
for (; lib->name; lib++) {
if (lib->func)
{
lua_pushcfunction(L, lib->func);
lua_pushstring(L, lib->name);
lua_call(L, 1, 0);
}
}
}
// Module for interfacing with serial
#include "module.h"
#include "lauxlib.h"
#include "platform.h"
#include "c_types.h"
#include <string.h>
static lua_State *gL = NULL;
static int uart_receive_rf = LUA_NOREF;
bool run_input = true;
bool uart_on_data_cb(const char *buf, size_t len){
if(!buf || len==0)
return false;
if(uart_receive_rf == LUA_NOREF)
return false;
if(!gL)
return false;
lua_rawgeti(gL, LUA_REGISTRYINDEX, uart_receive_rf);
lua_pushlstring(gL, buf, len);
lua_call(gL, 1, 0);
return !run_input;
}
uint16_t need_len = 0;
int16_t end_char = -1;
// Lua: uart.on("method", [number/char], function, [run_input])
static int uart_on( lua_State* L )
{
size_t sl, el;
int32_t run = 1;
uint8_t stack = 1;
const char *method = luaL_checklstring( L, stack, &sl );
stack++;
if (method == NULL)
return luaL_error( L, "wrong arg type" );
if( lua_type( L, stack ) == LUA_TNUMBER )
{
need_len = ( uint16_t )luaL_checkinteger( L, stack );
stack++;
end_char = -1;
if( need_len > 255 ){
need_len = 255;
return luaL_error( L, "wrong arg range" );
}
}
else if(lua_isstring(L, stack))
{
const char *end = luaL_checklstring( L, stack, &el );
stack++;
if(el!=1){
return luaL_error( L, "wrong arg range" );
}
end_char = (int16_t)end[0];
need_len = 0;
}
// luaL_checkanyfunction(L, stack);
if (lua_type(L, stack) == LUA_TFUNCTION || lua_type(L, stack) == LUA_TLIGHTFUNCTION){
if ( lua_isnumber(L, stack+1) ){
run = lua_tointeger(L, stack+1);
}
lua_pushvalue(L, stack); // copy argument (func) to the top of stack
} else {
lua_pushnil(L);
}
if(sl == 4 && strcmp(method, "data") == 0){
run_input = true;
if(uart_receive_rf != LUA_NOREF){
luaL_unref(L, LUA_REGISTRYINDEX, uart_receive_rf);
uart_receive_rf = LUA_NOREF;
}
if(!lua_isnil(L, -1)){
uart_receive_rf = luaL_ref(L, LUA_REGISTRYINDEX);
gL = L;
if(run==0)
run_input = false;
} else {
lua_pop(L, 1);
}
}else{
lua_pop(L, 1);
return luaL_error( L, "method not supported" );
}
return 0;
}
bool uart0_echo = true;
// Lua: actualbaud = setup( id, baud, databits, parity, stopbits, echo )
static int uart_setup( lua_State* L )
{
unsigned id, databits, parity, stopbits, echo = 1;
uint32_t baud, res;
id = luaL_checkinteger( L, 1 );
MOD_CHECK_ID( uart, id );
baud = luaL_checkinteger( L, 2 );
databits = luaL_checkinteger( L, 3 );
parity = luaL_checkinteger( L, 4 );
stopbits = luaL_checkinteger( L, 5 );
if(lua_isnumber(L,6)){
echo = lua_tointeger(L,6);
if(echo!=0)
uart0_echo = true;
else
uart0_echo = false;
}
res = platform_uart_setup( id, baud, databits, parity, stopbits );
lua_pushinteger( L, res );
return 1;
}
// Lua: alt( set )
static int uart_alt( lua_State* L )
{
unsigned set;
set = luaL_checkinteger( L, 1 );
platform_uart_alt( set );
return 0;
}
// Lua: write( id, string1, [string2], ..., [stringn] )
static int uart_write( lua_State* L )
{
int id;
const char* buf;
size_t len, i;
int total = lua_gettop( L ), s;
id = luaL_checkinteger( L, 1 );
MOD_CHECK_ID( uart, id );
for( s = 2; s <= total; s ++ )
{
if( lua_type( L, s ) == LUA_TNUMBER )
{
len = lua_tointeger( L, s );
if( len > 255 )
return luaL_error( L, "invalid number" );
platform_uart_send( id, (uint8_t)len );
}
else
{
luaL_checktype( L, s, LUA_TSTRING );
buf = lua_tolstring( L, s, &len );
for( i = 0; i < len; i ++ )
platform_uart_send( id, buf[ i ] );
}
}
return 0;
}
// Module function map
static const LUA_REG_TYPE uart_map[] = {
{ LSTRKEY( "setup" ), LFUNCVAL( uart_setup ) },
{ LSTRKEY( "write" ), LFUNCVAL( uart_write ) },
{ LSTRKEY( "on" ), LFUNCVAL( uart_on ) },
{ LSTRKEY( "alt" ), LFUNCVAL( uart_alt ) },
{ LSTRKEY( "STOPBITS_1" ), LNUMVAL( PLATFORM_UART_STOPBITS_1 ) },
{ LSTRKEY( "STOPBITS_1_5" ), LNUMVAL( PLATFORM_UART_STOPBITS_1_5 ) },
{ LSTRKEY( "STOPBITS_2" ), LNUMVAL( PLATFORM_UART_STOPBITS_2 ) },
{ LSTRKEY( "PARITY_NONE" ), LNUMVAL( PLATFORM_UART_PARITY_NONE ) },
{ LSTRKEY( "PARITY_EVEN" ), LNUMVAL( PLATFORM_UART_PARITY_EVEN ) },
{ LSTRKEY( "PARITY_ODD" ), LNUMVAL( PLATFORM_UART_PARITY_ODD ) },
{ LNILKEY, LNILVAL }
};
NODEMCU_MODULE(UART, "uart", uart_map, NULL);
COMPONENT_ADD_INCLUDEDIRS:=include
include $(IDF_PATH)/make/component_common.mk
#ifndef READLINE_APP_H
#define READLINE_APP_H
#include <stdbool.h>
bool uart_getc(char *c);
#endif /* READLINE_APP_H */
/*
* ESPRSSIF MIT License
*
* Copyright (c) 2015 <ESPRESSIF SYSTEMS (SHANGHAI) PTE LTD>
*
* Permission is hereby granted for use on ESPRESSIF SYSTEMS ESP32 only, in which case,
* it is 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.
*
*/
#ifndef __UART_H__
#define __UART_H__
//#include "c_types.h" /* for BIT(n) definition */
#include "soc/uart_register.h"
#include "task/task.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef enum {
UART_WordLength_5b = 0x0,
UART_WordLength_6b = 0x1,
UART_WordLength_7b = 0x2,
UART_WordLength_8b = 0x3
} UART_WordLength;
typedef enum {
USART_StopBits_1 = 0x1,
USART_StopBits_1_5 = 0x2,
USART_StopBits_2 = 0x3,
} UART_StopBits;
typedef enum {
UART0 = 0x0,
UART1 = 0x1,
} UART_Port;
typedef enum {
USART_Parity_None = 0x2,
USART_Parity_Even = 0x0,
USART_Parity_Odd = 0x1
} UART_ParityMode;
typedef enum {
BIT_RATE_300 = 300,
BIT_RATE_600 = 600,
BIT_RATE_1200 = 1200,
BIT_RATE_2400 = 2400,
BIT_RATE_4800 = 4800,
BIT_RATE_9600 = 9600,
BIT_RATE_19200 = 19200,
BIT_RATE_38400 = 38400,
BIT_RATE_57600 = 57600,
BIT_RATE_74880 = 74880,
BIT_RATE_115200 = 115200,
BIT_RATE_230400 = 230400,
BIT_RATE_460800 = 460800,
BIT_RATE_921600 = 921600,
BIT_RATE_1843200 = 1843200,
BIT_RATE_3686400 = 3686400,
} UART_BautRate; //you can add any rate you need in this range
typedef enum {
USART_HardwareFlowControl_None = 0x0,
USART_HardwareFlowControl_RTS = 0x1,
USART_HardwareFlowControl_CTS = 0x2,
USART_HardwareFlowControl_CTS_RTS = 0x3
} UART_HwFlowCtrl;
typedef enum {
UART_None_Inverse = 0x0,
UART_Rxd_Inverse = UART_RXD_INV,
UART_CTS_Inverse = UART_CTS_INV,
UART_Txd_Inverse = UART_TXD_INV,
UART_RTS_Inverse = UART_RTS_INV,
} UART_LineLevelInverse;
typedef struct {
UART_BautRate baud_rate;
UART_WordLength data_bits;
UART_ParityMode parity; // chip size in byte
UART_StopBits stop_bits;
UART_HwFlowCtrl flow_ctrl;
uint8 UART_RxFlowThresh ;
uint32 UART_InverseMask;
} UART_ConfigTypeDef;
typedef struct {
uint32 UART_IntrEnMask;
uint8 UART_RX_TimeOutIntrThresh;
uint8 UART_TX_FifoEmptyIntrThresh;
uint8 UART_RX_FifoFullIntrThresh;
} UART_IntrConfTypeDef;
//=======================================
/** \defgroup Driver_APIs Driver APIs
* @brief Driver APIs
*/
/** @addtogroup Driver_APIs
* @{
*/
/** \defgroup UART_Driver_APIs UART Driver APIs
* @brief UART driver APIs
*/
/** @addtogroup UART_Driver_APIs
* @{
*/
/**
* @brief Set UART baud rate.
*
* Example : uart_div_modify(uart_no, UART_CLK_FREQ / (UartDev.baut_rate));
*
* @param UART_Port uart_no : UART0 or UART1
* @param uint16 div : frequency divider
*
* @return null
*/
void uart_div_modify(UART_Port uart_no, uint16 div);
/**
* @brief Wait uart tx fifo empty, do not use it if tx flow control enabled.
*
* @param UART_Port uart_no : UART0 or UART1
*
* @return null
*/
void UART_WaitTxFifoEmpty(UART_Port uart_no); //do not use if tx flow control enabled
/**
* @brief Clear uart tx fifo and rx fifo.
*
* @param UART_Port uart_no : UART0 or UART1
*
* @return null
*/
void UART_ResetFifo(UART_Port uart_no);
/**
* @brief Clear uart interrupt flags.
*
* @param UART_Port uart_no : UART0 or UART1
* @param uint32 clr_mask : To clear the interrupt bits
*
* @return null
*/
void UART_ClearIntrStatus(UART_Port uart_no, uint32 clr_mask);
/**
* @brief Enable uart interrupts .
*
* @param UART_Port uart_no : UART0 or UART1
* @param uint32 ena_mask : To enable the interrupt bits
*
* @return null
*/
void UART_SetIntrEna(UART_Port uart_no, uint32 ena_mask);
/**
* @brief Register an application-specific interrupt handler for Uarts interrupts.
*
* @param void *fn : interrupt handler for Uart interrupts.
* @param void *arg : interrupt handler's arg.
*
* @return null
*/
void UART_intr_handler_register(void *fn, void *arg);
/**
* @brief Config from which serial output printf function.
*
* @param UART_Port uart_no : UART0 or UART1
*
* @return null
*/
void UART_SetPrintPort(UART_Port uart_no);
/**
* @brief Config Common parameters of serial ports.
*
* @param UART_Port uart_no : UART0 or UART1
* @param UART_ConfigTypeDef *pUARTConfig : parameters structure
*
* @return null
*/
void UART_ParamConfig(UART_Port uart_no, const UART_ConfigTypeDef *pUARTConfig);
/**
* @brief Config types of uarts.
*
* @param UART_Port uart_no : UART0 or UART1
* @param UART_IntrConfTypeDef *pUARTIntrConf : parameters structure
*
* @return null
*/
void UART_IntrConfig(UART_Port uart_no, const UART_IntrConfTypeDef *pUARTIntrConf);
/**
* @brief Config the length of the uart communication data bits.
*
* @param UART_Port uart_no : UART0 or UART1
* @param UART_WordLength len : the length of the uart communication data bits
*
* @return null
*/
void UART_SetWordLength(UART_Port uart_no, UART_WordLength len);
/**
* @brief Config the length of the uart communication stop bits.
*
* @param UART_Port uart_no : UART0 or UART1
* @param UART_StopBits bit_num : the length uart communication stop bits
*
* @return null
*/
void UART_SetStopBits(UART_Port uart_no, UART_StopBits bit_num);
/**
* @brief Configure whether to open the parity.
*
* @param UART_Port uart_no : UART0 or UART1
* @param UART_ParityMode Parity_mode : the enum of uart parity configuration
*
* @return null
*/
void UART_SetParity(UART_Port uart_no, UART_ParityMode Parity_mode) ;
/**
* @brief Configure the Baud rate.
*
* @param UART_Port uart_no : UART0 or UART1
* @param uint32 baud_rate : the Baud rate
*
* @return null
*/
void UART_SetBaudrate(UART_Port uart_no, uint32 baud_rate);
/**
* @brief Configure Hardware flow control.
*
* @param UART_Port uart_no : UART0 or UART1
* @param UART_HwFlowCtrl flow_ctrl : Hardware flow control mode
* @param uint8 rx_thresh : threshold of Hardware flow control
*
* @return null
*/
void UART_SetFlowCtrl(UART_Port uart_no, UART_HwFlowCtrl flow_ctrl, uint8 rx_thresh);
/**
* @brief Configure trigging signal of uarts.
*
* @param UART_Port uart_no : UART0 or UART1
* @param UART_LineLevelInverse inverse_mask : Choose need to flip the IO
*
* @return null
*/
void UART_SetLineInverse(UART_Port uart_no, UART_LineLevelInverse inverse_mask) ;
/**
* @}
*/
/**
* @}
*/
/**
* Set up uart0 for NodeMCU console use.
* @param config The UART params to apply.
* @param tsk NodeMCU task to be notified when there is input pending.
*/
void uart_init_uart0_console (const UART_ConfigTypeDef *config, task_handle_t tsk);
/**
* Generic UART send interface.
* @param uart_no Which UART to send on (UART0 or UART1).
* @param c The character to send.
*/
void uart_tx_one_char (uint32_t uart_no, uint8_t c);
/**
* Switch (or unswitch) UART0 to the alternate pins.
* Currently only ESP8266.
* @param on True to use alternate RX/TX pins, false to use default pins.
*/
void uart0_alt (bool on);
/**
* Attempts to pull a character off the UART0 receive queue.
* @param c Where to stash the received character, if any.
* @returns True if a character was stored in @c, false if no char available.
*/
bool uart0_getc (char *c);
/**
* Convenience/consistency wrapper for UART0 output.
* @param c The character to output.
*/
static inline void uart0_putc (char c) { uart_tx_one_char (UART0, c); }
#ifdef __cplusplus
}
#endif
#endif
#if 0
/*
* ESPRSSIF MIT License
*
* Copyright (c) 2015 <ESPRESSIF SYSTEMS (SHANGHAI) PTE LTD>
* 2016 DiUS Computing Pty Ltd <jmattsson@dius.com.au>
*
* Permission is hereby granted for use on ESPRESSIF SYSTEMS ESP8266/ESP32 only, in which case,
* it is 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 "soc/soc.h"
#include "soc/io_mux_reg.h"
#include "esp_intr.h"
#include "freertos/FreeRTOS.h"
#include "freertos/queue.h"
#include "freertos/xtensa_api.h"
#include "driver/uart.h"
#include "task/task.h"
#include <stdio.h>
#define UART_INTR_MASK 0x1ff
#define UART_LINE_INV_MASK (0x3f << 19)
static xQueueHandle uartQ[2];
static task_handle_t input_task = 0;
// FIXME: on the ESP32 the interrupts are not shared between UART0 & UART1
void uart_tx_one_char(uint32_t uart, uint8_t TxChar)
{
while (true) {
uint32 fifo_cnt = READ_PERI_REG(UART_STATUS_REG(uart)) & (UART_TXFIFO_CNT << UART_TXFIFO_CNT_S);
if ((fifo_cnt >> UART_TXFIFO_CNT_S & UART_TXFIFO_CNT) < 126) {
break;
}
}
WRITE_PERI_REG(UART_FIFO_REG(uart) , TxChar);
}
static void uart1_write_char(char c)
{
if (c == '\n') {
uart_tx_one_char(UART1, '\r');
uart_tx_one_char(UART1, '\n');
} else if (c == '\r') {
} else {
uart_tx_one_char(UART1, c);
}
}
static void uart0_write_char(char c)
{
if (c == '\n') {
uart_tx_one_char(UART0, '\r');
uart_tx_one_char(UART0, '\n');
} else if (c == '\r') {
} else {
uart_tx_one_char(UART0, c);
}
}
//=================================================================
void UART_SetWordLength(UART_Port uart_no, UART_WordLength len)
{
SET_PERI_REG_BITS(UART_CONF0_REG(uart_no), UART_BIT_NUM, len, UART_BIT_NUM_S);
}
void
UART_SetStopBits(UART_Port uart_no, UART_StopBits bit_num)
{
SET_PERI_REG_BITS(UART_CONF0_REG(uart_no), UART_STOP_BIT_NUM, bit_num, UART_STOP_BIT_NUM_S);
}
void UART_SetLineInverse(UART_Port uart_no, UART_LineLevelInverse inverse_mask)
{
CLEAR_PERI_REG_MASK(UART_CONF0_REG(uart_no), UART_LINE_INV_MASK);
SET_PERI_REG_MASK(UART_CONF0_REG(uart_no), inverse_mask);
}
void UART_SetParity(UART_Port uart_no, UART_ParityMode Parity_mode)
{
CLEAR_PERI_REG_MASK(UART_CONF0_REG(uart_no), UART_PARITY | UART_PARITY_EN);
if (Parity_mode == USART_Parity_None) {
} else {
SET_PERI_REG_MASK(UART_CONF0_REG(uart_no), Parity_mode | UART_PARITY_EN);
}
}
void UART_SetBaudrate(UART_Port uart_no, uint32 baud_rate)
{
uart_div_modify(uart_no, UART_CLK_FREQ / baud_rate);
}
//only when USART_HardwareFlowControl_RTS is set , will the rx_thresh value be set.
void UART_SetFlowCtrl(UART_Port uart_no, UART_HwFlowCtrl flow_ctrl, uint8 rx_thresh)
{
if (uart_no == 0)
{
if (flow_ctrl & USART_HardwareFlowControl_RTS) {
#if defined(__ESP8266__)
PIN_FUNC_SELECT(PERIPHS_IO_MUX_MTDO_U, FUNC_U0RTS);
#elif defined(__ESP32__)
PIN_FUNC_SELECT(PERIPHS_IO_MUX_GPIO22_U, FUNC_GPIO22_U0RTS);
#endif
SET_PERI_REG_BITS(UART_CONF1_REG(uart_no), UART_RX_FLOW_THRHD, rx_thresh, UART_RX_FLOW_THRHD_S);
SET_PERI_REG_MASK(UART_CONF1_REG(uart_no), UART_RX_FLOW_EN);
} else {
CLEAR_PERI_REG_MASK(UART_CONF1_REG(uart_no), UART_RX_FLOW_EN);
}
if (flow_ctrl & USART_HardwareFlowControl_CTS) {
#if defined(__ESP8266__)
PIN_FUNC_SELECT(PERIPHS_IO_MUX_MTCK_U, FUNC_UART0_CTS);
#elif defined(__ESP32__)
PIN_FUNC_SELECT(PERIPHS_IO_MUX_GPIO19_U, FUNC_GPIO19_U0CTS);
#endif
SET_PERI_REG_MASK(UART_CONF0_REG(uart_no), UART_TX_FLOW_EN);
} else {
CLEAR_PERI_REG_MASK(UART_CONF0_REG(uart_no), UART_TX_FLOW_EN);
}
}
}
void UART_WaitTxFifoEmpty(UART_Port uart_no) //do not use if tx flow control enabled
{
while (READ_PERI_REG(UART_STATUS_REG(uart_no)) & (UART_TXFIFO_CNT << UART_TXFIFO_CNT_S));
}
void UART_ResetFifo(UART_Port uart_no)
{
SET_PERI_REG_MASK(UART_CONF0_REG(uart_no), UART_RXFIFO_RST | UART_TXFIFO_RST);
CLEAR_PERI_REG_MASK(UART_CONF0_REG(uart_no), UART_RXFIFO_RST | UART_TXFIFO_RST);
}
void UART_ClearIntrStatus(UART_Port uart_no, uint32 clr_mask)
{
WRITE_PERI_REG(UART_INT_CLR_REG(uart_no), clr_mask);
}
void UART_SetIntrEna(UART_Port uart_no, uint32 ena_mask)
{
SET_PERI_REG_MASK(UART_INT_ENA_REG(uart_no), ena_mask);
}
void UART_intr_handler_register(void *fn, void *arg)
{
#if defined(__ESP8266__)
_xt_isr_attach(ETS_UART_INUM, fn, arg);
#elif defined(__ESP32__)
xt_set_interrupt_handler(ETS_UART0_INUM, fn, arg);
#endif
}
void UART_SetPrintPort(UART_Port uart_no)
{
if (uart_no == 1) {
ets_install_putc1(uart1_write_char);
} else {
ets_install_putc1(uart0_write_char);
}
}
void UART_ParamConfig(UART_Port uart_no, const UART_ConfigTypeDef *pUARTConfig)
{
if (uart_no == UART1) {
#if defined(__ESP8266__)
PIN_FUNC_SELECT(PERIPHS_IO_MUX_GPIO2_U, FUNC_U1TXD_BK);
#elif defined(__ESP32__)
PIN_FUNC_SELECT(PERIPHS_IO_MUX_SD_DATA3_U, FUNC_SD_DATA3_U1TXD);
#endif
} else {
PIN_PULLUP_DIS(PERIPHS_IO_MUX_U0TXD_U);
#if defined(__ESP8266__)
PIN_FUNC_SELECT(PERIPHS_IO_MUX_U0RXD_U, FUNC_U0RXD);
PIN_FUNC_SELECT(PERIPHS_IO_MUX_U0TXD_U, FUNC_U0TXD);
#elif defined(__ESP32__)
PIN_FUNC_SELECT(PERIPHS_IO_MUX_U0RXD_U, FUNC_U0RXD_U0RXD);
PIN_FUNC_SELECT(PERIPHS_IO_MUX_U0TXD_U, FUNC_U0TXD_U0TXD);
#endif
}
UART_SetFlowCtrl(uart_no, pUARTConfig->flow_ctrl, pUARTConfig->UART_RxFlowThresh);
UART_SetBaudrate(uart_no, pUARTConfig->baud_rate);
WRITE_PERI_REG(UART_CONF0_REG(uart_no),
((pUARTConfig->parity == USART_Parity_None) ? 0x0 : (UART_PARITY_EN | pUARTConfig->parity))
| (pUARTConfig->stop_bits << UART_STOP_BIT_NUM_S)
| (pUARTConfig->data_bits << UART_BIT_NUM_S)
| ((pUARTConfig->flow_ctrl & USART_HardwareFlowControl_CTS) ? UART_TX_FLOW_EN : 0x0)
| pUARTConfig->UART_InverseMask
#if defined(__ESP32__)
| UART_TICK_REF_ALWAYS_ON
#endif
);
UART_ResetFifo(uart_no);
}
void UART_IntrConfig(UART_Port uart_no, const UART_IntrConfTypeDef *pUARTIntrConf)
{
uint32 reg_val = 0;
UART_ClearIntrStatus(uart_no, UART_INTR_MASK);
reg_val = READ_PERI_REG(UART_CONF1_REG(uart_no));
reg_val |= ((pUARTIntrConf->UART_IntrEnMask & UART_RXFIFO_TOUT_INT_ENA) ?
((((pUARTIntrConf->UART_RX_TimeOutIntrThresh)&UART_RX_TOUT_THRHD) << UART_RX_TOUT_THRHD_S) | UART_RX_TOUT_EN) : 0);
reg_val |= ((pUARTIntrConf->UART_IntrEnMask & UART_RXFIFO_FULL_INT_ENA) ?
(((pUARTIntrConf->UART_RX_FifoFullIntrThresh)&UART_RXFIFO_FULL_THRHD) << UART_RXFIFO_FULL_THRHD_S) : 0);
reg_val |= ((pUARTIntrConf->UART_IntrEnMask & UART_TXFIFO_EMPTY_INT_ENA) ?
(((pUARTIntrConf->UART_TX_FifoEmptyIntrThresh)&UART_TXFIFO_EMPTY_THRHD) << UART_TXFIFO_EMPTY_THRHD_S) : 0);
WRITE_PERI_REG(UART_CONF1_REG(uart_no), reg_val);
CLEAR_PERI_REG_MASK(UART_INT_ENA_REG(uart_no), UART_INTR_MASK);
SET_PERI_REG_MASK(UART_INT_ENA_REG(uart_no), pUARTIntrConf->UART_IntrEnMask);
}
static void uart0_rx_intr_handler(void *para)
{
/* uart0 and uart1 intr combine togther, when interrupt occur, see reg 0x3ff20020, bit2, bit0 represents
* uart1 and uart0 respectively
*/
uint8 uart_no = UART0; // TODO: support UART1 as well
uint8 fifo_len = 0;
uint32 uart_intr_status = READ_PERI_REG(UART_INT_ST_REG(uart_no)) ;
while (uart_intr_status != 0x0) {
if (UART_FRM_ERR_INT_ST == (uart_intr_status & UART_FRM_ERR_INT_ST)) {
//os_printf_isr("FRM_ERR\r\n");
WRITE_PERI_REG(UART_INT_CLR_REG(uart_no), UART_FRM_ERR_INT_CLR);
} else if (UART_RXFIFO_FULL_INT_ST == (uart_intr_status & UART_RXFIFO_FULL_INT_ST)) {
//os_printf_isr("full\r\n");
fifo_len = (READ_PERI_REG(UART_STATUS_REG(uart_no)) >> UART_RXFIFO_CNT_S)&UART_RXFIFO_CNT;
for (int i = 0; i < fifo_len; ++i)
{
char c = READ_PERI_REG(UART_FIFO_REG(uart_no)) & 0xff;
if (uartQ[uart_no])
xQueueSendToBackFromISR (uartQ[uart_no], &c, NULL);
}
WRITE_PERI_REG(UART_INT_CLR_REG(uart_no), UART_RXFIFO_FULL_INT_CLR);
//CLEAR_PERI_REG_MASK(UART_INT_ENA_REG(uart_no), UART_RXFIFO_FULL_INT_ENA|UART_RXFIFO_TOUT_INT_ENA);
} else if (UART_RXFIFO_TOUT_INT_ST == (uart_intr_status & UART_RXFIFO_TOUT_INT_ST)) {
//os_printf_isr("timeout\r\n");
fifo_len = (READ_PERI_REG(UART_STATUS_REG(uart_no)) >> UART_RXFIFO_CNT_S)&UART_RXFIFO_CNT;
for (int i = 0; i < fifo_len; ++i)
{
char c = READ_PERI_REG(UART_FIFO_REG(uart_no)) & 0xff;
if (uartQ[uart_no])
xQueueSendToBackFromISR (uartQ[uart_no], &c, NULL);
}
WRITE_PERI_REG(UART_INT_CLR_REG(uart_no), UART_RXFIFO_TOUT_INT_CLR);
} else if (UART_TXFIFO_EMPTY_INT_ST == (uart_intr_status & UART_TXFIFO_EMPTY_INT_ST)) {
//os_printf_isr("empty\n\r");
WRITE_PERI_REG(UART_INT_CLR_REG(uart_no), UART_TXFIFO_EMPTY_INT_CLR);
CLEAR_PERI_REG_MASK(UART_INT_ENA_REG(uart_no), UART_TXFIFO_EMPTY_INT_ENA);
} else if (UART_RXFIFO_OVF_INT_ST == (READ_PERI_REG(UART_INT_ST_REG(uart_no)) & UART_RXFIFO_OVF_INT_ST)) {
WRITE_PERI_REG(UART_INT_CLR_REG(uart_no), UART_RXFIFO_OVF_INT_CLR);
//os_printf_isr("RX OVF!!\r\n");
} else {
//skip
}
uart_intr_status = READ_PERI_REG(UART_INT_ST_REG(uart_no)) ;
}
if (fifo_len && input_task)
task_post_low (input_task, false);
}
void uart_init_uart0_console (const UART_ConfigTypeDef *config, task_handle_t tsk)
{
input_task = tsk;
uartQ[0] = xQueueCreate (0x100, sizeof (char));
UART_WaitTxFifoEmpty(UART0);
UART_ParamConfig(UART0, config);
UART_IntrConfTypeDef uart_intr;
uart_intr.UART_IntrEnMask =
UART_RXFIFO_TOUT_INT_ENA |
UART_FRM_ERR_INT_ENA |
UART_RXFIFO_FULL_INT_ENA |
UART_TXFIFO_EMPTY_INT_ENA;
uart_intr.UART_RX_FifoFullIntrThresh = 10;
uart_intr.UART_RX_TimeOutIntrThresh = 2;
uart_intr.UART_TX_FifoEmptyIntrThresh = 20;
UART_IntrConfig(UART0, &uart_intr);
UART_SetPrintPort(UART0);
UART_intr_handler_register(uart0_rx_intr_handler, NULL);
ESP_UART0_INTR_ENABLE();
}
bool uart0_getc (char *c)
{
return (uartQ[UART0] && (xQueueReceive (uartQ[UART0], c, 0) == pdTRUE));
}
void uart0_alt (bool on)
{
#if defined(__ESP8266__)
if (on)
{
PIN_PULLUP_DIS(PERIPHS_IO_MUX_MTDO_U);
PIN_PULLUP_EN(PERIPHS_IO_MUX_MTCK_U);
PIN_FUNC_SELECT(PERIPHS_IO_MUX_MTCK_U, FUNC_U0CTS);
// now make RTS/CTS behave as TX/RX
IOSWAP |= (1 << IOSWAPU0);
}
else
{
PIN_PULLUP_DIS(PERIPHS_IO_MUX_U0TXD_U);
PIN_FUNC_SELECT(PERIPHS_IO_MUX_U0TXD_U, FUNC_U0TXD);
PIN_PULLUP_EN(PERIPHS_IO_MUX_U0RXD_U);
PIN_FUNC_SELECT(PERIPHS_IO_MUX_U0RXD_U, FUNC_U0RXD);
// now make RX/TX behave as TX/RX
IOSWAP &= ~(1 << IOSWAPU0);
}
#else
printf("Alternate UART0 pins not supported on this chip\n");
#endif
}
#endif
/**
* define start/end address of ro data.
*/
#ifndef __COMPILER_H__
#define __COMPILER_H__
#if defined(__ESP8266__)
extern char _irom0_text_start;
extern char _irom0_text_end;
#define RODATA_START_ADDRESS (&_irom0_text_start)
#define RODATA_END_ADDRESS (&_irom0_text_end)
#elif defined(__ESP32__)
#define RODATA_START_ADDRESS ((char*)0x3F400000)
#define RODATA_END_ADDRESS ((char*)0x3F800000)
#else // other compilers
/* Firstly, modify rodata's start/end address. Then, comment the line below */
#error "Please modify RODATA_START_ADDRESS and RODATA_END_ADDRESS below."
/* Perhaps you can use start/end address of flash */
#define RODATA_START_ADDRESS ((char*)0x40200000)
#define RODATA_END_ADDRESS ((char*)0x40280000)
#endif
#endif // __COMPILER_H__
COMPONENT_ADD_INCLUDEDIRS:=.
include $(IDF_PATH)/make/component_common.mk
/*
** $Id: lapi.c,v 2.55.1.5 2008/07/04 18:41:18 roberto Exp $
** Lua API
** See Copyright Notice in lua.h
*/
#define lapi_c
#define LUA_CORE
#define LUAC_CROSS_FILE
#include "lua.h"
//#include C_HEADER_ASSERT
#include C_HEADER_MATH
#include C_HEADER_STRING
#include "lapi.h"
#include "ldebug.h"
#include "ldo.h"
#include "lfunc.h"
#include "lgc.h"
#include "lmem.h"
#include "lobject.h"
#include "lstate.h"
#include "lstring.h"
#include "ltable.h"
#include "ltm.h"
#include "lundump.h"
#include "lvm.h"
#include "lrotable.h"
#if 0
const char lua_ident[] =
"$Lua: " LUA_RELEASE " " LUA_COPYRIGHT " $\n"
"$Authors: " LUA_AUTHORS " $\n"
"$URL: www.lua.org $\n";
#endif
#define api_checknelems(L, n) api_check(L, (n) <= (L->top - L->base))
#define api_checkvalidindex(L, i) api_check(L, (i) != luaO_nilobject)
#define api_incr_top(L) {api_check(L, L->top < L->ci->top); L->top++;}
static TValue *index2adr (lua_State *L, int idx) {
if (idx > 0) {
TValue *o = L->base + (idx - 1);
api_check(L, idx <= L->ci->top - L->base);
if (o >= L->top) return cast(TValue *, luaO_nilobject);
else return o;
}
else if (idx > LUA_REGISTRYINDEX) {
api_check(L, idx != 0 && -idx <= L->top - L->base);
return L->top + idx;
}
else switch (idx) { /* pseudo-indices */
case LUA_REGISTRYINDEX: return registry(L);
case LUA_ENVIRONINDEX: {
Closure *func = curr_func(L);
sethvalue(L, &L->env, func ? func->c.env : hvalue(gt(L)));
return &L->env;
}
case LUA_GLOBALSINDEX: return gt(L);
default: {
Closure *func = curr_func(L);
if (!func) return cast(TValue *, luaO_nilobject);
idx = LUA_GLOBALSINDEX - idx;
return (idx <= func->c.nupvalues)
? &func->c.upvalue[idx-1]
: cast(TValue *, luaO_nilobject);
}
}
}
static Table *getcurrenv (lua_State *L) {
if (L->ci == L->base_ci) /* no enclosing function? */
return hvalue(gt(L)); /* use global table as environment */
else {
Closure *func = curr_func(L);
return func ? func->c.env : hvalue(gt(L));
}
}
void luaA_pushobject (lua_State *L, const TValue *o) {
setobj2s(L, L->top, o);
api_incr_top(L);
}
LUA_API int lua_checkstack (lua_State *L, int size) {
int res = 1;
lua_lock(L);
if (size > LUAI_MAXCSTACK || (L->top - L->base + size) > LUAI_MAXCSTACK)
res = 0; /* stack overflow */
else if (size > 0) {
luaD_checkstack(L, size);
if (L->ci->top < L->top + size)
L->ci->top = L->top + size;
}
lua_unlock(L);
return res;
}
LUA_API void lua_xmove (lua_State *from, lua_State *to, int n) {
int i;
if (from == to) return;
lua_lock(to);
api_checknelems(from, n);
api_check(from, G(from) == G(to));
api_check(from, to->ci->top - to->top >= n);
from->top -= n;
for (i = 0; i < n; i++) {
setobj2s(to, to->top++, from->top + i);
}
lua_unlock(to);
}
LUA_API void lua_setlevel (lua_State *from, lua_State *to) {
to->nCcalls = from->nCcalls;
}
LUA_API lua_CFunction lua_atpanic (lua_State *L, lua_CFunction panicf) {
lua_CFunction old;
lua_lock(L);
old = G(L)->panic;
G(L)->panic = panicf;
lua_unlock(L);
return old;
}
LUA_API lua_State *lua_newthread (lua_State *L) {
lua_State *L1;
lua_lock(L);
luaC_checkGC(L);
L1 = luaE_newthread(L);
setthvalue(L, L->top, L1);
api_incr_top(L);
lua_unlock(L);
luai_userstatethread(L, L1);
return L1;
}
/*
** basic stack manipulation
*/
LUA_API int lua_gettop (lua_State *L) {
return cast_int(L->top - L->base);
}
LUA_API void lua_settop (lua_State *L, int idx) {
lua_lock(L);
if (idx >= 0) {
api_check(L, idx <= L->stack_last - L->base);
while (L->top < L->base + idx)
setnilvalue(L->top++);
L->top = L->base + idx;
}
else {
api_check(L, -(idx+1) <= (L->top - L->base));
L->top += idx+1; /* `subtract' index (index is negative) */
}
lua_unlock(L);
}
LUA_API void lua_remove (lua_State *L, int idx) {
StkId p;
lua_lock(L);
p = index2adr(L, idx);
api_checkvalidindex(L, p);
while (++p < L->top) setobjs2s(L, p-1, p);
L->top--;
lua_unlock(L);
}
LUA_API void lua_insert (lua_State *L, int idx) {
StkId p;
StkId q;
lua_lock(L);
p = index2adr(L, idx);
api_checkvalidindex(L, p);
for (q = L->top; q>p; q--) setobjs2s(L, q, q-1);
setobjs2s(L, p, L->top);
lua_unlock(L);
}
LUA_API void lua_replace (lua_State *L, int idx) {
StkId o;
lua_lock(L);
/* explicit test for incompatible code */
if (idx == LUA_ENVIRONINDEX && L->ci == L->base_ci)
luaG_runerror(L, "no calling environment");
api_checknelems(L, 1);
o = index2adr(L, idx);
api_checkvalidindex(L, o);
if (idx == LUA_ENVIRONINDEX) {
Closure *func = curr_func(L);
if (!func)
luaG_runerror(L, "attempt to set environment on lightfunction");
else {
api_check(L, ttistable(L->top - 1));
func->c.env = hvalue(L->top - 1);
luaC_barrier(L, func, L->top - 1);
}
}
else {
setobj(L, o, L->top - 1);
if (curr_func(L) && idx < LUA_GLOBALSINDEX) /* function upvalue? */
luaC_barrier(L, curr_func(L), L->top - 1);
}
L->top--;
lua_unlock(L);
}
LUA_API void lua_pushvalue (lua_State *L, int idx) {
lua_lock(L);
setobj2s(L, L->top, index2adr(L, idx));
api_incr_top(L);
lua_unlock(L);
}
/*
** access functions (stack -> C)
*/
LUA_API int lua_type (lua_State *L, int idx) {
StkId o = index2adr(L, idx);
return (o == luaO_nilobject) ? LUA_TNONE : ttype(o);
}
LUA_API const char *lua_typename (lua_State *L, int t) {
UNUSED(L);
return (t == LUA_TNONE) ? "no value" : luaT_typenames[t];
}
LUA_API int lua_iscfunction (lua_State *L, int idx) {
StkId o = index2adr(L, idx);
return iscfunction(o);
}
LUA_API int lua_isnumber (lua_State *L, int idx) {
TValue n;
const TValue *o = index2adr(L, idx);
return tonumber(o, &n);
}
LUA_API int lua_isstring (lua_State *L, int idx) {
int t = lua_type(L, idx);
return (t == LUA_TSTRING || t == LUA_TNUMBER);
}
LUA_API int lua_isuserdata (lua_State *L, int idx) {
const TValue *o = index2adr(L, idx);
return (ttisuserdata(o) || ttislightuserdata(o));
}
LUA_API int lua_rawequal (lua_State *L, int index1, int index2) {
StkId o1 = index2adr(L, index1);
StkId o2 = index2adr(L, index2);
return (o1 == luaO_nilobject || o2 == luaO_nilobject) ? 0
: luaO_rawequalObj(o1, o2);
}
LUA_API int lua_equal (lua_State *L, int index1, int index2) {
StkId o1, o2;
int i;
lua_lock(L); /* may call tag method */
o1 = index2adr(L, index1);
o2 = index2adr(L, index2);
i = (o1 == luaO_nilobject || o2 == luaO_nilobject) ? 0 : equalobj(L, o1, o2);
lua_unlock(L);
return i;
}
LUA_API int lua_lessthan (lua_State *L, int index1, int index2) {
StkId o1, o2;
int i;
lua_lock(L); /* may call tag method */
o1 = index2adr(L, index1);
o2 = index2adr(L, index2);
i = (o1 == luaO_nilobject || o2 == luaO_nilobject) ? 0
: luaV_lessthan(L, o1, o2);
lua_unlock(L);
return i;
}
LUA_API lua_Number lua_tonumber (lua_State *L, int idx) {
TValue n;
const TValue *o = index2adr(L, idx);
if (tonumber(o, &n))
return nvalue(o);
else
return 0;
}
LUA_API lua_Integer lua_tointeger (lua_State *L, int idx) {
TValue n;
const TValue *o = index2adr(L, idx);
if (tonumber(o, &n)) {
lua_Integer res;
lua_Number num = nvalue(o);
lua_number2integer(res, num);
return res;
}
else
return 0;
}
LUA_API int lua_toboolean (lua_State *L, int idx) {
const TValue *o = index2adr(L, idx);
return !l_isfalse(o);
}
LUA_API const char *lua_tolstring (lua_State *L, int idx, size_t *len) {
StkId o = index2adr(L, idx);
if (!ttisstring(o)) {
lua_lock(L); /* `luaV_tostring' may create a new string */
if (!luaV_tostring(L, o)) { /* conversion failed? */
if (len != NULL) *len = 0;
lua_unlock(L);
return NULL;
}
luaC_checkGC(L);
o = index2adr(L, idx); /* previous call may reallocate the stack */
lua_unlock(L);
}
if (len != NULL) *len = tsvalue(o)->len;
return svalue(o);
}
LUA_API size_t lua_objlen (lua_State *L, int idx) {
StkId o = index2adr(L, idx);
switch (ttype(o)) {
case LUA_TSTRING: return tsvalue(o)->len;
case LUA_TUSERDATA: return uvalue(o)->len;
case LUA_TTABLE: return luaH_getn(hvalue(o));
case LUA_TROTABLE: return luaH_getn_ro(rvalue(o));
case LUA_TNUMBER: {
size_t l;
lua_lock(L); /* `luaV_tostring' may create a new string */
l = (luaV_tostring(L, o) ? tsvalue(o)->len : 0);
lua_unlock(L);
return l;
}
default: return 0;
}
}
LUA_API lua_CFunction lua_tocfunction (lua_State *L, int idx) {
StkId o = index2adr(L, idx);
return (!iscfunction(o)) ? NULL : clvalue(o)->c.f;
}
LUA_API void *lua_touserdata (lua_State *L, int idx) {
StkId o = index2adr(L, idx);
switch (ttype(o)) {
case LUA_TUSERDATA: return (rawuvalue(o) + 1);
case LUA_TLIGHTUSERDATA: return pvalue(o);
default: return NULL;
}
}
LUA_API lua_State *lua_tothread (lua_State *L, int idx) {
StkId o = index2adr(L, idx);
return (!ttisthread(o)) ? NULL : thvalue(o);
}
LUA_API const void *lua_topointer (lua_State *L, int idx) {
StkId o = index2adr(L, idx);
switch (ttype(o)) {
case LUA_TTABLE: return hvalue(o);
case LUA_TFUNCTION: return clvalue(o);
case LUA_TTHREAD: return thvalue(o);
case LUA_TUSERDATA:
case LUA_TLIGHTUSERDATA:
return lua_touserdata(L, idx);
case LUA_TROTABLE:
case LUA_TLIGHTFUNCTION:
return pvalue(o);
default: return NULL;
}
}
/*
** push functions (C -> stack)
*/
LUA_API void lua_pushnil (lua_State *L) {
lua_lock(L);
setnilvalue(L->top);
api_incr_top(L);
lua_unlock(L);
}
LUA_API void lua_pushnumber (lua_State *L, lua_Number n) {
lua_lock(L);
setnvalue(L->top, n);
api_incr_top(L);
lua_unlock(L);
}
LUA_API void lua_pushinteger (lua_State *L, lua_Integer n) {
lua_lock(L);
setnvalue(L->top, cast_num(n));
api_incr_top(L);
lua_unlock(L);
}
LUA_API void lua_pushlstring (lua_State *L, const char *s, size_t len) {
lua_lock(L);
luaC_checkGC(L);
setsvalue2s(L, L->top, luaS_newlstr(L, s, len));
api_incr_top(L);
lua_unlock(L);
}
LUA_API void lua_pushrolstring (lua_State *L, const char *s, size_t len) {
lua_lock(L);
luaC_checkGC(L);
setsvalue2s(L, L->top, luaS_newrolstr(L, s, len));
api_incr_top(L);
lua_unlock(L);
}
LUA_API void lua_pushstring (lua_State *L, const char *s) {
if (s == NULL)
lua_pushnil(L);
else
lua_pushlstring(L, s, strlen(s));
}
LUA_API const char *lua_pushvfstring (lua_State *L, const char *fmt,
va_list argp) {
const char *ret;
lua_lock(L);
luaC_checkGC(L);
ret = luaO_pushvfstring(L, fmt, argp);
lua_unlock(L);
return ret;
}
LUA_API const char *lua_pushfstring (lua_State *L, const char *fmt, ...) {
const char *ret;
va_list argp;
lua_lock(L);
luaC_checkGC(L);
va_start(argp, fmt);
ret = luaO_pushvfstring(L, fmt, argp);
va_end(argp);
lua_unlock(L);
return ret;
}
LUA_API void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n) {
Closure *cl;
lua_lock(L);
luaC_checkGC(L);
api_checknelems(L, n);
cl = luaF_newCclosure(L, n, getcurrenv(L));
cl->c.f = fn;
L->top -= n;
while (n--)
setobj2n(L, &cl->c.upvalue[n], L->top+n);
setclvalue(L, L->top, cl);
lua_assert(iswhite(obj2gco(cl)));
api_incr_top(L);
lua_unlock(L);
}
LUA_API void lua_pushboolean (lua_State *L, int b) {
lua_lock(L);
setbvalue(L->top, (b != 0)); /* ensure that true is 1 */
api_incr_top(L);
lua_unlock(L);
}
LUA_API void lua_pushlightuserdata (lua_State *L, void *p) {
lua_lock(L);
setpvalue(L->top, p);
api_incr_top(L);
lua_unlock(L);
}
LUA_API void lua_pushrotable (lua_State *L, void *p) {
lua_lock(L);
setrvalue(L->top, p);
api_incr_top(L);
lua_unlock(L);
}
LUA_API void lua_pushlightfunction(lua_State *L, void *p) {
lua_lock(L);
setfvalue(L->top, p);
api_incr_top(L);
lua_unlock(L);
}
LUA_API int lua_pushthread (lua_State *L) {
lua_lock(L);
setthvalue(L, L->top, L);
api_incr_top(L);
lua_unlock(L);
return (G(L)->mainthread == L);
}
/*
** get functions (Lua -> stack)
*/
LUA_API void lua_gettable (lua_State *L, int idx) {
StkId t;
lua_lock(L);
t = index2adr(L, idx);
api_checkvalidindex(L, t);
luaV_gettable(L, t, L->top - 1, L->top - 1);
lua_unlock(L);
}
LUA_API void lua_getfield (lua_State *L, int idx, const char *k) {
StkId t;
TValue key;
lua_lock(L);
t = index2adr(L, idx);
api_checkvalidindex(L, t);
fixedstack(L);
setsvalue(L, &key, luaS_new(L, k));
unfixedstack(L);
luaV_gettable(L, t, &key, L->top);
api_incr_top(L);
lua_unlock(L);
}
LUA_API void lua_rawget (lua_State *L, int idx) {
StkId t;
const TValue *res;
lua_lock(L);
t = index2adr(L, idx);
api_check(L, ttistable(t) || ttisrotable(t));
res = ttistable(t) ? luaH_get(hvalue(t), L->top - 1) : luaH_get_ro(rvalue(t), L->top - 1);
setobj2s(L, L->top - 1, res);
lua_unlock(L);
}
LUA_API void lua_rawgeti (lua_State *L, int idx, int n) {
StkId o;
lua_lock(L);
o = index2adr(L, idx);
api_check(L, ttistable(o) || ttisrotable(o));
setobj2s(L, L->top, ttistable(o) ? luaH_getnum(hvalue(o), n) : luaH_getnum_ro(rvalue(o), n))
api_incr_top(L);
lua_unlock(L);
}
LUA_API void lua_createtable (lua_State *L, int narray, int nrec) {
lua_lock(L);
luaC_checkGC(L);
sethvalue(L, L->top, luaH_new(L, narray, nrec));
api_incr_top(L);
lua_unlock(L);
}
LUA_API int lua_getmetatable (lua_State *L, int objindex) {
const TValue *obj;
Table *mt = NULL;
int res;
lua_lock(L);
obj = index2adr(L, objindex);
switch (ttype(obj)) {
case LUA_TTABLE:
mt = hvalue(obj)->metatable;
break;
case LUA_TUSERDATA:
mt = uvalue(obj)->metatable;
break;
case LUA_TROTABLE:
mt = (Table*)luaR_getmeta(rvalue(obj));
break;
default:
mt = G(L)->mt[ttype(obj)];
break;
}
if (mt == NULL)
res = 0;
else {
if(luaR_isrotable(mt))
setrvalue(L->top, mt)
else
sethvalue(L, L->top, mt)
api_incr_top(L);
res = 1;
}
lua_unlock(L);
return res;
}
LUA_API void lua_getfenv (lua_State *L, int idx) {
StkId o;
lua_lock(L);
o = index2adr(L, idx);
api_checkvalidindex(L, o);
switch (ttype(o)) {
case LUA_TFUNCTION:
sethvalue(L, L->top, clvalue(o)->c.env);
break;
case LUA_TUSERDATA:
sethvalue(L, L->top, uvalue(o)->env);
break;
case LUA_TTHREAD:
setobj2s(L, L->top, gt(thvalue(o)));
break;
default:
setnilvalue(L->top);
break;
}
api_incr_top(L);
lua_unlock(L);
}
/*
** set functions (stack -> Lua)
*/
LUA_API void lua_settable (lua_State *L, int idx) {
StkId t;
lua_lock(L);
api_checknelems(L, 2);
t = index2adr(L, idx);
api_checkvalidindex(L, t);
luaV_settable(L, t, L->top - 2, L->top - 1);
L->top -= 2; /* pop index and value */
lua_unlock(L);
}
LUA_API void lua_setfield (lua_State *L, int idx, const char *k) {
StkId t;
lua_lock(L);
api_checknelems(L, 1);
t = index2adr(L, idx);
api_checkvalidindex(L, t);
setsvalue2s(L, L->top, luaS_new(L, k));
api_incr_top(L);
luaV_settable(L, t, L->top - 1, L->top - 2);
L->top -= 2; /* pop key and value */
lua_unlock(L);
}
LUA_API void lua_rawset (lua_State *L, int idx) {
StkId t;
lua_lock(L);
api_checknelems(L, 2);
t = index2adr(L, idx);
api_check(L, ttistable(t));
fixedstack(L);
setobj2t(L, luaH_set(L, hvalue(t), L->top-2), L->top-1);
unfixedstack(L);
luaC_barriert(L, hvalue(t), L->top-1);
L->top -= 2;
lua_unlock(L);
}
LUA_API void lua_rawseti (lua_State *L, int idx, int n) {
StkId o;
lua_lock(L);
api_checknelems(L, 1);
o = index2adr(L, idx);
api_check(L, ttistable(o));
fixedstack(L);
setobj2t(L, luaH_setnum(L, hvalue(o), n), L->top-1);
unfixedstack(L);
luaC_barriert(L, hvalue(o), L->top-1);
L->top--;
lua_unlock(L);
}
LUA_API int lua_setmetatable (lua_State *L, int objindex) {
TValue *obj;
Table *mt;
int isrometa = 0;
lua_lock(L);
api_checknelems(L, 1);
obj = index2adr(L, objindex);
api_checkvalidindex(L, obj);
if (ttisnil(L->top - 1))
mt = NULL;
else {
api_check(L, ttistable(L->top - 1) || ttisrotable(L->top - 1));
if (ttistable(L->top - 1))
mt = hvalue(L->top - 1);
else {
mt = (Table*)rvalue(L->top - 1);
isrometa = 1;
}
}
switch (ttype(obj)) {
case LUA_TTABLE: {
hvalue(obj)->metatable = mt;
if (mt && !isrometa)
luaC_objbarriert(L, hvalue(obj), mt);
break;
}
case LUA_TUSERDATA: {
uvalue(obj)->metatable = mt;
if (mt && !isrometa)
luaC_objbarrier(L, rawuvalue(obj), mt);
break;
}
default: {
G(L)->mt[ttype(obj)] = mt;
break;
}
}
L->top--;
lua_unlock(L);
return 1;
}
LUA_API int lua_setfenv (lua_State *L, int idx) {
StkId o;
int res = 1;
lua_lock(L);
api_checknelems(L, 1);
o = index2adr(L, idx);
api_checkvalidindex(L, o);
api_check(L, ttistable(L->top - 1));
switch (ttype(o)) {
case LUA_TFUNCTION:
clvalue(o)->c.env = hvalue(L->top - 1);
break;
case LUA_TUSERDATA:
uvalue(o)->env = hvalue(L->top - 1);
break;
case LUA_TTHREAD:
sethvalue(L, gt(thvalue(o)), hvalue(L->top - 1));
break;
default:
res = 0;
break;
}
if (res) luaC_objbarrier(L, gcvalue(o), hvalue(L->top - 1));
L->top--;
lua_unlock(L);
return res;
}
/*
** `load' and `call' functions (run Lua code)
*/
#define adjustresults(L,nres) \
{ if (nres == LUA_MULTRET && L->top >= L->ci->top) L->ci->top = L->top; }
#define checkresults(L,na,nr) \
api_check(L, (nr) == LUA_MULTRET || (L->ci->top - L->top >= (nr) - (na)))
LUA_API void lua_call (lua_State *L, int nargs, int nresults) {
StkId func;
lua_lock(L);
api_checknelems(L, nargs+1);
checkresults(L, nargs, nresults);
func = L->top - (nargs+1);
luaD_call(L, func, nresults);
adjustresults(L, nresults);
lua_unlock(L);
}
/*
** Execute a protected call.
*/
struct CallS { /* data to `f_call' */
StkId func;
int nresults;
};
static void f_call (lua_State *L, void *ud) {
struct CallS *c = cast(struct CallS *, ud);
luaD_call(L, c->func, c->nresults);
}
LUA_API int lua_pcall (lua_State *L, int nargs, int nresults, int errfunc) {
struct CallS c;
int status;
ptrdiff_t func;
lua_lock(L);
api_checknelems(L, nargs+1);
checkresults(L, nargs, nresults);
if (errfunc == 0)
func = 0;
else {
StkId o = index2adr(L, errfunc);
api_checkvalidindex(L, o);
func = savestack(L, o);
}
c.func = L->top - (nargs+1); /* function to be called */
c.nresults = nresults;
status = luaD_pcall(L, f_call, &c, savestack(L, c.func), func);
adjustresults(L, nresults);
lua_unlock(L);
return status;
}
/*
** Execute a protected C call.
*/
struct CCallS { /* data to `f_Ccall' */
lua_CFunction func;
void *ud;
};
static void f_Ccall (lua_State *L, void *ud) {
struct CCallS *c = cast(struct CCallS *, ud);
Closure *cl;
cl = luaF_newCclosure(L, 0, getcurrenv(L));
cl->c.f = c->func;
setclvalue(L, L->top, cl); /* push function */
api_incr_top(L);
setpvalue(L->top, c->ud); /* push only argument */
api_incr_top(L);
luaD_call(L, L->top - 2, 0);
}
LUA_API int lua_cpcall (lua_State *L, lua_CFunction func, void *ud) {
struct CCallS c;
int status;
lua_lock(L);
c.func = func;
c.ud = ud;
status = luaD_pcall(L, f_Ccall, &c, savestack(L, L->top), 0);
lua_unlock(L);
return status;
}
LUA_API int lua_load (lua_State *L, lua_Reader reader, void *data,
const char *chunkname) {
ZIO z;
int status;
lua_lock(L);
if (!chunkname) chunkname = "?";
luaZ_init(L, &z, reader, data);
status = luaD_protectedparser(L, &z, chunkname);
lua_unlock(L);
return status;
}
LUA_API int lua_dump (lua_State *L, lua_Writer writer, void *data) {
int status;
TValue *o;
lua_lock(L);
api_checknelems(L, 1);
o = L->top - 1;
if (isLfunction(o))
status = luaU_dump(L, clvalue(o)->l.p, writer, data, 0);
else
status = 1;
lua_unlock(L);
return status;
}
LUA_API int lua_status (lua_State *L) {
return L->status;
}
/*
** Garbage-collection function
*/
LUA_API int lua_gc (lua_State *L, int what, int data) {
int res = 0;
global_State *g;
lua_lock(L);
g = G(L);
switch (what) {
case LUA_GCSTOP: {
set_block_gc(L);
break;
}
case LUA_GCRESTART: {
unset_block_gc(L);
break;
}
case LUA_GCCOLLECT: {
luaC_fullgc(L);
break;
}
case LUA_GCCOUNT: {
/* GC values are expressed in Kbytes: #bytes/2^10 */
res = cast_int(g->totalbytes >> 10);
break;
}
case LUA_GCCOUNTB: {
res = cast_int(g->totalbytes & 0x3ff);
break;
}
case LUA_GCSTEP: {
if(is_block_gc(L)) {
res = 1; /* gc is block so we need to pretend that the collection cycle finished. */
break;
}
lu_mem a = (cast(lu_mem, data) << 10);
if (a <= g->totalbytes)
g->GCthreshold = g->totalbytes - a;
else
g->GCthreshold = 0;
while (g->GCthreshold <= g->totalbytes) {
luaC_step(L);
if (g->gcstate == GCSpause) { /* end of cycle? */
res = 1; /* signal it */
break;
}
}
break;
}
case LUA_GCSETPAUSE: {
res = g->gcpause;
g->gcpause = data;
break;
}
case LUA_GCSETSTEPMUL: {
res = g->gcstepmul;
g->gcstepmul = data;
break;
}
case LUA_GCSETMEMLIMIT: {
/* GC values are expressed in Kbytes: #bytes/2^10 */
lu_mem new_memlimit = (cast(lu_mem, data) << 10);
if(new_memlimit > 0 && new_memlimit < g->totalbytes) {
/* run a full GC to make totalbytes < the new limit. */
luaC_fullgc(L);
if(new_memlimit < g->totalbytes)
new_memlimit = (g->totalbytes + 1024) & ~(1024-1); /* round up to next multiple of 1024 */
}
g->memlimit = new_memlimit;
/* new memlimit might be > then requested memlimit. */
res = cast_int(new_memlimit >> 10);
break;
}
case LUA_GCGETMEMLIMIT: {
res = cast_int(g->memlimit >> 10);
break;
}
default: res = -1; /* invalid option */
}
lua_unlock(L);
return res;
}
/*
** miscellaneous functions
*/
LUA_API int lua_error (lua_State *L) {
lua_lock(L);
api_checknelems(L, 1);
luaG_errormsg(L);
lua_unlock(L);
return 0; /* to avoid warnings */
}
LUA_API int lua_next (lua_State *L, int idx) {
StkId t;
int more;
lua_lock(L);
t = index2adr(L, idx);
api_check(L, ttistable(t) || ttisrotable(t));
more = ttistable(t) ? luaH_next(L, hvalue(t), L->top - 1) : luaH_next_ro(L, rvalue(t), L->top - 1);
if (more) {
api_incr_top(L);
}
else /* no more elements */
L->top -= 1; /* remove key */
lua_unlock(L);
return more;
}
LUA_API void lua_concat (lua_State *L, int n) {
lua_lock(L);
api_checknelems(L, n);
if (n >= 2) {
luaC_checkGC(L);
luaV_concat(L, n, cast_int(L->top - L->base) - 1);
L->top -= (n-1);
}
else if (n == 0) { /* push empty string */
setsvalue2s(L, L->top, luaS_newlstr(L, "", 0));
api_incr_top(L);
}
/* else n == 1; nothing to do */
lua_unlock(L);
}
LUA_API lua_Alloc lua_getallocf (lua_State *L, void **ud) {
lua_Alloc f;
lua_lock(L);
if (ud) *ud = G(L)->ud;
f = G(L)->frealloc;
lua_unlock(L);
return f;
}
LUA_API void lua_setallocf (lua_State *L, lua_Alloc f, void *ud) {
lua_lock(L);
G(L)->ud = ud;
G(L)->frealloc = f;
lua_unlock(L);
}
LUA_API void *lua_newuserdata (lua_State *L, size_t size) {
Udata *u;
lua_lock(L);
luaC_checkGC(L);
u = luaS_newudata(L, size, getcurrenv(L));
setuvalue(L, L->top, u);
api_incr_top(L);
lua_unlock(L);
return u + 1;
}
static const char *aux_upvalue (StkId fi, int n, TValue **val) {
Closure *f;
if (!ttisfunction(fi)) return NULL;
f = clvalue(fi);
if (f->c.isC) {
if (!(1 <= n && n <= f->c.nupvalues)) return NULL;
*val = &f->c.upvalue[n-1];
return "";
}
else {
Proto *p = f->l.p;
if (!(1 <= n && n <= p->sizeupvalues)) return NULL;
*val = f->l.upvals[n-1]->v;
return getstr(p->upvalues[n-1]);
}
}
LUA_API const char *lua_getupvalue (lua_State *L, int funcindex, int n) {
const char *name;
TValue *val;
lua_lock(L);
name = aux_upvalue(index2adr(L, funcindex), n, &val);
if (name) {
setobj2s(L, L->top, val);
api_incr_top(L);
}
lua_unlock(L);
return name;
}
LUA_API const char *lua_setupvalue (lua_State *L, int funcindex, int n) {
const char *name;
TValue *val;
StkId fi;
lua_lock(L);
fi = index2adr(L, funcindex);
api_checknelems(L, 1);
name = aux_upvalue(fi, n, &val);
if (name) {
L->top--;
setobj(L, val, L->top);
luaC_barrier(L, clvalue(fi), L->top);
}
lua_unlock(L);
return name;
}
/*
** $Id: lapi.h,v 2.2.1.1 2007/12/27 13:02:25 roberto Exp $
** Auxiliary functions from Lua API
** See Copyright Notice in lua.h
*/
#ifndef lapi_h
#define lapi_h
#include "lobject.h"
LUAI_FUNC void luaA_pushobject (lua_State *L, const TValue *o);
#endif
/*
** $Id: lauxlib.c,v 1.159.1.3 2008/01/21 13:20:51 roberto Exp $
** Auxiliary functions for building Lua libraries
** See Copyright Notice in lua.h
*/
#define LUAC_CROSS_FILE
#include "lua.h"
#include C_HEADER_CTYPE
#include C_HEADER_ERRNO
#include C_HEADER_STDIO
#include C_HEADER_STDLIB
#include C_HEADER_STRING
#ifndef LUA_CROSS_COMPILER
#include "flash_fs.h"
#else
#endif
/* This file uses only the official API of Lua.
** Any function declared here could be written as an application function.
*/
#define lauxlib_c
#define LUA_LIB
#include "lrotable.h"
#include "lauxlib.h"
#include "lgc.h"
#include "ldo.h"
#include "lobject.h"
#include "lstate.h"
#include "legc.h"
#define FREELIST_REF 0 /* free list of references */
/* convert a stack index to positive */
#define abs_index(L, i) ((i) > 0 || (i) <= LUA_REGISTRYINDEX ? (i) : \
lua_gettop(L) + (i) + 1)
// Parameters for luaI_openlib
#define LUA_USECCLOSURES 0
#define LUA_USELIGHTFUNCTIONS 1
/*
** {======================================================
** Error-report functions
** =======================================================
*/
LUALIB_API int luaL_argerror (lua_State *L, int narg, const char *extramsg) {
lua_Debug ar;
if (!lua_getstack(L, 0, &ar)) /* no stack frame? */
return luaL_error(L, "bad argument #%d (%s)", narg, extramsg);
lua_getinfo(L, "n", &ar);
if (strcmp(ar.namewhat, "method") == 0) {
narg--; /* do not count `self' */
if (narg == 0) /* error is in the self argument itself? */
return luaL_error(L, "calling " LUA_QS " on bad self (%s)",
ar.name, extramsg);
}
if (ar.name == NULL)
ar.name = "?";
return luaL_error(L, "bad argument #%d to " LUA_QS " (%s)",
narg, ar.name, extramsg);
}
LUALIB_API int luaL_typerror (lua_State *L, int narg, const char *tname) {
const char *msg = lua_pushfstring(L, "%s expected, got %s",
tname, luaL_typename(L, narg));
return luaL_argerror(L, narg, msg);
}
static void tag_error (lua_State *L, int narg, int tag) {
luaL_typerror(L, narg, lua_typename(L, tag));
}
LUALIB_API void luaL_where (lua_State *L, int level) {
lua_Debug ar;
if (lua_getstack(L, level, &ar)) { /* check function at level */
lua_getinfo(L, "Sl", &ar); /* get info about it */
if (ar.currentline > 0) { /* is there info? */
lua_pushfstring(L, "%s:%d: ", ar.short_src, ar.currentline);
return;
}
}
lua_pushliteral(L, ""); /* else, no information available... */
}
LUALIB_API int luaL_error (lua_State *L, const char *fmt, ...) {
va_list argp;
va_start(argp, fmt);
luaL_where(L, 1);
lua_pushvfstring(L, fmt, argp);
va_end(argp);
lua_concat(L, 2);
return lua_error(L);
}
/* }====================================================== */
LUALIB_API int luaL_checkoption (lua_State *L, int narg, const char *def,
const char *const lst[]) {
const char *name = (def) ? luaL_optstring(L, narg, def) :
luaL_checkstring(L, narg);
int i;
for (i=0; lst[i]; i++)
if (strcmp(lst[i], name) == 0)
return i;
return luaL_argerror(L, narg,
lua_pushfstring(L, "invalid option " LUA_QS, name));
}
LUALIB_API int luaL_newmetatable (lua_State *L, const char *tname) {
lua_getfield(L, LUA_REGISTRYINDEX, tname); /* get registry.name */
if (!lua_isnil(L, -1)) /* name already in use? */
return 0; /* leave previous value on top, but return 0 */
lua_pop(L, 1);
lua_newtable(L); /* create metatable */
lua_pushvalue(L, -1);
lua_setfield(L, LUA_REGISTRYINDEX, tname); /* registry.name = metatable */
return 1;
}
LUALIB_API int luaL_rometatable (lua_State *L, const char* tname, void *p) {
lua_getfield(L, LUA_REGISTRYINDEX, tname); /* get registry.name */
if (!lua_isnil(L, -1)) /* name already in use? */
return 0; /* leave previous value on top, but return 0 */
lua_pop(L, 1);
lua_pushrotable(L, p);
lua_pushvalue(L, -1);
lua_setfield(L, LUA_REGISTRYINDEX, tname); /* registry.name = metatable */
return 1;
}
LUALIB_API void *luaL_checkudata (lua_State *L, int ud, const char *tname) {
void *p = lua_touserdata(L, ud);
if (p != NULL) { /* value is a userdata? */
if (lua_getmetatable(L, ud)) { /* does it have a metatable? */
lua_getfield(L, LUA_REGISTRYINDEX, tname); /* get correct metatable */
if (lua_rawequal(L, -1, -2)) { /* does it have the correct mt? */
lua_pop(L, 2); /* remove both metatables */
return p;
}
}
}
luaL_typerror(L, ud, tname); /* else error */
return NULL; /* to avoid warnings */
}
LUALIB_API void luaL_checkstack (lua_State *L, int space, const char *mes) {
if (!lua_checkstack(L, space))
luaL_error(L, "stack overflow (%s)", mes);
}
LUALIB_API void luaL_checktype (lua_State *L, int narg, int t) {
if (lua_type(L, narg) != t)
tag_error(L, narg, t);
}
LUALIB_API void luaL_checkanyfunction (lua_State *L, int narg) {
if (lua_type(L, narg) != LUA_TFUNCTION && lua_type(L, narg) != LUA_TLIGHTFUNCTION) {
const char *msg = lua_pushfstring(L, "function or lightfunction expected, got %s",
luaL_typename(L, narg));
luaL_argerror(L, narg, msg);
}
}
LUALIB_API void luaL_checkanytable (lua_State *L, int narg) {
if (lua_type(L, narg) != LUA_TTABLE && lua_type(L, narg) != LUA_TROTABLE) {
const char *msg = lua_pushfstring(L, "table or rotable expected, got %s",
luaL_typename(L, narg));
luaL_argerror(L, narg, msg);
}
}
LUALIB_API void luaL_checkany (lua_State *L, int narg) {
if (lua_type(L, narg) == LUA_TNONE)
luaL_argerror(L, narg, "value expected");
}
LUALIB_API const char *luaL_checklstring (lua_State *L, int narg, size_t *len) {
const char *s = lua_tolstring(L, narg, len);
if (!s) tag_error(L, narg, LUA_TSTRING);
return s;
}
LUALIB_API const char *luaL_optlstring (lua_State *L, int narg,
const char *def, size_t *len) {
if (lua_isnoneornil(L, narg)) {
if (len)
*len = (def ? strlen(def) : 0);
return def;
}
else return luaL_checklstring(L, narg, len);
}
LUALIB_API lua_Number luaL_checknumber (lua_State *L, int narg) {
lua_Number d = lua_tonumber(L, narg);
if (d == 0 && !lua_isnumber(L, narg)) /* avoid extra test when d is not 0 */
tag_error(L, narg, LUA_TNUMBER);
return d;
}
LUALIB_API lua_Number luaL_optnumber (lua_State *L, int narg, lua_Number def) {
return luaL_opt(L, luaL_checknumber, narg, def);
}
LUALIB_API lua_Integer luaL_checkinteger (lua_State *L, int narg) {
lua_Integer d = lua_tointeger(L, narg);
if (d == 0 && !lua_isnumber(L, narg)) /* avoid extra test when d is not 0 */
tag_error(L, narg, LUA_TNUMBER);
return d;
}
LUALIB_API lua_Integer luaL_optinteger (lua_State *L, int narg,
lua_Integer def) {
return luaL_opt(L, luaL_checkinteger, narg, def);
}
LUALIB_API int luaL_getmetafield (lua_State *L, int obj, const char *event) {
if (!lua_getmetatable(L, obj)) /* no metatable? */
return 0;
lua_pushstring(L, event);
lua_rawget(L, -2);
if (lua_isnil(L, -1)) {
lua_pop(L, 2); /* remove metatable and metafield */
return 0;
}
else {
lua_remove(L, -2); /* remove only metatable */
return 1;
}
}
LUALIB_API int luaL_callmeta (lua_State *L, int obj, const char *event) {
obj = abs_index(L, obj);
if (!luaL_getmetafield(L, obj, event)) /* no metafield? */
return 0;
lua_pushvalue(L, obj);
lua_call(L, 1, 1);
return 1;
}
LUALIB_API void (luaL_register) (lua_State *L, const char *libname,
const luaL_Reg *l) {
luaI_openlib(L, libname, l, 0, LUA_USECCLOSURES);
}
LUALIB_API void (luaL_register_light) (lua_State *L, const char *libname,
const luaL_Reg *l) {
#if LUA_OPTIMIZE_MEMORY > 0
luaI_openlib(L, libname, l, 0, LUA_USELIGHTFUNCTIONS);
#else
luaI_openlib(L, libname, l, 0, LUA_USECCLOSURES);
#endif
}
static int libsize (const luaL_Reg *l) {
int size = 0;
for (; l->name; l++) size++;
return size;
}
LUALIB_API void luaI_openlib (lua_State *L, const char *libname,
const luaL_Reg *l, int nup, int ftype) {
if (libname) {
int size = libsize(l);
/* check whether lib already exists */
luaL_findtable(L, LUA_REGISTRYINDEX, "_LOADED", 1);
lua_getfield(L, -1, libname); /* get _LOADED[libname] */
if (!lua_istable(L, -1)) { /* not found? */
lua_pop(L, 1); /* remove previous result */
/* try global variable (and create one if it does not exist) */
if (luaL_findtable(L, LUA_GLOBALSINDEX, libname, size) != NULL)
luaL_error(L, "name conflict for module " LUA_QS, libname);
lua_pushvalue(L, -1);
lua_setfield(L, -3, libname); /* _LOADED[libname] = new table */
}
lua_remove(L, -2); /* remove _LOADED table */
lua_insert(L, -(nup+1)); /* move library table to below upvalues */
}
for (; l->name; l++) {
int i;
for (i=0; i<nup; i++) /* copy upvalues to the top */
lua_pushvalue(L, -nup);
if (ftype == LUA_USELIGHTFUNCTIONS)
lua_pushlightfunction(L, l->func);
else
lua_pushcclosure(L, l->func, nup);
lua_setfield(L, -(nup+2), l->name);
}
lua_pop(L, nup); /* remove upvalues */
}
/*
** {======================================================
** getn-setn: size for arrays
** =======================================================
*/
#if defined(LUA_COMPAT_GETN)
static int checkint (lua_State *L, int topop) {
int n = (lua_type(L, -1) == LUA_TNUMBER) ? lua_tointeger(L, -1) : -1;
lua_pop(L, topop);
return n;
}
static void getsizes (lua_State *L) {
lua_getfield(L, LUA_REGISTRYINDEX, "LUA_SIZES");
if (lua_isnil(L, -1)) { /* no `size' table? */
lua_pop(L, 1); /* remove nil */
lua_newtable(L); /* create it */
lua_pushvalue(L, -1); /* `size' will be its own metatable */
lua_setmetatable(L, -2);
lua_pushliteral(L, "kv");
lua_setfield(L, -2, "__mode"); /* metatable(N).__mode = "kv" */
lua_pushvalue(L, -1);
lua_setfield(L, LUA_REGISTRYINDEX, "LUA_SIZES"); /* store in register */
}
}
LUALIB_API void luaL_setn (lua_State *L, int t, int n) {
t = abs_index(L, t);
lua_pushliteral(L, "n");
lua_rawget(L, t);
if (checkint(L, 1) >= 0) { /* is there a numeric field `n'? */
lua_pushliteral(L, "n"); /* use it */
lua_pushinteger(L, n);
lua_rawset(L, t);
}
else { /* use `sizes' */
getsizes(L);
lua_pushvalue(L, t);
lua_pushinteger(L, n);
lua_rawset(L, -3); /* sizes[t] = n */
lua_pop(L, 1); /* remove `sizes' */
}
}
LUALIB_API int luaL_getn (lua_State *L, int t) {
int n;
t = abs_index(L, t);
lua_pushliteral(L, "n"); /* try t.n */
lua_rawget(L, t);
if ((n = checkint(L, 1)) >= 0) return n;
getsizes(L); /* else try sizes[t] */
lua_pushvalue(L, t);
lua_rawget(L, -2);
if ((n = checkint(L, 2)) >= 0) return n;
return (int)lua_objlen(L, t);
}
#endif
/* }====================================================== */
LUALIB_API const char *luaL_gsub (lua_State *L, const char *s, const char *p,
const char *r) {
const char *wild;
size_t l = strlen(p);
luaL_Buffer b;
luaL_buffinit(L, &b);
while ((wild = strstr(s, p)) != NULL) {
luaL_addlstring(&b, s, wild - s); /* push prefix */
luaL_addstring(&b, r); /* push replacement in place of pattern */
s = wild + l; /* continue after `p' */
}
luaL_addstring(&b, s); /* push last suffix */
luaL_pushresult(&b);
return lua_tostring(L, -1);
}
LUALIB_API const char *luaL_findtable (lua_State *L, int idx,
const char *fname, int szhint) {
const char *e;
lua_pushvalue(L, idx);
do {
e = strchr(fname, '.');
if (e == NULL) e = fname + strlen(fname);
lua_pushlstring(L, fname, e - fname);
lua_rawget(L, -2);
if (lua_isnil(L, -1)) {
/* If looking for a global variable, check the rotables too */
void *ptable = luaR_findglobal(fname, e - fname);
if (ptable) {
lua_pop(L, 1);
lua_pushrotable(L, ptable);
}
}
if (lua_isnil(L, -1)) { /* no such field? */
lua_pop(L, 1); /* remove this nil */
lua_createtable(L, 0, (*e == '.' ? 1 : szhint)); /* new table for field */
lua_pushlstring(L, fname, e - fname);
lua_pushvalue(L, -2);
lua_settable(L, -4); /* set new table into field */
}
else if (!lua_istable(L, -1) && !lua_isrotable(L, -1)) { /* field has a non-table value? */
lua_pop(L, 2); /* remove table and value */
return fname; /* return problematic part of the name */
}
lua_remove(L, -2); /* remove previous table */
fname = e + 1;
} while (*e == '.');
return NULL;
}
/*
** {======================================================
** Generic Buffer manipulation
** =======================================================
*/
#define bufflen(B) ((B)->p - (B)->buffer)
#define bufffree(B) ((size_t)(LUAL_BUFFERSIZE - bufflen(B)))
#define LIMIT (LUA_MINSTACK/2)
static int emptybuffer (luaL_Buffer *B) {
size_t l = bufflen(B);
if (l == 0) return 0; /* put nothing on stack */
else {
lua_pushlstring(B->L, B->buffer, l);
B->p = B->buffer;
B->lvl++;
return 1;
}
}
static void adjuststack (luaL_Buffer *B) {
if (B->lvl > 1) {
lua_State *L = B->L;
int toget = 1; /* number of levels to concat */
size_t toplen = lua_strlen(L, -1);
do {
size_t l = lua_strlen(L, -(toget+1));
if (B->lvl - toget + 1 >= LIMIT || toplen > l) {
toplen += l;
toget++;
}
else break;
} while (toget < B->lvl);
lua_concat(L, toget);
B->lvl = B->lvl - toget + 1;
}
}
LUALIB_API char *luaL_prepbuffer (luaL_Buffer *B) {
if (emptybuffer(B))
adjuststack(B);
return B->buffer;
}
LUALIB_API void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l) {
while (l--)
luaL_addchar(B, *s++);
}
LUALIB_API void luaL_addstring (luaL_Buffer *B, const char *s) {
luaL_addlstring(B, s, strlen(s));
}
LUALIB_API void luaL_pushresult (luaL_Buffer *B) {
emptybuffer(B);
lua_concat(B->L, B->lvl);
B->lvl = 1;
}
LUALIB_API void luaL_addvalue (luaL_Buffer *B) {
lua_State *L = B->L;
size_t vl;
const char *s = lua_tolstring(L, -1, &vl);
if (vl <= bufffree(B)) { /* fit into buffer? */
memcpy(B->p, s, vl); /* put it there */
B->p += vl;
lua_pop(L, 1); /* remove from stack */
}
else {
if (emptybuffer(B))
lua_insert(L, -2); /* put buffer before new value */
B->lvl++; /* add new value into B stack */
adjuststack(B);
}
}
LUALIB_API void luaL_buffinit (lua_State *L, luaL_Buffer *B) {
B->L = L;
B->p = B->buffer;
B->lvl = 0;
}
/* }====================================================== */
LUALIB_API int luaL_ref (lua_State *L, int t) {
int ref;
t = abs_index(L, t);
if (lua_isnil(L, -1)) {
lua_pop(L, 1); /* remove from stack */
return LUA_REFNIL; /* `nil' has a unique fixed reference */
}
lua_rawgeti(L, t, FREELIST_REF); /* get first free element */
ref = (int)lua_tointeger(L, -1); /* ref = t[FREELIST_REF] */
lua_pop(L, 1); /* remove it from stack */
if (ref != 0) { /* any free element? */
lua_rawgeti(L, t, ref); /* remove it from list */
lua_rawseti(L, t, FREELIST_REF); /* (t[FREELIST_REF] = t[ref]) */
}
else { /* no free elements */
ref = (int)lua_objlen(L, t);
ref++; /* create new reference */
}
lua_rawseti(L, t, ref);
return ref;
}
LUALIB_API void luaL_unref (lua_State *L, int t, int ref) {
if (ref >= 0) {
t = abs_index(L, t);
lua_rawgeti(L, t, FREELIST_REF);
lua_rawseti(L, t, ref); /* t[ref] = t[FREELIST_REF] */
lua_pushinteger(L, ref);
lua_rawseti(L, t, FREELIST_REF); /* t[FREELIST_REF] = ref */
}
}
/*
** {======================================================
** Load functions
** =======================================================
*/
#ifdef LUA_CROSS_COMPILER
typedef struct LoadF {
int extraline;
FILE *f;
char buff[LUAL_BUFFERSIZE];
} LoadF;
static const char *getF (lua_State *L, void *ud, size_t *size) {
LoadF *lf = (LoadF *)ud;
(void)L;
if (lf->extraline) {
lf->extraline = 0;
*size = 1;
return "\n";
}
if (c_feof(lf->f)) return NULL;
*size = c_fread(lf->buff, 1, sizeof(lf->buff), lf->f);
return (*size > 0) ? lf->buff : NULL;
}
static int errfile (lua_State *L, const char *what, int fnameindex) {
const char *serr = c_strerror(errno);
const char *filename = lua_tostring(L, fnameindex) + 1;
lua_pushfstring(L, "cannot %s %s: %s", what, filename, serr);
lua_remove(L, fnameindex);
return LUA_ERRFILE;
}
LUALIB_API int luaL_loadfile (lua_State *L, const char *filename) {
LoadF lf;
int status, readstatus;
int c;
int fnameindex = lua_gettop(L) + 1; /* index of filename on the stack */
lf.extraline = 0;
if (filename == NULL) {
lua_pushliteral(L, "=stdin");
lf.f = c_stdin;
}
else {
lua_pushfstring(L, "@%s", filename);
lf.f = c_fopen(filename, "r");
if (lf.f == NULL) return errfile(L, "open", fnameindex);
}
c = c_getc(lf.f);
if (c == '#') { /* Unix exec. file? */
lf.extraline = 1;
while ((c = c_getc(lf.f)) != EOF && c != '\n') ; /* skip first line */
if (c == '\n') c = c_getc(lf.f);
}
if (c == LUA_SIGNATURE[0] && filename) { /* binary file? */
lf.f = c_freopen(filename, "rb", lf.f); /* reopen in binary mode */
if (lf.f == NULL) return errfile(L, "reopen", fnameindex);
/* skip eventual `#!...' */
while ((c = c_getc(lf.f)) != EOF && c != LUA_SIGNATURE[0]) ;
lf.extraline = 0;
}
c_ungetc(c, lf.f);
status = lua_load(L, getF, &lf, lua_tostring(L, -1));
readstatus = c_ferror(lf.f);
if (filename) c_fclose(lf.f); /* close file (even in case of errors) */
if (readstatus) {
lua_settop(L, fnameindex); /* ignore results from `lua_load' */
return errfile(L, "read", fnameindex);
}
lua_remove(L, fnameindex);
return status;
}
#else
#include C_HEADER_FCNTL
typedef struct LoadFSF {
int extraline;
int f;
char buff[LUAL_BUFFERSIZE];
} LoadFSF;
static const char *getFSF (lua_State *L, void *ud, size_t *size) {
LoadFSF *lf = (LoadFSF *)ud;
(void)L;
if (L == NULL && size == NULL) // Direct mode check
return NULL;
if (lf->extraline) {
lf->extraline = 0;
*size = 1;
return "\n";
}
if (fs_eof(lf->f)) return NULL;
*size = fs_read(lf->f, lf->buff, sizeof(lf->buff));
return (*size > 0) ? lf->buff : NULL;
}
static int errfsfile (lua_State *L, const char *what, int fnameindex) {
const char *filename = lua_tostring(L, fnameindex) + 1;
lua_pushfstring(L, "cannot %s %s", what, filename);
lua_remove(L, fnameindex);
return LUA_ERRFILE;
}
LUALIB_API int luaL_loadfsfile (lua_State *L, const char *filename) {
LoadFSF lf;
int status, readstatus;
int c;
int fnameindex = lua_gettop(L) + 1; /* index of filename on the stack */
lf.extraline = 0;
if (filename == NULL) {
return luaL_error(L, "filename is NULL");
}
else {
lua_pushfstring(L, "@%s", filename);
lf.f = fs_open(filename, FS_RDONLY);
if (lf.f < FS_OPEN_OK) return errfsfile(L, "open", fnameindex);
}
// if(fs_size(lf.f)>LUAL_BUFFERSIZE)
// return luaL_error(L, "file is too big");
c = fs_getc(lf.f);
if (c == '#') { /* Unix exec. file? */
lf.extraline = 1;
while ((c = fs_getc(lf.f)) != EOF && c != '\n') ; /* skip first line */
if (c == '\n') c = fs_getc(lf.f);
}
if (c == LUA_SIGNATURE[0] && filename) { /* binary file? */
fs_close(lf.f);
lf.f = fs_open(filename, FS_RDONLY); /* reopen in binary mode */
if (lf.f < FS_OPEN_OK) return errfsfile(L, "reopen", fnameindex);
/* skip eventual `#!...' */
while ((c = fs_getc(lf.f)) != EOF && c != LUA_SIGNATURE[0]) ;
lf.extraline = 0;
}
fs_ungetc(c, lf.f);
status = lua_load(L, getFSF, &lf, lua_tostring(L, -1));
if (filename) fs_close(lf.f); /* close file (even in case of errors) */
lua_remove(L, fnameindex);
return status;
}
#endif
typedef struct LoadS {
const char *s;
size_t size;
} LoadS;
static const char *getS (lua_State *L, void *ud, size_t *size) {
LoadS *ls = (LoadS *)ud;
(void)L;
if (L == NULL && size == NULL) // direct mode check
return NULL;
if (ls->size == 0) return NULL;
*size = ls->size;
ls->size = 0;
return ls->s;
}
LUALIB_API int luaL_loadbuffer (lua_State *L, const char *buff, size_t size,
const char *name) {
LoadS ls;
ls.s = buff;
ls.size = size;
return lua_load(L, getS, &ls, name);
}
LUALIB_API int (luaL_loadstring) (lua_State *L, const char *s) {
return luaL_loadbuffer(L, s, strlen(s), s);
}
/* }====================================================== */
static int l_check_memlimit(lua_State *L, size_t needbytes) {
global_State *g = G(L);
int cycle_count = 0;
lu_mem limit = g->memlimit - needbytes;
/* don't allow allocation if it requires more memory then the total limit. */
if (needbytes > g->memlimit) return 1;
/* make sure the GC is not disabled. */
if (!is_block_gc(L)) {
while (g->totalbytes >= limit) {
/* only allow the GC to finished atleast 1 full cycle. */
if (g->gcstate == GCSpause && ++cycle_count > 1) break;
luaC_step(L);
}
}
return (g->totalbytes >= limit) ? 1 : 0;
}
static void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize) {
lua_State *L = (lua_State *)ud;
int mode = L == NULL ? 0 : G(L)->egcmode;
void *nptr;
if (nsize == 0) {
free(ptr);
return NULL;
}
if (L != NULL && (mode & EGC_ALWAYS)) /* always collect memory if requested */
luaC_fullgc(L);
if(nsize > osize && L != NULL) {
#if defined(LUA_STRESS_EMERGENCY_GC)
luaC_fullgc(L);
#endif
if(G(L)->memlimit > 0 && (mode & EGC_ON_MEM_LIMIT) && l_check_memlimit(L, nsize - osize))
return NULL;
}
nptr = (void *)realloc(ptr, nsize);
if (nptr == NULL && L != NULL && (mode & EGC_ON_ALLOC_FAILURE)) {
luaC_fullgc(L); /* emergency full collection. */
nptr = (void *)realloc(ptr, nsize); /* try allocation again */
}
return nptr;
}
LUALIB_API void luaL_assertfail(const char *file, int line, const char *message) {
printf("ASSERT@%s(%d): %s\n", file, line, message);
}
static int panic (lua_State *L) {
(void)L; /* to avoid warnings */
#if defined(LUA_USE_STDIO)
c_fprintf(c_stderr, "PANIC: unprotected error in call to Lua API (%s)\n",
lua_tostring(L, -1));
#else
luai_writestringerror("PANIC: unprotected error in call to Lua API (%s)\n",
lua_tostring(L, -1));
#endif
while (1) {}
return 0;
}
LUALIB_API lua_State *luaL_newstate (void) {
lua_State *L = lua_newstate(l_alloc, NULL);
lua_setallocf(L, l_alloc, L); /* allocator need lua_State. */
if (L) lua_atpanic(L, &panic);
return L;
}
/*
** $Id: lauxlib.h,v 1.88.1.1 2007/12/27 13:02:25 roberto Exp $
** Auxiliary functions for building Lua libraries
** See Copyright Notice in lua.h
*/
#ifndef lauxlib_h
#define lauxlib_h
#include "lua.h"
#include <stdio.h>
#if defined(LUA_COMPAT_GETN)
LUALIB_API int (luaL_getn) (lua_State *L, int t);
LUALIB_API void (luaL_setn) (lua_State *L, int t, int n);
#else
#define luaL_getn(L,i) ((int)lua_objlen(L, i))
#define luaL_setn(L,i,j) ((void)0) /* no op! */
#endif
#if defined(LUA_COMPAT_OPENLIB)
#define luaI_openlib luaL_openlib
#endif
/* extra error code for `luaL_load' */
#define LUA_ERRFILE (LUA_ERRERR+1)
typedef struct luaL_Reg {
const char *name;
lua_CFunction func;
} luaL_Reg;
LUALIB_API void (luaI_openlib) (lua_State *L, const char *libname,
const luaL_Reg *l, int nup, int ftype);
LUALIB_API void (luaL_register) (lua_State *L, const char *libname,
const luaL_Reg *l);
LUALIB_API void (luaL_register_light) (lua_State *L, const char *libname,
const luaL_Reg *l);
LUALIB_API int (luaL_getmetafield) (lua_State *L, int obj, const char *e);
LUALIB_API int (luaL_callmeta) (lua_State *L, int obj, const char *e);
LUALIB_API int (luaL_typerror) (lua_State *L, int narg, const char *tname);
LUALIB_API int (luaL_argerror) (lua_State *L, int numarg, const char *extramsg);
LUALIB_API const char *(luaL_checklstring) (lua_State *L, int numArg,
size_t *l);
LUALIB_API const char *(luaL_optlstring) (lua_State *L, int numArg,
const char *def, size_t *l);
LUALIB_API lua_Number (luaL_checknumber) (lua_State *L, int numArg);
LUALIB_API lua_Number (luaL_optnumber) (lua_State *L, int nArg, lua_Number def);
LUALIB_API lua_Integer (luaL_checkinteger) (lua_State *L, int numArg);
LUALIB_API lua_Integer (luaL_optinteger) (lua_State *L, int nArg,
lua_Integer def);
LUALIB_API void (luaL_checkstack) (lua_State *L, int sz, const char *msg);
LUALIB_API void (luaL_checktype) (lua_State *L, int narg, int t);
LUALIB_API void (luaL_checkany) (lua_State *L, int narg);
LUALIB_API void (luaL_checkanyfunction) (lua_State *L, int narg);
LUALIB_API void (luaL_checkanytable) (lua_State *L, int narg);
LUALIB_API int (luaL_newmetatable) (lua_State *L, const char *tname);
LUALIB_API int (luaL_rometatable) (lua_State *L, const char* tname, void *p);
LUALIB_API void *(luaL_checkudata) (lua_State *L, int ud, const char *tname);
LUALIB_API void (luaL_where) (lua_State *L, int lvl);
LUALIB_API int (luaL_error) (lua_State *L, const char *fmt, ...);
LUALIB_API int (luaL_checkoption) (lua_State *L, int narg, const char *def,
const char *const lst[]);
LUALIB_API int (luaL_ref) (lua_State *L, int t);
LUALIB_API void (luaL_unref) (lua_State *L, int t, int ref);
#ifdef LUA_CROSS_COMPILER
LUALIB_API int (luaL_loadfile) (lua_State *L, const char *filename);
#else
LUALIB_API int (luaL_loadfsfile) (lua_State *L, const char *filename);
#endif
LUALIB_API int (luaL_loadbuffer) (lua_State *L, const char *buff, size_t sz,
const char *name);
LUALIB_API int (luaL_loadstring) (lua_State *L, const char *s);
LUALIB_API lua_State *(luaL_newstate) (void);
LUALIB_API const char *(luaL_gsub) (lua_State *L, const char *s, const char *p,
const char *r);
LUALIB_API const char *(luaL_findtable) (lua_State *L, int idx,
const char *fname, int szhint);
LUALIB_API void luaL_assertfail(const char *file, int line, const char *message);
/*
** ===============================================================
** some useful macros
** ===============================================================
*/
#define luaL_argcheck(L, cond,numarg,extramsg) \
((void)((cond) || luaL_argerror(L, (numarg), (extramsg))))
#define luaL_checkstring(L,n) (luaL_checklstring(L, (n), NULL))
#define luaL_optstring(L,n,d) (luaL_optlstring(L, (n), (d), NULL))
#define luaL_checkint(L,n) ((int)luaL_checkinteger(L, (n)))
#define luaL_optint(L,n,d) ((int)luaL_optinteger(L, (n), (d)))
#define luaL_checklong(L,n) ((long)luaL_checkinteger(L, (n)))
#define luaL_optlong(L,n,d) ((long)luaL_optinteger(L, (n), (d)))
#define luaL_typename(L,i) lua_typename(L, lua_type(L,(i)))
#if 0
#define luaL_dofile(L, fn) \
(luaL_loadfile(L, fn) || lua_pcall(L, 0, LUA_MULTRET, 0))
#else
#define luaL_dofile(L, fn) \
(luaL_loadfsfile(L, fn) || lua_pcall(L, 0, LUA_MULTRET, 0))
#endif
#define luaL_dostring(L, s) \
(luaL_loadstring(L, s) || lua_pcall(L, 0, LUA_MULTRET, 0))
#define luaL_getmetatable(L,n) (lua_getfield(L, LUA_REGISTRYINDEX, (n)))
#define luaL_opt(L,f,n,d) (lua_isnoneornil(L,(n)) ? (d) : f(L,(n)))
/*
** {======================================================
** Generic Buffer manipulation
** =======================================================
*/
typedef struct luaL_Buffer {
char *p; /* current position in buffer */
int lvl; /* number of strings in the stack (level) */
lua_State *L;
char buffer[LUAL_BUFFERSIZE];
} luaL_Buffer;
#define luaL_addchar(B,c) \
((void)((B)->p < ((B)->buffer+LUAL_BUFFERSIZE) || luaL_prepbuffer(B)), \
(*(B)->p++ = (char)(c)))
/* compatibility only */
#define luaL_putchar(B,c) luaL_addchar(B,c)
#define luaL_addsize(B,n) ((B)->p += (n))
LUALIB_API void (luaL_buffinit) (lua_State *L, luaL_Buffer *B);
LUALIB_API char *(luaL_prepbuffer) (luaL_Buffer *B);
LUALIB_API void (luaL_addlstring) (luaL_Buffer *B, const char *s, size_t l);
LUALIB_API void (luaL_addstring) (luaL_Buffer *B, const char *s);
LUALIB_API void (luaL_addvalue) (luaL_Buffer *B);
LUALIB_API void (luaL_pushresult) (luaL_Buffer *B);
/* }====================================================== */
/* compatibility with ref system */
/* pre-defined references */
#define LUA_NOREF (-2)
#define LUA_REFNIL (-1)
#define lua_ref(L,lock) ((lock) ? luaL_ref(L, LUA_REGISTRYINDEX) : \
(lua_pushstring(L, "unlocked references are obsolete"), lua_error(L), 0))
#define lua_unref(L,ref) luaL_unref(L, LUA_REGISTRYINDEX, (ref))
#define lua_getref(L,ref) lua_rawgeti(L, LUA_REGISTRYINDEX, (ref))
#define luaL_reg luaL_Reg
#endif
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment