text
stringlengths
7
35.3M
id
stringlengths
11
185
metadata
dict
__index_level_0__
int64
0
2.14k
# This file is part of the ios-cmake project. It was retrieved from # https://github.com/cristeab/ios-cmake.git, which is a fork of # https://code.google.com/p/ios-cmake/. Which in turn is based off of # the Platform/Darwin.cmake and Platform/UnixPaths.cmake files which # are included with CMake 2.8.4 # # The ios-cmake project is licensed under the new BSD license. # # Copyright (c) 2014, Bogdan Cristea and LTE Engineering Software, # Kitware, Inc., Insight Software Consortium. All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # # This file is based off of the Platform/Darwin.cmake and # Platform/UnixPaths.cmake files which are included with CMake 2.8.4 # It has been altered for iOS development. # # Updated by Alex Stewart ([email protected]) # # ***************************************************************************** # Now maintained by Alexander Widerberg (widerbergaren [at] gmail.com) # under the BSD-3-Clause license # https://github.com/leetal/ios-cmake # ***************************************************************************** # # INFORMATION / HELP # # The following arguments control the behaviour of this toolchain: # # PLATFORM: (default "OS") # OS = Build for iPhoneOS. # OS64 = Build for arm64 iphoneOS. # OS64COMBINED = Build for arm64 x86_64 iphoneOS. Combined into FAT STATIC lib (supported on 3.14+ of CMakewith "-G Xcode" argument ONLY) # SIMULATOR = Build for x86 i386 iphoneOS Simulator. # SIMULATOR64 = Build for x86_64 iphoneOS Simulator. # TVOS = Build for arm64 tvOS. # TVOSCOMBINED = Build for arm64 x86_64 tvOS. Combined into FAT STATIC lib (supported on 3.14+ of CMake with "-G Xcode" argument ONLY) # SIMULATOR_TVOS = Build for x86_64 tvOS Simulator. # WATCHOS = Build for armv7k arm64_32 for watchOS. # WATCHOSCOMBINED = Build for armv7k arm64_32 x86_64 watchOS. Combined into FAT STATIC lib (supported on 3.14+ of CMake with "-G Xcode" argument ONLY) # SIMULATOR_WATCHOS = Build for x86_64 for watchOS Simulator. # # CMAKE_OSX_SYSROOT: Path to the SDK to use. By default this is # automatically determined from PLATFORM and xcodebuild, but # can also be manually specified (although this should not be required). # # CMAKE_DEVELOPER_ROOT: Path to the Developer directory for the platform # being compiled for. By default this is automatically determined from # CMAKE_OSX_SYSROOT, but can also be manually specified (although this should # not be required). # # DEPLOYMENT_TARGET: Minimum SDK version to target. Default 2.0 on watchOS and 9.0 on tvOS+iOS # # ENABLE_BITCODE: (1|0) Enables or disables bitcode support. Default 1 (true) # # ENABLE_ARC: (1|0) Enables or disables ARC support. Default 1 (true, ARC enabled by default) # # ENABLE_VISIBILITY: (1|0) Enables or disables symbol visibility support. Default 0 (false, visibility hidden by default) # # ENABLE_STRICT_TRY_COMPILE: (1|0) Enables or disables strict try_compile() on all Check* directives (will run linker # to actually check if linking is possible). Default 0 (false, will set CMAKE_TRY_COMPILE_TARGET_TYPE to STATIC_LIBRARY) # # ARCHS: (armv7 armv7s armv7k arm64 arm64_32 i386 x86_64) If specified, will override the default architectures for the given PLATFORM # OS = armv7 armv7s arm64 (if applicable) # OS64 = arm64 (if applicable) # SIMULATOR = i386 # SIMULATOR64 = x86_64 # TVOS = arm64 # SIMULATOR_TVOS = x86_64 (i386 has since long been deprecated) # WATCHOS = armv7k arm64_32 (if applicable) # SIMULATOR_WATCHOS = x86_64 (i386 has since long been deprecated) # # This toolchain defines the following variables for use externally: # # XCODE_VERSION: Version number (not including Build version) of Xcode detected. # SDK_VERSION: Version of SDK being used. # CMAKE_OSX_ARCHITECTURES: Architectures being compiled for (generated from PLATFORM). # # This toolchain defines the following macros for use externally: # # set_xcode_property (TARGET XCODE_PROPERTY XCODE_VALUE XCODE_VARIANT) # A convenience macro for setting xcode specific properties on targets. # Available variants are: All, Release, RelWithDebInfo, Debug, MinSizeRel # example: set_xcode_property (myioslib IPHONEOS_DEPLOYMENT_TARGET "3.1" "all"). # # find_host_package (PROGRAM ARGS) # A macro used to find executable programs on the host system, not within the # environment. Thanks to the android-cmake project for providing the # command. # # ******************************** DEPRECATIONS ******************************* # # IOS_DEPLOYMENT_TARGET: (Deprecated) Alias to DEPLOYMENT_TARGET # CMAKE_IOS_DEVELOPER_ROOT: (Deprecated) Alias to CMAKE_DEVELOPER_ROOT # IOS_PLATFORM: (Deprecated) Alias to PLATFORM # IOS_ARCH: (Deprecated) Alias to ARCHS # # ***************************************************************************** # # Fix for PThread library not in path set(CMAKE_THREAD_LIBS_INIT "-lpthread") set(CMAKE_HAVE_THREADS_LIBRARY 1) set(CMAKE_USE_WIN32_THREADS_INIT 0) set(CMAKE_USE_PTHREADS_INIT 1) # Cache what generator is used set(USED_CMAKE_GENERATOR "${CMAKE_GENERATOR}" CACHE STRING "Expose CMAKE_GENERATOR" FORCE) if(${CMAKE_VERSION} VERSION_GREATER_EQUAL "3.14") set(MODERN_CMAKE YES) message(STATUS "Merging integrated CMake 3.14+ iOS,tvOS,watchOS,macOS toolchain(s) with this toolchain!") endif() # Get the Xcode version being used. execute_process(COMMAND xcodebuild -version OUTPUT_VARIABLE XCODE_VERSION ERROR_QUIET OUTPUT_STRIP_TRAILING_WHITESPACE) string(REGEX MATCH "Xcode [0-9\\.]+" XCODE_VERSION "${XCODE_VERSION}") string(REGEX REPLACE "Xcode ([0-9\\.]+)" "\\1" XCODE_VERSION "${XCODE_VERSION}") message(STATUS "Building with Xcode version: ${XCODE_VERSION}") ######## ALIASES (DEPRECATION WARNINGS) if(DEFINED IOS_PLATFORM) set(PLATFORM ${IOS_PLATFORM}) message(DEPRECATION "IOS_PLATFORM argument is DEPRECATED. Consider using the new PLATFORM argument instead.") endif() if(DEFINED IOS_DEPLOYMENT_TARGET) set(DEPLOYMENT_TARGET ${IOS_DEPLOYMENT_TARGET}) message(DEPRECATION "IOS_DEPLOYMENT_TARGET argument is DEPRECATED. Consider using the new DEPLOYMENT_TARGET argument instead.") endif() if(DEFINED CMAKE_IOS_DEVELOPER_ROOT) set(CMAKE_DEVELOPER_ROOT ${CMAKE_IOS_DEVELOPER_ROOT}) message(DEPRECATION "CMAKE_IOS_DEVELOPER_ROOT argument is DEPRECATED. Consider using the new CMAKE_DEVELOPER_ROOT argument instead.") endif() if(DEFINED IOS_ARCH) set(ARCHS ${IOS_ARCH}) message(DEPRECATION "IOS_ARCH argument is DEPRECATED. Consider using the new ARCHS argument instead.") endif() ######## END ALIASES # Unset the FORCE on cache variables if in try_compile() set(FORCE_CACHE FORCE) get_property(_CMAKE_IN_TRY_COMPILE GLOBAL PROPERTY IN_TRY_COMPILE) if(_CMAKE_IN_TRY_COMPILE) unset(FORCE_CACHE) endif() # Default to building for iPhoneOS if not specified otherwise, and we cannot # determine the platform from the CMAKE_OSX_ARCHITECTURES variable. The use # of CMAKE_OSX_ARCHITECTURES is such that try_compile() projects can correctly # determine the value of PLATFORM from the root project, as # CMAKE_OSX_ARCHITECTURES is propagated to them by CMake. if(NOT DEFINED PLATFORM) if (CMAKE_OSX_ARCHITECTURES) if(CMAKE_OSX_ARCHITECTURES MATCHES ".*arm.*" AND CMAKE_OSX_SYSROOT MATCHES ".*iphoneos.*") set(PLATFORM "OS") elseif(CMAKE_OSX_ARCHITECTURES MATCHES "i386" AND CMAKE_OSX_SYSROOT MATCHES ".*iphonesimulator.*") set(PLATFORM "SIMULATOR") elseif(CMAKE_OSX_ARCHITECTURES MATCHES "x86_64" AND CMAKE_OSX_SYSROOT MATCHES ".*iphonesimulator.*") set(PLATFORM "SIMULATOR64") elseif(CMAKE_OSX_ARCHITECTURES MATCHES "arm64" AND CMAKE_OSX_SYSROOT MATCHES ".*appletvos.*") set(PLATFORM "TVOS") elseif(CMAKE_OSX_ARCHITECTURES MATCHES "x86_64" AND CMAKE_OSX_SYSROOT MATCHES ".*appletvsimulator.*") set(PLATFORM "SIMULATOR_TVOS") elseif(CMAKE_OSX_ARCHITECTURES MATCHES ".*armv7k.*" AND CMAKE_OSX_SYSROOT MATCHES ".*watchos.*") set(PLATFORM "WATCHOS") elseif(CMAKE_OSX_ARCHITECTURES MATCHES "i386" AND CMAKE_OSX_SYSROOT MATCHES ".*watchsimulator.*") set(PLATFORM "SIMULATOR_WATCHOS") endif() endif() if (NOT PLATFORM) set(PLATFORM "OS") endif() endif() set(PLATFORM_INT "${PLATFORM}" CACHE STRING "Type of platform for which the build targets.") # Handle the case where we are targeting iOS and a version above 10.3.4 (32-bit support dropped officially) if(PLATFORM_INT STREQUAL "OS" AND DEPLOYMENT_TARGET VERSION_GREATER_EQUAL 10.3.4) set(PLATFORM_INT "OS64") message(STATUS "Targeting minimum SDK version ${DEPLOYMENT_TARGET}. Dropping 32-bit support.") elseif(PLATFORM_INT STREQUAL "SIMULATOR" AND DEPLOYMENT_TARGET VERSION_GREATER_EQUAL 10.3.4) set(PLATFORM_INT "SIMULATOR64") message(STATUS "Targeting minimum SDK version ${DEPLOYMENT_TARGET}. Dropping 32-bit support.") endif() # Determine the platform name and architectures for use in xcodebuild commands # from the specified PLATFORM name. if(PLATFORM_INT STREQUAL "OS") set(SDK_NAME iphoneos) if(NOT ARCHS) set(ARCHS armv7 armv7s arm64) endif() elseif(PLATFORM_INT STREQUAL "OS64") set(SDK_NAME iphoneos) if(NOT ARCHS) if (XCODE_VERSION VERSION_GREATER 10.0) set(ARCHS arm64) # Add arm64e when Apple have fixed the integration issues with it, libarclite_iphoneos.a is currently missung bitcode markers for example else() set(ARCHS arm64) endif() endif() elseif(PLATFORM_INT STREQUAL "OS64COMBINED") set(SDK_NAME iphoneos) if(MODERN_CMAKE) if(NOT ARCHS) if (XCODE_VERSION VERSION_GREATER 10.0) set(ARCHS arm64 x86_64) # Add arm64e when Apple have fixed the integration issues with it, libarclite_iphoneos.a is currently missung bitcode markers for example else() set(ARCHS arm64 x86_64) endif() endif() else() message(FATAL_ERROR "Please make sure that you are running CMake 3.14+ to make the OS64COMBINED setting work") endif() elseif(PLATFORM_INT STREQUAL "SIMULATOR") set(SDK_NAME iphonesimulator) if(NOT ARCHS) set(ARCHS i386) endif() message(DEPRECATION "SIMULATOR IS DEPRECATED. Consider using SIMULATOR64 instead.") elseif(PLATFORM_INT STREQUAL "SIMULATOR64") set(SDK_NAME iphonesimulator) if(NOT ARCHS) set(ARCHS x86_64) endif() elseif(PLATFORM_INT STREQUAL "TVOS") set(SDK_NAME appletvos) if(NOT ARCHS) set(ARCHS arm64) endif() elseif (PLATFORM_INT STREQUAL "TVOSCOMBINED") set(SDK_NAME appletvos) if(MODERN_CMAKE) if(NOT ARCHS) set(ARCHS arm64 x86_64) endif() else() message(FATAL_ERROR "Please make sure that you are running CMake 3.14+ to make the TVOSCOMBINED setting work") endif() elseif(PLATFORM_INT STREQUAL "SIMULATOR_TVOS") set(SDK_NAME appletvsimulator) if(NOT ARCHS) set(ARCHS x86_64) endif() elseif(PLATFORM_INT STREQUAL "WATCHOS") set(SDK_NAME watchos) if(NOT ARCHS) if (XCODE_VERSION VERSION_GREATER 10.0) set(ARCHS armv7k arm64_32) else() set(ARCHS armv7k) endif() endif() elseif(PLATFORM_INT STREQUAL "WATCHOSCOMBINED") set(SDK_NAME watchos) if(MODERN_CMAKE) if(NOT ARCHS) if (XCODE_VERSION VERSION_GREATER 10.0) set(ARCHS armv7k arm64_32 i386) else() set(ARCHS armv7k i386) endif() endif() else() message(FATAL_ERROR "Please make sure that you are running CMake 3.14+ to make the WATCHOSCOMBINED setting work") endif() elseif(PLATFORM_INT STREQUAL "SIMULATOR_WATCHOS") set(SDK_NAME watchsimulator) if(NOT ARCHS) set(ARCHS i386) endif() else() message(FATAL_ERROR "Invalid PLATFORM: ${PLATFORM_INT}") endif() message(STATUS "Configuring ${SDK_NAME} build for platform: ${PLATFORM_INT}, architecture(s): ${ARCHS}") if(MODERN_CMAKE AND PLATFORM_INT MATCHES ".*COMBINED" AND NOT USED_CMAKE_GENERATOR MATCHES "Xcode") message(FATAL_ERROR "The COMBINED options only work with Xcode generator, -G Xcode") endif() # If user did not specify the SDK root to use, then query xcodebuild for it. execute_process(COMMAND xcodebuild -version -sdk ${SDK_NAME} Path OUTPUT_VARIABLE CMAKE_OSX_SYSROOT_INT ERROR_QUIET OUTPUT_STRIP_TRAILING_WHITESPACE) if (NOT DEFINED CMAKE_OSX_SYSROOT_INT AND NOT DEFINED CMAKE_OSX_SYSROOT) message(SEND_ERROR "Please make sure that Xcode is installed and that the toolchain" "is pointing to the correct path. Please run:" "sudo xcode-select -s /Applications/Xcode.app/Contents/Developer" "and see if that fixes the problem for you.") message(FATAL_ERROR "Invalid CMAKE_OSX_SYSROOT: ${CMAKE_OSX_SYSROOT} " "does not exist.") elseif(DEFINED CMAKE_OSX_SYSROOT) message(STATUS "Using SDK: ${CMAKE_OSX_SYSROOT} for platform: ${PLATFORM_INT} when checking compatibility") elseif(DEFINED CMAKE_OSX_SYSROOT_INT) message(STATUS "Using SDK: ${CMAKE_OSX_SYSROOT_INT} for platform: ${PLATFORM_INT}") set(CMAKE_OSX_SYSROOT "${CMAKE_OSX_SYSROOT_INT}" CACHE INTERNAL "") endif() # Set Xcode property for SDKROOT as well if Xcode generator is used if(USED_CMAKE_GENERATOR MATCHES "Xcode") set(CMAKE_OSX_SYSROOT "${SDK_NAME}" CACHE INTERNAL "") if(NOT DEFINED CMAKE_XCODE_ATTRIBUTE_DEVELOPMENT_TEAM) set(CMAKE_XCODE_ATTRIBUTE_DEVELOPMENT_TEAM 123456789A CACHE INTERNAL "") endif() endif() # Specify minimum version of deployment target. if(NOT DEFINED DEPLOYMENT_TARGET) if (PLATFORM_INT STREQUAL "WATCHOS" OR PLATFORM_INT STREQUAL "SIMULATOR_WATCHOS") # Unless specified, SDK version 2.0 is used by default as minimum target version (watchOS). set(DEPLOYMENT_TARGET "2.0" CACHE STRING "Minimum SDK version to build for." ) else() # Unless specified, SDK version 9.0 is used by default as minimum target version (iOS, tvOS). set(DEPLOYMENT_TARGET "9.0" CACHE STRING "Minimum SDK version to build for." ) endif() message(STATUS "Using the default min-version since DEPLOYMENT_TARGET not provided!") endif() # Use bitcode or not if(NOT DEFINED ENABLE_BITCODE AND NOT ARCHS MATCHES "((^|;|, )(i386|x86_64))+") # Unless specified, enable bitcode support by default message(STATUS "Enabling bitcode support by default. ENABLE_BITCODE not provided!") set(ENABLE_BITCODE TRUE) elseif(NOT DEFINED ENABLE_BITCODE) message(STATUS "Disabling bitcode support by default on simulators. ENABLE_BITCODE not provided for override!") set(ENABLE_BITCODE FALSE) endif() set(ENABLE_BITCODE_INT ${ENABLE_BITCODE} CACHE BOOL "Whether or not to enable bitcode" ${FORCE_CACHE}) # Use ARC or not if(NOT DEFINED ENABLE_ARC) # Unless specified, enable ARC support by default set(ENABLE_ARC TRUE) message(STATUS "Enabling ARC support by default. ENABLE_ARC not provided!") endif() set(ENABLE_ARC_INT ${ENABLE_ARC} CACHE BOOL "Whether or not to enable ARC" ${FORCE_CACHE}) # Use hidden visibility or not if(NOT DEFINED ENABLE_VISIBILITY) # Unless specified, disable symbols visibility by default set(ENABLE_VISIBILITY FALSE) message(STATUS "Hiding symbols visibility by default. ENABLE_VISIBILITY not provided!") endif() set(ENABLE_VISIBILITY_INT ${ENABLE_VISIBILITY} CACHE BOOL "Whether or not to hide symbols (-fvisibility=hidden)" ${FORCE_CACHE}) # Set strict compiler checks or not if(NOT DEFINED ENABLE_STRICT_TRY_COMPILE) # Unless specified, disable strict try_compile() set(ENABLE_STRICT_TRY_COMPILE FALSE) message(STATUS "Using NON-strict compiler checks by default. ENABLE_STRICT_TRY_COMPILE not provided!") endif() set(ENABLE_STRICT_TRY_COMPILE_INT ${ENABLE_STRICT_TRY_COMPILE} CACHE BOOL "Whether or not to use strict compiler checks" ${FORCE_CACHE}) # Get the SDK version information. execute_process(COMMAND xcodebuild -sdk ${CMAKE_OSX_SYSROOT} -version SDKVersion OUTPUT_VARIABLE SDK_VERSION ERROR_QUIET OUTPUT_STRIP_TRAILING_WHITESPACE) # Find the Developer root for the specific iOS platform being compiled for # from CMAKE_OSX_SYSROOT. Should be ../../ from SDK specified in # CMAKE_OSX_SYSROOT. There does not appear to be a direct way to obtain # this information from xcrun or xcodebuild. if (NOT DEFINED CMAKE_DEVELOPER_ROOT AND NOT USED_CMAKE_GENERATOR MATCHES "Xcode") get_filename_component(PLATFORM_SDK_DIR ${CMAKE_OSX_SYSROOT} PATH) get_filename_component(CMAKE_DEVELOPER_ROOT ${PLATFORM_SDK_DIR} PATH) if (NOT DEFINED CMAKE_DEVELOPER_ROOT) message(FATAL_ERROR "Invalid CMAKE_DEVELOPER_ROOT: " "${CMAKE_DEVELOPER_ROOT} does not exist.") endif() endif() # Find the C & C++ compilers for the specified SDK. if(NOT CMAKE_C_COMPILER) execute_process(COMMAND xcrun -sdk ${CMAKE_OSX_SYSROOT} -find clang OUTPUT_VARIABLE CMAKE_C_COMPILER ERROR_QUIET OUTPUT_STRIP_TRAILING_WHITESPACE) message(STATUS "Using C compiler: ${CMAKE_C_COMPILER}") endif() if(NOT CMAKE_CXX_COMPILER) execute_process(COMMAND xcrun -sdk ${CMAKE_OSX_SYSROOT} -find clang++ OUTPUT_VARIABLE CMAKE_CXX_COMPILER ERROR_QUIET OUTPUT_STRIP_TRAILING_WHITESPACE) message(STATUS "Using CXX compiler: ${CMAKE_CXX_COMPILER}") endif() # Find (Apple's) libtool. execute_process(COMMAND xcrun -sdk ${CMAKE_OSX_SYSROOT} -find libtool OUTPUT_VARIABLE BUILD_LIBTOOL ERROR_QUIET OUTPUT_STRIP_TRAILING_WHITESPACE) message(STATUS "Using libtool: ${BUILD_LIBTOOL}") # Configure libtool to be used instead of ar + ranlib to build static libraries. # This is required on Xcode 7+, but should also work on previous versions of # Xcode. set(CMAKE_C_CREATE_STATIC_LIBRARY "${BUILD_LIBTOOL} -static -o <TARGET> <LINK_FLAGS> <OBJECTS> ") set(CMAKE_CXX_CREATE_STATIC_LIBRARY "${BUILD_LIBTOOL} -static -o <TARGET> <LINK_FLAGS> <OBJECTS> ") # Find the toolchain's provided install_name_tool if none is found on the host if(NOT CMAKE_INSTALL_NAME_TOOL) execute_process(COMMAND xcrun -sdk ${CMAKE_OSX_SYSROOT} -find install_name_tool OUTPUT_VARIABLE CMAKE_INSTALL_NAME_TOOL_INT ERROR_QUIET OUTPUT_STRIP_TRAILING_WHITESPACE) set(CMAKE_INSTALL_NAME_TOOL ${CMAKE_INSTALL_NAME_TOOL_INT} CACHE STRING "" ${FORCE_CACHE}) message(STATUS "Using install_name_tool: ${CMAKE_INSTALL_NAME_TOOL}") endif() # Get the version of Darwin (OS X) of the host. execute_process(COMMAND uname -r OUTPUT_VARIABLE CMAKE_HOST_SYSTEM_VERSION ERROR_QUIET OUTPUT_STRIP_TRAILING_WHITESPACE) # CMake 3.14+ support building for iOS, watchOS and tvOS out of the box. if(MODERN_CMAKE) if(SDK_NAME MATCHES "iphone") set(CMAKE_SYSTEM_NAME iOS CACHE INTERNAL "" ${FORCE_CACHE}) elseif(SDK_NAME MATCHES "appletv") set(CMAKE_SYSTEM_NAME tvOS CACHE INTERNAL "" ${FORCE_CACHE}) elseif(SDK_NAME MATCHES "watch") set(CMAKE_SYSTEM_NAME watchOS CACHE INTERNAL "" ${FORCE_CACHE}) endif() # Provide flags for a combined FAT library build on newer CMake versions if(PLATFORM_INT MATCHES ".*COMBINED") set(CMAKE_XCODE_ATTRIBUTE_ONLY_ACTIVE_ARCH NO CACHE INTERNAL "" ${FORCE_CACHE}) set(CMAKE_IOS_INSTALL_COMBINED YES CACHE INTERNAL "" ${FORCE_CACHE}) message(STATUS "Will combine built (static) artifacts into FAT lib...") endif() else() # Legacy code path prior to CMake 3.14 set(CMAKE_SYSTEM_NAME Darwin CACHE INTERNAL "" ${FORCE_CACHE}) endif() # Standard settings. set(CMAKE_SYSTEM_VERSION ${SDK_VERSION} CACHE INTERNAL "") set(UNIX TRUE CACHE BOOL "") set(APPLE TRUE CACHE BOOL "") set(IOS TRUE CACHE BOOL "") set(CMAKE_AR ar CACHE FILEPATH "" FORCE) set(CMAKE_RANLIB ranlib CACHE FILEPATH "" FORCE) set(CMAKE_STRIP strip CACHE FILEPATH "" FORCE) # Set the architectures for which to build. set(CMAKE_OSX_ARCHITECTURES ${ARCHS} CACHE STRING "Build architecture for iOS") # Change the type of target generated for try_compile() so it'll work when cross-compiling, weak compiler checks if(ENABLE_STRICT_TRY_COMPILE_INT) message(STATUS "Using strict compiler checks (default in CMake).") else() set(CMAKE_TRY_COMPILE_TARGET_TYPE STATIC_LIBRARY) endif() # All iOS/Darwin specific settings - some may be redundant. set(CMAKE_SHARED_LIBRARY_PREFIX "lib") set(CMAKE_SHARED_LIBRARY_SUFFIX ".dylib") set(CMAKE_SHARED_MODULE_PREFIX "lib") set(CMAKE_SHARED_MODULE_SUFFIX ".so") set(CMAKE_C_COMPILER_ABI ELF) set(CMAKE_CXX_COMPILER_ABI ELF) set(CMAKE_C_HAS_ISYSROOT 1) set(CMAKE_CXX_HAS_ISYSROOT 1) set(CMAKE_MODULE_EXISTS 1) set(CMAKE_DL_LIBS "") set(CMAKE_C_OSX_COMPATIBILITY_VERSION_FLAG "-compatibility_version ") set(CMAKE_C_OSX_CURRENT_VERSION_FLAG "-current_version ") set(CMAKE_CXX_OSX_COMPATIBILITY_VERSION_FLAG "${CMAKE_C_OSX_COMPATIBILITY_VERSION_FLAG}") set(CMAKE_CXX_OSX_CURRENT_VERSION_FLAG "${CMAKE_C_OSX_CURRENT_VERSION_FLAG}") if(ARCHS MATCHES "((^|;|, )(arm64|arm64e|x86_64))+") set(CMAKE_C_SIZEOF_DATA_PTR 8) set(CMAKE_CXX_SIZEOF_DATA_PTR 8) if(ARCHS MATCHES "((^|;|, )(arm64|arm64e))+") set(CMAKE_SYSTEM_PROCESSOR "aarch64") else() set(CMAKE_SYSTEM_PROCESSOR "x86_64") endif() message(STATUS "Using a data_ptr size of 8") else() set(CMAKE_C_SIZEOF_DATA_PTR 4) set(CMAKE_CXX_SIZEOF_DATA_PTR 4) set(CMAKE_SYSTEM_PROCESSOR "arm") message(STATUS "Using a data_ptr size of 4") endif() message(STATUS "Building for minimum ${SDK_NAME} version: ${DEPLOYMENT_TARGET}" " (SDK version: ${SDK_VERSION})") # Note that only Xcode 7+ supports the newer more specific: # -m${SDK_NAME}-version-min flags, older versions of Xcode use: # -m(ios/ios-simulator)-version-min instead. if(PLATFORM_INT STREQUAL "OS" OR PLATFORM_INT STREQUAL "OS64") if(XCODE_VERSION VERSION_LESS 7.0) set(SDK_NAME_VERSION_FLAGS "-mios-version-min=${DEPLOYMENT_TARGET}") else() # Xcode 7.0+ uses flags we can build directly from SDK_NAME. set(SDK_NAME_VERSION_FLAGS "-m${SDK_NAME}-version-min=${DEPLOYMENT_TARGET}") endif() elseif(PLATFORM_INT STREQUAL "TVOS") set(SDK_NAME_VERSION_FLAGS "-mtvos-version-min=${DEPLOYMENT_TARGET}") elseif(PLATFORM_INT STREQUAL "SIMULATOR_TVOS") set(SDK_NAME_VERSION_FLAGS "-mtvos-simulator-version-min=${DEPLOYMENT_TARGET}") elseif(PLATFORM_INT STREQUAL "WATCHOS") set(SDK_NAME_VERSION_FLAGS "-mwatchos-version-min=${DEPLOYMENT_TARGET}") elseif(PLATFORM_INT STREQUAL "SIMULATOR_WATCHOS") set(SDK_NAME_VERSION_FLAGS "-mwatchos-simulator-version-min=${DEPLOYMENT_TARGET}") else() # SIMULATOR or SIMULATOR64 both use -mios-simulator-version-min. set(SDK_NAME_VERSION_FLAGS "-mios-simulator-version-min=${DEPLOYMENT_TARGET}") endif() message(STATUS "Version flags set to: ${SDK_NAME_VERSION_FLAGS}") set(CMAKE_OSX_DEPLOYMENT_TARGET ${DEPLOYMENT_TARGET} CACHE STRING "Set CMake deployment target" ${FORCE_CACHE}) if(ENABLE_BITCODE_INT) set(BITCODE "-fembed-bitcode") set(CMAKE_XCODE_ATTRIBUTE_BITCODE_GENERATION_MODE bitcode CACHE INTERNAL "") message(STATUS "Enabling bitcode support.") else() set(BITCODE "") set(CMAKE_XCODE_ATTRIBUTE_ENABLE_BITCODE NO CACHE INTERNAL "") message(STATUS "Disabling bitcode support.") endif() if(ENABLE_ARC_INT) set(FOBJC_ARC "-fobjc-arc") set(CMAKE_XCODE_ATTRIBUTE_CLANG_ENABLE_OBJC_ARC YES CACHE INTERNAL "") message(STATUS "Enabling ARC support.") else() set(FOBJC_ARC "-fno-objc-arc") set(CMAKE_XCODE_ATTRIBUTE_CLANG_ENABLE_OBJC_ARC NO CACHE INTERNAL "") message(STATUS "Disabling ARC support.") endif() if(NOT ENABLE_VISIBILITY_INT) set(VISIBILITY "-fvisibility=hidden") set(CMAKE_XCODE_ATTRIBUTE_GCC_SYMBOLS_PRIVATE_EXTERN YES CACHE INTERNAL "") message(STATUS "Hiding symbols (-fvisibility=hidden).") else() set(VISIBILITY "") set(CMAKE_XCODE_ATTRIBUTE_GCC_SYMBOLS_PRIVATE_EXTERN NO CACHE INTERNAL "") endif() #Check if Xcode generator is used, since that will handle these flags automagically if(USED_CMAKE_GENERATOR MATCHES "Xcode") message(STATUS "Not setting any manual command-line buildflags, since Xcode is selected as generator.") else() set(CMAKE_C_FLAGS "${SDK_NAME_VERSION_FLAGS} ${BITCODE} -fobjc-abi-version=2 ${FOBJC_ARC} ${CMAKE_C_FLAGS}") # Hidden visibilty is required for C++ on iOS. set(CMAKE_CXX_FLAGS "${SDK_NAME_VERSION_FLAGS} ${BITCODE} ${VISIBILITY} -fvisibility-inlines-hidden -fobjc-abi-version=2 ${FOBJC_ARC} ${CMAKE_CXX_FLAGS}") set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS} -O0 -g ${CMAKE_CXX_FLAGS_DEBUG}") set(CMAKE_CXX_FLAGS_MINSIZEREL "${CMAKE_CXX_FLAGS} -DNDEBUG -Os -ffast-math ${CMAKE_CXX_FLAGS_MINSIZEREL}") set(CMAKE_CXX_FLAGS_RELWITHDEBINFO "${CMAKE_CXX_FLAGS} -DNDEBUG -O2 -g -ffast-math ${CMAKE_CXX_FLAGS_RELWITHDEBINFO}") set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS} -DNDEBUG -O3 -ffast-math ${CMAKE_CXX_FLAGS_RELEASE}") set(CMAKE_C_LINK_FLAGS "${SDK_NAME_VERSION_FLAGS} -Wl,-search_paths_first ${CMAKE_C_LINK_FLAGS}") set(CMAKE_CXX_LINK_FLAGS "${SDK_NAME_VERSION_FLAGS} -Wl,-search_paths_first ${CMAKE_CXX_LINK_FLAGS}") # In order to ensure that the updated compiler flags are used in try_compile() # tests, we have to forcibly set them in the CMake cache, not merely set them # in the local scope. list(APPEND VARS_TO_FORCE_IN_CACHE CMAKE_C_FLAGS CMAKE_CXX_FLAGS CMAKE_CXX_FLAGS_DEBUG CMAKE_CXX_FLAGS_RELWITHDEBINFO CMAKE_CXX_FLAGS_MINSIZEREL CMAKE_CXX_FLAGS_RELEASE CMAKE_C_LINK_FLAGS CMAKE_CXX_LINK_FLAGS) foreach(VAR_TO_FORCE ${VARS_TO_FORCE_IN_CACHE}) set(${VAR_TO_FORCE} "${${VAR_TO_FORCE}}" CACHE STRING "") endforeach() endif() set(CMAKE_PLATFORM_HAS_INSTALLNAME 1) set(CMAKE_SHARED_LINKER_FLAGS "-rpath @executable_path/Frameworks -rpath @loader_path/Frameworks") set(CMAKE_SHARED_LIBRARY_CREATE_C_FLAGS "-dynamiclib -Wl,-headerpad_max_install_names") set(CMAKE_SHARED_MODULE_CREATE_C_FLAGS "-bundle -Wl,-headerpad_max_install_names") set(CMAKE_SHARED_MODULE_LOADER_C_FLAG "-Wl,-bundle_loader,") set(CMAKE_SHARED_MODULE_LOADER_CXX_FLAG "-Wl,-bundle_loader,") set(CMAKE_FIND_LIBRARY_SUFFIXES ".tbd" ".dylib" ".so" ".a") set(CMAKE_SHARED_LIBRARY_SONAME_C_FLAG "-install_name") # Set the find root to the iOS developer roots and to user defined paths. set(CMAKE_FIND_ROOT_PATH ${CMAKE_OSX_SYSROOT_INT} ${CMAKE_PREFIX_PATH} CACHE STRING "Root path that will be prepended to all search paths") # Default to searching for frameworks first. set(CMAKE_FIND_FRAMEWORK FIRST) # Set up the default search directories for frameworks. set(CMAKE_FRAMEWORK_PATH ${CMAKE_DEVELOPER_ROOT}/Library/PrivateFrameworks ${CMAKE_OSX_SYSROOT_INT}/System/Library/Frameworks ${CMAKE_FRAMEWORK_PATH} CACHE STRING "Frameworks search paths" ${FORCE_CACHE}) # By default, search both the specified iOS SDK and the remainder of the host filesystem. if(NOT CMAKE_FIND_ROOT_PATH_MODE_PROGRAM) set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM BOTH CACHE STRING "" ${FORCE_CACHE}) endif() if(NOT CMAKE_FIND_ROOT_PATH_MODE_LIBRARY) set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY CACHE STRING "" ${FORCE_CACHE}) endif() if(NOT CMAKE_FIND_ROOT_PATH_MODE_INCLUDE) set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY CACHE STRING "" ${FORCE_CACHE}) endif() if(NOT CMAKE_FIND_ROOT_PATH_MODE_PACKAGE) set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY CACHE STRING "" ${FORCE_CACHE}) endif() # # Some helper-macros below to simplify and beautify the CMakeFile # # This little macro lets you set any Xcode specific property. macro(set_xcode_property TARGET XCODE_PROPERTY XCODE_VALUE XCODE_RELVERSION) set(XCODE_RELVERSION_I "${XCODE_RELVERSION}") if(XCODE_RELVERSION_I STREQUAL "All") set_property(TARGET ${TARGET} PROPERTY XCODE_ATTRIBUTE_${XCODE_PROPERTY} "${XCODE_VALUE}") else() set_property(TARGET ${TARGET} PROPERTY XCODE_ATTRIBUTE_${XCODE_PROPERTY}[variant=${XCODE_RELVERSION_I}] "${XCODE_VALUE}") endif() endmacro(set_xcode_property) # This macro lets you find executable programs on the host system. macro(find_host_package) set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY NEVER) set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE NEVER) set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE NEVER) set(IOS FALSE) find_package(${ARGN}) set(IOS TRUE) set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM BOTH) set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY BOTH) set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE BOTH) set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE BOTH) endmacro(find_host_package)
xLua/build/cmake/ios.toolchain.cmake/0
{ "file_path": "xLua/build/cmake/ios.toolchain.cmake", "repo_id": "xLua", "token_count": 11714 }
2,013
h3 code { font-family: inherit ; font-size: inherit ; } pre, code { font-size: 12pt ; } span.apii { float: right ; font-family: inherit ; font-style: normal ; font-size: small ; color: gray ; } p+h1, ul+h1 { padding-top: 0.4em ; padding-bottom: 0.4em ; padding-left: 30px ; margin-left: -30px ; background-color: #E0E0FF ; }
xLua/build/lua-5.1.5/doc/manual.css/0
{ "file_path": "xLua/build/lua-5.1.5/doc/manual.css", "repo_id": "xLua", "token_count": 153 }
2,014
/* ** $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 */ #include <ctype.h> #include <errno.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> /* 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 "lua.h" #include "lauxlib.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) /* ** {====================================================== ** 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 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_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); } 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) { 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); 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)) { /* 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)) { /* 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 ** ======================================================= */ 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 (feof(lf->f)) return NULL; *size = 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 = 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 = stdin; } else { lua_pushfstring(L, "@%s", filename); lf.f = fopen(filename, "r"); if (lf.f == NULL) return errfile(L, "open", fnameindex); } c = getc(lf.f); if (c == '#') { /* Unix exec. file? */ lf.extraline = 1; while ((c = getc(lf.f)) != EOF && c != '\n') ; /* skip first line */ if (c == '\n') c = getc(lf.f); } if (c == LUA_SIGNATURE[0] && filename) { /* binary file? */ lf.f = freopen(filename, "rb", lf.f); /* reopen in binary mode */ if (lf.f == NULL) return errfile(L, "reopen", fnameindex); /* skip eventual `#!...' */ while ((c = getc(lf.f)) != EOF && c != LUA_SIGNATURE[0]) ; lf.extraline = 0; } ungetc(c, lf.f); status = lua_load(L, getF, &lf, lua_tostring(L, -1)); readstatus = ferror(lf.f); if (filename) 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; } 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 (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 void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize) { (void)ud; (void)osize; if (nsize == 0) { free(ptr); return NULL; } else return realloc(ptr, nsize); } static int panic (lua_State *L) { (void)L; /* to avoid warnings */ fprintf(stderr, "PANIC: unprotected error in call to Lua API (%s)\n", lua_tostring(L, -1)); return 0; } LUALIB_API lua_State *luaL_newstate (void) { lua_State *L = lua_newstate(l_alloc, NULL); if (L) lua_atpanic(L, &panic); return L; }
xLua/build/lua-5.1.5/src/lauxlib.c/0
{ "file_path": "xLua/build/lua-5.1.5/src/lauxlib.c", "repo_id": "xLua", "token_count": 7860 }
2,015
/* ** $Id: liolib.c,v 2.73.1.4 2010/05/14 15:33:51 roberto Exp $ ** Standard I/O (and system) library ** See Copyright Notice in lua.h */ #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define liolib_c #define LUA_LIB #include "lua.h" #include "lauxlib.h" #include "lualib.h" #define IO_INPUT 1 #define IO_OUTPUT 2 static const char *const fnames[] = {"input", "output"}; static int pushresult (lua_State *L, int i, const char *filename) { int en = errno; /* calls to Lua API may change this value */ if (i) { lua_pushboolean(L, 1); return 1; } else { lua_pushnil(L); if (filename) lua_pushfstring(L, "%s: %s", filename, strerror(en)); else lua_pushfstring(L, "%s", strerror(en)); lua_pushinteger(L, en); return 3; } } static void fileerror (lua_State *L, int arg, const char *filename) { lua_pushfstring(L, "%s: %s", filename, strerror(errno)); luaL_argerror(L, arg, lua_tostring(L, -1)); } #define tofilep(L) ((FILE **)luaL_checkudata(L, 1, LUA_FILEHANDLE)) static int io_type (lua_State *L) { void *ud; luaL_checkany(L, 1); ud = lua_touserdata(L, 1); lua_getfield(L, LUA_REGISTRYINDEX, LUA_FILEHANDLE); if (ud == NULL || !lua_getmetatable(L, 1) || !lua_rawequal(L, -2, -1)) lua_pushnil(L); /* not a file */ else if (*((FILE **)ud) == NULL) lua_pushliteral(L, "closed file"); else lua_pushliteral(L, "file"); return 1; } static FILE *tofile (lua_State *L) { FILE **f = tofilep(L); if (*f == NULL) luaL_error(L, "attempt to use a closed file"); return *f; } /* ** When creating file handles, always creates a `closed' file handle ** before opening the actual file; so, if there is a memory error, the ** file is not left opened. */ static FILE **newfile (lua_State *L) { FILE **pf = (FILE **)lua_newuserdata(L, sizeof(FILE *)); *pf = NULL; /* file handle is currently `closed' */ luaL_getmetatable(L, LUA_FILEHANDLE); lua_setmetatable(L, -2); return pf; } /* ** function to (not) close the standard files stdin, stdout, and stderr */ static int io_noclose (lua_State *L) { lua_pushnil(L); lua_pushliteral(L, "cannot close standard file"); return 2; } /* ** function to close 'popen' files */ static int io_pclose (lua_State *L) { #if defined(WINAPI_FAMILY_PARTITION) return luaL_error(L, "unsupport api in uwp platform"); #else FILE **p = tofilep(L); int ok = lua_pclose(L, *p); *p = NULL; return pushresult(L, ok, NULL); #endif } /* ** function to close regular files */ static int io_fclose (lua_State *L) { FILE **p = tofilep(L); int ok = (fclose(*p) == 0); *p = NULL; return pushresult(L, ok, NULL); } static int aux_close (lua_State *L) { lua_getfenv(L, 1); lua_getfield(L, -1, "__close"); return (lua_tocfunction(L, -1))(L); } static int io_close (lua_State *L) { if (lua_isnone(L, 1)) lua_rawgeti(L, LUA_ENVIRONINDEX, IO_OUTPUT); tofile(L); /* make sure argument is a file */ return aux_close(L); } static int io_gc (lua_State *L) { FILE *f = *tofilep(L); /* ignore closed files */ if (f != NULL) aux_close(L); return 0; } static int io_tostring (lua_State *L) { FILE *f = *tofilep(L); if (f == NULL) lua_pushliteral(L, "file (closed)"); else lua_pushfstring(L, "file (%p)", f); return 1; } static int io_open (lua_State *L) { const char *filename = luaL_checkstring(L, 1); const char *mode = luaL_optstring(L, 2, "r"); FILE **pf = newfile(L); *pf = fopen(filename, mode); return (*pf == NULL) ? pushresult(L, 0, filename) : 1; } /* ** this function has a separated environment, which defines the ** correct __close for 'popen' files */ static int io_popen (lua_State *L) { #if defined(WINAPI_FAMILY_PARTITION) return luaL_error(L, "unsupport api in uwp platform"); #else const char *filename = luaL_checkstring(L, 1); const char *mode = luaL_optstring(L, 2, "r"); FILE **pf = newfile(L); *pf = lua_popen(L, filename, mode); return (*pf == NULL) ? pushresult(L, 0, filename) : 1; #endif } static int io_tmpfile (lua_State *L) { FILE **pf = newfile(L); *pf = tmpfile(); return (*pf == NULL) ? pushresult(L, 0, NULL) : 1; } static FILE *getiofile (lua_State *L, int findex) { FILE *f; lua_rawgeti(L, LUA_ENVIRONINDEX, findex); f = *(FILE **)lua_touserdata(L, -1); if (f == NULL) luaL_error(L, "standard %s file is closed", fnames[findex - 1]); return f; } static int g_iofile (lua_State *L, int f, const char *mode) { if (!lua_isnoneornil(L, 1)) { const char *filename = lua_tostring(L, 1); if (filename) { FILE **pf = newfile(L); *pf = fopen(filename, mode); if (*pf == NULL) fileerror(L, 1, filename); } else { tofile(L); /* check that it's a valid file handle */ lua_pushvalue(L, 1); } lua_rawseti(L, LUA_ENVIRONINDEX, f); } /* return current value */ lua_rawgeti(L, LUA_ENVIRONINDEX, f); return 1; } static int io_input (lua_State *L) { return g_iofile(L, IO_INPUT, "r"); } static int io_output (lua_State *L) { return g_iofile(L, IO_OUTPUT, "w"); } static int io_readline (lua_State *L); static void aux_lines (lua_State *L, int idx, int toclose) { lua_pushvalue(L, idx); lua_pushboolean(L, toclose); /* close/not close file when finished */ lua_pushcclosure(L, io_readline, 2); } static int f_lines (lua_State *L) { tofile(L); /* check that it's a valid file handle */ aux_lines(L, 1, 0); return 1; } static int io_lines (lua_State *L) { if (lua_isnoneornil(L, 1)) { /* no arguments? */ /* will iterate over default input */ lua_rawgeti(L, LUA_ENVIRONINDEX, IO_INPUT); return f_lines(L); } else { const char *filename = luaL_checkstring(L, 1); FILE **pf = newfile(L); *pf = fopen(filename, "r"); if (*pf == NULL) fileerror(L, 1, filename); aux_lines(L, lua_gettop(L), 1); return 1; } } /* ** {====================================================== ** READ ** ======================================================= */ static int read_number (lua_State *L, FILE *f) { lua_Number d; if (fscanf(f, LUA_NUMBER_SCAN, &d) == 1) { lua_pushnumber(L, d); return 1; } else { lua_pushnil(L); /* "result" to be removed */ return 0; /* read fails */ } } static int test_eof (lua_State *L, FILE *f) { int c = getc(f); ungetc(c, f); lua_pushlstring(L, NULL, 0); return (c != EOF); } static int read_line (lua_State *L, FILE *f) { luaL_Buffer b; luaL_buffinit(L, &b); for (;;) { size_t l; char *p = luaL_prepbuffer(&b); if (fgets(p, LUAL_BUFFERSIZE, f) == NULL) { /* eof? */ luaL_pushresult(&b); /* close buffer */ return (lua_objlen(L, -1) > 0); /* check whether read something */ } l = strlen(p); if (l == 0 || p[l-1] != '\n') luaL_addsize(&b, l); else { luaL_addsize(&b, l - 1); /* do not include `eol' */ luaL_pushresult(&b); /* close buffer */ return 1; /* read at least an `eol' */ } } } static int read_chars (lua_State *L, FILE *f, size_t n) { size_t rlen; /* how much to read */ size_t nr; /* number of chars actually read */ luaL_Buffer b; luaL_buffinit(L, &b); rlen = LUAL_BUFFERSIZE; /* try to read that much each time */ do { char *p = luaL_prepbuffer(&b); if (rlen > n) rlen = n; /* cannot read more than asked */ nr = fread(p, sizeof(char), rlen, f); luaL_addsize(&b, nr); n -= nr; /* still have to read `n' chars */ } while (n > 0 && nr == rlen); /* until end of count or eof */ luaL_pushresult(&b); /* close buffer */ return (n == 0 || lua_objlen(L, -1) > 0); } static int g_read (lua_State *L, FILE *f, int first) { int nargs = lua_gettop(L) - 1; int success; int n; clearerr(f); if (nargs == 0) { /* no arguments? */ success = read_line(L, f); n = first+1; /* to return 1 result */ } else { /* ensure stack space for all results and for auxlib's buffer */ luaL_checkstack(L, nargs+LUA_MINSTACK, "too many arguments"); success = 1; for (n = first; nargs-- && success; n++) { if (lua_type(L, n) == LUA_TNUMBER) { size_t l = (size_t)lua_tointeger(L, n); success = (l == 0) ? test_eof(L, f) : read_chars(L, f, l); } else { const char *p = lua_tostring(L, n); luaL_argcheck(L, p && p[0] == '*', n, "invalid option"); switch (p[1]) { case 'n': /* number */ success = read_number(L, f); break; case 'l': /* line */ success = read_line(L, f); break; case 'a': /* file */ read_chars(L, f, ~((size_t)0)); /* read MAX_SIZE_T chars */ success = 1; /* always success */ break; default: return luaL_argerror(L, n, "invalid format"); } } } } if (ferror(f)) return pushresult(L, 0, NULL); if (!success) { lua_pop(L, 1); /* remove last result */ lua_pushnil(L); /* push nil instead */ } return n - first; } static int io_read (lua_State *L) { return g_read(L, getiofile(L, IO_INPUT), 1); } static int f_read (lua_State *L) { return g_read(L, tofile(L), 2); } static int io_readline (lua_State *L) { FILE *f = *(FILE **)lua_touserdata(L, lua_upvalueindex(1)); int sucess; if (f == NULL) /* file is already closed? */ luaL_error(L, "file is already closed"); sucess = read_line(L, f); if (ferror(f)) return luaL_error(L, "%s", strerror(errno)); if (sucess) return 1; else { /* EOF */ if (lua_toboolean(L, lua_upvalueindex(2))) { /* generator created file? */ lua_settop(L, 0); lua_pushvalue(L, lua_upvalueindex(1)); aux_close(L); /* close it */ } return 0; } } /* }====================================================== */ static int g_write (lua_State *L, FILE *f, int arg) { int nargs = lua_gettop(L) - 1; int status = 1; for (; nargs--; arg++) { if (lua_type(L, arg) == LUA_TNUMBER) { /* optimization: could be done exactly as for strings */ status = status && fprintf(f, LUA_NUMBER_FMT, lua_tonumber(L, arg)) > 0; } else { size_t l; const char *s = luaL_checklstring(L, arg, &l); status = status && (fwrite(s, sizeof(char), l, f) == l); } } return pushresult(L, status, NULL); } static int io_write (lua_State *L) { return g_write(L, getiofile(L, IO_OUTPUT), 1); } static int f_write (lua_State *L) { return g_write(L, tofile(L), 2); } static int f_seek (lua_State *L) { static const int mode[] = {SEEK_SET, SEEK_CUR, SEEK_END}; static const char *const modenames[] = {"set", "cur", "end", NULL}; FILE *f = tofile(L); int op = luaL_checkoption(L, 2, "cur", modenames); long offset = luaL_optlong(L, 3, 0); op = fseek(f, offset, mode[op]); if (op) return pushresult(L, 0, NULL); /* error */ else { lua_pushinteger(L, ftell(f)); return 1; } } static int f_setvbuf (lua_State *L) { static const int mode[] = {_IONBF, _IOFBF, _IOLBF}; static const char *const modenames[] = {"no", "full", "line", NULL}; FILE *f = tofile(L); int op = luaL_checkoption(L, 2, NULL, modenames); lua_Integer sz = luaL_optinteger(L, 3, LUAL_BUFFERSIZE); int res = setvbuf(f, NULL, mode[op], sz); return pushresult(L, res == 0, NULL); } static int io_flush (lua_State *L) { return pushresult(L, fflush(getiofile(L, IO_OUTPUT)) == 0, NULL); } static int f_flush (lua_State *L) { return pushresult(L, fflush(tofile(L)) == 0, NULL); } static const luaL_Reg iolib[] = { {"close", io_close}, {"flush", io_flush}, {"input", io_input}, {"lines", io_lines}, {"open", io_open}, {"output", io_output}, {"popen", io_popen}, {"read", io_read}, {"tmpfile", io_tmpfile}, {"type", io_type}, {"write", io_write}, {NULL, NULL} }; static const luaL_Reg flib[] = { {"close", io_close}, {"flush", f_flush}, {"lines", f_lines}, {"read", f_read}, {"seek", f_seek}, {"setvbuf", f_setvbuf}, {"write", f_write}, {"__gc", io_gc}, {"__tostring", io_tostring}, {NULL, NULL} }; static void createmeta (lua_State *L) { luaL_newmetatable(L, LUA_FILEHANDLE); /* create metatable for file handles */ lua_pushvalue(L, -1); /* push metatable */ lua_setfield(L, -2, "__index"); /* metatable.__index = metatable */ luaL_register(L, NULL, flib); /* file methods */ } static void createstdfile (lua_State *L, FILE *f, int k, const char *fname) { *newfile(L) = f; if (k > 0) { lua_pushvalue(L, -1); lua_rawseti(L, LUA_ENVIRONINDEX, k); } lua_pushvalue(L, -2); /* copy environment */ lua_setfenv(L, -2); /* set it */ lua_setfield(L, -3, fname); } static void newfenv (lua_State *L, lua_CFunction cls) { lua_createtable(L, 0, 1); lua_pushcfunction(L, cls); lua_setfield(L, -2, "__close"); } LUALIB_API int luaopen_io (lua_State *L) { createmeta(L); /* create (private) environment (with fields IO_INPUT, IO_OUTPUT, __close) */ newfenv(L, io_fclose); lua_replace(L, LUA_ENVIRONINDEX); /* open library */ luaL_register(L, LUA_IOLIBNAME, iolib); /* create (and set) default files */ newfenv(L, io_noclose); /* close function for default files */ createstdfile(L, stdin, IO_INPUT, "stdin"); createstdfile(L, stdout, IO_OUTPUT, "stdout"); createstdfile(L, stderr, 0, "stderr"); lua_pop(L, 1); /* pop environment for default files */ lua_getfield(L, -1, "popen"); newfenv(L, io_pclose); /* create environment for 'popen' */ lua_setfenv(L, -2); /* set fenv for 'popen' */ lua_pop(L, 1); /* pop 'popen' */ return 1; }
xLua/build/lua-5.1.5/src/liolib.c/0
{ "file_path": "xLua/build/lua-5.1.5/src/liolib.c", "repo_id": "xLua", "token_count": 5999 }
2,016
/* ** $Id: lstate.h,v 2.24.1.2 2008/01/03 15:20:39 roberto Exp $ ** Global State ** See Copyright Notice in lua.h */ #ifndef lstate_h #define lstate_h #include "lua.h" #include "lobject.h" #include "ltm.h" #include "lzio.h" struct lua_longjmp; /* defined in ldo.c */ /* table of globals */ #define gt(L) (&L->l_gt) /* registry */ #define registry(L) (&G(L)->l_registry) /* extra stack space to handle TM calls and some other extras */ #define EXTRA_STACK 5 #define BASIC_CI_SIZE 8 #define BASIC_STACK_SIZE (2*LUA_MINSTACK) typedef struct stringtable { GCObject **hash; lu_int32 nuse; /* number of elements */ int size; } stringtable; /* ** informations about a call */ typedef struct CallInfo { StkId base; /* base for this function */ StkId func; /* function index in the stack */ StkId top; /* top for this function */ const Instruction *savedpc; int nresults; /* expected number of results from this function */ int tailcalls; /* number of tail calls lost under this entry */ } CallInfo; #define curr_func(L) (clvalue(L->ci->func)) #define ci_func(ci) (clvalue((ci)->func)) #define f_isLua(ci) (!ci_func(ci)->c.isC) #define isLua(ci) (ttisfunction((ci)->func) && f_isLua(ci)) /* ** `global state', shared by all threads of this state */ typedef struct global_State { stringtable strt; /* hash table for strings */ lua_Alloc frealloc; /* function to reallocate memory */ void *ud; /* auxiliary data to `frealloc' */ lu_byte currentwhite; lu_byte gcstate; /* state of garbage collector */ int sweepstrgc; /* position of sweep in `strt' */ GCObject *rootgc; /* list of all collectable objects */ GCObject **sweepgc; /* position of sweep in `rootgc' */ GCObject *gray; /* list of gray objects */ GCObject *grayagain; /* list of objects to be traversed atomically */ GCObject *weak; /* list of weak tables (to be cleared) */ GCObject *tmudata; /* last element of list of userdata to be GC */ Mbuffer buff; /* temporary buffer for string concatentation */ lu_mem GCthreshold; lu_mem totalbytes; /* number of bytes currently allocated */ lu_mem estimate; /* an estimate of number of bytes actually in use */ lu_mem gcdept; /* how much GC is `behind schedule' */ int gcpause; /* size of pause between successive GCs */ int gcstepmul; /* GC `granularity' */ lua_CFunction panic; /* to be called in unprotected errors */ TValue l_registry; struct lua_State *mainthread; UpVal uvhead; /* head of double-linked list of all open upvalues */ struct Table *mt[NUM_TAGS]; /* metatables for basic types */ TString *tmname[TM_N]; /* array with tag-method names */ } global_State; /* ** `per thread' state */ struct lua_State { CommonHeader; lu_byte status; StkId top; /* first free slot in the stack */ StkId base; /* base of current function */ global_State *l_G; CallInfo *ci; /* call info for current function */ const Instruction *savedpc; /* `savedpc' of current function */ StkId stack_last; /* last free slot in the stack */ StkId stack; /* stack base */ CallInfo *end_ci; /* points after end of ci array*/ CallInfo *base_ci; /* array of CallInfo's */ int stacksize; int size_ci; /* size of array `base_ci' */ unsigned short nCcalls; /* number of nested C calls */ unsigned short baseCcalls; /* nested C calls when resuming coroutine */ lu_byte hookmask; lu_byte allowhook; int basehookcount; int hookcount; lua_Hook hook; TValue l_gt; /* table of globals */ TValue env; /* temporary place for environments */ GCObject *openupval; /* list of open upvalues in this stack */ GCObject *gclist; struct lua_longjmp *errorJmp; /* current error recover point */ ptrdiff_t errfunc; /* current error handling function (stack index) */ }; #define G(L) (L->l_G) /* ** Union of all collectable objects */ union GCObject { GCheader gch; union TString ts; union Udata u; union Closure cl; struct Table h; struct Proto p; struct UpVal uv; struct lua_State th; /* thread */ }; /* macros to convert a GCObject into a specific value */ #define rawgco2ts(o) check_exp((o)->gch.tt == LUA_TSTRING, &((o)->ts)) #define gco2ts(o) (&rawgco2ts(o)->tsv) #define rawgco2u(o) check_exp((o)->gch.tt == LUA_TUSERDATA, &((o)->u)) #define gco2u(o) (&rawgco2u(o)->uv) #define gco2cl(o) check_exp((o)->gch.tt == LUA_TFUNCTION, &((o)->cl)) #define gco2h(o) check_exp((o)->gch.tt == LUA_TTABLE, &((o)->h)) #define gco2p(o) check_exp((o)->gch.tt == LUA_TPROTO, &((o)->p)) #define gco2uv(o) check_exp((o)->gch.tt == LUA_TUPVAL, &((o)->uv)) #define ngcotouv(o) \ check_exp((o) == NULL || (o)->gch.tt == LUA_TUPVAL, &((o)->uv)) #define gco2th(o) check_exp((o)->gch.tt == LUA_TTHREAD, &((o)->th)) /* macro to convert any Lua object into a GCObject */ #define obj2gco(v) (cast(GCObject *, (v))) LUAI_FUNC lua_State *luaE_newthread (lua_State *L); LUAI_FUNC void luaE_freethread (lua_State *L, lua_State *L1); #endif
xLua/build/lua-5.1.5/src/lstate.h/0
{ "file_path": "xLua/build/lua-5.1.5/src/lstate.h", "repo_id": "xLua", "token_count": 1898 }
2,017
/* ** $Id: lvm.c,v 2.63.1.5 2011/08/17 20:43:11 roberto Exp $ ** Lua virtual machine ** See Copyright Notice in lua.h */ #include <stdio.h> #include <stdlib.h> #include <string.h> #define lvm_c #define LUA_CORE #include "lua.h" #include "ldebug.h" #include "ldo.h" #include "lfunc.h" #include "lgc.h" #include "lobject.h" #include "lopcodes.h" #include "lstate.h" #include "lstring.h" #include "ltable.h" #include "ltm.h" #include "lvm.h" /* limit for table tag-method chains (to avoid loops) */ #define MAXTAGLOOP 100 const TValue *luaV_tonumber (const TValue *obj, TValue *n) { lua_Number num; if (ttisnumber(obj)) return obj; if (ttisstring(obj) && luaO_str2d(svalue(obj), &num)) { setnvalue(n, num); return n; } else return NULL; } int luaV_tostring (lua_State *L, StkId obj) { if (!ttisnumber(obj)) return 0; else { char s[LUAI_MAXNUMBER2STR]; lua_Number n = nvalue(obj); lua_number2str(s, n); setsvalue2s(L, obj, luaS_new(L, s)); return 1; } } static void traceexec (lua_State *L, const Instruction *pc) { lu_byte mask = L->hookmask; const Instruction *oldpc = L->savedpc; L->savedpc = pc; if ((mask & LUA_MASKCOUNT) && L->hookcount == 0) { resethookcount(L); luaD_callhook(L, LUA_HOOKCOUNT, -1); } if (mask & LUA_MASKLINE) { Proto *p = ci_func(L->ci)->l.p; int npc = pcRel(pc, p); int newline = getline(p, npc); /* call linehook when enter a new function, when jump back (loop), or when enter a new line */ if (npc == 0 || pc <= oldpc || newline != getline(p, pcRel(oldpc, p))) luaD_callhook(L, LUA_HOOKLINE, newline); } } static void callTMres (lua_State *L, StkId res, const TValue *f, const TValue *p1, const TValue *p2) { ptrdiff_t result = savestack(L, res); setobj2s(L, L->top, f); /* push function */ setobj2s(L, L->top+1, p1); /* 1st argument */ setobj2s(L, L->top+2, p2); /* 2nd argument */ luaD_checkstack(L, 3); L->top += 3; luaD_call(L, L->top - 3, 1); res = restorestack(L, result); L->top--; setobjs2s(L, res, L->top); } static void callTM (lua_State *L, const TValue *f, const TValue *p1, const TValue *p2, const TValue *p3) { setobj2s(L, L->top, f); /* push function */ setobj2s(L, L->top+1, p1); /* 1st argument */ setobj2s(L, L->top+2, p2); /* 2nd argument */ setobj2s(L, L->top+3, p3); /* 3th argument */ luaD_checkstack(L, 4); L->top += 4; luaD_call(L, L->top - 4, 0); } void luaV_gettable (lua_State *L, const TValue *t, TValue *key, StkId val) { int loop; for (loop = 0; loop < MAXTAGLOOP; loop++) { const TValue *tm; if (ttistable(t)) { /* `t' is a table? */ Table *h = hvalue(t); const TValue *res = luaH_get(h, key); /* do a primitive get */ if (!ttisnil(res) || /* result is no nil? */ (tm = fasttm(L, h->metatable, TM_INDEX)) == NULL) { /* or no TM? */ setobj2s(L, val, res); return; } /* else will try the tag method */ } else if (ttisnil(tm = luaT_gettmbyobj(L, t, TM_INDEX))) luaG_typeerror(L, t, "index"); if (ttisfunction(tm)) { callTMres(L, val, tm, t, key); return; } t = tm; /* else repeat with `tm' */ } luaG_runerror(L, "loop in gettable"); } void luaV_settable (lua_State *L, const TValue *t, TValue *key, StkId val) { int loop; TValue temp; for (loop = 0; loop < MAXTAGLOOP; loop++) { const TValue *tm; if (ttistable(t)) { /* `t' is a table? */ Table *h = hvalue(t); TValue *oldval = luaH_set(L, h, key); /* do a primitive set */ if (!ttisnil(oldval) || /* result is no nil? */ (tm = fasttm(L, h->metatable, TM_NEWINDEX)) == NULL) { /* or no TM? */ setobj2t(L, oldval, val); h->flags = 0; luaC_barriert(L, h, val); return; } /* else will try the tag method */ } else if (ttisnil(tm = luaT_gettmbyobj(L, t, TM_NEWINDEX))) luaG_typeerror(L, t, "index"); if (ttisfunction(tm)) { callTM(L, tm, t, key, val); return; } /* else repeat with `tm' */ setobj(L, &temp, tm); /* avoid pointing inside table (may rehash) */ t = &temp; } luaG_runerror(L, "loop in settable"); } static int call_binTM (lua_State *L, const TValue *p1, const TValue *p2, StkId res, TMS event) { const TValue *tm = luaT_gettmbyobj(L, p1, event); /* try first operand */ if (ttisnil(tm)) tm = luaT_gettmbyobj(L, p2, event); /* try second operand */ if (ttisnil(tm)) return 0; callTMres(L, res, tm, p1, p2); return 1; } static const TValue *get_compTM (lua_State *L, Table *mt1, Table *mt2, TMS event) { const TValue *tm1 = fasttm(L, mt1, event); const TValue *tm2; if (tm1 == NULL) return NULL; /* no metamethod */ if (mt1 == mt2) return tm1; /* same metatables => same metamethods */ tm2 = fasttm(L, mt2, event); if (tm2 == NULL) return NULL; /* no metamethod */ if (luaO_rawequalObj(tm1, tm2)) /* same metamethods? */ return tm1; return NULL; } static int call_orderTM (lua_State *L, const TValue *p1, const TValue *p2, TMS event) { const TValue *tm1 = luaT_gettmbyobj(L, p1, event); const TValue *tm2; if (ttisnil(tm1)) return -1; /* no metamethod? */ tm2 = luaT_gettmbyobj(L, p2, event); if (!luaO_rawequalObj(tm1, tm2)) /* different metamethods? */ return -1; callTMres(L, L->top, tm1, p1, p2); return !l_isfalse(L->top); } static int l_strcmp (const TString *ls, const TString *rs) { const char *l = getstr(ls); size_t ll = ls->tsv.len; const char *r = getstr(rs); size_t lr = rs->tsv.len; for (;;) { int temp = strcoll(l, r); if (temp != 0) return temp; else { /* strings are equal up to a `\0' */ size_t len = strlen(l); /* index of first `\0' in both strings */ if (len == lr) /* r is finished? */ return (len == ll) ? 0 : 1; else if (len == ll) /* l is finished? */ return -1; /* l is smaller than r (because r is not finished) */ /* both strings longer than `len'; go on comparing (after the `\0') */ len++; l += len; ll -= len; r += len; lr -= len; } } } int luaV_lessthan (lua_State *L, const TValue *l, const TValue *r) { int res; if (ttype(l) != ttype(r)) return luaG_ordererror(L, l, r); else if (ttisnumber(l)) return luai_numlt(nvalue(l), nvalue(r)); else if (ttisstring(l)) return l_strcmp(rawtsvalue(l), rawtsvalue(r)) < 0; else if ((res = call_orderTM(L, l, r, TM_LT)) != -1) return res; return luaG_ordererror(L, l, r); } static int lessequal (lua_State *L, const TValue *l, const TValue *r) { int res; if (ttype(l) != ttype(r)) return luaG_ordererror(L, l, r); else if (ttisnumber(l)) return luai_numle(nvalue(l), nvalue(r)); else if (ttisstring(l)) return l_strcmp(rawtsvalue(l), rawtsvalue(r)) <= 0; else if ((res = call_orderTM(L, l, r, TM_LE)) != -1) /* first try `le' */ return res; else if ((res = call_orderTM(L, r, l, TM_LT)) != -1) /* else try `lt' */ return !res; return luaG_ordererror(L, l, r); } int luaV_equalval (lua_State *L, const TValue *t1, const TValue *t2) { const TValue *tm; lua_assert(ttype(t1) == ttype(t2)); switch (ttype(t1)) { case LUA_TNIL: return 1; case LUA_TNUMBER: return luai_numeq(nvalue(t1), nvalue(t2)); case LUA_TBOOLEAN: return bvalue(t1) == bvalue(t2); /* true must be 1 !! */ case LUA_TLIGHTUSERDATA: return pvalue(t1) == pvalue(t2); case LUA_TUSERDATA: { if (uvalue(t1) == uvalue(t2)) return 1; tm = get_compTM(L, uvalue(t1)->metatable, uvalue(t2)->metatable, TM_EQ); break; /* will try TM */ } case LUA_TTABLE: { if (hvalue(t1) == hvalue(t2)) return 1; tm = get_compTM(L, hvalue(t1)->metatable, hvalue(t2)->metatable, TM_EQ); break; /* will try TM */ } default: return gcvalue(t1) == gcvalue(t2); } if (tm == NULL) return 0; /* no TM? */ callTMres(L, L->top, tm, t1, t2); /* call TM */ return !l_isfalse(L->top); } void luaV_concat (lua_State *L, int total, int last) { do { StkId top = L->base + last + 1; int n = 2; /* number of elements handled in this pass (at least 2) */ if (!(ttisstring(top-2) || ttisnumber(top-2)) || !tostring(L, top-1)) { if (!call_binTM(L, top-2, top-1, top-2, TM_CONCAT)) luaG_concaterror(L, top-2, top-1); } else if (tsvalue(top-1)->len == 0) /* second op is empty? */ (void)tostring(L, top - 2); /* result is first op (as string) */ else { /* at least two string values; get as many as possible */ size_t tl = tsvalue(top-1)->len; char *buffer; int i; /* collect total length */ for (n = 1; n < total && tostring(L, top-n-1); n++) { size_t l = tsvalue(top-n-1)->len; if (l >= MAX_SIZET - tl) luaG_runerror(L, "string length overflow"); tl += l; } buffer = luaZ_openspace(L, &G(L)->buff, tl); tl = 0; for (i=n; i>0; i--) { /* concat all strings */ size_t l = tsvalue(top-i)->len; memcpy(buffer+tl, svalue(top-i), l); tl += l; } setsvalue2s(L, top-n, luaS_newlstr(L, buffer, tl)); } total -= n-1; /* got `n' strings to create 1 new */ last -= n-1; } while (total > 1); /* repeat until only 1 result left */ } static void Arith (lua_State *L, StkId ra, const TValue *rb, const TValue *rc, TMS op) { TValue tempb, tempc; const TValue *b, *c; if ((b = luaV_tonumber(rb, &tempb)) != NULL && (c = luaV_tonumber(rc, &tempc)) != NULL) { lua_Number nb = nvalue(b), nc = nvalue(c); switch (op) { case TM_ADD: setnvalue(ra, luai_numadd(nb, nc)); break; case TM_SUB: setnvalue(ra, luai_numsub(nb, nc)); break; case TM_MUL: setnvalue(ra, luai_nummul(nb, nc)); break; case TM_DIV: setnvalue(ra, luai_numdiv(nb, nc)); break; case TM_MOD: setnvalue(ra, luai_nummod(nb, nc)); break; case TM_POW: setnvalue(ra, luai_numpow(nb, nc)); break; case TM_UNM: setnvalue(ra, luai_numunm(nb)); break; default: lua_assert(0); break; } } else if (!call_binTM(L, rb, rc, ra, op)) luaG_aritherror(L, rb, rc); } /* ** some macros for common tasks in `luaV_execute' */ #define runtime_check(L, c) { if (!(c)) break; } #define RA(i) (base+GETARG_A(i)) /* to be used after possible stack reallocation */ #define RB(i) check_exp(getBMode(GET_OPCODE(i)) == OpArgR, base+GETARG_B(i)) #define RC(i) check_exp(getCMode(GET_OPCODE(i)) == OpArgR, base+GETARG_C(i)) #define RKB(i) check_exp(getBMode(GET_OPCODE(i)) == OpArgK, \ ISK(GETARG_B(i)) ? k+INDEXK(GETARG_B(i)) : base+GETARG_B(i)) #define RKC(i) check_exp(getCMode(GET_OPCODE(i)) == OpArgK, \ ISK(GETARG_C(i)) ? k+INDEXK(GETARG_C(i)) : base+GETARG_C(i)) #define KBx(i) check_exp(getBMode(GET_OPCODE(i)) == OpArgK, k+GETARG_Bx(i)) #define dojump(L,pc,i) {(pc) += (i); luai_threadyield(L);} #define Protect(x) { L->savedpc = pc; {x;}; base = L->base; } #define arith_op(op,tm) { \ TValue *rb = RKB(i); \ TValue *rc = RKC(i); \ if (ttisnumber(rb) && ttisnumber(rc)) { \ lua_Number nb = nvalue(rb), nc = nvalue(rc); \ setnvalue(ra, op(nb, nc)); \ } \ else \ Protect(Arith(L, ra, rb, rc, tm)); \ } void luaV_execute (lua_State *L, int nexeccalls) { LClosure *cl; StkId base; TValue *k; const Instruction *pc; reentry: /* entry point */ lua_assert(isLua(L->ci)); pc = L->savedpc; cl = &clvalue(L->ci->func)->l; base = L->base; k = cl->p->k; /* main loop of interpreter */ for (;;) { const Instruction i = *pc++; StkId ra; if ((L->hookmask & (LUA_MASKLINE | LUA_MASKCOUNT)) && (--L->hookcount == 0 || L->hookmask & LUA_MASKLINE)) { traceexec(L, pc); if (L->status == LUA_YIELD) { /* did hook yield? */ L->savedpc = pc - 1; return; } base = L->base; } /* warning!! several calls may realloc the stack and invalidate `ra' */ ra = RA(i); lua_assert(base == L->base && L->base == L->ci->base); lua_assert(base <= L->top && L->top <= L->stack + L->stacksize); lua_assert(L->top == L->ci->top || luaG_checkopenop(i)); switch (GET_OPCODE(i)) { case OP_MOVE: { setobjs2s(L, ra, RB(i)); continue; } case OP_LOADK: { setobj2s(L, ra, KBx(i)); continue; } case OP_LOADBOOL: { setbvalue(ra, GETARG_B(i)); if (GETARG_C(i)) pc++; /* skip next instruction (if C) */ continue; } case OP_LOADNIL: { TValue *rb = RB(i); do { setnilvalue(rb--); } while (rb >= ra); continue; } case OP_GETUPVAL: { int b = GETARG_B(i); setobj2s(L, ra, cl->upvals[b]->v); continue; } case OP_GETGLOBAL: { TValue g; TValue *rb = KBx(i); sethvalue(L, &g, cl->env); lua_assert(ttisstring(rb)); Protect(luaV_gettable(L, &g, rb, ra)); continue; } case OP_GETTABLE: { Protect(luaV_gettable(L, RB(i), RKC(i), ra)); continue; } case OP_SETGLOBAL: { TValue g; sethvalue(L, &g, cl->env); lua_assert(ttisstring(KBx(i))); Protect(luaV_settable(L, &g, KBx(i), ra)); continue; } case OP_SETUPVAL: { UpVal *uv = cl->upvals[GETARG_B(i)]; setobj(L, uv->v, ra); luaC_barrier(L, uv, ra); continue; } case OP_SETTABLE: { Protect(luaV_settable(L, ra, RKB(i), RKC(i))); continue; } case OP_NEWTABLE: { int b = GETARG_B(i); int c = GETARG_C(i); sethvalue(L, ra, luaH_new(L, luaO_fb2int(b), luaO_fb2int(c))); Protect(luaC_checkGC(L)); continue; } case OP_SELF: { StkId rb = RB(i); setobjs2s(L, ra+1, rb); Protect(luaV_gettable(L, rb, RKC(i), ra)); continue; } case OP_ADD: { arith_op(luai_numadd, TM_ADD); continue; } case OP_SUB: { arith_op(luai_numsub, TM_SUB); continue; } case OP_MUL: { arith_op(luai_nummul, TM_MUL); continue; } case OP_DIV: { arith_op(luai_numdiv, TM_DIV); continue; } case OP_MOD: { arith_op(luai_nummod, TM_MOD); continue; } case OP_POW: { arith_op(luai_numpow, TM_POW); continue; } case OP_UNM: { TValue *rb = RB(i); if (ttisnumber(rb)) { lua_Number nb = nvalue(rb); setnvalue(ra, luai_numunm(nb)); } else { Protect(Arith(L, ra, rb, rb, TM_UNM)); } continue; } case OP_NOT: { int res = l_isfalse(RB(i)); /* next assignment may change this value */ setbvalue(ra, res); continue; } case OP_LEN: { const TValue *rb = RB(i); switch (ttype(rb)) { case LUA_TTABLE: { setnvalue(ra, cast_num(luaH_getn(hvalue(rb)))); break; } case LUA_TSTRING: { setnvalue(ra, cast_num(tsvalue(rb)->len)); break; } default: { /* try metamethod */ Protect( if (!call_binTM(L, rb, luaO_nilobject, ra, TM_LEN)) luaG_typeerror(L, rb, "get length of"); ) } } continue; } case OP_CONCAT: { int b = GETARG_B(i); int c = GETARG_C(i); Protect(luaV_concat(L, c-b+1, c); luaC_checkGC(L)); setobjs2s(L, RA(i), base+b); continue; } case OP_JMP: { dojump(L, pc, GETARG_sBx(i)); continue; } case OP_EQ: { TValue *rb = RKB(i); TValue *rc = RKC(i); Protect( if (equalobj(L, rb, rc) == GETARG_A(i)) dojump(L, pc, GETARG_sBx(*pc)); ) pc++; continue; } case OP_LT: { Protect( if (luaV_lessthan(L, RKB(i), RKC(i)) == GETARG_A(i)) dojump(L, pc, GETARG_sBx(*pc)); ) pc++; continue; } case OP_LE: { Protect( if (lessequal(L, RKB(i), RKC(i)) == GETARG_A(i)) dojump(L, pc, GETARG_sBx(*pc)); ) pc++; continue; } case OP_TEST: { if (l_isfalse(ra) != GETARG_C(i)) dojump(L, pc, GETARG_sBx(*pc)); pc++; continue; } case OP_TESTSET: { TValue *rb = RB(i); if (l_isfalse(rb) != GETARG_C(i)) { setobjs2s(L, ra, rb); dojump(L, pc, GETARG_sBx(*pc)); } pc++; continue; } case OP_CALL: { int b = GETARG_B(i); int nresults = GETARG_C(i) - 1; if (b != 0) L->top = ra+b; /* else previous instruction set top */ L->savedpc = pc; switch (luaD_precall(L, ra, nresults)) { case PCRLUA: { nexeccalls++; goto reentry; /* restart luaV_execute over new Lua function */ } case PCRC: { /* it was a C function (`precall' called it); adjust results */ if (nresults >= 0) L->top = L->ci->top; base = L->base; continue; } default: { return; /* yield */ } } } case OP_TAILCALL: { int b = GETARG_B(i); if (b != 0) L->top = ra+b; /* else previous instruction set top */ L->savedpc = pc; lua_assert(GETARG_C(i) - 1 == LUA_MULTRET); switch (luaD_precall(L, ra, LUA_MULTRET)) { case PCRLUA: { /* tail call: put new frame in place of previous one */ CallInfo *ci = L->ci - 1; /* previous frame */ int aux; StkId func = ci->func; StkId pfunc = (ci+1)->func; /* previous function index */ if (L->openupval) luaF_close(L, ci->base); L->base = ci->base = ci->func + ((ci+1)->base - pfunc); for (aux = 0; pfunc+aux < L->top; aux++) /* move frame down */ setobjs2s(L, func+aux, pfunc+aux); ci->top = L->top = func+aux; /* correct top */ lua_assert(L->top == L->base + clvalue(func)->l.p->maxstacksize); ci->savedpc = L->savedpc; ci->tailcalls++; /* one more call lost */ L->ci--; /* remove new frame */ goto reentry; } case PCRC: { /* it was a C function (`precall' called it) */ base = L->base; continue; } default: { return; /* yield */ } } } case OP_RETURN: { int b = GETARG_B(i); if (b != 0) L->top = ra+b-1; if (L->openupval) luaF_close(L, base); L->savedpc = pc; b = luaD_poscall(L, ra); if (--nexeccalls == 0) /* was previous function running `here'? */ return; /* no: return */ else { /* yes: continue its execution */ if (b) L->top = L->ci->top; lua_assert(isLua(L->ci)); lua_assert(GET_OPCODE(*((L->ci)->savedpc - 1)) == OP_CALL); goto reentry; } } case OP_FORLOOP: { lua_Number step = nvalue(ra+2); lua_Number idx = luai_numadd(nvalue(ra), step); /* increment index */ lua_Number limit = nvalue(ra+1); if (luai_numlt(0, step) ? luai_numle(idx, limit) : luai_numle(limit, idx)) { dojump(L, pc, GETARG_sBx(i)); /* jump back */ setnvalue(ra, idx); /* update internal index... */ setnvalue(ra+3, idx); /* ...and external index */ } continue; } case OP_FORPREP: { const TValue *init = ra; const TValue *plimit = ra+1; const TValue *pstep = ra+2; L->savedpc = pc; /* next steps may throw errors */ if (!tonumber(init, ra)) luaG_runerror(L, LUA_QL("for") " initial value must be a number"); else if (!tonumber(plimit, ra+1)) luaG_runerror(L, LUA_QL("for") " limit must be a number"); else if (!tonumber(pstep, ra+2)) luaG_runerror(L, LUA_QL("for") " step must be a number"); setnvalue(ra, luai_numsub(nvalue(ra), nvalue(pstep))); dojump(L, pc, GETARG_sBx(i)); continue; } case OP_TFORLOOP: { StkId cb = ra + 3; /* call base */ setobjs2s(L, cb+2, ra+2); setobjs2s(L, cb+1, ra+1); setobjs2s(L, cb, ra); L->top = cb+3; /* func. + 2 args (state and index) */ Protect(luaD_call(L, cb, GETARG_C(i))); L->top = L->ci->top; cb = RA(i) + 3; /* previous call may change the stack */ if (!ttisnil(cb)) { /* continue loop? */ setobjs2s(L, cb-1, cb); /* save control variable */ dojump(L, pc, GETARG_sBx(*pc)); /* jump back */ } pc++; continue; } case OP_SETLIST: { int n = GETARG_B(i); int c = GETARG_C(i); int last; Table *h; if (n == 0) { n = cast_int(L->top - ra) - 1; L->top = L->ci->top; } if (c == 0) c = cast_int(*pc++); runtime_check(L, ttistable(ra)); h = hvalue(ra); last = ((c-1)*LFIELDS_PER_FLUSH) + n; if (last > h->sizearray) /* needs more space? */ luaH_resizearray(L, h, last); /* pre-alloc it at once */ for (; n > 0; n--) { TValue *val = ra+n; setobj2t(L, luaH_setnum(L, h, last--), val); luaC_barriert(L, h, val); } continue; } case OP_CLOSE: { luaF_close(L, ra); continue; } case OP_CLOSURE: { Proto *p; Closure *ncl; int nup, j; p = cl->p->p[GETARG_Bx(i)]; nup = p->nups; ncl = luaF_newLclosure(L, nup, cl->env); ncl->l.p = p; for (j=0; j<nup; j++, pc++) { if (GET_OPCODE(*pc) == OP_GETUPVAL) ncl->l.upvals[j] = cl->upvals[GETARG_B(*pc)]; else { lua_assert(GET_OPCODE(*pc) == OP_MOVE); ncl->l.upvals[j] = luaF_findupval(L, base + GETARG_B(*pc)); } } setclvalue(L, ra, ncl); Protect(luaC_checkGC(L)); continue; } case OP_VARARG: { int b = GETARG_B(i) - 1; int j; CallInfo *ci = L->ci; int n = cast_int(ci->base - ci->func) - cl->p->numparams - 1; if (b == LUA_MULTRET) { Protect(luaD_checkstack(L, n)); ra = RA(i); /* previous call may change the stack */ b = n; L->top = ra + n; } for (j = 0; j < b; j++) { if (j < n) { setobjs2s(L, ra + j, ci->base - n + j); } else { setnilvalue(ra + j); } } continue; } } } }
xLua/build/lua-5.1.5/src/lvm.c/0
{ "file_path": "xLua/build/lua-5.1.5/src/lvm.c", "repo_id": "xLua", "token_count": 12328 }
2,018
.TH LUA 1 "$Date: 2014/12/10 15:55:45 $" .SH NAME lua \- Lua interpreter .SH SYNOPSIS .B lua [ .I options ] [ .I script [ .I args ] ] .SH DESCRIPTION .B lua is the standalone Lua interpreter. It loads and executes Lua programs, either in textual source form or in precompiled binary form. (Precompiled binaries are output by .BR luac , the Lua compiler.) .B lua can be used as a batch interpreter and also interactively. .LP The given .I options are handled in order and then the Lua program in file .I script is loaded and executed. The given .I args are available to .I script as strings in a global table named .BR arg . If no options or arguments are given, then .B "\-v \-i" is assumed when the standard input is a terminal; otherwise, .B "\-" is assumed. .LP In interactive mode, .B lua prompts the user, reads lines from the standard input, and executes them as they are read. If the line contains an expression or list of expressions, then the line is evaluated and the results are printed. If a line does not contain a complete statement, then a secondary prompt is displayed and lines are read until a complete statement is formed or a syntax error is found. .LP At the very start, before even handling the command line, .B lua checks the contents of the environment variables .B LUA_INIT_5_3 or .BR LUA_INIT , in that order. If the contents is of the form .RI '@ filename ', then .I filename is executed. Otherwise, the string is assumed to be a Lua statement and is executed. .SH OPTIONS .TP .BI \-e " stat" execute statement .IR stat . .TP .B \-i enter interactive mode after executing .IR script . .TP .BI \-l " name" execute the equivalent of .IB name =require(' name ') before executing .IR script . .TP .B \-v show version information. .TP .B \-E ignore environment variables. .TP .B \-\- stop handling options. .TP .B \- stop handling options and execute the standard input as a file. .SH "SEE ALSO" .BR luac (1) .br The documentation at lua.org, especially section 7 of the reference manual. .SH DIAGNOSTICS Error messages should be self explanatory. .SH AUTHORS R. Ierusalimschy, L. H. de Figueiredo, W. Celes .\" EOF
xLua/build/lua-5.3.3/doc/lua.1/0
{ "file_path": "xLua/build/lua-5.3.3/doc/lua.1", "repo_id": "xLua", "token_count": 680 }
2,019
/* ** $Id: lparser.h,v 1.76 2015/12/30 18:16:13 roberto Exp $ ** Lua Parser ** See Copyright Notice in lua.h */ #ifndef lparser_h #define lparser_h #include "llimits.h" #include "lobject.h" #include "lzio.h" /* ** Expression and variable descriptor. ** Code generation for variables and expressions can be delayed to allow ** optimizations; An 'expdesc' structure describes a potentially-delayed ** variable/expression. It has a description of its "main" value plus a ** list of conditional jumps that can also produce its value (generated ** by short-circuit operators 'and'/'or'). */ /* kinds of variables/expressions */ typedef enum { VVOID, /* when 'expdesc' describes the last expression a list, this kind means an empty list (so, no expression) */ VNIL, /* constant nil */ VTRUE, /* constant true */ VFALSE, /* constant false */ VK, /* constant in 'k'; info = index of constant in 'k' */ VKFLT, /* floating constant; nval = numerical float value */ VKINT, /* integer constant; nval = numerical integer value */ VNONRELOC, /* expression has its value in a fixed register; info = result register */ VLOCAL, /* local variable; info = local register */ VUPVAL, /* upvalue variable; info = index of upvalue in 'upvalues' */ VINDEXED, /* indexed variable; ind.vt = whether 't' is register or upvalue; ind.t = table register or upvalue; ind.idx = key's R/K index */ VJMP, /* expression is a test/comparison; info = pc of corresponding jump instruction */ VRELOCABLE, /* expression can put result in any register; info = instruction pc */ VCALL, /* expression is a function call; info = instruction pc */ VVARARG /* vararg expression; info = instruction pc */ } expkind; #define vkisvar(k) (VLOCAL <= (k) && (k) <= VINDEXED) #define vkisinreg(k) ((k) == VNONRELOC || (k) == VLOCAL) typedef struct expdesc { expkind k; union { lua_Integer ival; /* for VKINT */ lua_Number nval; /* for VKFLT */ int info; /* for generic use */ struct { /* for indexed variables (VINDEXED) */ short idx; /* index (R/K) */ lu_byte t; /* table (register or upvalue) */ lu_byte vt; /* whether 't' is register (VLOCAL) or upvalue (VUPVAL) */ } ind; } u; int t; /* patch list of 'exit when true' */ int f; /* patch list of 'exit when false' */ } expdesc; /* description of active local variable */ typedef struct Vardesc { short idx; /* variable index in stack */ } Vardesc; /* description of pending goto statements and label statements */ typedef struct Labeldesc { TString *name; /* label identifier */ int pc; /* position in code */ int line; /* line where it appeared */ lu_byte nactvar; /* local level where it appears in current block */ } Labeldesc; /* list of labels or gotos */ typedef struct Labellist { Labeldesc *arr; /* array */ int n; /* number of entries in use */ int size; /* array size */ } Labellist; /* dynamic structures used by the parser */ typedef struct Dyndata { struct { /* list of active local variables */ Vardesc *arr; int n; int size; } actvar; Labellist gt; /* list of pending gotos */ Labellist label; /* list of active labels */ } Dyndata; /* control of blocks */ struct BlockCnt; /* defined in lparser.c */ /* state needed to generate code for a given function */ typedef struct FuncState { Proto *f; /* current function header */ struct FuncState *prev; /* enclosing function */ struct LexState *ls; /* lexical state */ struct BlockCnt *bl; /* chain of current blocks */ int pc; /* next position to code (equivalent to 'ncode') */ int lasttarget; /* 'label' of last 'jump label' */ int jpc; /* list of pending jumps to 'pc' */ int nk; /* number of elements in 'k' */ int np; /* number of elements in 'p' */ int firstlocal; /* index of first local var (in Dyndata array) */ short nlocvars; /* number of elements in 'f->locvars' */ lu_byte nactvar; /* number of active local variables */ lu_byte nups; /* number of upvalues */ lu_byte freereg; /* first free register */ } FuncState; LUAI_FUNC LClosure *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff, Dyndata *dyd, const char *name, int firstchar); #endif
xLua/build/lua-5.3.3/src/lparser.h/0
{ "file_path": "xLua/build/lua-5.3.3/src/lparser.h", "repo_id": "xLua", "token_count": 1550 }
2,020
/* ** $Id: lcode.h,v 1.64 2016/01/05 16:22:37 roberto Exp $ ** Code generator for Lua ** See Copyright Notice in lua.h */ #ifndef lcode_h #define lcode_h #include "llex.h" #include "lobject.h" #include "lopcodes.h" #include "lparser.h" /* ** Marks the end of a patch list. It is an invalid value both as an absolute ** address, and as a list link (would link an element to itself). */ #define NO_JUMP (-1) /* ** grep "ORDER OPR" if you change these enums (ORDER OP) */ typedef enum BinOpr { OPR_ADD, OPR_SUB, OPR_MUL, OPR_MOD, OPR_POW, OPR_DIV, OPR_IDIV, OPR_BAND, OPR_BOR, OPR_BXOR, OPR_SHL, OPR_SHR, OPR_CONCAT, OPR_EQ, OPR_LT, OPR_LE, OPR_NE, OPR_GT, OPR_GE, OPR_AND, OPR_OR, OPR_NOBINOPR } BinOpr; typedef enum UnOpr { OPR_MINUS, OPR_BNOT, OPR_NOT, OPR_LEN, OPR_NOUNOPR } UnOpr; /* get (pointer to) instruction of given 'expdesc' */ #define getinstruction(fs,e) ((fs)->f->code[(e)->u.info]) #define luaK_codeAsBx(fs,o,A,sBx) luaK_codeABx(fs,o,A,(sBx)+MAXARG_sBx) #define luaK_setmultret(fs,e) luaK_setreturns(fs, e, LUA_MULTRET) #define luaK_jumpto(fs,t) luaK_patchlist(fs, luaK_jump(fs), t) LUAI_FUNC int luaK_codeABx (FuncState *fs, OpCode o, int A, unsigned int Bx); LUAI_FUNC int luaK_codeABC (FuncState *fs, OpCode o, int A, int B, int C); LUAI_FUNC int luaK_codek (FuncState *fs, int reg, int k); LUAI_FUNC void luaK_fixline (FuncState *fs, int line); LUAI_FUNC void luaK_nil (FuncState *fs, int from, int n); LUAI_FUNC void luaK_reserveregs (FuncState *fs, int n); LUAI_FUNC void luaK_checkstack (FuncState *fs, int n); LUAI_FUNC int luaK_stringK (FuncState *fs, TString *s); LUAI_FUNC int luaK_intK (FuncState *fs, lua_Integer n); LUAI_FUNC void luaK_dischargevars (FuncState *fs, expdesc *e); LUAI_FUNC int luaK_exp2anyreg (FuncState *fs, expdesc *e); LUAI_FUNC void luaK_exp2anyregup (FuncState *fs, expdesc *e); LUAI_FUNC void luaK_exp2nextreg (FuncState *fs, expdesc *e); LUAI_FUNC void luaK_exp2val (FuncState *fs, expdesc *e); LUAI_FUNC int luaK_exp2RK (FuncState *fs, expdesc *e); LUAI_FUNC void luaK_self (FuncState *fs, expdesc *e, expdesc *key); LUAI_FUNC void luaK_indexed (FuncState *fs, expdesc *t, expdesc *k); LUAI_FUNC void luaK_goiftrue (FuncState *fs, expdesc *e); LUAI_FUNC void luaK_goiffalse (FuncState *fs, expdesc *e); LUAI_FUNC void luaK_storevar (FuncState *fs, expdesc *var, expdesc *e); LUAI_FUNC void luaK_setreturns (FuncState *fs, expdesc *e, int nresults); LUAI_FUNC void luaK_setoneret (FuncState *fs, expdesc *e); LUAI_FUNC int luaK_jump (FuncState *fs); LUAI_FUNC void luaK_ret (FuncState *fs, int first, int nret); LUAI_FUNC void luaK_patchlist (FuncState *fs, int list, int target); LUAI_FUNC void luaK_patchtohere (FuncState *fs, int list); LUAI_FUNC void luaK_patchclose (FuncState *fs, int list, int level); LUAI_FUNC void luaK_concat (FuncState *fs, int *l1, int l2); LUAI_FUNC int luaK_getlabel (FuncState *fs); LUAI_FUNC void luaK_prefix (FuncState *fs, UnOpr op, expdesc *v, int line); LUAI_FUNC void luaK_infix (FuncState *fs, BinOpr op, expdesc *v); LUAI_FUNC void luaK_posfix (FuncState *fs, BinOpr op, expdesc *v1, expdesc *v2, int line); LUAI_FUNC void luaK_setlist (FuncState *fs, int base, int nelems, int tostore); #endif
xLua/build/lua-5.3.4/src/lcode.h/0
{ "file_path": "xLua/build/lua-5.3.4/src/lcode.h", "repo_id": "xLua", "token_count": 1485 }
2,021
/* ** $Id: llex.c,v 2.96 2016/05/02 14:02:12 roberto Exp $ ** Lexical Analyzer ** See Copyright Notice in lua.h */ #define llex_c #define LUA_CORE #include "lprefix.h" #include <locale.h> #include <string.h> #include "lua.h" #include "lctype.h" #include "ldebug.h" #include "ldo.h" #include "lgc.h" #include "llex.h" #include "lobject.h" #include "lparser.h" #include "lstate.h" #include "lstring.h" #include "ltable.h" #include "lzio.h" #define next(ls) (ls->current = zgetc(ls->z)) #define currIsNewline(ls) (ls->current == '\n' || ls->current == '\r') /* ORDER RESERVED */ static const char *const luaX_tokens [] = { "and", "break", "do", "else", "elseif", "end", "false", "for", "function", "goto", "if", "in", "local", "nil", "not", "or", "repeat", "return", "then", "true", "until", "while", "//", "..", "...", "==", ">=", "<=", "~=", "<<", ">>", "::", "<eof>", "<number>", "<integer>", "<name>", "<string>" }; #define save_and_next(ls) (save(ls, ls->current), next(ls)) static l_noret lexerror (LexState *ls, const char *msg, int token); static void save (LexState *ls, int c) { Mbuffer *b = ls->buff; if (luaZ_bufflen(b) + 1 > luaZ_sizebuffer(b)) { size_t newsize; if (luaZ_sizebuffer(b) >= MAX_SIZE/2) lexerror(ls, "lexical element too long", 0); newsize = luaZ_sizebuffer(b) * 2; luaZ_resizebuffer(ls->L, b, newsize); } b->buffer[luaZ_bufflen(b)++] = cast(char, c); } void luaX_init (lua_State *L) { int i; TString *e = luaS_newliteral(L, LUA_ENV); /* create env name */ luaC_fix(L, obj2gco(e)); /* never collect this name */ for (i=0; i<NUM_RESERVED; i++) { TString *ts = luaS_new(L, luaX_tokens[i]); luaC_fix(L, obj2gco(ts)); /* reserved words are never collected */ ts->extra = cast_byte(i+1); /* reserved word */ } } const char *luaX_token2str (LexState *ls, int token) { if (token < FIRST_RESERVED) { /* single-byte symbols? */ lua_assert(token == cast_uchar(token)); return luaO_pushfstring(ls->L, "'%c'", token); } else { const char *s = luaX_tokens[token - FIRST_RESERVED]; if (token < TK_EOS) /* fixed format (symbols and reserved words)? */ return luaO_pushfstring(ls->L, "'%s'", s); else /* names, strings, and numerals */ return s; } } static const char *txtToken (LexState *ls, int token) { switch (token) { case TK_NAME: case TK_STRING: case TK_FLT: case TK_INT: save(ls, '\0'); return luaO_pushfstring(ls->L, "'%s'", luaZ_buffer(ls->buff)); default: return luaX_token2str(ls, token); } } static l_noret lexerror (LexState *ls, const char *msg, int token) { msg = luaG_addinfo(ls->L, msg, ls->source, ls->linenumber); if (token) luaO_pushfstring(ls->L, "%s near %s", msg, txtToken(ls, token)); luaD_throw(ls->L, LUA_ERRSYNTAX); } l_noret luaX_syntaxerror (LexState *ls, const char *msg) { lexerror(ls, msg, ls->t.token); } /* ** creates a new string and anchors it in scanner's table so that ** it will not be collected until the end of the compilation ** (by that time it should be anchored somewhere) */ TString *luaX_newstring (LexState *ls, const char *str, size_t l) { lua_State *L = ls->L; TValue *o; /* entry for 'str' */ TString *ts = luaS_newlstr(L, str, l); /* create new string */ setsvalue2s(L, L->top++, ts); /* temporarily anchor it in stack */ o = luaH_set(L, ls->h, L->top - 1); if (ttisnil(o)) { /* not in use yet? */ /* boolean value does not need GC barrier; table has no metatable, so it does not need to invalidate cache */ setbvalue(o, 1); /* t[string] = true */ luaC_checkGC(L); } else { /* string already present */ ts = tsvalue(keyfromval(o)); /* re-use value previously stored */ } L->top--; /* remove string from stack */ return ts; } /* ** increment line number and skips newline sequence (any of ** \n, \r, \n\r, or \r\n) */ static void inclinenumber (LexState *ls) { int old = ls->current; lua_assert(currIsNewline(ls)); next(ls); /* skip '\n' or '\r' */ if (currIsNewline(ls) && ls->current != old) next(ls); /* skip '\n\r' or '\r\n' */ if (++ls->linenumber >= MAX_INT) lexerror(ls, "chunk has too many lines", 0); } void luaX_setinput (lua_State *L, LexState *ls, ZIO *z, TString *source, int firstchar) { ls->t.token = 0; ls->L = L; ls->current = firstchar; ls->lookahead.token = TK_EOS; /* no look-ahead token */ ls->z = z; ls->fs = NULL; ls->linenumber = 1; ls->lastline = 1; ls->source = source; ls->envn = luaS_newliteral(L, LUA_ENV); /* get env name */ luaZ_resizebuffer(ls->L, ls->buff, LUA_MINBUFFER); /* initialize buffer */ } /* ** ======================================================= ** LEXICAL ANALYZER ** ======================================================= */ static int check_next1 (LexState *ls, int c) { if (ls->current == c) { next(ls); return 1; } else return 0; } /* ** Check whether current char is in set 'set' (with two chars) and ** saves it */ static int check_next2 (LexState *ls, const char *set) { lua_assert(set[2] == '\0'); if (ls->current == set[0] || ls->current == set[1]) { save_and_next(ls); return 1; } else return 0; } /* LUA_NUMBER */ /* ** this function is quite liberal in what it accepts, as 'luaO_str2num' ** will reject ill-formed numerals. */ static int read_numeral (LexState *ls, SemInfo *seminfo) { TValue obj; const char *expo = "Ee"; int first = ls->current; lua_assert(lisdigit(ls->current)); save_and_next(ls); if (first == '0' && check_next2(ls, "xX")) /* hexadecimal? */ expo = "Pp"; for (;;) { if (check_next2(ls, expo)) /* exponent part? */ check_next2(ls, "-+"); /* optional exponent sign */ if (lisxdigit(ls->current)) save_and_next(ls); else if (ls->current == '.') save_and_next(ls); else break; } save(ls, '\0'); if (luaO_str2num(luaZ_buffer(ls->buff), &obj) == 0) /* format error? */ lexerror(ls, "malformed number", TK_FLT); if (ttisinteger(&obj)) { seminfo->i = ivalue(&obj); return TK_INT; } else { lua_assert(ttisfloat(&obj)); seminfo->r = fltvalue(&obj); return TK_FLT; } } /* ** skip a sequence '[=*[' or ']=*]'; if sequence is well formed, return ** its number of '='s; otherwise, return a negative number (-1 iff there ** are no '='s after initial bracket) */ static int skip_sep (LexState *ls) { int count = 0; int s = ls->current; lua_assert(s == '[' || s == ']'); save_and_next(ls); while (ls->current == '=') { save_and_next(ls); count++; } return (ls->current == s) ? count : (-count) - 1; } static void read_long_string (LexState *ls, SemInfo *seminfo, int sep) { int line = ls->linenumber; /* initial line (for error message) */ save_and_next(ls); /* skip 2nd '[' */ if (currIsNewline(ls)) /* string starts with a newline? */ inclinenumber(ls); /* skip it */ for (;;) { switch (ls->current) { case EOZ: { /* error */ const char *what = (seminfo ? "string" : "comment"); const char *msg = luaO_pushfstring(ls->L, "unfinished long %s (starting at line %d)", what, line); lexerror(ls, msg, TK_EOS); break; /* to avoid warnings */ } case ']': { if (skip_sep(ls) == sep) { save_and_next(ls); /* skip 2nd ']' */ goto endloop; } break; } case '\n': case '\r': { save(ls, '\n'); inclinenumber(ls); if (!seminfo) luaZ_resetbuffer(ls->buff); /* avoid wasting space */ break; } default: { if (seminfo) save_and_next(ls); else next(ls); } } } endloop: if (seminfo) seminfo->ts = luaX_newstring(ls, luaZ_buffer(ls->buff) + (2 + sep), luaZ_bufflen(ls->buff) - 2*(2 + sep)); } static void esccheck (LexState *ls, int c, const char *msg) { if (!c) { if (ls->current != EOZ) save_and_next(ls); /* add current to buffer for error message */ lexerror(ls, msg, TK_STRING); } } static int gethexa (LexState *ls) { save_and_next(ls); esccheck (ls, lisxdigit(ls->current), "hexadecimal digit expected"); return luaO_hexavalue(ls->current); } static int readhexaesc (LexState *ls) { int r = gethexa(ls); r = (r << 4) + gethexa(ls); luaZ_buffremove(ls->buff, 2); /* remove saved chars from buffer */ return r; } static unsigned long readutf8esc (LexState *ls) { unsigned long r; int i = 4; /* chars to be removed: '\', 'u', '{', and first digit */ save_and_next(ls); /* skip 'u' */ esccheck(ls, ls->current == '{', "missing '{'"); r = gethexa(ls); /* must have at least one digit */ while ((save_and_next(ls), lisxdigit(ls->current))) { i++; r = (r << 4) + luaO_hexavalue(ls->current); esccheck(ls, r <= 0x10FFFF, "UTF-8 value too large"); } esccheck(ls, ls->current == '}', "missing '}'"); next(ls); /* skip '}' */ luaZ_buffremove(ls->buff, i); /* remove saved chars from buffer */ return r; } static void utf8esc (LexState *ls) { char buff[UTF8BUFFSZ]; int n = luaO_utf8esc(buff, readutf8esc(ls)); for (; n > 0; n--) /* add 'buff' to string */ save(ls, buff[UTF8BUFFSZ - n]); } static int readdecesc (LexState *ls) { int i; int r = 0; /* result accumulator */ for (i = 0; i < 3 && lisdigit(ls->current); i++) { /* read up to 3 digits */ r = 10*r + ls->current - '0'; save_and_next(ls); } esccheck(ls, r <= UCHAR_MAX, "decimal escape too large"); luaZ_buffremove(ls->buff, i); /* remove read digits from buffer */ return r; } static void read_string (LexState *ls, int del, SemInfo *seminfo) { save_and_next(ls); /* keep delimiter (for error messages) */ while (ls->current != del) { switch (ls->current) { case EOZ: lexerror(ls, "unfinished string", TK_EOS); break; /* to avoid warnings */ case '\n': case '\r': lexerror(ls, "unfinished string", TK_STRING); break; /* to avoid warnings */ case '\\': { /* escape sequences */ int c; /* final character to be saved */ save_and_next(ls); /* keep '\\' for error messages */ switch (ls->current) { case 'a': c = '\a'; goto read_save; case 'b': c = '\b'; goto read_save; case 'f': c = '\f'; goto read_save; case 'n': c = '\n'; goto read_save; case 'r': c = '\r'; goto read_save; case 't': c = '\t'; goto read_save; case 'v': c = '\v'; goto read_save; case 'x': c = readhexaesc(ls); goto read_save; case 'u': utf8esc(ls); goto no_save; case '\n': case '\r': inclinenumber(ls); c = '\n'; goto only_save; case '\\': case '\"': case '\'': c = ls->current; goto read_save; case EOZ: goto no_save; /* will raise an error next loop */ case 'z': { /* zap following span of spaces */ luaZ_buffremove(ls->buff, 1); /* remove '\\' */ next(ls); /* skip the 'z' */ while (lisspace(ls->current)) { if (currIsNewline(ls)) inclinenumber(ls); else next(ls); } goto no_save; } default: { esccheck(ls, lisdigit(ls->current), "invalid escape sequence"); c = readdecesc(ls); /* digital escape '\ddd' */ goto only_save; } } read_save: next(ls); /* go through */ only_save: luaZ_buffremove(ls->buff, 1); /* remove '\\' */ save(ls, c); /* go through */ no_save: break; } default: save_and_next(ls); } } save_and_next(ls); /* skip delimiter */ seminfo->ts = luaX_newstring(ls, luaZ_buffer(ls->buff) + 1, luaZ_bufflen(ls->buff) - 2); } static int llex (LexState *ls, SemInfo *seminfo) { luaZ_resetbuffer(ls->buff); for (;;) { switch (ls->current) { case '\n': case '\r': { /* line breaks */ inclinenumber(ls); break; } case ' ': case '\f': case '\t': case '\v': { /* spaces */ next(ls); break; } case '-': { /* '-' or '--' (comment) */ next(ls); if (ls->current != '-') return '-'; /* else is a comment */ next(ls); if (ls->current == '[') { /* long comment? */ int sep = skip_sep(ls); luaZ_resetbuffer(ls->buff); /* 'skip_sep' may dirty the buffer */ if (sep >= 0) { read_long_string(ls, NULL, sep); /* skip long comment */ luaZ_resetbuffer(ls->buff); /* previous call may dirty the buff. */ break; } } /* else short comment */ while (!currIsNewline(ls) && ls->current != EOZ) next(ls); /* skip until end of line (or end of file) */ break; } case '[': { /* long string or simply '[' */ int sep = skip_sep(ls); if (sep >= 0) { read_long_string(ls, seminfo, sep); return TK_STRING; } else if (sep != -1) /* '[=...' missing second bracket */ lexerror(ls, "invalid long string delimiter", TK_STRING); return '['; } case '=': { next(ls); if (check_next1(ls, '=')) return TK_EQ; else return '='; } case '<': { next(ls); if (check_next1(ls, '=')) return TK_LE; else if (check_next1(ls, '<')) return TK_SHL; else return '<'; } case '>': { next(ls); if (check_next1(ls, '=')) return TK_GE; else if (check_next1(ls, '>')) return TK_SHR; else return '>'; } case '/': { next(ls); if (check_next1(ls, '/')) return TK_IDIV; else return '/'; } case '~': { next(ls); if (check_next1(ls, '=')) return TK_NE; else return '~'; } case ':': { next(ls); if (check_next1(ls, ':')) return TK_DBCOLON; else return ':'; } case '"': case '\'': { /* short literal strings */ read_string(ls, ls->current, seminfo); return TK_STRING; } case '.': { /* '.', '..', '...', or number */ save_and_next(ls); if (check_next1(ls, '.')) { if (check_next1(ls, '.')) return TK_DOTS; /* '...' */ else return TK_CONCAT; /* '..' */ } else if (!lisdigit(ls->current)) return '.'; else return read_numeral(ls, seminfo); } case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { return read_numeral(ls, seminfo); } case EOZ: { return TK_EOS; } default: { if (lislalpha(ls->current)) { /* identifier or reserved word? */ TString *ts; do { save_and_next(ls); } while (lislalnum(ls->current)); ts = luaX_newstring(ls, luaZ_buffer(ls->buff), luaZ_bufflen(ls->buff)); seminfo->ts = ts; if (isreserved(ts)) /* reserved word? */ return ts->extra - 1 + FIRST_RESERVED; else { return TK_NAME; } } else { /* single-char tokens (+ - / ...) */ int c = ls->current; next(ls); return c; } } } } } void luaX_next (LexState *ls) { ls->lastline = ls->linenumber; if (ls->lookahead.token != TK_EOS) { /* is there a look-ahead token? */ ls->t = ls->lookahead; /* use this one */ ls->lookahead.token = TK_EOS; /* and discharge it */ } else ls->t.token = llex(ls, &ls->t.seminfo); /* read next token */ } int luaX_lookahead (LexState *ls) { lua_assert(ls->lookahead.token == TK_EOS); ls->lookahead.token = llex(ls, &ls->lookahead.seminfo); return ls->lookahead.token; }
xLua/build/lua-5.3.4/src/llex.c/0
{ "file_path": "xLua/build/lua-5.3.4/src/llex.c", "repo_id": "xLua", "token_count": 7475 }
2,022
/* ** $Id: lstate.h,v 2.133 2016/12/22 13:08:50 roberto Exp $ ** Global State ** See Copyright Notice in lua.h */ #ifndef lstate_h #define lstate_h #include "lua.h" #include "lobject.h" #include "ltm.h" #include "lzio.h" /* ** Some notes about garbage-collected objects: All objects in Lua must ** be kept somehow accessible until being freed, so all objects always ** belong to one (and only one) of these lists, using field 'next' of ** the 'CommonHeader' for the link: ** ** 'allgc': all objects not marked for finalization; ** 'finobj': all objects marked for finalization; ** 'tobefnz': all objects ready to be finalized; ** 'fixedgc': all objects that are not to be collected (currently ** only small strings, such as reserved words). */ struct lua_longjmp; /* defined in ldo.c */ /* ** Atomic type (relative to signals) to better ensure that 'lua_sethook' ** is thread safe */ #if !defined(l_signalT) #include <signal.h> #define l_signalT sig_atomic_t #endif /* extra stack space to handle TM calls and some other extras */ #define EXTRA_STACK 5 #define BASIC_STACK_SIZE (2*LUA_MINSTACK) /* kinds of Garbage Collection */ #define KGC_NORMAL 0 #define KGC_EMERGENCY 1 /* gc was forced by an allocation failure */ typedef struct stringtable { TString **hash; int nuse; /* number of elements */ int size; } stringtable; /* ** Information about a call. ** When a thread yields, 'func' is adjusted to pretend that the ** top function has only the yielded values in its stack; in that ** case, the actual 'func' value is saved in field 'extra'. ** When a function calls another with a continuation, 'extra' keeps ** the function index so that, in case of errors, the continuation ** function can be called with the correct top. */ typedef struct CallInfo { StkId func; /* function index in the stack */ StkId top; /* top for this function */ struct CallInfo *previous, *next; /* dynamic call link */ union { struct { /* only for Lua functions */ StkId base; /* base for this function */ const Instruction *savedpc; } l; struct { /* only for C functions */ lua_KFunction k; /* continuation in case of yields */ ptrdiff_t old_errfunc; lua_KContext ctx; /* context info. in case of yields */ } c; } u; ptrdiff_t extra; short nresults; /* expected number of results from this function */ unsigned short callstatus; } CallInfo; /* ** Bits in CallInfo status */ #define CIST_OAH (1<<0) /* original value of 'allowhook' */ #define CIST_LUA (1<<1) /* call is running a Lua function */ #define CIST_HOOKED (1<<2) /* call is running a debug hook */ #define CIST_FRESH (1<<3) /* call is running on a fresh invocation of luaV_execute */ #define CIST_YPCALL (1<<4) /* call is a yieldable protected call */ #define CIST_TAIL (1<<5) /* call was tail called */ #define CIST_HOOKYIELD (1<<6) /* last hook called yielded */ #define CIST_LEQ (1<<7) /* using __lt for __le */ #define CIST_FIN (1<<8) /* call is running a finalizer */ #define isLua(ci) ((ci)->callstatus & CIST_LUA) /* assume that CIST_OAH has offset 0 and that 'v' is strictly 0/1 */ #define setoah(st,v) ((st) = ((st) & ~CIST_OAH) | (v)) #define getoah(st) ((st) & CIST_OAH) /* ** 'global state', shared by all threads of this state */ typedef struct global_State { lua_Alloc frealloc; /* function to reallocate memory */ void *ud; /* auxiliary data to 'frealloc' */ l_mem totalbytes; /* number of bytes currently allocated - GCdebt */ l_mem GCdebt; /* bytes allocated not yet compensated by the collector */ lu_mem GCmemtrav; /* memory traversed by the GC */ lu_mem GCestimate; /* an estimate of the non-garbage memory in use */ stringtable strt; /* hash table for strings */ TValue l_registry; unsigned int seed; /* randomized seed for hashes */ lu_byte currentwhite; lu_byte gcstate; /* state of garbage collector */ lu_byte gckind; /* kind of GC running */ lu_byte gcrunning; /* true if GC is running */ GCObject *allgc; /* list of all collectable objects */ GCObject **sweepgc; /* current position of sweep in list */ GCObject *finobj; /* list of collectable objects with finalizers */ GCObject *gray; /* list of gray objects */ GCObject *grayagain; /* list of objects to be traversed atomically */ GCObject *weak; /* list of tables with weak values */ GCObject *ephemeron; /* list of ephemeron tables (weak keys) */ GCObject *allweak; /* list of all-weak tables */ GCObject *tobefnz; /* list of userdata to be GC */ GCObject *fixedgc; /* list of objects not to be collected */ struct lua_State *twups; /* list of threads with open upvalues */ unsigned int gcfinnum; /* number of finalizers to call in each GC step */ int gcpause; /* size of pause between successive GCs */ int gcstepmul; /* GC 'granularity' */ lua_CFunction panic; /* to be called in unprotected errors */ struct lua_State *mainthread; const lua_Number *version; /* pointer to version number */ TString *memerrmsg; /* memory-error message */ TString *tmname[TM_N]; /* array with tag-method names */ struct Table *mt[LUA_NUMTAGS]; /* metatables for basic types */ TString *strcache[STRCACHE_N][STRCACHE_M]; /* cache for strings in API */ } global_State; /* ** 'per thread' state */ struct lua_State { CommonHeader; unsigned short nci; /* number of items in 'ci' list */ lu_byte status; StkId top; /* first free slot in the stack */ global_State *l_G; CallInfo *ci; /* call info for current function */ const Instruction *oldpc; /* last pc traced */ StkId stack_last; /* last free slot in the stack */ StkId stack; /* stack base */ UpVal *openupval; /* list of open upvalues in this stack */ GCObject *gclist; struct lua_State *twups; /* list of threads with open upvalues */ struct lua_longjmp *errorJmp; /* current error recover point */ CallInfo base_ci; /* CallInfo for first level (C calling Lua) */ volatile lua_Hook hook; ptrdiff_t errfunc; /* current error handling function (stack index) */ int stacksize; int basehookcount; int hookcount; unsigned short nny; /* number of non-yieldable calls in stack */ unsigned short nCcalls; /* number of nested C calls */ l_signalT hookmask; lu_byte allowhook; }; #define G(L) (L->l_G) /* ** Union of all collectable objects (only for conversions) */ union GCUnion { GCObject gc; /* common header */ struct TString ts; struct Udata u; union Closure cl; struct Table h; struct Proto p; struct lua_State th; /* thread */ }; #define cast_u(o) cast(union GCUnion *, (o)) /* macros to convert a GCObject into a specific value */ #define gco2ts(o) \ check_exp(novariant((o)->tt) == LUA_TSTRING, &((cast_u(o))->ts)) #define gco2u(o) check_exp((o)->tt == LUA_TUSERDATA, &((cast_u(o))->u)) #define gco2lcl(o) check_exp((o)->tt == LUA_TLCL, &((cast_u(o))->cl.l)) #define gco2ccl(o) check_exp((o)->tt == LUA_TCCL, &((cast_u(o))->cl.c)) #define gco2cl(o) \ check_exp(novariant((o)->tt) == LUA_TFUNCTION, &((cast_u(o))->cl)) #define gco2t(o) check_exp((o)->tt == LUA_TTABLE, &((cast_u(o))->h)) #define gco2p(o) check_exp((o)->tt == LUA_TPROTO, &((cast_u(o))->p)) #define gco2th(o) check_exp((o)->tt == LUA_TTHREAD, &((cast_u(o))->th)) /* macro to convert a Lua object into a GCObject */ #define obj2gco(v) \ check_exp(novariant((v)->tt) < LUA_TDEADKEY, (&(cast_u(v)->gc))) /* actual number of total bytes allocated */ #define gettotalbytes(g) cast(lu_mem, (g)->totalbytes + (g)->GCdebt) LUAI_FUNC void luaE_setdebt (global_State *g, l_mem debt); LUAI_FUNC void luaE_freethread (lua_State *L, lua_State *L1); LUAI_FUNC CallInfo *luaE_extendCI (lua_State *L); LUAI_FUNC void luaE_freeCI (lua_State *L); LUAI_FUNC void luaE_shrinkCI (lua_State *L); #endif
xLua/build/lua-5.3.4/src/lstate.h/0
{ "file_path": "xLua/build/lua-5.3.4/src/lstate.h", "repo_id": "xLua", "token_count": 2821 }
2,023
/* ** $Id: lundump.h,v 1.45 2015/09/08 15:41:05 roberto Exp $ ** load precompiled Lua chunks ** See Copyright Notice in lua.h */ #ifndef lundump_h #define lundump_h #include "llimits.h" #include "lobject.h" #include "lzio.h" /* data to catch conversion errors */ #define LUAC_DATA "\x19\x93\r\n\x1a\n" #define LUAC_INT 0x5678 #define LUAC_NUM cast_num(370.5) #define MYINT(s) (s[0]-'0') #define LUAC_VERSION (MYINT(LUA_VERSION_MAJOR)*16+MYINT(LUA_VERSION_MINOR)) #define LUAC_FORMAT 0 /* this is the official format */ /* load one chunk; from lundump.c */ LUAI_FUNC LClosure* luaU_undump (lua_State* L, ZIO* Z, const char* name); /* dump one chunk; from ldump.c */ LUAI_FUNC int luaU_dump (lua_State* L, const Proto* f, lua_Writer w, void* data, int strip); #endif
xLua/build/lua-5.3.4/src/lundump.h/0
{ "file_path": "xLua/build/lua-5.3.4/src/lundump.h", "repo_id": "xLua", "token_count": 359 }
2,024
/* ** $Id: ldebug.h,v 2.14.1.1 2017/04/19 17:20:42 roberto Exp $ ** Auxiliary functions from Debug Interface module ** See Copyright Notice in lua.h */ #ifndef ldebug_h #define ldebug_h #include "lstate.h" #define pcRel(pc, p) (cast(int, (pc) - (p)->code) - 1) #define getfuncline(f,pc) (((f)->lineinfo) ? (f)->lineinfo[pc] : -1) #define resethookcount(L) (L->hookcount = L->basehookcount) LUAI_FUNC l_noret luaG_typeerror (lua_State *L, const TValue *o, const char *opname); LUAI_FUNC l_noret luaG_concaterror (lua_State *L, const TValue *p1, const TValue *p2); LUAI_FUNC l_noret luaG_opinterror (lua_State *L, const TValue *p1, const TValue *p2, const char *msg); LUAI_FUNC l_noret luaG_tointerror (lua_State *L, const TValue *p1, const TValue *p2); LUAI_FUNC l_noret luaG_ordererror (lua_State *L, const TValue *p1, const TValue *p2); LUAI_FUNC l_noret luaG_runerror (lua_State *L, const char *fmt, ...); LUAI_FUNC const char *luaG_addinfo (lua_State *L, const char *msg, TString *src, int line); LUAI_FUNC l_noret luaG_errormsg (lua_State *L); LUAI_FUNC void luaG_traceexec (lua_State *L); #endif
xLua/build/lua-5.3.5/src/ldebug.h/0
{ "file_path": "xLua/build/lua-5.3.5/src/ldebug.h", "repo_id": "xLua", "token_count": 832 }
2,025
/* ** $Id: loadlib.c,v 1.130.1.1 2017/04/19 17:20:42 roberto Exp $ ** Dynamic library loader for Lua ** See Copyright Notice in lua.h ** ** This module contains an implementation of loadlib for Unix systems ** that have dlfcn, an implementation for Windows, and a stub for other ** systems. */ #define loadlib_c #define LUA_LIB #include "lprefix.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include "lua.h" #include "lauxlib.h" #include "lualib.h" /* ** LUA_IGMARK is a mark to ignore all before it when building the ** luaopen_ function name. */ #if !defined (LUA_IGMARK) #define LUA_IGMARK "-" #endif /* ** LUA_CSUBSEP is the character that replaces dots in submodule names ** when searching for a C loader. ** LUA_LSUBSEP is the character that replaces dots in submodule names ** when searching for a Lua loader. */ #if !defined(LUA_CSUBSEP) #define LUA_CSUBSEP LUA_DIRSEP #endif #if !defined(LUA_LSUBSEP) #define LUA_LSUBSEP LUA_DIRSEP #endif /* prefix for open functions in C libraries */ #define LUA_POF "luaopen_" /* separator for open functions in C libraries */ #define LUA_OFSEP "_" /* ** unique key for table in the registry that keeps handles ** for all loaded C libraries */ static const int CLIBS = 0; #define LIB_FAIL "open" #define setprogdir(L) ((void)0) /* ** system-dependent functions */ /* ** unload library 'lib' */ static void lsys_unloadlib (void *lib); /* ** load C library in file 'path'. If 'seeglb', load with all names in ** the library global. ** Returns the library; in case of error, returns NULL plus an ** error string in the stack. */ static void *lsys_load (lua_State *L, const char *path, int seeglb); /* ** Try to find a function named 'sym' in library 'lib'. ** Returns the function; in case of error, returns NULL plus an ** error string in the stack. */ static lua_CFunction lsys_sym (lua_State *L, void *lib, const char *sym); #if defined(LUA_USE_DLOPEN) /* { */ /* ** {======================================================================== ** This is an implementation of loadlib based on the dlfcn interface. ** The dlfcn interface is available in Linux, SunOS, Solaris, IRIX, FreeBSD, ** NetBSD, AIX 4.2, HPUX 11, and probably most other Unix flavors, at least ** as an emulation layer on top of native functions. ** ========================================================================= */ #include <dlfcn.h> /* ** Macro to convert pointer-to-void* to pointer-to-function. This cast ** is undefined according to ISO C, but POSIX assumes that it works. ** (The '__extension__' in gnu compilers is only to avoid warnings.) */ #if defined(__GNUC__) #define cast_func(p) (__extension__ (lua_CFunction)(p)) #else #define cast_func(p) ((lua_CFunction)(p)) #endif static void lsys_unloadlib (void *lib) { dlclose(lib); } static void *lsys_load (lua_State *L, const char *path, int seeglb) { void *lib = dlopen(path, RTLD_NOW | (seeglb ? RTLD_GLOBAL : RTLD_LOCAL)); if (lib == NULL) lua_pushstring(L, dlerror()); return lib; } static lua_CFunction lsys_sym (lua_State *L, void *lib, const char *sym) { lua_CFunction f = cast_func(dlsym(lib, sym)); if (f == NULL) lua_pushstring(L, dlerror()); return f; } /* }====================================================== */ #elif defined(LUA_DL_DLL) /* }{ */ /* ** {====================================================================== ** This is an implementation of loadlib for Windows using native functions. ** ======================================================================= */ #include <windows.h> /* ** optional flags for LoadLibraryEx */ #if !defined(LUA_LLE_FLAGS) #define LUA_LLE_FLAGS 0 #endif #undef setprogdir /* ** Replace in the path (on the top of the stack) any occurrence ** of LUA_EXEC_DIR with the executable's path. */ static void setprogdir (lua_State *L) { char buff[MAX_PATH + 1]; char *lb; DWORD nsize = sizeof(buff)/sizeof(char); DWORD n = GetModuleFileNameA(NULL, buff, nsize); /* get exec. name */ if (n == 0 || n == nsize || (lb = strrchr(buff, '\\')) == NULL) luaL_error(L, "unable to get ModuleFileName"); else { *lb = '\0'; /* cut name on the last '\\' to get the path */ luaL_gsub(L, lua_tostring(L, -1), LUA_EXEC_DIR, buff); lua_remove(L, -2); /* remove original string */ } } static void pusherror (lua_State *L) { int error = GetLastError(); char buffer[128]; if (FormatMessageA(FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM, NULL, error, 0, buffer, sizeof(buffer)/sizeof(char), NULL)) lua_pushstring(L, buffer); else lua_pushfstring(L, "system error %d\n", error); } static void lsys_unloadlib (void *lib) { FreeLibrary((HMODULE)lib); } static void *lsys_load (lua_State *L, const char *path, int seeglb) { HMODULE lib = LoadLibraryExA(path, NULL, LUA_LLE_FLAGS); (void)(seeglb); /* not used: symbols are 'global' by default */ if (lib == NULL) pusherror(L); return lib; } static lua_CFunction lsys_sym (lua_State *L, void *lib, const char *sym) { lua_CFunction f = (lua_CFunction)GetProcAddress((HMODULE)lib, sym); if (f == NULL) pusherror(L); return f; } /* }====================================================== */ #else /* }{ */ /* ** {====================================================== ** Fallback for other systems ** ======================================================= */ #undef LIB_FAIL #define LIB_FAIL "absent" #define DLMSG "dynamic libraries not enabled; check your Lua installation" static void lsys_unloadlib (void *lib) { (void)(lib); /* not used */ } static void *lsys_load (lua_State *L, const char *path, int seeglb) { (void)(path); (void)(seeglb); /* not used */ lua_pushliteral(L, DLMSG); return NULL; } static lua_CFunction lsys_sym (lua_State *L, void *lib, const char *sym) { (void)(lib); (void)(sym); /* not used */ lua_pushliteral(L, DLMSG); return NULL; } /* }====================================================== */ #endif /* } */ /* ** {================================================================== ** Set Paths ** =================================================================== */ /* ** LUA_PATH_VAR and LUA_CPATH_VAR are the names of the environment ** variables that Lua check to set its paths. */ #if !defined(LUA_PATH_VAR) #define LUA_PATH_VAR "LUA_PATH" #endif #if !defined(LUA_CPATH_VAR) #define LUA_CPATH_VAR "LUA_CPATH" #endif #define AUXMARK "\1" /* auxiliary mark */ /* ** return registry.LUA_NOENV as a boolean */ static int noenv (lua_State *L) { int b; lua_getfield(L, LUA_REGISTRYINDEX, "LUA_NOENV"); b = lua_toboolean(L, -1); lua_pop(L, 1); /* remove value */ return b; } /* ** Set a path */ static void setpath (lua_State *L, const char *fieldname, const char *envname, const char *dft) { const char *nver = lua_pushfstring(L, "%s%s", envname, LUA_VERSUFFIX); #if defined(WINAPI_FAMILY_PARTITION) const char *path = NULL; #else const char *path = getenv(nver); /* use versioned name */ if (path == NULL) /* no environment variable? */ path = getenv(envname); /* try unversioned name */ #endif if (path == NULL || noenv(L)) /* no environment variable? */ lua_pushstring(L, dft); /* use default */ else { /* replace ";;" by ";AUXMARK;" and then AUXMARK by default path */ path = luaL_gsub(L, path, LUA_PATH_SEP LUA_PATH_SEP, LUA_PATH_SEP AUXMARK LUA_PATH_SEP); luaL_gsub(L, path, AUXMARK, dft); lua_remove(L, -2); /* remove result from 1st 'gsub' */ } setprogdir(L); lua_setfield(L, -3, fieldname); /* package[fieldname] = path value */ lua_pop(L, 1); /* pop versioned variable name */ } /* }================================================================== */ /* ** return registry.CLIBS[path] */ static void *checkclib (lua_State *L, const char *path) { void *plib; lua_rawgetp(L, LUA_REGISTRYINDEX, &CLIBS); lua_getfield(L, -1, path); plib = lua_touserdata(L, -1); /* plib = CLIBS[path] */ lua_pop(L, 2); /* pop CLIBS table and 'plib' */ return plib; } /* ** registry.CLIBS[path] = plib -- for queries ** registry.CLIBS[#CLIBS + 1] = plib -- also keep a list of all libraries */ static void addtoclib (lua_State *L, const char *path, void *plib) { lua_rawgetp(L, LUA_REGISTRYINDEX, &CLIBS); lua_pushlightuserdata(L, plib); lua_pushvalue(L, -1); lua_setfield(L, -3, path); /* CLIBS[path] = plib */ lua_rawseti(L, -2, luaL_len(L, -2) + 1); /* CLIBS[#CLIBS + 1] = plib */ lua_pop(L, 1); /* pop CLIBS table */ } /* ** __gc tag method for CLIBS table: calls 'lsys_unloadlib' for all lib ** handles in list CLIBS */ static int gctm (lua_State *L) { lua_Integer n = luaL_len(L, 1); for (; n >= 1; n--) { /* for each handle, in reverse order */ lua_rawgeti(L, 1, n); /* get handle CLIBS[n] */ lsys_unloadlib(lua_touserdata(L, -1)); lua_pop(L, 1); /* pop handle */ } return 0; } /* error codes for 'lookforfunc' */ #define ERRLIB 1 #define ERRFUNC 2 /* ** Look for a C function named 'sym' in a dynamically loaded library ** 'path'. ** First, check whether the library is already loaded; if not, try ** to load it. ** Then, if 'sym' is '*', return true (as library has been loaded). ** Otherwise, look for symbol 'sym' in the library and push a ** C function with that symbol. ** Return 0 and 'true' or a function in the stack; in case of ** errors, return an error code and an error message in the stack. */ static int lookforfunc (lua_State *L, const char *path, const char *sym) { void *reg = checkclib(L, path); /* check loaded C libraries */ if (reg == NULL) { /* must load library? */ reg = lsys_load(L, path, *sym == '*'); /* global symbols if 'sym'=='*' */ if (reg == NULL) return ERRLIB; /* unable to load library */ addtoclib(L, path, reg); } if (*sym == '*') { /* loading only library (no function)? */ lua_pushboolean(L, 1); /* return 'true' */ return 0; /* no errors */ } else { lua_CFunction f = lsys_sym(L, reg, sym); if (f == NULL) return ERRFUNC; /* unable to find function */ lua_pushcfunction(L, f); /* else create new function */ return 0; /* no errors */ } } static int ll_loadlib (lua_State *L) { const char *path = luaL_checkstring(L, 1); const char *init = luaL_checkstring(L, 2); int stat = lookforfunc(L, path, init); if (stat == 0) /* no errors? */ return 1; /* return the loaded function */ else { /* error; error message is on stack top */ lua_pushnil(L); lua_insert(L, -2); lua_pushstring(L, (stat == ERRLIB) ? LIB_FAIL : "init"); return 3; /* return nil, error message, and where */ } } /* ** {====================================================== ** 'require' function ** ======================================================= */ static int readable (const char *filename) { FILE *f = fopen(filename, "r"); /* try to open file */ if (f == NULL) return 0; /* open failed */ fclose(f); return 1; } static const char *pushnexttemplate (lua_State *L, const char *path) { const char *l; while (*path == *LUA_PATH_SEP) path++; /* skip separators */ if (*path == '\0') return NULL; /* no more templates */ l = strchr(path, *LUA_PATH_SEP); /* find next separator */ if (l == NULL) l = path + strlen(path); lua_pushlstring(L, path, l - path); /* template */ return l; } static const char *searchpath (lua_State *L, const char *name, const char *path, const char *sep, const char *dirsep) { luaL_Buffer msg; /* to build error message */ luaL_buffinit(L, &msg); if (*sep != '\0') /* non-empty separator? */ name = luaL_gsub(L, name, sep, dirsep); /* replace it by 'dirsep' */ while ((path = pushnexttemplate(L, path)) != NULL) { const char *filename = luaL_gsub(L, lua_tostring(L, -1), LUA_PATH_MARK, name); lua_remove(L, -2); /* remove path template */ if (readable(filename)) /* does file exist and is readable? */ return filename; /* return that file name */ lua_pushfstring(L, "\n\tno file '%s'", filename); lua_remove(L, -2); /* remove file name */ luaL_addvalue(&msg); /* concatenate error msg. entry */ } luaL_pushresult(&msg); /* create error message */ return NULL; /* not found */ } static int ll_searchpath (lua_State *L) { const char *f = searchpath(L, luaL_checkstring(L, 1), luaL_checkstring(L, 2), luaL_optstring(L, 3, "."), luaL_optstring(L, 4, LUA_DIRSEP)); if (f != NULL) return 1; else { /* error message is on top of the stack */ lua_pushnil(L); lua_insert(L, -2); return 2; /* return nil + error message */ } } static const char *findfile (lua_State *L, const char *name, const char *pname, const char *dirsep) { const char *path; lua_getfield(L, lua_upvalueindex(1), pname); path = lua_tostring(L, -1); if (path == NULL) luaL_error(L, "'package.%s' must be a string", pname); return searchpath(L, name, path, ".", dirsep); } static int checkload (lua_State *L, int stat, const char *filename) { if (stat) { /* module loaded successfully? */ lua_pushstring(L, filename); /* will be 2nd argument to module */ return 2; /* return open function and file name */ } else return luaL_error(L, "error loading module '%s' from file '%s':\n\t%s", lua_tostring(L, 1), filename, lua_tostring(L, -1)); } static int searcher_Lua (lua_State *L) { const char *filename; const char *name = luaL_checkstring(L, 1); filename = findfile(L, name, "path", LUA_LSUBSEP); if (filename == NULL) return 1; /* module not found in this path */ return checkload(L, (luaL_loadfile(L, filename) == LUA_OK), filename); } /* ** Try to find a load function for module 'modname' at file 'filename'. ** First, change '.' to '_' in 'modname'; then, if 'modname' has ** the form X-Y (that is, it has an "ignore mark"), build a function ** name "luaopen_X" and look for it. (For compatibility, if that ** fails, it also tries "luaopen_Y".) If there is no ignore mark, ** look for a function named "luaopen_modname". */ static int loadfunc (lua_State *L, const char *filename, const char *modname) { const char *openfunc; const char *mark; modname = luaL_gsub(L, modname, ".", LUA_OFSEP); mark = strchr(modname, *LUA_IGMARK); if (mark) { int stat; openfunc = lua_pushlstring(L, modname, mark - modname); openfunc = lua_pushfstring(L, LUA_POF"%s", openfunc); stat = lookforfunc(L, filename, openfunc); if (stat != ERRFUNC) return stat; modname = mark + 1; /* else go ahead and try old-style name */ } openfunc = lua_pushfstring(L, LUA_POF"%s", modname); return lookforfunc(L, filename, openfunc); } static int searcher_C (lua_State *L) { const char *name = luaL_checkstring(L, 1); const char *filename = findfile(L, name, "cpath", LUA_CSUBSEP); if (filename == NULL) return 1; /* module not found in this path */ return checkload(L, (loadfunc(L, filename, name) == 0), filename); } static int searcher_Croot (lua_State *L) { const char *filename; const char *name = luaL_checkstring(L, 1); const char *p = strchr(name, '.'); int stat; if (p == NULL) return 0; /* is root */ lua_pushlstring(L, name, p - name); filename = findfile(L, lua_tostring(L, -1), "cpath", LUA_CSUBSEP); if (filename == NULL) return 1; /* root not found */ if ((stat = loadfunc(L, filename, name)) != 0) { if (stat != ERRFUNC) return checkload(L, 0, filename); /* real error */ else { /* open function not found */ lua_pushfstring(L, "\n\tno module '%s' in file '%s'", name, filename); return 1; } } lua_pushstring(L, filename); /* will be 2nd argument to module */ return 2; } static int searcher_preload (lua_State *L) { const char *name = luaL_checkstring(L, 1); lua_getfield(L, LUA_REGISTRYINDEX, LUA_PRELOAD_TABLE); if (lua_getfield(L, -1, name) == LUA_TNIL) /* not found? */ lua_pushfstring(L, "\n\tno field package.preload['%s']", name); return 1; } static void findloader (lua_State *L, const char *name) { int i; luaL_Buffer msg; /* to build error message */ luaL_buffinit(L, &msg); /* push 'package.searchers' to index 3 in the stack */ if (lua_getfield(L, lua_upvalueindex(1), "searchers") != LUA_TTABLE) luaL_error(L, "'package.searchers' must be a table"); /* iterate over available searchers to find a loader */ for (i = 1; ; i++) { if (lua_rawgeti(L, 3, i) == LUA_TNIL) { /* no more searchers? */ lua_pop(L, 1); /* remove nil */ luaL_pushresult(&msg); /* create error message */ luaL_error(L, "module '%s' not found:%s", name, lua_tostring(L, -1)); } lua_pushstring(L, name); lua_call(L, 1, 2); /* call it */ if (lua_isfunction(L, -2)) /* did it find a loader? */ return; /* module loader found */ else if (lua_isstring(L, -2)) { /* searcher returned error message? */ lua_pop(L, 1); /* remove extra return */ luaL_addvalue(&msg); /* concatenate error message */ } else lua_pop(L, 2); /* remove both returns */ } } static int ll_require (lua_State *L) { const char *name = luaL_checkstring(L, 1); lua_settop(L, 1); /* LOADED table will be at index 2 */ lua_getfield(L, LUA_REGISTRYINDEX, LUA_LOADED_TABLE); lua_getfield(L, 2, name); /* LOADED[name] */ if (lua_toboolean(L, -1)) /* is it there? */ return 1; /* package is already loaded */ /* else must load package */ lua_pop(L, 1); /* remove 'getfield' result */ findloader(L, name); lua_pushstring(L, name); /* pass name as argument to module loader */ lua_insert(L, -2); /* name is 1st argument (before search data) */ lua_call(L, 2, 1); /* run loader to load module */ if (!lua_isnil(L, -1)) /* non-nil return? */ lua_setfield(L, 2, name); /* LOADED[name] = returned value */ if (lua_getfield(L, 2, name) == LUA_TNIL) { /* module set no value? */ lua_pushboolean(L, 1); /* use true as result */ lua_pushvalue(L, -1); /* extra copy to be returned */ lua_setfield(L, 2, name); /* LOADED[name] = true */ } return 1; } /* }====================================================== */ /* ** {====================================================== ** 'module' function ** ======================================================= */ #if defined(LUA_COMPAT_MODULE) /* ** changes the environment variable of calling function */ static void set_env (lua_State *L) { lua_Debug ar; if (lua_getstack(L, 1, &ar) == 0 || lua_getinfo(L, "f", &ar) == 0 || /* get calling function */ lua_iscfunction(L, -1)) luaL_error(L, "'module' not called from a Lua function"); lua_pushvalue(L, -2); /* copy new environment table to top */ lua_setupvalue(L, -2, 1); lua_pop(L, 1); /* remove function */ } static void dooptions (lua_State *L, int n) { int i; for (i = 2; i <= n; i++) { if (lua_isfunction(L, i)) { /* avoid 'calling' extra info. */ lua_pushvalue(L, i); /* get option (a function) */ lua_pushvalue(L, -2); /* module */ lua_call(L, 1, 0); } } } static void modinit (lua_State *L, const char *modname) { const char *dot; lua_pushvalue(L, -1); lua_setfield(L, -2, "_M"); /* module._M = module */ lua_pushstring(L, modname); lua_setfield(L, -2, "_NAME"); dot = strrchr(modname, '.'); /* look for last dot in module name */ if (dot == NULL) dot = modname; else dot++; /* set _PACKAGE as package name (full module name minus last part) */ lua_pushlstring(L, modname, dot - modname); lua_setfield(L, -2, "_PACKAGE"); } static int ll_module (lua_State *L) { const char *modname = luaL_checkstring(L, 1); int lastarg = lua_gettop(L); /* last parameter */ luaL_pushmodule(L, modname, 1); /* get/create module table */ /* check whether table already has a _NAME field */ if (lua_getfield(L, -1, "_NAME") != LUA_TNIL) lua_pop(L, 1); /* table is an initialized module */ else { /* no; initialize it */ lua_pop(L, 1); modinit(L, modname); } lua_pushvalue(L, -1); set_env(L); dooptions(L, lastarg); return 1; } static int ll_seeall (lua_State *L) { luaL_checktype(L, 1, LUA_TTABLE); if (!lua_getmetatable(L, 1)) { lua_createtable(L, 0, 1); /* create new metatable */ lua_pushvalue(L, -1); lua_setmetatable(L, 1); } lua_pushglobaltable(L); lua_setfield(L, -2, "__index"); /* mt.__index = _G */ return 0; } #endif /* }====================================================== */ static const luaL_Reg pk_funcs[] = { {"loadlib", ll_loadlib}, {"searchpath", ll_searchpath}, #if defined(LUA_COMPAT_MODULE) {"seeall", ll_seeall}, #endif /* placeholders */ {"preload", NULL}, {"cpath", NULL}, {"path", NULL}, {"searchers", NULL}, {"loaded", NULL}, {NULL, NULL} }; static const luaL_Reg ll_funcs[] = { #if defined(LUA_COMPAT_MODULE) {"module", ll_module}, #endif {"require", ll_require}, {NULL, NULL} }; static void createsearcherstable (lua_State *L) { static const lua_CFunction searchers[] = {searcher_preload, searcher_Lua, searcher_C, searcher_Croot, NULL}; int i; /* create 'searchers' table */ lua_createtable(L, sizeof(searchers)/sizeof(searchers[0]) - 1, 0); /* fill it with predefined searchers */ for (i=0; searchers[i] != NULL; i++) { lua_pushvalue(L, -2); /* set 'package' as upvalue for all searchers */ lua_pushcclosure(L, searchers[i], 1); lua_rawseti(L, -2, i+1); } #if defined(LUA_COMPAT_LOADERS) lua_pushvalue(L, -1); /* make a copy of 'searchers' table */ lua_setfield(L, -3, "loaders"); /* put it in field 'loaders' */ #endif lua_setfield(L, -2, "searchers"); /* put it in field 'searchers' */ } /* ** create table CLIBS to keep track of loaded C libraries, ** setting a finalizer to close all libraries when closing state. */ static void createclibstable (lua_State *L) { lua_newtable(L); /* create CLIBS table */ lua_createtable(L, 0, 1); /* create metatable for CLIBS */ lua_pushcfunction(L, gctm); lua_setfield(L, -2, "__gc"); /* set finalizer for CLIBS table */ lua_setmetatable(L, -2); lua_rawsetp(L, LUA_REGISTRYINDEX, &CLIBS); /* set CLIBS table in registry */ } LUAMOD_API int luaopen_package (lua_State *L) { createclibstable(L); luaL_newlib(L, pk_funcs); /* create 'package' table */ createsearcherstable(L); /* set paths */ setpath(L, "path", LUA_PATH_VAR, LUA_PATH_DEFAULT); setpath(L, "cpath", LUA_CPATH_VAR, LUA_CPATH_DEFAULT); /* store config information */ lua_pushliteral(L, LUA_DIRSEP "\n" LUA_PATH_SEP "\n" LUA_PATH_MARK "\n" LUA_EXEC_DIR "\n" LUA_IGMARK "\n"); lua_setfield(L, -2, "config"); /* set field 'loaded' */ luaL_getsubtable(L, LUA_REGISTRYINDEX, LUA_LOADED_TABLE); lua_setfield(L, -2, "loaded"); /* set field 'preload' */ luaL_getsubtable(L, LUA_REGISTRYINDEX, LUA_PRELOAD_TABLE); lua_setfield(L, -2, "preload"); lua_pushglobaltable(L); lua_pushvalue(L, -2); /* set 'package' as upvalue for next lib */ luaL_setfuncs(L, ll_funcs, 1); /* open lib into global table */ lua_pop(L, 1); /* pop global table */ return 1; /* return 'package' table */ }
xLua/build/lua-5.3.5/src/loadlib.c/0
{ "file_path": "xLua/build/lua-5.3.5/src/loadlib.c", "repo_id": "xLua", "token_count": 9305 }
2,026
/* ** $Id: ltablib.c,v 1.93.1.1 2017/04/19 17:20:42 roberto Exp $ ** Library for Table Manipulation ** See Copyright Notice in lua.h */ #define ltablib_c #define LUA_LIB #include "lprefix.h" #include <limits.h> #include <stddef.h> #include <string.h> #include "lua.h" #include "lauxlib.h" #include "lualib.h" /* ** Operations that an object must define to mimic a table ** (some functions only need some of them) */ #define TAB_R 1 /* read */ #define TAB_W 2 /* write */ #define TAB_L 4 /* length */ #define TAB_RW (TAB_R | TAB_W) /* read/write */ #define aux_getn(L,n,w) (checktab(L, n, (w) | TAB_L), luaL_len(L, n)) static int checkfield (lua_State *L, const char *key, int n) { lua_pushstring(L, key); return (lua_rawget(L, -n) != LUA_TNIL); } /* ** Check that 'arg' either is a table or can behave like one (that is, ** has a metatable with the required metamethods) */ static void checktab (lua_State *L, int arg, int what) { if (lua_type(L, arg) != LUA_TTABLE) { /* is it not a table? */ int n = 1; /* number of elements to pop */ if (lua_getmetatable(L, arg) && /* must have metatable */ (!(what & TAB_R) || checkfield(L, "__index", ++n)) && (!(what & TAB_W) || checkfield(L, "__newindex", ++n)) && (!(what & TAB_L) || checkfield(L, "__len", ++n))) { lua_pop(L, n); /* pop metatable and tested metamethods */ } else luaL_checktype(L, arg, LUA_TTABLE); /* force an error */ } } #if defined(LUA_COMPAT_MAXN) static int maxn (lua_State *L) { lua_Number max = 0; luaL_checktype(L, 1, LUA_TTABLE); lua_pushnil(L); /* first key */ while (lua_next(L, 1)) { lua_pop(L, 1); /* remove value */ if (lua_type(L, -1) == LUA_TNUMBER) { lua_Number v = lua_tonumber(L, -1); if (v > max) max = v; } } lua_pushnumber(L, max); return 1; } #endif static int tinsert (lua_State *L) { lua_Integer e = aux_getn(L, 1, TAB_RW) + 1; /* first empty element */ lua_Integer pos; /* where to insert new element */ switch (lua_gettop(L)) { case 2: { /* called with only 2 arguments */ pos = e; /* insert new element at the end */ break; } case 3: { lua_Integer i; pos = luaL_checkinteger(L, 2); /* 2nd argument is the position */ luaL_argcheck(L, 1 <= pos && pos <= e, 2, "position out of bounds"); for (i = e; i > pos; i--) { /* move up elements */ lua_geti(L, 1, i - 1); lua_seti(L, 1, i); /* t[i] = t[i - 1] */ } break; } default: { return luaL_error(L, "wrong number of arguments to 'insert'"); } } lua_seti(L, 1, pos); /* t[pos] = v */ return 0; } static int tremove (lua_State *L) { lua_Integer size = aux_getn(L, 1, TAB_RW); lua_Integer pos = luaL_optinteger(L, 2, size); if (pos != size) /* validate 'pos' if given */ luaL_argcheck(L, 1 <= pos && pos <= size + 1, 1, "position out of bounds"); lua_geti(L, 1, pos); /* result = t[pos] */ for ( ; pos < size; pos++) { lua_geti(L, 1, pos + 1); lua_seti(L, 1, pos); /* t[pos] = t[pos + 1] */ } lua_pushnil(L); lua_seti(L, 1, pos); /* t[pos] = nil */ return 1; } /* ** Copy elements (1[f], ..., 1[e]) into (tt[t], tt[t+1], ...). Whenever ** possible, copy in increasing order, which is better for rehashing. ** "possible" means destination after original range, or smaller ** than origin, or copying to another table. */ static int tmove (lua_State *L) { lua_Integer f = luaL_checkinteger(L, 2); lua_Integer e = luaL_checkinteger(L, 3); lua_Integer t = luaL_checkinteger(L, 4); int tt = !lua_isnoneornil(L, 5) ? 5 : 1; /* destination table */ checktab(L, 1, TAB_R); checktab(L, tt, TAB_W); if (e >= f) { /* otherwise, nothing to move */ lua_Integer n, i; luaL_argcheck(L, f > 0 || e < LUA_MAXINTEGER + f, 3, "too many elements to move"); n = e - f + 1; /* number of elements to move */ luaL_argcheck(L, t <= LUA_MAXINTEGER - n + 1, 4, "destination wrap around"); if (t > e || t <= f || (tt != 1 && !lua_compare(L, 1, tt, LUA_OPEQ))) { for (i = 0; i < n; i++) { lua_geti(L, 1, f + i); lua_seti(L, tt, t + i); } } else { for (i = n - 1; i >= 0; i--) { lua_geti(L, 1, f + i); lua_seti(L, tt, t + i); } } } lua_pushvalue(L, tt); /* return destination table */ return 1; } static void addfield (lua_State *L, luaL_Buffer *b, lua_Integer i) { lua_geti(L, 1, i); if (!lua_isstring(L, -1)) luaL_error(L, "invalid value (%s) at index %d in table for 'concat'", luaL_typename(L, -1), i); luaL_addvalue(b); } static int tconcat (lua_State *L) { luaL_Buffer b; lua_Integer last = aux_getn(L, 1, TAB_R); size_t lsep; const char *sep = luaL_optlstring(L, 2, "", &lsep); lua_Integer i = luaL_optinteger(L, 3, 1); last = luaL_optinteger(L, 4, last); luaL_buffinit(L, &b); for (; i < last; i++) { addfield(L, &b, i); luaL_addlstring(&b, sep, lsep); } if (i == last) /* add last value (if interval was not empty) */ addfield(L, &b, i); luaL_pushresult(&b); return 1; } /* ** {====================================================== ** Pack/unpack ** ======================================================= */ static int pack (lua_State *L) { int i; int n = lua_gettop(L); /* number of elements to pack */ lua_createtable(L, n, 1); /* create result table */ lua_insert(L, 1); /* put it at index 1 */ for (i = n; i >= 1; i--) /* assign elements */ lua_seti(L, 1, i); lua_pushinteger(L, n); lua_setfield(L, 1, "n"); /* t.n = number of elements */ return 1; /* return table */ } static int unpack (lua_State *L) { lua_Unsigned n; lua_Integer i = luaL_optinteger(L, 2, 1); lua_Integer e = luaL_opt(L, luaL_checkinteger, 3, luaL_len(L, 1)); if (i > e) return 0; /* empty range */ n = (lua_Unsigned)e - i; /* number of elements minus 1 (avoid overflows) */ if (n >= (unsigned int)INT_MAX || !lua_checkstack(L, (int)(++n))) return luaL_error(L, "too many results to unpack"); for (; i < e; i++) { /* push arg[i..e - 1] (to avoid overflows) */ lua_geti(L, 1, i); } lua_geti(L, 1, e); /* push last element */ return (int)n; } /* }====================================================== */ /* ** {====================================================== ** Quicksort ** (based on 'Algorithms in MODULA-3', Robert Sedgewick; ** Addison-Wesley, 1993.) ** ======================================================= */ /* type for array indices */ typedef unsigned int IdxT; /* ** Produce a "random" 'unsigned int' to randomize pivot choice. This ** macro is used only when 'sort' detects a big imbalance in the result ** of a partition. (If you don't want/need this "randomness", ~0 is a ** good choice.) */ #if !defined(l_randomizePivot) /* { */ #include <time.h> /* size of 'e' measured in number of 'unsigned int's */ #define sof(e) (sizeof(e) / sizeof(unsigned int)) /* ** Use 'time' and 'clock' as sources of "randomness". Because we don't ** know the types 'clock_t' and 'time_t', we cannot cast them to ** anything without risking overflows. A safe way to use their values ** is to copy them to an array of a known type and use the array values. */ static unsigned int l_randomizePivot (void) { clock_t c = clock(); time_t t = time(NULL); unsigned int buff[sof(c) + sof(t)]; unsigned int i, rnd = 0; memcpy(buff, &c, sof(c) * sizeof(unsigned int)); memcpy(buff + sof(c), &t, sof(t) * sizeof(unsigned int)); for (i = 0; i < sof(buff); i++) rnd += buff[i]; return rnd; } #endif /* } */ /* arrays larger than 'RANLIMIT' may use randomized pivots */ #define RANLIMIT 100u static void set2 (lua_State *L, IdxT i, IdxT j) { lua_seti(L, 1, i); lua_seti(L, 1, j); } /* ** Return true iff value at stack index 'a' is less than the value at ** index 'b' (according to the order of the sort). */ static int sort_comp (lua_State *L, int a, int b) { if (lua_isnil(L, 2)) /* no function? */ return lua_compare(L, a, b, LUA_OPLT); /* a < b */ else { /* function */ int res; lua_pushvalue(L, 2); /* push function */ lua_pushvalue(L, a-1); /* -1 to compensate function */ lua_pushvalue(L, b-2); /* -2 to compensate function and 'a' */ lua_call(L, 2, 1); /* call function */ res = lua_toboolean(L, -1); /* get result */ lua_pop(L, 1); /* pop result */ return res; } } /* ** Does the partition: Pivot P is at the top of the stack. ** precondition: a[lo] <= P == a[up-1] <= a[up], ** so it only needs to do the partition from lo + 1 to up - 2. ** Pos-condition: a[lo .. i - 1] <= a[i] == P <= a[i + 1 .. up] ** returns 'i'. */ static IdxT partition (lua_State *L, IdxT lo, IdxT up) { IdxT i = lo; /* will be incremented before first use */ IdxT j = up - 1; /* will be decremented before first use */ /* loop invariant: a[lo .. i] <= P <= a[j .. up] */ for (;;) { /* next loop: repeat ++i while a[i] < P */ while (lua_geti(L, 1, ++i), sort_comp(L, -1, -2)) { if (i == up - 1) /* a[i] < P but a[up - 1] == P ?? */ luaL_error(L, "invalid order function for sorting"); lua_pop(L, 1); /* remove a[i] */ } /* after the loop, a[i] >= P and a[lo .. i - 1] < P */ /* next loop: repeat --j while P < a[j] */ while (lua_geti(L, 1, --j), sort_comp(L, -3, -1)) { if (j < i) /* j < i but a[j] > P ?? */ luaL_error(L, "invalid order function for sorting"); lua_pop(L, 1); /* remove a[j] */ } /* after the loop, a[j] <= P and a[j + 1 .. up] >= P */ if (j < i) { /* no elements out of place? */ /* a[lo .. i - 1] <= P <= a[j + 1 .. i .. up] */ lua_pop(L, 1); /* pop a[j] */ /* swap pivot (a[up - 1]) with a[i] to satisfy pos-condition */ set2(L, up - 1, i); return i; } /* otherwise, swap a[i] - a[j] to restore invariant and repeat */ set2(L, i, j); } } /* ** Choose an element in the middle (2nd-3th quarters) of [lo,up] ** "randomized" by 'rnd' */ static IdxT choosePivot (IdxT lo, IdxT up, unsigned int rnd) { IdxT r4 = (up - lo) / 4; /* range/4 */ IdxT p = rnd % (r4 * 2) + (lo + r4); lua_assert(lo + r4 <= p && p <= up - r4); return p; } /* ** QuickSort algorithm (recursive function) */ static void auxsort (lua_State *L, IdxT lo, IdxT up, unsigned int rnd) { while (lo < up) { /* loop for tail recursion */ IdxT p; /* Pivot index */ IdxT n; /* to be used later */ /* sort elements 'lo', 'p', and 'up' */ lua_geti(L, 1, lo); lua_geti(L, 1, up); if (sort_comp(L, -1, -2)) /* a[up] < a[lo]? */ set2(L, lo, up); /* swap a[lo] - a[up] */ else lua_pop(L, 2); /* remove both values */ if (up - lo == 1) /* only 2 elements? */ return; /* already sorted */ if (up - lo < RANLIMIT || rnd == 0) /* small interval or no randomize? */ p = (lo + up)/2; /* middle element is a good pivot */ else /* for larger intervals, it is worth a random pivot */ p = choosePivot(lo, up, rnd); lua_geti(L, 1, p); lua_geti(L, 1, lo); if (sort_comp(L, -2, -1)) /* a[p] < a[lo]? */ set2(L, p, lo); /* swap a[p] - a[lo] */ else { lua_pop(L, 1); /* remove a[lo] */ lua_geti(L, 1, up); if (sort_comp(L, -1, -2)) /* a[up] < a[p]? */ set2(L, p, up); /* swap a[up] - a[p] */ else lua_pop(L, 2); } if (up - lo == 2) /* only 3 elements? */ return; /* already sorted */ lua_geti(L, 1, p); /* get middle element (Pivot) */ lua_pushvalue(L, -1); /* push Pivot */ lua_geti(L, 1, up - 1); /* push a[up - 1] */ set2(L, p, up - 1); /* swap Pivot (a[p]) with a[up - 1] */ p = partition(L, lo, up); /* a[lo .. p - 1] <= a[p] == P <= a[p + 1 .. up] */ if (p - lo < up - p) { /* lower interval is smaller? */ auxsort(L, lo, p - 1, rnd); /* call recursively for lower interval */ n = p - lo; /* size of smaller interval */ lo = p + 1; /* tail call for [p + 1 .. up] (upper interval) */ } else { auxsort(L, p + 1, up, rnd); /* call recursively for upper interval */ n = up - p; /* size of smaller interval */ up = p - 1; /* tail call for [lo .. p - 1] (lower interval) */ } if ((up - lo) / 128 > n) /* partition too imbalanced? */ rnd = l_randomizePivot(); /* try a new randomization */ } /* tail call auxsort(L, lo, up, rnd) */ } static int sort (lua_State *L) { lua_Integer n = aux_getn(L, 1, TAB_RW); if (n > 1) { /* non-trivial interval? */ luaL_argcheck(L, n < INT_MAX, 1, "array too big"); if (!lua_isnoneornil(L, 2)) /* is there a 2nd argument? */ luaL_checktype(L, 2, LUA_TFUNCTION); /* must be a function */ lua_settop(L, 2); /* make sure there are two arguments */ auxsort(L, 1, (IdxT)n, 0); } return 0; } /* }====================================================== */ static const luaL_Reg tab_funcs[] = { {"concat", tconcat}, #if defined(LUA_COMPAT_MAXN) {"maxn", maxn}, #endif {"insert", tinsert}, {"pack", pack}, {"unpack", unpack}, {"remove", tremove}, {"move", tmove}, {"sort", sort}, {NULL, NULL} }; LUAMOD_API int luaopen_table (lua_State *L) { luaL_newlib(L, tab_funcs); #if defined(LUA_COMPAT_UNPACK) /* _G.unpack = table.unpack */ lua_getfield(L, -1, "unpack"); lua_setglobal(L, "unpack"); #endif return 1; }
xLua/build/lua-5.3.5/src/ltablib.c/0
{ "file_path": "xLua/build/lua-5.3.5/src/ltablib.c", "repo_id": "xLua", "token_count": 5954 }
2,027
# Makefile for installing Lua # See doc/readme.html for installation and customization instructions. # == CHANGE THE SETTINGS BELOW TO SUIT YOUR ENVIRONMENT ======================= # Your platform. See PLATS for possible values. PLAT= guess # Where to install. The installation starts in the src and doc directories, # so take care if INSTALL_TOP is not an absolute path. See the local target. # You may want to make INSTALL_LMOD and INSTALL_CMOD consistent with # LUA_ROOT, LUA_LDIR, and LUA_CDIR in luaconf.h. INSTALL_TOP= /usr/local INSTALL_BIN= $(INSTALL_TOP)/bin INSTALL_INC= $(INSTALL_TOP)/include INSTALL_LIB= $(INSTALL_TOP)/lib INSTALL_MAN= $(INSTALL_TOP)/man/man1 INSTALL_LMOD= $(INSTALL_TOP)/share/lua/$V INSTALL_CMOD= $(INSTALL_TOP)/lib/lua/$V # How to install. If your install program does not support "-p", then # you may have to run ranlib on the installed liblua.a. INSTALL= install -p INSTALL_EXEC= $(INSTALL) -m 0755 INSTALL_DATA= $(INSTALL) -m 0644 # # If you don't have "install" you can use "cp" instead. # INSTALL= cp -p # INSTALL_EXEC= $(INSTALL) # INSTALL_DATA= $(INSTALL) # Other utilities. MKDIR= mkdir -p RM= rm -f # == END OF USER SETTINGS -- NO NEED TO CHANGE ANYTHING BELOW THIS LINE ======= # Convenience platforms targets. PLATS= guess aix bsd c89 freebsd generic linux linux-readline macosx mingw posix solaris # What to install. TO_BIN= lua luac TO_INC= lua.h luaconf.h lualib.h lauxlib.h lua.hpp TO_LIB= liblua.a TO_MAN= lua.1 luac.1 # Lua version and release. V= 5.4 R= $V.1 # Targets start here. all: $(PLAT) $(PLATS) help test clean: @cd src && $(MAKE) $@ install: dummy cd src && $(MKDIR) $(INSTALL_BIN) $(INSTALL_INC) $(INSTALL_LIB) $(INSTALL_MAN) $(INSTALL_LMOD) $(INSTALL_CMOD) cd src && $(INSTALL_EXEC) $(TO_BIN) $(INSTALL_BIN) cd src && $(INSTALL_DATA) $(TO_INC) $(INSTALL_INC) cd src && $(INSTALL_DATA) $(TO_LIB) $(INSTALL_LIB) cd doc && $(INSTALL_DATA) $(TO_MAN) $(INSTALL_MAN) uninstall: cd src && cd $(INSTALL_BIN) && $(RM) $(TO_BIN) cd src && cd $(INSTALL_INC) && $(RM) $(TO_INC) cd src && cd $(INSTALL_LIB) && $(RM) $(TO_LIB) cd doc && cd $(INSTALL_MAN) && $(RM) $(TO_MAN) local: $(MAKE) install INSTALL_TOP=../install # make may get confused with install/ if it does not support .PHONY. dummy: # Echo config parameters. echo: @cd src && $(MAKE) -s echo @echo "PLAT= $(PLAT)" @echo "V= $V" @echo "R= $R" @echo "TO_BIN= $(TO_BIN)" @echo "TO_INC= $(TO_INC)" @echo "TO_LIB= $(TO_LIB)" @echo "TO_MAN= $(TO_MAN)" @echo "INSTALL_TOP= $(INSTALL_TOP)" @echo "INSTALL_BIN= $(INSTALL_BIN)" @echo "INSTALL_INC= $(INSTALL_INC)" @echo "INSTALL_LIB= $(INSTALL_LIB)" @echo "INSTALL_MAN= $(INSTALL_MAN)" @echo "INSTALL_LMOD= $(INSTALL_LMOD)" @echo "INSTALL_CMOD= $(INSTALL_CMOD)" @echo "INSTALL_EXEC= $(INSTALL_EXEC)" @echo "INSTALL_DATA= $(INSTALL_DATA)" # Echo pkg-config data. pc: @echo "version=$R" @echo "prefix=$(INSTALL_TOP)" @echo "libdir=$(INSTALL_LIB)" @echo "includedir=$(INSTALL_INC)" # Targets that do not create files (not all makes understand .PHONY). .PHONY: all $(PLATS) help test clean install uninstall local dummy echo pc # (end of Makefile)
xLua/build/lua-5.4.1/Makefile/0
{ "file_path": "xLua/build/lua-5.4.1/Makefile", "repo_id": "xLua", "token_count": 1239 }
2,028
/* ** $Id: lgc.h $ ** Garbage Collector ** See Copyright Notice in lua.h */ #ifndef lgc_h #define lgc_h #include "lobject.h" #include "lstate.h" /* ** Collectable objects may have one of three colors: white, which means ** the object is not marked; gray, which means the object is marked, but ** its references may be not marked; and black, which means that the ** object and all its references are marked. The main invariant of the ** garbage collector, while marking objects, is that a black object can ** never point to a white one. Moreover, any gray object must be in a ** "gray list" (gray, grayagain, weak, allweak, ephemeron) so that it ** can be visited again before finishing the collection cycle. (Open ** upvalues are an exception to this rule.) These lists have no meaning ** when the invariant is not being enforced (e.g., sweep phase). */ /* ** Possible states of the Garbage Collector */ #define GCSpropagate 0 #define GCSenteratomic 1 #define GCSatomic 2 #define GCSswpallgc 3 #define GCSswpfinobj 4 #define GCSswptobefnz 5 #define GCSswpend 6 #define GCScallfin 7 #define GCSpause 8 #define issweepphase(g) \ (GCSswpallgc <= (g)->gcstate && (g)->gcstate <= GCSswpend) /* ** macro to tell when main invariant (white objects cannot point to black ** ones) must be kept. During a collection, the sweep ** phase may break the invariant, as objects turned white may point to ** still-black objects. The invariant is restored when sweep ends and ** all objects are white again. */ #define keepinvariant(g) ((g)->gcstate <= GCSatomic) /* ** some useful bit tricks */ #define resetbits(x,m) ((x) &= cast_byte(~(m))) #define setbits(x,m) ((x) |= (m)) #define testbits(x,m) ((x) & (m)) #define bitmask(b) (1<<(b)) #define bit2mask(b1,b2) (bitmask(b1) | bitmask(b2)) #define l_setbit(x,b) setbits(x, bitmask(b)) #define resetbit(x,b) resetbits(x, bitmask(b)) #define testbit(x,b) testbits(x, bitmask(b)) /* ** Layout for bit use in 'marked' field. First three bits are ** used for object "age" in generational mode. Last bit is used ** by tests. */ #define WHITE0BIT 3 /* object is white (type 0) */ #define WHITE1BIT 4 /* object is white (type 1) */ #define BLACKBIT 5 /* object is black */ #define FINALIZEDBIT 6 /* object has been marked for finalization */ #define TESTBIT 7 #define WHITEBITS bit2mask(WHITE0BIT, WHITE1BIT) #define iswhite(x) testbits((x)->marked, WHITEBITS) #define isblack(x) testbit((x)->marked, BLACKBIT) #define isgray(x) /* neither white nor black */ \ (!testbits((x)->marked, WHITEBITS | bitmask(BLACKBIT))) #define tofinalize(x) testbit((x)->marked, FINALIZEDBIT) #define otherwhite(g) ((g)->currentwhite ^ WHITEBITS) #define isdeadm(ow,m) ((m) & (ow)) #define isdead(g,v) isdeadm(otherwhite(g), (v)->marked) #define changewhite(x) ((x)->marked ^= WHITEBITS) #define nw2black(x) \ check_exp(!iswhite(x), l_setbit((x)->marked, BLACKBIT)) #define luaC_white(g) cast_byte((g)->currentwhite & WHITEBITS) /* object age in generational mode */ #define G_NEW 0 /* created in current cycle */ #define G_SURVIVAL 1 /* created in previous cycle */ #define G_OLD0 2 /* marked old by frw. barrier in this cycle */ #define G_OLD1 3 /* first full cycle as old */ #define G_OLD 4 /* really old object (not to be visited) */ #define G_TOUCHED1 5 /* old object touched this cycle */ #define G_TOUCHED2 6 /* old object touched in previous cycle */ #define AGEBITS 7 /* all age bits (111) */ #define getage(o) ((o)->marked & AGEBITS) #define setage(o,a) ((o)->marked = cast_byte(((o)->marked & (~AGEBITS)) | a)) #define isold(o) (getage(o) > G_SURVIVAL) #define changeage(o,f,t) \ check_exp(getage(o) == (f), (o)->marked ^= ((f)^(t))) /* Default Values for GC parameters */ #define LUAI_GENMAJORMUL 100 #define LUAI_GENMINORMUL 20 /* wait memory to double before starting new cycle */ #define LUAI_GCPAUSE 200 /* ** some gc parameters are stored divided by 4 to allow a maximum value ** up to 1023 in a 'lu_byte'. */ #define getgcparam(p) ((p) * 4) #define setgcparam(p,v) ((p) = (v) / 4) #define LUAI_GCMUL 100 /* how much to allocate before next GC step (log2) */ #define LUAI_GCSTEPSIZE 13 /* 8 KB */ /* ** Check whether the declared GC mode is generational. While in ** generational mode, the collector can go temporarily to incremental ** mode to improve performance. This is signaled by 'g->lastatomic != 0'. */ #define isdecGCmodegen(g) (g->gckind == KGC_GEN || g->lastatomic != 0) /* ** Does one step of collection when debt becomes positive. 'pre'/'pos' ** allows some adjustments to be done only when needed. macro ** 'condchangemem' is used only for heavy tests (forcing a full ** GC cycle on every opportunity) */ #define luaC_condGC(L,pre,pos) \ { if (G(L)->GCdebt > 0) { pre; luaC_step(L); pos;}; \ condchangemem(L,pre,pos); } /* more often than not, 'pre'/'pos' are empty */ #define luaC_checkGC(L) luaC_condGC(L,(void)0,(void)0) #define luaC_barrier(L,p,v) ( \ (iscollectable(v) && isblack(p) && iswhite(gcvalue(v))) ? \ luaC_barrier_(L,obj2gco(p),gcvalue(v)) : cast_void(0)) #define luaC_barrierback(L,p,v) ( \ (iscollectable(v) && isblack(p) && iswhite(gcvalue(v))) ? \ luaC_barrierback_(L,p) : cast_void(0)) #define luaC_objbarrier(L,p,o) ( \ (isblack(p) && iswhite(o)) ? \ luaC_barrier_(L,obj2gco(p),obj2gco(o)) : cast_void(0)) LUAI_FUNC void luaC_fix (lua_State *L, GCObject *o); LUAI_FUNC void luaC_freeallobjects (lua_State *L); LUAI_FUNC void luaC_step (lua_State *L); LUAI_FUNC void luaC_runtilstate (lua_State *L, int statesmask); LUAI_FUNC void luaC_fullgc (lua_State *L, int isemergency); LUAI_FUNC GCObject *luaC_newobj (lua_State *L, int tt, size_t sz); LUAI_FUNC void luaC_barrier_ (lua_State *L, GCObject *o, GCObject *v); LUAI_FUNC void luaC_barrierback_ (lua_State *L, GCObject *o); LUAI_FUNC void luaC_checkfinalizer (lua_State *L, GCObject *o, Table *mt); LUAI_FUNC void luaC_changemode (lua_State *L, int newmode); #endif
xLua/build/lua-5.4.1/src/lgc.h/0
{ "file_path": "xLua/build/lua-5.4.1/src/lgc.h", "repo_id": "xLua", "token_count": 2304 }
2,029
############################################################################## # LuaJIT top level Makefile for installation. Requires GNU Make. # # Please read doc/install.html before changing any variables! # # Suitable for POSIX platforms (Linux, *BSD, OSX etc.). # Note: src/Makefile has many more configurable options. # # ##### This Makefile is NOT useful for Windows! ##### # For MSVC, please follow the instructions given in src/msvcbuild.bat. # For MinGW and Cygwin, cd to src and run make with the Makefile there. # # Copyright (C) 2005-2016 Mike Pall. See Copyright Notice in luajit.h ############################################################################## MAJVER= 2 MINVER= 1 RELVER= 0 PREREL= -beta2 VERSION= $(MAJVER).$(MINVER).$(RELVER)$(PREREL) ABIVER= 5.1 ############################################################################## # # Change the installation path as needed. This automatically adjusts # the paths in src/luaconf.h, too. Note: PREFIX must be an absolute path! # export PREFIX= /usr/local export MULTILIB= lib ############################################################################## DPREFIX= $(DESTDIR)$(PREFIX) INSTALL_BIN= $(DPREFIX)/bin INSTALL_LIB= $(DPREFIX)/$(MULTILIB) INSTALL_SHARE= $(DPREFIX)/share INSTALL_INC= $(DPREFIX)/include/luajit-$(MAJVER).$(MINVER) INSTALL_LJLIBD= $(INSTALL_SHARE)/luajit-$(VERSION) INSTALL_JITLIB= $(INSTALL_LJLIBD)/jit INSTALL_LMODD= $(INSTALL_SHARE)/lua INSTALL_LMOD= $(INSTALL_LMODD)/$(ABIVER) INSTALL_CMODD= $(INSTALL_LIB)/lua INSTALL_CMOD= $(INSTALL_CMODD)/$(ABIVER) INSTALL_MAN= $(INSTALL_SHARE)/man/man1 INSTALL_PKGCONFIG= $(INSTALL_LIB)/pkgconfig INSTALL_TNAME= luajit-$(VERSION) INSTALL_TSYMNAME= luajit INSTALL_ANAME= libluajit-$(ABIVER).a INSTALL_SONAME= libluajit-$(ABIVER).so.$(MAJVER).$(MINVER).$(RELVER) INSTALL_SOSHORT= libluajit-$(ABIVER).so INSTALL_DYLIBNAME= libluajit-$(ABIVER).$(MAJVER).$(MINVER).$(RELVER).dylib INSTALL_DYLIBSHORT1= libluajit-$(ABIVER).dylib INSTALL_DYLIBSHORT2= libluajit-$(ABIVER).$(MAJVER).dylib INSTALL_PCNAME= luajit.pc INSTALL_STATIC= $(INSTALL_LIB)/$(INSTALL_ANAME) INSTALL_DYN= $(INSTALL_LIB)/$(INSTALL_SONAME) INSTALL_SHORT1= $(INSTALL_LIB)/$(INSTALL_SOSHORT) INSTALL_SHORT2= $(INSTALL_LIB)/$(INSTALL_SOSHORT) INSTALL_T= $(INSTALL_BIN)/$(INSTALL_TNAME) INSTALL_TSYM= $(INSTALL_BIN)/$(INSTALL_TSYMNAME) INSTALL_PC= $(INSTALL_PKGCONFIG)/$(INSTALL_PCNAME) INSTALL_DIRS= $(INSTALL_BIN) $(INSTALL_LIB) $(INSTALL_INC) $(INSTALL_MAN) \ $(INSTALL_PKGCONFIG) $(INSTALL_JITLIB) $(INSTALL_LMOD) $(INSTALL_CMOD) UNINSTALL_DIRS= $(INSTALL_JITLIB) $(INSTALL_LJLIBD) $(INSTALL_INC) \ $(INSTALL_LMOD) $(INSTALL_LMODD) $(INSTALL_CMOD) $(INSTALL_CMODD) RM= rm -f MKDIR= mkdir -p RMDIR= rmdir 2>/dev/null SYMLINK= ln -sf INSTALL_X= install -m 0755 INSTALL_F= install -m 0644 UNINSTALL= $(RM) LDCONFIG= ldconfig -n SED_PC= sed -e "s|^prefix=.*|prefix=$(PREFIX)|" \ -e "s|^multilib=.*|multilib=$(MULTILIB)|" FILE_T= luajit FILE_A= libluajit.a FILE_SO= libluajit.so FILE_MAN= luajit.1 FILE_PC= luajit.pc FILES_INC= lua.h lualib.h lauxlib.h luaconf.h lua.hpp luajit.h FILES_JITLIB= bc.lua bcsave.lua dump.lua p.lua v.lua zone.lua \ dis_x86.lua dis_x64.lua dis_arm.lua dis_ppc.lua \ dis_mips.lua dis_mipsel.lua vmdef.lua ifeq (,$(findstring Windows,$(OS))) ifeq (Darwin,$(shell uname -s)) INSTALL_SONAME= $(INSTALL_DYLIBNAME) INSTALL_SHORT1= $(INSTALL_LIB)/$(INSTALL_DYLIBSHORT1) INSTALL_SHORT2= $(INSTALL_LIB)/$(INSTALL_DYLIBSHORT2) LDCONFIG= : endif endif ############################################################################## INSTALL_DEP= src/luajit default all $(INSTALL_DEP): @echo "==== Building LuaJIT $(VERSION) ====" $(MAKE) -C src @echo "==== Successfully built LuaJIT $(VERSION) ====" install: $(INSTALL_DEP) @echo "==== Installing LuaJIT $(VERSION) to $(PREFIX) ====" $(MKDIR) $(INSTALL_DIRS) cd src && $(INSTALL_X) $(FILE_T) $(INSTALL_T) cd src && test -f $(FILE_A) && $(INSTALL_F) $(FILE_A) $(INSTALL_STATIC) || : $(RM) $(INSTALL_DYN) $(INSTALL_SHORT1) $(INSTALL_SHORT2) cd src && test -f $(FILE_SO) && \ $(INSTALL_X) $(FILE_SO) $(INSTALL_DYN) && \ $(LDCONFIG) $(INSTALL_LIB) && \ $(SYMLINK) $(INSTALL_SONAME) $(INSTALL_SHORT1) && \ $(SYMLINK) $(INSTALL_SONAME) $(INSTALL_SHORT2) || : cd etc && $(INSTALL_F) $(FILE_MAN) $(INSTALL_MAN) cd etc && $(SED_PC) $(FILE_PC) > $(FILE_PC).tmp && \ $(INSTALL_F) $(FILE_PC).tmp $(INSTALL_PC) && \ $(RM) $(FILE_PC).tmp cd src && $(INSTALL_F) $(FILES_INC) $(INSTALL_INC) cd src/jit && $(INSTALL_F) $(FILES_JITLIB) $(INSTALL_JITLIB) @echo "==== Successfully installed LuaJIT $(VERSION) to $(PREFIX) ====" @echo "" @echo "Note: the development releases deliberately do NOT install a symlink for luajit" @echo "You can do this now by running this command (with sudo):" @echo "" @echo " $(SYMLINK) $(INSTALL_TNAME) $(INSTALL_TSYM)" @echo "" uninstall: @echo "==== Uninstalling LuaJIT $(VERSION) from $(PREFIX) ====" $(UNINSTALL) $(INSTALL_T) $(INSTALL_STATIC) $(INSTALL_DYN) $(INSTALL_SHORT1) $(INSTALL_SHORT2) $(INSTALL_MAN)/$(FILE_MAN) $(INSTALL_PC) for file in $(FILES_JITLIB); do \ $(UNINSTALL) $(INSTALL_JITLIB)/$$file; \ done for file in $(FILES_INC); do \ $(UNINSTALL) $(INSTALL_INC)/$$file; \ done $(LDCONFIG) $(INSTALL_LIB) $(RMDIR) $(UNINSTALL_DIRS) || : @echo "==== Successfully uninstalled LuaJIT $(VERSION) from $(PREFIX) ====" ############################################################################## amalg: @echo "Building LuaJIT $(VERSION)" $(MAKE) -C src amalg clean: $(MAKE) -C src clean .PHONY: all install amalg clean ##############################################################################
xLua/build/luajit-2.1.0b2/Makefile/0
{ "file_path": "xLua/build/luajit-2.1.0b2/Makefile", "repo_id": "xLua", "token_count": 2286 }
2,030
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>Installation</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <meta name="Author" content="Mike Pall"> <meta name="Copyright" content="Copyright (C) 2005-2016, Mike Pall"> <meta name="Language" content="en"> <link rel="stylesheet" type="text/css" href="bluequad.css" media="screen"> <link rel="stylesheet" type="text/css" href="bluequad-print.css" media="print"> <style type="text/css"> table.compat { line-height: 1.2; font-size: 80%; } table.compat td { border: 1px solid #bfcfff; height: 2.5em; } table.compat tr.compathead td { font-weight: bold; border-bottom: 2px solid #bfcfff; } tr.compathead td.compatos { vertical-align: top; } table.compat td.compatcpu { width: 18%; border-right: 2px solid #bfcfff; } td.compatos { width: 21%; vertical-align: middle; } td.compatno { background-color: #d0d0d0; } </style> </head> <body> <div id="site"> <a href="http://luajit.org"><span>Lua<span id="logo">JIT</span></span></a> </div> <div id="head"> <h1>Installation</h1> </div> <div id="nav"> <ul><li> <a href="luajit.html">LuaJIT</a> <ul><li> <a href="http://luajit.org/download.html">Download <span class="ext">&raquo;</span></a> </li><li> <a class="current" href="install.html">Installation</a> </li><li> <a href="running.html">Running</a> </li></ul> </li><li> <a href="extensions.html">Extensions</a> <ul><li> <a href="ext_ffi.html">FFI Library</a> <ul><li> <a href="ext_ffi_tutorial.html">FFI Tutorial</a> </li><li> <a href="ext_ffi_api.html">ffi.* API</a> </li><li> <a href="ext_ffi_semantics.html">FFI Semantics</a> </li></ul> </li><li> <a href="ext_jit.html">jit.* Library</a> </li><li> <a href="ext_c_api.html">Lua/C API</a> </li><li> <a href="ext_profiler.html">Profiler</a> </li></ul> </li><li> <a href="status.html">Status</a> <ul><li> <a href="changes.html">Changes</a> </li></ul> </li><li> <a href="faq.html">FAQ</a> </li><li> <a href="http://luajit.org/performance.html">Performance <span class="ext">&raquo;</span></a> </li><li> <a href="http://wiki.luajit.org/">Wiki <span class="ext">&raquo;</span></a> </li><li> <a href="http://luajit.org/list.html">Mailing List <span class="ext">&raquo;</span></a> </li></ul> </div> <div id="main"> <p> LuaJIT is only distributed as a source package. This page explains how to build and install LuaJIT with different operating systems and C&nbsp;compilers. </p> <p> For the impatient (on POSIX systems): </p> <pre class="code"> make &amp;&amp; sudo make install </pre> <p> LuaJIT currently builds out-of-the box on most systems. Here's the compatibility matrix for the supported combinations of operating systems, CPUs and compilers: </p> <table class="compat"> <tr class="compathead"> <td class="compatcpu">CPU / OS</td> <td class="compatos"><a href="#posix">Linux</a> or<br><a href="#android">Android</a></td> <td class="compatos"><a href="#posix">*BSD, Other</a></td> <td class="compatos"><a href="#posix">OSX 10.4+</a> or<br><a href="#ios">iOS 3.0+</a></td> <td class="compatos"><a href="#windows">Windows<br>XP/Vista/7</a></td> </tr> <tr class="odd separate"> <td class="compatcpu">x86 (32 bit)</td> <td class="compatos">GCC 4.2+</td> <td class="compatos">GCC 4.2+</td> <td class="compatos">XCode 5.0+<br>Clang</td> <td class="compatos">MSVC, MSVC/EE<br>WinSDK<br>MinGW, Cygwin</td> </tr> <tr class="even"> <td class="compatcpu">x64 (64 bit)</td> <td class="compatos">GCC 4.2+</td> <td class="compatos">ORBIS (<a href="#ps4">PS4</a>)</td> <td class="compatos">XCode 5.0+<br>Clang</td> <td class="compatos">MSVC + SDK v7.0<br>WinSDK v7.0<br>Durango (<a href="#xboxone">Xbox One</a>)</td> </tr> <tr class="odd"> <td class="compatcpu"><a href="#cross2">ARMv5+<br>ARM9E+</a></td> <td class="compatos">GCC 4.2+</td> <td class="compatos">GCC 4.2+<br>PSP2 (<a href="#psvita">PS VITA</a>)</td> <td class="compatos">XCode 5.0+<br>Clang</td> <td class="compatos compatno">&nbsp;</td> </tr> <tr class="even"> <td class="compatcpu"><a href="#cross2">ARM64</a></td> <td class="compatos">GCC 4.8+</td> <td class="compatos compatno">&nbsp;</td> <td class="compatos">XCode 6.0+<br>Clang 3.5+</td> <td class="compatos compatno">&nbsp;</td> </tr> <tr class="odd"> <td class="compatcpu"><a href="#cross2">PPC</a></td> <td class="compatos">GCC 4.3+</td> <td class="compatos">GCC 4.3+<br>GCC 4.1 (<a href="#ps3">PS3</a>)</td> <td class="compatos compatno">&nbsp;</td> <td class="compatos">XEDK (<a href="#xbox360">Xbox 360</a>)</td> </tr> <tr class="even"> <td class="compatcpu"><a href="#cross2">MIPS</a></td> <td class="compatos">GCC 4.3+</td> <td class="compatos">GCC 4.3+</td> <td class="compatos compatno">&nbsp;</td> <td class="compatos compatno">&nbsp;</td> </tr> </table> <h2>Configuring LuaJIT</h2> <p> The standard configuration should work fine for most installations. Usually there is no need to tweak the settings. The following files hold all user-configurable settings: </p> <ul> <li><tt>src/luaconf.h</tt> sets some configuration variables.</li> <li><tt>Makefile</tt> has settings for <b>installing</b> LuaJIT (POSIX only).</li> <li><tt>src/Makefile</tt> has settings for <b>compiling</b> LuaJIT under POSIX, MinGW or Cygwin.</li> <li><tt>src/msvcbuild.bat</tt> has settings for compiling LuaJIT with MSVC or WinSDK.</li> </ul> <p> Please read the instructions given in these files, before changing any settings. </p> <h2 id="posix">POSIX Systems (Linux, OSX, *BSD etc.)</h2> <h3>Prerequisites</h3> <p> Depending on your distribution, you may need to install a package for GCC, the development headers and/or a complete SDK. E.g. on a current Debian/Ubuntu, install <tt>libc6-dev</tt> with the package manager. </p> <p> Download the current source package of LuaJIT (pick the .tar.gz), if you haven't already done so. Move it to a directory of your choice, open a terminal window and change to this directory. Now unpack the archive and change to the newly created directory: </p> <pre class="code"> tar zxf LuaJIT-2.0.4.tar.gz cd LuaJIT-2.0.4</pre> <h3>Building LuaJIT</h3> <p> The supplied Makefiles try to auto-detect the settings needed for your operating system and your compiler. They need to be run with GNU Make, which is probably the default on your system, anyway. Simply run: </p> <pre class="code"> make </pre> <p> This always builds a native x86, x64 or PPC binary, depending on the host OS you're running this command on. Check the section on <a href="#cross">cross-compilation</a> for more options. </p> <p> By default, modules are only searched under the prefix <tt>/usr/local</tt>. You can add an extra prefix to the search paths by appending the <tt>PREFIX</tt> option, e.g.: </p> <pre class="code"> make PREFIX=/home/myself/lj2 </pre> <p> Note for OSX: if the <tt>MACOSX_DEPLOYMENT_TARGET</tt> environment variable is not set, then it's forced to <tt>10.4</tt>. </p> <h3>Installing LuaJIT</h3> <p> The top-level Makefile installs LuaJIT by default under <tt>/usr/local</tt>, i.e. the executable ends up in <tt>/usr/local/bin</tt> and so on. You need root privileges to write to this path. So, assuming sudo is installed on your system, run the following command and enter your sudo password: </p> <pre class="code"> sudo make install </pre> <p> Otherwise specify the directory prefix as an absolute path, e.g.: </p> <pre class="code"> make install PREFIX=/home/myself/lj2 </pre> <p> Obviously the prefixes given during build and installation need to be the same. </p> <h2 id="windows">Windows Systems</h2> <h3>Prerequisites</h3> <p> Either install one of the open source SDKs (<a href="http://mingw.org/"><span class="ext">&raquo;</span>&nbsp;MinGW</a> or <a href="http://www.cygwin.com/"><span class="ext">&raquo;</span>&nbsp;Cygwin</a>), which come with a modified GCC plus the required development headers. </p> <p> Or install Microsoft's Visual C++ (MSVC). The freely downloadable <a href="http://www.microsoft.com/Express/VC/"><span class="ext">&raquo;</span>&nbsp;Express Edition</a> works just fine, but only contains an x86 compiler. </p> <p> The freely downloadable <a href="http://msdn.microsoft.com/en-us/windowsserver/bb980924.aspx"><span class="ext">&raquo;</span>&nbsp;Windows SDK</a> only comes with command line tools, but this is all you need to build LuaJIT. It contains x86 and x64 compilers. </p> <p> Next, download the source package and unpack it using an archive manager (e.g. the Windows Explorer) to a directory of your choice. </p> <h3>Building with MSVC</h3> <p> Open a "Visual Studio .NET Command Prompt", <tt>cd</tt> to the directory where you've unpacked the sources and run these commands: </p> <pre class="code"> cd src msvcbuild </pre> <p> Then follow the installation instructions below. </p> <h3>Building with the Windows SDK</h3> <p> Open a "Windows SDK Command Shell" and select the x86 compiler: </p> <pre class="code"> setenv /release /x86 </pre> <p> Or select the x64 compiler: </p> <pre class="code"> setenv /release /x64 </pre> <p> Then <tt>cd</tt> to the directory where you've unpacked the sources and run these commands: </p> <pre class="code"> cd src msvcbuild </pre> <p> Then follow the installation instructions below. </p> <h3>Building with MinGW or Cygwin</h3> <p> Open a command prompt window and make sure the MinGW or Cygwin programs are in your path. Then <tt>cd</tt> to the directory where you've unpacked the sources and run this command for MinGW: </p> <pre class="code"> mingw32-make </pre> <p> Or this command for Cygwin: </p> <pre class="code"> make </pre> <p> Then follow the installation instructions below. </p> <h3>Installing LuaJIT</h3> <p> Copy <tt>luajit.exe</tt> and <tt>lua51.dll</tt> (built in the <tt>src</tt> directory) to a newly created directory (any location is ok). Add <tt>lua</tt> and <tt>lua\jit</tt> directories below it and copy all Lua files from the <tt>src\jit</tt> directory of the distribution to the latter directory. </p> <p> There are no hardcoded absolute path names &mdash; all modules are loaded relative to the directory where <tt>luajit.exe</tt> is installed (see <tt>src/luaconf.h</tt>). </p> <h2 id="cross">Cross-compiling LuaJIT</h2> <p> The GNU Makefile-based build system allows cross-compiling on any host for any supported target, as long as both architectures have the same pointer size. If you want to cross-compile to any 32 bit target on an x64 OS, you need to install the multilib development package (e.g. <tt>libc6-dev-i386</tt> on Debian/Ubuntu) and build a 32 bit host part (<tt>HOST_CC="gcc -m32"</tt>). </p> <p> You need to specify <tt>TARGET_SYS</tt> whenever the host OS and the target OS differ, or you'll get assembler or linker errors. E.g. if you're compiling on a Windows or OSX host for embedded Linux or Android, you need to add <tt>TARGET_SYS=Linux</tt> to the examples below. For a minimal target OS, you may need to disable the built-in allocator in <tt>src/Makefile</tt> and use <tt>TARGET_SYS=Other</tt>. The examples below only show some popular targets &mdash; please check the comments in <tt>src/Makefile</tt> for more details. </p> <pre class="code"> # Cross-compile to a 32 bit binary on a multilib x64 OS make CC="gcc -m32" # Cross-compile on Debian/Ubuntu for Windows (mingw32 package) make HOST_CC="gcc -m32" CROSS=i586-mingw32msvc- TARGET_SYS=Windows </pre> <p id="cross2"> The <tt>CROSS</tt> prefix allows specifying a standard GNU cross-compile toolchain (Binutils, GCC and a matching libc). The prefix may vary depending on the <tt>--target</tt> the toolchain was built for (note the <tt>CROSS</tt> prefix has a trailing <tt>"-"</tt>). The examples below use the canonical toolchain triplets for Linux. </p> <p> Since there's often no easy way to detect CPU features at runtime, it's important to compile with the proper CPU or architecture settings. You can specify these when building the toolchain yourself. Or add <tt>-mcpu=...</tt> or <tt>-march=...</tt> to <tt>TARGET_CFLAGS</tt>. For ARM it's important to have the correct <tt>-mfloat-abi=...</tt> setting, too. Otherwise LuaJIT may not run at the full performance of your target CPU. </p> <pre class="code"> # ARM soft-float make HOST_CC="gcc -m32" CROSS=arm-linux-gnueabi- \ TARGET_CFLAGS="-mfloat-abi=soft" # ARM soft-float ABI with VFP (example for Cortex-A8) make HOST_CC="gcc -m32" CROSS=arm-linux-gnueabi- \ TARGET_CFLAGS="-mcpu=cortex-a8 -mfloat-abi=softfp" # ARM hard-float ABI with VFP (armhf, requires recent toolchain) make HOST_CC="gcc -m32" CROSS=arm-linux-gnueabihf- # ARM64 (requires x64 host) make CROSS=aarch64-linux- # PPC make HOST_CC="gcc -m32" CROSS=powerpc-linux-gnu- # MIPS big-endian make HOST_CC="gcc -m32" CROSS=mips-linux- # MIPS little-endian make HOST_CC="gcc -m32" CROSS=mipsel-linux- </pre> <p> You can cross-compile for <b id="android">Android</b> using the <a href="http://developer.android.com/sdk/ndk/index.html"><span class="ext">&raquo;</span>&nbsp;Android NDK</a>. The environment variables need to match the install locations and the desired target platform. E.g. Android&nbsp;4.0 corresponds to ABI level&nbsp;14. For details check the folder <tt>docs</tt> in the NDK directory. </p> <p> Only a few common variations for the different CPUs, ABIs and platforms are listed. Please use your own judgement for which combination you want to build/deploy or which lowest common denominator you want to pick: </p> <pre class="code"> # Android/ARM, armeabi (ARMv5TE soft-float), Android 2.2+ (Froyo) NDK=/opt/android/ndk NDKABI=8 NDKVER=$NDK/toolchains/arm-linux-androideabi-4.6 NDKP=$NDKVER/prebuilt/linux-x86/bin/arm-linux-androideabi- NDKF="--sysroot $NDK/platforms/android-$NDKABI/arch-arm" make HOST_CC="gcc -m32" CROSS=$NDKP TARGET_FLAGS="$NDKF" # Android/ARM, armeabi-v7a (ARMv7 VFP), Android 4.0+ (ICS) NDK=/opt/android/ndk NDKABI=14 NDKVER=$NDK/toolchains/arm-linux-androideabi-4.6 NDKP=$NDKVER/prebuilt/linux-x86/bin/arm-linux-androideabi- NDKF="--sysroot $NDK/platforms/android-$NDKABI/arch-arm" NDKARCH="-march=armv7-a -mfloat-abi=softfp -Wl,--fix-cortex-a8" make HOST_CC="gcc -m32" CROSS=$NDKP TARGET_FLAGS="$NDKF $NDKARCH" # Android/MIPS, mips (MIPS32R1 hard-float), Android 4.0+ (ICS) NDK=/opt/android/ndk NDKABI=14 NDKVER=$NDK/toolchains/mipsel-linux-android-4.6 NDKP=$NDKVER/prebuilt/linux-x86/bin/mipsel-linux-android- NDKF="--sysroot $NDK/platforms/android-$NDKABI/arch-mips" make HOST_CC="gcc -m32" CROSS=$NDKP TARGET_FLAGS="$NDKF" # Android/x86, x86 (i686 SSE3), Android 4.0+ (ICS) NDK=/opt/android/ndk NDKABI=14 NDKVER=$NDK/toolchains/x86-4.6 NDKP=$NDKVER/prebuilt/linux-x86/bin/i686-linux-android- NDKF="--sysroot $NDK/platforms/android-$NDKABI/arch-x86" make HOST_CC="gcc -m32" CROSS=$NDKP TARGET_FLAGS="$NDKF" </pre> <p> You can cross-compile for <b id="ios">iOS 3.0+</b> (iPhone/iPad) using the <a href="http://developer.apple.com/devcenter/ios/index.action"><span class="ext">&raquo;</span>&nbsp;iOS SDK</a>: </p> <p style="font-size: 8pt;"> Note: <b>the JIT compiler is disabled for iOS</b>, because regular iOS Apps are not allowed to generate code at runtime. You'll only get the performance of the LuaJIT interpreter on iOS. This is still faster than plain Lua, but much slower than the JIT compiler. Please complain to Apple, not me. Or use Android. :-p </p> <pre class="code"> # iOS/ARM (32 bit) ISDKP=$(xcrun --sdk iphoneos --show-sdk-path) ICC=$(xcrun --sdk iphoneos --find clang) ISDKF="-arch armv7 -isysroot $ISDKP" make HOST_CC="clang -m32 -arch i386" CROSS="$(dirname $ICC)/" \ TARGET_FLAGS="$ISDKF" TARGET_SYS=iOS # iOS/ARM64 ISDKP=$(xcrun --sdk iphoneos --show-sdk-path) ICC=$(xcrun --sdk iphoneos --find clang) ISDKF="-arch arm64 -isysroot $ISDKP" make CROSS="$(dirname $ICC)/" TARGET_FLAGS="$ISDKF" TARGET_SYS=iOS </pre> <h3 id="consoles">Cross-compiling for consoles</h3> <p> Building LuaJIT for consoles requires both a supported host compiler (x86 or x64) and a cross-compiler (to PPC or ARM) from the official console SDK. </p> <p> Due to restrictions on consoles, the JIT compiler is disabled and only the fast interpreter is built. This is still faster than plain Lua, but much slower than the JIT compiler. The FFI is disabled, too, since it's not very useful in such an environment. </p> <p> The following commands build a static library <tt>libluajit.a</tt>, which can be linked against your game, just like the Lua library. </p> <p> To cross-compile for <b id="ps3">PS3</b> from a Linux host (requires 32&nbsp;bit GCC, i.e. multilib Linux/x64) or a Windows host (requires 32&nbsp;bit MinGW), run this command: </p> <pre class="code"> make HOST_CC="gcc -m32" CROSS=ppu-lv2- </pre> <p> To cross-compile for <b id="ps4">PS4</b> from a Windows host, open a "Visual Studio .NET Command Prompt" (64&nbsp;bit host compiler), <tt>cd</tt> to the directory where you've unpacked the sources and run the following commands: </p> <pre class="code"> cd src ps4build </pre> <p> To cross-compile for <b id="psvita">PS Vita</b> from a Windows host, open a "Visual Studio .NET Command Prompt" (32&nbsp;bit host compiler), <tt>cd</tt> to the directory where you've unpacked the sources and run the following commands: </p> <pre class="code"> cd src psvitabuild </pre> <p> To cross-compile for <b id="xbox360">Xbox 360</b> from a Windows host, open a "Visual Studio .NET Command Prompt" (32&nbsp;bit host compiler), <tt>cd</tt> to the directory where you've unpacked the sources and run the following commands: </p> <pre class="code"> cd src xedkbuild </pre> <p> To cross-compile for <b id="xboxone">Xbox One</b> from a Windows host, open a "Visual Studio .NET Command Prompt" (64&nbsp;bit host compiler), <tt>cd</tt> to the directory where you've unpacked the sources and run the following commands: </p> <pre class="code"> cd src xb1build </pre> <h2 id="embed">Embedding LuaJIT</h2> <p> LuaJIT is API-compatible with Lua 5.1. If you've already embedded Lua into your application, you probably don't need to do anything to switch to LuaJIT, except link with a different library: </p> <ul> <li>It's strongly suggested to build LuaJIT separately using the supplied build system. Please do <em>not</em> attempt to integrate the individual source files into your build tree. You'll most likely get the internal build dependencies wrong or mess up the compiler flags. Treat LuaJIT like any other external library and link your application with either the dynamic or static library, depending on your needs.</li> <li>If you want to load C modules compiled for plain Lua with <tt>require()</tt>, you need to make sure the public symbols (e.g. <tt>lua_pushnumber</tt>) are exported, too: <ul><li>On POSIX systems you can either link to the shared library or link the static library into your application. In the latter case you'll need to export all public symbols from your main executable (e.g. <tt>-Wl,-E</tt> on Linux) and add the external dependencies (e.g. <tt>-lm -ldl</tt> on Linux).</li> <li>Since Windows symbols are bound to a specific DLL name, you need to link to the <tt>lua51.dll</tt> created by the LuaJIT build (do not rename the DLL). You may link LuaJIT statically on Windows only if you don't intend to load Lua/C modules at runtime. </li></ul> </li> <li> If you're building a 64 bit application on OSX which links directly or indirectly against LuaJIT, you need to link your main executable with these flags: <pre class="code"> -pagezero_size 10000 -image_base 100000000 </pre> Also, it's recommended to <tt>rebase</tt> all (self-compiled) shared libraries which are loaded at runtime on OSX/x64 (e.g. C extension modules for Lua). See: <tt>man rebase</tt> </li> </ul> <p>Additional hints for initializing LuaJIT using the C API functions:</p> <ul> <li>Here's a <a href="http://lua-users.org/wiki/SimpleLuaApiExample"><span class="ext">&raquo;</span>&nbsp;simple example</a> for embedding Lua or LuaJIT into your application.</li> <li>Make sure you use <tt>luaL_newstate</tt>. Avoid using <tt>lua_newstate</tt>, since this uses the (slower) default memory allocator from your system (no support for this on x64).</li> <li>Make sure you use <tt>luaL_openlibs</tt> and not the old Lua 5.0 style of calling <tt>luaopen_base</tt> etc. directly.</li> <li>To change or extend the list of standard libraries to load, copy <tt>src/lib_init.c</tt> to your project and modify it accordingly. Make sure the <tt>jit</tt> library is loaded or the JIT compiler will not be activated.</li> <li>The <tt>bit.*</tt> module for bitwise operations is already built-in. There's no need to statically link <a href="http://bitop.luajit.org/"><span class="ext">&raquo;</span>&nbsp;Lua BitOp</a> to your application.</li> </ul> <h2 id="distro">Hints for Distribution Maintainers</h2> <p> The LuaJIT build system has extra provisions for the needs of most POSIX-based distributions. If you're a package maintainer for a distribution, <em>please</em> make use of these features and avoid patching, subverting, autotoolizing or messing up the build system in unspeakable ways. </p> <p> There should be absolutely no need to patch <tt>luaconf.h</tt> or any of the Makefiles. And please do not hand-pick files for your packages &mdash; simply use whatever <tt>make install</tt> creates. There's a reason for all of the files <em>and</em> directories it creates. </p> <p> The build system uses GNU make and auto-detects most settings based on the host you're building it on. This should work fine for native builds, even when sandboxed. You may need to pass some of the following flags to <em>both</em> the <tt>make</tt> and the <tt>make install</tt> command lines for a regular distribution build: </p> <ul> <li><tt>PREFIX</tt> overrides the installation path and should usually be set to <tt>/usr</tt>. Setting this also changes the module paths and the paths needed to locate the shared library.</li> <li><tt>DESTDIR</tt> is an absolute path which allows you to install to a shadow tree instead of the root tree of the build system.</li> <li><tt>MULTILIB</tt> sets the architecture-specific library path component for multilib systems. The default is <tt>lib</tt>.</li> <li>Have a look at the top-level <tt>Makefile</tt> and <tt>src/Makefile</tt> for additional variables to tweak. The following variables <em>may</em> be overridden, but it's <em>not</em> recommended, except for special needs like cross-builds: <tt>BUILDMODE, CC, HOST_CC, STATIC_CC, DYNAMIC_CC, CFLAGS, HOST_CFLAGS, TARGET_CFLAGS, LDFLAGS, HOST_LDFLAGS, TARGET_LDFLAGS, TARGET_SHLDFLAGS, TARGET_FLAGS, LIBS, HOST_LIBS, TARGET_LIBS, CROSS, HOST_SYS, TARGET_SYS </tt></li> </ul> <p> The build system has a special target for an amalgamated build, i.e. <tt>make amalg</tt>. This compiles the LuaJIT core as one huge C file and allows GCC to generate faster and shorter code. Alas, this requires lots of memory during the build. This may be a problem for some users, that's why it's not enabled by default. But it shouldn't be a problem for most build farms. It's recommended that binary distributions use this target for their LuaJIT builds. </p> <p> The tl;dr version of the above: </p> <pre class="code"> make amalg PREFIX=/usr && \ make install PREFIX=/usr DESTDIR=/tmp/buildroot </pre> <p> Finally, if you encounter any difficulties, please <a href="contact.html">contact me</a> first, instead of releasing a broken package onto unsuspecting users. Because they'll usually gonna complain to me (the upstream) and not you (the package maintainer), anyway. </p> <br class="flush"> </div> <div id="foot"> <hr class="hide"> Copyright &copy; 2005-2016 Mike Pall <span class="noprint"> &middot; <a href="contact.html">Contact</a> </span> </div> </body> </html>
xLua/build/luajit-2.1.0b2/doc/install.html/0
{ "file_path": "xLua/build/luajit-2.1.0b2/doc/install.html", "repo_id": "xLua", "token_count": 8504 }
2,031
------------------------------------------------------------------------------ -- DynASM. A dynamic assembler for code generation engines. -- Originally designed and implemented for LuaJIT. -- -- Copyright (C) 2005-2016 Mike Pall. All rights reserved. -- See below for full copyright notice. ------------------------------------------------------------------------------ -- Application information. local _info = { name = "DynASM", description = "A dynamic assembler for code generation engines", version = "1.4.0", vernum = 10400, release = "2015-10-18", author = "Mike Pall", url = "http://luajit.org/dynasm.html", license = "MIT", copyright = [[ Copyright (C) 2005-2016 Mike Pall. All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. [ MIT license: http://www.opensource.org/licenses/mit-license.php ] ]], } -- Cache library functions. local type, pairs, ipairs = type, pairs, ipairs local pcall, error, assert = pcall, error, assert local _s = string local sub, match, gmatch, gsub = _s.sub, _s.match, _s.gmatch, _s.gsub local format, rep, upper = _s.format, _s.rep, _s.upper local _t = table local insert, remove, concat, sort = _t.insert, _t.remove, _t.concat, _t.sort local exit = os.exit local io = io local stdin, stdout, stderr = io.stdin, io.stdout, io.stderr ------------------------------------------------------------------------------ -- Program options. local g_opt = {} -- Global state for current file. local g_fname, g_curline, g_indent, g_lineno, g_synclineno, g_arch local g_errcount = 0 -- Write buffer for output file. local g_wbuffer, g_capbuffer ------------------------------------------------------------------------------ -- Write an output line (or callback function) to the buffer. local function wline(line, needindent) local buf = g_capbuffer or g_wbuffer buf[#buf+1] = needindent and g_indent..line or line g_synclineno = g_synclineno + 1 end -- Write assembler line as a comment, if requestd. local function wcomment(aline) if g_opt.comment then wline(g_opt.comment..aline..g_opt.endcomment, true) end end -- Resync CPP line numbers. local function wsync() if g_synclineno ~= g_lineno and g_opt.cpp then wline("#line "..g_lineno..' "'..g_fname..'"') g_synclineno = g_lineno end end -- Dummy action flush function. Replaced with arch-specific function later. local function wflush(term) end -- Dump all buffered output lines. local function wdumplines(out, buf) for _,line in ipairs(buf) do if type(line) == "string" then assert(out:write(line, "\n")) else -- Special callback to dynamically insert lines after end of processing. line(out) end end end ------------------------------------------------------------------------------ -- Emit an error. Processing continues with next statement. local function werror(msg) error(format("%s:%s: error: %s:\n%s", g_fname, g_lineno, msg, g_curline), 0) end -- Emit a fatal error. Processing stops. local function wfatal(msg) g_errcount = "fatal" werror(msg) end -- Print a warning. Processing continues. local function wwarn(msg) stderr:write(format("%s:%s: warning: %s:\n%s\n", g_fname, g_lineno, msg, g_curline)) end -- Print caught error message. But suppress excessive errors. local function wprinterr(...) if type(g_errcount) == "number" then -- Regular error. g_errcount = g_errcount + 1 if g_errcount < 21 then -- Seems to be a reasonable limit. stderr:write(...) elseif g_errcount == 21 then stderr:write(g_fname, ":*: warning: too many errors (suppressed further messages).\n") end else -- Fatal error. stderr:write(...) return true -- Stop processing. end end ------------------------------------------------------------------------------ -- Map holding all option handlers. local opt_map = {} local opt_current -- Print error and exit with error status. local function opterror(...) stderr:write("dynasm.lua: ERROR: ", ...) stderr:write("\n") exit(1) end -- Get option parameter. local function optparam(args) local argn = args.argn local p = args[argn] if not p then opterror("missing parameter for option `", opt_current, "'.") end args.argn = argn + 1 return p end ------------------------------------------------------------------------------ -- Core pseudo-opcodes. local map_coreop = {} -- Dummy opcode map. Replaced by arch-specific map. local map_op = {} -- Forward declarations. local dostmt local readfile ------------------------------------------------------------------------------ -- Map for defines (initially empty, chains to arch-specific map). local map_def = {} -- Pseudo-opcode to define a substitution. map_coreop[".define_2"] = function(params, nparams) if not params then return nparams == 1 and "name" or "name, subst" end local name, def = params[1], params[2] or "1" if not match(name, "^[%a_][%w_]*$") then werror("bad or duplicate define") end map_def[name] = def end map_coreop[".define_1"] = map_coreop[".define_2"] -- Define a substitution on the command line. function opt_map.D(args) local namesubst = optparam(args) local name, subst = match(namesubst, "^([%a_][%w_]*)=(.*)$") if name then map_def[name] = subst elseif match(namesubst, "^[%a_][%w_]*$") then map_def[namesubst] = "1" else opterror("bad define") end end -- Undefine a substitution on the command line. function opt_map.U(args) local name = optparam(args) if match(name, "^[%a_][%w_]*$") then map_def[name] = nil else opterror("bad define") end end -- Helper for definesubst. local gotsubst local function definesubst_one(word) local subst = map_def[word] if subst then gotsubst = word; return subst else return word end end -- Iteratively substitute defines. local function definesubst(stmt) -- Limit number of iterations. for i=1,100 do gotsubst = false stmt = gsub(stmt, "#?[%w_]+", definesubst_one) if not gotsubst then break end end if gotsubst then wfatal("recursive define involving `"..gotsubst.."'") end return stmt end -- Dump all defines. local function dumpdefines(out, lvl) local t = {} for name in pairs(map_def) do t[#t+1] = name end sort(t) out:write("Defines:\n") for _,name in ipairs(t) do local subst = map_def[name] if g_arch then subst = g_arch.revdef(subst) end out:write(format(" %-20s %s\n", name, subst)) end out:write("\n") end ------------------------------------------------------------------------------ -- Support variables for conditional assembly. local condlevel = 0 local condstack = {} -- Evaluate condition with a Lua expression. Substitutions already performed. local function cond_eval(cond) local func, err if setfenv then func, err = loadstring("return "..cond, "=expr") else -- No globals. All unknown identifiers evaluate to nil. func, err = load("return "..cond, "=expr", "t", {}) end if func then if setfenv then setfenv(func, {}) -- No globals. All unknown identifiers evaluate to nil. end local ok, res = pcall(func) if ok then if res == 0 then return false end -- Oh well. return not not res end err = res end wfatal("bad condition: "..err) end -- Skip statements until next conditional pseudo-opcode at the same level. local function stmtskip() local dostmt_save = dostmt local lvl = 0 dostmt = function(stmt) local op = match(stmt, "^%s*(%S+)") if op == ".if" then lvl = lvl + 1 elseif lvl ~= 0 then if op == ".endif" then lvl = lvl - 1 end elseif op == ".elif" or op == ".else" or op == ".endif" then dostmt = dostmt_save dostmt(stmt) end end end -- Pseudo-opcodes for conditional assembly. map_coreop[".if_1"] = function(params) if not params then return "condition" end local lvl = condlevel + 1 local res = cond_eval(params[1]) condlevel = lvl condstack[lvl] = res if not res then stmtskip() end end map_coreop[".elif_1"] = function(params) if not params then return "condition" end if condlevel == 0 then wfatal(".elif without .if") end local lvl = condlevel local res = condstack[lvl] if res then if res == "else" then wfatal(".elif after .else") end else res = cond_eval(params[1]) if res then condstack[lvl] = res return end end stmtskip() end map_coreop[".else_0"] = function(params) if condlevel == 0 then wfatal(".else without .if") end local lvl = condlevel local res = condstack[lvl] condstack[lvl] = "else" if res then if res == "else" then wfatal(".else after .else") end stmtskip() end end map_coreop[".endif_0"] = function(params) local lvl = condlevel if lvl == 0 then wfatal(".endif without .if") end condlevel = lvl - 1 end -- Check for unfinished conditionals. local function checkconds() if g_errcount ~= "fatal" and condlevel ~= 0 then wprinterr(g_fname, ":*: error: unbalanced conditional\n") end end ------------------------------------------------------------------------------ -- Search for a file in the given path and open it for reading. local function pathopen(path, name) local dirsep = package and match(package.path, "\\") and "\\" or "/" for _,p in ipairs(path) do local fullname = p == "" and name or p..dirsep..name local fin = io.open(fullname, "r") if fin then g_fname = fullname return fin end end end -- Include a file. map_coreop[".include_1"] = function(params) if not params then return "filename" end local name = params[1] -- Save state. Ugly, I know. but upvalues are fast. local gf, gl, gcl, gi = g_fname, g_lineno, g_curline, g_indent -- Read the included file. local fatal = readfile(pathopen(g_opt.include, name) or wfatal("include file `"..name.."' not found")) -- Restore state. g_synclineno = -1 g_fname, g_lineno, g_curline, g_indent = gf, gl, gcl, gi if fatal then wfatal("in include file") end end -- Make .include and conditionals initially available, too. map_op[".include_1"] = map_coreop[".include_1"] map_op[".if_1"] = map_coreop[".if_1"] map_op[".elif_1"] = map_coreop[".elif_1"] map_op[".else_0"] = map_coreop[".else_0"] map_op[".endif_0"] = map_coreop[".endif_0"] ------------------------------------------------------------------------------ -- Support variables for macros. local mac_capture, mac_lineno, mac_name local mac_active = {} local mac_list = {} -- Pseudo-opcode to define a macro. map_coreop[".macro_*"] = function(mparams) if not mparams then return "name [, params...]" end -- Split off and validate macro name. local name = remove(mparams, 1) if not name then werror("missing macro name") end if not (match(name, "^[%a_][%w_%.]*$") or match(name, "^%.[%w_%.]*$")) then wfatal("bad macro name `"..name.."'") end -- Validate macro parameter names. local mdup = {} for _,mp in ipairs(mparams) do if not match(mp, "^[%a_][%w_]*$") then wfatal("bad macro parameter name `"..mp.."'") end if mdup[mp] then wfatal("duplicate macro parameter name `"..mp.."'") end mdup[mp] = true end -- Check for duplicate or recursive macro definitions. local opname = name.."_"..#mparams if map_op[opname] or map_op[name.."_*"] then wfatal("duplicate macro `"..name.."' ("..#mparams.." parameters)") end if mac_capture then wfatal("recursive macro definition") end -- Enable statement capture. local lines = {} mac_lineno = g_lineno mac_name = name mac_capture = function(stmt) -- Statement capture function. -- Stop macro definition with .endmacro pseudo-opcode. if not match(stmt, "^%s*.endmacro%s*$") then lines[#lines+1] = stmt return end mac_capture = nil mac_lineno = nil mac_name = nil mac_list[#mac_list+1] = opname -- Add macro-op definition. map_op[opname] = function(params) if not params then return mparams, lines end -- Protect against recursive macro invocation. if mac_active[opname] then wfatal("recursive macro invocation") end mac_active[opname] = true -- Setup substitution map. local subst = {} for i,mp in ipairs(mparams) do subst[mp] = params[i] end local mcom if g_opt.maccomment and g_opt.comment then mcom = " MACRO "..name.." ("..#mparams..")" wcomment("{"..mcom) end -- Loop through all captured statements for _,stmt in ipairs(lines) do -- Substitute macro parameters. local st = gsub(stmt, "[%w_]+", subst) st = definesubst(st) st = gsub(st, "%s*%.%.%s*", "") -- Token paste a..b. if mcom and sub(st, 1, 1) ~= "|" then wcomment(st) end -- Emit statement. Use a protected call for better diagnostics. local ok, err = pcall(dostmt, st) if not ok then -- Add the captured statement to the error. wprinterr(err, "\n", g_indent, "| ", stmt, "\t[MACRO ", name, " (", #mparams, ")]\n") end end if mcom then wcomment("}"..mcom) end mac_active[opname] = nil end end end -- An .endmacro pseudo-opcode outside of a macro definition is an error. map_coreop[".endmacro_0"] = function(params) wfatal(".endmacro without .macro") end -- Dump all macros and their contents (with -PP only). local function dumpmacros(out, lvl) sort(mac_list) out:write("Macros:\n") for _,opname in ipairs(mac_list) do local name = sub(opname, 1, -3) local params, lines = map_op[opname]() out:write(format(" %-20s %s\n", name, concat(params, ", "))) if lvl > 1 then for _,line in ipairs(lines) do out:write(" |", line, "\n") end out:write("\n") end end out:write("\n") end -- Check for unfinished macro definitions. local function checkmacros() if mac_capture then wprinterr(g_fname, ":", mac_lineno, ": error: unfinished .macro `", mac_name ,"'\n") end end ------------------------------------------------------------------------------ -- Support variables for captures. local cap_lineno, cap_name local cap_buffers = {} local cap_used = {} -- Start a capture. map_coreop[".capture_1"] = function(params) if not params then return "name" end wflush() local name = params[1] if not match(name, "^[%a_][%w_]*$") then wfatal("bad capture name `"..name.."'") end if cap_name then wfatal("already capturing to `"..cap_name.."' since line "..cap_lineno) end cap_name = name cap_lineno = g_lineno -- Create or continue a capture buffer and start the output line capture. local buf = cap_buffers[name] if not buf then buf = {}; cap_buffers[name] = buf end g_capbuffer = buf g_synclineno = 0 end -- Stop a capture. map_coreop[".endcapture_0"] = function(params) wflush() if not cap_name then wfatal(".endcapture without a valid .capture") end cap_name = nil cap_lineno = nil g_capbuffer = nil g_synclineno = 0 end -- Dump a capture buffer. map_coreop[".dumpcapture_1"] = function(params) if not params then return "name" end wflush() local name = params[1] if not match(name, "^[%a_][%w_]*$") then wfatal("bad capture name `"..name.."'") end cap_used[name] = true wline(function(out) local buf = cap_buffers[name] if buf then wdumplines(out, buf) end end) g_synclineno = 0 end -- Dump all captures and their buffers (with -PP only). local function dumpcaptures(out, lvl) out:write("Captures:\n") for name,buf in pairs(cap_buffers) do out:write(format(" %-20s %4s)\n", name, "("..#buf)) if lvl > 1 then local bar = rep("=", 76) out:write(" ", bar, "\n") for _,line in ipairs(buf) do out:write(" ", line, "\n") end out:write(" ", bar, "\n\n") end end out:write("\n") end -- Check for unfinished or unused captures. local function checkcaptures() if cap_name then wprinterr(g_fname, ":", cap_lineno, ": error: unfinished .capture `", cap_name,"'\n") return end for name in pairs(cap_buffers) do if not cap_used[name] then wprinterr(g_fname, ":*: error: missing .dumpcapture ", name ,"\n") end end end ------------------------------------------------------------------------------ -- Sections names. local map_sections = {} -- Pseudo-opcode to define code sections. -- TODO: Data sections, BSS sections. Needs extra C code and API. map_coreop[".section_*"] = function(params) if not params then return "name..." end if #map_sections > 0 then werror("duplicate section definition") end wflush() for sn,name in ipairs(params) do local opname = "."..name.."_0" if not match(name, "^[%a][%w_]*$") or map_op[opname] or map_op["."..name.."_*"] then werror("bad section name `"..name.."'") end map_sections[#map_sections+1] = name wline(format("#define DASM_SECTION_%s\t%d", upper(name), sn-1)) map_op[opname] = function(params) g_arch.section(sn-1) end end wline(format("#define DASM_MAXSECTION\t\t%d", #map_sections)) end -- Dump all sections. local function dumpsections(out, lvl) out:write("Sections:\n") for _,name in ipairs(map_sections) do out:write(format(" %s\n", name)) end out:write("\n") end ------------------------------------------------------------------------------ -- Replacement for customized Lua, which lacks the package library. local prefix = "" if not require then function require(name) local fp = assert(io.open(prefix..name..".lua")) local s = fp:read("*a") assert(fp:close()) return assert(loadstring(s, "@"..name..".lua"))() end end -- Load architecture-specific module. local function loadarch(arch) if not match(arch, "^[%w_]+$") then return "bad arch name" end local ok, m_arch = pcall(require, "dasm_"..arch) if not ok then return "cannot load module: "..m_arch end g_arch = m_arch wflush = m_arch.passcb(wline, werror, wfatal, wwarn) m_arch.setup(arch, g_opt) map_op, map_def = m_arch.mergemaps(map_coreop, map_def) end -- Dump architecture description. function opt_map.dumparch(args) local name = optparam(args) if not g_arch then local err = loadarch(name) if err then opterror(err) end end local t = {} for name in pairs(map_coreop) do t[#t+1] = name end for name in pairs(map_op) do t[#t+1] = name end sort(t) local out = stdout local _arch = g_arch._info out:write(format("%s version %s, released %s, %s\n", _info.name, _info.version, _info.release, _info.url)) g_arch.dumparch(out) local pseudo = true out:write("Pseudo-Opcodes:\n") for _,sname in ipairs(t) do local name, nparam = match(sname, "^(.+)_([0-9%*])$") if name then if pseudo and sub(name, 1, 1) ~= "." then out:write("\nOpcodes:\n") pseudo = false end local f = map_op[sname] local s if nparam ~= "*" then nparam = nparam + 0 end if nparam == 0 then s = "" elseif type(f) == "string" then s = map_op[".template__"](nil, f, nparam) else s = f(nil, nparam) end if type(s) == "table" then for _,s2 in ipairs(s) do out:write(format(" %-12s %s\n", name, s2)) end else out:write(format(" %-12s %s\n", name, s)) end end end out:write("\n") exit(0) end -- Pseudo-opcode to set the architecture. -- Only initially available (map_op is replaced when called). map_op[".arch_1"] = function(params) if not params then return "name" end local err = loadarch(params[1]) if err then wfatal(err) end wline(format("#if DASM_VERSION != %d", _info.vernum)) wline('#error "Version mismatch between DynASM and included encoding engine"') wline("#endif") end -- Dummy .arch pseudo-opcode to improve the error report. map_coreop[".arch_1"] = function(params) if not params then return "name" end wfatal("duplicate .arch statement") end ------------------------------------------------------------------------------ -- Dummy pseudo-opcode. Don't confuse '.nop' with 'nop'. map_coreop[".nop_*"] = function(params) if not params then return "[ignored...]" end end -- Pseudo-opcodes to raise errors. map_coreop[".error_1"] = function(params) if not params then return "message" end werror(params[1]) end map_coreop[".fatal_1"] = function(params) if not params then return "message" end wfatal(params[1]) end -- Dump all user defined elements. local function dumpdef(out) local lvl = g_opt.dumpdef if lvl == 0 then return end dumpsections(out, lvl) dumpdefines(out, lvl) if g_arch then g_arch.dumpdef(out, lvl) end dumpmacros(out, lvl) dumpcaptures(out, lvl) end ------------------------------------------------------------------------------ -- Helper for splitstmt. local splitlvl local function splitstmt_one(c) if c == "(" then splitlvl = ")"..splitlvl elseif c == "[" then splitlvl = "]"..splitlvl elseif c == "{" then splitlvl = "}"..splitlvl elseif c == ")" or c == "]" or c == "}" then if sub(splitlvl, 1, 1) ~= c then werror("unbalanced (), [] or {}") end splitlvl = sub(splitlvl, 2) elseif splitlvl == "" then return " \0 " end return c end -- Split statement into (pseudo-)opcode and params. local function splitstmt(stmt) -- Convert label with trailing-colon into .label statement. local label = match(stmt, "^%s*(.+):%s*$") if label then return ".label", {label} end -- Split at commas and equal signs, but obey parentheses and brackets. splitlvl = "" stmt = gsub(stmt, "[,%(%)%[%]{}]", splitstmt_one) if splitlvl ~= "" then werror("unbalanced () or []") end -- Split off opcode. local op, other = match(stmt, "^%s*([^%s%z]+)%s*(.*)$") if not op then werror("bad statement syntax") end -- Split parameters. local params = {} for p in gmatch(other, "%s*(%Z+)%z?") do params[#params+1] = gsub(p, "%s+$", "") end if #params > 16 then werror("too many parameters") end params.op = op return op, params end -- Process a single statement. dostmt = function(stmt) -- Ignore empty statements. if match(stmt, "^%s*$") then return end -- Capture macro defs before substitution. if mac_capture then return mac_capture(stmt) end stmt = definesubst(stmt) -- Emit C code without parsing the line. if sub(stmt, 1, 1) == "|" then local tail = sub(stmt, 2) wflush() if sub(tail, 1, 2) == "//" then wcomment(tail) else wline(tail, true) end return end -- Split into (pseudo-)opcode and params. local op, params = splitstmt(stmt) -- Get opcode handler (matching # of parameters or generic handler). local f = map_op[op.."_"..#params] or map_op[op.."_*"] if not f then if not g_arch then wfatal("first statement must be .arch") end -- Improve error report. for i=0,9 do if map_op[op.."_"..i] then werror("wrong number of parameters for `"..op.."'") end end werror("unknown statement `"..op.."'") end -- Call opcode handler or special handler for template strings. if type(f) == "string" then map_op[".template__"](params, f) else f(params) end end -- Process a single line. local function doline(line) if g_opt.flushline then wflush() end -- Assembler line? local indent, aline = match(line, "^(%s*)%|(.*)$") if not aline then -- No, plain C code line, need to flush first. wflush() wsync() wline(line, false) return end g_indent = indent -- Remember current line indentation. -- Emit C code (even from macros). Avoids echo and line parsing. if sub(aline, 1, 1) == "|" then if not mac_capture then wsync() elseif g_opt.comment then wsync() wcomment(aline) end dostmt(aline) return end -- Echo assembler line as a comment. if g_opt.comment then wsync() wcomment(aline) end -- Strip assembler comments. aline = gsub(aline, "//.*$", "") -- Split line into statements at semicolons. if match(aline, ";") then for stmt in gmatch(aline, "[^;]+") do dostmt(stmt) end else dostmt(aline) end end ------------------------------------------------------------------------------ -- Write DynASM header. local function dasmhead(out) out:write(format([[ /* ** This file has been pre-processed with DynASM. ** %s ** DynASM version %s, DynASM %s version %s ** DO NOT EDIT! The original file is in "%s". */ ]], _info.url, _info.version, g_arch._info.arch, g_arch._info.version, g_fname)) end -- Read input file. readfile = function(fin) g_indent = "" g_lineno = 0 g_synclineno = -1 -- Process all lines. for line in fin:lines() do g_lineno = g_lineno + 1 g_curline = line local ok, err = pcall(doline, line) if not ok and wprinterr(err, "\n") then return true end end wflush() -- Close input file. assert(fin == stdin or fin:close()) end -- Write output file. local function writefile(outfile) local fout -- Open output file. if outfile == nil or outfile == "-" then fout = stdout else fout = assert(io.open(outfile, "w")) end -- Write all buffered lines wdumplines(fout, g_wbuffer) -- Close output file. assert(fout == stdout or fout:close()) -- Optionally dump definitions. dumpdef(fout == stdout and stderr or stdout) end -- Translate an input file to an output file. local function translate(infile, outfile) g_wbuffer = {} g_indent = "" g_lineno = 0 g_synclineno = -1 -- Put header. wline(dasmhead) -- Read input file. local fin if infile == "-" then g_fname = "(stdin)" fin = stdin else g_fname = infile fin = assert(io.open(infile, "r")) end readfile(fin) -- Check for errors. if not g_arch then wprinterr(g_fname, ":*: error: missing .arch directive\n") end checkconds() checkmacros() checkcaptures() if g_errcount ~= 0 then stderr:write(g_fname, ":*: info: ", g_errcount, " error", (type(g_errcount) == "number" and g_errcount > 1) and "s" or "", " in input file -- no output file generated.\n") dumpdef(stderr) exit(1) end -- Write output file. writefile(outfile) end ------------------------------------------------------------------------------ -- Print help text. function opt_map.help() stdout:write("DynASM -- ", _info.description, ".\n") stdout:write("DynASM ", _info.version, " ", _info.release, " ", _info.url, "\n") stdout:write[[ Usage: dynasm [OPTION]... INFILE.dasc|- -h, --help Display this help text. -V, --version Display version and copyright information. -o, --outfile FILE Output file name (default is stdout). -I, --include DIR Add directory to the include search path. -c, --ccomment Use /* */ comments for assembler lines. -C, --cppcomment Use // comments for assembler lines (default). -N, --nocomment Suppress assembler lines in output. -M, --maccomment Show macro expansions as comments (default off). -L, --nolineno Suppress CPP line number information in output. -F, --flushline Flush action list for every line. -D NAME[=SUBST] Define a substitution. -U NAME Undefine a substitution. -P, --dumpdef Dump defines, macros, etc. Repeat for more output. -A, --dumparch ARCH Load architecture ARCH and dump description. ]] exit(0) end -- Print version information. function opt_map.version() stdout:write(format("%s version %s, released %s\n%s\n\n%s", _info.name, _info.version, _info.release, _info.url, _info.copyright)) exit(0) end -- Misc. options. function opt_map.outfile(args) g_opt.outfile = optparam(args) end function opt_map.include(args) insert(g_opt.include, 1, optparam(args)) end function opt_map.ccomment() g_opt.comment = "/*|"; g_opt.endcomment = " */" end function opt_map.cppcomment() g_opt.comment = "//|"; g_opt.endcomment = "" end function opt_map.nocomment() g_opt.comment = false end function opt_map.maccomment() g_opt.maccomment = true end function opt_map.nolineno() g_opt.cpp = false end function opt_map.flushline() g_opt.flushline = true end function opt_map.dumpdef() g_opt.dumpdef = g_opt.dumpdef + 1 end ------------------------------------------------------------------------------ -- Short aliases for long options. local opt_alias = { h = "help", ["?"] = "help", V = "version", o = "outfile", I = "include", c = "ccomment", C = "cppcomment", N = "nocomment", M = "maccomment", L = "nolineno", F = "flushline", P = "dumpdef", A = "dumparch", } -- Parse single option. local function parseopt(opt, args) opt_current = #opt == 1 and "-"..opt or "--"..opt local f = opt_map[opt] or opt_map[opt_alias[opt]] if not f then opterror("unrecognized option `", opt_current, "'. Try `--help'.\n") end f(args) end -- Parse arguments. local function parseargs(args) -- Default options. g_opt.comment = "//|" g_opt.endcomment = "" g_opt.cpp = true g_opt.dumpdef = 0 g_opt.include = { "" } -- Process all option arguments. args.argn = 1 repeat local a = args[args.argn] if not a then break end local lopt, opt = match(a, "^%-(%-?)(.+)") if not opt then break end args.argn = args.argn + 1 if lopt == "" then -- Loop through short options. for o in gmatch(opt, ".") do parseopt(o, args) end else -- Long option. parseopt(opt, args) end until false -- Check for proper number of arguments. local nargs = #args - args.argn + 1 if nargs ~= 1 then if nargs == 0 then if g_opt.dumpdef > 0 then return dumpdef(stdout) end end opt_map.help() end -- Translate a single input file to a single output file -- TODO: Handle multiple files? translate(args[args.argn], g_opt.outfile) end ------------------------------------------------------------------------------ -- Add the directory dynasm.lua resides in to the Lua module search path. local arg = arg if arg and arg[0] then prefix = match(arg[0], "^(.*[/\\])") if package and prefix then package.path = prefix.."?.lua;"..package.path end end -- Start DynASM. parseargs{...} ------------------------------------------------------------------------------
xLua/build/luajit-2.1.0b2/dynasm/dynasm.lua/0
{ "file_path": "xLua/build/luajit-2.1.0b2/dynasm/dynasm.lua", "repo_id": "xLua", "token_count": 11193 }
2,032
/* ** Debug library. ** Copyright (C) 2005-2016 Mike Pall. See Copyright Notice in luajit.h ** ** Major portions taken verbatim or adapted from the Lua interpreter. ** Copyright (C) 1994-2008 Lua.org, PUC-Rio. See Copyright Notice in lua.h */ #define lib_debug_c #define LUA_LIB #include "lua.h" #include "lauxlib.h" #include "lualib.h" #include "lj_obj.h" #include "lj_gc.h" #include "lj_err.h" #include "lj_debug.h" #include "lj_lib.h" /* ------------------------------------------------------------------------ */ #define LJLIB_MODULE_debug LJLIB_CF(debug_getregistry) { copyTV(L, L->top++, registry(L)); return 1; } LJLIB_CF(debug_getmetatable) LJLIB_REC(.) { lj_lib_checkany(L, 1); if (!lua_getmetatable(L, 1)) { setnilV(L->top-1); } return 1; } LJLIB_CF(debug_setmetatable) { lj_lib_checktabornil(L, 2); L->top = L->base+2; lua_setmetatable(L, 1); #if !LJ_52 setboolV(L->top-1, 1); #endif return 1; } LJLIB_CF(debug_getfenv) { lj_lib_checkany(L, 1); lua_getfenv(L, 1); return 1; } LJLIB_CF(debug_setfenv) { lj_lib_checktab(L, 2); L->top = L->base+2; if (!lua_setfenv(L, 1)) lj_err_caller(L, LJ_ERR_SETFENV); return 1; } /* ------------------------------------------------------------------------ */ static void settabss(lua_State *L, const char *i, const char *v) { lua_pushstring(L, v); lua_setfield(L, -2, i); } static void settabsi(lua_State *L, const char *i, int v) { lua_pushinteger(L, v); lua_setfield(L, -2, i); } static void settabsb(lua_State *L, const char *i, int v) { lua_pushboolean(L, v); lua_setfield(L, -2, i); } static lua_State *getthread(lua_State *L, int *arg) { if (L->base < L->top && tvisthread(L->base)) { *arg = 1; return threadV(L->base); } else { *arg = 0; return L; } } static void treatstackoption(lua_State *L, lua_State *L1, const char *fname) { if (L == L1) { lua_pushvalue(L, -2); lua_remove(L, -3); } else lua_xmove(L1, L, 1); lua_setfield(L, -2, fname); } LJLIB_CF(debug_getinfo) { lj_Debug ar; int arg, opt_f = 0, opt_L = 0; lua_State *L1 = getthread(L, &arg); const char *options = luaL_optstring(L, arg+2, "flnSu"); if (lua_isnumber(L, arg+1)) { if (!lua_getstack(L1, (int)lua_tointeger(L, arg+1), (lua_Debug *)&ar)) { setnilV(L->top-1); return 1; } } else if (L->base+arg < L->top && tvisfunc(L->base+arg)) { options = lua_pushfstring(L, ">%s", options); setfuncV(L1, L1->top++, funcV(L->base+arg)); } else { lj_err_arg(L, arg+1, LJ_ERR_NOFUNCL); } if (!lj_debug_getinfo(L1, options, &ar, 1)) lj_err_arg(L, arg+2, LJ_ERR_INVOPT); lua_createtable(L, 0, 16); /* Create result table. */ for (; *options; options++) { switch (*options) { case 'S': settabss(L, "source", ar.source); settabss(L, "short_src", ar.short_src); settabsi(L, "linedefined", ar.linedefined); settabsi(L, "lastlinedefined", ar.lastlinedefined); settabss(L, "what", ar.what); break; case 'l': settabsi(L, "currentline", ar.currentline); break; case 'u': settabsi(L, "nups", ar.nups); settabsi(L, "nparams", ar.nparams); settabsb(L, "isvararg", ar.isvararg); break; case 'n': settabss(L, "name", ar.name); settabss(L, "namewhat", ar.namewhat); break; case 'f': opt_f = 1; break; case 'L': opt_L = 1; break; default: break; } } if (opt_L) treatstackoption(L, L1, "activelines"); if (opt_f) treatstackoption(L, L1, "func"); return 1; /* Return result table. */ } LJLIB_CF(debug_getlocal) { int arg; lua_State *L1 = getthread(L, &arg); lua_Debug ar; const char *name; int slot = lj_lib_checkint(L, arg+2); if (tvisfunc(L->base+arg)) { L->top = L->base+arg+1; lua_pushstring(L, lua_getlocal(L, NULL, slot)); return 1; } if (!lua_getstack(L1, lj_lib_checkint(L, arg+1), &ar)) lj_err_arg(L, arg+1, LJ_ERR_LVLRNG); name = lua_getlocal(L1, &ar, slot); if (name) { lua_xmove(L1, L, 1); lua_pushstring(L, name); lua_pushvalue(L, -2); return 2; } else { setnilV(L->top-1); return 1; } } LJLIB_CF(debug_setlocal) { int arg; lua_State *L1 = getthread(L, &arg); lua_Debug ar; TValue *tv; if (!lua_getstack(L1, lj_lib_checkint(L, arg+1), &ar)) lj_err_arg(L, arg+1, LJ_ERR_LVLRNG); tv = lj_lib_checkany(L, arg+3); copyTV(L1, L1->top++, tv); lua_pushstring(L, lua_setlocal(L1, &ar, lj_lib_checkint(L, arg+2))); return 1; } static int debug_getupvalue(lua_State *L, int get) { int32_t n = lj_lib_checkint(L, 2); const char *name; lj_lib_checkfunc(L, 1); name = get ? lua_getupvalue(L, 1, n) : lua_setupvalue(L, 1, n); if (name) { lua_pushstring(L, name); if (!get) return 1; copyTV(L, L->top, L->top-2); L->top++; return 2; } return 0; } LJLIB_CF(debug_getupvalue) { return debug_getupvalue(L, 1); } LJLIB_CF(debug_setupvalue) { lj_lib_checkany(L, 3); return debug_getupvalue(L, 0); } LJLIB_CF(debug_upvalueid) { GCfunc *fn = lj_lib_checkfunc(L, 1); int32_t n = lj_lib_checkint(L, 2) - 1; if ((uint32_t)n >= fn->l.nupvalues) lj_err_arg(L, 2, LJ_ERR_IDXRNG); setlightudV(L->top-1, isluafunc(fn) ? (void *)gcref(fn->l.uvptr[n]) : (void *)&fn->c.upvalue[n]); return 1; } LJLIB_CF(debug_upvaluejoin) { GCfunc *fn[2]; GCRef *p[2]; int i; for (i = 0; i < 2; i++) { int32_t n; fn[i] = lj_lib_checkfunc(L, 2*i+1); if (!isluafunc(fn[i])) lj_err_arg(L, 2*i+1, LJ_ERR_NOLFUNC); n = lj_lib_checkint(L, 2*i+2) - 1; if ((uint32_t)n >= fn[i]->l.nupvalues) lj_err_arg(L, 2*i+2, LJ_ERR_IDXRNG); p[i] = &fn[i]->l.uvptr[n]; } setgcrefr(*p[0], *p[1]); lj_gc_objbarrier(L, fn[0], gcref(*p[1])); return 0; } #if LJ_52 LJLIB_CF(debug_getuservalue) { TValue *o = L->base; if (o < L->top && tvisudata(o)) settabV(L, o, tabref(udataV(o)->env)); else setnilV(o); L->top = o+1; return 1; } LJLIB_CF(debug_setuservalue) { TValue *o = L->base; if (!(o < L->top && tvisudata(o))) lj_err_argt(L, 1, LUA_TUSERDATA); if (!(o+1 < L->top && tvistab(o+1))) lj_err_argt(L, 2, LUA_TTABLE); L->top = o+2; lua_setfenv(L, 1); return 1; } #endif /* ------------------------------------------------------------------------ */ static const char KEY_HOOK = 'h'; static void hookf(lua_State *L, lua_Debug *ar) { static const char *const hooknames[] = {"call", "return", "line", "count", "tail return"}; lua_pushlightuserdata(L, (void *)&KEY_HOOK); lua_rawget(L, LUA_REGISTRYINDEX); if (lua_isfunction(L, -1)) { lua_pushstring(L, hooknames[(int)ar->event]); if (ar->currentline >= 0) lua_pushinteger(L, ar->currentline); else lua_pushnil(L); lua_call(L, 2, 0); } } static int makemask(const char *smask, int count) { int mask = 0; if (strchr(smask, 'c')) mask |= LUA_MASKCALL; if (strchr(smask, 'r')) mask |= LUA_MASKRET; if (strchr(smask, 'l')) mask |= LUA_MASKLINE; if (count > 0) mask |= LUA_MASKCOUNT; return mask; } static char *unmakemask(int mask, char *smask) { int i = 0; if (mask & LUA_MASKCALL) smask[i++] = 'c'; if (mask & LUA_MASKRET) smask[i++] = 'r'; if (mask & LUA_MASKLINE) smask[i++] = 'l'; smask[i] = '\0'; return smask; } LJLIB_CF(debug_sethook) { int arg, mask, count; lua_Hook func; (void)getthread(L, &arg); if (lua_isnoneornil(L, arg+1)) { lua_settop(L, arg+1); func = NULL; mask = 0; count = 0; /* turn off hooks */ } else { const char *smask = luaL_checkstring(L, arg+2); luaL_checktype(L, arg+1, LUA_TFUNCTION); count = luaL_optint(L, arg+3, 0); func = hookf; mask = makemask(smask, count); } lua_pushlightuserdata(L, (void *)&KEY_HOOK); lua_pushvalue(L, arg+1); lua_rawset(L, LUA_REGISTRYINDEX); lua_sethook(L, func, mask, count); return 0; } LJLIB_CF(debug_gethook) { char buff[5]; int mask = lua_gethookmask(L); lua_Hook hook = lua_gethook(L); if (hook != NULL && hook != hookf) { /* external hook? */ lua_pushliteral(L, "external hook"); } else { lua_pushlightuserdata(L, (void *)&KEY_HOOK); lua_rawget(L, LUA_REGISTRYINDEX); /* get hook */ } lua_pushstring(L, unmakemask(mask, buff)); lua_pushinteger(L, lua_gethookcount(L)); return 3; } /* ------------------------------------------------------------------------ */ LJLIB_CF(debug_debug) { for (;;) { char buffer[250]; fputs("lua_debug> ", stderr); if (fgets(buffer, sizeof(buffer), stdin) == 0 || strcmp(buffer, "cont\n") == 0) return 0; if (luaL_loadbuffer(L, buffer, strlen(buffer), "=(debug command)") || lua_pcall(L, 0, 0, 0)) { fputs(lua_tostring(L, -1), stderr); fputs("\n", stderr); } lua_settop(L, 0); /* remove eventual returns */ } } /* ------------------------------------------------------------------------ */ #define LEVELS1 12 /* size of the first part of the stack */ #define LEVELS2 10 /* size of the second part of the stack */ LJLIB_CF(debug_traceback) { int arg; lua_State *L1 = getthread(L, &arg); const char *msg = lua_tostring(L, arg+1); if (msg == NULL && L->top > L->base+arg) L->top = L->base+arg+1; else luaL_traceback(L, L1, msg, lj_lib_optint(L, arg+2, (L == L1))); return 1; } /* ------------------------------------------------------------------------ */ #include "lj_libdef.h" LUALIB_API int luaopen_debug(lua_State *L) { LJ_LIB_REG(L, LUA_DBLIBNAME, debug); return 1; }
xLua/build/luajit-2.1.0b2/src/lib_debug.c/0
{ "file_path": "xLua/build/luajit-2.1.0b2/src/lib_debug.c", "repo_id": "xLua", "token_count": 4514 }
2,033
/* ** IR assembler (SSA IR -> machine code). ** Copyright (C) 2005-2016 Mike Pall. See Copyright Notice in luajit.h */ #ifndef _LJ_ASM_H #define _LJ_ASM_H #include "lj_jit.h" #if LJ_HASJIT LJ_FUNC void lj_asm_trace(jit_State *J, GCtrace *T); LJ_FUNC void lj_asm_patchexit(jit_State *J, GCtrace *T, ExitNo exitno, MCode *target); #endif #endif
xLua/build/luajit-2.1.0b2/src/lj_asm.h/0
{ "file_path": "xLua/build/luajit-2.1.0b2/src/lj_asm.h", "repo_id": "xLua", "token_count": 165 }
2,034
/* ** FFI C callback handling. ** Copyright (C) 2005-2016 Mike Pall. See Copyright Notice in luajit.h */ #include "lj_obj.h" #if LJ_HASFFI #include "lj_gc.h" #include "lj_err.h" #include "lj_tab.h" #include "lj_state.h" #include "lj_frame.h" #include "lj_ctype.h" #include "lj_cconv.h" #include "lj_ccall.h" #include "lj_ccallback.h" #include "lj_target.h" #include "lj_mcode.h" #include "lj_trace.h" #include "lj_vm.h" /* -- Target-specific handling of callback slots -------------------------- */ #define CALLBACK_MCODE_SIZE (LJ_PAGESIZE * LJ_NUM_CBPAGE) #if LJ_OS_NOJIT /* Callbacks disabled. */ #define CALLBACK_SLOT2OFS(slot) (0*(slot)) #define CALLBACK_OFS2SLOT(ofs) (0*(ofs)) #define CALLBACK_MAX_SLOT 0 #elif LJ_TARGET_X86ORX64 #define CALLBACK_MCODE_HEAD (LJ_64 ? 8 : 0) #define CALLBACK_MCODE_GROUP (-2+1+2+(LJ_GC64 ? 10 : 5)+(LJ_64 ? 6 : 5)) #define CALLBACK_SLOT2OFS(slot) \ (CALLBACK_MCODE_HEAD + CALLBACK_MCODE_GROUP*((slot)/32) + 4*(slot)) static MSize CALLBACK_OFS2SLOT(MSize ofs) { MSize group; ofs -= CALLBACK_MCODE_HEAD; group = ofs / (32*4 + CALLBACK_MCODE_GROUP); return (ofs % (32*4 + CALLBACK_MCODE_GROUP))/4 + group*32; } #define CALLBACK_MAX_SLOT \ (((CALLBACK_MCODE_SIZE-CALLBACK_MCODE_HEAD)/(CALLBACK_MCODE_GROUP+4*32))*32) #elif LJ_TARGET_ARM #define CALLBACK_MCODE_HEAD 32 #elif LJ_TARGET_ARM64 #define CALLBACK_MCODE_HEAD 32 #elif LJ_TARGET_PPC #define CALLBACK_MCODE_HEAD 24 #elif LJ_TARGET_MIPS #define CALLBACK_MCODE_HEAD 24 #else /* Missing support for this architecture. */ #define CALLBACK_SLOT2OFS(slot) (0*(slot)) #define CALLBACK_OFS2SLOT(ofs) (0*(ofs)) #define CALLBACK_MAX_SLOT 0 #endif #ifndef CALLBACK_SLOT2OFS #define CALLBACK_SLOT2OFS(slot) (CALLBACK_MCODE_HEAD + 8*(slot)) #define CALLBACK_OFS2SLOT(ofs) (((ofs)-CALLBACK_MCODE_HEAD)/8) #define CALLBACK_MAX_SLOT (CALLBACK_OFS2SLOT(CALLBACK_MCODE_SIZE)) #endif /* Convert callback slot number to callback function pointer. */ static void *callback_slot2ptr(CTState *cts, MSize slot) { return (uint8_t *)cts->cb.mcode + CALLBACK_SLOT2OFS(slot); } /* Convert callback function pointer to slot number. */ MSize lj_ccallback_ptr2slot(CTState *cts, void *p) { uintptr_t ofs = (uintptr_t)((uint8_t *)p -(uint8_t *)cts->cb.mcode); if (ofs < CALLBACK_MCODE_SIZE) { MSize slot = CALLBACK_OFS2SLOT((MSize)ofs); if (CALLBACK_SLOT2OFS(slot) == (MSize)ofs) return slot; } return ~0u; /* Not a known callback function pointer. */ } /* Initialize machine code for callback function pointers. */ #if LJ_OS_NOJIT /* Disabled callback support. */ #define callback_mcode_init(g, p) UNUSED(p) #elif LJ_TARGET_X86ORX64 static void callback_mcode_init(global_State *g, uint8_t *page) { uint8_t *p = page; uint8_t *target = (uint8_t *)(void *)lj_vm_ffi_callback; MSize slot; #if LJ_64 *(void **)p = target; p += 8; #endif for (slot = 0; slot < CALLBACK_MAX_SLOT; slot++) { /* mov al, slot; jmp group */ *p++ = XI_MOVrib | RID_EAX; *p++ = (uint8_t)slot; if ((slot & 31) == 31 || slot == CALLBACK_MAX_SLOT-1) { /* push ebp/rbp; mov ah, slot>>8; mov ebp, &g. */ *p++ = XI_PUSH + RID_EBP; *p++ = XI_MOVrib | (RID_EAX+4); *p++ = (uint8_t)(slot >> 8); #if LJ_GC64 *p++ = 0x48; *p++ = XI_MOVri | RID_EBP; *(uint64_t *)p = (uint64_t)(g); p += 8; #else *p++ = XI_MOVri | RID_EBP; *(int32_t *)p = i32ptr(g); p += 4; #endif #if LJ_64 /* jmp [rip-pageofs] where lj_vm_ffi_callback is stored. */ *p++ = XI_GROUP5; *p++ = XM_OFS0 + (XOg_JMP<<3) + RID_EBP; *(int32_t *)p = (int32_t)(page-(p+4)); p += 4; #else /* jmp lj_vm_ffi_callback. */ *p++ = XI_JMP; *(int32_t *)p = target-(p+4); p += 4; #endif } else { *p++ = XI_JMPs; *p++ = (uint8_t)((2+2)*(31-(slot&31)) - 2); } } lua_assert(p - page <= CALLBACK_MCODE_SIZE); } #elif LJ_TARGET_ARM static void callback_mcode_init(global_State *g, uint32_t *page) { uint32_t *p = page; void *target = (void *)lj_vm_ffi_callback; MSize slot; /* This must match with the saveregs macro in buildvm_arm.dasc. */ *p++ = ARMI_SUB|ARMF_D(RID_R12)|ARMF_N(RID_R12)|ARMF_M(RID_PC); *p++ = ARMI_PUSH|ARMF_N(RID_SP)|RSET_RANGE(RID_R4,RID_R11+1)|RID2RSET(RID_LR); *p++ = ARMI_SUB|ARMI_K12|ARMF_D(RID_R12)|ARMF_N(RID_R12)|CALLBACK_MCODE_HEAD; *p++ = ARMI_STR|ARMI_LS_P|ARMI_LS_W|ARMF_D(RID_R12)|ARMF_N(RID_SP)|(CFRAME_SIZE-4*9); *p++ = ARMI_LDR|ARMI_LS_P|ARMI_LS_U|ARMF_D(RID_R12)|ARMF_N(RID_PC); *p++ = ARMI_LDR|ARMI_LS_P|ARMI_LS_U|ARMF_D(RID_PC)|ARMF_N(RID_PC); *p++ = u32ptr(g); *p++ = u32ptr(target); for (slot = 0; slot < CALLBACK_MAX_SLOT; slot++) { *p++ = ARMI_MOV|ARMF_D(RID_R12)|ARMF_M(RID_PC); *p = ARMI_B | ((page-p-2) & 0x00ffffffu); p++; } lua_assert(p - page <= CALLBACK_MCODE_SIZE); } #elif LJ_TARGET_ARM64 static void callback_mcode_init(global_State *g, uint32_t *page) { uint32_t *p = page; void *target = (void *)lj_vm_ffi_callback; MSize slot; *p++ = A64I_LDRLx | A64F_D(RID_X11) | A64F_S19(4); *p++ = A64I_LDRLx | A64F_D(RID_X10) | A64F_S19(5); *p++ = A64I_BR | A64F_N(RID_X11); *p++ = A64I_NOP; ((void **)p)[0] = target; ((void **)p)[1] = g; p += 4; for (slot = 0; slot < CALLBACK_MAX_SLOT; slot++) { *p++ = A64I_MOVZw | A64F_D(RID_X9) | A64F_U16(slot); *p = A64I_B | A64F_S26((page-p) & 0x03ffffffu); p++; } lua_assert(p - page <= CALLBACK_MCODE_SIZE); } #elif LJ_TARGET_PPC static void callback_mcode_init(global_State *g, uint32_t *page) { uint32_t *p = page; void *target = (void *)lj_vm_ffi_callback; MSize slot; *p++ = PPCI_LIS | PPCF_T(RID_TMP) | (u32ptr(target) >> 16); *p++ = PPCI_LIS | PPCF_T(RID_R12) | (u32ptr(g) >> 16); *p++ = PPCI_ORI | PPCF_A(RID_TMP)|PPCF_T(RID_TMP) | (u32ptr(target) & 0xffff); *p++ = PPCI_ORI | PPCF_A(RID_R12)|PPCF_T(RID_R12) | (u32ptr(g) & 0xffff); *p++ = PPCI_MTCTR | PPCF_T(RID_TMP); *p++ = PPCI_BCTR; for (slot = 0; slot < CALLBACK_MAX_SLOT; slot++) { *p++ = PPCI_LI | PPCF_T(RID_R11) | slot; *p = PPCI_B | (((page-p) & 0x00ffffffu) << 2); p++; } lua_assert(p - page <= CALLBACK_MCODE_SIZE); } #elif LJ_TARGET_MIPS static void callback_mcode_init(global_State *g, uint32_t *page) { uint32_t *p = page; void *target = (void *)lj_vm_ffi_callback; MSize slot; *p++ = MIPSI_SW | MIPSF_T(RID_R1)|MIPSF_S(RID_SP) | 0; *p++ = MIPSI_LUI | MIPSF_T(RID_R3) | (u32ptr(target) >> 16); *p++ = MIPSI_LUI | MIPSF_T(RID_R2) | (u32ptr(g) >> 16); *p++ = MIPSI_ORI | MIPSF_T(RID_R3)|MIPSF_S(RID_R3) |(u32ptr(target)&0xffff); *p++ = MIPSI_JR | MIPSF_S(RID_R3); *p++ = MIPSI_ORI | MIPSF_T(RID_R2)|MIPSF_S(RID_R2) | (u32ptr(g)&0xffff); for (slot = 0; slot < CALLBACK_MAX_SLOT; slot++) { *p = MIPSI_B | ((page-p-1) & 0x0000ffffu); p++; *p++ = MIPSI_LI | MIPSF_T(RID_R1) | slot; } lua_assert(p - page <= CALLBACK_MCODE_SIZE); } #else /* Missing support for this architecture. */ #define callback_mcode_init(g, p) UNUSED(p) #endif /* -- Machine code management --------------------------------------------- */ #if LJ_TARGET_WINDOWS #define WIN32_LEAN_AND_MEAN #include <windows.h> #elif LJ_TARGET_POSIX #include <sys/mman.h> #ifndef MAP_ANONYMOUS #define MAP_ANONYMOUS MAP_ANON #endif #endif /* Allocate and initialize area for callback function pointers. */ static void callback_mcode_new(CTState *cts) { size_t sz = (size_t)CALLBACK_MCODE_SIZE; void *p; if (CALLBACK_MAX_SLOT == 0) lj_err_caller(cts->L, LJ_ERR_FFI_CBACKOV); #if LJ_TARGET_WINDOWS p = VirtualAlloc(NULL, sz, MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE); if (!p) lj_err_caller(cts->L, LJ_ERR_FFI_CBACKOV); #elif LJ_TARGET_POSIX p = mmap(NULL, sz, (PROT_READ|PROT_WRITE), MAP_PRIVATE|MAP_ANONYMOUS, -1, 0); if (p == MAP_FAILED) lj_err_caller(cts->L, LJ_ERR_FFI_CBACKOV); #else /* Fallback allocator. Fails if memory is not executable by default. */ p = lj_mem_new(cts->L, sz); #endif cts->cb.mcode = p; callback_mcode_init(cts->g, p); lj_mcode_sync(p, (char *)p + sz); #if LJ_TARGET_WINDOWS { DWORD oprot; VirtualProtect(p, sz, PAGE_EXECUTE_READ, &oprot); } #elif LJ_TARGET_POSIX mprotect(p, sz, (PROT_READ|PROT_EXEC)); #endif } /* Free area for callback function pointers. */ void lj_ccallback_mcode_free(CTState *cts) { size_t sz = (size_t)CALLBACK_MCODE_SIZE; void *p = cts->cb.mcode; if (p == NULL) return; #if LJ_TARGET_WINDOWS VirtualFree(p, 0, MEM_RELEASE); UNUSED(sz); #elif LJ_TARGET_POSIX munmap(p, sz); #else lj_mem_free(cts->g, p, sz); #endif } /* -- C callback entry ---------------------------------------------------- */ /* Target-specific handling of register arguments. Similar to lj_ccall.c. */ #if LJ_TARGET_X86 #define CALLBACK_HANDLE_REGARG \ if (!isfp) { /* Only non-FP values may be passed in registers. */ \ if (n > 1) { /* Anything > 32 bit is passed on the stack. */ \ if (!LJ_ABI_WIN) ngpr = maxgpr; /* Prevent reordering. */ \ } else if (ngpr + 1 <= maxgpr) { \ sp = &cts->cb.gpr[ngpr]; \ ngpr += n; \ goto done; \ } \ } #elif LJ_TARGET_X64 && LJ_ABI_WIN /* Windows/x64 argument registers are strictly positional (use ngpr). */ #define CALLBACK_HANDLE_REGARG \ if (isfp) { \ if (ngpr < maxgpr) { sp = &cts->cb.fpr[ngpr++]; UNUSED(nfpr); goto done; } \ } else { \ if (ngpr < maxgpr) { sp = &cts->cb.gpr[ngpr++]; goto done; } \ } #elif LJ_TARGET_X64 #define CALLBACK_HANDLE_REGARG \ if (isfp) { \ if (nfpr + n <= CCALL_NARG_FPR) { \ sp = &cts->cb.fpr[nfpr]; \ nfpr += n; \ goto done; \ } \ } else { \ if (ngpr + n <= maxgpr) { \ sp = &cts->cb.gpr[ngpr]; \ ngpr += n; \ goto done; \ } \ } #elif LJ_TARGET_ARM #if LJ_ABI_SOFTFP #define CALLBACK_HANDLE_REGARG_FP1 UNUSED(isfp); #define CALLBACK_HANDLE_REGARG_FP2 #else #define CALLBACK_HANDLE_REGARG_FP1 \ if (isfp) { \ if (n == 1) { \ if (fprodd) { \ sp = &cts->cb.fpr[fprodd-1]; \ fprodd = 0; \ goto done; \ } else if (nfpr + 1 <= CCALL_NARG_FPR) { \ sp = &cts->cb.fpr[nfpr++]; \ fprodd = nfpr; \ goto done; \ } \ } else { \ if (nfpr + 1 <= CCALL_NARG_FPR) { \ sp = &cts->cb.fpr[nfpr++]; \ goto done; \ } \ } \ fprodd = 0; /* No reordering after the first FP value is on stack. */ \ } else { #define CALLBACK_HANDLE_REGARG_FP2 } #endif #define CALLBACK_HANDLE_REGARG \ CALLBACK_HANDLE_REGARG_FP1 \ if (n > 1) ngpr = (ngpr + 1u) & ~1u; /* Align to regpair. */ \ if (ngpr + n <= maxgpr) { \ sp = &cts->cb.gpr[ngpr]; \ ngpr += n; \ goto done; \ } CALLBACK_HANDLE_REGARG_FP2 #elif LJ_TARGET_ARM64 #define CALLBACK_HANDLE_REGARG \ if (isfp) { \ if (nfpr + n <= CCALL_NARG_FPR) { \ sp = &cts->cb.fpr[nfpr]; \ nfpr += n; \ goto done; \ } else { \ nfpr = CCALL_NARG_FPR; /* Prevent reordering. */ \ } \ } else { \ if (!LJ_TARGET_IOS && n > 1) \ ngpr = (ngpr + 1u) & ~1u; /* Align to regpair. */ \ if (ngpr + n <= maxgpr) { \ sp = &cts->cb.gpr[ngpr]; \ ngpr += n; \ goto done; \ } else { \ ngpr = CCALL_NARG_GPR; /* Prevent reordering. */ \ } \ } #elif LJ_TARGET_PPC #define CALLBACK_HANDLE_REGARG \ if (isfp) { \ if (nfpr + 1 <= CCALL_NARG_FPR) { \ sp = &cts->cb.fpr[nfpr++]; \ cta = ctype_get(cts, CTID_DOUBLE); /* FPRs always hold doubles. */ \ goto done; \ } \ } else { /* Try to pass argument in GPRs. */ \ if (n > 1) { \ lua_assert(ctype_isinteger(cta->info) && n == 2); /* int64_t. */ \ ngpr = (ngpr + 1u) & ~1u; /* Align int64_t to regpair. */ \ } \ if (ngpr + n <= maxgpr) { \ sp = &cts->cb.gpr[ngpr]; \ ngpr += n; \ goto done; \ } \ } #define CALLBACK_HANDLE_RET \ if (ctype_isfp(ctr->info) && ctr->size == sizeof(float)) \ *(double *)dp = *(float *)dp; /* FPRs always hold doubles. */ #elif LJ_TARGET_MIPS #define CALLBACK_HANDLE_GPR \ if (n > 1) ngpr = (ngpr + 1u) & ~1u; /* Align to regpair. */ \ if (ngpr + n <= maxgpr) { \ sp = &cts->cb.gpr[ngpr]; \ ngpr += n; \ goto done; \ } #if !LJ_ABI_SOFTFP /* MIPS32 hard-float */ #define CALLBACK_HANDLE_REGARG \ if (isfp && nfpr < CCALL_NARG_FPR) { /* Try to pass argument in FPRs. */ \ sp = (void *)((uint8_t *)&cts->cb.fpr[nfpr] + ((LJ_BE && n==1) ? 4 : 0)); \ nfpr++; ngpr += n; \ goto done; \ } else { /* Try to pass argument in GPRs. */ \ nfpr = CCALL_NARG_FPR; \ CALLBACK_HANDLE_GPR \ } #else /* MIPS32 soft-float */ #define CALLBACK_HANDLE_REGARG \ CALLBACK_HANDLE_GPR \ UNUSED(isfp); #endif #define CALLBACK_HANDLE_RET \ if (ctype_isfp(ctr->info) && ctr->size == sizeof(float)) \ ((float *)dp)[1] = *(float *)dp; #else #error "Missing calling convention definitions for this architecture" #endif /* Convert and push callback arguments to Lua stack. */ static void callback_conv_args(CTState *cts, lua_State *L) { TValue *o = L->top; intptr_t *stack = cts->cb.stack; MSize slot = cts->cb.slot; CTypeID id = 0, rid, fid; int gcsteps = 0; CType *ct; GCfunc *fn; int fntp; MSize ngpr = 0, nsp = 0, maxgpr = CCALL_NARG_GPR; #if CCALL_NARG_FPR MSize nfpr = 0; #if LJ_TARGET_ARM MSize fprodd = 0; #endif #endif if (slot < cts->cb.sizeid && (id = cts->cb.cbid[slot]) != 0) { ct = ctype_get(cts, id); rid = ctype_cid(ct->info); /* Return type. x86: +(spadj<<16). */ fn = funcV(lj_tab_getint(cts->miscmap, (int32_t)slot)); fntp = LJ_TFUNC; } else { /* Must set up frame first, before throwing the error. */ ct = NULL; rid = 0; fn = (GCfunc *)L; fntp = LJ_TTHREAD; } /* Continuation returns from callback. */ if (LJ_FR2) { (o++)->u64 = LJ_CONT_FFI_CALLBACK; (o++)->u64 = rid; o++; } else { o->u32.lo = LJ_CONT_FFI_CALLBACK; o->u32.hi = rid; o++; } setframe_gc(o, obj2gco(fn), fntp); setframe_ftsz(o, ((char *)(o+1) - (char *)L->base) + FRAME_CONT); L->top = L->base = ++o; if (!ct) lj_err_caller(cts->L, LJ_ERR_FFI_BADCBACK); if (isluafunc(fn)) setcframe_pc(L->cframe, proto_bc(funcproto(fn))+1); lj_state_checkstack(L, LUA_MINSTACK); /* May throw. */ o = L->base; /* Might have been reallocated. */ #if LJ_TARGET_X86 /* x86 has several different calling conventions. */ switch (ctype_cconv(ct->info)) { case CTCC_FASTCALL: maxgpr = 2; break; case CTCC_THISCALL: maxgpr = 1; break; default: maxgpr = 0; break; } #endif fid = ct->sib; while (fid) { CType *ctf = ctype_get(cts, fid); if (!ctype_isattrib(ctf->info)) { CType *cta; void *sp; CTSize sz; int isfp; MSize n; lua_assert(ctype_isfield(ctf->info)); cta = ctype_rawchild(cts, ctf); isfp = ctype_isfp(cta->info); sz = (cta->size + CTSIZE_PTR-1) & ~(CTSIZE_PTR-1); n = sz / CTSIZE_PTR; /* Number of GPRs or stack slots needed. */ CALLBACK_HANDLE_REGARG /* Handle register arguments. */ /* Otherwise pass argument on stack. */ if (CCALL_ALIGN_STACKARG && LJ_32 && sz == 8) nsp = (nsp + 1) & ~1u; /* Align 64 bit argument on stack. */ sp = &stack[nsp]; nsp += n; done: if (LJ_BE && cta->size < CTSIZE_PTR) sp = (void *)((uint8_t *)sp + CTSIZE_PTR-cta->size); gcsteps += lj_cconv_tv_ct(cts, cta, 0, o++, sp); } fid = ctf->sib; } L->top = o; #if LJ_TARGET_X86 /* Store stack adjustment for returns from non-cdecl callbacks. */ if (ctype_cconv(ct->info) != CTCC_CDECL) { #if LJ_FR2 (L->base-3)->u64 |= (nsp << (16+2)); #else (L->base-2)->u32.hi |= (nsp << (16+2)); #endif } #endif while (gcsteps-- > 0) lj_gc_check(L); } /* Convert Lua object to callback result. */ static void callback_conv_result(CTState *cts, lua_State *L, TValue *o) { #if LJ_FR2 CType *ctr = ctype_raw(cts, (uint16_t)(L->base-3)->u64); #else CType *ctr = ctype_raw(cts, (uint16_t)(L->base-2)->u32.hi); #endif #if LJ_TARGET_X86 cts->cb.gpr[2] = 0; #endif if (!ctype_isvoid(ctr->info)) { uint8_t *dp = (uint8_t *)&cts->cb.gpr[0]; #if CCALL_NUM_FPR if (ctype_isfp(ctr->info)) dp = (uint8_t *)&cts->cb.fpr[0]; #endif lj_cconv_ct_tv(cts, ctr, dp, o, 0); #ifdef CALLBACK_HANDLE_RET CALLBACK_HANDLE_RET #endif /* Extend returned integers to (at least) 32 bits. */ if (ctype_isinteger_or_bool(ctr->info) && ctr->size < 4) { if (ctr->info & CTF_UNSIGNED) *(uint32_t *)dp = ctr->size == 1 ? (uint32_t)*(uint8_t *)dp : (uint32_t)*(uint16_t *)dp; else *(int32_t *)dp = ctr->size == 1 ? (int32_t)*(int8_t *)dp : (int32_t)*(int16_t *)dp; } #if LJ_TARGET_X86 if (ctype_isfp(ctr->info)) cts->cb.gpr[2] = ctr->size == sizeof(float) ? 1 : 2; #endif } } /* Enter callback. */ lua_State * LJ_FASTCALL lj_ccallback_enter(CTState *cts, void *cf) { lua_State *L = cts->L; global_State *g = cts->g; lua_assert(L != NULL); if (tvref(g->jit_base)) { setstrV(L, L->top++, lj_err_str(L, LJ_ERR_FFI_BADCBACK)); if (g->panic) g->panic(L); exit(EXIT_FAILURE); } lj_trace_abort(g); /* Never record across callback. */ /* Setup C frame. */ cframe_prev(cf) = L->cframe; setcframe_L(cf, L); cframe_errfunc(cf) = -1; cframe_nres(cf) = 0; L->cframe = cf; callback_conv_args(cts, L); return L; /* Now call the function on this stack. */ } /* Leave callback. */ void LJ_FASTCALL lj_ccallback_leave(CTState *cts, TValue *o) { lua_State *L = cts->L; GCfunc *fn; TValue *obase = L->base; L->base = L->top; /* Keep continuation frame for throwing errors. */ if (o >= L->base) { /* PC of RET* is lost. Point to last line for result conv. errors. */ fn = curr_func(L); if (isluafunc(fn)) { GCproto *pt = funcproto(fn); setcframe_pc(L->cframe, proto_bc(pt)+pt->sizebc+1); } } callback_conv_result(cts, L, o); /* Finally drop C frame and continuation frame. */ L->top -= 2+2*LJ_FR2; L->base = obase; L->cframe = cframe_prev(L->cframe); cts->cb.slot = 0; /* Blacklist C function that called the callback. */ } /* -- C callback management ----------------------------------------------- */ /* Get an unused slot in the callback slot table. */ static MSize callback_slot_new(CTState *cts, CType *ct) { CTypeID id = ctype_typeid(cts, ct); CTypeID1 *cbid = cts->cb.cbid; MSize top; for (top = cts->cb.topid; top < cts->cb.sizeid; top++) if (LJ_LIKELY(cbid[top] == 0)) goto found; #if CALLBACK_MAX_SLOT if (top >= CALLBACK_MAX_SLOT) #endif lj_err_caller(cts->L, LJ_ERR_FFI_CBACKOV); if (!cts->cb.mcode) callback_mcode_new(cts); lj_mem_growvec(cts->L, cbid, cts->cb.sizeid, CALLBACK_MAX_SLOT, CTypeID1); cts->cb.cbid = cbid; memset(cbid+top, 0, (cts->cb.sizeid-top)*sizeof(CTypeID1)); found: cbid[top] = id; cts->cb.topid = top+1; return top; } /* Check for function pointer and supported argument/result types. */ static CType *callback_checkfunc(CTState *cts, CType *ct) { int narg = 0; if (!ctype_isptr(ct->info) || (LJ_64 && ct->size != CTSIZE_PTR)) return NULL; ct = ctype_rawchild(cts, ct); if (ctype_isfunc(ct->info)) { CType *ctr = ctype_rawchild(cts, ct); CTypeID fid = ct->sib; if (!(ctype_isvoid(ctr->info) || ctype_isenum(ctr->info) || ctype_isptr(ctr->info) || (ctype_isnum(ctr->info) && ctr->size <= 8))) return NULL; if ((ct->info & CTF_VARARG)) return NULL; while (fid) { CType *ctf = ctype_get(cts, fid); if (!ctype_isattrib(ctf->info)) { CType *cta; lua_assert(ctype_isfield(ctf->info)); cta = ctype_rawchild(cts, ctf); if (!(ctype_isenum(cta->info) || ctype_isptr(cta->info) || (ctype_isnum(cta->info) && cta->size <= 8)) || ++narg >= LUA_MINSTACK-3) return NULL; } fid = ctf->sib; } return ct; } return NULL; } /* Create a new callback and return the callback function pointer. */ void *lj_ccallback_new(CTState *cts, CType *ct, GCfunc *fn) { ct = callback_checkfunc(cts, ct); if (ct) { MSize slot = callback_slot_new(cts, ct); GCtab *t = cts->miscmap; setfuncV(cts->L, lj_tab_setint(cts->L, t, (int32_t)slot), fn); lj_gc_anybarriert(cts->L, t); return callback_slot2ptr(cts, slot); } return NULL; /* Bad conversion. */ } #endif
xLua/build/luajit-2.1.0b2/src/lj_ccallback.c/0
{ "file_path": "xLua/build/luajit-2.1.0b2/src/lj_ccallback.c", "repo_id": "xLua", "token_count": 9982 }
2,035
/* ** Debugging and introspection. ** Copyright (C) 2005-2016 Mike Pall. See Copyright Notice in luajit.h */ #define lj_debug_c #define LUA_CORE #include "lj_obj.h" #include "lj_err.h" #include "lj_debug.h" #include "lj_buf.h" #include "lj_tab.h" #include "lj_state.h" #include "lj_frame.h" #include "lj_bc.h" #include "lj_strfmt.h" #if LJ_HASJIT #include "lj_jit.h" #endif /* -- Frames -------------------------------------------------------------- */ /* Get frame corresponding to a level. */ cTValue *lj_debug_frame(lua_State *L, int level, int *size) { cTValue *frame, *nextframe, *bot = tvref(L->stack)+LJ_FR2; /* Traverse frames backwards. */ for (nextframe = frame = L->base-1; frame > bot; ) { if (frame_gc(frame) == obj2gco(L)) level++; /* Skip dummy frames. See lj_err_optype_call(). */ if (level-- == 0) { *size = (int)(nextframe - frame); return frame; /* Level found. */ } nextframe = frame; if (frame_islua(frame)) { frame = frame_prevl(frame); } else { if (frame_isvarg(frame)) level++; /* Skip vararg pseudo-frame. */ frame = frame_prevd(frame); } } *size = level; return NULL; /* Level not found. */ } /* Invalid bytecode position. */ #define NO_BCPOS (~(BCPos)0) /* Return bytecode position for function/frame or NO_BCPOS. */ static BCPos debug_framepc(lua_State *L, GCfunc *fn, cTValue *nextframe) { const BCIns *ins; GCproto *pt; BCPos pos; lua_assert(fn->c.gct == ~LJ_TFUNC || fn->c.gct == ~LJ_TTHREAD); if (!isluafunc(fn)) { /* Cannot derive a PC for non-Lua functions. */ return NO_BCPOS; } else if (nextframe == NULL) { /* Lua function on top. */ void *cf = cframe_raw(L->cframe); if (cf == NULL || (char *)cframe_pc(cf) == (char *)cframe_L(cf)) return NO_BCPOS; ins = cframe_pc(cf); /* Only happens during error/hook handling. */ } else { if (frame_islua(nextframe)) { ins = frame_pc(nextframe); } else if (frame_iscont(nextframe)) { ins = frame_contpc(nextframe); } else { /* Lua function below errfunc/gc/hook: find cframe to get the PC. */ void *cf = cframe_raw(L->cframe); TValue *f = L->base-1; for (;;) { if (cf == NULL) return NO_BCPOS; while (cframe_nres(cf) < 0) { if (f >= restorestack(L, -cframe_nres(cf))) break; cf = cframe_raw(cframe_prev(cf)); if (cf == NULL) return NO_BCPOS; } if (f < nextframe) break; if (frame_islua(f)) { f = frame_prevl(f); } else { if (frame_isc(f) || (frame_iscont(f) && frame_iscont_fficb(f))) cf = cframe_raw(cframe_prev(cf)); f = frame_prevd(f); } } ins = cframe_pc(cf); } } pt = funcproto(fn); pos = proto_bcpos(pt, ins) - 1; #if LJ_HASJIT if (pos > pt->sizebc) { /* Undo the effects of lj_trace_exit for JLOOP. */ GCtrace *T = (GCtrace *)((char *)(ins-1) - offsetof(GCtrace, startins)); lua_assert(bc_isret(bc_op(ins[-1]))); pos = proto_bcpos(pt, mref(T->startpc, const BCIns)); } #endif return pos; } /* -- Line numbers -------------------------------------------------------- */ /* Get line number for a bytecode position. */ BCLine LJ_FASTCALL lj_debug_line(GCproto *pt, BCPos pc) { const void *lineinfo = proto_lineinfo(pt); if (pc <= pt->sizebc && lineinfo) { BCLine first = pt->firstline; if (pc == pt->sizebc) return first + pt->numline; if (pc-- == 0) return first; if (pt->numline < 256) return first + (BCLine)((const uint8_t *)lineinfo)[pc]; else if (pt->numline < 65536) return first + (BCLine)((const uint16_t *)lineinfo)[pc]; else return first + (BCLine)((const uint32_t *)lineinfo)[pc]; } return 0; } /* Get line number for function/frame. */ static BCLine debug_frameline(lua_State *L, GCfunc *fn, cTValue *nextframe) { BCPos pc = debug_framepc(L, fn, nextframe); if (pc != NO_BCPOS) { GCproto *pt = funcproto(fn); lua_assert(pc <= pt->sizebc); return lj_debug_line(pt, pc); } return -1; } /* -- Variable names ------------------------------------------------------ */ /* Get name of a local variable from slot number and PC. */ static const char *debug_varname(const GCproto *pt, BCPos pc, BCReg slot) { const char *p = (const char *)proto_varinfo(pt); if (p) { BCPos lastpc = 0; for (;;) { const char *name = p; uint32_t vn = *(const uint8_t *)p; BCPos startpc, endpc; if (vn < VARNAME__MAX) { if (vn == VARNAME_END) break; /* End of varinfo. */ } else { do { p++; } while (*(const uint8_t *)p); /* Skip over variable name. */ } p++; lastpc = startpc = lastpc + lj_buf_ruleb128(&p); if (startpc > pc) break; endpc = startpc + lj_buf_ruleb128(&p); if (pc < endpc && slot-- == 0) { if (vn < VARNAME__MAX) { #define VARNAMESTR(name, str) str "\0" name = VARNAMEDEF(VARNAMESTR); #undef VARNAMESTR if (--vn) while (*name++ || --vn) ; } return name; } } } return NULL; } /* Get name of local variable from 1-based slot number and function/frame. */ static TValue *debug_localname(lua_State *L, const lua_Debug *ar, const char **name, BCReg slot1) { uint32_t offset = (uint32_t)ar->i_ci & 0xffff; uint32_t size = (uint32_t)ar->i_ci >> 16; TValue *frame = tvref(L->stack) + offset; TValue *nextframe = size ? frame + size : NULL; GCfunc *fn = frame_func(frame); BCPos pc = debug_framepc(L, fn, nextframe); if (!nextframe) nextframe = L->top+LJ_FR2; if ((int)slot1 < 0) { /* Negative slot number is for varargs. */ if (pc != NO_BCPOS) { GCproto *pt = funcproto(fn); if ((pt->flags & PROTO_VARARG)) { slot1 = pt->numparams + (BCReg)(-(int)slot1); if (frame_isvarg(frame)) { /* Vararg frame has been set up? (pc!=0) */ nextframe = frame; frame = frame_prevd(frame); } if (frame + slot1+LJ_FR2 < nextframe) { *name = "(*vararg)"; return frame+slot1; } } } return NULL; } if (pc != NO_BCPOS && (*name = debug_varname(funcproto(fn), pc, slot1-1)) != NULL) ; else if (slot1 > 0 && frame + slot1+LJ_FR2 < nextframe) *name = "(*temporary)"; return frame+slot1; } /* Get name of upvalue. */ const char *lj_debug_uvname(GCproto *pt, uint32_t idx) { const uint8_t *p = proto_uvinfo(pt); lua_assert(idx < pt->sizeuv); if (!p) return ""; if (idx) while (*p++ || --idx) ; return (const char *)p; } /* Get name and value of upvalue. */ const char *lj_debug_uvnamev(cTValue *o, uint32_t idx, TValue **tvp) { if (tvisfunc(o)) { GCfunc *fn = funcV(o); if (isluafunc(fn)) { GCproto *pt = funcproto(fn); if (idx < pt->sizeuv) { *tvp = uvval(&gcref(fn->l.uvptr[idx])->uv); return lj_debug_uvname(pt, idx); } } else { if (idx < fn->c.nupvalues) { *tvp = &fn->c.upvalue[idx]; return ""; } } } return NULL; } /* Deduce name of an object from slot number and PC. */ const char *lj_debug_slotname(GCproto *pt, const BCIns *ip, BCReg slot, const char **name) { const char *lname; restart: lname = debug_varname(pt, proto_bcpos(pt, ip), slot); if (lname != NULL) { *name = lname; return "local"; } while (--ip > proto_bc(pt)) { BCIns ins = *ip; BCOp op = bc_op(ins); BCReg ra = bc_a(ins); if (bcmode_a(op) == BCMbase) { if (slot >= ra && (op != BC_KNIL || slot <= bc_d(ins))) return NULL; } else if (bcmode_a(op) == BCMdst && ra == slot) { switch (bc_op(ins)) { case BC_MOV: if (ra == slot) { slot = bc_d(ins); goto restart; } break; case BC_GGET: *name = strdata(gco2str(proto_kgc(pt, ~(ptrdiff_t)bc_d(ins)))); return "global"; case BC_TGETS: *name = strdata(gco2str(proto_kgc(pt, ~(ptrdiff_t)bc_c(ins)))); if (ip > proto_bc(pt)) { BCIns insp = ip[-1]; if (bc_op(insp) == BC_MOV && bc_a(insp) == ra+1+LJ_FR2 && bc_d(insp) == bc_b(ins)) return "method"; } return "field"; case BC_UGET: *name = lj_debug_uvname(pt, bc_d(ins)); return "upvalue"; default: return NULL; } } } return NULL; } /* Deduce function name from caller of a frame. */ const char *lj_debug_funcname(lua_State *L, cTValue *frame, const char **name) { cTValue *pframe; GCfunc *fn; BCPos pc; if (frame <= tvref(L->stack)+LJ_FR2) return NULL; if (frame_isvarg(frame)) frame = frame_prevd(frame); pframe = frame_prev(frame); fn = frame_func(pframe); pc = debug_framepc(L, fn, frame); if (pc != NO_BCPOS) { GCproto *pt = funcproto(fn); const BCIns *ip = &proto_bc(pt)[check_exp(pc < pt->sizebc, pc)]; MMS mm = bcmode_mm(bc_op(*ip)); if (mm == MM_call) { BCReg slot = bc_a(*ip); if (bc_op(*ip) == BC_ITERC) slot -= 3; return lj_debug_slotname(pt, ip, slot, name); } else if (mm != MM__MAX) { *name = strdata(mmname_str(G(L), mm)); return "metamethod"; } } return NULL; } /* -- Source code locations ----------------------------------------------- */ /* Generate shortened source name. */ void lj_debug_shortname(char *out, GCstr *str, BCLine line) { const char *src = strdata(str); if (*src == '=') { strncpy(out, src+1, LUA_IDSIZE); /* Remove first char. */ out[LUA_IDSIZE-1] = '\0'; /* Ensures null termination. */ } else if (*src == '@') { /* Output "source", or "...source". */ size_t len = str->len-1; src++; /* Skip the `@' */ if (len >= LUA_IDSIZE) { src += len-(LUA_IDSIZE-4); /* Get last part of file name. */ *out++ = '.'; *out++ = '.'; *out++ = '.'; } strcpy(out, src); } else { /* Output [string "string"] or [builtin:name]. */ size_t len; /* Length, up to first control char. */ for (len = 0; len < LUA_IDSIZE-12; len++) if (((const unsigned char *)src)[len] < ' ') break; strcpy(out, line == ~(BCLine)0 ? "[builtin:" : "[string \""); out += 9; if (src[len] != '\0') { /* Must truncate? */ if (len > LUA_IDSIZE-15) len = LUA_IDSIZE-15; strncpy(out, src, len); out += len; strcpy(out, "..."); out += 3; } else { strcpy(out, src); out += len; } strcpy(out, line == ~(BCLine)0 ? "]" : "\"]"); } } /* Add current location of a frame to error message. */ void lj_debug_addloc(lua_State *L, const char *msg, cTValue *frame, cTValue *nextframe) { if (frame) { GCfunc *fn = frame_func(frame); if (isluafunc(fn)) { BCLine line = debug_frameline(L, fn, nextframe); if (line >= 0) { GCproto *pt = funcproto(fn); char buf[LUA_IDSIZE]; lj_debug_shortname(buf, proto_chunkname(pt), pt->firstline); lj_strfmt_pushf(L, "%s:%d: %s", buf, line, msg); return; } } } lj_strfmt_pushf(L, "%s", msg); } /* Push location string for a bytecode position to Lua stack. */ void lj_debug_pushloc(lua_State *L, GCproto *pt, BCPos pc) { GCstr *name = proto_chunkname(pt); const char *s = strdata(name); MSize i, len = name->len; BCLine line = lj_debug_line(pt, pc); if (pt->firstline == ~(BCLine)0) { lj_strfmt_pushf(L, "builtin:%s", s); } else if (*s == '@') { s++; len--; for (i = len; i > 0; i--) if (s[i] == '/' || s[i] == '\\') { s += i+1; break; } lj_strfmt_pushf(L, "%s:%d", s, line); } else if (len > 40) { lj_strfmt_pushf(L, "%p:%d", pt, line); } else if (*s == '=') { lj_strfmt_pushf(L, "%s:%d", s+1, line); } else { lj_strfmt_pushf(L, "\"%s\":%d", s, line); } } /* -- Public debug API ---------------------------------------------------- */ /* lua_getupvalue() and lua_setupvalue() are in lj_api.c. */ LUA_API const char *lua_getlocal(lua_State *L, const lua_Debug *ar, int n) { const char *name = NULL; if (ar) { TValue *o = debug_localname(L, ar, &name, (BCReg)n); if (name) { copyTV(L, L->top, o); incr_top(L); } } else if (tvisfunc(L->top-1) && isluafunc(funcV(L->top-1))) { name = debug_varname(funcproto(funcV(L->top-1)), 0, (BCReg)n-1); } return name; } LUA_API const char *lua_setlocal(lua_State *L, const lua_Debug *ar, int n) { const char *name = NULL; TValue *o = debug_localname(L, ar, &name, (BCReg)n); if (name) copyTV(L, o, L->top-1); L->top--; return name; } int lj_debug_getinfo(lua_State *L, const char *what, lj_Debug *ar, int ext) { int opt_f = 0, opt_L = 0; TValue *frame = NULL; TValue *nextframe = NULL; GCfunc *fn; if (*what == '>') { TValue *func = L->top - 1; api_check(L, tvisfunc(func)); fn = funcV(func); L->top--; what++; } else { uint32_t offset = (uint32_t)ar->i_ci & 0xffff; uint32_t size = (uint32_t)ar->i_ci >> 16; lua_assert(offset != 0); frame = tvref(L->stack) + offset; if (size) nextframe = frame + size; lua_assert(frame <= tvref(L->maxstack) && (!nextframe || nextframe <= tvref(L->maxstack))); fn = frame_func(frame); lua_assert(fn->c.gct == ~LJ_TFUNC); } for (; *what; what++) { if (*what == 'S') { if (isluafunc(fn)) { GCproto *pt = funcproto(fn); BCLine firstline = pt->firstline; GCstr *name = proto_chunkname(pt); ar->source = strdata(name); lj_debug_shortname(ar->short_src, name, pt->firstline); ar->linedefined = (int)firstline; ar->lastlinedefined = (int)(firstline + pt->numline); ar->what = (firstline || !pt->numline) ? "Lua" : "main"; } else { ar->source = "=[C]"; ar->short_src[0] = '['; ar->short_src[1] = 'C'; ar->short_src[2] = ']'; ar->short_src[3] = '\0'; ar->linedefined = -1; ar->lastlinedefined = -1; ar->what = "C"; } } else if (*what == 'l') { ar->currentline = frame ? debug_frameline(L, fn, nextframe) : -1; } else if (*what == 'u') { ar->nups = fn->c.nupvalues; if (ext) { if (isluafunc(fn)) { GCproto *pt = funcproto(fn); ar->nparams = pt->numparams; ar->isvararg = !!(pt->flags & PROTO_VARARG); } else { ar->nparams = 0; ar->isvararg = 1; } } } else if (*what == 'n') { ar->namewhat = frame ? lj_debug_funcname(L, frame, &ar->name) : NULL; if (ar->namewhat == NULL) { ar->namewhat = ""; ar->name = NULL; } } else if (*what == 'f') { opt_f = 1; } else if (*what == 'L') { opt_L = 1; } else { return 0; /* Bad option. */ } } if (opt_f) { setfuncV(L, L->top, fn); incr_top(L); } if (opt_L) { if (isluafunc(fn)) { GCtab *t = lj_tab_new(L, 0, 0); GCproto *pt = funcproto(fn); const void *lineinfo = proto_lineinfo(pt); if (lineinfo) { BCLine first = pt->firstline; int sz = pt->numline < 256 ? 1 : pt->numline < 65536 ? 2 : 4; MSize i, szl = pt->sizebc-1; for (i = 0; i < szl; i++) { BCLine line = first + (sz == 1 ? (BCLine)((const uint8_t *)lineinfo)[i] : sz == 2 ? (BCLine)((const uint16_t *)lineinfo)[i] : (BCLine)((const uint32_t *)lineinfo)[i]); setboolV(lj_tab_setint(L, t, line), 1); } } settabV(L, L->top, t); } else { setnilV(L->top); } incr_top(L); } return 1; /* Ok. */ } LUA_API int lua_getinfo(lua_State *L, const char *what, lua_Debug *ar) { return lj_debug_getinfo(L, what, (lj_Debug *)ar, 0); } LUA_API int lua_getstack(lua_State *L, int level, lua_Debug *ar) { int size; cTValue *frame = lj_debug_frame(L, level, &size); if (frame) { ar->i_ci = (size << 16) + (int)(frame - tvref(L->stack)); return 1; } else { ar->i_ci = level - size; return 0; } } #if LJ_HASPROFILE /* Put the chunkname into a buffer. */ static int debug_putchunkname(SBuf *sb, GCproto *pt, int pathstrip) { GCstr *name = proto_chunkname(pt); const char *p = strdata(name); if (pt->firstline == ~(BCLine)0) { lj_buf_putmem(sb, "[builtin:", 9); lj_buf_putstr(sb, name); lj_buf_putb(sb, ']'); return 0; } if (*p == '=' || *p == '@') { MSize len = name->len-1; p++; if (pathstrip) { int i; for (i = len-1; i >= 0; i--) if (p[i] == '/' || p[i] == '\\') { len -= i+1; p = p+i+1; break; } } lj_buf_putmem(sb, p, len); } else { lj_buf_putmem(sb, "[string]", 8); } return 1; } /* Put a compact stack dump into a buffer. */ void lj_debug_dumpstack(lua_State *L, SBuf *sb, const char *fmt, int depth) { int level = 0, dir = 1, pathstrip = 1; MSize lastlen = 0; if (depth < 0) { level = ~depth; depth = dir = -1; } /* Reverse frames. */ while (level != depth) { /* Loop through all frame. */ int size; cTValue *frame = lj_debug_frame(L, level, &size); if (frame) { cTValue *nextframe = size ? frame+size : NULL; GCfunc *fn = frame_func(frame); const uint8_t *p = (const uint8_t *)fmt; int c; while ((c = *p++)) { switch (c) { case 'p': /* Preserve full path. */ pathstrip = 0; break; case 'F': case 'f': { /* Dump function name. */ const char *name; const char *what = lj_debug_funcname(L, frame, &name); if (what) { if (c == 'F' && isluafunc(fn)) { /* Dump module:name for 'F'. */ GCproto *pt = funcproto(fn); if (pt->firstline != ~(BCLine)0) { /* Not a bytecode builtin. */ debug_putchunkname(sb, pt, pathstrip); lj_buf_putb(sb, ':'); } } lj_buf_putmem(sb, name, (MSize)strlen(name)); break; } /* else: can't derive a name, dump module:line. */ } /* fallthrough */ case 'l': /* Dump module:line. */ if (isluafunc(fn)) { GCproto *pt = funcproto(fn); if (debug_putchunkname(sb, pt, pathstrip)) { /* Regular Lua function. */ BCLine line = c == 'l' ? debug_frameline(L, fn, nextframe) : pt->firstline; lj_buf_putb(sb, ':'); lj_strfmt_putint(sb, line >= 0 ? line : pt->firstline); } } else if (isffunc(fn)) { /* Dump numbered builtins. */ lj_buf_putmem(sb, "[builtin#", 9); lj_strfmt_putint(sb, fn->c.ffid); lj_buf_putb(sb, ']'); } else { /* Dump C function address. */ lj_buf_putb(sb, '@'); lj_strfmt_putptr(sb, fn->c.f); } break; case 'Z': /* Zap trailing separator. */ lastlen = sbuflen(sb); break; default: lj_buf_putb(sb, c); break; } } } else if (dir == 1) { break; } else { level -= size; /* Reverse frame order: quickly skip missing level. */ } level += dir; } if (lastlen) setsbufP(sb, sbufB(sb) + lastlen); /* Zap trailing separator. */ } #endif /* Number of frames for the leading and trailing part of a traceback. */ #define TRACEBACK_LEVELS1 12 #define TRACEBACK_LEVELS2 10 LUALIB_API void luaL_traceback (lua_State *L, lua_State *L1, const char *msg, int level) { int top = (int)(L->top - L->base); int lim = TRACEBACK_LEVELS1; lua_Debug ar; if (msg) lua_pushfstring(L, "%s\n", msg); lua_pushliteral(L, "stack traceback:"); while (lua_getstack(L1, level++, &ar)) { GCfunc *fn; if (level > lim) { if (!lua_getstack(L1, level + TRACEBACK_LEVELS2, &ar)) { level--; } else { lua_pushliteral(L, "\n\t..."); lua_getstack(L1, -10, &ar); level = ar.i_ci - TRACEBACK_LEVELS2; } lim = 2147483647; continue; } lua_getinfo(L1, "Snlf", &ar); fn = funcV(L1->top-1); L1->top--; if (isffunc(fn) && !*ar.namewhat) lua_pushfstring(L, "\n\t[builtin#%d]:", fn->c.ffid); else lua_pushfstring(L, "\n\t%s:", ar.short_src); if (ar.currentline > 0) lua_pushfstring(L, "%d:", ar.currentline); if (*ar.namewhat) { lua_pushfstring(L, " in function " LUA_QS, ar.name); } else { if (*ar.what == 'm') { lua_pushliteral(L, " in main chunk"); } else if (*ar.what == 'C') { lua_pushfstring(L, " at %p", fn->c.f); } else { lua_pushfstring(L, " in function <%s:%d>", ar.short_src, ar.linedefined); } } if ((int)(L->top - L->base) - top >= 15) lua_concat(L, (int)(L->top - L->base) - top); } lua_concat(L, (int)(L->top - L->base) - top); }
xLua/build/luajit-2.1.0b2/src/lj_debug.c/0
{ "file_path": "xLua/build/luajit-2.1.0b2/src/lj_debug.c", "repo_id": "xLua", "token_count": 9140 }
2,036
/* ** Function handling (prototypes, functions and upvalues). ** Copyright (C) 2005-2016 Mike Pall. See Copyright Notice in luajit.h ** ** Portions taken verbatim or adapted from the Lua interpreter. ** Copyright (C) 1994-2008 Lua.org, PUC-Rio. See Copyright Notice in lua.h */ #define lj_func_c #define LUA_CORE #include "lj_obj.h" #include "lj_gc.h" #include "lj_func.h" #include "lj_trace.h" #include "lj_vm.h" /* -- Prototypes ---------------------------------------------------------- */ void LJ_FASTCALL lj_func_freeproto(global_State *g, GCproto *pt) { lj_mem_free(g, pt, pt->sizept); } /* -- Upvalues ------------------------------------------------------------ */ static void unlinkuv(GCupval *uv) { lua_assert(uvprev(uvnext(uv)) == uv && uvnext(uvprev(uv)) == uv); setgcrefr(uvnext(uv)->prev, uv->prev); setgcrefr(uvprev(uv)->next, uv->next); } /* Find existing open upvalue for a stack slot or create a new one. */ static GCupval *func_finduv(lua_State *L, TValue *slot) { global_State *g = G(L); GCRef *pp = &L->openupval; GCupval *p; GCupval *uv; /* Search the sorted list of open upvalues. */ while (gcref(*pp) != NULL && uvval((p = gco2uv(gcref(*pp)))) >= slot) { lua_assert(!p->closed && uvval(p) != &p->tv); if (uvval(p) == slot) { /* Found open upvalue pointing to same slot? */ if (isdead(g, obj2gco(p))) /* Resurrect it, if it's dead. */ flipwhite(obj2gco(p)); return p; } pp = &p->nextgc; } /* No matching upvalue found. Create a new one. */ uv = lj_mem_newt(L, sizeof(GCupval), GCupval); newwhite(g, uv); uv->gct = ~LJ_TUPVAL; uv->closed = 0; /* Still open. */ setmref(uv->v, slot); /* Pointing to the stack slot. */ /* NOBARRIER: The GCupval is new (marked white) and open. */ setgcrefr(uv->nextgc, *pp); /* Insert into sorted list of open upvalues. */ setgcref(*pp, obj2gco(uv)); setgcref(uv->prev, obj2gco(&g->uvhead)); /* Insert into GC list, too. */ setgcrefr(uv->next, g->uvhead.next); setgcref(uvnext(uv)->prev, obj2gco(uv)); setgcref(g->uvhead.next, obj2gco(uv)); lua_assert(uvprev(uvnext(uv)) == uv && uvnext(uvprev(uv)) == uv); return uv; } /* Create an empty and closed upvalue. */ static GCupval *func_emptyuv(lua_State *L) { GCupval *uv = (GCupval *)lj_mem_newgco(L, sizeof(GCupval)); uv->gct = ~LJ_TUPVAL; uv->closed = 1; setnilV(&uv->tv); setmref(uv->v, &uv->tv); return uv; } /* Close all open upvalues pointing to some stack level or above. */ void LJ_FASTCALL lj_func_closeuv(lua_State *L, TValue *level) { GCupval *uv; global_State *g = G(L); while (gcref(L->openupval) != NULL && uvval((uv = gco2uv(gcref(L->openupval)))) >= level) { GCobj *o = obj2gco(uv); lua_assert(!isblack(o) && !uv->closed && uvval(uv) != &uv->tv); setgcrefr(L->openupval, uv->nextgc); /* No longer in open list. */ if (isdead(g, o)) { lj_func_freeuv(g, uv); } else { unlinkuv(uv); lj_gc_closeuv(g, uv); } } } void LJ_FASTCALL lj_func_freeuv(global_State *g, GCupval *uv) { if (!uv->closed) unlinkuv(uv); lj_mem_freet(g, uv); } /* -- Functions (closures) ------------------------------------------------ */ GCfunc *lj_func_newC(lua_State *L, MSize nelems, GCtab *env) { GCfunc *fn = (GCfunc *)lj_mem_newgco(L, sizeCfunc(nelems)); fn->c.gct = ~LJ_TFUNC; fn->c.ffid = FF_C; fn->c.nupvalues = (uint8_t)nelems; /* NOBARRIER: The GCfunc is new (marked white). */ setmref(fn->c.pc, &G(L)->bc_cfunc_ext); setgcref(fn->c.env, obj2gco(env)); return fn; } static GCfunc *func_newL(lua_State *L, GCproto *pt, GCtab *env) { uint32_t count; GCfunc *fn = (GCfunc *)lj_mem_newgco(L, sizeLfunc((MSize)pt->sizeuv)); fn->l.gct = ~LJ_TFUNC; fn->l.ffid = FF_LUA; fn->l.nupvalues = 0; /* Set to zero until upvalues are initialized. */ /* NOBARRIER: Really a setgcref. But the GCfunc is new (marked white). */ setmref(fn->l.pc, proto_bc(pt)); setgcref(fn->l.env, obj2gco(env)); /* Saturating 3 bit counter (0..7) for created closures. */ count = (uint32_t)pt->flags + PROTO_CLCOUNT; pt->flags = (uint8_t)(count - ((count >> PROTO_CLC_BITS) & PROTO_CLCOUNT)); return fn; } /* Create a new Lua function with empty upvalues. */ GCfunc *lj_func_newL_empty(lua_State *L, GCproto *pt, GCtab *env) { GCfunc *fn = func_newL(L, pt, env); MSize i, nuv = pt->sizeuv; /* NOBARRIER: The GCfunc is new (marked white). */ for (i = 0; i < nuv; i++) { GCupval *uv = func_emptyuv(L); uv->dhash = (uint32_t)(uintptr_t)pt ^ ((uint32_t)proto_uv(pt)[i] << 24); setgcref(fn->l.uvptr[i], obj2gco(uv)); } fn->l.nupvalues = (uint8_t)nuv; return fn; } /* Do a GC check and create a new Lua function with inherited upvalues. */ GCfunc *lj_func_newL_gc(lua_State *L, GCproto *pt, GCfuncL *parent) { GCfunc *fn; GCRef *puv; MSize i, nuv; TValue *base; lj_gc_check_fixtop(L); fn = func_newL(L, pt, tabref(parent->env)); /* NOBARRIER: The GCfunc is new (marked white). */ puv = parent->uvptr; nuv = pt->sizeuv; base = L->base; for (i = 0; i < nuv; i++) { uint32_t v = proto_uv(pt)[i]; GCupval *uv; if ((v & PROTO_UV_LOCAL)) { uv = func_finduv(L, base + (v & 0xff)); uv->immutable = ((v / PROTO_UV_IMMUTABLE) & 1); uv->dhash = (uint32_t)(uintptr_t)mref(parent->pc, char) ^ (v << 24); } else { uv = &gcref(puv[v])->uv; } setgcref(fn->l.uvptr[i], obj2gco(uv)); } fn->l.nupvalues = (uint8_t)nuv; return fn; } void LJ_FASTCALL lj_func_free(global_State *g, GCfunc *fn) { MSize size = isluafunc(fn) ? sizeLfunc((MSize)fn->l.nupvalues) : sizeCfunc((MSize)fn->c.nupvalues); lj_mem_free(g, fn, size); }
xLua/build/luajit-2.1.0b2/src/lj_func.c/0
{ "file_path": "xLua/build/luajit-2.1.0b2/src/lj_func.c", "repo_id": "xLua", "token_count": 2528 }
2,037
/* ** Machine code management. ** Copyright (C) 2005-2016 Mike Pall. See Copyright Notice in luajit.h */ #define lj_mcode_c #define LUA_CORE #include "lj_obj.h" #if LJ_HASJIT #include "lj_gc.h" #include "lj_err.h" #include "lj_jit.h" #include "lj_mcode.h" #include "lj_trace.h" #include "lj_dispatch.h" #endif #if LJ_HASJIT || LJ_HASFFI #include "lj_vm.h" #endif /* -- OS-specific functions ----------------------------------------------- */ #if LJ_HASJIT || LJ_HASFFI /* Define this if you want to run LuaJIT with Valgrind. */ #ifdef LUAJIT_USE_VALGRIND #include <valgrind/valgrind.h> #endif #if LJ_TARGET_IOS void sys_icache_invalidate(void *start, size_t len); #endif /* Synchronize data/instruction cache. */ void lj_mcode_sync(void *start, void *end) { #ifdef LUAJIT_USE_VALGRIND VALGRIND_DISCARD_TRANSLATIONS(start, (char *)end-(char *)start); #endif #if LJ_TARGET_X86ORX64 UNUSED(start); UNUSED(end); #elif LJ_TARGET_IOS sys_icache_invalidate(start, (char *)end-(char *)start); #elif LJ_TARGET_PPC lj_vm_cachesync(start, end); #elif defined(__GNUC__) __clear_cache(start, end); #else #error "Missing builtin to flush instruction cache" #endif } #endif #if LJ_HASJIT #if LJ_TARGET_WINDOWS #define WIN32_LEAN_AND_MEAN #include <windows.h> #define MCPROT_RW PAGE_READWRITE #define MCPROT_RX PAGE_EXECUTE_READ #define MCPROT_RWX PAGE_EXECUTE_READWRITE static void *mcode_alloc_at(jit_State *J, uintptr_t hint, size_t sz, DWORD prot) { void *p = VirtualAlloc((void *)hint, sz, MEM_RESERVE|MEM_COMMIT|MEM_TOP_DOWN, prot); if (!p && !hint) lj_trace_err(J, LJ_TRERR_MCODEAL); return p; } static void mcode_free(jit_State *J, void *p, size_t sz) { UNUSED(J); UNUSED(sz); VirtualFree(p, 0, MEM_RELEASE); } static int mcode_setprot(void *p, size_t sz, DWORD prot) { DWORD oprot; return !VirtualProtect(p, sz, prot, &oprot); } #elif LJ_TARGET_POSIX #include <sys/mman.h> #ifndef MAP_ANONYMOUS #define MAP_ANONYMOUS MAP_ANON #endif #define MCPROT_RW (PROT_READ|PROT_WRITE) #define MCPROT_RX (PROT_READ|PROT_EXEC) #define MCPROT_RWX (PROT_READ|PROT_WRITE|PROT_EXEC) static void *mcode_alloc_at(jit_State *J, uintptr_t hint, size_t sz, int prot) { void *p = mmap((void *)hint, sz, prot, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0); if (p == MAP_FAILED) { if (!hint) lj_trace_err(J, LJ_TRERR_MCODEAL); p = NULL; } return p; } static void mcode_free(jit_State *J, void *p, size_t sz) { UNUSED(J); munmap(p, sz); } static int mcode_setprot(void *p, size_t sz, int prot) { return mprotect(p, sz, prot); } #elif LJ_64 #error "Missing OS support for explicit placement of executable memory" #else /* Fallback allocator. This will fail if memory is not executable by default. */ #define LUAJIT_UNPROTECT_MCODE #define MCPROT_RW 0 #define MCPROT_RX 0 #define MCPROT_RWX 0 static void *mcode_alloc_at(jit_State *J, uintptr_t hint, size_t sz, int prot) { UNUSED(hint); UNUSED(prot); return lj_mem_new(J->L, sz); } static void mcode_free(jit_State *J, void *p, size_t sz) { lj_mem_free(J2G(J), p, sz); } #endif /* -- MCode area protection ----------------------------------------------- */ /* Define this ONLY if page protection twiddling becomes a bottleneck. */ #ifdef LUAJIT_UNPROTECT_MCODE /* It's generally considered to be a potential security risk to have ** pages with simultaneous write *and* execute access in a process. ** ** Do not even think about using this mode for server processes or ** apps handling untrusted external data (such as a browser). ** ** The security risk is not in LuaJIT itself -- but if an adversary finds ** any *other* flaw in your C application logic, then any RWX memory page ** simplifies writing an exploit considerably. */ #define MCPROT_GEN MCPROT_RWX #define MCPROT_RUN MCPROT_RWX static void mcode_protect(jit_State *J, int prot) { UNUSED(J); UNUSED(prot); } #else /* This is the default behaviour and much safer: ** ** Most of the time the memory pages holding machine code are executable, ** but NONE of them is writable. ** ** The current memory area is marked read-write (but NOT executable) only ** during the short time window while the assembler generates machine code. */ #define MCPROT_GEN MCPROT_RW #define MCPROT_RUN MCPROT_RX /* Protection twiddling failed. Probably due to kernel security. */ static LJ_NOINLINE void mcode_protfail(jit_State *J) { lua_CFunction panic = J2G(J)->panic; if (panic) { lua_State *L = J->L; setstrV(L, L->top++, lj_err_str(L, LJ_ERR_JITPROT)); panic(L); } } /* Change protection of MCode area. */ static void mcode_protect(jit_State *J, int prot) { if (J->mcprot != prot) { if (LJ_UNLIKELY(mcode_setprot(J->mcarea, J->szmcarea, prot))) mcode_protfail(J); J->mcprot = prot; } } #endif /* -- MCode area allocation ----------------------------------------------- */ #if LJ_TARGET_X64 #define mcode_validptr(p) ((p) && (uintptr_t)(p) < (uintptr_t)1<<47) #else #define mcode_validptr(p) ((p) && (uintptr_t)(p) < 0xffff0000) #endif #ifdef LJ_TARGET_JUMPRANGE /* Get memory within relative jump distance of our code in 64 bit mode. */ static void *mcode_alloc(jit_State *J, size_t sz) { /* Target an address in the static assembler code (64K aligned). ** Try addresses within a distance of target-range/2+1MB..target+range/2-1MB. ** Use half the jump range so every address in the range can reach any other. */ #if LJ_TARGET_MIPS /* Use the middle of the 256MB-aligned region. */ uintptr_t target = ((uintptr_t)(void *)lj_vm_exit_handler & 0xf0000000u) + 0x08000000u; #else uintptr_t target = (uintptr_t)(void *)lj_vm_exit_handler & ~(uintptr_t)0xffff; #endif const uintptr_t range = (1u << (LJ_TARGET_JUMPRANGE-1)) - (1u << 21); /* First try a contiguous area below the last one. */ uintptr_t hint = J->mcarea ? (uintptr_t)J->mcarea - sz : 0; int i; for (i = 0; i < 32; i++) { /* 32 attempts ought to be enough ... */ if (mcode_validptr(hint)) { void *p = mcode_alloc_at(J, hint, sz, MCPROT_GEN); if (mcode_validptr(p) && ((uintptr_t)p + sz - target < range || target - (uintptr_t)p < range)) return p; if (p) mcode_free(J, p, sz); /* Free badly placed area. */ } /* Next try probing pseudo-random addresses. */ do { hint = (0x78fb ^ LJ_PRNG_BITS(J, 15)) << 16; /* 64K aligned. */ } while (!(hint + sz < range)); hint = target + hint - (range>>1); } lj_trace_err(J, LJ_TRERR_MCODEAL); /* Give up. OS probably ignores hints? */ return NULL; } #else /* All memory addresses are reachable by relative jumps. */ static void *mcode_alloc(jit_State *J, size_t sz) { #ifdef __OpenBSD__ /* Allow better executable memory allocation for OpenBSD W^X mode. */ void *p = mcode_alloc_at(J, 0, sz, MCPROT_RUN); if (p && mcode_setprot(p, sz, MCPROT_GEN)) { mcode_free(J, p, sz); return NULL; } return p; #else return mcode_alloc_at(J, 0, sz, MCPROT_GEN); #endif } #endif /* -- MCode area management ----------------------------------------------- */ /* Linked list of MCode areas. */ typedef struct MCLink { MCode *next; /* Next area. */ size_t size; /* Size of current area. */ } MCLink; /* Allocate a new MCode area. */ static void mcode_allocarea(jit_State *J) { MCode *oldarea = J->mcarea; size_t sz = (size_t)J->param[JIT_P_sizemcode] << 10; sz = (sz + LJ_PAGESIZE-1) & ~(size_t)(LJ_PAGESIZE - 1); J->mcarea = (MCode *)mcode_alloc(J, sz); J->szmcarea = sz; J->mcprot = MCPROT_GEN; J->mctop = (MCode *)((char *)J->mcarea + J->szmcarea); J->mcbot = (MCode *)((char *)J->mcarea + sizeof(MCLink)); ((MCLink *)J->mcarea)->next = oldarea; ((MCLink *)J->mcarea)->size = sz; J->szallmcarea += sz; } /* Free all MCode areas. */ void lj_mcode_free(jit_State *J) { MCode *mc = J->mcarea; J->mcarea = NULL; J->szallmcarea = 0; while (mc) { MCode *next = ((MCLink *)mc)->next; mcode_free(J, mc, ((MCLink *)mc)->size); mc = next; } } /* -- MCode transactions -------------------------------------------------- */ /* Reserve the remainder of the current MCode area. */ MCode *lj_mcode_reserve(jit_State *J, MCode **lim) { if (!J->mcarea) mcode_allocarea(J); else mcode_protect(J, MCPROT_GEN); *lim = J->mcbot; return J->mctop; } /* Commit the top part of the current MCode area. */ void lj_mcode_commit(jit_State *J, MCode *top) { J->mctop = top; mcode_protect(J, MCPROT_RUN); } /* Abort the reservation. */ void lj_mcode_abort(jit_State *J) { if (J->mcarea) mcode_protect(J, MCPROT_RUN); } /* Set/reset protection to allow patching of MCode areas. */ MCode *lj_mcode_patch(jit_State *J, MCode *ptr, int finish) { #ifdef LUAJIT_UNPROTECT_MCODE UNUSED(J); UNUSED(ptr); UNUSED(finish); return NULL; #else if (finish) { if (J->mcarea == ptr) mcode_protect(J, MCPROT_RUN); else if (LJ_UNLIKELY(mcode_setprot(ptr, ((MCLink *)ptr)->size, MCPROT_RUN))) mcode_protfail(J); return NULL; } else { MCode *mc = J->mcarea; /* Try current area first to use the protection cache. */ if (ptr >= mc && ptr < (MCode *)((char *)mc + J->szmcarea)) { mcode_protect(J, MCPROT_GEN); return mc; } /* Otherwise search through the list of MCode areas. */ for (;;) { mc = ((MCLink *)mc)->next; lua_assert(mc != NULL); if (ptr >= mc && ptr < (MCode *)((char *)mc + ((MCLink *)mc)->size)) { if (LJ_UNLIKELY(mcode_setprot(mc, ((MCLink *)mc)->size, MCPROT_GEN))) mcode_protfail(J); return mc; } } } #endif } /* Limit of MCode reservation reached. */ void lj_mcode_limiterr(jit_State *J, size_t need) { size_t sizemcode, maxmcode; lj_mcode_abort(J); sizemcode = (size_t)J->param[JIT_P_sizemcode] << 10; sizemcode = (sizemcode + LJ_PAGESIZE-1) & ~(size_t)(LJ_PAGESIZE - 1); maxmcode = (size_t)J->param[JIT_P_maxmcode] << 10; if ((size_t)need > sizemcode) lj_trace_err(J, LJ_TRERR_MCODEOV); /* Too long for any area. */ if (J->szallmcarea + sizemcode > maxmcode) lj_trace_err(J, LJ_TRERR_MCODEAL); mcode_allocarea(J); lj_trace_err(J, LJ_TRERR_MCODELM); /* Retry with new area. */ } #endif
xLua/build/luajit-2.1.0b2/src/lj_mcode.c/0
{ "file_path": "xLua/build/luajit-2.1.0b2/src/lj_mcode.c", "repo_id": "xLua", "token_count": 4304 }
2,038
/* ** Low-overhead profiling. ** Copyright (C) 2005-2016 Mike Pall. See Copyright Notice in luajit.h */ #ifndef _LJ_PROFILE_H #define _LJ_PROFILE_H #include "lj_obj.h" #if LJ_HASPROFILE LJ_FUNC void LJ_FASTCALL lj_profile_interpreter(lua_State *L); #if !LJ_PROFILE_SIGPROF LJ_FUNC void LJ_FASTCALL lj_profile_hook_enter(global_State *g); LJ_FUNC void LJ_FASTCALL lj_profile_hook_leave(global_State *g); #endif #endif #endif
xLua/build/luajit-2.1.0b2/src/lj_profile.h/0
{ "file_path": "xLua/build/luajit-2.1.0b2/src/lj_profile.h", "repo_id": "xLua", "token_count": 195 }
2,039
/* ** Definitions for target CPU. ** Copyright (C) 2005-2016 Mike Pall. See Copyright Notice in luajit.h */ #ifndef _LJ_TARGET_H #define _LJ_TARGET_H #include "lj_def.h" #include "lj_arch.h" /* -- Registers and spill slots ------------------------------------------- */ /* Register type (uint8_t in ir->r). */ typedef uint32_t Reg; /* The hi-bit is NOT set for an allocated register. This means the value ** can be directly used without masking. The hi-bit is set for a register ** allocation hint or for RID_INIT, RID_SINK or RID_SUNK. */ #define RID_NONE 0x80 #define RID_MASK 0x7f #define RID_INIT (RID_NONE|RID_MASK) #define RID_SINK (RID_INIT-1) #define RID_SUNK (RID_INIT-2) #define ra_noreg(r) ((r) & RID_NONE) #define ra_hasreg(r) (!((r) & RID_NONE)) /* The ra_hashint() macro assumes a previous test for ra_noreg(). */ #define ra_hashint(r) ((r) < RID_SUNK) #define ra_gethint(r) ((Reg)((r) & RID_MASK)) #define ra_sethint(rr, r) rr = (uint8_t)((r)|RID_NONE) #define ra_samehint(r1, r2) (ra_gethint((r1)^(r2)) == 0) /* Spill slot 0 means no spill slot has been allocated. */ #define SPS_NONE 0 #define ra_hasspill(s) ((s) != SPS_NONE) /* Combined register and spill slot (uint16_t in ir->prev). */ typedef uint32_t RegSP; #define REGSP(r, s) ((r) + ((s) << 8)) #define REGSP_HINT(r) ((r)|RID_NONE) #define REGSP_INIT REGSP(RID_INIT, 0) #define regsp_reg(rs) ((rs) & 255) #define regsp_spill(rs) ((rs) >> 8) #define regsp_used(rs) \ (((rs) & ~REGSP(RID_MASK, 0)) != REGSP(RID_NONE, 0)) /* -- Register sets ------------------------------------------------------- */ /* Bitset for registers. 32 registers suffice for most architectures. ** Note that one set holds bits for both GPRs and FPRs. */ #if LJ_TARGET_PPC || LJ_TARGET_MIPS typedef uint64_t RegSet; #else typedef uint32_t RegSet; #endif #define RID2RSET(r) (((RegSet)1) << (r)) #define RSET_EMPTY ((RegSet)0) #define RSET_RANGE(lo, hi) ((RID2RSET((hi)-(lo))-1) << (lo)) #define rset_test(rs, r) ((int)((rs) >> (r)) & 1) #define rset_set(rs, r) (rs |= RID2RSET(r)) #define rset_clear(rs, r) (rs &= ~RID2RSET(r)) #define rset_exclude(rs, r) (rs & ~RID2RSET(r)) #if LJ_TARGET_PPC || LJ_TARGET_MIPS #define rset_picktop(rs) ((Reg)(__builtin_clzll(rs)^63)) #define rset_pickbot(rs) ((Reg)__builtin_ctzll(rs)) #else #define rset_picktop(rs) ((Reg)lj_fls(rs)) #define rset_pickbot(rs) ((Reg)lj_ffs(rs)) #endif /* -- Register allocation cost -------------------------------------------- */ /* The register allocation heuristic keeps track of the cost for allocating ** a specific register: ** ** A free register (obviously) has a cost of 0 and a 1-bit in the free mask. ** ** An already allocated register has the (non-zero) IR reference in the lowest ** bits and the result of a blended cost-model in the higher bits. ** ** The allocator first checks the free mask for a hit. Otherwise an (unrolled) ** linear search for the minimum cost is used. The search doesn't need to ** keep track of the position of the minimum, which makes it very fast. ** The lowest bits of the minimum cost show the desired IR reference whose ** register is the one to evict. ** ** Without the cost-model this degenerates to the standard heuristics for ** (reverse) linear-scan register allocation. Since code generation is done ** in reverse, a live interval extends from the last use to the first def. ** For an SSA IR the IR reference is the first (and only) def and thus ** trivially marks the end of the interval. The LSRA heuristics says to pick ** the register whose live interval has the furthest extent, i.e. the lowest ** IR reference in our case. ** ** A cost-model should take into account other factors, like spill-cost and ** restore- or rematerialization-cost, which depend on the kind of instruction. ** E.g. constants have zero spill costs, variant instructions have higher ** costs than invariants and PHIs should preferably never be spilled. ** ** Here's a first cut at simple, but effective blended cost-model for R-LSRA: ** - Due to careful design of the IR, constants already have lower IR ** references than invariants and invariants have lower IR references ** than variants. ** - The cost in the upper 16 bits is the sum of the IR reference and a ** weighted score. The score currently only takes into account whether ** the IRT_ISPHI bit is set in the instruction type. ** - The PHI weight is the minimum distance (in IR instructions) a PHI ** reference has to be further apart from a non-PHI reference to be spilled. ** - It should be a power of two (for speed) and must be between 2 and 32768. ** Good values for the PHI weight seem to be between 40 and 150. ** - Further study is required. */ #define REGCOST_PHI_WEIGHT 64 /* Cost for allocating a specific register. */ typedef uint32_t RegCost; /* Note: assumes 16 bit IRRef1. */ #define REGCOST(cost, ref) ((RegCost)(ref) + ((RegCost)(cost) << 16)) #define regcost_ref(rc) ((IRRef1)(rc)) #define REGCOST_T(t) \ ((RegCost)((t)&IRT_ISPHI) * (((RegCost)(REGCOST_PHI_WEIGHT)<<16)/IRT_ISPHI)) #define REGCOST_REF_T(ref, t) (REGCOST((ref), (ref)) + REGCOST_T((t))) /* -- Target-specific definitions ----------------------------------------- */ #if LJ_TARGET_X86ORX64 #include "lj_target_x86.h" #elif LJ_TARGET_ARM #include "lj_target_arm.h" #elif LJ_TARGET_ARM64 #include "lj_target_arm64.h" #elif LJ_TARGET_PPC #include "lj_target_ppc.h" #elif LJ_TARGET_MIPS #include "lj_target_mips.h" #else #error "Missing include for target CPU" #endif #ifdef EXITSTUBS_PER_GROUP /* Return the address of an exit stub. */ static LJ_AINLINE char *exitstub_addr_(char **group, uint32_t exitno) { lua_assert(group[exitno / EXITSTUBS_PER_GROUP] != NULL); return (char *)group[exitno / EXITSTUBS_PER_GROUP] + EXITSTUB_SPACING*(exitno % EXITSTUBS_PER_GROUP); } /* Avoid dependence on lj_jit.h if only including lj_target.h. */ #define exitstub_addr(J, exitno) \ ((MCode *)exitstub_addr_((char **)((J)->exitstubgroup), (exitno))) #endif #endif
xLua/build/luajit-2.1.0b2/src/lj_target.h/0
{ "file_path": "xLua/build/luajit-2.1.0b2/src/lj_target.h", "repo_id": "xLua", "token_count": 2194 }
2,040
/* ** $Id: lua.h,v 1.218.1.5 2008/08/06 13:30:12 roberto Exp $ ** Lua - An Extensible Extension Language ** Lua.org, PUC-Rio, Brazil (http://www.lua.org) ** See Copyright Notice at the end of this file */ #ifndef lua_h #define lua_h #include <stdarg.h> #include <stddef.h> #include "luaconf.h" #define LUA_VERSION "Lua 5.1" #define LUA_RELEASE "Lua 5.1.4" #define LUA_VERSION_NUM 501 #define LUA_COPYRIGHT "Copyright (C) 1994-2008 Lua.org, PUC-Rio" #define LUA_AUTHORS "R. Ierusalimschy, L. H. de Figueiredo & W. Celes" /* mark for precompiled code (`<esc>Lua') */ #define LUA_SIGNATURE "\033Lua" /* option for multiple returns in `lua_pcall' and `lua_call' */ #define LUA_MULTRET (-1) /* ** pseudo-indices */ #define LUA_REGISTRYINDEX (-10000) #define LUA_ENVIRONINDEX (-10001) #define LUA_GLOBALSINDEX (-10002) #define lua_upvalueindex(i) (LUA_GLOBALSINDEX-(i)) /* thread status; 0 is OK */ #define LUA_YIELD 1 #define LUA_ERRRUN 2 #define LUA_ERRSYNTAX 3 #define LUA_ERRMEM 4 #define LUA_ERRERR 5 typedef struct lua_State lua_State; typedef int (*lua_CFunction) (lua_State *L); /* ** functions that read/write blocks when loading/dumping Lua chunks */ typedef const char * (*lua_Reader) (lua_State *L, void *ud, size_t *sz); typedef int (*lua_Writer) (lua_State *L, const void* p, size_t sz, void* ud); /* ** prototype for memory-allocation functions */ typedef void * (*lua_Alloc) (void *ud, void *ptr, size_t osize, size_t nsize); /* ** basic types */ #define LUA_TNONE (-1) #define LUA_TNIL 0 #define LUA_TBOOLEAN 1 #define LUA_TLIGHTUSERDATA 2 #define LUA_TNUMBER 3 #define LUA_TSTRING 4 #define LUA_TTABLE 5 #define LUA_TFUNCTION 6 #define LUA_TUSERDATA 7 #define LUA_TTHREAD 8 /* minimum Lua stack available to a C function */ #define LUA_MINSTACK 20 /* ** generic extra include file */ #if defined(LUA_USER_H) #include LUA_USER_H #endif /* type of numbers in Lua */ typedef LUA_NUMBER lua_Number; /* type for integer functions */ typedef LUA_INTEGER lua_Integer; /* ** state manipulation */ LUA_API lua_State *(lua_newstate) (lua_Alloc f, void *ud); LUA_API void (lua_close) (lua_State *L); LUA_API lua_State *(lua_newthread) (lua_State *L); LUA_API lua_CFunction (lua_atpanic) (lua_State *L, lua_CFunction panicf); /* ** basic stack manipulation */ LUA_API int (lua_gettop) (lua_State *L); LUA_API void (lua_settop) (lua_State *L, int idx); LUA_API void (lua_pushvalue) (lua_State *L, int idx); LUA_API void (lua_remove) (lua_State *L, int idx); LUA_API void (lua_insert) (lua_State *L, int idx); LUA_API void (lua_replace) (lua_State *L, int idx); LUA_API int (lua_checkstack) (lua_State *L, int sz); LUA_API void (lua_xmove) (lua_State *from, lua_State *to, int n); /* ** access functions (stack -> C) */ LUA_API int (lua_isnumber) (lua_State *L, int idx); LUA_API int (lua_isstring) (lua_State *L, int idx); LUA_API int (lua_iscfunction) (lua_State *L, int idx); LUA_API int (lua_isuserdata) (lua_State *L, int idx); LUA_API int (lua_type) (lua_State *L, int idx); LUA_API const char *(lua_typename) (lua_State *L, int tp); LUA_API int (lua_equal) (lua_State *L, int idx1, int idx2); LUA_API int (lua_rawequal) (lua_State *L, int idx1, int idx2); LUA_API int (lua_lessthan) (lua_State *L, int idx1, int idx2); LUA_API lua_Number (lua_tonumber) (lua_State *L, int idx); LUA_API lua_Integer (lua_tointeger) (lua_State *L, int idx); LUA_API int (lua_toboolean) (lua_State *L, int idx); LUA_API const char *(lua_tolstring) (lua_State *L, int idx, size_t *len); LUA_API size_t (lua_objlen) (lua_State *L, int idx); LUA_API lua_CFunction (lua_tocfunction) (lua_State *L, int idx); LUA_API void *(lua_touserdata) (lua_State *L, int idx); LUA_API lua_State *(lua_tothread) (lua_State *L, int idx); LUA_API const void *(lua_topointer) (lua_State *L, int idx); /* ** push functions (C -> stack) */ LUA_API void (lua_pushnil) (lua_State *L); LUA_API void (lua_pushnumber) (lua_State *L, lua_Number n); LUA_API void (lua_pushinteger) (lua_State *L, lua_Integer n); LUA_API void (lua_pushlstring) (lua_State *L, const char *s, size_t l); LUA_API void (lua_pushstring) (lua_State *L, const char *s); LUA_API const char *(lua_pushvfstring) (lua_State *L, const char *fmt, va_list argp); LUA_API const char *(lua_pushfstring) (lua_State *L, const char *fmt, ...); LUA_API void (lua_pushcclosure) (lua_State *L, lua_CFunction fn, int n); LUA_API void (lua_pushboolean) (lua_State *L, int b); LUA_API void (lua_pushlightuserdata) (lua_State *L, void *p); LUA_API int (lua_pushthread) (lua_State *L); /* ** get functions (Lua -> stack) */ LUA_API void (lua_gettable) (lua_State *L, int idx); LUA_API void (lua_getfield) (lua_State *L, int idx, const char *k); LUA_API void (lua_rawget) (lua_State *L, int idx); LUA_API void (lua_rawgeti) (lua_State *L, int idx, int n); LUA_API void (lua_createtable) (lua_State *L, int narr, int nrec); LUA_API void *(lua_newuserdata) (lua_State *L, size_t sz); LUA_API int (lua_getmetatable) (lua_State *L, int objindex); LUA_API void (lua_getfenv) (lua_State *L, int idx); /* ** set functions (stack -> Lua) */ LUA_API void (lua_settable) (lua_State *L, int idx); LUA_API void (lua_setfield) (lua_State *L, int idx, const char *k); LUA_API void (lua_rawset) (lua_State *L, int idx); LUA_API void (lua_rawseti) (lua_State *L, int idx, int n); LUA_API int (lua_setmetatable) (lua_State *L, int objindex); LUA_API int (lua_setfenv) (lua_State *L, int idx); /* ** `load' and `call' functions (load and run Lua code) */ LUA_API void (lua_call) (lua_State *L, int nargs, int nresults); LUA_API int (lua_pcall) (lua_State *L, int nargs, int nresults, int errfunc); LUA_API int (lua_cpcall) (lua_State *L, lua_CFunction func, void *ud); LUA_API int (lua_load) (lua_State *L, lua_Reader reader, void *dt, const char *chunkname); LUA_API int (lua_dump) (lua_State *L, lua_Writer writer, void *data); /* ** coroutine functions */ LUA_API int (lua_yield) (lua_State *L, int nresults); LUA_API int (lua_resume) (lua_State *L, int narg); LUA_API int (lua_status) (lua_State *L); /* ** garbage-collection function and options */ #define LUA_GCSTOP 0 #define LUA_GCRESTART 1 #define LUA_GCCOLLECT 2 #define LUA_GCCOUNT 3 #define LUA_GCCOUNTB 4 #define LUA_GCSTEP 5 #define LUA_GCSETPAUSE 6 #define LUA_GCSETSTEPMUL 7 #define LUA_GCISRUNNING 9 LUA_API int (lua_gc) (lua_State *L, int what, int data); /* ** miscellaneous functions */ LUA_API int (lua_error) (lua_State *L); LUA_API int (lua_next) (lua_State *L, int idx); LUA_API void (lua_concat) (lua_State *L, int n); LUA_API lua_Alloc (lua_getallocf) (lua_State *L, void **ud); LUA_API void lua_setallocf (lua_State *L, lua_Alloc f, void *ud); /* ** =============================================================== ** some useful macros ** =============================================================== */ #define lua_pop(L,n) lua_settop(L, -(n)-1) #define lua_newtable(L) lua_createtable(L, 0, 0) #define lua_register(L,n,f) (lua_pushcfunction(L, (f)), lua_setglobal(L, (n))) #define lua_pushcfunction(L,f) lua_pushcclosure(L, (f), 0) #define lua_strlen(L,i) lua_objlen(L, (i)) #define lua_isfunction(L,n) (lua_type(L, (n)) == LUA_TFUNCTION) #define lua_istable(L,n) (lua_type(L, (n)) == LUA_TTABLE) #define lua_islightuserdata(L,n) (lua_type(L, (n)) == LUA_TLIGHTUSERDATA) #define lua_isnil(L,n) (lua_type(L, (n)) == LUA_TNIL) #define lua_isboolean(L,n) (lua_type(L, (n)) == LUA_TBOOLEAN) #define lua_isthread(L,n) (lua_type(L, (n)) == LUA_TTHREAD) #define lua_isnone(L,n) (lua_type(L, (n)) == LUA_TNONE) #define lua_isnoneornil(L, n) (lua_type(L, (n)) <= 0) #define lua_pushliteral(L, s) \ lua_pushlstring(L, "" s, (sizeof(s)/sizeof(char))-1) #define lua_setglobal(L,s) lua_setfield(L, LUA_GLOBALSINDEX, (s)) #define lua_getglobal(L,s) lua_getfield(L, LUA_GLOBALSINDEX, (s)) #define lua_tostring(L,i) lua_tolstring(L, (i), NULL) /* ** compatibility macros and functions */ #define lua_open() luaL_newstate() #define lua_getregistry(L) lua_pushvalue(L, LUA_REGISTRYINDEX) #define lua_getgccount(L) lua_gc(L, LUA_GCCOUNT, 0) #define lua_Chunkreader lua_Reader #define lua_Chunkwriter lua_Writer /* hack */ LUA_API void lua_setlevel (lua_State *from, lua_State *to); /* ** {====================================================================== ** Debug API ** ======================================================================= */ /* ** Event codes */ #define LUA_HOOKCALL 0 #define LUA_HOOKRET 1 #define LUA_HOOKLINE 2 #define LUA_HOOKCOUNT 3 #define LUA_HOOKTAILRET 4 /* ** Event masks */ #define LUA_MASKCALL (1 << LUA_HOOKCALL) #define LUA_MASKRET (1 << LUA_HOOKRET) #define LUA_MASKLINE (1 << LUA_HOOKLINE) #define LUA_MASKCOUNT (1 << LUA_HOOKCOUNT) typedef struct lua_Debug lua_Debug; /* activation record */ /* Functions to be called by the debuger in specific events */ typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar); LUA_API int lua_getstack (lua_State *L, int level, lua_Debug *ar); LUA_API int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar); LUA_API const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n); LUA_API const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n); LUA_API const char *lua_getupvalue (lua_State *L, int funcindex, int n); LUA_API const char *lua_setupvalue (lua_State *L, int funcindex, int n); LUA_API int lua_sethook (lua_State *L, lua_Hook func, int mask, int count); LUA_API lua_Hook lua_gethook (lua_State *L); LUA_API int lua_gethookmask (lua_State *L); LUA_API int lua_gethookcount (lua_State *L); /* From Lua 5.2. */ LUA_API void *lua_upvalueid (lua_State *L, int idx, int n); LUA_API void lua_upvaluejoin (lua_State *L, int idx1, int n1, int idx2, int n2); LUA_API int lua_loadx (lua_State *L, lua_Reader reader, void *dt, const char *chunkname, const char *mode); struct lua_Debug { int event; const char *name; /* (n) */ const char *namewhat; /* (n) `global', `local', `field', `method' */ const char *what; /* (S) `Lua', `C', `main', `tail' */ const char *source; /* (S) */ int currentline; /* (l) */ int nups; /* (u) number of upvalues */ int linedefined; /* (S) */ int lastlinedefined; /* (S) */ char short_src[LUA_IDSIZE]; /* (S) */ /* private part */ int i_ci; /* active function */ }; /* }====================================================================== */ /****************************************************************************** * Copyright (C) 1994-2008 Lua.org, PUC-Rio. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ******************************************************************************/ #endif
xLua/build/luajit-2.1.0b2/src/lua.h/0
{ "file_path": "xLua/build/luajit-2.1.0b2/src/lua.h", "repo_id": "xLua", "token_count": 5001 }
2,041
<!DOCTYPE html> <html> <head> <title>FFI Tutorial</title> <meta charset="utf-8"> <meta name="Copyright" content="Copyright (C) 2005-2021"> <meta name="Language" content="en"> <link rel="stylesheet" type="text/css" href="bluequad.css" media="screen"> <link rel="stylesheet" type="text/css" href="bluequad-print.css" media="print"> <style type="text/css"> table.idiomtable { font-size: 90%; line-height: 1.2; } table.idiomtable tt { font-size: 100%; } table.idiomtable td { vertical-align: top; } tr.idiomhead td { font-weight: bold; } td.idiomlua b { font-weight: normal; color: #2142bf; } </style> </head> <body> <div id="site"> <a href="https://luajit.org"><span>Lua<span id="logo">JIT</span></span></a> </div> <div id="head"> <h1>FFI Tutorial</h1> </div> <div id="nav"> <ul><li> <a href="luajit.html">LuaJIT</a> <ul><li> <a href="https://luajit.org/download.html">Download <span class="ext">&raquo;</span></a> </li><li> <a href="install.html">Installation</a> </li><li> <a href="running.html">Running</a> </li></ul> </li><li> <a href="extensions.html">Extensions</a> <ul><li> <a href="ext_ffi.html">FFI Library</a> <ul><li> <a class="current" href="ext_ffi_tutorial.html">FFI Tutorial</a> </li><li> <a href="ext_ffi_api.html">ffi.* API</a> </li><li> <a href="ext_ffi_semantics.html">FFI Semantics</a> </li></ul> </li><li> <a href="ext_buffer.html">String Buffers</a> </li><li> <a href="ext_jit.html">jit.* Library</a> </li><li> <a href="ext_c_api.html">Lua/C API</a> </li><li> <a href="ext_profiler.html">Profiler</a> </li></ul> </li><li> <a href="status.html">Status</a> </li><li> <a href="faq.html">FAQ</a> </li><li> <a href="http://wiki.luajit.org/">Wiki <span class="ext">&raquo;</span></a> </li><li> <a href="https://luajit.org/list.html">Mailing List <span class="ext">&raquo;</span></a> </li></ul> </div> <div id="main"> <p> This page is intended to give you an overview of the features of the FFI library by presenting a few use cases and guidelines. </p> <p> This page makes no attempt to explain all of the FFI library, though. You'll want to have a look at the <a href="ext_ffi_api.html">ffi.* API function reference</a> and the <a href="ext_ffi_semantics.html">FFI semantics</a> to learn more. </p> <h2 id="load">Loading the FFI Library</h2> <p> The FFI library is built into LuaJIT by default, but it's not loaded and initialized by default. The suggested way to use the FFI library is to add the following to the start of every Lua file that needs one of its functions: </p> <pre class="code"> local ffi = require("ffi") </pre> <p> Please note this doesn't define an <tt>ffi</tt> variable in the table of globals &mdash; you really need to use the local variable. The <tt>require</tt> function ensures the library is only loaded once. </p> <p style="font-size: 8pt;"> Note: If you want to experiment with the FFI from the interactive prompt of the command line executable, omit the <tt>local</tt>, as it doesn't preserve local variables across lines. </p> <h2 id="sleep">Accessing Standard System Functions</h2> <p> The following code explains how to access standard system functions. We slowly print two lines of dots by sleeping for 10&nbsp;milliseconds after each dot: </p> <pre class="code mark"> <span class="codemark">&nbsp; &#9312; &#9313; &#9314; &#9315; &#9316; &#9317;</span>local ffi = require("ffi") ffi.cdef[[ <span style="color:#00a000;">void Sleep(int ms); int poll(struct pollfd *fds, unsigned long nfds, int timeout);</span> ]] local sleep if ffi.os == "Windows" then function sleep(s) ffi.C.Sleep(s*1000) end else function sleep(s) ffi.C.poll(nil, 0, s*1000) end end for i=1,160 do io.write("."); io.flush() sleep(0.01) end io.write("\n") </pre> <p> Here's the step-by-step explanation: </p> <p> <span class="mark">&#9312;</span> This defines the C&nbsp;library functions we're going to use. The part inside the double-brackets (in green) is just standard C&nbsp;syntax. You can usually get this info from the C&nbsp;header files or the documentation provided by each C&nbsp;library or C&nbsp;compiler. </p> <p> <span class="mark">&#9313;</span> The difficulty we're facing here, is that there are different standards to choose from. Windows has a simple <tt>Sleep()</tt> function. On other systems there are a variety of functions available to achieve sub-second sleeps, but with no clear consensus. Thankfully <tt>poll()</tt> can be used for this task, too, and it's present on most non-Windows systems. The check for <tt>ffi.os</tt> makes sure we use the Windows-specific function only on Windows systems. </p> <p> <span class="mark">&#9314;</span> Here we're wrapping the call to the C&nbsp;function in a Lua function. This isn't strictly necessary, but it's helpful to deal with system-specific issues only in one part of the code. The way we're wrapping it ensures the check for the OS is only done during initialization and not for every call. </p> <p> <span class="mark">&#9315;</span> A more subtle point is that we defined our <tt>sleep()</tt> function (for the sake of this example) as taking the number of seconds, but accepting fractional seconds. Multiplying this by 1000 gets us milliseconds, but that still leaves it a Lua number, which is a floating-point value. Alas, the <tt>Sleep()</tt> function only accepts an integer value. Luckily for us, the FFI library automatically performs the conversion when calling the function (truncating the FP value towards zero, like in C). </p> <p style="font-size: 8pt;"> Some readers will notice that <tt>Sleep()</tt> is part of <tt>KERNEL32.DLL</tt> and is also a <tt>stdcall</tt> function. So how can this possibly work? The FFI library provides the <tt>ffi.C</tt> default C&nbsp;library namespace, which allows calling functions from the default set of libraries, like a C&nbsp;compiler would. Also, the FFI library automatically detects <tt>stdcall</tt> functions, so you don't need to declare them as such. </p> <p> <span class="mark">&#9316;</span> The <tt>poll()</tt> function takes a couple more arguments we're not going to use. You can simply use <tt>nil</tt> to pass a <tt>NULL</tt> pointer and <tt>0</tt> for the <tt>nfds</tt> parameter. Please note that the number&nbsp;<tt>0</tt> <em>does not convert to a pointer value</em>, unlike in C++. You really have to pass pointers to pointer arguments and numbers to number arguments. </p> <p style="font-size: 8pt;"> The page on <a href="ext_ffi_semantics.html">FFI semantics</a> has all of the gory details about <a href="ext_ffi_semantics.html#convert">conversions between Lua objects and C&nbsp;types</a>. For the most part you don't have to deal with this, as it's performed automatically and it's carefully designed to bridge the semantic differences between Lua and C. </p> <p> <span class="mark">&#9317;</span> Now that we have defined our own <tt>sleep()</tt> function, we can just call it from plain Lua code. That wasn't so bad, huh? Turning these boring animated dots into a fascinating best-selling game is left as an exercise for the reader. :-) </p> <h2 id="zlib">Accessing the zlib Compression Library</h2> <p> The following code shows how to access the <a href="https://zlib.net/"><span class="ext">&raquo;</span>&nbsp;zlib</a> compression library from Lua code. We'll define two convenience wrapper functions that take a string and compress or uncompress it to another string: </p> <pre class="code mark"> <span class="codemark">&nbsp; &#9312; &#9313; &#9314; &#9315; &#9316; &#9317; &#9318;</span>local ffi = require("ffi") ffi.cdef[[ <span style="color:#00a000;">unsigned long compressBound(unsigned long sourceLen); int compress2(uint8_t *dest, unsigned long *destLen, const uint8_t *source, unsigned long sourceLen, int level); int uncompress(uint8_t *dest, unsigned long *destLen, const uint8_t *source, unsigned long sourceLen);</span> ]] local zlib = ffi.load(ffi.os == "Windows" and "zlib1" or "z") local function compress(txt) local n = zlib.compressBound(#txt) local buf = ffi.new("uint8_t[?]", n) local buflen = ffi.new("unsigned long[1]", n) local res = zlib.compress2(buf, buflen, txt, #txt, 9) assert(res == 0) return ffi.string(buf, buflen[0]) end local function uncompress(comp, n) local buf = ffi.new("uint8_t[?]", n) local buflen = ffi.new("unsigned long[1]", n) local res = zlib.uncompress(buf, buflen, comp, #comp) assert(res == 0) return ffi.string(buf, buflen[0]) end -- Simple test code. local txt = string.rep("abcd", 1000) print("Uncompressed size: ", #txt) local c = compress(txt) print("Compressed size: ", #c) local txt2 = uncompress(c, #txt) assert(txt2 == txt) </pre> <p> Here's the step-by-step explanation: </p> <p> <span class="mark">&#9312;</span> This defines some of the C&nbsp;functions provided by zlib. For the sake of this example, some type indirections have been reduced and it uses the pre-defined fixed-size integer types, while still adhering to the zlib API/ABI. </p> <p> <span class="mark">&#9313;</span> This loads the zlib shared library. On POSIX systems it's named <tt>libz.so</tt> and usually comes pre-installed. Since <tt>ffi.load()</tt> automatically adds any missing standard prefixes/suffixes, we can simply load the <tt>"z"</tt> library. On Windows it's named <tt>zlib1.dll</tt> and you'll have to download it first from the <a href="https://zlib.net/"><span class="ext">&raquo;</span>&nbsp;zlib site</a>. The check for <tt>ffi.os</tt> makes sure we pass the right name to <tt>ffi.load()</tt>. </p> <p> <span class="mark">&#9314;</span> First, the maximum size of the compression buffer is obtained by calling the <tt>zlib.compressBound</tt> function with the length of the uncompressed string. The next line allocates a byte buffer of this size. The <tt>[?]</tt> in the type specification indicates a variable-length array (VLA). The actual number of elements of this array is given as the 2nd argument to <tt>ffi.new()</tt>. </p> <p> <span class="mark">&#9315;</span> This may look strange at first, but have a look at the declaration of the <tt>compress2</tt> function from zlib: the destination length is defined as a pointer! This is because you pass in the maximum buffer size and get back the actual length that was used. </p> <p> In C you'd pass in the address of a local variable (<tt>&amp;buflen</tt>). But since there's no address-of operator in Lua, we'll just pass in a one-element array. Conveniently it can be initialized with the maximum buffer size in one step. Calling the actual <tt>zlib.compress2</tt> function is then straightforward. </p> <p> <span class="mark">&#9316;</span> We want to return the compressed data as a Lua string, so we'll use <tt>ffi.string()</tt>. It needs a pointer to the start of the data and the actual length. The length has been returned in the <tt>buflen</tt> array, so we'll just get it from there. </p> <p style="font-size: 8pt;"> Note that since the function returns now, the <tt>buf</tt> and <tt>buflen</tt> variables will eventually be garbage collected. This is fine, because <tt>ffi.string()</tt> has copied the contents to a newly created (interned) Lua string. If you plan to call this function lots of times, consider reusing the buffers and/or handing back the results in buffers instead of strings. This will reduce the overhead for garbage collection and string interning. </p> <p> <span class="mark">&#9317;</span> The <tt>uncompress</tt> functions does the exact opposite of the <tt>compress</tt> function. The compressed data doesn't include the size of the original string, so this needs to be passed in. Otherwise no surprises here. </p> <p> <span class="mark">&#9318;</span> The code, that makes use of the functions we just defined, is just plain Lua code. It doesn't need to know anything about the LuaJIT FFI &mdash; the convenience wrapper functions completely hide it. </p> <p> One major advantage of the LuaJIT FFI is that you are now able to write those wrappers <em>in Lua</em>. And at a fraction of the time it would cost you to create an extra C&nbsp;module using the Lua/C API. Many of the simpler C&nbsp;functions can probably be used directly from your Lua code, without any wrappers. </p> <p style="font-size: 8pt;"> Side note: the zlib API uses the <tt>long</tt> type for passing lengths and sizes around. But all those zlib functions actually only deal with 32&nbsp;bit values. This is an unfortunate choice for a public API, but may be explained by zlib's history &mdash; we'll just have to deal with it. </p> <p style="font-size: 8pt;"> First, you should know that a <tt>long</tt> is a 64&nbsp;bit type e.g. on POSIX/x64 systems, but a 32&nbsp;bit type on Windows/x64 and on 32&nbsp;bit systems. Thus a <tt>long</tt> result can be either a plain Lua number or a boxed 64&nbsp;bit integer cdata object, depending on the target system. </p> <p style="font-size: 8pt;"> Ok, so the <tt>ffi.*</tt> functions generally accept cdata objects wherever you'd want to use a number. That's why we get a away with passing <tt>n</tt> to <tt>ffi.string()</tt> above. But other Lua library functions or modules don't know how to deal with this. So for maximum portability one needs to use <tt>tonumber()</tt> on returned <tt>long</tt> results before passing them on. Otherwise the application might work on some systems, but would fail in a POSIX/x64 environment. </p> <h2 id="metatype">Defining Metamethods for a C&nbsp;Type</h2> <p> The following code explains how to define metamethods for a C type. We define a simple point type and add some operations to it: </p> <pre class="code mark"> <span class="codemark">&nbsp; &#9312; &#9313; &#9314; &#9315; &#9316; &#9317;</span>local ffi = require("ffi") ffi.cdef[[ <span style="color:#00a000;">typedef struct { double x, y; } point_t;</span> ]] local point local mt = { __add = function(a, b) return point(a.x+b.x, a.y+b.y) end, __len = function(a) return math.sqrt(a.x*a.x + a.y*a.y) end, __index = { area = function(a) return a.x*a.x + a.y*a.y end, }, } point = ffi.metatype("point_t", mt) local a = point(3, 4) print(a.x, a.y) --> 3 4 print(#a) --> 5 print(a:area()) --> 25 local b = a + point(0.5, 8) print(#b) --> 12.5 </pre> <p> Here's the step-by-step explanation: </p> <p> <span class="mark">&#9312;</span> This defines the C&nbsp;type for a two-dimensional point object. </p> <p> <span class="mark">&#9313;</span> We have to declare the variable holding the point constructor first, because it's used inside of a metamethod. </p> <p> <span class="mark">&#9314;</span> Let's define an <tt>__add</tt> metamethod which adds the coordinates of two points and creates a new point object. For simplicity, this function assumes that both arguments are points. But it could be any mix of objects, if at least one operand is of the required type (e.g. adding a point plus a number or vice versa). Our <tt>__len</tt> metamethod returns the distance of a point to the origin. </p> <p> <span class="mark">&#9315;</span> If we run out of operators, we can define named methods, too. Here the <tt>__index</tt> table defines an <tt>area</tt> function. For custom indexing needs, one might want to define <tt>__index</tt> and <tt>__newindex</tt> <em>functions</em> instead. </p> <p> <span class="mark">&#9316;</span> This associates the metamethods with our C&nbsp;type. This only needs to be done once. For convenience, a constructor is returned by <a href="ext_ffi_api.html#ffi_metatype"><tt>ffi.metatype()</tt></a>. We're not required to use it, though. The original C&nbsp;type can still be used e.g. to create an array of points. The metamethods automatically apply to any and all uses of this type. </p> <p> Please note that the association with a metatable is permanent and <b>the metatable must not be modified afterwards!</b> Ditto for the <tt>__index</tt> table. </p> <p> <span class="mark">&#9317;</span> Here are some simple usage examples for the point type and their expected results. The pre-defined operations (such as <tt>a.x</tt>) can be freely mixed with the newly defined metamethods. Note that <tt>area</tt> is a method and must be called with the Lua syntax for methods: <tt>a:area()</tt>, not <tt>a.area()</tt>. </p> <p> The C&nbsp;type metamethod mechanism is most useful when used in conjunction with C&nbsp;libraries that are written in an object-oriented style. Creators return a pointer to a new instance and methods take an instance pointer as the first argument. Sometimes you can just point <tt>__index</tt> to the library namespace and <tt>__gc</tt> to the destructor and you're done. But often enough you'll want to add convenience wrappers, e.g. to return actual Lua strings or when returning multiple values. </p> <p> Some C libraries only declare instance pointers as an opaque <tt>void&nbsp;*</tt> type. In this case you can use a fake type for all declarations, e.g. a pointer to a named (incomplete) struct will do: <tt>typedef struct foo_type *foo_handle</tt>. The C&nbsp;side doesn't know what you declare with the LuaJIT FFI, but as long as the underlying types are compatible, everything still works. </p> <h2 id="idioms">Translating C&nbsp;Idioms</h2> <p> Here's a list of common C&nbsp;idioms and their translation to the LuaJIT FFI: </p> <table class="idiomtable"> <tr class="idiomhead"> <td class="idiomdesc">Idiom</td> <td class="idiomc">C&nbsp;code</td> <td class="idiomlua">Lua code</td> </tr> <tr class="odd separate"> <td class="idiomdesc">Pointer dereference<br><tt>int *p;</tt></td><td class="idiomc"><tt>x = *p;<br>*p = y;</tt></td><td class="idiomlua"><tt>x = <b>p[0]</b><br><b>p[0]</b> = y</tt></td></tr> <tr class="even"> <td class="idiomdesc">Pointer indexing<br><tt>int i, *p;</tt></td><td class="idiomc"><tt>x = p[i];<br>p[i+1] = y;</tt></td><td class="idiomlua"><tt>x = p[i]<br>p[i+1] = y</tt></td></tr> <tr class="odd"> <td class="idiomdesc">Array indexing<br><tt>int i, a[];</tt></td><td class="idiomc"><tt>x = a[i];<br>a[i+1] = y;</tt></td><td class="idiomlua"><tt>x = a[i]<br>a[i+1] = y</tt></td></tr> <tr class="even separate"> <td class="idiomdesc"><tt>struct</tt>/<tt>union</tt> dereference<br><tt>struct foo s;</tt></td><td class="idiomc"><tt>x = s.field;<br>s.field = y;</tt></td><td class="idiomlua"><tt>x = s.field<br>s.field = y</tt></td></tr> <tr class="odd"> <td class="idiomdesc"><tt>struct</tt>/<tt>union</tt> pointer deref.<br><tt>struct foo *sp;</tt></td><td class="idiomc"><tt>x = sp->field;<br>sp->field = y;</tt></td><td class="idiomlua"><tt>x = <b>s.field</b><br><b>s.field</b> = y</tt></td></tr> <tr class="even separate"> <td class="idiomdesc">Pointer arithmetic<br><tt>int i, *p;</tt></td><td class="idiomc"><tt>x = p + i;<br>y = p - i;</tt></td><td class="idiomlua"><tt>x = p + i<br>y = p - i</tt></td></tr> <tr class="odd"> <td class="idiomdesc">Pointer difference<br><tt>int *p1, *p2;</tt></td><td class="idiomc"><tt>x = p1 - p2;</tt></td><td class="idiomlua"><tt>x = p1 - p2</tt></td></tr> <tr class="even"> <td class="idiomdesc">Array element pointer<br><tt>int i, a[];</tt></td><td class="idiomc"><tt>x = &amp;a[i];</tt></td><td class="idiomlua"><tt>x = <b>a+i</b></tt></td></tr> <tr class="odd"> <td class="idiomdesc">Cast pointer to address<br><tt>int *p;</tt></td><td class="idiomc"><tt>x = (intptr_t)p;</tt></td><td class="idiomlua"><tt>x = <b>tonumber(<br>&nbsp;ffi.cast("intptr_t",<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;p))</b></tt></td></tr> <tr class="even separate"> <td class="idiomdesc">Functions with outargs<br><tt>void foo(int *inoutlen);</tt></td><td class="idiomc"><tt>int len = x;<br>foo(&amp;len);<br>y = len;</tt></td><td class="idiomlua"><tt><b>local len =<br>&nbsp;&nbsp;ffi.new("int[1]", x)<br>foo(len)<br>y = len[0]</b></tt></td></tr> <tr class="odd"> <td class="idiomdesc"><a href="ext_ffi_semantics.html#convert_vararg">Vararg conversions</a><br><tt>int printf(char *fmt, ...);</tt></td><td class="idiomc"><tt>printf("%g", 1.0);<br>printf("%d", 1);<br>&nbsp;</tt></td><td class="idiomlua"><tt>printf("%g", 1);<br>printf("%d",<br>&nbsp;&nbsp;<b>ffi.new("int", 1)</b>)</tt></td></tr> </table> <h2 id="cache">To Cache or Not to Cache</h2> <p> It's a common Lua idiom to cache library functions in local variables or upvalues, e.g.: </p> <pre class="code"> local byte, char = string.byte, string.char local function foo(x) return char(byte(x)+1) end </pre> <p> This replaces several hash-table lookups with a (faster) direct use of a local or an upvalue. This is less important with LuaJIT, since the JIT compiler optimizes hash-table lookups a lot and is even able to hoist most of them out of the inner loops. It can't eliminate <em>all</em> of them, though, and it saves some typing for often-used functions. So there's still a place for this, even with LuaJIT. </p> <p> The situation is a bit different with C&nbsp;function calls via the FFI library. The JIT compiler has special logic to eliminate <em>all of the lookup overhead</em> for functions resolved from a <a href="ext_ffi_semantics.html#clib">C&nbsp;library namespace</a>! Thus it's not helpful and actually counter-productive to cache individual C&nbsp;functions like this: </p> <pre class="code"> local <b>funca</b>, <b>funcb</b> = ffi.C.funca, ffi.C.funcb -- <span style="color:#c00000;">Not helpful!</span> local function foo(x, n) for i=1,n do <b>funcb</b>(<b>funca</b>(x, i), 1) end end </pre> <p> This turns them into indirect calls and generates bigger and slower machine code. Instead you'll want to cache the namespace itself and rely on the JIT compiler to eliminate the lookups: </p> <pre class="code"> local <b>C</b> = ffi.C -- <span style="color:#00a000;">Instead use this!</span> local function foo(x, n) for i=1,n do <b>C.funcb</b>(<b>C.funca</b>(x, i), 1) end end </pre> <p> This generates both shorter and faster code. So <b>don't cache C&nbsp;functions</b>, but <b>do</b> cache namespaces! Most often the namespace is already in a local variable at an outer scope, e.g. from <tt>local&nbsp;lib&nbsp;=&nbsp;ffi.load(...)</tt>. Note that copying it to a local variable in the function scope is unnecessary. </p> <br class="flush"> </div> <div id="foot"> <hr class="hide"> Copyright &copy; 2005-2021 <span class="noprint"> &middot; <a href="contact.html">Contact</a> </span> </div> </body> </html>
xLua/build/luajit-2.1.0b3/doc/ext_ffi_tutorial.html/0
{ "file_path": "xLua/build/luajit-2.1.0b3/doc/ext_ffi_tutorial.html", "repo_id": "xLua", "token_count": 7954 }
2,042
/* ** DynASM MIPS encoding engine. ** Copyright (C) 2005-2021 Mike Pall. All rights reserved. ** Released under the MIT license. See dynasm.lua for full copyright notice. */ #include <stddef.h> #include <stdarg.h> #include <string.h> #include <stdlib.h> #define DASM_ARCH "mips" #ifndef DASM_EXTERN #define DASM_EXTERN(a,b,c,d) 0 #endif /* Action definitions. */ enum { DASM_STOP, DASM_SECTION, DASM_ESC, DASM_REL_EXT, /* The following actions need a buffer position. */ DASM_ALIGN, DASM_REL_LG, DASM_LABEL_LG, /* The following actions also have an argument. */ DASM_REL_PC, DASM_LABEL_PC, DASM_IMM, DASM_IMMS, DASM__MAX }; /* Maximum number of section buffer positions for a single dasm_put() call. */ #define DASM_MAXSECPOS 25 /* DynASM encoder status codes. Action list offset or number are or'ed in. */ #define DASM_S_OK 0x00000000 #define DASM_S_NOMEM 0x01000000 #define DASM_S_PHASE 0x02000000 #define DASM_S_MATCH_SEC 0x03000000 #define DASM_S_RANGE_I 0x11000000 #define DASM_S_RANGE_SEC 0x12000000 #define DASM_S_RANGE_LG 0x13000000 #define DASM_S_RANGE_PC 0x14000000 #define DASM_S_RANGE_REL 0x15000000 #define DASM_S_UNDEF_LG 0x21000000 #define DASM_S_UNDEF_PC 0x22000000 /* Macros to convert positions (8 bit section + 24 bit index). */ #define DASM_POS2IDX(pos) ((pos)&0x00ffffff) #define DASM_POS2BIAS(pos) ((pos)&0xff000000) #define DASM_SEC2POS(sec) ((sec)<<24) #define DASM_POS2SEC(pos) ((pos)>>24) #define DASM_POS2PTR(D, pos) (D->sections[DASM_POS2SEC(pos)].rbuf + (pos)) /* Action list type. */ typedef const unsigned int *dasm_ActList; /* Per-section structure. */ typedef struct dasm_Section { int *rbuf; /* Biased buffer pointer (negative section bias). */ int *buf; /* True buffer pointer. */ size_t bsize; /* Buffer size in bytes. */ int pos; /* Biased buffer position. */ int epos; /* End of biased buffer position - max single put. */ int ofs; /* Byte offset into section. */ } dasm_Section; /* Core structure holding the DynASM encoding state. */ struct dasm_State { size_t psize; /* Allocated size of this structure. */ dasm_ActList actionlist; /* Current actionlist pointer. */ int *lglabels; /* Local/global chain/pos ptrs. */ size_t lgsize; int *pclabels; /* PC label chains/pos ptrs. */ size_t pcsize; void **globals; /* Array of globals (bias -10). */ dasm_Section *section; /* Pointer to active section. */ size_t codesize; /* Total size of all code sections. */ int maxsection; /* 0 <= sectionidx < maxsection. */ int status; /* Status code. */ dasm_Section sections[1]; /* All sections. Alloc-extended. */ }; /* The size of the core structure depends on the max. number of sections. */ #define DASM_PSZ(ms) (sizeof(dasm_State)+(ms-1)*sizeof(dasm_Section)) /* Initialize DynASM state. */ void dasm_init(Dst_DECL, int maxsection) { dasm_State *D; size_t psz = 0; int i; Dst_REF = NULL; DASM_M_GROW(Dst, struct dasm_State, Dst_REF, psz, DASM_PSZ(maxsection)); D = Dst_REF; D->psize = psz; D->lglabels = NULL; D->lgsize = 0; D->pclabels = NULL; D->pcsize = 0; D->globals = NULL; D->maxsection = maxsection; for (i = 0; i < maxsection; i++) { D->sections[i].buf = NULL; /* Need this for pass3. */ D->sections[i].rbuf = D->sections[i].buf - DASM_SEC2POS(i); D->sections[i].bsize = 0; D->sections[i].epos = 0; /* Wrong, but is recalculated after resize. */ } } /* Free DynASM state. */ void dasm_free(Dst_DECL) { dasm_State *D = Dst_REF; int i; for (i = 0; i < D->maxsection; i++) if (D->sections[i].buf) DASM_M_FREE(Dst, D->sections[i].buf, D->sections[i].bsize); if (D->pclabels) DASM_M_FREE(Dst, D->pclabels, D->pcsize); if (D->lglabels) DASM_M_FREE(Dst, D->lglabels, D->lgsize); DASM_M_FREE(Dst, D, D->psize); } /* Setup global label array. Must be called before dasm_setup(). */ void dasm_setupglobal(Dst_DECL, void **gl, unsigned int maxgl) { dasm_State *D = Dst_REF; D->globals = gl - 10; /* Negative bias to compensate for locals. */ DASM_M_GROW(Dst, int, D->lglabels, D->lgsize, (10+maxgl)*sizeof(int)); } /* Grow PC label array. Can be called after dasm_setup(), too. */ void dasm_growpc(Dst_DECL, unsigned int maxpc) { dasm_State *D = Dst_REF; size_t osz = D->pcsize; DASM_M_GROW(Dst, int, D->pclabels, D->pcsize, maxpc*sizeof(int)); memset((void *)(((unsigned char *)D->pclabels)+osz), 0, D->pcsize-osz); } /* Setup encoder. */ void dasm_setup(Dst_DECL, const void *actionlist) { dasm_State *D = Dst_REF; int i; D->actionlist = (dasm_ActList)actionlist; D->status = DASM_S_OK; D->section = &D->sections[0]; memset((void *)D->lglabels, 0, D->lgsize); if (D->pclabels) memset((void *)D->pclabels, 0, D->pcsize); for (i = 0; i < D->maxsection; i++) { D->sections[i].pos = DASM_SEC2POS(i); D->sections[i].ofs = 0; } } #ifdef DASM_CHECKS #define CK(x, st) \ do { if (!(x)) { \ D->status = DASM_S_##st|(p-D->actionlist-1); return; } } while (0) #define CKPL(kind, st) \ do { if ((size_t)((char *)pl-(char *)D->kind##labels) >= D->kind##size) { \ D->status = DASM_S_RANGE_##st|(p-D->actionlist-1); return; } } while (0) #else #define CK(x, st) ((void)0) #define CKPL(kind, st) ((void)0) #endif /* Pass 1: Store actions and args, link branches/labels, estimate offsets. */ void dasm_put(Dst_DECL, int start, ...) { va_list ap; dasm_State *D = Dst_REF; dasm_ActList p = D->actionlist + start; dasm_Section *sec = D->section; int pos = sec->pos, ofs = sec->ofs; int *b; if (pos >= sec->epos) { DASM_M_GROW(Dst, int, sec->buf, sec->bsize, sec->bsize + 2*DASM_MAXSECPOS*sizeof(int)); sec->rbuf = sec->buf - DASM_POS2BIAS(pos); sec->epos = (int)sec->bsize/sizeof(int) - DASM_MAXSECPOS+DASM_POS2BIAS(pos); } b = sec->rbuf; b[pos++] = start; va_start(ap, start); while (1) { unsigned int ins = *p++; unsigned int action = (ins >> 16) - 0xff00; if (action >= DASM__MAX) { ofs += 4; } else { int *pl, n = action >= DASM_REL_PC ? va_arg(ap, int) : 0; switch (action) { case DASM_STOP: goto stop; case DASM_SECTION: n = (ins & 255); CK(n < D->maxsection, RANGE_SEC); D->section = &D->sections[n]; goto stop; case DASM_ESC: p++; ofs += 4; break; case DASM_REL_EXT: break; case DASM_ALIGN: ofs += (ins & 255); b[pos++] = ofs; break; case DASM_REL_LG: n = (ins & 2047) - 10; pl = D->lglabels + n; /* Bkwd rel or global. */ if (n >= 0) { CK(n>=10||*pl<0, RANGE_LG); CKPL(lg, LG); goto putrel; } pl += 10; n = *pl; if (n < 0) n = 0; /* Start new chain for fwd rel if label exists. */ goto linkrel; case DASM_REL_PC: pl = D->pclabels + n; CKPL(pc, PC); putrel: n = *pl; if (n < 0) { /* Label exists. Get label pos and store it. */ b[pos] = -n; } else { linkrel: b[pos] = n; /* Else link to rel chain, anchored at label. */ *pl = pos; } pos++; break; case DASM_LABEL_LG: pl = D->lglabels + (ins & 2047) - 10; CKPL(lg, LG); goto putlabel; case DASM_LABEL_PC: pl = D->pclabels + n; CKPL(pc, PC); putlabel: n = *pl; /* n > 0: Collapse rel chain and replace with label pos. */ while (n > 0) { int *pb = DASM_POS2PTR(D, n); n = *pb; *pb = pos; } *pl = -pos; /* Label exists now. */ b[pos++] = ofs; /* Store pass1 offset estimate. */ break; case DASM_IMM: case DASM_IMMS: #ifdef DASM_CHECKS CK((n & ((1<<((ins>>10)&31))-1)) == 0, RANGE_I); #endif n >>= ((ins>>10)&31); #ifdef DASM_CHECKS if (ins & 0x8000) CK(((n + (1<<(((ins>>5)&31)-1)))>>((ins>>5)&31)) == 0, RANGE_I); else CK((n>>((ins>>5)&31)) == 0, RANGE_I); #endif b[pos++] = n; break; } } } stop: va_end(ap); sec->pos = pos; sec->ofs = ofs; } #undef CK /* Pass 2: Link sections, shrink aligns, fix label offsets. */ int dasm_link(Dst_DECL, size_t *szp) { dasm_State *D = Dst_REF; int secnum; int ofs = 0; #ifdef DASM_CHECKS *szp = 0; if (D->status != DASM_S_OK) return D->status; { int pc; for (pc = 0; pc*sizeof(int) < D->pcsize; pc++) if (D->pclabels[pc] > 0) return DASM_S_UNDEF_PC|pc; } #endif { /* Handle globals not defined in this translation unit. */ int idx; for (idx = 10; idx*sizeof(int) < D->lgsize; idx++) { int n = D->lglabels[idx]; /* Undefined label: Collapse rel chain and replace with marker (< 0). */ while (n > 0) { int *pb = DASM_POS2PTR(D, n); n = *pb; *pb = -idx; } } } /* Combine all code sections. No support for data sections (yet). */ for (secnum = 0; secnum < D->maxsection; secnum++) { dasm_Section *sec = D->sections + secnum; int *b = sec->rbuf; int pos = DASM_SEC2POS(secnum); int lastpos = sec->pos; while (pos != lastpos) { dasm_ActList p = D->actionlist + b[pos++]; while (1) { unsigned int ins = *p++; unsigned int action = (ins >> 16) - 0xff00; switch (action) { case DASM_STOP: case DASM_SECTION: goto stop; case DASM_ESC: p++; break; case DASM_REL_EXT: break; case DASM_ALIGN: ofs -= (b[pos++] + ofs) & (ins & 255); break; case DASM_REL_LG: case DASM_REL_PC: pos++; break; case DASM_LABEL_LG: case DASM_LABEL_PC: b[pos++] += ofs; break; case DASM_IMM: case DASM_IMMS: pos++; break; } } stop: (void)0; } ofs += sec->ofs; /* Next section starts right after current section. */ } D->codesize = ofs; /* Total size of all code sections */ *szp = ofs; return DASM_S_OK; } #ifdef DASM_CHECKS #define CK(x, st) \ do { if (!(x)) return DASM_S_##st|(p-D->actionlist-1); } while (0) #else #define CK(x, st) ((void)0) #endif /* Pass 3: Encode sections. */ int dasm_encode(Dst_DECL, void *buffer) { dasm_State *D = Dst_REF; char *base = (char *)buffer; unsigned int *cp = (unsigned int *)buffer; int secnum; /* Encode all code sections. No support for data sections (yet). */ for (secnum = 0; secnum < D->maxsection; secnum++) { dasm_Section *sec = D->sections + secnum; int *b = sec->buf; int *endb = sec->rbuf + sec->pos; while (b != endb) { dasm_ActList p = D->actionlist + *b++; while (1) { unsigned int ins = *p++; unsigned int action = (ins >> 16) - 0xff00; int n = (action >= DASM_ALIGN && action < DASM__MAX) ? *b++ : 0; switch (action) { case DASM_STOP: case DASM_SECTION: goto stop; case DASM_ESC: *cp++ = *p++; break; case DASM_REL_EXT: n = DASM_EXTERN(Dst, (unsigned char *)cp, (ins & 2047), 1); goto patchrel; case DASM_ALIGN: ins &= 255; while ((((char *)cp - base) & ins)) *cp++ = 0x60000000; break; case DASM_REL_LG: if (n < 0) { n = (int)((ptrdiff_t)D->globals[-n] - (ptrdiff_t)cp); goto patchrel; } /* fallthrough */ case DASM_REL_PC: CK(n >= 0, UNDEF_PC); n = *DASM_POS2PTR(D, n); if (ins & 2048) n = (n + (int)(size_t)base) & 0x0fffffff; else n = n - (int)((char *)cp - base); patchrel: { unsigned int e = 16 + ((ins >> 12) & 15); CK((n & 3) == 0 && ((n + ((ins & 2048) ? 0 : (1<<(e+1)))) >> (e+2)) == 0, RANGE_REL); cp[-1] |= ((n>>2) & ((1<<e)-1)); } break; case DASM_LABEL_LG: ins &= 2047; if (ins >= 20) D->globals[ins-10] = (void *)(base + n); break; case DASM_LABEL_PC: break; case DASM_IMMS: cp[-1] |= ((n>>3) & 4); n &= 0x1f; /* fallthrough */ case DASM_IMM: cp[-1] |= (n & ((1<<((ins>>5)&31))-1)) << (ins&31); break; default: *cp++ = ins; break; } } stop: (void)0; } } if (base + D->codesize != (char *)cp) /* Check for phase errors. */ return DASM_S_PHASE; return DASM_S_OK; } #undef CK /* Get PC label offset. */ int dasm_getpclabel(Dst_DECL, unsigned int pc) { dasm_State *D = Dst_REF; if (pc*sizeof(int) < D->pcsize) { int pos = D->pclabels[pc]; if (pos < 0) return *DASM_POS2PTR(D, -pos); if (pos > 0) return -1; /* Undefined. */ } return -2; /* Unused or out of range. */ } #ifdef DASM_CHECKS /* Optional sanity checker to call between isolated encoding steps. */ int dasm_checkstep(Dst_DECL, int secmatch) { dasm_State *D = Dst_REF; if (D->status == DASM_S_OK) { int i; for (i = 1; i <= 9; i++) { if (D->lglabels[i] > 0) { D->status = DASM_S_UNDEF_LG|i; break; } D->lglabels[i] = 0; } } if (D->status == DASM_S_OK && secmatch >= 0 && D->section != &D->sections[secmatch]) D->status = DASM_S_MATCH_SEC|(D->section-D->sections); return D->status; } #endif
xLua/build/luajit-2.1.0b3/dynasm/dasm_mips.h/0
{ "file_path": "xLua/build/luajit-2.1.0b3/dynasm/dasm_mips.h", "repo_id": "xLua", "token_count": 5660 }
2,043
lib_aux.o: lib_aux.c lua.h luaconf.h lauxlib.h lj_obj.h lj_def.h \ lj_arch.h lj_err.h lj_errmsg.h lj_state.h lj_trace.h lj_jit.h lj_ir.h \ lj_dispatch.h lj_bc.h lj_traceerr.h lj_lib.h lib_base.o: lib_base.c lua.h luaconf.h lauxlib.h lualib.h lj_obj.h \ lj_def.h lj_arch.h lj_gc.h lj_err.h lj_errmsg.h lj_debug.h lj_buf.h \ lj_str.h lj_tab.h lj_meta.h lj_state.h lj_frame.h lj_bc.h lj_ctype.h \ lj_cconv.h lj_ff.h lj_ffdef.h lj_dispatch.h lj_jit.h lj_ir.h lj_char.h \ lj_strscan.h lj_strfmt.h lj_lib.h lj_libdef.h lib_bit.o: lib_bit.c lua.h luaconf.h lauxlib.h lualib.h lj_obj.h lj_def.h \ lj_arch.h lj_err.h lj_errmsg.h lj_buf.h lj_gc.h lj_str.h lj_strscan.h \ lj_strfmt.h lj_ctype.h lj_cdata.h lj_cconv.h lj_carith.h lj_ff.h \ lj_ffdef.h lj_lib.h lj_libdef.h lib_buffer.o: lib_buffer.c lua.h luaconf.h lauxlib.h lualib.h lj_obj.h \ lj_def.h lj_arch.h lj_gc.h lj_err.h lj_errmsg.h lj_buf.h lj_str.h \ lj_tab.h lj_udata.h lj_meta.h lj_ctype.h lj_cdata.h lj_cconv.h \ lj_strfmt.h lj_serialize.h lj_lib.h lj_libdef.h lib_debug.o: lib_debug.c lua.h luaconf.h lauxlib.h lualib.h lj_obj.h \ lj_def.h lj_arch.h lj_gc.h lj_err.h lj_errmsg.h lj_debug.h lj_lib.h \ lj_libdef.h lib_ffi.o: lib_ffi.c lua.h luaconf.h lauxlib.h lualib.h lj_obj.h lj_def.h \ lj_arch.h lj_gc.h lj_err.h lj_errmsg.h lj_str.h lj_tab.h lj_meta.h \ lj_ctype.h lj_cparse.h lj_cdata.h lj_cconv.h lj_carith.h lj_ccall.h \ lj_ccallback.h lj_clib.h lj_strfmt.h lj_ff.h lj_ffdef.h lj_lib.h \ lj_libdef.h lib_init.o: lib_init.c lua.h luaconf.h lauxlib.h lualib.h lj_arch.h lib_io.o: lib_io.c lua.h luaconf.h lauxlib.h lualib.h lj_obj.h lj_def.h \ lj_arch.h lj_gc.h lj_err.h lj_errmsg.h lj_buf.h lj_str.h lj_state.h \ lj_strfmt.h lj_ff.h lj_ffdef.h lj_lib.h lj_libdef.h lib_jit.o: lib_jit.c lua.h luaconf.h lauxlib.h lualib.h lj_obj.h lj_def.h \ lj_arch.h lj_gc.h lj_err.h lj_errmsg.h lj_debug.h lj_str.h lj_tab.h \ lj_state.h lj_bc.h lj_ctype.h lj_ir.h lj_jit.h lj_ircall.h lj_iropt.h \ lj_target.h lj_target_*.h lj_trace.h lj_dispatch.h lj_traceerr.h \ lj_vm.h lj_vmevent.h lj_lib.h luajit.h lj_libdef.h lib_math.o: lib_math.c lua.h luaconf.h lauxlib.h lualib.h lj_obj.h \ lj_def.h lj_arch.h lj_lib.h lj_vm.h lj_prng.h lj_libdef.h lib_os.o: lib_os.c lua.h luaconf.h lauxlib.h lualib.h lj_obj.h lj_def.h \ lj_arch.h lj_gc.h lj_err.h lj_errmsg.h lj_buf.h lj_str.h lj_lib.h \ lj_libdef.h lib_package.o: lib_package.c lua.h luaconf.h lauxlib.h lualib.h lj_obj.h \ lj_def.h lj_arch.h lj_err.h lj_errmsg.h lj_lib.h lib_string.o: lib_string.c lua.h luaconf.h lauxlib.h lualib.h lj_obj.h \ lj_def.h lj_arch.h lj_gc.h lj_err.h lj_errmsg.h lj_buf.h lj_str.h \ lj_tab.h lj_meta.h lj_state.h lj_ff.h lj_ffdef.h lj_bcdump.h lj_lex.h \ lj_char.h lj_strfmt.h lj_lib.h lj_libdef.h lib_table.o: lib_table.c lua.h luaconf.h lauxlib.h lualib.h lj_obj.h \ lj_def.h lj_arch.h lj_gc.h lj_err.h lj_errmsg.h lj_buf.h lj_str.h \ lj_tab.h lj_ff.h lj_ffdef.h lj_lib.h lj_libdef.h lj_alloc.o: lj_alloc.c lj_def.h lua.h luaconf.h lj_arch.h lj_alloc.h \ lj_prng.h lj_api.o: lj_api.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h lj_gc.h \ lj_err.h lj_errmsg.h lj_debug.h lj_str.h lj_tab.h lj_func.h lj_udata.h \ lj_meta.h lj_state.h lj_bc.h lj_frame.h lj_trace.h lj_jit.h lj_ir.h \ lj_dispatch.h lj_traceerr.h lj_vm.h lj_strscan.h lj_strfmt.h lj_asm.o: lj_asm.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h lj_gc.h \ lj_buf.h lj_str.h lj_tab.h lj_frame.h lj_bc.h lj_ctype.h lj_ir.h \ lj_jit.h lj_ircall.h lj_iropt.h lj_mcode.h lj_trace.h lj_dispatch.h \ lj_traceerr.h lj_snap.h lj_asm.h lj_vm.h lj_target.h lj_target_*.h \ lj_emit_*.h lj_asm_*.h lj_assert.o: lj_assert.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h lj_bc.o: lj_bc.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h lj_bc.h \ lj_bcdef.h lj_bcread.o: lj_bcread.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \ lj_gc.h lj_err.h lj_errmsg.h lj_buf.h lj_str.h lj_tab.h lj_bc.h \ lj_ctype.h lj_cdata.h lualib.h lj_lex.h lj_bcdump.h lj_state.h \ lj_strfmt.h lj_bcwrite.o: lj_bcwrite.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \ lj_gc.h lj_buf.h lj_str.h lj_bc.h lj_ctype.h lj_dispatch.h lj_jit.h \ lj_ir.h lj_strfmt.h lj_bcdump.h lj_lex.h lj_err.h lj_errmsg.h lj_vm.h lj_buf.o: lj_buf.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h lj_gc.h \ lj_err.h lj_errmsg.h lj_buf.h lj_str.h lj_tab.h lj_strfmt.h lj_carith.o: lj_carith.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \ lj_gc.h lj_err.h lj_errmsg.h lj_tab.h lj_meta.h lj_ir.h lj_ctype.h \ lj_cconv.h lj_cdata.h lj_carith.h lj_strscan.h lj_ccall.o: lj_ccall.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \ lj_gc.h lj_err.h lj_errmsg.h lj_tab.h lj_ctype.h lj_cconv.h lj_cdata.h \ lj_ccall.h lj_trace.h lj_jit.h lj_ir.h lj_dispatch.h lj_bc.h \ lj_traceerr.h lj_ccallback.o: lj_ccallback.c lj_obj.h lua.h luaconf.h lj_def.h \ lj_arch.h lj_gc.h lj_err.h lj_errmsg.h lj_tab.h lj_state.h lj_frame.h \ lj_bc.h lj_ctype.h lj_cconv.h lj_ccall.h lj_ccallback.h lj_target.h \ lj_target_*.h lj_mcode.h lj_jit.h lj_ir.h lj_trace.h lj_dispatch.h \ lj_traceerr.h lj_vm.h lj_cconv.o: lj_cconv.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \ lj_err.h lj_errmsg.h lj_buf.h lj_gc.h lj_str.h lj_tab.h lj_ctype.h \ lj_cdata.h lj_cconv.h lj_ccallback.h lj_cdata.o: lj_cdata.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \ lj_gc.h lj_err.h lj_errmsg.h lj_tab.h lj_ctype.h lj_cconv.h lj_cdata.h lj_char.o: lj_char.c lj_char.h lj_def.h lua.h luaconf.h lj_clib.o: lj_clib.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h lj_gc.h \ lj_err.h lj_errmsg.h lj_tab.h lj_str.h lj_udata.h lj_ctype.h lj_cconv.h \ lj_cdata.h lj_clib.h lj_strfmt.h lj_cparse.o: lj_cparse.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \ lj_gc.h lj_err.h lj_errmsg.h lj_buf.h lj_str.h lj_ctype.h lj_cparse.h \ lj_frame.h lj_bc.h lj_vm.h lj_char.h lj_strscan.h lj_strfmt.h lj_crecord.o: lj_crecord.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \ lj_err.h lj_errmsg.h lj_tab.h lj_frame.h lj_bc.h lj_ctype.h lj_gc.h \ lj_cdata.h lj_cparse.h lj_cconv.h lj_carith.h lj_clib.h lj_ccall.h \ lj_ff.h lj_ffdef.h lj_ir.h lj_jit.h lj_ircall.h lj_iropt.h lj_trace.h \ lj_dispatch.h lj_traceerr.h lj_record.h lj_ffrecord.h lj_snap.h \ lj_crecord.h lj_strfmt.h lj_ctype.o: lj_ctype.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \ lj_gc.h lj_err.h lj_errmsg.h lj_str.h lj_tab.h lj_strfmt.h lj_ctype.h \ lj_ccallback.h lj_buf.h lj_debug.o: lj_debug.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \ lj_err.h lj_errmsg.h lj_debug.h lj_buf.h lj_gc.h lj_str.h lj_tab.h \ lj_state.h lj_frame.h lj_bc.h lj_strfmt.h lj_jit.h lj_ir.h lj_dispatch.o: lj_dispatch.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \ lj_err.h lj_errmsg.h lj_buf.h lj_gc.h lj_str.h lj_func.h lj_tab.h \ lj_meta.h lj_debug.h lj_state.h lj_frame.h lj_bc.h lj_ff.h lj_ffdef.h \ lj_strfmt.h lj_jit.h lj_ir.h lj_ccallback.h lj_ctype.h lj_trace.h \ lj_dispatch.h lj_traceerr.h lj_profile.h lj_vm.h luajit.h lj_err.o: lj_err.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h lj_err.h \ lj_errmsg.h lj_debug.h lj_str.h lj_func.h lj_state.h lj_frame.h lj_bc.h \ lj_ff.h lj_ffdef.h lj_trace.h lj_jit.h lj_ir.h lj_dispatch.h \ lj_traceerr.h lj_vm.h lj_strfmt.h lj_ffrecord.o: lj_ffrecord.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \ lj_err.h lj_errmsg.h lj_buf.h lj_gc.h lj_str.h lj_tab.h lj_frame.h \ lj_bc.h lj_ff.h lj_ffdef.h lj_ir.h lj_jit.h lj_ircall.h lj_iropt.h \ lj_trace.h lj_dispatch.h lj_traceerr.h lj_record.h lj_ffrecord.h \ lj_crecord.h lj_vm.h lj_strscan.h lj_strfmt.h lj_serialize.h lj_recdef.h lj_func.o: lj_func.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h lj_gc.h \ lj_func.h lj_trace.h lj_jit.h lj_ir.h lj_dispatch.h lj_bc.h \ lj_traceerr.h lj_vm.h lj_gc.o: lj_gc.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h lj_gc.h \ lj_err.h lj_errmsg.h lj_buf.h lj_str.h lj_tab.h lj_func.h lj_udata.h \ lj_meta.h lj_state.h lj_frame.h lj_bc.h lj_ctype.h lj_cdata.h lj_trace.h \ lj_jit.h lj_ir.h lj_dispatch.h lj_traceerr.h lj_vm.h lj_gdbjit.o: lj_gdbjit.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \ lj_gc.h lj_err.h lj_errmsg.h lj_debug.h lj_frame.h lj_bc.h lj_buf.h \ lj_str.h lj_strfmt.h lj_jit.h lj_ir.h lj_dispatch.h lj_ir.o: lj_ir.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h lj_gc.h \ lj_buf.h lj_str.h lj_tab.h lj_ir.h lj_jit.h lj_ircall.h lj_iropt.h \ lj_trace.h lj_dispatch.h lj_bc.h lj_traceerr.h lj_ctype.h lj_cdata.h \ lj_carith.h lj_vm.h lj_strscan.h lj_serialize.h lj_strfmt.h lj_prng.h lj_lex.o: lj_lex.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h lj_gc.h \ lj_err.h lj_errmsg.h lj_buf.h lj_str.h lj_tab.h lj_ctype.h lj_cdata.h \ lualib.h lj_state.h lj_lex.h lj_parse.h lj_char.h lj_strscan.h \ lj_strfmt.h lj_lib.o: lj_lib.c lauxlib.h lua.h luaconf.h lj_obj.h lj_def.h lj_arch.h \ lj_gc.h lj_err.h lj_errmsg.h lj_str.h lj_tab.h lj_func.h lj_bc.h \ lj_dispatch.h lj_jit.h lj_ir.h lj_ctype.h lj_vm.h lj_strscan.h \ lj_strfmt.h lj_lex.h lj_bcdump.h lj_lib.h lj_load.o: lj_load.c lua.h luaconf.h lauxlib.h lj_obj.h lj_def.h \ lj_arch.h lj_gc.h lj_err.h lj_errmsg.h lj_buf.h lj_str.h lj_func.h \ lj_frame.h lj_bc.h lj_vm.h lj_lex.h lj_bcdump.h lj_parse.h lj_mcode.o: lj_mcode.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \ lj_gc.h lj_err.h lj_errmsg.h lj_jit.h lj_ir.h lj_mcode.h lj_trace.h \ lj_dispatch.h lj_bc.h lj_traceerr.h lj_prng.h lj_vm.h lj_meta.o: lj_meta.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h lj_gc.h \ lj_err.h lj_errmsg.h lj_buf.h lj_str.h lj_tab.h lj_meta.h lj_frame.h \ lj_bc.h lj_vm.h lj_strscan.h lj_strfmt.h lj_lib.h lj_obj.o: lj_obj.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h lj_opt_dce.o: lj_opt_dce.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \ lj_ir.h lj_jit.h lj_iropt.h lj_opt_fold.o: lj_opt_fold.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \ lj_buf.h lj_gc.h lj_str.h lj_tab.h lj_ir.h lj_jit.h lj_ircall.h \ lj_iropt.h lj_trace.h lj_dispatch.h lj_bc.h lj_traceerr.h lj_ctype.h \ lj_carith.h lj_vm.h lj_strscan.h lj_strfmt.h lj_folddef.h lj_opt_loop.o: lj_opt_loop.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \ lj_err.h lj_errmsg.h lj_buf.h lj_gc.h lj_str.h lj_ir.h lj_jit.h \ lj_iropt.h lj_trace.h lj_dispatch.h lj_bc.h lj_traceerr.h lj_snap.h \ lj_vm.h lj_opt_mem.o: lj_opt_mem.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \ lj_tab.h lj_ir.h lj_jit.h lj_iropt.h lj_ircall.h lj_dispatch.h lj_bc.h lj_opt_narrow.o: lj_opt_narrow.c lj_obj.h lua.h luaconf.h lj_def.h \ lj_arch.h lj_bc.h lj_ir.h lj_jit.h lj_iropt.h lj_trace.h lj_dispatch.h \ lj_traceerr.h lj_vm.h lj_strscan.h lj_opt_sink.o: lj_opt_sink.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \ lj_ir.h lj_jit.h lj_iropt.h lj_target.h lj_target_*.h lj_opt_split.o: lj_opt_split.c lj_obj.h lua.h luaconf.h lj_def.h \ lj_arch.h lj_err.h lj_errmsg.h lj_buf.h lj_gc.h lj_str.h lj_ir.h \ lj_jit.h lj_ircall.h lj_iropt.h lj_dispatch.h lj_bc.h lj_vm.h lj_parse.o: lj_parse.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \ lj_gc.h lj_err.h lj_errmsg.h lj_debug.h lj_buf.h lj_str.h lj_tab.h \ lj_func.h lj_state.h lj_bc.h lj_ctype.h lj_strfmt.h lj_lex.h lj_parse.h \ lj_vm.h lj_vmevent.h lj_prng.o: lj_prng.c lj_def.h lua.h luaconf.h lj_arch.h lj_prng.h lj_profile.o: lj_profile.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \ lj_buf.h lj_gc.h lj_str.h lj_frame.h lj_bc.h lj_debug.h lj_dispatch.h \ lj_jit.h lj_ir.h lj_trace.h lj_traceerr.h lj_profile.h luajit.h lj_record.o: lj_record.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \ lj_err.h lj_errmsg.h lj_str.h lj_tab.h lj_meta.h lj_frame.h lj_bc.h \ lj_ctype.h lj_gc.h lj_ff.h lj_ffdef.h lj_debug.h lj_ir.h lj_jit.h \ lj_ircall.h lj_iropt.h lj_trace.h lj_dispatch.h lj_traceerr.h \ lj_record.h lj_ffrecord.h lj_snap.h lj_vm.h lj_prng.h lj_serialize.o: lj_serialize.c lj_obj.h lua.h luaconf.h lj_def.h \ lj_arch.h lj_err.h lj_errmsg.h lj_buf.h lj_gc.h lj_str.h lj_tab.h \ lj_udata.h lj_ctype.h lj_cdata.h lj_ir.h lj_serialize.h lj_snap.o: lj_snap.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h lj_gc.h \ lj_tab.h lj_state.h lj_frame.h lj_bc.h lj_ir.h lj_jit.h lj_iropt.h \ lj_trace.h lj_dispatch.h lj_traceerr.h lj_snap.h lj_target.h \ lj_target_*.h lj_ctype.h lj_cdata.h lj_state.o: lj_state.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \ lj_gc.h lj_err.h lj_errmsg.h lj_buf.h lj_str.h lj_tab.h lj_func.h \ lj_meta.h lj_state.h lj_frame.h lj_bc.h lj_ctype.h lj_trace.h lj_jit.h \ lj_ir.h lj_dispatch.h lj_traceerr.h lj_vm.h lj_prng.h lj_lex.h \ lj_alloc.h luajit.h lj_str.o: lj_str.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h lj_gc.h \ lj_err.h lj_errmsg.h lj_str.h lj_char.h lj_prng.h lj_strfmt.o: lj_strfmt.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \ lj_err.h lj_errmsg.h lj_buf.h lj_gc.h lj_str.h lj_meta.h lj_state.h \ lj_char.h lj_strfmt.h lj_ctype.h lj_lib.h lj_strfmt_num.o: lj_strfmt_num.c lj_obj.h lua.h luaconf.h lj_def.h \ lj_arch.h lj_buf.h lj_gc.h lj_str.h lj_strfmt.h lj_strscan.o: lj_strscan.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \ lj_char.h lj_strscan.h lj_tab.o: lj_tab.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h lj_gc.h \ lj_err.h lj_errmsg.h lj_tab.h lj_trace.o: lj_trace.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \ lj_gc.h lj_err.h lj_errmsg.h lj_debug.h lj_str.h lj_frame.h lj_bc.h \ lj_state.h lj_ir.h lj_jit.h lj_iropt.h lj_mcode.h lj_trace.h \ lj_dispatch.h lj_traceerr.h lj_snap.h lj_gdbjit.h lj_record.h lj_asm.h \ lj_vm.h lj_vmevent.h lj_target.h lj_target_*.h lj_prng.h lj_udata.o: lj_udata.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \ lj_gc.h lj_err.h lj_errmsg.h lj_udata.h lj_vmevent.o: lj_vmevent.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \ lj_str.h lj_tab.h lj_state.h lj_dispatch.h lj_bc.h lj_jit.h lj_ir.h \ lj_vm.h lj_vmevent.h lj_vmmath.o: lj_vmmath.c lj_obj.h lua.h luaconf.h lj_def.h lj_arch.h \ lj_ir.h lj_vm.h ljamalg.o: ljamalg.c lua.h luaconf.h lauxlib.h lj_assert.c lj_obj.h \ lj_def.h lj_arch.h lj_gc.c lj_gc.h lj_err.h lj_errmsg.h lj_buf.h \ lj_str.h lj_tab.h lj_func.h lj_udata.h lj_meta.h lj_state.h lj_frame.h \ lj_bc.h lj_ctype.h lj_cdata.h lj_trace.h lj_jit.h lj_ir.h lj_dispatch.h \ lj_traceerr.h lj_vm.h lj_err.c lj_debug.h lj_ff.h lj_ffdef.h lj_strfmt.h \ lj_char.c lj_char.h lj_bc.c lj_bcdef.h lj_obj.c lj_buf.c lj_str.c \ lj_prng.h lj_tab.c lj_func.c lj_udata.c lj_meta.c lj_strscan.h lj_lib.h \ lj_debug.c lj_prng.c lj_state.c lj_lex.h lj_alloc.h luajit.h \ lj_dispatch.c lj_ccallback.h lj_profile.h lj_vmevent.c lj_vmevent.h \ lj_vmmath.c lj_strscan.c lj_strfmt.c lj_strfmt_num.c lj_serialize.c \ lj_serialize.h lj_api.c lj_profile.c lj_lex.c lualib.h lj_parse.h \ lj_parse.c lj_bcread.c lj_bcdump.h lj_bcwrite.c lj_load.c lj_ctype.c \ lj_cdata.c lj_cconv.h lj_cconv.c lj_ccall.c lj_ccall.h lj_ccallback.c \ lj_target.h lj_target_*.h lj_mcode.h lj_carith.c lj_carith.h lj_clib.c \ lj_clib.h lj_cparse.c lj_cparse.h lj_lib.c lj_ir.c lj_ircall.h \ lj_iropt.h lj_opt_mem.c lj_opt_fold.c lj_folddef.h lj_opt_narrow.c \ lj_opt_dce.c lj_opt_loop.c lj_snap.h lj_opt_split.c lj_opt_sink.c \ lj_mcode.c lj_snap.c lj_record.c lj_record.h lj_ffrecord.h lj_crecord.c \ lj_crecord.h lj_ffrecord.c lj_recdef.h lj_asm.c lj_asm.h lj_emit_*.h \ lj_asm_*.h lj_trace.c lj_gdbjit.h lj_gdbjit.c lj_alloc.c lib_aux.c \ lib_base.c lj_libdef.h lib_math.c lib_string.c lib_table.c lib_io.c \ lib_os.c lib_package.c lib_debug.c lib_bit.c lib_jit.c lib_ffi.c \ lib_buffer.c lib_init.c luajit.o: luajit.c lua.h luaconf.h lauxlib.h lualib.h luajit.h lj_arch.h host/buildvm.o: host/buildvm.c host/buildvm.h lj_def.h lua.h luaconf.h \ lj_arch.h lj_obj.h lj_def.h lj_arch.h lj_gc.h lj_obj.h lj_bc.h lj_ir.h \ lj_ircall.h lj_ir.h lj_jit.h lj_frame.h lj_bc.h lj_dispatch.h lj_ctype.h \ lj_gc.h lj_ccall.h lj_ctype.h luajit.h \ host/buildvm_arch.h lj_traceerr.h host/buildvm_asm.o: host/buildvm_asm.c host/buildvm.h lj_def.h lua.h luaconf.h \ lj_arch.h lj_bc.h lj_def.h lj_arch.h host/buildvm_fold.o: host/buildvm_fold.c host/buildvm.h lj_def.h lua.h \ luaconf.h lj_arch.h lj_obj.h lj_def.h lj_arch.h lj_ir.h lj_obj.h host/buildvm_lib.o: host/buildvm_lib.c host/buildvm.h lj_def.h lua.h luaconf.h \ lj_arch.h lj_obj.h lj_def.h lj_arch.h lj_bc.h lj_lib.h lj_obj.h \ host/buildvm_libbc.h host/buildvm_peobj.o: host/buildvm_peobj.c host/buildvm.h lj_def.h lua.h \ luaconf.h lj_arch.h lj_bc.h lj_def.h lj_arch.h host/minilua.o: host/minilua.c
xLua/build/luajit-2.1.0b3/src/Makefile.dep/0
{ "file_path": "xLua/build/luajit-2.1.0b3/src/Makefile.dep", "repo_id": "xLua", "token_count": 10108 }
2,044
---------------------------------------------------------------------------- -- LuaJIT ARM disassembler module. -- -- Copyright (C) 2005-2021 Mike Pall. All rights reserved. -- Released under the MIT license. See Copyright Notice in luajit.h ---------------------------------------------------------------------------- -- This is a helper module used by the LuaJIT machine code dumper module. -- -- It disassembles most user-mode ARMv7 instructions -- NYI: Advanced SIMD and VFP instructions. ------------------------------------------------------------------------------ local type = type local sub, byte, format = string.sub, string.byte, string.format local match, gmatch = string.match, string.gmatch local concat = table.concat local bit = require("bit") local band, bor, ror, tohex = bit.band, bit.bor, bit.ror, bit.tohex local lshift, rshift, arshift = bit.lshift, bit.rshift, bit.arshift ------------------------------------------------------------------------------ -- Opcode maps ------------------------------------------------------------------------------ local map_loadc = { shift = 8, mask = 15, [10] = { shift = 20, mask = 1, [0] = { shift = 23, mask = 3, [0] = "vmovFmDN", "vstmFNdr", _ = { shift = 21, mask = 1, [0] = "vstrFdl", { shift = 16, mask = 15, [13] = "vpushFdr", _ = "vstmdbFNdr", } }, }, { shift = 23, mask = 3, [0] = "vmovFDNm", { shift = 16, mask = 15, [13] = "vpopFdr", _ = "vldmFNdr", }, _ = { shift = 21, mask = 1, [0] = "vldrFdl", "vldmdbFNdr", }, }, }, [11] = { shift = 20, mask = 1, [0] = { shift = 23, mask = 3, [0] = "vmovGmDN", "vstmGNdr", _ = { shift = 21, mask = 1, [0] = "vstrGdl", { shift = 16, mask = 15, [13] = "vpushGdr", _ = "vstmdbGNdr", } }, }, { shift = 23, mask = 3, [0] = "vmovGDNm", { shift = 16, mask = 15, [13] = "vpopGdr", _ = "vldmGNdr", }, _ = { shift = 21, mask = 1, [0] = "vldrGdl", "vldmdbGNdr", }, }, }, _ = { shift = 0, mask = 0 -- NYI ldc, mcrr, mrrc. }, } local map_vfps = { shift = 6, mask = 0x2c001, [0] = "vmlaF.dnm", "vmlsF.dnm", [0x04000] = "vnmlsF.dnm", [0x04001] = "vnmlaF.dnm", [0x08000] = "vmulF.dnm", [0x08001] = "vnmulF.dnm", [0x0c000] = "vaddF.dnm", [0x0c001] = "vsubF.dnm", [0x20000] = "vdivF.dnm", [0x24000] = "vfnmsF.dnm", [0x24001] = "vfnmaF.dnm", [0x28000] = "vfmaF.dnm", [0x28001] = "vfmsF.dnm", [0x2c000] = "vmovF.dY", [0x2c001] = { shift = 7, mask = 0x1e01, [0] = "vmovF.dm", "vabsF.dm", [0x0200] = "vnegF.dm", [0x0201] = "vsqrtF.dm", [0x0800] = "vcmpF.dm", [0x0801] = "vcmpeF.dm", [0x0a00] = "vcmpzF.d", [0x0a01] = "vcmpzeF.d", [0x0e01] = "vcvtG.dF.m", [0x1000] = "vcvt.f32.u32Fdm", [0x1001] = "vcvt.f32.s32Fdm", [0x1800] = "vcvtr.u32F.dm", [0x1801] = "vcvt.u32F.dm", [0x1a00] = "vcvtr.s32F.dm", [0x1a01] = "vcvt.s32F.dm", }, } local map_vfpd = { shift = 6, mask = 0x2c001, [0] = "vmlaG.dnm", "vmlsG.dnm", [0x04000] = "vnmlsG.dnm", [0x04001] = "vnmlaG.dnm", [0x08000] = "vmulG.dnm", [0x08001] = "vnmulG.dnm", [0x0c000] = "vaddG.dnm", [0x0c001] = "vsubG.dnm", [0x20000] = "vdivG.dnm", [0x24000] = "vfnmsG.dnm", [0x24001] = "vfnmaG.dnm", [0x28000] = "vfmaG.dnm", [0x28001] = "vfmsG.dnm", [0x2c000] = "vmovG.dY", [0x2c001] = { shift = 7, mask = 0x1e01, [0] = "vmovG.dm", "vabsG.dm", [0x0200] = "vnegG.dm", [0x0201] = "vsqrtG.dm", [0x0800] = "vcmpG.dm", [0x0801] = "vcmpeG.dm", [0x0a00] = "vcmpzG.d", [0x0a01] = "vcmpzeG.d", [0x0e01] = "vcvtF.dG.m", [0x1000] = "vcvt.f64.u32GdFm", [0x1001] = "vcvt.f64.s32GdFm", [0x1800] = "vcvtr.u32FdG.m", [0x1801] = "vcvt.u32FdG.m", [0x1a00] = "vcvtr.s32FdG.m", [0x1a01] = "vcvt.s32FdG.m", }, } local map_datac = { shift = 24, mask = 1, [0] = { shift = 4, mask = 1, [0] = { shift = 8, mask = 15, [10] = map_vfps, [11] = map_vfpd, -- NYI cdp, mcr, mrc. }, { shift = 8, mask = 15, [10] = { shift = 20, mask = 15, [0] = "vmovFnD", "vmovFDn", [14] = "vmsrD", [15] = { shift = 12, mask = 15, [15] = "vmrs", _ = "vmrsD", }, }, }, }, "svcT", } local map_loadcu = { shift = 0, mask = 0, -- NYI unconditional CP load/store. } local map_datacu = { shift = 0, mask = 0, -- NYI unconditional CP data. } local map_simddata = { shift = 0, mask = 0, -- NYI SIMD data. } local map_simdload = { shift = 0, mask = 0, -- NYI SIMD load/store, preload. } local map_preload = { shift = 0, mask = 0, -- NYI preload. } local map_media = { shift = 20, mask = 31, [0] = false, { --01 shift = 5, mask = 7, [0] = "sadd16DNM", "sasxDNM", "ssaxDNM", "ssub16DNM", "sadd8DNM", false, false, "ssub8DNM", }, { --02 shift = 5, mask = 7, [0] = "qadd16DNM", "qasxDNM", "qsaxDNM", "qsub16DNM", "qadd8DNM", false, false, "qsub8DNM", }, { --03 shift = 5, mask = 7, [0] = "shadd16DNM", "shasxDNM", "shsaxDNM", "shsub16DNM", "shadd8DNM", false, false, "shsub8DNM", }, false, { --05 shift = 5, mask = 7, [0] = "uadd16DNM", "uasxDNM", "usaxDNM", "usub16DNM", "uadd8DNM", false, false, "usub8DNM", }, { --06 shift = 5, mask = 7, [0] = "uqadd16DNM", "uqasxDNM", "uqsaxDNM", "uqsub16DNM", "uqadd8DNM", false, false, "uqsub8DNM", }, { --07 shift = 5, mask = 7, [0] = "uhadd16DNM", "uhasxDNM", "uhsaxDNM", "uhsub16DNM", "uhadd8DNM", false, false, "uhsub8DNM", }, { --08 shift = 5, mask = 7, [0] = "pkhbtDNMU", false, "pkhtbDNMU", { shift = 16, mask = 15, [15] = "sxtb16DMU", _ = "sxtab16DNMU", }, "pkhbtDNMU", "selDNM", "pkhtbDNMU", }, false, { --0a shift = 5, mask = 7, [0] = "ssatDxMu", "ssat16DxM", "ssatDxMu", { shift = 16, mask = 15, [15] = "sxtbDMU", _ = "sxtabDNMU", }, "ssatDxMu", false, "ssatDxMu", }, { --0b shift = 5, mask = 7, [0] = "ssatDxMu", "revDM", "ssatDxMu", { shift = 16, mask = 15, [15] = "sxthDMU", _ = "sxtahDNMU", }, "ssatDxMu", "rev16DM", "ssatDxMu", }, { --0c shift = 5, mask = 7, [3] = { shift = 16, mask = 15, [15] = "uxtb16DMU", _ = "uxtab16DNMU", }, }, false, { --0e shift = 5, mask = 7, [0] = "usatDwMu", "usat16DwM", "usatDwMu", { shift = 16, mask = 15, [15] = "uxtbDMU", _ = "uxtabDNMU", }, "usatDwMu", false, "usatDwMu", }, { --0f shift = 5, mask = 7, [0] = "usatDwMu", "rbitDM", "usatDwMu", { shift = 16, mask = 15, [15] = "uxthDMU", _ = "uxtahDNMU", }, "usatDwMu", "revshDM", "usatDwMu", }, { --10 shift = 12, mask = 15, [15] = { shift = 5, mask = 7, "smuadNMS", "smuadxNMS", "smusdNMS", "smusdxNMS", }, _ = { shift = 5, mask = 7, [0] = "smladNMSD", "smladxNMSD", "smlsdNMSD", "smlsdxNMSD", }, }, false, false, false, { --14 shift = 5, mask = 7, [0] = "smlaldDNMS", "smlaldxDNMS", "smlsldDNMS", "smlsldxDNMS", }, { --15 shift = 5, mask = 7, [0] = { shift = 12, mask = 15, [15] = "smmulNMS", _ = "smmlaNMSD", }, { shift = 12, mask = 15, [15] = "smmulrNMS", _ = "smmlarNMSD", }, false, false, false, false, "smmlsNMSD", "smmlsrNMSD", }, false, false, { --18 shift = 5, mask = 7, [0] = { shift = 12, mask = 15, [15] = "usad8NMS", _ = "usada8NMSD", }, }, false, { --1a shift = 5, mask = 3, [2] = "sbfxDMvw", }, { --1b shift = 5, mask = 3, [2] = "sbfxDMvw", }, { --1c shift = 5, mask = 3, [0] = { shift = 0, mask = 15, [15] = "bfcDvX", _ = "bfiDMvX", }, }, { --1d shift = 5, mask = 3, [0] = { shift = 0, mask = 15, [15] = "bfcDvX", _ = "bfiDMvX", }, }, { --1e shift = 5, mask = 3, [2] = "ubfxDMvw", }, { --1f shift = 5, mask = 3, [2] = "ubfxDMvw", }, } local map_load = { shift = 21, mask = 9, { shift = 20, mask = 5, [0] = "strtDL", "ldrtDL", [4] = "strbtDL", [5] = "ldrbtDL", }, _ = { shift = 20, mask = 5, [0] = "strDL", "ldrDL", [4] = "strbDL", [5] = "ldrbDL", } } local map_load1 = { shift = 4, mask = 1, [0] = map_load, map_media, } local map_loadm = { shift = 20, mask = 1, [0] = { shift = 23, mask = 3, [0] = "stmdaNR", "stmNR", { shift = 16, mask = 63, [45] = "pushR", _ = "stmdbNR", }, "stmibNR", }, { shift = 23, mask = 3, [0] = "ldmdaNR", { shift = 16, mask = 63, [61] = "popR", _ = "ldmNR", }, "ldmdbNR", "ldmibNR", }, } local map_data = { shift = 21, mask = 15, [0] = "andDNPs", "eorDNPs", "subDNPs", "rsbDNPs", "addDNPs", "adcDNPs", "sbcDNPs", "rscDNPs", "tstNP", "teqNP", "cmpNP", "cmnNP", "orrDNPs", "movDPs", "bicDNPs", "mvnDPs", } local map_mul = { shift = 21, mask = 7, [0] = "mulNMSs", "mlaNMSDs", "umaalDNMS", "mlsDNMS", "umullDNMSs", "umlalDNMSs", "smullDNMSs", "smlalDNMSs", } local map_sync = { shift = 20, mask = 15, -- NYI: brackets around N. R(D+1) for ldrexd/strexd. [0] = "swpDMN", false, false, false, "swpbDMN", false, false, false, "strexDMN", "ldrexDN", "strexdDN", "ldrexdDN", "strexbDMN", "ldrexbDN", "strexhDN", "ldrexhDN", } local map_mulh = { shift = 21, mask = 3, [0] = { shift = 5, mask = 3, [0] = "smlabbNMSD", "smlatbNMSD", "smlabtNMSD", "smlattNMSD", }, { shift = 5, mask = 3, [0] = "smlawbNMSD", "smulwbNMS", "smlawtNMSD", "smulwtNMS", }, { shift = 5, mask = 3, [0] = "smlalbbDNMS", "smlaltbDNMS", "smlalbtDNMS", "smlalttDNMS", }, { shift = 5, mask = 3, [0] = "smulbbNMS", "smultbNMS", "smulbtNMS", "smulttNMS", }, } local map_misc = { shift = 4, mask = 7, -- NYI: decode PSR bits of msr. [0] = { shift = 21, mask = 1, [0] = "mrsD", "msrM", }, { shift = 21, mask = 3, "bxM", false, "clzDM", }, { shift = 21, mask = 3, "bxjM", }, { shift = 21, mask = 3, "blxM", }, false, { shift = 21, mask = 3, [0] = "qaddDMN", "qsubDMN", "qdaddDMN", "qdsubDMN", }, false, { shift = 21, mask = 3, "bkptK", }, } local map_datar = { shift = 4, mask = 9, [9] = { shift = 5, mask = 3, [0] = { shift = 24, mask = 1, [0] = map_mul, map_sync, }, { shift = 20, mask = 1, [0] = "strhDL", "ldrhDL", }, { shift = 20, mask = 1, [0] = "ldrdDL", "ldrsbDL", }, { shift = 20, mask = 1, [0] = "strdDL", "ldrshDL", }, }, _ = { shift = 20, mask = 25, [16] = { shift = 7, mask = 1, [0] = map_misc, map_mulh, }, _ = { shift = 0, mask = 0xffffffff, [bor(0xe1a00000)] = "nop", _ = map_data, } }, } local map_datai = { shift = 20, mask = 31, -- NYI: decode PSR bits of msr. Decode imm12. [16] = "movwDW", [20] = "movtDW", [18] = { shift = 0, mask = 0xf00ff, [0] = "nopv6", _ = "msrNW", }, [22] = "msrNW", _ = map_data, } local map_branch = { shift = 24, mask = 1, [0] = "bB", "blB" } local map_condins = { [0] = map_datar, map_datai, map_load, map_load1, map_loadm, map_branch, map_loadc, map_datac } -- NYI: setend. local map_uncondins = { [0] = false, map_simddata, map_simdload, map_preload, false, "blxB", map_loadcu, map_datacu, } ------------------------------------------------------------------------------ local map_gpr = { [0] = "r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "sp", "lr", "pc", } local map_cond = { [0] = "eq", "ne", "hs", "lo", "mi", "pl", "vs", "vc", "hi", "ls", "ge", "lt", "gt", "le", "al", } local map_shift = { [0] = "lsl", "lsr", "asr", "ror", } ------------------------------------------------------------------------------ -- Output a nicely formatted line with an opcode and operands. local function putop(ctx, text, operands) local pos = ctx.pos local extra = "" if ctx.rel then local sym = ctx.symtab[ctx.rel] if sym then extra = "\t->"..sym elseif band(ctx.op, 0x0e000000) ~= 0x0a000000 then extra = "\t; 0x"..tohex(ctx.rel) end end if ctx.hexdump > 0 then ctx.out(format("%08x %s %-5s %s%s\n", ctx.addr+pos, tohex(ctx.op), text, concat(operands, ", "), extra)) else ctx.out(format("%08x %-5s %s%s\n", ctx.addr+pos, text, concat(operands, ", "), extra)) end ctx.pos = pos + 4 end -- Fallback for unknown opcodes. local function unknown(ctx) return putop(ctx, ".long", { "0x"..tohex(ctx.op) }) end -- Format operand 2 of load/store opcodes. local function fmtload(ctx, op, pos) local base = map_gpr[band(rshift(op, 16), 15)] local x, ofs local ext = (band(op, 0x04000000) == 0) if not ext and band(op, 0x02000000) == 0 then ofs = band(op, 4095) if band(op, 0x00800000) == 0 then ofs = -ofs end if base == "pc" then ctx.rel = ctx.addr + pos + 8 + ofs end ofs = "#"..ofs elseif ext and band(op, 0x00400000) ~= 0 then ofs = band(op, 15) + band(rshift(op, 4), 0xf0) if band(op, 0x00800000) == 0 then ofs = -ofs end if base == "pc" then ctx.rel = ctx.addr + pos + 8 + ofs end ofs = "#"..ofs else ofs = map_gpr[band(op, 15)] if ext or band(op, 0xfe0) == 0 then elseif band(op, 0xfe0) == 0x60 then ofs = format("%s, rrx", ofs) else local sh = band(rshift(op, 7), 31) if sh == 0 then sh = 32 end ofs = format("%s, %s #%d", ofs, map_shift[band(rshift(op, 5), 3)], sh) end if band(op, 0x00800000) == 0 then ofs = "-"..ofs end end if ofs == "#0" then x = format("[%s]", base) elseif band(op, 0x01000000) == 0 then x = format("[%s], %s", base, ofs) else x = format("[%s, %s]", base, ofs) end if band(op, 0x01200000) == 0x01200000 then x = x.."!" end return x end -- Format operand 2 of vector load/store opcodes. local function fmtvload(ctx, op, pos) local base = map_gpr[band(rshift(op, 16), 15)] local ofs = band(op, 255)*4 if band(op, 0x00800000) == 0 then ofs = -ofs end if base == "pc" then ctx.rel = ctx.addr + pos + 8 + ofs end if ofs == 0 then return format("[%s]", base) else return format("[%s, #%d]", base, ofs) end end local function fmtvr(op, vr, sh0, sh1) if vr == "s" then return format("s%d", 2*band(rshift(op, sh0), 15)+band(rshift(op, sh1), 1)) else return format("d%d", band(rshift(op, sh0), 15)+band(rshift(op, sh1-4), 16)) end end -- Disassemble a single instruction. local function disass_ins(ctx) local pos = ctx.pos local b0, b1, b2, b3 = byte(ctx.code, pos+1, pos+4) local op = bor(lshift(b3, 24), lshift(b2, 16), lshift(b1, 8), b0) local operands = {} local suffix = "" local last, name, pat local vr ctx.op = op ctx.rel = nil local cond = rshift(op, 28) local opat if cond == 15 then opat = map_uncondins[band(rshift(op, 25), 7)] else if cond ~= 14 then suffix = map_cond[cond] end opat = map_condins[band(rshift(op, 25), 7)] end while type(opat) ~= "string" do if not opat then return unknown(ctx) end opat = opat[band(rshift(op, opat.shift), opat.mask)] or opat._ end name, pat = match(opat, "^([a-z0-9]*)(.*)") if sub(pat, 1, 1) == "." then local s2, p2 = match(pat, "^([a-z0-9.]*)(.*)") suffix = suffix..s2 pat = p2 end for p in gmatch(pat, ".") do local x = nil if p == "D" then x = map_gpr[band(rshift(op, 12), 15)] elseif p == "N" then x = map_gpr[band(rshift(op, 16), 15)] elseif p == "S" then x = map_gpr[band(rshift(op, 8), 15)] elseif p == "M" then x = map_gpr[band(op, 15)] elseif p == "d" then x = fmtvr(op, vr, 12, 22) elseif p == "n" then x = fmtvr(op, vr, 16, 7) elseif p == "m" then x = fmtvr(op, vr, 0, 5) elseif p == "P" then if band(op, 0x02000000) ~= 0 then x = ror(band(op, 255), 2*band(rshift(op, 8), 15)) else x = map_gpr[band(op, 15)] if band(op, 0xff0) ~= 0 then operands[#operands+1] = x local s = map_shift[band(rshift(op, 5), 3)] local r = nil if band(op, 0xf90) == 0 then if s == "ror" then s = "rrx" else r = "#32" end elseif band(op, 0x10) == 0 then r = "#"..band(rshift(op, 7), 31) else r = map_gpr[band(rshift(op, 8), 15)] end if name == "mov" then name = s; x = r elseif r then x = format("%s %s", s, r) else x = s end end end elseif p == "L" then x = fmtload(ctx, op, pos) elseif p == "l" then x = fmtvload(ctx, op, pos) elseif p == "B" then local addr = ctx.addr + pos + 8 + arshift(lshift(op, 8), 6) if cond == 15 then addr = addr + band(rshift(op, 23), 2) end ctx.rel = addr x = "0x"..tohex(addr) elseif p == "F" then vr = "s" elseif p == "G" then vr = "d" elseif p == "." then suffix = suffix..(vr == "s" and ".f32" or ".f64") elseif p == "R" then if band(op, 0x00200000) ~= 0 and #operands == 1 then operands[1] = operands[1].."!" end local t = {} for i=0,15 do if band(rshift(op, i), 1) == 1 then t[#t+1] = map_gpr[i] end end x = "{"..concat(t, ", ").."}" elseif p == "r" then if band(op, 0x00200000) ~= 0 and #operands == 2 then operands[1] = operands[1].."!" end local s = tonumber(sub(last, 2)) local n = band(op, 255) if vr == "d" then n = rshift(n, 1) end operands[#operands] = format("{%s-%s%d}", last, vr, s+n-1) elseif p == "W" then x = band(op, 0x0fff) + band(rshift(op, 4), 0xf000) elseif p == "T" then x = "#0x"..tohex(band(op, 0x00ffffff), 6) elseif p == "U" then x = band(rshift(op, 7), 31) if x == 0 then x = nil end elseif p == "u" then x = band(rshift(op, 7), 31) if band(op, 0x40) == 0 then if x == 0 then x = nil else x = "lsl #"..x end else if x == 0 then x = "asr #32" else x = "asr #"..x end end elseif p == "v" then x = band(rshift(op, 7), 31) elseif p == "w" then x = band(rshift(op, 16), 31) elseif p == "x" then x = band(rshift(op, 16), 31) + 1 elseif p == "X" then x = band(rshift(op, 16), 31) - last + 1 elseif p == "Y" then x = band(rshift(op, 12), 0xf0) + band(op, 0x0f) elseif p == "K" then x = "#0x"..tohex(band(rshift(op, 4), 0x0000fff0) + band(op, 15), 4) elseif p == "s" then if band(op, 0x00100000) ~= 0 then suffix = "s"..suffix end else assert(false) end if x then last = x if type(x) == "number" then x = "#"..x end operands[#operands+1] = x end end return putop(ctx, name..suffix, operands) end ------------------------------------------------------------------------------ -- Disassemble a block of code. local function disass_block(ctx, ofs, len) if not ofs then ofs = 0 end local stop = len and ofs+len or #ctx.code ctx.pos = ofs ctx.rel = nil while ctx.pos < stop do disass_ins(ctx) end end -- Extended API: create a disassembler context. Then call ctx:disass(ofs, len). local function create(code, addr, out) local ctx = {} ctx.code = code ctx.addr = addr or 0 ctx.out = out or io.write ctx.symtab = {} ctx.disass = disass_block ctx.hexdump = 8 return ctx end -- Simple API: disassemble code (a string) at address and output via out. local function disass(code, addr, out) create(code, addr, out):disass() end -- Return register name for RID. local function regname(r) if r < 16 then return map_gpr[r] end return "d"..(r-16) end -- Public module functions. return { create = create, disass = disass, regname = regname }
xLua/build/luajit-2.1.0b3/src/jit/dis_arm.lua/0
{ "file_path": "xLua/build/luajit-2.1.0b3/src/jit/dis_arm.lua", "repo_id": "xLua", "token_count": 9531 }
2,045
/* ** $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 <stddef.h> #include <stdio.h> #include "lua.h" /* 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 (luaL_openlib) (lua_State *L, const char *libname, const luaL_Reg *l, int nup); LUALIB_API void (luaL_register) (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 int (luaL_newmetatable) (lua_State *L, const char *tname); 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[]); /* pre-defined references */ #define LUA_NOREF (-2) #define LUA_REFNIL (-1) LUALIB_API int (luaL_ref) (lua_State *L, int t); LUALIB_API void (luaL_unref) (lua_State *L, int t, int ref); LUALIB_API int (luaL_loadfile) (lua_State *L, const char *filename); 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); /* From Lua 5.2. */ LUALIB_API int luaL_fileresult(lua_State *L, int stat, const char *fname); LUALIB_API int luaL_execresult(lua_State *L, int stat); LUALIB_API int (luaL_loadfilex) (lua_State *L, const char *filename, const char *mode); LUALIB_API int (luaL_loadbufferx) (lua_State *L, const char *buff, size_t sz, const char *name, const char *mode); LUALIB_API void luaL_traceback (lua_State *L, lua_State *L1, const char *msg, int level); LUALIB_API void (luaL_setfuncs) (lua_State *L, const luaL_Reg *l, int nup); LUALIB_API void (luaL_pushmodule) (lua_State *L, const char *modname, int sizehint); LUALIB_API void *(luaL_testudata) (lua_State *L, int ud, const char *tname); LUALIB_API void (luaL_setmetatable) (lua_State *L, const char *tname); /* ** =============================================================== ** 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))) #define luaL_dofile(L, fn) \ (luaL_loadfile(L, fn) || lua_pcall(L, 0, LUA_MULTRET, 0)) #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))) /* From Lua 5.2. */ #define luaL_newlibtable(L, l) \ lua_createtable(L, 0, sizeof(l)/sizeof((l)[0]) - 1) #define luaL_newlib(L, l) (luaL_newlibtable(L, l), luaL_setfuncs(L, l, 0)) /* ** {====================================================== ** 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); /* }====================================================== */ #endif
xLua/build/luajit-2.1.0b3/src/lauxlib.h/0
{ "file_path": "xLua/build/luajit-2.1.0b3/src/lauxlib.h", "repo_id": "xLua", "token_count": 2753 }
2,046
/* ** Bundled memory allocator. ** ** Beware: this is a HEAVILY CUSTOMIZED version of dlmalloc. ** The original bears the following remark: ** ** This is a version (aka dlmalloc) of malloc/free/realloc written by ** Doug Lea and released to the public domain, as explained at ** https://creativecommons.org/licenses/publicdomain. ** ** * Version pre-2.8.4 Wed Mar 29 19:46:29 2006 (dl at gee) ** ** No additional copyright is claimed over the customizations. ** Please do NOT bother the original author about this version here! ** ** If you want to use dlmalloc in another project, you should get ** the original from: ftp://gee.cs.oswego.edu/pub/misc/ ** For thread-safe derivatives, take a look at: ** - ptmalloc: https://www.malloc.de/ ** - nedmalloc: https://www.nedprod.com/programs/portable/nedmalloc/ */ #define lj_alloc_c #define LUA_CORE /* To get the mremap prototype. Must be defined before any system includes. */ #if defined(__linux__) && !defined(_GNU_SOURCE) #define _GNU_SOURCE #endif #include "lj_def.h" #include "lj_arch.h" #include "lj_alloc.h" #include "lj_prng.h" #ifndef LUAJIT_USE_SYSMALLOC #define MAX_SIZE_T (~(size_t)0) #define MALLOC_ALIGNMENT ((size_t)8U) #define DEFAULT_GRANULARITY ((size_t)128U * (size_t)1024U) #define DEFAULT_TRIM_THRESHOLD ((size_t)2U * (size_t)1024U * (size_t)1024U) #define DEFAULT_MMAP_THRESHOLD ((size_t)128U * (size_t)1024U) #define MAX_RELEASE_CHECK_RATE 255 /* ------------------- size_t and alignment properties -------------------- */ /* The byte and bit size of a size_t */ #define SIZE_T_SIZE (sizeof(size_t)) #define SIZE_T_BITSIZE (sizeof(size_t) << 3) /* Some constants coerced to size_t */ /* Annoying but necessary to avoid errors on some platforms */ #define SIZE_T_ZERO ((size_t)0) #define SIZE_T_ONE ((size_t)1) #define SIZE_T_TWO ((size_t)2) #define TWO_SIZE_T_SIZES (SIZE_T_SIZE<<1) #define FOUR_SIZE_T_SIZES (SIZE_T_SIZE<<2) #define SIX_SIZE_T_SIZES (FOUR_SIZE_T_SIZES+TWO_SIZE_T_SIZES) /* The bit mask value corresponding to MALLOC_ALIGNMENT */ #define CHUNK_ALIGN_MASK (MALLOC_ALIGNMENT - SIZE_T_ONE) /* the number of bytes to offset an address to align it */ #define align_offset(A)\ ((((size_t)(A) & CHUNK_ALIGN_MASK) == 0)? 0 :\ ((MALLOC_ALIGNMENT - ((size_t)(A) & CHUNK_ALIGN_MASK)) & CHUNK_ALIGN_MASK)) /* -------------------------- MMAP support ------------------------------- */ #define MFAIL ((void *)(MAX_SIZE_T)) #define CMFAIL ((char *)(MFAIL)) /* defined for convenience */ #define IS_DIRECT_BIT (SIZE_T_ONE) /* Determine system-specific block allocation method. */ #if LJ_TARGET_WINDOWS #define WIN32_LEAN_AND_MEAN #include <windows.h> #define LJ_ALLOC_VIRTUALALLOC 1 #if LJ_64 && !LJ_GC64 #define LJ_ALLOC_NTAVM 1 #endif #else #include <errno.h> /* If this include fails, then rebuild with: -DLUAJIT_USE_SYSMALLOC */ #include <sys/mman.h> #define LJ_ALLOC_MMAP 1 #if LJ_64 #define LJ_ALLOC_MMAP_PROBE 1 #if LJ_GC64 #define LJ_ALLOC_MBITS 47 /* 128 TB in LJ_GC64 mode. */ #elif LJ_TARGET_X64 && LJ_HASJIT /* Due to limitations in the x64 compiler backend. */ #define LJ_ALLOC_MBITS 31 /* 2 GB on x64 with !LJ_GC64. */ #else #define LJ_ALLOC_MBITS 32 /* 4 GB on other archs with !LJ_GC64. */ #endif #endif #if LJ_64 && !LJ_GC64 && defined(MAP_32BIT) #define LJ_ALLOC_MMAP32 1 #endif #if LJ_TARGET_LINUX #define LJ_ALLOC_MREMAP 1 #endif #endif #if LJ_ALLOC_VIRTUALALLOC #if LJ_ALLOC_NTAVM /* Undocumented, but hey, that's what we all love so much about Windows. */ typedef long (*PNTAVM)(HANDLE handle, void **addr, ULONG_PTR zbits, size_t *size, ULONG alloctype, ULONG prot); static PNTAVM ntavm; /* Number of top bits of the lower 32 bits of an address that must be zero. ** Apparently 0 gives us full 64 bit addresses and 1 gives us the lower 2GB. */ #define NTAVM_ZEROBITS 1 static void init_mmap(void) { ntavm = (PNTAVM)GetProcAddress(GetModuleHandleA("ntdll.dll"), "NtAllocateVirtualMemory"); } #define INIT_MMAP() init_mmap() /* Win64 32 bit MMAP via NtAllocateVirtualMemory. */ static void *mmap_plain(size_t size) { DWORD olderr = GetLastError(); void *ptr = NULL; long st = ntavm(INVALID_HANDLE_VALUE, &ptr, NTAVM_ZEROBITS, &size, MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE); SetLastError(olderr); return st == 0 ? ptr : MFAIL; } /* For direct MMAP, use MEM_TOP_DOWN to minimize interference */ static void *direct_mmap(size_t size) { DWORD olderr = GetLastError(); void *ptr = NULL; long st = ntavm(INVALID_HANDLE_VALUE, &ptr, NTAVM_ZEROBITS, &size, MEM_RESERVE|MEM_COMMIT|MEM_TOP_DOWN, PAGE_READWRITE); SetLastError(olderr); return st == 0 ? ptr : MFAIL; } #else /* Win32 MMAP via VirtualAlloc */ static void *mmap_plain(size_t size) { DWORD olderr = GetLastError(); void *ptr = LJ_WIN_VALLOC(0, size, MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE); SetLastError(olderr); return ptr ? ptr : MFAIL; } /* For direct MMAP, use MEM_TOP_DOWN to minimize interference */ static void *direct_mmap(size_t size) { DWORD olderr = GetLastError(); void *ptr = LJ_WIN_VALLOC(0, size, MEM_RESERVE|MEM_COMMIT|MEM_TOP_DOWN, PAGE_READWRITE); SetLastError(olderr); return ptr ? ptr : MFAIL; } #endif #define CALL_MMAP(prng, size) mmap_plain(size) #define DIRECT_MMAP(prng, size) direct_mmap(size) /* This function supports releasing coalesed segments */ static int CALL_MUNMAP(void *ptr, size_t size) { DWORD olderr = GetLastError(); MEMORY_BASIC_INFORMATION minfo; char *cptr = (char *)ptr; while (size) { if (VirtualQuery(cptr, &minfo, sizeof(minfo)) == 0) return -1; if (minfo.BaseAddress != cptr || minfo.AllocationBase != cptr || minfo.State != MEM_COMMIT || minfo.RegionSize > size) return -1; if (VirtualFree(cptr, 0, MEM_RELEASE) == 0) return -1; cptr += minfo.RegionSize; size -= minfo.RegionSize; } SetLastError(olderr); return 0; } #elif LJ_ALLOC_MMAP #define MMAP_PROT (PROT_READ|PROT_WRITE) #if !defined(MAP_ANONYMOUS) && defined(MAP_ANON) #define MAP_ANONYMOUS MAP_ANON #endif #define MMAP_FLAGS (MAP_PRIVATE|MAP_ANONYMOUS) #if LJ_ALLOC_MMAP_PROBE #ifdef MAP_TRYFIXED #define MMAP_FLAGS_PROBE (MMAP_FLAGS|MAP_TRYFIXED) #else #define MMAP_FLAGS_PROBE MMAP_FLAGS #endif #define LJ_ALLOC_MMAP_PROBE_MAX 30 #define LJ_ALLOC_MMAP_PROBE_LINEAR 5 #define LJ_ALLOC_MMAP_PROBE_LOWER ((uintptr_t)0x4000) static void *mmap_probe(PRNGState *rs, size_t size) { /* Hint for next allocation. Doesn't need to be thread-safe. */ static uintptr_t hint_addr = 0; int olderr = errno; int retry; for (retry = 0; retry < LJ_ALLOC_MMAP_PROBE_MAX; retry++) { void *p = mmap((void *)hint_addr, size, MMAP_PROT, MMAP_FLAGS_PROBE, -1, 0); uintptr_t addr = (uintptr_t)p; if ((addr >> LJ_ALLOC_MBITS) == 0 && addr >= LJ_ALLOC_MMAP_PROBE_LOWER && ((addr + size) >> LJ_ALLOC_MBITS) == 0) { /* We got a suitable address. Bump the hint address. */ hint_addr = addr + size; errno = olderr; return p; } if (p != MFAIL) { munmap(p, size); } else if (errno == ENOMEM) { return MFAIL; } if (hint_addr) { /* First, try linear probing. */ if (retry < LJ_ALLOC_MMAP_PROBE_LINEAR) { hint_addr += 0x1000000; if (((hint_addr + size) >> LJ_ALLOC_MBITS) != 0) hint_addr = 0; continue; } else if (retry == LJ_ALLOC_MMAP_PROBE_LINEAR) { /* Next, try a no-hint probe to get back an ASLR address. */ hint_addr = 0; continue; } } /* Finally, try pseudo-random probing. */ do { hint_addr = lj_prng_u64(rs) & (((uintptr_t)1<<LJ_ALLOC_MBITS)-LJ_PAGESIZE); } while (hint_addr < LJ_ALLOC_MMAP_PROBE_LOWER); } errno = olderr; return MFAIL; } #endif #if LJ_ALLOC_MMAP32 #if LJ_TARGET_SOLARIS #define LJ_ALLOC_MMAP32_START ((uintptr_t)0x1000) #else #define LJ_ALLOC_MMAP32_START ((uintptr_t)0) #endif #if LJ_ALLOC_MMAP_PROBE static void *mmap_map32(PRNGState *rs, size_t size) #else static void *mmap_map32(size_t size) #endif { #if LJ_ALLOC_MMAP_PROBE static int fallback = 0; if (fallback) return mmap_probe(rs, size); #endif { int olderr = errno; void *ptr = mmap((void *)LJ_ALLOC_MMAP32_START, size, MMAP_PROT, MAP_32BIT|MMAP_FLAGS, -1, 0); errno = olderr; /* This only allows 1GB on Linux. So fallback to probing to get 2GB. */ #if LJ_ALLOC_MMAP_PROBE if (ptr == MFAIL) { fallback = 1; return mmap_probe(rs, size); } #endif return ptr; } } #endif #if LJ_ALLOC_MMAP32 #if LJ_ALLOC_MMAP_PROBE #define CALL_MMAP(prng, size) mmap_map32(prng, size) #else #define CALL_MMAP(prng, size) mmap_map32(size) #endif #elif LJ_ALLOC_MMAP_PROBE #define CALL_MMAP(prng, size) mmap_probe(prng, size) #else static void *mmap_plain(size_t size) { int olderr = errno; void *ptr = mmap(NULL, size, MMAP_PROT, MMAP_FLAGS, -1, 0); errno = olderr; return ptr; } #define CALL_MMAP(prng, size) mmap_plain(size) #endif #if LJ_64 && !LJ_GC64 && ((defined(__FreeBSD__) && __FreeBSD__ < 10) || defined(__FreeBSD_kernel__)) && !LJ_TARGET_PS4 #include <sys/resource.h> static void init_mmap(void) { struct rlimit rlim; rlim.rlim_cur = rlim.rlim_max = 0x10000; setrlimit(RLIMIT_DATA, &rlim); /* Ignore result. May fail later. */ } #define INIT_MMAP() init_mmap() #endif static int CALL_MUNMAP(void *ptr, size_t size) { int olderr = errno; int ret = munmap(ptr, size); errno = olderr; return ret; } #if LJ_ALLOC_MREMAP /* Need to define _GNU_SOURCE to get the mremap prototype. */ static void *CALL_MREMAP_(void *ptr, size_t osz, size_t nsz, int flags) { int olderr = errno; ptr = mremap(ptr, osz, nsz, flags); errno = olderr; return ptr; } #define CALL_MREMAP(addr, osz, nsz, mv) CALL_MREMAP_((addr), (osz), (nsz), (mv)) #define CALL_MREMAP_NOMOVE 0 #define CALL_MREMAP_MAYMOVE 1 #if LJ_64 && (!LJ_GC64 || LJ_TARGET_ARM64) #define CALL_MREMAP_MV CALL_MREMAP_NOMOVE #else #define CALL_MREMAP_MV CALL_MREMAP_MAYMOVE #endif #endif #endif #ifndef INIT_MMAP #define INIT_MMAP() ((void)0) #endif #ifndef DIRECT_MMAP #define DIRECT_MMAP(prng, s) CALL_MMAP(prng, s) #endif #ifndef CALL_MREMAP #define CALL_MREMAP(addr, osz, nsz, mv) ((void)osz, MFAIL) #endif /* ----------------------- Chunk representations ------------------------ */ struct malloc_chunk { size_t prev_foot; /* Size of previous chunk (if free). */ size_t head; /* Size and inuse bits. */ struct malloc_chunk *fd; /* double links -- used only if free. */ struct malloc_chunk *bk; }; typedef struct malloc_chunk mchunk; typedef struct malloc_chunk *mchunkptr; typedef struct malloc_chunk *sbinptr; /* The type of bins of chunks */ typedef size_t bindex_t; /* Described below */ typedef unsigned int binmap_t; /* Described below */ typedef unsigned int flag_t; /* The type of various bit flag sets */ /* ------------------- Chunks sizes and alignments ----------------------- */ #define MCHUNK_SIZE (sizeof(mchunk)) #define CHUNK_OVERHEAD (SIZE_T_SIZE) /* Direct chunks need a second word of overhead ... */ #define DIRECT_CHUNK_OVERHEAD (TWO_SIZE_T_SIZES) /* ... and additional padding for fake next-chunk at foot */ #define DIRECT_FOOT_PAD (FOUR_SIZE_T_SIZES) /* The smallest size we can malloc is an aligned minimal chunk */ #define MIN_CHUNK_SIZE\ ((MCHUNK_SIZE + CHUNK_ALIGN_MASK) & ~CHUNK_ALIGN_MASK) /* conversion from malloc headers to user pointers, and back */ #define chunk2mem(p) ((void *)((char *)(p) + TWO_SIZE_T_SIZES)) #define mem2chunk(mem) ((mchunkptr)((char *)(mem) - TWO_SIZE_T_SIZES)) /* chunk associated with aligned address A */ #define align_as_chunk(A) (mchunkptr)((A) + align_offset(chunk2mem(A))) /* Bounds on request (not chunk) sizes. */ #define MAX_REQUEST ((~MIN_CHUNK_SIZE+1) << 2) #define MIN_REQUEST (MIN_CHUNK_SIZE - CHUNK_OVERHEAD - SIZE_T_ONE) /* pad request bytes into a usable size */ #define pad_request(req) \ (((req) + CHUNK_OVERHEAD + CHUNK_ALIGN_MASK) & ~CHUNK_ALIGN_MASK) /* pad request, checking for minimum (but not maximum) */ #define request2size(req) \ (((req) < MIN_REQUEST)? MIN_CHUNK_SIZE : pad_request(req)) /* ------------------ Operations on head and foot fields ----------------- */ #define PINUSE_BIT (SIZE_T_ONE) #define CINUSE_BIT (SIZE_T_TWO) #define INUSE_BITS (PINUSE_BIT|CINUSE_BIT) /* Head value for fenceposts */ #define FENCEPOST_HEAD (INUSE_BITS|SIZE_T_SIZE) /* extraction of fields from head words */ #define cinuse(p) ((p)->head & CINUSE_BIT) #define pinuse(p) ((p)->head & PINUSE_BIT) #define chunksize(p) ((p)->head & ~(INUSE_BITS)) #define clear_pinuse(p) ((p)->head &= ~PINUSE_BIT) #define clear_cinuse(p) ((p)->head &= ~CINUSE_BIT) /* Treat space at ptr +/- offset as a chunk */ #define chunk_plus_offset(p, s) ((mchunkptr)(((char *)(p)) + (s))) #define chunk_minus_offset(p, s) ((mchunkptr)(((char *)(p)) - (s))) /* Ptr to next or previous physical malloc_chunk. */ #define next_chunk(p) ((mchunkptr)(((char *)(p)) + ((p)->head & ~INUSE_BITS))) #define prev_chunk(p) ((mchunkptr)(((char *)(p)) - ((p)->prev_foot) )) /* extract next chunk's pinuse bit */ #define next_pinuse(p) ((next_chunk(p)->head) & PINUSE_BIT) /* Get/set size at footer */ #define get_foot(p, s) (((mchunkptr)((char *)(p) + (s)))->prev_foot) #define set_foot(p, s) (((mchunkptr)((char *)(p) + (s)))->prev_foot = (s)) /* Set size, pinuse bit, and foot */ #define set_size_and_pinuse_of_free_chunk(p, s)\ ((p)->head = (s|PINUSE_BIT), set_foot(p, s)) /* Set size, pinuse bit, foot, and clear next pinuse */ #define set_free_with_pinuse(p, s, n)\ (clear_pinuse(n), set_size_and_pinuse_of_free_chunk(p, s)) #define is_direct(p)\ (!((p)->head & PINUSE_BIT) && ((p)->prev_foot & IS_DIRECT_BIT)) /* Get the internal overhead associated with chunk p */ #define overhead_for(p)\ (is_direct(p)? DIRECT_CHUNK_OVERHEAD : CHUNK_OVERHEAD) /* ---------------------- Overlaid data structures ----------------------- */ struct malloc_tree_chunk { /* The first four fields must be compatible with malloc_chunk */ size_t prev_foot; size_t head; struct malloc_tree_chunk *fd; struct malloc_tree_chunk *bk; struct malloc_tree_chunk *child[2]; struct malloc_tree_chunk *parent; bindex_t index; }; typedef struct malloc_tree_chunk tchunk; typedef struct malloc_tree_chunk *tchunkptr; typedef struct malloc_tree_chunk *tbinptr; /* The type of bins of trees */ /* A little helper macro for trees */ #define leftmost_child(t) ((t)->child[0] != 0? (t)->child[0] : (t)->child[1]) /* ----------------------------- Segments -------------------------------- */ struct malloc_segment { char *base; /* base address */ size_t size; /* allocated size */ struct malloc_segment *next; /* ptr to next segment */ }; typedef struct malloc_segment msegment; typedef struct malloc_segment *msegmentptr; /* ---------------------------- malloc_state ----------------------------- */ /* Bin types, widths and sizes */ #define NSMALLBINS (32U) #define NTREEBINS (32U) #define SMALLBIN_SHIFT (3U) #define SMALLBIN_WIDTH (SIZE_T_ONE << SMALLBIN_SHIFT) #define TREEBIN_SHIFT (8U) #define MIN_LARGE_SIZE (SIZE_T_ONE << TREEBIN_SHIFT) #define MAX_SMALL_SIZE (MIN_LARGE_SIZE - SIZE_T_ONE) #define MAX_SMALL_REQUEST (MAX_SMALL_SIZE - CHUNK_ALIGN_MASK - CHUNK_OVERHEAD) struct malloc_state { binmap_t smallmap; binmap_t treemap; size_t dvsize; size_t topsize; mchunkptr dv; mchunkptr top; size_t trim_check; size_t release_checks; mchunkptr smallbins[(NSMALLBINS+1)*2]; tbinptr treebins[NTREEBINS]; msegment seg; PRNGState *prng; }; typedef struct malloc_state *mstate; #define is_initialized(M) ((M)->top != 0) /* -------------------------- system alloc setup ------------------------- */ /* page-align a size */ #define page_align(S)\ (((S) + (LJ_PAGESIZE - SIZE_T_ONE)) & ~(LJ_PAGESIZE - SIZE_T_ONE)) /* granularity-align a size */ #define granularity_align(S)\ (((S) + (DEFAULT_GRANULARITY - SIZE_T_ONE))\ & ~(DEFAULT_GRANULARITY - SIZE_T_ONE)) #if LJ_TARGET_WINDOWS #define mmap_align(S) granularity_align(S) #else #define mmap_align(S) page_align(S) #endif /* True if segment S holds address A */ #define segment_holds(S, A)\ ((char *)(A) >= S->base && (char *)(A) < S->base + S->size) /* Return segment holding given address */ static msegmentptr segment_holding(mstate m, char *addr) { msegmentptr sp = &m->seg; for (;;) { if (addr >= sp->base && addr < sp->base + sp->size) return sp; if ((sp = sp->next) == 0) return 0; } } /* Return true if segment contains a segment link */ static int has_segment_link(mstate m, msegmentptr ss) { msegmentptr sp = &m->seg; for (;;) { if ((char *)sp >= ss->base && (char *)sp < ss->base + ss->size) return 1; if ((sp = sp->next) == 0) return 0; } } /* TOP_FOOT_SIZE is padding at the end of a segment, including space that may be needed to place segment records and fenceposts when new noncontiguous segments are added. */ #define TOP_FOOT_SIZE\ (align_offset(TWO_SIZE_T_SIZES)+pad_request(sizeof(struct malloc_segment))+MIN_CHUNK_SIZE) /* ---------------------------- Indexing Bins ---------------------------- */ #define is_small(s) (((s) >> SMALLBIN_SHIFT) < NSMALLBINS) #define small_index(s) ((s) >> SMALLBIN_SHIFT) #define small_index2size(i) ((i) << SMALLBIN_SHIFT) #define MIN_SMALL_INDEX (small_index(MIN_CHUNK_SIZE)) /* addressing by index. See above about smallbin repositioning */ #define smallbin_at(M, i) ((sbinptr)((char *)&((M)->smallbins[(i)<<1]))) #define treebin_at(M,i) (&((M)->treebins[i])) /* assign tree index for size S to variable I */ #define compute_tree_index(S, I)\ {\ unsigned int X = (unsigned int)(S >> TREEBIN_SHIFT);\ if (X == 0) {\ I = 0;\ } else if (X > 0xFFFF) {\ I = NTREEBINS-1;\ } else {\ unsigned int K = lj_fls(X);\ I = (bindex_t)((K << 1) + ((S >> (K + (TREEBIN_SHIFT-1)) & 1)));\ }\ } /* Bit representing maximum resolved size in a treebin at i */ #define bit_for_tree_index(i) \ (i == NTREEBINS-1)? (SIZE_T_BITSIZE-1) : (((i) >> 1) + TREEBIN_SHIFT - 2) /* Shift placing maximum resolved bit in a treebin at i as sign bit */ #define leftshift_for_tree_index(i) \ ((i == NTREEBINS-1)? 0 : \ ((SIZE_T_BITSIZE-SIZE_T_ONE) - (((i) >> 1) + TREEBIN_SHIFT - 2))) /* The size of the smallest chunk held in bin with index i */ #define minsize_for_tree_index(i) \ ((SIZE_T_ONE << (((i) >> 1) + TREEBIN_SHIFT)) | \ (((size_t)((i) & SIZE_T_ONE)) << (((i) >> 1) + TREEBIN_SHIFT - 1))) /* ------------------------ Operations on bin maps ----------------------- */ /* bit corresponding to given index */ #define idx2bit(i) ((binmap_t)(1) << (i)) /* Mark/Clear bits with given index */ #define mark_smallmap(M,i) ((M)->smallmap |= idx2bit(i)) #define clear_smallmap(M,i) ((M)->smallmap &= ~idx2bit(i)) #define smallmap_is_marked(M,i) ((M)->smallmap & idx2bit(i)) #define mark_treemap(M,i) ((M)->treemap |= idx2bit(i)) #define clear_treemap(M,i) ((M)->treemap &= ~idx2bit(i)) #define treemap_is_marked(M,i) ((M)->treemap & idx2bit(i)) /* mask with all bits to left of least bit of x on */ #define left_bits(x) ((x<<1) | (~(x<<1)+1)) /* Set cinuse bit and pinuse bit of next chunk */ #define set_inuse(M,p,s)\ ((p)->head = (((p)->head & PINUSE_BIT)|s|CINUSE_BIT),\ ((mchunkptr)(((char *)(p)) + (s)))->head |= PINUSE_BIT) /* Set cinuse and pinuse of this chunk and pinuse of next chunk */ #define set_inuse_and_pinuse(M,p,s)\ ((p)->head = (s|PINUSE_BIT|CINUSE_BIT),\ ((mchunkptr)(((char *)(p)) + (s)))->head |= PINUSE_BIT) /* Set size, cinuse and pinuse bit of this chunk */ #define set_size_and_pinuse_of_inuse_chunk(M, p, s)\ ((p)->head = (s|PINUSE_BIT|CINUSE_BIT)) /* ----------------------- Operations on smallbins ----------------------- */ /* Link a free chunk into a smallbin */ #define insert_small_chunk(M, P, S) {\ bindex_t I = small_index(S);\ mchunkptr B = smallbin_at(M, I);\ mchunkptr F = B;\ if (!smallmap_is_marked(M, I))\ mark_smallmap(M, I);\ else\ F = B->fd;\ B->fd = P;\ F->bk = P;\ P->fd = F;\ P->bk = B;\ } /* Unlink a chunk from a smallbin */ #define unlink_small_chunk(M, P, S) {\ mchunkptr F = P->fd;\ mchunkptr B = P->bk;\ bindex_t I = small_index(S);\ if (F == B) {\ clear_smallmap(M, I);\ } else {\ F->bk = B;\ B->fd = F;\ }\ } /* Unlink the first chunk from a smallbin */ #define unlink_first_small_chunk(M, B, P, I) {\ mchunkptr F = P->fd;\ if (B == F) {\ clear_smallmap(M, I);\ } else {\ B->fd = F;\ F->bk = B;\ }\ } /* Replace dv node, binning the old one */ /* Used only when dvsize known to be small */ #define replace_dv(M, P, S) {\ size_t DVS = M->dvsize;\ if (DVS != 0) {\ mchunkptr DV = M->dv;\ insert_small_chunk(M, DV, DVS);\ }\ M->dvsize = S;\ M->dv = P;\ } /* ------------------------- Operations on trees ------------------------- */ /* Insert chunk into tree */ #define insert_large_chunk(M, X, S) {\ tbinptr *H;\ bindex_t I;\ compute_tree_index(S, I);\ H = treebin_at(M, I);\ X->index = I;\ X->child[0] = X->child[1] = 0;\ if (!treemap_is_marked(M, I)) {\ mark_treemap(M, I);\ *H = X;\ X->parent = (tchunkptr)H;\ X->fd = X->bk = X;\ } else {\ tchunkptr T = *H;\ size_t K = S << leftshift_for_tree_index(I);\ for (;;) {\ if (chunksize(T) != S) {\ tchunkptr *C = &(T->child[(K >> (SIZE_T_BITSIZE-SIZE_T_ONE)) & 1]);\ K <<= 1;\ if (*C != 0) {\ T = *C;\ } else {\ *C = X;\ X->parent = T;\ X->fd = X->bk = X;\ break;\ }\ } else {\ tchunkptr F = T->fd;\ T->fd = F->bk = X;\ X->fd = F;\ X->bk = T;\ X->parent = 0;\ break;\ }\ }\ }\ } #define unlink_large_chunk(M, X) {\ tchunkptr XP = X->parent;\ tchunkptr R;\ if (X->bk != X) {\ tchunkptr F = X->fd;\ R = X->bk;\ F->bk = R;\ R->fd = F;\ } else {\ tchunkptr *RP;\ if (((R = *(RP = &(X->child[1]))) != 0) ||\ ((R = *(RP = &(X->child[0]))) != 0)) {\ tchunkptr *CP;\ while ((*(CP = &(R->child[1])) != 0) ||\ (*(CP = &(R->child[0])) != 0)) {\ R = *(RP = CP);\ }\ *RP = 0;\ }\ }\ if (XP != 0) {\ tbinptr *H = treebin_at(M, X->index);\ if (X == *H) {\ if ((*H = R) == 0) \ clear_treemap(M, X->index);\ } else {\ if (XP->child[0] == X) \ XP->child[0] = R;\ else \ XP->child[1] = R;\ }\ if (R != 0) {\ tchunkptr C0, C1;\ R->parent = XP;\ if ((C0 = X->child[0]) != 0) {\ R->child[0] = C0;\ C0->parent = R;\ }\ if ((C1 = X->child[1]) != 0) {\ R->child[1] = C1;\ C1->parent = R;\ }\ }\ }\ } /* Relays to large vs small bin operations */ #define insert_chunk(M, P, S)\ if (is_small(S)) { insert_small_chunk(M, P, S)\ } else { tchunkptr TP = (tchunkptr)(P); insert_large_chunk(M, TP, S); } #define unlink_chunk(M, P, S)\ if (is_small(S)) { unlink_small_chunk(M, P, S)\ } else { tchunkptr TP = (tchunkptr)(P); unlink_large_chunk(M, TP); } /* ----------------------- Direct-mmapping chunks ----------------------- */ static void *direct_alloc(mstate m, size_t nb) { size_t mmsize = mmap_align(nb + SIX_SIZE_T_SIZES + CHUNK_ALIGN_MASK); if (LJ_LIKELY(mmsize > nb)) { /* Check for wrap around 0 */ char *mm = (char *)(DIRECT_MMAP(m->prng, mmsize)); if (mm != CMFAIL) { size_t offset = align_offset(chunk2mem(mm)); size_t psize = mmsize - offset - DIRECT_FOOT_PAD; mchunkptr p = (mchunkptr)(mm + offset); p->prev_foot = offset | IS_DIRECT_BIT; p->head = psize|CINUSE_BIT; chunk_plus_offset(p, psize)->head = FENCEPOST_HEAD; chunk_plus_offset(p, psize+SIZE_T_SIZE)->head = 0; return chunk2mem(p); } } UNUSED(m); return NULL; } static mchunkptr direct_resize(mchunkptr oldp, size_t nb) { size_t oldsize = chunksize(oldp); if (is_small(nb)) /* Can't shrink direct regions below small size */ return NULL; /* Keep old chunk if big enough but not too big */ if (oldsize >= nb + SIZE_T_SIZE && (oldsize - nb) <= (DEFAULT_GRANULARITY >> 1)) { return oldp; } else { size_t offset = oldp->prev_foot & ~IS_DIRECT_BIT; size_t oldmmsize = oldsize + offset + DIRECT_FOOT_PAD; size_t newmmsize = mmap_align(nb + SIX_SIZE_T_SIZES + CHUNK_ALIGN_MASK); char *cp = (char *)CALL_MREMAP((char *)oldp - offset, oldmmsize, newmmsize, CALL_MREMAP_MV); if (cp != CMFAIL) { mchunkptr newp = (mchunkptr)(cp + offset); size_t psize = newmmsize - offset - DIRECT_FOOT_PAD; newp->head = psize|CINUSE_BIT; chunk_plus_offset(newp, psize)->head = FENCEPOST_HEAD; chunk_plus_offset(newp, psize+SIZE_T_SIZE)->head = 0; return newp; } } return NULL; } /* -------------------------- mspace management -------------------------- */ /* Initialize top chunk and its size */ static void init_top(mstate m, mchunkptr p, size_t psize) { /* Ensure alignment */ size_t offset = align_offset(chunk2mem(p)); p = (mchunkptr)((char *)p + offset); psize -= offset; m->top = p; m->topsize = psize; p->head = psize | PINUSE_BIT; /* set size of fake trailing chunk holding overhead space only once */ chunk_plus_offset(p, psize)->head = TOP_FOOT_SIZE; m->trim_check = DEFAULT_TRIM_THRESHOLD; /* reset on each update */ } /* Initialize bins for a new mstate that is otherwise zeroed out */ static void init_bins(mstate m) { /* Establish circular links for smallbins */ bindex_t i; for (i = 0; i < NSMALLBINS; i++) { sbinptr bin = smallbin_at(m,i); bin->fd = bin->bk = bin; } } /* Allocate chunk and prepend remainder with chunk in successor base. */ static void *prepend_alloc(mstate m, char *newbase, char *oldbase, size_t nb) { mchunkptr p = align_as_chunk(newbase); mchunkptr oldfirst = align_as_chunk(oldbase); size_t psize = (size_t)((char *)oldfirst - (char *)p); mchunkptr q = chunk_plus_offset(p, nb); size_t qsize = psize - nb; set_size_and_pinuse_of_inuse_chunk(m, p, nb); /* consolidate remainder with first chunk of old base */ if (oldfirst == m->top) { size_t tsize = m->topsize += qsize; m->top = q; q->head = tsize | PINUSE_BIT; } else if (oldfirst == m->dv) { size_t dsize = m->dvsize += qsize; m->dv = q; set_size_and_pinuse_of_free_chunk(q, dsize); } else { if (!cinuse(oldfirst)) { size_t nsize = chunksize(oldfirst); unlink_chunk(m, oldfirst, nsize); oldfirst = chunk_plus_offset(oldfirst, nsize); qsize += nsize; } set_free_with_pinuse(q, qsize, oldfirst); insert_chunk(m, q, qsize); } return chunk2mem(p); } /* Add a segment to hold a new noncontiguous region */ static void add_segment(mstate m, char *tbase, size_t tsize) { /* Determine locations and sizes of segment, fenceposts, old top */ char *old_top = (char *)m->top; msegmentptr oldsp = segment_holding(m, old_top); char *old_end = oldsp->base + oldsp->size; size_t ssize = pad_request(sizeof(struct malloc_segment)); char *rawsp = old_end - (ssize + FOUR_SIZE_T_SIZES + CHUNK_ALIGN_MASK); size_t offset = align_offset(chunk2mem(rawsp)); char *asp = rawsp + offset; char *csp = (asp < (old_top + MIN_CHUNK_SIZE))? old_top : asp; mchunkptr sp = (mchunkptr)csp; msegmentptr ss = (msegmentptr)(chunk2mem(sp)); mchunkptr tnext = chunk_plus_offset(sp, ssize); mchunkptr p = tnext; /* reset top to new space */ init_top(m, (mchunkptr)tbase, tsize - TOP_FOOT_SIZE); /* Set up segment record */ set_size_and_pinuse_of_inuse_chunk(m, sp, ssize); *ss = m->seg; /* Push current record */ m->seg.base = tbase; m->seg.size = tsize; m->seg.next = ss; /* Insert trailing fenceposts */ for (;;) { mchunkptr nextp = chunk_plus_offset(p, SIZE_T_SIZE); p->head = FENCEPOST_HEAD; if ((char *)(&(nextp->head)) < old_end) p = nextp; else break; } /* Insert the rest of old top into a bin as an ordinary free chunk */ if (csp != old_top) { mchunkptr q = (mchunkptr)old_top; size_t psize = (size_t)(csp - old_top); mchunkptr tn = chunk_plus_offset(q, psize); set_free_with_pinuse(q, psize, tn); insert_chunk(m, q, psize); } } /* -------------------------- System allocation -------------------------- */ static void *alloc_sys(mstate m, size_t nb) { char *tbase = CMFAIL; size_t tsize = 0; /* Directly map large chunks */ if (LJ_UNLIKELY(nb >= DEFAULT_MMAP_THRESHOLD)) { void *mem = direct_alloc(m, nb); if (mem != 0) return mem; } { size_t req = nb + TOP_FOOT_SIZE + SIZE_T_ONE; size_t rsize = granularity_align(req); if (LJ_LIKELY(rsize > nb)) { /* Fail if wraps around zero */ char *mp = (char *)(CALL_MMAP(m->prng, rsize)); if (mp != CMFAIL) { tbase = mp; tsize = rsize; } } } if (tbase != CMFAIL) { msegmentptr sp = &m->seg; /* Try to merge with an existing segment */ while (sp != 0 && tbase != sp->base + sp->size) sp = sp->next; if (sp != 0 && segment_holds(sp, m->top)) { /* append */ sp->size += tsize; init_top(m, m->top, m->topsize + tsize); } else { sp = &m->seg; while (sp != 0 && sp->base != tbase + tsize) sp = sp->next; if (sp != 0) { char *oldbase = sp->base; sp->base = tbase; sp->size += tsize; return prepend_alloc(m, tbase, oldbase, nb); } else { add_segment(m, tbase, tsize); } } if (nb < m->topsize) { /* Allocate from new or extended top space */ size_t rsize = m->topsize -= nb; mchunkptr p = m->top; mchunkptr r = m->top = chunk_plus_offset(p, nb); r->head = rsize | PINUSE_BIT; set_size_and_pinuse_of_inuse_chunk(m, p, nb); return chunk2mem(p); } } return NULL; } /* ----------------------- system deallocation -------------------------- */ /* Unmap and unlink any mmapped segments that don't contain used chunks */ static size_t release_unused_segments(mstate m) { size_t released = 0; size_t nsegs = 0; msegmentptr pred = &m->seg; msegmentptr sp = pred->next; while (sp != 0) { char *base = sp->base; size_t size = sp->size; msegmentptr next = sp->next; nsegs++; { mchunkptr p = align_as_chunk(base); size_t psize = chunksize(p); /* Can unmap if first chunk holds entire segment and not pinned */ if (!cinuse(p) && (char *)p + psize >= base + size - TOP_FOOT_SIZE) { tchunkptr tp = (tchunkptr)p; if (p == m->dv) { m->dv = 0; m->dvsize = 0; } else { unlink_large_chunk(m, tp); } if (CALL_MUNMAP(base, size) == 0) { released += size; /* unlink obsoleted record */ sp = pred; sp->next = next; } else { /* back out if cannot unmap */ insert_large_chunk(m, tp, psize); } } } pred = sp; sp = next; } /* Reset check counter */ m->release_checks = nsegs > MAX_RELEASE_CHECK_RATE ? nsegs : MAX_RELEASE_CHECK_RATE; return released; } static int alloc_trim(mstate m, size_t pad) { size_t released = 0; if (pad < MAX_REQUEST && is_initialized(m)) { pad += TOP_FOOT_SIZE; /* ensure enough room for segment overhead */ if (m->topsize > pad) { /* Shrink top space in granularity-size units, keeping at least one */ size_t unit = DEFAULT_GRANULARITY; size_t extra = ((m->topsize - pad + (unit - SIZE_T_ONE)) / unit - SIZE_T_ONE) * unit; msegmentptr sp = segment_holding(m, (char *)m->top); if (sp->size >= extra && !has_segment_link(m, sp)) { /* can't shrink if pinned */ size_t newsize = sp->size - extra; /* Prefer mremap, fall back to munmap */ if ((CALL_MREMAP(sp->base, sp->size, newsize, CALL_MREMAP_NOMOVE) != MFAIL) || (CALL_MUNMAP(sp->base + newsize, extra) == 0)) { released = extra; } } if (released != 0) { sp->size -= released; init_top(m, m->top, m->topsize - released); } } /* Unmap any unused mmapped segments */ released += release_unused_segments(m); /* On failure, disable autotrim to avoid repeated failed future calls */ if (released == 0 && m->topsize > m->trim_check) m->trim_check = MAX_SIZE_T; } return (released != 0)? 1 : 0; } /* ---------------------------- malloc support --------------------------- */ /* allocate a large request from the best fitting chunk in a treebin */ static void *tmalloc_large(mstate m, size_t nb) { tchunkptr v = 0; size_t rsize = ~nb+1; /* Unsigned negation */ tchunkptr t; bindex_t idx; compute_tree_index(nb, idx); if ((t = *treebin_at(m, idx)) != 0) { /* Traverse tree for this bin looking for node with size == nb */ size_t sizebits = nb << leftshift_for_tree_index(idx); tchunkptr rst = 0; /* The deepest untaken right subtree */ for (;;) { tchunkptr rt; size_t trem = chunksize(t) - nb; if (trem < rsize) { v = t; if ((rsize = trem) == 0) break; } rt = t->child[1]; t = t->child[(sizebits >> (SIZE_T_BITSIZE-SIZE_T_ONE)) & 1]; if (rt != 0 && rt != t) rst = rt; if (t == 0) { t = rst; /* set t to least subtree holding sizes > nb */ break; } sizebits <<= 1; } } if (t == 0 && v == 0) { /* set t to root of next non-empty treebin */ binmap_t leftbits = left_bits(idx2bit(idx)) & m->treemap; if (leftbits != 0) t = *treebin_at(m, lj_ffs(leftbits)); } while (t != 0) { /* find smallest of tree or subtree */ size_t trem = chunksize(t) - nb; if (trem < rsize) { rsize = trem; v = t; } t = leftmost_child(t); } /* If dv is a better fit, return NULL so malloc will use it */ if (v != 0 && rsize < (size_t)(m->dvsize - nb)) { mchunkptr r = chunk_plus_offset(v, nb); unlink_large_chunk(m, v); if (rsize < MIN_CHUNK_SIZE) { set_inuse_and_pinuse(m, v, (rsize + nb)); } else { set_size_and_pinuse_of_inuse_chunk(m, v, nb); set_size_and_pinuse_of_free_chunk(r, rsize); insert_chunk(m, r, rsize); } return chunk2mem(v); } return NULL; } /* allocate a small request from the best fitting chunk in a treebin */ static void *tmalloc_small(mstate m, size_t nb) { tchunkptr t, v; mchunkptr r; size_t rsize; bindex_t i = lj_ffs(m->treemap); v = t = *treebin_at(m, i); rsize = chunksize(t) - nb; while ((t = leftmost_child(t)) != 0) { size_t trem = chunksize(t) - nb; if (trem < rsize) { rsize = trem; v = t; } } r = chunk_plus_offset(v, nb); unlink_large_chunk(m, v); if (rsize < MIN_CHUNK_SIZE) { set_inuse_and_pinuse(m, v, (rsize + nb)); } else { set_size_and_pinuse_of_inuse_chunk(m, v, nb); set_size_and_pinuse_of_free_chunk(r, rsize); replace_dv(m, r, rsize); } return chunk2mem(v); } /* ----------------------------------------------------------------------- */ void *lj_alloc_create(PRNGState *rs) { size_t tsize = DEFAULT_GRANULARITY; char *tbase; INIT_MMAP(); UNUSED(rs); tbase = (char *)(CALL_MMAP(rs, tsize)); if (tbase != CMFAIL) { size_t msize = pad_request(sizeof(struct malloc_state)); mchunkptr mn; mchunkptr msp = align_as_chunk(tbase); mstate m = (mstate)(chunk2mem(msp)); memset(m, 0, msize); msp->head = (msize|PINUSE_BIT|CINUSE_BIT); m->seg.base = tbase; m->seg.size = tsize; m->release_checks = MAX_RELEASE_CHECK_RATE; init_bins(m); mn = next_chunk(mem2chunk(m)); init_top(m, mn, (size_t)((tbase + tsize) - (char *)mn) - TOP_FOOT_SIZE); return m; } return NULL; } void lj_alloc_setprng(void *msp, PRNGState *rs) { mstate ms = (mstate)msp; ms->prng = rs; } void lj_alloc_destroy(void *msp) { mstate ms = (mstate)msp; msegmentptr sp = &ms->seg; while (sp != 0) { char *base = sp->base; size_t size = sp->size; sp = sp->next; CALL_MUNMAP(base, size); } } static LJ_NOINLINE void *lj_alloc_malloc(void *msp, size_t nsize) { mstate ms = (mstate)msp; void *mem; size_t nb; if (nsize <= MAX_SMALL_REQUEST) { bindex_t idx; binmap_t smallbits; nb = (nsize < MIN_REQUEST)? MIN_CHUNK_SIZE : pad_request(nsize); idx = small_index(nb); smallbits = ms->smallmap >> idx; if ((smallbits & 0x3U) != 0) { /* Remainderless fit to a smallbin. */ mchunkptr b, p; idx += ~smallbits & 1; /* Uses next bin if idx empty */ b = smallbin_at(ms, idx); p = b->fd; unlink_first_small_chunk(ms, b, p, idx); set_inuse_and_pinuse(ms, p, small_index2size(idx)); mem = chunk2mem(p); return mem; } else if (nb > ms->dvsize) { if (smallbits != 0) { /* Use chunk in next nonempty smallbin */ mchunkptr b, p, r; size_t rsize; binmap_t leftbits = (smallbits << idx) & left_bits(idx2bit(idx)); bindex_t i = lj_ffs(leftbits); b = smallbin_at(ms, i); p = b->fd; unlink_first_small_chunk(ms, b, p, i); rsize = small_index2size(i) - nb; /* Fit here cannot be remainderless if 4byte sizes */ if (SIZE_T_SIZE != 4 && rsize < MIN_CHUNK_SIZE) { set_inuse_and_pinuse(ms, p, small_index2size(i)); } else { set_size_and_pinuse_of_inuse_chunk(ms, p, nb); r = chunk_plus_offset(p, nb); set_size_and_pinuse_of_free_chunk(r, rsize); replace_dv(ms, r, rsize); } mem = chunk2mem(p); return mem; } else if (ms->treemap != 0 && (mem = tmalloc_small(ms, nb)) != 0) { return mem; } } } else if (nsize >= MAX_REQUEST) { nb = MAX_SIZE_T; /* Too big to allocate. Force failure (in sys alloc) */ } else { nb = pad_request(nsize); if (ms->treemap != 0 && (mem = tmalloc_large(ms, nb)) != 0) { return mem; } } if (nb <= ms->dvsize) { size_t rsize = ms->dvsize - nb; mchunkptr p = ms->dv; if (rsize >= MIN_CHUNK_SIZE) { /* split dv */ mchunkptr r = ms->dv = chunk_plus_offset(p, nb); ms->dvsize = rsize; set_size_and_pinuse_of_free_chunk(r, rsize); set_size_and_pinuse_of_inuse_chunk(ms, p, nb); } else { /* exhaust dv */ size_t dvs = ms->dvsize; ms->dvsize = 0; ms->dv = 0; set_inuse_and_pinuse(ms, p, dvs); } mem = chunk2mem(p); return mem; } else if (nb < ms->topsize) { /* Split top */ size_t rsize = ms->topsize -= nb; mchunkptr p = ms->top; mchunkptr r = ms->top = chunk_plus_offset(p, nb); r->head = rsize | PINUSE_BIT; set_size_and_pinuse_of_inuse_chunk(ms, p, nb); mem = chunk2mem(p); return mem; } return alloc_sys(ms, nb); } static LJ_NOINLINE void *lj_alloc_free(void *msp, void *ptr) { if (ptr != 0) { mchunkptr p = mem2chunk(ptr); mstate fm = (mstate)msp; size_t psize = chunksize(p); mchunkptr next = chunk_plus_offset(p, psize); if (!pinuse(p)) { size_t prevsize = p->prev_foot; if ((prevsize & IS_DIRECT_BIT) != 0) { prevsize &= ~IS_DIRECT_BIT; psize += prevsize + DIRECT_FOOT_PAD; CALL_MUNMAP((char *)p - prevsize, psize); return NULL; } else { mchunkptr prev = chunk_minus_offset(p, prevsize); psize += prevsize; p = prev; /* consolidate backward */ if (p != fm->dv) { unlink_chunk(fm, p, prevsize); } else if ((next->head & INUSE_BITS) == INUSE_BITS) { fm->dvsize = psize; set_free_with_pinuse(p, psize, next); return NULL; } } } if (!cinuse(next)) { /* consolidate forward */ if (next == fm->top) { size_t tsize = fm->topsize += psize; fm->top = p; p->head = tsize | PINUSE_BIT; if (p == fm->dv) { fm->dv = 0; fm->dvsize = 0; } if (tsize > fm->trim_check) alloc_trim(fm, 0); return NULL; } else if (next == fm->dv) { size_t dsize = fm->dvsize += psize; fm->dv = p; set_size_and_pinuse_of_free_chunk(p, dsize); return NULL; } else { size_t nsize = chunksize(next); psize += nsize; unlink_chunk(fm, next, nsize); set_size_and_pinuse_of_free_chunk(p, psize); if (p == fm->dv) { fm->dvsize = psize; return NULL; } } } else { set_free_with_pinuse(p, psize, next); } if (is_small(psize)) { insert_small_chunk(fm, p, psize); } else { tchunkptr tp = (tchunkptr)p; insert_large_chunk(fm, tp, psize); if (--fm->release_checks == 0) release_unused_segments(fm); } } return NULL; } static LJ_NOINLINE void *lj_alloc_realloc(void *msp, void *ptr, size_t nsize) { if (nsize >= MAX_REQUEST) { return NULL; } else { mstate m = (mstate)msp; mchunkptr oldp = mem2chunk(ptr); size_t oldsize = chunksize(oldp); mchunkptr next = chunk_plus_offset(oldp, oldsize); mchunkptr newp = 0; size_t nb = request2size(nsize); /* Try to either shrink or extend into top. Else malloc-copy-free */ if (is_direct(oldp)) { newp = direct_resize(oldp, nb); /* this may return NULL. */ } else if (oldsize >= nb) { /* already big enough */ size_t rsize = oldsize - nb; newp = oldp; if (rsize >= MIN_CHUNK_SIZE) { mchunkptr rem = chunk_plus_offset(newp, nb); set_inuse(m, newp, nb); set_inuse(m, rem, rsize); lj_alloc_free(m, chunk2mem(rem)); } } else if (next == m->top && oldsize + m->topsize > nb) { /* Expand into top */ size_t newsize = oldsize + m->topsize; size_t newtopsize = newsize - nb; mchunkptr newtop = chunk_plus_offset(oldp, nb); set_inuse(m, oldp, nb); newtop->head = newtopsize |PINUSE_BIT; m->top = newtop; m->topsize = newtopsize; newp = oldp; } if (newp != 0) { return chunk2mem(newp); } else { void *newmem = lj_alloc_malloc(m, nsize); if (newmem != 0) { size_t oc = oldsize - overhead_for(oldp); memcpy(newmem, ptr, oc < nsize ? oc : nsize); lj_alloc_free(m, ptr); } return newmem; } } } void *lj_alloc_f(void *msp, void *ptr, size_t osize, size_t nsize) { (void)osize; if (nsize == 0) { return lj_alloc_free(msp, ptr); } else if (ptr == NULL) { return lj_alloc_malloc(msp, nsize); } else { return lj_alloc_realloc(msp, ptr, nsize); } } #endif
xLua/build/luajit-2.1.0b3/src/lj_alloc.c/0
{ "file_path": "xLua/build/luajit-2.1.0b3/src/lj_alloc.c", "repo_id": "xLua", "token_count": 18750 }
2,047
/* ** Bytecode writer. ** Copyright (C) 2005-2021 Mike Pall. See Copyright Notice in luajit.h */ #define lj_bcwrite_c #define LUA_CORE #include "lj_obj.h" #include "lj_gc.h" #include "lj_buf.h" #include "lj_bc.h" #if LJ_HASFFI #include "lj_ctype.h" #endif #if LJ_HASJIT #include "lj_dispatch.h" #include "lj_jit.h" #endif #include "lj_strfmt.h" #include "lj_bcdump.h" #include "lj_vm.h" /* Context for bytecode writer. */ typedef struct BCWriteCtx { SBuf sb; /* Output buffer. */ GCproto *pt; /* Root prototype. */ lua_Writer wfunc; /* Writer callback. */ void *wdata; /* Writer callback data. */ int strip; /* Strip debug info. */ int status; /* Status from writer callback. */ #ifdef LUA_USE_ASSERT global_State *g; #endif } BCWriteCtx; #ifdef LUA_USE_ASSERT #define lj_assertBCW(c, ...) lj_assertG_(ctx->g, (c), __VA_ARGS__) #else #define lj_assertBCW(c, ...) ((void)ctx) #endif /* -- Bytecode writer ----------------------------------------------------- */ /* Write a single constant key/value of a template table. */ static void bcwrite_ktabk(BCWriteCtx *ctx, cTValue *o, int narrow) { char *p = lj_buf_more(&ctx->sb, 1+10); if (tvisstr(o)) { const GCstr *str = strV(o); MSize len = str->len; p = lj_buf_more(&ctx->sb, 5+len); p = lj_strfmt_wuleb128(p, BCDUMP_KTAB_STR+len); p = lj_buf_wmem(p, strdata(str), len); } else if (tvisint(o)) { *p++ = BCDUMP_KTAB_INT; p = lj_strfmt_wuleb128(p, intV(o)); } else if (tvisnum(o)) { if (!LJ_DUALNUM && narrow) { /* Narrow number constants to integers. */ lua_Number num = numV(o); int32_t k = lj_num2int(num); if (num == (lua_Number)k) { /* -0 is never a constant. */ *p++ = BCDUMP_KTAB_INT; p = lj_strfmt_wuleb128(p, k); ctx->sb.w = p; return; } } *p++ = BCDUMP_KTAB_NUM; p = lj_strfmt_wuleb128(p, o->u32.lo); p = lj_strfmt_wuleb128(p, o->u32.hi); } else { lj_assertBCW(tvispri(o), "unhandled type %d", itype(o)); *p++ = BCDUMP_KTAB_NIL+~itype(o); } ctx->sb.w = p; } /* Write a template table. */ static void bcwrite_ktab(BCWriteCtx *ctx, char *p, const GCtab *t) { MSize narray = 0, nhash = 0; if (t->asize > 0) { /* Determine max. length of array part. */ ptrdiff_t i; TValue *array = tvref(t->array); for (i = (ptrdiff_t)t->asize-1; i >= 0; i--) if (!tvisnil(&array[i])) break; narray = (MSize)(i+1); } if (t->hmask > 0) { /* Count number of used hash slots. */ MSize i, hmask = t->hmask; Node *node = noderef(t->node); for (i = 0; i <= hmask; i++) nhash += !tvisnil(&node[i].val); } /* Write number of array slots and hash slots. */ p = lj_strfmt_wuleb128(p, narray); p = lj_strfmt_wuleb128(p, nhash); ctx->sb.w = p; if (narray) { /* Write array entries (may contain nil). */ MSize i; TValue *o = tvref(t->array); for (i = 0; i < narray; i++, o++) bcwrite_ktabk(ctx, o, 1); } if (nhash) { /* Write hash entries. */ MSize i = nhash; Node *node = noderef(t->node) + t->hmask; for (;; node--) if (!tvisnil(&node->val)) { bcwrite_ktabk(ctx, &node->key, 0); bcwrite_ktabk(ctx, &node->val, 1); if (--i == 0) break; } } } /* Write GC constants of a prototype. */ static void bcwrite_kgc(BCWriteCtx *ctx, GCproto *pt) { MSize i, sizekgc = pt->sizekgc; GCRef *kr = mref(pt->k, GCRef) - (ptrdiff_t)sizekgc; for (i = 0; i < sizekgc; i++, kr++) { GCobj *o = gcref(*kr); MSize tp, need = 1; char *p; /* Determine constant type and needed size. */ if (o->gch.gct == ~LJ_TSTR) { tp = BCDUMP_KGC_STR + gco2str(o)->len; need = 5+gco2str(o)->len; } else if (o->gch.gct == ~LJ_TPROTO) { lj_assertBCW((pt->flags & PROTO_CHILD), "prototype has unexpected child"); tp = BCDUMP_KGC_CHILD; #if LJ_HASFFI } else if (o->gch.gct == ~LJ_TCDATA) { CTypeID id = gco2cd(o)->ctypeid; need = 1+4*5; if (id == CTID_INT64) { tp = BCDUMP_KGC_I64; } else if (id == CTID_UINT64) { tp = BCDUMP_KGC_U64; } else { lj_assertBCW(id == CTID_COMPLEX_DOUBLE, "bad cdata constant CTID %d", id); tp = BCDUMP_KGC_COMPLEX; } #endif } else { lj_assertBCW(o->gch.gct == ~LJ_TTAB, "bad constant GC type %d", o->gch.gct); tp = BCDUMP_KGC_TAB; need = 1+2*5; } /* Write constant type. */ p = lj_buf_more(&ctx->sb, need); p = lj_strfmt_wuleb128(p, tp); /* Write constant data (if any). */ if (tp >= BCDUMP_KGC_STR) { p = lj_buf_wmem(p, strdata(gco2str(o)), gco2str(o)->len); } else if (tp == BCDUMP_KGC_TAB) { bcwrite_ktab(ctx, p, gco2tab(o)); continue; #if LJ_HASFFI } else if (tp != BCDUMP_KGC_CHILD) { cTValue *q = (TValue *)cdataptr(gco2cd(o)); p = lj_strfmt_wuleb128(p, q[0].u32.lo); p = lj_strfmt_wuleb128(p, q[0].u32.hi); if (tp == BCDUMP_KGC_COMPLEX) { p = lj_strfmt_wuleb128(p, q[1].u32.lo); p = lj_strfmt_wuleb128(p, q[1].u32.hi); } #endif } ctx->sb.w = p; } } /* Write number constants of a prototype. */ static void bcwrite_knum(BCWriteCtx *ctx, GCproto *pt) { MSize i, sizekn = pt->sizekn; cTValue *o = mref(pt->k, TValue); char *p = lj_buf_more(&ctx->sb, 10*sizekn); for (i = 0; i < sizekn; i++, o++) { int32_t k; if (tvisint(o)) { k = intV(o); goto save_int; } else { /* Write a 33 bit ULEB128 for the int (lsb=0) or loword (lsb=1). */ if (!LJ_DUALNUM) { /* Narrow number constants to integers. */ lua_Number num = numV(o); k = lj_num2int(num); if (num == (lua_Number)k) { /* -0 is never a constant. */ save_int: p = lj_strfmt_wuleb128(p, 2*(uint32_t)k | ((uint32_t)k&0x80000000u)); if (k < 0) p[-1] = (p[-1] & 7) | ((k>>27) & 0x18); continue; } } p = lj_strfmt_wuleb128(p, 1+(2*o->u32.lo | (o->u32.lo & 0x80000000u))); if (o->u32.lo >= 0x80000000u) p[-1] = (p[-1] & 7) | ((o->u32.lo>>27) & 0x18); p = lj_strfmt_wuleb128(p, o->u32.hi); } } ctx->sb.w = p; } /* Write bytecode instructions. */ static char *bcwrite_bytecode(BCWriteCtx *ctx, char *p, GCproto *pt) { MSize nbc = pt->sizebc-1; /* Omit the [JI]FUNC* header. */ #if LJ_HASJIT uint8_t *q = (uint8_t *)p; #endif p = lj_buf_wmem(p, proto_bc(pt)+1, nbc*(MSize)sizeof(BCIns)); UNUSED(ctx); #if LJ_HASJIT /* Unpatch modified bytecode containing ILOOP/JLOOP etc. */ if ((pt->flags & PROTO_ILOOP) || pt->trace) { jit_State *J = L2J(sbufL(&ctx->sb)); MSize i; for (i = 0; i < nbc; i++, q += sizeof(BCIns)) { BCOp op = (BCOp)q[LJ_ENDIAN_SELECT(0, 3)]; if (op == BC_IFORL || op == BC_IITERL || op == BC_ILOOP || op == BC_JFORI) { q[LJ_ENDIAN_SELECT(0, 3)] = (uint8_t)(op-BC_IFORL+BC_FORL); } else if (op == BC_JFORL || op == BC_JITERL || op == BC_JLOOP) { BCReg rd = q[LJ_ENDIAN_SELECT(2, 1)] + (q[LJ_ENDIAN_SELECT(3, 0)] << 8); memcpy(q, &traceref(J, rd)->startins, 4); } } } #endif return p; } /* Write prototype. */ static void bcwrite_proto(BCWriteCtx *ctx, GCproto *pt) { MSize sizedbg = 0; char *p; /* Recursively write children of prototype. */ if ((pt->flags & PROTO_CHILD)) { ptrdiff_t i, n = pt->sizekgc; GCRef *kr = mref(pt->k, GCRef) - 1; for (i = 0; i < n; i++, kr--) { GCobj *o = gcref(*kr); if (o->gch.gct == ~LJ_TPROTO) bcwrite_proto(ctx, gco2pt(o)); } } /* Start writing the prototype info to a buffer. */ p = lj_buf_need(&ctx->sb, 5+4+6*5+(pt->sizebc-1)*(MSize)sizeof(BCIns)+pt->sizeuv*2); p += 5; /* Leave room for final size. */ /* Write prototype header. */ *p++ = (pt->flags & (PROTO_CHILD|PROTO_VARARG|PROTO_FFI)); *p++ = pt->numparams; *p++ = pt->framesize; *p++ = pt->sizeuv; p = lj_strfmt_wuleb128(p, pt->sizekgc); p = lj_strfmt_wuleb128(p, pt->sizekn); p = lj_strfmt_wuleb128(p, pt->sizebc-1); if (!ctx->strip) { if (proto_lineinfo(pt)) sizedbg = pt->sizept - (MSize)((char *)proto_lineinfo(pt) - (char *)pt); p = lj_strfmt_wuleb128(p, sizedbg); if (sizedbg) { p = lj_strfmt_wuleb128(p, pt->firstline); p = lj_strfmt_wuleb128(p, pt->numline); } } /* Write bytecode instructions and upvalue refs. */ p = bcwrite_bytecode(ctx, p, pt); p = lj_buf_wmem(p, proto_uv(pt), pt->sizeuv*2); ctx->sb.w = p; /* Write constants. */ bcwrite_kgc(ctx, pt); bcwrite_knum(ctx, pt); /* Write debug info, if not stripped. */ if (sizedbg) { p = lj_buf_more(&ctx->sb, sizedbg); p = lj_buf_wmem(p, proto_lineinfo(pt), sizedbg); ctx->sb.w = p; } /* Pass buffer to writer function. */ if (ctx->status == 0) { MSize n = sbuflen(&ctx->sb) - 5; MSize nn = (lj_fls(n)+8)*9 >> 6; char *q = ctx->sb.b + (5 - nn); p = lj_strfmt_wuleb128(q, n); /* Fill in final size. */ lj_assertBCW(p == ctx->sb.b + 5, "bad ULEB128 write"); ctx->status = ctx->wfunc(sbufL(&ctx->sb), q, nn+n, ctx->wdata); } } /* Write header of bytecode dump. */ static void bcwrite_header(BCWriteCtx *ctx) { GCstr *chunkname = proto_chunkname(ctx->pt); const char *name = strdata(chunkname); MSize len = chunkname->len; char *p = lj_buf_need(&ctx->sb, 5+5+len); *p++ = BCDUMP_HEAD1; *p++ = BCDUMP_HEAD2; *p++ = BCDUMP_HEAD3; *p++ = BCDUMP_VERSION; *p++ = (ctx->strip ? BCDUMP_F_STRIP : 0) + LJ_BE*BCDUMP_F_BE + ((ctx->pt->flags & PROTO_FFI) ? BCDUMP_F_FFI : 0) + LJ_FR2*BCDUMP_F_FR2; if (!ctx->strip) { p = lj_strfmt_wuleb128(p, len); p = lj_buf_wmem(p, name, len); } ctx->status = ctx->wfunc(sbufL(&ctx->sb), ctx->sb.b, (MSize)(p - ctx->sb.b), ctx->wdata); } /* Write footer of bytecode dump. */ static void bcwrite_footer(BCWriteCtx *ctx) { if (ctx->status == 0) { uint8_t zero = 0; ctx->status = ctx->wfunc(sbufL(&ctx->sb), &zero, 1, ctx->wdata); } } /* Protected callback for bytecode writer. */ static TValue *cpwriter(lua_State *L, lua_CFunction dummy, void *ud) { BCWriteCtx *ctx = (BCWriteCtx *)ud; UNUSED(L); UNUSED(dummy); lj_buf_need(&ctx->sb, 1024); /* Avoids resize for most prototypes. */ bcwrite_header(ctx); bcwrite_proto(ctx, ctx->pt); bcwrite_footer(ctx); return NULL; } /* Write bytecode for a prototype. */ int lj_bcwrite(lua_State *L, GCproto *pt, lua_Writer writer, void *data, int strip) { BCWriteCtx ctx; int status; ctx.pt = pt; ctx.wfunc = writer; ctx.wdata = data; ctx.strip = strip; ctx.status = 0; #ifdef LUA_USE_ASSERT ctx.g = G(L); #endif lj_buf_init(L, &ctx.sb); status = lj_vm_cpcall(L, NULL, &ctx, cpwriter); if (status == 0) status = ctx.status; lj_buf_free(G(sbufL(&ctx.sb)), &ctx.sb); return status; }
xLua/build/luajit-2.1.0b3/src/lj_bcwrite.c/0
{ "file_path": "xLua/build/luajit-2.1.0b3/src/lj_bcwrite.c", "repo_id": "xLua", "token_count": 5287 }
2,048
/* ** FFI C library loader. ** Copyright (C) 2005-2021 Mike Pall. See Copyright Notice in luajit.h */ #ifndef _LJ_CLIB_H #define _LJ_CLIB_H #include "lj_obj.h" #if LJ_HASFFI /* Namespace for C library indexing. */ #define CLNS_INDEX ((1u<<CT_FUNC)|(1u<<CT_EXTERN)|(1u<<CT_CONSTVAL)) /* C library namespace. */ typedef struct CLibrary { void *handle; /* Opaque handle for dynamic library loader. */ GCtab *cache; /* Cache for resolved symbols. Anchored in ud->env. */ } CLibrary; LJ_FUNC TValue *lj_clib_index(lua_State *L, CLibrary *cl, GCstr *name); LJ_FUNC void lj_clib_load(lua_State *L, GCtab *mt, GCstr *name, int global); LJ_FUNC void lj_clib_unload(CLibrary *cl); LJ_FUNC void lj_clib_default(lua_State *L, GCtab *mt); #endif #endif
xLua/build/luajit-2.1.0b3/src/lj_clib.h/0
{ "file_path": "xLua/build/luajit-2.1.0b3/src/lj_clib.h", "repo_id": "xLua", "token_count": 319 }
2,049
/* ** x86/x64 instruction emitter. ** Copyright (C) 2005-2021 Mike Pall. See Copyright Notice in luajit.h */ /* -- Emit basic instructions --------------------------------------------- */ #define MODRM(mode, r1, r2) ((MCode)((mode)+(((r1)&7)<<3)+((r2)&7))) #if LJ_64 #define REXRB(p, rr, rb) \ { MCode rex = 0x40 + (((rr)>>1)&4) + (((rb)>>3)&1); \ if (rex != 0x40) *--(p) = rex; } #define FORCE_REX 0x200 #define REX_64 (FORCE_REX|0x080000) #define VEX_64 0x800000 #else #define REXRB(p, rr, rb) ((void)0) #define FORCE_REX 0 #define REX_64 0 #define VEX_64 0 #endif #if LJ_GC64 #define REX_GC64 REX_64 #else #define REX_GC64 0 #endif #define emit_i8(as, i) (*--as->mcp = (MCode)(i)) #define emit_i32(as, i) (*(int32_t *)(as->mcp-4) = (i), as->mcp -= 4) #define emit_u32(as, u) (*(uint32_t *)(as->mcp-4) = (u), as->mcp -= 4) #define emit_x87op(as, xo) \ (*(uint16_t *)(as->mcp-2) = (uint16_t)(xo), as->mcp -= 2) /* op */ static LJ_AINLINE MCode *emit_op(x86Op xo, Reg rr, Reg rb, Reg rx, MCode *p, int delta) { int n = (int8_t)xo; if (n == -60) { /* VEX-encoded instruction */ #if LJ_64 xo ^= (((rr>>1)&4)+((rx>>2)&2)+((rb>>3)&1))<<13; #endif *(uint32_t *)(p+delta-5) = (uint32_t)xo; return p+delta-5; } #if defined(__GNUC__) || defined(__clang__) if (__builtin_constant_p(xo) && n == -2) p[delta-2] = (MCode)(xo >> 24); else if (__builtin_constant_p(xo) && n == -3) *(uint16_t *)(p+delta-3) = (uint16_t)(xo >> 16); else #endif *(uint32_t *)(p+delta-5) = (uint32_t)xo; p += n + delta; #if LJ_64 { uint32_t rex = 0x40 + ((rr>>1)&(4+(FORCE_REX>>1)))+((rx>>2)&2)+((rb>>3)&1); if (rex != 0x40) { rex |= (rr >> 16); if (n == -4) { *p = (MCode)rex; rex = (MCode)(xo >> 8); } else if ((xo & 0xffffff) == 0x6600fd) { *p = (MCode)rex; rex = 0x66; } *--p = (MCode)rex; } } #else UNUSED(rr); UNUSED(rb); UNUSED(rx); #endif return p; } /* op + modrm */ #define emit_opm(xo, mode, rr, rb, p, delta) \ (p[(delta)-1] = MODRM((mode), (rr), (rb)), \ emit_op((xo), (rr), (rb), 0, (p), (delta))) /* op + modrm + sib */ #define emit_opmx(xo, mode, scale, rr, rb, rx, p) \ (p[-1] = MODRM((scale), (rx), (rb)), \ p[-2] = MODRM((mode), (rr), RID_ESP), \ emit_op((xo), (rr), (rb), (rx), (p), -1)) /* op r1, r2 */ static void emit_rr(ASMState *as, x86Op xo, Reg r1, Reg r2) { MCode *p = as->mcp; as->mcp = emit_opm(xo, XM_REG, r1, r2, p, 0); } #if LJ_64 && defined(LUA_USE_ASSERT) /* [addr] is sign-extended in x64 and must be in lower 2G (not 4G). */ static int32_t ptr2addr(const void *p) { lj_assertX((uintptr_t)p < (uintptr_t)0x80000000, "pointer outside 2G range"); return i32ptr(p); } #else #define ptr2addr(p) (i32ptr((p))) #endif /* op r, [base+ofs] */ static void emit_rmro(ASMState *as, x86Op xo, Reg rr, Reg rb, int32_t ofs) { MCode *p = as->mcp; x86Mode mode; if (ra_hasreg(rb)) { if (LJ_GC64 && rb == RID_RIP) { mode = XM_OFS0; p -= 4; *(int32_t *)p = ofs; } else if (ofs == 0 && (rb&7) != RID_EBP) { mode = XM_OFS0; } else if (checki8(ofs)) { *--p = (MCode)ofs; mode = XM_OFS8; } else { p -= 4; *(int32_t *)p = ofs; mode = XM_OFS32; } if ((rb&7) == RID_ESP) *--p = MODRM(XM_SCALE1, RID_ESP, RID_ESP); } else { *(int32_t *)(p-4) = ofs; #if LJ_64 p[-5] = MODRM(XM_SCALE1, RID_ESP, RID_EBP); p -= 5; rb = RID_ESP; #else p -= 4; rb = RID_EBP; #endif mode = XM_OFS0; } as->mcp = emit_opm(xo, mode, rr, rb, p, 0); } /* op r, [base+idx*scale+ofs] */ static void emit_rmrxo(ASMState *as, x86Op xo, Reg rr, Reg rb, Reg rx, x86Mode scale, int32_t ofs) { MCode *p = as->mcp; x86Mode mode; if (ofs == 0 && (rb&7) != RID_EBP) { mode = XM_OFS0; } else if (checki8(ofs)) { mode = XM_OFS8; *--p = (MCode)ofs; } else { mode = XM_OFS32; p -= 4; *(int32_t *)p = ofs; } as->mcp = emit_opmx(xo, mode, scale, rr, rb, rx, p); } /* op r, i */ static void emit_gri(ASMState *as, x86Group xg, Reg rb, int32_t i) { MCode *p = as->mcp; x86Op xo; if (checki8(i)) { *--p = (MCode)i; xo = XG_TOXOi8(xg); } else { p -= 4; *(int32_t *)p = i; xo = XG_TOXOi(xg); } as->mcp = emit_opm(xo, XM_REG, (Reg)(xg & 7) | (rb & REX_64), rb, p, 0); } /* op [base+ofs], i */ static void emit_gmroi(ASMState *as, x86Group xg, Reg rb, int32_t ofs, int32_t i) { x86Op xo; if (checki8(i)) { emit_i8(as, i); xo = XG_TOXOi8(xg); } else { emit_i32(as, i); xo = XG_TOXOi(xg); } emit_rmro(as, xo, (Reg)(xg & 7), rb, ofs); } #define emit_shifti(as, xg, r, i) \ (emit_i8(as, (i)), emit_rr(as, XO_SHIFTi, (Reg)(xg), (r))) /* op r, rm/mrm */ static void emit_mrm(ASMState *as, x86Op xo, Reg rr, Reg rb) { MCode *p = as->mcp; x86Mode mode = XM_REG; if (rb == RID_MRM) { rb = as->mrm.base; if (rb == RID_NONE) { rb = RID_EBP; mode = XM_OFS0; p -= 4; *(int32_t *)p = as->mrm.ofs; if (as->mrm.idx != RID_NONE) goto mrmidx; #if LJ_64 *--p = MODRM(XM_SCALE1, RID_ESP, RID_EBP); rb = RID_ESP; #endif } else if (LJ_GC64 && rb == RID_RIP) { lj_assertA(as->mrm.idx == RID_NONE, "RIP-rel mrm cannot have index"); mode = XM_OFS0; p -= 4; *(int32_t *)p = as->mrm.ofs; } else { if (as->mrm.ofs == 0 && (rb&7) != RID_EBP) { mode = XM_OFS0; } else if (checki8(as->mrm.ofs)) { *--p = (MCode)as->mrm.ofs; mode = XM_OFS8; } else { p -= 4; *(int32_t *)p = as->mrm.ofs; mode = XM_OFS32; } if (as->mrm.idx != RID_NONE) { mrmidx: as->mcp = emit_opmx(xo, mode, as->mrm.scale, rr, rb, as->mrm.idx, p); return; } if ((rb&7) == RID_ESP) *--p = MODRM(XM_SCALE1, RID_ESP, RID_ESP); } } as->mcp = emit_opm(xo, mode, rr, rb, p, 0); } /* op rm/mrm, i */ static void emit_gmrmi(ASMState *as, x86Group xg, Reg rb, int32_t i) { x86Op xo; if (checki8(i)) { emit_i8(as, i); xo = XG_TOXOi8(xg); } else { emit_i32(as, i); xo = XG_TOXOi(xg); } emit_mrm(as, xo, (Reg)(xg & 7) | (rb & REX_64), (rb & ~REX_64)); } /* -- Emit loads/stores --------------------------------------------------- */ /* mov [base+ofs], i */ static void emit_movmroi(ASMState *as, Reg base, int32_t ofs, int32_t i) { emit_i32(as, i); emit_rmro(as, XO_MOVmi, 0, base, ofs); } /* mov [base+ofs], r */ #define emit_movtomro(as, r, base, ofs) \ emit_rmro(as, XO_MOVto, (r), (base), (ofs)) /* Get/set global_State fields. */ #define emit_opgl(as, xo, r, field) \ emit_rma(as, (xo), (r), (void *)&J2G(as->J)->field) #define emit_getgl(as, r, field) emit_opgl(as, XO_MOV, (r)|REX_GC64, field) #define emit_setgl(as, r, field) emit_opgl(as, XO_MOVto, (r)|REX_GC64, field) #define emit_setvmstate(as, i) \ (emit_i32(as, i), emit_opgl(as, XO_MOVmi, 0, vmstate)) /* mov r, i / xor r, r */ static void emit_loadi(ASMState *as, Reg r, int32_t i) { /* XOR r,r is shorter, but modifies the flags. This is bad for HIOP/jcc. */ if (i == 0 && !(LJ_32 && (IR(as->curins)->o == IR_HIOP || (as->curins+1 < as->T->nins && IR(as->curins+1)->o == IR_HIOP))) && !((*as->mcp == 0x0f && (as->mcp[1] & 0xf0) == XI_JCCn) || (*as->mcp & 0xf0) == XI_JCCs)) { emit_rr(as, XO_ARITH(XOg_XOR), r, r); } else { MCode *p = as->mcp; *(int32_t *)(p-4) = i; p[-5] = (MCode)(XI_MOVri+(r&7)); p -= 5; REXRB(p, 0, r); as->mcp = p; } } #if LJ_GC64 #define dispofs(as, k) \ ((intptr_t)((uintptr_t)(k) - (uintptr_t)J2GG(as->J)->dispatch)) #define mcpofs(as, k) \ ((intptr_t)((uintptr_t)(k) - (uintptr_t)as->mcp)) #define mctopofs(as, k) \ ((intptr_t)((uintptr_t)(k) - (uintptr_t)as->mctop)) /* mov r, addr */ #define emit_loada(as, r, addr) \ emit_loadu64(as, (r), (uintptr_t)(addr)) #else /* mov r, addr */ #define emit_loada(as, r, addr) \ emit_loadi(as, (r), ptr2addr((addr))) #endif #if LJ_64 /* mov r, imm64 or shorter 32 bit extended load. */ static void emit_loadu64(ASMState *as, Reg r, uint64_t u64) { if (checku32(u64)) { /* 32 bit load clears upper 32 bits. */ emit_loadi(as, r, (int32_t)u64); } else if (checki32((int64_t)u64)) { /* Sign-extended 32 bit load. */ MCode *p = as->mcp; *(int32_t *)(p-4) = (int32_t)u64; as->mcp = emit_opm(XO_MOVmi, XM_REG, REX_64, r, p, -4); #if LJ_GC64 } else if (checki32(dispofs(as, u64))) { emit_rmro(as, XO_LEA, r|REX_64, RID_DISPATCH, (int32_t)dispofs(as, u64)); } else if (checki32(mcpofs(as, u64)) && checki32(mctopofs(as, u64))) { /* Since as->realign assumes the code size doesn't change, check ** RIP-relative addressing reachability for both as->mcp and as->mctop. */ emit_rmro(as, XO_LEA, r|REX_64, RID_RIP, (int32_t)mcpofs(as, u64)); #endif } else { /* Full-size 64 bit load. */ MCode *p = as->mcp; *(uint64_t *)(p-8) = u64; p[-9] = (MCode)(XI_MOVri+(r&7)); p[-10] = 0x48 + ((r>>3)&1); p -= 10; as->mcp = p; } } #endif /* op r, [addr] */ static void emit_rma(ASMState *as, x86Op xo, Reg rr, const void *addr) { #if LJ_GC64 if (checki32(dispofs(as, addr))) { emit_rmro(as, xo, rr, RID_DISPATCH, (int32_t)dispofs(as, addr)); } else if (checki32(mcpofs(as, addr)) && checki32(mctopofs(as, addr))) { emit_rmro(as, xo, rr, RID_RIP, (int32_t)mcpofs(as, addr)); } else if (!checki32((intptr_t)addr)) { Reg ra = (rr & 15); if (xo != XO_MOV) { /* We can't allocate a register here. Use and restore DISPATCH. Ugly. */ uint64_t dispaddr = (uintptr_t)J2GG(as->J)->dispatch; uint8_t i8 = xo == XO_GROUP3b ? *as->mcp++ : 0; ra = RID_DISPATCH; if (checku32(dispaddr)) { emit_loadi(as, ra, (int32_t)dispaddr); } else { /* Full-size 64 bit load. */ MCode *p = as->mcp; *(uint64_t *)(p-8) = dispaddr; p[-9] = (MCode)(XI_MOVri+(ra&7)); p[-10] = 0x48 + ((ra>>3)&1); p -= 10; as->mcp = p; } if (xo == XO_GROUP3b) emit_i8(as, i8); } emit_rmro(as, xo, rr, ra, 0); emit_loadu64(as, ra, (uintptr_t)addr); } else #endif { MCode *p = as->mcp; *(int32_t *)(p-4) = ptr2addr(addr); #if LJ_64 p[-5] = MODRM(XM_SCALE1, RID_ESP, RID_EBP); as->mcp = emit_opm(xo, XM_OFS0, rr, RID_ESP, p, -5); #else as->mcp = emit_opm(xo, XM_OFS0, rr, RID_EBP, p, -4); #endif } } /* Load 64 bit IR constant into register. */ static void emit_loadk64(ASMState *as, Reg r, IRIns *ir) { Reg r64; x86Op xo; const uint64_t *k = &ir_k64(ir)->u64; if (rset_test(RSET_FPR, r)) { r64 = r; xo = XO_MOVSD; } else { r64 = r | REX_64; xo = XO_MOV; } if (*k == 0) { emit_rr(as, rset_test(RSET_FPR, r) ? XO_XORPS : XO_ARITH(XOg_XOR), r, r); #if LJ_GC64 } else if (checki32((intptr_t)k) || checki32(dispofs(as, k)) || (checki32(mcpofs(as, k)) && checki32(mctopofs(as, k)))) { emit_rma(as, xo, r64, k); } else { if (ir->i) { lj_assertA(*k == *(uint64_t*)(as->mctop - ir->i), "bad interned 64 bit constant"); } else if (as->curins <= as->stopins && rset_test(RSET_GPR, r)) { emit_loadu64(as, r, *k); return; } else { /* If all else fails, add the FP constant at the MCode area bottom. */ while ((uintptr_t)as->mcbot & 7) *as->mcbot++ = XI_INT3; *(uint64_t *)as->mcbot = *k; ir->i = (int32_t)(as->mctop - as->mcbot); as->mcbot += 8; as->mclim = as->mcbot + MCLIM_REDZONE; lj_mcode_commitbot(as->J, as->mcbot); } emit_rmro(as, xo, r64, RID_RIP, (int32_t)mcpofs(as, as->mctop - ir->i)); #else } else { emit_rma(as, xo, r64, k); #endif } } /* -- Emit control-flow instructions -------------------------------------- */ /* Label for short jumps. */ typedef MCode *MCLabel; #if LJ_32 && LJ_HASFFI /* jmp short target */ static void emit_sjmp(ASMState *as, MCLabel target) { MCode *p = as->mcp; ptrdiff_t delta = target - p; lj_assertA(delta == (int8_t)delta, "short jump target out of range"); p[-1] = (MCode)(int8_t)delta; p[-2] = XI_JMPs; as->mcp = p - 2; } #endif /* jcc short target */ static void emit_sjcc(ASMState *as, int cc, MCLabel target) { MCode *p = as->mcp; ptrdiff_t delta = target - p; lj_assertA(delta == (int8_t)delta, "short jump target out of range"); p[-1] = (MCode)(int8_t)delta; p[-2] = (MCode)(XI_JCCs+(cc&15)); as->mcp = p - 2; } /* jcc short (pending target) */ static MCLabel emit_sjcc_label(ASMState *as, int cc) { MCode *p = as->mcp; p[-1] = 0; p[-2] = (MCode)(XI_JCCs+(cc&15)); as->mcp = p - 2; return p; } /* Fixup jcc short target. */ static void emit_sfixup(ASMState *as, MCLabel source) { source[-1] = (MCode)(as->mcp-source); } /* Return label pointing to current PC. */ #define emit_label(as) ((as)->mcp) /* Compute relative 32 bit offset for jump and call instructions. */ static LJ_AINLINE int32_t jmprel(jit_State *J, MCode *p, MCode *target) { ptrdiff_t delta = target - p; UNUSED(J); lj_assertJ(delta == (int32_t)delta, "jump target out of range"); return (int32_t)delta; } /* jcc target */ static void emit_jcc(ASMState *as, int cc, MCode *target) { MCode *p = as->mcp; *(int32_t *)(p-4) = jmprel(as->J, p, target); p[-5] = (MCode)(XI_JCCn+(cc&15)); p[-6] = 0x0f; as->mcp = p - 6; } /* jmp target */ static void emit_jmp(ASMState *as, MCode *target) { MCode *p = as->mcp; *(int32_t *)(p-4) = jmprel(as->J, p, target); p[-5] = XI_JMP; as->mcp = p - 5; } /* call target */ static void emit_call_(ASMState *as, MCode *target) { MCode *p = as->mcp; #if LJ_64 if (target-p != (int32_t)(target-p)) { /* Assumes RID_RET is never an argument to calls and always clobbered. */ emit_rr(as, XO_GROUP5, XOg_CALL, RID_RET); emit_loadu64(as, RID_RET, (uint64_t)target); return; } #endif *(int32_t *)(p-4) = jmprel(as->J, p, target); p[-5] = XI_CALL; as->mcp = p - 5; } #define emit_call(as, f) emit_call_(as, (MCode *)(void *)(f)) /* -- Emit generic operations --------------------------------------------- */ /* Use 64 bit operations to handle 64 bit IR types. */ #if LJ_64 #define REX_64IR(ir, r) ((r) + (irt_is64((ir)->t) ? REX_64 : 0)) #define VEX_64IR(ir, r) ((r) + (irt_is64((ir)->t) ? VEX_64 : 0)) #else #define REX_64IR(ir, r) (r) #define VEX_64IR(ir, r) (r) #endif /* Generic move between two regs. */ static void emit_movrr(ASMState *as, IRIns *ir, Reg dst, Reg src) { UNUSED(ir); if (dst < RID_MAX_GPR) emit_rr(as, XO_MOV, REX_64IR(ir, dst), src); else emit_rr(as, XO_MOVAPS, dst, src); } /* Generic load of register with base and (small) offset address. */ static void emit_loadofs(ASMState *as, IRIns *ir, Reg r, Reg base, int32_t ofs) { if (r < RID_MAX_GPR) emit_rmro(as, XO_MOV, REX_64IR(ir, r), base, ofs); else emit_rmro(as, irt_isnum(ir->t) ? XO_MOVSD : XO_MOVSS, r, base, ofs); } /* Generic store of register with base and (small) offset address. */ static void emit_storeofs(ASMState *as, IRIns *ir, Reg r, Reg base, int32_t ofs) { if (r < RID_MAX_GPR) emit_rmro(as, XO_MOVto, REX_64IR(ir, r), base, ofs); else emit_rmro(as, irt_isnum(ir->t) ? XO_MOVSDto : XO_MOVSSto, r, base, ofs); } /* Add offset to pointer. */ static void emit_addptr(ASMState *as, Reg r, int32_t ofs) { if (ofs) { emit_gri(as, XG_ARITHi(XOg_ADD), r|REX_GC64, ofs); } } #define emit_spsub(as, ofs) emit_addptr(as, RID_ESP|REX_64, -(ofs)) /* Prefer rematerialization of BASE/L from global_State over spills. */ #define emit_canremat(ref) ((ref) <= REF_BASE)
xLua/build/luajit-2.1.0b3/src/lj_emit_x86.h/0
{ "file_path": "xLua/build/luajit-2.1.0b3/src/lj_emit_x86.h", "repo_id": "xLua", "token_count": 8100 }
2,050
/* ** IR CALL* instruction definitions. ** Copyright (C) 2005-2021 Mike Pall. See Copyright Notice in luajit.h */ #ifndef _LJ_IRCALL_H #define _LJ_IRCALL_H #include "lj_obj.h" #include "lj_ir.h" #include "lj_jit.h" /* C call info for CALL* instructions. */ typedef struct CCallInfo { ASMFunction func; /* Function pointer. */ uint32_t flags; /* Number of arguments and flags. */ } CCallInfo; #define CCI_NARGS(ci) ((ci)->flags & 0xff) /* # of args. */ #define CCI_NARGS_MAX 32 /* Max. # of args. */ #define CCI_OTSHIFT 16 #define CCI_OPTYPE(ci) ((ci)->flags >> CCI_OTSHIFT) /* Get op/type. */ #define CCI_TYPE(ci) (((ci)->flags>>CCI_OTSHIFT) & IRT_TYPE) #define CCI_OPSHIFT 24 #define CCI_OP(ci) ((ci)->flags >> CCI_OPSHIFT) /* Get op. */ #define CCI_CALL_N (IR_CALLN << CCI_OPSHIFT) #define CCI_CALL_A (IR_CALLA << CCI_OPSHIFT) #define CCI_CALL_L (IR_CALLL << CCI_OPSHIFT) #define CCI_CALL_S (IR_CALLS << CCI_OPSHIFT) #define CCI_CALL_FN (CCI_CALL_N|CCI_CC_FASTCALL) #define CCI_CALL_FA (CCI_CALL_A|CCI_CC_FASTCALL) #define CCI_CALL_FL (CCI_CALL_L|CCI_CC_FASTCALL) #define CCI_CALL_FS (CCI_CALL_S|CCI_CC_FASTCALL) /* C call info flags. */ #define CCI_T (IRT_GUARD << CCI_OTSHIFT) /* May throw. */ #define CCI_L 0x0100 /* Implicit L arg. */ #define CCI_CASTU64 0x0200 /* Cast u64 result to number. */ #define CCI_NOFPRCLOBBER 0x0400 /* Does not clobber any FPRs. */ #define CCI_VARARG 0x0800 /* Vararg function. */ #define CCI_CC_MASK 0x3000 /* Calling convention mask. */ #define CCI_CC_SHIFT 12 /* ORDER CC */ #define CCI_CC_CDECL 0x0000 /* Default cdecl calling convention. */ #define CCI_CC_THISCALL 0x1000 /* Thiscall calling convention. */ #define CCI_CC_FASTCALL 0x2000 /* Fastcall calling convention. */ #define CCI_CC_STDCALL 0x3000 /* Stdcall calling convention. */ /* Extra args for SOFTFP, SPLIT 64 bit. */ #define CCI_XARGS_SHIFT 14 #define CCI_XARGS(ci) (((ci)->flags >> CCI_XARGS_SHIFT) & 3) #define CCI_XA (1u << CCI_XARGS_SHIFT) #if LJ_SOFTFP32 || (LJ_32 && LJ_HASFFI) #define CCI_XNARGS(ci) (CCI_NARGS((ci)) + CCI_XARGS((ci))) #else #define CCI_XNARGS(ci) CCI_NARGS((ci)) #endif /* Helpers for conditional function definitions. */ #define IRCALLCOND_ANY(x) x #if LJ_TARGET_X86ORX64 #define IRCALLCOND_FPMATH(x) NULL #else #define IRCALLCOND_FPMATH(x) x #endif #if LJ_SOFTFP #define IRCALLCOND_SOFTFP(x) x #if LJ_HASFFI #define IRCALLCOND_SOFTFP_FFI(x) x #else #define IRCALLCOND_SOFTFP_FFI(x) NULL #endif #else #define IRCALLCOND_SOFTFP(x) NULL #define IRCALLCOND_SOFTFP_FFI(x) NULL #endif #if LJ_SOFTFP && LJ_TARGET_MIPS #define IRCALLCOND_SOFTFP_MIPS(x) x #else #define IRCALLCOND_SOFTFP_MIPS(x) NULL #endif #if LJ_SOFTFP && LJ_TARGET_MIPS64 #define IRCALLCOND_SOFTFP_MIPS64(x) x #else #define IRCALLCOND_SOFTFP_MIPS64(x) NULL #endif #define LJ_NEED_FP64 (LJ_TARGET_ARM || LJ_TARGET_PPC || LJ_TARGET_MIPS) #if LJ_HASFFI && (LJ_SOFTFP || LJ_NEED_FP64) #define IRCALLCOND_FP64_FFI(x) x #else #define IRCALLCOND_FP64_FFI(x) NULL #endif #if LJ_HASFFI #define IRCALLCOND_FFI(x) x #if LJ_32 #define IRCALLCOND_FFI32(x) x #else #define IRCALLCOND_FFI32(x) NULL #endif #else #define IRCALLCOND_FFI(x) NULL #define IRCALLCOND_FFI32(x) NULL #endif #if LJ_HASBUFFER #define IRCALLCOND_BUFFER(x) x #else #define IRCALLCOND_BUFFER(x) NULL #endif #if LJ_HASBUFFER && LJ_HASFFI #define IRCALLCOND_BUFFFI(x) x #else #define IRCALLCOND_BUFFFI(x) NULL #endif #if LJ_SOFTFP #define XA_FP CCI_XA #define XA2_FP (CCI_XA+CCI_XA) #else #define XA_FP 0 #define XA2_FP 0 #endif #if LJ_SOFTFP32 #define XA_FP32 CCI_XA #define XA2_FP32 (CCI_XA+CCI_XA) #else #define XA_FP32 0 #define XA2_FP32 0 #endif #if LJ_32 #define XA_64 CCI_XA #define XA2_64 (CCI_XA+CCI_XA) #else #define XA_64 0 #define XA2_64 0 #endif /* Function definitions for CALL* instructions. */ #define IRCALLDEF(_) \ _(ANY, lj_str_cmp, 2, FN, INT, CCI_NOFPRCLOBBER) \ _(ANY, lj_str_find, 4, N, PGC, 0) \ _(ANY, lj_str_new, 3, S, STR, CCI_L|CCI_T) \ _(ANY, lj_strscan_num, 2, FN, INT, 0) \ _(ANY, lj_strfmt_int, 2, FN, STR, CCI_L|CCI_T) \ _(ANY, lj_strfmt_num, 2, FN, STR, CCI_L|CCI_T) \ _(ANY, lj_strfmt_char, 2, FN, STR, CCI_L|CCI_T) \ _(ANY, lj_strfmt_putint, 2, FL, PGC, CCI_T) \ _(ANY, lj_strfmt_putnum, 2, FL, PGC, CCI_T) \ _(ANY, lj_strfmt_putquoted, 2, FL, PGC, CCI_T) \ _(ANY, lj_strfmt_putfxint, 3, L, PGC, XA_64|CCI_T) \ _(ANY, lj_strfmt_putfnum_int, 3, L, PGC, XA_FP|CCI_T) \ _(ANY, lj_strfmt_putfnum_uint, 3, L, PGC, XA_FP|CCI_T) \ _(ANY, lj_strfmt_putfnum, 3, L, PGC, XA_FP|CCI_T) \ _(ANY, lj_strfmt_putfstr, 3, L, PGC, CCI_T) \ _(ANY, lj_strfmt_putfchar, 3, L, PGC, CCI_T) \ _(ANY, lj_buf_putmem, 3, S, PGC, CCI_T) \ _(ANY, lj_buf_putstr, 2, FL, PGC, CCI_T) \ _(ANY, lj_buf_putchar, 2, FL, PGC, CCI_T) \ _(ANY, lj_buf_putstr_reverse, 2, FL, PGC, CCI_T) \ _(ANY, lj_buf_putstr_lower, 2, FL, PGC, CCI_T) \ _(ANY, lj_buf_putstr_upper, 2, FL, PGC, CCI_T) \ _(ANY, lj_buf_putstr_rep, 3, L, PGC, CCI_T) \ _(ANY, lj_buf_puttab, 5, L, PGC, CCI_T) \ _(BUFFER, lj_bufx_set, 4, S, NIL, 0) \ _(BUFFFI, lj_bufx_more, 2, FS, INT, CCI_T) \ _(BUFFER, lj_serialize_put, 2, FS, PGC, CCI_T) \ _(BUFFER, lj_serialize_get, 2, FS, PTR, CCI_T) \ _(BUFFER, lj_serialize_encode, 2, FA, STR, CCI_L|CCI_T) \ _(BUFFER, lj_serialize_decode, 3, A, INT, CCI_L|CCI_T) \ _(ANY, lj_buf_tostr, 1, FL, STR, CCI_T) \ _(ANY, lj_tab_new_ah, 3, A, TAB, CCI_L|CCI_T) \ _(ANY, lj_tab_new1, 2, FA, TAB, CCI_L|CCI_T) \ _(ANY, lj_tab_dup, 2, FA, TAB, CCI_L|CCI_T) \ _(ANY, lj_tab_clear, 1, FS, NIL, 0) \ _(ANY, lj_tab_newkey, 3, S, PGC, CCI_L|CCI_T) \ _(ANY, lj_tab_keyindex, 2, FL, INT, 0) \ _(ANY, lj_vm_next, 2, FL, PTR, 0) \ _(ANY, lj_tab_len, 1, FL, INT, 0) \ _(ANY, lj_tab_len_hint, 2, FL, INT, 0) \ _(ANY, lj_gc_step_jit, 2, FS, NIL, CCI_L) \ _(ANY, lj_gc_barrieruv, 2, FS, NIL, 0) \ _(ANY, lj_mem_newgco, 2, FA, PGC, CCI_L|CCI_T) \ _(ANY, lj_prng_u64d, 1, FS, NUM, CCI_CASTU64) \ _(ANY, lj_vm_modi, 2, FN, INT, 0) \ _(ANY, log10, 1, N, NUM, XA_FP) \ _(ANY, exp, 1, N, NUM, XA_FP) \ _(ANY, sin, 1, N, NUM, XA_FP) \ _(ANY, cos, 1, N, NUM, XA_FP) \ _(ANY, tan, 1, N, NUM, XA_FP) \ _(ANY, asin, 1, N, NUM, XA_FP) \ _(ANY, acos, 1, N, NUM, XA_FP) \ _(ANY, atan, 1, N, NUM, XA_FP) \ _(ANY, sinh, 1, N, NUM, XA_FP) \ _(ANY, cosh, 1, N, NUM, XA_FP) \ _(ANY, tanh, 1, N, NUM, XA_FP) \ _(ANY, fputc, 2, S, INT, 0) \ _(ANY, fwrite, 4, S, INT, 0) \ _(ANY, fflush, 1, S, INT, 0) \ /* ORDER FPM */ \ _(FPMATH, lj_vm_floor, 1, N, NUM, XA_FP) \ _(FPMATH, lj_vm_ceil, 1, N, NUM, XA_FP) \ _(FPMATH, lj_vm_trunc, 1, N, NUM, XA_FP) \ _(FPMATH, sqrt, 1, N, NUM, XA_FP) \ _(ANY, log, 1, N, NUM, XA_FP) \ _(ANY, lj_vm_log2, 1, N, NUM, XA_FP) \ _(ANY, lj_vm_powi, 2, N, NUM, XA_FP) \ _(ANY, pow, 2, N, NUM, XA2_FP) \ _(ANY, atan2, 2, N, NUM, XA2_FP) \ _(ANY, ldexp, 2, N, NUM, XA_FP) \ _(SOFTFP, lj_vm_tobit, 1, N, INT, XA_FP32) \ _(SOFTFP, softfp_add, 2, N, NUM, XA2_FP32) \ _(SOFTFP, softfp_sub, 2, N, NUM, XA2_FP32) \ _(SOFTFP, softfp_mul, 2, N, NUM, XA2_FP32) \ _(SOFTFP, softfp_div, 2, N, NUM, XA2_FP32) \ _(SOFTFP, softfp_cmp, 2, N, NIL, XA2_FP32) \ _(SOFTFP, softfp_i2d, 1, N, NUM, 0) \ _(SOFTFP, softfp_d2i, 1, N, INT, XA_FP32) \ _(SOFTFP_MIPS, lj_vm_sfmin, 2, N, NUM, XA2_FP32) \ _(SOFTFP_MIPS, lj_vm_sfmax, 2, N, NUM, XA2_FP32) \ _(SOFTFP_MIPS64, lj_vm_tointg, 1, N, INT, 0) \ _(SOFTFP_FFI, softfp_ui2d, 1, N, NUM, 0) \ _(SOFTFP_FFI, softfp_f2d, 1, N, NUM, 0) \ _(SOFTFP_FFI, softfp_d2ui, 1, N, INT, XA_FP32) \ _(SOFTFP_FFI, softfp_d2f, 1, N, FLOAT, XA_FP32) \ _(SOFTFP_FFI, softfp_i2f, 1, N, FLOAT, 0) \ _(SOFTFP_FFI, softfp_ui2f, 1, N, FLOAT, 0) \ _(SOFTFP_FFI, softfp_f2i, 1, N, INT, 0) \ _(SOFTFP_FFI, softfp_f2ui, 1, N, INT, 0) \ _(FP64_FFI, fp64_l2d, 1, N, NUM, XA_64) \ _(FP64_FFI, fp64_ul2d, 1, N, NUM, XA_64) \ _(FP64_FFI, fp64_l2f, 1, N, FLOAT, XA_64) \ _(FP64_FFI, fp64_ul2f, 1, N, FLOAT, XA_64) \ _(FP64_FFI, fp64_d2l, 1, N, I64, XA_FP) \ _(FP64_FFI, fp64_d2ul, 1, N, U64, XA_FP) \ _(FP64_FFI, fp64_f2l, 1, N, I64, 0) \ _(FP64_FFI, fp64_f2ul, 1, N, U64, 0) \ _(FFI, lj_carith_divi64, 2, N, I64, XA2_64|CCI_NOFPRCLOBBER) \ _(FFI, lj_carith_divu64, 2, N, U64, XA2_64|CCI_NOFPRCLOBBER) \ _(FFI, lj_carith_modi64, 2, N, I64, XA2_64|CCI_NOFPRCLOBBER) \ _(FFI, lj_carith_modu64, 2, N, U64, XA2_64|CCI_NOFPRCLOBBER) \ _(FFI, lj_carith_powi64, 2, N, I64, XA2_64|CCI_NOFPRCLOBBER) \ _(FFI, lj_carith_powu64, 2, N, U64, XA2_64|CCI_NOFPRCLOBBER) \ _(FFI, lj_cdata_newv, 4, S, CDATA, CCI_L) \ _(FFI, lj_cdata_setfin, 4, S, NIL, CCI_L) \ _(FFI, strlen, 1, L, INTP, 0) \ _(FFI, memcpy, 3, S, PTR, 0) \ _(FFI, memset, 3, S, PTR, 0) \ _(FFI, lj_vm_errno, 0, S, INT, CCI_NOFPRCLOBBER) \ _(FFI32, lj_carith_mul64, 2, N, I64, XA2_64|CCI_NOFPRCLOBBER) \ _(FFI32, lj_carith_shl64, 2, N, U64, XA_64|CCI_NOFPRCLOBBER) \ _(FFI32, lj_carith_shr64, 2, N, U64, XA_64|CCI_NOFPRCLOBBER) \ _(FFI32, lj_carith_sar64, 2, N, U64, XA_64|CCI_NOFPRCLOBBER) \ _(FFI32, lj_carith_rol64, 2, N, U64, XA_64|CCI_NOFPRCLOBBER) \ _(FFI32, lj_carith_ror64, 2, N, U64, XA_64|CCI_NOFPRCLOBBER) \ \ /* End of list. */ typedef enum { #define IRCALLENUM(cond, name, nargs, kind, type, flags) IRCALL_##name, IRCALLDEF(IRCALLENUM) #undef IRCALLENUM IRCALL__MAX } IRCallID; LJ_FUNC TRef lj_ir_call(jit_State *J, IRCallID id, ...); LJ_DATA const CCallInfo lj_ir_callinfo[IRCALL__MAX+1]; /* Soft-float declarations. */ #if LJ_SOFTFP #if LJ_TARGET_ARM #define softfp_add __aeabi_dadd #define softfp_sub __aeabi_dsub #define softfp_mul __aeabi_dmul #define softfp_div __aeabi_ddiv #define softfp_cmp __aeabi_cdcmple #define softfp_i2d __aeabi_i2d #define softfp_d2i __aeabi_d2iz #define softfp_ui2d __aeabi_ui2d #define softfp_f2d __aeabi_f2d #define softfp_d2ui __aeabi_d2uiz #define softfp_d2f __aeabi_d2f #define softfp_i2f __aeabi_i2f #define softfp_ui2f __aeabi_ui2f #define softfp_f2i __aeabi_f2iz #define softfp_f2ui __aeabi_f2uiz #define fp64_l2d __aeabi_l2d #define fp64_ul2d __aeabi_ul2d #define fp64_l2f __aeabi_l2f #define fp64_ul2f __aeabi_ul2f #if LJ_TARGET_IOS #define fp64_d2l __fixdfdi #define fp64_d2ul __fixunsdfdi #define fp64_f2l __fixsfdi #define fp64_f2ul __fixunssfdi #else #define fp64_d2l __aeabi_d2lz #define fp64_d2ul __aeabi_d2ulz #define fp64_f2l __aeabi_f2lz #define fp64_f2ul __aeabi_f2ulz #endif #elif LJ_TARGET_MIPS || LJ_TARGET_PPC #define softfp_add __adddf3 #define softfp_sub __subdf3 #define softfp_mul __muldf3 #define softfp_div __divdf3 #define softfp_cmp __ledf2 #define softfp_i2d __floatsidf #define softfp_d2i __fixdfsi #define softfp_ui2d __floatunsidf #define softfp_f2d __extendsfdf2 #define softfp_d2ui __fixunsdfsi #define softfp_d2f __truncdfsf2 #define softfp_i2f __floatsisf #define softfp_ui2f __floatunsisf #define softfp_f2i __fixsfsi #define softfp_f2ui __fixunssfsi #else #error "Missing soft-float definitions for target architecture" #endif extern double softfp_add(double a, double b); extern double softfp_sub(double a, double b); extern double softfp_mul(double a, double b); extern double softfp_div(double a, double b); extern void softfp_cmp(double a, double b); extern double softfp_i2d(int32_t a); extern int32_t softfp_d2i(double a); #if LJ_HASFFI extern double softfp_ui2d(uint32_t a); extern double softfp_f2d(float a); extern uint32_t softfp_d2ui(double a); extern float softfp_d2f(double a); extern float softfp_i2f(int32_t a); extern float softfp_ui2f(uint32_t a); extern int32_t softfp_f2i(float a); extern uint32_t softfp_f2ui(float a); #endif #if LJ_TARGET_MIPS extern double lj_vm_sfmin(double a, double b); extern double lj_vm_sfmax(double a, double b); #endif #endif #if LJ_HASFFI && LJ_NEED_FP64 && !(LJ_TARGET_ARM && LJ_SOFTFP) #if defined(__GNUC__) || defined(__clang__) #define fp64_l2d __floatdidf #define fp64_ul2d __floatundidf #define fp64_l2f __floatdisf #define fp64_ul2f __floatundisf #define fp64_d2l __fixdfdi #define fp64_d2ul __fixunsdfdi #define fp64_f2l __fixsfdi #define fp64_f2ul __fixunssfdi #else #error "Missing fp64 helper definitions for this compiler" #endif #endif #if LJ_HASFFI && (LJ_SOFTFP || LJ_NEED_FP64) extern double fp64_l2d(int64_t a); extern double fp64_ul2d(uint64_t a); extern float fp64_l2f(int64_t a); extern float fp64_ul2f(uint64_t a); extern int64_t fp64_d2l(double a); extern uint64_t fp64_d2ul(double a); extern int64_t fp64_f2l(float a); extern uint64_t fp64_f2ul(float a); #endif #endif
xLua/build/luajit-2.1.0b3/src/lj_ircall.h/0
{ "file_path": "xLua/build/luajit-2.1.0b3/src/lj_ircall.h", "repo_id": "xLua", "token_count": 7231 }
2,051
/* ** LOOP: Loop Optimizations. ** Copyright (C) 2005-2021 Mike Pall. See Copyright Notice in luajit.h */ #define lj_opt_loop_c #define LUA_CORE #include "lj_obj.h" #if LJ_HASJIT #include "lj_err.h" #include "lj_buf.h" #include "lj_ir.h" #include "lj_jit.h" #include "lj_iropt.h" #include "lj_trace.h" #include "lj_snap.h" #include "lj_vm.h" /* Loop optimization: ** ** Traditional Loop-Invariant Code Motion (LICM) splits the instructions ** of a loop into invariant and variant instructions. The invariant ** instructions are hoisted out of the loop and only the variant ** instructions remain inside the loop body. ** ** Unfortunately LICM is mostly useless for compiling dynamic languages. ** The IR has many guards and most of the subsequent instructions are ** control-dependent on them. The first non-hoistable guard would ** effectively prevent hoisting of all subsequent instructions. ** ** That's why we use a special form of unrolling using copy-substitution, ** combined with redundancy elimination: ** ** The recorded instruction stream is re-emitted to the compiler pipeline ** with substituted operands. The substitution table is filled with the ** refs returned by re-emitting each instruction. This can be done ** on-the-fly, because the IR is in strict SSA form, where every ref is ** defined before its use. ** ** This aproach generates two code sections, separated by the LOOP ** instruction: ** ** 1. The recorded instructions form a kind of pre-roll for the loop. It ** contains a mix of invariant and variant instructions and performs ** exactly one loop iteration (but not necessarily the 1st iteration). ** ** 2. The loop body contains only the variant instructions and performs ** all remaining loop iterations. ** ** On first sight that looks like a waste of space, because the variant ** instructions are present twice. But the key insight is that the ** pre-roll honors the control-dependencies for *both* the pre-roll itself ** *and* the loop body! ** ** It also means one doesn't have to explicitly model control-dependencies ** (which, BTW, wouldn't help LICM much). And it's much easier to ** integrate sparse snapshotting with this approach. ** ** One of the nicest aspects of this approach is that all of the ** optimizations of the compiler pipeline (FOLD, CSE, FWD, etc.) can be ** reused with only minor restrictions (e.g. one should not fold ** instructions across loop-carried dependencies). ** ** But in general all optimizations can be applied which only need to look ** backwards into the generated instruction stream. At any point in time ** during the copy-substitution process this contains both a static loop ** iteration (the pre-roll) and a dynamic one (from the to-be-copied ** instruction up to the end of the partial loop body). ** ** Since control-dependencies are implicitly kept, CSE also applies to all ** kinds of guards. The major advantage is that all invariant guards can ** be hoisted, too. ** ** Load/store forwarding works across loop iterations, too. This is ** important if loop-carried dependencies are kept in upvalues or tables. ** E.g. 'self.idx = self.idx + 1' deep down in some OO-style method may ** become a forwarded loop-recurrence after inlining. ** ** Since the IR is in SSA form, loop-carried dependencies have to be ** modeled with PHI instructions. The potential candidates for PHIs are ** collected on-the-fly during copy-substitution. After eliminating the ** redundant ones, PHI instructions are emitted *below* the loop body. ** ** Note that this departure from traditional SSA form doesn't change the ** semantics of the PHI instructions themselves. But it greatly simplifies ** on-the-fly generation of the IR and the machine code. */ /* Some local macros to save typing. Undef'd at the end. */ #define IR(ref) (&J->cur.ir[(ref)]) /* Pass IR on to next optimization in chain (FOLD). */ #define emitir(ot, a, b) (lj_ir_set(J, (ot), (a), (b)), lj_opt_fold(J)) /* Emit raw IR without passing through optimizations. */ #define emitir_raw(ot, a, b) (lj_ir_set(J, (ot), (a), (b)), lj_ir_emit(J)) /* -- PHI elimination ----------------------------------------------------- */ /* Emit or eliminate collected PHIs. */ static void loop_emit_phi(jit_State *J, IRRef1 *subst, IRRef1 *phi, IRRef nphi, SnapNo onsnap) { int passx = 0; IRRef i, j, nslots; IRRef invar = J->chain[IR_LOOP]; /* Pass #1: mark redundant and potentially redundant PHIs. */ for (i = 0, j = 0; i < nphi; i++) { IRRef lref = phi[i]; IRRef rref = subst[lref]; if (lref == rref || rref == REF_DROP) { /* Invariants are redundant. */ irt_clearphi(IR(lref)->t); } else { phi[j++] = (IRRef1)lref; if (!(IR(rref)->op1 == lref || IR(rref)->op2 == lref)) { /* Quick check for simple recurrences failed, need pass2. */ irt_setmark(IR(lref)->t); passx = 1; } } } nphi = j; /* Pass #2: traverse variant part and clear marks of non-redundant PHIs. */ if (passx) { SnapNo s; for (i = J->cur.nins-1; i > invar; i--) { IRIns *ir = IR(i); if (!irref_isk(ir->op2)) irt_clearmark(IR(ir->op2)->t); if (!irref_isk(ir->op1)) { irt_clearmark(IR(ir->op1)->t); if (ir->op1 < invar && ir->o >= IR_CALLN && ir->o <= IR_CARG) { /* ORDER IR */ ir = IR(ir->op1); while (ir->o == IR_CARG) { if (!irref_isk(ir->op2)) irt_clearmark(IR(ir->op2)->t); if (irref_isk(ir->op1)) break; ir = IR(ir->op1); irt_clearmark(ir->t); } } } } for (s = J->cur.nsnap-1; s >= onsnap; s--) { SnapShot *snap = &J->cur.snap[s]; SnapEntry *map = &J->cur.snapmap[snap->mapofs]; MSize n, nent = snap->nent; for (n = 0; n < nent; n++) { IRRef ref = snap_ref(map[n]); if (!irref_isk(ref)) irt_clearmark(IR(ref)->t); } } } /* Pass #3: add PHIs for variant slots without a corresponding SLOAD. */ nslots = J->baseslot+J->maxslot; for (i = 1; i < nslots; i++) { IRRef ref = tref_ref(J->slot[i]); while (!irref_isk(ref) && ref != subst[ref]) { IRIns *ir = IR(ref); irt_clearmark(ir->t); /* Unmark potential uses, too. */ if (irt_isphi(ir->t) || irt_ispri(ir->t)) break; irt_setphi(ir->t); if (nphi >= LJ_MAX_PHI) lj_trace_err(J, LJ_TRERR_PHIOV); phi[nphi++] = (IRRef1)ref; ref = subst[ref]; if (ref > invar) break; } } /* Pass #4: propagate non-redundant PHIs. */ while (passx) { passx = 0; for (i = 0; i < nphi; i++) { IRRef lref = phi[i]; IRIns *ir = IR(lref); if (!irt_ismarked(ir->t)) { /* Propagate only from unmarked PHIs. */ IRIns *irr = IR(subst[lref]); if (irt_ismarked(irr->t)) { /* Right ref points to other PHI? */ irt_clearmark(irr->t); /* Mark that PHI as non-redundant. */ passx = 1; /* Retry. */ } } } } /* Pass #5: emit PHI instructions or eliminate PHIs. */ for (i = 0; i < nphi; i++) { IRRef lref = phi[i]; IRIns *ir = IR(lref); if (!irt_ismarked(ir->t)) { /* Emit PHI if not marked. */ IRRef rref = subst[lref]; if (rref > invar) irt_setphi(IR(rref)->t); emitir_raw(IRT(IR_PHI, irt_type(ir->t)), lref, rref); } else { /* Otherwise eliminate PHI. */ irt_clearmark(ir->t); irt_clearphi(ir->t); } } } /* -- Loop unrolling using copy-substitution ------------------------------ */ /* Copy-substitute snapshot. */ static void loop_subst_snap(jit_State *J, SnapShot *osnap, SnapEntry *loopmap, IRRef1 *subst) { SnapEntry *nmap, *omap = &J->cur.snapmap[osnap->mapofs]; SnapEntry *nextmap = &J->cur.snapmap[snap_nextofs(&J->cur, osnap)]; MSize nmapofs; MSize on, ln, nn, onent = osnap->nent; BCReg nslots = osnap->nslots; SnapShot *snap = &J->cur.snap[J->cur.nsnap]; if (irt_isguard(J->guardemit)) { /* Guard inbetween? */ nmapofs = J->cur.nsnapmap; J->cur.nsnap++; /* Add new snapshot. */ } else { /* Otherwise overwrite previous snapshot. */ snap--; nmapofs = snap->mapofs; } J->guardemit.irt = 0; /* Setup new snapshot. */ snap->mapofs = (uint32_t)nmapofs; snap->ref = (IRRef1)J->cur.nins; snap->mcofs = 0; snap->nslots = nslots; snap->topslot = osnap->topslot; snap->count = 0; nmap = &J->cur.snapmap[nmapofs]; /* Substitute snapshot slots. */ on = ln = nn = 0; while (on < onent) { SnapEntry osn = omap[on], lsn = loopmap[ln]; if (snap_slot(lsn) < snap_slot(osn)) { /* Copy slot from loop map. */ nmap[nn++] = lsn; ln++; } else { /* Copy substituted slot from snapshot map. */ if (snap_slot(lsn) == snap_slot(osn)) ln++; /* Shadowed loop slot. */ if (!irref_isk(snap_ref(osn))) osn = snap_setref(osn, subst[snap_ref(osn)]); nmap[nn++] = osn; on++; } } while (snap_slot(loopmap[ln]) < nslots) /* Copy remaining loop slots. */ nmap[nn++] = loopmap[ln++]; snap->nent = (uint8_t)nn; omap += onent; nmap += nn; while (omap < nextmap) /* Copy PC + frame links. */ *nmap++ = *omap++; J->cur.nsnapmap = (uint32_t)(nmap - J->cur.snapmap); } typedef struct LoopState { jit_State *J; IRRef1 *subst; MSize sizesubst; } LoopState; /* Unroll loop. */ static void loop_unroll(LoopState *lps) { jit_State *J = lps->J; IRRef1 phi[LJ_MAX_PHI]; uint32_t nphi = 0; IRRef1 *subst; SnapNo onsnap; SnapShot *osnap, *loopsnap; SnapEntry *loopmap, *psentinel; IRRef ins, invar; /* Allocate substitution table. ** Only non-constant refs in [REF_BIAS,invar) are valid indexes. */ invar = J->cur.nins; lps->sizesubst = invar - REF_BIAS; lps->subst = lj_mem_newvec(J->L, lps->sizesubst, IRRef1); subst = lps->subst - REF_BIAS; subst[REF_BASE] = REF_BASE; /* LOOP separates the pre-roll from the loop body. */ emitir_raw(IRTG(IR_LOOP, IRT_NIL), 0, 0); /* Grow snapshot buffer and map for copy-substituted snapshots. ** Need up to twice the number of snapshots minus #0 and loop snapshot. ** Need up to twice the number of entries plus fallback substitutions ** from the loop snapshot entries for each new snapshot. ** Caveat: both calls may reallocate J->cur.snap and J->cur.snapmap! */ onsnap = J->cur.nsnap; lj_snap_grow_buf(J, 2*onsnap-2); lj_snap_grow_map(J, J->cur.nsnapmap*2+(onsnap-2)*J->cur.snap[onsnap-1].nent); /* The loop snapshot is used for fallback substitutions. */ loopsnap = &J->cur.snap[onsnap-1]; loopmap = &J->cur.snapmap[loopsnap->mapofs]; /* The PC of snapshot #0 and the loop snapshot must match. */ psentinel = &loopmap[loopsnap->nent]; lj_assertJ(*psentinel == J->cur.snapmap[J->cur.snap[0].nent], "mismatched PC for loop snapshot"); *psentinel = SNAP(255, 0, 0); /* Replace PC with temporary sentinel. */ /* Start substitution with snapshot #1 (#0 is empty for root traces). */ osnap = &J->cur.snap[1]; /* Copy and substitute all recorded instructions and snapshots. */ for (ins = REF_FIRST; ins < invar; ins++) { IRIns *ir; IRRef op1, op2; if (ins >= osnap->ref) /* Instruction belongs to next snapshot? */ loop_subst_snap(J, osnap++, loopmap, subst); /* Copy-substitute it. */ /* Substitute instruction operands. */ ir = IR(ins); op1 = ir->op1; if (!irref_isk(op1)) op1 = subst[op1]; op2 = ir->op2; if (!irref_isk(op2)) op2 = subst[op2]; if (irm_kind(lj_ir_mode[ir->o]) == IRM_N && op1 == ir->op1 && op2 == ir->op2) { /* Regular invariant ins? */ subst[ins] = (IRRef1)ins; /* Shortcut. */ } else { /* Re-emit substituted instruction to the FOLD/CSE/etc. pipeline. */ IRType1 t = ir->t; /* Get this first, since emitir may invalidate ir. */ IRRef ref = tref_ref(emitir(ir->ot & ~IRT_ISPHI, op1, op2)); subst[ins] = (IRRef1)ref; if (ref != ins) { IRIns *irr = IR(ref); if (ref < invar) { /* Loop-carried dependency? */ /* Potential PHI? */ if (!irref_isk(ref) && !irt_isphi(irr->t) && !irt_ispri(irr->t)) { irt_setphi(irr->t); if (nphi >= LJ_MAX_PHI) lj_trace_err(J, LJ_TRERR_PHIOV); phi[nphi++] = (IRRef1)ref; } /* Check all loop-carried dependencies for type instability. */ if (!irt_sametype(t, irr->t)) { if (irt_isinteger(t) && irt_isinteger(irr->t)) continue; else if (irt_isnum(t) && irt_isinteger(irr->t)) /* Fix int->num. */ ref = tref_ref(emitir(IRTN(IR_CONV), ref, IRCONV_NUM_INT)); else if (irt_isnum(irr->t) && irt_isinteger(t)) /* Fix num->int. */ ref = tref_ref(emitir(IRTGI(IR_CONV), ref, IRCONV_INT_NUM|IRCONV_CHECK)); else lj_trace_err(J, LJ_TRERR_TYPEINS); subst[ins] = (IRRef1)ref; irr = IR(ref); goto phiconv; } } else if (ref != REF_DROP && ref > invar && ((irr->o == IR_CONV && irr->op1 < invar) || (irr->o == IR_ALEN && irr->op2 < invar && irr->op2 != REF_NIL))) { /* May need an extra PHI for a CONV or ALEN hint. */ ref = irr->o == IR_CONV ? irr->op1 : irr->op2; irr = IR(ref); phiconv: if (ref < invar && !irref_isk(ref) && !irt_isphi(irr->t)) { irt_setphi(irr->t); if (nphi >= LJ_MAX_PHI) lj_trace_err(J, LJ_TRERR_PHIOV); phi[nphi++] = (IRRef1)ref; } } } } } if (!irt_isguard(J->guardemit)) /* Drop redundant snapshot. */ J->cur.nsnapmap = (uint32_t)J->cur.snap[--J->cur.nsnap].mapofs; lj_assertJ(J->cur.nsnapmap <= J->sizesnapmap, "bad snapshot map index"); *psentinel = J->cur.snapmap[J->cur.snap[0].nent]; /* Restore PC. */ loop_emit_phi(J, subst, phi, nphi, onsnap); } /* Undo any partial changes made by the loop optimization. */ static void loop_undo(jit_State *J, IRRef ins, SnapNo nsnap, MSize nsnapmap) { ptrdiff_t i; SnapShot *snap = &J->cur.snap[nsnap-1]; SnapEntry *map = J->cur.snapmap; map[snap->mapofs + snap->nent] = map[J->cur.snap[0].nent]; /* Restore PC. */ J->cur.nsnapmap = (uint32_t)nsnapmap; J->cur.nsnap = nsnap; J->guardemit.irt = 0; lj_ir_rollback(J, ins); for (i = 0; i < BPROP_SLOTS; i++) { /* Remove backprop. cache entries. */ BPropEntry *bp = &J->bpropcache[i]; if (bp->val >= ins) bp->key = 0; } for (ins--; ins >= REF_FIRST; ins--) { /* Remove flags. */ IRIns *ir = IR(ins); irt_clearphi(ir->t); irt_clearmark(ir->t); } } /* Protected callback for loop optimization. */ static TValue *cploop_opt(lua_State *L, lua_CFunction dummy, void *ud) { UNUSED(L); UNUSED(dummy); loop_unroll((LoopState *)ud); return NULL; } /* Loop optimization. */ int lj_opt_loop(jit_State *J) { IRRef nins = J->cur.nins; SnapNo nsnap = J->cur.nsnap; MSize nsnapmap = J->cur.nsnapmap; LoopState lps; int errcode; lps.J = J; lps.subst = NULL; lps.sizesubst = 0; errcode = lj_vm_cpcall(J->L, NULL, &lps, cploop_opt); lj_mem_freevec(J2G(J), lps.subst, lps.sizesubst, IRRef1); if (LJ_UNLIKELY(errcode)) { lua_State *L = J->L; if (errcode == LUA_ERRRUN && tvisnumber(L->top-1)) { /* Trace error? */ int32_t e = numberVint(L->top-1); switch ((TraceError)e) { case LJ_TRERR_TYPEINS: /* Type instability. */ case LJ_TRERR_GFAIL: /* Guard would always fail. */ /* Unrolling via recording fixes many cases, e.g. a flipped boolean. */ if (--J->instunroll < 0) /* But do not unroll forever. */ break; L->top--; /* Remove error object. */ loop_undo(J, nins, nsnap, nsnapmap); return 1; /* Loop optimization failed, continue recording. */ default: break; } } lj_err_throw(L, errcode); /* Propagate all other errors. */ } return 0; /* Loop optimization is ok. */ } #undef IR #undef emitir #undef emitir_raw #endif
xLua/build/luajit-2.1.0b3/src/lj_opt_loop.c/0
{ "file_path": "xLua/build/luajit-2.1.0b3/src/lj_opt_loop.c", "repo_id": "xLua", "token_count": 6392 }
2,052
/* ** Snapshot handling. ** Copyright (C) 2005-2021 Mike Pall. See Copyright Notice in luajit.h */ #ifndef _LJ_SNAP_H #define _LJ_SNAP_H #include "lj_obj.h" #include "lj_jit.h" #if LJ_HASJIT LJ_FUNC void lj_snap_add(jit_State *J); LJ_FUNC void lj_snap_purge(jit_State *J); LJ_FUNC void lj_snap_shrink(jit_State *J); LJ_FUNC IRIns *lj_snap_regspmap(jit_State *J, GCtrace *T, SnapNo snapno, IRIns *ir); LJ_FUNC void lj_snap_replay(jit_State *J, GCtrace *T); LJ_FUNC const BCIns *lj_snap_restore(jit_State *J, void *exptr); LJ_FUNC void lj_snap_grow_buf_(jit_State *J, MSize need); LJ_FUNC void lj_snap_grow_map_(jit_State *J, MSize need); static LJ_AINLINE void lj_snap_grow_buf(jit_State *J, MSize need) { if (LJ_UNLIKELY(need > J->sizesnap)) lj_snap_grow_buf_(J, need); } static LJ_AINLINE void lj_snap_grow_map(jit_State *J, MSize need) { if (LJ_UNLIKELY(need > J->sizesnapmap)) lj_snap_grow_map_(J, need); } #endif #endif
xLua/build/luajit-2.1.0b3/src/lj_snap.h/0
{ "file_path": "xLua/build/luajit-2.1.0b3/src/lj_snap.h", "repo_id": "xLua", "token_count": 446 }
2,053
/* ** Definitions for PPC CPUs. ** Copyright (C) 2005-2021 Mike Pall. See Copyright Notice in luajit.h */ #ifndef _LJ_TARGET_PPC_H #define _LJ_TARGET_PPC_H /* -- Registers IDs ------------------------------------------------------- */ #define GPRDEF(_) \ _(R0) _(SP) _(SYS1) _(R3) _(R4) _(R5) _(R6) _(R7) \ _(R8) _(R9) _(R10) _(R11) _(R12) _(SYS2) _(R14) _(R15) \ _(R16) _(R17) _(R18) _(R19) _(R20) _(R21) _(R22) _(R23) \ _(R24) _(R25) _(R26) _(R27) _(R28) _(R29) _(R30) _(R31) #define FPRDEF(_) \ _(F0) _(F1) _(F2) _(F3) _(F4) _(F5) _(F6) _(F7) \ _(F8) _(F9) _(F10) _(F11) _(F12) _(F13) _(F14) _(F15) \ _(F16) _(F17) _(F18) _(F19) _(F20) _(F21) _(F22) _(F23) \ _(F24) _(F25) _(F26) _(F27) _(F28) _(F29) _(F30) _(F31) #define VRIDDEF(_) #define RIDENUM(name) RID_##name, enum { GPRDEF(RIDENUM) /* General-purpose registers (GPRs). */ FPRDEF(RIDENUM) /* Floating-point registers (FPRs). */ RID_MAX, RID_TMP = RID_R0, /* Calling conventions. */ RID_RET = RID_R3, RID_RETHI = RID_R3, RID_RETLO = RID_R4, RID_FPRET = RID_F1, /* These definitions must match with the *.dasc file(s): */ RID_BASE = RID_R14, /* Interpreter BASE. */ RID_LPC = RID_R16, /* Interpreter PC. */ RID_DISPATCH = RID_R17, /* Interpreter DISPATCH table. */ RID_LREG = RID_R18, /* Interpreter L. */ RID_JGL = RID_R31, /* On-trace: global_State + 32768. */ /* Register ranges [min, max) and number of registers. */ RID_MIN_GPR = RID_R0, RID_MAX_GPR = RID_R31+1, RID_MIN_FPR = RID_F0, RID_MAX_FPR = RID_F31+1, RID_NUM_GPR = RID_MAX_GPR - RID_MIN_GPR, RID_NUM_FPR = RID_MAX_FPR - RID_MIN_FPR }; #define RID_NUM_KREF RID_NUM_GPR #define RID_MIN_KREF RID_R0 /* -- Register sets ------------------------------------------------------- */ /* Make use of all registers, except TMP, SP, SYS1, SYS2 and JGL. */ #define RSET_FIXED \ (RID2RSET(RID_TMP)|RID2RSET(RID_SP)|RID2RSET(RID_SYS1)|\ RID2RSET(RID_SYS2)|RID2RSET(RID_JGL)) #define RSET_GPR (RSET_RANGE(RID_MIN_GPR, RID_MAX_GPR) - RSET_FIXED) #define RSET_FPR RSET_RANGE(RID_MIN_FPR, RID_MAX_FPR) #define RSET_ALL (RSET_GPR|RSET_FPR) #define RSET_INIT RSET_ALL #define RSET_SCRATCH_GPR (RSET_RANGE(RID_R3, RID_R12+1)) #define RSET_SCRATCH_FPR (RSET_RANGE(RID_F0, RID_F13+1)) #define RSET_SCRATCH (RSET_SCRATCH_GPR|RSET_SCRATCH_FPR) #define REGARG_FIRSTGPR RID_R3 #define REGARG_LASTGPR RID_R10 #define REGARG_NUMGPR 8 #define REGARG_FIRSTFPR RID_F1 #define REGARG_LASTFPR RID_F8 #define REGARG_NUMFPR 8 /* -- Spill slots --------------------------------------------------------- */ /* Spill slots are 32 bit wide. An even/odd pair is used for FPRs. ** ** SPS_FIXED: Available fixed spill slots in interpreter frame. ** This definition must match with the *.dasc file(s). ** ** SPS_FIRST: First spill slot for general use. ** [sp+12] tmplo word \ ** [sp+ 8] tmphi word / tmp dword, parameter area for callee ** [sp+ 4] tmpw, LR of callee ** [sp+ 0] stack chain */ #define SPS_FIXED 7 #define SPS_FIRST 4 /* Stack offsets for temporary slots. Used for FP<->int conversions etc. */ #define SPOFS_TMPW 4 #define SPOFS_TMP 8 #define SPOFS_TMPHI 8 #define SPOFS_TMPLO 12 #define sps_scale(slot) (4 * (int32_t)(slot)) #define sps_align(slot) (((slot) - SPS_FIXED + 3) & ~3) /* -- Exit state ---------------------------------------------------------- */ /* This definition must match with the *.dasc file(s). */ typedef struct { lua_Number fpr[RID_NUM_FPR]; /* Floating-point registers. */ intptr_t gpr[RID_NUM_GPR]; /* General-purpose registers. */ int32_t spill[256]; /* Spill slots. */ } ExitState; /* Highest exit + 1 indicates stack check. */ #define EXITSTATE_CHECKEXIT 1 /* Return the address of a per-trace exit stub. */ static LJ_AINLINE uint32_t *exitstub_trace_addr_(uint32_t *p, uint32_t exitno) { while (*p == 0x60000000) p++; /* Skip PPCI_NOP. */ return p + 3 + exitno; } /* Avoid dependence on lj_jit.h if only including lj_target.h. */ #define exitstub_trace_addr(T, exitno) \ exitstub_trace_addr_((MCode *)((char *)(T)->mcode + (T)->szmcode), (exitno)) /* -- Instructions -------------------------------------------------------- */ /* Instruction fields. */ #define PPCF_CC(cc) ((((cc) & 3) << 16) | (((cc) & 4) << 22)) #define PPCF_T(r) ((r) << 21) #define PPCF_A(r) ((r) << 16) #define PPCF_B(r) ((r) << 11) #define PPCF_C(r) ((r) << 6) #define PPCF_MB(n) ((n) << 6) #define PPCF_ME(n) ((n) << 1) #define PPCF_Y 0x00200000 #define PPCF_DOT 0x00000001 typedef enum PPCIns { /* Integer instructions. */ PPCI_MR = 0x7c000378, PPCI_NOP = 0x60000000, PPCI_LI = 0x38000000, PPCI_LIS = 0x3c000000, PPCI_ADD = 0x7c000214, PPCI_ADDC = 0x7c000014, PPCI_ADDO = 0x7c000614, PPCI_ADDE = 0x7c000114, PPCI_ADDZE = 0x7c000194, PPCI_ADDME = 0x7c0001d4, PPCI_ADDI = 0x38000000, PPCI_ADDIS = 0x3c000000, PPCI_ADDIC = 0x30000000, PPCI_ADDICDOT = 0x34000000, PPCI_SUBF = 0x7c000050, PPCI_SUBFC = 0x7c000010, PPCI_SUBFO = 0x7c000450, PPCI_SUBFE = 0x7c000110, PPCI_SUBFZE = 0x7c000190, PPCI_SUBFME = 0x7c0001d0, PPCI_SUBFIC = 0x20000000, PPCI_NEG = 0x7c0000d0, PPCI_AND = 0x7c000038, PPCI_ANDC = 0x7c000078, PPCI_NAND = 0x7c0003b8, PPCI_ANDIDOT = 0x70000000, PPCI_ANDISDOT = 0x74000000, PPCI_OR = 0x7c000378, PPCI_NOR = 0x7c0000f8, PPCI_ORI = 0x60000000, PPCI_ORIS = 0x64000000, PPCI_XOR = 0x7c000278, PPCI_EQV = 0x7c000238, PPCI_XORI = 0x68000000, PPCI_XORIS = 0x6c000000, PPCI_CMPW = 0x7c000000, PPCI_CMPLW = 0x7c000040, PPCI_CMPWI = 0x2c000000, PPCI_CMPLWI = 0x28000000, PPCI_MULLW = 0x7c0001d6, PPCI_MULLI = 0x1c000000, PPCI_MULLWO = 0x7c0005d6, PPCI_EXTSB = 0x7c000774, PPCI_EXTSH = 0x7c000734, PPCI_SLW = 0x7c000030, PPCI_SRW = 0x7c000430, PPCI_SRAW = 0x7c000630, PPCI_SRAWI = 0x7c000670, PPCI_RLWNM = 0x5c000000, PPCI_RLWINM = 0x54000000, PPCI_RLWIMI = 0x50000000, PPCI_B = 0x48000000, PPCI_BL = 0x48000001, PPCI_BC = 0x40800000, PPCI_BCL = 0x40800001, PPCI_BCTR = 0x4e800420, PPCI_BCTRL = 0x4e800421, PPCI_CRANDC = 0x4c000102, PPCI_CRXOR = 0x4c000182, PPCI_CRAND = 0x4c000202, PPCI_CREQV = 0x4c000242, PPCI_CRORC = 0x4c000342, PPCI_CROR = 0x4c000382, PPCI_MFLR = 0x7c0802a6, PPCI_MTCTR = 0x7c0903a6, PPCI_MCRXR = 0x7c000400, /* Load/store instructions. */ PPCI_LWZ = 0x80000000, PPCI_LBZ = 0x88000000, PPCI_STW = 0x90000000, PPCI_STB = 0x98000000, PPCI_LHZ = 0xa0000000, PPCI_LHA = 0xa8000000, PPCI_STH = 0xb0000000, PPCI_STWU = 0x94000000, PPCI_LFS = 0xc0000000, PPCI_LFD = 0xc8000000, PPCI_STFS = 0xd0000000, PPCI_STFD = 0xd8000000, PPCI_LWZX = 0x7c00002e, PPCI_LBZX = 0x7c0000ae, PPCI_STWX = 0x7c00012e, PPCI_STBX = 0x7c0001ae, PPCI_LHZX = 0x7c00022e, PPCI_LHAX = 0x7c0002ae, PPCI_STHX = 0x7c00032e, PPCI_LWBRX = 0x7c00042c, PPCI_STWBRX = 0x7c00052c, PPCI_LFSX = 0x7c00042e, PPCI_LFDX = 0x7c0004ae, PPCI_STFSX = 0x7c00052e, PPCI_STFDX = 0x7c0005ae, /* FP instructions. */ PPCI_FMR = 0xfc000090, PPCI_FNEG = 0xfc000050, PPCI_FABS = 0xfc000210, PPCI_FRSP = 0xfc000018, PPCI_FCTIWZ = 0xfc00001e, PPCI_FADD = 0xfc00002a, PPCI_FSUB = 0xfc000028, PPCI_FMUL = 0xfc000032, PPCI_FDIV = 0xfc000024, PPCI_FSQRT = 0xfc00002c, PPCI_FMADD = 0xfc00003a, PPCI_FMSUB = 0xfc000038, PPCI_FNMSUB = 0xfc00003c, PPCI_FCMPU = 0xfc000000, PPCI_FSEL = 0xfc00002e, } PPCIns; typedef enum PPCCC { CC_GE, CC_LE, CC_NE, CC_NS, CC_LT, CC_GT, CC_EQ, CC_SO } PPCCC; #endif
xLua/build/luajit-2.1.0b3/src/lj_target_ppc.h/0
{ "file_path": "xLua/build/luajit-2.1.0b3/src/lj_target_ppc.h", "repo_id": "xLua", "token_count": 3883 }
2,054
/* ** LuaJIT frontend. Runs commands, scripts, read-eval-print (REPL) etc. ** Copyright (C) 2005-2021 Mike Pall. See Copyright Notice in luajit.h ** ** Major portions taken verbatim or adapted from the Lua interpreter. ** Copyright (C) 1994-2008 Lua.org, PUC-Rio. See Copyright Notice in lua.h */ #include <stdio.h> #include <stdlib.h> #include <string.h> #define luajit_c #include "lua.h" #include "lauxlib.h" #include "lualib.h" #include "luajit.h" #include "lj_arch.h" #if LJ_TARGET_POSIX #include <unistd.h> #define lua_stdin_is_tty() isatty(0) #elif LJ_TARGET_WINDOWS #include <io.h> #ifdef __BORLANDC__ #define lua_stdin_is_tty() isatty(_fileno(stdin)) #else #define lua_stdin_is_tty() _isatty(_fileno(stdin)) #endif #else #define lua_stdin_is_tty() 1 #endif #if !LJ_TARGET_CONSOLE #include <signal.h> #endif static lua_State *globalL = NULL; static const char *progname = LUA_PROGNAME; #if !LJ_TARGET_CONSOLE static void lstop(lua_State *L, lua_Debug *ar) { (void)ar; /* unused arg. */ lua_sethook(L, NULL, 0, 0); /* Avoid luaL_error -- a C hook doesn't add an extra frame. */ luaL_where(L, 0); lua_pushfstring(L, "%sinterrupted!", lua_tostring(L, -1)); lua_error(L); } static void laction(int i) { signal(i, SIG_DFL); /* if another SIGINT happens before lstop, terminate process (default action) */ lua_sethook(globalL, lstop, LUA_MASKCALL | LUA_MASKRET | LUA_MASKCOUNT, 1); } #endif static void print_usage(void) { fputs("usage: ", stderr); fputs(progname, stderr); fputs(" [options]... [script [args]...].\n" "Available options are:\n" " -e chunk Execute string " LUA_QL("chunk") ".\n" " -l name Require library " LUA_QL("name") ".\n" " -b ... Save or list bytecode.\n" " -j cmd Perform LuaJIT control command.\n" " -O[opt] Control LuaJIT optimizations.\n" " -i Enter interactive mode after executing " LUA_QL("script") ".\n" " -v Show version information.\n" " -E Ignore environment variables.\n" " -- Stop handling options.\n" " - Execute stdin and stop handling options.\n", stderr); fflush(stderr); } static void l_message(const char *pname, const char *msg) { if (pname) { fputs(pname, stderr); fputc(':', stderr); fputc(' ', stderr); } fputs(msg, stderr); fputc('\n', stderr); fflush(stderr); } static int report(lua_State *L, int status) { if (status && !lua_isnil(L, -1)) { const char *msg = lua_tostring(L, -1); if (msg == NULL) msg = "(error object is not a string)"; l_message(progname, msg); lua_pop(L, 1); } return status; } static int traceback(lua_State *L) { if (!lua_isstring(L, 1)) { /* Non-string error object? Try metamethod. */ if (lua_isnoneornil(L, 1) || !luaL_callmeta(L, 1, "__tostring") || !lua_isstring(L, -1)) return 1; /* Return non-string error object. */ lua_remove(L, 1); /* Replace object by result of __tostring metamethod. */ } luaL_traceback(L, L, lua_tostring(L, 1), 1); return 1; } static int docall(lua_State *L, int narg, int clear) { int status; int base = lua_gettop(L) - narg; /* function index */ lua_pushcfunction(L, traceback); /* push traceback function */ lua_insert(L, base); /* put it under chunk and args */ #if !LJ_TARGET_CONSOLE signal(SIGINT, laction); #endif status = lua_pcall(L, narg, (clear ? 0 : LUA_MULTRET), base); #if !LJ_TARGET_CONSOLE signal(SIGINT, SIG_DFL); #endif lua_remove(L, base); /* remove traceback function */ /* force a complete garbage collection in case of errors */ if (status != LUA_OK) lua_gc(L, LUA_GCCOLLECT, 0); return status; } static void print_version(void) { fputs(LUAJIT_VERSION " -- " LUAJIT_COPYRIGHT ". " LUAJIT_URL "\n", stdout); } static void print_jit_status(lua_State *L) { int n; const char *s; lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED"); lua_getfield(L, -1, "jit"); /* Get jit.* module table. */ lua_remove(L, -2); lua_getfield(L, -1, "status"); lua_remove(L, -2); n = lua_gettop(L); lua_call(L, 0, LUA_MULTRET); fputs(lua_toboolean(L, n) ? "JIT: ON" : "JIT: OFF", stdout); for (n++; (s = lua_tostring(L, n)); n++) { putc(' ', stdout); fputs(s, stdout); } putc('\n', stdout); lua_settop(L, 0); /* clear stack */ } static void createargtable(lua_State *L, char **argv, int argc, int argf) { int i; lua_createtable(L, argc - argf, argf); for (i = 0; i < argc; i++) { lua_pushstring(L, argv[i]); lua_rawseti(L, -2, i - argf); } lua_setglobal(L, "arg"); } static int dofile(lua_State *L, const char *name) { int status = luaL_loadfile(L, name) || docall(L, 0, 1); return report(L, status); } static int dostring(lua_State *L, const char *s, const char *name) { int status = luaL_loadbuffer(L, s, strlen(s), name) || docall(L, 0, 1); return report(L, status); } static int dolibrary(lua_State *L, const char *name) { lua_getglobal(L, "require"); lua_pushstring(L, name); return report(L, docall(L, 1, 1)); } static void write_prompt(lua_State *L, int firstline) { const char *p; lua_getfield(L, LUA_GLOBALSINDEX, firstline ? "_PROMPT" : "_PROMPT2"); p = lua_tostring(L, -1); if (p == NULL) p = firstline ? LUA_PROMPT : LUA_PROMPT2; fputs(p, stdout); fflush(stdout); lua_pop(L, 1); /* remove global */ } static int incomplete(lua_State *L, int status) { if (status == LUA_ERRSYNTAX) { size_t lmsg; const char *msg = lua_tolstring(L, -1, &lmsg); const char *tp = msg + lmsg - (sizeof(LUA_QL("<eof>")) - 1); if (strstr(msg, LUA_QL("<eof>")) == tp) { lua_pop(L, 1); return 1; } } return 0; /* else... */ } static int pushline(lua_State *L, int firstline) { char buf[LUA_MAXINPUT]; write_prompt(L, firstline); if (fgets(buf, LUA_MAXINPUT, stdin)) { size_t len = strlen(buf); if (len > 0 && buf[len-1] == '\n') buf[len-1] = '\0'; if (firstline && buf[0] == '=') lua_pushfstring(L, "return %s", buf+1); else lua_pushstring(L, buf); return 1; } return 0; } static int loadline(lua_State *L) { int status; lua_settop(L, 0); if (!pushline(L, 1)) return -1; /* no input */ for (;;) { /* repeat until gets a complete line */ status = luaL_loadbuffer(L, lua_tostring(L, 1), lua_strlen(L, 1), "=stdin"); if (!incomplete(L, status)) break; /* cannot try to add lines? */ if (!pushline(L, 0)) /* no more input? */ return -1; lua_pushliteral(L, "\n"); /* add a new line... */ lua_insert(L, -2); /* ...between the two lines */ lua_concat(L, 3); /* join them */ } lua_remove(L, 1); /* remove line */ return status; } static void dotty(lua_State *L) { int status; const char *oldprogname = progname; progname = NULL; while ((status = loadline(L)) != -1) { if (status == LUA_OK) status = docall(L, 0, 0); report(L, status); if (status == LUA_OK && lua_gettop(L) > 0) { /* any result to print? */ lua_getglobal(L, "print"); lua_insert(L, 1); if (lua_pcall(L, lua_gettop(L)-1, 0, 0) != 0) l_message(progname, lua_pushfstring(L, "error calling " LUA_QL("print") " (%s)", lua_tostring(L, -1))); } } lua_settop(L, 0); /* clear stack */ fputs("\n", stdout); fflush(stdout); progname = oldprogname; } static int handle_script(lua_State *L, char **argx) { int status; const char *fname = argx[0]; if (strcmp(fname, "-") == 0 && strcmp(argx[-1], "--") != 0) fname = NULL; /* stdin */ status = luaL_loadfile(L, fname); if (status == LUA_OK) { /* Fetch args from arg table. LUA_INIT or -e might have changed them. */ int narg = 0; lua_getglobal(L, "arg"); if (lua_istable(L, -1)) { do { narg++; lua_rawgeti(L, -narg, narg); } while (!lua_isnil(L, -1)); lua_pop(L, 1); lua_remove(L, -narg); narg--; } else { lua_pop(L, 1); } status = docall(L, narg, 0); } return report(L, status); } /* Load add-on module. */ static int loadjitmodule(lua_State *L) { lua_getglobal(L, "require"); lua_pushliteral(L, "jit."); lua_pushvalue(L, -3); lua_concat(L, 2); if (lua_pcall(L, 1, 1, 0)) { const char *msg = lua_tostring(L, -1); if (msg && !strncmp(msg, "module ", 7)) goto nomodule; return report(L, 1); } lua_getfield(L, -1, "start"); if (lua_isnil(L, -1)) { nomodule: l_message(progname, "unknown luaJIT command or jit.* modules not installed"); return 1; } lua_remove(L, -2); /* Drop module table. */ return 0; } /* Run command with options. */ static int runcmdopt(lua_State *L, const char *opt) { int narg = 0; if (opt && *opt) { for (;;) { /* Split arguments. */ const char *p = strchr(opt, ','); narg++; if (!p) break; if (p == opt) lua_pushnil(L); else lua_pushlstring(L, opt, (size_t)(p - opt)); opt = p + 1; } if (*opt) lua_pushstring(L, opt); else lua_pushnil(L); } return report(L, lua_pcall(L, narg, 0, 0)); } /* JIT engine control command: try jit library first or load add-on module. */ static int dojitcmd(lua_State *L, const char *cmd) { const char *opt = strchr(cmd, '='); lua_pushlstring(L, cmd, opt ? (size_t)(opt - cmd) : strlen(cmd)); lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED"); lua_getfield(L, -1, "jit"); /* Get jit.* module table. */ lua_remove(L, -2); lua_pushvalue(L, -2); lua_gettable(L, -2); /* Lookup library function. */ if (!lua_isfunction(L, -1)) { lua_pop(L, 2); /* Drop non-function and jit.* table, keep module name. */ if (loadjitmodule(L)) return 1; } else { lua_remove(L, -2); /* Drop jit.* table. */ } lua_remove(L, -2); /* Drop module name. */ return runcmdopt(L, opt ? opt+1 : opt); } /* Optimization flags. */ static int dojitopt(lua_State *L, const char *opt) { lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED"); lua_getfield(L, -1, "jit.opt"); /* Get jit.opt.* module table. */ lua_remove(L, -2); lua_getfield(L, -1, "start"); lua_remove(L, -2); return runcmdopt(L, opt); } /* Save or list bytecode. */ static int dobytecode(lua_State *L, char **argv) { int narg = 0; lua_pushliteral(L, "bcsave"); if (loadjitmodule(L)) return 1; if (argv[0][2]) { narg++; argv[0][1] = '-'; lua_pushstring(L, argv[0]+1); } for (argv++; *argv != NULL; narg++, argv++) lua_pushstring(L, *argv); report(L, lua_pcall(L, narg, 0, 0)); return -1; } /* check that argument has no extra characters at the end */ #define notail(x) {if ((x)[2] != '\0') return -1;} #define FLAGS_INTERACTIVE 1 #define FLAGS_VERSION 2 #define FLAGS_EXEC 4 #define FLAGS_OPTION 8 #define FLAGS_NOENV 16 static int collectargs(char **argv, int *flags) { int i; for (i = 1; argv[i] != NULL; i++) { if (argv[i][0] != '-') /* Not an option? */ return i; switch (argv[i][1]) { /* Check option. */ case '-': notail(argv[i]); return i+1; case '\0': return i; case 'i': notail(argv[i]); *flags |= FLAGS_INTERACTIVE; /* fallthrough */ case 'v': notail(argv[i]); *flags |= FLAGS_VERSION; break; case 'e': *flags |= FLAGS_EXEC; /* fallthrough */ case 'j': /* LuaJIT extension */ case 'l': *flags |= FLAGS_OPTION; if (argv[i][2] == '\0') { i++; if (argv[i] == NULL) return -1; } break; case 'O': break; /* LuaJIT extension */ case 'b': /* LuaJIT extension */ if (*flags) return -1; *flags |= FLAGS_EXEC; return i+1; case 'E': *flags |= FLAGS_NOENV; break; default: return -1; /* invalid option */ } } return i; } static int runargs(lua_State *L, char **argv, int argn) { int i; for (i = 1; i < argn; i++) { if (argv[i] == NULL) continue; lua_assert(argv[i][0] == '-'); switch (argv[i][1]) { case 'e': { const char *chunk = argv[i] + 2; if (*chunk == '\0') chunk = argv[++i]; lua_assert(chunk != NULL); if (dostring(L, chunk, "=(command line)") != 0) return 1; break; } case 'l': { const char *filename = argv[i] + 2; if (*filename == '\0') filename = argv[++i]; lua_assert(filename != NULL); if (dolibrary(L, filename)) return 1; break; } case 'j': { /* LuaJIT extension. */ const char *cmd = argv[i] + 2; if (*cmd == '\0') cmd = argv[++i]; lua_assert(cmd != NULL); if (dojitcmd(L, cmd)) return 1; break; } case 'O': /* LuaJIT extension. */ if (dojitopt(L, argv[i] + 2)) return 1; break; case 'b': /* LuaJIT extension. */ return dobytecode(L, argv+i); default: break; } } return LUA_OK; } static int handle_luainit(lua_State *L) { #if LJ_TARGET_CONSOLE const char *init = NULL; #else const char *init = getenv(LUA_INIT); #endif if (init == NULL) return LUA_OK; else if (init[0] == '@') return dofile(L, init+1); else return dostring(L, init, "=" LUA_INIT); } static struct Smain { char **argv; int argc; int status; } smain; static int pmain(lua_State *L) { struct Smain *s = &smain; char **argv = s->argv; int argn; int flags = 0; globalL = L; if (argv[0] && argv[0][0]) progname = argv[0]; LUAJIT_VERSION_SYM(); /* Linker-enforced version check. */ argn = collectargs(argv, &flags); if (argn < 0) { /* Invalid args? */ print_usage(); s->status = 1; return 0; } if ((flags & FLAGS_NOENV)) { lua_pushboolean(L, 1); lua_setfield(L, LUA_REGISTRYINDEX, "LUA_NOENV"); } /* Stop collector during library initialization. */ lua_gc(L, LUA_GCSTOP, 0); luaL_openlibs(L); lua_gc(L, LUA_GCRESTART, -1); createargtable(L, argv, s->argc, argn); if (!(flags & FLAGS_NOENV)) { s->status = handle_luainit(L); if (s->status != LUA_OK) return 0; } if ((flags & FLAGS_VERSION)) print_version(); s->status = runargs(L, argv, argn); if (s->status != LUA_OK) return 0; if (s->argc > argn) { s->status = handle_script(L, argv + argn); if (s->status != LUA_OK) return 0; } if ((flags & FLAGS_INTERACTIVE)) { print_jit_status(L); dotty(L); } else if (s->argc == argn && !(flags & (FLAGS_EXEC|FLAGS_VERSION))) { if (lua_stdin_is_tty()) { print_version(); print_jit_status(L); dotty(L); } else { dofile(L, NULL); /* Executes stdin as a file. */ } } return 0; } int main(int argc, char **argv) { int status; lua_State *L = lua_open(); if (L == NULL) { l_message(argv[0], "cannot create state: not enough memory"); return EXIT_FAILURE; } smain.argc = argc; smain.argv = argv; status = lua_cpcall(L, pmain, NULL); report(L, status); lua_close(L); return (status || smain.status > 0) ? EXIT_FAILURE : EXIT_SUCCESS; }
xLua/build/luajit-2.1.0b3/src/luajit.c/0
{ "file_path": "xLua/build/luajit-2.1.0b3/src/luajit.c", "repo_id": "xLua", "token_count": 6810 }
2,055
/* * This file defines string hash function using CRC32. It takes advantage of * Intel hardware support (crc32 instruction, SSE 4.2) to speedup the CRC32 * computation. The hash functions try to compute CRC32 of length and up * to 128 bytes of given string. */ #ifndef _LJ_STR_HASH_X64_H_ #define _LJ_STR_HASH_X64_H_ #if defined(__SSE4_2__) && defined(__x86_64) && defined(__GNUC__) #include <stdint.h> #include <sys/types.h> #include <unistd.h> #include <time.h> #include <smmintrin.h> #include "../../lj_def.h" #undef LJ_AINLINE #define LJ_AINLINE #ifdef __MINGW32__ #define random() ((long) rand()) #define srandom(seed) srand(seed) #endif static const uint64_t* cast_uint64p(const char* str) { return (const uint64_t*)(void*)str; } static const uint32_t* cast_uint32p(const char* str) { return (const uint32_t*)(void*)str; } /* hash string with len in [1, 4) */ static LJ_AINLINE uint32_t lj_str_hash_1_4(const char* str, uint32_t len) { #if 0 /* TODO: The if-1 part (i.e the original algorithm) is working better when * the load-factor is high, as revealed by conflict benchmark (via * 'make benchmark' command); need to understand why it's so. */ uint32_t v = str[0]; v = (v << 8) | str[len >> 1]; v = (v << 8) | str[len - 1]; v = (v << 8) | len; return _mm_crc32_u32(0, v); #else uint32_t a, b, h = len; a = *(const uint8_t *)str; h ^= *(const uint8_t *)(str+len-1); b = *(const uint8_t *)(str+(len>>1)); h ^= b; h -= lj_rol(b, 14); a ^= h; a -= lj_rol(h, 11); b ^= a; b -= lj_rol(a, 25); h ^= b; h -= lj_rol(b, 16); return h; #endif } /* hash string with len in [4, 16) */ static LJ_AINLINE uint32_t lj_str_hash_4_16(const char* str, uint32_t len) { uint64_t v1, v2, h; if (len >= 8) { v1 = *cast_uint64p(str); v2 = *cast_uint64p(str + len - 8); } else { v1 = *cast_uint32p(str); v2 = *cast_uint32p(str + len - 4); } h = _mm_crc32_u32(0, len); h = _mm_crc32_u64(h, v1); h = _mm_crc32_u64(h, v2); return h; } /* hash string with length in [16, 128) */ static uint32_t lj_str_hash_16_128(const char* str, uint32_t len) { uint64_t h1, h2; uint32_t i; h1 = _mm_crc32_u32(0, len); h2 = 0; for (i = 0; i < len - 16; i += 16) { h1 += _mm_crc32_u64(h1, *cast_uint64p(str + i)); h2 += _mm_crc32_u64(h2, *cast_uint64p(str + i + 8)); }; h1 = _mm_crc32_u64(h1, *cast_uint64p(str + len - 16)); h2 = _mm_crc32_u64(h2, *cast_uint64p(str + len - 8)); return _mm_crc32_u32(h1, h2); } /* ************************************************************************** * * Following is code about hashing string with length >= 128 * * ************************************************************************** */ static uint32_t random_pos[32][2]; static const int8_t log2_tab[128] = { -1,0,1,1,2,2,2,2,3,3,3,3,3,3,3,3,4,4, 4,4,4,4,4,4,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5, 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6, 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6 }; /* return floor(log2(n)) */ static LJ_AINLINE uint32_t log2_floor(uint32_t n) { if (n <= 127) { return log2_tab[n]; } if ((n >> 8) <= 127) { return log2_tab[n >> 8] + 8; } if ((n >> 16) <= 127) { return log2_tab[n >> 16] + 16; } if ((n >> 24) <= 127) { return log2_tab[n >> 24] + 24; } return 31; } #define POW2_MASK(n) ((1L << (n)) - 1) /* This function is to populate `random_pos` such that random_pos[i][*] * contains random value in the range of [2**i, 2**(i+1)). */ static void x64_init_random(void) { int i, seed, rml; /* Calculate the ceil(log2(RAND_MAX)) */ rml = log2_floor(RAND_MAX); if (RAND_MAX & (RAND_MAX - 1)) { rml += 1; } /* Init seed */ seed = _mm_crc32_u32(0, getpid()); seed = _mm_crc32_u32(seed, time(NULL)); srandom(seed); /* Now start to populate the random_pos[][]. */ for (i = 0; i < 3; i++) { /* No need to provide random value for chunk smaller than 8 bytes */ random_pos[i][0] = random_pos[i][1] = 0; } for (; i < rml; i++) { random_pos[i][0] = random() & POW2_MASK(i+1); random_pos[i][1] = random() & POW2_MASK(i+1); } for (; i < 31; i++) { int j; for (j = 0; j < 2; j++) { uint32_t v, scale; scale = random_pos[i - rml][0]; if (scale == 0) { scale = 1; } v = (random() * scale) & POW2_MASK(i+1); random_pos[i][j] = v; } } } #undef POW2_MASK void __attribute__((constructor)) x64_init_random_constructor() { x64_init_random(); } /* Return a pre-computed random number in the range of [1**chunk_sz_order, * 1**(chunk_sz_order+1)). It is "unsafe" in the sense that the return value * may be greater than chunk-size; it is up to the caller to make sure * "chunk-base + return-value-of-this-func" has valid virtual address. */ static LJ_AINLINE uint32_t get_random_pos_unsafe(uint32_t chunk_sz_order, uint32_t idx) { uint32_t pos = random_pos[chunk_sz_order][idx & 1]; return pos; } static LJ_NOINLINE uint32_t lj_str_hash_128_above(const char* str, uint32_t len) { uint32_t chunk_num, chunk_sz, chunk_sz_log2, i, pos1, pos2; uint64_t h1, h2, v; const char* chunk_ptr; chunk_num = 16; chunk_sz = len / chunk_num; chunk_sz_log2 = log2_floor(chunk_sz); pos1 = get_random_pos_unsafe(chunk_sz_log2, 0); pos2 = get_random_pos_unsafe(chunk_sz_log2, 1); h1 = _mm_crc32_u32(0, len); h2 = 0; /* loop over 14 chunks, 2 chunks at a time */ for (i = 0, chunk_ptr = str; i < (chunk_num / 2 - 1); chunk_ptr += chunk_sz, i++) { v = *cast_uint64p(chunk_ptr + pos1); h1 = _mm_crc32_u64(h1, v); v = *cast_uint64p(chunk_ptr + chunk_sz + pos2); h2 = _mm_crc32_u64(h2, v); } /* the last two chunks */ v = *cast_uint64p(chunk_ptr + pos1); h1 = _mm_crc32_u64(h1, v); v = *cast_uint64p(chunk_ptr + chunk_sz - 8 - pos2); h2 = _mm_crc32_u64(h2, v); /* process the trailing part */ h1 = _mm_crc32_u64(h1, *cast_uint64p(str)); h2 = _mm_crc32_u64(h2, *cast_uint64p(str + len - 8)); h1 = _mm_crc32_u32(h1, h2); return h1; } /* NOTE: the "len" should not be zero */ static LJ_AINLINE uint32_t lj_str_hash(const char* str, size_t len) { if (len < 128) { if (len >= 16) { /* [16, 128) */ return lj_str_hash_16_128(str, len); } if (len >= 4) { /* [4, 16) */ return lj_str_hash_4_16(str, len); } /* [0, 4) */ return lj_str_hash_1_4(str, len); } /* [128, inf) */ return lj_str_hash_128_above(str, len); } #define LJ_ARCH_STR_HASH lj_str_hash #else #undef LJ_ARCH_STR_HASH #endif #endif /*_LJ_STR_HASH_X64_H_*/
xLua/build/luajit-2.1.0b3/src/x64/src/lj_str_hash_x64.h/0
{ "file_path": "xLua/build/luajit-2.1.0b3/src/x64/src/lj_str_hash_x64.h", "repo_id": "xLua", "token_count": 3222 }
2,056
/*=========================================================================*\ * Input/Output interface for Lua programs * LuaSocket toolkit \*=========================================================================*/ #include "lua.h" #include "lauxlib.h" #include "buffer.h" /*=========================================================================*\ * Internal function prototypes \*=========================================================================*/ static int recvraw(p_buffer buf, size_t wanted, luaL_Buffer *b); static int recvline(p_buffer buf, luaL_Buffer *b); static int recvall(p_buffer buf, luaL_Buffer *b); static int buffer_get(p_buffer buf, const char **data, size_t *count); static void buffer_skip(p_buffer buf, size_t count); static int sendraw(p_buffer buf, const char *data, size_t count, size_t *sent); /* min and max macros */ #ifndef MIN #define MIN(x, y) ((x) < (y) ? x : y) #endif #ifndef MAX #define MAX(x, y) ((x) > (y) ? x : y) #endif /*=========================================================================*\ * Exported functions \*=========================================================================*/ /*-------------------------------------------------------------------------*\ * Initializes module \*-------------------------------------------------------------------------*/ int buffer_open(lua_State *L) { (void) L; return 0; } /*-------------------------------------------------------------------------*\ * Initializes C structure \*-------------------------------------------------------------------------*/ void buffer_init(p_buffer buf, p_io io, p_timeout tm) { buf->first = buf->last = 0; buf->io = io; buf->tm = tm; buf->received = buf->sent = 0; buf->birthday = timeout_gettime(); } /*-------------------------------------------------------------------------*\ * object:getstats() interface \*-------------------------------------------------------------------------*/ int buffer_meth_getstats(lua_State *L, p_buffer buf) { lua_pushnumber(L, (lua_Number) buf->received); lua_pushnumber(L, (lua_Number) buf->sent); lua_pushnumber(L, timeout_gettime() - buf->birthday); return 3; } /*-------------------------------------------------------------------------*\ * object:setstats() interface \*-------------------------------------------------------------------------*/ int buffer_meth_setstats(lua_State *L, p_buffer buf) { buf->received = (long) luaL_optnumber(L, 2, (lua_Number) buf->received); buf->sent = (long) luaL_optnumber(L, 3, (lua_Number) buf->sent); if (lua_isnumber(L, 4)) buf->birthday = timeout_gettime() - lua_tonumber(L, 4); lua_pushnumber(L, 1); return 1; } /*-------------------------------------------------------------------------*\ * object:send() interface \*-------------------------------------------------------------------------*/ int buffer_meth_send(lua_State *L, p_buffer buf) { int top = lua_gettop(L); int err = IO_DONE; size_t size = 0, sent = 0; const char *data = luaL_checklstring(L, 2, &size); long start = (long) luaL_optnumber(L, 3, 1); long end = (long) luaL_optnumber(L, 4, -1); #ifdef LUASOCKET_DEBUG p_timeout tm = timeout_markstart(buf->tm); #endif if (start < 0) start = (long) (size+start+1); if (end < 0) end = (long) (size+end+1); if (start < 1) start = (long) 1; if (end > (long) size) end = (long) size; if (start <= end) err = sendraw(buf, data+start-1, end-start+1, &sent); /* check if there was an error */ if (err != IO_DONE) { lua_pushnil(L); lua_pushstring(L, buf->io->error(buf->io->ctx, err)); lua_pushnumber(L, (lua_Number) (sent+start-1)); } else { lua_pushnumber(L, (lua_Number) (sent+start-1)); lua_pushnil(L); lua_pushnil(L); } #ifdef LUASOCKET_DEBUG /* push time elapsed during operation as the last return value */ lua_pushnumber(L, timeout_gettime() - timeout_getstart(tm)); #endif return lua_gettop(L) - top; } /*-------------------------------------------------------------------------*\ * object:receive() interface \*-------------------------------------------------------------------------*/ int buffer_meth_receive(lua_State *L, p_buffer buf) { int err = IO_DONE, top = lua_gettop(L); luaL_Buffer b; size_t size; const char *part = luaL_optlstring(L, 3, "", &size); #ifdef LUASOCKET_DEBUG p_timeout tm = timeout_markstart(buf->tm); #endif /* initialize buffer with optional extra prefix * (useful for concatenating previous partial results) */ luaL_buffinit(L, &b); luaL_addlstring(&b, part, size); /* receive new patterns */ if (!lua_isnumber(L, 2)) { const char *p= luaL_optstring(L, 2, "*l"); if (p[0] == '*' && p[1] == 'l') err = recvline(buf, &b); else if (p[0] == '*' && p[1] == 'a') err = recvall(buf, &b); else luaL_argcheck(L, 0, 2, "invalid receive pattern"); /* get a fixed number of bytes (minus what was already partially * received) */ } else { double n = lua_tonumber(L, 2); size_t wanted = (size_t) n; luaL_argcheck(L, n >= 0, 2, "invalid receive pattern"); if (size == 0 || wanted > size) err = recvraw(buf, wanted-size, &b); } /* check if there was an error */ if (err != IO_DONE) { /* we can't push anyting in the stack before pushing the * contents of the buffer. this is the reason for the complication */ luaL_pushresult(&b); lua_pushstring(L, buf->io->error(buf->io->ctx, err)); lua_pushvalue(L, -2); lua_pushnil(L); lua_replace(L, -4); } else { luaL_pushresult(&b); lua_pushnil(L); lua_pushnil(L); } #ifdef LUASOCKET_DEBUG /* push time elapsed during operation as the last return value */ lua_pushnumber(L, timeout_gettime() - timeout_getstart(tm)); #endif return lua_gettop(L) - top; } /*-------------------------------------------------------------------------*\ * Determines if there is any data in the read buffer \*-------------------------------------------------------------------------*/ int buffer_isempty(p_buffer buf) { return buf->first >= buf->last; } /*=========================================================================*\ * Internal functions \*=========================================================================*/ /*-------------------------------------------------------------------------*\ * Sends a block of data (unbuffered) \*-------------------------------------------------------------------------*/ #define STEPSIZE 8192 static int sendraw(p_buffer buf, const char *data, size_t count, size_t *sent) { p_io io = buf->io; p_timeout tm = buf->tm; size_t total = 0; int err = IO_DONE; while (total < count && err == IO_DONE) { size_t done = 0; size_t step = (count-total <= STEPSIZE)? count-total: STEPSIZE; err = io->send(io->ctx, data+total, step, &done, tm); total += done; } *sent = total; buf->sent += total; return err; } /*-------------------------------------------------------------------------*\ * Reads a fixed number of bytes (buffered) \*-------------------------------------------------------------------------*/ static int recvraw(p_buffer buf, size_t wanted, luaL_Buffer *b) { int err = IO_DONE; size_t total = 0; while (err == IO_DONE) { size_t count; const char *data; err = buffer_get(buf, &data, &count); count = MIN(count, wanted - total); luaL_addlstring(b, data, count); buffer_skip(buf, count); total += count; if (total >= wanted) break; } return err; } /*-------------------------------------------------------------------------*\ * Reads everything until the connection is closed (buffered) \*-------------------------------------------------------------------------*/ static int recvall(p_buffer buf, luaL_Buffer *b) { int err = IO_DONE; size_t total = 0; while (err == IO_DONE) { const char *data; size_t count; err = buffer_get(buf, &data, &count); total += count; luaL_addlstring(b, data, count); buffer_skip(buf, count); } if (err == IO_CLOSED) { if (total > 0) return IO_DONE; else return IO_CLOSED; } else return err; } /*-------------------------------------------------------------------------*\ * Reads a line terminated by a CR LF pair or just by a LF. The CR and LF * are not returned by the function and are discarded from the buffer \*-------------------------------------------------------------------------*/ static int recvline(p_buffer buf, luaL_Buffer *b) { int err = IO_DONE; while (err == IO_DONE) { size_t count, pos; const char *data; err = buffer_get(buf, &data, &count); pos = 0; while (pos < count && data[pos] != '\n') { /* we ignore all \r's */ if (data[pos] != '\r') luaL_addchar(b, data[pos]); pos++; } if (pos < count) { /* found '\n' */ buffer_skip(buf, pos+1); /* skip '\n' too */ break; /* we are done */ } else /* reached the end of the buffer */ buffer_skip(buf, pos); } return err; } /*-------------------------------------------------------------------------*\ * Skips a given number of bytes from read buffer. No data is read from the * transport layer \*-------------------------------------------------------------------------*/ static void buffer_skip(p_buffer buf, size_t count) { buf->received += count; buf->first += count; if (buffer_isempty(buf)) buf->first = buf->last = 0; } /*-------------------------------------------------------------------------*\ * Return any data available in buffer, or get more data from transport layer * if buffer is empty \*-------------------------------------------------------------------------*/ static int buffer_get(p_buffer buf, const char **data, size_t *count) { int err = IO_DONE; p_io io = buf->io; p_timeout tm = buf->tm; if (buffer_isempty(buf)) { size_t got; err = io->recv(io->ctx, buf->data, BUF_SIZE, &got, tm); buf->first = 0; buf->last = got; } *count = buf->last - buf->first; *data = buf->data + buf->first; return err; }
xLua/build/luasocket/buffer.c/0
{ "file_path": "xLua/build/luasocket/buffer.c", "repo_id": "xLua", "token_count": 3611 }
2,057
/*=========================================================================*\ * Select implementation * LuaSocket toolkit \*=========================================================================*/ #include <string.h> #include "lua.h" #include "lauxlib.h" #include "socket.h" #include "timeout.h" #include "select.h" /*=========================================================================*\ * Internal function prototypes. \*=========================================================================*/ static t_socket getfd(lua_State *L); static int dirty(lua_State *L); static void collect_fd(lua_State *L, int tab, int itab, fd_set *set, t_socket *max_fd); static int check_dirty(lua_State *L, int tab, int dtab, fd_set *set); static void return_fd(lua_State *L, fd_set *set, t_socket max_fd, int itab, int tab, int start); static void make_assoc(lua_State *L, int tab); static int global_select(lua_State *L); /* functions in library namespace */ static luaL_Reg func[] = { {"select", global_select}, {NULL, NULL} }; /*=========================================================================*\ * Exported functions \*=========================================================================*/ /*-------------------------------------------------------------------------*\ * Initializes module \*-------------------------------------------------------------------------*/ int select_open(lua_State *L) { lua_pushstring(L, "_SETSIZE"); lua_pushnumber(L, FD_SETSIZE); lua_rawset(L, -3); #if LUA_VERSION_NUM > 501 && !defined(LUA_COMPAT_MODULE) luaL_setfuncs(L, func, 0); #else luaL_openlib(L, NULL, func, 0); #endif return 0; } /*=========================================================================*\ * Global Lua functions \*=========================================================================*/ /*-------------------------------------------------------------------------*\ * Waits for a set of sockets until a condition is met or timeout. \*-------------------------------------------------------------------------*/ static int global_select(lua_State *L) { int rtab, wtab, itab, ret, ndirty; t_socket max_fd = SOCKET_INVALID; fd_set rset, wset; t_timeout tm; double t = luaL_optnumber(L, 3, -1); FD_ZERO(&rset); FD_ZERO(&wset); lua_settop(L, 3); lua_newtable(L); itab = lua_gettop(L); lua_newtable(L); rtab = lua_gettop(L); lua_newtable(L); wtab = lua_gettop(L); collect_fd(L, 1, itab, &rset, &max_fd); collect_fd(L, 2, itab, &wset, &max_fd); ndirty = check_dirty(L, 1, rtab, &rset); t = ndirty > 0? 0.0: t; timeout_init(&tm, t, -1); timeout_markstart(&tm); ret = socket_select(max_fd+1, &rset, &wset, NULL, &tm); if (ret > 0 || ndirty > 0) { return_fd(L, &rset, max_fd+1, itab, rtab, ndirty); return_fd(L, &wset, max_fd+1, itab, wtab, 0); make_assoc(L, rtab); make_assoc(L, wtab); return 2; } else if (ret == 0) { lua_pushstring(L, "timeout"); return 3; } else { luaL_error(L, "select failed"); return 3; } } /*=========================================================================*\ * Internal functions \*=========================================================================*/ static t_socket getfd(lua_State *L) { t_socket fd = SOCKET_INVALID; lua_pushstring(L, "getfd"); lua_gettable(L, -2); if (!lua_isnil(L, -1)) { lua_pushvalue(L, -2); lua_call(L, 1, 1); if (lua_isnumber(L, -1)) { double numfd = lua_tonumber(L, -1); fd = (numfd >= 0.0)? (t_socket) numfd: SOCKET_INVALID; } } lua_pop(L, 1); return fd; } static int dirty(lua_State *L) { int is = 0; lua_pushstring(L, "dirty"); lua_gettable(L, -2); if (!lua_isnil(L, -1)) { lua_pushvalue(L, -2); lua_call(L, 1, 1); is = lua_toboolean(L, -1); } lua_pop(L, 1); return is; } static void collect_fd(lua_State *L, int tab, int itab, fd_set *set, t_socket *max_fd) { int i = 1, n = 0; /* nil is the same as an empty table */ if (lua_isnil(L, tab)) return; /* otherwise we need it to be a table */ luaL_checktype(L, tab, LUA_TTABLE); for ( ;; ) { t_socket fd; lua_pushnumber(L, i); lua_gettable(L, tab); if (lua_isnil(L, -1)) { lua_pop(L, 1); break; } /* getfd figures out if this is a socket */ fd = getfd(L); if (fd != SOCKET_INVALID) { /* make sure we don't overflow the fd_set */ #ifdef _WIN32 if (n >= FD_SETSIZE) luaL_argerror(L, tab, "too many sockets"); #else if (fd >= FD_SETSIZE) luaL_argerror(L, tab, "descriptor too large for set size"); #endif FD_SET(fd, set); n++; /* keep track of the largest descriptor so far */ if (*max_fd == SOCKET_INVALID || *max_fd < fd) *max_fd = fd; /* make sure we can map back from descriptor to the object */ lua_pushnumber(L, (lua_Number) fd); lua_pushvalue(L, -2); lua_settable(L, itab); } lua_pop(L, 1); i = i + 1; } } static int check_dirty(lua_State *L, int tab, int dtab, fd_set *set) { int ndirty = 0, i = 1; if (lua_isnil(L, tab)) return 0; for ( ;; ) { t_socket fd; lua_pushnumber(L, i); lua_gettable(L, tab); if (lua_isnil(L, -1)) { lua_pop(L, 1); break; } fd = getfd(L); if (fd != SOCKET_INVALID && dirty(L)) { lua_pushnumber(L, ++ndirty); lua_pushvalue(L, -2); lua_settable(L, dtab); FD_CLR(fd, set); } lua_pop(L, 1); i = i + 1; } return ndirty; } static void return_fd(lua_State *L, fd_set *set, t_socket max_fd, int itab, int tab, int start) { t_socket fd; for (fd = 0; fd < max_fd; fd++) { if (FD_ISSET(fd, set)) { lua_pushnumber(L, ++start); lua_pushnumber(L, (lua_Number) fd); lua_gettable(L, itab); lua_settable(L, tab); } } } static void make_assoc(lua_State *L, int tab) { int i = 1, atab; lua_newtable(L); atab = lua_gettop(L); for ( ;; ) { lua_pushnumber(L, i); lua_gettable(L, tab); if (!lua_isnil(L, -1)) { lua_pushnumber(L, i); lua_pushvalue(L, -2); lua_settable(L, atab); lua_pushnumber(L, i); lua_settable(L, atab); } else { lua_pop(L, 1); break; } i = i+1; } }
xLua/build/luasocket/select.c/0
{ "file_path": "xLua/build/luasocket/select.c", "repo_id": "xLua", "token_count": 3131 }
2,058
if [ -n "$ANDROID_NDK" ]; then export NDK=${ANDROID_NDK} elif [ -n "$ANDROID_NDK_HOME" ]; then export NDK=${ANDROID_NDK_HOME} elif [ -n "$ANDROID_NDK_HOME" ]; then export NDK=${ANDROID_NDK_HOME} else export NDK=~/android-ndk-r15c fi if [ ! -d "$NDK" ]; then echo "Please set ANDROID_NDK environment to the root of NDK." exit 1 fi function build() { API=$1 ABI=$2 TOOLCHAIN_ANME=$3 BUILD_PATH=build.Android.${ABI} cmake -H. -B${BUILD_PATH} -DANDROID_ABI=${ABI} -DCMAKE_BUILD_TYPE=Release -DCMAKE_TOOLCHAIN_FILE=${NDK}/build/cmake/android.toolchain.cmake -DANDROID_NATIVE_API_LEVEL=${API} -DANDROID_TOOLCHAIN=clang -DANDROID_TOOLCHAIN_NAME=${TOOLCHAIN_ANME} cmake --build ${BUILD_PATH} --config Release mkdir -p plugin_lua53/Plugins/Android/libs/${ABI}/ cp ${BUILD_PATH}/libxlua.so plugin_lua53/Plugins/Android/libs/${ABI}/libxlua.so } build android-16 armeabi-v7a arm-linux-androideabi-4.9 build android-16 arm64-v8a arm-linux-androideabi-clang build android-16 x86 x86-4.9
xLua/build/make_android_lua53.sh/0
{ "file_path": "xLua/build/make_android_lua53.sh", "repo_id": "xLua", "token_count": 484 }
2,059
mkdir -p build_osx_54 && cd build_osx_54 cmake -DLUA_VERSION=5.4.1 -GXcode ../ cd .. cmake --build build_osx_54 --config Release mkdir -p plugin_lua54/Plugins/xlua.bundle/Contents/MacOS/ cp build_osx_54/Release/xlua.bundle/Contents/MacOS/xlua plugin_lua54/Plugins/xlua.bundle/Contents/MacOS/xlua
xLua/build/make_osx_lua54.sh/0
{ "file_path": "xLua/build/make_osx_lua54.sh", "repo_id": "xLua", "token_count": 125 }
2,060
mkdir build32 & pushd build32 cmake -G "Visual Studio 14 2015" .. IF %ERRORLEVEL% NEQ 0 cmake -G "Visual Studio 15 2017" .. popd cmake --build build32 --config Release md plugin_lua53\Plugins\x86 copy /Y build32\Release\xlua.dll plugin_lua53\Plugins\x86\xlua.dll pause
xLua/build/vs2015/make_win32_lua53.bat/0
{ "file_path": "xLua/build/vs2015/make_win32_lua53.bat", "repo_id": "xLua", "token_count": 97 }
2,061
--- title: 特性 type: guide order: 1001 --- ## 特性 ### 总体 * **Lua虚拟机支持** * Lua5.3.3 * Luajit2.1beta2 <br> * **Unity3D版本支持** * Unity5 * Unity4 <br> * **平台支持** * windows 64/32 * android * ios 64/32/bitcode * osx <br> * **互访技术** * 生成适配代码 * 反射 <br> * **易用性** * 解压即可用 * 开发期无需生成代码 * 生成代码和反射间可无缝切换 * 更简单的无GC api * 菜单简单易懂 * 配置可以多份,按模块划分,也可以直接在目标类型上打Attribute标签 * 自动生成link.xml防止代码剪裁 * Plugins部分采用cmake编译,更简单 * 核心代码不依赖生成代码,可以随时删除生成目录 <br> * **性能** * Lazyload技术,避免用不上的类型的开销 * lua函数映射到c# delegate,lua table映射到interface,可实现接口层面无C# gc alloc开销 * 所有基本值类型,所有枚举,字段都是值类型的struct,在Lua和C#间传递无C# gc alloc * LuaTable,LuaFunction提供无gc访问接口 * 通过代码生成期的静态分析,生成最优代码 * 支持C#和Lua间指针传递 * 自动解除已经Destroy的UnityEngine.Object的引用 <br> * **扩展性** * 不用改代码就可以加入Lua第三方扩展 * 生成引擎提供接口做二次开发 ### 支持为如下C#实现打补丁 * 构造函数 * 析构函数 * 成员函数 * 静态函数 * 泛化函数 * 操作符重载 * 成员属性 * 静态属性 * 事件 ### Lua代码加载 * **加载字符串** * 支持加载后立即执行 * 支持加载后返回一个delegate或者LuaFunction,调用delegate或者LuaFunction后可传脚本参数 <br> * **Resources目录的文件** * 直接require <br> * **自定义loader** * Lua里头require时触发 * require参数透传给loader,loader读取Lua代码返回 <br> * **Lua原有的方式** * Lua原有的方式都保留 ### Lua调用C# * 创建C#对象 * C#静态属性,字段 * C#静态方法 * C#成员属性,字段 * C#成员方法 <br> * **C#继承** * 子类对象可以直接调用父类的方法,访问父类属性 * 子类模块可以直接调用父类的静态方法,静态属性 <br> * **扩展方法(Extension methods)** * 就像普通成员方法一样使用 <br> * **参数的输入输出属性(out,ref)** * out对应一个lua返回值 * ref对应一个lua参数以及一个lua返回值 <br> * **函数重载** * 支持重载 * 由于lua数据类型远比C#要少,会出现无法判断的情况,可通过扩展方法来来调用。 <br> * **操作符重载** * 支持的操作符:+,-,*,/,==,一元-,<,<=, %,[] * 其它操作符可以借助扩展方法调用 <br> * **参数默认值** * C#参数有默认值,在lua可以不传 <br> * **可变参数** * 在对应可变参数部分,直接输入一个个参数即可,不需要把这些参数扩到一个数组里头 <br> * **泛化方法调用** * 静态方法可以自行封装使用 * 成员函数可通过扩展方法封装使用 <br> * **枚举类型** * 数字或字符串到枚举的转换 <br> * **delegate** * 调用一个C# delegate * +操作符 * -操作符 * 把一个lua函数作为一个c# delegate传递给c# <br> * **event** * 增加事件回调 * 移除事件回调 <br> * **64位整数** * 传递无gc而且无精度损失 * lua53下使用原生64位支持 * 可以和number运算 * 以java的方式支持无符号64位整数 <br> * **table的自动转换到C#复杂类型** * obj.complexField = {a = 1, b = {c = 1}},obj是一个C#对象,complexField是两层嵌套的struct或者class <br> * **typeof** * 对应C#的typeof操作符,返回Type对象 <br> * lua侧直接clone <br> * **decimal** * 传递无gc而且无精度损失 ### C#调用Lua * **调用Lua函数** * 以delegate方式调用Lua函数 * 以LuaFunction调用lua函数 <br> * **访问Lua的table** * LuaTable的泛化Get/Set接口,调用无gc,可指明Key,Value的类型 * 用标注了CSharpCallLua的interface访问 * 值拷贝到struct,class ### Lua虚拟机 * 虚拟机gc参数读取及设置 ### 工具链 * **Lua Profiler** * 可根据函数调用总时长,平均每次调用时长,调用次数排序 * 显示lua函数名及其所在文件的名字及行号 * 如果C#函数,会显示这个是C#函数 <br> * 支持真机调试
xLua/docs/source/src/v1/guide/features.md/0
{ "file_path": "xLua/docs/source/src/v1/guide/features.md", "repo_id": "xLua", "token_count": 2892 }
2,062
article color:rgb(82,82,82); text-align left h1,h2 font-size 2.25rem font-weight 500 margin-bottom 3rem h3,h4,h5 font-weight 400 h3 font-size 1.375rem margin-top 3.125rem margin-bottom 1.875rem h3:before content "#" margin-right 0.25rem color $main-color opacity 0.3 h4 font-size 1rem margin-top 2.125rem margin-bottom 1.25rem h5 font-size 1rem margin-left 1.25rem margin-top 2.125rem p font-size 1rem margin-bottom 1.25rem margin-top 0.625rem line-height 1.8 color rgb(82,82,82) ul padding-left 2 rem position inherit list-style disc font-size 0.9rem li padding-top 0.25rem color rgb(82,82,82); table width 100% border-collapse collapse border 0 border-spacing 0 margin-bottom 1rem margin-top 1rem; tr:nth-child(even) td background-color rgb(247,247,247) .title-row background-color #ededed tr th, td padding 0.5rem 1rem 0.5rem 1rem color rgb(82,82,82) th background-color #e8e8e8 font-weight bold font-size 0.85rem td font-size 0.75rem blockquote padding 12px 24px 12px 30px margin 2em 0 border-left 4px solid $main-color background-color rgb(248,248,248) position relative p padding 0 margin 0 &:before position absolute top 14px left -12px background-color $main-color color #fff content "!" width 20px height 20px border-radius 100% text-align center line-height 20px font-weight bold font-family $code-font font-size 14px code background-color #efefef em color $medium code border-radius 3px background-color rgb(240, 242, 241) font-size 0.75rem line-height 1.8 padding 1px 5px 1px 5px color: $main-color font-family source-code-pro, monospace margin-left 5px margin-right 5px text-shadow 0px 1px white p.tip background-color: $main-color border-radius 3px color #fff padding 10px 15px 10px 15px margin-bottom 50px a color #FFF p color #FFF margin 0 auto p a text-decoration underline color #FFF p a:hover color:rgb(252,216,214); ol list-style-type:none; counter-reset:sectioncounter; padding-left 1 rem position inherit font-size 0.9rem li color rgb(82,82,82); padding-top 0.25rem li:before content:counter(sectioncounter) ". " counter-increment:sectioncounter hr height:1px; border:none; border-top:1px dashed rgb(220,220,220); figure margin 1.2rem 0 .highlight overflow-x auto position relative padding 0 background-color rgb(248,248,248) padding .8rem .8rem .4rem line-height 1.1rem border-radius $radius font-size 0.85rem table, tr, td width 100% border-collapse collapse padding 0 margin 0 .gutter width 1.5rem .code $code-line-height = 1.5rem color #525252 font-size 0.825rem pre padding 1.2rem 1.4rem line-height $code-line-height margin 0 .line min-height $code-line-height &.html, &.js, &.bash, &.css, &.csharp, &.lua .code:after position absolute top 0 right 0 color #ccc text-align right font-size .75rem padding 5px 10px 0 line-height 15px height 15px font-weight 600 &.html .code:after content 'HTML' &.csharp .code:after content 'C#' &.lua .code:after content 'Lua' &.js .code:after content 'JS' &.bash .code:after content 'Shell' &.css .code:after content 'CSS' .gutter pre color #999 pre color: #525252 .function .keyword, .constant color: $main-color .keyword, .attribute color: $main-color .number, .literal color: #AE81FF .tag, .tag .title, .change, .winutils, .flow, .lisp .title, .clojure .built_in, .nginx .title, .tex .special color: #2973b7 .class .title color: white .symbol, .symbol .string, .value, .regexp color: $main-color .title color: #2973b7 .tag .value, .string, .subst, .haskell .type, .preprocessor, .ruby .class .parent, .built_in, .sql .aggregate, .django .template_tag, .django .variable, .smalltalk .class, .javadoc, .django .filter .argument, .smalltalk .localvars, .smalltalk .array, .attr_selector, .pseudo, .addition, .stream, .envvar, .apache .tag, .apache .cbracket, .tex .command, .prompt color: $main-color .comment, .java .annotation, .python .decorator, .template_comment, .pi, .doctype, .deletion, .shebang, .apache .sqbracket, .tex .formula color: #b3b3b3 .coffeescript .javascript, .javascript .xml, .tex .formula, .xml .javascript, .xml .vbscript, .xml .css, .xml .cdata opacity: 0.5 @media screen and (min-width: 960px) article .highlight font-size 1.125rem
xLua/docs/source/themes/catlib/source/css/_markdown.styl/0
{ "file_path": "xLua/docs/source/themes/catlib/source/css/_markdown.styl", "repo_id": "xLua", "token_count": 3816 }
2,063